sprawdzak / dev-server.mjs
ArtemisFowlAI's picture
Wdrożenie Sprawdzaka
3e08b05 verified
Raw History Blame Contribute Delete
3.16 kB
// Server for the Mac and the Hugging Face Space: serves public/ and the API.
// GET /api/check -> status for the page POST /api/check -> run a check (NDJSON stream)
// Usage: npm run dev (reads .env.local) | npm run mock (no API keys needed)
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
const root = path.dirname(fileURLToPath(import.meta.url));
try { process.loadEnvFile(path.join(root, '.env.local')); } catch {}
const { handleCheck, status } = await import('./lib/pipeline.js');
const PUBLIC = path.join(root, 'public');
const PORT = Number(process.env.PORT) || 3001; // 3000 is taken by Vardrobe
const TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json',
'.webmanifest': 'application/manifest+json',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.ico': 'image/x-icon',
};
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
try {
if (url.pathname === '/api/check') {
const ac = new AbortController();
res.on('close', () => { if (!res.writableEnded) ac.abort(); });
const chunks = [];
for await (const c of req) chunks.push(c);
const headers = new Headers();
for (const [k, v] of Object.entries(req.headers)) if (v != null) headers.set(k, Array.isArray(v) ? v.join(', ') : v);
const request = new Request(url, {
method: req.method,
headers,
body: req.method === 'POST' ? Buffer.concat(chunks) : undefined,
signal: ac.signal,
});
let response;
if (req.method === 'POST') response = await handleCheck(request);
else if (req.method === 'GET') response = Response.json(await status(request), { headers: { 'cache-control': 'no-store' } });
else response = new Response('', { status: 405 });
res.writeHead(response.status, Object.fromEntries(response.headers));
if (response.body) for await (const chunk of response.body) res.write(chunk);
res.end();
return;
}
const rel = url.pathname === '/' ? 'index.html' : decodeURIComponent(url.pathname).replace(/^\/+/, '');
const file = path.normalize(path.join(PUBLIC, rel));
if (!file.startsWith(PUBLIC + path.sep)) { res.writeHead(403).end(); return; }
const data = await readFile(file);
res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream' });
res.end(data);
} catch (e) {
if (!res.headersSent) res.writeHead(e && e.code === 'ENOENT' ? 404 : 500);
res.end();
}
});
server.listen(PORT, '0.0.0.0', () => {
const lan = Object.values(os.networkInterfaces()).flat().find((i) => i && i.family === 'IPv4' && !i.internal);
console.log(`Sprawdzak: http://localhost:${PORT}` + (lan ? ` (telefon w tej samej sieci Wi-Fi: http://${lan.address}:${PORT})` : ''));
if (process.env.SPRAWDZAK_MOCK === '1') console.log('Tryb testowy: bez wyszukiwania i bez AI.');
});