Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

4.7 KB
Raw Blame
// Serves the site locally: bun site/serve.ts [port] [--lan]  ->  http://localhost:4173/
//   --lan   listen on every interface and print the LAN address, so a phone on the same network can open the pages
//           and the packages in play/ (threert://<lan ip>:<port>/play/<id>).
// three.js and the QR encoder come from node_modules (npm install first); site/media is committed (rebuild: bun
// site/tools/media.ts). releases/ and play/ are generated by the client repository's release script (site/README.md):
// without them the Download page says that no build is published on this host (play/ is only read by clients before
// 0.4.0, whose Showcase listed it).
import { existsSync, statSync } from "node:fs";
import { networkInterfaces } from "node:os";
import { extname, join, normalize, resolve } from "node:path";
import { VENDOR } from "./tools/vendor.ts";
import { clientFile } from "./worker.ts";

const root = resolve(import.meta.dir);
const args = process.argv.slice(2);
const lan = args.includes("--lan");
const port = Number(args.find((a) => /^\d+$/.test(a)) ?? process.env.PORT ?? 4173);

// What the site is made of: the pages, their shared files, and the two generated directories. Nothing else under
// site/ (tools, the worker, this file) is served.
const PAGES = new Set(["index.html", "showcase/index.html", "download/index.html", "docs/index.html", "docs/rendering/index.html", "privacy/index.html", "blog/index.html", "blog/ps3/index.html"]);
const DIRS = ["css/", "js/", "brand/", "media/", "releases/", "play/"];
const TYPES: Record<string, string> = {
  ".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8",
  ".json": "application/json", ".ts": "text/plain; charset=utf-8", ".svg": "image/svg+xml", ".webp": "image/webp", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
  ".glb": "model/gltf-binary", ".gltf": "model/gltf+json", ".bin": "application/octet-stream", ".hdr": "application/octet-stream", ".exr": "application/octet-stream", ".ktx2": "image/ktx2",
  ".mp4": "video/mp4", ".dmg": "application/x-apple-diskimage", ".zip": "application/zip",
  ".apk": "application/vnd.android.package-archive", ".gz": "application/gzip",
};

for (const f of Object.values(VENDOR)) if (!existsSync(f)) console.warn(`missing ${f}: run npm install at the repo root`);
for (const [f, what] of [["releases/latest.json", "the Download page has no build to offer"], ["play/index.json", "clients before 0.4.0 have no examples to list"]]) {
  if (!existsSync(join(root, f))) console.warn(`no site/${f}: ${what} (site/README.md)`);
}

const isFile = (f: string) => existsSync(f) && statSync(f).isFile();

Bun.serve({
  port,
  hostname: lan ? "0.0.0.0" : "127.0.0.1",
  fetch(req) {
    const url = new URL(req.url);
    let path: string;
    try {
      path = decodeURIComponent(url.pathname);
    } catch {
      return new Response("bad request", { status: 400 });
    }
    let rel = path.replace(/^\/+/, "");
    if (rel === "" || rel.endsWith("/")) rel += "index.html";
    const vendored = VENDOR[rel];
    const file = vendored ?? normalize(join(root, rel));
    if (!vendored) {
      if (!file.startsWith(root + "/")) return new Response("not found", { status: 404 });
      // A directory without its slash: redirect, so the page's relative links resolve (as the deployed site does).
      if (existsSync(file) && statSync(file).isDirectory() && isFile(join(file, "index.html"))) return Response.redirect(`${url.pathname}/${url.search}`, 301);
      if (!PAGES.has(rel) && !DIRS.some((d) => rel.startsWith(d))) return new Response("not found", { status: 404 });
    }
    if (!isFile(file)) return new Response("not found", { status: 404 });
    const headers: Record<string, string> = { "cache-control": "no-cache", "content-type": TYPES[extname(file).toLowerCase()] ?? "application/octet-stream" };
    // Packages are fetched by native clients and by pages on other origins (a game's own site).
    if (rel.startsWith("play/")) headers["access-control-allow-origin"] = "*";
    // The clients' files are downloads, as the Worker serves them.
    const client = clientFile(`/${rel}`);
    if (client) {
      headers["content-type"] = client.type;
      headers["content-disposition"] = `attachment; filename="${client.key}"`;
    }
    return new Response(Bun.file(file), { headers });
  },
});

console.log(`ThreeRT site: http://localhost:${port}/`);
if (lan) {
  const nets = networkInterfaces();
  const ip = ["en0", "en1", ...Object.keys(nets)].flatMap((n) => nets[n] ?? []).find((n) => n.family === "IPv4" && !n.internal)?.address;
  console.log(ip ? `         LAN: http://${ip}:${port}/  (open this one for QR codes a phone can use)` : "         LAN: no network address found");
}