gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit4639caf74639caf7Report W61 theme startup blocker and day39 Style probemre4639caf7/tests/browser.mjs

135.8 KB

  1. // tests/browser.mjs — THE GATE of gitoria.worldapi.org (ticket #6: repos with their own address).
  2. // Its own gitoria server on its own storage, its OWN ident (a copy of ident's code without .env —
  3. // codes go to a mail sink, tests/identkit.mjs), real headless Chromes for everything visible.
  4. // `*.gitoria.test` is mapped to 127.0.0.1 inside Chrome (--host-resolver-rules), so a repo really
  5. // lives at http://<slug>.gitoria.test:<port>/ — the same mechanism as <slug>.gitoria.worldapi.org.
  6. //
  7. // node tests/browser.mjs (GITORIA_GATE_PORT server, default 8700; GITORIA_GATE_IDENT_PORT, default 8701;
  8. // GITORIA_GATE_CHROME "8702-8709" = Chrome debug ports)
  9. // Screenshots (390 / 1280 px) land in .scratch/gate-*.png. Every process started is stopped by PID.
  10. import { spawn, execFileSync } from 'node:child_process';
  11. import { request as httpRequest } from 'node:http';
  12. import { rmSync, mkdirSync, writeFileSync, existsSync, readdirSync, readFileSync } from 'node:fs';
  13. import { dirname, join, resolve } from 'node:path';
  14. import { fileURLToPath } from 'node:url';
  15. import { launchBrowser } from './cdp.mjs';
  16. import { launchFirefox } from './firefox.mjs';
  17. import { startIdent } from './identkit.mjs';
  18. import { startTickets } from './ticketskit.mjs';
  19. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  20. const HERE = dirname(fileURLToPath(import.meta.url));
  21. const APP = resolve(HERE, '..');
  22. const BIN = join(APP, 'bin/hybriel');
  23. const PORT = Number(process.env.GITORIA_GATE_PORT || 8700);
  24. const IDENT_PORT = Number(process.env.GITORIA_GATE_IDENT_PORT || 8701);
  25. const API = `http://127.0.0.1:${PORT}`; // node's view of the server
  26. const BASE = `http://gitoria.test:${PORT}`; // the browser's view: the main address
  27. // ident as the BROWSER sees it: same site as gitoria.test (the selector's fetch carries ident's Lax cookie only same-site)
  28. const IDENT_B = `http://ident.gitoria.test:${IDENT_PORT}`;
  29. const REPO = (slug) => `http://${slug}.gitoria.test:${PORT}`;
  30. const TICKETS_PORT = Number(process.env.GITORIA_GATE_TICKETS_PORT || 8702);
  31. const FIREFOX_PORT = Number(process.env.GITORIA_GATE_FIREFOX || 8699); // WebDriver BiDi port of the gate's Firefox
  32. const [CH_FROM, CH_TO] = (process.env.GITORIA_GATE_CHROME || '8703-8709').split('-').map(Number);
  33. process.env.HL_CHROME_ARGS = '--host-resolver-rules=MAP *.gitoria.test 127.0.0.1, MAP gitoria.test 127.0.0.1';
  34. const SCRATCH = join(APP, '.scratch');
  35. const STORE = join(SCRATCH, 'gate-store');
  36. const ORIGINS = ['alpha', 'beta-2', 'gamma'].map(x => `http://${x}.gitoria.test:${PORT}`).join(',');
  37. const TICKETS_DIR = process.env.GITORIA_GATE_TICKETS_DIR || [resolve(APP, '../tickets.worldapi.org'), '/media/STORAGE/projects/WorldAPI/tickets.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  38. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  39. rmSync(STORE, { recursive: true, force: true });
  40. mkdirSync(STORE, { recursive: true });
  41. // IW (creator 2026-10-24, "you removed the ident widget from all sites"): ident's <ident-selector> stands in the header, VISIBLE, top right — signed
  42. // out and signed in, on the phone and on the desktop. Returns 'ok' or what is wrong (hidden by an ancestor, no box, outside the viewport, not in the
  43. // header, not on the right, covered by something else).
  44. const SELECTOR_IN_HEADER = `(() => { const s = document.querySelector('application-header ident-selector'); if (!s) return 'no ident-selector in the header';
  45. for (let e = s; e && e !== document.documentElement; e = e.parentElement) { const c = getComputedStyle(e); if (c.display === 'none') return 'display:none on ' + e.tagName; if (c.visibility === 'hidden') return 'visibility:hidden on ' + e.tagName; if (+c.opacity === 0) return 'opacity 0 on ' + e.tagName; }
  46. const b = s.getBoundingClientRect(), h = document.querySelector('application-header').getBoundingClientRect();
  47. if (b.width < 40 || b.height < 30) return 'no box ' + b.width + 'x' + b.height;
  48. if (b.left < 0 || b.top < 0 || b.right > innerWidth + 0.5 || b.bottom > innerHeight) return 'outside the viewport ' + JSON.stringify([b.left, b.top, b.right, b.bottom]);
  49. if (b.top < h.top - 1 || b.bottom > h.bottom + 1) return 'not inside the header row ' + JSON.stringify([b.top, b.bottom, h.top, h.bottom]);
  50. if (b.left + b.width / 2 < innerWidth / 2) return 'not at the top right ' + b.left;
  51. const top = document.elementFromPoint(b.left + b.width / 2, b.top + b.height / 2); if (!top || !top.closest('ident-selector')) return 'covered by ' + (top && top.tagName);
  52. return 'ok'; })()`;
  53. let failures = 0, passes = 0;
  54. function check(label, ok, detail = '') {
  55. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  56. if (ok) passes++; else failures++;
  57. }
  58. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  59. const J = JSON.stringify;
  60. const XSS = '</script><b id="xss">x</b><script>window.__xss=1</script>';
  61. let log = '';
  62. let server = null, ident = null, tickets = null, ff = null;
  63. const browsers = [];
  64. function startServer(extraEnv = {}) {
  65. log += '\n==== gitoria server start\n';
  66. server = spawn(BIN, ['project.hl'], {
  67. cwd: APP,
  68. env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_WATCH: '0', GITORIA_GIT: join(STORE, 'git'),
  69. GITORIA_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, ...extraEnv },
  70. stdio: ['ignore', 'pipe', 'pipe'],
  71. });
  72. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  73. }
  74. async function serverUp() {
  75. for (let i = 0; i < 480; i++) { try { const r = await fetch(API + '/api/repos'); if (r.ok) return; } catch {} await sleep(250); }
  76. throw new Error('gitoria did not come up\n' + log);
  77. }
  78. async function stopServer() {
  79. if (!server) return;
  80. try { server.kill('SIGTERM'); } catch {}
  81. await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });
  82. server = null;
  83. }
  84. const SLOW = Number(process.env.GITORIA_GATE_SLOW || 3);
  85. function patient(page) {
  86. const waitFor = page.waitFor.bind(page);
  87. page.waitFor = (expr, o = {}) => waitFor(expr, { ...o, timeout: (o.timeout || 10000) * SLOW });
  88. const goto = page.goto.bind(page);
  89. page.goto = (url, o = {}) => goto(url, { ...o, timeout: (o.timeout || 15000) * SLOW });
  90. return page;
  91. }
  92. async function newPage() {
  93. const b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  94. browsers.push(b);
  95. return patient(await b.newPage());
  96. }
  97. async function viewport(page, width, height) {
  98. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  99. await sleep(250);
  100. }
  101. async function shot(page, name) {
  102. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  103. writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64'));
  104. }
  105. const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  106. const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'page hydrated' });
  107. const txt = (page, sel) => page.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || null`);
  108. const has = (page, sel) => page.evaluate(`!!document.querySelector(${J(sel)})`);
  109. // THE SHELL (gitoria#23, the theme's header): "Log out" sits in the user menu's dropdown, and on a phone "Log in with ident" sits in
  110. // the ident dropdown — a person opens the dropdown first. When the target already shows (the login button in the header from
  111. // 60rem, the old shell) it is clicked straight away.
  112. const shows = (page, sel) => page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);
  113. async function clickInMenu(page, sel, toggle) {
  114. await page.waitForSelector(sel);
  115. if (!(await shows(page, sel)) && await has(page, toggle)) {
  116. await page.click(toggle);
  117. await page.waitFor(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`, { label: 'menu open for ' + sel });
  118. }
  119. await page.click(sel);
  120. }
  121. const MEASURE = readFileSync(join(HERE, 'mobile-measure.js'), 'utf8');
  122. // INSIDE ident's selector (shadow DOM): an expression over its root `r`, and a REAL click (as in tickets' gate)
  123. const sh = (expr) => `(() => { const h = document.querySelector('#selector'); const r = h && h.shadowRoot; if (!r) return null; return (${expr}); })()`;
  124. async function shClick(page, inner, name = null) {
  125. const find = `(() => { const h = document.querySelector('#selector'); const r = h && h.shadowRoot; if (!r) return null; const el = ${name === null ? `r.querySelector(${J(inner)})` : `[...r.querySelectorAll(${J(inner)})].find(b => b.textContent === ${J(name)})`}; if (!el) return null; el.scrollIntoView({ block: 'center' }); const b = el.getBoundingClientRect(); if (!b.width) return null; return { x: b.left + b.width / 2, y: b.top + b.height / 2 }; })()`;
  126. const box = await page.waitFor(find, { label: 'selector ' + inner + ' ' + (name || '') });
  127. const at = { x: Math.round(box.x), y: Math.round(box.y), button: 'left', clickCount: 1 };
  128. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...at, buttons: 0 });
  129. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...at, buttons: 1 });
  130. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, buttons: 0 });
  131. }
  132. async function identSignIn(page, email) {
  133. await page.goto(IDENT_B + '/');
  134. await page.waitForSelector('#email');
  135. await hydrated(page);
  136. await page.type('#email', email);
  137. await page.click('#sendcode');
  138. // ident#20: a sent code NAVIGATES to ident's /code page; type only once that page is hydrated
  139. await page.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident /code page' });
  140. await hydrated(page);
  141. await page.type('#code', ident.lastCode(email));
  142. await page.click('#verify');
  143. await page.waitForSelector('#signout, #menusignout', { timeout: 10000 });
  144. }
  145. // the plain LOGIN LINK (ident's /login with the app key and the callback — the header has no button for it since 2026-10-24, the selector is the way
  146. // in, but the old way is still served): opened as the button's link did → ident's "choose an identity" → back to the main address
  147. let LOGIN_URL = null;
  148. async function buttonLogin(page) {
  149. await page.goto(LOGIN_URL);
  150. await page.waitForSelector('#chooselist', { timeout: 10000 });
  151. await hydrated(page);
  152. await page.click('#chooselist li:nth-child(1) .choose');
  153. }
  154. async function nameIt(page, name) {
  155. await page.waitForSelector('#nameform');
  156. await hydrated(page);
  157. await page.type('#displayname', name);
  158. await page.click('#namesave');
  159. await page.waitFor('!document.querySelector("#nameform")', { label: 'name saved' });
  160. }
  161. async function createRepo(page, slug, description) {
  162. await page.evaluate('document.querySelector("#slug").value = ""; document.querySelector("#description").value = ""');
  163. await page.type('#slug', slug);
  164. if (description) await page.type('#description', description);
  165. await page.click('#createsave');
  166. }
  167. // the FIRST HTML of a page as the server sends it, for any Host (node's fetch cannot set Host) — gitoria#16
  168. const firstHtml = (path, host, cookie) => new Promise((res, rej) => {
  169. const rq = httpRequest({ host: '127.0.0.1', port: PORT, path, headers: { host, ...(cookie ? { cookie } : {}) } }, (r) => {
  170. let b = ''; r.setEncoding('utf8'); r.on('data', d => b += d); r.on('end', () => res({ status: r.statusCode, headers: r.headers, body: b }));
  171. });
  172. rq.on('error', rej); rq.end();
  173. });
  174. const bodyText = (html) => ((html.match(/<body>([\s\S]*)<\/body>/) || [])[1] || '').replace(/<script[\s\S]*?<\/script>/g, '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ');
  175. const emitFace = async (event, payload, cookie) => {
  176. const r = await fetch(API + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: 1, event, payload }) });
  177. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  178. return { status: r.status, raw: t, value: j && j.value };
  179. };
  180. try {
  181. // ---- our own ident; gitoria is registered with ONE origin: the main address ------------------------
  182. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  183. const alice = await ident.signIn('[email protected]');
  184. const gateAcct = await ident.signIn('[email protected]');
  185. const APPKEY = await ident.registerApp(alice, 'gitoria (gate)', [BASE, `http://*.gitoria.test:${PORT}`]); // the main address AND every repo address (ident's wildcard origin)
  186. LOGIN_URL = `${IDENT_B}/login?key=${APPKEY.key}&return=${encodeURIComponent(BASE + '/login/callback')}`;
  187. check('ident: our own ident runs (a copy without .env), gitoria is registered', /^pk_[0-9a-f]{32}$/.test(APPKEY.key) && !existsSync(join(STORE, 'ident', 'ident-code', '.env')));
  188. // our own tickets (a copy without .env), with a token for its user "gitoria" — gitoria opens tickets with it
  189. tickets = await startTickets({ ticketsDir: TICKETS_DIR, workDir: join(STORE, 'tickets'), port: TICKETS_PORT, ident, who: alice, origins: ORIGINS });
  190. check('tickets: our own tickets runs (a copy without .env), gitoria has an API token', /^tkt_[0-9a-f]{48}$/.test(tickets.token) && !existsSync(join(STORE, 'tickets', 'tickets-code', '.env')));
  191. const env = { IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret, GITORIA_TICKETS_URL: tickets.base };
  192. startServer(env);
  193. await serverUp();
  194. // ---- the API (reads are public) --------------------------------------------------------------
  195. let r = await fetch(API + '/api/repos');
  196. check('api: GET /api/repos is empty at the start', r.status === 200 && J(await r.json()) === '{"repos":[]}');
  197. r = await fetch(API + '/api/repos', { method: 'POST', body: '{}' });
  198. check('api: POST /api/repos without a token → 401 (creating needs a gtr_ token; gate tests/create-api.mjs)', r.status === 401);
  199. r = await fetch(API + '/api/repos/nothing');
  200. check('api: unknown repo → 404', r.status === 404);
  201. r = await fetch(API + '/api/repos', { headers: { accept: 'text/markdown' } });
  202. check('api: Markdown read view of the list', /text\/markdown/.test(r.headers.get('content-type')) && /^# Repositories \(0\)/.test(await r.text()));
  203. // mission 010 (hybriel#197): the menu marker is in the SERVER'S HTML (a plain fetch, no script): aria-current="page" on the "Repositories" links (header and phone sidebar), on every page.
  204. // gitoria's one item links to the MAIN address (absolute href, so a repo address links back), and /code, /pulls … are not below '/': the route cannot tell, `current = true` stays.
  205. for (const p of ['/', '/code', '/pulls', '/releases']) {
  206. const h = await (await fetch(API + p, { headers: { accept: 'text/html' } })).text();
  207. const marks = [...h.matchAll(/<a [^>]*aria-current="page"[^>]*>/g)];
  208. check('server HTML ' + p + ': the menu marks Repositories (aria-current="page", class current) before any script runs', marks.length >= 1 && marks.every(m => /class="current"/.test(m[0])), J(marks.map(m => m[0])));
  209. }
  210. // ---- the login button's server half: where does ?next= lead? ------------------------------------
  211. const cbCookie = 'gitoriasid=' + 'ab'.repeat(16);
  212. // a failed login is a PAGE now (components/loginfailed.hl, gitoria#16): the reason is parked in the session → /login/failed
  213. const failedPage = async (url) => {
  214. const c = await fetch(url, { redirect: 'manual' });
  215. const ck = (c.headers.get('set-cookie') || '').split(';')[0];
  216. const pg = await firstHtml('/login/failed', `gitoria.test:${PORT}`, ck);
  217. return { status: c.status, location: c.headers.get('location'), cookie: ck, page: bodyText(pg.body), pageStatus: pg.status };
  218. };
  219. let lf = await failedPage(API + '/login/callback');
  220. check('login: /login/callback without a code → /login/failed says "ident sent no login code"', lf.status === 302 && lf.location === '/login/failed' && lf.pageStatus === 200 && /Login failed/.test(lf.page) && /ident sent no login code/.test(lf.page), J(lf));
  221. lf = await failedPage(API + '/login/callback?ident_code=' + 'ab'.repeat(24));
  222. check('login: an unknown code → /login/failed says "ident refused"', lf.status === 302 && lf.location === '/login/failed' && /ident refused/.test(lf.page), J(lf));
  223. const nexts = [
  224. ['/', '/'], ['/x?y=1', '/x?y=1'], [REPO('alpha') + '/code', REPO('alpha') + '/code'], [REPO('alpha') + '/', REPO('alpha') + '/'], [REPO('alpha'), REPO('alpha') + '/'],
  225. ['//evil.example', '/'], ['http://evil.example/', '/'], [REPO('www') + '/', '/'], [`http://alpha.gitoria.test:${PORT}.evil.example/`, '/'],
  226. [REPO('alpha') + '/a b', '/'], [REPO('a--b') + '/', '/'], [REPO('Alpha') + '/', '/'], ['/x\r\nSet-Cookie: a=b', '/'], ['/login/callback', '/'], ['', '/'],
  227. [`https://alpha.gitoria.test:${PORT}/`, '/'], [`http://x.y.gitoria.test:${PORT}/`, '/'],
  228. ];
  229. let allNext = true, nextDetail = '';
  230. for (const [want, expect] of nexts) {
  231. const code = await ident.selectorCode(gateAcct, APPKEY, BASE);
  232. const c = await fetch(API + '/login/callback?next=' + encodeURIComponent(want) + '&ident_code=' + code, { redirect: 'manual' });
  233. const loc = c.headers.get('location');
  234. if (c.status !== 302 || loc !== expect) { allNext = false; nextDetail += ` [${J(want)} → ${c.status} ${loc}, wanted ${expect}]`; }
  235. }
  236. check('login: ?next= accepts a path or a valid repo address, everything else → /', allNext, nextDetail);
  237. const cookieCode = await ident.selectorCode(gateAcct, APPKEY, BASE);
  238. const cc = await fetch(API + '/login/callback?ident_code=' + cookieCode, { redirect: 'manual' });
  239. const setCookie = cc.headers.get('set-cookie') || '';
  240. check('login: the session cookie is shared by every repo address (Domain=.gitoria.test)', /^gitoriasid=[0-9a-f]{32};/.test(setCookie) && /Domain=\.gitoria\.test/.test(setCookie) && /HttpOnly/.test(setCookie), setCookie);
  241. // ---- the re-vendored Hybriel (mission 033): what the dropped local patches did is upstream now ------------
  242. r = await fetch(API + '/__hl/app.css');
  243. const css = await r.text();
  244. check('styles: /__hl/app.css is 200 and the token file\'s var() tokens are in :root and used (hybriel#39 upstream)', r.status === 200 && /:root\s*\{[^}]*--dark\s*:/.test(css) && /var\(--/.test(css), css.slice(0, 200));
  245. // ---- forged face session: nobody logged in may create --------------------------------------------
  246. let f = await emitFace('gitoriaCreate', ['forged', '', { user: { id: 'x' } }]);
  247. check('face: a forged trailing session argument creates nothing', !(await (await fetch(API + '/api/repos/forged')).ok) && !(f.value && f.value.repo), f.raw);
  248. f = await emitFace('gitoriaCreate', ['anon', '']);
  249. check('face: not logged in → refused with a message', f.value && /log in/.test(f.value.error || ''), f.raw);
  250. // ---- A = alice in a browser -----------------------------------------------------------------------
  251. const A = await newPage();
  252. await identSignIn(A, '[email protected]');
  253. await A.goto(BASE + '/');
  254. await A.waitFor('!!document.querySelector("#heading")', { label: 'main address shows the list' });
  255. await hydrated(A);
  256. check('main address: "Repositories", empty list, hint to log in, no create form', (await txt(A, '#heading')) === 'Repositories' && (await has(A, '#empty')) && (await has(A, '#loginhint')) && !(await has(A, '#createform')));
  257. check('signed out: the selector stands alone in the header — NO second "Log in with ident" button next to it (creator 2026-10-24)', await A.evaluate(`!!document.querySelector('application-header > ident-selector#selector') && !document.querySelector('#loginbutton') && !document.querySelector('a[href*="/login?key="]') && ![...document.querySelectorAll('application-header a, application-header button')].some(e => /log in with ident/i.test(e.textContent))`));
  258. await buttonLogin(A);
  259. await A.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector("#nameform")`, { label: 'A back with the name prompt' });
  260. check('button: back on the main address, logged in, asked for a display name', await has(A, '#whoami') && !(await has(A, '#loginbutton')));
  261. await nameIt(A, 'alice');
  262. await A.waitForSelector('#createform');
  263. check('named: the "create a repository" form appears', (await txt(A, '#whoami')) === 'alice');
  264. // ---- B = a signed-out viewer of the main address, for the live list ---------------------------------
  265. const B = await newPage();
  266. await B.goto(BASE + '/');
  267. await B.waitForSelector('#empty');
  268. await hydrated(B);
  269. // ---- create ---------------------------------------------------------------------------------------
  270. const errAfter = async (slug, want) => {
  271. await createRepo(A, slug, '');
  272. await A.waitFor(`new RegExp(${J(want)}).test(document.querySelector("#createerror").textContent)`, { label: 'error for ' + slug });
  273. const e = await txt(A, '#createerror');
  274. check(`create: "${slug}" is refused — ${want}`, new RegExp(want).test(e), e);
  275. return e;
  276. };
  277. await errAfter('Bad Slug', 'only have lowercase');
  278. await errAfter('www', 'reserved');
  279. await errAfter('ab-', 'starts and ends');
  280. await errAfter('ab--cd', 'two hyphens');
  281. await errAfter('-abc', 'starts and ends');
  282. check('create: nothing was stored by the refusals', J(await (await fetch(API + '/api/repos')).json()) === '{"repos":[]}');
  283. await A.evaluate('document.querySelector("#createerror").textContent = ""');
  284. await createRepo(A, 'alpha', 'The first repository');
  285. await A.waitForSelector('#created');
  286. check('create: "alpha" is created, the page says so and links to its address', /alpha/.test(await txt(A, '#created')) && (await A.evaluate('document.querySelector("#createdlink").href')) === REPO('alpha') + '/');
  287. check('create: the list shows alpha with description, owner alice and time', await A.evaluate(`(() => { const li = document.querySelector('#repos li'); return !!li && /alpha/.test(li.textContent) && /The first repository/.test(li.textContent) && /alice/.test(li.textContent) && /\\d{4}-\\d\\d-\\d\\d \\d\\d:\\d\\d/.test(li.textContent) && li.querySelector('a').href === ${J(REPO('alpha') + '/')}; })()`), await A.evaluate('document.querySelector("#repos li").outerHTML'));
  288. await B.waitFor('document.querySelectorAll("#repos li").length === 1', { label: 'B sees alpha live' });
  289. check('live: the signed-out viewer B sees alpha without a reload', /alpha/.test(await txt(B, '#repos')) && !(await has(B, '#empty')));
  290. await errAfter('alpha', 'taken');
  291. await A.evaluate('document.querySelector("#createerror").textContent = ""');
  292. await createRepo(A, 'beta-2', '');
  293. await A.waitFor('document.querySelectorAll("#repos li").length === 2', { label: 'A: two repos' });
  294. await B.waitFor('document.querySelectorAll("#repos li").length === 2', { label: 'B: two repos' });
  295. check('create: a second repo (with a hyphen) and the list is newest first', (await A.evaluate('[...document.querySelectorAll("#repos .slug")].map(a => a.textContent).join()')) === 'beta-2,alpha');
  296. r = await fetch(API + '/api/repos/alpha');
  297. const alphaRow = await r.json();
  298. check('api: GET /api/repos/alpha = slug, description, owner, address', alphaRow.slug === 'alpha' && alphaRow.description === 'The first repository' && alphaRow.owner === 'alice' && alphaRow.address === REPO('alpha') + '/' && /^[0-9a-z]{12}$/.test(alphaRow.id), J(alphaRow));
  299. r = await fetch(API + '/api/repos/alpha', { headers: { accept: 'text/markdown' } });
  300. const md = await r.text();
  301. check('api: Markdown read view of a repo', /^# alpha\n/.test(md), md);
  302. // ---- the address: <slug>.gitoria.test ------------------------------------------------------------------
  303. await A.goto(REPO('alpha') + '/');
  304. await A.waitFor('!!document.querySelector("#reponame")', { label: 'alpha at its own address' });
  305. check('alpha.<domain> shows that repo: name, description, address, owner', (await txt(A, '#reponame')) === 'alpha' && (await txt(A, '#repodescription')) === 'The first repository' && (await txt(A, '#repoaddress')) === REPO('alpha') + '/' && (await txt(A, '#repoowner')) === 'alice' && !(await has(A, '#createform')), await A.evaluate('document.querySelector("repo-home").innerText'));
  306. check('alpha.<domain>: the login is shared with the main address (same cookie)', (await txt(A, '#whoami')) === 'alice');
  307. check('alpha.<domain>: the title is the repo page, tab title set', (await A.evaluate('document.title')) !== '');
  308. await A.goto(REPO('nothing-here') + '/');
  309. await A.waitFor('!!document.querySelector("#missing")', { label: 'unknown address' });
  310. check('an address nobody created → "No such repository" with a link to the main address', (await txt(A, '#missing')) === 'No such repository' && (await A.evaluate('document.querySelector("#toall").href')) === BASE + '/');
  311. await A.goto(REPO('www') + '/');
  312. await A.waitFor('!!document.querySelector("#missing")', { label: 'reserved address' });
  313. check('a reserved address is no repo either', true);
  314. await A.goto(BASE + '/');
  315. await A.waitFor('!!document.querySelector("#repos li")', { label: 'back on main' });
  316. await A.click('#repos li:nth-child(2) .slug');
  317. await A.waitFor(`location.hostname === 'alpha.gitoria.test' && !!document.querySelector("#reponame")`, { label: 'click on alpha' });
  318. check('clicking a repo in the list opens its own address', (await txt(A, '#reponame')) === 'alpha');
  319. // ---- login FROM a repo address: through the main address and back --------------------------------------
  320. await identSignIn(B, '[email protected]');
  321. await B.goto(REPO('alpha') + '/');
  322. await B.waitFor('!!document.querySelector("#reponame")', { label: 'B at alpha' });
  323. check('signed out at alpha.<domain>: repo visible, the SAME selector in the header as on the main address (not hidden), no "Log in with ident" button', (await has(B, '#selector')) && !(await has(B, '#loginbutton')) && !(await has(B, '#whoami')) && (await B.evaluate(SELECTOR_IN_HEADER)) === 'ok', await B.evaluate(SELECTOR_IN_HEADER));
  324. await hydrated(B);
  325. await B.evaluate('window.__repoMarker = 5');
  326. await shClick(B, '#choose');
  327. await B.waitFor(sh(`r.querySelectorAll('[part~="identity"]').length > 0`), { label: 'B: selector list at alpha' });
  328. await shClick(B, '[part~="identity"]', 'Default');
  329. await B.waitFor('!!document.querySelector("#whoami")', { label: 'B logged in at alpha by the selector' });
  330. check('login ON alpha.<domain> by the selector (ident answers the repo address through the wildcard origin): no reload, still at alpha, logged in', (await B.evaluate('window.__repoMarker')) === 5 && (await B.evaluate('location.href')) === REPO('alpha') + '/' && /logged in with/.test(await B.evaluate(`document.querySelector('#selector').shadowRoot.textContent`)), await B.evaluate('location.href + " " + document.body.innerText.slice(0, 200)'));
  331. await B.waitFor('!!document.querySelector("#reponame")', { label: 'B: the repo page after the login' });
  332. check('…the repo page follows: alice (named by the prompt or not) is the user of the session', (await txt(B, '#whoami')) === 'alice' || !!(await has(B, '#nameform')), await B.evaluate('location.href + " " + document.body.innerText.slice(0, 300)'));
  333. if (await has(B, '#nameform')) await nameIt(B, 'alice');
  334. await B.goto(BASE + '/');
  335. await B.waitForSelector('#createform');
  336. check('the same login holds on the main address (cookie for all addresses)', (await txt(B, '#whoami')) === 'alice');
  337. // ---- the homepage of a repo (ticket #8): README.md, or the $docs folder --------------------------------------
  338. check('a new repo has an empty bare git repository', existsSync(join(STORE, 'git', 'alpha.git', 'HEAD')), J(existsSync(join(STORE, 'git'))));
  339. const pushFiles = (slug, files) => { // a commit into the bare repo, the way a push would leave it
  340. const work = join(STORE, 'work-' + slug);
  341. rmSync(work, { recursive: true, force: true }); mkdirSync(work, { recursive: true });
  342. const git = (...a) => execFileSync('git', ['-C', work, '-c', 'user.name=t', '-c', '[email protected]', ...a], { stdio: 'pipe' });
  343. git('init', '-q', '-b', 'main');
  344. for (const [p, c] of Object.entries(files)) { mkdirSync(dirname(join(work, p)), { recursive: true }); writeFileSync(join(work, p), c); }
  345. git('add', '-A'); git('commit', '-q', '-m', 'files');
  346. git('push', '-q', '-f', join(STORE, 'git', slug + '.git'), 'main');
  347. };
  348. const homeText = async (p) => { await p.waitFor('!document.querySelector("#docsloading") && (!!document.querySelector("#homepage") || !!document.querySelector("#nohomepage"))', { label: 'homepage answer' }); return await p.evaluate('document.body.innerText'); };
  349. await A.goto(REPO('alpha') + '/');
  350. check('an empty repo says it has no README.md yet', /no README\.md yet/.test(await homeText(A)));
  351. pushFiles('alpha', {
  352. 'README.md': '# Alpha project\n\nSome **strong** and *soft* text with `code` and a [link](https://example.org/x).\n\n- one\n- two\n\n> quoted words\n\n| Name | Value |\n|---|---|\n| a | 1 |\n| b | 2 |\n\n---\n\n```\nlet x = 1 < 2\n```\n\n<script>window.__pwned = 1</script>\n\n[bad](javascript:alert(1))\n',
  353. 'docs/other.md': '# not the homepage\n',
  354. });
  355. await A.goto(REPO('alpha') + '/');
  356. const alphaText = await homeText(A);
  357. check('/ shows README.md as HTML: heading, strong, list, quote, table, rule, code block', await A.evaluate(`(() => { const m = document.querySelector('#homepage markdown-text'); return !!m && m.querySelector('h2')?.textContent === 'Alpha project' && m.querySelector('strong')?.textContent === 'strong' && m.querySelectorAll('ul li').length === 2 && m.querySelector('blockquote')?.textContent.trim() === 'quoted words' && m.querySelectorAll('table tr').length === 3 && m.querySelector('td')?.textContent === 'a' && !!m.querySelector('hr') && m.querySelector('pre code')?.textContent === 'let x = 1 < 2'; })()`), alphaText.slice(0, 400));
  358. check('README links are real links; javascript: and raw HTML stay text', await A.evaluate(`(() => { const m = document.querySelector('#homepage markdown-text'); return m.querySelector('a').getAttribute('href') === 'https://example.org/x' && !m.querySelector('script') && !window.__pwned && m.textContent.includes('<script>window.__pwned = 1</script>') && m.textContent.includes('[bad](javascript:alert(1))') && ![...m.querySelectorAll('a')].some(a => /javascript/.test(a.getAttribute('href'))); })()`));
  359. pushFiles('alpha', {
  360. 'README.md': '# Root readme\n',
  361. '$docs/b-second.md': '# Second doc\n\nText two.\n',
  362. '$docs/a-first.md': '# First doc\n\nText one.\n',
  363. '$docs/sub/c-third.md': '## Third doc\n',
  364. '$docs/notes.txt': 'not markdown\n',
  365. });
  366. await A.goto(REPO('alpha') + '/');
  367. await homeText(A);
  368. check('with a $docs folder its Markdown files form the homepage (in path order), the root README does not', await A.evaluate(`(() => { const h = [...document.querySelectorAll('#homepage h2, #homepage h3')].map(x => x.textContent).join('|'); return h === 'First doc|Second doc|Third doc' && !document.body.innerText.includes('Root readme') && !document.body.innerText.includes('not markdown'); })()`), await A.evaluate('document.body.innerText.slice(0, 400)'));
  369. check('the homepage of another repo is untouched (beta-2 has no README.md)', await (async () => { await A.goto(REPO('beta-2') + '/'); return /no README\.md yet/.test(await homeText(A)); })());
  370. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  371. await viewport(A, w, h);
  372. pushFiles('beta-2', { 'README.md': '# Wide table\n\n| a | b | c | d | e | f | g | h |\n|---|---|---|---|---|---|---|---|\n| aaaaaaaaaaaaaaa | bbbbbbbbbbbbbbbbb | cccccccccccccccccc | ddddddddddddddd | eeeeeeeeeeeeeee | ffffffffffffffff | ggggggggggggggg | hhhhhhhhhhhhhhh |\n\nhttps://example.org/a/very/long/url/that/should/wrap/somewhere/because/it/is/really/quite/long/indeed\n' });
  373. await A.goto(REPO('beta-2') + '/');
  374. await homeText(A);
  375. check(`layout ${w}px: the homepage has no horizontal overflow`, await noOverflow(A));
  376. await shot(A, `${name}-home`);
  377. }
  378. // ---- browsing code (ticket #9): /code, /branch/<name>, /commit/<id> ------------------------------------------
  379. const gitIn = (work, ...a) => execFileSync('git', ['-C', work, '-c', 'user.name=t', '-c', '[email protected]', ...a], { stdio: 'pipe' }).toString();
  380. const work = join(STORE, 'work-code');
  381. rmSync(work, { recursive: true, force: true }); mkdirSync(join(work, 'src', 'deep'), { recursive: true });
  382. gitIn(work, 'init', '-q', '-b', 'main');
  383. writeFileSync(join(work, 'README.md'), '# Code repo\n');
  384. writeFileSync(join(work, 'src', 'a.txt'), 'line one\n\n indented <b>&amp;</b>\n');
  385. writeFileSync(join(work, 'src', 'deep', 'b.txt'), 'deep file\n');
  386. writeFileSync(join(work, 'my file.txt'), 'spaced name\n');
  387. writeFileSync(join(work, 'bin.dat'), Buffer.from([0, 1, 2, 255, 0, 254, 0, 0]));
  388. gitIn(work, 'add', '-A'); gitIn(work, 'commit', '-q', '-m', 'first commit');
  389. const firstSha = gitIn(work, 'rev-parse', 'HEAD').trim();
  390. writeFileSync(join(work, 'src', 'a.txt'), 'main changed\n');
  391. gitIn(work, 'commit', '-qam', 'second on main');
  392. const mainSha = gitIn(work, 'rev-parse', 'HEAD').trim();
  393. gitIn(work, 'checkout', '-q', '-b', 'feature/x', firstSha);
  394. writeFileSync(join(work, 'src', 'a.txt'), 'feature changed\n');
  395. writeFileSync(join(work, 'only-feature.txt'), 'f\n');
  396. gitIn(work, 'add', '-A'); gitIn(work, 'commit', '-q', '-m', 'feature work');
  397. gitIn(work, 'checkout', '-q', '-b', 'dev', firstSha);
  398. gitIn(work, 'push', '-q', '-f', join(STORE, 'git', 'alpha.git'), 'main', 'feature/x', 'dev');
  399. const codeReady = (p) => p.waitFor('!document.querySelector("#codeloading") && (!!document.querySelector("#codemessage") || !!document.querySelector("#codefile") || !!document.querySelector("#entries") || !!document.querySelector("#noentries"))', { label: 'code answer' });
  400. const names = (p, sel) => p.evaluate(`[...document.querySelectorAll(${J(sel)})].map(x => x.textContent.trim()).join('|')`);
  401. await viewport(A, 1280, 900);
  402. await A.goto(REPO('alpha') + '/code');
  403. await codeReady(A);
  404. check('/code: the main branch at its last commit (tree: folder first, then files)', await txt(A, '#coderef') === 'main' && (await names(A, '#entries li > :first-child')) === 'src|README.md|bin.dat|my file.txt' && (await txt(A, '#commitsubject')) === 'second on main' && (await txt(A, '#commitlink')) === mainSha.slice(0, 8), await A.evaluate('document.body.innerText.slice(0, 500)'));
  405. check('/code: latest commits and branches are listed, the main branch marked', (await names(A, '#commits a')) === mainSha.slice(0, 8) + '|' + firstSha.slice(0, 8) && (await names(A, '#branches li > :first-child')) === 'dev|feature/x|main' && /main branch/.test(await txt(A, '#branches')), await A.evaluate('document.querySelector("#branches").innerText'));
  406. await A.click('#entries a.dir');
  407. await A.waitFor('location.pathname === "/code/src" && !!document.querySelector("#crumbs strong") && document.querySelector("#crumbs strong").textContent === "src" && !!document.querySelector("#entries")', { label: 'folder opened' });
  408. check('a folder link opens the folder (client navigation), crumbs show the path', (await A.evaluate('location.pathname')) === '/code/src' && (await names(A, '#entries li > :first-child')) === 'deep|a.txt' && (await names(A, '#crumbs a, #crumbs strong')) === 'main|src', await A.evaluate('location.pathname + " " + document.body.innerText.slice(0, 300)'));
  409. await A.goto(REPO('alpha') + '/code/src/a.txt');
  410. await codeReady(A);
  411. check('/code/<file>: numbered lines with the exact text (HTML stays text, blank lines kept)', await A.evaluate(`(() => { const li = [...document.querySelectorAll('#lines li')]; return li.length === 1 && li[0].textContent === 'main changed'; })()`), await A.evaluate('document.body.innerText.slice(0, 300)'));
  412. await A.goto(REPO('alpha') + '/commit/' + firstSha + '/src/a.txt');
  413. await codeReady(A);
  414. check('/commit/<id>/<file>: the file as it was at that commit', await A.evaluate(`[...document.querySelectorAll('#lines li')].map(l => l.textContent).join('|')`) === 'line one|| indented <b>&amp;</b>' && (await txt(A, '#codekind')) === 'Commit' && !(await has(A, '#lines script')), await A.evaluate('document.body.innerText.slice(0, 300)'));
  415. await A.goto(REPO('alpha') + '/commit/' + firstSha.slice(0, 7));
  416. await codeReady(A);
  417. check('/commit/<short id>: the whole project at that commit (an old tree, no later file)', (await names(A, '#entries li > :first-child')) === 'src|README.md|bin.dat|my file.txt' && (await txt(A, '#commitsubject')) === 'first commit' && (await txt(A, '#coderef')) === firstSha.slice(0, 8), await A.evaluate('document.body.innerText.slice(0, 300)'));
  418. await A.goto(REPO('alpha') + '/branch/feature/x');
  419. await codeReady(A);
  420. check('/branch/<name with a slash>: that branch at its last commit', (await txt(A, '#coderef')) === 'feature/x' && (await names(A, '#entries li > :first-child')) === 'src|README.md|bin.dat|my file.txt|only-feature.txt' && (await txt(A, '#commitsubject')) === 'feature work', await A.evaluate('document.body.innerText.slice(0, 300)'));
  421. await A.goto(REPO('alpha') + '/branch/feature/x/src/a.txt');
  422. await codeReady(A);
  423. check('/branch/<name>/<file>: the file on that branch', (await names(A, '#lines li')) === 'feature changed', await A.evaluate('document.body.innerText.slice(0, 300)'));
  424. await A.goto(REPO('alpha') + '/code/my%20file.txt');
  425. await codeReady(A);
  426. check('a file with a space in its name opens', (await names(A, '#lines li')) === 'spaced name');
  427. await A.goto(REPO('alpha') + '/code/bin.dat');
  428. await codeReady(A);
  429. check('a binary file is not shown as text', (await has(A, '#binary')) && !(await has(A, '#lines li')));
  430. for (const [path, want] of [['/code/nope', /No such path/], ['/branch/nobranch', /no branch 'nobranch'/], ['/commit/deadbeef', /No commit 'deadbeef'/], ['/commit/zz', /No such commit/], ['/code/src/nope/deeper', /No such path/]]) {
  431. await A.goto(REPO('alpha') + path);
  432. await codeReady(A);
  433. check(`${path}: a plain message, no crash`, want.test(await txt(A, '#codemessage') || ''), await A.evaluate('document.body.innerText.slice(0, 200)'));
  434. }
  435. await A.goto(BASE + '/');
  436. await A.waitForSelector('#createform');
  437. await hydrated(A);
  438. await createRepo(A, 'gamma', XSS);
  439. await A.waitFor('!!document.querySelector("#created")', { label: 'gamma created' });
  440. await A.goto(REPO('gamma') + '/code');
  441. await codeReady(A);
  442. check('an empty repo says it has no commits yet', /no commits yet/.test(await txt(A, '#codemessage') || ''), await A.evaluate('document.body.innerText.slice(0, 200)'));
  443. // "Add code to this repository" (gitoria#20): stands as plain text, not a collapsible, ONLY on the Code page of an
  444. // empty repo (gamma) — checked on every tab of an empty repo AND a filled one (alpha, has commits)
  445. check('empty repo /code: "Add code to this repository" stands as plain text (no <details>, no <summary>)', (await has(A, '#addcode')) && (await A.evaluate('document.querySelector("#addcode").tagName')) !== 'DETAILS' && !(await has(A, '#addcode summary')) && (await A.evaluate('!!document.querySelector("#clonecommand").offsetParent')), await A.evaluate('document.querySelector("#addcode") ? document.querySelector("#addcode").outerHTML.slice(0, 150) : "missing"'));
  446. const addCodeTabs = [['/', '#nohomepage, #homepage'], ['/pulls', '#pullsmessage, #pullshelp'], ['/releases', '#releasesmessage, #releaseshelp'], ['/tickets', '#ticketsnotconnected, #ticketlist'], ['/settings', '#connecttickets, #notconnected']];
  447. for (const [p, sel] of addCodeTabs) {
  448. await A.goto(REPO('gamma') + p);
  449. await A.waitFor(`!!document.querySelector(${J(sel)})`, { label: 'gamma ' + p + ' for addcode check' });
  450. check(`empty repo ${p}: no "Add code" box (only the Code page has it)`, !(await has(A, '#addcode')), await A.evaluate('document.body.innerText.slice(0, 150)'));
  451. }
  452. for (const [p, sel] of [['/code', '#entries, #codemessage'], ...addCodeTabs]) {
  453. await A.goto(REPO('alpha') + p);
  454. await A.waitFor(`!!document.querySelector(${J(sel)})`, { label: 'alpha ' + p + ' for addcode check' });
  455. check(`filled repo ${p}: no "Add code" box (already has commits)`, !(await has(A, '#addcode')), await A.evaluate('document.body.innerText.slice(0, 150)'));
  456. }
  457. await A.goto(REPO('alpha') + '/code');
  458. await codeReady(A);
  459. check('the owner sees "Make main" on the other branches, not on the main one', (await A.evaluate('document.querySelectorAll("#branches .setmain").length')) === 2, await A.evaluate('document.querySelector("#branches").innerText'));
  460. await hydrated(A); // the view is in the FIRST HTML now: wait for the page to be live before clicking
  461. await A.click('#branches .setmain');
  462. await A.waitFor('document.querySelector("#coderef") && document.querySelector("#coderef").textContent === "dev"', { label: 'main branch changed' });
  463. check('"Make main" changes the main branch: /code now shows it (kept in the repo record)', (await txt(A, '#coderef')) === 'dev' && (await names(A, '#entries li > :first-child')) === 'src|README.md|bin.dat|my file.txt' && (await txt(A, '#commitsubject')) === 'first commit' && (await (await fetch(API + '/api/repos/alpha')).json()).branch === 'dev', await A.evaluate('document.body.innerText.slice(0, 300)'));
  464. await A.goto(REPO('alpha') + '/');
  465. await homeText(A);
  466. check('the homepage README follows the main branch too', await A.evaluate('!!document.querySelector("#homepage")'));
  467. const S = await newPage();
  468. await S.goto(REPO('alpha') + '/code');
  469. await codeReady(S);
  470. check('a signed-out viewer sees the code, but no "Make main"', (await txt(S, '#coderef')) === 'dev' && (await S.evaluate('document.querySelectorAll("#branches .setmain").length')) === 0);
  471. const forged = await emitFace('gitoriaSetBranch', ['alpha', 'main', 'code', '', 'x'], '');
  472. const still = await (await fetch(API + '/api/repos/alpha')).json();
  473. check('face: a stranger cannot change the main branch', still.branch === 'dev', J(forged) + J(still));
  474. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  475. await viewport(A, w, h);
  476. await A.goto(REPO('alpha') + '/code');
  477. await codeReady(A);
  478. check(`layout ${w}px: /code has no horizontal overflow`, await noOverflow(A));
  479. await shot(A, `${name}-code`);
  480. await A.goto(REPO('alpha') + '/code/src/a.txt');
  481. await codeReady(A);
  482. check(`layout ${w}px: a file view has no horizontal overflow of the page`, await noOverflow(A));
  483. await shot(A, `${name}-file`);
  484. }
  485. await viewport(A, 1280, 900);
  486. // the connect flow in the browser: the owner (alice, logged in at tickets with the gate's cookie) clicks "Tickets: connect"
  487. // in the repo's settings, picks the project on tickets and continues back to the repo
  488. const connectRepo = async (page, slug, projectValue, newTitle) => {
  489. const [ck, cv] = tickets.cookie.split('=');
  490. await page.send('Network.setCookie', { name: ck, value: cv, url: tickets.base });
  491. await page.goto(REPO(slug) + '/settings');
  492. await page.waitFor('!!document.querySelector("#connecttickets")', { label: 'settings: connect button' });
  493. await page.click('#connecttickets');
  494. await page.waitFor('location.origin === ' + J(tickets.base) + ' && !!document.querySelector("#connectform")', { label: 'tickets connect page' });
  495. await hydrated(page);
  496. if (newTitle) {
  497. await page.evaluate('(() => { const s = document.querySelector("#connectproject"); s.value = ""; s.dispatchEvent(new Event("change", { bubbles: true })); })()');
  498. await page.waitFor('!!document.querySelector("#connecttitleinput")', { label: 'new project title field' });
  499. await page.type('#connecttitleinput', newTitle);
  500. } else if (projectValue) {
  501. await page.evaluate(`(() => { const s = document.querySelector("#connectproject"); s.value = ${J(projectValue)}; s.dispatchEvent(new Event("change", { bubbles: true })); })()`);
  502. }
  503. await page.click('#connectconfirm');
  504. try { await page.waitFor('!!document.querySelector("#connectcontinue")', { label: 'tickets: connected' }); }
  505. catch (e) { throw new Error(e.message + ' | page: ' + await page.evaluate('(document.querySelector("#connectmessage") || {}).textContent + " / " + document.body.innerHTML.slice(0, 1500)')); }
  506. await page.click('#connectcontinue');
  507. await page.waitFor(`location.hostname === '${slug}.gitoria.test' && !!document.querySelector("#connectedto")`, { label: 'back in settings, connected' });
  508. };
  509. // ---- the repo's tickets (gitoria#10): /tickets lists tickets.worldapi.org's project, the first ticket makes it ----
  510. const PROJ = 'alpha.gitoria.test';
  511. await A.goto(REPO('alpha') + '/tickets');
  512. await A.waitFor('!!document.querySelector("#ticketsnotconnected")', { label: 'tickets page, not connected' });
  513. check('connect: an unconnected repo says so on /tickets, no form, no list', !(await has(A, '#newticketform')) && !(await has(A, '#ticketlist')));
  514. await S.goto(REPO('alpha') + '/settings');
  515. await S.waitFor('!!document.querySelector("#notconnected")', { label: 'S: settings' });
  516. check('connect: a signed-out viewer sees "not connected" and no connect button', !(await has(S, '#connecttickets')) && !(await has(S, '#disconnecttickets')));
  517. // the owner connects: the project exists in tickets (made by the tickets user of alice, its admin)
  518. const mk = await fetch(tickets.base + '/api/projects', { method: 'POST', headers: { authorization: 'Bearer ' + tickets.token, 'content-type': 'application/json' }, body: J({ title: PROJ, slug: PROJ }) });
  519. check('connect: the project for alpha exists in tickets', mk.status === 201 || mk.status === 200, String(mk.status));
  520. await connectRepo(A, 'alpha', null, null);
  521. check('connect: settings says connected to that project, with the disconnect button', /alpha/.test(await txt(A, '#connectedto')) && (await has(A, '#disconnecttickets')));
  522. check('connect: tickets shows the connection', J((await tickets.api(`/api/projects/${PROJ}/connections`)).json).includes('alpha'), J((await tickets.api(`/api/projects/${PROJ}/connections`))));
  523. await A.goto(REPO('alpha') + '/tickets');
  524. await A.waitFor('!!document.querySelector("#noticketsyet")', { label: 'tickets page, connected, no ticket yet' });
  525. check('tickets: /tickets of a connected repo without tickets says so, has the nav link and the form', (await has(A, '#navtickets')) && (await has(A, '#newticketform')) && !(await has(A, '#ticketlist')));
  526. await S.goto(REPO('alpha') + '/tickets');
  527. await S.waitFor('!!document.querySelector("#noticketsyet")', { label: 'S: tickets page' });
  528. await hydrated(S);
  529. check('tickets: a signed-out viewer sees the page with a login hint and no form', (await has(S, '#ticketsloginhint')) && !(await has(S, '#newticketform')));
  530. await hydrated(A);
  531. await A.evaluate('document.querySelector("#newticket").open = true');
  532. await A.type('#ticketsubject', ' ');
  533. await A.click('#ticketsave');
  534. await A.waitFor('!!document.querySelector("#newticketerror").textContent', { label: 'blank subject refused' });
  535. await A.evaluate('document.querySelector("#ticketsubject").value = ""; document.querySelector("#newticket").open = true');
  536. check('tickets: a blank subject is refused in words', /subject/.test(await txt(A, '#newticketerror')));
  537. await A.type('#ticketsubject', 'First <b>ticket</b>');
  538. await A.type('#ticketsummary', 'Some **words**');
  539. await A.click('#ticketsave');
  540. await A.waitFor('document.querySelectorAll("#ticketlist li").length === 1', { label: 'first ticket listed' });
  541. const t1 = (await tickets.api(`/api/projects/${PROJ}/tickets/1`)).json.ticket;
  542. check('tickets: a ticket opened in gitoria lands in the connected project, created by the person (alice = the tickets user "gitoria")', t1 && t1.subject === 'First <b>ticket</b>' && t1.state === 'open' && t1.summary === 'Some **words**' && t1.createdBy === 'gitoria', J(t1));
  543. check('tickets: the list row = #1, the subject as text (no HTML), state, link into tickets', await A.evaluate(`(() => { const li = document.querySelector('#ticketlist li'); return /#1/.test(li.textContent) && li.textContent.includes('First <b>ticket</b>') && !li.querySelector('b') && /open/.test(li.textContent) && li.querySelector('a.subject').href === ${J(tickets.base + '/' + PROJ + '/1')}; })()`));
  544. // the server pushes `ticketOpened` BEFORE it answers the face, so the list row can show up before openIt clears the form
  545. // (seen once on hybriel master ff51cf46) — wait for the face's answer, the notice
  546. await A.waitFor('!!document.querySelector("#ticketnotice")', { label: 'notice after the face answered' }).catch(() => null);
  547. check('tickets: the form is cleared and says "Opened ticket #1"', (await A.evaluate('document.querySelector("#ticketsubject").value')) === '' && /#1/.test(await txt(A, '#ticketnotice')), J({ subject: await A.evaluate('document.querySelector("#ticketsubject").value'), notice: await txt(A, '#ticketnotice') }));
  548. await S.waitFor('document.querySelectorAll("#ticketlist li").length === 1', { label: 'S sees it live' });
  549. check('live: the signed-out viewer sees the new ticket without a reload', /First/.test(await txt(S, '#ticketlist')) && !(await has(S, '#noticketsyet')));
  550. // a ticket opened in tickets itself, and one with a name only tickets knows: shown on the next load
  551. const ext = await fetch(tickets.base + '/api/projects/' + PROJ + '/tickets', { method: 'POST', headers: { authorization: 'Bearer ' + tickets.token, 'content-type': 'application/json' }, body: J({ subject: 'From tickets itself' }) });
  552. check('tickets: a ticket made on tickets.worldapi.org directly → 201', ext.status === 201);
  553. await A.goto(REPO('alpha') + '/tickets');
  554. await A.waitFor('document.querySelectorAll("#ticketlist li").length === 2', { label: 'two tickets after reload' });
  555. check('tickets: after a reload both are listed, newest update first', /From tickets itself/.test(await txt(A, '#ticketlist li:first-child')) && /First/.test(await txt(A, '#ticketlist li:nth-child(2)')) && (await A.evaluate('document.querySelector("#ticketsall").href')) === tickets.base + '/projects/' + PROJ);
  556. check('tickets: another repo has none of them', (await tickets.api('/api/projects/beta-2.gitoria.test/tickets')).status === 404);
  557. await S.goto(REPO('beta-2') + '/tickets');
  558. await S.waitFor('!!document.querySelector("#ticketsnotconnected")', { label: 'beta-2 is not connected' });
  559. check('tickets: beta-2 is not connected and shows none of them', !(await has(S, '#ticketlist')));
  560. await S.goto(REPO('nothing-here') + '/tickets');
  561. await S.waitFor('!!document.querySelector("#missing")', { label: 'unknown repo tickets' });
  562. check('tickets: an address nobody created has no tickets page', true);
  563. f = await emitFace('gitoriaOpenTicket', ['alpha', 'anon', '']);
  564. check('face: not logged in → a ticket is refused', f.value && /log in/.test(f.value.error || '') && (await tickets.api(`/api/projects/${PROJ}/tickets`)).json.tickets.length === 2, f.raw);
  565. f = await emitFace('gitoriaOpenTicket', ['alpha', 'forged', '', { user: { id: 'x' } }]);
  566. check('face: a forged trailing session opens nothing', !(f.value && f.value.ticket) && (await tickets.api(`/api/projects/${PROJ}/tickets`)).json.tickets.length === 2, f.raw);
  567. f = await emitFace('gitoriaOpenTicket', ['no-such-repo', 'x', '']);
  568. check('face: an unknown repo → refused, no project made', f.value && /no such repository/.test(f.value.error || '') && (await tickets.api('/api/projects/no-such-repo.gitoria.test/tickets')).status === 404, f.raw);
  569. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  570. await viewport(A, w, h);
  571. await A.goto(REPO('alpha') + '/tickets');
  572. await A.waitFor('document.querySelectorAll("#ticketlist li").length === 2', { label: 'tickets for layout' });
  573. check(`layout ${w}px: /tickets has no horizontal overflow`, await noOverflow(A));
  574. await shot(A, `${name}-tickets`);
  575. }
  576. await viewport(A, 1280, 900);
  577. await tickets.stop();
  578. await S.goto(REPO('alpha') + '/tickets');
  579. await S.waitFor('!!document.querySelector("#ticketserror")', { label: 'tickets down' });
  580. check('tickets down: the page says tickets.worldapi.org did not answer', /did not answer/.test(await txt(S, '#ticketserror')));
  581. tickets = await startTickets({ ticketsDir: TICKETS_DIR, workDir: join(STORE, 'tickets2'), port: TICKETS_PORT, ident, who: alice, origins: ORIGINS });
  582. // ---- #N links both ways (gitoria#18): the tickets copy is new; connect alpha again, then a REAL push over HTTP ----
  583. await fetch(tickets.base + '/api/projects', { method: 'POST', headers: { authorization: 'Bearer ' + tickets.token, 'content-type': 'application/json' }, body: J({ title: PROJ, slug: PROJ }) });
  584. await fetch(tickets.base + '/api/projects/' + PROJ + '/tickets', { method: 'POST', headers: { authorization: 'Bearer ' + tickets.token, 'content-type': 'application/json' }, body: J({ subject: 'Login is broken' }) });
  585. await connectRepo(A, 'alpha', null, null);
  586. check('connect: connecting again after tickets was replaced works (new key, page says connected)', /alpha/.test(await txt(A, '#connectedto')));
  587. const sid = (await A.cookies([REPO('alpha')])).find(c => /sid$/.test(c.name));
  588. const mkTok = await emitFace('gitoriaMakeToken', ['gate push'], sid.name + '=' + sid.value);
  589. const PUSHTOKEN = mkTok.value && mkTok.value.token;
  590. check('links: a push token for alice', /^gtr_[0-9a-f]{40}$/.test(PUSHTOKEN || ''), mkTok.raw);
  591. const lw = join(STORE, 'work-links');
  592. rmSync(lw, { recursive: true, force: true });
  593. execFileSync('git', ['clone', '-q', join(STORE, 'git', 'alpha.git'), lw], { stdio: 'pipe' });
  594. const lg = (...a) => execFileSync('git', ['-C', lw, '-c', 'user.name=alice', '-c', '[email protected]', ...a], { stdio: 'pipe' }).toString();
  595. const pushHttp = (...refs) => lg('-c', 'http.extraHeader=Host: alpha.gitoria.test:' + PORT, 'push', '-q', `http://alice:${PUSHTOKEN}@127.0.0.1:${PORT}/alpha.git`, ...refs);
  596. const ticketMd = async (n) => (await (await fetch(`${tickets.base}/api/projects/${PROJ}/tickets/${n}`, { headers: { accept: 'text/markdown' } })).text());
  597. writeFileSync(join(lw, 'login.txt'), 'x\n'); lg('add', '-A'); lg('commit', '-q', '-m', 'fix login, #1 and a bogus #99');
  598. const mentionSha = lg('rev-parse', 'HEAD').trim();
  599. pushHttp('HEAD:main');
  600. let tmd = '';
  601. for (let i = 0; i < 20 && !/Mentioned in commit/.test(tmd); i++) { tmd = await ticketMd(1); if (!/Mentioned in commit/.test(tmd)) await sleep(500); }
  602. check('links: a pushed commit "fix login, #1" → ticket 1 in tickets shows "Mentioned in commit" with the commit link', /Mentioned in commit/.test(tmd) && tmd.includes(mentionSha.slice(0, 8)) && tmd.includes('/commit/' + mentionSha), tmd.slice(0, 600));
  603. check('links: a ticket that does not exist (#99) is skipped quietly', (await tickets.api(`/api/projects/${PROJ}/tickets/99`)).status === 404);
  604. const cnt = (t) => (t.match(/Mentioned in commit/g) || []).length;
  605. pushHttp('HEAD:refs/heads/other');
  606. await sleep(1500);
  607. check('links: pushing the same commit again does not comment twice', cnt(await ticketMd(1)) === 1, String(cnt(await ticketMd(1))));
  608. await A.goto(REPO('alpha') + '/commit/' + mentionSha);
  609. await A.waitFor('!!document.querySelector("#reponame")', { label: 'commit page' });
  610. await sleep(1500);
  611. check('links: the commit page shows #1 as a link into the ticket', await A.evaluate(`(() => { const a = [...document.querySelectorAll('a')].filter(x => x.href === ${J(tickets.base + '/projects/' + PROJ + '/1')}); return a.length > 0; })()`), await A.evaluate(`(document.querySelector('#commitsubject') || {}).innerHTML + ' | ' + location.href`));
  612. // "fixes #1" in a merged pull request sets the ticket to review
  613. lg('checkout', '-q', '-b', 'fixbr'); writeFileSync(join(lw, 'fix.txt'), 'y\n'); lg('add', '-A'); lg('commit', '-q', '-m', '|||PR|main] Fix the login, fixes #1');
  614. pushHttp('fixbr');
  615. await A.goto(REPO('alpha') + '/pulls');
  616. await A.waitFor('!!document.querySelector("#reponame")', { label: 'pulls page' });
  617. await sleep(1500);
  618. check('links: the open pull request lists #1 as a link', await A.evaluate(`[...document.querySelectorAll('a')].some(x => x.href === ${J(tickets.base + '/projects/' + PROJ + '/1')} && x.closest('#pulllist'))`) || await A.evaluate(`[...document.querySelectorAll('a')].some(x => x.href === ${J(tickets.base + '/projects/' + PROJ + '/1')})`));
  619. check('links: an open pull request does not change the ticket', (await tickets.api(`/api/projects/${PROJ}/tickets/1`)).json.ticket.state === 'open');
  620. lg('checkout', '-q', 'main'); lg('merge', '-q', '--no-ff', '-m', 'merge the fix', 'fixbr');
  621. pushHttp('main');
  622. let st = '';
  623. for (let i = 0; i < 20 && st !== 'review'; i++) { st = (await tickets.api(`/api/projects/${PROJ}/tickets/1`)).json.ticket.stateSlug; if (st !== 'review') await sleep(500); }
  624. check('links: the pull request "fixes #1" is merged (pushed) → ticket 1 is set to review', st === 'review', st);
  625. const before2 = cnt(await ticketMd(1));
  626. pushHttp('main');
  627. await sleep(1000);
  628. check('links: a second push comments nothing twice and does not set it again', cnt(await ticketMd(1)) === before2 && before2 === 2 && ((await ticketMd(1)).match(/Fixed by the merged pull request/g) || []).length === 1);
  629. // disconnect from gitoria's side, and tickets' side sees it gone
  630. await A.goto(REPO('alpha') + '/settings');
  631. await A.waitFor('!!document.querySelector("#disconnecttickets")', { label: 'settings, connected' });
  632. await hydrated(A);
  633. await A.click('#disconnecttickets');
  634. await A.waitFor('!!document.querySelector("#notconnected")', { label: 'disconnected' });
  635. await A.goto(REPO('alpha') + '/tickets');
  636. await A.waitFor('!!document.querySelector("#ticketsnotconnected")', { label: 'tickets page after disconnect' });
  637. check('connect: "Forget the connection" → /tickets says not connected again', true);
  638. await connectRepo(A, 'alpha', null, null);
  639. // ---- pull requests (gitoria#11): /pulls lists the commits that start with |||PR -------------------------------
  640. const pw = join(STORE, 'work-pulls');
  641. rmSync(pw, { recursive: true, force: true }); mkdirSync(pw, { recursive: true });
  642. gitIn(pw, 'init', '-q', '-b', 'main');
  643. writeFileSync(join(pw, 'a.txt'), 'base\n'); gitIn(pw, 'add', '-A'); gitIn(pw, 'commit', '-q', '-m', 'base');
  644. const baseSha = gitIn(pw, 'rev-parse', 'HEAD').trim();
  645. const branchCommit = (name, msg) => { gitIn(pw, 'checkout', '-q', '-b', name, baseSha); writeFileSync(join(pw, name.replace(/\//g, '_') + '.txt'), name + '\n'); gitIn(pw, 'add', '-A'); gitIn(pw, 'commit', '-q', '-m', msg); return gitIn(pw, 'rev-parse', 'HEAD').trim(); };
  646. gitIn(pw, 'branch', 'dev');
  647. const fixSha = branchCommit('fix-a', '|||PR Fix the <b>thing</b>');
  648. gitIn(pw, 'commit', '-q', '--allow-empty', '-m', 'more work on fix-a');
  649. branchCommit('topic/one', '|||PR|dev] Topic to dev');
  650. branchCommit('ghost', '|||PR|nope] Lost target');
  651. branchCommit('plain', 'not a pull request |||PR');
  652. branchCommit('nospace', '|||PR|main]glued');
  653. branchCommit('old', '|||PR Old work');
  654. gitIn(pw, 'checkout', '-q', 'main'); gitIn(pw, 'merge', '-q', '--ff-only', 'old');
  655. gitIn(pw, 'push', '-q', '-f', join(STORE, 'git', 'beta-2.git'), 'main', 'dev', 'fix-a', 'topic/one', 'ghost', 'plain', 'nospace', 'old');
  656. const pullsReady = (p) => p.waitFor('!document.querySelector("#pullsloading") && (!!document.querySelector("#pullsmessage") || !!document.querySelector("#pullshelp"))', { label: 'pulls answer' });
  657. await A.goto(REPO('beta-2') + '/pulls');
  658. await pullsReady(A);
  659. const rows = await A.evaluate(`[...document.querySelectorAll('#pulllist li')].map(li => [li.querySelector('.subject').textContent.replace(/^#[0-9]+/, ''), li.querySelector('.open,.merged').textContent, li.querySelector('.branches').textContent.replace(/\\s+/g, ' ').trim()].join(' ~ '))`);
  660. check('/pulls: one request per marker commit, title without the marker, source → target, state', rows.length === 4 && rows.includes('Fix the <b>thing</b> ~ open ~ fix-a→main') && rows.includes('Topic to dev ~ open ~ topic/one→dev') && rows.includes('Old work ~ merged ~ old→main') && rows.some(r => r.startsWith('Lost target ~ open ~ ghost→nope (no such branch)')), J(rows));
  661. check('/pulls (gitoria#40): every request shows its own number #N, 1..4 once each', J(await A.evaluate(`[...document.querySelectorAll('#pulllist li .subject .number')].map(n => n.textContent).sort()`)) === J(['#1', '#2', '#3', '#4']), J(await A.evaluate(`[...document.querySelectorAll('#pulllist li .subject .number')].map(n => n.textContent)`)));
  662. check('/pulls: no request from a marker inside the text or without the space after ]; HTML stays text', !rows.some(r => /Not a pull|glued|plain|nospace/.test(r)) && !(await has(A, '#pulllist b')), J(rows));
  663. check('/pulls: the title links to the PR page (gitoria#45), the branches to their pages, the nav link is there', await A.evaluate(`(() => { const a = [...document.querySelectorAll('#pulllist li')].find(li => li.textContent.includes('Fix the')); return /^\\/pulls\\/\\d+$/.test(a.querySelector('.subject a').pathname) && a.querySelector('a.source').pathname === '/branch/fix-a' && a.querySelector('a.target').pathname === '/branch/main'; })() && !!document.querySelector('#navpulls')`));
  664. await A.evaluate(`[...document.querySelectorAll('#pulllist a.source')].find(a => a.textContent === 'fix-a').click()`);
  665. await A.waitFor('location.pathname === "/branch/fix-a"', { label: 'source branch link' });
  666. await S.goto(REPO('beta-2') + '/pulls');
  667. await pullsReady(S);
  668. check('/pulls: a signed-out viewer sees the same list', (await S.evaluate('document.querySelectorAll("#pulllist li").length')) === 4);
  669. await S.goto(REPO('gamma') + '/pulls');
  670. await pullsReady(S);
  671. check('/pulls of an empty repo says it has no commits yet', /no commits yet/.test(await txt(S, '#pullsmessage') || ''));
  672. await S.goto(REPO('alpha') + '/pulls');
  673. await pullsReady(S);
  674. check('/pulls of alpha lists just the one request from the #N test (merged, "fixes #1" a link)', (await S.evaluate('document.querySelectorAll("#pulllist li").length')) === 1 && !(await has(S, '#nopulls')) && (await S.evaluate('!!document.querySelector("#pulllist li .merged") && !!document.querySelector("#pulllist a.ticketref")')));
  675. await S.goto(REPO('nothing-here') + '/pulls');
  676. await S.waitFor('!!document.querySelector("#missing")', { label: 'unknown repo pulls' });
  677. const forgedPulls = await emitFace('gitoriaPulls', ['beta-2', 'x', 'evil'], '');
  678. check('face: a forged session gets no pull list', !forgedPulls.value || forgedPulls.value.ok !== true, J(forgedPulls));
  679. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  680. await viewport(A, w, h);
  681. await A.goto(REPO('beta-2') + '/pulls');
  682. await pullsReady(A);
  683. check(`layout ${w}px: /pulls has no horizontal overflow`, await noOverflow(A));
  684. await shot(A, `${name}-pulls`);
  685. }
  686. await viewport(A, 1280, 900);
  687. // ---- merge button (gitoria#17): the owner merges a pull request, only by clicking; a conflict merges nothing ------
  688. const mergeBtns = (p) => p.evaluate(`[...document.querySelectorAll('#pulllist li')].filter(li => li.querySelector('button.mergepr')).map(li => li.querySelector('.subject').textContent.replace(/^#[0-9]+/, '')).join('|')`);
  689. await A.goto(REPO('beta-2') + '/pulls');
  690. await pullsReady(A);
  691. check('merge: the owner sees Merge on the open requests with a source and a target, not on merged / lost ones', (await mergeBtns(A)) === 'Topic to dev|Fix the <b>thing</b>', await mergeBtns(A));
  692. await S.goto(REPO('beta-2') + '/pulls');
  693. await pullsReady(S);
  694. check('merge: a signed-out viewer sees no Merge button', (await S.evaluate('document.querySelectorAll("button.mergepr").length')) === 0);
  695. const forgedMerge = await emitFace('gitoriaMergePull', ['beta-2', fixSha, 'evil'], '');
  696. check('merge: a forged session cannot merge', !forgedMerge.value || forgedMerge.value.error != null || forgedMerge.value.result == null, J(forgedMerge));
  697. // a branch that conflicts with main
  698. gitIn(pw, 'checkout', '-q', '-b', 'clash', baseSha); writeFileSync(join(pw, 'a.txt'), 'clash side\n'); gitIn(pw, 'add', '-A'); gitIn(pw, 'commit', '-q', '-m', '|||PR Clashing change');
  699. gitIn(pw, 'checkout', '-q', 'main'); writeFileSync(join(pw, 'a.txt'), 'main side\n'); gitIn(pw, 'add', '-A'); gitIn(pw, 'commit', '-q', '-m', 'main edits a.txt');
  700. gitIn(pw, 'push', '-q', '-f', join(STORE, 'git', 'beta-2.git'), 'main', 'clash');
  701. const mainBefore = gitIn(join(STORE, 'git', 'beta-2.git'), 'rev-parse', 'main').trim();
  702. await A.goto(REPO('beta-2') + '/pulls');
  703. await pullsReady(A);
  704. await hydrated(A); // the list is in the first HTML: its Merge buttons only work once the page is live (a click before is lost)
  705. const clickMerge = (title) => A.evaluate(`(() => { const li = [...document.querySelectorAll('#pulllist li')].find(l => l.querySelector('.subject').textContent.replace(/^#[0-9]+/, '') === ${J(title)}); li.querySelector('button.mergepr').click(); })()`);
  706. await clickMerge('Clashing change');
  707. await A.waitFor('/conflicts/.test((document.querySelector("#mergeerror")||{}).textContent||"")', { label: 'conflict message' }).catch(async e => { throw new Error(e.message + ' ' + await A.evaluate('document.querySelector("#pulllist").innerText + document.querySelector("#mergeerror").outerHTML')); });
  708. check('merge: a conflict says so, names the file and merges nothing', /a\.txt/.test(await txt(A, '#mergeerror')) && gitIn(join(STORE, 'git', 'beta-2.git'), 'rev-parse', 'main').trim() === mainBefore && (await A.evaluate('document.querySelectorAll("#pulllist li .open").length')) >= 3);
  709. await clickMerge('Fix the <b>thing</b>');
  710. await A.waitFor('[...document.querySelectorAll("#pulllist li")].some(l => l.querySelector(".subject").textContent.replace(/^#[0-9]+/, \'\') === "Fix the <b>thing</b>" && l.querySelector(".merged"))', { label: 'fix-a merged' }).catch(async e => { throw new Error(e.message + ' ' + await A.evaluate('document.querySelector("#pulllist").innerText + document.querySelector("#mergeerror").textContent')); });
  711. const bare = join(STORE, 'git', 'beta-2.git');
  712. const mainLog = gitIn(bare, 'log', '--format=%s|%an', 'main');
  713. check('merge: the click merges the branch into the target: merge commit by the owner, the branch commits are in main', /Merge branch 'fix-a' into main\|/.test(mainLog) && gitIn(bare, 'merge-base', '--is-ancestor', 'fix-a', 'main') !== null && /more work on fix-a/.test(mainLog) && gitIn(bare, 'show', 'main:fix-a.txt').trim() === 'fix-a', mainLog);
  714. check('merge: the other side (main\'s own commit) is kept; the merge commit has two parents', /main edits a\.txt/.test(mainLog) && gitIn(bare, 'rev-list', '--parents', '-n1', 'main').trim().split(' ').length === 3);
  715. check('merge: the request now shows merged and its Merge button is gone', !(await A.evaluate(`[...document.querySelectorAll('#pulllist li')].some(l => l.querySelector('.subject').textContent.replace(/^#[0-9]+/, '') === 'Fix the <b>thing</b>' && l.querySelector('button.mergepr'))`)) && !(await txt(A, '#mergeerror')), J([await txt(A, '#mergeerror'), await A.evaluate(`[...document.querySelectorAll('#pulllist li')].filter(l => l.querySelector('.subject').textContent.replace(/^#[0-9]+/, '').startsWith('Fix')).map(l => l.innerHTML).join()`)]));
  716. await S.goto(REPO('beta-2') + '/pulls');
  717. await pullsReady(S);
  718. check('merge: a reload (signed out) shows it merged', await S.evaluate(`[...document.querySelectorAll('#pulllist li')].some(l => l.querySelector('.subject').textContent.replace(/^#[0-9]+/, '') === 'Fix the <b>thing</b>' && l.querySelector('.merged'))`));
  719. await viewport(A, 1280, 900);
  720. // ---- releases (gitoria#12): /releases lists the |||RL commits of the main branch, versions counted up ---------
  721. const rw = join(STORE, 'work-rel');
  722. rmSync(rw, { recursive: true, force: true }); mkdirSync(rw, { recursive: true });
  723. gitIn(rw, 'init', '-q', '-b', 'main');
  724. const rc = (msg) => { gitIn(rw, 'commit', '-q', '--allow-empty', '-m', msg); return gitIn(rw, 'rev-parse', 'HEAD').trim(); };
  725. rc('start');
  726. rc('|||RL First <b>one</b>');
  727. rc('work');
  728. rc('|||RL|med Feature drop');
  729. rc('|||RL|mj Big one');
  730. rc('|||RL');
  731. rc('text |||RL not a release');
  732. rc('|||RL|nonsense x');
  733. rc('|||RL|1.1.1a By hand');
  734. const lastSha = rc('|||RL after the hand one');
  735. rc('|||RL|1.1.1a again the same');
  736. gitIn(rw, 'checkout', '-q', '-b', 'side'); rc('|||RL on a side branch');
  737. gitIn(rw, 'push', '-q', '-f', join(STORE, 'git', 'beta-2.git'), 'main', 'side');
  738. const relReady = (p) => p.waitFor('!document.querySelector("#releasesloading") && (!!document.querySelector("#releasesmessage") || !!document.querySelector("#releaseshelp"))', { label: 'releases answer' });
  739. await A.goto(REPO('beta-2') + '/releases');
  740. await relReady(A);
  741. const rel = await A.evaluate(`[...document.querySelectorAll('#releaselist li')].map(li => li.querySelector('.version') && li.querySelector('.subject') ? li.querySelector('.version').textContent + ' ~ ' + li.querySelector('.subject').textContent + (li.querySelector('.latest') ? ' ~ latest' : '') : 'HTML ' + li.innerHTML)`);
  742. check('/releases: versions counted up (patch, med, mj, by hand, then on), newest first, latest marked', J(rel) === J(['1.1.2 ~ after the hand one ~ latest', '1.1.1a ~ By hand', '1.0.1 ~ ' + rel[2].split(' ~ ')[1], '1.0.0 ~ Big one', '0.1.0 ~ Feature drop', '0.0.1 ~ First <b>one</b>']), J(rel));
  743. check('/releases: no release from a marker inside the text, a bad version, a repeated version or another branch; HTML stays text', rel.length === 6 && !(await has(A, '#releaselist b')), J(rel));
  744. check('/releases: a release links to its commit, the nav link is there', await A.evaluate(`document.querySelector('#releaselist li a.subject').href.endsWith('/commit/${lastSha}') && !!document.querySelector('#navreleases')`));
  745. await S.goto(REPO('gamma') + '/releases');
  746. await relReady(S);
  747. check('/releases of an empty repo says it has no commits yet', /no commits yet/.test(await txt(S, '#releasesmessage') || ''));
  748. await S.goto(REPO('alpha') + '/releases');
  749. await relReady(S);
  750. check('/releases of a repo without release commits says "No release yet"', (await has(S, '#noreleases')) && !(await has(S, '#releaselist li')));
  751. const forgedRel = await emitFace('gitoriaReleases', ['beta-2', 'x', 'evil'], '');
  752. check('face: a forged session gets no release list', !forgedRel.value || forgedRel.value.ok !== true, J(forgedRel));
  753. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  754. await viewport(A, w, h);
  755. await A.goto(REPO('beta-2') + '/releases');
  756. await relReady(A);
  757. check(`layout ${w}px: /releases has no horizontal overflow`, await noOverflow(A));
  758. await shot(A, `${name}-releases`);
  759. }
  760. await viewport(A, 1280, 900);
  761. // ---- gitoria#16: every repo view is its own page, rendered on the SERVER for the request's host ---------------
  762. const AH = `alpha.gitoria.test:${PORT}`;
  763. // the git views are read on the server too (hl:proc run(), hybriel#80): the FIRST HTML holds the content, no loading step
  764. const BH = `beta-2.gitoria.test:${PORT}`;
  765. const firstViews = [
  766. ['/', AH, (b, t) => /id="homepage"/.test(b) && /Code repo/.test(t), 'Readme: the README (main branch dev)'],
  767. ['/code', AH, (b, t) => /id="entries"/.test(b) && /<a class="dir" href="\/code\/src">src<\/a>/.test(b) && /README\.md/.test(t) && /id="coderef">dev</.test(b), 'Code: the file list of the main branch'],
  768. ['/code/src', AH, (b, t) => /<a class="dir" href="\/code\/src\/deep">deep<\/a>/.test(b) && /a\.txt/.test(t), 'Code/<path>: the folder (the * part reaches the page)'],
  769. ['/code/src/a.txt', AH, (b, t) => /id="lines"/.test(b) && /line one/.test(t), 'Code/<file>: the file lines'],
  770. ['/branch/main', AH, (b, t) => /id="coderef">main</.test(b) && /id="entries"/.test(b) && /second on main/.test(t), 'Branch main: its tree and last commit'],
  771. ['/branch/feature/x', AH, (b, t) => /id="coderef">feature\/x</.test(b) && /only-feature\.txt/.test(t), 'Branch with a slash'],
  772. ['/commit/' + firstSha, AH, (b, t) => /id="codekind"[^>]*>Commit</.test(b) && /id="entries"/.test(b) && /first commit/.test(t), 'Commit: the project at that commit'],
  773. ['/pulls', BH, (b, t) => /id="pulllist"/.test(b) && /Fix the/.test(t), 'Pull requests: the list'],
  774. ['/releases', BH, (b, t) => /id="releaselist"/.test(b) && /1\.1\.2/.test(t) && /after the hand one/.test(t), 'Releases: the list'],
  775. ];
  776. for (const [path, host, ok, what] of firstViews) {
  777. const f = await firstHtml(path, host);
  778. const t = bodyText(f.body);
  779. check(`first HTML of ${host.split('.')[0]}${path}: ${what}, no "Loading"`, f.status === 200 && /id="reponame"/.test(f.body) && ok(f.body, t) && !/Loading/i.test(t), t.slice(0, 400));
  780. }
  781. r = await fetch(API + '/host.js');
  782. check('/host.js is gone (404)', r.status === 404, String(r.status));
  783. let fh, ft;
  784. // (the tickets copy was restarted empty above) one ticket made in tickets itself, then the page from scratch
  785. // tickets #20: a ticket needs an existing project, made by its first admin (as gitoria does)
  786. await fetch(tickets.base + '/api/projects', { method: 'POST', headers: { authorization: 'Bearer ' + tickets.token, 'content-type': 'application/json' }, body: J({ title: 'alpha.gitoria.test', slug: 'alpha.gitoria.test' }) });
  787. await fetch(tickets.base + '/api/projects/alpha.gitoria.test/tickets', { method: 'POST', headers: { authorization: 'Bearer ' + tickets.token, 'content-type': 'application/json' }, body: J({ subject: 'From tickets itself' }) });
  788. fh = await firstHtml('/tickets', AH);
  789. ft = bodyText(fh.body);
  790. check('first HTML of alpha/tickets: the ticket list itself is there (no loading step)', /id="ticketlist"/.test(fh.body) && /From tickets itself/.test(ft) && !/Loading/.test(ft), ft.slice(0, 400));
  791. fh = await firstHtml('/', `gitoria.test:${PORT}`);
  792. ft = bodyText(fh.body);
  793. check('first HTML of the main address: the repo list with every repo (no loading step)', /<h1 id="heading">Repositories<\/h1>/.test(fh.body) && /alpha/.test(ft) && /beta-2/.test(ft) && /gamma/.test(ft) && !/Loading/.test(ft), ft.slice(0, 300));
  794. check('first HTML: the hostile description of gamma stays inside the seed string (no second script, no <b id=xss>) — hybriel#34 upstream', !/<b id="xss">/.test(fh.body) && (fh.body.match(/<script\b/g) || []).length === (fh.body.match(/<\/script>/g) || []).length && fh.body.includes('\\u003c/script>'), (fh.body.match(/xss[^,]{0,80}/) || [''])[0]);
  795. let allMissing = true, missDetail = '';
  796. for (const p of ['/', '/code', '/code/src', '/branch/main', '/commit/abcdef1', '/pulls', '/releases', '/tickets']) {
  797. const m = await firstHtml(p, `nothing-here.gitoria.test:${PORT}`);
  798. if (m.status !== 200 || !/<h1 id="missing">No such repository<\/h1>/.test(m.body) || /id="reponame"/.test(m.body)) { allMissing = false; missDetail += ' ' + p + ':' + m.status; }
  799. }
  800. check('unknown repo: every view says "No such repository" in the first HTML', allMissing, missDetail);
  801. // direct load of every view in Chrome
  802. const views = [
  803. ['/', '#homepage, #nohomepage', 'Readme'], ['/code', '#entries', 'Code'], ['/code/src/a.txt', '#lines', 'Code'], ['/branch/feature/x', '#entries', 'Branch'],
  804. ['/commit/' + firstSha.slice(0, 8), '#entries', 'Commit'], ['/pulls', '#pullshelp', 'Pull requests'], ['/releases', '#releaseshelp', 'Releases'], ['/tickets', '#ticketlist', 'Tickets'],
  805. ];
  806. let direct = true, directDetail = '';
  807. for (const [p, sel, title] of views) {
  808. await A.goto(REPO('alpha') + p);
  809. try { await A.waitFor(`!!document.querySelector(${J(sel)}) && !!document.querySelector('#reponame')`, { label: 'direct ' + p, timeout: 6000 }); } catch { direct = false; directDetail += ' ' + p + ' (no ' + sel + ')'; continue; }
  810. const t = await A.evaluate('document.title');
  811. if (!t.startsWith(title === 'Readme' ? 'alpha' : title) || !t.includes('alpha')) { direct = false; directDetail += ` ${p} title ${J(t)}`; }
  812. }
  813. check('direct load of every view (Readme, Code, a file, Branch, Commit, Pulls, Releases, Tickets): its content, its tab title', direct, directDetail);
  814. // gitoria#22 repo tabs: the active tab of each of the 8 views is marked (aria-current="page", exactly one) AND looks different
  815. // (computed font-weight / bottom border differ from every other tab); every tab link goes where it always went; a missing
  816. // repo shows only the message (the view's own content is not there).
  817. const tabLinks = { '#navhome': '/', '#navcode': '/code', '#navpulls': '/pulls', '#navreleases': '/releases', '#navtickets': '/tickets', '#navsettings': '/settings' };
  818. const tabViews = [['/', '#navhome'], ['/code', '#navcode'], ['/code/src/a.txt', '#navcode'], ['/branch/feature/x', '#navcode'], ['/commit/' + firstSha.slice(0, 8), '#navcode'], ['/pulls', '#navpulls'], ['/releases', '#navreleases'], ['/tickets', '#navtickets'], ['/settings', '#navsettings']];
  819. let tabsOk = true, tabsDetail = '', linksOk = true, linksDetail = '';
  820. for (const [p, want] of tabViews) {
  821. await A.goto(REPO('alpha') + p);
  822. try { await A.waitFor(`!!document.querySelector('#reponav a[aria-current=page]')`, { label: 'active tab ' + p, timeout: 6000 }); } catch { tabsOk = false; tabsDetail += ` ${p}: no aria-current`; continue; }
  823. const st = await A.evaluate(`(() => { const all = [...document.querySelectorAll('#reponav a')]; const cur = all.filter(a => a.getAttribute('aria-current') === 'page'); const css = a => { const c = getComputedStyle(a); return c.fontWeight + '|' + c.borderBottomWidth + '|' + c.color; };
  824. return { ids: cur.map(a => a.id), vals: cur.map(a => a.getAttribute('aria-current')), curCss: cur.length ? css(cur[0]) : '', others: all.filter(a => a.getAttribute('aria-current') !== 'page').map(css), hrefs: Object.fromEntries(all.map(a => ['#' + a.id, a.getAttribute('href')])) }; })()`);
  825. if (st.ids.length !== 1 || st.ids[0] !== want.slice(1) || st.vals[0] !== 'page') { tabsOk = false; tabsDetail += ` ${p}: marked ${J(st.ids)} ${J(st.vals)}`; }
  826. if (st.others.some(o => o === st.curCss)) { tabsOk = false; tabsDetail += ` ${p}: active tab not styled differently (${st.curCss})`; }
  827. for (const [id, href] of Object.entries(tabLinks)) if (st.hrefs[id] !== href) { linksOk = false; linksDetail += ` ${p} ${id}=${st.hrefs[id]}`; }
  828. }
  829. await shot(A, 'gate-repotabs-active');
  830. check('repo tabs: on each of the 8 views (Readme, Code, a file, Branch, Commit, Pulls, Releases, Tickets, Settings) exactly its tab has aria-current="page" and a visibly different style', tabsOk, tabsDetail);
  831. check('repo tabs: every tab link still goes where it went (/, /code, /pulls, /releases, /tickets, /settings) on every view', linksOk, linksDetail);
  832. let missOk = true, missDetail2 = '';
  833. for (const p of ['/', '/code', '/code/src', '/branch/main', '/commit/abcdef1', '/pulls', '/releases', '/tickets', '/settings']) {
  834. await A.goto(REPO('nothing-here') + p);
  835. await A.waitFor('!!document.querySelector("#missing")', { label: 'missing ' + p, timeout: 6000 });
  836. const m = await A.evaluate(`(() => { const r = document.querySelector('main'); return { text: r.innerText.replace(/\\s+/g, ' ').trim(), nav: !!document.querySelector('#reponav'), kids: [...r.querySelectorAll('repo-page > *')].filter(e => e.textContent.trim() !== '').length }; })()`);
  837. if (m.text !== 'No such repository Nobody has created this address yet. All repositories' || m.nav || m.kids !== 1) { missOk = false; missDetail2 += ` ${p}: ${J(m)}`; }
  838. }
  839. check('repo tabs: an unknown repo shows only "No such repository" + its link on all 8 views (no page content, no nav) — in the browser', missOk, missDetail2);
  840. // hl:web navigation: Readme → Code → Releases → Tickets → Pulls → Readme without a page load
  841. await A.goto(REPO('alpha') + '/');
  842. await A.waitFor('!!document.querySelector("#homepage, #nohomepage")', { label: 'nav start: Readme' });
  843. await hydrated(A);
  844. await A.evaluate('window.__navMarker = 42');
  845. const navSteps = [['#navcode', '/code', '#entries'], ['#navreleases', '/releases', '#releaseshelp'], ['#navtickets', '/tickets', '#ticketlist'], ['#navpulls', '/pulls', '#pullshelp'], ['#navhome', '/', '#homepage, #nohomepage']];
  846. let navOk = true, navDetail = '';
  847. for (const [link, path, sel] of navSteps) {
  848. await A.click(link);
  849. try { await A.waitFor(`location.pathname === ${J(path)} && !!document.querySelector(${J(sel)})`, { label: 'nav to ' + path, timeout: 6000 }); } catch { navOk = false; navDetail += ` ${path}: ${await A.evaluate('location.pathname + " " + document.body.innerText.slice(0, 120)')}`; continue; }
  850. if ((await A.evaluate('window.__navMarker')) !== 42) { navOk = false; navDetail += ` ${path}: page reloaded`; }
  851. if ((await txt(A, '#reponame')) !== 'alpha' || (await A.evaluate('location.host')) !== AH) { navOk = false; navDetail += ` ${path}: wrong repo/host`; }
  852. }
  853. check('navigation Readme → Code → Releases → Tickets → Pulls → Readme: no full page load (window marker survives), the address bar follows, content right', navOk, navDetail);
  854. // gitoria#22 / D-CHAIN: ALL repo pages stand under ONE layout level (components/repo.hl: the repo head + the tab nav + a slot). A tab click
  855. // (a real click) replaces only the page in the slot: the repo head, the tab nav, its links and the shell are the SAME node objects
  856. // before and after (tagged with a property here), nothing is removed from or added to the repo head, and the marked tab follows
  857. // the page (also on the Back button). Fails on the old code (every click rebuilt the whole <main>: head and nav were new nodes).
  858. await A.goto(REPO('alpha') + '/');
  859. await A.waitFor('!!document.querySelector("#homepage, #nohomepage") && !!document.querySelector("#reponav")', { label: 'chain start: Readme' });
  860. await hydrated(A);
  861. await A.evaluate(`(() => { const q = (s) => document.querySelector(s); window.__chain = { shell: q('main'), page: q('main repo-page'), head: q('repo-head'), name: q('#reponame'), nav: q('#reponav'), link: q('#navcode'), header: q('application-header') };
  862. for (const k in window.__chain) window.__chain[k].__chainTag = k; window.__headMut = 0;
  863. window.__moHead = new MutationObserver((r) => { window.__headMut += r.length; }); window.__moHead.observe(q('repo-head'), { childList: true, subtree: true });
  864. window.__slotMut = 0; window.__moSlot = new MutationObserver((r) => { window.__slotMut += r.length; }); window.__moSlot.observe(q('main repo-page'), { childList: true }); return true; })()`);
  865. const sameNodes = `(() => { const q = (s) => document.querySelector(s); const now = { shell: q('main'), page: q('main repo-page'), head: q('repo-head'), name: q('#reponame'), nav: q('#reponav'), link: q('#navcode'), header: q('application-header') };
  866. return Object.keys(now).filter(k => !(now[k] && now[k] === window.__chain[k] && now[k].__chainTag === k && now[k].isConnected)).join(); })()`;
  867. let chainOk = true, chainDetail = '';
  868. const chainSteps = [['#navcode', '/code', '#entries', 'navcode'], ['#navpulls', '/pulls', '#pullshelp', 'navpulls'], ['#navreleases', '/releases', '#releaseshelp', 'navreleases'], ['#navtickets', '/tickets', '#ticketlist', 'navtickets'], ['#navhome', '/', '#homepage', 'navhome'], ['#navcode', '/code', '#entries', 'navcode']];
  869. for (const [link, path, sel, marked] of chainSteps) {
  870. await A.click(link);
  871. try { await A.waitFor(`location.pathname === ${J(path)} && !!document.querySelector(${J(sel)})`, { label: 'chain nav ' + path, timeout: 8000 }); } catch { chainOk = false; chainDetail += ` ${path}: timeout`; continue; }
  872. const lost = await A.evaluate(sameNodes);
  873. const cur = await A.evaluate(`[...document.querySelectorAll('#reponav a[aria-current=page]')].map(a => a.id).join()`);
  874. if (lost !== '') { chainOk = false; chainDetail += ` ${path}: NOT the same node: ${lost};`; }
  875. if (cur !== marked) { chainOk = false; chainDetail += ` ${path}: marked ${cur};`; }
  876. }
  877. check('chain: Readme → Code → Pulls → Releases → Tickets → Readme → Code (real clicks): the shell, the repo page, the repo head, the name, the tab nav and its links are the SAME node objects after every click, and the marked tab follows', chainOk, chainDetail);
  878. check('chain: the repo head got no child added or removed while the tabs were clicked (only the slot page changed)', (await A.evaluate('window.__headMut')) === 0 && (await A.evaluate('window.__slotMut')) > 0, 'head mutations ' + (await A.evaluate('window.__headMut')) + ', slot-parent mutations ' + (await A.evaluate('window.__slotMut')));
  879. await A.evaluate('history.back()');
  880. await A.waitFor('location.pathname === "/" && !!document.querySelector("#homepage, #nohomepage")', { label: 'chain back to Readme' });
  881. check('chain: the Back button goes to the Readme inside the same chain (same head node, Readme tab marked)', (await A.evaluate(sameNodes)) === '' && (await A.evaluate(`[...document.querySelectorAll('#reponav a[aria-current=page]')].map(a => a.id).join()`)) === 'navhome');
  882. // inside the Code tab: a folder, a commit page, a branch page — still the same chain (code, branch, commit are three routes, one level)
  883. await A.click('#navcode');
  884. await A.waitFor('location.pathname === "/code" && !!document.querySelector("#entries")', { label: 'chain: code' });
  885. await A.click('#commits a');
  886. await A.waitFor('location.pathname.startsWith("/commit/") && !!document.querySelector("#commitsubject")', { label: 'chain: a commit page', timeout: 15000 });
  887. const lostCommit = await A.evaluate(sameNodes);
  888. check('chain: Code → a commit page (another route) keeps head and nav, "Code" stays marked', lostCommit === '' && (await A.evaluate(`[...document.querySelectorAll('#reponav a[aria-current=page]')].map(a => a.id).join()`)) === 'navcode', lostCommit);
  889. await A.click('#navhome');
  890. await A.waitFor('location.pathname === "/" && !!document.querySelector("#homepage, #nohomepage")', { label: 'chain: back at Readme' });
  891. await A.evaluate('window.__moHead.disconnect(); window.__moSlot.disconnect(); 0');
  892. await A.evaluate('window.__navMarker = 42'); // the chain block above loaded the page afresh: the marker for the folder step below
  893. await A.click('#navcode');
  894. await A.waitFor('location.pathname === "/code" && !!document.querySelector("#entries a.dir")', { label: 'code for folder nav' });
  895. await A.click('#entries a.dir');
  896. await A.waitFor('location.pathname === "/code/src" && !!document.querySelector("#crumbs strong") && document.querySelector("#crumbs strong").textContent === "src"', { label: 'folder via nav' });
  897. check('navigation inside Code (a folder) keeps the page too, and the browser Back button goes back to /code', (await A.evaluate('window.__navMarker')) === 42 && await (async () => { await A.evaluate('history.back()'); await A.waitFor('location.pathname === "/code" && [...document.querySelectorAll("#entries a")].some(x => x.textContent === "src")', { label: 'back to /code' }); return (await A.evaluate('window.__navMarker')) === 42; })());
  898. // NAVIGATION WHILE LOGGED IN (the creator saw full page loads): a fresh browser, logged in through the button on the
  899. // repo address like a person, then Readme → Code → Releases → Pulls → Tickets → Code → a folder with real clicks
  900. const L = await newPage();
  901. { const [lk, lv] = alice.cookie.split('='); await L.send('Network.enable'); await L.send('Network.setCookie', { name: lk, value: lv, url: IDENT_B + '/' }); }
  902. await L.goto(REPO('alpha') + '/');
  903. await L.waitFor('!!document.querySelector("#selector") && !!document.querySelector("#reponame")', { label: 'L: repo, signed out' });
  904. await hydrated(L);
  905. await shClick(L, '#choose');
  906. await L.waitFor(sh(`r.querySelectorAll('[part~="identity"]').length > 0`), { label: 'L: selector list at alpha' });
  907. await shClick(L, '[part~="identity"]', 'Default');
  908. await L.waitFor(`location.href === ${J(REPO('alpha') + '/')} && !!document.querySelector("#whoami") && !!document.querySelector("#homepage")`, { label: 'L: back logged in' });
  909. await hydrated(L);
  910. await L.evaluate('window.__navMarker = 99');
  911. // the folder step waits for '#crumbs a' (only inside a folder): '#crumbs strong' is already on /code, so it passed with /code/src still in flight
  912. const loggedSteps = [['#navhome', '/', '#homepage'], ['#navcode', '/code', '#entries'], ['#navreleases', '/releases', '#releaseshelp'], ['#navpulls', '/pulls', '#pullshelp'], ['#navtickets', '/tickets', '#ticketlist'], ['#navcode', '/code', '#entries'], ['#entries a.dir', '/code/src', '#crumbs a']];
  913. let liOk = true, liDetail = '';
  914. for (const [link, path, sel] of loggedSteps) {
  915. await L.click(link);
  916. try { await L.waitFor(`location.pathname === ${J(path)} && !!document.querySelector(${J(sel)}) && !!document.querySelector('#whoami')`, { label: 'L nav ' + path, timeout: 6000 }); } catch { liOk = false; liDetail += ` ${path}: ${await L.evaluate('location.pathname + " " + document.body.innerText.slice(0, 120)')}`; continue; }
  917. if ((await L.evaluate('window.__navMarker')) !== 99) { liOk = false; liDetail += ` ${path}: FULL PAGE LOAD`; await L.evaluate('window.__navMarker = 99'); await hydrated(L); }
  918. if ((await txt(L, '#reponame')) !== 'alpha' || (await txt(L, '#whoami')) !== 'alice') { liOk = false; liDetail += ` ${path}: wrong repo/user`; }
  919. }
  920. check('navigation LOGGED IN (button login on the repo address): Readme → Code → Releases → Pulls → Tickets → Code → a folder, real clicks: no full page load, content right, still logged in', liOk, liDetail);
  921. // the same on an EMPTY repo the user owns (like the creator's live repos: no commit yet)
  922. const emptySteps = [['#navcode', '/code', '#codemessage'], ['#navreleases', '/releases', '#releasesmessage'], ['#navpulls', '/pulls', '#pullsmessage'], ['#navtickets', '/tickets', '#ticketsnotconnected'], ['#navhome', '/', '#nohomepage']];
  923. await L.goto(REPO('gamma') + '/');
  924. await L.waitFor('!!document.querySelector("#nohomepage") && !!document.querySelector("#whoami")', { label: 'L: gamma' });
  925. await hydrated(L);
  926. await L.evaluate('window.__navMarker = 98');
  927. let emOk = true, emDetail = '';
  928. for (const [link, path, sel] of emptySteps) {
  929. await L.click(link);
  930. try { await L.waitFor(`location.pathname === ${J(path)} && !!document.querySelector(${J(sel)}) && !!document.querySelector('#whoami')`, { label: 'L gamma ' + path, timeout: 6000 }); } catch { emOk = false; emDetail += ` ${path}: ${await L.evaluate('location.pathname + " " + document.body.innerText.slice(0, 120)')}`; continue; }
  931. if ((await L.evaluate('window.__navMarker')) !== 98) { emOk = false; emDetail += ` ${path}: FULL PAGE LOAD`; await L.evaluate('window.__navMarker = 98'); await hydrated(L); }
  932. }
  933. check('navigation LOGGED IN on an empty repo the user owns: Code → Releases → Pulls → Tickets → Readme, no full page load', emOk, emDetail);
  934. // the socket gone (Cloudflare closes an idle WebSocket after ~100 s): navigation rides the POST fallback
  935. await L.goto(REPO('alpha') + '/');
  936. await L.waitFor('!!document.querySelector("#homepage") && !!document.querySelector("#whoami")', { label: 'L: alpha again' });
  937. await hydrated(L);
  938. await L.evaluate('window.__hl.socket.close(); window.__navMarker = 97');
  939. await L.waitFor('!window.__hl.socket', { label: 'L: socket gone' });
  940. let pfOk = true, pfDetail = '';
  941. for (const [link, path, sel] of [['#navcode', '/code', '#entries'], ['#navreleases', '/releases', '#releaseshelp'], ['#navhome', '/', '#homepage']]) {
  942. await L.click(link);
  943. try { await L.waitFor(`location.pathname === ${J(path)} && !!document.querySelector(${J(sel)}) && !!document.querySelector('#whoami')`, { label: 'L post ' + path, timeout: 6000 }); } catch { pfOk = false; pfDetail += ` ${path}: timeout`; continue; }
  944. if ((await L.evaluate('window.__navMarker')) !== 97) { pfOk = false; pfDetail += ` ${path}: FULL PAGE LOAD`; break; }
  945. }
  946. check('navigation LOGGED IN with the socket closed (POST fallback): no full page load, still logged in', pfOk, pfDetail);
  947. // THE SAME IN A REAL FIREFOX (the creator's browser; tests/firefox.mjs, WebDriver BiDi, real pointer clicks)
  948. ff = await launchFirefox({ port: FIREFOX_PORT, hosts: ['gitoria.test', 'alpha.gitoria.test', 'beta-2.gitoria.test', 'gamma.gitoria.test', 'ident.gitoria.test'] });
  949. { const [fk, fv] = alice.cookie.split('='); await ff.setCookie(fk, fv, 'ident.gitoria.test'); }
  950. const ffLive = () => ff.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'firefox: page hydrated' });
  951. await ff.goto(REPO('alpha') + '/');
  952. await ff.waitFor('!!document.querySelector("#selector") && !!document.querySelector("#reponame")', { label: 'firefox: repo, signed out' });
  953. await ffLive();
  954. // (no header button any more: the plain login link, opened as the button's link did — back on the main address, then the repo address)
  955. await ff.goto(LOGIN_URL);
  956. await ff.waitFor('!!document.querySelector("#chooselist li .choose")', { label: 'firefox: ident chooser' });
  957. await ffLive();
  958. await ff.click('#chooselist li:nth-child(1) .choose');
  959. await ff.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector("#whoami")`, { label: 'firefox: back logged in on the main address', timeout: 30000 });
  960. await ff.goto(REPO('alpha') + '/');
  961. await ff.waitFor(`location.href === ${J(REPO('alpha') + '/')} && !!document.querySelector("#whoami") && !!document.querySelector("#homepage")`, { label: 'firefox: the repo address knows the login', timeout: 30000 });
  962. await ffLive();
  963. await ff.evaluate('window.__navMarker = 99');
  964. let ffOk = true, ffDetail = '';
  965. for (const [link, path, sel] of loggedSteps) {
  966. await ff.click(link);
  967. try { await ff.waitFor(`location.pathname === ${J(path)} && !!document.querySelector(${J(sel)}) && !!document.querySelector('#whoami')`, { label: 'firefox nav ' + path, timeout: 8000 }); } catch { ffOk = false; ffDetail += ` ${path}: ${await ff.evaluate('location.pathname + " " + document.body.innerText.slice(0, 120)')}`; continue; }
  968. if ((await ff.evaluate('window.__navMarker')) !== 99) { ffOk = false; ffDetail += ` ${path}: FULL PAGE LOAD`; await ff.evaluate('window.__navMarker = 99'); await ffLive(); }
  969. if ((await ff.evaluate('document.querySelector("#reponame").textContent + "/" + document.querySelector("#whoami").textContent')) !== 'alpha/alice') { ffOk = false; ffDetail += ` ${path}: wrong repo/user`; }
  970. }
  971. check('FIREFOX, navigation LOGGED IN: Readme → Code → Releases → Pulls → Tickets → Code → a folder, real clicks: no full page load, content right, still logged in', ffOk, ffDetail);
  972. await ff.goto(REPO('gamma') + '/');
  973. await ff.waitFor('!!document.querySelector("#nohomepage") && !!document.querySelector("#whoami")', { label: 'firefox: gamma' });
  974. await ffLive();
  975. await ff.evaluate('window.__navMarker = 98');
  976. let ffeOk = true, ffeDetail = '';
  977. for (const [link, path, sel] of emptySteps) {
  978. await ff.click(link);
  979. try { await ff.waitFor(`location.pathname === ${J(path)} && !!document.querySelector(${J(sel)}) && !!document.querySelector('#whoami')`, { label: 'firefox gamma ' + path, timeout: 8000 }); } catch { ffeOk = false; ffeDetail += ` ${path}: ${await ff.evaluate('location.pathname + " " + document.body.innerText.slice(0, 120)')}`; continue; }
  980. if ((await ff.evaluate('window.__navMarker')) !== 98) { ffeOk = false; ffeDetail += ` ${path}: FULL PAGE LOAD`; await ff.evaluate('window.__navMarker = 98'); await ffLive(); }
  981. }
  982. check('FIREFOX, navigation LOGGED IN on an empty repo the user owns, no full page load', ffeOk, ffeDetail);
  983. check('FIREFOX: no console errors', ff.errors.length === 0, ff.errors.join(' | '));
  984. await ff.close(); ff = null;
  985. await A.goto(BASE + '/');
  986. await A.waitFor('document.querySelectorAll("#repos li").length === 3', { label: 'list with gamma' });
  987. check('the hostile description shows as text on the list, nothing of it ran (hybriel#34 upstream)', (await A.evaluate('!window.__xss && !document.querySelector("#xss")')) && (await txt(A, '#repos')).includes(XSS), await txt(A, '#repos'));
  988. // ---- layout ------------------------------------------------------------------------------------------------
  989. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  990. await viewport(A, w, h);
  991. await A.goto(BASE + '/');
  992. await A.waitFor('document.querySelectorAll("#repos li").length === 3', { label: 'list for layout' });
  993. check(`layout ${w}px: main address has no horizontal overflow`, await noOverflow(A));
  994. await shot(A, `${name}-main`);
  995. await A.goto(REPO('alpha') + '/');
  996. await A.waitFor('!!document.querySelector("#reponame")');
  997. check(`layout ${w}px: repo address has no horizontal overflow`, await noOverflow(A));
  998. await shot(A, `${name}-repo`);
  999. }
  1000. // ---- PHONE FIRST (gitoria#23): every page at 390 px (mobile Chrome, DPR 2, touch) measured by tests/mobile-measure.js ----
  1001. // no sideways scroll (scrollWidth against a FIXED 390: a mobile viewport grows with the page, so innerWidth would hide it),
  1002. // every tap target ≥ 44×44 (inline links in a sentence exempt), fields ≥ 16 px, text ≥ 14 px, the header ≤ the theme's 52 px,
  1003. // code / tables inside the screen. A long real line: a 20 000-character line on a branch `wide` of alpha. Then the phone's
  1004. // three dropdowns opened by a tap: ☰ (the main menu), the user menu, the ident dropdown (signed out).
  1005. const wideWork = join(STORE, 'work-wide');
  1006. rmSync(wideWork, { recursive: true, force: true });
  1007. execFileSync('git', ['clone', '-q', join(STORE, 'git', 'alpha.git'), wideWork], { stdio: 'pipe' });
  1008. gitIn(wideWork, 'checkout', '-q', '-b', 'wide');
  1009. writeFileSync(join(wideWork, 'long.txt'), 'short line\n' + 'x'.repeat(20000) + ' the end\n');
  1010. gitIn(wideWork, 'add', '-A'); gitIn(wideWork, 'commit', '-q', '-m', 'a very long line');
  1011. gitIn(wideWork, 'push', '-q', 'origin', 'wide');
  1012. const UA_PHONE = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1';
  1013. const phone = async (p) => {
  1014. await p.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  1015. await p.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  1016. await p.send('Emulation.setUserAgentOverride', { userAgent: UA_PHONE, platform: 'iPhone' });
  1017. return p;
  1018. };
  1019. const PH = await phone(patient(await browsers[0].newPage())); // alice's Chrome (signed in)
  1020. const PO = await phone(await newPage()); // a fresh Chrome: signed out
  1021. const measure = async (p) => { await hydrated(p); await sleep(600); return p.evaluate('window.__W = 390;' + MEASURE); };
  1022. const phonePages = [
  1023. [PH, 'main address', BASE + '/', '#repos li'], [PH, 'repo readme', REPO('alpha') + '/', '#reponame'], [PH, '/code', REPO('alpha') + '/code', '#entries li'],
  1024. [PH, '/code/src', REPO('alpha') + '/code/src', '#entries li'], [PH, 'a file', REPO('alpha') + '/code/src/a.txt', '#lines li'],
  1025. [PH, 'a 20 000-character line', REPO('alpha') + '/branch/wide/long.txt', '#lines li'], [PH, '/branch/feature/x', REPO('alpha') + '/branch/feature/x', '#entries li'],
  1026. [PH, '/commit/<first>', REPO('alpha') + '/commit/' + firstSha, '#entries li'], [PH, '/pulls', REPO('alpha') + '/pulls', 'repo-pulls'],
  1027. [PH, '/releases', REPO('beta-2') + '/releases', '#releaselist li'], [PH, '/tickets', REPO('alpha') + '/tickets', 'repo-tickets'],
  1028. [PH, '/settings', REPO('alpha') + '/settings', 'repo-settings'], [PH, 'no such repository', REPO('nothing-here') + '/', '#missing'],
  1029. [PH, '/login/failed', BASE + '/login/failed', '#home'], [PO, 'main address signed out', BASE + '/', '#repos li'],
  1030. ];
  1031. for (const [p, name, url, ready] of phonePages) {
  1032. let m = null;
  1033. try { await p.goto(url); await p.waitForSelector(ready); m = await measure(p); } catch (e) { m = { ok: false, error: e.message }; }
  1034. check(`phone 390: ${name} — no sideways scroll, targets ≥ 44 px, fields ≥ 16 px, text ≥ 14 px, header ≤ 52 px, code inside`, m.ok === true,
  1035. m.error || J({ scrollWidth: m.docScrollWidth, tapsSmall: m.tapsSmall + '/' + m.taps, small: m.tapsSmallList, inputs: m.inputsSmallList, text: m.textSmallList, header: m.headerH, boxes: m.boxesOver }));
  1036. if (/20 000/.test(name) && m.ok !== undefined) check('phone 390: the 20 000-character line scrolls inside its own box', await p.evaluate(`(() => { const l = document.querySelector('#lines'); return !!l && l.scrollWidth > 5000 && l.getBoundingClientRect().right <= 390 && document.documentElement.scrollWidth <= 390; })()`));
  1037. if (name === '/code') check('phone 390: the repo tab row wraps in its own row (2 rows, no overflow, inside the screen)', await p.evaluate(`(() => { const n = document.querySelector('repo-nav'); if (!n) return false; const k = [...n.children]; return new Set(k.map(a => Math.round(a.getBoundingClientRect().top))).size >= 2 && n.scrollWidth <= n.clientWidth + 1 && Math.max(...k.map(a => a.getBoundingClientRect().right)) <= 390; })()`), await p.evaluate('(document.querySelector("repo-nav") || {}).outerHTML || "no repo-nav"'));
  1038. }
  1039. { const nf = await fetch(API + '/no/such/page', { redirect: 'manual' }); const nt = await nf.text(); const na = await fetch(API + '/api/nope'); const nr = await fetch(API + '/code', { headers: { Host: `alpha.gitoria.test:${PORT}` } });
  1040. check('phone 390 (MG): an unknown path answers 404 with the shell page (header, menu, "Page not found"), an unknown /api path a JSON 404 in the contract shape (error.code not_found)', nf.status === 404 && /<application-header/.test(nt) && /Page not found/.test(nt) && na.status === 404 && /^application\/json/.test(na.headers.get('content-type')) && (await na.json()).error.code === 'not_found' && nr.status === 200, nf.status + ' ' + na.status + ' ' + nr.status); }
  1041. // ---- MG mobile audit (mission MG, 2026-10-23): what the numbers above cannot see — order, alignment, duplicates, dead space ----
  1042. const geo = (p, js) => p.evaluate(`(() => { ${js} })()`);
  1043. // the 404 page is static (no live socket): measured without waiting for hydration
  1044. { let m; try { await PH.goto(BASE + '/no/such/page/' + 'x'.repeat(90)); await PH.waitForSelector('#notfound'); await sleep(600); m = await PH.evaluate('window.__W = 390;' + MEASURE); } catch (e) { m = { ok: false, error: e.message }; }
  1045. check('phone 390 (MG): the 404 page for a long unknown address fits (no sideways scroll, targets ≥ 44 px, shell header)', m.ok === true && m.headerH > 0, m.error || J({ w: m.docScrollWidth, small: m.tapsSmallList, header: m.headerH })); }
  1046. await PH.goto(BASE + '/'); await PH.waitForSelector('#repos li'); await hydrated(PH);
  1047. check('phone 390 (MG): the main address shows the first repository in the first screen — before the create form, tokens and keys', await geo(PH, `const li = document.querySelector('#repos li'); return !!li && li.getBoundingClientRect().top < 400;`), await geo(PH, `return Math.round(document.querySelector('#repos li').getBoundingClientRect().top)`));
  1048. check('phone 390 (MG): no dead strip under a form button (an empty error line takes no room)', await geo(PH, `const f = document.querySelector('#createform'); const b = f.querySelector('button'); return f.getBoundingClientRect().bottom - b.getBoundingClientRect().bottom <= 20;`), await geo(PH, `const f = document.querySelector('#createform'); return Math.round(f.getBoundingClientRect().bottom - f.querySelector('button').getBoundingClientRect().bottom)`));
  1049. await PH.goto(REPO('alpha') + '/code'); await PH.waitForSelector('#entries li'); await hydrated(PH);
  1050. check('phone 390 (MG): /code says the branch name once at the top (no second "main" row above the file list)', await geo(PH, `const name = document.querySelector('#coderef').textContent.trim(); const shown = (e) => e.getBoundingClientRect().height > 0; const same = [...document.querySelectorAll('code-head strong, #crumbs strong')].filter(e => shown(e) && e.textContent.trim() === name); return same.length === 1;`));
  1051. check('phone 390 (MG): the six repo tabs are a 3 × 2 grid of equal cells', await geo(PH, `const k = [...document.querySelectorAll('repo-nav a')].map(a => a.getBoundingClientRect()); return k.length === 6 && new Set(k.map(r => Math.round(r.width))).size === 1 && new Set(k.map(r => Math.round(r.top))).size === 2 && new Set(k.map(r => Math.round(r.left))).size === 3;`), await geo(PH, `return JSON.stringify([...document.querySelectorAll('repo-nav a')].map(a => { const r = a.getBoundingClientRect(); return [Math.round(r.left), Math.round(r.top), Math.round(r.width)]; }))`));
  1052. check('phone 390 (MG): the commit rows list hash and date on one line, then the subject, then the author, in every row', await geo(PH, `const rows = [...document.querySelectorAll('#commits li')]; if (rows.length < 1) return false; const tops = (li) => [...li.children].map(c => Math.round(c.getBoundingClientRect().top - li.getBoundingClientRect().top)); const t = rows.map(tops); return rows.every((li, i) => t[i][3] < t[i][1] && t[i][1] > t[i][0] && t[i][2] > t[i][1]);`), await geo(PH, `return JSON.stringify([...document.querySelectorAll('#commits li')].slice(0, 3).map(li => [...li.children].map(c => Math.round(c.getBoundingClientRect().top - li.getBoundingClientRect().top))))`));
  1053. await PH.goto(REPO('alpha') + '/pulls'); await PH.waitForSelector('#pulllist li'); await hydrated(PH);
  1054. check('phone 390 (MG): a pull request title has its own row (full width, the state badge below it)', await geo(PH, `const rows = [...document.querySelectorAll('#pulllist li')]; return rows.length >= 1 && rows.every(li => { const s = li.querySelector('.subject').getBoundingClientRect(), r = li.getBoundingClientRect(); const st = li.querySelector('.open,.merged').getBoundingClientRect(); return s.width >= r.width - 40 && st.top >= s.bottom - 1; });`), await geo(PH, `return JSON.stringify([...document.querySelectorAll('#pulllist li')].map(li => [Math.round(li.querySelector('.subject').getBoundingClientRect().width), Math.round(li.getBoundingClientRect().width)]))`));
  1055. await PH.goto(REPO('alpha') + '/tickets'); await PH.waitForSelector('#ticketlist li'); await hydrated(PH);
  1056. check('phone 390 (MG): ticket rows line up — number, subject and state each in their own column', await geo(PH, `const rows = [...document.querySelectorAll('#ticketlist li')]; return rows.length >= 1 && rows.every(li => getComputedStyle(li).display === 'grid') && new Set(rows.map(li => Math.round(li.querySelector('a.subject').getBoundingClientRect().left))).size === 1;`));
  1057. await PH.goto(REPO('gamma') + '/code'); await PH.waitForSelector('#addcode'); await hydrated(PH);
  1058. check('phone 390 (MG): the clone and push commands wrap — none hides its end behind a sideways scroll', await geo(PH, `const p = [...document.querySelectorAll('#addcode pre')]; return p.length >= 3 && p.every(e => e.scrollWidth <= e.clientWidth + 1);`), await geo(PH, `return JSON.stringify([...document.querySelectorAll('#addcode pre')].map(e => [e.scrollWidth, e.clientWidth]))`));
  1059. // the dropdowns, opened with a real tap: their box inside the screen, every link / button in them ≥ 44×44
  1060. const dropdown = async (p, toggle, box) => {
  1061. if (!(await has(p, toggle))) return { error: 'no ' + toggle };
  1062. await p.click(toggle);
  1063. try { await p.waitFor(`!!document.querySelector(${J(box)}) && document.querySelector(${J(box)}).matches(':popover-open')`, { label: box + ' open', timeout: 3000 }); } catch { return { error: box + ' did not open' }; }
  1064. await sleep(300);
  1065. return p.evaluate(`(() => { const b = document.querySelector(${J(box)}); const r = b.getBoundingClientRect(); const items = [...b.querySelectorAll('a[href], button')].filter(e => e.getBoundingClientRect().width > 0);
  1066. return { inside: r.left >= 0 && r.right <= 390, items: items.map(e => e.textContent.trim()), small: items.filter(e => { const q = e.getBoundingClientRect(); return q.width < 43.5 || q.height < 43.5; }).map(e => e.textContent.trim() + ' ' + Math.round(e.getBoundingClientRect().width) + 'x' + Math.round(e.getBoundingClientRect().height)) }; })()`);
  1067. };
  1068. await PH.goto(REPO('alpha') + '/code'); await PH.waitForSelector('#entries li'); await hydrated(PH);
  1069. let dd = await dropdown(PH, 'button.menu-toggle', '#sidebar');
  1070. check('phone 390: ☰ opens the main menu (Repositories) inside the screen, its targets ≥ 44 px', !dd.error && dd.inside && dd.small.length === 0 && dd.items.includes('Repositories'), J(dd));
  1071. if (!dd.error) {
  1072. await PH.click('#sidebar a[href]');
  1073. await PH.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector('#repos li')`, { label: 'menu → main address' }).catch(() => {});
  1074. check('phone 390: a tap on "Repositories" in the ☰ menu goes to the main address', (await PH.evaluate('location.href')) === BASE + '/');
  1075. }
  1076. // gitoria#23 reopened ("In the sidebar is only one item Repositories that leads to a 404"): the same tap AFTER the page changed in place
  1077. // (a repo tab, a folder, a file, each a real tap) — the shell is re-rendered in the browser there, and the link used to turn into a 404.
  1078. for (const [steps, label] of [[['#navcode'], 'after the Code tab'], [['#navcode', '#entries a.dir'], 'after a folder'], [['#navcode', '#entries a.dir', '#entries a:not(.dir)'], 'after a file'], [['#navpulls', '#navhome'], 'after Pull requests and Readme']]) {
  1079. await PH.goto(REPO('alpha') + '/'); await PH.waitForSelector('#reponame'); await hydrated(PH);
  1080. let trail = 'start';
  1081. for (const s of steps) { await PH.click(s); await sleep(1200); trail += ' > ' + s; }
  1082. const hrefs = await PH.evaluate('[...document.querySelectorAll("#sidebar a[href], application-header main-menu a[href]")].map(a => a.href)');
  1083. await PH.click('button.menu-toggle'); await sleep(400);
  1084. await PH.click('#sidebar a[href]');
  1085. await PH.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector('#repos li')`, { label: 'menu → main address ' + label, timeout: 8000 }).catch(() => {});
  1086. const at = await PH.evaluate('location.href'), h = await PH.evaluate('(document.querySelector("h1") || {}).textContent');
  1087. check(`phone 390 (gitoria#23): ☰ then "Repositories" ${label} reaches the repo list on the main address (not a 404)`, at === BASE + '/' && h === 'Repositories' && hrefs.every(x => x === BASE + '/'), J({ trail, at, h, hrefs }));
  1088. }
  1089. await PH.goto(REPO('alpha') + '/'); await PH.waitForSelector('#reponame'); await hydrated(PH);
  1090. check('phone 390: no user icon; your name and Log out stand in the header, inside the screen, 44 px high', await PH.evaluate('(() => { const ok = e => { if (!e) return false; const r = e.getBoundingClientRect(); return r.width > 0 && r.height >= 40 && r.top >= 0 && r.bottom <= innerHeight && r.right <= innerWidth; }; return !document.querySelector("button.user-toggle, user-menu") && ok(document.querySelector("#logout")) && ok(document.querySelector("#whoami")); })()'));
  1091. { const gap = await PH.evaluate('(() => { const t = e => { const r = document.createRange(); r.selectNodeContents(e); return r.getBoundingClientRect(); }; const a = document.querySelector("#whoami").getBoundingClientRect(), b = t(document.querySelector("#logout")); return b.left - a.right; })()'); check('phone 390: the name and the text Log out do not touch (at least 3 px between the name and the text, not "aliceLog out")', gap >= 3, String(gap)); }
  1092. await PO.goto(REPO('alpha') + '/'); await PO.waitForSelector('#reponame'); await hydrated(PO);
  1093. // a repo address (alpha.gitoria…): the SAME selector as on the main address, nothing else beside it
  1094. check('phone 390, signed out on a repo address: ident\'s selector stands at the top right of the header (not hidden), no "Log in" button, no icon, no dropdown', (await PO.evaluate(SELECTOR_IN_HEADER)) === 'ok' && !(await has(PO, '#loginbutton')) && !(await has(PO, 'button.ident-toggle')), await PO.evaluate(SELECTOR_IN_HEADER));
  1095. await shot(PH, 'phone-usermenu');
  1096. await PH.close(); await PO.close();
  1097. // ---- the identity selector (gitoria#14): choose an identity on the main address, no reload ------------------------
  1098. const C = await newPage();
  1099. // alice is already signed in to ident (over REST, ident allows only 3 codes per address): hand C that ident session
  1100. const [ck, cv] = alice.cookie.split('=');
  1101. await C.send('Network.enable');
  1102. await C.send('Network.setCookie', { name: ck, value: cv, url: IDENT_B + '/' });
  1103. await C.goto(BASE + '/');
  1104. await C.waitFor('!!document.querySelector("#heading")', { label: 'C: main address' });
  1105. await hydrated(C);
  1106. await C.evaluate('window.__loginMarker = 1');
  1107. // hybriel#43: a second tab of the SAME browser (same session) on a code view — the login/logout flip of the shell
  1108. // must leave the page in the slot alone (no re-creation, no "Loading")
  1109. const C2 = patient(await browsers[browsers.length - 1].newPage());
  1110. await C2.goto(REPO('alpha') + '/code');
  1111. await C2.waitFor('!!document.querySelector("#entries") && !!document.querySelector("#selector.out")', { label: 'C2: code view' });
  1112. await hydrated(C2);
  1113. await C2.evaluate('window.__flipMarker = 7; document.querySelector("#entries").dataset.keep = "1"');
  1114. const codeKept = async () => C2.evaluate('window.__flipMarker === 7 && !!document.querySelector("#entries[data-keep]") && [...document.querySelectorAll("#entries a")].some(a => a.textContent === "src") && !/Loading/i.test(document.body.innerText)');
  1115. check('selector: signed out, ident\'s "choose ident" stands alone in the header (no login button beside it)', await C.evaluate(`(() => { const s = document.querySelector('#selector'); const r = s && s.shadowRoot; return !!r && /choose/.test(r.querySelector('#choose').textContent) && !s.hasAttribute('logged-in') && !document.querySelector('#loginbutton'); })()`));
  1116. for (const [w, h] of [[390, 844], [1280, 900]]) {
  1117. await viewport(C, w, h);
  1118. check(`IW ${w}px signed out: ident's selector stands visible at the top right of the header`, (await C.evaluate(SELECTOR_IN_HEADER)) === 'ok', await C.evaluate(SELECTOR_IN_HEADER));
  1119. }
  1120. await viewport(C, 1280, 900);
  1121. await shClick(C, '#choose');
  1122. await C.waitFor(sh(`r.querySelectorAll('[part~="identity"]').length > 0`), { label: 'selector list' });
  1123. await shClick(C, '[part~="identity"]', 'Default');
  1124. await C.waitFor('!!document.querySelector("#logout")', { label: 'C: logged in after the selector login' });
  1125. check('selector login: no reload, logged in, the button is gone, the selector says so', (await C.evaluate('window.__loginMarker')) === 1 && await has(C, '#logout') && !(await has(C, '#loginbutton')) && await C.evaluate('document.querySelector("#selector").hasAttribute("logged-in")') && !(await has(C, '#loginerror')));
  1126. await C.waitFor('!!document.querySelector("#createform")', { label: 'C: create form after the selector login' });
  1127. check('selector login: the page follows (create form), the same session as after the button', await has(C, '#createform') && (await txt(C, '#whoami')) === 'alice');
  1128. for (const [w, h] of [[390, 844], [1280, 900]]) {
  1129. await viewport(C, w, h);
  1130. check(`IW ${w}px signed in: ident's selector stands visible at the top right of the header and shows it is logged in`, (await C.evaluate(SELECTOR_IN_HEADER)) === 'ok' && /logged in with/.test(await C.evaluate(`document.querySelector('#selector').shadowRoot.textContent`)), await C.evaluate(SELECTOR_IN_HEADER));
  1131. check(`IW ${w}px signed in: Log out is reachable (the user menu opens by a real click and shows it, 44 px high, inside the screen)`, await C.evaluate('(() => { const b = document.querySelector("#logout").getBoundingClientRect(); return b.width > 0 && b.height >= 44 && b.bottom <= innerHeight && b.right <= innerWidth; })()'));
  1132. }
  1133. await viewport(C, 1280, 900);
  1134. // THE LOGIN IS ONE LOGIN FOR THE MAIN ADDRESS AND EVERY REPO ADDRESS (creator 2026-10-24: "does not keep the state from the main site"): one cookie
  1135. // for all of them (Domain=.gitoria.test), so a fresh load of a repo address is signed in as the same user, the selector there says so, and the
  1136. // browser holds exactly ONE gitoriasid (a second, host-only one would shadow it)
  1137. await C.goto(REPO('alpha') + '/');
  1138. await C.waitFor('!!document.querySelector("#reponame") && !!document.querySelector("#whoami")', { label: 'C: the repo address after the login on the main address' });
  1139. await hydrated(C);
  1140. const sidCookies = (await C.cookies([BASE, REPO('alpha')])).filter(c => c.name === 'gitoriasid');
  1141. check('state: logged in on the main address → a fresh load of the repo address is logged in as the same user, one gitoriasid cookie for all addresses (Domain=.gitoria.test)', (await txt(C, '#whoami')) === 'alice' && /logged in with/.test(await C.evaluate(`document.querySelector('#selector').shadowRoot.textContent`)) && sidCookies.length === 1 && sidCookies[0].domain === '.gitoria.test', J(sidCookies.map(c => [c.name, c.domain, c.path])));
  1142. for (const [w, h] of [[390, 844], [1280, 900]]) {
  1143. await viewport(C, w, h);
  1144. check(`IW ${w}px signed in on a repo address: ident's selector stands visible at the top right of the header and shows it is logged in (same as on the main address)`, (await C.evaluate(SELECTOR_IN_HEADER)) === 'ok' && /logged in with/.test(await C.evaluate(`document.querySelector('#selector').shadowRoot.textContent`)), await C.evaluate(SELECTOR_IN_HEADER));
  1145. }
  1146. await viewport(C, 1280, 900);
  1147. await C.goto(BASE + '/');
  1148. await C.waitFor('!!document.querySelector("#createform")', { label: 'C: back on the main address' });
  1149. await hydrated(C);
  1150. // (the other tab must learn of the login before the cookie experiments below change the browser's cookies)
  1151. await C2.waitFor('!!document.querySelector("#whoami")', { label: 'C2: logged in by the other tab' });
  1152. check('hybriel#43: a code view in another tab of the session flips to logged in, the code stays (same elements, no "Loading", no reload)', await codeKept(), await C2.evaluate('document.body.innerText.slice(0, 300)'));
  1153. // ---- gitoria#24: ONE SIGN-IN for the main address and every repo address, even when the browser holds TWO gitoriasid cookies -------------
  1154. // The old situation, built by hand with the real browser: the signed-in session as a HOST-ONLY cookie of the main address (from before the
  1155. // Domain was set) and, newer, a Domain cookie that is NOT the signed-in session (what a repo address hands a visitor without a cookie).
  1156. // hl:web reads the last one, so the page used to show him signed out. Only Network.setCookie / deleteCookies of this cookie name are used.
  1157. const signedSid = sidCookies.find(c => c.domain.startsWith('.'))?.value || sidCookies[0]?.value;
  1158. const dupState = async () => (await C.cookies([BASE, REPO('alpha')])).filter(c => c.name === 'gitoriasid').map(c => ({ host: c.domain.startsWith('.') ? 'domain' : 'hostonly', same: c.value === signedSid }));
  1159. const holdBoth = async () => {
  1160. await C.send('Network.deleteCookies', { name: 'gitoriasid', url: BASE + '/' });
  1161. await C.send('Network.deleteCookies', { name: 'gitoriasid', url: BASE + '/', domain: '.gitoria.test' });
  1162. await C.send('Network.deleteCookies', { name: 'gitoriasid', url: BASE + '/', domain: 'gitoria.test' });
  1163. await C.send('Network.setCookie', { name: 'gitoriasid', value: signedSid, url: BASE + '/', httpOnly: true, path: '/' }); // host-only, signed in
  1164. await C.send('Network.setCookie', { name: 'gitoriasid', value: 'cd'.repeat(16), domain: '.gitoria.test', path: '/', httpOnly: true }); // Domain, anonymous
  1165. };
  1166. { // the server alone, no browser: both ids in one Cookie header (signed in first, anonymous last — the order a browser sends them)
  1167. const both = await fetch(API + '/', { headers: { cookie: `gitoriasid=${signedSid}; gitoriasid=${'cd'.repeat(16)}` } });
  1168. const sc = both.headers.get('set-cookie') || '';
  1169. check('gitoria#24 server: two gitoriasid cookies in one request → the signed-in one is used and re-issued with the Domain', both.status === 200 && sc.startsWith('gitoriasid=' + signedSid + ';') && /Domain=\.gitoria\.test/.test(sc), both.status + ' ' + sc);
  1170. const none = await fetch(API + '/', { headers: { cookie: `gitoriasid=${'cd'.repeat(16)}` } });
  1171. check('gitoria#24 server: an anonymous cookie alone is never turned into a signed-in one and gets no new cookie', none.status === 200 && !none.headers.get('set-cookie'), none.status + ' ' + none.headers.get('set-cookie'));
  1172. }
  1173. await holdBoth();
  1174. await C.goto(BASE + '/');
  1175. await C.waitFor('!!document.querySelector("#createform") && !!document.querySelector("#whoami")', { label: 'C: main address with two cookies (signed in one first)', timeout: 30000 })
  1176. await hydrated(C);
  1177. const afterBoth = await dupState();
  1178. check('gitoria#24: a browser holding BOTH a signed-in host-only and an anonymous Domain gitoriasid cookie is signed in on the main address after one visit, and ends with the signed-in id only', (await txt(C, '#whoami')) === 'alice' && afterBoth.length >= 1 && afterBoth.every(x => x.same) && afterBoth.some(x => x.host === 'domain'), J(afterBoth));
  1179. // the host-only cookie of the main address is never sent to a repo address, so the repo address can only learn of the login after a visit to the main address
  1180. await holdBoth();
  1181. await C.goto(BASE + '/');
  1182. await C.waitFor('!!document.querySelector("#whoami")', { label: 'C: main address with two cookies, again', timeout: 30000 });
  1183. await hydrated(C);
  1184. for (let i = 0; i < 60 && !(await dupState()).some(x => x.host === 'domain' && x.same); i++) await new Promise(r => setTimeout(r, 500)); // the page's own call has moved the login to the Domain
  1185. await C.goto(REPO('alpha') + '/');
  1186. await C.waitFor('!!document.querySelector("#reponame")', { label: 'C: repo address with two cookies' });
  1187. await hydrated(C);
  1188. await C.waitFor('!!document.querySelector("#whoami")', { label: 'C: signed in on the repo address with two cookies', timeout: 30000 }).catch(() => {});
  1189. check('gitoria#24: the same browser on a repo address (anonymous Domain cookie newer than the signed-in one) is signed in there too', (await has(C, '#whoami')) && (await txt(C, '#whoami')) === 'alice', await C.evaluate('document.body.innerText.slice(0, 200)'));
  1190. // (a login that exists ONLY as an old host-only cookie cannot be built here: the server issued this session with the Domain, and hl:web
  1191. // (W138) re-issues a cookie only when its attributes changed or after a day. A session from before the Domain was set has no issue record
  1192. // and is re-issued on its first request: that is covered by hl:web's own gate for W138.)
  1193. // first a visit to a repo address WITHOUT any cookie, then the main address: still signed in? (the repo address must not shadow the login with an anonymous cookie)
  1194. await C.send('Network.deleteCookies', { name: 'gitoriasid', url: BASE + '/', domain: '.gitoria.test' });
  1195. await C.send('Network.deleteCookies', { name: 'gitoriasid', url: BASE + '/' });
  1196. await C.send('Network.setCookie', { name: 'gitoriasid', value: signedSid, url: BASE + '/', httpOnly: true, path: '/' });
  1197. await C.goto(REPO('alpha') + '/');
  1198. await C.waitFor('!!document.querySelector("#reponame")', { label: 'C: repo address (host-only login only)' });
  1199. await hydrated(C);
  1200. await C.goto(BASE + '/');
  1201. await C.waitFor('!!document.querySelector("#createform") || !!document.querySelector("#loginhint")', { label: 'C: back on the main address' });
  1202. await hydrated(C);
  1203. await C.waitFor('!!document.querySelector("#whoami")', { label: 'C: still signed in on the main address', timeout: 30000 }).catch(() => {});
  1204. check('gitoria#24: visiting a repo address first and the main address afterwards leaves him signed in', (await has(C, '#whoami')) && (await txt(C, '#whoami')) === 'alice', J(await dupState()));
  1205. // back to the normal state for the rest of the gate: one Domain cookie
  1206. await C.send('Network.deleteCookies', { name: 'gitoriasid', url: BASE + '/' });
  1207. await C.send('Network.setCookie', { name: 'gitoriasid', value: signedSid, domain: '.gitoria.test', path: '/', httpOnly: true });
  1208. await C.goto(BASE + '/');
  1209. await C.waitFor('!!document.querySelector("#createform")', { label: 'C: main address, one Domain cookie again' });
  1210. await hydrated(C);
  1211. // THE SELECTOR IS ident's CURRENT ONE on every address — the script is loaded from ident (no copy in the app), byte for byte the file in ident's repo
  1212. const identJs = await fetch(`http://127.0.0.1:${IDENT_PORT}/selector.js`).then(r => r.text());
  1213. const wantJs = readFileSync(join(IDENT_DIR, 'selector.js'), 'utf8');
  1214. const srcs = [await C.evaluate(`[...document.querySelectorAll('script[src*="selector"]')].map(x => x.src)`), (await firstHtml('/', `alpha.gitoria.test:${PORT}`)).body.match(/<script[^>]*src="[^"]*selector[^"]*"/g)];
  1215. check('selector: ident\'s current selector.js on every address — loaded from ident (<ident>/selector.js, on the main address and on a repo address), served byte for byte as ident\'s file, the app keeps no copy', J(srcs[0]) === J([IDENT_B + '/selector.js']) && srcs[1].length === 1 && srcs[1][0].includes(IDENT_B + '/selector.js') && identJs === wantJs && !existsSync(join(APP, 'selector.js')) && !readdirSync(join(APP, 'components')).some(f => /selector/i.test(f)), J(srcs) + ' ' + (identJs === wantJs));
  1216. await clickInMenu(C, '#logout', 'button.user-toggle');
  1217. await C.waitFor('!!document.querySelector("#selector.out") && !document.querySelector("#whoami")', { label: 'C: logged out' });
  1218. await C.waitFor(sh(`/choose/.test(r.querySelector('#choose').textContent)`), { label: 'selector reset' });
  1219. await C2.waitFor('!!document.querySelector("#selector.out") && !document.querySelector("#whoami")', { label: 'C2: logged out by the other tab' });
  1220. check('hybriel#43: … and back to logged out, the code still stays', await codeKept(), await C2.evaluate('document.body.innerText.slice(0, 300)'));
  1221. check('selector: logout resets it to "choose ident"', await C.evaluate('!document.querySelector("#selector").hasAttribute("logged-in")') && (await C.evaluate('document.querySelectorAll("ident-selector").length')) === 1);
  1222. await C.goto(REPO('alpha') + '/');
  1223. await C.waitFor('!!document.querySelector("#selector.out") && !!document.querySelector("#reponame")', { label: 'C: repo address' });
  1224. await hydrated(C);
  1225. const repoSel = await firstHtml('/', `alpha.gitoria.test:${PORT}`);
  1226. check('repo address: the SAME selector as on the main address (server html: class "out", no onrepo, the same script and key), nothing hidden, no login button', /<ident-selector[^>]*class="out"/.test(repoSel.body) && !/onrepo/.test(repoSel.body) && !/id="loginbutton"/.test(repoSel.body) && await C.evaluate('getComputedStyle(document.querySelector("#selector")).display !== "none"') && !(await has(C, '#loginbutton')));
  1227. for (const [w, h] of [[390, 844], [1280, 900]]) {
  1228. await viewport(C, w, h);
  1229. check(`IW ${w}px signed out on a repo address: ident's selector stands visible at the top right of the header`, (await C.evaluate(SELECTOR_IN_HEADER)) === 'ok', await C.evaluate(SELECTOR_IN_HEADER));
  1230. }
  1231. await viewport(C, 1280, 900);
  1232. const loginFx = await fetch(API + '/login.js');
  1233. check('/login.js is served', loginFx.status === 200 && /ident-login/.test(await loginFx.text()));
  1234. // ---- logout, then the data survives a restart --------------------------------------------------------------
  1235. await A.goto(BASE + '/');
  1236. await A.waitForSelector('#logout');
  1237. await hydrated(A);
  1238. await clickInMenu(A, '#logout', 'button.user-toggle');
  1239. await A.waitFor('!!document.querySelector("#selector.out") && !document.querySelector("#createform")', { label: 'logged out' });
  1240. await A.waitFor('!!document.querySelector("#loginhint")', { label: 'A: list after the logout' });
  1241. check('logout: the button and the create form switch without a reload', await has(A, '#loginhint'), await A.evaluate('document.body.innerText.slice(0, 300)'));
  1242. // the page switches BEFORE the server has the logout (showOut runs beside the emit): stopping the server now could cut
  1243. // the emit off ("the socket closed and the POST fallback failed", seen once in mission 069) — wait until the server agrees
  1244. let serverOut = false;
  1245. for (let i = 0; i < 50 && !serverOut; i++) {
  1246. serverOut = await A.evaluate(`fetch('/', { cache: 'no-store' }).then(r => r.text()).then(t => /<ident-selector[^>]*class="out"/.test(t))`);
  1247. if (!serverOut) await sleep(200);
  1248. }
  1249. check('logout: the server has it too (a fresh / of that session is signed out)', serverOut);
  1250. await stopServer();
  1251. startServer(env);
  1252. await serverUp();
  1253. const again = await (await fetch(API + '/api/repos')).json();
  1254. check('restart: all repos are still there (storage/mpackdb/repos.db)', again.repos.length === 3 && again.repos.map(x => x.slug).join() === 'gamma,beta-2,alpha', J(again));
  1255. check('storage: the tables are in <store>/mpackdb/', ['repos', 'users'].every(t => readdirSync(join(STORE, 'mpackdb')).some(n => n.startsWith(t + '.'))), J(readdirSync(join(STORE, 'mpackdb'))));
  1256. const problems = Object.entries({ A, B, C, C2, S, L }).flatMap(([n, p]) => p.problems().filter(m => !/favicon|ERR_|Failed to load resource/.test(m.text)).map(m => ({ ...m, text: n + ': ' + m.text })));
  1257. check('browsers: no console errors', problems.length === 0, problems.map(m => m.text).join(" | "));
  1258. check('server log: no error other than absorbed ones', !/error(?!: absorbed)/i.test(log.replace(/error absorbed[^\n]*/g, '')), log.split('\n').filter(l => /error/i.test(l)).slice(0, 5).join(" | "));
  1259. // ==== mission 046: THE INSTALLABLE APP — hl:web's own manifest + service worker (project.hl appIcons / offline =
  1260. // [ Index ]). Last, so every check above ran on the gate's usual Chromes: those are closed now and ONE fresh Chrome
  1261. // treats the two test origins as secure (a service worker needs a secure context; plain-http *.gitoria.test is not
  1262. // one — https / localhost are, so the live site needs no flag). The manifest and every icon over HTTP; Chrome's own
  1263. // verdict; the worker registered and controlling; then OFFLINE: the tab loses the network (the note appears), the
  1264. // server is stopped too (CDP's offline emulation does not reach the worker's own fetches — measured in tracker's
  1265. // gate — so only a dead server proves the cache), and `/` still opens from the cache: header + note + the list as
  1266. // last seen. A data page gets hl:web's "Unavailable offline" page. The same on a repo address (its own origin).
  1267. const html = await (await fetch(API + '/')).text();
  1268. const mhref = (html.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  1269. check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (the token `darker`)',
  1270. mhref === '/__hl/manifest.webmanifest' && html.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')
  1271. && html.includes('<link rel="icon" href="/icons/favicon.svg">') && html.includes('<meta name="theme-color" content="rgb(15, 20, 25)">'), html.slice(0, 900));
  1272. const mres = await fetch(API + mhref);
  1273. const man = await mres.json();
  1274. check('pwa: the manifest is served as application/manifest+json: name "gitoria", start_url /, scope /, display standalone, the token colours',
  1275. /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'gitoria' && man.short_name === 'gitoria' && man.start_url === '/' && man.scope === '/'
  1276. && man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', J(man));
  1277. const iconOk = [];
  1278. for (const ic of man.icons || []) {
  1279. const ir = await fetch(API + ic.src);
  1280. const b = Buffer.from(await ir.arrayBuffer());
  1281. iconOk.push(ir.ok && ic.type === 'image/png' && b.readUInt32BE(16) === Number(ic.sizes.split('x')[0]) && b.readUInt32BE(20) === Number(ic.sizes.split('x')[1]));
  1282. }
  1283. check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',
  1284. iconOk.length === 4 && iconOk.every(Boolean) && ['any', 'maskable'].every(pu => ['192x192', '512x512'].every(sz => man.icons.some(i => i.purpose === pu && i.sizes === sz))), J(man.icons) + ' ' + J(iconOk));
  1285. const touch = await fetch(API + '/icons/apple-touch-icon.png');
  1286. const touchBytes = Buffer.from(await touch.arrayBuffer());
  1287. const fav = await fetch(API + '/icons/favicon.svg');
  1288. const favText = await fav.text();
  1289. const ico = await fetch(API + '/favicon.ico');
  1290. const icoBytes = Buffer.from(await ico.arrayBuffer());
  1291. check('pwa: apple-touch-icon is a 180×180 PNG, the favicon an SVG in gitoria blue, /favicon.ico a real icon file',
  1292. touch.ok && touchBytes.readUInt32BE(16) === 180 && fav.ok && /image\/svg\+xml/.test(fav.headers.get('content-type') || '') && favText.includes('#569bd4')
  1293. && ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);
  1294. const repoMan = await (await fetch(API + '/__hl/manifest.webmanifest', { headers: { Host: `alpha.gitoria.test:${PORT}` } })).json();
  1295. check('pwa: a repo address serves the same manifest (its own origin, start_url / = its Readme)', repoMan.name === 'gitoria' && repoMan.start_url === '/', J(repoMan));
  1296. for (const b of browsers) { try { await b.close(); } catch {} }
  1297. browsers.length = 0;
  1298. process.env.HL_CHROME_ARGS += `|--unsafely-treat-insecure-origin-as-secure=${BASE},${REPO('alpha')}`;
  1299. const P = await newPage();
  1300. const pev = (e) => P.evaluate(e);
  1301. await P.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  1302. const workerOn = async (label) => {
  1303. await hydrated(P);
  1304. await P.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { timeout: 15000, label: label + ': service worker active' });
  1305. await P.waitFor(`!!navigator.serviceWorker.controller`, { timeout: 10000, label: label + ': page controlled by the worker' });
  1306. };
  1307. await P.goto(BASE + '/');
  1308. await P.waitFor('document.querySelectorAll("#repos li").length === 3', { label: 'pwa: list' });
  1309. await workerOn('main');
  1310. const inst = await P.send('Page.getInstallabilityErrors');
  1311. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));
  1312. const am = await P.send('Page.getAppManifest');
  1313. check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, J(am.errors));
  1314. check('pwa: hl:web\'s service worker is registered for the whole app (scope /) and controls the page',
  1315. (await pev(`navigator.serviceWorker.getRegistration().then(r => new URL(r.scope).pathname + ' ' + new URL(r.active.scriptURL).pathname)`)) === '/ /__hl/sw.js' && (await pev('!!navigator.serviceWorker.controller')));
  1316. check('pwa: online, no offline note', !(await has(P, '#offline')));
  1317. await shot(P, 'pwa-phone-online');
  1318. // a repo address: its own origin → its own worker, `/` (the Readme) kept there too
  1319. await P.goto(REPO('alpha') + '/');
  1320. await P.waitFor('!!document.querySelector("#reponame")', { label: 'pwa: alpha readme' });
  1321. await workerOn('alpha');
  1322. check('pwa: a repo address registers its own worker too (scope /)', (await pev(`navigator.serviceWorker.getRegistration().then(r => location.host + ' ' + new URL(r.scope).pathname)`)) === `alpha.gitoria.test:${PORT} /`);
  1323. await P.goto(BASE + '/');
  1324. await P.waitFor('document.querySelectorAll("#repos li").length === 3', { label: 'pwa: list again' });
  1325. await hydrated(P);
  1326. await P.setOffline(true);
  1327. await P.waitFor(`!!document.querySelector('#offline')`, { timeout: 5000, label: 'offline note (live)' }).catch(() => {});
  1328. check('offline: the open page says so within seconds (the shell\'s tick)', (await txt(P, '#offline')) === 'You are offline. Repositories and code need the network.');
  1329. await stopServer();
  1330. let down = false;
  1331. try { await fetch(API + '/api/repos'); } catch { down = true; }
  1332. await P.goto(BASE + '/');
  1333. await P.waitFor(`!!document.querySelector('#offline')`, { timeout: 8000, label: 'offline note after reload' }).catch(() => {});
  1334. check('offline: with the server gone too, a reload of / still opens the shell from the worker\'s cache — header, brand, the note, the list as last seen',
  1335. down && (await txt(P, 'application-header .brand')) === 'gitoria' && await has(P, '#offline')
  1336. && (await pev('document.querySelectorAll("#repos li").length')) === 3
  1337. && (await pev(`getComputedStyle(document.querySelector('application-header')).backgroundColor`)) === 'rgb(15, 20, 25)', 'server down: ' + down + ' ' + (await pev('document.body.innerText.slice(0, 200)')));
  1338. await shot(P, 'pwa-phone-offline');
  1339. await P.goto(REPO('alpha') + '/');
  1340. await P.waitFor(`!!document.querySelector('#offline')`, { timeout: 8000, label: 'offline note on alpha' }).catch(() => {});
  1341. check('offline: a repo address\'s / (the Readme) opens from its own cache, with the note', (await txt(P, '#reponame')) !== null && await has(P, '#offline'), await pev('document.body.innerText.slice(0, 200)'));
  1342. await P.goto(REPO('alpha') + '/code');
  1343. check('offline: a data page (/code) is not kept — hl:web\'s "Unavailable offline" page', (await pev(`!!document.querySelector('main[data-hl-offline]') && document.querySelector('h1').textContent`)) === 'Unavailable offline');
  1344. await P.setOffline(false);
  1345. startServer(env);
  1346. await serverUp();
  1347. await P.goto(BASE + '/');
  1348. await hydrated(P);
  1349. await P.waitFor(`!document.querySelector('#offline')`, { timeout: 5000, label: 'note gone' }).catch(() => {});
  1350. check('back online: / from the server again, no offline note', !(await has(P, '#offline')) && (await pev('document.querySelectorAll("#repos li").length')) === 3);
  1351. } catch (e) {
  1352. failures++;
  1353. console.log('FAIL gate crashed — ' + (e && e.stack || e));
  1354. } finally {
  1355. for (const b of browsers) { try { await b.close(); } catch {} }
  1356. if (ff) { try { await ff.close(); } catch {} }
  1357. await stopServer();
  1358. if (tickets) await tickets.stop();
  1359. if (ident) await ident.stop();
  1360. writeFileSync(join(SCRATCH, 'gate-server.log'), log);
  1361. console.log(`${passes} passed, ${failures} failed`);
  1362. process.exit(failures ? 1 : 0);
  1363. }

