import { createServer } from "http"; import load from "better-sqlite3"; import * as brotli from "brotli"; const name = process.argv[2] || "./archive.sqlite3"; const db = load(name); const getStmt = db.prepare( "select content, compressed from files where path = ?" ); const port = 8080; createServer((req, res) => { let url = req.url; if (!url) throw new Error("wtf"); { const indexQ = url.indexOf("?"); if (indexQ !== -1) url = url.slice(0, indexQ); } if (url.endsWith("/")) url += "index.html"; url = decodeURI(url); // prettier-ignore const r = /** @type {{content:Buffer, compressed:boolean}} */(getStmt.get(url)); if (!r) { res.writeHead(404).end("not found"); return; } if (r.compressed) { let encodings = req.headers["accept-encoding"]; if (encodings instanceof Array) encodings = encodings[0]; if (encodings) encodings = encodings.split(", "); if (encodings?.includes("br")) { res .writeHead(200, { "content-encoding": "br", }) .end(r.content); } else { res.writeHead(200).end(brotli.decompress(r.content)); } } else { res.writeHead(200).end(r.content); } }).listen(port, () => console.debug(`Listening in ${port}`));