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(editor): desktop is a native target — one assembly path for all five

esenginefb93faab9d45
diff --git a/build-tools/utils/desktopApp.js b/build-tools/utils/desktopApp.js
index 70a5dd3bc..8b706dbbb 100644
--- a/build-tools/utils/desktopApp.js
+++ b/build-tools/utils/desktopApp.js
@@ -13,7 +13,7 @@
import path from 'path';
import { existsSync } from 'fs';
-import { chmod, cp, mkdir, readFile, rm, writeFile } from 'fs/promises';
+import { chmod, cp, mkdir, readdir, readFile, rm, writeFile } from 'fs/promises';
import { pngToIcns } from './icns.js';
import { desktopTemplateSources } from './nativeTemplate.js';
import { fillTemplate } from './nativeApp.js';
@@ -61,9 +61,17 @@ export async function assembleMacApp(options) {
await cp(sources.executable, executable);
await chmod(executable, 0o755);
- await cp(contentDir, path.join(resources, 'Content'), { recursive: true });
+ // Entry by entry: the bundle usually lands INSIDE the export directory (the
+ // layout Android has), and copying a directory into itself is refused before
+ // any filter is consulted. Bundles are skipped as not-content.
+ const content = path.join(resources, 'Content');
+ await mkdir(content, { recursive: true });
+ for (const entry of await readdir(contentDir)) {
+ if (entry.endsWith('.app')) continue;
+ await cp(path.join(contentDir, entry), path.join(content, entry), { recursive: true });
+ }
if (existsSync(sources.bytecode)) {
- await cp(sources.bytecode, path.join(resources, 'Content', path.basename(sources.bytecode)));
+ await cp(sources.bytecode, path.join(content, path.basename(sources.bytecode)));
}
const iconPng = options.iconPng && existsSync(options.iconPng) ? options.iconPng : sources.icon;
diff --git a/build-tools/utils/nativeTemplate.d.ts b/build-tools/utils/nativeTemplate.d.ts
index 2158dc991..7d14c3111 100644
--- a/build-tools/utils/nativeTemplate.d.ts
+++ b/build-tools/utils/nativeTemplate.d.ts
@@ -7,7 +7,7 @@
/** Every platform a runtime template exists for. `macos` is one of them because a
* desktop package is assembled from a template exactly as a phone's is — that
* sameness is the point (see docs/REARCH_STEAM.md §6.0). */
-export type NativePlatform = 'android' | 'ios' | 'macos';
+export type NativePlatform = 'android' | 'ios' | 'macos' | 'windows' | 'linux';
export interface NativeTemplateManifest {
kind: 'estella-native-template';
diff --git a/build-tools/utils/nativeTemplate.js b/build-tools/utils/nativeTemplate.js
index 4aaeacc2b..e841d1fd4 100644
--- a/build-tools/utils/nativeTemplate.js
+++ b/build-tools/utils/nativeTemplate.js
@@ -167,7 +167,9 @@ export function templateLayout(platform, options = {}) {
{ rel: DEFAULT_ICON, from: (ctx) => path.join(ctx.root, 'native', 'icon.png') },
];
}
- throw new Error(`Unknown native platform "${platform}" (expected android, ios or macos).`);
+ // windows and linux are named ids with no layout yet (S3c): a template for one
+ // cannot be installed, so this is only reached if something invents one.
+ throw new Error(`No template layout for "${platform}" — android, ios and macos have one.`);
}
/**
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index ea570589e..120f7b882 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -46,6 +46,7 @@ import { emitAndroidGradleProject } from '../../build-tools/utils/gradleProject.
import { androidTemplateSources } from '../../build-tools/utils/nativeTemplate.js';
import { assembleApk, apkFileName } from '../../build-tools/utils/apk.js';
import { assembleAab, aabFileName } from '../../build-tools/utils/aab.js';
+import { assembleMacApp } from '../../build-tools/utils/desktopApp.js';
import { debugSigningKey, type SigningKey } from '../../build-tools/utils/androidKeystore.js';
import { isNativePlatform, type ExportPlatform } from '../src/project/platforms';
import type { SizeBudget } from '../src/project/sizeBudget';
@@ -202,6 +203,9 @@ export interface ExportGameResult {
/** Android: the signed App Bundle, when the project asked for one. Play takes
* this; it is not installable. */
aabFile?: string;
+ /** Desktop: the assembled app bundle. Absent when no desktop runtime template
+ * is installed (the export still carries its content). */
+ appBundle?: string;
/** Playable, zip-delivery networks: the archive written beside the HTML — the file
* the network takes an upload of. */
zipFile?: string;
@@ -263,131 +267,6 @@ function esengineGlobalPlugin(): Plugin {
};
}
-function slugify(title: string): string {
- return title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'game';
-}
-
-/** The Electron main process for an exported desktop game: serve the bundled web
- * payload (./app) over a stable, fetch-enabled `game://` scheme and show it in a
- * window. Mirrors the editor's estella:// scheme (file:// blocks fetch of sibling
- * assets + wasm streaming, which the runtime needs). */
-function desktopMain(title: string, orientation: ScreenOrientation): string {
- const [winW, winH] = orientation === 'portrait' ? [720, 1280] : [1280, 720];
- return `'use strict';
-// Generated by Estella exportGame — the desktop shell for this game.
-const { app, protocol, BrowserWindow, net } = require('electron');
-const path = require('node:path');
-const { pathToFileURL } = require('node:url');
-
-const SCHEME = 'game';
-const ROOT = path.join(__dirname, 'app');
-const MIME = {
- html: 'text/html', js: 'text/javascript', mjs: 'text/javascript', css: 'text/css',
- json: 'application/json', wasm: 'application/wasm', map: 'application/json',
- png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp',
- svg: 'image/svg+xml', ktx2: 'image/ktx2',
- ogg: 'audio/ogg', mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4', aac: 'audio/aac',
- fnt: 'text/plain', ttf: 'font/ttf', woff: 'font/woff', woff2: 'font/woff2',
-};
-
-// Emscripten/embind glue JIT-compiles call bridges (new Function) → needs unsafe-eval.
-process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
-
-protocol.registerSchemesAsPrivileged([
- { scheme: SCHEME, privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true, stream: true } },
-]);
-
-function createWindow() {
- const win = new BrowserWindow({
- width: ${winW},
- height: ${winH},
- backgroundColor: '#0e121b',
- title: ${JSON.stringify(title)},
- webPreferences: { contextIsolation: true, sandbox: true },
- });
- win.removeMenu();
- win.loadURL(SCHEME + '://app/index.html');
-}
-
-app.whenReady().then(() => {
- protocol.handle(SCHEME, async (req) => {
- let rel = decodeURIComponent(new URL(req.url).pathname).replace(/^\\/+/, '') || 'index.html';
- const filePath = path.join(ROOT, rel);
- // Contain within ROOT (no path traversal out of the bundled payload).
- // path-sandbox: this is emitted into the shipped game and cannot import the
- // editor's module. Lexical is enough because the payload is BUILT file by file
- // (the cook writes bytes, esbuild writes outputs) — no link can be in it.
- if (filePath !== ROOT && !filePath.startsWith(ROOT + path.sep)) {
- return new Response('forbidden', { status: 403 });
- }
- try {
- const res = await net.fetch(pathToFileURL(filePath).toString());
- const ext = path.extname(filePath).slice(1).toLowerCase();
- const headers = new Headers(res.headers);
- headers.set('content-type', MIME[ext] || 'application/octet-stream');
- return new Response(res.body, { status: res.status, headers });
- } catch {
- return new Response('not found', { status: 404 });
- }
- });
- createWindow();
- app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); });
-});
-
-app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
-`;
-}
-
-function desktopPackageJson(title: string, appId?: string, productName?: string): string {
- const slug = slugify(productName || title);
- return JSON.stringify({
- name: slug,
- version: '1.0.0',
- private: true,
- main: 'main.cjs',
- scripts: { start: 'electron .', dist: 'electron-builder' },
- devDependencies: { electron: '^42.0.0', 'electron-builder': '^25.0.0' },
- build: {
- appId: appId || `com.estella.${slug}`,
- productName: productName || title,
- files: ['main.cjs', 'app/**/*'],
- directories: { output: 'installer' },
- mac: { target: 'dmg' },
- win: { target: 'nsis' },
- linux: { target: 'AppImage' },
- },
- }, null, 2) + '\n';
-}
-
-function desktopReadme(title: string): string {
- return `# ${title}
-
-A desktop build exported from Estella. The game (\`app/\`) is the same play==ship
-runtime served over a \`game://\` scheme by the Electron shell (\`main.cjs\`).
-
-## Run it
-
- npm install
- npm start
-
-## Package a native installer (.dmg / .exe / AppImage)
-
- npm install
- npm run dist
-
-The installer is written to \`installer/\`. Build each OS's installer on that OS
-(electron-builder doesn't cross-compile reliably).
-`;
-}
-
-/** Stage the Electron shell around the web payload already built under `<absOut>/app`. */
-async function stageDesktopApp(absOut: string, title: string, orientation: ScreenOrientation, appId?: string, productName?: string): Promise<void> {
- const display = productName || title;
- await writeFile(path.join(absOut, 'main.cjs'), desktopMain(display, orientation));
- await writeFile(path.join(absOut, 'package.json'), desktopPackageJson(title, appId, productName));
- await writeFile(path.join(absOut, 'README.md'), desktopReadme(display));
-}
-
export interface ExportGameOptions {
root: string;
entryScene: string;
@@ -419,8 +298,7 @@ export interface ExportGameOptions {
/** The ad network a playable targets (`packaging.platforms.playable.network`),
* resolved by the caller since a project can define its own. Absent ⇒ generic. */
playableAdProfile?: PlayableAdProfile;
- /** Desktop installer id (Project Settings → Packaging → Desktop); default com.estella.<slug>. */
- desktopAppId?: string;
+
/** Desktop product/display name (Project Settings); default the project title. */
desktopProductName?: string;
/** WeChat appid (Project Settings → Packaging → WeChat). */
@@ -467,6 +345,10 @@ export interface ExportGameOptions {
* which carries every architecture it will ship. Omitted (or null) exports
* content only. */
androidTemplate?: string | null;
+ /** Desktop: the installed runtime template for THIS OS, resolved by the caller
+ * (the template ids are per-OS where the platform id is not). Omitted (or
+ * null) exports content only. */
+ desktopTemplate?: string | null;
/**
* What an Android export produces. 'package' assembles the APK (and the App
* Bundle beside it when asked); 'project' writes an Android Studio project the
@@ -523,11 +405,8 @@ function playableBudgets(profile: PlayableAdProfile | undefined): readonly SizeB
/**
* Weigh what the export produced, and judge it against the limits in force.
*
- * Measures the PAYLOAD — for the desktop target the web build under `app/`, not
- * the Electron shell around it, which weighs the same for every game and would
- * bury the part a developer can act on. A failed export is not measured: half a
- * package has no meaningful size, and a number next to an error reads as if the
- * build were fine.
+ * Measures the PAYLOAD. A failed export is not measured: half a package has no
+ * meaningful size, and a number next to an error reads as if the build were fine.
*/
async function attachSizeReport(result: ExportGameResult, opts: ExportGameOptions): Promise<ExportGameResult> {
if (!result.ok) return result;
@@ -538,10 +417,10 @@ async function attachSizeReport(result: ExportGameResult, opts: ExportGameOption
const packages = [result.apkFile, result.aabFile, result.zipFile].filter((p): p is string => !!p);
const deliverable = result.platform === 'playable'
? result.zipFile ?? path.join(result.outDir, 'index.html')
- : result.apkFile ?? result.aabFile;
+ : result.apkFile ?? result.aabFile ?? result.appBundle;
try {
const size = await measureBuild({
- root: result.platform === 'desktop' ? path.join(result.outDir, 'app') : result.outDir,
+ root: result.outDir,
platform: result.platform,
profileBudgets: opts.miniGameProfile?.sizeBudgets
?? (result.platform === 'playable' ? playableBudgets(opts.playableAdProfile) : undefined),
@@ -648,8 +527,9 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
// project (which is what `dist-game` has always meant), and leaves a properly
// drive-qualified absolute path alone.
const absOut = path.resolve(opts.root, opts.outDir);
- // Desktop nests the web build under app/; the Electron shell sits beside it.
- const payloadDir = platform === 'desktop' ? path.join(absOut, 'app') : absOut;
+ // Every target writes its payload at the top level, desktop included: it is a
+ // native target, so what it writes is content.
+ const payloadDir = absOut;
// The native app carries the runtime in its binary (engine core + SDK bundle),
// so its export is CONTENT: cooked assets, manifests, scenes, config — no host
// page, no SDK/wasm tree, and project scripts as a plain script the host evals.
@@ -663,6 +543,8 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
let androidProject: string | undefined;
let apkFile: string | undefined;
let aabFile: string | undefined;
+ /** Desktop: the assembled `<name>.app`. */
+ let appBundle: string | undefined;
await mkdir(payloadDir, { recursive: true });
const common: BuildOptions = {
bundle: true,
@@ -789,7 +671,10 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
if (nativeContent) {
const appConfig: NativeAppConfig = {
id: opts.appId ?? 'com.estella.game',
- name: title,
+ // The desktop override predates this path as electron-builder's
+ // productName; it means the same thing a bundle's CFBundleName does, so it
+ // keeps working and now names the .app itself.
+ name: (platform === 'desktop' && opts.desktopProductName) || title,
version: opts.appVersion ?? '1.0',
versionCode: opts.androidVersionCode ?? 1,
orientation,
@@ -823,6 +708,25 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
}
}
+ if (platform === 'desktop') {
+ const template = opts.desktopTemplate ?? null;
+ if (!template) {
+ warnings.push('No desktop runtime template is installed for this editor version, so no app '
+ + 'was assembled — the content is here. Install one from the Desktop row in Package '
+ + 'Project, then export again.');
+ } else if (process.platform === 'darwin') {
+ progress({ phase: 'Assembling the app bundle' });
+ appBundle = await assembleMacApp({
+ templateDir: template, contentDir: absOut, outDir: absOut, app: appConfig,
+ iconPng: opts.appIcon ? path.join(opts.root, opts.appIcon) : undefined,
+ warn: (m: string) => warnings.push(m),
+ });
+ } else {
+ warnings.push(`Assembling a desktop app on ${process.platform} is not written yet — the `
+ + 'content is here, and a macOS editor packages it.');
+ }
+ }
+
if (platform === 'android') {
const template = opts.androidTemplate ?? null;
const wantsProject = opts.androidOutput === 'project';
@@ -849,12 +753,10 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
}
}
- // 6. Desktop: wrap the payload in a runnable Electron app.
- if (platform === 'desktop') { progress({ phase: 'Staging Electron app' }); await stageDesktopApp(absOut, title, orientation, opts.desktopAppId, opts.desktopProductName); }
-
return {
ok: errors.length === 0, platform, outDir: absOut, included: cook.included.length,
warnings, errors, ...(xcodeProject ? { xcodeProject } : {}), ...(androidProject ? { androidProject } : {}),
...(apkFile ? { apkFile } : {}), ...(aabFile ? { aabFile } : {}),
+ ...(appBundle ? { appBundle } : {}),
};
}
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index fb655b97e..72a1f94c6 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -38,6 +38,7 @@ import {
iosSourcesFromTemplate, resolveNativeTemplate, installNativeTemplate, listNativeTemplates,
removeNativeTemplate, downloadNativeTemplate,
} from './nativeTemplates';
+import { desktopTemplateFor } from '../src/project/platforms';
import { loopbackServer, closeAllLoopbackServers } from './loopbackServer';
import { httpContentType } from './mimeTypes';
import { buildPlayRealm } from './buildPlayRealm';
@@ -1172,11 +1173,11 @@ ipcMain.handle(
platform: opts?.platform,
miniGameProfile: projectPlatform?.profile,
playableAdProfile: playableAdProfile ?? undefined,
- desktopAppId: plat?.desktop?.appId,
desktopProductName: plat?.desktop?.productName,
wechatAppid: plat?.wechat?.appid,
// The app's identity, by the one rule every target resolves it with.
- appId: opts?.platform === 'ios' ? resolveAppId(manifest, 'ios') : resolveAppId(manifest, 'android'),
+ appId: resolveAppId(manifest, opts?.platform === 'ios' ? 'ios'
+ : opts?.platform === 'desktop' ? 'desktop' : 'android'),
appVersion: manifest.version,
androidVersionCode: plat?.android?.versionCode,
androidAppBundle: plat?.android?.appBundle,
@@ -1203,6 +1204,10 @@ ipcMain.handle(
androidTemplate: opts?.platform === 'android'
? (resolveNativeTemplate('android', app.getVersion())?.dir ?? null)
: null,
+ // Desktop assembles the same way; the template it needs is this OS's.
+ desktopTemplate: opts?.platform === 'desktop'
+ ? (resolveNativeTemplate(desktopTemplateFor(process.platform), app.getVersion())?.dir ?? null)
+ : null,
androidOutput: plat?.android?.output,
onProgress: (p) => e.sender.send('project:exportProgress', p),
});
diff --git a/desktop/electron/platformCatalog.ts b/desktop/electron/platformCatalog.ts
index a7f0b0821..b86a0ea0e 100644
--- a/desktop/electron/platformCatalog.ts
+++ b/desktop/electron/platformCatalog.ts
@@ -30,7 +30,7 @@ import {
BUILTIN_PLAYABLE_PROFILES, builtinPlayableProfile, genericPlayableProfile,
type PlayableAdProfile,
} from './playableAdProfile';
-import { BUILTIN_PLATFORMS, type PlatformPrereq } from '../src/project/platforms';
+import { BUILTIN_PLATFORMS, desktopTemplateFor, type PlatformPrereq } from '../src/project/platforms';
import { resolveNativeTemplate } from './nativeTemplates';
import { templateId } from '../../build-tools/utils/nativeTemplate.js';
import type { MiniGameExportProfile, MiniGameConfigContext } from './miniGameExportProfile';
@@ -85,12 +85,21 @@ function builtinReadiness(
switch (id) {
case 'web':
- case 'desktop':
// The web payload's engine runtime ships with the editor.
return has(dirs.web, 'esengine.js')
? { ready: true }
: { ready: false, prereq: { kind: 'runtime-missing', dir: posix(dirs.web), looked: ['esengine.js'], command: 'node build-tools/cli.js build -t web' } };
+ case 'desktop': {
+ // Like Android: the runtime template IS the prerequisite, because the app is
+ // assembled here in pure Node. Which template depends on the OS — the ids
+ // are per-OS where the platform id is not.
+ const template = desktopTemplateFor(process.platform);
+ return resolveNativeTemplate(template, engineVersion)
+ ? { ready: true }
+ : { ready: false, prereq: { kind: 'template-missing', id: templateId(template), version: engineVersion } };
+ }
+
case 'playable':
// Playable inlines the WEB runtime (exportPlayable reads esengine.js) — it
// does NOT need a `-t playable` build, whatever the old static hint said.
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index d7b08fbda..a90f76ca8 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -116,8 +116,8 @@ export const projectMessages = defineMessages({
zh: '静态、自包含的网页构建——可托管在任何地方。',
},
'build.blurb.desktop': {
- en: 'Electron app — package to .dmg / .exe / AppImage.',
- zh: 'Electron 应用——可打包为 .dmg / .exe / AppImage。',
+ en: 'Content for the native desktop app (Metal / D3D12 / Vulkan) — a real app, not a browser.',
+ zh: '原生桌面应用(Metal / D3D12 / Vulkan)的内容——真正的应用,而非浏览器。',
},
'build.blurb.wechat': { en: 'WeChat MiniGame package.', zh: '微信小游戏包。' },
'build.blurb.playable': {
@@ -137,8 +137,8 @@ export const projectMessages = defineMessages({
zh: '在下方通过 http 预览,或将 {out}/ 上传到任意静态托管。(网页构建需要 http 源——直接打开 index.html 无法流式加载 wasm。)',
},
'build.next.desktop': {
- en: 'cd {out} && npm install && npm start — or npm run dist for a native installer.',
- zh: 'cd {out} && npm install && npm start——或运行 npm run dist 以生成原生安装包。',
+ en: 'The app is in {out}/ — double-click it. Nothing to install first.',
+ zh: '应用就在 {out}/ 中——双击即可运行,无需先安装任何东西。',
},
'build.next.wechat': {
en: 'Open {out}/ in WeChat DevTools, then set your appid in project.config.json.',
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index 6b2f307ec..9259d7b25 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -382,13 +382,13 @@ export const settingsMessages = defineMessages({
},
'set.project.packaging.desktop.appId': { en: 'Desktop App ID', zh: '桌面 App ID' },
'set.project.packaging.desktop.appId.desc': {
- en: 'Overrides the Application ID for the desktop installer only (electron-builder appId).',
- zh: '仅为桌面安装包覆盖应用 ID(electron-builder appId)。',
+ en: 'Overrides the Application ID for the desktop app only (its bundle identifier).',
+ zh: '仅为桌面应用覆盖应用 ID(即其 bundle identifier)。',
},
'set.project.packaging.desktop.productName': { en: 'Product name', zh: '产品名称' },
'set.project.packaging.desktop.productName.desc': {
- en: 'Display name for the desktop app + installer (defaults to the project name).',
- zh: '桌面应用与安装包的显示名称(默认为项目名)。',
+ en: 'Display name for the desktop app, and the name of the app itself (defaults to the project name).',
+ zh: '桌面应用的显示名称,也是应用本身的名字(默认为项目名)。',
},
// — Setting-fired feedback —
diff --git a/desktop/src/project/platforms.ts b/desktop/src/project/platforms.ts
index c043a83f4..7aba89a1e 100644
--- a/desktop/src/project/platforms.ts
+++ b/desktop/src/project/platforms.ts
@@ -42,13 +42,29 @@ export type ExportPlatform = BuiltinPlatform | (string & {});
* `native/README.md`). They share ONE runtime and ONE export payload — content
* only, since the engine, the SDK and the game runtime live in the app binary —
* and differ in how that content is assembled into an installable app.
+ *
+ * `desktop` is one of them. The rule is not "mobile" but whether the host is
+ * OURS: where a browser or a mini-game platform already provides JS and a GPU the
+ * web runtime fits, and where the app must BE the host the native one does
+ * (docs/REARCH_STEAM.md §6.0).
*/
-export const NATIVE_PLATFORMS = ['android', 'ios'] as const;
+export const NATIVE_PLATFORMS = ['android', 'ios', 'desktop'] as const;
export type NativePlatform = (typeof NATIVE_PLATFORMS)[number];
/** Whether this target's export is app CONTENT rather than a runnable payload. */
export function isNativePlatform(platform: ExportPlatform): platform is NativePlatform {
- return platform === 'android' || platform === 'ios';
+ return (NATIVE_PLATFORMS as readonly string[]).includes(platform);
+}
+
+/**
+ * The runtime template a desktop package is assembled from, for the OS building
+ * it — per-OS where the platform id is not, because the binaries are.
+ *
+ * Assembly is pure Node, but only macOS can sign a macOS bundle.
+ */
+export function desktopTemplateFor(osPlatform: string): 'macos' | 'windows' | 'linux' {
+ if (osPlatform === 'darwin') return 'macos';
+ return osPlatform === 'win32' ? 'windows' : 'linux';
}
/**
diff --git a/desktop/tests/export-desktop.test.ts b/desktop/tests/export-desktop.test.ts
index 36febe2b5..b88cf9453 100644
--- a/desktop/tests/export-desktop.test.ts
+++ b/desktop/tests/export-desktop.test.ts
@@ -1,12 +1,15 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file Desktop (Electron) export. Asserts the web payload lands under app/ and a
- * runnable Electron shell (main.cjs registering the game:// scheme +
- * electron-builder-wired package.json) is staged beside it.
+ * @file Desktop export. It is a NATIVE target now: the payload is app content —
+ * no HTML page, no SDK/wasm tree — and the app is assembled from a runtime
+ * template, exactly as the APK and the Xcode project are.
+ *
+ * Pinned here: no npm project, nothing for the user to install before running
+ * what the editor produced.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, readdirSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -46,7 +49,7 @@ beforeAll(async () => {
afterAll(() => rmSync(root, { recursive: true, force: true }));
describe('exportGame (desktop)', () => {
- it('stages an Electron shell around the web payload', async () => {
+ it('exports app CONTENT, not a web payload in a shell', async () => {
const res = await exportGame({
root,
entryScene: 'scenes/main.esscene',
@@ -57,52 +60,84 @@ describe('exportGame (desktop)', () => {
outDir: out,
title: 'My Cool Game',
platform: 'desktop',
- desktopAppId: 'com.studio.cool',
+ appId: 'com.studio.cool',
desktopProductName: 'Cool Override',
});
expect(res.ok).toBe(true);
expect(res.platform).toBe('desktop');
- // Web payload nested under app/.
- const app = path.join(out, 'app');
- for (const f of ['index.html', 'game.js', 'scripts.mjs', 'game.config.json', 'asset-manifest.json']) {
- expect(existsSync(path.join(app, f))).toBe(true);
+ // Content only, at the top level — no app/ nesting, because there is no shell
+ // to nest under any more.
+ const present = readdirSync(out).sort();
+ for (const f of ['game.config.json', 'app.config.json', 'asset-manifest.json', 'scripts.js']) {
+ expect(present, `missing ${f}`).toContain(f);
+ }
+ // The web payload's pieces are gone: the engine, the SDK and the runtime are
+ // in the app binary, so shipping them again would be shipping two engines.
+ for (const f of ['index.html', 'game.js', 'scripts.mjs', 'app', 'sdk', 'wasm']) {
+ expect(existsSync(path.join(out, f))).toBe(false);
+ }
+
+ // The identity a packager reads, by the same rule every native target uses.
+ const app = JSON.parse(readFileSync(path.join(out, 'app.config.json'), 'utf8'));
+ expect(app.id).toBe('com.studio.cool');
+ // productName was electron-builder's; it means what CFBundleName does, so it
+ // still names the app.
+ expect(app.name).toBe('Cool Override');
+
+ // No template installed in this test's environment ⇒ content, and a warning
+ // that says so rather than a silent half-export.
+ if (!res.appBundle) {
+ expect(res.warnings.join(' ')).toMatch(/runtime template/i);
}
- expect(existsSync(path.join(app, 'wasm', 'esengine.js'))).toBe(true);
- expect(existsSync(path.join(app, 'sdk', 'index.js'))).toBe(true);
- // Content-addressed by default: the texture ships as assets/<hash>.png.
- const m = JSON.parse(readFileSync(path.join(app, 'asset-manifest.json'), 'utf8')) as
- { groups: Record<string, { assets: Record<string, { type: string; path: string }> }> };
- const tex = Object.values(m.groups)
- .flatMap((g) => Object.values(g.assets))
- .find((a) => a.type === 'texture')!;
- expect(tex.path).toMatch(/^assets\/[0-9a-f]{16}\.png$/);
- expect(existsSync(path.join(app, tex.path))).toBe(true);
-
- // Electron shell beside it.
- const main = readFileSync(path.join(out, 'main.cjs'), 'utf8');
- expect(main).toContain('registerSchemesAsPrivileged');
- expect(main).toContain("SCHEME = 'game'");
- expect(main).toContain('://app/index.html'); // window loads the payload over the scheme
- // Default landscape ⇒ 1280×720 window; the desktop page carries NO rotate overlay
- // (a resizable desktop window isn't a phone — orientation is the window aspect).
- expect(main).toContain('width: 1280');
- expect(main).toContain('height: 720');
- expect(readFileSync(path.join(app, 'index.html'), 'utf8')).not.toContain('rotate-hint');
-
- const pkg = JSON.parse(readFileSync(path.join(out, 'package.json'), 'utf8'));
- expect(pkg.main).toBe('main.cjs');
- expect(pkg.scripts.start).toBe('electron .');
- expect(pkg.scripts.dist).toBe('electron-builder');
- expect(pkg.build.appId).toBe('com.studio.cool'); // from Project Settings
- expect(pkg.build.productName).toBe('Cool Override');
- expect(pkg.name).toBe('cool-override'); // slugified from product name
- expect(pkg.build.files).toContain('app/**/*');
-
- expect(existsSync(path.join(out, 'README.md'))).toBe(true);
}, 60_000);
+ it('assembles the app when a runtime template is there', async () => {
+ // A fake template, because what is under test is the EXPORT reaching the
+ // assembler — the assembler itself is pinned in desktop-app.test.ts.
+ const template = path.join(root, '_template');
+ mkdirSync(template, { recursive: true });
+ writeFileSync(path.join(template, 'estella_desktop'), 'runtime');
+ writeFileSync(path.join(template, 'esengine.native.qjsbc'), 'bytecode');
+ writeFileSync(path.join(template, 'Info.plist.in'),
+ '<plist><dict><key>N</key><string>@APP_NAME@</string></dict></plist>');
+
+ const packed = path.join(root, 'dist-desktop-packed');
+ const res = await exportGame({
+ root,
+ entryScene: 'scenes/main.esscene',
+ gameHostEntry: GAME_HOST,
+ scriptsEntry: 'src/main.ts',
+ sdkDistDir: path.join(root, '_sdk'),
+ wasmDir: path.join(root, '_wasm'),
+ outDir: packed,
+ title: 'Packed Game',
+ platform: 'desktop',
+ desktopTemplate: template,
+ });
+
+ expect(res.ok).toBe(true);
+ if (process.platform !== 'darwin') {
+ // Honest rather than silent: assembly is written for macOS only so far.
+ expect(res.appBundle).toBeUndefined();
+ expect(res.warnings.join(' ')).toMatch(/not written yet/);
+ return;
+ }
+ expect(res.appBundle).toBe(path.join(packed, 'Packed Game.app'));
+ // The runtime's bytecode joins the game's files in ONE namespace, which is
+ // what the host reads — the whole reason the bundle is laid out this way.
+ const content = path.join(res.appBundle!, 'Contents/Resources/Content');
+ expect(existsSync(path.join(content, 'game.config.json'))).toBe(true);
+ expect(existsSync(path.join(content, 'esengine.native.qjsbc'))).toBe(true);
+ }, 60_000);
+
+ it('no longer writes anything electron-builder would read', async () => {
+ for (const f of ['main.cjs', 'package.json', 'README.md']) {
+ expect(existsSync(path.join(out, f))).toBe(false);
+ }
+ });
+
it('leaves the web target unnested (no app/ wrapper)', async () => {
const webOut = path.join(root, 'dist-web');
const res = await exportGame({
@@ -122,16 +157,4 @@ describe('exportGame (desktop)', () => {
expect(existsSync(path.join(webOut, 'main.cjs'))).toBe(false);
}, 60_000);
- it('sizes the desktop window to a portrait orientation', async () => {
- const pOut = path.join(root, 'dist-desktop-portrait');
- const res = await exportGame({
- root, entryScene: 'scenes/main.esscene', gameHostEntry: GAME_HOST, scriptsEntry: 'src/main.ts',
- sdkDistDir: path.join(root, '_sdk'), wasmDir: path.join(root, '_wasm'),
- outDir: pOut, title: 'Portrait Game', platform: 'desktop', orientation: 'portrait',
- });
- expect(res.ok).toBe(true);
- const main = readFileSync(path.join(pOut, 'main.cjs'), 'utf8');
- expect(main).toContain('width: 720');
- expect(main).toContain('height: 1280');
- }, 60_000);
});