78 lines
2.2 KiB
TypeScript
78 lines
2.2 KiB
TypeScript
// HTTP and Express server entrypoint mounting API routes, static bundles/assets, and starting background loops.
|
|
import express, { type Response } from "express";
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { seedAI } from "./ai.js";
|
|
import { APP_ROOT, config } from "./config.js";
|
|
import { initEconomy } from "./economy.js";
|
|
import { setBroadcaster } from "./events.js";
|
|
import { resolveGmatConsoleBin } from "./gmat_runner.js";
|
|
import { apiRouter } from "./routes.js";
|
|
import { getWorld, loadDb } from "./store.js";
|
|
import { initWorld, tick } from "./world.js";
|
|
|
|
const app = express();
|
|
app.use(express.json({ limit: "4mb" }));
|
|
|
|
app.use("/api", apiRouter);
|
|
|
|
const sseClients = new Set<Response>();
|
|
setBroadcaster((event) => {
|
|
const payload = `data: ${JSON.stringify(event)}\n\n`;
|
|
for (const res of sseClients) {
|
|
try {
|
|
res.write(payload);
|
|
} catch {
|
|
sseClients.delete(res);
|
|
}
|
|
}
|
|
});
|
|
|
|
app.get("/api/events", (req, res) => {
|
|
res.writeHead(200, {
|
|
"Content-Type": "text/event-stream",
|
|
"Cache-Control": "no-cache",
|
|
Connection: "keep-alive",
|
|
"X-Accel-Buffering": "no",
|
|
});
|
|
res.write(`data: ${JSON.stringify({ type: "hello", at: Date.now() })}\n\n`);
|
|
sseClients.add(res);
|
|
req.on("close", () => sseClients.delete(res));
|
|
});
|
|
|
|
app.use("/bundle", express.static(path.join(APP_ROOT, "dist", "bundle")));
|
|
app.use(express.static(path.join(APP_ROOT, "public")));
|
|
app.use("/data", express.static(path.join(APP_ROOT, "data")));
|
|
|
|
const modelsDir = path.join(APP_ROOT, "models");
|
|
if (fs.existsSync(modelsDir)) {
|
|
app.use("/models", express.static(modelsDir, { maxAge: "1h" }));
|
|
}
|
|
|
|
app.get(/.*/, (req, res, next) => {
|
|
if (req.path.startsWith("/api/")) {
|
|
next();
|
|
return;
|
|
}
|
|
res.sendFile(path.join(APP_ROOT, "public", "index.html"));
|
|
});
|
|
|
|
loadDb();
|
|
initWorld();
|
|
initEconomy(getWorld());
|
|
seedAI();
|
|
|
|
setInterval(tick, 1000);
|
|
|
|
app.listen(config.port, () => {
|
|
const gmatConsole = resolveGmatConsoleBin();
|
|
console.log(
|
|
`Space Gaem: You Will Feel the Pain (TypeScript Prototype) on http://localhost:${config.port}`,
|
|
);
|
|
console.log(
|
|
` GMAT: ${gmatConsole ?? "NOT FOUND (analytic ephemeris fallback)"}`,
|
|
);
|
|
console.log(
|
|
` Server password: ${config.serverPassword ? "required" : "none"}`,
|
|
);
|
|
});
|