Files
HMDesign/scripts/serve-quality-reference.mjs

19 lines
1.4 KiB
JavaScript

import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
const routes = [['/themes/', 'storybook-static/themes'], ['/storybook/', 'storybook-static'], ['/publisher/', 'examples/publisher-list/dist'], ['/dashboard/', 'dist-dashboard'], ['/recruit/', 'dist-recruit'], ['/', 'dist']];
const mime = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.ttf': 'font/ttf' };
http.createServer((req, res) => {
try {
const pathname = decodeURIComponent(new URL(req.url, 'http://127.0.0.1').pathname);
const [prefix, folder] = routes.find(([p]) => pathname.startsWith(p));
const root = path.resolve(folder);
let file = path.resolve(root, `.${pathname.slice(prefix.length - 1)}`);
const relative = path.relative(root, file);
if (relative.startsWith('..') || path.isAbsolute(relative)) { res.writeHead(403); res.end(); return; }
if (fs.existsSync(file) && fs.statSync(file).isDirectory()) file = path.join(file, 'index.html');
if (!fs.existsSync(file)) { res.writeHead(404); res.end(); return; }
res.writeHead(200, { 'Content-Type': mime[path.extname(file)] ?? 'application/octet-stream' }); fs.createReadStream(file).pipe(res);
} catch { res.writeHead(400); res.end(); }
}).listen(6322, '127.0.0.1', () => console.log('Quality reference preview: http://127.0.0.1:6322/'));