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: add build settings optimization with caching, history and improved UI
esengine0ab7587dca45
diff --git a/editor/src/builder/BatchBuilder.ts b/editor/src/builder/BatchBuilder.tsnew file mode 100644index 000000000..928fd0da1--- /dev/null+++ b/editor/src/builder/BatchBuilder.ts@@ -0,0 +1,332 @@+/**+ * @file BatchBuilder.ts+ * @brief Batch build multiple configurations+ */++import { BuildConfig } from '../types/BuildTypes';+import { BuildService, BuildResult } from './BuildService';+import { BuildProgressReporter, BuildProgress } from './BuildProgress';+import { BuildHistory, BuildHistoryEntry } from './BuildHistory';++// =============================================================================+// Types+// =============================================================================++export interface BatchBuildResult {+ success: boolean;+ results: ConfigBuildResult[];+ totalDuration: number;+ successCount: number;+ failureCount: number;+}++export interface ConfigBuildResult {+ configId: string;+ configName: string;+ result: BuildResult;+ duration: number;+}++export interface BatchBuildProgress {+ totalConfigs: number;+ completedConfigs: number;+ currentConfig: string;+ overallProgress: number;+ configProgresses: Map<string, BuildProgress>;+}++export type BatchProgressListener = (progress: BatchBuildProgress) => void;++// =============================================================================+// BatchBuilder Class+// =============================================================================++export class BatchBuilder {+ private projectPath_: string;+ private buildService_: BuildService;+ private history_: BuildHistory | null;+ private listeners_: Set<BatchProgressListener>;+ private aborted_: boolean;++ constructor(projectPath: string, history?: BuildHistory) {+ this.projectPath_ = projectPath;+ this.buildService_ = new BuildService(projectPath);+ this.history_ = history || null;+ this.listeners_ = new Set();+ this.aborted_ = false;+ }++ onProgress(listener: BatchProgressListener): () => void {+ this.listeners_.add(listener);+ return () => this.listeners_.delete(listener);+ }++ private notify(progress: BatchBuildProgress): void {+ for (const listener of this.listeners_) {+ listener(progress);+ }+ }++ abort(): void {+ this.aborted_ = true;+ }++ async buildAll(configs: BuildConfig[]): Promise<BatchBuildResult> {+ const startTime = Date.now();+ const results: ConfigBuildResult[] = [];+ this.aborted_ = false;++ const progress: BatchBuildProgress = {+ totalConfigs: configs.length,+ completedConfigs: 0,+ currentConfig: '',+ overallProgress: 0,+ configProgresses: new Map(),+ };++ for (let i = 0; i < configs.length; i++) {+ if (this.aborted_) {+ break;+ }++ const config = configs[i];+ progress.currentConfig = config.name;+ progress.overallProgress = (i / configs.length) * 100;+ this.notify(progress);++ const configStartTime = Date.now();++ try {+ const result = await this.buildService_.build(config);+ const duration = Date.now() - configStartTime;++ results.push({+ configId: config.id,+ configName: config.name,+ result,+ duration,+ });++ if (this.history_) {+ this.history_.addEntry({+ configId: config.id,+ configName: config.name,+ platform: config.platform,+ timestamp: Date.now(),+ duration,+ status: result.success ? 'success' : 'failed',+ outputPath: result.outputPath,+ error: result.error,+ });+ }+ } catch (err) {+ const duration = Date.now() - configStartTime;+ const errorMsg = err instanceof Error ? err.message : String(err);++ results.push({+ configId: config.id,+ configName: config.name,+ result: {+ success: false,+ error: errorMsg,+ },+ duration,+ });++ if (this.history_) {+ this.history_.addEntry({+ configId: config.id,+ configName: config.name,+ platform: config.platform,+ timestamp: Date.now(),+ duration,+ status: 'failed',+ error: errorMsg,+ });+ }+ }++ progress.completedConfigs = i + 1;+ }++ const totalDuration = Date.now() - startTime;+ const successCount = results.filter(r => r.result.success).length;+ const failureCount = results.length - successCount;++ progress.overallProgress = 100;+ progress.currentConfig = '';+ this.notify(progress);++ if (this.history_) {+ await this.history_.save();+ }++ return {+ success: failureCount === 0 && !this.aborted_,+ results,+ totalDuration,+ successCount,+ failureCount,+ };+ }++ async buildSelected(configs: BuildConfig[], selectedIds: string[]): Promise<BatchBuildResult> {+ const selectedConfigs = configs.filter(c => selectedIds.includes(c.id));+ return this.buildAll(selectedConfigs);+ }++ async buildPlatform(configs: BuildConfig[], platform: string): Promise<BatchBuildResult> {+ const platformConfigs = configs.filter(c => c.platform === platform);+ return this.buildAll(platformConfigs);+ }+}++// =============================================================================+// Parallel Batch Builder+// =============================================================================++export class ParallelBatchBuilder {+ private projectPath_: string;+ private history_: BuildHistory | null;+ private maxConcurrent_: number;+ private listeners_: Set<BatchProgressListener>;+ private aborted_: boolean;++ constructor(projectPath: string, options?: { history?: BuildHistory; maxConcurrent?: number }) {+ this.projectPath_ = projectPath;+ this.history_ = options?.history || null;+ this.maxConcurrent_ = options?.maxConcurrent || 2;+ this.listeners_ = new Set();+ this.aborted_ = false;+ }++ onProgress(listener: BatchProgressListener): () => void {+ this.listeners_.add(listener);+ return () => this.listeners_.delete(listener);+ }++ private notify(progress: BatchBuildProgress): void {+ for (const listener of this.listeners_) {+ listener(progress);+ }+ }++ abort(): void {+ this.aborted_ = true;+ }++ async buildAll(configs: BuildConfig[]): Promise<BatchBuildResult> {+ const startTime = Date.now();+ const results: ConfigBuildResult[] = [];+ this.aborted_ = false;++ const progress: BatchBuildProgress = {+ totalConfigs: configs.length,+ completedConfigs: 0,+ currentConfig: '',+ overallProgress: 0,+ configProgresses: new Map(),+ };++ const queue = [...configs];+ const inProgress: Promise<void>[] = [];++ const buildConfig = async (config: BuildConfig): Promise<void> => {+ if (this.aborted_) return;++ const buildService = new BuildService(this.projectPath_);+ const configStartTime = Date.now();++ try {+ const result = await buildService.build(config);+ const duration = Date.now() - configStartTime;++ results.push({+ configId: config.id,+ configName: config.name,+ result,+ duration,+ });++ if (this.history_) {+ this.history_.addEntry({+ configId: config.id,+ configName: config.name,+ platform: config.platform,+ timestamp: Date.now(),+ duration,+ status: result.success ? 'success' : 'failed',+ outputPath: result.outputPath,+ error: result.error,+ });+ }+ } catch (err) {+ const duration = Date.now() - configStartTime;+ const errorMsg = err instanceof Error ? err.message : String(err);++ results.push({+ configId: config.id,+ configName: config.name,+ result: {+ success: false,+ error: errorMsg,+ },+ duration,+ });++ if (this.history_) {+ this.history_.addEntry({+ configId: config.id,+ configName: config.name,+ platform: config.platform,+ timestamp: Date.now(),+ duration,+ status: 'failed',+ error: errorMsg,+ });+ }+ }++ progress.completedConfigs++;+ progress.overallProgress = (progress.completedConfigs / progress.totalConfigs) * 100;+ this.notify(progress);+ };++ while (queue.length > 0 || inProgress.length > 0) {+ if (this.aborted_) break;++ while (inProgress.length < this.maxConcurrent_ && queue.length > 0) {+ const config = queue.shift()!;+ const promise = buildConfig(config).then(() => {+ const index = inProgress.indexOf(promise);+ if (index !== -1) {+ inProgress.splice(index, 1);+ }+ });+ inProgress.push(promise);+ }++ if (inProgress.length > 0) {+ await Promise.race(inProgress);+ }+ }++ await Promise.all(inProgress);++ const totalDuration = Date.now() - startTime;+ const successCount = results.filter(r => r.result.success).length;+ const failureCount = results.length - successCount;++ if (this.history_) {+ await this.history_.save();+ }++ return {+ success: failureCount === 0 && !this.aborted_,+ results,+ totalDuration,+ successCount,+ failureCount,+ };+ }+}diff --git a/editor/src/builder/BuildCache.ts b/editor/src/builder/BuildCache.tsnew file mode 100644index 000000000..1ec21c9e3--- /dev/null+++ b/editor/src/builder/BuildCache.ts@@ -0,0 +1,259 @@+/**+ * @file BuildCache.ts+ * @brief Incremental build cache for file change detection+ */++// =============================================================================+// Types+// =============================================================================++export interface FileHash {+ path: string;+ hash: string;+ lastModified: number;+ size: number;+}++export interface BuildCacheData {+ version: string;+ configId: string;+ timestamp: number;+ files: Record<string, FileHash>;+ compiledScripts?: string;+ compiledScriptsHash?: string;+}++export interface FileChangeResult {+ added: string[];+ modified: string[];+ removed: string[];+ unchanged: string[];+}++// =============================================================================+// Constants+// =============================================================================++const CACHE_VERSION = '1.0';+const CACHE_DIR = '.esengine/build-cache';++// =============================================================================+// Hash Utilities+// =============================================================================++async function computeHash(content: string | Uint8Array): Promise<string> {+ const data = typeof content === 'string'+ ? new TextEncoder().encode(content)+ : new Uint8Array(content);++ const hashBuffer = await crypto.subtle.digest('SHA-256', data);+ const hashArray = Array.from(new Uint8Array(hashBuffer));+ return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');+}++async function computeFileHash(fs: NativeFileSystem, filePath: string): Promise<FileHash | null> {+ try {+ const content = await fs.readFile(filePath);+ const stats = await fs.stat(filePath);+ const hash = await computeHash(content);++ return {+ path: filePath,+ hash,+ lastModified: stats.mtimeMs,+ size: stats.size,+ };+ } catch {+ return null;+ }+}++// =============================================================================+// BuildCache Class+// =============================================================================++export class BuildCache {+ private projectDir_: string;+ private fs_: NativeFileSystem | null;++ constructor(projectDir: string) {+ this.projectDir_ = projectDir;+ this.fs_ = window.__esengine_fs ?? null;+ }++ private getFs(): NativeFileSystem {+ if (!this.fs_) {+ throw new Error('Native file system not available');+ }+ return this.fs_;+ }++ private getCachePath(configId: string): string {+ return `${this.projectDir_}/${CACHE_DIR}/${configId}.json`;+ }++ private getCacheDir(): string {+ return `${this.projectDir_}/${CACHE_DIR}`;+ }++ async loadCache(configId: string): Promise<BuildCacheData | null> {+ if (!this.fs_) return null;++ const cachePath = this.getCachePath(configId);++ try {+ const content = await this.fs_.readFile(cachePath);+ const decoder = new TextDecoder();+ const jsonStr = decoder.decode(content);+ const data = JSON.parse(jsonStr) as BuildCacheData;++ if (data.version !== CACHE_VERSION) {+ return null;+ }++ return data;+ } catch {+ return null;+ }+ }++ async saveCache(data: BuildCacheData): Promise<void> {+ const fs = this.getFs();+ const cacheDir = this.getCacheDir();+ const cachePath = this.getCachePath(data.configId);++ try {+ await fs.mkdir(cacheDir, { recursive: true });+ } catch {+ // Directory may already exist+ }++ const jsonStr = JSON.stringify(data, null, 2);+ const encoder = new TextEncoder();+ await fs.writeFile(cachePath, encoder.encode(jsonStr));+ }++ async invalidateCache(configId: string): Promise<void> {+ if (!this.fs_) return;++ const cachePath = this.getCachePath(configId);++ try {+ await this.fs_.unlink(cachePath);+ } catch {+ // Cache may not exist+ }+ }++ async getChangedFiles(+ currentFiles: string[],+ cached: BuildCacheData | null+ ): Promise<FileChangeResult> {+ const result: FileChangeResult = {+ added: [],+ modified: [],+ removed: [],+ unchanged: [],+ };++ if (!cached) {+ result.added = [...currentFiles];+ return result;+ }++ if (!this.fs_) {+ result.added = [...currentFiles];+ return result;+ }++ const cachedPaths = new Set(Object.keys(cached.files));+ const currentPaths = new Set(currentFiles);++ for (const filePath of currentFiles) {+ if (!cachedPaths.has(filePath)) {+ result.added.push(filePath);+ } else {+ const cachedFile = cached.files[filePath];+ const currentHash = await computeFileHash(this.fs_, filePath);++ if (!currentHash) {+ result.removed.push(filePath);+ } else if (currentHash.hash !== cachedFile.hash) {+ result.modified.push(filePath);+ } else {+ result.unchanged.push(filePath);+ }+ }+ }++ for (const cachedPath of cachedPaths) {+ if (!currentPaths.has(cachedPath)) {+ result.removed.push(cachedPath);+ }+ }++ return result;+ }++ async computeFilesHash(filePaths: string[]): Promise<Record<string, FileHash>> {+ const result: Record<string, FileHash> = {};++ if (!this.fs_) return result;++ const fs = this.fs_;+ const promises = filePaths.map(async (filePath) => {+ const hash = await computeFileHash(fs, filePath);+ if (hash) {+ result[filePath] = hash;+ }+ });++ await Promise.all(promises);+ return result;+ }++ async createCacheData(+ configId: string,+ filePaths: string[],+ compiledScripts?: string+ ): Promise<BuildCacheData> {+ const files = await this.computeFilesHash(filePaths);+ const compiledScriptsHash = compiledScripts+ ? await computeHash(compiledScripts)+ : undefined;++ return {+ version: CACHE_VERSION,+ configId,+ timestamp: Date.now(),+ files,+ compiledScripts,+ compiledScriptsHash,+ };+ }++ hasChanges(changes: FileChangeResult): boolean {+ return changes.added.length > 0 ||+ changes.modified.length > 0 ||+ changes.removed.length > 0;+ }++ async clearAllCaches(): Promise<void> {+ if (!this.fs_) return;++ const cacheDir = this.getCacheDir();++ try {+ const entries = await this.fs_.readdir(cacheDir);+ for (const entry of entries) {+ if (entry.endsWith('.json')) {+ await this.fs_.unlink(`${cacheDir}/${entry}`);+ }+ }+ } catch {+ // Cache directory may not exist+ }+ }+}++export { computeHash };diff --git a/editor/src/builder/BuildConfigIO.ts b/editor/src/builder/BuildConfigIO.tsnew file mode 100644index 000000000..dcc90a76f--- /dev/null+++ b/editor/src/builder/BuildConfigIO.ts@@ -0,0 +1,267 @@+/**+ * @file BuildConfigIO.ts+ * @brief Build configuration import/export functionality+ */++import { BuildConfig, BuildPlatform } from '../types/BuildTypes';++// =============================================================================+// Types+// =============================================================================++export interface ExportedConfig {+ version: '1.0';+ exportedAt: string;+ configs: BuildConfig[];+}++export interface ImportResult {+ success: boolean;+ configs: BuildConfig[];+ errors: string[];+}++// =============================================================================+// Constants+// =============================================================================++const EXPORT_VERSION = '1.0';++// =============================================================================+// BuildConfigIO Class+// =============================================================================++export class BuildConfigIO {+ private fs_: NativeFileSystem | null;++ constructor() {+ this.fs_ = window.__esengine_fs ?? null;+ }++ async exportConfigs(configs: BuildConfig[], outputPath: string): Promise<void> {+ if (!this.fs_) {+ throw new Error('Native file system not available');+ }++ const exportData: ExportedConfig = {+ version: EXPORT_VERSION,+ exportedAt: new Date().toISOString(),+ configs: configs.map(config => this.sanitizeConfigForExport(config)),+ };++ const jsonStr = JSON.stringify(exportData, null, 2);+ const encoder = new TextEncoder();+ await this.fs_.writeFile(outputPath, encoder.encode(jsonStr));+ }++ async importConfigs(filePath: string): Promise<ImportResult> {+ const result: ImportResult = {+ success: false,+ configs: [],+ errors: [],+ };++ if (!this.fs_) {+ result.errors.push('Native file system not available');+ return result;+ }++ try {+ const content = await this.fs_.readFile(filePath);+ const decoder = new TextDecoder();+ const jsonStr = decoder.decode(content);+ const data = JSON.parse(jsonStr);++ if (!this.isValidExportFormat(data)) {+ result.errors.push('Invalid export file format');+ return result;+ }++ for (const config of data.configs) {+ const validation = this.validateConfig(config);+ if (validation.valid) {+ const importedConfig = this.prepareConfigForImport(config);+ result.configs.push(importedConfig);+ } else {+ result.errors.push(`Config '${config.name || 'unknown'}': ${validation.error}`);+ }+ }++ result.success = result.configs.length > 0;+ } catch (err) {+ result.errors.push(`Failed to read file: ${err instanceof Error ? err.message : String(err)}`);+ }++ return result;+ }++ exportConfigsToJson(configs: BuildConfig[]): string {+ const exportData: ExportedConfig = {+ version: EXPORT_VERSION,+ exportedAt: new Date().toISOString(),+ configs: configs.map(config => this.sanitizeConfigForExport(config)),+ };++ return JSON.stringify(exportData, null, 2);+ }++ importConfigsFromJson(jsonStr: string): ImportResult {+ const result: ImportResult = {+ success: false,+ configs: [],+ errors: [],+ };++ try {+ const data = JSON.parse(jsonStr);++ if (!this.isValidExportFormat(data)) {+ result.errors.push('Invalid export file format');+ return result;+ }++ for (const config of data.configs) {+ const validation = this.validateConfig(config);+ if (validation.valid) {+ const importedConfig = this.prepareConfigForImport(config);+ result.configs.push(importedConfig);+ } else {+ result.errors.push(`Config '${config.name || 'unknown'}': ${validation.error}`);+ }+ }++ result.success = result.configs.length > 0;+ } catch (err) {+ result.errors.push(`Failed to parse JSON: ${err instanceof Error ? err.message : String(err)}`);+ }++ return result;+ }++ private isValidExportFormat(data: unknown): data is ExportedConfig {+ if (!data || typeof data !== 'object') return false;++ const obj = data as Record<string, unknown>;+ return (+ obj.version === EXPORT_VERSION &&+ typeof obj.exportedAt === 'string' &&+ Array.isArray(obj.configs)+ );+ }++ private validateConfig(config: unknown): { valid: boolean; error?: string } {+ if (!config || typeof config !== 'object') {+ return { valid: false, error: 'Invalid config object' };+ }++ const cfg = config as Record<string, unknown>;++ if (typeof cfg.name !== 'string' || !cfg.name) {+ return { valid: false, error: 'Missing or invalid name' };+ }++ if (!this.isValidPlatform(cfg.platform)) {+ return { valid: false, error: 'Invalid platform' };+ }++ if (!Array.isArray(cfg.scenes)) {+ return { valid: false, error: 'Missing scenes array' };+ }++ if (!Array.isArray(cfg.defines)) {+ return { valid: false, error: 'Missing defines array' };+ }++ return { valid: true };+ }++ private isValidPlatform(platform: unknown): platform is BuildPlatform {+ return platform === 'playable' || platform === 'wechat';+ }++ private sanitizeConfigForExport(config: BuildConfig): BuildConfig {+ return {+ id: config.id,+ name: config.name,+ platform: config.platform,+ scenes: [...config.scenes],+ defines: [...config.defines],+ playableSettings: config.playableSettings+ ? { ...config.playableSettings }+ : undefined,+ wechatSettings: config.wechatSettings+ ? { ...config.wechatSettings }+ : undefined,+ };+ }++ private prepareConfigForImport(config: BuildConfig): BuildConfig {+ return {+ ...config,+ id: `${config.platform}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,+ };+ }+}++// =============================================================================+// Download Helper (for browser)+// =============================================================================++export function downloadConfigsAsFile(configs: BuildConfig[], filename: string = 'build-configs.json'): void {+ const io = new BuildConfigIO();+ const jsonStr = io.exportConfigsToJson(configs);++ const blob = new Blob([jsonStr], { type: 'application/json' });+ const url = URL.createObjectURL(blob);++ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);++ URL.revokeObjectURL(url);+}++export async function uploadConfigsFromFile(): Promise<ImportResult> {+ return new Promise((resolve) => {+ const input = document.createElement('input');+ input.type = 'file';+ input.accept = '.json';++ input.onchange = async () => {+ const file = input.files?.[0];+ if (!file) {+ resolve({+ success: false,+ configs: [],+ errors: ['No file selected'],+ });+ return;+ }++ try {+ const text = await file.text();+ const io = new BuildConfigIO();+ resolve(io.importConfigsFromJson(text));+ } catch (err) {+ resolve({+ success: false,+ configs: [],+ errors: [`Failed to read file: ${err instanceof Error ? err.message : String(err)}`],+ });+ }+ };++ input.oncancel = () => {+ resolve({+ success: false,+ configs: [],+ errors: ['Import cancelled'],+ });+ };++ input.click();+ });+}diff --git a/editor/src/builder/BuildConfigService.ts b/editor/src/builder/BuildConfigService.tsnew file mode 100644index 000000000..f29b8da62--- /dev/null+++ b/editor/src/builder/BuildConfigService.ts@@ -0,0 +1,276 @@+/**+ * @file BuildConfigService.ts+ * @brief Project-level build configuration management+ */++import {+ BuildConfig,+ BuildSettings,+ BuildPlatform,+ createDefaultBuildSettings,+ createDefaultBuildConfig,+} from '../types/BuildTypes';++// =============================================================================+// Types+// =============================================================================++export interface BuildSettingsFile {+ version: '1.0';+ activePlatform: BuildPlatform;+ activeConfigId: string;+ configs: BuildConfig[];+}++export type ConfigChangeListener = (settings: BuildSettings) => void;++// =============================================================================+// Constants+// =============================================================================++const CONFIG_VERSION = '1.0';+const CONFIG_DIR = '.esengine';+const CONFIG_FILENAME = 'build.json';+const LEGACY_STORAGE_KEY = 'esengine_build_settings';++// =============================================================================+// BuildConfigService Class+// =============================================================================++export class BuildConfigService {+ private projectDir_: string;+ private settings_: BuildSettings;+ private fs_: NativeFileSystem | null;+ private listeners_: Set<ConfigChangeListener>;+ private loaded_: boolean;++ constructor(projectDir: string) {+ this.projectDir_ = projectDir;+ this.settings_ = createDefaultBuildSettings();+ this.fs_ = window.__esengine_fs ?? null;+ this.listeners_ = new Set();+ this.loaded_ = false;+ }++ private getConfigPath(): string {+ return `${this.projectDir_}/${CONFIG_DIR}/${CONFIG_FILENAME}`;+ }++ private getConfigDir(): string {+ return `${this.projectDir_}/${CONFIG_DIR}`;+ }++ private notify(): void {+ for (const listener of this.listeners_) {+ listener(this.settings_);+ }+ }++ onChange(listener: ConfigChangeListener): () => void {+ this.listeners_.add(listener);+ return () => this.listeners_.delete(listener);+ }++ async load(): Promise<BuildSettings> {+ if (!this.fs_) {+ const migrated = await this.migrateFromLocalStorage();+ if (!migrated) {+ this.settings_ = createDefaultBuildSettings();+ }+ this.loaded_ = true;+ return this.settings_;+ }++ const configPath = this.getConfigPath();++ try {+ const content = await this.fs_.readFile(configPath);+ const decoder = new TextDecoder();+ const jsonStr = decoder.decode(content);+ const file = JSON.parse(jsonStr) as BuildSettingsFile;++ if (file.version === CONFIG_VERSION) {+ this.settings_ = {+ activePlatform: file.activePlatform,+ activeConfigId: file.activeConfigId,+ configs: file.configs,+ };+ this.loaded_ = true;+ return this.settings_;+ }+ } catch {+ // Config file doesn't exist, try migration+ }++ const migrated = await this.migrateFromLocalStorage();+ if (migrated) {+ this.loaded_ = true;+ return this.settings_;+ }++ this.settings_ = createDefaultBuildSettings();+ this.loaded_ = true;+ return this.settings_;+ }++ async save(): Promise<void> {+ if (!this.fs_) return;++ const configDir = this.getConfigDir();+ const configPath = this.getConfigPath();++ try {+ await this.fs_.mkdir(configDir, { recursive: true });+ } catch {+ // Directory may already exist+ }++ const file: BuildSettingsFile = {+ version: CONFIG_VERSION,+ activePlatform: this.settings_.activePlatform,+ activeConfigId: this.settings_.activeConfigId,+ configs: this.settings_.configs,+ };++ const jsonStr = JSON.stringify(file, null, 2);+ const encoder = new TextEncoder();+ await this.fs_.writeFile(configPath, encoder.encode(jsonStr));+ }++ async migrateFromLocalStorage(): Promise<boolean> {+ try {+ const stored = localStorage.getItem(LEGACY_STORAGE_KEY);+ if (!stored) return false;++ const settings = JSON.parse(stored) as BuildSettings;+ if (!settings.configs || settings.configs.length === 0) {+ return false;+ }++ this.settings_ = settings;+ await this.save();++ localStorage.removeItem(LEGACY_STORAGE_KEY);+ console.log('[BuildConfigService] Migrated settings from localStorage to project file');+ return true;+ } catch {+ return false;+ }+ }++ getSettings(): BuildSettings {+ return this.settings_;+ }++ getConfigs(): BuildConfig[] {+ return this.settings_.configs;+ }++ getConfig(id: string): BuildConfig | undefined {+ return this.settings_.configs.find(c => c.id === id);+ }++ getActiveConfig(): BuildConfig | undefined {+ return this.getConfig(this.settings_.activeConfigId);+ }++ getConfigsByPlatform(platform: BuildPlatform): BuildConfig[] {+ return this.settings_.configs.filter(c => c.platform === platform);+ }++ addConfig(config: BuildConfig): void {+ this.settings_.configs.push(config);+ this.notify();+ }++ updateConfig(id: string, updates: Partial<BuildConfig>): void {+ const index = this.settings_.configs.findIndex(c => c.id === id);+ if (index !== -1) {+ this.settings_.configs[index] = {+ ...this.settings_.configs[index],+ ...updates,+ };+ this.notify();+ }+ }++ removeConfig(id: string): void {+ const index = this.settings_.configs.findIndex(c => c.id === id);+ if (index !== -1) {+ this.settings_.configs.splice(index, 1);++ if (this.settings_.activeConfigId === id) {+ const platformConfigs = this.getConfigsByPlatform(this.settings_.activePlatform);+ this.settings_.activeConfigId = platformConfigs[0]?.id || '';+ }++ this.notify();+ }+ }++ duplicateConfig(id: string, newName: string): BuildConfig | undefined {+ const original = this.getConfig(id);+ if (!original) return undefined;++ const newConfig: BuildConfig = {+ ...JSON.parse(JSON.stringify(original)),+ id: `${original.platform}-${Date.now()}`,+ name: newName,+ };++ this.addConfig(newConfig);+ return newConfig;+ }++ setActivePlatform(platform: BuildPlatform): void {+ this.settings_.activePlatform = platform;++ const platformConfigs = this.getConfigsByPlatform(platform);+ const currentActive = this.getActiveConfig();+ if (!currentActive || currentActive.platform !== platform) {+ this.settings_.activeConfigId = platformConfigs[0]?.id || '';+ }++ this.notify();+ }++ setActiveConfig(id: string): void {+ const config = this.getConfig(id);+ if (config) {+ this.settings_.activeConfigId = id;+ this.settings_.activePlatform = config.platform;+ this.notify();+ }+ }++ createConfig(platform: BuildPlatform, name: string): BuildConfig {+ const config = createDefaultBuildConfig(platform, name);+ this.addConfig(config);+ return config;+ }++ isLoaded(): boolean {+ return this.loaded_;+ }+}++// =============================================================================+// Singleton Instance+// =============================================================================++let serviceInstance: BuildConfigService | null = null;++export function getBuildConfigService(projectDir?: string): BuildConfigService {+ if (!serviceInstance && projectDir) {+ serviceInstance = new BuildConfigService(projectDir);+ }+ if (!serviceInstance) {+ throw new Error('BuildConfigService not initialized');+ }+ return serviceInstance;+}++export function initBuildConfigService(projectDir: string): BuildConfigService {+ serviceInstance = new BuildConfigService(projectDir);+ return serviceInstance;+}diff --git a/editor/src/builder/BuildHistory.ts b/editor/src/builder/BuildHistory.tsnew file mode 100644index 000000000..b8c4de13b--- /dev/null+++ b/editor/src/builder/BuildHistory.ts@@ -0,0 +1,253 @@+/**+ * @file BuildHistory.ts+ * @brief Build history tracking and management+ */++// =============================================================================+// Types+// =============================================================================++export type BuildStatus = 'success' | 'failed' | 'cancelled';++export interface BuildHistoryEntry {+ id: string;+ configId: string;+ configName: string;+ platform: string;+ timestamp: number;+ duration: number;+ status: BuildStatus;+ outputPath?: string;+ outputSize?: number;+ error?: string;+}++export interface BuildHistoryData {+ version: string;+ entries: BuildHistoryEntry[];+}++// =============================================================================+// Constants+// =============================================================================++const HISTORY_VERSION = '1.0';+const HISTORY_DIR = '.esengine';+const HISTORY_FILENAME = 'build-history.json';+const MAX_ENTRIES = 100;+const MAX_ENTRIES_PER_CONFIG = 20;++// =============================================================================+// BuildHistory Class+// =============================================================================++export class BuildHistory {+ private projectDir_: string;+ private entries_: BuildHistoryEntry[];+ private fs_: NativeFileSystem | null;+ private loaded_: boolean;++ constructor(projectDir: string) {+ this.projectDir_ = projectDir;+ this.entries_ = [];+ this.fs_ = window.__esengine_fs ?? null;+ this.loaded_ = false;+ }++ private getHistoryPath(): string {+ return `${this.projectDir_}/${HISTORY_DIR}/${HISTORY_FILENAME}`;+ }++ private getHistoryDir(): string {+ return `${this.projectDir_}/${HISTORY_DIR}`;+ }++ async load(): Promise<void> {+ if (!this.fs_) {+ this.loaded_ = true;+ return;+ }++ const historyPath = this.getHistoryPath();++ try {+ const content = await this.fs_.readFile(historyPath);+ const decoder = new TextDecoder();+ const jsonStr = decoder.decode(content);+ const data = JSON.parse(jsonStr) as BuildHistoryData;++ if (data.version === HISTORY_VERSION) {+ this.entries_ = data.entries;+ }+ } catch {+ this.entries_ = [];+ }++ this.loaded_ = true;+ }++ async save(): Promise<void> {+ if (!this.fs_) return;++ const historyDir = this.getHistoryDir();+ const historyPath = this.getHistoryPath();++ try {+ await this.fs_.mkdir(historyDir, { recursive: true });+ } catch {+ // Directory may already exist+ }++ const data: BuildHistoryData = {+ version: HISTORY_VERSION,+ entries: this.entries_,+ };++ const jsonStr = JSON.stringify(data, null, 2);+ const encoder = new TextEncoder();+ await this.fs_.writeFile(historyPath, encoder.encode(jsonStr));+ }++ addEntry(entry: Omit<BuildHistoryEntry, 'id'>): BuildHistoryEntry {+ const fullEntry: BuildHistoryEntry = {+ ...entry,+ id: `build-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,+ };++ this.entries_.unshift(fullEntry);+ this.pruneEntries();++ return fullEntry;+ }++ private pruneEntries(): void {+ if (this.entries_.length > MAX_ENTRIES) {+ this.entries_ = this.entries_.slice(0, MAX_ENTRIES);+ }++ const configCounts = new Map<string, number>();+ const keptEntries: BuildHistoryEntry[] = [];++ for (const entry of this.entries_) {+ const count = configCounts.get(entry.configId) || 0;+ if (count < MAX_ENTRIES_PER_CONFIG) {+ keptEntries.push(entry);+ configCounts.set(entry.configId, count + 1);+ }+ }++ this.entries_ = keptEntries;+ }++ getEntries(configId?: string): BuildHistoryEntry[] {+ if (configId) {+ return this.entries_.filter(e => e.configId === configId);+ }+ return [...this.entries_];+ }++ getLatest(configId: string): BuildHistoryEntry | undefined {+ return this.entries_.find(e => e.configId === configId);+ }++ getRecentBuilds(limit: number = 10): BuildHistoryEntry[] {+ return this.entries_.slice(0, limit);+ }++ getSuccessRate(configId?: string): number {+ const entries = configId+ ? this.entries_.filter(e => e.configId === configId)+ : this.entries_;++ if (entries.length === 0) return 0;++ const successCount = entries.filter(e => e.status === 'success').length;+ return (successCount / entries.length) * 100;+ }++ getAverageDuration(configId?: string): number {+ const entries = configId+ ? this.entries_.filter(e => e.configId === configId && e.status === 'success')+ : this.entries_.filter(e => e.status === 'success');++ if (entries.length === 0) return 0;++ const totalDuration = entries.reduce((sum, e) => sum + e.duration, 0);+ return totalDuration / entries.length;+ }++ clearHistory(configId?: string): void {+ if (configId) {+ this.entries_ = this.entries_.filter(e => e.configId !== configId);+ } else {+ this.entries_ = [];+ }+ }++ removeEntry(entryId: string): void {+ const index = this.entries_.findIndex(e => e.id === entryId);+ if (index !== -1) {+ this.entries_.splice(index, 1);+ }+ }++ isLoaded(): boolean {+ return this.loaded_;+ }+}++// =============================================================================+// Formatting Helpers+// =============================================================================++export function formatBuildTime(timestamp: number): string {+ const now = Date.now();+ const diff = now - timestamp;++ if (diff < 60000) {+ return 'Just now';+ } else if (diff < 3600000) {+ const minutes = Math.floor(diff / 60000);+ return `${minutes} min ago`;+ } else if (diff < 86400000) {+ const hours = Math.floor(diff / 3600000);+ return `${hours} hour${hours > 1 ? 's' : ''} ago`;+ } else {+ const date = new Date(timestamp);+ return date.toLocaleDateString();+ }+}++export function formatBuildDuration(ms: number): string {+ if (ms < 1000) {+ return `${ms}ms`;+ } else if (ms < 60000) {+ return `${(ms / 1000).toFixed(1)}s`;+ } else {+ const minutes = Math.floor(ms / 60000);+ const seconds = Math.floor((ms % 60000) / 1000);+ return `${minutes}m ${seconds}s`;+ }+}++export function getBuildStatusIcon(status: BuildStatus): string {+ switch (status) {+ case 'success':+ return '✓';+ case 'failed':+ return '✗';+ case 'cancelled':+ return '○';+ }+}++export function getBuildStatusClass(status: BuildStatus): string {+ switch (status) {+ case 'success':+ return 'build-status-success';+ case 'failed':+ return 'build-status-failed';+ case 'cancelled':+ return 'build-status-cancelled';+ }+}diff --git a/editor/src/builder/BuildPipeline.ts b/editor/src/builder/BuildPipeline.tsnew file mode 100644index 000000000..f981f5dbd--- /dev/null+++ b/editor/src/builder/BuildPipeline.ts@@ -0,0 +1,315 @@+/**+ * @file BuildPipeline.ts+ * @brief Parallel build task execution with dependency management+ */++import { BuildProgressReporter } from './BuildProgress';++// =============================================================================+// Types+// =============================================================================++export interface BuildTask {+ id: string;+ name: string;+ dependencies: string[];+ execute: () => Promise<void>;+ weight: number;+}++export interface TaskResult {+ id: string;+ success: boolean;+ error?: string;+ duration: number;+}++export interface PipelineResult {+ success: boolean;+ results: TaskResult[];+ totalDuration: number;+}++type TaskStatus = 'pending' | 'running' | 'completed' | 'failed';++interface TaskState {+ task: BuildTask;+ status: TaskStatus;+ result?: TaskResult;+}++// =============================================================================+// BuildPipeline Class+// =============================================================================++export class BuildPipeline {+ private tasks_: Map<string, TaskState>;+ private progress_: BuildProgressReporter | null;+ private totalWeight_: number;+ private completedWeight_: number;+ private aborted_: boolean;++ constructor(progress?: BuildProgressReporter) {+ this.tasks_ = new Map();+ this.progress_ = progress || null;+ this.totalWeight_ = 0;+ this.completedWeight_ = 0;+ this.aborted_ = false;+ }++ addTask(task: BuildTask): void {+ this.tasks_.set(task.id, {+ task,+ status: 'pending',+ });+ this.totalWeight_ += task.weight;+ }++ addTasks(tasks: BuildTask[]): void {+ for (const task of tasks) {+ this.addTask(task);+ }+ }++ abort(): void {+ this.aborted_ = true;+ }++ private canExecute(taskId: string): boolean {+ const state = this.tasks_.get(taskId);+ if (!state || state.status !== 'pending') {+ return false;+ }++ for (const depId of state.task.dependencies) {+ const depState = this.tasks_.get(depId);+ if (!depState || depState.status !== 'completed') {+ return false;+ }+ }++ return true;+ }++ private getExecutableTasks(): string[] {+ const executable: string[] = [];+ for (const [id] of this.tasks_) {+ if (this.canExecute(id)) {+ executable.push(id);+ }+ }+ return executable;+ }++ private hasFailed(): boolean {+ for (const [, state] of this.tasks_) {+ if (state.status === 'failed') {+ return true;+ }+ }+ return false;+ }++ private hasBlockedTasks(): boolean {+ for (const [, state] of this.tasks_) {+ if (state.status === 'pending') {+ const canRun = this.canExecute(state.task.id);+ if (!canRun) {+ const blockedByFailed = state.task.dependencies.some(depId => {+ const depState = this.tasks_.get(depId);+ return depState?.status === 'failed';+ });+ if (blockedByFailed) {+ return true;+ }+ }+ }+ }+ return false;+ }++ private allCompleted(): boolean {+ for (const [, state] of this.tasks_) {+ if (state.status !== 'completed' && state.status !== 'failed') {+ return false;+ }+ }+ return true;+ }++ private updateProgress(): void {+ if (!this.progress_) return;++ const percentage = this.totalWeight_ > 0+ ? (this.completedWeight_ / this.totalWeight_) * 100+ : 0;++ this.progress_.setCurrentTask('Executing tasks...', percentage);+ }++ async execute(): Promise<PipelineResult> {+ const startTime = Date.now();+ const results: TaskResult[] = [];++ this.validateDependencies();++ while (!this.allCompleted() && !this.aborted_) {+ const executableIds = this.getExecutableTasks();++ if (executableIds.length === 0) {+ if (this.hasFailed() || this.hasBlockedTasks()) {+ break;+ }+ await new Promise(resolve => setTimeout(resolve, 10));+ continue;+ }++ const promises = executableIds.map(async (taskId) => {+ const state = this.tasks_.get(taskId)!;+ state.status = 'running';++ this.progress_?.log('info', `Starting: ${state.task.name}`);++ const taskStart = Date.now();++ try {+ await state.task.execute();+ const duration = Date.now() - taskStart;++ state.status = 'completed';+ state.result = {+ id: taskId,+ success: true,+ duration,+ };++ this.completedWeight_ += state.task.weight;+ this.updateProgress();++ this.progress_?.log('info', `Completed: ${state.task.name} (${duration}ms)`);+ results.push(state.result);+ } catch (err) {+ const duration = Date.now() - taskStart;+ const errorMsg = err instanceof Error ? err.message : String(err);++ state.status = 'failed';+ state.result = {+ id: taskId,+ success: false,+ error: errorMsg,+ duration,+ };++ this.progress_?.log('error', `Failed: ${state.task.name} - ${errorMsg}`);+ results.push(state.result);+ }+ });++ await Promise.all(promises);+ }++ const totalDuration = Date.now() - startTime;+ const success = !this.hasFailed() && !this.aborted_ && this.allCompleted();++ return {+ success,+ results,+ totalDuration,+ };+ }++ private validateDependencies(): void {+ for (const [id, state] of this.tasks_) {+ for (const depId of state.task.dependencies) {+ if (!this.tasks_.has(depId)) {+ throw new Error(`Task '${id}' depends on unknown task '${depId}'`);+ }+ }+ }++ this.detectCycles();+ }++ private detectCycles(): void {+ const visited = new Set<string>();+ const recursionStack = new Set<string>();++ const dfs = (taskId: string): boolean => {+ visited.add(taskId);+ recursionStack.add(taskId);++ const state = this.tasks_.get(taskId);+ if (state) {+ for (const depId of state.task.dependencies) {+ if (!visited.has(depId)) {+ if (dfs(depId)) return true;+ } else if (recursionStack.has(depId)) {+ return true;+ }+ }+ }++ recursionStack.delete(taskId);+ return false;+ };++ for (const [id] of this.tasks_) {+ if (!visited.has(id)) {+ if (dfs(id)) {+ throw new Error('Circular dependency detected in build tasks');+ }+ }+ }+ }++ getTaskIds(): string[] {+ return Array.from(this.tasks_.keys());+ }++ getTaskStatus(taskId: string): TaskStatus | undefined {+ return this.tasks_.get(taskId)?.status;+ }+}++// =============================================================================+// Task Builder Helpers+// =============================================================================++export function createTask(+ id: string,+ name: string,+ execute: () => Promise<void>,+ options?: { dependencies?: string[]; weight?: number }+): BuildTask {+ return {+ id,+ name,+ execute,+ dependencies: options?.dependencies || [],+ weight: options?.weight || 1,+ };+}++export function createPlayableTasks(+ loadSdk: () => Promise<void>,+ compileScripts: () => Promise<void>,+ collectAssets: () => Promise<void>,+ loadScene: () => Promise<void>,+ assembleHtml: () => Promise<void>,+ writeOutput: () => Promise<void>+): BuildTask[] {+ return [+ createTask('loadSdk', 'Load SDK', loadSdk, { weight: 1 }),+ createTask('compileScripts', 'Compile Scripts', compileScripts, { weight: 3 }),+ createTask('collectAssets', 'Collect Assets', collectAssets, { weight: 2 }),+ createTask('loadScene', 'Load Scene', loadScene, { weight: 1 }),+ createTask('assembleHtml', 'Assemble HTML', assembleHtml, {+ dependencies: ['loadSdk', 'compileScripts', 'collectAssets', 'loadScene'],+ weight: 2,+ }),+ createTask('writeOutput', 'Write Output', writeOutput, {+ dependencies: ['assembleHtml'],+ weight: 1,+ }),+ ];+}diff --git a/editor/src/builder/BuildProgress.ts b/editor/src/builder/BuildProgress.tsnew file mode 100644index 000000000..275569341--- /dev/null+++ b/editor/src/builder/BuildProgress.ts@@ -0,0 +1,257 @@+/**+ * @file BuildProgress.ts+ * @brief Build progress reporting system+ */++// =============================================================================+// Types+// =============================================================================++export type BuildPhase =+ | 'preparing'+ | 'compiling'+ | 'processing_assets'+ | 'assembling'+ | 'writing'+ | 'completed'+ | 'failed';++export type LogLevel = 'info' | 'warn' | 'error' | 'debug';++export interface BuildLogEntry {+ timestamp: number;+ level: LogLevel;+ message: string;+ phase?: BuildPhase;+}++export interface BuildProgress {+ phase: BuildPhase;+ overallProgress: number;+ currentTask: string;+ currentTaskProgress: number;+ logs: BuildLogEntry[];+ startTime: number;+ estimatedTimeRemaining?: number;+}++export type ProgressListener = (progress: BuildProgress) => void;++// =============================================================================+// Phase Weights+// =============================================================================++const PHASE_WEIGHTS: Record<BuildPhase, { start: number; end: number }> = {+ preparing: { start: 0, end: 10 },+ compiling: { start: 10, end: 50 },+ processing_assets: { start: 50, end: 80 },+ assembling: { start: 80, end: 95 },+ writing: { start: 95, end: 100 },+ completed: { start: 100, end: 100 },+ failed: { start: 0, end: 0 },+};++const PHASE_NAMES: Record<BuildPhase, string> = {+ preparing: 'Preparing build...',+ compiling: 'Compiling scripts...',+ processing_assets: 'Processing assets...',+ assembling: 'Assembling output...',+ writing: 'Writing files...',+ completed: 'Build completed',+ failed: 'Build failed',+};++// =============================================================================+// BuildProgressReporter Class+// =============================================================================++export class BuildProgressReporter {+ private progress_: BuildProgress;+ private listeners_: Set<ProgressListener>;+ private lastProgressUpdate_: number;+ private phaseTimes_: Map<BuildPhase, number>;++ constructor() {+ this.progress_ = {+ phase: 'preparing',+ overallProgress: 0,+ currentTask: '',+ currentTaskProgress: 0,+ logs: [],+ startTime: Date.now(),+ };+ this.listeners_ = new Set();+ this.lastProgressUpdate_ = Date.now();+ this.phaseTimes_ = new Map();+ }++ onProgress(listener: ProgressListener): () => void {+ this.listeners_.add(listener);+ listener(this.progress_);+ return () => this.listeners_.delete(listener);+ }++ private notify(): void {+ for (const listener of this.listeners_) {+ listener({ ...this.progress_ });+ }+ }++ private calculateOverallProgress(): number {+ const weights = PHASE_WEIGHTS[this.progress_.phase];+ if (!weights) return 0;++ const phaseRange = weights.end - weights.start;+ const phaseProgress = (this.progress_.currentTaskProgress / 100) * phaseRange;+ return Math.round(weights.start + phaseProgress);+ }++ private updateEstimatedTime(): void {+ const elapsed = Date.now() - this.progress_.startTime;+ const progress = this.progress_.overallProgress;++ if (progress > 5 && progress < 95) {+ const estimatedTotal = (elapsed / progress) * 100;+ this.progress_.estimatedTimeRemaining = Math.max(0, estimatedTotal - elapsed);+ } else {+ this.progress_.estimatedTimeRemaining = undefined;+ }+ }++ setPhase(phase: BuildPhase): void {+ if (this.progress_.phase !== phase) {+ this.phaseTimes_.set(phase, Date.now());+ }++ this.progress_.phase = phase;+ this.progress_.currentTask = PHASE_NAMES[phase];+ this.progress_.currentTaskProgress = 0;+ this.progress_.overallProgress = this.calculateOverallProgress();+ this.updateEstimatedTime();++ this.log('info', `Phase: ${PHASE_NAMES[phase]}`);+ this.notify();+ }++ setCurrentTask(task: string, progress?: number): void {+ this.progress_.currentTask = task;+ if (progress !== undefined) {+ this.progress_.currentTaskProgress = Math.max(0, Math.min(100, progress));+ }+ this.progress_.overallProgress = this.calculateOverallProgress();+ this.updateEstimatedTime();++ const now = Date.now();+ if (now - this.lastProgressUpdate_ > 100) {+ this.lastProgressUpdate_ = now;+ this.notify();+ }+ }++ incrementTaskProgress(increment: number): void {+ this.progress_.currentTaskProgress = Math.min(+ 100,+ this.progress_.currentTaskProgress + increment+ );+ this.progress_.overallProgress = this.calculateOverallProgress();+ this.updateEstimatedTime();++ const now = Date.now();+ if (now - this.lastProgressUpdate_ > 100) {+ this.lastProgressUpdate_ = now;+ this.notify();+ }+ }++ log(level: LogLevel, message: string): void {+ const entry: BuildLogEntry = {+ timestamp: Date.now(),+ level,+ message,+ phase: this.progress_.phase,+ };+ this.progress_.logs.push(entry);++ if (level !== 'debug') {+ this.notify();+ }+ }++ complete(): void {+ this.progress_.phase = 'completed';+ this.progress_.overallProgress = 100;+ this.progress_.currentTaskProgress = 100;+ this.progress_.currentTask = 'Build completed';+ this.progress_.estimatedTimeRemaining = 0;+ this.log('info', 'Build completed successfully');+ this.notify();+ }++ fail(error: string): void {+ this.progress_.phase = 'failed';+ this.progress_.currentTask = 'Build failed';+ this.log('error', error);+ this.notify();+ }++ getProgress(): BuildProgress {+ return { ...this.progress_ };+ }++ getDuration(): number {+ return Date.now() - this.progress_.startTime;+ }++ getLogs(): BuildLogEntry[] {+ return [...this.progress_.logs];+ }++ getLogsAsText(): string {+ return this.progress_.logs+ .map(entry => {+ const time = new Date(entry.timestamp).toLocaleTimeString();+ const level = entry.level.toUpperCase().padEnd(5);+ return `[${time}] ${level} ${entry.message}`;+ })+ .join('\n');+ }++ reset(): void {+ this.progress_ = {+ phase: 'preparing',+ overallProgress: 0,+ currentTask: '',+ currentTaskProgress: 0,+ logs: [],+ startTime: Date.now(),+ };+ this.phaseTimes_.clear();+ this.notify();+ }+}++// =============================================================================+// Formatting Utilities+// =============================================================================++export function formatDuration(ms: number): string {+ if (ms < 1000) {+ return `${ms}ms`;+ } else if (ms < 60000) {+ return `${(ms / 1000).toFixed(1)}s`;+ } else {+ const minutes = Math.floor(ms / 60000);+ const seconds = Math.floor((ms % 60000) / 1000);+ return `${minutes}m ${seconds}s`;+ }+}++export function formatSize(bytes: number): string {+ if (bytes < 1024) {+ return `${bytes} B`;+ } else if (bytes < 1024 * 1024) {+ return `${(bytes / 1024).toFixed(1)} KB`;+ } else {+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;+ }+}diff --git a/editor/src/builder/BuildService.ts b/editor/src/builder/BuildService.tsindex 7eb81cd9e..91f3636c0 100644--- a/editor/src/builder/BuildService.ts+++ b/editor/src/builder/BuildService.ts@@ -6,6 +6,9 @@import type { BuildConfig } from '../types/BuildTypes';import { PlayableBuilder } from './PlayableBuilder';import { WeChatBuilder } from './WeChatBuilder';+import { BuildCache } from './BuildCache';+import { BuildProgressReporter, formatDuration } from './BuildProgress';+import { BuildHistory } from './BuildHistory';// =============================================================================// Types@@ -14,12 +17,22 @@ import { WeChatBuilder } from './WeChatBuilder';export interface BuildResult {success: boolean;outputPath?: string;+ outputSize?: number;error?: string;+ duration?: number;+ cached?: boolean;}export interface BuildContext {projectPath: string;config: BuildConfig;+ progress?: BuildProgressReporter;+ cache?: BuildCache;+}++export interface BuildOptions {+ useCache?: boolean;+ progress?: BuildProgressReporter;}// =============================================================================@@ -28,40 +41,130 @@ export interface BuildContext {export class BuildService {private projectPath_: string;+ private cache_: BuildCache;+ private history_: BuildHistory | null;- constructor(projectPath: string) {+ constructor(projectPath: string, history?: BuildHistory) {this.projectPath_ = projectPath;+ this.cache_ = new BuildCache(projectPath);+ this.history_ = history || null;}- async build(config: BuildConfig): Promise<BuildResult> {+ async build(config: BuildConfig, options?: BuildOptions): Promise<BuildResult> {+ const progress = options?.progress || new BuildProgressReporter();+ const useCache = options?.useCache ?? true;+ const startTime = Date.now();+console.log(`[BuildService] Starting build for config: ${config.name}`);console.log(`[BuildService] Platform: ${config.platform}`);console.log(`[BuildService] Scenes: ${config.scenes.join(', ')}`);+ progress.setPhase('preparing');+ progress.log('info', `Building config: ${config.name}`);+const context: BuildContext = {projectPath: this.projectPath_,config,+ progress,+ cache: useCache ? this.cache_ : undefined,};try {+ let result: BuildResult;+if (config.platform === 'playable') {const builder = new PlayableBuilder(context);- return await builder.build();+ result = await builder.build();} else if (config.platform === 'wechat') {const builder = new WeChatBuilder(context);- return await builder.build();+ result = await builder.build();} else {+ progress.fail(`Unknown platform: ${config.platform}`);return {success: false,error: `Unknown platform: ${config.platform}`,};}++ const duration = Date.now() - startTime;+ result.duration = duration;++ if (result.success) {+ progress.complete();+ progress.log('info', `Build completed in ${formatDuration(duration)}`);++ if (this.history_) {+ this.history_.addEntry({+ configId: config.id,+ configName: config.name,+ platform: config.platform,+ timestamp: Date.now(),+ duration,+ status: 'success',+ outputPath: result.outputPath,+ outputSize: result.outputSize,+ });+ await this.history_.save();+ }+ } else {+ progress.fail(result.error || 'Build failed');++ if (this.history_) {+ this.history_.addEntry({+ configId: config.id,+ configName: config.name,+ platform: config.platform,+ timestamp: Date.now(),+ duration,+ status: 'failed',+ error: result.error,+ });+ await this.history_.save();+ }+ }++ return result;} catch (err) {+ const duration = Date.now() - startTime;+ const errorMsg = err instanceof Error ? err.message : String(err);+console.error('[BuildService] Build failed:', err);+ progress.fail(errorMsg);++ if (this.history_) {+ this.history_.addEntry({+ configId: config.id,+ configName: config.name,+ platform: config.platform,+ timestamp: Date.now(),+ duration,+ status: 'failed',+ error: errorMsg,+ });+ await this.history_.save();+ }+return {success: false,- error: String(err),+ error: errorMsg,+ duration,};}}++ getCache(): BuildCache {+ return this.cache_;+ }++ getHistory(): BuildHistory | null {+ return this.history_;+ }++ async clearCache(configId?: string): Promise<void> {+ if (configId) {+ await this.cache_.invalidateCache(configId);+ } else {+ await this.cache_.clearAllCaches();+ }+ }}diff --git a/editor/src/builder/BuildSettingsDialog.ts b/editor/src/builder/BuildSettingsDialog.tsindex 5c38269ce..a83984fe3 100644--- a/editor/src/builder/BuildSettingsDialog.ts+++ b/editor/src/builder/BuildSettingsDialog.ts@@ -1,6 +1,6 @@/*** @file BuildSettingsDialog.ts- * @brief Build settings dialog UI component+ * @brief Build settings dialog UI component with three-column layout*/import { icons } from '../utils/icons';@@ -14,6 +14,12 @@ import {} from '../types/BuildTypes';import { type BuildResult } from './BuildService';import { showProgressToast, dismissToast, showToast } from '../ui/Toast';+import { BuildHistory, formatBuildTime, formatBuildDuration, getBuildStatusIcon, type BuildHistoryEntry } from './BuildHistory';+import { BuildConfigService, initBuildConfigService } from './BuildConfigService';+import { downloadConfigsAsFile, uploadConfigsFromFile } from './BuildConfigIO';+import { BUILD_TEMPLATES, createConfigFromTemplate, type BuildTemplate } from './BuildTemplates';+import { BatchBuilder } from './BatchBuilder';+import { formatSize } from './BuildProgress';// =============================================================================// Types@@ -26,7 +32,7 @@ export interface BuildSettingsDialogOptions {}// =============================================================================-// Storage+// Storage (Legacy - for migration)// =============================================================================const BUILD_SETTINGS_KEY = 'esengine_build_settings';@@ -56,6 +62,22 @@ export class BuildSettingsDialog {this.options_ = options;this.settings_ = loadBuildSettings();+ const projectDir = this.getProjectDir();+ this.configService_ = initBuildConfigService(projectDir);+ this.history_ = new BuildHistory(projectDir);+ this.batchBuilder_ = new BatchBuilder(projectDir, this.history_);++ this.initAsync();+ }++ private async initAsync(): Promise<void> {+ await Promise.all([+ this.configService_.load(),+ this.history_.load(),+ ]);++ this.settings_ = this.configService_.getSettings();+if (!this.settings_.activeConfigId && this.settings_.configs.length > 0) {this.settings_.activeConfigId = this.settings_.configs[0].id;}@@ -69,11 +91,16 @@ export class BuildSettingsDialog {}dispose(): void {- saveBuildSettings(this.settings_);+ this.saveSettings();if (this.keyHandler_) {document.removeEventListener('keydown', this.keyHandler_);}- this.overlay_.remove();+ this.overlay_?.remove();+ }++ private async saveSettings(): Promise<void> {+ saveBuildSettings(this.settings_);+ await this.configService_.save();}private getActiveConfig(): BuildConfig | null {@@ -81,26 +108,50 @@ export class BuildSettingsDialog {}private render(): void {+ if (!this.overlay_) return;+const config = this.getActiveConfig();this.overlay_.innerHTML = `- <div class="es-build-dialog">+ <div class="es-build-dialog es-build-dialog-wide"><div class="es-dialog-header"><span class="es-dialog-title">${icons.cog(16)} Build Settings</span><button class="es-dialog-close" data-action="close">×</button></div><div class="es-build-toolbar">- <button class="es-btn es-btn-icon" data-action="add-config" title="Add Build Config">- ${icons.plus(14)} Add Config- </button>+ <div class="es-build-toolbar-left">+ <button class="es-btn es-btn-icon" data-action="add-config" title="Add Build Config">+ ${icons.plus(14)} Add+ </button>+ <button class="es-btn es-btn-icon" data-action="import-configs" title="Import Configs">+ ${icons.upload(14)} Import+ </button>+ <button class="es-btn es-btn-icon" data-action="export-configs" title="Export Configs">+ ${icons.download(14)} Export+ </button>+ <button class="es-btn es-btn-icon" data-action="show-templates" title="Templates">+ ${icons.template(14)} Templates+ </button>+ </div>+ <div class="es-build-toolbar-right">+ <button class="es-btn" data-action="build-all" title="Build All Configs">+ Build All+ </button>+ <button class="es-btn es-btn-primary" data-action="build" ${!config ? 'disabled' : ''}>+ ${icons.play(14)} Build+ </button>+ </div></div>- <div class="es-build-body">+ <div class="es-build-body es-build-body-three-col"><div class="es-build-sidebar">${this.renderSidebar()}</div><div class="es-build-detail">${config ? this.renderDetail(config) : this.renderNoConfig()}</div>+ <div class="es-build-output">+ ${config ? this.renderOutputPanel(config) : ''}+ </div></div></div>`;@@ -131,8 +182,14 @@ export class BuildSettingsDialog {private renderConfigItem(config: BuildConfig): string {const isActive = this.settings_.activeConfigId === config.id;+ const latestBuild = this.history_.getLatest(config.id);+ const statusIndicator = latestBuild+ ? `<span class="es-build-status-dot es-build-status-${latestBuild.status}"></span>`+ : '';+return `<div class="es-build-config-item ${isActive ? 'es-active' : ''}" data-config="${config.id}">+ ${statusIndicator}<span class="es-build-config-name">${config.name}</span><button class="es-btn-icon es-build-config-delete" data-action="delete-config" data-config="${config.id}" title="Delete">${icons.x(10)}@@ -154,30 +211,105 @@ export class BuildSettingsDialog {return `<div class="es-build-detail-header"><div class="es-build-detail-title">- <h3>${config.name}</h3>+ <input type="text" class="es-build-name-input" id="config-name-input"+ value="${config.name}" placeholder="Config Name"><span class="es-build-detail-platform">${this.getPlatformName(config.platform)}</span></div><div class="es-build-detail-actions">- <button class="es-btn" data-action="switch-config">Switch</button>- <button class="es-btn es-btn-primary" data-action="build">- ${icons.play(14)} Build+ <button class="es-btn es-btn-icon" data-action="duplicate-config" title="Duplicate">+ ${icons.copy(14)}</button></div></div><div class="es-build-detail-content"><div class="es-build-data-section">- <h4>Build Data</h4>${this.renderScenesSection(config)}${this.renderDefinesSection(config)}</div><div class="es-build-settings-section">- <h4>Platform Settings</h4>${this.renderPlatformSettings(config)}</div></div>`;}+ private renderOutputPanel(config: BuildConfig): string {+ const latestBuild = this.history_.getLatest(config.id);+ const recentBuilds = this.history_.getEntries(config.id).slice(0, 5);++ const latestSection = latestBuild ? `+ <div class="es-build-output-latest">+ <div class="es-build-output-stat">+ <span class="es-build-output-label">Last Build</span>+ <span class="es-build-output-value">${formatBuildTime(latestBuild.timestamp)}</span>+ </div>+ <div class="es-build-output-stat">+ <span class="es-build-output-label">Status</span>+ <span class="es-build-output-value es-build-status-${latestBuild.status}">+ ${getBuildStatusIcon(latestBuild.status)} ${latestBuild.status}+ </span>+ </div>+ ${latestBuild.outputSize ? `+ <div class="es-build-output-stat">+ <span class="es-build-output-label">Size</span>+ <span class="es-build-output-value">${formatSize(latestBuild.outputSize)}</span>+ </div>+ ` : ''}+ <div class="es-build-output-stat">+ <span class="es-build-output-label">Duration</span>+ <span class="es-build-output-value">${formatBuildDuration(latestBuild.duration)}</span>+ </div>+ ${latestBuild.outputPath ? `+ <div class="es-build-output-actions">+ <button class="es-btn es-btn-small" data-action="open-output" data-path="${latestBuild.outputPath}">+ ${icons.folder(12)} Open+ </button>+ <button class="es-btn es-btn-small" data-action="preview-output" data-path="${latestBuild.outputPath}">+ ${icons.play(12)} Preview+ </button>+ </div>+ ` : ''}+ </div>+ ` : `+ <div class="es-build-output-empty">+ No builds yet+ </div>+ `;++ const historySection = recentBuilds.length > 0 ? `+ <div class="es-build-history">+ <div class="es-build-section-title">Build History</div>+ <div class="es-build-history-list">+ ${recentBuilds.map(entry => this.renderHistoryEntry(entry)).join('')}+ </div>+ </div>+ ` : '';++ return `+ <div class="es-build-output-header">+ <span class="es-build-section-title">Build Output</span>+ ${recentBuilds.length > 0 ? `+ <button class="es-btn-icon" data-action="clear-history" title="Clear History">+ ${icons.trash(12)}+ </button>+ ` : ''}+ </div>+ ${latestSection}+ ${historySection}+ `;+ }++ private renderHistoryEntry(entry: BuildHistoryEntry): string {+ const time = new Date(entry.timestamp).toLocaleTimeString();+ return `+ <div class="es-build-history-item es-build-status-${entry.status}">+ <span class="es-build-history-icon">${getBuildStatusIcon(entry.status)}</span>+ <span class="es-build-history-time">${time}</span>+ <span class="es-build-history-duration">${formatBuildDuration(entry.duration)}</span>+ </div>+ `;+ }+private renderScenesSection(config: BuildConfig): string {const isExpanded = this.expandedSections_.has('scenes');const scenesHtml = config.scenes.length > 0@@ -197,13 +329,14 @@ export class BuildSettingsDialog {<div class="es-build-collapse-header">${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}<span>Scenes</span>+ <span class="es-build-collapse-count">${config.scenes.length}</span></div><div class="es-build-collapse-content"><div class="es-build-scene-list">${scenesHtml}</div><button class="es-btn es-btn-link" data-action="add-current-scene">- Add Current Scene+ ${icons.plus(12)} Add Current Scene</button></div></div>@@ -228,6 +361,7 @@ export class BuildSettingsDialog {<div class="es-build-collapse-header">${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}<span>Script Defines</span>+ <span class="es-build-collapse-count">${config.defines.length}</span></div><div class="es-build-collapse-content"><div class="es-build-define-list">@@ -335,7 +469,7 @@ export class BuildSettingsDialog {<div class="es-build-collapse ${isExpanded ? 'es-expanded' : ''}" data-section="platform"><div class="es-build-collapse-header">${isExpanded ? icons.chevronDown(12) : icons.chevronRight(12)}- <span>${platformName}设置</span>+ <span>${platformName} Settings</span></div><div class="es-build-collapse-content">${settingsHtml}@@ -354,6 +488,8 @@ export class BuildSettingsDialog {}private setupEvents(): void {+ if (!this.overlay_) return;+this.overlay_.addEventListener('click', (e) => {const target = e.target as HTMLElement;@@ -411,15 +547,52 @@ export class BuildSettingsDialog {this.handleInputChange(target);});+ this.overlay_.addEventListener('input', (e) => {+ const target = e.target as HTMLInputElement;+ if (target.id === 'config-name-input') {+ const config = this.getActiveConfig();+ if (config) {+ config.name = target.value;+ this.saveSettings();+ }+ }+ });+this.keyHandler_ = (e: KeyboardEvent) => {if (e.key === 'Escape') {this.close();}++ if ((e.metaKey || e.ctrlKey) && e.key === 'b') {+ e.preventDefault();+ const config = this.getActiveConfig();+ if (config) {+ this.handleBuild(config);+ }+ }++ if ((e.metaKey || e.ctrlKey) && e.key === 'd') {+ e.preventDefault();+ const config = this.getActiveConfig();+ if (config) {+ this.duplicateConfig(config);+ }+ }++ if (e.key === 'Delete' || e.key === 'Backspace') {+ const target = e.target as HTMLElement;+ if (target.tagName !== 'INPUT' && target.tagName !== 'TEXTAREA') {+ const config = this.getActiveConfig();+ if (config) {+ this.deleteConfig(config.id);+ }+ }+ }};document.addEventListener('keydown', this.keyHandler_);}- private handleAction(action: string | undefined, element: HTMLElement): void {+ private async handleAction(action: string | undefined, element: HTMLElement): Promise<void> {const config = this.getActiveConfig();switch (action) {@@ -435,6 +608,12 @@ export class BuildSettingsDialog {break;}+ case 'duplicate-config':+ if (config) {+ this.duplicateConfig(config);+ }+ break;+case 'add-current-scene':if (config) {const editor = (window as any).__esengine_editor;@@ -443,7 +622,7 @@ export class BuildSettingsDialog {const relativePath = this.toRelativePath(scenePath);if (!config.scenes.includes(relativePath)) {config.scenes.push(relativePath);- saveBuildSettings(this.settings_);+ await this.saveSettings();this.render();}}@@ -454,7 +633,7 @@ export class BuildSettingsDialog {const index = parseInt(element.dataset.index ?? '-1', 10);if (config && index >= 0) {config.scenes.splice(index, 1);- saveBuildSettings(this.settings_);+ await this.saveSettings();this.render();}break;@@ -465,7 +644,7 @@ export class BuildSettingsDialog {const value = input?.value.trim();if (config && value && !config.defines.includes(value)) {config.defines.push(value);- saveBuildSettings(this.settings_);+ await this.saveSettings();this.render();}break;@@ -475,7 +654,7 @@ export class BuildSettingsDialog {const index = parseInt(element.dataset.index ?? '-1', 10);if (config && index >= 0) {config.defines.splice(index, 1);- saveBuildSettings(this.settings_);+ await this.saveSettings();this.render();}break;@@ -487,16 +666,42 @@ export class BuildSettingsDialog {}break;- case 'switch-config':- // Cycle to next config of same platform+ case 'build-all':+ this.handleBuildAll();+ break;++ case 'import-configs':+ this.handleImportConfigs();+ break;++ case 'export-configs':+ downloadConfigsAsFile(this.settings_.configs);+ break;++ case 'show-templates':+ this.showTemplatesDialog();+ break;++ case 'open-output': {+ const path = element.dataset.path;+ if (path) {+ this.openOutputFolder(path);+ }+ break;+ }++ case 'preview-output': {+ const path = element.dataset.path;+ if (path) {+ this.previewOutput(path);+ }+ break;+ }++ case 'clear-history':if (config) {- const platformConfigs = this.settings_.configs.filter(- c => c.platform === config.platform- );- const idx = platformConfigs.findIndex(c => c.id === config.id);- const nextIdx = (idx + 1) % platformConfigs.length;- this.settings_.activeConfigId = platformConfigs[nextIdx].id;- saveBuildSettings(this.settings_);+ this.history_.clearHistory(config.id);+ await this.history_.save();this.render();}break;@@ -508,6 +713,10 @@ export class BuildSettingsDialog {case 'browse-output':this.browseFile('playable-output', 'HTML File', ['html']);break;++ case 'browse-sdk':+ this.browseFile('wechat-sdk', 'SDK File', ['js', 'cjs']);+ break;}}@@ -535,7 +744,6 @@ export class BuildSettingsDialog {const id = target.id;- // Playable settingsif (config.playableSettings) {if (id === 'playable-startup-scene') {config.playableSettings.startupScene = target.value;@@ -550,7 +758,6 @@ export class BuildSettingsDialog {}}- // WeChat settingsif (config.wechatSettings) {if (id === 'wechat-appid') {config.wechatSettings.appId = target.value;@@ -567,7 +774,7 @@ export class BuildSettingsDialog {}}- saveBuildSettings(this.settings_);+ this.saveSettings();}private showAddConfigDialog(): void {@@ -603,7 +810,7 @@ export class BuildSettingsDialog {const close = () => dialog.remove();dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);- dialog.querySelector('[data-action="confirm"]')?.addEventListener('click', () => {+ dialog.querySelector('[data-action="confirm"]')?.addEventListener('click', async () => {const nameInput = dialog.querySelector('#config-name') as HTMLInputElement;const platformSelect = dialog.querySelector('#config-platform') as HTMLSelectElement;const name = nameInput.value.trim() || 'New Config';@@ -612,13 +819,105 @@ export class BuildSettingsDialog {const newConfig = createDefaultBuildConfig(platform, name);this.settings_.configs.push(newConfig);this.settings_.activeConfigId = newConfig.id;- saveBuildSettings(this.settings_);+ await this.saveSettings();close();this.render();});}+ private showTemplatesDialog(): void {+ const dialog = document.createElement('div');+ dialog.className = 'es-build-add-dialog';++ const templatesHtml = BUILD_TEMPLATES.map(t => `+ <div class="es-build-template-item" data-template="${t.id}">+ <div class="es-build-template-header">+ <span class="es-build-template-name">${t.name}</span>+ <span class="es-build-template-platform">${t.platform}</span>+ </div>+ <div class="es-build-template-desc">${t.description}</div>+ </div>+ `).join('');++ dialog.innerHTML = `+ <div class="es-dialog" style="max-width: 400px;">+ <div class="es-dialog-header">+ <span class="es-dialog-title">Build Templates</span>+ <button class="es-dialog-close" data-action="cancel">×</button>+ </div>+ <div class="es-dialog-body">+ <div class="es-build-templates-list">+ ${templatesHtml}+ </div>+ </div>+ <div class="es-dialog-footer">+ <button class="es-dialog-btn" data-action="cancel">Cancel</button>+ </div>+ </div>+ `;++ this.overlay_.appendChild(dialog);++ const close = () => dialog.remove();++ dialog.querySelector('[data-action="cancel"]')?.addEventListener('click', close);++ dialog.querySelectorAll('.es-build-template-item').forEach(item => {+ item.addEventListener('click', async () => {+ const templateId = (item as HTMLElement).dataset.template;+ const template = BUILD_TEMPLATES.find(t => t.id === templateId);+ if (template) {+ const newConfig = createConfigFromTemplate(template);+ this.settings_.configs.push(newConfig);+ this.settings_.activeConfigId = newConfig.id;+ await this.saveSettings();+ close();+ this.render();+ }+ });+ });+ }++ private async handleImportConfigs(): Promise<void> {+ const result = await uploadConfigsFromFile();++ if (result.success && result.configs.length > 0) {+ for (const config of result.configs) {+ this.settings_.configs.push(config);+ }+ await this.saveSettings();+ this.render();++ showToast({+ type: 'success',+ title: 'Import Successful',+ message: `Imported ${result.configs.length} config(s)`,+ duration: 3000,+ });+ } else if (result.errors.length > 0) {+ showToast({+ type: 'error',+ title: 'Import Failed',+ message: result.errors[0],+ duration: 5000,+ });+ }+ }++ private duplicateConfig(config: BuildConfig): void {+ const newConfig: BuildConfig = {+ ...JSON.parse(JSON.stringify(config)),+ id: `${config.platform}-${Date.now()}`,+ name: `${config.name} (Copy)`,+ };++ this.settings_.configs.push(newConfig);+ this.settings_.activeConfigId = newConfig.id;+ this.saveSettings();+ this.render();+ }+private deleteConfig(configId: string): void {const idx = this.settings_.configs.findIndex(c => c.id === configId);if (idx >= 0) {@@ -626,25 +925,23 @@ export class BuildSettingsDialog {if (this.settings_.activeConfigId === configId) {this.settings_.activeConfigId = this.settings_.configs[0]?.id ?? '';}- saveBuildSettings(this.settings_);+ this.saveSettings();this.render();}}private async handleBuild(config: BuildConfig): Promise<void> {const buildBtn = this.overlay_.querySelector('[data-action="build"]') as HTMLButtonElement;- const switchBtn = this.overlay_.querySelector('[data-action="switch-config"]') as HTMLButtonElement;+ const buildAllBtn = this.overlay_.querySelector('[data-action="build-all"]') as HTMLButtonElement;- // Disable buttonsif (buildBtn) {buildBtn.disabled = true;buildBtn.innerHTML = `${icons.refresh(14)} Building...`;}- if (switchBtn) {- switchBtn.disabled = true;+ if (buildAllBtn) {+ buildAllBtn.disabled = true;}- // Show progress toastconst platformName = this.getPlatformName(config.platform);const toastId = showProgressToast(`Building ${config.name}`,@@ -657,7 +954,18 @@ export class BuildSettingsDialog {dismissToast(toastId);if (result.success && result.outputPath) {- // Show success toast with action to open folder+ this.history_.addEntry({+ configId: config.id,+ configName: config.name,+ platform: config.platform,+ timestamp: Date.now(),+ duration: result.duration || 0,+ status: 'success',+ outputPath: result.outputPath,+ outputSize: result.outputSize,+ });+ await this.history_.save();+showToast({type: 'success',title: 'Build Completed',@@ -676,6 +984,17 @@ export class BuildSettingsDialog {],});} else if (!result.success) {+ this.history_.addEntry({+ configId: config.id,+ configName: config.name,+ platform: config.platform,+ timestamp: Date.now(),+ duration: result.duration || 0,+ status: 'failed',+ error: result.error,+ });+ await this.history_.save();+showToast({type: 'error',title: 'Build Failed',@@ -683,6 +1002,8 @@ export class BuildSettingsDialog {duration: 5000,});}++ this.render();} catch (err) {dismissToast(toastId);showToast({@@ -692,13 +1013,66 @@ export class BuildSettingsDialog {duration: 5000,});} finally {- // Re-enable buttonsif (buildBtn) {buildBtn.disabled = false;buildBtn.innerHTML = `${icons.play(14)} Build`;}- if (switchBtn) {- switchBtn.disabled = false;+ if (buildAllBtn) {+ buildAllBtn.disabled = false;+ }+ }+ }++ private async handleBuildAll(): Promise<void> {+ const buildBtn = this.overlay_.querySelector('[data-action="build"]') as HTMLButtonElement;+ const buildAllBtn = this.overlay_.querySelector('[data-action="build-all"]') as HTMLButtonElement;++ if (buildBtn) buildBtn.disabled = true;+ if (buildAllBtn) {+ buildAllBtn.disabled = true;+ buildAllBtn.textContent = 'Building...';+ }++ const toastId = showProgressToast(+ 'Building All Configs',+ `0 / ${this.settings_.configs.length} completed`+ );++ try {+ const result = await this.batchBuilder_.buildAll(this.settings_.configs);++ dismissToast(toastId);++ if (result.success) {+ showToast({+ type: 'success',+ title: 'Build All Completed',+ message: `${result.successCount} succeeded, ${result.failureCount} failed`,+ duration: 5000,+ });+ } else {+ showToast({+ type: 'error',+ title: 'Build All Completed with Errors',+ message: `${result.successCount} succeeded, ${result.failureCount} failed`,+ duration: 5000,+ });+ }++ this.render();+ } catch (err) {+ dismissToast(toastId);+ showToast({+ type: 'error',+ title: 'Build All Failed',+ message: String(err),+ duration: 5000,+ });+ } finally {+ if (buildBtn) buildBtn.disabled = false;+ if (buildAllBtn) {+ buildAllBtn.disabled = false;+ buildAllBtn.textContent = 'Build All';}}}@@ -725,9 +1099,7 @@ export class BuildSettingsDialog {private async openOutputFolder(outputPath: string): Promise<void> {try {- // Get directory from output pathconst dirPath = outputPath.replace(/\\/g, '/').split('/').slice(0, -1).join('/');-const fs = (window as any).__esengine_fs;if (fs?.openFolder) {await fs.openFolder(dirPath);@@ -737,6 +1109,17 @@ export class BuildSettingsDialog {}}+ private async previewOutput(outputPath: string): Promise<void> {+ try {+ const fs = (window as any).__esengine_fs;+ if (fs?.openFile) {+ await fs.openFile(outputPath);+ }+ } catch (err) {+ console.error('Failed to preview output:', err);+ }+ }+// =========================================================================// Member Variables// =========================================================================@@ -744,6 +1127,9 @@ export class BuildSettingsDialog {private overlay_!: HTMLElement;private options_!: BuildSettingsDialogOptions;private settings_!: BuildSettings;+ private configService_!: BuildConfigService;+ private history_!: BuildHistory;+ private batchBuilder_!: BatchBuilder;private expandedSections_: Set<string> = new Set(['scenes', 'defines', 'platform']);private keyHandler_: ((e: KeyboardEvent) => void) | null = null;}diff --git a/editor/src/builder/BuildTemplates.ts b/editor/src/builder/BuildTemplates.tsnew file mode 100644index 000000000..128615526--- /dev/null+++ b/editor/src/builder/BuildTemplates.ts@@ -0,0 +1,221 @@+/**+ * @file BuildTemplates.ts+ * @brief Preset build configuration templates+ */++import {+ BuildConfig,+ BuildPlatform,+ PlayableSettings,+ WeChatSettings,+} from '../types/BuildTypes';++// =============================================================================+// Types+// =============================================================================++export interface BuildTemplate {+ id: string;+ name: string;+ description: string;+ platform: BuildPlatform;+ icon: string;+ defines: string[];+ playableSettings?: Partial<PlayableSettings>;+ wechatSettings?: Partial<WeChatSettings>;+}++// =============================================================================+// Preset Templates+// =============================================================================++export const BUILD_TEMPLATES: BuildTemplate[] = [+ {+ id: 'facebook-playable',+ name: 'Facebook Playable',+ description: 'Optimized for Facebook playable ads (2MB limit)',+ platform: 'playable',+ icon: 'facebook',+ defines: [],+ playableSettings: {+ isDevelopment: false,+ minifyCode: true,+ embedFonts: false,+ outputPath: 'build/facebook-playable.html',+ },+ },+ {+ id: 'google-playable',+ name: 'Google Playable',+ description: 'Optimized for Google playable ads (5MB limit)',+ platform: 'playable',+ icon: 'google',+ defines: [],+ playableSettings: {+ isDevelopment: false,+ minifyCode: true,+ embedFonts: true,+ outputPath: 'build/google-playable.html',+ },+ },+ {+ id: 'playable-debug',+ name: 'Playable Debug',+ description: 'Development build with debug features enabled',+ platform: 'playable',+ icon: 'bug',+ defines: ['DEBUG'],+ playableSettings: {+ isDevelopment: true,+ minifyCode: false,+ embedFonts: true,+ outputPath: 'build/playable-debug.html',+ },+ },+ {+ id: 'wechat-production',+ name: 'WeChat Production',+ description: 'Production build with subpackage support',+ platform: 'wechat',+ icon: 'package',+ defines: [],+ wechatSettings: {+ bundleMode: 'subpackage',+ orientation: 'portrait',+ },+ },+ {+ id: 'wechat-debug',+ name: 'WeChat Debug',+ description: 'Development build with debug features',+ platform: 'wechat',+ icon: 'bug',+ defines: ['DEBUG'],+ wechatSettings: {+ bundleMode: 'single',+ orientation: 'portrait',+ },+ },+ {+ id: 'wechat-single-file',+ name: 'WeChat Single File',+ description: 'Single file bundle for simple games',+ platform: 'wechat',+ icon: 'file',+ defines: [],+ wechatSettings: {+ bundleMode: 'singleFile',+ orientation: 'portrait',+ },+ },+ {+ id: 'wechat-landscape',+ name: 'WeChat Landscape',+ description: 'Landscape orientation for wide-screen games',+ platform: 'wechat',+ icon: 'monitor',+ defines: [],+ wechatSettings: {+ bundleMode: 'subpackage',+ orientation: 'landscape',+ },+ },+];++// =============================================================================+// Template Functions+// =============================================================================++export function getTemplates(): BuildTemplate[] {+ return BUILD_TEMPLATES;+}++export function getTemplatesByPlatform(platform: BuildPlatform): BuildTemplate[] {+ return BUILD_TEMPLATES.filter(t => t.platform === platform);+}++export function getTemplate(templateId: string): BuildTemplate | undefined {+ return BUILD_TEMPLATES.find(t => t.id === templateId);+}++export function createConfigFromTemplate(+ template: BuildTemplate,+ name?: string+): BuildConfig {+ const configId = `${template.platform}-${Date.now()}`;+ const configName = name || template.name;++ const config: BuildConfig = {+ id: configId,+ name: configName,+ platform: template.platform,+ scenes: [],+ defines: [...template.defines],+ };++ if (template.platform === 'playable') {+ config.playableSettings = {+ startupScene: '',+ isDevelopment: template.playableSettings?.isDevelopment ?? true,+ minifyCode: template.playableSettings?.minifyCode ?? false,+ embedFonts: template.playableSettings?.embedFonts ?? true,+ outputPath: template.playableSettings?.outputPath ?? 'build/playable.html',+ };+ } else {+ config.wechatSettings = {+ appId: '',+ version: '1.0.0',+ bundleMode: template.wechatSettings?.bundleMode ?? 'subpackage',+ outputDir: template.wechatSettings?.outputDir ?? 'build/wechat',+ sdkPath: '',+ orientation: template.wechatSettings?.orientation ?? 'portrait',+ };+ }++ return config;+}++export function applyTemplateToConfig(+ config: BuildConfig,+ template: BuildTemplate+): BuildConfig {+ if (config.platform !== template.platform) {+ throw new Error('Template platform does not match config platform');+ }++ const updated = { ...config };+ updated.defines = [...template.defines];++ if (template.platform === 'playable' && template.playableSettings && updated.playableSettings) {+ updated.playableSettings = {+ ...updated.playableSettings,+ ...template.playableSettings,+ };+ } else if (template.platform === 'wechat' && template.wechatSettings && updated.wechatSettings) {+ updated.wechatSettings = {+ ...updated.wechatSettings,+ ...template.wechatSettings,+ };+ }++ return updated;+}++// =============================================================================+// Template Icon Mapping+// =============================================================================++export function getTemplateIconSvg(iconId: string): string {+ const icons: Record<string, string> = {+ facebook: `<svg viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>`,+ google: `<svg viewBox="0 0 24 24" fill="currentColor"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>`,+ bug: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M8 2l1.88 1.88M14.12 3.88L16 2M9 7.13v-1a3.003 3.003 0 116 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a6 6 0 0112 0v3c0 3.3-2.7 6-6 6z"/><path d="M12 20v-9M6.53 9C4.6 8.8 3 7.1 3 5M6 13H3M6 17l-3 1M17.47 9c1.93-.2 3.53-1.9 3.53-4M18 13h3M18 17l3 1"/></svg>`,+ package: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M16.5 9.4l-9-5.19M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/><path d="M3.27 6.96L12 12.01l8.73-5.05M12 22.08V12"/></svg>`,+ file: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><path d="M14 2v6h6M16 13H8M16 17H8M10 9H8"/></svg>`,+ monitor: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><path d="M8 21h8M12 17v4"/></svg>`,+ play: `<svg viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,+ box: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/><path d="M3.27 6.96L12 12.01l8.73-5.05M12 22.08V12"/></svg>`,+ };++ return icons[iconId] || icons['box'];+}diff --git a/editor/src/builder/PlayableBuilder.ts b/editor/src/builder/PlayableBuilder.tsindex 4e4a936e1..51e764f09 100644--- a/editor/src/builder/PlayableBuilder.ts+++ b/editor/src/builder/PlayableBuilder.ts@@ -12,6 +12,8 @@import * as esbuild from 'esbuild-wasm/esm/browser';import type { BuildResult, BuildContext } from './BuildService';+import { BuildProgressReporter } from './BuildProgress';+import { BuildCache, type BuildCacheData } from './BuildCache';// =============================================================================// Types@@ -143,6 +145,8 @@ export class PlayableBuilder {this.context_ = context;this.fs_ = (window as any).__esengine_fs ?? null;this.projectDir_ = getProjectDir(context.projectPath);+ this.progress_ = context.progress || new BuildProgressReporter();+ this.cache_ = context.cache || null;}// =========================================================================@@ -164,10 +168,18 @@ export class PlayableBuilder {return { success: false, error: 'No startup scene configured. Add a scene to the build or set a startup scene.' };}- console.log('[PlayableBuilder] Starting build...');+ this.progress_.setPhase('preparing');+ this.progress_.log('info', 'Starting Playable build...');try {+ // Check cache for compiled scripts+ let cachedData: BuildCacheData | null = null;+ if (this.cache_) {+ cachedData = await this.cache_.loadCache(this.context_.config.id);+ }+// 1. Load SDK+ this.progress_.setCurrentTask('Loading SDK...', 0);const wasmSdk = await this.loadSdk();if (!wasmSdk) {return {@@ -175,32 +187,58 @@ export class PlayableBuilder {error: "SDK not found. Please run 'scripts/build-web-single.bat' first.",};}- console.log(`[PlayableBuilder] SDK loaded: ${wasmSdk.length} bytes`);+ this.progress_.log('info', `SDK loaded: ${wasmSdk.length} bytes`);// 2. Compile user scripts- const gameCode = await this.compileUserScripts();- console.log(`[PlayableBuilder] Scripts compiled: ${gameCode.length} bytes`);+ this.progress_.setPhase('compiling');+ this.progress_.setCurrentTask('Compiling scripts...', 0);++ let gameCode: string;+ const scriptsPath = joinPath(this.projectDir_, 'assets/scripts');+ const scriptFiles = await this.getScriptFiles(scriptsPath);++ if (cachedData?.compiledScripts && this.cache_) {+ const changes = await this.cache_.getChangedFiles(scriptFiles, cachedData);+ if (!this.cache_.hasChanges(changes)) {+ gameCode = cachedData.compiledScripts;+ this.progress_.log('info', 'Using cached compiled scripts');+ } else {+ gameCode = await this.compileUserScripts();+ this.progress_.log('info', `Scripts compiled: ${gameCode.length} bytes`);+ }+ } else {+ gameCode = await this.compileUserScripts();+ this.progress_.log('info', `Scripts compiled: ${gameCode.length} bytes`);+ }// 3. Read startup scene+ this.progress_.setCurrentTask('Loading scene...', 50);const scenePath = this.resolveScenePath(startupScene);const sceneContent = await this.fs_.readFile(scenePath);if (!sceneContent) {return { success: false, error: `Startup scene not found: ${scenePath}` };}- console.log(`[PlayableBuilder] Scene loaded: ${scenePath}`);+ this.progress_.log('info', `Scene loaded: ${scenePath}`);// 4. Collect and inline assets+ this.progress_.setPhase('processing_assets');+ this.progress_.setCurrentTask('Collecting assets...', 0);const assets = await this.collectAssets();- console.log(`[PlayableBuilder] Collected ${assets.size} assets`);+ this.progress_.log('info', `Collected ${assets.size} assets`);+ this.progress_.setCurrentTask('Inlining assets...', 50);const gameCodeWithAssets = this.inlineAssets(gameCode, assets);const sceneDataWithAssets = this.inlineAssets(sceneContent, assets);// 5. Assemble HTML+ this.progress_.setPhase('assembling');+ this.progress_.setCurrentTask('Assembling HTML...', 0);const html = this.assembleHTML(wasmSdk, gameCodeWithAssets, sceneDataWithAssets);- console.log(`[PlayableBuilder] HTML assembled: ${html.length} bytes`);+ this.progress_.log('info', `HTML assembled: ${html.length} bytes`);// 6. Write output+ this.progress_.setPhase('writing');+ this.progress_.setCurrentTask('Writing output...', 0);const outputPath = this.resolveOutputPath(settings.outputPath);const outputDir = getDir(outputPath);@@ -208,17 +246,43 @@ export class PlayableBuilder {const success = await this.fs_.writeFile(outputPath, html);if (success) {- console.log(`[PlayableBuilder] Build successful: ${outputPath}`);- return { success: true, outputPath };+ // Save cache+ if (this.cache_) {+ const cacheData = await this.cache_.createCacheData(+ this.context_.config.id,+ scriptFiles,+ gameCode+ );+ await this.cache_.saveCache(cacheData);+ }++ this.progress_.log('info', `Build successful: ${outputPath}`);+ return {+ success: true,+ outputPath,+ outputSize: new TextEncoder().encode(html).length,+ };} else {return { success: false, error: 'Failed to write output file' };}} catch (err) {console.error('[PlayableBuilder] Build error:', err);+ this.progress_.fail(String(err));return { success: false, error: String(err) };}}+ private async getScriptFiles(scriptsPath: string): Promise<string[]> {+ if (!await this.fs_!.exists(scriptsPath)) {+ return [];+ }++ const entries = await this.fs_!.listDirectoryDetailed(scriptsPath);+ return entries+ .filter(e => !e.isDirectory && e.name.endsWith('.ts'))+ .map(e => joinPath(scriptsPath, e.name));+ }+// =========================================================================// Private Methods// =========================================================================@@ -479,4 +543,6 @@ ${imports}private context_: BuildContext;private fs_: NativeFS | null;private projectDir_: string;+ private progress_: BuildProgressReporter;+ private cache_: BuildCache | null;}diff --git a/editor/src/builder/WeChatBuilder.ts b/editor/src/builder/WeChatBuilder.tsindex 170d75826..d3a4862ec 100644--- a/editor/src/builder/WeChatBuilder.ts+++ b/editor/src/builder/WeChatBuilder.ts@@ -5,6 +5,8 @@import * as esbuild from 'esbuild-wasm/esm/browser';import type { BuildResult, BuildContext } from './BuildService';+import { BuildProgressReporter } from './BuildProgress';+import { BuildCache } from './BuildCache';// =============================================================================// Types@@ -59,11 +61,15 @@ export class WeChatBuilder {private context_: BuildContext;private fs_: NativeFS | null;private projectDir_: string;+ private progress_: BuildProgressReporter;+ private cache_: BuildCache | null;constructor(context: BuildContext) {this.context_ = context;this.fs_ = (window as any).__esengine_fs ?? null;this.projectDir_ = getProjectDir(context.projectPath);+ this.progress_ = context.progress || new BuildProgressReporter();+ this.cache_ = context.cache || null;}async build(): Promise<BuildResult> {@@ -76,7 +82,8 @@ export class WeChatBuilder {return { success: false, error: 'WeChat settings not configured' };}- console.log('[WeChatBuilder] Starting build...');+ this.progress_.setPhase('preparing');+ this.progress_.log('info', 'Starting WeChat MiniGame build...');try {const outputDir = joinPath(this.projectDir_, settings.outputDir);@@ -85,29 +92,41 @@ export class WeChatBuilder {await this.fs_.createDirectory(outputDir);// 1. Generate project.config.json+ this.progress_.setCurrentTask('Generating project.config.json...', 10);await this.generateProjectConfig(outputDir, settings);- console.log('[WeChatBuilder] Generated project.config.json');+ this.progress_.log('info', 'Generated project.config.json');// 2. Generate game.json+ this.progress_.setCurrentTask('Generating game.json...', 20);await this.generateGameJson(outputDir);- console.log('[WeChatBuilder] Generated game.json');+ this.progress_.log('info', 'Generated game.json');// 3. Compile and generate game.js+ this.progress_.setPhase('compiling');+ this.progress_.setCurrentTask('Compiling scripts...', 0);await this.generateGameJs(outputDir);- console.log('[WeChatBuilder] Generated game.js');+ this.progress_.log('info', 'Generated game.js');// 4. Copy scenes+ this.progress_.setPhase('processing_assets');+ this.progress_.setCurrentTask('Copying scenes...', 0);await this.copyScenes(outputDir);- console.log('[WeChatBuilder] Copied scenes');+ this.progress_.log('info', 'Copied scenes');// 5. Copy assets+ this.progress_.setCurrentTask('Copying assets...', 50);await this.copyAssets(outputDir);- console.log('[WeChatBuilder] Copied assets');+ this.progress_.log('info', 'Copied assets');- console.log(`[WeChatBuilder] Build successful: ${outputDir}`);+ // 6. Write output+ this.progress_.setPhase('writing');+ this.progress_.setCurrentTask('Finalizing...', 0);++ this.progress_.log('info', `Build successful: ${outputDir}`);return { success: true, outputPath: outputDir };} catch (err) {console.error('[WeChatBuilder] Build error:', err);+ this.progress_.fail(String(err));return { success: false, error: String(err) };}}diff --git a/editor/src/builder/index.ts b/editor/src/builder/index.tsindex 4a4932ad2..a1b0c42de 100644--- a/editor/src/builder/index.ts+++ b/editor/src/builder/index.ts@@ -4,6 +4,15 @@*/export { BuildSettingsDialog, showBuildSettingsDialog } from './BuildSettingsDialog';-export { BuildService, type BuildResult, type BuildContext } from './BuildService';+export { BuildService, type BuildResult, type BuildContext, type BuildOptions } from './BuildService';export { PlayableBuilder } from './PlayableBuilder';export { WeChatBuilder } from './WeChatBuilder';++export { BuildCache, type BuildCacheData, type FileHash, type FileChangeResult } from './BuildCache';+export { BuildProgressReporter, formatDuration, formatSize, type BuildProgress, type BuildLogEntry, type BuildPhase, type LogLevel } from './BuildProgress';+export { BuildConfigService, getBuildConfigService, initBuildConfigService, type BuildSettingsFile } from './BuildConfigService';+export { BuildPipeline, createTask, createPlayableTasks, type BuildTask, type TaskResult, type PipelineResult } from './BuildPipeline';+export { BuildConfigIO, downloadConfigsAsFile, uploadConfigsFromFile, type ExportedConfig, type ImportResult } from './BuildConfigIO';+export { BuildHistory, formatBuildTime, formatBuildDuration, getBuildStatusIcon, getBuildStatusClass, type BuildHistoryEntry, type BuildStatus } from './BuildHistory';+export { BUILD_TEMPLATES, getTemplates, getTemplatesByPlatform, getTemplate, createConfigFromTemplate, applyTemplateToConfig, getTemplateIconSvg, type BuildTemplate } from './BuildTemplates';+export { BatchBuilder, ParallelBatchBuilder, type BatchBuildResult, type ConfigBuildResult, type BatchBuildProgress } from './BatchBuilder';diff --git a/editor/src/styles/editor.css b/editor/src/styles/editor.cssindex e55c807c8..445d082d3 100644--- a/editor/src/styles/editor.css+++ b/editor/src/styles/editor.css@@ -3208,3 +3208,263 @@ svg {.es-output-success {color: var(--es-success);}++/* =============================================================================+ * Build Settings Dialog - Three Column Layout+ * ============================================================================= */++.es-build-dialog-wide {+ max-width: 1000px;+}++.es-build-body-three-col {+ display: flex;+ flex: 1;+ min-height: 450px;+ max-height: 65vh;+ overflow: hidden;+}++.es-build-body-three-col .es-build-sidebar {+ width: 180px;+ min-width: 160px;+}++.es-build-body-three-col .es-build-detail {+ flex: 1;+ min-width: 300px;+ border-right: 1px solid var(--es-border);+}++.es-build-body-three-col .es-build-output {+ width: 220px;+ min-width: 180px;+ flex-shrink: 0;+ display: flex;+ flex-direction: column;+ background: var(--es-bg-primary);+ padding: 12px;+ overflow-y: auto;+}++.es-build-toolbar-left,+.es-build-toolbar-right {+ display: flex;+ align-items: center;+ gap: 6px;+}++.es-build-toolbar-left {+ flex: 1;+}++.es-build-output-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 12px;+}++.es-build-output-latest {+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 4px;+ padding: 12px;+ margin-bottom: 16px;+}++.es-build-output-empty {+ text-align: center;+ color: var(--es-text-secondary);+ font-size: 12px;+ padding: 24px 8px;+ background: var(--es-bg-secondary);+ border: 1px solid var(--es-border);+ border-radius: 4px;+}++.es-build-output-stat {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 8px;+ font-size: 12px;+}++.es-build-output-stat:last-child {+ margin-bottom: 0;+}++.es-build-output-label {+ color: var(--es-text-secondary);+}++.es-build-output-value {+ color: var(--es-text-primary);+ font-weight: 500;+}++.es-build-output-actions {+ display: flex;+ gap: 8px;+ margin-top: 12px;+ padding-top: 12px;+ border-top: 1px solid var(--es-border);+}++.es-btn-small {+ padding: 4px 8px;+ font-size: 11px;+ display: flex;+ align-items: center;+ gap: 4px;+}++/* Build Status Indicators */+.es-build-status-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ flex-shrink: 0;+}++.es-build-status-dot.es-build-status-success {+ background: var(--es-success);+}++.es-build-status-dot.es-build-status-failed {+ background: var(--es-danger);+}++.es-build-status-dot.es-build-status-cancelled {+ background: var(--es-text-secondary);+}++.es-build-status-success {+ color: var(--es-success);+}++.es-build-status-failed {+ color: var(--es-danger);+}++.es-build-status-cancelled {+ color: var(--es-text-secondary);+}++/* Build History */+.es-build-history {+ margin-top: 8px;+}++.es-build-history-list {+ display: flex;+ flex-direction: column;+ gap: 4px;+ margin-top: 8px;+}++.es-build-history-item {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 8px;+ background: var(--es-bg-secondary);+ border-radius: 3px;+ font-size: 11px;+}++.es-build-history-icon {+ font-size: 12px;+}++.es-build-history-time {+ flex: 1;+ color: var(--es-text-primary);+}++.es-build-history-duration {+ color: var(--es-text-secondary);+}++/* Config Name Input */+.es-build-name-input {+ background: transparent;+ border: 1px solid transparent;+ color: var(--es-text-primary);+ font-size: 16px;+ font-weight: 600;+ padding: 4px 8px;+ border-radius: 3px;+ width: 200px;+}++.es-build-name-input:hover {+ background: var(--es-bg-tertiary);+}++.es-build-name-input:focus {+ outline: none;+ background: var(--es-bg-primary);+ border-color: var(--es-accent);+}++/* Collapse Count Badge */+.es-build-collapse-count {+ margin-left: auto;+ font-size: 10px;+ background: var(--es-bg-hover);+ color: var(--es-text-secondary);+ padding: 2px 6px;+ border-radius: 10px;+}++/* Build Templates */+.es-build-templates-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+ max-height: 400px;+ overflow-y: auto;+}++.es-build-template-item {+ padding: 12px;+ background: var(--es-bg-primary);+ border: 1px solid var(--es-border);+ border-radius: 4px;+ cursor: pointer;+ transition: all 0.15s;+}++.es-build-template-item:hover {+ border-color: var(--es-accent);+ background: var(--es-bg-tertiary);+}++.es-build-template-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 4px;+}++.es-build-template-name {+ font-size: 13px;+ font-weight: 500;+ color: var(--es-text-primary);+}++.es-build-template-platform {+ font-size: 10px;+ padding: 2px 6px;+ background: var(--es-bg-tertiary);+ color: var(--es-text-secondary);+ border-radius: 3px;+ text-transform: uppercase;+}++.es-build-template-desc {+ font-size: 11px;+ color: var(--es-text-secondary);+}diff --git a/editor/src/types/BuildTypes.ts b/editor/src/types/BuildTypes.tsindex f4283b860..3d41ffa0b 100644--- a/editor/src/types/BuildTypes.ts+++ b/editor/src/types/BuildTypes.ts@@ -8,6 +8,8 @@// =============================================================================export type BuildPlatform = 'playable' | 'wechat';+export type BuildStatus = 'success' | 'failed' | 'cancelled';+export type BuildPhase = 'preparing' | 'compiling' | 'processing_assets' | 'assembling' | 'writing' | 'completed' | 'failed';export interface PlatformInfo {id: BuildPlatform;@@ -70,6 +72,150 @@ export interface BuildSettings {configs: BuildConfig[];}+// =============================================================================+// Build Settings File (Project-level)+// =============================================================================++export interface BuildSettingsFile {+ version: '1.0';+ activePlatform: BuildPlatform;+ activeConfigId: string;+ configs: BuildConfig[];+}++// =============================================================================+// Build Cache Types+// =============================================================================++export interface FileHash {+ path: string;+ hash: string;+ lastModified: number;+ size: number;+}++export interface BuildCacheData {+ version: string;+ configId: string;+ timestamp: number;+ files: Record<string, FileHash>;+ compiledScripts?: string;+ compiledScriptsHash?: string;+}++export interface FileChangeResult {+ added: string[];+ modified: string[];+ removed: string[];+ unchanged: string[];+}++// =============================================================================+// Build Progress Types+// =============================================================================++export type LogLevel = 'info' | 'warn' | 'error' | 'debug';++export interface BuildLogEntry {+ timestamp: number;+ level: LogLevel;+ message: string;+ phase?: BuildPhase;+}++export interface BuildProgress {+ phase: BuildPhase;+ overallProgress: number;+ currentTask: string;+ currentTaskProgress: number;+ logs: BuildLogEntry[];+ startTime: number;+ estimatedTimeRemaining?: number;+}++// =============================================================================+// Build History Types+// =============================================================================++export interface BuildHistoryEntry {+ id: string;+ configId: string;+ configName: string;+ platform: string;+ timestamp: number;+ duration: number;+ status: BuildStatus;+ outputPath?: string;+ outputSize?: number;+ error?: string;+}++// =============================================================================+// Build Pipeline Types+// =============================================================================++export interface BuildTask {+ id: string;+ name: string;+ dependencies: string[];+ execute: () => Promise<void>;+ weight: number;+}++export interface TaskResult {+ id: string;+ success: boolean;+ error?: string;+ duration: number;+}++export interface PipelineResult {+ success: boolean;+ results: TaskResult[];+ totalDuration: number;+}++// =============================================================================+// Batch Build Types+// =============================================================================++export interface BatchBuildResult {+ success: boolean;+ results: ConfigBuildResult[];+ totalDuration: number;+ successCount: number;+ failureCount: number;+}++export interface ConfigBuildResult {+ configId: string;+ configName: string;+ result: BuildResult;+ duration: number;+}++export interface BuildResult {+ success: boolean;+ outputPath?: string;+ outputSize?: number;+ error?: string;+}++// =============================================================================+// Template Types+// =============================================================================++export interface BuildTemplate {+ id: string;+ name: string;+ description: string;+ platform: BuildPlatform;+ icon: string;+ defines: string[];+ playableSettings?: Partial<PlayableSettings>;+ wechatSettings?: Partial<WeChatSettings>;+}+// =============================================================================// Default Values// =============================================================================diff --git a/editor/src/types/globals.d.ts b/editor/src/types/globals.d.tsnew file mode 100644index 000000000..fa8a8d3f2--- /dev/null+++ b/editor/src/types/globals.d.ts@@ -0,0 +1,52 @@+/**+ * @file globals.d.ts+ * @brief Global type declarations for editor+ */++interface FileStat {+ size: number;+ mtimeMs: number;+ isDirectory: boolean;+ isFile: boolean;+}++interface DirectoryEntry {+ name: string;+ isDirectory: boolean;+}++interface OpenDialogOptions {+ title?: string;+ filters?: Array<{ name: string; extensions: string[] }>;+ properties?: string[];+}++interface NativeFileSystem {+ exists(path: string): Promise<boolean>;+ readFile(path: string): Promise<Uint8Array>;+ readBinaryFile(path: string): Promise<Uint8Array | null>;+ writeFile(path: string, content: Uint8Array | string): Promise<boolean>;+ writeBinaryFile(path: string, data: Uint8Array): Promise<boolean>;+ copyFile(src: string, dest: string): Promise<boolean>;+ unlink(path: string): Promise<void>;+ mkdir(path: string, options?: { recursive?: boolean }): Promise<void>;+ readdir(path: string): Promise<string[]>;+ stat(path: string): Promise<FileStat>;+ createDirectory(path: string): Promise<boolean>;+ listDirectoryDetailed(path: string): Promise<DirectoryEntry[]>;+ showOpenDialog(options: OpenDialogOptions): Promise<string[] | null>;+ openFolder(path: string): Promise<void>;+ openFile(path: string): Promise<void>;+ getEngineWxgameJs(): Promise<string>;+ getEngineWxgameWasm(): Promise<Uint8Array>;+ getSdkWechatJs(): Promise<string>;+}++interface EditorGlobals {+ currentScenePath?: string;+}++interface Window {+ __esengine_fs?: NativeFileSystem;+ __esengine_editor?: EditorGlobals;+}diff --git a/editor/src/utils/icons.ts b/editor/src/utils/icons.tsindex 1b515c9d2..07a3eb6cc 100644--- a/editor/src/utils/icons.ts+++ b/editor/src/utils/icons.ts@@ -45,6 +45,9 @@ import {Play,Square,Grid3X3,+ Upload,+ Download,+ LayoutTemplate,} from 'lucide';// =============================================================================@@ -141,6 +144,9 @@ export const icons = {stop: (size?: number) => renderIcon(Square as IconNode, size),grid: (size?: number) => renderIcon(Grid3X3 as IconNode, size),rect: (size?: number) => renderIcon(Square as IconNode, size),+ upload: (size?: number) => renderIcon(Upload as IconNode, size),+ download: (size?: number) => renderIcon(Download as IconNode, size),+ template: (size?: number) => renderIcon(LayoutTemplate as IconNode, size),};export type IconName = keyof typeof icons;