gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2bf5343e2bf5343egitoria 007: theme re-copied from layouts dbe3de7 (44 px taps), redundant tap overrides dropped, crumbs class, real-browser walk test, reportmre2bf5343e/tests/browser.mjs

103.7 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. let failures = 0, passes = 0;
  42. function check(label, ok, detail = '') {
  43. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  44. if (ok) passes++; else failures++;
  45. }
  46. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  47. const J = JSON.stringify;
  48. const XSS = '</script><b id="xss">x</b><script>window.__xss=1</script>';
  49. let log = '';
  50. let server = null, ident = null, tickets = null, ff = null;
  51. const browsers = [];
  52. function startServer(extraEnv = {}) {
  53. log += '\n==== gitoria server start\n';
  54. server = spawn(BIN, ['project.hl'], {
  55. cwd: APP,
  56. 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'),
  57. GITORIA_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, ...extraEnv },
  58. stdio: ['ignore', 'pipe', 'pipe'],
  59. });
  60. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  61. }
  62. async function serverUp() {
  63. for (let i = 0; i < 480; i++) { try { const r = await fetch(API + '/api/repos'); if (r.ok) return; } catch {} await sleep(250); }
  64. throw new Error('gitoria did not come up\n' + log);
  65. }
  66. async function stopServer() {
  67. if (!server) return;
  68. try { server.kill('SIGTERM'); } catch {}
  69. await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });
  70. server = null;
  71. }
  72. const SLOW = Number(process.env.GITORIA_GATE_SLOW || 3);
  73. function patient(page) {
  74. const waitFor = page.waitFor.bind(page);
  75. page.waitFor = (expr, o = {}) => waitFor(expr, { ...o, timeout: (o.timeout || 10000) * SLOW });
  76. const goto = page.goto.bind(page);
  77. page.goto = (url, o = {}) => goto(url, { ...o, timeout: (o.timeout || 15000) * SLOW });
  78. return page;
  79. }
  80. async function newPage() {
  81. const b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  82. browsers.push(b);
  83. return patient(await b.newPage());
  84. }
  85. async function viewport(page, width, height) {
  86. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  87. await sleep(250);
  88. }
  89. async function shot(page, name) {
  90. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  91. writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64'));
  92. }
  93. const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  94. const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'page hydrated' });
  95. const txt = (page, sel) => page.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || null`);
  96. const has = (page, sel) => page.evaluate(`!!document.querySelector(${J(sel)})`);
  97. // 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
  98. // the ident dropdown — a person opens the dropdown first. When the target already shows (the login button in the header from
  99. // 60rem, the old shell) it is clicked straight away.
  100. const shows = (page, sel) => page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);
  101. async function clickInMenu(page, sel, toggle) {
  102. await page.waitForSelector(sel);
  103. if (!(await shows(page, sel)) && await has(page, toggle)) {
  104. await page.click(toggle);
  105. await page.waitFor(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`, { label: 'menu open for ' + sel });
  106. }
  107. await page.click(sel);
  108. }
  109. const MEASURE = readFileSync(join(HERE, 'mobile-measure.js'), 'utf8');
  110. // INSIDE ident's selector (shadow DOM): an expression over its root `r`, and a REAL click (as in tickets' gate)
  111. const sh = (expr) => `(() => { const h = document.querySelector('#selector'); const r = h && h.shadowRoot; if (!r) return null; return (${expr}); })()`;
  112. async function shClick(page, inner, name = null) {
  113. 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 }; })()`;
  114. const box = await page.waitFor(find, { label: 'selector ' + inner + ' ' + (name || '') });
  115. const at = { x: Math.round(box.x), y: Math.round(box.y), button: 'left', clickCount: 1 };
  116. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...at, buttons: 0 });
  117. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...at, buttons: 1 });
  118. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, buttons: 0 });
  119. }
  120. async function identSignIn(page, email) {
  121. await page.goto(IDENT_B + '/');
  122. await page.waitForSelector('#email');
  123. await hydrated(page);
  124. await page.type('#email', email);
  125. await page.click('#sendcode');
  126. // ident#20: a sent code NAVIGATES to ident's /code page; type only once that page is hydrated
  127. await page.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident /code page' });
  128. await hydrated(page);
  129. await page.type('#code', ident.lastCode(email));
  130. await page.click('#verify');
  131. await page.waitForSelector('#signout', { timeout: 10000 });
  132. }
  133. // the login button of the page we are on → ident's "choose an identity" → back
  134. async function buttonLogin(page) {
  135. await clickInMenu(page, '#loginbutton', 'button.ident-toggle');
  136. await page.waitForSelector('#chooselist', { timeout: 10000 });
  137. await hydrated(page);
  138. await page.click('#chooselist li:nth-child(1) .choose');
  139. }
  140. async function nameIt(page, name) {
  141. await page.waitForSelector('#nameform');
  142. await hydrated(page);
  143. await page.type('#displayname', name);
  144. await page.click('#namesave');
  145. await page.waitFor('!document.querySelector("#nameform")', { label: 'name saved' });
  146. }
  147. async function createRepo(page, slug, description) {
  148. await page.evaluate('document.querySelector("#slug").value = ""; document.querySelector("#description").value = ""');
  149. await page.type('#slug', slug);
  150. if (description) await page.type('#description', description);
  151. await page.click('#createsave');
  152. }
  153. // the FIRST HTML of a page as the server sends it, for any Host (node's fetch cannot set Host) — gitoria#16
  154. const firstHtml = (path, host, cookie) => new Promise((res, rej) => {
  155. const rq = httpRequest({ host: '127.0.0.1', port: PORT, path, headers: { host, ...(cookie ? { cookie } : {}) } }, (r) => {
  156. let b = ''; r.setEncoding('utf8'); r.on('data', d => b += d); r.on('end', () => res({ status: r.statusCode, headers: r.headers, body: b }));
  157. });
  158. rq.on('error', rej); rq.end();
  159. });
  160. const bodyText = (html) => ((html.match(/<body>([\s\S]*)<\/body>/) || [])[1] || '').replace(/<script[\s\S]*?<\/script>/g, '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ');
  161. const emitFace = async (event, payload, cookie) => {
  162. const r = await fetch(API + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: 1, event, payload }) });
  163. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  164. return { status: r.status, raw: t, value: j && j.value };
  165. };
  166. try {
  167. // ---- our own ident; gitoria is registered with ONE origin: the main address ------------------------
  168. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  169. const alice = await ident.signIn('[email protected]');
  170. const gateAcct = await ident.signIn('[email protected]');
  171. const APPKEY = await ident.registerApp(alice, 'gitoria (gate)', [BASE]);
  172. 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')));
  173. // our own tickets (a copy without .env), with a token for its user "gitoria" — gitoria opens tickets with it
  174. tickets = await startTickets({ ticketsDir: TICKETS_DIR, workDir: join(STORE, 'tickets'), port: TICKETS_PORT, ident, who: alice, origins: ORIGINS });
  175. 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')));
  176. const env = { IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret, GITORIA_TICKETS_URL: tickets.base };
  177. startServer(env);
  178. await serverUp();
  179. // ---- the API (reads are public) --------------------------------------------------------------
  180. let r = await fetch(API + '/api/repos');
  181. check('api: GET /api/repos is empty at the start', r.status === 200 && J(await r.json()) === '{"repos":[]}');
  182. r = await fetch(API + '/api/repos', { method: 'POST', body: '{}' });
  183. check('api: POST /api/repos → 405 (creating is a web action)', r.status === 405);
  184. r = await fetch(API + '/api/repos/nothing');
  185. check('api: unknown repo → 404', r.status === 404);
  186. r = await fetch(API + '/api/repos', { headers: { accept: 'text/markdown' } });
  187. check('api: Markdown read view of the list', /text\/markdown/.test(r.headers.get('content-type')) && /^# Repositories \(0\)/.test(await r.text()));
  188. // ---- the login button's server half: where does ?next= lead? ------------------------------------
  189. const cbCookie = 'gitoriasid=' + 'ab'.repeat(16);
  190. // a failed login is a PAGE now (components/loginfailed.hl, gitoria#16): the reason is parked in the session → /login/failed
  191. const failedPage = async (url) => {
  192. const c = await fetch(url, { redirect: 'manual' });
  193. const ck = (c.headers.get('set-cookie') || '').split(';')[0];
  194. const pg = await firstHtml('/login/failed', `gitoria.test:${PORT}`, ck);
  195. return { status: c.status, location: c.headers.get('location'), cookie: ck, page: bodyText(pg.body), pageStatus: pg.status };
  196. };
  197. let lf = await failedPage(API + '/login/callback');
  198. 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));
  199. lf = await failedPage(API + '/login/callback?ident_code=' + 'ab'.repeat(24));
  200. check('login: an unknown code → /login/failed says "ident refused"', lf.status === 302 && lf.location === '/login/failed' && /ident refused/.test(lf.page), J(lf));
  201. const nexts = [
  202. ['/', '/'], ['/x?y=1', '/x?y=1'], [REPO('alpha') + '/code', REPO('alpha') + '/code'], [REPO('alpha') + '/', REPO('alpha') + '/'], [REPO('alpha'), REPO('alpha') + '/'],
  203. ['//evil.example', '/'], ['http://evil.example/', '/'], [REPO('www') + '/', '/'], [`http://alpha.gitoria.test:${PORT}.evil.example/`, '/'],
  204. [REPO('alpha') + '/a b', '/'], [REPO('a--b') + '/', '/'], [REPO('Alpha') + '/', '/'], ['/x\r\nSet-Cookie: a=b', '/'], ['/login/callback', '/'], ['', '/'],
  205. [`https://alpha.gitoria.test:${PORT}/`, '/'], [`http://x.y.gitoria.test:${PORT}/`, '/'],
  206. ];
  207. let allNext = true, nextDetail = '';
  208. for (const [want, expect] of nexts) {
  209. const code = await ident.selectorCode(gateAcct, APPKEY, BASE);
  210. const c = await fetch(API + '/login/callback?next=' + encodeURIComponent(want) + '&ident_code=' + code, { redirect: 'manual' });
  211. const loc = c.headers.get('location');
  212. if (c.status !== 302 || loc !== expect) { allNext = false; nextDetail += ` [${J(want)} → ${c.status} ${loc}, wanted ${expect}]`; }
  213. }
  214. check('login: ?next= accepts a path or a valid repo address, everything else → /', allNext, nextDetail);
  215. const cookieCode = await ident.selectorCode(gateAcct, APPKEY, BASE);
  216. const cc = await fetch(API + '/login/callback?ident_code=' + cookieCode, { redirect: 'manual' });
  217. const setCookie = cc.headers.get('set-cookie') || '';
  218. 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);
  219. // ---- the re-vendored Hybriel (mission 033): what the dropped local patches did is upstream now ------------
  220. r = await fetch(API + '/__hl/app.css');
  221. const css = await r.text();
  222. 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));
  223. // ---- forged face session: nobody logged in may create --------------------------------------------
  224. let f = await emitFace('gitoriaCreate', ['forged', '', { user: { id: 'x' } }]);
  225. check('face: a forged trailing session argument creates nothing', !(await (await fetch(API + '/api/repos/forged')).ok) && !(f.value && f.value.repo), f.raw);
  226. f = await emitFace('gitoriaCreate', ['anon', '']);
  227. check('face: not logged in → refused with a message', f.value && /log in/.test(f.value.error || ''), f.raw);
  228. // ---- A = alice in a browser -----------------------------------------------------------------------
  229. const A = await newPage();
  230. await identSignIn(A, '[email protected]');
  231. await A.goto(BASE + '/');
  232. await A.waitFor('!!document.querySelector("#heading")', { label: 'main address shows the list' });
  233. await hydrated(A);
  234. 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')));
  235. check('signed out: the login button goes to ident /login with the app key and the callback', (await A.evaluate('document.querySelector("#loginbutton").getAttribute("href")')) === `${IDENT_B}/login?key=${APPKEY.key}&return=${encodeURIComponent(BASE + '/login/callback')}`);
  236. await buttonLogin(A);
  237. await A.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector("#nameform")`, { label: 'A back with the name prompt' });
  238. check('button: back on the main address, logged in, asked for a display name', await has(A, '#whoami') && !(await has(A, '#loginbutton')));
  239. await nameIt(A, 'alice');
  240. await A.waitForSelector('#createform');
  241. check('named: the "create a repository" form appears', (await txt(A, '#whoami')) === 'alice');
  242. // ---- B = a signed-out viewer of the main address, for the live list ---------------------------------
  243. const B = await newPage();
  244. await B.goto(BASE + '/');
  245. await B.waitForSelector('#empty');
  246. await hydrated(B);
  247. // ---- create ---------------------------------------------------------------------------------------
  248. const errAfter = async (slug, want) => {
  249. await createRepo(A, slug, '');
  250. await A.waitFor(`new RegExp(${J(want)}).test(document.querySelector("#createerror").textContent)`, { label: 'error for ' + slug });
  251. const e = await txt(A, '#createerror');
  252. check(`create: "${slug}" is refused — ${want}`, new RegExp(want).test(e), e);
  253. return e;
  254. };
  255. await errAfter('Bad Slug', 'only have lowercase');
  256. await errAfter('www', 'reserved');
  257. await errAfter('ab-', 'starts and ends');
  258. await errAfter('ab--cd', 'two hyphens');
  259. await errAfter('-abc', 'starts and ends');
  260. check('create: nothing was stored by the refusals', J(await (await fetch(API + '/api/repos')).json()) === '{"repos":[]}');
  261. await A.evaluate('document.querySelector("#createerror").textContent = ""');
  262. await createRepo(A, 'alpha', 'The first repository');
  263. await A.waitForSelector('#created');
  264. 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') + '/');
  265. 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'));
  266. await B.waitFor('document.querySelectorAll("#repos li").length === 1', { label: 'B sees alpha live' });
  267. check('live: the signed-out viewer B sees alpha without a reload', /alpha/.test(await txt(B, '#repos')) && !(await has(B, '#empty')));
  268. await errAfter('alpha', 'taken');
  269. await A.evaluate('document.querySelector("#createerror").textContent = ""');
  270. await createRepo(A, 'beta-2', '');
  271. await A.waitFor('document.querySelectorAll("#repos li").length === 2', { label: 'A: two repos' });
  272. await B.waitFor('document.querySelectorAll("#repos li").length === 2', { label: 'B: two repos' });
  273. 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');
  274. r = await fetch(API + '/api/repos/alpha');
  275. const alphaRow = await r.json();
  276. 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));
  277. r = await fetch(API + '/api/repos/alpha', { headers: { accept: 'text/markdown' } });
  278. const md = await r.text();
  279. check('api: Markdown read view of a repo', /^# alpha\n/.test(md), md);
  280. // ---- the address: <slug>.gitoria.test ------------------------------------------------------------------
  281. await A.goto(REPO('alpha') + '/');
  282. await A.waitFor('!!document.querySelector("#reponame")', { label: 'alpha at its own address' });
  283. 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'));
  284. check('alpha.<domain>: the login is shared with the main address (same cookie)', (await txt(A, '#whoami')) === 'alice');
  285. check('alpha.<domain>: the title is the repo page, tab title set', (await A.evaluate('document.title')) !== '');
  286. await A.goto(REPO('nothing-here') + '/');
  287. await A.waitFor('!!document.querySelector("#missing")', { label: 'unknown address' });
  288. 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 + '/');
  289. await A.goto(REPO('www') + '/');
  290. await A.waitFor('!!document.querySelector("#missing")', { label: 'reserved address' });
  291. check('a reserved address is no repo either', true);
  292. await A.goto(BASE + '/');
  293. await A.waitFor('!!document.querySelector("#repos li")', { label: 'back on main' });
  294. await A.click('#repos li:nth-child(2) .slug');
  295. await A.waitFor(`location.hostname === 'alpha.gitoria.test' && !!document.querySelector("#reponame")`, { label: 'click on alpha' });
  296. check('clicking a repo in the list opens its own address', (await txt(A, '#reponame')) === 'alpha');
  297. // ---- login FROM a repo address: through the main address and back --------------------------------------
  298. await identSignIn(B, '[email protected]');
  299. await B.goto(REPO('alpha') + '/');
  300. await B.waitFor('!!document.querySelector("#reponame")', { label: 'B at alpha' });
  301. check('signed out at alpha.<domain>: repo visible, login button there', (await has(B, '#loginbutton')) && !(await has(B, '#whoami')));
  302. await hydrated(B);
  303. await buttonLogin(B);
  304. await B.waitFor(`location.href === ${J(REPO('alpha') + '/')} && !!document.querySelector("#whoami")`, { label: 'B logged in back at alpha' });
  305. await B.waitFor('!!document.querySelector("#reponame")', { label: 'B: the repo page after the login' });
  306. check('login started at alpha.<domain> returns to alpha.<domain>, logged in', (await txt(B, '#whoami')) === 'alice' && (await txt(B, '#reponame')) === 'alpha', await B.evaluate('location.href + " " + document.body.innerText.slice(0, 300)'));
  307. await B.goto(BASE + '/');
  308. await B.waitForSelector('#createform');
  309. check('the same login holds on the main address (cookie for all addresses)', (await txt(B, '#whoami')) === 'alice');
  310. // ---- the homepage of a repo (ticket #8): README.md, or the $docs folder --------------------------------------
  311. check('a new repo has an empty bare git repository', existsSync(join(STORE, 'git', 'alpha.git', 'HEAD')), J(existsSync(join(STORE, 'git'))));
  312. const pushFiles = (slug, files) => { // a commit into the bare repo, the way a push would leave it
  313. const work = join(STORE, 'work-' + slug);
  314. rmSync(work, { recursive: true, force: true }); mkdirSync(work, { recursive: true });
  315. const git = (...a) => execFileSync('git', ['-C', work, '-c', 'user.name=t', '-c', '[email protected]', ...a], { stdio: 'pipe' });
  316. git('init', '-q', '-b', 'main');
  317. for (const [p, c] of Object.entries(files)) { mkdirSync(dirname(join(work, p)), { recursive: true }); writeFileSync(join(work, p), c); }
  318. git('add', '-A'); git('commit', '-q', '-m', 'files');
  319. git('push', '-q', '-f', join(STORE, 'git', slug + '.git'), 'main');
  320. };
  321. 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'); };
  322. await A.goto(REPO('alpha') + '/');
  323. check('an empty repo says it has no README.md yet', /no README\.md yet/.test(await homeText(A)));
  324. pushFiles('alpha', {
  325. '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',
  326. 'docs/other.md': '# not the homepage\n',
  327. });
  328. await A.goto(REPO('alpha') + '/');
  329. const alphaText = await homeText(A);
  330. 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));
  331. 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'))); })()`));
  332. pushFiles('alpha', {
  333. 'README.md': '# Root readme\n',
  334. '$docs/b-second.md': '# Second doc\n\nText two.\n',
  335. '$docs/a-first.md': '# First doc\n\nText one.\n',
  336. '$docs/sub/c-third.md': '## Third doc\n',
  337. '$docs/notes.txt': 'not markdown\n',
  338. });
  339. await A.goto(REPO('alpha') + '/');
  340. await homeText(A);
  341. 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)'));
  342. 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)); })());
  343. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  344. await viewport(A, w, h);
  345. 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' });
  346. await A.goto(REPO('beta-2') + '/');
  347. await homeText(A);
  348. check(`layout ${w}px: the homepage has no horizontal overflow`, await noOverflow(A));
  349. await shot(A, `${name}-home`);
  350. }
  351. // ---- browsing code (ticket #9): /code, /branch/<name>, /commit/<id> ------------------------------------------
  352. const gitIn = (work, ...a) => execFileSync('git', ['-C', work, '-c', 'user.name=t', '-c', '[email protected]', ...a], { stdio: 'pipe' }).toString();
  353. const work = join(STORE, 'work-code');
  354. rmSync(work, { recursive: true, force: true }); mkdirSync(join(work, 'src', 'deep'), { recursive: true });
  355. gitIn(work, 'init', '-q', '-b', 'main');
  356. writeFileSync(join(work, 'README.md'), '# Code repo\n');
  357. writeFileSync(join(work, 'src', 'a.txt'), 'line one\n\n indented <b>&amp;</b>\n');
  358. writeFileSync(join(work, 'src', 'deep', 'b.txt'), 'deep file\n');
  359. writeFileSync(join(work, 'my file.txt'), 'spaced name\n');
  360. writeFileSync(join(work, 'bin.dat'), Buffer.from([0, 1, 2, 255, 0, 254, 0, 0]));
  361. gitIn(work, 'add', '-A'); gitIn(work, 'commit', '-q', '-m', 'first commit');
  362. const firstSha = gitIn(work, 'rev-parse', 'HEAD').trim();
  363. writeFileSync(join(work, 'src', 'a.txt'), 'main changed\n');
  364. gitIn(work, 'commit', '-qam', 'second on main');
  365. const mainSha = gitIn(work, 'rev-parse', 'HEAD').trim();
  366. gitIn(work, 'checkout', '-q', '-b', 'feature/x', firstSha);
  367. writeFileSync(join(work, 'src', 'a.txt'), 'feature changed\n');
  368. writeFileSync(join(work, 'only-feature.txt'), 'f\n');
  369. gitIn(work, 'add', '-A'); gitIn(work, 'commit', '-q', '-m', 'feature work');
  370. gitIn(work, 'checkout', '-q', '-b', 'dev', firstSha);
  371. gitIn(work, 'push', '-q', '-f', join(STORE, 'git', 'alpha.git'), 'main', 'feature/x', 'dev');
  372. const codeReady = (p) => p.waitFor('!document.querySelector("#codeloading") && (!!document.querySelector("#codemessage") || !!document.querySelector("#codefile") || !!document.querySelector("#entries") || !!document.querySelector("#noentries"))', { label: 'code answer' });
  373. const names = (p, sel) => p.evaluate(`[...document.querySelectorAll(${J(sel)})].map(x => x.textContent.trim()).join('|')`);
  374. await viewport(A, 1280, 900);
  375. await A.goto(REPO('alpha') + '/code');
  376. await codeReady(A);
  377. 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)'));
  378. 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'));
  379. await A.click('#entries a.dir');
  380. await A.waitFor('location.pathname === "/code/src" && !!document.querySelector("#crumbs strong") && document.querySelector("#crumbs strong").textContent === "src" && !!document.querySelector("#entries")', { label: 'folder opened' });
  381. 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)'));
  382. await A.goto(REPO('alpha') + '/code/src/a.txt');
  383. await codeReady(A);
  384. 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)'));
  385. await A.goto(REPO('alpha') + '/commit/' + firstSha + '/src/a.txt');
  386. await codeReady(A);
  387. 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)'));
  388. await A.goto(REPO('alpha') + '/commit/' + firstSha.slice(0, 7));
  389. await codeReady(A);
  390. 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)'));
  391. await A.goto(REPO('alpha') + '/branch/feature/x');
  392. await codeReady(A);
  393. 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)'));
  394. await A.goto(REPO('alpha') + '/branch/feature/x/src/a.txt');
  395. await codeReady(A);
  396. 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)'));
  397. await A.goto(REPO('alpha') + '/code/my%20file.txt');
  398. await codeReady(A);
  399. check('a file with a space in its name opens', (await names(A, '#lines li')) === 'spaced name');
  400. await A.goto(REPO('alpha') + '/code/bin.dat');
  401. await codeReady(A);
  402. check('a binary file is not shown as text', (await has(A, '#binary')) && !(await has(A, '#lines li')));
  403. 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/]]) {
  404. await A.goto(REPO('alpha') + path);
  405. await codeReady(A);
  406. check(`${path}: a plain message, no crash`, want.test(await txt(A, '#codemessage') || ''), await A.evaluate('document.body.innerText.slice(0, 200)'));
  407. }
  408. await A.goto(BASE + '/');
  409. await A.waitForSelector('#createform');
  410. await hydrated(A);
  411. await createRepo(A, 'gamma', XSS);
  412. await A.waitFor('!!document.querySelector("#created")', { label: 'gamma created' });
  413. await A.goto(REPO('gamma') + '/code');
  414. await codeReady(A);
  415. 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)'));
  416. // "Add code to this repository" (gitoria#20): stands as plain text, not a collapsible, ONLY on the Code page of an
  417. // empty repo (gamma) — checked on every tab of an empty repo AND a filled one (alpha, has commits)
  418. 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"'));
  419. const addCodeTabs = [['/', '#nohomepage, #homepage'], ['/pulls', '#pullsmessage, #pullshelp'], ['/releases', '#releasesmessage, #releaseshelp'], ['/tickets', '#ticketsnotconnected, #ticketlist'], ['/settings', '#connecttickets, #notconnected']];
  420. for (const [p, sel] of addCodeTabs) {
  421. await A.goto(REPO('gamma') + p);
  422. await A.waitFor(`!!document.querySelector(${J(sel)})`, { label: 'gamma ' + p + ' for addcode check' });
  423. 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)'));
  424. }
  425. for (const [p, sel] of [['/code', '#entries, #codemessage'], ...addCodeTabs]) {
  426. await A.goto(REPO('alpha') + p);
  427. await A.waitFor(`!!document.querySelector(${J(sel)})`, { label: 'alpha ' + p + ' for addcode check' });
  428. check(`filled repo ${p}: no "Add code" box (already has commits)`, !(await has(A, '#addcode')), await A.evaluate('document.body.innerText.slice(0, 150)'));
  429. }
  430. await A.goto(REPO('alpha') + '/code');
  431. await codeReady(A);
  432. 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'));
  433. await hydrated(A); // the view is in the FIRST HTML now: wait for the page to be live before clicking
  434. await A.click('#branches .setmain');
  435. await A.waitFor('document.querySelector("#coderef") && document.querySelector("#coderef").textContent === "dev"', { label: 'main branch changed' });
  436. 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)'));
  437. await A.goto(REPO('alpha') + '/');
  438. await homeText(A);
  439. check('the homepage README follows the main branch too', await A.evaluate('!!document.querySelector("#homepage")'));
  440. const S = await newPage();
  441. await S.goto(REPO('alpha') + '/code');
  442. await codeReady(S);
  443. 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);
  444. const forged = await emitFace('gitoriaSetBranch', ['alpha', 'main', 'code', '', 'x'], '');
  445. const still = await (await fetch(API + '/api/repos/alpha')).json();
  446. check('face: a stranger cannot change the main branch', still.branch === 'dev', J(forged) + J(still));
  447. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  448. await viewport(A, w, h);
  449. await A.goto(REPO('alpha') + '/code');
  450. await codeReady(A);
  451. check(`layout ${w}px: /code has no horizontal overflow`, await noOverflow(A));
  452. await shot(A, `${name}-code`);
  453. await A.goto(REPO('alpha') + '/code/src/a.txt');
  454. await codeReady(A);
  455. check(`layout ${w}px: a file view has no horizontal overflow of the page`, await noOverflow(A));
  456. await shot(A, `${name}-file`);
  457. }
  458. await viewport(A, 1280, 900);
  459. // the connect flow in the browser: the owner (alice, logged in at tickets with the gate's cookie) clicks "Tickets: connect"
  460. // in the repo's settings, picks the project on tickets and continues back to the repo
  461. const connectRepo = async (page, slug, projectValue, newTitle) => {
  462. const [ck, cv] = tickets.cookie.split('=');
  463. await page.send('Network.setCookie', { name: ck, value: cv, url: tickets.base });
  464. await page.goto(REPO(slug) + '/settings');
  465. await page.waitFor('!!document.querySelector("#connecttickets")', { label: 'settings: connect button' });
  466. await page.click('#connecttickets');
  467. await page.waitFor('location.origin === ' + J(tickets.base) + ' && !!document.querySelector("#connectform")', { label: 'tickets connect page' });
  468. await hydrated(page);
  469. if (newTitle) {
  470. await page.evaluate('(() => { const s = document.querySelector("#connectproject"); s.value = ""; s.dispatchEvent(new Event("change", { bubbles: true })); })()');
  471. await page.waitFor('!!document.querySelector("#connecttitleinput")', { label: 'new project title field' });
  472. await page.type('#connecttitleinput', newTitle);
  473. } else if (projectValue) {
  474. await page.evaluate(`(() => { const s = document.querySelector("#connectproject"); s.value = ${J(projectValue)}; s.dispatchEvent(new Event("change", { bubbles: true })); })()`);
  475. }
  476. await page.click('#connectconfirm');
  477. try { await page.waitFor('!!document.querySelector("#connectcontinue")', { label: 'tickets: connected' }); }
  478. catch (e) { throw new Error(e.message + ' | page: ' + await page.evaluate('(document.querySelector("#connectmessage") || {}).textContent + " / " + document.body.innerHTML.slice(0, 1500)')); }
  479. await page.click('#connectcontinue');
  480. await page.waitFor(`location.hostname === '${slug}.gitoria.test' && !!document.querySelector("#connectedto")`, { label: 'back in settings, connected' });
  481. };
  482. // ---- the repo's tickets (gitoria#10): /tickets lists tickets.worldapi.org's project, the first ticket makes it ----
  483. const PROJ = 'alpha.gitoria.test';
  484. await A.goto(REPO('alpha') + '/tickets');
  485. await A.waitFor('!!document.querySelector("#ticketsnotconnected")', { label: 'tickets page, not connected' });
  486. check('connect: an unconnected repo says so on /tickets, no form, no list', !(await has(A, '#newticketform')) && !(await has(A, '#ticketlist')));
  487. await S.goto(REPO('alpha') + '/settings');
  488. await S.waitFor('!!document.querySelector("#notconnected")', { label: 'S: settings' });
  489. check('connect: a signed-out viewer sees "not connected" and no connect button', !(await has(S, '#connecttickets')) && !(await has(S, '#disconnecttickets')));
  490. // the owner connects: the project exists in tickets (made by the tickets user of alice, its admin)
  491. 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 }) });
  492. check('connect: the project for alpha exists in tickets', mk.status === 201 || mk.status === 200, String(mk.status));
  493. await connectRepo(A, 'alpha', null, null);
  494. check('connect: settings says connected to that project, with the disconnect button', /alpha/.test(await txt(A, '#connectedto')) && (await has(A, '#disconnecttickets')));
  495. 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`))));
  496. await A.goto(REPO('alpha') + '/tickets');
  497. await A.waitFor('!!document.querySelector("#noticketsyet")', { label: 'tickets page, connected, no ticket yet' });
  498. 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')));
  499. await S.goto(REPO('alpha') + '/tickets');
  500. await S.waitFor('!!document.querySelector("#noticketsyet")', { label: 'S: tickets page' });
  501. await hydrated(S);
  502. check('tickets: a signed-out viewer sees the page with a login hint and no form', (await has(S, '#ticketsloginhint')) && !(await has(S, '#newticketform')));
  503. await hydrated(A);
  504. await A.evaluate('document.querySelector("#newticket").open = true');
  505. await A.type('#ticketsubject', ' ');
  506. await A.click('#ticketsave');
  507. await A.waitFor('!!document.querySelector("#newticketerror").textContent', { label: 'blank subject refused' });
  508. await A.evaluate('document.querySelector("#ticketsubject").value = ""; document.querySelector("#newticket").open = true');
  509. check('tickets: a blank subject is refused in words', /subject/.test(await txt(A, '#newticketerror')));
  510. await A.type('#ticketsubject', 'First <b>ticket</b>');
  511. await A.type('#ticketsummary', 'Some **words**');
  512. await A.click('#ticketsave');
  513. await A.waitFor('document.querySelectorAll("#ticketlist li").length === 1', { label: 'first ticket listed' });
  514. const t1 = (await tickets.api(`/api/projects/${PROJ}/tickets/1`)).json.ticket;
  515. 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));
  516. 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')}; })()`));
  517. // the server pushes `ticketOpened` BEFORE it answers the face, so the list row can show up before openIt clears the form
  518. // (seen once on hybriel master ff51cf46) — wait for the face's answer, the notice
  519. await A.waitFor('!!document.querySelector("#ticketnotice")', { label: 'notice after the face answered' }).catch(() => null);
  520. 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') }));
  521. await S.waitFor('document.querySelectorAll("#ticketlist li").length === 1', { label: 'S sees it live' });
  522. check('live: the signed-out viewer sees the new ticket without a reload', /First/.test(await txt(S, '#ticketlist')) && !(await has(S, '#noticketsyet')));
  523. // a ticket opened in tickets itself, and one with a name only tickets knows: shown on the next load
  524. 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' }) });
  525. check('tickets: a ticket made on tickets.worldapi.org directly → 201', ext.status === 201);
  526. await A.goto(REPO('alpha') + '/tickets');
  527. await A.waitFor('document.querySelectorAll("#ticketlist li").length === 2', { label: 'two tickets after reload' });
  528. 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);
  529. check('tickets: another repo has none of them', (await tickets.api('/api/projects/beta-2.gitoria.test/tickets')).status === 404);
  530. await S.goto(REPO('beta-2') + '/tickets');
  531. await S.waitFor('!!document.querySelector("#ticketsnotconnected")', { label: 'beta-2 is not connected' });
  532. check('tickets: beta-2 is not connected and shows none of them', !(await has(S, '#ticketlist')));
  533. await S.goto(REPO('nothing-here') + '/tickets');
  534. await S.waitFor('!!document.querySelector("#missing")', { label: 'unknown repo tickets' });
  535. check('tickets: an address nobody created has no tickets page', true);
  536. f = await emitFace('gitoriaOpenTicket', ['alpha', 'anon', '']);
  537. 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);
  538. f = await emitFace('gitoriaOpenTicket', ['alpha', 'forged', '', { user: { id: 'x' } }]);
  539. 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);
  540. f = await emitFace('gitoriaOpenTicket', ['no-such-repo', 'x', '']);
  541. 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);
  542. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  543. await viewport(A, w, h);
  544. await A.goto(REPO('alpha') + '/tickets');
  545. await A.waitFor('document.querySelectorAll("#ticketlist li").length === 2', { label: 'tickets for layout' });
  546. check(`layout ${w}px: /tickets has no horizontal overflow`, await noOverflow(A));
  547. await shot(A, `${name}-tickets`);
  548. }
  549. await viewport(A, 1280, 900);
  550. await tickets.stop();
  551. await S.goto(REPO('alpha') + '/tickets');
  552. await S.waitFor('!!document.querySelector("#ticketserror")', { label: 'tickets down' });
  553. check('tickets down: the page says tickets.worldapi.org did not answer', /did not answer/.test(await txt(S, '#ticketserror')));
  554. tickets = await startTickets({ ticketsDir: TICKETS_DIR, workDir: join(STORE, 'tickets2'), port: TICKETS_PORT, ident, who: alice, origins: ORIGINS });
  555. // ---- #N links both ways (gitoria#18): the tickets copy is new; connect alpha again, then a REAL push over HTTP ----
  556. await fetch(tickets.base + '/api/projects', { method: 'POST', headers: { authorization: 'Bearer ' + tickets.token, 'content-type': 'application/json' }, body: J({ title: PROJ, slug: PROJ }) });
  557. 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' }) });
  558. await connectRepo(A, 'alpha', null, null);
  559. check('connect: connecting again after tickets was replaced works (new key, page says connected)', /alpha/.test(await txt(A, '#connectedto')));
  560. const sid = (await A.cookies([REPO('alpha')])).find(c => /sid$/.test(c.name));
  561. const mkTok = await emitFace('gitoriaMakeToken', ['gate push'], sid.name + '=' + sid.value);
  562. const PUSHTOKEN = mkTok.value && mkTok.value.token;
  563. check('links: a push token for alice', /^gtr_[0-9a-f]{40}$/.test(PUSHTOKEN || ''), mkTok.raw);
  564. const lw = join(STORE, 'work-links');
  565. rmSync(lw, { recursive: true, force: true });
  566. execFileSync('git', ['clone', '-q', join(STORE, 'git', 'alpha.git'), lw], { stdio: 'pipe' });
  567. const lg = (...a) => execFileSync('git', ['-C', lw, '-c', 'user.name=alice', '-c', '[email protected]', ...a], { stdio: 'pipe' }).toString();
  568. 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);
  569. const ticketMd = async (n) => (await (await fetch(`${tickets.base}/api/projects/${PROJ}/tickets/${n}`, { headers: { accept: 'text/markdown' } })).text());
  570. writeFileSync(join(lw, 'login.txt'), 'x\n'); lg('add', '-A'); lg('commit', '-q', '-m', 'fix login, #1 and a bogus #99');
  571. const mentionSha = lg('rev-parse', 'HEAD').trim();
  572. pushHttp('HEAD:main');
  573. let tmd = '';
  574. 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); }
  575. 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));
  576. check('links: a ticket that does not exist (#99) is skipped quietly', (await tickets.api(`/api/projects/${PROJ}/tickets/99`)).status === 404);
  577. const cnt = (t) => (t.match(/Mentioned in commit/g) || []).length;
  578. pushHttp('HEAD:refs/heads/other');
  579. await sleep(1500);
  580. check('links: pushing the same commit again does not comment twice', cnt(await ticketMd(1)) === 1, String(cnt(await ticketMd(1))));
  581. await A.goto(REPO('alpha') + '/commit/' + mentionSha);
  582. await A.waitFor('!!document.querySelector("#reponame")', { label: 'commit page' });
  583. await sleep(1500);
  584. 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`));
  585. // "fixes #1" in a merged pull request sets the ticket to review
  586. 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');
  587. pushHttp('fixbr');
  588. await A.goto(REPO('alpha') + '/pulls');
  589. await A.waitFor('!!document.querySelector("#reponame")', { label: 'pulls page' });
  590. await sleep(1500);
  591. 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')})`));
  592. check('links: an open pull request does not change the ticket', (await tickets.api(`/api/projects/${PROJ}/tickets/1`)).json.ticket.state === 'open');
  593. lg('checkout', '-q', 'main'); lg('merge', '-q', '--no-ff', '-m', 'merge the fix', 'fixbr');
  594. pushHttp('main');
  595. let st = '';
  596. 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); }
  597. check('links: the pull request "fixes #1" is merged (pushed) → ticket 1 is set to review', st === 'review', st);
  598. const before2 = cnt(await ticketMd(1));
  599. pushHttp('main');
  600. await sleep(1000);
  601. 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);
  602. // disconnect from gitoria's side, and tickets' side sees it gone
  603. await A.goto(REPO('alpha') + '/settings');
  604. await A.waitFor('!!document.querySelector("#disconnecttickets")', { label: 'settings, connected' });
  605. await hydrated(A);
  606. await A.click('#disconnecttickets');
  607. await A.waitFor('!!document.querySelector("#notconnected")', { label: 'disconnected' });
  608. await A.goto(REPO('alpha') + '/tickets');
  609. await A.waitFor('!!document.querySelector("#ticketsnotconnected")', { label: 'tickets page after disconnect' });
  610. check('connect: "Forget the connection" → /tickets says not connected again', true);
  611. await connectRepo(A, 'alpha', null, null);
  612. // ---- pull requests (gitoria#11): /pulls lists the commits that start with |||PR -------------------------------
  613. const pw = join(STORE, 'work-pulls');
  614. rmSync(pw, { recursive: true, force: true }); mkdirSync(pw, { recursive: true });
  615. gitIn(pw, 'init', '-q', '-b', 'main');
  616. writeFileSync(join(pw, 'a.txt'), 'base\n'); gitIn(pw, 'add', '-A'); gitIn(pw, 'commit', '-q', '-m', 'base');
  617. const baseSha = gitIn(pw, 'rev-parse', 'HEAD').trim();
  618. 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(); };
  619. gitIn(pw, 'branch', 'dev');
  620. const fixSha = branchCommit('fix-a', '|||PR Fix the <b>thing</b>');
  621. gitIn(pw, 'commit', '-q', '--allow-empty', '-m', 'more work on fix-a');
  622. branchCommit('topic/one', '|||PR|dev] Topic to dev');
  623. branchCommit('ghost', '|||PR|nope] Lost target');
  624. branchCommit('plain', 'not a pull request |||PR');
  625. branchCommit('nospace', '|||PR|main]glued');
  626. branchCommit('old', '|||PR Old work');
  627. gitIn(pw, 'checkout', '-q', 'main'); gitIn(pw, 'merge', '-q', '--ff-only', 'old');
  628. gitIn(pw, 'push', '-q', '-f', join(STORE, 'git', 'beta-2.git'), 'main', 'dev', 'fix-a', 'topic/one', 'ghost', 'plain', 'nospace', 'old');
  629. const pullsReady = (p) => p.waitFor('!document.querySelector("#pullsloading") && (!!document.querySelector("#pullsmessage") || !!document.querySelector("#pullshelp"))', { label: 'pulls answer' });
  630. await A.goto(REPO('beta-2') + '/pulls');
  631. await pullsReady(A);
  632. const rows = await A.evaluate(`[...document.querySelectorAll('#pulllist li')].map(li => [li.querySelector('.subject').textContent, li.querySelector('.open,.merged').textContent, li.querySelector('.branches').textContent.replace(/\\s+/g, ' ').trim()].join(' ~ '))`);
  633. 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));
  634. 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));
  635. check('/pulls: the title links to the commit, 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 a.querySelector('.subject a').href.endsWith('/commit/${fixSha}') && a.querySelector('a.source').pathname === '/branch/fix-a' && a.querySelector('a.target').pathname === '/branch/main'; })() && !!document.querySelector('#navpulls')`));
  636. await A.evaluate(`[...document.querySelectorAll('#pulllist a.source')].find(a => a.textContent === 'fix-a').click()`);
  637. await A.waitFor('location.pathname === "/branch/fix-a"', { label: 'source branch link' });
  638. await S.goto(REPO('beta-2') + '/pulls');
  639. await pullsReady(S);
  640. check('/pulls: a signed-out viewer sees the same list', (await S.evaluate('document.querySelectorAll("#pulllist li").length')) === 4);
  641. await S.goto(REPO('gamma') + '/pulls');
  642. await pullsReady(S);
  643. check('/pulls of an empty repo says it has no commits yet', /no commits yet/.test(await txt(S, '#pullsmessage') || ''));
  644. await S.goto(REPO('alpha') + '/pulls');
  645. await pullsReady(S);
  646. 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")')));
  647. await S.goto(REPO('nothing-here') + '/pulls');
  648. await S.waitFor('!!document.querySelector("#missing")', { label: 'unknown repo pulls' });
  649. const forgedPulls = await emitFace('gitoriaPulls', ['beta-2', 'x', 'evil'], '');
  650. check('face: a forged session gets no pull list', !forgedPulls.value || forgedPulls.value.ok !== true, J(forgedPulls));
  651. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  652. await viewport(A, w, h);
  653. await A.goto(REPO('beta-2') + '/pulls');
  654. await pullsReady(A);
  655. check(`layout ${w}px: /pulls has no horizontal overflow`, await noOverflow(A));
  656. await shot(A, `${name}-pulls`);
  657. }
  658. await viewport(A, 1280, 900);
  659. // ---- merge button (gitoria#17): the owner merges a pull request, only by clicking; a conflict merges nothing ------
  660. const mergeBtns = (p) => p.evaluate(`[...document.querySelectorAll('#pulllist li')].filter(li => li.querySelector('button.mergepr')).map(li => li.querySelector('.subject').textContent).join('|')`);
  661. await A.goto(REPO('beta-2') + '/pulls');
  662. await pullsReady(A);
  663. 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));
  664. await S.goto(REPO('beta-2') + '/pulls');
  665. await pullsReady(S);
  666. check('merge: a signed-out viewer sees no Merge button', (await S.evaluate('document.querySelectorAll("button.mergepr").length')) === 0);
  667. const forgedMerge = await emitFace('gitoriaMergePull', ['beta-2', fixSha, 'evil'], '');
  668. check('merge: a forged session cannot merge', !forgedMerge.value || forgedMerge.value.error != null || forgedMerge.value.result == null, J(forgedMerge));
  669. // a branch that conflicts with main
  670. 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');
  671. 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');
  672. gitIn(pw, 'push', '-q', '-f', join(STORE, 'git', 'beta-2.git'), 'main', 'clash');
  673. const mainBefore = gitIn(join(STORE, 'git', 'beta-2.git'), 'rev-parse', 'main').trim();
  674. await A.goto(REPO('beta-2') + '/pulls');
  675. await pullsReady(A);
  676. const clickMerge = (title) => A.evaluate(`(() => { const li = [...document.querySelectorAll('#pulllist li')].find(l => l.querySelector('.subject').textContent === ${J(title)}); li.querySelector('button.mergepr').click(); })()`);
  677. await clickMerge('Clashing change');
  678. 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')); });
  679. 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);
  680. await clickMerge('Fix the <b>thing</b>');
  681. await A.waitFor('[...document.querySelectorAll("#pulllist li")].some(l => l.querySelector(".subject").textContent === "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')); });
  682. const bare = join(STORE, 'git', 'beta-2.git');
  683. const mainLog = gitIn(bare, 'log', '--format=%s|%an', 'main');
  684. 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);
  685. 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);
  686. 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 === '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.startsWith('Fix')).map(l => l.innerHTML).join()`)]));
  687. await S.goto(REPO('beta-2') + '/pulls');
  688. await pullsReady(S);
  689. check('merge: a reload (signed out) shows it merged', await S.evaluate(`[...document.querySelectorAll('#pulllist li')].some(l => l.querySelector('.subject').textContent === 'Fix the <b>thing</b>' && l.querySelector('.merged'))`));
  690. await viewport(A, 1280, 900);
  691. // ---- releases (gitoria#12): /releases lists the |||RL commits of the main branch, versions counted up ---------
  692. const rw = join(STORE, 'work-rel');
  693. rmSync(rw, { recursive: true, force: true }); mkdirSync(rw, { recursive: true });
  694. gitIn(rw, 'init', '-q', '-b', 'main');
  695. const rc = (msg) => { gitIn(rw, 'commit', '-q', '--allow-empty', '-m', msg); return gitIn(rw, 'rev-parse', 'HEAD').trim(); };
  696. rc('start');
  697. rc('|||RL First <b>one</b>');
  698. rc('work');
  699. rc('|||RL|med Feature drop');
  700. rc('|||RL|mj Big one');
  701. rc('|||RL');
  702. rc('text |||RL not a release');
  703. rc('|||RL|nonsense x');
  704. rc('|||RL|1.1.1a By hand');
  705. const lastSha = rc('|||RL after the hand one');
  706. rc('|||RL|1.1.1a again the same');
  707. gitIn(rw, 'checkout', '-q', '-b', 'side'); rc('|||RL on a side branch');
  708. gitIn(rw, 'push', '-q', '-f', join(STORE, 'git', 'beta-2.git'), 'main', 'side');
  709. const relReady = (p) => p.waitFor('!document.querySelector("#releasesloading") && (!!document.querySelector("#releasesmessage") || !!document.querySelector("#releaseshelp"))', { label: 'releases answer' });
  710. await A.goto(REPO('beta-2') + '/releases');
  711. await relReady(A);
  712. 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)`);
  713. 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));
  714. 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));
  715. 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')`));
  716. await S.goto(REPO('gamma') + '/releases');
  717. await relReady(S);
  718. check('/releases of an empty repo says it has no commits yet', /no commits yet/.test(await txt(S, '#releasesmessage') || ''));
  719. await S.goto(REPO('alpha') + '/releases');
  720. await relReady(S);
  721. check('/releases of a repo without release commits says "No release yet"', (await has(S, '#noreleases')) && !(await has(S, '#releaselist li')));
  722. const forgedRel = await emitFace('gitoriaReleases', ['beta-2', 'x', 'evil'], '');
  723. check('face: a forged session gets no release list', !forgedRel.value || forgedRel.value.ok !== true, J(forgedRel));
  724. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  725. await viewport(A, w, h);
  726. await A.goto(REPO('beta-2') + '/releases');
  727. await relReady(A);
  728. check(`layout ${w}px: /releases has no horizontal overflow`, await noOverflow(A));
  729. await shot(A, `${name}-releases`);
  730. }
  731. await viewport(A, 1280, 900);
  732. // ---- gitoria#16: every repo view is its own page, rendered on the SERVER for the request's host ---------------
  733. const AH = `alpha.gitoria.test:${PORT}`;
  734. // the git views are read on the server too (hl:proc run(), hybriel#80): the FIRST HTML holds the content, no loading step
  735. const BH = `beta-2.gitoria.test:${PORT}`;
  736. const firstViews = [
  737. ['/', AH, (b, t) => /id="homepage"/.test(b) && /Code repo/.test(t), 'Readme: the README (main branch dev)'],
  738. ['/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'],
  739. ['/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)'],
  740. ['/code/src/a.txt', AH, (b, t) => /id="lines"/.test(b) && /line one/.test(t), 'Code/<file>: the file lines'],
  741. ['/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'],
  742. ['/branch/feature/x', AH, (b, t) => /id="coderef">feature\/x</.test(b) && /only-feature\.txt/.test(t), 'Branch with a slash'],
  743. ['/commit/' + firstSha, AH, (b, t) => /id="codekind"[^>]*>Commit</.test(b) && /id="entries"/.test(b) && /first commit/.test(t), 'Commit: the project at that commit'],
  744. ['/pulls', BH, (b, t) => /id="pulllist"/.test(b) && /Fix the/.test(t), 'Pull requests: the list'],
  745. ['/releases', BH, (b, t) => /id="releaselist"/.test(b) && /1\.1\.2/.test(t) && /after the hand one/.test(t), 'Releases: the list'],
  746. ];
  747. for (const [path, host, ok, what] of firstViews) {
  748. const f = await firstHtml(path, host);
  749. const t = bodyText(f.body);
  750. 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));
  751. }
  752. r = await fetch(API + '/host.js');
  753. check('/host.js is gone (404)', r.status === 404, String(r.status));
  754. let fh, ft;
  755. // (the tickets copy was restarted empty above) one ticket made in tickets itself, then the page from scratch
  756. // tickets #20: a ticket needs an existing project, made by its first admin (as gitoria does)
  757. 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' }) });
  758. 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' }) });
  759. fh = await firstHtml('/tickets', AH);
  760. ft = bodyText(fh.body);
  761. 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));
  762. fh = await firstHtml('/', `gitoria.test:${PORT}`);
  763. ft = bodyText(fh.body);
  764. 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));
  765. 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]);
  766. let allMissing = true, missDetail = '';
  767. for (const p of ['/', '/code', '/code/src', '/branch/main', '/commit/abcdef1', '/pulls', '/releases', '/tickets']) {
  768. const m = await firstHtml(p, `nothing-here.gitoria.test:${PORT}`);
  769. 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; }
  770. }
  771. check('unknown repo: every view says "No such repository" in the first HTML', allMissing, missDetail);
  772. // direct load of every view in Chrome
  773. const views = [
  774. ['/', '#homepage, #nohomepage', 'Readme'], ['/code', '#entries', 'Code'], ['/code/src/a.txt', '#lines', 'Code'], ['/branch/feature/x', '#entries', 'Branch'],
  775. ['/commit/' + firstSha.slice(0, 8), '#entries', 'Commit'], ['/pulls', '#pullshelp', 'Pull requests'], ['/releases', '#releaseshelp', 'Releases'], ['/tickets', '#ticketlist', 'Tickets'],
  776. ];
  777. let direct = true, directDetail = '';
  778. for (const [p, sel, title] of views) {
  779. await A.goto(REPO('alpha') + p);
  780. try { await A.waitFor(`!!document.querySelector(${J(sel)}) && !!document.querySelector('#reponame')`, { label: 'direct ' + p, timeout: 6000 }); } catch { direct = false; directDetail += ' ' + p + ' (no ' + sel + ')'; continue; }
  781. const t = await A.evaluate('document.title');
  782. if (!t.startsWith(title === 'Readme' ? 'alpha' : title) || !t.includes('alpha')) { direct = false; directDetail += ` ${p} title ${J(t)}`; }
  783. }
  784. check('direct load of every view (Readme, Code, a file, Branch, Commit, Pulls, Releases, Tickets): its content, its tab title', direct, directDetail);
  785. // hl:web navigation: Readme → Code → Releases → Tickets → Pulls → Readme without a page load
  786. await A.goto(REPO('alpha') + '/');
  787. await A.waitFor('!!document.querySelector("#homepage, #nohomepage")', { label: 'nav start: Readme' });
  788. await hydrated(A);
  789. await A.evaluate('window.__navMarker = 42');
  790. const navSteps = [['#navcode', '/code', '#entries'], ['#navreleases', '/releases', '#releaseshelp'], ['#navtickets', '/tickets', '#ticketlist'], ['#navpulls', '/pulls', '#pullshelp'], ['#navhome', '/', '#homepage, #nohomepage']];
  791. let navOk = true, navDetail = '';
  792. for (const [link, path, sel] of navSteps) {
  793. await A.click(link);
  794. 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; }
  795. if ((await A.evaluate('window.__navMarker')) !== 42) { navOk = false; navDetail += ` ${path}: page reloaded`; }
  796. if ((await txt(A, '#reponame')) !== 'alpha' || (await A.evaluate('location.host')) !== AH) { navOk = false; navDetail += ` ${path}: wrong repo/host`; }
  797. }
  798. check('navigation Readme → Code → Releases → Tickets → Pulls → Readme: no full page load (window marker survives), the address bar follows, content right', navOk, navDetail);
  799. await A.click('#navcode');
  800. await A.waitFor('location.pathname === "/code" && !!document.querySelector("#entries a.dir")', { label: 'code for folder nav' });
  801. await A.click('#entries a.dir');
  802. await A.waitFor('location.pathname === "/code/src" && !!document.querySelector("#crumbs strong") && document.querySelector("#crumbs strong").textContent === "src"', { label: 'folder via nav' });
  803. 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; })());
  804. // NAVIGATION WHILE LOGGED IN (the creator saw full page loads): a fresh browser, logged in through the button on the
  805. // repo address like a person, then Readme → Code → Releases → Pulls → Tickets → Code → a folder with real clicks
  806. const L = await newPage();
  807. { const [lk, lv] = alice.cookie.split('='); await L.send('Network.enable'); await L.send('Network.setCookie', { name: lk, value: lv, url: IDENT_B + '/' }); }
  808. await L.goto(REPO('alpha') + '/');
  809. await L.waitFor('!!document.querySelector("#loginbutton") && !!document.querySelector("#reponame")', { label: 'L: repo, signed out' });
  810. await hydrated(L);
  811. await buttonLogin(L);
  812. await L.waitFor(`location.href === ${J(REPO('alpha') + '/')} && !!document.querySelector("#whoami") && !!document.querySelector("#homepage")`, { label: 'L: back logged in' });
  813. await hydrated(L);
  814. await L.evaluate('window.__navMarker = 99');
  815. // 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
  816. 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']];
  817. let liOk = true, liDetail = '';
  818. for (const [link, path, sel] of loggedSteps) {
  819. await L.click(link);
  820. 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; }
  821. if ((await L.evaluate('window.__navMarker')) !== 99) { liOk = false; liDetail += ` ${path}: FULL PAGE LOAD`; await L.evaluate('window.__navMarker = 99'); await hydrated(L); }
  822. if ((await txt(L, '#reponame')) !== 'alpha' || (await txt(L, '#whoami')) !== 'alice') { liOk = false; liDetail += ` ${path}: wrong repo/user`; }
  823. }
  824. 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);
  825. // the same on an EMPTY repo the user owns (like the creator's live repos: no commit yet)
  826. const emptySteps = [['#navcode', '/code', '#codemessage'], ['#navreleases', '/releases', '#releasesmessage'], ['#navpulls', '/pulls', '#pullsmessage'], ['#navtickets', '/tickets', '#ticketsnotconnected'], ['#navhome', '/', '#nohomepage']];
  827. await L.goto(REPO('gamma') + '/');
  828. await L.waitFor('!!document.querySelector("#nohomepage") && !!document.querySelector("#whoami")', { label: 'L: gamma' });
  829. await hydrated(L);
  830. await L.evaluate('window.__navMarker = 98');
  831. let emOk = true, emDetail = '';
  832. for (const [link, path, sel] of emptySteps) {
  833. await L.click(link);
  834. 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; }
  835. if ((await L.evaluate('window.__navMarker')) !== 98) { emOk = false; emDetail += ` ${path}: FULL PAGE LOAD`; await L.evaluate('window.__navMarker = 98'); await hydrated(L); }
  836. }
  837. check('navigation LOGGED IN on an empty repo the user owns: Code → Releases → Pulls → Tickets → Readme, no full page load', emOk, emDetail);
  838. // the socket gone (Cloudflare closes an idle WebSocket after ~100 s): navigation rides the POST fallback
  839. await L.goto(REPO('alpha') + '/');
  840. await L.waitFor('!!document.querySelector("#homepage") && !!document.querySelector("#whoami")', { label: 'L: alpha again' });
  841. await hydrated(L);
  842. await L.evaluate('window.__hl.socket.close(); window.__navMarker = 97');
  843. await L.waitFor('!window.__hl.socket', { label: 'L: socket gone' });
  844. let pfOk = true, pfDetail = '';
  845. for (const [link, path, sel] of [['#navcode', '/code', '#entries'], ['#navreleases', '/releases', '#releaseshelp'], ['#navhome', '/', '#homepage']]) {
  846. await L.click(link);
  847. 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; }
  848. if ((await L.evaluate('window.__navMarker')) !== 97) { pfOk = false; pfDetail += ` ${path}: FULL PAGE LOAD`; break; }
  849. }
  850. check('navigation LOGGED IN with the socket closed (POST fallback): no full page load, still logged in', pfOk, pfDetail);
  851. // THE SAME IN A REAL FIREFOX (the creator's browser; tests/firefox.mjs, WebDriver BiDi, real pointer clicks)
  852. ff = await launchFirefox({ port: FIREFOX_PORT, hosts: ['gitoria.test', 'alpha.gitoria.test', 'beta-2.gitoria.test', 'gamma.gitoria.test', 'ident.gitoria.test'] });
  853. { const [fk, fv] = alice.cookie.split('='); await ff.setCookie(fk, fv, 'ident.gitoria.test'); }
  854. const ffLive = () => ff.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'firefox: page hydrated' });
  855. await ff.goto(REPO('alpha') + '/');
  856. await ff.waitFor('!!document.querySelector("#loginbutton") && !!document.querySelector("#reponame")', { label: 'firefox: repo, signed out' });
  857. await ffLive();
  858. await ff.click('#loginbutton');
  859. await ff.waitFor('!!document.querySelector("#chooselist li .choose")', { label: 'firefox: ident chooser' });
  860. await ffLive();
  861. await ff.click('#chooselist li:nth-child(1) .choose');
  862. await ff.waitFor(`location.href === ${J(REPO('alpha') + '/')} && !!document.querySelector("#whoami") && !!document.querySelector("#homepage")`, { label: 'firefox: back logged in', timeout: 30000 });
  863. await ffLive();
  864. await ff.evaluate('window.__navMarker = 99');
  865. let ffOk = true, ffDetail = '';
  866. for (const [link, path, sel] of loggedSteps) {
  867. await ff.click(link);
  868. 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; }
  869. if ((await ff.evaluate('window.__navMarker')) !== 99) { ffOk = false; ffDetail += ` ${path}: FULL PAGE LOAD`; await ff.evaluate('window.__navMarker = 99'); await ffLive(); }
  870. if ((await ff.evaluate('document.querySelector("#reponame").textContent + "/" + document.querySelector("#whoami").textContent')) !== 'alpha/alice') { ffOk = false; ffDetail += ` ${path}: wrong repo/user`; }
  871. }
  872. 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);
  873. await ff.goto(REPO('gamma') + '/');
  874. await ff.waitFor('!!document.querySelector("#nohomepage") && !!document.querySelector("#whoami")', { label: 'firefox: gamma' });
  875. await ffLive();
  876. await ff.evaluate('window.__navMarker = 98');
  877. let ffeOk = true, ffeDetail = '';
  878. for (const [link, path, sel] of emptySteps) {
  879. await ff.click(link);
  880. 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; }
  881. if ((await ff.evaluate('window.__navMarker')) !== 98) { ffeOk = false; ffeDetail += ` ${path}: FULL PAGE LOAD`; await ff.evaluate('window.__navMarker = 98'); await ffLive(); }
  882. }
  883. check('FIREFOX, navigation LOGGED IN on an empty repo the user owns, no full page load', ffeOk, ffeDetail);
  884. check('FIREFOX: no console errors', ff.errors.length === 0, ff.errors.join(' | '));
  885. await ff.close(); ff = null;
  886. await A.goto(BASE + '/');
  887. await A.waitFor('document.querySelectorAll("#repos li").length === 3', { label: 'list with gamma' });
  888. 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'));
  889. // ---- layout ------------------------------------------------------------------------------------------------
  890. for (const [w, h, name] of [[390, 844, 'narrow'], [1280, 900, 'wide']]) {
  891. await viewport(A, w, h);
  892. await A.goto(BASE + '/');
  893. await A.waitFor('document.querySelectorAll("#repos li").length === 3', { label: 'list for layout' });
  894. check(`layout ${w}px: main address has no horizontal overflow`, await noOverflow(A));
  895. await shot(A, `${name}-main`);
  896. await A.goto(REPO('alpha') + '/');
  897. await A.waitFor('!!document.querySelector("#reponame")');
  898. check(`layout ${w}px: repo address has no horizontal overflow`, await noOverflow(A));
  899. await shot(A, `${name}-repo`);
  900. }
  901. // ---- PHONE FIRST (gitoria#23): every page at 390 px (mobile Chrome, DPR 2, touch) measured by tests/mobile-measure.js ----
  902. // no sideways scroll (scrollWidth against a FIXED 390: a mobile viewport grows with the page, so innerWidth would hide it),
  903. // every tap target ≥ 44×44 (inline links in a sentence exempt), fields ≥ 16 px, text ≥ 14 px, the header ≤ the theme's 52 px,
  904. // code / tables inside the screen. A long real line: a 20 000-character line on a branch `wide` of alpha. Then the phone's
  905. // three dropdowns opened by a tap: ☰ (the main menu), the user menu, the ident dropdown (signed out).
  906. const wideWork = join(STORE, 'work-wide');
  907. rmSync(wideWork, { recursive: true, force: true });
  908. execFileSync('git', ['clone', '-q', join(STORE, 'git', 'alpha.git'), wideWork], { stdio: 'pipe' });
  909. gitIn(wideWork, 'checkout', '-q', '-b', 'wide');
  910. writeFileSync(join(wideWork, 'long.txt'), 'short line\n' + 'x'.repeat(20000) + ' the end\n');
  911. gitIn(wideWork, 'add', '-A'); gitIn(wideWork, 'commit', '-q', '-m', 'a very long line');
  912. gitIn(wideWork, 'push', '-q', 'origin', 'wide');
  913. 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';
  914. const phone = async (p) => {
  915. await p.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  916. await p.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  917. await p.send('Emulation.setUserAgentOverride', { userAgent: UA_PHONE, platform: 'iPhone' });
  918. return p;
  919. };
  920. const PH = await phone(patient(await browsers[0].newPage())); // alice's Chrome (signed in)
  921. const PO = await phone(await newPage()); // a fresh Chrome: signed out
  922. const measure = async (p) => { await hydrated(p); await sleep(600); return p.evaluate('window.__W = 390;' + MEASURE); };
  923. const phonePages = [
  924. [PH, 'main address', BASE + '/', '#repos li'], [PH, 'repo readme', REPO('alpha') + '/', '#reponame'], [PH, '/code', REPO('alpha') + '/code', '#entries li'],
  925. [PH, '/code/src', REPO('alpha') + '/code/src', '#entries li'], [PH, 'a file', REPO('alpha') + '/code/src/a.txt', '#lines li'],
  926. [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'],
  927. [PH, '/commit/<first>', REPO('alpha') + '/commit/' + firstSha, '#entries li'], [PH, '/pulls', REPO('alpha') + '/pulls', 'repo-pulls'],
  928. [PH, '/releases', REPO('beta-2') + '/releases', '#releaselist li'], [PH, '/tickets', REPO('alpha') + '/tickets', 'repo-tickets'],
  929. [PH, '/settings', REPO('alpha') + '/settings', 'repo-settings'], [PH, 'no such repository', REPO('nothing-here') + '/', '#missing'],
  930. [PH, '/login/failed', BASE + '/login/failed', '#home'], [PO, 'main address signed out', BASE + '/', '#repos li'],
  931. ];
  932. for (const [p, name, url, ready] of phonePages) {
  933. let m = null;
  934. try { await p.goto(url); await p.waitForSelector(ready); m = await measure(p); } catch (e) { m = { ok: false, error: e.message }; }
  935. check(`phone 390: ${name} — no sideways scroll, targets ≥ 44 px, fields ≥ 16 px, text ≥ 14 px, header ≤ 52 px, code inside`, m.ok === true,
  936. 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 }));
  937. 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; })()`));
  938. 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"'));
  939. }
  940. // the dropdowns, opened with a real tap: their box inside the screen, every link / button in them ≥ 44×44
  941. const dropdown = async (p, toggle, box) => {
  942. if (!(await has(p, toggle))) return { error: 'no ' + toggle };
  943. await p.click(toggle);
  944. 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' }; }
  945. await sleep(300);
  946. 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);
  947. 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)) }; })()`);
  948. };
  949. await PH.goto(REPO('alpha') + '/code'); await PH.waitForSelector('#entries li'); await hydrated(PH);
  950. let dd = await dropdown(PH, 'button.menu-toggle', '#sidebar');
  951. 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));
  952. if (!dd.error) {
  953. await PH.click('#sidebar a[href]');
  954. await PH.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector('#repos li')`, { label: 'menu → main address' }).catch(() => {});
  955. check('phone 390: a tap on "Repositories" in the ☰ menu goes to the main address', (await PH.evaluate('location.href')) === BASE + '/');
  956. }
  957. await PH.goto(REPO('alpha') + '/'); await PH.waitForSelector('#reponame'); await hydrated(PH);
  958. dd = await dropdown(PH, 'button.user-toggle', '#user-menu');
  959. check('phone 390: the user icon opens the user menu (Access tokens, SSH keys, Log out) inside the screen, targets ≥ 44 px', !dd.error && dd.inside && dd.small.length === 0 && J(dd.items) === J(['Access tokens', 'SSH keys', 'Log out']), J(dd));
  960. await PO.goto(REPO('alpha') + '/'); await PO.waitForSelector('#reponame'); await hydrated(PO);
  961. dd = await dropdown(PO, 'button.ident-toggle', '#ident-panel');
  962. check('phone 390, signed out: the ident icon opens the dropdown with "Log in with ident" inside the screen, ≥ 44 px', !dd.error && dd.inside && dd.small.length === 0 && dd.items.includes('Log in with ident'), J(dd));
  963. await shot(PH, 'phone-usermenu');
  964. await PH.close(); await PO.close();
  965. // ---- the identity selector (gitoria#14): choose an identity on the main address, no reload ------------------------
  966. const C = await newPage();
  967. // alice is already signed in to ident (over REST, ident allows only 3 codes per address): hand C that ident session
  968. const [ck, cv] = alice.cookie.split('=');
  969. await C.send('Network.enable');
  970. await C.send('Network.setCookie', { name: ck, value: cv, url: IDENT_B + '/' });
  971. await C.goto(BASE + '/');
  972. await C.waitFor('!!document.querySelector("#heading")', { label: 'C: main address' });
  973. await hydrated(C);
  974. await C.evaluate('window.__loginMarker = 1');
  975. // hybriel#43: a second tab of the SAME browser (same session) on a code view — the login/logout flip of the shell
  976. // must leave the page in the slot alone (no re-creation, no "Loading")
  977. const C2 = patient(await browsers[browsers.length - 1].newPage());
  978. await C2.goto(REPO('alpha') + '/code');
  979. await C2.waitFor('!!document.querySelector("#entries") && !!document.querySelector("#loginbutton")', { label: 'C2: code view' });
  980. await hydrated(C2);
  981. await C2.evaluate('window.__flipMarker = 7; document.querySelector("#entries").dataset.keep = "1"');
  982. 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)');
  983. check('selector: signed out, ident\'s "choose ident" sits beside the login button', 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'); })()`));
  984. await shClick(C, '#choose');
  985. await C.waitFor(sh(`r.querySelectorAll('[part~="identity"]').length > 0`), { label: 'selector list' });
  986. await shClick(C, '[part~="identity"]', 'Default');
  987. await C.waitFor('!!document.querySelector("#logout")', { label: 'C: logged in after the selector login' });
  988. 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')));
  989. await C.waitFor('!!document.querySelector("#createform")', { label: 'C: create form after the selector login' });
  990. check('selector login: the page follows (create form), the same session as after the button', await has(C, '#createform') && (await txt(C, '#whoami')) === 'alice');
  991. await C2.waitFor('!!document.querySelector("#whoami")', { label: 'C2: logged in by the other tab' });
  992. 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)'));
  993. await clickInMenu(C, '#logout', 'button.user-toggle');
  994. await C.waitFor('!!document.querySelector("#loginbutton")', { label: 'C: logged out' });
  995. await C.waitFor(sh(`/choose/.test(r.querySelector('#choose').textContent)`), { label: 'selector reset' });
  996. await C2.waitFor('!!document.querySelector("#loginbutton")', { label: 'C2: logged out by the other tab' });
  997. check('hybriel#43: … and back to logged out, the code still stays', await codeKept(), await C2.evaluate('document.body.innerText.slice(0, 300)'));
  998. 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);
  999. await C.goto(REPO('alpha') + '/');
  1000. await C.waitFor('!!document.querySelector("#loginbutton") && !!document.querySelector("#reponame")', { label: 'C: repo address' });
  1001. await hydrated(C);
  1002. const repoSel = await firstHtml('/', `alpha.gitoria.test:${PORT}`);
  1003. check('repo address: the selector is hidden (class onrepo from the server\'s host, ident knows only the main origin), the button stays', /<ident-selector[^>]*class="out onrepo"/.test(repoSel.body) && await C.evaluate('getComputedStyle(document.querySelector("#selector")).display === "none"') && await has(C, '#loginbutton'));
  1004. const loginFx = await fetch(API + '/login.js');
  1005. check('/login.js is served', loginFx.status === 200 && /ident-login/.test(await loginFx.text()));
  1006. // ---- logout, then the data survives a restart --------------------------------------------------------------
  1007. await A.goto(BASE + '/');
  1008. await A.waitForSelector('#logout');
  1009. await hydrated(A);
  1010. await clickInMenu(A, '#logout', 'button.user-toggle');
  1011. await A.waitFor('!!document.querySelector("#loginbutton") && !document.querySelector("#createform")', { label: 'logged out' });
  1012. await A.waitFor('!!document.querySelector("#loginhint")', { label: 'A: list after the logout' });
  1013. 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)'));
  1014. // the page switches BEFORE the server has the logout (showOut runs beside the emit): stopping the server now could cut
  1015. // the emit off ("the socket closed and the POST fallback failed", seen once in mission 069) — wait until the server agrees
  1016. let serverOut = false;
  1017. for (let i = 0; i < 50 && !serverOut; i++) {
  1018. serverOut = await A.evaluate(`fetch('/', { cache: 'no-store' }).then(r => r.text()).then(t => t.includes('id="loginbutton"'))`);
  1019. if (!serverOut) await sleep(200);
  1020. }
  1021. check('logout: the server has it too (a fresh / of that session is signed out)', serverOut);
  1022. await stopServer();
  1023. startServer(env);
  1024. await serverUp();
  1025. const again = await (await fetch(API + '/api/repos')).json();
  1026. 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));
  1027. 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'))));
  1028. 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 })));
  1029. check('browsers: no console errors', problems.length === 0, problems.map(m => m.text).join(" | "));
  1030. 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(" | "));
  1031. // ==== mission 046: THE INSTALLABLE APP — hl:web's own manifest + service worker (project.hl appIcons / offline =
  1032. // [ Index ]). Last, so every check above ran on the gate's usual Chromes: those are closed now and ONE fresh Chrome
  1033. // treats the two test origins as secure (a service worker needs a secure context; plain-http *.gitoria.test is not
  1034. // one — https / localhost are, so the live site needs no flag). The manifest and every icon over HTTP; Chrome's own
  1035. // verdict; the worker registered and controlling; then OFFLINE: the tab loses the network (the note appears), the
  1036. // server is stopped too (CDP's offline emulation does not reach the worker's own fetches — measured in tracker's
  1037. // gate — so only a dead server proves the cache), and `/` still opens from the cache: header + note + the list as
  1038. // last seen. A data page gets hl:web's "Unavailable offline" page. The same on a repo address (its own origin).
  1039. const html = await (await fetch(API + '/')).text();
  1040. const mhref = (html.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  1041. check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (the token `darker`)',
  1042. mhref === '/__hl/manifest.webmanifest' && html.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')
  1043. && html.includes('<link rel="icon" href="/icons/favicon.svg">') && html.includes('<meta name="theme-color" content="rgb(15, 20, 25)">'), html.slice(0, 900));
  1044. const mres = await fetch(API + mhref);
  1045. const man = await mres.json();
  1046. check('pwa: the manifest is served as application/manifest+json: name "gitoria", start_url /, scope /, display standalone, the token colours',
  1047. /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'gitoria' && man.short_name === 'gitoria' && man.start_url === '/' && man.scope === '/'
  1048. && man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', J(man));
  1049. const iconOk = [];
  1050. for (const ic of man.icons || []) {
  1051. const ir = await fetch(API + ic.src);
  1052. const b = Buffer.from(await ir.arrayBuffer());
  1053. 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]));
  1054. }
  1055. check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',
  1056. 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));
  1057. const touch = await fetch(API + '/icons/apple-touch-icon.png');
  1058. const touchBytes = Buffer.from(await touch.arrayBuffer());
  1059. const fav = await fetch(API + '/icons/favicon.svg');
  1060. const favText = await fav.text();
  1061. const ico = await fetch(API + '/favicon.ico');
  1062. const icoBytes = Buffer.from(await ico.arrayBuffer());
  1063. check('pwa: apple-touch-icon is a 180×180 PNG, the favicon an SVG in gitoria blue, /favicon.ico a real icon file',
  1064. touch.ok && touchBytes.readUInt32BE(16) === 180 && fav.ok && /image\/svg\+xml/.test(fav.headers.get('content-type') || '') && favText.includes('#569bd4')
  1065. && ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);
  1066. const repoMan = await (await fetch(API + '/__hl/manifest.webmanifest', { headers: { Host: `alpha.gitoria.test:${PORT}` } })).json();
  1067. check('pwa: a repo address serves the same manifest (its own origin, start_url / = its Readme)', repoMan.name === 'gitoria' && repoMan.start_url === '/', J(repoMan));
  1068. for (const b of browsers) { try { await b.close(); } catch {} }
  1069. browsers.length = 0;
  1070. process.env.HL_CHROME_ARGS += `|--unsafely-treat-insecure-origin-as-secure=${BASE},${REPO('alpha')}`;
  1071. const P = await newPage();
  1072. const pev = (e) => P.evaluate(e);
  1073. await P.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  1074. const workerOn = async (label) => {
  1075. await hydrated(P);
  1076. await P.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { timeout: 15000, label: label + ': service worker active' });
  1077. await P.waitFor(`!!navigator.serviceWorker.controller`, { timeout: 10000, label: label + ': page controlled by the worker' });
  1078. };
  1079. await P.goto(BASE + '/');
  1080. await P.waitFor('document.querySelectorAll("#repos li").length === 3', { label: 'pwa: list' });
  1081. await workerOn('main');
  1082. const inst = await P.send('Page.getInstallabilityErrors');
  1083. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));
  1084. const am = await P.send('Page.getAppManifest');
  1085. check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, J(am.errors));
  1086. check('pwa: hl:web\'s service worker is registered for the whole app (scope /) and controls the page',
  1087. (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')));
  1088. check('pwa: online, no offline note', !(await has(P, '#offline')));
  1089. await shot(P, 'pwa-phone-online');
  1090. // a repo address: its own origin → its own worker, `/` (the Readme) kept there too
  1091. await P.goto(REPO('alpha') + '/');
  1092. await P.waitFor('!!document.querySelector("#reponame")', { label: 'pwa: alpha readme' });
  1093. await workerOn('alpha');
  1094. 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} /`);
  1095. await P.goto(BASE + '/');
  1096. await P.waitFor('document.querySelectorAll("#repos li").length === 3', { label: 'pwa: list again' });
  1097. await hydrated(P);
  1098. await P.setOffline(true);
  1099. await P.waitFor(`!!document.querySelector('#offline')`, { timeout: 5000, label: 'offline note (live)' }).catch(() => {});
  1100. 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.');
  1101. await stopServer();
  1102. let down = false;
  1103. try { await fetch(API + '/api/repos'); } catch { down = true; }
  1104. await P.goto(BASE + '/');
  1105. await P.waitFor(`!!document.querySelector('#offline')`, { timeout: 8000, label: 'offline note after reload' }).catch(() => {});
  1106. 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',
  1107. down && (await txt(P, 'application-header .brand')) === 'gitoria' && await has(P, '#offline')
  1108. && (await pev('document.querySelectorAll("#repos li").length')) === 3
  1109. && (await pev(`getComputedStyle(document.querySelector('application-header')).backgroundColor`)) === 'rgb(15, 20, 25)', 'server down: ' + down + ' ' + (await pev('document.body.innerText.slice(0, 200)')));
  1110. await shot(P, 'pwa-phone-offline');
  1111. await P.goto(REPO('alpha') + '/');
  1112. await P.waitFor(`!!document.querySelector('#offline')`, { timeout: 8000, label: 'offline note on alpha' }).catch(() => {});
  1113. 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)'));
  1114. await P.goto(REPO('alpha') + '/code');
  1115. 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');
  1116. await P.setOffline(false);
  1117. startServer(env);
  1118. await serverUp();
  1119. await P.goto(BASE + '/');
  1120. await hydrated(P);
  1121. await P.waitFor(`!document.querySelector('#offline')`, { timeout: 5000, label: 'note gone' }).catch(() => {});
  1122. check('back online: / from the server again, no offline note', !(await has(P, '#offline')) && (await pev('document.querySelectorAll("#repos li").length')) === 3);
  1123. } catch (e) {
  1124. failures++;
  1125. console.log('FAIL gate crashed — ' + (e && e.stack || e));
  1126. } finally {
  1127. for (const b of browsers) { try { await b.close(); } catch {} }
  1128. if (ff) { try { await ff.close(); } catch {} }
  1129. await stopServer();
  1130. if (tickets) await tickets.stop();
  1131. if (ident) await ident.stop();
  1132. writeFileSync(join(SCRATCH, 'gate-server.log'), log);
  1133. console.log(`${passes} passed, ${failures} failed`);
  1134. process.exit(failures ? 1 : 0);
  1135. }

Branches

Latest commits

  • 2bf5343egitoria 007: theme re-copied from layouts dbe3de7 (44 px taps), redundant tap overrides dropped, crumbs class, real-browser walk test, reportmre
  • 18843648deploy.sh: a gate without a 'passed,' line (check-theme) no longer ends the script silently (grep under pipefail) — print check-theme's summary, as layouts doesmre
  • e6dff0cbgitoria#23: report 005, STATUS, LOGmre
  • 7f992d62gitoria#23: phone first on the shared theme — brand, branch and pull links 44 px, readme code 14 px; gate block "phone first" (15 pages at 390 + the three dropdowns, fails 20 on old), dropdown-aware login/logout clicks, check-theme in GATESmre
  • a2a840a5gitoria#23 WIP (quota stop): theme from layouts, styles inherit it, shell on the theme's header/menus/sidebar, phone measurement script; gates not runmre
  • 12b665b0mission brief 005mre
  • b680c483Revert "gitoria#22: RepoTabs wrapping component for the repo tabs (active tab, no content for a missing repo)"mre
  • 4fda244fgitoria#22: RepoTabs wrapping component for the repo tabs (active tab, no content for a missing repo)mre
  • 0fd5e280mission brief 004mre
  • e1d425e7paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • e59ff114deploy.sh: wait up to DEPLOY_URL_WAIT (120 s) for 200 after the restart, as the other apps (cold compile, hybriel#148)mre
  • bcafcceb003: compose cache volume + tmpfs /tmp, gate start waits 120 s, report/LOG/STATUSmre
  • bed3f2d5Re-vendor Hybriel to the shared static build 0f396652 (plugins; bin/ is git-ignored)mre
  • 3207e128mission brief 003mre
  • 18ab71fbtests/ticketskit: wait up to 120 s for tickets (native Hybriel cold compile ~25 s, hybriel#148)mre
  • 4fffa966docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 4f47843egate: ticket links use the tickets short URL (/<slug>/<n>, tickets#25)mre
  • 86605446mission 002 (code order) 4/4: README file map + import order + 'Same output' test + gate run with a tickets HEAD copy, STATUS (entry, lessons), LOG, report; tests/realdata-baseline.mjs + realdata-compare.py (a cleanup answers the same on live data: pages, modules, API, git over HTTPS and SSH, faces), tests/letcount.pymre
  • cc7bf7bamission 002 (code order) 3/4: let only where a variable is reassigned or re-bound in a loop body (289 lets → plain declarations; 213 left: 125 reassigned, 88 loop-bound; no member/import/param clash). gates 200/0, 46/0, 44/0; real-data reads + writes identical (browser modules: var → const only)mre
  • 090a20c6mission 002 (code order) 2/4: one lib/ file per topic — git.hl split into git (calls, branches, init, temp folder) / homepage / code / pulls / releases (+ git-helpers: paths, ids, |||PR/|||RL markers); repos-helpers, tickets-helpers, transport-helpers; util.hl = localtime + env, storage dir, addresses, lists, text checks, one newest-first sort (was 3 copies); the function routes out of project.hl into lib/api.hl (thin; plumbing in api-helpers.hl), sshgate.hl folded into api.hl + sshkeys.hl keyLine + repos.hl mayPush; 'Make main' and the merge answer out of the faces (code.hl makeMain, pulls.hl pullsView), one login helper (users.hl userOfLoginCode); project.hl is the map. Session-writing routes get &req + &server.sessions. gates 200/0, 46/0, 44/0; real-data identical except /login/failed now shows the parked reason for a browser that already had a session (the old copy-of-req lost it)mre