| 1 | import { createServer as httpServer } from 'node:http' ; |
| 2 | import { readFile } from 'node:fs/promises' ; |
| 3 | import { fileURLToPath } from 'node:url' ; |
| 4 | import { resolve } from 'node:path' ; |
| 5 | |
| 6 | export function createServer() { |
| 7 | return httpServer(async (req, res) => { |
| 8 | const pathname = new URL(req.url, 'http://localhost' ).pathname; |
| 9 | const path = pathname === '/' ? '/demo/index.html' : pathname; |
| 10 | if (!/^\/(demo|src)\/[a-zA-Z0-9_/-]+\.(html|css|js|svg)$/.test(path) || !['GET' , 'HEAD' ].includes(req.method)) { |
| 11 | res.writeHead(404); res.end('Not found' ); return; |
| 12 | } |
| 13 | try { |
| 14 | const data = await readFile(new URL('.' + path, import.meta.url)); |
| 15 | const mime = { html:'text/html; charset=utf-8' , css:'text/css' , js:'text/javascript' , svg:'image/svg+xml' }[path.split('.' ).at(-1)]; |
| 16 | res.writeHead(200, {'Content-Type' :mime,'Cache-Control' :'no-cache' ,'X-Content-Type-Options' :'nosniff' }); |
| 17 | res.end(req.method === 'HEAD' ? undefined : data); |
| 18 | } catch { res.writeHead(404); res.end('Not found' ); } |
| 19 | }); |
| 20 | } |
| 21 | if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { |
| 22 | const port = Number(process.env.PORT || 4174); |
| 23 | createServer().listen(port, '0.0.0.0' , () => console.log(`Seedmark: http://localhost:${port}` )); |
| 24 | } |