summaryrefslogtreecommitdiff
path: root/test/web/catalog_ui.mjs
blob: bed40b24e50aaca707e37a71b97d1bb9889a3f1b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// Real Chromium regression checks for the integrated 9web views. No npm deps.
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import fs from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import net from 'node:net';

const binary = path.resolve(process.argv[2] || 'zig-out/bin/9web');
const work = await fs.mkdtemp(path.join(os.tmpdir(), '9web-ui-'));
const children = [], exceptions = [], pending = new Map();
let socket, serial = 0;
function start(command, args) {
  const p = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
  p.output = ''; p.stdout.on('data', b => { p.output += b; }); p.stderr.on('data', b => { p.output += b; });
  p.on('error', e => { p.output += e.message; }); children.push(p); return p;
}
async function port() {
  const s = net.createServer(); s.listen(0, '127.0.0.1'); await once(s, 'listening');
  const n = s.address().port; await new Promise(resolve => s.close(resolve)); return n;
}
async function wait(fn, message, timeout = 15000) {
  const until = Date.now() + timeout;
  while (Date.now() < until) { try { const value = await fn(); if (value) return value; } catch {} await new Promise(r => setTimeout(r, 50)); }
  throw new Error('timeout: ' + message);
}
function cdp(method, params = {}) {
  return new Promise((resolve, reject) => {
    const id = ++serial;
    const timer = setTimeout(() => { pending.delete(id); reject(new Error(`CDP timeout: ${method}`)); }, 10000);
    pending.set(id, { resolve, reject, timer }); socket.send(JSON.stringify({ id, method, params }));
  });
}
async function evaluate(expression) {
  const r = await cdp('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
  if (r.exceptionDetails) throw new Error(JSON.stringify(r.exceptionDetails));
  return r.result.value;
}
async function click(selector) { await evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`); }
async function view(name) {
  await click(`#view-${name}`);
  await wait(() => evaluate(`!document.getElementById('${name}-view').hidden`), name + ' view');
}
async function readySites() { await wait(() => evaluate(`document.querySelectorAll('#sites-entries tr').length === 1`), 'site row'); }

try {
  const root = path.join(work, 'public'); await fs.mkdir(root);
  await fs.writeFile(path.join(root, 'index.html'), '<h1>Fixture</h1>');
  const dashboard = await port(), sitePort = await port(), debugPort = await port();
  await fs.writeFile(path.join(work, 'config.json'), JSON.stringify({ sites: [{ name: 'fixture', title: 'Fixture notes', cwd: work, root, port: sitePort, build: ['sh', '-c', 'echo integrated-build'], inputs: ['public/index.html'] }] }));
  const web = start(binary, ['--listen', `127.0.0.1:${dashboard}`, '--catalog', path.join(work, 'config.json'), '--catalog-socket', path.join(work, 'catalog.sock'), '--state-dir', path.join(work, 'state')]);
  const url = `http://127.0.0.1:${dashboard}`;
  await wait(async () => (await fetch(url)).ok, 'server ready');
  assert.equal((await (await fetch(url + '/_cloud9/config.json')).json()).catalog, true);
  assert.equal((await fetch(url + '/_cloud9/catalog.js')).status, 404, 'standalone JS removed');
  start(process.env.CLOUD9_CHROME || 'google-chrome-stable', ['--headless=new', '--no-sandbox', '--disable-dev-shm-usage', '--no-first-run', '--no-default-browser-check', `--user-data-dir=${work}/chrome`, `--remote-debugging-port=${debugPort}`, 'about:blank']);
  const target = await wait(async () => (await fetch(`http://127.0.0.1:${debugPort}/json/new?about:blank`, { method: 'PUT' })).json(), 'browser ready');
  socket = new WebSocket(target.webSocketDebuggerUrl); await once(socket, 'open');
  socket.addEventListener('message', ({ data }) => {
    const m = JSON.parse(data);
    if (m.id) {
      const p = pending.get(m.id); if (!p) return; clearTimeout(p.timer); pending.delete(m.id);
      if (m.error) p.reject(new Error(JSON.stringify(m.error))); else p.resolve(m.result);
    } else if (m.method === 'Runtime.exceptionThrown') exceptions.push(m.params.exceptionDetails);
  });
  await cdp('Runtime.enable'); await cdp('Page.enable');
  await cdp('Emulation.setDeviceMetricsOverride', { width: 1200, height: 850, deviceScaleFactor: 1, mobile: false });
  await cdp('Page.navigate', { url });
  await wait(() => evaluate(`document.getElementById('status')?.textContent.includes('entries')`), 'files loaded');
  assert.equal(await evaluate(`document.querySelectorAll('header').length`), 1);
  assert.equal(await evaluate(`getComputedStyle(document.documentElement).backgroundColor`), 'rgb(255, 255, 255)');
  assert.equal(await evaluate(`document.getElementById('view-files').getAttribute('aria-current')`), 'page');
  await view('sites'); await readySites();
  assert.equal(await evaluate(`document.querySelector('#sites-entries .site-name').href`), `http://127.0.0.1:${sitePort}/`);
  assert.equal(await evaluate(`document.querySelectorAll('link[rel=stylesheet]').length`), 1);
  assert.equal(await evaluate(`document.querySelector('link[rel=stylesheet]').getAttribute('href')`), '/_cloud9/style.css');
  // Build button writes through the same /fs tree as the normal file browser.
  await click('#sites-entries button');
  await wait(() => evaluate(`document.querySelector('#sites-entries .site-phase').textContent.includes('exit 0')`), 'build complete');
  await evaluate(`document.querySelector('#sites-entries button').focus()`);
  await click('#sites-reload');
  await evaluate(`document.querySelector('#sites-entries button').focus()`);
  await wait(() => evaluate(`!document.getElementById('sites-reload').disabled`), 'refresh complete');
  assert.equal(await evaluate(`document.activeElement === document.querySelector('#sites-entries button')`), true, 'refresh preserves focused control');
  await click('#sites-entries a[data-path$="/log"]');
  await wait(() => evaluate(`document.getElementById('editor').value.includes('integrated-build')`), 'log in file viewer');
  assert.equal(await evaluate(`document.getElementById('files-view').hidden`), false);
  // Switching views preserves the existing file editor and its unsaved contents.
  await evaluate(`document.getElementById('editor').value = 'unsaved note'; document.getElementById('editor').dispatchEvent(new Event('input'))`);
  await view('sites'); await view('services');
  await wait(() => evaluate(`document.getElementById('services-status').textContent.includes('HTTP services')`), 'services loaded');
  await evaluate('history.back()');
  await wait(() => evaluate(`!document.getElementById('sites-view').hidden`), 'back to sites');
  await evaluate('history.back()');
  await wait(() => evaluate(`!document.getElementById('files-view').hidden`), 'back to files');
  assert.equal(await evaluate(`document.getElementById('editor').value`), 'unsaved note');
  assert.equal(await evaluate(`document.getElementById('edit-status').textContent`), 'Unsaved changes.');
  // Reload/deep-link into a tab; no synthetic 9P path is reserved for the tab.
  await evaluate(`window.onbeforeunload = null; window.confirm = () => true`);
  // A fresh target avoids bypassing the intentional beforeunload prompt.
  const target2 = await (await fetch(`http://127.0.0.1:${debugPort}/json/new?${encodeURIComponent(url + '/?view=sites')}`, { method: 'PUT' })).json();
  socket.close(); socket = new WebSocket(target2.webSocketDebuggerUrl); await once(socket, 'open');
  socket.addEventListener('message', ({ data }) => {
    const m = JSON.parse(data); if (!m.id) return;
    const p = pending.get(m.id); if (!p) return; clearTimeout(p.timer); pending.delete(m.id);
    if (m.error) p.reject(new Error(JSON.stringify(m.error))); else p.resolve(m.result);
  });
  await cdp('Runtime.enable'); await cdp('Page.enable'); await readySites();
  assert.equal(await evaluate(`document.getElementById('view-sites').getAttribute('aria-current')`), 'page');
  await cdp('Emulation.setDeviceMetricsOverride', { width: 1200, height: 850, deviceScaleFactor: 1, mobile: false });
  await fs.mkdir('.zig-cache/catalog-ui', { recursive: true });
  await fs.writeFile('.zig-cache/catalog-ui/sites.png', Buffer.from((await cdp('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  await view('services');
  await wait(() => evaluate(`document.getElementById('services-status').textContent.includes('HTTP services')`), 'services ready');
  await fs.writeFile('.zig-cache/catalog-ui/services.png', Buffer.from((await cdp('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  await view('sites');
  await cdp('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  assert.equal(await evaluate(`document.documentElement.scrollWidth <= innerWidth`), true, 'mobile page does not overflow');
  await fs.writeFile('.zig-cache/catalog-ui/mobile.png', Buffer.from((await cdp('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  assert.deepEqual(exceptions, []);
  console.log('catalog_ui: shared shell/style, tab history, file/log navigation, build control, focus, dirty edits and mobile layout passed');
} catch (e) {
  for (const child of children) console.error(child.output.slice(-5000));
  throw e;
} finally {
  socket?.close();
  for (const p of children.reverse()) {
    if (p.exitCode === null) { p.kill('SIGTERM'); await Promise.race([once(p, 'exit'), new Promise(r => setTimeout(r, 3000))]); if (p.exitCode === null) p.kill('SIGKILL'); }
  }
  await fs.rm(work, { recursive: true, force: true });
}