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): package for iOS from an installed runtime template

esenginedba8f7cf150c
diff --git a/build-tools/cli.js b/build-tools/cli.js
index 7a5b9d511..efca65e7f 100644
--- a/build-tools/cli.js
+++ b/build-tools/cli.js
@@ -172,12 +172,18 @@ program
.option('--keystore <path>', 'Android --package: signing keystore (default: the debug one)')
.option('--jdk <dir>', 'JDK home for the APK step (else JAVA_HOME, or the JDK Android Studio bundles)')
.option('--content <dir>', 'Ship an exported project (Package Project -> Android / iOS) as the app content')
+ .option('--no-template', 'Skip refreshing this machine\'s runtime template with the build')
+ .option('--template-only', 'Emit the runtime template from an existing build, without rebuilding', false)
+ .option('--template-out <dir>', 'Also write the distributable template archive here (for a release)')
.option('-v, --verbose', 'Verbose output', false)
.action(async (options) => {
logger.setVerbose(options.verbose);
try {
await buildNative({
target: options.target,
+ template: options.template,
+ templateOnly: options.templateOnly,
+ templateOut: options.templateOut,
dawn: options.dawn,
dawnBuild: options.dawnBuild,
quickjs: options.quickjs,
diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.js
index 1ddfb5c43..4ac87ff06 100644
--- a/build-tools/tasks/native.js
+++ b/build-tools/tasks/native.js
@@ -15,9 +15,13 @@ import config from '../build.config.js';
import * as logger from '../utils/logger.js';
import { runCommand, getCpuCount, resolvePython } from '../utils/emscripten.js';
import { requireSdk, requireNdk, sdkCmake } from '../utils/android.js';
-import { packageNativeApk, BYTECODE_FILE } from './nativePackage.js';
-import { readAppConfig, iosInterfaceOrientations, fillTemplate } from '../utils/nativeApp.js';
-import { renderPbxproj, renderScheme } from '../utils/xcodeProject.js';
+import { packageNativeApk } from './nativePackage.js';
+import { emitNativeTemplate, readEngineVersion } from './nativeTemplateEmit.js';
+import {
+ BYTECODE_FILE, findTemplate, iosTemplateSources, templateStoreDir,
+} from '../utils/nativeTemplate.js';
+import { readAppConfig, fillTemplate } from '../utils/nativeApp.js';
+import { emitIosXcodeProject } from '../utils/iosProject.js';
// Generate the native (QuickJS) ECS bindings from the SAME reflection source EHT
// uses for the web embind bindings — so the two surfaces can never drift. Written
@@ -289,6 +293,16 @@ async function buildAndroidHost(options) {
logger.success(`Host: ${path.join('build-native', 'libestella_js_host.so')}`);
+ // The binaries this machine just produced are the same for every game, so they
+ // are packed for everyone else's — see build-tools/utils/nativeTemplate.js. Only
+ // the JS host is one: the pure-C++ reference host is not what a game ships on.
+ if (quickjs && options.template !== false) {
+ await emitNativeTemplate({
+ platform: 'android', abi, root: rootDir, dawnBuild, ndk, sdk,
+ androidPlatform: platform, jdk: options.jdk, zipTo: options.templateOut,
+ });
+ }
+
if (options.package) {
await packageNativeApk({
dawnBuild, abi, platform, keystore: options.keystore, jdk: options.jdk,
@@ -392,76 +406,6 @@ async function writeIosAppIdentity(rootDir, contentDir) {
logger.info(`App: ${app.name} (${app.id}) v${app.version} — ${app.orientation}`);
}
-/** A target/product name Xcode and the shell can both carry unquoted. */
-function xcodeTargetName(appName) {
- const cleaned = appName.replace(/[^A-Za-z0-9]+/g, '');
- return cleaned || 'EstellaGame';
-}
-
-/**
- * Turn an export into a self-contained Xcode project, in place — the iOS
- * counterpart of `--package`'s APK.
- *
- * The export directory BECOMES the project: its cooked files stay where they are
- * and join the resources phase directly (they land at the bundle root, which is
- * where the host looks), with the app shell, the engine xcframework and the
- * .xcodeproj written alongside. So "Build" in the editor hands back something to
- * double-click — no xcodegen, no shared project in the engine checkout that a
- * second game would overwrite.
- */
-async function emitIosXcodeProject(rootDir, contentDir, deploymentTarget) {
- const app = readAppConfig(contentDir, (m) => logger.warn(m));
- const name = xcodeTargetName(app.name);
- const frameworkName = 'Estella.xcframework';
- const projectDir = path.join(contentDir, `${name}.xcodeproj`);
- const appDir = path.join(contentDir, 'App');
- const frameworkDest = path.join(contentDir, frameworkName);
-
- // Rewritten wholesale so a re-export never inherits the last one's stale
- // slices, plist or object graph.
- await rm(projectDir, { recursive: true, force: true });
- await rm(appDir, { recursive: true, force: true });
- await rm(frameworkDest, { recursive: true, force: true });
-
- await cp(path.join(rootDir, XCFRAMEWORK), frameworkDest, { recursive: true });
-
- await mkdir(appDir, { recursive: true });
- const iosDir = path.join(rootDir, 'native', 'ios');
- await cp(path.join(iosDir, 'App', 'main.m'), path.join(appDir, 'main.m'));
- const orientations = iosInterfaceOrientations(app.orientation)
- .map((o) => `\t\t<string>${o}</string>`).join('\n');
- writeFileSync(path.join(appDir, 'Info.plist'), fillTemplate(
- readFileSync(path.join(iosDir, 'App', 'Info.plist.in'), 'utf8'),
- { APP_NAME: app.name, VERSION_NAME: app.version, VERSION_CODE: app.versionCode, ORIENTATIONS: orientations },
- ), 'utf8');
-
- // Everything the export wrote, minus what this function just added. Dotfiles
- // stay out: .DS_Store in a resources phase is a code-signing failure.
- const skip = new Set([`${name}.xcodeproj`, 'App', frameworkName]);
- const resources = (await readdir(contentDir, { withFileTypes: true }))
- .filter((e) => !skip.has(e.name) && !e.name.startsWith('.'))
- .map((e) => ({ name: e.name, isDir: e.isDirectory() }))
- .sort((a, b) => a.name.localeCompare(b.name));
-
- await mkdir(path.join(projectDir, 'xcshareddata', 'xcschemes'), { recursive: true });
- writeFileSync(path.join(projectDir, 'project.pbxproj'), renderPbxproj({
- name,
- bundleId: app.id,
- version: app.version,
- versionCode: app.versionCode,
- deploymentTarget,
- frameworkName,
- resources,
- }), 'utf8');
- writeFileSync(
- path.join(projectDir, 'xcshareddata', 'xcschemes', `${name}.xcscheme`),
- renderScheme(name), 'utf8');
-
- logger.success(`iOS project: ${path.join(contentDir, `${name}.xcodeproj`)}`);
- logger.info(`App: ${app.name} (${app.id}) v${app.version} — ${app.orientation}`);
- return { name, projectDir };
-}
-
async function buildIosHost(options) {
if (process.platform !== 'darwin') throw new Error('The iOS host builds on macOS only.');
const rootDir = config.paths.root;
@@ -507,30 +451,83 @@ async function buildIosHost(options) {
logger.success(`iOS host: ${path.join(slice.dir, 'libestella_ios.a')}`);
await assembleXcframework(rootDir, env);
- // --package: the export becomes a project of its own. Without it the engine's
- // own native/ios shell is staged instead — that one is for working ON the
- // host, where the Xcode project is checked in and the content is scratch.
- if (options.package) {
- if (!options.content) {
- throw new Error('--package needs the game to package: pass --content <dir> from '
- + 'the editor\'s iOS export.');
- }
- const contentDir = path.isAbsolute(options.content)
- ? options.content : path.join(rootDir, options.content);
- if (!existsSync(contentDir)) throw new Error(`--content dir not found: ${contentDir}`);
- const { projectDir } = await emitIosXcodeProject(rootDir, contentDir, deploymentTarget);
- logger.info(`Next: open ${projectDir} — pick your Team under Signing & Capabilities, then Run.`);
- return;
+ // See buildAndroidHost: the compiled half is project-independent, so it is
+ // packed as a template the editor (and everyone without Xcode's dependencies)
+ // can consume.
+ if (options.template !== false) {
+ await emitNativeTemplate({
+ platform: 'ios', root: rootDir, deploymentTarget, zipTo: options.templateOut,
+ });
}
+ // Without --package the engine's own native/ios shell is staged instead — that
+ // one is for working ON the host, where the Xcode project is checked in and the
+ // content is scratch.
const staged = options.content ? await stageIosContent(rootDir, options.content) : null;
await writeIosAppIdentity(rootDir, staged);
logger.info('Next: cd native/ios && xcodegen && open EstellaiOS.xcodeproj — pick your Team, then Run.');
}
+/**
+ * Wrap an iOS export in an Xcode project — from the installed runtime template,
+ * with no compiler involved. The same call the editor's export makes, so a project
+ * assembled here and one assembled there are the same project.
+ */
+async function packageIosProject(options) {
+ const rootDir = config.paths.root;
+ if (!options.content) {
+ throw new Error('--package needs the game to package: pass --content <dir> from '
+ + "the editor's iOS export.");
+ }
+ const contentDir = path.isAbsolute(options.content)
+ ? options.content : path.join(rootDir, options.content);
+ if (!existsSync(contentDir)) throw new Error(`--content dir not found: ${contentDir}`);
+
+ const engineVersion = readEngineVersion(rootDir);
+ const template = findTemplate({ platform: 'ios', engineVersion });
+ if (!template || template.missing.length > 0) {
+ throw new Error(`No iOS runtime template for v${engineVersion}. Build one with `
+ + '`cli native --target ios`, or install a release archive into '
+ + `${templateStoreDir()}.`);
+ }
+
+ const app = readAppConfig(contentDir, (m) => logger.warn(m));
+ const projectDir = await emitIosXcodeProject(
+ contentDir, app, iosTemplateSources(template.dir),
+ options.iosMin || template.manifest.deploymentTarget);
+ logger.success(`iOS project: ${projectDir}`);
+ logger.info(`App: ${app.name} (${app.id}) v${app.version} — ${app.orientation}`);
+ logger.info(`Next: open ${projectDir} — pick your Team under Signing & Capabilities, then Run.`);
+}
+
+/** Pack what a previous build left behind, without rebuilding — what CI runs after
+ * its build step, and what re-stamps a template whose emit failed. */
+async function emitFromExistingBuild(target, options) {
+ const rootDir = config.paths.root;
+ if (target === 'ios') {
+ return emitNativeTemplate({
+ platform: 'ios', root: rootDir,
+ deploymentTarget: options.iosMin, zipTo: options.templateOut,
+ });
+ }
+ const sdk = requireSdk();
+ return emitNativeTemplate({
+ platform: 'android', abi: options.abi, root: rootDir,
+ dawnBuild: options.dawnBuild || process.env.ESTELLA_DAWN_BUILD,
+ ndk: requireNdk(sdk), sdk, androidPlatform: options.platform, jdk: options.jdk,
+ zipTo: options.templateOut,
+ });
+}
+
export async function buildNative(options = {}) {
const target = (options.target || 'android').toLowerCase();
- if (target === 'ios') return buildIosHost(options);
- if (target !== 'android') throw new Error(`Unknown --target ${target} (expected android or ios).`);
- return buildAndroidHost(options);
+ if (target !== 'ios' && target !== 'android') {
+ throw new Error(`Unknown --target ${target} (expected android or ios).`);
+ }
+ if (options.templateOnly) return emitFromExistingBuild(target, options);
+ // On iOS, packaging is ASSEMBLY: the pieces come from the installed runtime
+ // template, so it needs no toolchain and never builds. (Android's assembler
+ // still reads the build tree — see docs/REARCH_NATIVE_DISTRIBUTION.md P1.)
+ if (options.package && target === 'ios') return packageIosProject(options);
+ return target === 'ios' ? buildIosHost(options) : buildAndroidHost(options);
}
diff --git a/build-tools/utils/iosProject.d.ts b/build-tools/utils/iosProject.d.ts
new file mode 100644
index 000000000..821fa11ff
--- /dev/null
+++ b/build-tools/utils/iosProject.d.ts
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Types for iosProject.js — the module is plain ESM so the CLI can run it unbuilt,
+// and this is how the editor's TypeScript sees it.
+
+/**
+ * The prebuilt pieces a project is wrapped around, named file by file: they come
+ * from a runtime template, whose layout table is the only thing that knows where
+ * they sit inside it (see nativeTemplate.js).
+ */
+export interface IosProjectSources {
+ /** The engine, built for device + simulator. */
+ xcframework: string;
+ /** The app shell's entry point — it calls `EstellaRunApp()`. */
+ mainM: string;
+ /** The Info.plist template the app's identity is substituted into. */
+ infoPlistIn: string;
+}
+
+export interface IosAppIdentity {
+ id: string;
+ name: string;
+ version: string;
+ versionCode: number;
+ orientation: 'landscape' | 'portrait';
+}
+
+export function emitIosXcodeProject(
+ contentDir: string,
+ app: IosAppIdentity,
+ sources: IosProjectSources,
+ deploymentTarget?: string,
+): Promise<string>;
diff --git a/build-tools/utils/iosProject.js b/build-tools/utils/iosProject.js
new file mode 100644
index 000000000..a454c132f
--- /dev/null
+++ b/build-tools/utils/iosProject.js
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Turning an iOS export into a project the user can open.
+//
+// An export that hands back a content folder plus two commands to type is not a
+// build — every engine worth using gives you an Xcode project you can
+// double-click. Generating one needs NO compiler: the engine is a prebuilt
+// xcframework from the runtime template and the app shell is a `main.m` plus a
+// plist, so the whole step is copy + write.
+//
+// Plain ESM, and the ONE implementation: the editor's export and
+// `cli native --target ios --package` both call it, so a project written by the
+// CLI and one written by the editor cannot differ.
+
+import path from 'path';
+import { cp, mkdir, readdir, rm, readFile, writeFile } from 'fs/promises';
+import { renderPbxproj, renderScheme } from './xcodeProject.js';
+import { iosInterfaceOrientations } from './nativeApp.js';
+
+/** A target/product name Xcode and the shell can both carry unquoted. */
+function targetName(appName) {
+ return appName.replace(/[^A-Za-z0-9]+/g, '') || 'EstellaGame';
+}
+
+/**
+ * Write the Xcode project into an export, in place: the export directory BECOMES
+ * the project. Its cooked files stay where they are and join the resources phase
+ * directly — they land at the bundle root, which is where the host reads them.
+ *
+ * @param {string} contentDir The export (cooked content + the two configs).
+ * @param {{id: string, name: string, version: string, versionCode: number,
+ * orientation: 'landscape'|'portrait'}} app From `app.config.json`.
+ * @param {{xcframework: string, mainM: string, infoPlistIn: string}} sources
+ * The prebuilt pieces, out of the installed runtime template.
+ * @param {string} [deploymentTarget]
+ * @returns {Promise<string>} The `.xcodeproj` path, to reveal or open.
+ */
+export async function emitIosXcodeProject(contentDir, app, sources, deploymentTarget = '17.0') {
+ const name = targetName(app.name);
+ const frameworkName = 'Estella.xcframework';
+ const projectDir = path.join(contentDir, `${name}.xcodeproj`);
+ const appDir = path.join(contentDir, 'App');
+ const frameworkDest = path.join(contentDir, frameworkName);
+
+ // Rewritten wholesale so a re-export never inherits the last one's stale
+ // slices, plist or object graph.
+ await rm(projectDir, { recursive: true, force: true });
+ await rm(appDir, { recursive: true, force: true });
+ await rm(frameworkDest, { recursive: true, force: true });
+
+ await cp(sources.xcframework, frameworkDest, { recursive: true });
+ await mkdir(appDir, { recursive: true });
+ await cp(sources.mainM, path.join(appDir, 'main.m'));
+
+ const template = await readFile(sources.infoPlistIn, 'utf8');
+ const orientations = iosInterfaceOrientations(app.orientation)
+ .map((o) => `\t\t<string>${o}</string>`).join('\n');
+ await writeFile(path.join(appDir, 'Info.plist'), template
+ .replace(/@APP_NAME@/g, app.name)
+ .replace(/@VERSION_NAME@/g, app.version)
+ .replace(/@VERSION_CODE@/g, String(app.versionCode))
+ .replace(/@ORIENTATIONS@/g, orientations));
+
+ // Everything the export wrote, minus what this function just added. Dotfiles
+ // stay out: a .DS_Store in a resources phase is a code-signing failure.
+ const skip = new Set([`${name}.xcodeproj`, 'App', frameworkName]);
+ const resources = (await readdir(contentDir, { withFileTypes: true }))
+ .filter((e) => !skip.has(e.name) && !e.name.startsWith('.'))
+ .map((e) => ({ name: e.name, isDir: e.isDirectory() }))
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ await mkdir(path.join(projectDir, 'xcshareddata', 'xcschemes'), { recursive: true });
+ await writeFile(path.join(projectDir, 'project.pbxproj'), renderPbxproj({
+ name,
+ bundleId: app.id,
+ version: app.version,
+ versionCode: app.versionCode,
+ deploymentTarget,
+ frameworkName,
+ resources,
+ }));
+ await writeFile(
+ path.join(projectDir, 'xcshareddata', 'xcschemes', `${name}.xcscheme`),
+ renderScheme(name));
+
+ return projectDir;
+}
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index b54484bb9..ad94f5629 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -37,8 +37,7 @@ import type { PlayableAdProfile } from './playableAdProfile';
import type { OnExportProgress } from './exportProgress';
import { ESENGINE_EXTERNAL } from './esengineResolve';
import { orientationCss, orientationOverlayHtml, orientationLockScript, orientationLockCspHash, type ScreenOrientation } from './orientationHtml';
-
-import { emitIosXcodeProject, type IosProjectSources } from './iosProject';
+import { emitIosXcodeProject, type IosProjectSources } from '../../build-tools/utils/iosProject.js';
import { isNativePlatform, type ExportPlatform } from '../src/project/platforms';
import { collectSubsystems, subsystemGapWarnings, targetGaps, type Subsystem } from '../src/project/targetSupport';
export type { ExportPlatform };
@@ -656,9 +655,9 @@ export async function exportGame(opts: {
const projectDir = await emitIosXcodeProject(absOut, appConfig, sources);
xcodeProject = projectDir;
} else {
- warnings.push('The engine is not built for iOS on this machine, so no Xcode project was '
- + 'written — the content is here. Build it once with `node build-tools/cli.js '
- + '--target ios`, then export again.');
+ warnings.push('No iOS runtime template is installed for this editor version, so no Xcode '
+ + 'project was written — the content is here. Install one from the iOS row in Package '
+ + 'Project, then export again.');
}
}
}
diff --git a/desktop/electron/iosProject.ts b/desktop/electron/iosProject.ts
deleted file mode 100644
index ad770d222..000000000
--- a/desktop/electron/iosProject.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file iosProject.ts
- * @brief Turn an iOS export into a project the user can open.
- *
- * @details An export that hands back a content folder plus two commands to type is
- * not a build — Unity and Godot both give you an Xcode project you can
- * double-click, and so should this. Generating one needs no compiler: the
- * engine is a prebuilt xcframework and the app shell is a `main.m` plus a
- * plist, so the whole step is copy + write, which is why it belongs in the
- * export rather than behind a separate "assemble" action.
- *
- * The pbxproj writer is shared with `cli native --target ios --package`
- * (build-tools/utils/xcodeProject.js) so the two paths cannot drift.
- */
-
-import path from 'node:path';
-import { existsSync } from 'node:fs';
-import { cp, mkdir, readdir, rm, readFile, writeFile } from 'node:fs/promises';
-// @ts-expect-error — plain ESM JS, shared with the CLI; bundled in by vite.
-import { renderPbxproj, renderScheme } from '../../build-tools/utils/xcodeProject.js';
-
-export interface IosProjectSources {
- /** The engine, built for device + simulator (`cli native --target ios`). */
- xcframework: string;
- /** Holds `main.m` and `Info.plist.in` — the signing/packaging shell. */
- appShell: string;
-}
-
-export interface IosAppIdentity {
- id: string;
- name: string;
- version: string;
- versionCode: number;
- orientation: 'landscape' | 'portrait';
-}
-
-/**
- * Where the pieces live, or null when this install cannot finish an iOS export.
- *
- * A dev checkout builds the xcframework into `build-native-ios/`; a shipped editor
- * carries it as a resource. Absent means the engine was never built for iOS here —
- * the export still writes its content, it just cannot wrap a project around it.
- */
-export function iosProjectSources(candidates: {
- resourcesPath?: string;
- repoRoot?: string;
-}): IosProjectSources | null {
- const roots = [
- ...(candidates.resourcesPath ? [path.join(candidates.resourcesPath, 'ios')] : []),
- ...(candidates.repoRoot ? [candidates.repoRoot] : []),
- ];
- for (const root of roots) {
- const xcframework = path.join(root, 'build-native-ios', 'Estella.xcframework');
- const appShell = path.join(root, 'native', 'ios', 'App');
- if (existsSync(xcframework) && existsSync(path.join(appShell, 'main.m'))) {
- return { xcframework, appShell };
- }
- // A shipped editor stages them flat, without the checkout's directory shape.
- const flatFramework = path.join(root, 'Estella.xcframework');
- const flatShell = path.join(root, 'App');
- if (existsSync(flatFramework) && existsSync(path.join(flatShell, 'main.m'))) {
- return { xcframework: flatFramework, appShell: flatShell };
- }
- }
- return null;
-}
-
-/** A target/product name Xcode and the shell can both carry unquoted. */
-function targetName(appName: string): string {
- return appName.replace(/[^A-Za-z0-9]+/g, '') || 'EstellaGame';
-}
-
-/** The orientations the OS may rotate among; mirrors nativeApp.js's iOS mapping. */
-function interfaceOrientations(orientation: 'landscape' | 'portrait'): string[] {
- return orientation === 'portrait'
- ? ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown']
- : ['UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];
-}
-
-/**
- * Write the Xcode project into an export, in place: the export directory BECOMES
- * the project. Its cooked files stay where they are and join the resources phase
- * directly — they land at the bundle root, which is where the host reads them.
- *
- * @returns The `.xcodeproj` path, for the editor to reveal or open.
- */
-export async function emitIosXcodeProject(
- contentDir: string,
- app: IosAppIdentity,
- sources: IosProjectSources,
- deploymentTarget = '17.0',
-): Promise<string> {
- const name = targetName(app.name);
- const frameworkName = 'Estella.xcframework';
- const projectDir = path.join(contentDir, `${name}.xcodeproj`);
- const appDir = path.join(contentDir, 'App');
- const frameworkDest = path.join(contentDir, frameworkName);
-
- // Rewritten wholesale so a re-export never inherits the last one's stale
- // slices, plist or object graph.
- await rm(projectDir, { recursive: true, force: true });
- await rm(appDir, { recursive: true, force: true });
- await rm(frameworkDest, { recursive: true, force: true });
-
- await cp(sources.xcframework, frameworkDest, { recursive: true });
- await mkdir(appDir, { recursive: true });
- await cp(path.join(sources.appShell, 'main.m'), path.join(appDir, 'main.m'));
-
- const template = await readFile(path.join(sources.appShell, 'Info.plist.in'), 'utf8');
- const orientations = interfaceOrientations(app.orientation)
- .map((o) => `\t\t<string>${o}</string>`).join('\n');
- await writeFile(path.join(appDir, 'Info.plist'), template
- .replace(/@APP_NAME@/g, app.name)
- .replace(/@VERSION_NAME@/g, app.version)
- .replace(/@VERSION_CODE@/g, String(app.versionCode))
- .replace(/@ORIENTATIONS@/g, orientations));
-
- // Everything the export wrote, minus what this function just added. Dotfiles
- // stay out: a .DS_Store in a resources phase is a code-signing failure.
- const skip = new Set([`${name}.xcodeproj`, 'App', frameworkName]);
- const resources = (await readdir(contentDir, { withFileTypes: true }))
- .filter((e) => !skip.has(e.name) && !e.name.startsWith('.'))
- .map((e) => ({ name: e.name, isDir: e.isDirectory() }))
- .sort((a, b) => a.name.localeCompare(b.name));
-
- await mkdir(path.join(projectDir, 'xcshareddata', 'xcschemes'), { recursive: true });
- await writeFile(path.join(projectDir, 'project.pbxproj'), renderPbxproj({
- name,
- bundleId: app.id,
- version: app.version,
- versionCode: app.versionCode,
- deploymentTarget,
- frameworkName,
- resources,
- }));
- await writeFile(
- path.join(projectDir, 'xcshareddata', 'xcschemes', `${name}.xcscheme`),
- renderScheme(name));
-
- return projectDir;
-}
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 295fc80dd..352540c9e 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -31,7 +31,9 @@ import { cookAssets } from './cookAssets';
import { startProjectWatch, stopProjectWatch } from './projectWatcher';
import { importAssets, createAsset, IMPORT_EXTENSIONS } from './importAssets';
import { exportGame } from './exportGame';
-import { iosProjectSources } from './iosProject';
+import {
+ iosSourcesFromTemplate, installNativeTemplate, listNativeTemplates, removeNativeTemplate,
+} from './nativeTemplates';
import { loopbackServer, closeAllLoopbackServers } from './loopbackServer';
import { httpContentType } from './mimeTypes';
import { buildPlayRealm } from './buildPlayRealm';
@@ -793,7 +795,9 @@ ipcMain.handle('project:cookAssets', async (_e, outDir?: string) => {
// Every platform this project can package for, each with its engine runtime
// probed on disk — so the Package dialog can say what is ready BEFORE a build
// runs, and can list the platforms the project defines for itself.
-ipcMain.handle('project:listPlatforms', async () => listPlatforms(projectRoot, platformRuntimeDirs()));
+ipcMain.handle('project:listPlatforms', async () =>
+ listPlatforms(projectRoot, platformRuntimeDirs(), app.getVersion()),
+);
// The ad networks a playable can target — built-ins plus the project's own, so the
// Packaging page offers a network the editor never heard of on equal terms.
@@ -886,11 +890,10 @@ ipcMain.handle(
compressAudio: opts?.compressAudio,
atlasTextures: opts?.atlasTextures,
// iOS wraps its content in an Xcode project; these are the prebuilt pieces
- // it needs. Null on an install where the engine was never built for iOS —
- // the export then says so instead of writing a project that cannot link.
- iosSources: opts?.platform === 'ios'
- ? iosProjectSources({ resourcesPath: app.isPackaged ? process.resourcesPath : undefined, repoRoot: REPO_ROOT })
- : null,
+ // it needs, out of the installed runtime template. Null when none is
+ // installed for this editor version — the export then says so instead of
+ // writing a project that cannot link.
+ iosSources: opts?.platform === 'ios' ? iosSourcesFromTemplate(app.getVersion()) : null,
onProgress: (p) => e.sender.send('project:exportProgress', p),
});
},
@@ -984,6 +987,23 @@ ipcMain.handle('plugins:reveal', async (_e, id: string) => {
if (dir) shell.openPath(dir);
});
+// — Native runtime templates. The prebuilt engine a mobile target is assembled
+// around: the editor never compiles one, it installs the release's artifact. —
+ipcMain.handle('nativeTemplates:list', () => listNativeTemplates(app.getVersion()));
+ipcMain.handle('nativeTemplates:install', async () => {
+ if (!win) return { ok: false, error: 'no window' };
+ const res = await dialog.showOpenDialog(win, {
+ title: 'Install a runtime template',
+ filters: [{ name: 'Estella runtime template', extensions: ['zip'] }],
+ properties: ['openFile'],
+ });
+ if (res.canceled || res.filePaths.length === 0) return { ok: false, canceled: true };
+ return installNativeTemplate(res.filePaths[0], app.getVersion());
+});
+ipcMain.handle('nativeTemplates:remove', (_e, platform: 'android' | 'ios', abi: string, version: string) =>
+ removeNativeTemplate(platform, abi, version),
+);
+
// New-project templates + creation (launcher New tab).
ipcMain.handle('templates:list', () => listTemplates());
ipcMain.handle('project:createFromTemplate', (_e, templateDir: string, location: string, name: string) =>
diff --git a/desktop/electron/nativeTemplates.ts b/desktop/electron/nativeTemplates.ts
new file mode 100644
index 000000000..5534e75ab
--- /dev/null
+++ b/desktop/electron/nativeTemplates.ts
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file nativeTemplates.ts
+ * @brief The editor's half of the runtime-template contract: find one, install one.
+ *
+ * @details A native target's compiled half — the engine, Dawn, QuickJS, the Java
+ * shim — is the same for every game, so it is built once per release and
+ * shipped as a template rather than rebuilt by everyone who wants to put a
+ * game on a phone. The editor never compiles it; it looks one up and
+ * assembles the app around it.
+ *
+ * The layout and the store path come from build-tools/utils/nativeTemplate.js,
+ * which the CLI's emitter reads too — so what is written and what is looked
+ * for cannot drift.
+ */
+
+import path from 'node:path';
+import { existsSync, readFileSync, rmSync, renameSync, mkdirSync, readdirSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import {
+ findTemplate, readTemplateManifest, missingTemplateFiles, installedTemplateDir,
+ templateStoreDir, iosTemplateSources, DEFAULT_ABI,
+ type NativePlatform, type NativeTemplateManifest,
+} from '../../build-tools/utils/nativeTemplate.js';
+import { extractZip } from '../../build-tools/utils/zip.js';
+
+export type { NativePlatform, NativeTemplateManifest };
+
+/** A template this editor can actually use, with where it came from. */
+export interface UsableTemplate {
+ dir: string;
+ manifest: NativeTemplateManifest;
+}
+
+/**
+ * The runtime template for @p platform, or null when this machine has none for
+ * this editor version.
+ *
+ * A template whose files are incomplete counts as absent: half a template
+ * produces an app that fails to link, which is worse than one that is not offered.
+ */
+export function resolveNativeTemplate(platform: NativePlatform, engineVersion: string): UsableTemplate | null {
+ const found = findTemplate({ platform, engineVersion });
+ if (!found || found.missing.length > 0) return null;
+ return { dir: found.dir, manifest: found.manifest };
+}
+
+/** The three files an iOS Xcode project is built around, or null without a template. */
+export function iosSourcesFromTemplate(engineVersion: string): {
+ xcframework: string; mainM: string; infoPlistIn: string;
+} | null {
+ const template = resolveNativeTemplate('ios', engineVersion);
+ return template ? iosTemplateSources(template.dir) : null;
+}
+
+/** One row of the installed-template list. */
+export interface NativeTemplateEntry {
+ id: string;
+ platform: string;
+ abi: string;
+ engineVersion: string;
+ dir: string;
+ /** Usable by THIS editor — an older release's template stays listed (removing
+ * it is the user's call) but cannot be packaged with. */
+ current: boolean;
+}
+
+/** Every template installed on this machine, newest version first. */
+export function listNativeTemplates(engineVersion: string): NativeTemplateEntry[] {
+ const store = templateStoreDir();
+ if (!existsSync(store)) return [];
+ const out: NativeTemplateEntry[] = [];
+ for (const version of readdirSync(store, { withFileTypes: true }).filter((e) => e.isDirectory())) {
+ const versionDir = path.join(store, version.name);
+ for (const entry of readdirSync(versionDir, { withFileTypes: true }).filter((e) => e.isDirectory())) {
+ const dir = path.join(versionDir, entry.name);
+ const manifest = readTemplateManifest(dir);
+ if (!manifest) continue;
+ out.push({
+ id: manifest.id,
+ platform: manifest.platform,
+ abi: manifest.abi,
+ engineVersion: manifest.engineVersion,
+ dir,
+ current: manifest.engineVersion === engineVersion
+ && missingTemplateFiles(dir, manifest.platform, { abi: manifest.abi }).length === 0,
+ });
+ }
+ }
+ return out.sort((a, b) => b.engineVersion.localeCompare(a.engineVersion) || a.id.localeCompare(b.id));
+}
+
+export interface InstallResult {
+ ok: boolean;
+ id?: string;
+ engineVersion?: string;
+ dir?: string;
+ /** Installed, but built for another release — it is stored under its own
+ * version and simply will not be offered until the editor matches. */
+ versionMismatch?: boolean;
+ error?: string;
+}
+
+/**
+ * Install a template archive.
+ *
+ * Unpacked to a staging directory and validated BEFORE anything replaces an
+ * installed template: a truncated download must not take out the working copy.
+ * The archive is untrusted input, so entry names are checked by `extractZip`.
+ */
+export function installNativeTemplate(zipPath: string, engineVersion: string): InstallResult {
+ const store = templateStoreDir();
+ const staging = path.join(store, `.incoming-${randomUUID()}`);
+ try {
+ mkdirSync(staging, { recursive: true });
+ extractZip(readFileSync(zipPath), staging);
+
+ const manifest = readTemplateManifest(staging);
+ if (!manifest) {
+ return { ok: false, error: 'not an Estella runtime template (no readable template.json)' };
+ }
+ const missing = missingTemplateFiles(staging, manifest.platform, { abi: manifest.abi });
+ if (missing.length > 0) {
+ return { ok: false, error: `incomplete template — missing ${missing.join(', ')}` };
+ }
+
+ const dest = installedTemplateDir(manifest.engineVersion, manifest.platform, manifest.abi, store);
+ rmSync(dest, { recursive: true, force: true });
+ mkdirSync(path.dirname(dest), { recursive: true });
+ renameSync(staging, dest);
+ return {
+ ok: true,
+ id: manifest.id,
+ engineVersion: manifest.engineVersion,
+ dir: dest,
+ versionMismatch: manifest.engineVersion !== engineVersion,
+ };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ } finally {
+ rmSync(staging, { recursive: true, force: true });
+ }
+}
+
+/** Delete an installed template. Takes the id + version rather than a path, so a
+ * renderer can never ask the main process to remove an arbitrary directory. */
+export function removeNativeTemplate(platform: NativePlatform, abi: string, engineVersion: string): boolean {
+ const dir = installedTemplateDir(engineVersion, platform, abi || DEFAULT_ABI[platform]);
+ if (!readTemplateManifest(dir)) return false;
+ rmSync(dir, { recursive: true, force: true });
+ return true;
+}
diff --git a/desktop/electron/platformCatalog.ts b/desktop/electron/platformCatalog.ts
index f4a77884d..168050334 100644
--- a/desktop/electron/platformCatalog.ts
+++ b/desktop/electron/platformCatalog.ts
@@ -31,6 +31,8 @@ import {
type PlayableAdProfile,
} from './playableAdProfile';
import { BUILTIN_PLATFORMS, type PlatformPrereq } from '../src/project/platforms';
+import { resolveNativeTemplate } from './nativeTemplates';
+import { templateId, DEFAULT_ABI } from '../../build-tools/utils/nativeTemplate.js';
import type { MiniGameExportProfile, MiniGameConfigContext } from './miniGameExportProfile';
/** Where a project keeps its own platform profiles. */
@@ -99,7 +101,9 @@ function hasNdk(sdk: string): boolean {
}
/** A built-in target's runtime dependency, as a real file probe. */
-function builtinReadiness(id: string, dirs: PlatformRuntimeDirs): { ready: boolean; prereq?: PlatformPrereq } {
+function builtinReadiness(
+ id: string, dirs: PlatformRuntimeDirs, engineVersion: string,
+): { ready: boolean; prereq?: PlatformPrereq } {
const has = (dir: string, file: string) => existsSync(path.join(dir, file));
switch (id) {
@@ -131,13 +135,19 @@ function builtinReadiness(id: string, dirs: PlatformRuntimeDirs): { ready: boole
return hasNdk(sdk) ? { ready: true } : { ready: false, prereq: { kind: 'toolchain-missing', tool: 'android-ndk' } };
}
- case 'ios':
- // Apple's toolchain is macOS-only, so this row is honest about the machine
- // it is running on rather than pretending every editor can finish the job.
+ case 'ios': {
+ // The template comes first because it is the harder blocker: without it the
+ // export cannot even write the Xcode project. WITH it, a Windows editor
+ // writes a complete project (the xcframework included) to carry to a Mac —
+ // the artifact is portable even though Apple's toolchain is not.
+ if (!resolveNativeTemplate('ios', engineVersion)) {
+ return { ready: false, prereq: { kind: 'template-missing', id: templateId('ios', DEFAULT_ABI.ios), version: engineVersion } };
+ }
if (process.platform !== 'darwin') return { ready: false, prereq: { kind: 'toolchain-missing', tool: 'macos' } };
return existsSync('/Applications/Xcode.app')
? { ready: true }
: { ready: false, prereq: { kind: 'toolchain-missing', tool: 'xcode' } };
+ }
default:
return { ready: true };
@@ -613,11 +623,13 @@ export async function loadPlayableProfile(root: string | null, id: string | unde
* Every platform this project can target, built-ins first, then the project's
* own — each with its readiness probed.
*/
-export async function listPlatforms(root: string | null, dirs: PlatformRuntimeDirs): Promise<PlatformStatus[]> {
+export async function listPlatforms(
+ root: string | null, dirs: PlatformRuntimeDirs, engineVersion: string,
+): Promise<PlatformStatus[]> {
const out: PlatformStatus[] = BUILTIN_PLATFORMS.map((id) => ({
id,
source: 'builtin' as const,
- ...builtinReadiness(id, dirs),
+ ...builtinReadiness(id, dirs, engineVersion),
}));
if (!root) return out;
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 9a4a9abd8..df4f229de 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -13,6 +13,7 @@ import type {
import type { PlayRealmResult } from './buildPlayRealm';
import type { LatestRelease } from './updateCheck';
import type { DiscoveredPlugin, CompiledPlugin } from './pluginHost';
+import type { NativeTemplateEntry, InstallResult } from './nativeTemplates';
// The privileged bridge the renderer is allowed to touch. Keep this surface small
// and explicit — anything the editor needs from the OS or Node goes through here.
@@ -221,6 +222,16 @@ const api = {
/** Reveal the plugin's folder in Finder / Explorer. */
reveal: (id: string): Promise<void> => ipcRenderer.invoke('plugins:reveal', id),
},
+ // The prebuilt engine a mobile target is assembled around. The editor installs
+ // one; it never compiles one (see electron/nativeTemplates.ts).
+ nativeTemplates: {
+ list: (): Promise<NativeTemplateEntry[]> => ipcRenderer.invoke('nativeTemplates:list'),
+ /** Pick an archive and install it. Main owns the file dialog, so the renderer
+ * never handles a path it could have made up. */
+ install: (): Promise<InstallResult & { canceled?: boolean }> => ipcRenderer.invoke('nativeTemplates:install'),
+ remove: (platform: 'android' | 'ios', abi: string, version: string): Promise<boolean> =>
+ ipcRenderer.invoke('nativeTemplates:remove', platform, abi, version),
+ },
// Recent projects (launcher), persisted in userData.
recents: {
list: (): Promise<RecentEntry[]> => ipcRenderer.invoke('recents:list'),
diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsx
index da560ace5..7eab027c8 100644
--- a/desktop/src/components/BuildDialog.tsx
+++ b/desktop/src/components/BuildDialog.tsx
@@ -92,6 +92,9 @@ interface PlatformDef {
/** What KIND of prerequisite — a missing engine runtime blocks the package, a
* missing native toolchain only blocks the final app assembly. */
prereqKind?: PlatformPrereq['kind'];
+ /** The runtime template this target wants, when that is what is missing. Kept so
+ * the install action can say which version a wrong archive should have been. */
+ templateWant?: { id: string; version: string };
/** http-servable target → offer a loopback-http Preview (opening the build via
* file:// hits the browser's opaque-origin rules; http is its real surface). */
httpPreview?: boolean;
@@ -161,6 +164,9 @@ const TOOLCHAIN_TEXT: Record<NativeToolchain, string> = {
function prereqText(r: { prereq?: PlatformPrereq }): string | undefined {
if (!r.prereq) return undefined;
if (r.prereq.kind === 'toolchain-missing') return TOOLCHAIN_TEXT[r.prereq.tool];
+ if (r.prereq.kind === 'template-missing') {
+ return t('build.templateMissing', { id: r.prereq.id, version: r.prereq.version });
+ }
// A built-in target comes with the command that fixes it, and WHERE the editor
// keeps its runtime is not the developer's business — the command is. A project
// platform has no command (only the project knows how it builds one), so there
@@ -232,6 +238,10 @@ export function BuildDialog() {
const def = platforms.find((p) => p.id === platform) ?? platforms[0];
const running = phase === 'running';
+ // Bumped when something the probes read changes on disk (a runtime template is
+ // installed), so the rows re-probe instead of the dialog having to be reopened.
+ const [probeTick, setProbeTick] = useState(0);
+ const [templateNote, setTemplateNote] = useState<{ text: string; error: boolean } | null>(null);
useEffect(() => {
let alive = true;
@@ -246,6 +256,8 @@ export function BuildDialog() {
return {
...p, ready: r.ready, prereq: prereqText(r), prereqKind: r.prereq?.kind,
fixCommand: r.prereq?.kind === 'runtime-missing' ? r.prereq.command : undefined,
+ templateWant: r.prereq?.kind === 'template-missing'
+ ? { id: r.prereq.id, version: r.prereq.version } : undefined,
};
});
for (const r of rows) {
@@ -279,9 +291,10 @@ export function BuildDialog() {
if (cur && !saved.outDir?.[platform]) setOutDir(cur.defaultOut);
})();
return () => { alive = false; };
- // Runs once: the catalog is read when the dialog opens.
+ // The catalog is read when the dialog opens, and again when a probe's input
+ // changed (probeTick).
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ }, [probeTick]);
// The build's scene set, mirroring the exporter's discovery: every scene
// under the project's scenes dir (plus the entry wherever it lives), entry
@@ -396,6 +409,31 @@ export function BuildDialog() {
setTimeout(() => setCopiedFix(false), 1600);
};
+ /** Install a runtime template the user downloaded, then re-probe: the row that
+ * asked for it becomes ready without reopening the dialog. */
+ const installTemplate = async () => {
+ const res = await window.estella.nativeTemplates?.install?.();
+ if (!res || res.canceled) return;
+ if (!res.ok) {
+ setTemplateNote({ text: res.error ?? '', error: true });
+ return;
+ }
+ if (res.versionMismatch) {
+ setTemplateNote({
+ text: t('build.templateVersionMismatch', {
+ version: res.engineVersion ?? '', editor: def.templateWant?.version ?? '',
+ }),
+ error: true,
+ });
+ } else {
+ setTemplateNote({
+ text: t('build.templateInstalled', { id: res.id ?? '', version: res.engineVersion ?? '' }),
+ error: false,
+ });
+ }
+ setProbeTick((n) => n + 1);
+ };
+
const browse = async () => {
const dir = await window.estella.project?.chooseDirectory?.();
if (dir) setOutDir(dir);
@@ -625,8 +663,22 @@ export function BuildDialog() {
native toolchain still exports the app's content — only the
assembly step (which may run on another machine) needs it. */}
<span className="build__prereq-hint">
- {def.prereqKind === 'toolchain-missing' ? t('build.toolchainHint') : t('build.notReadyHint')}
+ {def.prereqKind === 'toolchain-missing' ? t('build.toolchainHint')
+ : def.prereqKind === 'template-missing' ? t('build.templateHint')
+ : t('build.notReadyHint')}
</span>
+ {def.prereqKind === 'template-missing' && (
+ <div className="build__fix">
+ <Button onClick={() => void installTemplate()}>
+ <Package size={12} /> {t('build.installTemplate')}
+ </Button>
+ {templateNote && (
+ <span className={templateNote.error ? 'is-error selectable' : 'selectable'}>
+ {templateNote.text}
+ </span>
+ )}
+ </div>
+ )}
{def.fixCommand && (
<div className="build__fix">
<code className="selectable">{def.fixCommand}</code>
diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.ts
index 868ce3a6d..86540c946 100644
--- a/desktop/src/i18n/messages/project.ts
+++ b/desktop/src/i18n/messages/project.ts
@@ -49,6 +49,25 @@ export const projectMessages = defineMessages({
en: 'Building the iOS app needs a Mac with Xcode — Apple ships no toolchain for this OS.',
zh: '构建 iOS 应用需要装有 Xcode 的 Mac——Apple 未在本系统提供工具链。',
},
+ // — The runtime template: the prebuilt engine a native app is assembled around.
+ // Not a toolchain and not something to build — an artifact of this release. —
+ 'build.templateMissing': {
+ en: 'No {id} runtime template for v{version} on this machine.',
+ zh: '本机没有 v{version} 的 {id} 运行时模板。',
+ },
+ 'build.templateHint': {
+ en: 'It is the prebuilt engine the app is assembled around — download it from this release and install it here, once per editor version. Building it yourself needs the engine sources.',
+ zh: '它是应用装配所围绕的预编译引擎——从本版本的发布页下载并在此安装,每个编辑器版本装一次即可。自行构建它需要引擎源码。',
+ },
+ 'build.installTemplate': { en: 'Install from file…', zh: '从文件安装…' },
+ 'build.templateInstalled': {
+ en: 'Installed the {id} runtime template (v{version}).',
+ zh: '已安装 {id} 运行时模板(v{version})。',
+ },
+ 'build.templateVersionMismatch': {
+ en: 'That template is built for v{version}; this editor is v{editor}. A template must match exactly — the SDK is compiled into the app binary.',
+ zh: '该模板面向 v{version} 构建,而当前编辑器是 v{editor}。模板必须精确匹配——SDK 是编译进应用二进制的。',
+ },
'build.toolchainHint': {
en: 'The export still writes the app\'s content here; assembling the installable app needs this toolchain, and that step can run on another machine.',
zh: '导出仍会在此写出应用内容;将其装配成可安装的应用才需要该工具链,且这一步可以在另一台机器上完成。',
@@ -144,8 +163,8 @@ export const projectMessages = defineMessages({
zh: '据此构建签名 APK:node build-tools/cli.js native --package --content {out}(一次性的 Dawn + QuickJS 准备见 native/README.md)。',
},
'build.next.ios': {
- en: 'On a Mac: node build-tools/cli.js native --target ios --package --content {out} — that writes the Xcode project around this content.',
- zh: '在 Mac 上运行:node build-tools/cli.js native --target ios --package --content {out} —— 它会围绕这份内容写出 Xcode 工程。',
+ en: 'The content is in {out}. Install the iOS runtime template to get an Xcode project written around it.',
+ zh: '内容已写入 {out}。安装 iOS 运行时模板后,导出会围绕它写出 Xcode 工程。',
},
'build.next.iosProject': {
en: 'The Xcode project is written — open it, pick your Team under Signing & Capabilities, then Run.',
diff --git a/desktop/src/project/platforms.ts b/desktop/src/project/platforms.ts
index b35cc5a1d..4ab59429d 100644
--- a/desktop/src/project/platforms.ts
+++ b/desktop/src/project/platforms.ts
@@ -97,6 +97,20 @@ export type PlatformPrereq =
kind: 'toolchain-missing';
/** Which piece is absent — the dialog maps it to a localized sentence. */
tool: NativeToolchain;
+ }
+ | {
+ /**
+ * No RUNTIME TEMPLATE for this target: the prebuilt engine a native app is
+ * assembled around (see `build-tools/utils/nativeTemplate.js`). Its own kind
+ * because the fix is neither "build the engine" nor "install a toolchain" —
+ * it is an artifact this editor release ships, installed once.
+ */
+ kind: 'template-missing';
+ /** The template looked for (`ios-arm64`). */
+ id: string;
+ /** The version it must carry — this editor's. A template is matched exactly:
+ * the SDK bundle is compiled into the app binary. */
+ version: string;
};
/** The native toolchain pieces the editor probes for. */
diff --git a/desktop/tests/native-template.test.ts b/desktop/tests/native-template.test.ts
new file mode 100644
index 000000000..7645c825f
--- /dev/null
+++ b/desktop/tests/native-template.test.ts
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// The runtime-template store. A native app's compiled half ships as an artifact
+// rather than being rebuilt on every user's machine, so what is pinned here is the
+// contract between the emitter and the editor:
+//
+// 1. A template is matched EXACTLY on version — the SDK bundle is compiled into
+// the app binary, so a near-miss fails on a device instead of in the dialog.
+// 2. An archive is untrusted input, and an incomplete one must not replace a
+// working install.
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import {
+ resolveNativeTemplate, iosSourcesFromTemplate, installNativeTemplate,
+ listNativeTemplates, removeNativeTemplate,
+} from '../electron/nativeTemplates';
+import { listPlatforms } from '../electron/platformCatalog';
+import {
+ requiredTemplateFiles, installedTemplateDir, TEMPLATE_FORMAT, TEMPLATE_MANIFEST,
+} from '../../build-tools/utils/nativeTemplate.js';
+import { makeZip } from '../../build-tools/utils/zip.js';
+
+const VERSION = '9.9.9';
+
+let store: string;
+let scratch: string;
+
+beforeEach(() => {
+ scratch = mkdtempSync(path.join(tmpdir(), 'es-tmpl-'));
+ store = path.join(scratch, 'templates');
+ process.env.ESTELLA_NATIVE_TEMPLATES = store;
+});
+
+afterEach(() => {
+ delete process.env.ESTELLA_NATIVE_TEMPLATES;
+ rmSync(scratch, { recursive: true, force: true });
+});
+
+/** Every file the layout declares required, with a stand-in body — so the fixture
+ * follows the contract rather than a copy of it that can go stale. */
+function templateEntries(version: string, omit?: string): { name: string; data: Buffer }[] {
+ const entries = requiredTemplateFiles('ios')
+ .filter((rel) => rel !== omit)
+ .map((rel) => ({ name: rel, data: Buffer.from(`stand-in for ${rel}`) }));
+ entries.push({
+ name: TEMPLATE_MANIFEST,
+ data: Buffer.from(JSON.stringify({
+ kind: 'estella-native-template',
+ formatVersion: TEMPLATE_FORMAT,
+ id: 'ios-arm64',
+ platform: 'ios',
+ abi: 'arm64',
+ engineVersion: version,
+ spineVersion: '4.2',
+ deploymentTarget: '17.0',
+ })),
+ });
+ return entries;
+}
+
+function writeTemplateZip(version: string, omit?: string): string {
+ const file = path.join(scratch, `template-${version}.zip`);
+ writeFileSync(file, makeZip(templateEntries(version, omit)));
+ return file;
+}
+
+describe('installing a runtime template', () => {
+ it('installs an archive and makes the platform resolvable', () => {
+ expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
+
+ const res = installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+
+ expect(res.ok).toBe(true);
+ expect(res.versionMismatch).toBe(false);
+ expect(res.dir).toBe(installedTemplateDir(VERSION, 'ios', 'arm64', store));
+
+ const resolved = resolveNativeTemplate('ios', VERSION);
+ expect(resolved?.manifest.engineVersion).toBe(VERSION);
+ const sources = iosSourcesFromTemplate(VERSION)!;
+ expect(existsSync(sources.xcframework)).toBe(true);
+ expect(existsSync(sources.mainM)).toBe(true);
+ expect(existsSync(sources.infoPlistIn)).toBe(true);
+ });
+
+ it('stores a template built for another release, but does not offer it', () => {
+ const res = installNativeTemplate(writeTemplateZip('1.0.0'), VERSION);
+
+ expect(res.ok).toBe(true);
+ // Named, so the dialog can say which version the archive was for.
+ expect(res.versionMismatch).toBe(true);
+ expect(res.engineVersion).toBe('1.0.0');
+ expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
+ expect(listNativeTemplates(VERSION)).toEqual([
+ expect.objectContaining({ id: 'ios-arm64', engineVersion: '1.0.0', current: false }),
+ ]);
+ });
+
+ it('rejects an incomplete archive, and leaves the installed one alone', () => {
+ installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+
+ const res = installNativeTemplate(writeTemplateZip(VERSION, 'App/main.m'), VERSION);
+
+ expect(res.ok).toBe(false);
+ expect(res.error).toContain('App/main.m');
+ // The working install survived the bad one.
+ expect(resolveNativeTemplate('ios', VERSION)).not.toBeNull();
+ });
+
+ it('rejects an archive that is not a template at all', () => {
+ const file = path.join(scratch, 'random.zip');
+ writeFileSync(file, makeZip([{ name: 'readme.txt', data: Buffer.from('hi') }]));
+
+ expect(installNativeTemplate(file, VERSION).error).toContain('template.json');
+ });
+
+ it('refuses an archive that would write outside the store', () => {
+ const file = path.join(scratch, 'evil.zip');
+ writeFileSync(file, makeZip([{ name: '../escaped.txt', data: Buffer.from('x') }]));
+
+ expect(installNativeTemplate(file, VERSION).error).toContain('unsafe');
+ expect(existsSync(path.join(scratch, 'escaped.txt'))).toBe(false);
+ });
+
+ it('treats a half-deleted install as absent rather than usable', () => {
+ installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+ rmSync(path.join(installedTemplateDir(VERSION, 'ios', 'arm64', store), 'App', 'main.m'));
+
+ expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
+ });
+
+ it('removes an installed template', () => {
+ installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+
+ expect(removeNativeTemplate('ios', 'arm64', VERSION)).toBe(true);
+ expect(resolveNativeTemplate('ios', VERSION)).toBeNull();
+ expect(removeNativeTemplate('ios', 'arm64', VERSION)).toBe(false);
+ });
+});
+
+describe('the iOS row reports what is missing', () => {
+ const dirs = () => ({ web: path.join(scratch, 'web'), wechat: path.join(scratch, 'wx') });
+ const iosRow = async () => (await listPlatforms(null, dirs(), VERSION)).find((r) => r.id === 'ios')!;
+
+ it('asks for the runtime template before anything about Xcode', async () => {
+ const row = await iosRow();
+
+ expect(row.ready).toBe(false);
+ expect(row.prereq).toEqual({ kind: 'template-missing', id: 'ios-arm64', version: VERSION });
+ });
+
+ it('moves on to the toolchain once a template is installed', async () => {
+ installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+
+ const row = await iosRow();
+
+ // On a Mac with Xcode that is everything; elsewhere the toolchain is the
+ // remaining gap — and the export still writes a project to carry to a Mac.
+ if (row.ready) expect(row.prereq).toBeUndefined();
+ else expect(row.prereq?.kind).toBe('toolchain-missing');
+ });
+});
+
+describe('the template layout is the one source of filenames', () => {
+ it('assembles the iOS project from paths inside the installed template', () => {
+ installNativeTemplate(writeTemplateZip(VERSION), VERSION);
+ const dir = installedTemplateDir(VERSION, 'ios', 'arm64', store);
+
+ const sources = iosSourcesFromTemplate(VERSION)!;
+
+ expect(sources.xcframework).toBe(path.join(dir, 'Estella.xcframework'));
+ expect(sources.mainM).toBe(path.join(dir, 'App', 'main.m'));
+ expect(sources.infoPlistIn).toBe(path.join(dir, 'App', 'Info.plist.in'));
+ // And each is something the emitter is required to have written.
+ const required = requiredTemplateFiles('ios');
+ for (const file of Object.values(sources)) {
+ expect(required).toContain(path.relative(dir, file).split(path.sep).join('/'));
+ }
+ });
+});
diff --git a/desktop/tests/platform-catalog.test.ts b/desktop/tests/platform-catalog.test.ts
index ebb2d5ccb..d3a1aa9db 100644
--- a/desktop/tests/platform-catalog.test.ts
+++ b/desktop/tests/platform-catalog.test.ts
@@ -23,6 +23,10 @@ let root: string;
let webDir: string;
let wxDir: string;
+/** The editor version the probes run as. A native runtime template is matched
+ * against it exactly, so the tests own both ends of that comparison. */
+const VERSION = '9.9.9';
+
const dirs = () => ({ web: webDir, wechat: wxDir });
function writePlatform(name: string, source: string): void {
@@ -37,15 +41,19 @@ beforeEach(() => {
wxDir = path.join(root, 'rt-wechat');
mkdirSync(webDir, { recursive: true });
mkdirSync(wxDir, { recursive: true });
+ // The native probes read the machine's template store; point it at this test's
+ // own empty one, or the result would depend on what the developer has installed.
+ process.env.ESTELLA_NATIVE_TEMPLATES = path.join(root, 'templates');
});
afterEach(() => {
+ delete process.env.ESTELLA_NATIVE_TEMPLATES;
rmSync(root, { recursive: true, force: true });
});
describe('listPlatforms — built-in readiness is probed', () => {
it('web/desktop/playable are not ready without the web engine glue', async () => {
- const rows = await listPlatforms(root, dirs());
+ const rows = await listPlatforms(root, dirs(), VERSION);
const byId = Object.fromEntries(rows.map((r) => [r.id, r]));
expect(byId.web.ready).toBe(false);
@@ -56,7 +64,7 @@ describe('listPlatforms — built-in readiness is probed', () => {
it('the web glue makes playable ready too — it inlines the WEB runtime, not a -t playable one', async () => {
writeFileSync(path.join(webDir, 'esengine.js'), '//');
- const rows = await listPlatforms(root, dirs());
+ const rows = await listPlatforms(root, dirs(), VERSION);
const byId = Object.fromEntries(rows.map((r) => [r.id, r]));
expect(byId.web.ready).toBe(true);
@@ -69,15 +77,15 @@ describe('listPlatforms — built-in readiness is probed', () => {
it('WeChat accepts either its own glue or a web-aligned one', async () => {
writeFileSync(path.join(wxDir, 'esengine.wxgame.js'), '//');
- expect((await listPlatforms(root, dirs())).find((r) => r.id === 'wechat')?.ready).toBe(true);
+ expect((await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'wechat')?.ready).toBe(true);
rmSync(path.join(wxDir, 'esengine.wxgame.js'));
writeFileSync(path.join(wxDir, 'esengine.js'), '//');
- expect((await listPlatforms(root, dirs())).find((r) => r.id === 'wechat')?.ready).toBe(true);
+ expect((await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'wechat')?.ready).toBe(true);
});
it('reports paths with forward slashes, whatever the platform separator', async () => {
- const wx = (await listPlatforms(root, dirs())).find((r) => r.id === 'wechat');
+ const wx = (await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'wechat');
expect(wx?.prereq?.dir).not.toContain('\\');
});
});
@@ -90,7 +98,7 @@ describe('listPlatforms — platforms the project defines', () => {
};`);
writeFileSync(path.join(webDir, 'esengine.js'), '//');
- const rows = await listPlatforms(root, dirs());
+ const rows = await listPlatforms(root, dirs(), VERSION);
const acme = rows.find((r) => r.id === 'acme');
expect(acme).toBeDefined();
expect(acme!.source).toBe('project');
@@ -107,7 +115,7 @@ describe('listPlatforms — platforms the project defines', () => {
};`);
writeFileSync(path.join(webDir, 'esengine.js'), '//');
- const acme = (await listPlatforms(root, dirs())).find((r) => r.id === 'acme');
+ const acme = (await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'acme');
expect(acme!.ready).toBe(false);
expect(acme!.prereq?.dir).toBe('build/wasm/acme');
// The editor does not know how a project builds its own runtime, so it
@@ -117,7 +125,7 @@ describe('listPlatforms — platforms the project defines', () => {
it('a broken profile is listed with its error, not silently dropped', async () => {
writePlatform('bad.mjs', 'export default { this is not valid javascript');
- const rows = await listPlatforms(root, dirs());
+ const rows = await listPlatforms(root, dirs(), VERSION);
const bad = rows.find((r) => r.id === 'bad');
expect(bad).toBeDefined();
expect(bad!.ready).toBe(false);
@@ -132,7 +140,7 @@ describe('listPlatforms — platforms the project defines', () => {
writePlatform('c.mjs', `export default { id: 'ok-id', emitConfigFiles: () => [] };`);
writePlatform('d.mjs', `export default { id: 'ok-id2', label: 'X' };`);
- const rows = await listPlatforms(root, dirs());
+ const rows = await listPlatforms(root, dirs(), VERSION);
const errs = rows.filter((r) => r.source === 'project').map((r) => r.error);
expect(errs).toHaveLength(4);
expect(errs[0]).toContain('built-in');
@@ -144,7 +152,7 @@ describe('listPlatforms — platforms the project defines', () => {
});
it('lists only built-ins when no project is open', async () => {
- const rows = await listPlatforms(null, dirs());
+ const rows = await listPlatforms(null, dirs(), VERSION);
expect(rows.every((r) => r.source === 'builtin')).toBe(true);
});
});
@@ -170,7 +178,7 @@ describe('createProjectPlatform — scaffolding', () => {
// What was scaffolded is immediately a real platform.
writeFileSync(path.join(webDir, 'esengine.js'), '//');
- const rows = await listPlatforms(root, dirs());
+ const rows = await listPlatforms(root, dirs(), VERSION);
const acme = rows.find((r) => r.id === 'acme-play');
expect(acme?.source).toBe('project');
expect(acme?.label).toBe('ACME Play');
@@ -271,7 +279,7 @@ describe('loadProjectPlatform — the profile handed to exportMiniGame', () => {
id: 'acme', label: 'ACME Play', runtimeProfile: 'src/missing.ts',
emitConfigFiles: () => [],
};`);
- const acme = (await listPlatforms(root, dirs())).find((r) => r.id === 'acme');
+ const acme = (await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'acme');
expect(acme!.ready).toBe(false);
expect(acme!.error).toContain('runtimeProfile');
});
@@ -283,7 +291,7 @@ describe('loadProjectPlatform — the profile handed to exportMiniGame', () => {
id: 'acme', label: 'A', runtimeProfile: 'src/rt', emitConfigFiles: () => [],
};`);
writeFileSync(path.join(webDir, 'esengine.js'), '//');
- const acme = (await listPlatforms(root, dirs())).find((r) => r.id === 'acme');
+ const acme = (await listPlatforms(root, dirs(), VERSION)).find((r) => r.id === 'acme');
expect(acme!.error).toBeUndefined();
expect(acme!.ready).toBe(true);
});
@@ -386,7 +394,7 @@ describe('playable ad networks', () => {
writePlatform('acme-mini.mjs', `export default {
id: 'acme-mini', label: 'Acme MiniGame', emitConfigFiles: () => [],
};`);
- expect((await listPlatforms(root, dirs())).map((r) => r.id)).not.toContain('acme-ads');
+ expect((await listPlatforms(root, dirs(), VERSION)).map((r) => r.id)).not.toContain('acme-ads');
expect((await listPlayableNetworks(root)).map((r) => r.id)).not.toContain('acme-mini');
// And a network id must not shadow a network the editor ships.
writePlatform('meta.mjs', "export default { id: 'meta', kind: 'playable', label: 'Mine', maxBytes: 1, limitNote: 'x' };");
diff --git a/desktop/tests/platform-trust.test.ts b/desktop/tests/platform-trust.test.ts
index ca6fe8125..11465838f 100644
--- a/desktop/tests/platform-trust.test.ts
+++ b/desktop/tests/platform-trust.test.ts
@@ -22,6 +22,7 @@ import { discoverPlugins } from '../electron/pluginHost';
let root: string;
let userData: string;
const dirs = { web: '/nonexistent-web', wechat: '/nonexistent-wechat' };
+const VERSION = '9.9.9';
/** Set by a loaded profile, so a test can prove whether the import actually ran. */
const IMPORT_MARKER = 'estella-platform-trust-test-imported';
@@ -29,6 +30,8 @@ const IMPORT_MARKER = 'estella-platform-trust-test-imported';
beforeAll(() => {
root = mkdtempSync(path.join(tmpdir(), 'estella-platform-'));
userData = mkdtempSync(path.join(tmpdir(), 'estella-userdata-'));
+ // Keep the native probes off this machine's installed templates.
+ process.env.ESTELLA_NATIVE_TEMPLATES = path.join(root, 'templates');
mkdirSync(path.join(root, PROJECT_PLATFORM_DIR), { recursive: true });
writeFileSync(
path.join(root, PROJECT_PLATFORM_DIR, 'acme.mjs'),
@@ -39,6 +42,7 @@ beforeAll(() => {
afterAll(() => {
setPlatformTrustGate(null);
+ delete process.env.ESTELLA_NATIVE_TEMPLATES;
rmSync(root, { recursive: true, force: true });
rmSync(userData, { recursive: true, force: true });
});
@@ -48,7 +52,7 @@ afterEach(() => {
delete (globalThis as Record<string, unknown>)[IMPORT_MARKER];
});
-const acmeRow = async () => (await listPlatforms(root, dirs)).find((p) => p.id === 'acme');
+const acmeRow = async () => (await listPlatforms(root, dirs, VERSION)).find((p) => p.id === 'acme');
describe('project platform trust gate', () => {
it('does not import an unapproved profile', async () => {