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(openpaas): integrate SUD runtime and PinK directory export

yhh385ef1809599
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index b189d5f4a..69f804742 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -55,6 +55,11 @@ jobs:
with:
name: wasm-wechat
path: build/wasm/wechat/
+ - name: Download this commit's compatibility mini-game runtime
+ uses: actions/download-artifact@v8
+ with:
+ name: wasm-quickgame
+ path: build/wasm/quickgame/
- name: Build the shipping SDK
run: pnpm --filter ./sdk build
- name: Install headless Chromium
@@ -80,6 +85,15 @@ jobs:
node pipeline/bin/estella.mjs export templates/wechat-minigame --profile wechat --wasm build/wasm/wechat --out output/wechat-starter-ci-production --json output/wechat-starter-ci-production.json
node tools/tests/export-wechat-starter-fixture.mjs --wasm build/wasm/wechat --out output/wechat-starter-ci-fixture
node tools/tests/wechat-starter.e2e.mjs --dir output/wechat-starter-ci-fixture --out output/wechat-starter-ci-check
+ - name: Check OpenPaaS 2D and 3D exports in a headless contract host
+ run: node tools/tests/openpaas-runtime.e2e.mjs --wasm build/wasm/quickgame --out output/openpaas-ci-check
+ - name: Upload OpenPaaS contract observations and frames
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: openpaas-contract-checks
+ path: output/openpaas-ci-check/
+ retention-days: 3
- name: Check authored Poki gameplay and the standalone example in SDK mocks
run: |
node pipeline/bin/estella.mjs export examples/mobile-controls --profile poki --wasm build/wasm/web --out output/poki-training-ci-export --json output/poki-training-ci-export.json
@@ -227,6 +241,14 @@ jobs:
path: build/wasm/wechat/
retention-days: 3
+ - name: Upload compatibility mini-game wasm artifact
+ uses: actions/upload-artifact@v7
+ with:
+ name: wasm-quickgame
+ path: build/wasm/quickgame/
+ if-no-files-found: error
+ retention-days: 3
+
- name: Upload wechat GLX wasm artifact
uses: actions/upload-artifact@v7
with:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4e21d993e..d854858d3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Added
+- **SUD OpenPaaS development export.** An opt-in project platform preset exports a `main.js` directory for PinK's third-party builder. Its SDK profile bridges `sud`, package-file WASM loading, XHR, WebSocket and localStorage through the shared 2D/3D mini-game runtime. Headless checks exercise real exported 2D and 3D frames, including a WASM result without `module`; PinK packaging and Android/iOS acceptance remain pending. Login, ads, payment, WebGPU and EmscriptenGLX are not enabled by this initial integration.
+
- **Plugin filesystem operations.** Editor plugins can read and write binary assets directly, list directories, inspect files, create folders, rename and delete in their own directory or the capability-gated project scope. Moves preserve asset UUID sidecars, deletion uses the OS trash, and project edits join the existing file journal. User-installed plugins outside the project are supported; generated plugin data no longer repeatedly reloads its producer. Addresses [#99](https://github.com/esengine/estella/issues/99).
- **One-click LAN device preview.** Scan Preview beside Play prepares the current scene for a phone browser, with a QR popover, tokenized local-network address, connected devices and advanced scene/interface settings. Scene and asset saves publish complete preview builds; compatible script changes retain the world through existing hot-swap APIs, with explicit reload reasons otherwise. Closing the project or stopping invalidates the session. The same Web runtime serves 2D and 3D; native/minigame device acceptance remains separate.
diff --git a/docs/astro/src/content/docs/publishing/minigame-platforms.mdx b/docs/astro/src/content/docs/publishing/minigame-platforms.mdx
index 3773105bc..2e457ec90 100644
--- a/docs/astro/src/content/docs/publishing/minigame-platforms.mdx
+++ b/docs/astro/src/content/docs/publishing/minigame-platforms.mdx
@@ -19,6 +19,72 @@ shipping to WeChat, you want [WeChat MiniGame](/docs/publishing/wechat/) instead
beyond WeChat are brought up against real devices.
</Aside>
+## SUD OpenPaaS development export
+
+Estella ships an opt-in OpenPaaS preset for **2D and 3D** through the existing
+project platform mechanism. Copy `pipeline/platforms/openpaas.mjs` into your
+project as `.esengine/platforms/openpaas.mjs`. No custom editor layout is required.
+Review and trust that project profile through the normal project-code flow when
+using the editor.
+
+From an Estella source checkout, build the compatibility mini-game runtime and
+export the project:
+
+```sh
+node build-tools/cli.js build -t quickgame --no-sync
+node pipeline/bin/estella.mjs export <project> --platform openpaas --out output/my-sud-game
+```
+
+The preset selects the CommonJS compatibility runtime (without WASM SIMD or
+BigInt i64 at the JS boundary). It uses the shared cook, SDK and renderer, with
+`sud` canvas, input, lifecycle and audio; XHR, native WebSocket and localStorage
+are bridged to the same platform interfaces. WASM loads through
+`WebAssembly.instantiateFromFile`, with package-relative paths normalized. The
+loader accepts an instance without a compiled `module`, as documented for iOS.
+
+In **PinK → Project → Third-party generated**, choose the exported directory
+containing `main.js`, `game-bundle.js` and `wasm/`. Select your platform game ID,
+configure orientation and version to match the project, then build and upload.
+PinK produces the `.sp` package; Estella does not upload or submit it for review.
+Open the development version in OpenPaaS and scan its package QR code with
+**Hello PinK**. The supplied Unity and Laya guides use this same third-party
+directory workflow; their engine-specific converters are not required here.
+
+<Aside type="caution">
+ **Development integration, device acceptance pending.** The headless contract
+ host renders real exported 2D and 3D packages, but does not reproduce SUD's
+ native renderer, audio or iOS WASM implementation. Validate both dimensions on
+ Android and iOS, including input, suspend/resume, rotation, audio, resource
+ loading and any physics/animation/AOT modules your project uses. The official
+ WASM documentation marks imported Table/Global objects unsupported on iOS;
+ accepting an absent `module` alone does not resolve those restrictions.
+</Aside>
+
+This preset uses WebGL2. WebGPU, EmscriptenGLX, login, ads and payment are not
+enabled. Assets are carried in the main directory; platform subpackage splitting
+and Brotli WASM loading are not enabled. Streaming-world exports remain subject
+to the existing mini-game restriction. PinK build success, upload, review and
+real-device acceptance must be recorded separately from Estella export success.
+The compatibility build supplies the core engine. Physics, Spine and other
+optional WASM modules need matching artifacts in the selected `wasmDir`; export
+fails if content requires one that is absent. Those modules have not been
+certified on OpenPaaS by this integration.
+
+Run the reproducible local contract check without opening an editor:
+
+```sh
+node tools/tests/openpaas-runtime.e2e.mjs --wasm build/wasm/quickgame --out output/openpaas-runtime
+```
+
+It writes 2D/3D frames and a report explicitly marking device acceptance pending.
+Android Hello PinK exposes vConsole; the supplied guide also names device logs
+under `/storage/emulated/0/Android/data/global.sud.hellopink/files/SUD/SUDLogs/SUDGI/`.
+The guide states that iOS has no vConsole.
+
+References: [engine adaptation](https://developer.sud.tech/openpaas/minigame/guide/game-engine/engine-adaptation.html),
+[adapter](https://developer.sud.tech/openpaas/minigame/guide/runtime/adapter.html),
+[WASM API](https://developer.sud.tech/openpaas/minigame/client-api/web-assembly-apis/webAssemblyApis.html).
+
## What a vendor costs
A profile is **three facts and, at most, one method**:
diff --git a/docs/astro/src/content/docs/zh-cn/publishing/minigame-platforms.mdx b/docs/astro/src/content/docs/zh-cn/publishing/minigame-platforms.mdx
index 4d24785a9..21a820299 100644
--- a/docs/astro/src/content/docs/zh-cn/publishing/minigame-platforms.mdx
+++ b/docs/astro/src/content/docs/zh-cn/publishing/minigame-platforms.mdx
@@ -17,6 +17,60 @@ import { Steps, Aside } from '@astrojs/starlight/components';
还会增加字段。
</Aside>
+## SUD OpenPaaS 开发导出
+
+OpenPaaS 通过现有的项目平台机制接入,**2D / 3D 共用同一套资源处理、SDK 和运行时**。
+将 `pipeline/platforms/openpaas.mjs` 复制到项目的 `.esengine/platforms/openpaas.mjs`。
+不需要专用编辑器布局;在编辑器中使用时,按现有项目代码流程检查并信任这个平台配置。
+
+在 Estella 源码仓库中构建兼容版小游戏运行时,再导出项目:
+
+```sh
+node build-tools/cli.js build -t quickgame --no-sync
+node pipeline/bin/estella.mjs export <项目目录> --platform openpaas --out output/my-sud-game
+```
+
+预设会选择 CommonJS 兼容版引擎,不使用 WASM SIMD 和 JS 边界的 BigInt i64。
+画布、输入、生命周期和音频调用 `sud`;HTTP、WebSocket 和存储分别桥接到标准
+XMLHttpRequest、WebSocket 和 localStorage。WASM 通过
+`WebAssembly.instantiateFromFile` 加载,代码包路径会先规范化;支持官方文档所述的
+iOS 仅返回 instance、没有编译后 module 的结果。
+
+打开 **PinK → 项目 → 第三方生成**,选择导出的目录,其中包含 `main.js`、
+`game-bundle.js` 和 `wasm/`。选择平台游戏 ID,按项目设置核对横竖屏和版本,
+然后构建、上传。`.sp` 由 PinK 生成,Estella 不会自动上传或提交审核。
+在 OpenPaaS 的开发版本详情中,用 **Hello PinK** 扫描包链接二维码调试。
+提供的 Unity / Laya 指南采用的也是这个第三方目录流程;这里不需要安装它们各自的转换插件。
+
+<Aside type="caution">
+ **当前为开发接入,真机验收待完成。** 无窗口契约宿主已能加载真实引擎和导出的
+ 2D / 3D 场景,但无法复现 SUD 原生渲染、音频和 iOS WASM 实现。
+ Android / iOS 都需要检查画面、触控、横竖屏、切后台恢复、音频、资源加载,
+ 以及项目实际使用的物理、动画和 AOT 模块。官方文档标注 iOS 暂不支持导入
+ Table / Global;支持省略 module 并不意味着这些限制也已解决。
+</Aside>
+
+首阶段使用 WebGL2,未启用 WebGPU、EmscriptenGLX、登录、广告和支付。
+资源随主目录交付,尚未启用平台分包和 Brotli WASM 加载;流式大世界导出继续遵循
+现有小游戏限制。Estella 导出、PinK 构建上传、平台审核和真机验收应分别记录。
+兼容版构建提供主引擎;物理、Spine 等可选 WASM 模块需要在选定的 `wasmDir` 中提供
+匹配的构建产物,内容依赖但产物缺失时导出会失败。本次接入尚未完成这些模块的 OpenPaaS 验收。
+
+不打开编辑器即可运行可复现的契约检查:
+
+```sh
+node tools/tests/openpaas-runtime.e2e.mjs --wasm build/wasm/quickgame --out output/openpaas-runtime
+```
+
+结果包含 2D / 3D 截图及报告,并明确标记真机验收待完成。
+提供的文档说明 Android Hello PinK 可以打开 vConsole,也可以通过设备日志目录
+`/storage/emulated/0/Android/data/global.sud.hellopink/files/SUD/SUDLogs/SUDGI/` 排查启动失败;
+iOS 不提供 vConsole。
+
+参考:[引擎适配](https://developer.sud.tech/openpaas/minigame/guide/game-engine/engine-adaptation.html)、
+[Adapter](https://developer.sud.tech/openpaas/minigame/guide/runtime/adapter.html)、
+[WASM API](https://developer.sud.tech/openpaas/minigame/client-api/web-assembly-apis/webAssemblyApis.html)。
+
## 接入一个平台的成本
一个 profile 就是**三个事实,外加至多一个方法**:
diff --git a/pipeline/platforms/openpaas.mjs b/pipeline/platforms/openpaas.mjs
new file mode 100644
index 000000000..2c8af58b9
--- /dev/null
+++ b/pipeline/platforms/openpaas.mjs
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+// Copy into <project>/.esengine/platforms/openpaas.mjs.
+// Uses Estella's shared runtime and export pipeline. PinK builds the .sp file.
+export default {
+ id: 'openpaas',
+ label: 'SUD OpenPaaS',
+ blurb: 'PinK third-party directory (2D / 3D). Device acceptance pending.',
+ preset: 'openpaas',
+ engineBuild: 'quickgame',
+ defaultOut: 'dist-openpaas',
+};
diff --git a/pipeline/src/bundle/engineSubpaths.ts b/pipeline/src/bundle/engineSubpaths.ts
index ccdc9b334..65614ec8d 100644
--- a/pipeline/src/bundle/engineSubpaths.ts
+++ b/pipeline/src/bundle/engineSubpaths.ts
@@ -26,6 +26,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {
'esengine/quickgame': 'quickgame/index.js',
'esengine/alipay': 'alipay/index.js',
'esengine/huawei': 'huawei/index.js',
+ 'esengine/openpaas': 'openpaas/index.js',
'esengine/wasm': 'wasm.js',
};
@@ -34,7 +35,7 @@ export const ESENGINE_SUBPATHS: Readonly<Record<string, string>> = {
* loads, a platform adapter an entry chooses rather than content asking for it,
* and the debug channel a development export adds. Named here so the pickable set is derived rather than written twice.
*/
-export const NOT_A_MODULE: ReadonlySet<string> = new Set(['esengine/wasm', 'esengine/debug-channel', 'esengine/douyin', 'esengine/kuaishou', 'esengine/bilibili', 'esengine/quickgame', 'esengine/alipay', 'esengine/huawei']);
+export const NOT_A_MODULE: ReadonlySet<string> = new Set(['esengine/wasm', 'esengine/debug-channel', 'esengine/douyin', 'esengine/kuaishou', 'esengine/bilibili', 'esengine/quickgame', 'esengine/alipay', 'esengine/huawei', 'esengine/openpaas']);
/** The modules a project can force in or refuse, as `features.modules` keys it. */
export const ENGINE_MODULES: readonly string[] =
diff --git a/pipeline/src/bundle/runtimeHosts.ts b/pipeline/src/bundle/runtimeHosts.ts
index 41dbee7a3..3133525c7 100644
--- a/pipeline/src/bundle/runtimeHosts.ts
+++ b/pipeline/src/bundle/runtimeHosts.ts
@@ -18,7 +18,7 @@ import { ESENGINE_EXTERNAL } from './esengineResolve';
export const RUNTIME_HOSTS = [
'gameHost', 'playableHost', 'playableLoader', 'douyinPlatformProfile', 'kuaishouPlatformProfile',
'bilibiliPlatformProfile', 'quickgamePlatformProfile', 'alipayPlatformProfile',
- 'huaweiPlatformProfile',
+ 'huaweiPlatformProfile', 'openpaasPlatformProfile',
] as const;
export type RuntimeHost = (typeof RUNTIME_HOSTS)[number];
diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.ts
index dd3ba0e55..375a46317 100644
--- a/pipeline/src/export/exportMiniGame.ts
+++ b/pipeline/src/export/exportMiniGame.ts
@@ -658,7 +658,7 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
);
}
}
- await writeFile(path.join(absOut, 'game.js'),
+ await writeFile(path.join(absOut, profile.entryFile ?? 'game.js'),
profile.emitEntry({ sideModules, engineGlueFile, runtimeDir: runtimeLayout.runtimeDir,
engineSubpackage: runtimeLayout.subpackage?.name ?? null, hostGlobal: profile.hostGlobal }));
const configFiles = profile.emitConfigFiles({
diff --git a/pipeline/src/export/miniGameExportProfile.ts b/pipeline/src/export/miniGameExportProfile.ts
index cae435967..21a345e94 100644
--- a/pipeline/src/export/miniGameExportProfile.ts
+++ b/pipeline/src/export/miniGameExportProfile.ts
@@ -27,7 +27,7 @@ import path from 'node:path';
* ship can still be exported by handing {@link exportMiniGame} a profile.
* Mirrors the SDK's `MiniGameVendor` (sdk/src/platform/minigame/api.ts).
*/
-export type MiniGameVendor = 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'quickgame' | 'alipay' | 'huawei' | (string & {});
+export type MiniGameVendor = 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'quickgame' | 'alipay' | 'huawei' | 'openpaas' | (string & {});
/** Vendor-neutral facts the pipeline computes, handed to the config emitter. */
export interface MiniGameConfigContext {
@@ -181,6 +181,8 @@ if (__task && __task.onProgressUpdate) {
export interface MiniGameExportProfile {
/** Vendor identity — the export result's `platform` + diagnostics. */
readonly id: MiniGameVendor;
+ /** Root script the vendor runs; most hosts use game.js, OpenPaaS uses main.js. */
+ readonly entryFile?: string;
/** SDK dist entry the bundle aliases `esengine` to (index.wechat.js). */
readonly sdkEntryFile: string;
/**
@@ -288,6 +290,42 @@ export interface MiniGameExportProfile {
emitEntry(ctx: MiniGameEntryContext): string;
}
+/** SUD's third-party-generated directory, consumed by PinK to build the .sp.
+ * Account, game ID, version and orientation are configured in PinK, not in a
+ * fabricated WeChat project.config.json. No upload or review is performed here.
+ */
+export const openpaasExportProfile: MiniGameExportProfile = {
+ id: 'openpaas',
+ entryFile: 'main.js',
+ sdkEntryFile: 'index.minigame.js',
+ runtimeInit: 'initMiniGameRuntime',
+ runtimeProfileHost: 'openpaasPlatformProfile',
+ engineGlueCandidates: MINIGAME_ENGINE_GLUE,
+ esTarget: 'es2016',
+ wasmBuildHint: 'quickgame',
+ hostGlobal: 'sud',
+ sideModuleBuildTargets: {},
+ nativeSuffixes: new Set(['.js', '.json']),
+ packerSuffixes: null,
+ wasmBrotli: false,
+ // A plain third-party directory carries assets in its main package. PinK's
+ // subpackage manifest format has not been supplied, so do not invent one.
+ subpackageDir: '',
+ emitConfigFiles(ctx) {
+ if (ctx.subPackages.length || ctx.hasOpenData) {
+ throw new Error('OpenPaaS third-party export does not yet support subpackages or an open-data context');
+ }
+ return [{ file: 'OPENPAAS.txt', content:
+ `Estella / SUD OpenPaaS development package\n`
+ + `Project: ${ctx.title}\nOrientation: ${ctx.orientation}\n`
+ + 'In PinK select Project > Third-party generated and choose this directory.\n'
+ + 'Select your platform game ID and configure orientation and version in PinK.\n'
+ + 'Build and upload, then scan the development version QR code using Hello PinK.\n'
+ + 'Android and iOS device acceptance is pending; export success is not platform acceptance.\n' }];
+ },
+ emitEntry: defaultMiniGameEntry,
+};
+
// =============================================================================
// WeChat profile
// =============================================================================
diff --git a/pipeline/src/export/platformCatalog.ts b/pipeline/src/export/platformCatalog.ts
index 8f6301ae3..a051e7534 100644
--- a/pipeline/src/export/platformCatalog.ts
+++ b/pipeline/src/export/platformCatalog.ts
@@ -25,7 +25,7 @@ import { existsSync } from 'node:fs';
import { readdir, mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
-import { defaultMiniGameEntry } from './miniGameExportProfile';
+import { defaultMiniGameEntry, openpaasExportProfile } from './miniGameExportProfile';
import {
BUILTIN_PLAYABLE_PROFILES, builtinPlayableProfile, genericPlayableProfile, isPlayableZipFileName,
type PlayableAdProfile,
@@ -206,6 +206,10 @@ export type ProjectPlatformKind = 'minigame' | 'playable';
/** The shape a `.esengine/platforms/<id>.mjs` default-exports. */
export interface ProjectPlatformModule extends Partial<MiniGameExportProfile>, Partial<PlayableAdProfile> {
id: string;
+ /** A shipped packaging/runtime profile, opt-in through the existing project platform seam. */
+ preset?: 'openpaas';
+ /** Family engine variant to use unless wasmDir overrides it. */
+ engineBuild?: 'minigame' | 'quickgame';
/** Shown in the platform list (the project names its own platforms). */
label: string;
kind?: ProjectPlatformKind;
@@ -528,7 +532,15 @@ async function importPlatformModule(
}
return { mod: candidate };
}
- if (typeof candidate.emitConfigFiles !== 'function') return { error: 'profile has no `emitConfigFiles(ctx)`' };
+ if (candidate.preset !== undefined && candidate.preset !== 'openpaas') return { error: 'unknown mini-game profile preset' };
+ if (candidate.engineBuild !== undefined && !['minigame', 'quickgame'].includes(candidate.engineBuild)) {
+ return { error: 'engineBuild must be minigame or quickgame' };
+ }
+ if (candidate.entryFile !== undefined && (typeof candidate.entryFile !== 'string'
+ || !/^[A-Za-z0-9_-][A-Za-z0-9_.-]*\.js$/.test(candidate.entryFile))) {
+ return { error: 'entryFile must be a root-level JavaScript filename' };
+ }
+ if (!candidate.preset && typeof candidate.emitConfigFiles !== 'function') return { error: 'profile has no `emitConfigFiles(ctx)`' };
return { mod: candidate };
} catch (err) {
return { error: err instanceof Error ? err.message : String(err) };
@@ -561,10 +573,13 @@ export async function loadProjectPlatform(root: string, id: string, dirs: Platfo
const runtimeProfileModule = mod.runtimeProfile
? (path.isAbsolute(mod.runtimeProfile) ? mod.runtimeProfile : path.join(root, mod.runtimeProfile))
: undefined;
- const profile = { ...MINIGAME_PROFILE_DEFAULTS, ...mod, runtimeProfileModule } as MiniGameExportProfile;
+ const preset = mod.preset === 'openpaas' ? openpaasExportProfile : {};
+ const profile = { ...MINIGAME_PROFILE_DEFAULTS, ...preset, ...mod, runtimeProfileModule,
+ ...(runtimeProfileModule ? { runtimeProfileHost: undefined } : {}),
+ } as MiniGameExportProfile;
const wasmDir = mod.wasmDir
? (path.isAbsolute(mod.wasmDir) ? mod.wasmDir : path.join(root, mod.wasmDir))
- : dirs.minigame;
+ : dirs[mod.engineBuild ?? (mod.preset === 'openpaas' ? 'quickgame' : 'minigame')];
return { profile, wasmDir, defaultOut: mod.defaultOut ?? `dist-${id}` };
}
return null;
@@ -710,7 +725,7 @@ export async function listPlatforms(
if (mod.kind === 'playable') continue;
const wasmDir = mod.wasmDir
? (path.isAbsolute(mod.wasmDir) ? mod.wasmDir : path.join(root, mod.wasmDir))
- : dirs.minigame;
+ : dirs[mod.engineBuild ?? (mod.preset === 'openpaas' ? 'quickgame' : 'minigame')];
// A runtime half that points nowhere is caught here rather than on a device:
// the export would bundle fine and then fail to resolve the import.
if (mod.runtimeProfile) {
diff --git a/pipeline/src/runtime/openpaasPlatformProfile.ts b/pipeline/src/runtime/openpaasPlatformProfile.ts
new file mode 100644
index 000000000..327c3b827
--- /dev/null
+++ b/pipeline/src/runtime/openpaasPlatformProfile.ts
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { openpaasProfile } from 'esengine/openpaas';
+
+export default openpaasProfile;
diff --git a/pipeline/tests/export-openpaas.test.ts b/pipeline/tests/export-openpaas.test.ts
new file mode 100644
index 000000000..85ddc671c
--- /dev/null
+++ b/pipeline/tests/export-openpaas.test.ts
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync, copyFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { loadProjectPlatform, listPlatforms } from '../src/export/platformCatalog';
+import { exportGame } from '../src/export/exportGame';
+import { OFFICIAL_PACKAGES } from './officialPackagesDir';
+
+let root: string;
+let dirs: { web: string; minigame: string; quickgame: string };
+const sdk = () => path.join(root, '_sdk');
+beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-openpaas-'));
+ dirs = { web: path.join(root, '_web'), minigame: path.join(root, '_minigame'), quickgame: path.join(root, '_compat') };
+ for (const dir of [dirs.web, dirs.minigame, dirs.quickgame, sdk(), path.join(sdk(), 'openpaas'),
+ path.join(root, 'scenes'), path.join(root, '.esengine/platforms')]) mkdirSync(dir, { recursive: true });
+ copyFileSync(path.resolve(__dirname, '../platforms/openpaas.mjs'), path.join(root, '.esengine/platforms/openpaas.mjs'));
+ writeFileSync(path.join(dirs.quickgame, 'esengine.wxgame.js'), 'module.exports = () => Promise.resolve({});');
+ writeFileSync(path.join(dirs.quickgame, 'esengine.wxgame.wasm'), Uint8Array.from([0,97,115,109,1,0,0,0]));
+ writeFileSync(path.join(sdk(), 'index.minigame.js'), 'export function initMiniGameRuntime(){}\nexport function installMiniGamePlatform(){}');
+ writeFileSync(path.join(sdk(), 'openpaas/index.js'), 'export const openpaasProfile = {id:"openpaas",hostLabel:"SUD OpenPaaS"};');
+ for (const [name, type, uuid] of [['2d', 'Sprite', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'],
+ ['3d', 'MeshRenderer', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb']]) {
+ writeFileSync(path.join(root, `scenes/${name}.esscene`), JSON.stringify({
+ version: '1.0', name, entities: [{ id: 1, components: [{ type, data: {} }] }],
+ }));
+ writeFileSync(path.join(root, `scenes/${name}.esscene.meta`), JSON.stringify({ uuid, version: '2.0', type: 'scene', importer: {} }));
+ }
+});
+afterAll(() => rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }));
+
+describe('OpenPaaS third-party directory export', () => {
+ it('loads the shipped preset and probes the same compatibility runtime the exporter uses', async () => {
+ const loaded = await loadProjectPlatform(root, 'openpaas', dirs);
+ expect(loaded).not.toBeNull();
+ expect(loaded!.wasmDir).toBe(dirs.quickgame);
+ expect(loaded!.profile.entryFile).toBe('main.js');
+ expect(loaded!.profile.runtimeProfileHost).toBe('openpaasPlatformProfile');
+ const rows = await listPlatforms(root, dirs, '0.0.0', { emcc: null, cc: null });
+ expect(rows.find(row => row.id === 'openpaas')).toMatchObject({ ready: true, source: 'project' });
+ });
+
+ it('exports both 2D and 3D scenes through the shared pipeline with main.js and uncompressed wasm', async () => {
+ const loaded = (await loadProjectPlatform(root, 'openpaas', dirs))!;
+ const out = path.join(root, 'out');
+ const result = await exportGame({
+ root, platform: 'openpaas', miniGameProfile: loaded.profile,
+ entryScene: 'scenes/2d.esscene', sdkDistDir: sdk(), wasmDir: loaded.wasmDir, outDir: out,
+ hostsDir: path.resolve(__dirname, '../src/runtime'), packagesDir: OFFICIAL_PACKAGES,
+ compressWasm: true, engineSubpackage: true, orientation: 'landscape', aotMode: 'dev',
+ });
+ expect(result.errors).toEqual([]); expect(result.ok).toBe(true);
+ expect(result.platform).toBe('openpaas');
+ const entry = readFileSync(path.join(out, 'main.js'), 'utf8');
+ expect(entry).toContain("require('./wasm/esengine.wxgame.js')");
+ expect(entry).toContain("require('./game-bundle.js')");
+ expect(entry).not.toContain('loadSubpackage');
+ expect(existsSync(path.join(out, 'game.js'))).toBe(false);
+ expect(existsSync(path.join(out, 'project.config.json'))).toBe(false);
+ expect(existsSync(path.join(out, 'wasm/esengine.wxgame.wasm'))).toBe(true);
+ expect(existsSync(path.join(out, 'wasm/esengine.wxgame.wasm.br'))).toBe(false);
+ expect(readFileSync(path.join(out, 'scenes/2d.json'), 'utf8')).toContain('Sprite');
+ expect(readFileSync(path.join(out, 'scenes/3d.json'), 'utf8')).toContain('MeshRenderer');
+ expect(readFileSync(path.join(out, 'game-bundle.js'), 'utf8')).toContain('installMiniGamePlatform');
+ expect(readFileSync(path.join(out, 'OPENPAAS.txt'), 'utf8')).toContain('acceptance is pending');
+ }, 180_000);
+
+ it('rejects a misspelled preset instead of silently choosing generic host defaults', async () => {
+ writeFileSync(path.join(root, '.esengine/platforms/typo.mjs'),
+ 'export default {id:"typo",label:"Typo",preset:"openpass"}');
+ const rows = await listPlatforms(root, dirs, '0.0.0', { emcc: null, cc: null });
+ expect(rows.find(row => row.id === 'typo')?.error).toContain('unknown mini-game profile preset');
+ expect(await loadProjectPlatform(root, 'typo', dirs)).toBeNull();
+ });
+
+ it('allows a project entry filename but rejects traversal outside the export directory', async () => {
+ for (const [id, entryFile] of [['named', 'startup.js'], ['traversal', '../outside.js']]) {
+ writeFileSync(path.join(root, `.esengine/platforms/${id}.mjs`),
+ `export default ${JSON.stringify({ id, label: id, preset: 'openpaas', entryFile })}`);
+ }
+ expect((await loadProjectPlatform(root, 'named', dirs))?.profile.entryFile).toBe('startup.js');
+ expect(await loadProjectPlatform(root, 'traversal', dirs)).toBeNull();
+ });
+});
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 4ba3d6acc..cac311fc4 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -5679,7 +5679,7 @@ changedTouches: MiniGameTouch[]
## MiniGameVendor — type @experimental
```
-'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'quickgame' | 'alipay' | 'huawei' | (string & {})
+'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'quickgame' | 'alipay' | 'huawei' | 'openpaas' | (string & {})
```
## MissingAssetCallback — type @experimental
diff --git a/sdk/etc/openpaas.api.md b/sdk/etc/openpaas.api.md
new file mode 100644
index 000000000..c63d7d25b
--- /dev/null
+++ b/sdk/etc/openpaas.api.md
@@ -0,0 +1,34 @@
+# API surface — esengine/openpaas
+
+<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
+Symbols: 0 public · 0 beta · 4 experimental · 0 deprecated
+
+## OpenPaaSEnvironment — interface @experimental
+```
+WebAssembly: { instantiateFromFile?(path: string, imports: WebAssembly.Imports): Promise<WasmInstantiateResult>; }
+WebSocket: { new (url: string | URL, protocols?: string | string[]): WebSocket; prototype: WebSocket; readonly CONNECTING: 0; readonly OPEN: 1; readonly CLOSING: 2; readonly CLOSED: 3; }
+XMLHttpRequest: { new (): XMLHttpRequest; prototype: XMLHttpRequest; readonly UNSENT: 0; readonly OPENED: 1; readonly HEADERS_RECEIVED: 2; readonly LOADING: 3; readonly DONE: 4; }
+localStorage: Pick<Storage, "length" | "getItem" | "setItem" | "removeItem" | "key">
+sud: OpenPaaSHost
+```
+
+## OpenPaaSHost — type @experimental
+```
+Pick<MiniGameGlobal,
+ 'createCanvas' | 'createImage' | 'getFileSystemManager' | 'createInnerAudioContext'
+ | 'getSystemInfoSync' | 'onTouchStart' | 'onTouchMove' | 'onTouchEnd'
+ | 'offTouchStart' | 'offTouchMove' | 'offTouchEnd'> & Partial<Pick<MiniGameGlobal,
+ 'env' | 'onTouchCancel' | 'offTouchCancel' | 'onShow' | 'offShow' | 'onHide' | 'offHide'
+ | 'onError' | 'offError' | 'onWindowResize' | 'showLoading' | 'hideLoading'>>
+```
+
+## createOpenPaaSProfile — function @experimental
+```
+(environment: OpenPaaSEnvironment): MiniGameProfile
+```
+
+## openpaasProfile — const @experimental
+```
+MiniGameProfile
+```
+
diff --git a/sdk/package.json b/sdk/package.json
index 0628be4cf..61991986c 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -120,6 +120,10 @@
"./huawei": {
"import": "./dist/huawei/index.js",
"types": "./dist/huawei/index.d.ts"
+ },
+ "./openpaas": {
+ "import": "./dist/openpaas/index.js",
+ "types": "./dist/openpaas/index.d.ts"
}
},
"files": [
diff --git a/sdk/rolldown.config.js b/sdk/rolldown.config.js
index 2c55ba31b..1df52da6a 100644
--- a/sdk/rolldown.config.js
+++ b/sdk/rolldown.config.js
@@ -108,6 +108,7 @@ export default defineConfig([
'quickgame/index': 'src/platform/quickgame/index.ts',
'alipay/index': 'src/platform/alipay/index.ts',
'huawei/index': 'src/platform/huawei/index.ts',
+ 'openpaas/index': 'src/openpaas/index.ts',
'wasm': 'src/wasm.ts',
},
// Only the node entry reaches these; a browser entry that did would fail
diff --git a/sdk/rollup.config.js b/sdk/rollup.config.js
index ec5055f16..58e3337d1 100644
--- a/sdk/rollup.config.js
+++ b/sdk/rollup.config.js
@@ -22,6 +22,7 @@ export default [
'quickgame/index': 'src/platform/quickgame/index.ts',
'alipay/index': 'src/platform/alipay/index.ts',
'huawei/index': 'src/platform/huawei/index.ts',
+ 'openpaas/index': 'src/openpaas/index.ts',
'spine/index': 'src/spine/index.ts',
'tilemap/index': 'src/tilemap/index.ts',
'logic/index': 'src/logic/index.ts',
diff --git a/sdk/src/openpaas/index.ts b/sdk/src/openpaas/index.ts
new file mode 100644
index 000000000..b212e34d1
--- /dev/null
+++ b/sdk/src/openpaas/index.ts
@@ -0,0 +1,4 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+export { openpaasProfile, createOpenPaaSProfile } from '../platform/openpaas/profile';
+export type { OpenPaaSHost, OpenPaaSEnvironment } from '../platform/openpaas/profile';
diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.ts
index 9e66cd0c3..056b7c28f 100644
--- a/sdk/src/platform/minigame/api.ts
+++ b/sdk/src/platform/minigame/api.ts
@@ -400,7 +400,7 @@ export interface MiniGameGlobal extends MiniGameDeviceHost {
* never heard of and get the whole family for it. Nothing in the SDK branches on
* this value — it is identity (adapter name, diagnostics, logs), not behavior.
*/
-export type MiniGameVendor = 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'quickgame' | 'alipay' | 'huawei' | (string & {});
+export type MiniGameVendor = 'wechat' | 'douyin' | 'kuaishou' | 'bilibili' | 'quickgame' | 'alipay' | 'huawei' | 'openpaas' | (string & {});
/**
* A vendor described as DATA — three facts and, at most, one method.
diff --git a/sdk/src/platform/minigame/fetch.ts b/sdk/src/platform/minigame/fetch.ts
index 84985bd55..d5897cc25 100644
--- a/sdk/src/platform/minigame/fetch.ts
+++ b/sdk/src/platform/minigame/fetch.ts
@@ -90,7 +90,7 @@ export function polyfillFetch(g: MiniGameGlobal): void {
ok: response.ok,
status: response.status,
statusText: response.statusText,
- headers: new Headers(response.headers),
+ headers: responseHeaders(response.headers),
json: () => response.json(),
text: () => response.text(),
arrayBuffer: () => response.arrayBuffer(),
@@ -108,3 +108,24 @@ export function polyfillFetch(g: MiniGameGlobal): void {
};
}
}
+
+/** Mini-game hosts may provide XHR without the browser's Fetch/Headers classes. */
+function responseHeaders(values: Record<string, string>): Headers | MiniGameResponseHeaders {
+ if (typeof Headers !== 'undefined') return new Headers(values);
+ return new MiniGameResponseHeaders(values);
+}
+
+/** Read-only response header view, like a network Response's immutable headers. */
+class MiniGameResponseHeaders {
+ private readonly values_: Map<string, string>;
+ constructor(values: Record<string, string>) { this.values_ = new Map(Object.entries(values)); }
+ get(name: string): string | null { return this.values_.get(name.toLowerCase()) ?? null; }
+ has(name: string): boolean { return this.values_.has(name.toLowerCase()); }
+ entries(): IterableIterator<[string, string]> { return this.values_.entries(); }
+ keys(): IterableIterator<string> { return this.values_.keys(); }
+ values(): IterableIterator<string> { return this.values_.values(); }
+ [Symbol.iterator](): IterableIterator<[string, string]> { return this.entries(); }
+ forEach(callback: (value: string, key: string, headers: MiniGameResponseHeaders) => void, thisArg?: unknown): void {
+ this.values_.forEach((value, key) => callback.call(thisArg, value, key, this));
+ }
+}
diff --git a/sdk/src/platform/openpaas/profile.ts b/sdk/src/platform/openpaas/profile.ts
new file mode 100644
index 000000000..9dff9228b
--- /dev/null
+++ b/sdk/src/platform/openpaas/profile.ts
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import type {
+ MiniGameGlobal, MiniGameProfile, MiniGameRequestOptions, MiniGameSocketTask,
+ MiniGameFileSystemManager,
+} from '../minigame/api';
+import type { WasmInstantiateResult } from '../types';
+
+/** The documented sud surface, before bridging standard Web APIs into the family. */
+export type OpenPaaSHost = Pick<MiniGameGlobal,
+ 'createCanvas' | 'createImage' | 'getFileSystemManager' | 'createInnerAudioContext'
+ | 'getSystemInfoSync' | 'onTouchStart' | 'onTouchMove' | 'onTouchEnd'
+ | 'offTouchStart' | 'offTouchMove' | 'offTouchEnd'> & Partial<Pick<MiniGameGlobal,
+ 'env' | 'onTouchCancel' | 'offTouchCancel' | 'onShow' | 'offShow' | 'onHide' | 'offHide'
+ | 'onError' | 'offError' | 'onWindowResize' | 'showLoading' | 'hideLoading'>>;
+
+/** Injectable host dependencies; importing the SDK does not touch native globals. */
+export interface OpenPaaSEnvironment {
+ sud: OpenPaaSHost;
+ localStorage: Pick<Storage, 'getItem' | 'setItem' | 'removeItem' | 'key' | 'length'>;
+ XMLHttpRequest: typeof XMLHttpRequest;
+ WebSocket: typeof WebSocket;
+ WebAssembly: {
+ instantiateFromFile?(path: string, imports: WebAssembly.Imports): Promise<WasmInstantiateResult>;
+ };
+}
+
+/** Package files are rooted at the game directory; user-data aliases stay intact. */
+function packagePath(path: string): string {
+ if (/^(?:[a-z][a-z\d+.-]*:|\/)/i.test(path)) return path;
+ const parts: string[] = [];
+ for (const part of path.replace(/\\/g, '/').split('/')) {
+ if (!part || part === '.') continue;
+ if (part === '..') {
+ if (!parts.length) throw new Error('OpenPaaS package path escapes the game directory');
+ parts.pop();
+ } else parts.push(part);
+ }
+ return parts.join('/');
+}
+
+function fileSystem(fs: MiniGameFileSystemManager): MiniGameFileSystemManager {
+ return {
+ readFileSync: (path, encoding) => fs.readFileSync(packagePath(path), encoding),
+ readFile: opts => fs.readFile({ ...opts, filePath: packagePath(opts.filePath) }),
+ access: opts => fs.access({ ...opts, path: packagePath(opts.path) }),
+ accessSync: path => fs.accessSync(packagePath(path)),
+ writeFile: opts => fs.writeFile({ ...opts, filePath: packagePath(opts.filePath) }),
+ ...(fs.readdir ? { readdir: (opts: Parameters<NonNullable<typeof fs.readdir>>[0]) =>
+ fs.readdir!({ ...opts, dirPath: packagePath(opts.dirPath) }) } : {}),
+ ...(fs.stat ? { stat: (opts: Parameters<NonNullable<typeof fs.stat>>[0]) =>
+ fs.stat!({ ...opts, path: packagePath(opts.path) }) } : {}),
+ ...(fs.unlink ? { unlink: (opts: Parameters<NonNullable<typeof fs.unlink>>[0]) =>
+ fs.unlink!({ ...opts, filePath: packagePath(opts.filePath) }) } : {}),
+ ...(fs.rename ? { rename: (opts: Parameters<NonNullable<typeof fs.rename>>[0]) =>
+ fs.rename!({ ...opts, oldPath: packagePath(opts.oldPath), newPath: packagePath(opts.newPath) }) } : {}),
+ };
+}
+
+function request(env: OpenPaaSEnvironment, opts: MiniGameRequestOptions): void {
+ const xhr = new env.XMLHttpRequest();
+ let settled = false;
+ const fail = (message: string): void => {
+ if (settled) return;
+ settled = true;
+ opts.fail?.({ errMsg: `OpenPaaS ${message}: ${opts.url}` });
+ };
+ xhr.open(opts.method ?? 'GET', opts.url, true);
+ xhr.responseType = opts.responseType === 'arraybuffer' ? 'arraybuffer' : 'text';
+ if (opts.timeout !== undefined) xhr.timeout = opts.timeout;
+ for (const [name, value] of Object.entries(opts.header ?? {})) xhr.setRequestHeader(name, value);
+ xhr.onload = () => {
+ if (settled) return;
+ settled = true;
+ const header: Record<string, string> = {};
+ for (const line of xhr.getAllResponseHeaders().split(/\r?\n/)) {
+ const colon = line.indexOf(':');
+ if (colon > 0) header[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
+ }
+ opts.success?.({ statusCode: xhr.status, header,
+ data: xhr.responseType === 'arraybuffer' ? xhr.response : xhr.responseText });
+ };
+ xhr.onerror = () => fail('request failed');
+ xhr.ontimeout = () => fail('request timed out');
+ xhr.onabort = () => fail('request aborted');
+ xhr.send(opts.data ?? null);
+}
+
+function connectSocket(env: OpenPaaSEnvironment, opts: { url: string; protocols?: string[] }): MiniGameSocketTask {
+ const socket = opts.protocols?.length
+ ? new env.WebSocket(opts.url, opts.protocols) : new env.WebSocket(opts.url);
+ socket.binaryType = 'arraybuffer';
+ return {
+ send: ({ data }) => socket.send(data),
+ close: ({ code, reason }) => socket.close(code, reason),
+ onOpen: cb => { socket.onopen = cb; },
+ onMessage: cb => { socket.onmessage = event => cb({ data: event.data }); },
+ onClose: cb => { socket.onclose = event => cb({ code: event.code, reason: event.reason }); },
+ onError: cb => { socket.onerror = cb; },
+ };
+}
+
+/** Bind documented APIs only. Commercial services require their own acceptance. */
+function normalize(env: OpenPaaSEnvironment): MiniGameGlobal {
+ const sud = env.sud;
+ const required = <K extends keyof OpenPaaSHost>(key: K): OpenPaaSHost[K] => {
+ const value = sud[key];
+ return (typeof value === 'function' ? value.bind(sud) : value) as OpenPaaSHost[K];
+ };
+ const host: MiniGameGlobal = {
+ createCanvas: required('createCanvas'), createImage: required('createImage'),
+ createInnerAudioContext: required('createInnerAudioContext'),
+ getSystemInfoSync: required('getSystemInfoSync'),
+ getFileSystemManager: () => fileSystem(sud.getFileSystemManager()),
+ onTouchStart: required('onTouchStart'), onTouchMove: required('onTouchMove'),
+ onTouchEnd: required('onTouchEnd'), offTouchStart: required('offTouchStart'),
+ offTouchMove: required('offTouchMove'), offTouchEnd: required('offTouchEnd'),
+ request: opts => request(env, opts),
+ connectSocket: opts => connectSocket(env, opts),
+ getStorageSync: key => env.localStorage.getItem(key),
+ setStorageSync: (key, value) => env.localStorage.setItem(key, value),
+ removeStorageSync: key => env.localStorage.removeItem(key),
+ getStorageInfoSync: () => {
+ const keys: string[] = [];
+ for (let i = 0; i < env.localStorage.length; i++) {
+ const key = env.localStorage.key(i);
+ if (key !== null) keys.push(key);
+ }
+ return { keys };
+ },
+ env: sud.env,
+ };
+ for (const key of ['onTouchCancel', 'offTouchCancel', 'onShow', 'offShow', 'onHide', 'offHide',
+ 'onError', 'offError', 'onWindowResize', 'showLoading', 'hideLoading'] as const) {
+ const fn = sud[key];
+ if (fn) Object.defineProperty(host, key, { value: fn.bind(sud), enumerable: true });
+ }
+ return host;
+}
+
+/** Create a SUD OpenPaaS profile over native APIs or a headless contract fixture. */
+export function createOpenPaaSProfile(environment: OpenPaaSEnvironment): MiniGameProfile {
+ return {
+ id: 'openpaas', hostLabel: 'SUD OpenPaaS',
+ global: normalize(environment),
+ async instantiateWasm(pathOrBuffer, imports) {
+ if (typeof pathOrBuffer !== 'string') {
+ throw new Error('OpenPaaS WebAssembly.instantiateFromFile requires a package file path');
+ }
+ const wasm = environment.WebAssembly;
+ if (typeof wasm.instantiateFromFile !== 'function') {
+ throw new Error('OpenPaaS runtime is missing WebAssembly.instantiateFromFile');
+ }
+ try {
+ return await wasm.instantiateFromFile(packagePath(pathOrBuffer), imports);
+ } catch (error) {
+ throw new Error(`OpenPaaS failed to instantiate ${pathOrBuffer}; verify the runtime supports this module's imports, SIMD and BigInt: ${String(error)}`);
+ }
+ },
+ };
+}
+
+/** Lazy: safe to bundle on a desktop where `sud` is absent. */
+export const openpaasProfile: MiniGameProfile = {
+ id: 'openpaas', hostLabel: 'SUD OpenPaaS',
+ get global() { return createOpenPaaSProfile(runtimeEnvironment()).global; },
+ instantiateWasm(path, imports) { return createOpenPaaSProfile(runtimeEnvironment()).instantiateWasm!(path, imports); },
+};
+
+function runtimeEnvironment(): OpenPaaSEnvironment {
+ const env = globalThis as unknown as OpenPaaSEnvironment;
+ if (!env.sud) throw new Error('SUD OpenPaaS requires the sud runtime (PinK / Hello PinK)');
+ return env;
+}
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index 96e3c255c..c9868be29 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -40,7 +40,8 @@ export interface PlatformRequestOptions {
export interface WasmInstantiateResult {
instance: WebAssembly.Instance;
- module: WebAssembly.Module;
+ /** Some file-based mini-game loaders (OpenPaaS on iOS) return only an instance. */
+ module?: WebAssembly.Module;
}
// =============================================================================
diff --git a/sdk/tests/openpaas-platform.test.ts b/sdk/tests/openpaas-platform.test.ts
new file mode 100644
index 000000000..fb352512a
--- /dev/null
+++ b/sdk/tests/openpaas-platform.test.ts
@@ -0,0 +1,195 @@
+// @vitest-environment node
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createOpenPaaSProfile, openpaasProfile, type OpenPaaSEnvironment, type OpenPaaSHost } from '../src/openpaas';
+import { MiniGamePlatformAdapter } from '../src/platform/minigame/adapter';
+import { InputState, inputEventCallbacks } from '../src/input/input';
+import type { MiniGameTouchEvent } from '../src/platform/minigame/api';
+import { polyfillFetch } from '../src/platform/minigame/fetch';
+
+class XHR {
+ static last: XHR;
+ responseType = ''; response = new ArrayBuffer(0); responseText = ''; status = 0; timeout = 0;
+ onload?: () => void; onerror?: () => void; onabort?: () => void; ontimeout?: () => void;
+ headers: Record<string, string> = {};
+ open = vi.fn(); send = vi.fn();
+ constructor() { XHR.last = this; }
+ setRequestHeader(key: string, value: string) { this.headers[key] = value; }
+ getAllResponseHeaders() { return 'Content-Type: application/json\r\nX-Trace: a:b\r\n'; }
+}
+
+class Socket {
+ static last: Socket;
+ binaryType = ''; onopen?: () => void; onerror?: (err: unknown) => void;
+ onmessage?: (event: { data: string | ArrayBuffer }) => void;
+ onclose?: (event: { code: number; reason: string }) => void;
+ send = vi.fn(); close = vi.fn();
+ constructor(readonly url: string, readonly protocols?: string[]) { Socket.last = this; }
+}
+
+function fixture() {
+ const handlers = new Map<string, Set<Function>>();
+ const on = (name: string) => (cb: Function) => {
+ if (!handlers.has(name)) handlers.set(name, new Set());
+ handlers.get(name)!.add(cb);
+ };
+ const off = (name: string) => (cb: Function) => { handlers.get(name)?.delete(cb); };
+ const fs = {
+ readFileSync: vi.fn(() => new ArrayBuffer(8)), readFile: vi.fn(), access: vi.fn(),
+ accessSync: vi.fn(), writeFile: vi.fn(), rename: vi.fn(),
+ };
+ const sud: OpenPaaSHost = {
+ env: { USER_DATA_PATH: 'sudfile://usr' },
+ createCanvas() {
+ expect(this).toBe(sud);
+ return { width: 1, height: 1, getContext: () => null };
+ },
+ createImage: vi.fn() as never, createInnerAudioContext: vi.fn() as never,
+ getSystemInfoSync: () => ({ windowWidth: 320, windowHeight: 240, pixelRatio: 2 }),
+ getFileSystemManager: () => fs,
+ onTouchStart: on('start'), offTouchStart: off('start'),
+ onTouchMove: on('move'), offTouchMove: off('move'),
+ onTouchEnd: on('end'), offTouchEnd: off('end'),
+ onTouchCancel: on('cancel'), offTouchCancel: off('cancel'),
+ onHide: on('hide'), offHide: off('hide'), onShow: on('show'), offShow: off('show'),
+ };
+ const data = new Map<string, string>();
+ const env: OpenPaaSEnvironment = {
+ sud, XMLHttpRequest: XHR as unknown as typeof XMLHttpRequest,
+ WebSocket: Socket as unknown as typeof WebSocket,
+ localStorage: {
+ getItem: key => data.get(key) ?? null, setItem: (k, v) => { data.set(k, v); },
+ removeItem: key => { data.delete(key); }, key: i => [...data.keys()][i] ?? null,
+ get length() { return data.size; },
+ },
+ WebAssembly: { instantiateFromFile: vi.fn() },
+ };
+ const profile = createOpenPaaSProfile(env);
+ const adapter = new MiniGamePlatformAdapter(profile);
+ const emit = (name: string, event?: unknown) => { for (const cb of handlers.get(name) ?? []) cb(event); };
+ return { env, profile, adapter, fs, emit, handlers, data };
+}
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('SUD OpenPaaS host contract (not device acceptance)', () => {
+ it('imports without sud and reports a useful error only when selected', () => {
+ vi.stubGlobal('sud', undefined);
+ expect(openpaasProfile.id).toBe('openpaas');
+ expect(() => openpaasProfile.global).toThrow('requires the sud runtime');
+ });
+
+ it('loads a real wasm instance through the package-path API, including an iOS result without module', async () => {
+ const { env, adapter } = fixture();
+ const bytes = Uint8Array.from([0,97,115,109,1,0,0,0]);
+ const result = await WebAssembly.instantiate(bytes, {});
+ env.WebAssembly.instantiateFromFile = vi.fn(async () => ({ instance: result.instance }));
+ const imports = { env: { memory: new WebAssembly.Memory({ initial: 1 }) } };
+ const loaded = await adapter.instantiateWasm('./wasm/../wasm/core.wasm', imports);
+ expect(loaded.instance).toBeInstanceOf(WebAssembly.Instance);
+ expect(loaded.module).toBeUndefined();
+ expect(env.WebAssembly.instantiateFromFile).toHaveBeenCalledWith('wasm/core.wasm', imports);
+ await expect(adapter.instantiateWasm(bytes.buffer, {})).rejects.toThrow('package file path');
+ await expect(adapter.instantiateWasm('../escape.wasm', {})).rejects.toThrow('escapes');
+ });
+
+ it('reports unavailable loaders and native wasm failures without hanging', async () => {
+ const { env, adapter } = fixture();
+ env.WebAssembly.instantiateFromFile = undefined;
+ await expect(adapter.instantiateWasm('core.wasm', {})).rejects.toThrow('missing WebAssembly.instantiateFromFile');
+ env.WebAssembly.instantiateFromFile = vi.fn(async () => { throw new Error('unsupported import'); });
+ await expect(adapter.instantiateWasm('core.wasm', {})).rejects.toThrow('unsupported import');
+ });
+
+ it('normalizes package paths but preserves user-data aliases and does not use a network fetch for files', async () => {
+ const { adapter, fs } = fixture();
+ await adapter.readFile('./assets/./model.glb');
+ expect(fs.readFileSync).toHaveBeenLastCalledWith('assets/model.glb', undefined);
+ await adapter.readFile('sudfile://usr/cache.bin');
+ expect(fs.readFileSync).toHaveBeenLastCalledWith('sudfile://usr/cache.bin', undefined);
+ await expect(adapter.readFile('../secret')).rejects.toThrow('escapes');
+ });
+
+ it('preserves persistent empty values and clears only a requested namespace', () => {
+ const { adapter, profile, data } = fixture();
+ adapter.setStorageItem('game:empty', ''); adapter.setStorageItem('other', '0');
+ const restarted = new MiniGamePlatformAdapter(profile);
+ expect(restarted.getStorageItem('game:empty')).toBe('');
+ expect(restarted.getStorageItem('missing')).toBeNull();
+ restarted.clearStorage('game:');
+ expect(data.has('game:empty')).toBe(false);
+ expect(restarted.getStorageItem('other')).toBe('0');
+ });
+
+ it('maps HTTP method, body, timeout, headers and non-2xx responses without swallowing failures', async () => {
+ const { adapter } = fixture();
+ const pending = adapter.fetch('https://game.example/api', {
+ method: 'POST', body: 'payload', headers: { Authorization: 'test' }, timeout: 1234,
+ });
+ const xhr = XHR.last;
+ expect(xhr.open).toHaveBeenCalledWith('POST', 'https://game.example/api', true);
+ expect(xhr.send).toHaveBeenCalledWith('payload'); expect(xhr.timeout).toBe(1234);
+ expect(xhr.headers.Authorization).toBe('test');
+ xhr.status = 404; xhr.responseText = '{"message":"missing"}'; xhr.onload!();
+ const response = await pending;
+ expect(response.ok).toBe(false); expect(response.status).toBe(404);
+ expect(response.headers['x-trace']).toBe('a:b');
+ expect(await response.json()).toEqual({ message: 'missing' });
+ for (const event of ['onerror', 'ontimeout', 'onabort'] as const) {
+ const failed = adapter.fetch('https://game.example/fail');
+ XHR.last[event]!();
+ await expect(failed).rejects.toThrow('OpenPaaS');
+ }
+ });
+
+ it('keeps binary resource responses intact', async () => {
+ const { adapter } = fixture();
+ const pending = adapter.fetch('https://game.example/model.glb', { responseType: 'arraybuffer' });
+ const buffer = Uint8Array.from([0, 255, 2, 0]).buffer;
+ XHR.last.status = 200; XHR.last.response = buffer; XHR.last.onload!();
+ expect(await (await pending).arrayBuffer()).toBe(buffer);
+ });
+
+ it('provides fetch response headers when the native host has neither fetch nor Headers', async () => {
+ const { profile } = fixture();
+ vi.stubGlobal('fetch', undefined); vi.stubGlobal('Headers', undefined);
+ polyfillFetch(profile.global);
+ const pending = fetch('https://game.example/resource');
+ XHR.last.status = 200; XHR.last.responseText = 'ok'; XHR.last.onload!();
+ const response = await pending;
+ expect(response.headers.get('Content-Type')).toBe('application/json');
+ expect(response.headers.get('missing')).toBeNull();
+ expect(response.headers.has('X-Trace')).toBe(true);
+ expect(await response.text()).toBe('ok');
+ });
+
+ it('bridges native WebSocket events, binary messages and queued sends', () => {
+ const { adapter } = fixture();
+ const socket = adapter.createSocket({ url: 'wss://game.example', protocols: ['game'] });
+ const opened = vi.fn(), received = vi.fn(), closed = vi.fn();
+ socket.on('open', opened); socket.on('message', received); socket.on('close', closed);
+ socket.send('queued'); socket.connect();
+ expect(Socket.last.protocols).toEqual(['game']); expect(Socket.last.binaryType).toBe('arraybuffer');
+ Socket.last.onopen!(); expect(opened).toHaveBeenCalledOnce();
+ expect(Socket.last.send).toHaveBeenCalledWith('queued');
+ const bytes = new ArrayBuffer(4); Socket.last.onmessage!({ data: bytes });
+ expect(received).toHaveBeenCalledWith(bytes);
+ socket.close(1000, 'done'); expect(Socket.last.close).toHaveBeenCalledWith(1000, 'done');
+ Socket.last.onclose!({ code: 1000, reason: 'done' });
+ expect(socket.readyState).toBe('closed'); expect(closed).toHaveBeenCalledWith(1000, 'done');
+ });
+
+ it('sizes the primary canvas and cancels held input on hide with removable listeners', () => {
+ const { adapter, emit, handlers } = fixture();
+ const canvas = adapter.createScreenCanvas();
+ expect([canvas.width, canvas.height]).toEqual([640, 480]);
+ const input = new InputState(); adapter.bindInputEvents(inputEventCallbacks(input));
+ emit('start', { changedTouches: [{ identifier: 7, clientX: 20, clientY: 30 }] } satisfies MiniGameTouchEvent);
+ expect(input.touches.size).toBe(1);
+ emit('hide'); expect(input.touches.size).toBe(0);
+ adapter.unbindInputEvents();
+ expect([...handlers.values()].every(set => set.size === 0)).toBe(true);
+ expect(adapter.canPay()).toBe(false); expect(adapter.canSignIn()).toBe(false);
+ });
+});
diff --git a/tools/lib/sdkProgram.mjs b/tools/lib/sdkProgram.mjs
index 498c9a8f8..bbe848468 100644
--- a/tools/lib/sdkProgram.mjs
+++ b/tools/lib/sdkProgram.mjs
@@ -67,6 +67,7 @@ export const ENTRIES = {
'wasm': 'src/wasm.ts',
'wechat': 'src/index.wechat.ts',
'minigame': 'src/index.minigame.ts',
+ 'openpaas': 'src/openpaas/index.ts',
};
/**
diff --git a/tools/nativeScriptModules.js b/tools/nativeScriptModules.js
index 354e62bfd..3b5107c5c 100644
--- a/tools/nativeScriptModules.js
+++ b/tools/nativeScriptModules.js
@@ -118,6 +118,10 @@ export const MODULES = {
disposition: 'forbidden-native-script',
why: "Huawei's quick-game profile — it names a host global (`qg`) that a native build does not have",
},
+ 'esengine/openpaas': {
+ disposition: 'forbidden-native-script',
+ why: "OpenPaaS's platform profile requires the sud host and is unavailable in a native build",
+ },
};
/** The `exports` subpath ("." / "./physics3d") a specifier corresponds to. */
diff --git a/tools/tests/openpaas-runtime.e2e.mjs b/tools/tests/openpaas-runtime.e2e.mjs
new file mode 100644
index 000000000..3a33810bb
--- /dev/null
+++ b/tools/tests/openpaas-runtime.e2e.mjs
@@ -0,0 +1,131 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+// Real exported engine and WebGL frames in a headless contract host. This does
+// not emulate SUD's native renderer, audio or device-specific WebAssembly.
+import fs from 'node:fs/promises';
+import { readFileSync, realpathSync, statSync } from 'node:fs';
+import path from 'node:path';
+import http from 'node:http';
+import assert from 'node:assert/strict';
+import crypto from 'node:crypto';
+import { fileURLToPath } from 'node:url';
+import { createRequire } from 'node:module';
+import { chromium } from 'playwright';
+import { HOST_PAGE } from '../launchers/minigameHost.mjs';
+import { runTool } from '../lib/runTool.mjs';
+
+const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+const args = process.argv.slice(2);
+const flag = (key, fallback) => args.includes(key) ? args[args.indexOf(key) + 1] : fallback;
+const wasm = path.resolve(flag('--wasm', 'build/wasm/quickgame'));
+const out = path.resolve(flag('--out', 'output/openpaas-runtime'));
+await fs.mkdir(out, { recursive: true });
+const project = await fs.mkdtemp(path.join(out, 'fixture-'));
+const report = { status: 'failed', mode: 'headless-contract-host', deviceAcceptance: 'pending', scenes: [], errors: [] };
+const sha = data => crypto.createHash('sha256').update(data).digest('hex');
+const { PNG } = createRequire(new URL('../../pipeline/package.json', import.meta.url))('pngjs');
+const entity = (id, name, components) => ({ id, name, parent: null, children: [], visible: true, components });
+const component = (type, data) => ({ type, data });
+let browser;
+try {
+ await fs.mkdir(path.join(project, 'assets/scenes'), { recursive: true });
+ await fs.mkdir(path.join(project, '.esengine/platforms'), { recursive: true });
+ await fs.copyFile(path.join(repo, 'pipeline/platforms/openpaas.mjs'), path.join(project, '.esengine/platforms/openpaas.mjs'));
+ await fs.writeFile(path.join(project, 'project.esproject'), JSON.stringify({
+ formatVersion: '1', name: 'OpenPaaS contract fixture', defaultScene: 'assets/scenes/2d.esscene',
+ designResolution: { width: 640, height: 360 },
+ }));
+ for (const dimension of ['2d', '3d']) {
+ const scene = { version: 4, name: dimension, entities: [
+ entity(0, 'Camera', [component('Transform', { position: { x: 0, y: 0, z: 5 } }),
+ component('Camera', { projectionType: dimension === '2d' ? 1 : 0, orthoSize: 180, fov: 60,
+ nearPlane: 0.1, farPlane: 100, isActive: true, priority: 0 })]),
+ entity(1, dimension === '2d' ? 'Sprite' : 'Cube', [component('Transform', dimension === '3d'
+ ? { scale: { x: 0.01, y: 0.01, z: 0.01 } } : {}),
+ component(dimension === '2d' ? 'Sprite' : 'MeshRenderer', dimension === '2d'
+ ? { size: { x: 160, y: 120 }, color: { r: 1, g: 0.3, b: 0.1, a: 1 } }
+ : { mesh: 'builtin:cube', enabled: true, lit: false, opaque: true,
+ color: { r: 0.1, g: 0.7, b: 1, a: 1 } })]),
+ ] };
+ const sceneFile = path.join(project, `assets/scenes/${dimension}.esscene`);
+ await fs.writeFile(sceneFile, JSON.stringify(scene));
+ await fs.writeFile(sceneFile + '.meta', JSON.stringify({ version: '2.0', type: 'scene', importer: {},
+ uuid: dimension === '2d' ? 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' : 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb' }));
+ }
+ browser = await chromium.launch({ headless: true, args: ['--enable-unsafe-swiftshader', '--use-angle=swiftshader', '--mute-audio'] });
+ for (const dimension of ['2d', '3d']) {
+ const dir = path.join(out, dimension);
+ const exported = runTool(process.execPath, [path.join(repo, 'pipeline/bin/estella.mjs'), 'export', project,
+ '--platform', 'openpaas', '--wasm', wasm, '--scene', `assets/scenes/${dimension}.esscene`,
+ '--out', dir, '--json', dir + '.json'], { cwd: repo, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });
+ assert.equal(exported.status, 0, `${dimension} export failed: ${exported.stderr ?? exported.stdout}`);
+ let html = HOST_PAGE('main.js');
+ const marker = " try {\n log('booting";
+ assert.ok(html.includes(marker), 'contract host hook changed');
+ html = html.replace(marker, `
+ // SUD uses standard XHR / WebSocket / localStorage, not wx.request/storage.
+ globalThis.sud = { ...wx };
+ for (const key of ['request', 'connectSocket', 'getStorageSync', 'setStorageSync',
+ 'removeStorageSync', 'getStorageInfoSync', 'loadSubpackage']) delete sud[key];
+ WebAssembly.instantiateFromFile = async (path, imports) => {
+ if (path.startsWith('./') || path.includes('..')) throw Error('Invalid SUD package path');
+ const response = await fetch('/' + path);
+ if (!response.ok) throw Error('Missing wasm ' + path);
+ const { instance } = await WebAssembly.instantiate(await response.arrayBuffer(), imports);
+ return { instance }; // iOS contract: module is absent.
+ };
+ globalThis.wx = undefined; globalThis.tt = undefined; globalThis.WXWebAssembly = undefined;
+ globalThis.__draws = 0;
+ for (const key of ['drawArrays', 'drawElements', 'drawArraysInstanced', 'drawElementsInstanced']) {
+ const original = WebGL2RenderingContext.prototype[key];
+ WebGL2RenderingContext.prototype[key] = function (...args) { __draws++; return original.apply(this, args); };
+ }
+` + marker);
+ html = html.replace('dirOf(file), wx, globalThis);', 'dirOf(file), undefined, globalThis);');
+ const root = realpathSync(dir);
+ const server = http.createServer((req, res) => {
+ try {
+ const rel = decodeURIComponent(new URL(req.url, 'http://localhost').pathname).slice(1);
+ if (!rel) { res.setHeader('Content-Type', 'text/html'); res.end(html); return; }
+ const file = realpathSync(path.resolve(root, rel));
+ if (!file.startsWith(root + path.sep) || !statSync(file).isFile()) throw Error('Outside export');
+ res.setHeader('Content-Type', ({ '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm' })[path.extname(file)] ?? 'application/octet-stream');
+ res.end(readFileSync(file));
+ } catch { res.writeHead(404).end(); }
+ });
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+ const context = await browser.newContext({ viewport: { width: 640, height: 360 }, hasTouch: true });
+ try {
+ const page = await context.newPage();
+ page.on('pageerror', error => report.errors.push(`${dimension}: ${error}`));
+ page.on('console', message => { if (message.type() === 'error') report.errors.push(`${dimension}: ${message.text()}`); });
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ await context.route('**/*', route => route.request().url().startsWith(origin + '/')
+ ? route.continue() : route.abort());
+ await page.goto(origin + '/');
+ await page.waitForFunction(() => globalThis.__estellaLoading === null && globalThis.__draws >= 3, {}, { timeout: 30000 });
+ const frame = await page.screenshot({ path: path.join(out, `${dimension}.png`) });
+ const image = PNG.sync.read(frame);
+ let different = 0;
+ for (let i = 0; i < image.data.length; i += 4) {
+ if (Math.abs(image.data[i] - image.data[0]) + Math.abs(image.data[i + 1] - image.data[1])
+ + Math.abs(image.data[i + 2] - image.data[2]) > 40) different++;
+ }
+ assert.ok(different > 200, `${dimension} frame is flat (${different} distinct pixels)`);
+ report.scenes.push({ dimension, draws: await page.evaluate(() => __draws), differentPixels: different,
+ screenshotSha256: sha(frame), engineSha256: sha(await fs.readFile(path.join(dir, 'wasm/esengine.wxgame.wasm'))) });
+ } finally {
+ await context.close();
+ await new Promise(resolve => server.close(resolve));
+ }
+ }
+ assert.deepEqual(report.errors, []);
+ report.status = 'checks-passed';
+} finally {
+ await browser?.close();
+ await fs.writeFile(path.join(out, 'report.json'), JSON.stringify(report, null, 2));
+ const resolved = path.resolve(project);
+ if (!resolved.startsWith(out + path.sep)) throw Error('Unexpected fixture cleanup path');
+ await fs.rm(resolved, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+}
+console.log('OpenPaaS: 2D and 3D exported packages rendered in headless contract host; device acceptance pending.');