laureen
Publish static Space from 6953707
b968036
Raw History Blame Contribute Delete
2.46 kB
import { createServer } from 'node:http';
import { createReadStream } from 'node:fs';
import { realpath, stat } from 'node:fs/promises';
import { dirname, extname, resolve, sep } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createExamHandler } from './exam.mjs';
const defaultRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../dist');
const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.wasm': 'application/wasm', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.ico': 'image/x-icon', '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.woff2': 'font/woff2' };
export function createExamServer({ root = defaultRoot, ...options } = {}) {
const handler = createExamHandler(options);
return createServer(async (req, res) => {
if (await handler(req, res)) return;
try {
if (!['GET', 'HEAD'].includes(req.method)) { res.writeHead(405); res.end(); return; }
const path = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
if (path.includes('\\') || path.split('/').some(part => part.startsWith('.'))) throw new Error('Invalid path');
const base = await realpath(root);
let target = resolve(base, `.${path}`);
if (!target.startsWith(base + sep) && target !== base) throw new Error('Invalid path');
try { if ((await stat(target)).isDirectory()) target = resolve(target, 'index.html'); }
catch { if (!extname(path) && !path.startsWith('/api/')) target = resolve(base, 'index.html'); }
target = await realpath(target);
if (!target.startsWith(base + sep)) throw new Error('Invalid path');
const info = await stat(target);
if (!info.isFile()) throw new Error('Not a file');
res.writeHead(200, { 'Content-Type': types[extname(target)] || 'application/octet-stream', 'Content-Length': info.size, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-cache' });
if (req.method === 'HEAD') res.end();
else createReadStream(target).on('error', () => res.destroy()).pipe(res);
} catch { res.writeHead(404); res.end('Not found'); }
});
}
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
const port = Number(process.env.PORT || 8080);
createExamServer().listen(port, '0.0.0.0', () => console.log(`Simulator listening on port ${port}`));
}