Files
oaktracker/oras/server.mjs
T

80 lines
2.9 KiB
JavaScript

import http from 'node:http';
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = Number(process.env.PORT || 4173);
const HOST = process.env.HOST || '127.0.0.1';
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.mjs': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.ico': 'image/x-icon',
};
export function createStaticServer(rootDir = __dirname) {
const resolvedRoot = path.resolve(rootDir);
return http.createServer(async (req, res) => {
try {
const rawPath = (req.url || '/').split('?')[0];
const decodedRaw = decodeURIComponent(rawPath);
if (decodedRaw.split(/[\\/]/).includes('..')) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Forbidden');
return;
}
const reqUrl = new URL(req.url || '/', 'http://localhost');
let relPath = decodeURIComponent(reqUrl.pathname);
if (relPath === '/api/assets-status') {
const localSpritesDir = path.join(resolvedRoot, 'assets', 'sprites', 'pokemon');
const dirStat = await fs.stat(localSpritesDir).catch(() => null);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-cache' });
res.end(JSON.stringify({ hasLocalSprites: Boolean(dirStat?.isDirectory()) }));
return;
}
if (relPath === '/') relPath = '/index.html';
const targetPath = path.resolve(resolvedRoot, '.' + relPath);
if (targetPath !== resolvedRoot && !targetPath.startsWith(resolvedRoot + path.sep)) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Forbidden');
return;
}
const stat = await fs.stat(targetPath).catch(() => null);
if (!stat || !stat.isFile()) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not found');
return;
}
const ext = path.extname(targetPath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
const content = await fs.readFile(targetPath);
res.writeHead(200, {
'Content-Type': contentType,
'Cache-Control': 'no-cache',
});
res.end(content);
} catch (err) {
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`Server error: ${err.message}`);
}
});
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const server = createStaticServer();
server.listen(PORT, HOST, () => {
console.log(`Professor Oak Tracker running at http://${HOST}:${PORT}`);
});
}