Files
WT-Offline/apps/ai-lab/server/lab-api.ts
T

148 lines
6.3 KiB
TypeScript

/**
* Dev-server API of the AI lab (local only):
* GET /api/maps levels that have a navigation pack in mapsDir
* GET /api/maps/file?name= a pack or POI file of mapsDir
* GET /api/logs game logs (.clog) in logsDir, newest first
* GET /api/logs/text?name= a log decrypted with wtotools (cached until the log changes)
* GET /api/scene?name= the 3D map (.wtoscene) of a level, built from its .wtogeo in geoDir
* (cached until the geometry changes)
* Paths come from lab.local.json next to this app (see lab.local.example.json).
*/
import { execFile } from 'node:child_process';
import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
import type { ServerResponse } from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { buildMapScene, encodeMapScene, readGeo } from '@wto/ground-sim';
import type { Connect, Plugin } from 'vite';
interface LabConfig {
readonly mapsDir: string;
/** Where the navigation bake left the levels' .wtogeo geometry. */
readonly geoDir: string;
readonly logsDir: string;
readonly python: string;
}
const APP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const CACHE_DIR = path.join(APP_DIR, '.cache');
const SAFE_NAME = /^[\w.-]+$/;
function loadConfig(): LabConfig {
const file = path.join(APP_DIR, 'lab.local.json');
const raw = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>) : {};
const str = (key: string, fallback: string): string => (typeof raw[key] === 'string' ? (raw[key] as string) : fallback);
const mapsDir = str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps'));
return {
mapsDir,
geoDir: str('geoDir', path.join(mapsDir, '..', 'work')),
logsDir: str('logsDir', ''),
python: str('python', 'python'),
};
}
function sendJson(res: ServerResponse, status: number, body: unknown): void {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(body));
}
function sendFile(res: ServerResponse, file: string, type: string): void {
res.statusCode = 200;
res.setHeader('Content-Type', type);
createReadStream(file).pipe(res);
}
function listMaps(cfg: LabConfig): { level: string; pois: boolean; scene: boolean }[] {
if (!existsSync(cfg.mapsDir)) return [];
return readdirSync(cfg.mapsDir)
.filter((f) => f.endsWith('.wtonav'))
.map((f) => {
const level = f.slice(0, -'.wtonav'.length);
return {
level,
pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)),
scene: existsSync(path.join(cfg.geoDir, `${level}.wtogeo`)),
};
});
}
function listLogs(cfg: LabConfig): { name: string; size: number; mtime: number }[] {
if (cfg.logsDir === '' || !existsSync(cfg.logsDir)) return [];
return readdirSync(cfg.logsDir)
.filter((f) => f.endsWith('.clog'))
.map((name) => {
const st = statSync(path.join(cfg.logsDir, name));
return { name, size: st.size, mtime: st.mtimeMs };
})
.sort((a, b) => b.mtime - a.mtime);
}
/** Decrypts `name` into the cache unless the cached text is newer than the log. */
function decryptLog(cfg: LabConfig, name: string): Promise<string> {
const source = path.join(cfg.logsDir, name);
const out = path.join(CACHE_DIR, `${name}.txt`);
mkdirSync(CACHE_DIR, { recursive: true });
if (existsSync(out) && statSync(out).mtimeMs >= statSync(source).mtimeMs) return Promise.resolve(out);
return new Promise((resolve, reject) => {
execFile(cfg.python, ['-m', 'wtotools.cli', 'decrypt-clog', source, '--out', out], { timeout: 180_000 }, (err, _stdout, stderr) => {
if (err !== null) reject(new Error(`decrypt-clog failed: ${stderr || err.message}`));
else resolve(out);
});
});
}
/** Builds the level's 3D map into the cache unless the cached one is newer than its geometry. */
function sceneFile(cfg: LabConfig, level: string): string | undefined {
const geo = path.join(cfg.geoDir, `${level}.wtogeo`);
if (!existsSync(geo)) return undefined;
const out = path.join(CACHE_DIR, `${level}.wtoscene`);
if (existsSync(out) && statSync(out).mtimeMs >= statSync(geo).mtimeMs) return out;
mkdirSync(CACHE_DIR, { recursive: true });
writeFileSync(out, encodeMapScene(buildMapScene(readGeo(readFileSync(geo)))));
return out;
}
async function handle(cfg: LabConfig, url: URL, res: ServerResponse): Promise<boolean> {
const name = url.searchParams.get('name') ?? '';
if (url.pathname === '/api/maps') { sendJson(res, 200, listMaps(cfg)); return true; }
if (url.pathname === '/api/logs') { sendJson(res, 200, listLogs(cfg)); return true; }
const known = ['/api/maps/file', '/api/logs/text', '/api/scene'];
if (!known.includes(url.pathname)) return false;
if (!SAFE_NAME.test(name)) { sendJson(res, 400, { error: 'bad file name' }); return true; }
if (url.pathname === '/api/scene') {
const file = sceneFile(cfg, name);
if (file === undefined) sendJson(res, 404, { error: `no ${name}.wtogeo in ${cfg.geoDir}` });
else sendFile(res, file, 'application/octet-stream');
return true;
}
if (url.pathname === '/api/maps/file') {
const file = path.join(cfg.mapsDir, name);
if (!existsSync(file)) sendJson(res, 404, { error: `no ${name} in ${cfg.mapsDir}` });
else sendFile(res, file, name.endsWith('.json') ? 'application/json' : 'application/octet-stream');
return true;
}
if (!name.endsWith('.clog') || !existsSync(path.join(cfg.logsDir, name))) {
sendJson(res, 404, { error: `no log ${name}` });
return true;
}
sendFile(res, await decryptLog(cfg, name), 'text/plain; charset=utf-8');
return true;
}
export function labApi(): Plugin {
return {
name: 'wto-ai-lab-api',
configureServer(server) {
const middleware: Connect.NextHandleFunction = (req, res, next) => {
const url = new URL(req.url ?? '/', 'http://localhost');
if (!url.pathname.startsWith('/api/')) { next(); return; }
handle(loadConfig(), url, res)
.then((handled) => { if (!handled) sendJson(res, 404, { error: 'unknown endpoint' }); })
.catch((err: unknown) => sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) }));
};
server.middlewares.use(middleware);
},
};
}