sokko-g/server.mjs
Shinuwa 5ce35cd7ba Add the Sokko TCG collectible card mini-game
Add the server-backed card game: Discord login, recharging pack openings,
album, trades, gifts, stardust shop, campaign codes and its administration,
stored in SQLite and disabled in production until configured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 17:47:35 +01:00

114 lines
3.9 KiB
JavaScript

// Rôle : sert l'application Vite construite ou les sources publiques avec leur politique de cache.
import { createReadStream, existsSync, statSync } from "node:fs";
import { loadProjectEnv } from "./scripts/load-project-env.mjs";
import { createCardsApiHandler } from "./services/cards/api.js";
import { createServer } from "node:http";
import { extname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const modulePath = fileURLToPath(import.meta.url);
const projectRoot = resolve(fileURLToPath(new URL(".", import.meta.url)));
const websiteRoot = join(projectRoot, "website");
const distRoot = join(websiteRoot, "dist");
const defaultRoot = existsSync(distRoot) ? distRoot : websiteRoot;
const defaultPublicRoot = existsSync(distRoot) ? distRoot : join(websiteRoot, "public");
const types = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp"
};
function isInsideRoot(parent, file) {
const relativePath = relative(parent, file);
return Boolean(relativePath) && !relativePath.startsWith("..") && !relativePath.startsWith("/");
}
function fileIfReadable(parent, file) {
return isInsideRoot(parent, file) && existsSync(file) && statSync(file).isFile() ? file : null;
}
function resolvePath(url, root, publicRoot) {
let requested;
try {
requested = decodeURIComponent(new URL(url, "http://localhost").pathname);
} catch {
return null;
}
const candidate = fileIfReadable(root, resolve(root, `.${requested}`));
if (candidate) return candidate;
const publicCandidate = fileIfReadable(publicRoot, resolve(publicRoot, `.${requested}`));
if (publicCandidate) return publicCandidate;
return extname(requested) ? null : join(root, "index.html");
}
function isVersionedAsset(root, file) {
const relativePath = relative(root, file).replaceAll("\\", "/");
const fileName = relativePath.split("/").at(-1) || "";
return relativePath.startsWith("assets/") && /-[a-z0-9_-]{8,}\.[^.]+(?:\.map)?$/i.test(fileName);
}
function getCacheControl(root, file) {
const extension = extname(file);
if (extension === ".html") return "no-store";
if (extension === ".json") return "no-cache";
if (isVersionedAsset(root, file)) return "public, max-age=31536000, immutable";
return "no-cache";
}
export function createStaticServer({ root = defaultRoot, publicRoot = defaultPublicRoot, cardsApi = null } = {}) {
const server = createServer(async (req, res) => {
if (cardsApi && await cardsApi(req, res)) return;
const file = resolvePath(req.url || "/", root, publicRoot);
if (!file || !existsSync(file)) {
res.writeHead(404, {
"Content-Type": "text/plain; charset=utf-8",
"Cache-Control": "no-store"
});
res.end("Not found");
return;
}
res.writeHead(200, {
"Content-Type": types[extname(file)] || "application/octet-stream",
"Cache-Control": getCacheControl(root, file)
});
createReadStream(file).pipe(res);
});
if (cardsApi?.close) server.once("close", cardsApi.close);
return server;
}
export function startServer({ cardsApiOptions = {} } = {}) {
loadProjectEnv();
const port = Number(process.env.PORT || 5173);
const cardsApi = createCardsApiHandler({ projectRoot, ...cardsApiOptions });
const server = createStaticServer({ cardsApi });
server.on("error", (error) => {
if (error.code === "EADDRINUSE") {
console.error(`Port ${port} is already in use. Set PORT to another value.`);
process.exit(1);
}
console.error(error);
process.exit(1);
});
server.listen(port, () => {
console.log(`Sokko G dev server running at http://localhost:${port}`);
});
return server;
}
if (process.argv[1] && resolve(process.argv[1]) === modulePath) startServer();