Files
Zebratic dcdb3069a8 fix: increase build timeouts (120s→300s) and improve error messages
- npm install: 120s → 300s (cold cache can be slow)
- expo prebuild: 120s → 300s
- Better error reporting when steps fail
2026-03-17 00:13:26 +00:00

501 lines
20 KiB
JavaScript

const express = require("express");
const { execSync, exec } = require("child_process");
const fs = require("fs");
const path = require("path");
const JSZip = require("jszip");
const crypto = require("crypto");
const app = express();
app.use(express.json({ limit: "50mb" }));
// Logging helper
function log(buildId, level, message, extra) {
const ts = new Date().toISOString();
const prefix = buildId ? `[${ts}] [${level.toUpperCase()}] [${buildId}]` : `[${ts}] [${level.toUpperCase()}]`;
const line = extra ? `${prefix} ${message} ${JSON.stringify(extra)}` : `${prefix} ${message}`;
console.log(line);
}
const BUILDS_DIR = "/app/builds";
const PROJECTS_DIR = "/app/projects";
// Ensure dirs exist
fs.mkdirSync(BUILDS_DIR, { recursive: true });
fs.mkdirSync(PROJECTS_DIR, { recursive: true });
// Track active builds and queue
const MAX_CONCURRENT = 3;
const activeBuildIds = new Set();
const buildQueue = [];
function processQueue() {
while (buildQueue.length > 0 && activeBuildIds.size < MAX_CONCURRENT) {
const next = buildQueue.shift();
runBuild(next);
}
}
// Health check
app.get("/health", (req, res) => {
res.json({ status: "ok", activeBuilds: activeBuildIds.size, queuedBuilds: buildQueue.length });
});
// Build APK
app.post("/build", async (req, res) => {
const { buildId, files, appName, packageName, version } = req.body;
if (!buildId || !files) {
return res.status(400).json({ error: "buildId and files required" });
}
const buildJob = { buildId, files, appName, packageName, version };
if (activeBuildIds.size >= MAX_CONCURRENT) {
// Queue it
buildQueue.push(buildJob);
const statusFile = path.join(BUILDS_DIR, `${buildId}.status.json`);
log(buildId, "info", "Build queued", { position: buildQueue.length, activeBuilds: activeBuildIds.size });
updateStatus(statusFile, "queued", "Waiting in queue...", { position: buildQueue.length });
return res.json({ status: "queued", buildId });
}
// Start immediately
res.json({ status: "building", buildId });
runBuild(buildJob);
});
async function runBuild({ buildId, files, appName, packageName, version }) {
activeBuildIds.add(buildId);
log(buildId, "info", "Build started", { files: Object.keys(files).length, appName, packageName });
const projectDir = path.join(PROJECTS_DIR, buildId);
const statusFile = path.join(BUILDS_DIR, `${buildId}.status.json`);
try {
log(buildId, "info", "Setting up project directory");
updateStatus(statusFile, "building", "Setting up project...", { progress: 5 });
// Clean up any previous attempt
if (fs.existsSync(projectDir)) {
fs.rmSync(projectDir, { recursive: true });
}
fs.mkdirSync(projectDir, { recursive: true });
// ── Template-based build: start from golden template, merge LLM additions ──
const TEMPLATE_DIR = path.join(__dirname, "template");
const CONFIG_FILES = ["package.json", "app.json", "babel.config.js", "tsconfig.json"];
// 1. Copy template files as the base
for (const cf of CONFIG_FILES) {
const src = path.join(TEMPLATE_DIR, cf);
const dst = path.join(projectDir, cf);
if (fs.existsSync(src)) {
fs.copyFileSync(src, dst);
}
}
// 2. Parse LLM-generated package.json for extra deps (if any)
const pkgPath = path.join(projectDir, "package.json");
const templatePkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
const coreDeps = new Set(Object.keys(templatePkg.dependencies));
const coreDevDeps = new Set(Object.keys(templatePkg.devDependencies || {}));
if (files["package.json"]) {
try {
const llmPkg = JSON.parse(files["package.json"]);
// Add extra deps that aren't in the template (never override core)
for (const [dep, ver] of Object.entries(llmPkg.dependencies || {})) {
if (!coreDeps.has(dep)) {
templatePkg.dependencies[dep] = ver;
}
}
for (const [dep, ver] of Object.entries(llmPkg.devDependencies || {})) {
if (!coreDevDeps.has(dep)) {
templatePkg.devDependencies[dep] = ver;
}
}
} catch (e) {
log(buildId, "warn", "Could not parse LLM package.json, using template only");
}
}
// Update package name
templatePkg.name = (packageName || "apk-forge-app").replace(/[^a-z0-9-]/g, "-");
fs.writeFileSync(pkgPath, JSON.stringify(templatePkg, null, 2));
// 3. Merge app.json — take name/slug/colors from LLM, keep template structure
const appJsonPath = path.join(projectDir, "app.json");
const templateAppJson = JSON.parse(fs.readFileSync(appJsonPath, "utf-8"));
if (files["app.json"]) {
try {
const llmAppJson = JSON.parse(files["app.json"]);
const llmExpo = llmAppJson.expo || {};
// Merge cosmetic fields from LLM
if (llmExpo.name) templateAppJson.expo.name = llmExpo.name;
if (llmExpo.slug) templateAppJson.expo.slug = llmExpo.slug;
if (llmExpo.icon) templateAppJson.expo.icon = llmExpo.icon;
if (llmExpo.splash?.backgroundColor) templateAppJson.expo.splash.backgroundColor = llmExpo.splash.backgroundColor;
if (llmExpo.android?.adaptiveIcon?.backgroundColor) {
templateAppJson.expo.android.adaptiveIcon.backgroundColor = llmExpo.android.adaptiveIcon.backgroundColor;
}
if (llmExpo.android?.package) templateAppJson.expo.android.package = llmExpo.android.package;
// Merge extra plugins from LLM
if (llmExpo.plugins) {
const existingPlugins = new Set(templateAppJson.expo.plugins.map(p => typeof p === "string" ? p : p[0]));
for (const plugin of llmExpo.plugins) {
const pluginName = typeof plugin === "string" ? plugin : plugin[0];
if (!existingPlugins.has(pluginName)) {
templateAppJson.expo.plugins.push(plugin);
}
}
}
} catch (e) {
log(buildId, "warn", "Could not parse LLM app.json, using template only");
}
}
// Apply defaults
const safeName = (appName || templateAppJson.expo.name || "APK Forge App").replace(/[^a-zA-Z0-9 ]/g, "");
const safeSlug = safeName.toLowerCase().replace(/\s+/g, "-");
templateAppJson.expo.name = safeName;
if (!templateAppJson.expo.slug || templateAppJson.expo.slug === "my-app") templateAppJson.expo.slug = safeSlug;
if (!templateAppJson.expo.android.package) {
templateAppJson.expo.android.package = packageName || `com.apkforge.${safeSlug.replace(/-/g, "")}`;
}
fs.writeFileSync(appJsonPath, JSON.stringify(templateAppJson, null, 2));
// 4. Write only LLM-generated source files (skip config files handled by template)
const skipFiles = new Set(CONFIG_FILES);
for (const [filePath, content] of Object.entries(files)) {
if (skipFiles.has(filePath)) continue;
const fullPath = path.join(projectDir, filePath);
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
fs.writeFileSync(fullPath, content);
}
// Create placeholder assets if missing
const assetsDir = path.join(projectDir, "assets");
fs.mkdirSync(assetsDir, { recursive: true });
const placeholderPng = createPlaceholderPng();
// Replace ALL invalid PNG files in assets (LLM generates text placeholders like "<binary placeholder>")
const requiredAssets = ["icon.png", "splash-icon.png", "splash.png", "adaptive-icon.png", "favicon.png"];
for (const name of requiredAssets) {
const p = path.join(assetsDir, name);
const isPng = fs.existsSync(p) && fs.readFileSync(p).slice(0, 4).toString("hex") === "89504e47";
if (!isPng) {
fs.writeFileSync(p, placeholderPng);
}
}
// Also fix any other .png files in assets that aren't valid PNGs
if (fs.existsSync(assetsDir)) {
for (const file of fs.readdirSync(assetsDir)) {
if (file.endsWith(".png")) {
const p = path.join(assetsDir, file);
const isPng = fs.readFileSync(p).slice(0, 4).toString("hex") === "89504e47";
if (!isPng) {
fs.writeFileSync(p, placeholderPng);
}
}
}
}
// Ensure babel.config.js
const babelPath = path.join(projectDir, "babel.config.js");
if (!fs.existsSync(babelPath)) {
fs.writeFileSync(babelPath, `module.exports = function (api) {
api.cache(true);
return { presets: ['babel-preset-expo'] };
};\n`);
}
// Ensure tsconfig.json
const tsconfigPath = path.join(projectDir, "tsconfig.json");
if (!fs.existsSync(tsconfigPath)) {
fs.writeFileSync(tsconfigPath, JSON.stringify({
extends: "expo/tsconfig.base",
compilerOptions: { strict: true }
}, null, 2));
}
log(buildId, "info", "Installing dependencies (npm install --legacy-peer-deps)");
updateStatus(statusFile, "building", "Installing dependencies...", { progress: 20 });
try {
execSync("npm install --legacy-peer-deps", { cwd: projectDir, stdio: "pipe", timeout: 300000 });
} catch (npmErr) {
const stderr = npmErr.stderr ? npmErr.stderr.toString().slice(-300) : "";
log(buildId, "error", "npm install failed", { stderr: stderr.slice(-200), message: npmErr.message });
throw new Error(`npm install failed: ${npmErr.message.includes("ETIMEDOUT") ? "Timed out after 5 minutes" : stderr || npmErr.message}`);
}
log(buildId, "info", "Dependencies installed successfully");
// Ensure app.json has android.package
if (fs.existsSync(appJsonPath)) {
const appJson = JSON.parse(fs.readFileSync(appJsonPath, "utf-8"));
if (!appJson.expo) appJson.expo = {};
if (!appJson.expo.android) appJson.expo.android = {};
if (!appJson.expo.android.package) {
const safeName = (appJson.expo.name || appJson.expo.slug || "myapp")
.toLowerCase().replace(/[^a-z0-9]/g, "");
appJson.expo.android.package = `com.apkforge.${safeName}`;
}
if (!appJson.expo.slug) {
appJson.expo.slug = (appJson.expo.name || "myapp").toLowerCase().replace(/[^a-z0-9-]/g, "-");
}
// Ensure splash screen config (prevents missing resource errors)
if (!appJson.expo.splash) appJson.expo.splash = {};
if (!appJson.expo.splash.backgroundColor) appJson.expo.splash.backgroundColor = "#1a1a2e";
if (!appJson.expo.splash.image) appJson.expo.splash.image = "./assets/splash-icon.png";
if (!appJson.expo.splash.resizeMode) appJson.expo.splash.resizeMode = "contain";
// Ensure adaptive icon
if (!appJson.expo.android.adaptiveIcon) appJson.expo.android.adaptiveIcon = {};
if (!appJson.expo.android.adaptiveIcon.backgroundColor) appJson.expo.android.adaptiveIcon.backgroundColor = "#1a1a2e";
if (!appJson.expo.android.adaptiveIcon.foregroundImage) appJson.expo.android.adaptiveIcon.foregroundImage = "./assets/adaptive-icon.png";
// Ensure icon
if (!appJson.expo.icon) appJson.expo.icon = "./assets/icon.png";
fs.writeFileSync(appJsonPath, JSON.stringify(appJson, null, 2));
}
log(buildId, "info", "Running expo prebuild --platform android");
updateStatus(statusFile, "building", "Generating native project...", { progress: 45 });
try {
execSync("npx expo prebuild --platform android --no-install", {
cwd: projectDir,
stdio: "pipe", maxBuffer: 50 * 1024 * 1024,
timeout: 300000,
env: { ...process.env, CI: "1", EXPO_NO_TELEMETRY: "1" }
});
} catch (prebuildErr) {
const stderr = prebuildErr.stderr ? prebuildErr.stderr.toString().slice(-500) : "";
const stdout = prebuildErr.stdout ? prebuildErr.stdout.toString().slice(-500) : "";
log(buildId, "error", "Expo prebuild failed", { stderr: stderr.slice(-200), stdout: stdout.slice(-200) });
throw new Error(`Expo prebuild failed: ${stderr || stdout || prebuildErr.message}`);
}
// Verify android directory was created
const androidDir = path.join(projectDir, "android");
if (!fs.existsSync(androidDir)) {
log(buildId, "error", "Expo prebuild did not generate android directory");
throw new Error("Expo prebuild did not generate android directory");
}
// Fix Kotlin/Compose version compatibility
const gradlePropsPath = path.join(androidDir, "gradle.properties");
let gradleProps = fs.existsSync(gradlePropsPath) ? fs.readFileSync(gradlePropsPath, "utf-8") : "";
if (!gradleProps.includes("suppressKotlinVersionCompatibilityCheck")) {
log(buildId, "info", "Adding Kotlin version compatibility suppression");
gradleProps += "\nkotlin.suppressKotlinVersionCompatibilityCheck=true\n";
fs.writeFileSync(gradlePropsPath, gradleProps);
}
// Also patch android/build.gradle to add compose compiler suppression
const rootBuildGradle = path.join(androidDir, "build.gradle");
if (fs.existsSync(rootBuildGradle)) {
let buildGradle = fs.readFileSync(rootBuildGradle, "utf-8");
if (!buildGradle.includes("suppressKotlinVersionCompatibilityCheck")) {
// Add subprojects block to suppress Kotlin version check in all modules
buildGradle += `
subprojects {
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
kotlinOptions {
freeCompilerArgs += ["-P", "plugin:androidx.compose.compiler.plugins.kotlin:suppressKotlinVersionCompatibilityCheck=true"]
}
}
}
`;
fs.writeFileSync(rootBuildGradle, buildGradle);
log(buildId, "info", "Patched build.gradle with Compose compiler suppression");
}
}
log(buildId, "info", "Starting Gradle assembleRelease");
updateStatus(statusFile, "building", "Compiling APK (this takes a few minutes)...", { progress: 60 });
execSync("chmod +x gradlew && ./gradlew assembleRelease --no-daemon -Dorg.gradle.jvmargs='-Xmx2g'", {
cwd: androidDir,
stdio: "pipe",
timeout: 1200000, // 20 min max (first Gradle build downloads deps)
maxBuffer: 100 * 1024 * 1024, // 100MB — Gradle is verbose
env: { ...process.env, ANDROID_HOME: "/opt/android-sdk", JAVA_HOME: "/usr/lib/jvm/java-17-openjdk-amd64", NODE_ENV: "production" }
});
// Find the APK
const apkDir = path.join(projectDir, "android/app/build/outputs/apk/release");
const apkFiles = fs.existsSync(apkDir) ? fs.readdirSync(apkDir).filter(f => f.endsWith(".apk")) : [];
if (apkFiles.length === 0) {
log(buildId, "error", "APK file not found after Gradle build");
throw new Error("APK not found after build");
}
// Copy APK to builds dir
const apkSrc = path.join(apkDir, apkFiles[0]);
const apkDst = path.join(BUILDS_DIR, `${buildId}.apk`);
fs.copyFileSync(apkSrc, apkDst);
const stats = fs.statSync(apkDst);
const versionSuffix = version ? `-${version}` : "";
log(buildId, "info", "Build completed successfully", { apkSize: stats.size });
updateStatus(statusFile, "completed", "Build complete!", {
fileSize: stats.size,
fileName: `${appName || "app"}${versionSuffix}.apk`,
progress: 100,
version: version || null
});
// Clean up project dir to save space
fs.rmSync(projectDir, { recursive: true, force: true });
} catch (err) {
log(buildId, "error", "Build failed: " + err.message);
updateStatus(statusFile, "failed", err.message || "Build failed");
// Clean up
if (fs.existsSync(projectDir)) {
fs.rmSync(projectDir, { recursive: true, force: true });
}
} finally {
activeBuildIds.delete(buildId);
processQueue();
}
}
// Get build status
app.get("/build/:buildId/status", (req, res) => {
const statusFile = path.join(BUILDS_DIR, `${req.params.buildId}.status.json`);
if (!fs.existsSync(statusFile)) {
return res.status(404).json({ error: "Build not found" });
}
res.json(JSON.parse(fs.readFileSync(statusFile, "utf8")));
});
// Download APK
app.get("/build/:buildId/download", (req, res) => {
const apkPath = path.join(BUILDS_DIR, `${req.params.buildId}.apk`);
if (!fs.existsSync(apkPath)) {
return res.status(404).json({ error: "APK not found" });
}
const statusFile = path.join(BUILDS_DIR, `${req.params.buildId}.status.json`);
let fileName = "app.apk";
if (fs.existsSync(statusFile)) {
try {
const s = JSON.parse(fs.readFileSync(statusFile, "utf8"));
if (s.fileName) fileName = s.fileName;
} catch {}
}
res.download(apkPath, fileName);
});
// Source code ZIP
app.post("/source", async (req, res) => {
const { files, appName, packageName } = req.body;
if (!files) return res.status(400).json({ error: "files required" });
const zip = new JSZip();
const folder = zip.folder(appName || "expo-project");
for (const [filePath, content] of Object.entries(files)) {
folder.file(filePath, content);
}
// Add scaffolding files if not present
if (!files["package.json"]) {
folder.file("package.json", JSON.stringify({
name: (packageName || "apk-forge-app").replace(/[^a-z0-9-]/g, "-"),
version: "1.0.0",
main: "expo/AppEntry.js",
scripts: { start: "expo start", android: "expo start --android" },
dependencies: {
"expo": "~52.0.0", "react": "18.3.1", "react-native": "0.76.3"
}
}, null, 2));
}
if (!files["app.json"]) {
const safeName = (appName || "My App").replace(/[^a-zA-Z0-9 ]/g, "");
folder.file("app.json", JSON.stringify({
expo: { name: safeName, slug: safeName.toLowerCase().replace(/\s+/g, "-"), version: "1.0.0" }
}, null, 2));
}
if (!files["README.md"]) {
folder.file("README.md", `# ${appName || "Expo App"}\n\nGenerated by APK Forge.\n\n## Getting Started\n\n\`\`\`bash\nnpm install\nnpx expo start\n\`\`\`\n`);
}
const buffer = await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE" });
res.set({
"Content-Type": "application/zip",
"Content-Disposition": `attachment; filename="${appName || "project"}-source.zip"`,
"Content-Length": buffer.length
});
res.send(buffer);
});
// SSE subscribers per buildId
const sseClients = new Map(); // buildId -> Set<res>
function broadcastBuildUpdate(buildId, data) {
const clients = sseClients.get(buildId);
if (!clients) return;
const payload = `data: ${JSON.stringify(data)}\n\n`;
for (const res of clients) {
try { res.write(payload); } catch { clients.delete(res); }
}
// Close connections on terminal states
if (data.status === "completed" || data.status === "failed") {
for (const res of clients) {
try { res.end(); } catch {}
}
sseClients.delete(buildId);
}
}
// SSE endpoint for build progress
app.get("/build/:buildId/stream", (req, res) => {
const { buildId } = req.params;
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
// Send current status immediately
const statusFile = path.join(BUILDS_DIR, `${buildId}.status.json`);
if (fs.existsSync(statusFile)) {
try {
const current = JSON.parse(fs.readFileSync(statusFile, "utf8"));
res.write(`data: ${JSON.stringify(current)}\n\n`);
// If already terminal, close
if (current.status === "completed" || current.status === "failed") {
res.end();
return;
}
} catch {}
}
// Register for future updates
if (!sseClients.has(buildId)) sseClients.set(buildId, new Set());
sseClients.get(buildId).add(res);
req.on("close", () => {
const clients = sseClients.get(buildId);
if (clients) { clients.delete(res); if (clients.size === 0) sseClients.delete(buildId); }
});
});
function updateStatus(file, status, message, extra = {}) {
const data = { status, message, updatedAt: new Date().toISOString(), ...extra };
fs.writeFileSync(file, JSON.stringify(data));
// Extract buildId from filename
const buildId = path.basename(file).replace(".status.json", "");
broadcastBuildUpdate(buildId, data);
}
// Create a minimal 1x1 PNG placeholder
function createPlaceholderPng() {
// Minimal valid PNG: 1x1 pixel, RGBA, dark background
return Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"base64"
);
}
const PORT = process.env.PORT || 3001;
app.listen(PORT, "0.0.0.0", () => {
console.log(`Build worker running on port ${PORT}`);
});