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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): a platform list that can grow, and says what is missing before you build
yhh7a4d608e9e91
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex dd898e14a..24a55770b 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -30,6 +30,8 @@ import { activeRemoteRoot } from '../../sdk/src/asset/assetGroups';import type { PackagedGameConfig } from 'esengine';import { IMPORT_MAP_JSON, IMPORT_MAP_CSP_HASH } from './buildPlayRealm';import { exportWeChat } from './exportWeChat';+import { exportMiniGame } from './exportMiniGame';+import type { MiniGameExportProfile } from './miniGameExportProfile';import { exportPlayable } from './exportPlayable';import type { OnExportProgress } from './exportProgress';import { ESENGINE_EXTERNAL } from './esengineResolve';@@ -339,6 +341,11 @@ export async function exportGame(opts: {desktopProductName?: string;/** WeChat appid (Project Settings → Packaging → WeChat). */wechatAppid?: string;+ /** A project-supplied mini-game export profile (`.esengine/platforms/<id>.mjs`),+ * for a platform the editor does not ship. Present ⇒ the mini-game pipeline+ * runs with it, whatever `platform` says. Loaded by the main process, which is+ * where its emit hooks can be called. */+ miniGameProfile?: MiniGameExportProfile;/** Project-wide screen orientation (format.ts resolveOrientation) — consumed by* EVERY target: WeChat game.json, the web/playable rotate hint, the desktop* window's aspect. Default landscape (the engine's 1920×1080 Canvas aspect). */@@ -373,6 +380,36 @@ export async function exportGame(opts: {const progress = opts.onProgress ?? (() => {});const scenes = await discoverProjectScenes(opts.root, opts.entryScene, opts.scenesDir, opts.excludeScenes);+ // A platform the editor does not ship: the project supplied an export profile+ // (.esengine/platforms/<id>.mjs, loaded by the main process since it carries+ // functions). It rides the same vendor-neutral mini-game pipeline WeChat does+ // — that pipeline taking a profile is exactly what makes this possible.+ if (opts.miniGameProfile) {+ return exportMiniGame(opts.miniGameProfile, {+ root: opts.root,+ entryScene: opts.entryScene,+ scenes,+ scriptsEntry: opts.scriptsEntry,+ sdkDir: opts.sdkDistDir,+ wasmDir: opts.wasmDir,+ outDir: opts.outDir,+ title,+ appid: opts.wechatAppid,+ orientation,+ ySortLayers: opts.ySortLayers,+ colorSpace: opts.colorSpace,+ screenFit: opts.screenFit,+ uiTheme: opts.uiTheme,+ uiThemeColors: opts.uiThemeColors,+ minify: opts.minify,+ contentAddressed: opts.contentAddressed,+ compressTextures: opts.compressTextures,+ compressAudio: opts.compressAudio,+ atlasTextures: opts.atlasTextures,+ onProgress: opts.onProgress,+ });+ }+// WeChat has no import maps + a different module/asset model → its own pipeline.if (platform === 'wechat') {return exportWeChat({diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 71d32ab98..8e6ffbd5f 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -39,6 +39,7 @@ import { ensureProjectShaderTwins } from './shaderTwins';import { installCrashCapture, logsDir } from './resilience';import { mcpMode, startMcpEndpoint } from './mcpEndpoint';import { checkForUpdate } from './updateCheck';+import { listPlatforms, loadProjectPlatform, type PlatformRuntimeDirs } from './platformCatalog';import { resolveLayout, resolveScripts, resolveOrientation, resolveScreenFit, type ExportPlatform } from '../src/project/format';import type { WorkspaceState } from '../src/project/format';@@ -558,6 +559,19 @@ const requireRoot = (): string => {return projectRoot;};+/**+ * Engine runtime dirs — probed by the platform catalog and copied from by the+ * exporters. Resolved in one place so "is this target ready?" and "where does+ * its runtime come from?" can never answer differently.+ */+const platformRuntimeDirs = (): PlatformRuntimeDirs => ({+ web: WEB_WASM_DIR,+ // The -t wechat build (WXWebAssembly glue) syncs to wasm-wechat; fall back to+ // the repo's build dir when running from source.+ wechat: [unpacked(path.join(VITE_PUBLIC, 'wasm-wechat')), path.join(process.env.APP_ROOT!, '..', 'build', 'wasm', 'wechat')]+ .find(existsSync) ?? unpacked(path.join(VITE_PUBLIC, 'wasm-wechat')),+});+// Adopt a freshly opened project as the active root + (re)start the fs watcher// so on-disk changes push to the renderer, and stage the SDK types into// .esengine/sdk so the project's tsconfig resolves `esengine` in the IDE.@@ -755,6 +769,11 @@ ipcMain.handle('project:cookAssets', async (_e, outDir?: string) => {return cookAssets(root, { entryScenes: entry ? [entry] : [], outDir: outDir ?? 'build' });});+// 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()));+// Export a runnable web build (play == ship): cook + game host + wasm + index.html.ipcMain.handle('project:exportGame',@@ -764,11 +783,16 @@ ipcMain.handle(const entryScene = manifest.defaultScene;if (!entryScene) throw new Error('project has no defaultScene to export');const sdkDistDir = SDK_DIST;- const webWasm = WEB_WASM_DIR;- // WeChat needs the -t wechat runtime (WXWebAssembly glue); build it with- // `node build-tools/cli.js build -t wechat`. Absent → exportWeChat warns.- const wechatWasm = [unpacked(path.join(VITE_PUBLIC, 'wasm-wechat')), path.join(process.env.APP_ROOT!, '..', 'build', 'wasm', 'wechat')]- .find(existsSync) ?? unpacked(path.join(VITE_PUBLIC, 'wasm-wechat'));+ const dirs = platformRuntimeDirs();+ const webWasm = dirs.web;+ const wechatWasm = dirs.wechat;+ // A platform the editor does not ship: the project defines it in+ // .esengine/platforms/<id>.mjs. Loaded HERE because the profile carries emit+ // hooks (functions), which cannot cross IPC — the renderer only ever saw its+ // metadata. Absent for every built-in id.+ const projectPlatform = opts?.platform+ ? await loadProjectPlatform(root, opts.platform, dirs)+ : null;const plat = manifest.packaging?.platforms;const ySortLayers =(manifest.features?.rendering?.ySortLayers ?? []).reduce((m, i) => m | (1 << i), 0) >>> 0;@@ -792,10 +816,12 @@ ipcMain.handle(playableHostEntry: path.join(HOSTS_DIR, 'playableHost.js'),scriptsEntry: resolveScripts(manifest).main,sdkDistDir,- wasmDir: opts?.platform === 'wechat' ? wechatWasm : webWasm,+ // A project platform names its own runtime dir (default: the web one).+ wasmDir: projectPlatform ? projectPlatform.wasmDir : opts?.platform === 'wechat' ? wechatWasm : webWasm,outDir: opts?.outDir || 'dist-game',title: manifest.name,platform: opts?.platform,+ miniGameProfile: projectPlatform?.profile,desktopAppId: plat?.desktop?.appId,desktopProductName: plat?.desktop?.productName,wechatAppid: plat?.wechat?.appid,diff --git a/desktop/electron/miniGameExportProfile.ts b/desktop/electron/miniGameExportProfile.tsindex 1bb18cdea..8569ab6d7 100644--- a/desktop/electron/miniGameExportProfile.ts+++ b/desktop/electron/miniGameExportProfile.ts@@ -41,6 +41,28 @@ export interface MiniGameEntryContext {engineGlueFile: string;}+/**+ * The generated mini-game entry: require the engine glue + each side module,+ * then boot the bundle. Pure CommonJS with no vendor API in it — every host+ * loads JS the same way — so this is the family default, and a profile only+ * overrides it for an unusual loader.+ */+export function defaultMiniGameEntry(ctx: MiniGameEntryContext): string {+ const requires = ctx.sideModules+ .map((m) => ` ${JSON.stringify(m.id)}: asFactory(require('./wasm/${m.file}.js')),`)+ .join('\n');+ return `'use strict';+// Generated by Estella exportGame (MiniGame entry).+const asFactory = (m) => (typeof m === 'function' ? m : (m && m.default) || m);+const engineFactory = asFactory(require('./wasm/${ctx.engineGlueFile}'));+const sideModuleFactories = {+${requires}+};+const bundle = require('./game-bundle.js');+bundle.boot(engineFactory, sideModuleFactories);+`;+}+export interface MiniGameExportProfile {/** Vendor identity — the export result's `platform` + diagnostics. */readonly id: MiniGameVendor;@@ -125,19 +147,5 @@ export const wechatExportProfile: MiniGameExportProfile = {];},- emitEntry(ctx) {- const requires = ctx.sideModules- .map((m) => ` ${JSON.stringify(m.id)}: asFactory(require('./wasm/${m.file}.js')),`)- .join('\n');- return `'use strict';-// Generated by Estella exportGame (WeChat MiniGame entry).-const asFactory = (m) => (typeof m === 'function' ? m : (m && m.default) || m);-const engineFactory = asFactory(require('./wasm/${ctx.engineGlueFile}'));-const sideModuleFactories = {-${requires}-};-const bundle = require('./game-bundle.js');-bundle.boot(engineFactory, sideModuleFactories);-`;- },+ emitEntry: defaultMiniGameEntry,};diff --git a/desktop/electron/platformCatalog.ts b/desktop/electron/platformCatalog.tsnew file mode 100644index 000000000..359efd0fd--- /dev/null+++ b/desktop/electron/platformCatalog.ts@@ -0,0 +1,273 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The set of platforms this project can package for, and whether each one+ * can actually run right now.+ *+ * Two things the renderer cannot answer for itself:+ *+ * 1. READINESS. A target needs its engine runtime on disk; the dialog used+ * to carry a static "requires the X runtime" line that showed whether or+ * not you had built it — noise when you had, and a surprise mid-export+ * when you hadn't. Readiness is a filesystem fact, so it is probed here.+ *+ * 2. PROJECT PLATFORMS. A game can ship a vendor the editor does not know+ * about by dropping a profile in `.esengine/platforms/<id>.mjs`. Those+ * modules export FUNCTIONS (emitConfigFiles / emitEntry), which cannot+ * cross the IPC boundary — so the renderer gets metadata only, and the+ * profile itself is loaded here, in the process that runs the export.+ *+ * The mini-game family is what makes (2) cheap: the pipeline is already+ * vendor-neutral (exportMiniGame), so a project platform is a data literal+ * merged over MINIGAME_PROFILE_DEFAULTS, not a fork of anything.+ */+import { existsSync } from 'node:fs';+import { readdir } from 'node:fs/promises';+import path from 'node:path';+import { pathToFileURL } from 'node:url';+import { defaultMiniGameEntry } from './miniGameExportProfile';+import type { MiniGameExportProfile, MiniGameConfigContext } from './miniGameExportProfile';++/** Where a project keeps its own platform profiles. */+export const PROJECT_PLATFORM_DIR = path.join('.esengine', 'platforms');++/** Engine runtime dirs the probes look in (resolved by main.ts). */+export interface PlatformRuntimeDirs {+ /** Web/playable engine runtime (esengine.js + esengine.wasm). */+ web: string;+ /** WeChat engine runtime (esengine.wxgame.js + .wasm). */+ wechat: string;+}++/** What the renderer needs to draw one platform row. Serializable by construction. */+export interface PlatformStatus {+ id: string;+ /** 'builtin' rows get their label/icon/blurb from the editor's i18n; 'project'+ * rows carry their own, since the project named them. */+ source: 'builtin' | 'project';+ /** The engine runtime this target needs is present. */+ ready: boolean;+ /** Present when `ready` is false. STRUCTURED, not prose: the main process has+ * no locale, so it reports the facts and the renderer writes the sentence. */+ prereq?: {+ kind: 'runtime-missing';+ /** Display path that was searched (project-relative where possible). */+ dir: string;+ /** Glue filenames looked for in it. */+ looked: string[];+ /** The build command that produces it — only when the editor ships that target. */+ command?: string;+ };+ /** Project platforms only — display data lifted from the profile. */+ label?: string;+ blurb?: string;+ defaultOut?: string;+ /** Project platforms only — the module failed to load, and why. The row still+ * appears (silently dropping a file the user wrote is worse than naming it). */+ error?: string;+}++// =============================================================================+// Built-in readiness+// =============================================================================++/** Display paths with forward slashes — the dialog shows them to a human, and a+ * Windows `build\wasm\acme` reads worse than `build/wasm/acme`. */+const posix = (p: string): string => p.split(path.sep).join('/');++/** A built-in target's runtime dependency, as a real file probe. */+function builtinReadiness(id: string, dirs: PlatformRuntimeDirs): { ready: boolean; prereq?: PlatformStatus['prereq'] } {+ const has = (dir: string, file: string) => existsSync(path.join(dir, file));++ 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 'playable':+ // Playable inlines the WEB runtime (exportPlayable reads esengine.js) — it+ // does NOT need a `-t playable` build, whatever the old static hint said.+ 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 'wechat':+ return has(dirs.wechat, 'esengine.wxgame.js') || has(dirs.wechat, 'esengine.js')+ ? { ready: true }+ : { ready: false, prereq: { kind: 'runtime-missing', dir: posix(dirs.wechat), looked: ['esengine.wxgame.js'], command: 'node build-tools/cli.js build -t wechat' } };++ case 'native':+ // The native host is a C++ build with its own toolchain — not a file the+ // editor can stage, so this stays advisory rather than a probe.+ return { ready: true };++ default:+ return { ready: true };+ }+}++const BUILTIN_IDS = ['web', 'desktop', 'wechat', 'playable', 'native'] as const;++// =============================================================================+// Project platform profiles+// =============================================================================++/**+ * Everything a mini-game export profile needs when the project did not say.+ * Defaults describe a STANDARD host: the vendor-neutral SDK entry, the standard+ * `WebAssembly` engine glue, and the generic entry above. A project platform+ * that matches those supplies only `id`, `label` and `emitConfigFiles`.+ */+export const MINIGAME_PROFILE_DEFAULTS = {+ sdkEntryFile: 'index.minigame.js',+ runtimeInit: 'initMiniGameRuntime',+ engineGlueCandidates: ['esengine.js'] as readonly string[],+ esTarget: 'es2017' as const,+ wasmBuildHint: 'web',+ sideModuleBuildTargets: {} as Readonly<Record<string, string>>,+ nativeSuffixes: new Set(['.js', '.json']) as ReadonlySet<string>,+ binRestageExts: [] as readonly string[],+ subpackageDir: 'subpackages',+ emitEntry: defaultMiniGameEntry,+};++/** The shape a `.esengine/platforms/<id>.mjs` default-exports. */+export interface ProjectPlatformModule extends Partial<MiniGameExportProfile> {+ id: string;+ /** Shown in the platform list (the project names its own platforms). */+ label: string;+ blurb?: string;+ defaultOut?: string;+ /** Engine runtime dir for this platform, relative to the project root.+ * Absent → the editor's web runtime. */+ wasmDir?: string;+ emitConfigFiles(ctx: MiniGameConfigContext): Array<{ file: string; content: string }>;+}++/** A loaded project platform: the export profile plus where its runtime lives. */+export interface ProjectPlatform {+ profile: MiniGameExportProfile;+ /** Absolute runtime dir, resolved from the module's `wasmDir` or the web default. */+ wasmDir: string;+ defaultOut: string;+}++function platformDir(root: string): string {+ return path.join(root, PROJECT_PLATFORM_DIR);+}++/** Ids that would collide with a built-in, or that are unsafe as a directory name. */+function idProblem(id: unknown): string | null {+ if (typeof id !== 'string' || id.length === 0) return 'profile has no string `id`';+ if (!/^[a-z0-9][a-z0-9-]*$/.test(id)) return `id "${id}" must be lowercase letters, digits and dashes`;+ if ((BUILTIN_IDS as readonly string[]).includes(id)) return `id "${id}" is a built-in platform`;+ return null;+}++/**+ * Import one project platform module. Returns its raw export, or an error string+ * — never throws: a project that ships a broken profile must still be able to+ * open the dialog and package for every other target.+ */+async function importPlatformModule(file: string): Promise<{ mod?: ProjectPlatformModule; error?: string }> {+ try {+ // Cache-busted so editing the profile and re-opening the dialog picks it up+ // without restarting the editor.+ const url = `${pathToFileURL(file).href}?t=${Date.now()}`;+ const ns = (await import(/* @vite-ignore */ url)) as { default?: unknown };+ const mod = ns.default;+ if (!mod || typeof mod !== 'object') return { error: 'module has no default export object' };+ const candidate = mod as ProjectPlatformModule;+ const bad = idProblem(candidate.id);+ if (bad) return { error: bad };+ if (typeof candidate.label !== 'string' || !candidate.label) return { error: 'profile has no `label`' };+ if (typeof candidate.emitConfigFiles !== 'function') return { error: 'profile has no `emitConfigFiles(ctx)`' };+ return { mod: candidate };+ } catch (err) {+ return { error: err instanceof Error ? err.message : String(err) };+ }+}++/** Every `.mjs` under the project's platform dir, sorted for a stable list. */+async function projectPlatformFiles(root: string): Promise<string[]> {+ const dir = platformDir(root);+ if (!existsSync(dir)) return [];+ try {+ const names = await readdir(dir);+ return names.filter((n) => n.endsWith('.mjs')).sort().map((n) => path.join(dir, n));+ } catch {+ return [];+ }+}++/**+ * Load the project platform with this id, merged over the family defaults and+ * ready to hand to {@link exportMiniGame}. Null when there is no such platform.+ */+export async function loadProjectPlatform(root: string, id: string, dirs: PlatformRuntimeDirs): Promise<ProjectPlatform | null> {+ for (const file of await projectPlatformFiles(root)) {+ const { mod } = await importPlatformModule(file);+ if (!mod || mod.id !== id) continue;+ const profile = { ...MINIGAME_PROFILE_DEFAULTS, ...mod } as MiniGameExportProfile;+ const wasmDir = mod.wasmDir+ ? (path.isAbsolute(mod.wasmDir) ? mod.wasmDir : path.join(root, mod.wasmDir))+ : dirs.web;+ return { profile, wasmDir, defaultOut: mod.defaultOut ?? `dist-${id}` };+ }+ return null;+}++// =============================================================================+// The catalog+// =============================================================================++/**+ * 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[]> {+ const out: PlatformStatus[] = BUILTIN_IDS.map((id) => ({+ id,+ source: 'builtin' as const,+ ...builtinReadiness(id, dirs),+ }));++ if (!root) return out;++ for (const file of await projectPlatformFiles(root)) {+ const { mod, error } = await importPlatformModule(file);+ if (error || !mod) {+ out.push({+ id: path.basename(file, '.mjs'),+ source: 'project',+ ready: false,+ label: path.basename(file),+ error,+ });+ continue;+ }+ const wasmDir = mod.wasmDir+ ? (path.isAbsolute(mod.wasmDir) ? mod.wasmDir : path.join(root, mod.wasmDir))+ : dirs.web;+ const glues = mod.engineGlueCandidates ?? MINIGAME_PROFILE_DEFAULTS.engineGlueCandidates;+ const ready = glues.some((g) => existsSync(path.join(wasmDir, g)));+ out.push({+ id: mod.id,+ source: 'project',+ ready,+ label: mod.label,+ blurb: mod.blurb,+ defaultOut: mod.defaultOut ?? `dist-${mod.id}`,+ prereq: ready+ ? undefined+ // No command: the editor does not know how this project builds its own+ // engine runtime, so it reports where it looked and stops there.+ : { kind: 'runtime-missing', dir: posix(path.relative(root, wasmDir) || wasmDir), looked: [...glues] },+ });+ }++ return out;+}diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex fd149ea4e..c0f31b7c0 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -7,6 +7,7 @@ import type { ExtractSchemasResult } from './extractSchemas';import type { ScanAssetsResult, AssetIndex, IncrementalScanResult } from './assetDb';import type { CookResult } from './cookAssets';import type { ExportGameResult } from './exportGame';+import type { PlatformStatus } from './platformCatalog';import type { PlayRealmResult } from './buildPlayRealm';import type { LatestRelease } from './updateCheck';@@ -93,6 +94,9 @@ const api = {ipcRenderer.invoke('project:scanAssetsIncremental', paths),/** Cook reachable assets for shipping → staged files + runtime manifest in `outDir`. */cookAssets: (outDir?: string): Promise<CookResult> => ipcRenderer.invoke('project:cookAssets', outDir),+ /** The platforms this project can package for — built-ins plus any the project+ * defines in `.esengine/platforms/` — each with its engine runtime probed. */+ listPlatforms: (): Promise<PlatformStatus[]> => ipcRenderer.invoke('project:listPlatforms'),/** Export a runnable web build (play==ship) → self-contained `outDir` (default dist-game/). */exportGame: (opts?: { outDir?: string; minify?: boolean; sourcemap?: boolean; platform?: ExportPlatform; compressTextures?: boolean; compressAudio?: boolean; atlasTextures?: boolean }): Promise<ExportGameResult> =>ipcRenderer.invoke('project:exportGame', opts),diff --git a/desktop/src/components/BuildDialog.tsx b/desktop/src/components/BuildDialog.tsxindex 84c33c35c..3f7807b59 100644--- a/desktop/src/components/BuildDialog.tsx+++ b/desktop/src/components/BuildDialog.tsx@@ -3,10 +3,19 @@/*** @file BuildDialog.tsx — the "Package Project" modal.* Pick a target platform + configuration + output, hit Build, watch the- * cook → bundle → copy run, then reveal the output. The dialog is driven by- * a per-platform descriptor table ({@link PLATFORMS}): each platform supplies- * its icon, blurb, default output, which options apply, any build prerequisite,- * and the post-build next-steps — so the UI is contextual per target.+ * cook → bundle → copy run, then reveal the output.+ *+ * Layout: a category'd platform nav on the left, that platform's settings on+ * the right — the same shape (and the same visual language) as the Settings+ * dialog's section nav, because the platform list only grows: mini-game+ * vendors, mobile targets, and whatever a project defines for itself. A row+ * of tiles could not take that.+ *+ * The list is assembled, not hardcoded. Built-ins supply their icon/label/+ * blurb here; the main process supplies READINESS (is this target's engine+ * runtime actually on disk?) and any platform the project defines in+ * `.esengine/platforms/`. So a target says what it needs BEFORE a build runs,+ * and a project's own vendor sits in the list beside the built-ins.** Altitude: this dialog is the *publish* layer, so it does NOT carry* per-asset optimization. Texture compression / Max Size / audio bitrate are@@ -14,10 +23,10 @@* chooses whether to HONOR those settings (`assetCompression: 'auto'`) or* skip them for fast iteration (`'skip'`). Every target is live.*/-import { useState, useSyncExternalStore, type ReactNode } from 'react';+import { useState, useEffect, useSyncExternalStore, type ReactNode } from 'react';import {Loader2, FolderOpen, CheckCircle2, AlertCircle, Boxes, Info, Copy, ExternalLink, Play,- Globe, Monitor, MessageSquare, ChevronRight, Smartphone,+ Globe, Monitor, MessageSquare, ChevronRight, Smartphone, Package, TriangleAlert,} from 'lucide-react';import type { ExportPlatform } from '@/project/format';import { Modal } from '@/components/Modal';@@ -42,12 +51,30 @@ interface Result {errors: string[];}+/** Nav groupings. Order here is the order they appear. */+type PlatformCategory = 'general' | 'minigame' | 'mobile' | 'custom';++const CATEGORY_ORDER: PlatformCategory[] = ['general', 'minigame', 'mobile', 'custom'];+const CATEGORY_LABEL: Record<PlatformCategory, string> = {+ general: t('build.cat.general'),+ minigame: t('build.cat.minigame'),+ mobile: t('build.cat.mobile'),+ custom: t('build.cat.custom'),+};+/** Per-platform packaging descriptor — drives the contextual UI + guidance. */interface PlatformDef {id: Platform;label: string;ready: boolean;- /** Target glyph shown on the platform tile. */+ category: PlatformCategory;+ /** Defined by the project rather than shipped by the editor. */+ custom?: boolean;+ /** A project platform whose profile module threw — shown, not swallowed. */+ loadError?: string;+ /** The command that produces this target's missing runtime (probed, not assumed). */+ fixCommand?: string;+ /** Target glyph shown in the nav. */icon: ReactNode;/** One-line description of the target (shown under the platform row). */blurb: string;@@ -63,35 +90,37 @@ interface PlatformDef {next: (outDir: string) => string;}-const PLATFORMS: PlatformDef[] = [+/** The targets the editor ships. Readiness is filled in from the main process —+ * the static "requires the X runtime" lines these used to carry showed whether or+ * not you had built it, and one of them (playable) was simply wrong: that export+ * inlines the WEB runtime, not a `-t playable` one. */+const BUILTIN_PLATFORMS: PlatformDef[] = [{- id: 'web', label: t('build.plat.web'), ready: true, icon: <Globe size={17} />,+ id: 'web', label: t('build.plat.web'), ready: true, category: 'general', icon: <Globe size={17} />,blurb: t('build.blurb.web'),defaultOut: 'dist-web', sourceMaps: true, httpPreview: true,next: (o) => t('build.next.web', { out: o }),},{- id: 'desktop', label: t('build.plat.desktop'), ready: true, icon: <Monitor size={17} />,+ id: 'desktop', label: t('build.plat.desktop'), ready: true, category: 'general', icon: <Monitor size={17} />,blurb: t('build.blurb.desktop'),defaultOut: 'dist-desktop', sourceMaps: true,next: (o) => t('build.next.desktop', { out: o }),},{- id: 'wechat', label: t('build.plat.wechat'), ready: true, icon: <MessageSquare size={17} />,+ id: 'wechat', label: t('build.plat.wechat'), ready: true, category: 'minigame', icon: <MessageSquare size={17} />,blurb: t('build.blurb.wechat'),defaultOut: 'dist-wechat', sourceMaps: false,- prereq: t('build.prereq.wechat'),next: (o) => t('build.next.wechat', { out: o }),},{- id: 'playable', label: t('build.plat.playable'), ready: true, icon: <Play size={16} />,+ id: 'playable', label: t('build.plat.playable'), ready: true, category: 'general', icon: <Play size={16} />,blurb: t('build.blurb.playable'),defaultOut: 'dist-playable', sourceMaps: false, httpPreview: true,- prereq: t('build.prereq.playable'),next: () => t('build.next.playable'),},{- id: 'native', label: t('build.plat.native'), ready: true, icon: <Smartphone size={17} />,+ id: 'native', label: t('build.plat.native'), ready: true, category: 'mobile', icon: <Smartphone size={17} />,blurb: t('build.blurb.native'),defaultOut: 'dist-native', sourceMaps: false,prereq: t('build.prereq.native'),@@ -101,6 +130,18 @@ const PLATFORMS: PlatformDef[] = [const mb = (bytes: number): string => `${(bytes / 1024 / 1024).toFixed(1)} MB`;+/** The main process reports WHERE it looked and FOR WHAT; the sentence is written+ * here, where the locale is. */+function prereqText(r: { prereq?: { dir: string; looked: string[]; command?: string } }): string | undefined {+ if (!r.prereq) return undefined;+ // 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+ // the searched dir IS the actionable fact: it is a path the project configured.+ if (r.prereq.command) return t('build.notReady');+ return t('build.runtimeMissingIn', { dir: r.prereq.dir, files: r.prereq.looked.join(', ') });+}+/** A titled section box — gives the dialog visual grouping instead of a flat column. */function Group({ title, count, children }: { title: string; count?: string; children: ReactNode }) {return (@@ -121,7 +162,11 @@ export function BuildDialog() {// Restore the project's persisted Package Project settings (project.esproject).const [saved] = useState(() => ProjectStore.packagingSettings());const initialPlatform: Platform = saved.platform ?? 'web';- const initialDef = PLATFORMS.find((p) => p.id === initialPlatform) ?? PLATFORMS[0];+ const initialDef = BUILTIN_PLATFORMS.find((p) => p.id === initialPlatform) ?? BUILTIN_PLATFORMS[0];++ // The built-ins are what we can draw immediately; readiness and the project's+ // own platforms arrive from the main process (both are filesystem facts).+ const [platforms, setPlatforms] = useState<PlatformDef[]>(BUILTIN_PLATFORMS);const [platform, setPlatform] = useState<Platform>(initialPlatform);const [config, setConfig] = useState<Config>(saved.config ?? 'shipping');@@ -133,6 +178,7 @@ export function BuildDialog() {// Inspector; this only picks whether to apply them.const [assetCompression, setAssetCompression] = useState<AssetCompression>(saved.assetCompression ?? 'auto');const [advOpen, setAdvOpen] = useState(false);+ const [copiedFix, setCopiedFix] = useState(false);const [phase, setPhase] = useState<Phase>('idle');const [result, setResult] = useState<Result | null>(null);const [log, setLog] = useState<string[]>([]);@@ -140,9 +186,52 @@ export function BuildDialog() {// assets are fetched from for hot update. Written on blur.const [cdnRoot, setCdnRoot] = useState(() => ProjectStore.activeProfileRemoteRoot());- const def = PLATFORMS.find((p) => p.id === platform)!;+ const def = platforms.find((p) => p.id === platform) ?? platforms[0];const running = phase === 'running';+ useEffect(() => {+ let alive = true;+ void (async () => {+ const rows = (await window.estella.project?.listPlatforms?.()) ?? [];+ if (!alive || rows.length === 0) return;+ const byId = new Map(rows.map((r) => [r.id, r]));+ const merged: PlatformDef[] = BUILTIN_PLATFORMS.map((p) => {+ const r = byId.get(p.id);+ if (!r) return p;+ // A probed prerequisite replaces the static one; `prereq` survives only+ // where there is nothing to probe (native's toolchain).+ return { ...p, ready: r.ready, prereq: prereqText(r) ?? p.prereq, fixCommand: r.prereq?.command };+ });+ for (const r of rows) {+ if (r.source !== 'project') continue;+ merged.push({+ id: r.id,+ label: r.label ?? r.id,+ ready: r.ready,+ category: 'custom',+ custom: true,+ loadError: r.error,+ icon: <Package size={17} />,+ blurb: r.blurb ?? t('build.customHint'),+ defaultOut: r.defaultOut ?? `dist-${r.id}`,+ sourceMaps: false,+ prereq: prereqText(r),+ fixCommand: r.prereq?.command,+ next: (o) => t('build.next.custom', { out: o }),+ });+ }+ setPlatforms(merged);+ // A project platform restored from settings has no descriptor until now, so+ // the output box opened on the built-in fallback's default — correct it,+ // unless the project saved an explicit dir for it.+ const cur = merged.find((p) => p.id === platform);+ if (cur && !saved.outDir?.[platform]) setOutDir(cur.defaultOut);+ })();+ return () => { alive = false; };+ // Runs once: the catalog is read when the dialog opens.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+// 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// first. Reads the live asset index, so it tracks file changes.@@ -155,7 +244,8 @@ export function BuildDialog() {const shippedScenes = sceneList.filter((s) => s.path === project?.defaultScene || !excludedScenes.has(s.path)).length;const pickPlatform = (p: PlatformDef) => {- if (!p.ready) return;+ // A not-ready target is still selectable: seeing WHY it is not ready is the+ // point, and what a build may attempt is the developer's call.setPlatform(p.id);setPhase('idle');setResult(null);@@ -163,6 +253,12 @@ export function BuildDialog() {setOutDir(saved.outDir?.[p.id] ?? p.defaultOut);};+ const copyFix = (cmd: string) => {+ void navigator.clipboard?.writeText(cmd);+ setCopiedFix(true);+ setTimeout(() => setCopiedFix(false), 1600);+ };+const browse = async () => {const dir = await window.estella.project?.chooseDirectory?.();if (dir) setOutDir(dir);@@ -246,32 +342,81 @@ export function BuildDialog() {);return (- <Modal title={t('build.title')} onClose={running ? () => {} : close} footer={footer} width={520}>+ <Modal title={t('build.title')} onClose={running ? () => {} : close} footer={footer} width={720}><div className="build">- <div className="build__label">{t('build.platform')}</div>- <div className="build__platforms">- {PLATFORMS.map((p) => (- <button- key={p.id}- type="button"- className={`build__plat${platform === p.id ? ' on' : ''}`}- disabled={!p.ready}- aria-pressed={platform === p.id}- title={p.ready ? p.label : t('build.comingSoon')}- onClick={() => pickPlatform(p)}- >- {p.icon}- <span className="build__plat-name">{p.label}</span>- </button>- ))}- </div>- <div className="build__blurb">{def.blurb}</div>+ <nav className="build__nav" aria-label={t('build.platform')}>+ {CATEGORY_ORDER.map((cat) => {+ const items = platforms.filter((p) => p.category === cat);+ // The custom group always shows, so a project that has none still+ // learns the capability exists.+ if (items.length === 0 && cat !== 'custom') return null;+ return (+ <div key={cat} className="build__nav-group">+ <div className="build__nav-sec">{CATEGORY_LABEL[cat]}</div>+ {items.map((p) => (+ <button+ key={p.id}+ type="button"+ className={`build__nav-item${platform === p.id ? ' active' : ''}`}+ aria-current={platform === p.id}+ disabled={running}+ title={p.label}+ onClick={() => pickPlatform(p)}+ >+ <span className="build__nav-icon">{p.icon}</span>+ <span className="build__nav-label">{p.label}</span>+ {p.loadError+ ? <AlertCircle size={12} className="build__nav-flag is-error" />+ : !p.ready+ ? <TriangleAlert size={12} className="build__nav-flag is-warn" />+ : null}+ </button>+ ))}+ {cat === 'custom' && items.length === 0 && (+ <div className="build__nav-empty">{t('build.noCustomPlatforms')}</div>+ )}+ </div>+ );+ })}+ </nav>- {def.prereq && (- <div className="build__prereq">- <Info size={13} /> <span className="selectable">{def.prereq}</span>+ <div className="build__content">+ <div className="build__head">+ <span className="build__head-title">{def.label}</span>+ <span className="build__blurb">{def.blurb}</span></div>- )}++ {def.loadError && (+ <div className="build__prereq is-error">+ <AlertCircle size={13} />+ <span className="selectable">{t('build.platformBroken')} — {def.loadError}</span>+ </div>+ )}++ {!def.ready && !def.loadError && (+ <div className="build__prereq is-warn">+ <TriangleAlert size={13} />+ <div className="build__prereq-body">+ <span className="selectable">{def.prereq ?? t('build.notReady')}</span>+ <span className="build__prereq-hint">{t('build.notReadyHint')}</span>+ {def.fixCommand && (+ <div className="build__fix">+ <code className="selectable">{def.fixCommand}</code>+ <Button onClick={() => copyFix(def.fixCommand!)}>+ <Copy size={12} /> {copiedFix ? t('build.copied') : t('build.copyCommand')}+ </Button>+ </div>+ )}+ </div>+ </div>+ )}++ {/* Nothing to probe (native's toolchain) — advisory, and only when ready. */}+ {def.ready && def.prereq && (+ <div className="build__prereq">+ <Info size={13} /> <span className="selectable">{def.prereq}</span>+ </div>+ )}<Group title={t('build.secBuild')}><div className="build__row">@@ -439,8 +584,9 @@ export function BuildDialog() {{result && result.warnings.length > 0 && (<div className="build__warn selectable">{t('build.warnings', { count: result.warnings.length, first: result.warnings[0] })}</div>)}- </div>- )}+ </div>+ )}+ </div></div></Modal>);diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.tsindex 51a174700..504e1dba3 100644--- a/desktop/src/i18n/messages/project.ts+++ b/desktop/src/i18n/messages/project.ts@@ -14,8 +14,36 @@ export const projectMessages = defineMessages({'build.plat.wechat': { en: 'WeChat', zh: '微信小游戏' },'build.plat.playable': { en: 'Playable', zh: 'Playable' },'build.plat.native': { en: 'Mobile', zh: '移动原生' },- 'build.comingSoon': { en: 'Coming soon', zh: '即将推出' },- 'build.soon': { en: 'soon', zh: '即将' },+ // — Platform categories (the nav's group headings) —+ 'build.cat.general': { en: 'General', zh: '通用' },+ 'build.cat.minigame': { en: 'Mini-Games', zh: '小游戏' },+ 'build.cat.mobile': { en: 'Mobile', zh: '移动' },+ 'build.cat.custom': { en: 'Project', zh: '项目自定义' },+ // — Runtime readiness (probed on disk, not a static hint) —+ 'build.notReady': { en: 'Engine runtime missing', zh: '缺少引擎运行时' },+ 'build.runtimeMissingIn': {+ en: 'Engine runtime not found in {dir} (looked for {files})',+ zh: '在 {dir} 中未找到引擎运行时(查找的文件:{files})',+ },+ 'build.notReadyHint': {+ en: 'This target needs an engine runtime that is not built yet. Packaging will fail until it is.',+ zh: '该目标需要的引擎运行时尚未构建,在此之前打包会失败。',+ },+ 'build.copyCommand': { en: 'Copy command', zh: '复制命令' },+ 'build.copied': { en: 'Copied', zh: '已复制' },+ 'build.platformBroken': { en: 'This platform profile failed to load', zh: '该平台配置加载失败' },+ 'build.customHint': {+ en: 'Defined by this project in .esengine/platforms/ — it rides the same mini-game pipeline as the built-in targets.',+ zh: '由本项目在 .esengine/platforms/ 中定义,与内置目标走同一条小游戏导出管线。',+ },+ 'build.next.custom': {+ en: 'Package written to {out} — open it in your platform\'s devtools.',+ zh: '包已输出到 {out} —— 用该平台的开发者工具打开。',+ },+ 'build.noCustomPlatforms': {+ en: 'Drop a profile in .esengine/platforms/<id>.mjs to add your own target.',+ zh: '在 .esengine/platforms/<id>.mjs 放一个配置文件即可添加自己的目标。',+ },'build.blurb.web': {en: 'Static, self-contained web build — host it anywhere.',zh: '静态、自包含的网页构建——可托管在任何地方。',@@ -33,14 +61,6 @@ export const projectMessages = defineMessages({en: 'Content for the native iOS / Android app — a real app, not a WebView.',zh: '原生 iOS / Android 应用的内容——真正的原生应用,而非 WebView。',},- 'build.prereq.wechat': {- en: 'Requires the WeChat runtime — run: node build-tools/cli.js build -t wechat',- zh: '需要微信运行时——请运行:node build-tools/cli.js build -t wechat',- },- 'build.prereq.playable': {- en: 'Requires the single-file runtime — run: node build-tools/cli.js build -t playable',- zh: '需要单文件运行时——请运行:node build-tools/cli.js build -t playable',- },'build.prereq.native': {en: 'Needs the native host — see native/README.md (embedded Dawn + QuickJS).',zh: '需要原生宿主——见 native/README.md(内嵌 Dawn + QuickJS)。',@@ -80,7 +100,7 @@ export const projectMessages = defineMessages({// the Inspector's Import Settings; the build only picks honor-vs-skip) —'build.secBuild': { en: 'Build', zh: '构建' },'build.advanced': { en: 'Advanced', zh: '高级' },- 'build.assetCompression': { en: 'Asset compression', zh: '资源压缩' },+ 'build.assetCompression': { en: 'Compression', zh: '资源压缩' },'build.assetAuto': { en: 'By import settings', zh: '按导入设置' },'build.assetSkip': { en: 'Skip all', zh: '全部跳过' },'build.assetCompressionTip': {@@ -107,7 +127,7 @@ export const projectMessages = defineMessages({},// — Asset delivery (CDN / hot-update) —- 'build.cdnRoot': { en: 'CDN root (hot-update)', zh: 'CDN 地址(热更)' },+ 'build.cdnRoot': { en: 'CDN root', zh: 'CDN 地址' },'build.cdnRootTip': {en: 'Base URL that remote-group assets are fetched from for this build profile. Empty → remote groups load from the game origin. Mark folders remote in the Content Browser (right-click → Delivery).',zh: '当前构建 profile 下远端组资产的拉取根地址。留空则从游戏同源加载。在内容浏览器右键文件夹 → 交付方式 里把文件夹标为远端。',diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.tsindex 6520b07e6..37acdd3e1 100644--- a/desktop/src/project/format.ts+++ b/desktop/src/project/format.ts@@ -125,7 +125,14 @@ export interface DesktopPackaging { appId?: string; productName?: string; }/** Every export target. The single source: the electron export pipeline, the IPC* surface and the build dialog all name their platforms from here. */-export type ExportPlatform = 'web' | 'desktop' | 'wechat' | 'playable' | 'native';+/**+ * A packaging target. The editor's built-ins are named for completion, but the+ * type is OPEN: a project can add its own platform by dropping a profile in+ * `.esengine/platforms/<id>.mjs`, and that id flows through packaging settings,+ * the export result and the cook's per-platform Import Settings key exactly like+ * a built-in one.+ */+export type ExportPlatform = 'web' | 'desktop' | 'wechat' | 'playable' | 'native' | (string & {});/** Persisted Package Project settings (UE's ProjectPackagingSettings analog) —* committed with the project so the build dialog restores the last target/config@@ -363,7 +370,10 @@ export function parseManifest(raw: unknown): ProjectManifest {if (o.packaging && typeof o.packaging === 'object') {const p = o.packaging as Record<string, unknown>;const pkg: ProjectPackaging = {};- if (p.platform === 'web' || p.platform === 'desktop' || p.platform === 'wechat' || p.platform === 'playable') pkg.platform = p.platform;+ // Any non-empty id: built-ins plus whatever platforms the project defines.+ // (The old enumeration silently dropped 'native', so packaging for it never+ // persisted and the dialog reopened on web.)+ if (typeof p.platform === 'string' && p.platform !== '') pkg.platform = p.platform;if (p.config === 'development' || p.config === 'shipping') pkg.config = p.config;if (typeof p.sourceMaps === 'boolean') pkg.sourceMaps = p.sourceMaps;if (typeof p.openFolder === 'boolean') pkg.openFolder = p.openFolder;@@ -380,8 +390,10 @@ export function parseManifest(raw: unknown): ProjectManifest {if (p.outDir && typeof p.outDir === 'object') {const od = p.outDir as Record<string, unknown>;const out: NonNullable<ProjectPackaging['outDir']> = {};- for (const k of ['web', 'desktop', 'wechat', 'playable'] as const) {- if (typeof od[k] === 'string') out[k] = od[k] as string;+ // Per-platform output dirs, keyed by whatever platform ids this project has+ // used — built-in or its own.+ for (const [k, v] of Object.entries(od)) {+ if (typeof v === 'string' && v !== '') out[k] = v;}if (Object.keys(out).length > 0) pkg.outDir = out;}diff --git a/desktop/src/theme/menus.css b/desktop/src/theme/menus.cssindex b73effc70..1a19c55bb 100644--- a/desktop/src/theme/menus.css+++ b/desktop/src/theme/menus.css@@ -207,28 +207,97 @@.tmpick__num { width: 90px; height: 26px; }/* ── Package / Build dialog ── */-.build { display: flex; flex-direction: column; gap: 12px; }+/* Two panes: the platform nav (which only grows) and that platform's settings.+ The nav deliberately speaks the Settings dialog's language — same sizes, same+ --acc-soft + rail active state — so the two read as one editor. */+.build { display: flex; gap: 0; min-height: 392px; }+.build__nav {+ width: 176px;+ flex-shrink: 0;+ align-self: stretch;+ overflow-y: auto;+ padding: 0 8px 0 0;+ border-right: 1px solid var(--border-line);+}+.build__nav-group + .build__nav-group { margin-top: 2px; }+.build__nav-sec {+ font-size: var(--fs-2xs);+ text-transform: uppercase;+ letter-spacing: 0.6px;+ color: var(--text-mute);+ font-weight: 700;+ padding: 10px 8px 4px;+}+.build__nav-item {+ width: 100%;+ display: flex;+ align-items: center;+ gap: 8px;+ height: 30px;+ padding: 0 8px;+ border-radius: var(--r-sm);+ color: var(--text-dim);+ font-size: var(--fs-sm);+ text-align: left;+ position: relative;+ transition: color var(--t-fast), background var(--t-fast);+}+.build__nav-item:hover:not(:disabled) { color: var(--text); background: var(--srf-3); }+.build__nav-item.active { color: var(--text); background: var(--acc-soft); }+.build__nav-item.active::before {+ content: '';+ position: absolute;+ left: 0;+ top: 6px;+ bottom: 6px;+ width: 2px;+ border-radius: var(--r-pill);+ background: var(--acc);+}+.build__nav-item:disabled { opacity: 0.55; }+.build__nav-icon { display: grid; place-items: center; width: 17px; flex-shrink: 0; opacity: 0.92; }+.build__nav-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.build__nav-flag { flex-shrink: 0; }+.build__nav-flag.is-warn { color: var(--warn); }+.build__nav-flag.is-error { color: var(--error); }+.build__nav-empty { font-size: var(--fs-2xs); line-height: 1.5; color: var(--text-mute); padding: 2px 8px 6px; overflow-wrap: anywhere; }++.build__content {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 12px;+ padding-left: 14px;+ overflow-y: auto;+}+.build__head { display: flex; flex-direction: column; gap: 3px; }+.build__head-title { font-size: var(--fs-md); font-weight: 600; color: var(--text); }.build__label { font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; color: var(--text-mute); }-.build__platforms { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }-.build__plat { position: relative; height: 58px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; font-size: var(--fs-xs); color: var(--text-dim); background: var(--srf-3); border: 1px solid var(--border-line); border-radius: var(--r-md); transition: color var(--t-fast), background var(--t-fast), border-color var(--t-fast); }-.build__plat svg { opacity: 0.92; }-.build__plat-name { line-height: 1; }-.build__plat:not(:disabled):hover { color: var(--text); border-color: var(--text-mute); }-.build__plat.on { color: var(--on-accent); background: var(--acc); border-color: var(--acc); }-.build__plat:disabled { opacity: 0.5; }-.build__plat .soon { position: absolute; bottom: 5px; font-size: var(--fs-3xs); text-transform: uppercase; letter-spacing: 0.4px; color: var(--text-mute); }.build__row { display: flex; align-items: center; gap: 12px; }-.build__row .build__label { width: 92px; flex-shrink: 0; }+.build__row .build__label { width: 118px; flex-shrink: 0; line-height: 1.3; }+/* Every text field in the dialog, not just the output box: the CDN field under+ Advanced matched nothing and rendered as the browser's white default. */+.build input:not([type]), .build input[type='text'] {+ min-width: 0;+ height: 26px;+ padding: 0 8px;+ font-size: var(--fs-xs);+ font-family: var(--mono);+ color: var(--text);+ background: var(--inset);+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ outline: none;+}+.build input:not([type]):focus, .build input[type='text']:focus { border-color: var(--acc); }+.build input::placeholder { color: var(--text-mute); }+.build__row > input { flex: 1; }.build__out { flex: 1; display: flex; gap: 6px; }-.build__out input { flex: 1; min-width: 0; height: 26px; padding: 0 8px; font-size: var(--fs-xs); font-family: var(--mono); color: var(--text); background: var(--inset); border: 1px solid var(--border); border-radius: var(--r-sm); outline: none; }-.build__out input:focus { border-color: var(--acc); }+.build__out input { flex: 1; }.build__opt { display: flex; align-items: center; gap: 8px; font-size: var(--fs-sm); color: var(--text-dim); cursor: pointer; }-.build__summary { font-size: var(--fs-xs); color: var(--text-mute); }-.build__summary strong { color: var(--text-dim); font-family: var(--mono); }/* Scenes in build — the exporter's scene set (startup pinned, exclusions live). */-.build__scenes { display: flex; flex-direction: column; gap: 2px; max-height: 148px; overflow-y: auto; padding: 6px 8px; background: var(--srf-3); border: 1px solid var(--border-line); border-radius: var(--r-sm); }.build__scenes-list { display: flex; flex-direction: column; gap: 2px; max-height: 150px; overflow-y: auto; margin: -2px 0; }-.build__scenes-head { font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; color: var(--text-mute); padding-bottom: 3px; }.build__scene { display: flex; align-items: center; gap: 6px; height: 24px; }.build__scene-start { display: grid; place-items: center; width: 20px; height: 20px; border-radius: var(--r-xs); color: transparent; background: none; }.build__scene-start.is-on { color: var(--star-hi); }@@ -244,9 +313,28 @@.build__status.done .build__status-line { color: var(--run-hi); }.build__status.error .build__status-line { color: var(--error); }.build__status .build__warn { color: var(--warn); }-.build__blurb { font-size: var(--fs-xs); color: var(--text-mute); margin-top: -6px; }+.build__blurb { font-size: var(--fs-xs); color: var(--text-mute); line-height: 1.5; }.build__prereq { display: flex; align-items: flex-start; gap: 7px; padding: 8px 10px; border-radius: var(--r-sm); font-size: var(--fs-xs); color: var(--text-dim); background: var(--srf-3); border: 1px solid var(--border-line); }.build__prereq svg { flex-shrink: 0; margin-top: 1px; color: var(--text-mute); }+.build__prereq.is-warn { border-color: color-mix(in srgb, var(--warn) 40%, var(--border-line)); }+.build__prereq.is-warn > svg { color: var(--warn); }+.build__prereq.is-error { border-color: color-mix(in srgb, var(--error) 40%, var(--border-line)); }+.build__prereq.is-error > svg { color: var(--error); }+.build__prereq-body { display: flex; flex-direction: column; gap: 6px; min-width: 0; }+.build__prereq-hint { color: var(--text-mute); line-height: 1.5; }+.build__fix { display: flex; align-items: center; gap: 8px; min-width: 0; }+.build__fix code {+ flex: 1;+ min-width: 0;+ overflow-x: auto;+ white-space: nowrap;+ padding: 4px 7px;+ font-family: var(--mono);+ font-size: var(--fs-2xs);+ color: var(--text-dim);+ background: var(--inset);+ border-radius: var(--r-xs);+}.build__next { font-size: var(--fs-xs); color: var(--text-mute); font-family: var(--mono); }.build__actions { display: flex; gap: 8px; margin-top: 2px; }.build__log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; max-height: 116px; overflow-y: auto; font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-mute); }@@ -266,15 +354,14 @@.build__group-count { margin-left: auto; font-family: var(--mono); font-size: var(--fs-2xs); color: var(--text-mute); }.build__group-body { padding: 10px 11px; display: flex; flex-direction: column; gap: 10px; }.build__group-body .build__row { gap: 10px; }-.build__group-body .build__label { width: 74px; }-.build__tip { font-size: var(--fs-2xs); color: var(--text-mute); line-height: 1.45; margin-top: -3px; }+.build__group-body .build__label { width: 118px; }/* Progressive disclosure: advanced (hot-update CDN / source maps / open folder). */.build__adv { display: flex; align-items: center; gap: 6px; font-size: var(--fs-xs); color: var(--text-dim); background: none; border: none; cursor: pointer; padding: 2px 0; }.build__adv:hover { color: var(--text); }.build__adv .chev { display: inline-flex; transition: transform var(--t-fast); color: var(--text-mute); }.build__adv.open .chev { transform: rotate(90deg); }-.build__adv-body { display: flex; flex-direction: column; gap: 10px; padding: 4px 0 2px 2px; }+.build__adv-body { display: flex; flex-direction: column; gap: 10px; padding: 4px 0 2px 12px; }/* "compression lives in Import Settings" pointer + footer scene/target summary. */.build__hint { display: inline-flex; align-items: center; gap: 5px; font-size: var(--fs-2xs); color: var(--text-mute); }diff --git a/desktop/tests/platform-catalog.test.ts b/desktop/tests/platform-catalog.test.tsnew file mode 100644index 000000000..4cc24aca7--- /dev/null+++ b/desktop/tests/platform-catalog.test.ts@@ -0,0 +1,193 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// The platform catalog: what the Package dialog can offer, and whether each+// target can actually run. Two behaviours worth pinning down —+//+// 1. Readiness is a PROBE, not a constant. The dialog used to carry static+// "requires the X runtime" prose that was true whether or not you had built+// it (and, for playable, was simply wrong).+// 2. A project can add a platform the editor never heard of, and a broken one+// must not take the dialog down with it.+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { listPlatforms, loadProjectPlatform, PROJECT_PLATFORM_DIR } from '../electron/platformCatalog';++let root: string;+let webDir: string;+let wxDir: string;++const dirs = () => ({ web: webDir, wechat: wxDir });++function writePlatform(name: string, source: string): void {+ const dir = path.join(root, PROJECT_PLATFORM_DIR);+ mkdirSync(dir, { recursive: true });+ writeFileSync(path.join(dir, name), source);+}++beforeEach(() => {+ root = mkdtempSync(path.join(tmpdir(), 'es-platcat-'));+ webDir = path.join(root, 'rt-web');+ wxDir = path.join(root, 'rt-wechat');+ mkdirSync(webDir, { recursive: true });+ mkdirSync(wxDir, { recursive: true });+});++afterEach(() => {+ 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 byId = Object.fromEntries(rows.map((r) => [r.id, r]));++ expect(byId.web.ready).toBe(false);+ expect(byId.desktop.ready).toBe(false);+ expect(byId.playable.ready).toBe(false);+ expect(byId.web.prereq?.command).toContain('build -t web');+ });++ 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 byId = Object.fromEntries(rows.map((r) => [r.id, r]));++ expect(byId.web.ready).toBe(true);+ expect(byId.playable.ready).toBe(true);+ expect(byId.playable.prereq).toBeUndefined();+ // WeChat has its own runtime and is unaffected by the web one.+ expect(byId.wechat.ready).toBe(false);+ expect(byId.wechat.prereq?.command).toContain('build -t wechat');+ });++ 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);++ 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);+ });++ it('reports paths with forward slashes, whatever the platform separator', async () => {+ const wx = (await listPlatforms(root, dirs())).find((r) => r.id === 'wechat');+ expect(wx?.prereq?.dir).not.toContain('\\');+ });+});++describe('listPlatforms — platforms the project defines', () => {+ it('finds a profile and lifts its display data', async () => {+ writePlatform('acme.mjs', `export default {+ id: 'acme', label: 'ACME Play', blurb: 'ACME package.', defaultOut: 'dist-acme',+ emitConfigFiles: () => [{ file: 'game.json', content: '{}' }],+ };`);+ writeFileSync(path.join(webDir, 'esengine.js'), '//');++ const rows = await listPlatforms(root, dirs());+ const acme = rows.find((r) => r.id === 'acme');+ expect(acme).toBeDefined();+ expect(acme!.source).toBe('project');+ expect(acme!.label).toBe('ACME Play');+ expect(acme!.defaultOut).toBe('dist-acme');+ // No wasmDir of its own → the editor's web runtime, which exists here.+ expect(acme!.ready).toBe(true);+ });++ it('probes the profile\'s own runtime dir when it names one', async () => {+ writePlatform('acme.mjs', `export default {+ id: 'acme', label: 'ACME Play', wasmDir: 'build/wasm/acme',+ emitConfigFiles: () => [],+ };`);+ writeFileSync(path.join(webDir, 'esengine.js'), '//');++ const acme = (await listPlatforms(root, dirs())).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+ // reports where it looked and offers no command.+ expect(acme!.prereq?.command).toBeUndefined();+ });++ 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 bad = rows.find((r) => r.id === 'bad');+ expect(bad).toBeDefined();+ expect(bad!.ready).toBe(false);+ expect(bad!.error).toBeTruthy();+ // Every built-in still came through.+ expect(rows.filter((r) => r.source === 'builtin')).toHaveLength(5);+ });++ it('rejects a profile that shadows a built-in, or has no id/label/emitter', async () => {+ writePlatform('a.mjs', `export default { id: 'wechat', label: 'Fake', emitConfigFiles: () => [] };`);+ writePlatform('b.mjs', `export default { id: 'Bad Id', label: 'X', emitConfigFiles: () => [] };`);+ 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 errs = rows.filter((r) => r.source === 'project').map((r) => r.error);+ expect(errs).toHaveLength(4);+ expect(errs[0]).toContain('built-in');+ expect(errs[1]).toContain('lowercase');+ expect(errs[2]).toContain('label');+ expect(errs[3]).toContain('emitConfigFiles');+ // The real WeChat row is untouched by the impostor.+ expect(rows.filter((r) => r.id === 'wechat' && r.source === 'builtin')).toHaveLength(1);+ });++ it('lists only built-ins when no project is open', async () => {+ const rows = await listPlatforms(null, dirs());+ expect(rows.every((r) => r.source === 'builtin')).toBe(true);+ });+});++describe('loadProjectPlatform — the profile handed to exportMiniGame', () => {+ it('merges over the family defaults, so a minimal profile is complete', async () => {+ writePlatform('acme.mjs', `export default {+ id: 'acme', label: 'ACME Play',+ emitConfigFiles: (ctx) => [{ file: 'game.json', content: JSON.stringify({ t: ctx.title }) }],+ };`);++ const loaded = await loadProjectPlatform(root, 'acme', dirs());+ expect(loaded).not.toBeNull();+ const p = loaded!.profile;++ // Supplied by the project.+ expect(p.id).toBe('acme');+ // Defaulted — a standard mini-game host needs none of these spelled out.+ expect(p.sdkEntryFile).toBe('index.minigame.js');+ expect(p.runtimeInit).toBe('initMiniGameRuntime');+ expect(p.engineGlueCandidates).toEqual(['esengine.js']);+ expect(p.esTarget).toBe('es2017');+ expect(p.subpackageDir).toBe('subpackages');+ expect(typeof p.emitEntry).toBe('function');++ // The default entry is the same CommonJS shape WeChat ships.+ const entry = p.emitEntry({ sideModules: [{ id: 'physics', file: 'physics' }], engineGlueFile: 'esengine.js' });+ expect(entry).toContain("require('./wasm/esengine.js')");+ expect(entry).toContain(`"physics": asFactory(require('./wasm/physics.js'))`);+ expect(entry).toContain("require('./game-bundle.js')");++ // And the project's own emitter is what runs for config.+ expect(p.emitConfigFiles({ title: 'T', appid: '', orientation: 'portrait', subPackages: [], includeSuffixes: [] }))+ .toEqual([{ file: 'game.json', content: '{"t":"T"}' }]);+ });++ it('resolves wasmDir against the project root, defaulting to the web runtime', async () => {+ writePlatform('a.mjs', `export default { id: 'a', label: 'A', wasmDir: 'rt/a', emitConfigFiles: () => [] };`);+ writePlatform('b.mjs', `export default { id: 'b', label: 'B', emitConfigFiles: () => [] };`);++ expect((await loadProjectPlatform(root, 'a', dirs()))!.wasmDir).toBe(path.join(root, 'rt', 'a'));+ expect((await loadProjectPlatform(root, 'b', dirs()))!.wasmDir).toBe(webDir);+ expect((await loadProjectPlatform(root, 'b', dirs()))!.defaultOut).toBe('dist-b');+ });++ it('is null for a built-in id, so the built-in pipeline keeps it', async () => {+ expect(await loadProjectPlatform(root, 'wechat', dirs())).toBeNull();+ expect(await loadProjectPlatform(root, 'nope', dirs())).toBeNull();+ });+});diff --git a/desktop/tests/project-packaging.test.ts b/desktop/tests/project-packaging.test.tsindex da74c473b..a8fc6d943 100644--- a/desktop/tests/project-packaging.test.ts+++ b/desktop/tests/project-packaging.test.ts@@ -18,14 +18,30 @@ describe('parseManifest — packaging', () => {});});- it('drops invalid platform/config + non-string outDir entries', () => {+ it('drops invalid config + non-string outDir entries', () => {const m = parseManifest({name: 'X',- packaging: { platform: 'switch', config: 'debug', sourceMaps: 'yes', outDir: { web: 'ok', desktop: 123 } },+ packaging: { config: 'debug', sourceMaps: 'yes', outDir: { web: 'ok', desktop: 123 } },});expect(m.packaging).toEqual({ outDir: { web: 'ok' } });});+ // The platform id is OPEN: a project can define its own target in+ // .esengine/platforms/, so the manifest parser cannot tell an unknown id from+ // a bad one. It keeps any non-empty string and drops everything else.+ it('keeps an unknown platform id (a project may define one) but drops non-strings', () => {+ expect(parseManifest({ name: 'X', packaging: { platform: 'acme-play' } }).packaging?.platform).toBe('acme-play');+ // 'native' used to be dropped by an enumeration that forgot it.+ expect(parseManifest({ name: 'X', packaging: { platform: 'native' } }).packaging?.platform).toBe('native');+ expect(parseManifest({ name: 'X', packaging: { platform: '' } }).packaging).toBeUndefined();+ expect(parseManifest({ name: 'X', packaging: { platform: 7 } }).packaging).toBeUndefined();+ });++ it('keeps per-platform output dirs for project-defined platforms', () => {+ const m = parseManifest({ name: 'X', packaging: { outDir: { 'acme-play': 'dist-acme', native: 'dist-native' } } });+ expect(m.packaging?.outDir).toEqual({ 'acme-play': 'dist-acme', native: 'dist-native' });+ });+it('parses excludeScenes, dropping non-string / empty entries', () => {const m = parseManifest({name: 'X',diff --git a/docs/astro/src/content/docs/guides/minigame-platforms.mdx b/docs/astro/src/content/docs/guides/minigame-platforms.mdxindex 49523e9bd..83a4394ee 100644--- a/docs/astro/src/content/docs/guides/minigame-platforms.mdx+++ b/docs/astro/src/content/docs/guides/minigame-platforms.mdx@@ -136,9 +136,50 @@ function with WeChat's staged wasm name filled in, and nothing else.## Packaging-The export pipeline (`exportMiniGame`) is shared the same way: cook → manifest →-scene transform → side-module scan → bundle → config/entry → runtime copy. A-vendor is a `MiniGameExportProfile` describing what varies:+Drop a profile in `.esengine/platforms/<id>.mjs` and your platform appears in+**Package Project** under *Project*, beside the built-in targets:++```js+// .esengine/platforms/acme-play.mjs+export default {+ id: 'acme-play',+ label: 'ACME Play',+ blurb: 'ACME mini-game package.',+ defaultOut: 'dist-acme',++ emitConfigFiles(ctx) {+ return [{+ file: 'game.json',+ content: JSON.stringify({+ orientation: ctx.orientation,+ appName: ctx.title,+ ...(ctx.subPackages.length > 0 ? { subPackages: ctx.subPackages } : {}),+ }, null, 2) + '\n',+ }];+ },+};+```++That is the whole file. Three facts and one emitter — the rest defaults to a+standard mini-game host: the vendor-neutral SDK entry (`index.minigame.js`),+`initMiniGameRuntime`, the standard `WebAssembly` engine glue, and the generic+CommonJS `game.js`. Everything else — cook, manifest, scene transform,+side-module scan, bundling, runtime copy — is the same pipeline WeChat uses.++The `id` must be lowercase letters/digits/dashes and must not shadow a built-in.+It is also the cook's **Import Settings key**, so per-texture compression+overrides can target your platform by name.++<Aside type="note">+ A profile that fails to load is listed with its error rather than dropped —+ and the editor probes the engine runtime your platform needs (`wasmDir`,+ default: the editor's web runtime), so the dialog says what is missing before+ a build runs instead of failing halfway through one.+</Aside>++### The full profile++Everything you can override, and what the pipeline uses it for:| Field | What it says || --- | --- |@@ -151,15 +192,13 @@ vendor is a `MiniGameExportProfile` describing what varies:| `nativeSuffixes` / `binRestageExts` | the packer's suffix policy || `subpackageDir` | where lazy groups stage || `emitConfigFiles` / `emitEntry` | the vendor's config files and `game.js` |+| `wasmDir` | project-relative engine runtime dir (default: the editor's web runtime) |-<Aside type="caution">- **The export side lives in the editor, not in the SDK.** Adding a vendor to- *Package Project* means editing the engine: a profile in- `desktop/electron/miniGameExportProfile.ts`, a case in `exportGame.ts`, a card- in the Build dialog, and a wasm target in `build-tools/build.config.js` if the- host needs its own engine build. The runtime side above needs none of that —- you can ship to an unsupported host today by driving `initMiniGameRuntime`- from your own packaging script.+<Aside type="note">+ The profile module runs in the editor's **main process**, not the renderer —+ its emitters are functions, which cannot cross the IPC boundary. That is why+ the file is plain `.mjs` with a default export rather than anything registered+ through an API.</Aside>## Does the host need its own engine build?diff --git a/docs/astro/src/content/docs/zh-cn/guides/minigame-platforms.mdx b/docs/astro/src/content/docs/zh-cn/guides/minigame-platforms.mdxindex 77bbe9c44..76caf30aa 100644--- a/docs/astro/src/content/docs/zh-cn/guides/minigame-platforms.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/minigame-platforms.mdx@@ -128,9 +128,47 @@ manifest,然后跑起 app——和微信走的是同一条序列。`initWeChat## 打包-导出管线(`exportMiniGame`)以同样的方式共享:cook → manifest → 场景变换 →-side-module 扫描 → 打包 → 配置/入口 → 拷贝运行时。一个平台就是一个-`MiniGameExportProfile`,描述有差异的部分:+在项目里放一个 `.esengine/platforms/<id>.mjs`,你的平台就会出现在**打包项目**+对话框的「项目自定义」分组里,与内置目标并列:++```js+// .esengine/platforms/acme-play.mjs+export default {+ id: 'acme-play',+ label: 'ACME Play',+ blurb: 'ACME 小游戏包。',+ defaultOut: 'dist-acme',++ emitConfigFiles(ctx) {+ return [{+ file: 'game.json',+ content: JSON.stringify({+ orientation: ctx.orientation,+ appName: ctx.title,+ ...(ctx.subPackages.length > 0 ? { subPackages: ctx.subPackages } : {}),+ }, null, 2) + '\n',+ }];+ },+};+```++整个文件就这些。三个事实加一个 emitter——其余全部落到「标准小游戏宿主」的默认值:+平台中立的 SDK 入口(`index.minigame.js`)、`initMiniGameRuntime`、标准+`WebAssembly` 引擎 glue,以及通用的 CommonJS `game.js`。剩下的一切——cook、+manifest、场景变换、side-module 扫描、打包、运行时拷贝——与微信走的是同一条管线。++`id` 只能是小写字母/数字/短横线,且不能与内置平台重名。它同时是 cook 的+**导入设置键**,所以逐纹理的压缩覆盖可以按名字指定你的平台。++<Aside type="note">+ 加载失败的 profile 会**带着错误信息列出来**,而不是被悄悄丢弃;编辑器还会探测+ 你的平台所需的引擎运行时(`wasmDir`,默认用编辑器自带的 web 运行时),所以对话框+ 在打包**之前**就告诉你缺什么,而不是打到一半才失败。+</Aside>++### 完整的 profile 字段++可覆盖的全部字段,以及管线拿它做什么:| 字段 | 含义 || --- | --- |@@ -143,13 +181,12 @@ side-module 扫描 → 打包 → 配置/入口 → 拷贝运行时。一个平| `nativeSuffixes` / `binRestageExts` | 打包器的后缀策略 || `subpackageDir` | 懒加载分组落盘的位置 || `emitConfigFiles` / `emitEntry` | 该平台的配置文件与 `game.js` |+| `wasmDir` | 相对项目的引擎运行时目录(默认用编辑器自带的 web 运行时) |-<Aside type="caution">- **导出侧在编辑器里,不在 SDK 里。** 要让一个平台出现在「打包项目」中,需要改引擎:- 在 `desktop/electron/miniGameExportProfile.ts` 加 profile、在 `exportGame.ts` 加分派、- 在构建弹窗加卡片,如果宿主需要自己的引擎构建,还要在- `build-tools/build.config.js` 加 wasm 目标。上面的运行时侧不需要这些——你今天就可以- 用自己的打包脚本驱动 `initMiniGameRuntime`,发布到未内置的宿主。+<Aside type="note">+ profile 模块跑在编辑器的**主进程**里,而不是渲染进程——它的 emitter 是函数,+ 无法跨 IPC 传递。这也是为什么它是一个带默认导出的普通 `.mjs` 文件,+ 而不是通过某个 API 注册。</Aside>## 宿主需要单独的引擎构建吗?