42 lines
1.8 KiB
TypeScript
42 lines
1.8 KiB
TypeScript
// Local dev server: the web build at / and a game folder at /data/, with HTTP range
|
|
// requests and case-insensitive paths (the browser asks for lower-case names).
|
|
// Usage: bun tools/serve.ts <dist dir> <game dir> [port]
|
|
import { join } from "node:path";
|
|
import { readdirSync, existsSync, statSync } from "node:fs";
|
|
|
|
const [dist, gameDir, port = "8790"] = process.argv.slice(2);
|
|
if (!dist || !gameDir) throw new Error("usage: bun tools/serve.ts <dist dir> <game dir> [port]");
|
|
|
|
// Finds "models/gta3.img" as "MODELS/GTA3.IMG" or any other casing on disk.
|
|
function resolveCase(root: string, rel: string): string | null {
|
|
let dir = root;
|
|
for (const part of rel.split("/").filter(Boolean)) {
|
|
if (part === "..") return null;
|
|
const hit = readdirSync(dir).find((n) => n.toLowerCase() === part.toLowerCase());
|
|
if (!hit) return null;
|
|
dir = join(dir, hit);
|
|
}
|
|
return existsSync(dir) && statSync(dir).isFile() ? dir : null;
|
|
}
|
|
|
|
Bun.serve({
|
|
port: Number(port),
|
|
hostname: "127.0.0.1",
|
|
fetch(req) {
|
|
const path = decodeURIComponent(new URL(req.url).pathname);
|
|
const file = path.startsWith("/data/")
|
|
? resolveCase(gameDir, path.slice(6))
|
|
: resolveCase(dist, path === "/" ? "index.html" : path.slice(1));
|
|
if (!file) return new Response("not found", { status: 404 });
|
|
const body = Bun.file(file);
|
|
const range = req.headers.get("range")?.match(/bytes=(\d+)-(\d*)/);
|
|
if (!range) return new Response(body, { headers: { "Accept-Ranges": "bytes" } });
|
|
const start = Number(range[1]);
|
|
const end = range[2] ? Math.min(Number(range[2]), body.size - 1) : body.size - 1;
|
|
return new Response(body.slice(start, end + 1), {
|
|
status: 206,
|
|
headers: { "Content-Range": `bytes ${start}-${end}/${body.size}`, "Accept-Ranges": "bytes" },
|
|
});
|
|
},
|
|
});
|
|
console.log(`serving on http://127.0.0.1:${port}`);
|