Branches

Latest commits

  • 4639caf7Report W61 theme startup blocker and day39 Style probemre
  • 4a3f557eImport layouts theme ebd00b6 for W61 (startup blocked)mre
  • 53ca42b2log: W60 merged, W61 W62 startedmre
  • 80870a33mission W61: style passmre
  • 560fd208Merge W60: helpers, bound forms, login in topics, two form fixes (gitoria#28 #32 #33)mre
  • ac5ba6a4log: W60, #25 measuredmre
  • 220f6342W60: record corrected form proof, full AE and remaining gapsmre
  • 7e31cac5gitoria#28: restrict reply form layout to reply formsmre
  • ae373cfdgitoria#28: keep each reply draft in its thread componentmre
  • eeeebd5agitoria: insert a newly created organization oncemre
  • 34d2d5cagitoria: clear the bound public-key textarea after creationmre
  • 119e54c0W60: restore conductor-owned tracking filesmre
  • 24b479e7W60: record final gates, Chrome failures and AE evidencemre
  • 5e11184cW60: record partial validation, framework gaps and cleanupmre
  • 20fe13fagitoria#33: centralize login and tickets connection statemre
  • 859754c0gitoria#29: retain the offline note and record the framework gapmre
  • d140bc04gitoria#30: reproduce the upsert ordering constraintmre
  • 6960e8f8gitoria#28: keep form values in bound component membersmre
  • 0db27200gitoria#32: share character checks and environment lookupmre
  • 452f6a1amission W60: logic clean-upsmre