import { request } from 'node:http'; import { fileURLToPath } from 'node:url'; import { readFileSync } from 'node:fs'; import { testerSocketPath, TESTER_ORIGIN } from '../../webui/src/tester-socket.mjs'; export function testerRequest({ dataRoot, path = '/healthz', method = 'GET', body, headers = {}, timeout = 30000 }) { if (typeof path !== 'string' || !/^\/(?!\/)/.test(path) || /[\r\n\0]/.test(path)) return Promise.reject(Error('tester-http-path')); const data = body === undefined ? undefined : JSON.stringify(body); if (data && Buffer.byteLength(data) > 16384) return Promise.reject(Error('tester-http-size')); return new Promise((resolve, reject) => { const req = request({ socketPath: testerSocketPath(dataRoot), path, method, headers: { host: new URL(TESTER_ORIGIN).host, origin: TESTER_ORIGIN, 'sec-fetch-site': 'same-origin', ...(data ? { 'content-type': 'application/json' } : {}), ...headers } }, res => { const chunks = []; let size = 0; res.on('data', b => { size += b.length; if (size > 8 * 1024 * 1024) req.destroy(Error('tester-http-size')); else chunks.push(b); }); res.on('error', reject); res.on('end', () => { const text = Buffer.concat(chunks).toString('utf8'); try { resolve({ status: res.statusCode, text, body: res.headers['content-type']?.includes('json') ? JSON.parse(text) : null }); } catch { reject(Error('tester-http-response')); } }); }); req.setTimeout(timeout, () => req.destroy(Error('tester-http-timeout'))); req.on('error', reject); req.end(data); }); } if (process.argv[1] === fileURLToPath(import.meta.url)) { try { const { loadSystem } = await import('./config.mjs'); const [method = 'GET', path = '/healthz'] = process.argv.slice(2); if (!['GET', 'HEAD', 'POST'].includes(method) || process.argv.length > 4) throw Error('tester-http-usage'); const body = method === 'POST' ? JSON.parse(readFileSync(0, 'utf8')) : undefined; const result = await testerRequest({ dataRoot: loadSystem().dataRoot, path, method, body }); process.stdout.write(JSON.stringify(result) + '\n'); if (result.status >= 400) process.exitCode = 2; } catch { process.stderr.write('tester-http-refused\n'); process.exitCode = 2; } }