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: auto-install pre-packaged emsdk toolchain from GitHub Releases
esengineb6c2c4e78fb1
diff --git a/build-tools/toolchain/package-emsdk.js b/build-tools/toolchain/package-emsdk.jsnew file mode 100644index 000000000..c99c8fa7e--- /dev/null+++ b/build-tools/toolchain/package-emsdk.js@@ -0,0 +1,164 @@+#!/usr/bin/env node++/**+ * Packages a pre-activated emsdk into a distributable archive for the editor's+ * "Auto Install" feature. Run this on each target platform (or in CI) to+ * produce per-platform archives that are uploaded to GitHub Releases.+ *+ * Prerequisites:+ * 1. emsdk is cloned and activated:+ * git clone https://github.com/emscripten-core/emsdk.git+ * cd emsdk && ./emsdk install 5.0.0 && ./emsdk activate 5.0.0+ * 2. Node.js >= 18+ *+ * Usage:+ * node package-emsdk.js <emsdk-path> [--output <dir>]+ *+ * Output:+ * emsdk-<version>-<platform>.tar.gz (macOS/Linux)+ * emsdk-<version>-<platform>.zip (Windows)+ */++import fs from 'fs';+import path from 'path';+import os from 'os';+import { execSync } from 'child_process';++const EMSDK_VERSION = '5.0.0';++const KEEP_DIRS = [+ 'upstream/emscripten',+ 'upstream/bin',+ 'upstream/lib',+ 'python',+ 'node',+];++const KEEP_ROOT_FILES = [+ '.emscripten',+ 'emsdk',+ 'emsdk.bat',+ 'emsdk.ps1',+ 'emsdk_env.sh',+ 'emsdk_env.bat',+ 'emsdk_env.ps1',+ 'emsdk_env.fish',+ 'emsdk_manifest.json',+];++function getPlatform() {+ const p = os.platform();+ if (p === 'darwin') return 'mac';+ if (p === 'win32') return 'win';+ return 'linux';+}++function parseArgs() {+ const args = process.argv.slice(2);+ let emsdkPath = null;+ let outputDir = '.';++ for (let i = 0; i < args.length; i++) {+ if (args[i] === '--output' && args[i + 1]) {+ outputDir = args[++i];+ } else if (!args[i].startsWith('-')) {+ emsdkPath = args[i];+ }+ }++ if (!emsdkPath) {+ console.error('Usage: node package-emsdk.js <emsdk-path> [--output <dir>]');+ process.exit(1);+ }++ return { emsdkPath: path.resolve(emsdkPath), outputDir: path.resolve(outputDir) };+}++function log(msg) {+ console.log(`[package-emsdk] ${msg}`);+}++function main() {+ const { emsdkPath, outputDir } = parseArgs();++ if (!fs.existsSync(path.join(emsdkPath, 'upstream/emscripten'))) {+ console.error(`Invalid emsdk path: ${emsdkPath}`);+ process.exit(1);+ }++ const platform = getPlatform();+ const archiveName = `emsdk-${EMSDK_VERSION}-${platform}`;+ const isWindows = platform === 'win';++ fs.mkdirSync(outputDir, { recursive: true });++ if (isWindows) {+ const outFile = path.join(outputDir, `${archiveName}.zip`);+ log(`Creating ${outFile}...`);++ const includeArgs = KEEP_DIRS.map(d => `"${archiveName}/${d}/*"`).join(' ');+ const rootFileArgs = KEEP_ROOT_FILES+ .filter(f => fs.existsSync(path.join(emsdkPath, f)))+ .map(f => `"${archiveName}/${f}"`)+ .join(' ');++ // Create a temporary symlink/junction with the archive name+ const tmpLink = path.join(path.dirname(emsdkPath), archiveName);+ try {+ if (fs.existsSync(tmpLink)) fs.rmSync(tmpLink, { recursive: true });+ execSync(`mklink /J "${tmpLink}" "${emsdkPath}"`, { shell: 'cmd', stdio: 'pipe' });+ } catch {+ // Fallback: just use the directory name+ log('Warning: mklink failed, using xcopy fallback');+ }++ const cwd = path.dirname(emsdkPath);+ const srcDir = fs.existsSync(tmpLink) ? archiveName : path.basename(emsdkPath);++ execSync(+ `powershell -NoProfile -Command "Compress-Archive -Path '${srcDir}' -DestinationPath '${outFile}' -Force"`,+ { cwd, stdio: 'inherit' },+ );++ if (fs.existsSync(tmpLink) && tmpLink !== emsdkPath) {+ execSync(`rmdir "${tmpLink}"`, { shell: 'cmd', stdio: 'pipe' });+ }++ log(`Done: ${outFile}`);+ } else {+ const outFile = path.join(outputDir, `${archiveName}.tar.gz`);+ log(`Creating ${outFile}...`);++ const includePaths = [+ ...KEEP_DIRS.map(d => `${archiveName}/${d}`),+ ...KEEP_ROOT_FILES+ .filter(f => fs.existsSync(path.join(emsdkPath, f)))+ .map(f => `${archiveName}/${f}`),+ ];++ // Create a symlink so the archive has the right top-level dir name+ const tmpLink = path.join(path.dirname(emsdkPath), archiveName);+ let srcDir = archiveName;+ try {+ if (fs.existsSync(tmpLink)) fs.rmSync(tmpLink, { recursive: true, force: true });+ fs.symlinkSync(emsdkPath, tmpLink);+ } catch {+ srcDir = path.basename(emsdkPath);+ }++ const cwd = path.dirname(emsdkPath);+ execSync(+ `tar czf "${outFile}" ${includePaths.join(' ')}`,+ { cwd, stdio: 'inherit' },+ );++ if (fs.existsSync(tmpLink) && tmpLink !== emsdkPath) {+ fs.rmSync(tmpLink, { recursive: true, force: true });+ }++ const stat = fs.statSync(outFile);+ log(`Done: ${outFile} (${(stat.size / 1024 / 1024).toFixed(1)} MB)`);+ }+}++main();diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lockindex 106582757..ec0f572a2 100644--- a/desktop/src-tauri/Cargo.lock+++ b/desktop/src-tauri/Cargo.lock@@ -392,6 +392,16 @@ dependencies = ["version_check",]+[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]+[[package]]name = "core-foundation"version = "0.10.1"@@ -415,9 +425,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1"dependencies = ["bitflags 2.10.0",- "core-foundation",+ "core-foundation 0.10.1","core-graphics-types",- "foreign-types",+ "foreign-types 0.5.0","libc",]@@ -428,7 +438,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"dependencies = ["bitflags 2.10.0",- "core-foundation",+ "core-foundation 0.10.1","libc",]@@ -782,9 +792,13 @@ dependencies = [name = "esengine-editor"version = "0.1.0"dependencies = [+ "flate2",+ "futures-util","open",+ "reqwest 0.12.28","serde","serde_json",+ "tar","tauri","tauri-build","tauri-plugin-dialog",@@ -866,6 +880,15 @@ version = "1.0.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"+[[package]]+name = "foreign-types"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"+dependencies = [+ "foreign-types-shared 0.1.1",+]+[[package]]name = "foreign-types"version = "0.5.0"@@ -873,7 +896,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"dependencies = ["foreign-types-macros",- "foreign-types-shared",+ "foreign-types-shared 0.3.1",][[package]]@@ -887,6 +910,12 @@ dependencies = ["syn 2.0.114",]+[[package]]+name = "foreign-types-shared"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"+[[package]]name = "foreign-types-shared"version = "0.3.1"@@ -1295,6 +1324,25 @@ dependencies = ["syn 2.0.114",]+[[package]]+name = "h2"+version = "0.4.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"+dependencies = [+ "atomic-waker",+ "bytes",+ "fnv",+ "futures-core",+ "futures-sink",+ "http",+ "indexmap 2.13.0",+ "slab",+ "tokio",+ "tokio-util",+ "tracing",+]+[[package]]name = "hashbrown"version = "0.12.3"@@ -1407,6 +1455,7 @@ dependencies = ["bytes","futures-channel","futures-core",+ "h2","http","http-body","httparse",@@ -1434,6 +1483,22 @@ dependencies = ["tower-service",]+[[package]]+name = "hyper-tls"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"+dependencies = [+ "bytes",+ "http-body-util",+ "hyper",+ "hyper-util",+ "native-tls",+ "tokio",+ "tokio-native-tls",+ "tower-service",+]+[[package]]name = "hyper-util"version = "0.1.20"@@ -1452,9 +1517,11 @@ dependencies = ["percent-encoding","pin-project-lite","socket2",+ "system-configuration","tokio","tower-service","tracing",+ "windows-registry",][[package]]@@ -2043,6 +2110,23 @@ dependencies = ["windows-sys 0.60.2",]+[[package]]+name = "native-tls"+version = "0.2.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"+dependencies = [+ "libc",+ "log",+ "openssl",+ "openssl-probe",+ "openssl-sys",+ "schannel",+ "security-framework",+ "security-framework-sys",+ "tempfile",+]+[[package]]name = "ndk"version = "0.9.0"@@ -2405,12 +2489,50 @@ dependencies = ["pathdiff",]+[[package]]+name = "openssl"+version = "0.10.75"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328"+dependencies = [+ "bitflags 2.10.0",+ "cfg-if",+ "foreign-types 0.3.2",+ "libc",+ "once_cell",+ "openssl-macros",+ "openssl-sys",+]++[[package]]+name = "openssl-macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "openssl-probe"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"+[[package]]+name = "openssl-sys"+version = "0.9.111"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321"+dependencies = [+ "cc",+ "libc",+ "pkg-config",+ "vcpkg",+]+[[package]]name = "option-ext"version = "0.2.0"@@ -2976,6 +3098,49 @@ version = "0.8.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c"+[[package]]+name = "reqwest"+version = "0.12.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "encoding_rs",+ "futures-core",+ "futures-util",+ "h2",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-tls",+ "hyper-util",+ "js-sys",+ "log",+ "mime",+ "native-tls",+ "percent-encoding",+ "pin-project-lite",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tokio-native-tls",+ "tokio-util",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wasm-streams",+ "web-sys",+]+[[package]]name = "reqwest"version = "0.13.1"@@ -3116,7 +3281,7 @@ version = "0.6.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784"dependencies = [- "core-foundation",+ "core-foundation 0.10.1","core-foundation-sys","jni","log",@@ -3154,6 +3319,12 @@ version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"+[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"+[[package]]name = "same-file"version = "1.0.6"@@ -3236,7 +3407,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b3297343eaf830f66ede390ea39da1d462b6b0c1b000f420d0a83f898bbbe6ef"dependencies = ["bitflags 2.10.0",- "core-foundation",+ "core-foundation 0.10.1","core-foundation-sys","libc","security-framework-sys",@@ -3375,6 +3546,18 @@ dependencies = ["serde_core",]+[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]+[[package]]name = "serde_with"version = "3.16.1"@@ -3692,6 +3875,27 @@ dependencies = ["syn 2.0.114",]+[[package]]+name = "system-configuration"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"+dependencies = [+ "bitflags 2.10.0",+ "core-foundation 0.9.4",+ "system-configuration-sys",+]++[[package]]+name = "system-configuration-sys"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"+dependencies = [+ "core-foundation-sys",+ "libc",+]+[[package]]name = "system-deps"version = "6.2.2"@@ -3713,7 +3917,7 @@ checksum = "f3a753bdc39c07b192151523a3f77cd0394aa75413802c883a0f6f6a0e5ee2e7"dependencies = ["bitflags 2.10.0","block2",- "core-foundation",+ "core-foundation 0.10.1","core-graphics","crossbeam-channel","dispatch",@@ -3804,7 +4008,7 @@ dependencies = ["percent-encoding","plist","raw-window-handle",- "reqwest",+ "reqwest 0.13.1","serde","serde_json","serde_repr",@@ -3994,7 +4198,7 @@ dependencies = ["minisign-verify","osakit","percent-encoding",- "reqwest",+ "reqwest 0.13.1","rustls","semver","serde",@@ -4256,6 +4460,16 @@ dependencies = ["syn 2.0.114",]+[[package]]+name = "tokio-native-tls"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"+dependencies = [+ "native-tls",+ "tokio",+]+[[package]]name = "tokio-rustls"version = "0.26.4"@@ -4593,6 +4807,12 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "vcpkg"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"+[[package]]name = "version-compare"version = "0.2.1"@@ -4985,6 +5205,17 @@ dependencies = ["windows-link 0.1.3",]+[[package]]+name = "windows-registry"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"+dependencies = [+ "windows-link 0.2.1",+ "windows-result 0.4.1",+ "windows-strings 0.5.1",+]+[[package]]name = "windows-result"version = "0.3.4"diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.tomlindex 55f084904..56fd2060d 100644--- a/desktop/src-tauri/Cargo.toml+++ b/desktop/src-tauri/Cargo.toml@@ -27,6 +27,10 @@ open = "5"urlencoding = "2"zip = "2"url = "2"+reqwest = { version = "0.12", features = ["stream"] }+futures-util = "0.3"+flate2 = "1"+tar = "0.4"[profile.release]panic = "abort"diff --git a/desktop/src-tauri/src/compiler.rs b/desktop/src-tauri/src/compiler.rsindex 831876266..8a4288f41 100644--- a/desktop/src-tauri/src/compiler.rs+++ b/desktop/src-tauri/src/compiler.rs@@ -1,5 +1,6 @@//! Toolchain management and WASM compilation.+use futures_util::StreamExt;use serde::{Deserialize, Serialize};use std::collections::HashMap;use std::path::{Path, PathBuf};@@ -104,12 +105,26 @@ pub struct CompileResult {}const EMSDK_VERSION: &str = "5.0.0";-const EMSDK_GIT_URL: &str = "https://github.com/emscripten-core/emsdk.git";+const EMSDK_DOWNLOAD_BASE: &str = "https://github.com/esengine/emsdk-releases/releases/download";const MIN_EMSCRIPTEN_VERSION: &str = "5.0.0";const MIN_CMAKE_VERSION: &str = "3.16";const MIN_PYTHON_VERSION: &str = "3.0";+fn toolchain_archive_url() -> String {+ let (os, ext) = if cfg!(target_os = "windows") {+ ("win", "zip")+ } else if cfg!(target_os = "macos") {+ ("mac", "tar.gz")+ } else {+ ("linux", "tar.gz")+ };+ format!(+ "{}/v{}/emsdk-{}-{}.{}",+ EMSDK_DOWNLOAD_BASE, EMSDK_VERSION, EMSDK_VERSION, os, ext+ )+}+fn version_ge(actual: &str, required: &str) -> bool {let parse = |s: &str| -> Vec<u32> {s.split('.')@@ -287,8 +302,12 @@ fn find_emsdk_python(emsdk_path: &Path) -> Option<(PathBuf, String)> {}let entries = std::fs::read_dir(&python_dir).ok()?;for entry in entries.flatten() {- let bin_name = if cfg!(windows) { "python.exe" } else { "python3" };- let python_bin = entry.path().join("bin").join(bin_name);+ let python_bin = if cfg!(windows) {+ // Windows: <emsdk>/python/<version>/python.exe (no bin subdirectory)+ entry.path().join("python.exe")+ } else {+ entry.path().join("bin").join("python3")+ };if python_bin.exists() {let output = std::process::Command::new(&python_bin).arg("--version")@@ -473,60 +492,35 @@ pub fn set_emsdk_path(app: AppHandle, path: String) -> Result<ToolchainStatus, Spub async fn install_emsdk(app: AppHandle) -> Result<ToolchainStatus, String> {let install_dir = default_emsdk_install_path(&app);let install_dir_str = install_dir.to_string_lossy().to_string();+ let url = toolchain_archive_url();+ let is_zip = url.ends_with(".zip");++ emit_progress(&app, "download", "Downloading toolchain...", 0.05);- emit_progress(&app, "download", "Cloning emsdk...", 0.1);+ // Download archive with progress+ let archive_data = download_with_progress(&app, &url).await?;- // Clone emsdk+ // Clean previous installif install_dir.exists() {std::fs::remove_dir_all(&install_dir).map_err(|e| e.to_string())?;}+ std::fs::create_dir_all(&install_dir).map_err(|e| e.to_string())?;- run_command_streamed(- &app,- "git",- &[- "clone".to_string(),- "--depth".to_string(),- "1".to_string(),- EMSDK_GIT_URL.to_string(),- install_dir_str.clone(),- ],- &std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),- &HashMap::new(),- )- .await?;-- // Install + activate- emit_progress(&app, "install", "Installing Emscripten...", 0.3);+ emit_progress(&app, "extract", "Extracting toolchain...", 0.7);- let emsdk_bin = if cfg!(windows) {- install_dir.join("emsdk.bat")- } else {- install_dir.join("emsdk")- };- let emsdk_str = emsdk_bin.to_string_lossy().to_string();-- run_command_streamed(- &app,- &emsdk_str,- &["install".to_string(), EMSDK_VERSION.to_string()],- &install_dir,- &HashMap::new(),- )- .await?;-- emit_progress(&app, "activate", "Activating Emscripten...", 0.7);-- run_command_streamed(- &app,- &emsdk_str,- &["activate".to_string(), EMSDK_VERSION.to_string()],- &install_dir,- &HashMap::new(),- )- .await?;+ // Extract archive+ let target = install_dir.clone();+ tokio::task::spawn_blocking(move || {+ if is_zip {+ extract_zip(&archive_data, &target)+ } else {+ extract_tar_gz(&archive_data, &target)+ }+ })+ .await+ .map_err(|e| format!("Extract task failed: {}", e))??;- emit_progress(&app, "complete", "emsdk installed!", 1.0);+ emit_progress(&app, "complete", "Toolchain installed!", 1.0);// Save pathlet mut config = load_config(&app);@@ -536,6 +530,130 @@ pub async fn install_emsdk(app: AppHandle) -> Result<ToolchainStatus, String> {Ok(get_toolchain_status(app))}+async fn download_with_progress(app: &AppHandle, url: &str) -> Result<Vec<u8>, String> {+ let response = reqwest::get(url)+ .await+ .map_err(|e| format!("Download failed: {}", e))?;++ if !response.status().is_success() {+ return Err(format!("Download failed: HTTP {}", response.status()));+ }++ let total_size = response.content_length().unwrap_or(0);+ let mut downloaded: u64 = 0;+ let mut data = Vec::with_capacity(total_size as usize);+ let mut stream = response.bytes_stream();++ while let Some(chunk) = stream.next().await {+ let chunk = chunk.map_err(|e| format!("Download interrupted: {}", e))?;+ data.extend_from_slice(&chunk);+ downloaded += chunk.len() as u64;++ if total_size > 0 {+ let pct = (downloaded as f32 / total_size as f32).min(0.65);+ let size_mb = downloaded as f32 / 1_048_576.0;+ let total_mb = total_size as f32 / 1_048_576.0;+ emit_progress(+ app,+ "download",+ &format!("Downloading toolchain... {:.0}/{:.0} MB", size_mb, total_mb),+ 0.05 + pct,+ );+ }+ }++ Ok(data)+}++fn extract_zip(data: &[u8], target: &Path) -> Result<(), String> {+ let cursor = std::io::Cursor::new(data);+ let mut archive = zip::ZipArchive::new(cursor).map_err(|e| format!("Invalid zip: {}", e))?;++ for i in 0..archive.len() {+ let mut file = archive.by_index(i).map_err(|e| e.to_string())?;+ let name = file.name().to_string();++ // Strip the top-level directory (e.g., "emsdk-5.0.0-win/")+ let relative = strip_top_dir(&name);+ if relative.is_empty() {+ continue;+ }++ let out_path = target.join(relative);++ if file.is_dir() {+ std::fs::create_dir_all(&out_path).map_err(|e| e.to_string())?;+ } else {+ if let Some(parent) = out_path.parent() {+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;+ }+ let mut out = std::fs::File::create(&out_path).map_err(|e| e.to_string())?;+ std::io::copy(&mut file, &mut out).map_err(|e| e.to_string())?;++ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if let Some(mode) = file.unix_mode() {+ std::fs::set_permissions(&out_path, std::fs::Permissions::from_mode(mode))+ .ok();+ }+ }+ }+ }+ Ok(())+}++fn extract_tar_gz(data: &[u8], target: &Path) -> Result<(), String> {+ let cursor = std::io::Cursor::new(data);+ let gz = flate2::read::GzDecoder::new(cursor);+ let mut archive = tar::Archive::new(gz);++ // Unpack stripping the top-level directory+ for entry in archive.entries().map_err(|e| e.to_string())? {+ let mut entry = entry.map_err(|e| e.to_string())?;+ let path = entry.path().map_err(|e| e.to_string())?.into_owned();+ let path_str = path.to_string_lossy().to_string();++ let relative = strip_top_dir(&path_str);+ if relative.is_empty() {+ continue;+ }++ let out_path = target.join(relative);++ if entry.header().entry_type().is_dir() {+ std::fs::create_dir_all(&out_path).map_err(|e| e.to_string())?;+ } else {+ if let Some(parent) = out_path.parent() {+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;+ }+ let mut out = std::fs::File::create(&out_path).map_err(|e| e.to_string())?;+ std::io::copy(&mut entry, &mut out).map_err(|e| e.to_string())?;++ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ if let Some(mode) = entry.header().mode().ok() {+ std::fs::set_permissions(+ &out_path,+ std::fs::Permissions::from_mode(mode),+ )+ .ok();+ }+ }+ }+ }+ Ok(())+}++fn strip_top_dir(path: &str) -> &str {+ // "emsdk-5.0.0-mac/upstream/emscripten/emcc" → "upstream/emscripten/emcc"+ match path.find('/') {+ Some(idx) => &path[idx + 1..],+ None => "",+ }+}+#[tauri::command]pub async fn compile_wasm(app: AppHandle,diff --git a/editor/src/builder/BuildSettingsDialog.ts b/editor/src/builder/BuildSettingsDialog.tsindex 2ef09433c..0a75f0205 100644--- a/editor/src/builder/BuildSettingsDialog.ts+++ b/editor/src/builder/BuildSettingsDialog.ts@@ -669,7 +669,7 @@ export class BuildSettingsDialog {${icons.folder(12)} Select emsdk</button><button class="es-btn" data-action="install-emsdk">- ${icons.download(12)} Install emsdk+ ${icons.download(12)} Auto Install</button></div></div>@@ -1154,16 +1154,26 @@ export class BuildSettingsDialog {}private async handleInstallEmsdk(): Promise<void> {- const toastId = showProgressToast('Installing emsdk...');+ const toastId = showProgressToast('Downloading toolchain...');+ let unlisten: (() => void) | undefined;try {const { invoke } = await import('@tauri-apps/api/core');+ const { listen } = await import('@tauri-apps/api/event');+ unlisten = await listen<{ stage: string; message: string; progress: number }>('compile-progress', (event) => {+ updateToast(toastId, {+ message: event.payload.message,+ progress: event.payload.progress,+ });+ });await invoke('install_emsdk');dismissToast(toastId);- showSuccessToast('emsdk installed');+ showSuccessToast('Toolchain installed');await this.checkToolchainStatus();} catch (err: any) {dismissToast(toastId);showErrorToast(`Install failed: ${err}`);+ } finally {+ unlisten?.();}}