'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const { chromium } = require('playwright');
const { transform } = require('esbuild');
const ROOT = path.resolve(__dirname, '../..');
const SHOTS = path.join(ROOT, '.cache/screenshots');
const fixture = (name) => fs.readFileSync(path.join(ROOT, 'tests/fixtures/luci-realtime', name), 'utf8');
let server, base, browser;
test.before(async () => {
fs.mkdirSync(SHOTS, { recursive: true });
const source = fs.readFileSync(path.join(ROOT, 'htdocs/luci-static/carbon/carbon.js'), 'utf8');
const css = fs.readFileSync(path.join(ROOT, 'htdocs/luci-static/carbon/carbon.css'), 'utf8');
const minified = (await transform(source, { minify: true, loader: 'js' })).code;
server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname.endsWith('.js')) {
res.setHeader('content-type', 'text/javascript');
res.end(url.pathname === '/min.js' ? minified : source);
}
else {
res.setHeader('content-type', 'text/html');
res.end(`
`);
}
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
base = 'http://127.0.0.1:' + server.address().port;
browser = await chromium.launch({ executablePath: process.env.CARBON_TEST_BROWSER || undefined });
});
test.after(async () => {
if (browser) await browser.close();
if (server) await new Promise((resolve) => server.close(resolve));
});
async function mount(page, kind, count = 1) {
await page.evaluate(({ source, svg, kind, count }) => {
const ticks = [];
let timestamp = 1000;
window.rpcCalls = 0;
const rpc = { declare: (spec) => () => {
if (spec.method !== 'getRealtimeStats') return Promise.resolve([]);
window.rpcCalls++;
const start = timestamp;
timestamp += 60;
return Promise.resolve(Array.from({ length: 60 }, (_, i) =>
[start + i, 10000 + i * 100, 20000 + i * 80, 30 + i % 5]));
} };
const L = { bind: (fn, ctx) => fn.bind(ctx), resolveDefault: (p, value) => Promise.resolve(p).catch(() => value) };
const view = new Function('view', 'poll', 'request', 'rpc', 'L', source)(
{ extend: (v) => v }, { add: (fn) => ticks.push(fn) }, {}, rpc, L);
// The connection table is independent of the SVG plot under test.
view.updateConntrack = () => {};
const ids = { load: ['load01', 'load05', 'load15'], bandwidth: ['rx', 'tx'], connections: ['tcp', 'udp', 'other'] }[kind];
window.graphs = [];
for (let i = 0; i < count; i++) {
const container = document.createElement('div');
container.style.cssText = 'width:100%;height:300px;border:1px solid #000;background:#fff';
container.innerHTML = svg.slice(svg.indexOf('