Skip to content
1        10        20        30        40        50        60        70        80        901// Minimal static file server for the game, using Bun's built-in HTTP server.23import { readdir } from 'node:fs/promises';4import { extname, join, relative, resolve, sep } from 'node:path';56const rootArgument = process.argv[2];7const root = rootArgument ? resolve(rootArgument) : resolve(import.meta.dir, '..');8const hostname = process.env.HOST ?? '127.0.0.1';9const port = Number(process.env.PORT ?? 9999);1011const MIME = {12  '.html': 'text/html; charset=utf-8',13  '.js': 'text/javascript; charset=utf-8',14  '.css': 'text/css; charset=utf-8',15  '.json': 'application/json; charset=utf-8',16  '.svg': 'image/svg+xml',17  '.png': 'image/png',18  '.glb': 'model/gltf-binary',19  '.gltf': 'model/gltf+json',20  '.bin': 'application/octet-stream',21  '.ico': 'image/x-icon',22  '.woff2': 'font/woff2',23};2425// Every model under assets/ in a stable order, relative to the served root.26// The model gallery page uses this instead of keeping a manifest in sync.27async function listModels(directory) {28  const entries = await readdir(directory, { withFileTypes: true });29  const files = [];30  for (const entry of entries) {31    const path = join(directory, entry.name);32    if (entry.isDirectory()) files.push(...(await listModels(path)));33    else if (/\.(glb|gltf)$/i.test(entry.name)) files.push(relative(root, path));34  }35  return files.sort((a, b) => a.localeCompare(b));36}3738const server = Bun.serve({39  hostname,40  port,41  async fetch(request) {42    if (request.method !== 'GET' && request.method !== 'HEAD') {43      return new Response('Method not allowed', { status: 405 });44    }4546    const url = new URL(request.url);4748    if (url.pathname === '/__models') {49      try {50        return Response.json({ models: await listModels(join(root, 'assets')) });51      } catch {52        return Response.json({ models: [] });53      }54    }5556    let pathname;57    try {58      pathname = decodeURIComponent(url.pathname);59    } catch {60      return new Response('Bad request', { status: 400 });61    }6263    if (pathname.endsWith('/')) pathname += 'index.html';64    const filePath = resolve(root, `.${pathname}`);65    if (filePath !== root && !filePath.startsWith(root + sep)) {66      return new Response('Forbidden', { status: 403 });67    }6869    const file = Bun.file(filePath);70    if (!(await file.exists())) {71      return new Response('Not found', { status: 404 });72    }7374    return new Response(request.method === 'HEAD' ? null : file, {75      headers: {76        'Content-Type': MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream',77      },78    });79  },80});8182console.log(`Torment is running at ${server.url}`);