34 lines
1.7 KiB
JavaScript
34 lines
1.7 KiB
JavaScript
import http from 'node:http';
|
|
import { readFile, stat } from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'renderer');
|
|
const port = Number(process.env.PORT || 41737);
|
|
const mime = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.svg': 'image/svg+xml' };
|
|
|
|
const server = http.createServer(async (request, response) => {
|
|
try {
|
|
const pathname = decodeURIComponent(new URL(request.url, `http://${request.headers.host}`).pathname);
|
|
if (pathname === '/__forgeflow_test_ready__') {
|
|
response.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
response.end('forgeflow-demo-ready');
|
|
return;
|
|
}
|
|
const relative = pathname === '/' ? 'index.html' : pathname.replace(/^\//, '');
|
|
const target = path.resolve(root, relative);
|
|
if (!target.startsWith(root)) throw Object.assign(new Error('Forbidden'), { code: 'EACCES' });
|
|
const info = await stat(target);
|
|
if (!info.isFile()) throw Object.assign(new Error('Not found'), { code: 'ENOENT' });
|
|
response.writeHead(200, { 'Content-Type': mime[path.extname(target)] || 'application/octet-stream', 'Cache-Control': 'no-store' });
|
|
response.end(await readFile(target));
|
|
} catch (error) {
|
|
response.writeHead(error.code === 'ENOENT' ? 404 : 403, { 'Content-Type': 'text/plain' });
|
|
response.end(error.code === 'ENOENT' ? 'Not found' : 'Forbidden');
|
|
}
|
|
});
|
|
|
|
server.listen(port, '127.0.0.1', () => {
|
|
console.log(`ForgeFlow demo: http://127.0.0.1:${port}`);
|
|
});
|