feat: add local build console

This commit is contained in:
que01 committed 2026-09-22 14:15:32 +08:00
1 parent 4ec4372b35
commit 3760650c70
9 files changed
+72 -43

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env node
"use strict";
const http = require("http"), fs = require("fs"), path = require("path"), crypto = require("crypto"), child = require("child_process");
const { unzipSync } = require("fflate");
const { readAreaConfig } = require("./lib/area-config");
const { STAGES } = require("./lib/build-stages");
const root = path.resolve(__dirname, ".."), configDir = path.join(root, "config", "areas"), managedRoot = path.join(root, "inputs", "console"), stateRoot = path.join(root, ".build-console", "areas"), uiFile = path.join(__dirname, "console", "index.html");
let active = null;
const send = (res, status, data) => { res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }); res.end(JSON.stringify(data)); };
const safeKey = value => { const key = String(value || "").toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, ""); if (!key) throw Error("请输入只含字母、数字、- 或 _ 的配置名称"); return key; };
const under = (file, base) => { const resolved = path.resolve(file), parent = path.resolve(base); return resolved === parent || resolved.startsWith(`${parent}${path.sep}`); };
function areas() { return fs.readdirSync(configDir).filter(x => x.endsWith(".json")).sort().map(file => { const config = path.join(configDir, file); try { const a = readAreaConfig(config, { repoRoot: root }); const preview = a.outputs.cesiumPreview, manifest = a.outputs.packageManifest; return { key:path.basename(file,".json"), id:a.id, config, input:a.input, zip:a.nativeRoadPackage, treeStyle:a.blender.treeStyle, output:a.outputs.areaDir, preview:fs.existsSync(preview) ? `/artifacts/${path.basename(file,".json")}/${path.basename(preview)}` : null, manifest:fs.existsSync(manifest) ? `/artifacts/${path.basename(file,".json")}/package/manifest.json` : null }; } catch (e) { return { key:path.basename(file,".json"), error:e.message }; } }); }
function inspectZip(bytes) { let files; try { files = unzipSync(bytes); } catch (_) { throw Error("道路 ZIP 无法解压"); } if (!files["manifest.json"]) throw Error("道路 ZIP 缺少 manifest.json"); let manifest; try { manifest=JSON.parse(Buffer.from(files["manifest.json"]).toString("utf8")); } catch (_) { throw Error("道路 ZIP manifest.json 无效"); } if (manifest.contract !== "native-road-package/v1.1" || !manifest.areaId) throw Error("道路 ZIP 不是受支持的 native-road-package/v1.1"); return { areaId:manifest.areaId, contract:manifest.contract }; }
function body(req) { return new Promise((resolve,reject) => { let data=""; req.on("data", c=>{ data+=c; if(data.length>100*1024*1024) reject(Error("上传文件过大")); }); req.on("end",()=>{ try { resolve(JSON.parse(data||"{}")); } catch (_) { reject(Error("请求 JSON 无效")); } }); }); }
function trash(target) { if (!fs.existsSync(target)) return; if (!under(target, root)) throw Error("拒绝清理项目外文件"); child.execFileSync("osascript", ["-e", `tell application \"Finder\" to delete POSIX file ${JSON.stringify(target)}`]); }
function serve(req,res) { const url = new URL(req.url, "http://127.0.0.1"); if (req.method==="GET" && url.pathname==="/") { res.writeHead(200,{"content-type":"text/html; charset=utf-8"}); return res.end(fs.readFileSync(uiFile)); }
if(req.method==="GET"&&url.pathname==="/api/health") return send(res,200,{node:process.version, blender:fs.existsSync("/Applications/Blender.app/Contents/MacOS/Blender"), areas:areas().length});
if(req.method==="GET"&&url.pathname==="/api/areas") return send(res,200,{areas:areas(),stages:STAGES,treeStyles:["natural","procedural","shapespark"]});
if(req.method==="POST"&&url.pathname==="/api/inspect") return body(req).then(x=>send(res,200,inspectZip(Buffer.from(x.zip,"base64")))).catch(e=>send(res,400,{error:e.message}));
if(req.method==="POST"&&url.pathname==="/api/import") return body(req).then(x=>{ const key=safeKey(x.key), osm=Buffer.from(x.osm,"base64"), zip=Buffer.from(x.zip,"base64"), info=inspectZip(zip), dir=path.join(managedRoot,key); if(fs.existsSync(path.join(configDir,`${key}.json`))) throw Error("该配置名称已存在;请另存为新名称"); fs.mkdirSync(dir,{recursive:true}); const osmFile=path.join(dir,"source.osm"), zipFile=path.join(dir,"roads.zip"); fs.writeFileSync(osmFile,osm); fs.writeFileSync(zipFile,zip); const out=path.join(root,"outputs",key), config={id:info.areaId,input:osmFile,nativeRoadPackage:zipFile,outputRoot:path.join(root,"outputs"),outputs:{areaDir:out,fileStem:key},blender:{roadProvider:"native",treeStyle:x.treeStyle||"natural"}}; const file=path.join(configDir,`${key}.json`); fs.writeFileSync(file,JSON.stringify(config,null,2)+"\n"); fs.mkdirSync(stateRoot,{recursive:true}); fs.writeFileSync(path.join(stateRoot,`${key}.json`),JSON.stringify({key,config:file,managed:dir,output:out},null,2)); send(res,201,{key,id:info.areaId}); }).catch(e=>send(res,400,{error:e.message}));
if(req.method==="POST"&&url.pathname==="/api/build") return body(req).then(x=>{ if(active&&!active.done) throw Error("已有构建正在运行"); const key=safeKey(x.key), file=path.join(configDir,`${key}.json`); if(!fs.existsSync(file)) throw Error("配置不存在"); const args=[path.join(__dirname,"build-area.js"),"--config",file]; if(Array.isArray(x.stages)&&x.stages.length) args.push("--stages",x.stages.join(",")); const proc=child.spawn(process.execPath,args,{cwd:root}); const job=active={id:crypto.randomUUID(),key,logs:[],done:false}; for(const s of [proc.stdout,proc.stderr]) s.on("data",b=>job.logs.push(b.toString())); proc.on("close",code=>{job.logs.push(`\n构建结束:${code===0?"成功":"失败"} (${code})\n`);job.done=true;job.code=code;}); send(res,202,{id:job.id}); }).catch(e=>send(res,409,{error:e.message}));
if(req.method==="GET"&&url.pathname==="/api/job") return send(res,200,active||{done:true});
if(req.method==="POST"&&url.pathname==="/api/cleanup") return body(req).then(x=>{ const keys=Array.isArray(x.keys)?x.keys:[]; const known=new Map(areas().map(a=>[a.key,a])); for(const raw of keys){const key=safeKey(raw), area=known.get(key), config=path.join(configDir,`${key}.json`); if(!area||!fs.existsSync(config)) throw Error(`区域不存在:${key}`); trash(area.output||path.join(root,"outputs",key)); const rec=path.join(stateRoot,`${key}.json`); if(x.mode==="remove"){ if(fs.existsSync(rec)){const r=JSON.parse(fs.readFileSync(rec));trash(r.managed);trash(rec);} trash(config); } } send(res,200,{ok:true}); }).catch(e=>send(res,400,{error:e.message}));
if(req.method==="GET"&&url.pathname.startsWith("/artifacts/")){const [, ,key,...rest]=url.pathname.split("/");const a=areas().find(x=>x.key===key);const f=path.resolve(a?.output||"",...rest);if(!a||!under(f,a.output)||!fs.existsSync(f))return send(res,404,{error:"未找到产物"});return fs.createReadStream(f).pipe(res);} send(res,404,{error:"Not found"}); }
http.createServer((q,s)=>serve(q,s)).listen(8788,"127.0.0.1",()=>{const u="http://127.0.0.1:8788/";console.log(`Build console: ${u}`);child.spawn("open",[u],{detached:true,stdio:"ignore"}).unref();});