gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitc37488b1c37488b1MN report: alignment updatemrec37488b1/tests/browser.mjs

54.9 KB

  1. // tests/browser.mjs — THE GATE of notes.worldapi.org (tickets notes#1: sidebar + Markdown editor; notes#2: offline + sync;
  2. // notes#4: offline and sync in pure Hybriel — hl:web's own worker, kept state per user and queue; Chrome offline through CDP).
  3. // Its own notes server on its own storage, its OWN ident (a copy of ident's code without .env — codes go to a mail
  4. // sink, tests/identkit.mjs), real headless Chromes for everything visible. `*.notes.test` is mapped to 127.0.0.1
  5. // inside Chrome (--host-resolver-rules) so ident and the app are the same site, as on worldapi.org.
  6. //
  7. // node tests/browser.mjs (NOTES_GATE_PORT server, default 8702; NOTES_GATE_IDENT_PORT, default 8701;
  8. // NOTES_GATE_CHROME "8713-8719" = Chrome debug ports)
  9. // Screenshots (390 / 1280 px) land in .scratch/gate-*.png. Every process started is stopped by PID.
  10. // NOTES_GATE_SOFT=1 (old code only: waits do not stop the gate), NOTES_GATE_DEBUG=1 (a crash dumps both devices' state).
  11. // NOTES_GATE_UNTIL=<section> stops after that section (offline, outage, conflict, delete, …) while working on the gate.
  12. import { spawn } from 'node:child_process';
  13. import { rmSync, mkdirSync, writeFileSync, existsSync } from 'node:fs';
  14. import { dirname, join, resolve } from 'node:path';
  15. import { fileURLToPath } from 'node:url';
  16. import { launchBrowser } from './cdp.mjs';
  17. import { startIdent } from './identkit.mjs';
  18. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  19. const HERE = dirname(fileURLToPath(import.meta.url));
  20. const APP = resolve(HERE, '..');
  21. const BIN = join(APP, 'bin/hybriel');
  22. const PORT = Number(process.env.NOTES_GATE_PORT || 8702);
  23. const IDENT_PORT = Number(process.env.NOTES_GATE_IDENT_PORT || 8701);
  24. const API = `http://127.0.0.1:${PORT}`;
  25. const BASE = `http://notes.test:${PORT}`;
  26. const IDENT_B = `http://ident.notes.test:${IDENT_PORT}`;
  27. const [CH_FROM, CH_TO] = (process.env.NOTES_GATE_CHROME || '8703-8709').split('-').map(Number);
  28. process.env.HL_CHROME_ARGS = '--host-resolver-rules=MAP *.notes.test 127.0.0.1, MAP notes.test 127.0.0.1|--unsafely-treat-insecure-origin-as-secure=' + `http://notes.test:${PORT}`; // a service worker needs a secure origin (https on worldapi.org)
  29. const SCRATCH = join(APP, '.scratch');
  30. const STORE = join(SCRATCH, 'gate-store');
  31. const IDENT_DIR = process.env.NOTES_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  32. rmSync(STORE, { recursive: true, force: true });
  33. mkdirSync(STORE, { recursive: true });
  34. let failures = 0, passes = 0;
  35. function check(label, ok, detail = '') {
  36. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  37. if (ok) passes++; else failures++;
  38. }
  39. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  40. const J = JSON.stringify;
  41. let log = '';
  42. let server = null, ident = null;
  43. const browsers = [];
  44. function startServer(extraEnv = {}) {
  45. log += '\n==== notes server start\n';
  46. server = spawn(BIN, ['project.hl'], {
  47. cwd: APP,
  48. env: { ...process.env, NOTES_PORT: String(PORT), NOTES_STORAGE: join(STORE, 'mpackdb'), NOTES_SESSIONS: join(STORE, 'sessions') + '/', NOTES_WATCH: '0',
  49. NOTES_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, ...extraEnv },
  50. stdio: ['ignore', 'pipe', 'pipe'],
  51. });
  52. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  53. }
  54. async function serverUp() {
  55. for (let i = 0; i < 480; i++) { try { const r = await fetch(API + '/'); if (r.ok) return; } catch {} await sleep(250); }
  56. throw new Error('notes did not come up\n' + log);
  57. }
  58. async function stopServer() {
  59. if (!server) return;
  60. try { server.kill('SIGTERM'); } catch {}
  61. await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });
  62. server = null;
  63. }
  64. const SLOW = Number(process.env.NOTES_GATE_SLOW || 3);
  65. // NOTES_GATE_SOFT=1: a wait that times out is logged and the gate goes on (the checks decide) — to run this gate against
  66. // OLD code and see which checks fail there; never for a real gate run
  67. const SOFT = process.env.NOTES_GATE_SOFT === '1';
  68. function patient(page) {
  69. const waitFor = page.waitFor.bind(page);
  70. page.waitFor = (expr, o = {}) => SOFT
  71. ? waitFor(expr, { ...o, timeout: o.timeout || 10000 }).catch((e) => { console.log('note (soft): ' + e.message); return false; })
  72. : waitFor(expr, { ...o, timeout: (o.timeout || 10000) * SLOW });
  73. const goto = page.goto.bind(page);
  74. page.goto = (url, o = {}) => goto(url, { ...o, timeout: (o.timeout || 15000) * SLOW });
  75. return page;
  76. }
  77. // a page of a NEW Chrome (own cookies), or — given `like` — another tab of the same Chrome (same login)
  78. async function newPage(like = null) {
  79. if (like) return patient(await like.__browser.newPage());
  80. const b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  81. browsers.push(b);
  82. const p = patient(await b.newPage());
  83. p.__browser = b;
  84. return p;
  85. }
  86. async function viewport(page, width, height) {
  87. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  88. await sleep(250);
  89. }
  90. async function shot(page, name) {
  91. await page.send('Page.bringToFront');
  92. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  93. writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64'));
  94. }
  95. const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  96. const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'page hydrated' });
  97. const txt = (page, sel) => page.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || null`);
  98. const has = (page, sel) => page.evaluate(`!!document.querySelector(${J(sel)})`);
  99. const subjects = (page) => page.evaluate(`[...document.querySelectorAll('#notes a')].map(a => a.textContent)`);
  100. const UNTIL = process.env.NOTES_GATE_UNTIL || '';
  101. const until = (name) => { if (UNTIL === name) throw Object.assign(new Error('stopped after ' + name), { until: true }); };
  102. const visible = (page, sel) => page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);
  103. async function identSignIn(page, email) {
  104. await page.goto(IDENT_B + '/');
  105. await page.waitForSelector('#email');
  106. await hydrated(page);
  107. await page.type('#email', email);
  108. await page.click('#sendcode');
  109. await page.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident /code page' });
  110. await hydrated(page);
  111. await page.type('#code', ident.lastCode(email));
  112. await page.click('#verify');
  113. await page.waitForSelector('#signout', { timeout: 10000 });
  114. }
  115. // the login button of the page we are on → ident's "choose an identity" → back
  116. async function buttonLogin(page) {
  117. await page.click('#loginbutton');
  118. await page.waitForSelector('#chooselist', { timeout: 10000 });
  119. await hydrated(page);
  120. await page.click('#chooselist li:nth-child(1) .choose');
  121. }
  122. // ---- REAL clicks and keys into the editor's shadow DOM (as in tickets' gate) ----------------------------
  123. const mdR = (expr) => `(() => { const r = document.querySelector('#notetext md-editor'); if (!r) return null; return (${expr}); })()`;
  124. const CTRL = 2;
  125. async function mdClick(page, sel) {
  126. const bx = await page.evaluate(mdR(`(() => { const el = r.querySelector(${J(sel)}); if (!el) return null; el.scrollIntoView({ block: 'center' }); const q = el.getBoundingClientRect(); return { x: q.left, y: q.top, w: q.width, h: q.height }; })()`));
  127. if (!bx || !bx.w) throw new Error('mdClick: ' + sel + ' is not laid out');
  128. const x = Math.round(bx.x + bx.w / 2), y = Math.round(bx.y + bx.h / 2);
  129. for (const [type, buttons] of [['mouseMoved', 0], ['mousePressed', 1], ['mouseReleased', 0]]) await page.send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1, buttons });
  130. await sleep(80);
  131. }
  132. async function mdPress(page, key, mods = 0) {
  133. const K = { Enter: [13, 'Enter', '\r'], End: [35, 'End'], Tab: [9, 'Tab'] }[key];
  134. const [vk, code, text] = K;
  135. const t = text && !(mods & CTRL) ? text : undefined;
  136. await page.send('Input.dispatchKeyEvent', { type: t ? 'keyDown' : 'rawKeyDown', modifiers: mods, key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk, ...(t ? { text: t, unmodifiedText: t } : {}) });
  137. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: mods, key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk });
  138. await sleep(30);
  139. }
  140. async function mdType(page, text) {
  141. for (const ch of text) {
  142. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });
  143. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
  144. }
  145. await sleep(60);
  146. }
  147. const taVal = (page) => page.evaluate(`document.querySelector('#notetext input[name=text]').value`);
  148. // the block builds the surface's content once the page is live (a 100 ms animation, no mount event): wait for it, or a click lands in an empty surface
  149. const editorReady = (page, label) => page.waitFor(mdR(`!!r.querySelector('md-editor article > *')`), { label });
  150. const emitFace = async (event, payload, cookie) => {
  151. const r = await fetch(API + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: 1, event, payload }) });
  152. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  153. return { status: r.status, raw: t, value: j && j.value };
  154. };
  155. // ---- CHROME OFFLINE (notes#4): CDP cuts the page AND its service worker. An open WebSocket survives the cut
  156. // (report 005), so every offline check first RELOADS offline: the page boots from hl:web's worker, no socket opens.
  157. async function workerSessions(page) {
  158. const conn = page.__browser.conn;
  159. page.__workers = page.__workers || new Map();
  160. const { targetInfos } = await conn.send('Target.getTargets');
  161. for (const t of targetInfos) {
  162. if (t.type === 'service_worker' && !page.__workers.has(t.targetId)) {
  163. const { sessionId } = await conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });
  164. await conn.send('Network.enable', {}, sessionId);
  165. page.__workers.set(t.targetId, sessionId);
  166. }
  167. }
  168. return [...page.__workers.values()];
  169. }
  170. async function setOffline(page, off) {
  171. await page.setOffline(off);
  172. for (const s of await workerSessions(page)) await page.__browser.conn.send('Network.emulateNetworkConditions', { offline: off, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, s);
  173. }
  174. const socketOpen = (page) => page.evaluate('!!(window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1)');
  175. const booted = (page, label) => page.waitFor('!!window.__hl', { label });
  176. // what hl:web keeps in this browser (IndexedDB `hl-offline`: `state`, `queue`) and the worker's documents
  177. const keptCopy = (page) => page.evaluate(`(async () => {
  178. const dbs = (await indexedDB.databases()).map(d => d.name);
  179. // every database of this origin, every store (hl:web's \`hl-offline\` and anything else, e.g. the old notes-<user>)
  180. let state = [], queue = [];
  181. for (const name of dbs) {
  182. const db = await new Promise((ok, no) => { const r = indexedDB.open(name); r.onsuccess = () => ok(r.result); r.onerror = () => no(r.error); });
  183. const all = (st) => new Promise((ok) => { try { const r = db.transaction(st, 'readonly').objectStore(st).getAll(); r.onsuccess = () => ok(r.result); r.onerror = () => ok([]); } catch (e) { ok([]); } });
  184. for (const st of [...db.objectStoreNames]) { const rows = await all(st); if (name === 'hl-offline' && st === 'queue') queue = rows; else state.push({ db: name, store: st, rows }); }
  185. db.close();
  186. }
  187. const docs = [];
  188. for (const k of await caches.keys()) { const c = await caches.open(k); for (const r of await c.keys()) { const res = await c.match(r); if ((res.headers.get('content-type') || '').includes('text/html')) docs.push({ cache: k, path: new URL(r.url).pathname, html: await res.text() }); } }
  189. return { dbs, state: JSON.stringify(state), queue: queue.length, queueText: JSON.stringify(queue), docs };
  190. })()`);
  191. // the editor: <md-editor>'s own surface when the element is defined, else the plain textarea it wraps — real keys either way
  192. const mdDefined = (page) => page.evaluate(`!!document.querySelector('#notetext md-editor article')`);
  193. async function typeAtEnd(page, text) {
  194. if (await mdDefined(page)) {
  195. await editorReady(page, 'editor');
  196. await mdClick(page, 'md-editor article');
  197. await mdPress(page, 'End', CTRL);
  198. } else {
  199. await page.click('#notetext');
  200. await mdPress(page, 'End', CTRL);
  201. }
  202. await mdType(page, text);
  203. }
  204. try {
  205. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  206. const alice = await ident.signIn('[email protected]');
  207. await ident.signIn('[email protected]');
  208. const APPKEY = await ident.registerApp(alice, 'notes (gate)', [BASE]);
  209. check('ident: our own ident runs (a copy without .env), notes is registered', /^pk_[0-9a-f]{32}$/.test(APPKEY.key) && !existsSync(join(STORE, 'ident', 'ident-code', '.env')));
  210. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  211. await serverUp();
  212. // ---- signed out -------------------------------------------------------------------------------------
  213. let html = await (await fetch(API + '/')).text();
  214. check('signed out: the page only asks to log in (no list, no editor, no notes)', /Log in with ident/.test(html) && !/id="newnote"|<note-list|<md-editor|id="notesapp"/.test(html), html.slice(html.indexOf('<body')).slice(0, 300));
  215. // mission 015 (route marker, hybriel#197): the menu's one item "Notes" (href /) is marked in the SERVER's html on every page: the list, a note, the login failure
  216. for (const pg of ['/', '/note/abc123def456', '/login/failed']) {
  217. const h = await (await fetch(API + pg)).text();
  218. const links = [...h.matchAll(/<a [^>]*href="\/"[^>]*>Notes/g)].map(m => m[0]);
  219. check(`server html ${pg}: the menu marks Notes (aria-current=page, class current), in both menus, before any script`, links.length >= 2 && links.every(l => /aria-current="page"/.test(l) && /class="current"/.test(l)), J(links));
  220. }
  221. let r = await fetch(API + '/login/callback', { redirect: 'manual' });
  222. check('login: /login/callback without a code → /login/failed', r.status === 302 && r.headers.get('location') === '/login/failed');
  223. r = await fetch(API + '/api/notes');
  224. check('signed out: the notes API answers 401', r.status === 401);
  225. r = await (await fetch(API + '/api/me')).json();
  226. check('signed out: /api/me says nobody', r.user === null, J(r));
  227. // ---- log in with ident (the button flow) on device A ----------------------------------------------------
  228. const a = await newPage();
  229. globalThis.__debugPages = { A: a };
  230. await viewport(a, 1280, 900);
  231. await identSignIn(a, '[email protected]');
  232. await a.goto(BASE + '/');
  233. await hydrated(a);
  234. check('signed out (browser): "Log in with ident" shows, no "New note"', await has(a, '#loginbutton') && !(await has(a, '#newnote')));
  235. await buttonLogin(a);
  236. await a.waitForSelector('#newnote', { timeout: 15000 });
  237. check('login: alice sees her (empty) list and "New note"', (await txt(a, '#empty')) !== null && (await subjects(a)).length === 0 && await has(a, '#logout'));
  238. const cookieOf = async (page) => (await page.cookies([BASE])).filter(c => c.name === 'notessid').map(c => 'notessid=' + c.value)[0];
  239. const cookieA = await cookieOf(a);
  240. const apiGet = async (path, cookie) => { const x = await fetch(API + path, { headers: { cookie } }); return { status: x.status, json: await x.json().catch(() => null) }; };
  241. const apiPost = async (body, cookie) => { const x = await fetch(API + '/api/notes', { method: 'POST', headers: { cookie, 'content-type': 'application/json' }, body: typeof body === 'string' ? body : J(body) }); return { status: x.status, json: await x.json().catch(() => null) }; };
  242. const serverNotes = async (cookie) => {
  243. const list = (await apiGet('/api/notes', cookie)).json.notes.filter(n => !n.gone);
  244. const out = [];
  245. for (const n of list) out.push({ ...n, text: (await apiGet('/api/notes?id=' + n.id, cookie)).json.text });
  246. return out;
  247. };
  248. const untilServer = async (cookie, pred, label) => {
  249. for (let i = 0; i < 80; i++) { const ns = await serverNotes(cookie); if (pred(ns)) return ns; await sleep(250); }
  250. throw new Error('server never showed: ' + label + ' ' + J(await serverNotes(cookie)));
  251. };
  252. // the page has synced when its socket is open and nothing waits in hl:web's queue (the replay is done)
  253. const synced = async (page, label) => {
  254. await page.waitFor('!!(window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1)', { label: label + ' (socket)', timeout: 20000 });
  255. for (let i = 0; i < 120; i++) { if ((await keptCopy(page)).queue === 0) return true; await sleep(250); }
  256. console.log('note: ' + label + ': the queue never emptied'); // the checks after this decide
  257. return false;
  258. };
  259. const keptPaths = (page) => page.evaluate(`(async () => { const out = []; for (const k of await caches.keys()) { if (!k.startsWith('hl-shell-')) continue; const c = await caches.open(k); for (const r of await c.keys()) out.push(new URL(r.url).pathname); } return out.sort().join(' '); })()`);
  260. const shellKept = async (page) => { for (let i = 0; i < 80; i++) { if (/(^| )\/( |$)/.test(await keptPaths(page))) return true; await sleep(250); } console.log('note: the page was never kept by hl:web: ' + await keptPaths(page)); return false; };
  261. await a.waitFor('!!navigator.serviceWorker.controller', { label: 'page controlled by a service worker' });
  262. await shellKept(a);
  263. const kp = await keptPaths(a);
  264. check("offline: hl:web's worker keeps the page document and the shell (runtime, client half, stylesheet, page modules)",
  265. /(^| )\/( |$)/.test(kp) && /\/__hl\/hl-runtime\.js/.test(kp) && /\/__hl\/web\/client\.js/.test(kp) && /\/__hl\/app\.css/.test(kp) && /\/components\/notes\.hl/.test(kp), kp);
  266. // ---- THE INSTALLABLE APP (mission 046): hl:web's own manifest from project.hl appIcons, and since notes#4 its own
  267. // generated service worker too (`offline = [Notes]`): notes' /sw.js and /notes-offline.js are gone.
  268. const pwaHtml = await (await fetch(API + '/')).text();
  269. const mhref = (pwaHtml.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  270. check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (the header token `darker`)',
  271. mhref === '/__hl/manifest.webmanifest' && pwaHtml.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')
  272. && pwaHtml.includes('<link rel="icon" href="/icons/favicon.svg">') && pwaHtml.includes('<meta name="theme-color" content="rgb(15, 20, 25)">'), pwaHtml.slice(0, 900));
  273. const mres = await fetch(API + mhref);
  274. const man = await mres.json();
  275. check('pwa: the manifest is served as application/manifest+json: name "notes", start_url /, scope /, display standalone, the token colours',
  276. /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'notes' && man.short_name === 'notes' && man.start_url === '/' && man.scope === '/'
  277. && man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', J(man));
  278. const iconOk = [];
  279. for (const ic of man.icons || []) {
  280. const ir = await fetch(API + ic.src);
  281. const buf = Buffer.from(await ir.arrayBuffer());
  282. iconOk.push(ir.ok && ic.type === 'image/png' && buf.readUInt32BE(16) === Number(ic.sizes.split('x')[0]) && buf.readUInt32BE(20) === Number(ic.sizes.split('x')[1]));
  283. }
  284. check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',
  285. 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));
  286. const touch = await fetch(API + '/icons/apple-touch-icon.png');
  287. const touchBytes = Buffer.from(await touch.arrayBuffer());
  288. const fav = await fetch(API + '/icons/favicon.svg');
  289. const favText = await fav.text();
  290. const ico = await fetch(API + '/favicon.ico');
  291. const icoBytes = Buffer.from(await ico.arrayBuffer());
  292. check('pwa: apple-touch-icon is a 180×180 PNG, the favicon an SVG in notes yellow, /favicon.ico a real icon file',
  293. touch.ok && touchBytes.readUInt32BE(16) === 180 && fav.ok && /image\/svg\+xml/.test(fav.headers.get('content-type') || '') && favText.includes('#dcdcaa')
  294. && ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);
  295. const am = await a.send('Page.getAppManifest');
  296. check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, J(am.errors));
  297. const inst = await a.send('Page.getInstallabilityErrors');
  298. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));
  299. const regs = await a.evaluate(`navigator.serviceWorker.getRegistrations().then(rs => rs.map(r => new URL(r.scope).pathname + ' ' + new URL((r.active || r.waiting || r.installing).scriptURL).pathname).join(','))`);
  300. check("pwa: exactly one service worker — hl:web's generated /__hl/sw.js for scope /, it controls the page; /sw.js and /notes-offline.js are gone (404)",
  301. regs === '/ /__hl/sw.js' && new URL(await a.evaluate('navigator.serviceWorker.controller.scriptURL')).pathname === '/__hl/sw.js'
  302. && (await fetch(API + '/sw.js')).status === 404 && (await fetch(API + '/notes-offline.js')).status === 404, regs);
  303. const pageJs = await a.evaluate(`[...document.scripts].map(x => x.src ? new URL(x.src).pathname : 'inline').join(' ')`);
  304. check('no hand-written notes JavaScript on the page: only hl:web, ident and login.js (no md-editor.js: the Hybriel MdEditor block draws the editor)', !/notes-offline|\/sw\.js|md-editor/.test(pageJs), pageJs);
  305. check('mission 010: /md-editor.js is gone (404) and no <md-editor> custom element is defined — the block\'s <md-editor> is plain Hybriel', (await fetch(API + '/md-editor.js')).status === 404 && !(await a.evaluate(`!!customElements.get('md-editor')`)), pageJs);
  306. // ---- new note: heading and text; saved on the server ------------------------------------------------------
  307. await a.click('#newnote');
  308. await a.waitFor(`/^\\/note\\/l[0-9a-f]+$/.test(location.pathname)`, { label: 'the new note is open' });
  309. await a.waitForSelector('#notetext');
  310. await editorReady(a, 'editor on the new note');
  311. check('new note: opens on the right, the sidebar lists it as "Untitled note"', (await subjects(a)).join('|') === 'Untitled note' && await visible(a, 'note-list') && await visible(a, 'note-editor'), J(await subjects(a)));
  312. await mdClick(a, 'md-editor article');
  313. await mdType(a, '# Groceries');
  314. await mdPress(a, 'Enter');
  315. await mdType(a, 'milk and bread');
  316. await a.waitFor(`document.querySelector('#notes a').textContent === 'Groceries'`, { label: 'sidebar shows the heading as the subject' });
  317. const t1 = await taVal(a);
  318. check('editor: "# " became a heading, the textarea holds the Markdown', t1 === '# Groceries\n\nmilk and bread' || t1 === '# Groceries\nmilk and bread', J(t1));
  319. check('editor: the heading is formatted (h1 in the editor)', await a.evaluate(mdR(`!!r.querySelector('md-editor article h1')`)));
  320. let sn = await untilServer(cookieA, ns => ns.length === 1 && /^# Groceries/.test(ns[0].text) && /milk and bread$/.test(ns[0].text), 'Groceries');
  321. check('online: the note reached the server, which gave it its own id', /^[0-9a-z]{12}$/.test(sn[0].id), J(sn));
  322. await a.waitFor(`location.pathname === '/note/${sn[0].id}'`, { label: 'the address follows the server id' });
  323. const firstUrl = '/note/' + sn[0].id;
  324. await shot(a, 'desktop-one-note');
  325. // ---- a second note; the edited one goes to the top ------------------------------------------------------------
  326. await a.click('#newnote');
  327. await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: 'second note' });
  328. await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ''`, { label: 'the second note is empty' });
  329. await editorReady(a, 'editor on the second note');
  330. await mdClick(a, 'md-editor article');
  331. await mdType(a, 'Zebra facts');
  332. await a.waitFor(`document.querySelector('#notes a').textContent === 'Zebra facts'`, { label: 'Zebra on top' });
  333. check('sidebar: two notes, the newest edited on top', (await subjects(a)).join('|') === 'Zebra facts|Groceries', J(await subjects(a)));
  334. await untilServer(cookieA, ns => ns.length === 2, 'two notes');
  335. await a.click(`#notes a[href="${firstUrl}"]`);
  336. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'Groceries text loaded' });
  337. check('sidebar click: the note opens on the right with its text', location_ok(await a.evaluate('location.pathname'), firstUrl));
  338. function location_ok(x, y) { return x === y; }
  339. // ---- device B (another browser, same login) gets the notes -------------------------------------------------------
  340. const b = await newPage();
  341. globalThis.__debugPages.B = b;
  342. await viewport(b, 1280, 900);
  343. await identSignIn(b, '[email protected]');
  344. await b.goto(BASE + '/');
  345. await hydrated(b);
  346. await buttonLogin(b);
  347. await b.waitForSelector('#newnote', { timeout: 15000 });
  348. await b.waitFor(`document.querySelectorAll('#notes a').length === 2`, { label: 'device B pulled the notes' });
  349. check('second device: the same two notes appear after login', (await subjects(b)).join('|') === 'Zebra facts|Groceries', J(await subjects(b)));
  350. await b.goto(BASE + firstUrl);
  351. await b.waitForSelector('#notetext');
  352. await b.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'B opened Groceries by its address' });
  353. check('second device: a note address opens the note', true);
  354. const cookieB = await cookieOf(b);
  355. await shellKept(b);
  356. // ---- CHROME OFFLINE on A (notes#4): CDP cuts the page and its worker, then the page is RELOADED offline ---------------
  357. await setOffline(a, true);
  358. await a.goto(BASE + firstUrl);
  359. await booted(a, 'offline: the page boots from the worker');
  360. await a.waitForSelector('#notetext', { timeout: 20000 });
  361. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'offline: the note opens from the browser copy' });
  362. check('offline: the page reloads with no network and shows the note and the list', (await subjects(a)).join('|') === 'Zebra facts|Groceries', J(await subjects(a)));
  363. check('chrome offline (new): the reload really is offline — the page booted from the worker and has no socket', !(await socketOpen(a)) && await a.evaluate('navigator.onLine === false'));
  364. await sleep(1500);
  365. check('chrome offline (new): the MdEditor block is there offline (it is in the page itself — no script file to keep)', await mdDefined(a), 'no md-editor article offline');
  366. await typeAtEnd(a, ' and eggs');
  367. await a.waitFor(`document.querySelector('#notes a').textContent === 'Groceries'`, { label: 'offline edit moves the note to the top' });
  368. await a.click('#newnote');
  369. await a.waitFor(`/^\\/note\\/l[0-9a-f]+$/.test(location.pathname)`, { label: 'offline: new note' });
  370. await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ''`, { label: 'offline: the new note is empty' });
  371. await typeAtEnd(a, 'Written offline');
  372. await a.waitFor(`document.querySelector('#notes a').textContent === 'Written offline'`, { label: 'offline note in the list' });
  373. const saysOffline = await a.waitFor(`/Offline/.test((document.getElementById('syncstate') || {}).textContent || '')`, { label: 'the page says it is offline' }).then(() => true, () => false);
  374. check('offline: the sidebar says the changes are kept here', saysOffline, J(await txt(a, '#syncstate')));
  375. await sleep(2500);
  376. const waiting = await keptCopy(a);
  377. const onServer = (await serverNotes(cookieA)).map(n => n.text);
  378. check('chrome offline (new): the edit and the new note wait in the browser (hl:web queue) — the server has neither yet',
  379. waiting.queue >= 2 && /and eggs/.test(waiting.queueText) && /Written offline/.test(waiting.queueText) && !onServer.some(t => /and eggs|Written offline/.test(t)), J({ q: waiting.queue, onServer }));
  380. await a.goto(BASE + '/');
  381. await booted(a, 'offline / boots');
  382. await a.waitForSelector('#notes a');
  383. await a.waitFor(`/Offline/.test((document.getElementById('syncstate') || {}).textContent || '')`, { label: 'offline / says it is offline' });
  384. check('offline: a reload of / with no network opens the shell (header, brand, logout, the list) and says it is offline (mission 046)',
  385. (await txt(a, 'application-header .brand')) === 'notes' && await has(a, '#logout') && await has(a, 'note-list') && /Offline/.test(await txt(a, '#syncstate')));
  386. await viewport(a, 390, 844);
  387. await shot(a, 'pwa-phone-offline');
  388. await viewport(a, 1280, 900);
  389. check('offline: after another reload the offline edits are all there', (await subjects(a)).join('|') === 'Written offline|Groceries|Zebra facts', J(await subjects(a)));
  390. await a.click('#notes li:nth-child(2) a');
  391. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('milk and bread and eggs')`, { label: 'the offline edit is in the note' });
  392. check('offline: the edited text survived the reload', true);
  393. until('offline');
  394. // ---- back online: it reaches the server, and device B --------------------------------------------------------------
  395. await setOffline(a, false);
  396. sn = await untilServer(cookieA, ns => ns.length === 3 && ns.some(n => /milk and bread and eggs$/.test(n.text)) && ns.some(n => n.text === 'Written offline'), 'the offline edits');
  397. check('back online: the offline edit and the offline note reached the server', sn.filter(n => n.text === 'Written offline').length === 1, J(sn));
  398. await synced(a, 'A back online');
  399. await a.waitFor(`[...document.querySelectorAll('#notes a')].length === 3 && [...document.querySelectorAll('#notes a')].every(x => !/\\/note\\/l/.test(x.getAttribute('href')))`, { label: 'the offline note got a server id' });
  400. check('back online: the offline note now has a server id', true);
  401. await b.waitFor(`document.querySelectorAll('#notes a').length === 3`, { label: 'B got the offline note' });
  402. await b.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('and eggs')`, { label: 'B shows the edit in the open note' });
  403. check('second device: sees the edit made offline on the first (open note refreshed) and the new note', (await subjects(b)).join('|') === 'Written offline|Groceries|Zebra facts', J(await subjects(b)));
  404. until('online');
  405. // ---- the same note edited on two devices while both are offline: nothing is lost -----------------------------------
  406. await b.click('#notes li:nth-child(3) a');
  407. await b.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Zebra facts'`, { label: 'B opened Zebra' });
  408. await a.click('#notes li:nth-child(3) a');
  409. await a.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Zebra facts'`, { label: 'A opened Zebra' });
  410. await stopServer();
  411. await typeAtEnd(a, ' on A');
  412. await sleep(1200);
  413. await typeAtEnd(b, ' on B');
  414. await sleep(300);
  415. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  416. await serverUp();
  417. await synced(a, 'A after the outage');
  418. await synced(b, 'B after the outage');
  419. sn = await untilServer(cookieA, ns => ns.length === 4, 'the conflict copy');
  420. const texts = sn.map(n => n.text);
  421. check('conflict: the later edit (B) is the note, the other (A) is kept as a copy — nothing lost', texts.includes('Zebra facts on B') && texts.some(t => t.startsWith('Zebra facts on A') && /kept as a copy/.test(t)), J(texts));
  422. await a.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'A shows the copy' });
  423. await b.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'B shows the copy' });
  424. check('conflict: both devices end with the same four notes', (await subjects(a)).slice().sort().join('|') === (await subjects(b)).slice().sort().join('|'), J(await subjects(a)) + J(await subjects(b)));
  425. until('conflict');
  426. // mission 014 (hybriel#196): "Delete note" is pressed ONCE and the question must open and stay open >= 0.5 s. (Mission 012 pressed
  427. // again when it closed by itself; the cause was notes.hl open() setting `asking = false` only after the awaited flush(0) ack.)
  428. const openAsk = async (page, label) => {
  429. const shown = `document.querySelector('#deleteyes').getBoundingClientRect().width > 0`;
  430. await page.click('#delete');
  431. await page.waitFor(shown, { label: label + ' opens' });
  432. const t0 = Date.now();
  433. while (Date.now() - t0 < 500) {
  434. if (!(await page.evaluate(shown))) throw new Error('the delete question closed by itself within 0.5 s: ' + label);
  435. await sleep(50);
  436. }
  437. return 1;
  438. };
  439. // ---- delete on A reaches B -------------------------------------------------------------------------------------------------
  440. await a.click('#notes li:nth-child(1) a');
  441. await a.waitFor(`!!document.getElementById('notetext')`, { label: 'A opened a note to delete' });
  442. const doomed = await a.evaluate('document.querySelector("#notetext input[name=text]").value');
  443. check('delete: the question is hidden until "Delete note" is clicked', !(await visible(a, '#deleteyes')));
  444. await openAsk(a, 'delete question');
  445. await a.click('#deleteno');
  446. await a.waitFor(`document.querySelector('#deleteyes').getBoundingClientRect().width === 0`, { label: 'kept' });
  447. check('delete: "Keep" changes nothing', (await subjects(a)).length === 4);
  448. await openAsk(a, 'delete question again');
  449. await a.click('#deleteyes');
  450. await a.waitFor(`location.pathname === '/' && document.querySelectorAll('#notes a').length === 3`, { label: 'back to the list, one note less' });
  451. check('delete: the note is gone from the list and the page is the list again', await has(a, '#pick'));
  452. await untilServer(cookieA, ns => ns.length === 3 && !ns.some(n => n.text === doomed), 'the delete');
  453. await b.waitFor(`document.querySelectorAll('#notes a').length === 3`, { label: 'B follows the delete' });
  454. check('delete: the other device follows', true);
  455. until('delete');
  456. // ---- NEW (notes#4): one device OFFLINE (Chrome, reloaded offline), the other online, the same note ----------------------
  457. const pickNote = async (page, subject) => {
  458. await page.evaluate(`[...document.querySelectorAll('#notes a')].find(x => x.textContent === ${J(subject)}).scrollIntoView()`);
  459. const i = await page.evaluate(`[...document.querySelectorAll('#notes a')].findIndex(x => x.textContent === ${J(subject)})`);
  460. await page.click(`#notes li:nth-child(${i + 1}) a`);
  461. };
  462. await pickNote(a, 'Written offline');
  463. await a.waitFor(`location.pathname.startsWith('/note/') && document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'A opened "Written offline"' });
  464. const splitUrl = await a.evaluate('location.pathname');
  465. await setOffline(a, true);
  466. await a.goto(BASE + splitUrl);
  467. await booted(a, 'A offline again');
  468. await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'A offline: the note' });
  469. await typeAtEnd(a, ' / A offline');
  470. await a.waitFor(`document.querySelector('#notes a').textContent === 'Written offline / A offline'`, { label: 'A offline: typed' });
  471. await sleep(2000);
  472. await pickNote(b, 'Written offline');
  473. await b.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'B opened it' });
  474. await typeAtEnd(b, ' / B online');
  475. await untilServer(cookieA, ns => ns.some(n => n.text === 'Written offline / B online'), 'B online save');
  476. check('one offline (new): while A is offline, B\'s online edit reaches the server and A\'s does not',
  477. !(await serverNotes(cookieA)).some(n => /A offline/.test(n.text)) && (await keptCopy(a)).queue >= 1);
  478. await setOffline(a, false);
  479. sn = await untilServer(cookieA, ns => ns.length === 4, 'the copy of the offline edit');
  480. const split = sn.map(n => n.text);
  481. check('one offline (new): back online, the later edit (B) is the note and A\'s offline edit is kept as a copy — nothing lost',
  482. split.includes('Written offline / B online') && split.some(t => t.startsWith('Written offline / A offline') && /kept as a copy/.test(t)), J(split));
  483. await synced(a, 'A back after the split');
  484. await a.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'A shows the copy' });
  485. await b.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'B shows the copy' });
  486. await a.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Written offline / B online'`, { label: 'A shows the winner in its editor' });
  487. check('one offline (new): both devices list the same four notes; A\'s editor now shows the winning text',
  488. (await subjects(a)).slice().sort().join('|') === (await subjects(b)).slice().sort().join('|'), J(await subjects(a)) + J(await subjects(b)));
  489. until('split');
  490. // ---- NEW (N1): TWO WRITERS on one note, both ways, by real keys: what B types must reach A as surely as A's reaches B ------------
  491. // (before the fix, tab A kept its own already-sent edit laid over the server's list, so B's text never showed in A)
  492. const twoPath = await a.evaluate('location.pathname');
  493. await b.goto(BASE + twoPath);
  494. await b.waitFor(`!!document.querySelector('#notetext md-editor article > *')`, { label: 'two writers: B opened the note' });
  495. await editorReady(a, 'two writers: A editor');
  496. const typeAt = async (page, mark) => { await mdClick(page, 'article'); await mdPress(page, 'End', CTRL); await mdType(page, mark); };
  497. let twoOk = true, twoWhy = '';
  498. for (let i = 1; i <= 3 && twoOk; i++) {
  499. for (const [src, dst, who, mark] of [[a, b, 'A', ` +a${i}`], [b, a, 'B', ` +b${i}`]]) {
  500. await typeAt(src, mark);
  501. try { await dst.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith(${J(mark)})`, { label: `two writers: ${who}'s ${mark} reaches the other tab`, timeout: 8000 }); }
  502. catch (e) { twoOk = false; twoWhy = `${who} typed ${mark}, the other tab shows …${(await taVal(dst)).slice(-30)}`; break; }
  503. }
  504. }
  505. check('two writers: text typed in tab B reaches tab A, and A\'s reaches B (3 rounds each way)', twoOk, twoWhy);
  506. await sleep(1500);
  507. const finalA = await taVal(a), finalB = await taVal(b);
  508. check('two writers: both tabs end with the same text holding every typed mark', finalA === finalB && [1, 2, 3].every(i => finalA.includes(` +a${i}`) && finalA.includes(` +b${i}`)), J(finalA.slice(-60)) + J(finalB.slice(-60)));
  509. await a.goto(BASE + twoPath);
  510. await editorReady(a, 'two writers: A reloaded');
  511. check('two writers: after a reload nothing is lost', (await taVal(a)).endsWith(' +b3') && (await taVal(a)).includes(' +a3'), J((await taVal(a)).slice(-40)));
  512. until('twowriters');
  513. // ---- somebody else sees nothing of it ----------------------------------------------------------------------------------------
  514. const bob = await newPage();
  515. await viewport(bob, 1280, 900);
  516. await identSignIn(bob, '[email protected]');
  517. await bob.goto(BASE + '/');
  518. await hydrated(bob);
  519. await buttonLogin(bob);
  520. await bob.waitForSelector('#newnote', { timeout: 15000 });
  521. await sleep(800);
  522. check('another user: an empty list', (await subjects(bob)).length === 0);
  523. const cookieBob = await cookieOf(bob);
  524. const alicePick = (await serverNotes(cookieA))[0];
  525. const aliceId = alicePick.id;
  526. check("another user: alice's note is not in bob's API", (await apiGet('/api/notes?id=' + aliceId, cookieBob)).status === 404 && (await apiGet('/api/notes', cookieBob)).json.notes.length === 0);
  527. await apiPost({ op: 'save', id: aliceId, local: '', text: 'hacked', base: 0, at: 1 }, cookieBob);
  528. await apiPost({ op: 'delete', id: aliceId, base: 0 }, cookieBob);
  529. check("another user: saving over / deleting alice's note does not touch it", (await serverNotes(cookieA)).some(n => n.id === aliceId && n.text === alicePick.text));
  530. check('a note over the size limit is refused, not cut', (await apiPost({ op: 'save', id: '', local: 'x1', text: 'x'.repeat(200001), base: 0, at: 1 }, cookieA)).status === 400);
  531. check('the API refuses invalid JSON and wrong fields with 400', (await apiPost('{nope', cookieA)).status === 400 && (await apiPost({ op: 'save', id: 5 }, cookieA)).status === 400 && (await apiPost({ op: 'zap' }, cookieA)).status === 400);
  532. // a retried push (the answer was lost) does not make a second note
  533. await apiPost({ op: 'save', id: '', local: 'lretry', text: 'retry me', base: 0, at: 5 }, cookieA);
  534. await apiPost({ op: 'save', id: '', local: 'lretry', text: 'retry me', base: 0, at: 5 }, cookieA);
  535. check('a push repeated after a lost answer makes no second note', (await serverNotes(cookieA)).filter(n => n.text === 'retry me').length === 1);
  536. // ---- MARKDOWN TABLES (notes#5): a table TYPED with real keys becomes a real <table>; a line with pipes stays text --------
  537. await a.goto(BASE + '/');
  538. await a.waitForSelector('#newnote');
  539. await hydrated(a); // the server-rendered button is clickable before the client mounts: that click is lost
  540. await a.click('#newnote');
  541. await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: 'tables: new note' });
  542. await editorReady(a, 'tables: editor');
  543. await mdClick(a, 'md-editor article');
  544. await mdType(a, 'Shopping table');
  545. await mdPress(a, 'Enter');
  546. await mdType(a, 'a | b stays text');
  547. await mdPress(a, 'Enter');
  548. await mdType(a, '| Item | Qty | Note \\| x |');
  549. await mdPress(a, 'Enter');
  550. await mdType(a, '|:---|:---:|---:|');
  551. await mdPress(a, 'Enter');
  552. await mdType(a, '**milk**');
  553. await mdPress(a, 'Tab');
  554. await mdType(a, '`2`');
  555. await mdPress(a, 'Tab');
  556. await mdType(a, 'a|b');
  557. await mdPress(a, 'Enter');
  558. await mdType(a, 'bread');
  559. await mdPress(a, 'Tab');
  560. await mdType(a, '1');
  561. await mdPress(a, 'Tab');
  562. await mdType(a, 'Donaudampfschifffahrtsgesellschaftskapitaenswitwenrentenversicherung');
  563. await mdPress(a, 'Enter');
  564. await mdPress(a, 'Enter');
  565. await mdType(a, 'after the table');
  566. const tableOf = (page) => page.evaluate(mdR(`(() => {
  567. const t = r.querySelector('md-editor article table'); if (!t) return null;
  568. const cell = (c) => ({ text: c.textContent, html: c.innerHTML, align: c.getAttribute('data-align') || '', css: getComputedStyle(c).textAlign });
  569. return { head: [...t.querySelectorAll('thead th')].map(cell), rows: [...t.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(cell)),
  570. ps: [...r.querySelectorAll('md-editor article > p')].map(p => p.textContent), order: [...r.querySelector('md-editor article').children].map(e => e.tagName).join(' ') };
  571. })()`));
  572. const tableOk = (t) => !!t && t.head.map(c => c.text).join('/') === 'Item/Qty/Note | x'
  573. && t.head.map(c => c.align + ':' + c.css).join(' ') === 'left:left center:center right:right'
  574. && t.rows.length === 2 && /^<strong>milk<\/strong>\u200b?$/.test(t.rows[0][0].html) && /^<code>2<\/code>\u200b?$/.test(t.rows[0][1].html) && t.rows[0][2].text === 'a|b'
  575. && t.rows[1].map(c => c.text).join('/').startsWith('bread/1/Donaudampf') && t.rows[1][1].css === 'center';
  576. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('after the table')`, { label: 'tables: typed to the end' });
  577. let tb = await tableOf(a);
  578. check('tables: typed header + delimiter + rows became a <table> (th, aligned left/center/right, bold + code cells, a typed pipe in a cell, \\| in the header)', tableOk(tb), J(tb));
  579. check('tables: the line with pipes stays a paragraph, text before and after the table too',
  580. !!tb && tb.ps.join('/') === 'Shopping table/a | b stays text/after the table' && tb.order === 'P P TABLE P', J(tb && [tb.ps, tb.order]));
  581. const md = await taVal(a);
  582. const mdLines = md.split('\n');
  583. const reparsed = mdLines.map(l => l === '' ? '' : l.startsWith('|') ? 'T' : 'p').join('').replace(/T+/g, 'T' + mdLines.filter(l => l.startsWith('|')).length);
  584. check('tables: the note is GitHub Markdown — pipe rows, `:---`/`:-:`/`--:`, escaped pipes, bold/code kept',
  585. /^\| Item +\| Qty +\| Note \\\| x +\|$/.test(mdLines.find(l => l.startsWith('| Item')) || '') && /^\| :-+ \| :-+: \| -+: \|$/.test(mdLines.find(l => /^\| :-/.test(l)) || '')
  586. && /\| \*\*milk\*\* +\| `2` +\| a\\\|b +\|/.test(md) && reparsed === 'ppT4p', J(md) + ' ' + reparsed);
  587. const tableNote = await untilServer(cookieA, ns => ns.some(n => n.text === md), 'the table note');
  588. const tableId = tableNote.find(n => n.text === md).id;
  589. await a.goto(BASE + '/note/' + tableId);
  590. await a.waitForSelector('#notetext');
  591. await editorReady(a, 'tables: reopened');
  592. await a.waitFor(mdR(`!!r.querySelector('md-editor article table')`), { label: 'tables: table after reload' });
  593. tb = await tableOf(a);
  594. check('tables: reopened from the server the note shows the same table, the text is unchanged', tableOk(tb) && (await taVal(a)) === md, J(tb));
  595. await viewport(a, 1280, 900);
  596. await shot(a, 'tables-desktop');
  597. await viewport(a, 390, 844);
  598. await sleep(300);
  599. const scroll = await a.evaluate(mdR(`(() => { const t = r.querySelector('md-editor article table'); const box = r.querySelector('md-editor article').getBoundingClientRect(); const q = t.getBoundingClientRect(); return { sw: t.scrollWidth, cw: t.clientWidth, inBox: q.right <= box.right + 1, ov: getComputedStyle(t).overflowX }; })()`));
  600. check('tables: on a phone the wide table scrolls inside its box, the page does not scroll sideways',
  601. scroll.sw > scroll.cw && scroll.inBox && /auto|scroll/.test(scroll.ov) && await noOverflow(a), J(scroll));
  602. await shot(a, 'tables-phone');
  603. const phoneEd = await a.evaluate(mdR(`(() => { const nav = r.querySelector('nav'); const bs = [...r.querySelectorAll('nav button')].map(x => x.getBoundingClientRect()); const q = r.getBoundingClientRect(); const tx = r.querySelector('article'); return { editorW: Math.round(q.width), viewW: innerWidth, small: bs.filter(x => x.width > 0 && (x.width < 43.5 || x.height < 43.5)).length, buttons: bs.length, fs: parseFloat(getComputedStyle(tx).fontSize), files: [...r.querySelectorAll('nav button')].some(x => /file/i.test(x.textContent) && x.getBoundingClientRect().width > 0) }; })()`));
  604. check('mission 010 (phone, 390): the editor fits the screen, every toolbar button is >= 44 px, the text is >= 16 px, no File button (files="off", the notes have no uploads)',
  605. phoneEd.editorW <= phoneEd.viewW && phoneEd.buttons > 0 && phoneEd.small === 0 && phoneEd.fs >= 16 && !phoneEd.files, J(phoneEd));
  606. await viewport(a, 1280, 900);
  607. // a cell edited in place: only that cell changes in the Markdown
  608. await mdClick(a, 'md-editor article tbody tr:first-child td:nth-child(2)');
  609. await mdPress(a, 'End');
  610. await mdType(a, '0');
  611. await a.waitFor(`document.querySelector('#notetext input[name=text]').value !== ${J(md)}`, { label: 'tables: cell edit' });
  612. const md2 = await taVal(a);
  613. const outside = (t) => t.split('\n').filter(l => !l.startsWith('|')).join('\n');
  614. const cellNow = (/\| \*\*milk\*\* +\| `(\d+)` +\|/.exec(md2) || [])[1] ? 'code:' + /\| \*\*milk\*\* +\| `(\d+)` +\|/.exec(md2)[1] : null;
  615. check('tables: typing in a cell changes that cell (`2` → `20`), the text around the table stays byte for byte', cellNow === 'code:20' && outside(md2) === outside(md) && md2.split('\n').filter(l => l.startsWith('|')).length === 4, J(md2));
  616. // offline: the table renders from the browser copy with the server gone
  617. await untilServer(cookieA, ns => ns.some(n => n.text === md2), 'the cell edit');
  618. await synced(a, 'tables: saved');
  619. await stopServer();
  620. await a.goto(BASE + '/note/' + tableId);
  621. await a.waitForSelector('#notetext', { timeout: 20000 });
  622. await a.waitFor(`document.querySelector('#notetext input[name=text]').value === ${J(md2)}`, { label: 'tables: offline text' });
  623. await sleep(1500);
  624. tb = null;
  625. if (await mdDefined(a)) {
  626. await editorReady(a, 'tables: offline');
  627. await a.waitFor(mdR(`!!r.querySelector('md-editor article table')`), { label: 'tables: offline table' });
  628. tb = await tableOf(a);
  629. }
  630. check('tables: offline (server stopped) the note opens from the browser copy with the table', !!tb && tb.rows.length === 2 && tb.rows[0][1].text === '20' && (await taVal(a)) === md2, tb ? J(tb) : 'no <md-editor> offline (Hybriel gap, report 007); the text itself is there: ' + ((await taVal(a)) === md2));
  631. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  632. await serverUp();
  633. await synced(a, 'tables: after the outage');
  634. // ---- phone and desktop layout ----------------------------------------------------------------------------------------------------
  635. await a.goto(BASE + '/');
  636. await a.waitForSelector('#notes a');
  637. await hydrated(a); // the sidebar links are server-rendered too
  638. await viewport(a, 390, 844);
  639. check('phone: the list alone, no note', await visible(a, 'note-list') && !(await visible(a, 'note-reader')) && await noOverflow(a));
  640. await shot(a, 'phone-list');
  641. // MN (mobile audit): the list header stands on the 16 px gutter like the rows' text, not on the screen edge
  642. const hdr = await a.evaluate(`(() => { const h = document.querySelector('note-list h1').getBoundingClientRect(), b = document.querySelector('#newnote').getBoundingClientRect(), r = document.querySelector('#notes a').getBoundingClientRect(); return { h1: Math.round(h.left), btnGap: Math.round(innerWidth - b.right), rowText: Math.round(r.left + parseFloat(getComputedStyle(document.querySelector('#notes a')).paddingLeft)) }; })()`);
  643. check('MN phone list: "Notes" and "New note" stand on the 16 px gutter (same left edge as the row text, not 4 px from the screen edge)', hdr.h1 >= 14 && hdr.btnGap >= 14 && Math.abs(hdr.h1 - hdr.rowText) <= 2, J(hdr));
  644. await a.click('#notes a');
  645. await a.waitForSelector('#notetext');
  646. await editorReady(a, 'phone editor');
  647. check('phone: the opened note replaces the list, with a way back', !(await visible(a, 'note-list')) && await visible(a, 'note-editor') && await visible(a, '.back') && await noOverflow(a));
  648. await shot(a, 'phone-note');
  649. // MN: back link close to the editor; "Delete note" under the editor's edge; the delete question on its own line with two equal buttons
  650. const g1 = await a.evaluate(`(() => { const q = (x) => document.querySelector(x).getBoundingClientRect(); return { gap: Math.round(q('#notetext').top - q('a.back').bottom), delLeft: q('#delete').left, edLeft: q('#notetext').left, backLeft: q('a.back').left }; })()`);
  651. check('MN phone note: the gap between "All notes" and the editor is <= 20 px, "Delete note" button left edge = editor left edge = All notes left edge', g1.gap <= 20 && Math.abs(g1.delLeft - g1.edLeft) <= 1 && Math.abs(g1.backLeft - g1.edLeft) <= 1, J(g1));
  652. await a.click('#delete');
  653. await a.waitFor(`getComputedStyle(document.querySelector('#deleteask')).display !== 'none'`, { label: 'delete question open' });
  654. const g2 = await a.evaluate(`(() => { const q = (x) => document.querySelector(x).getBoundingClientRect(); const t = document.querySelector('#deleteask ask-text').getBoundingClientRect(); return { qLeft: t.left, edLeft: q('#notetext').left, edRight: q('#notetext').right, rowLeft: q('#deleteyes').left, rowRight: q('#deleteno').right, qBottom: Math.round(t.bottom), yesTop: Math.round(q('#deleteyes').top), noTop: Math.round(q('#deleteno').top), yesW: Math.round(q('#deleteyes').width), noW: Math.round(q('#deleteno').width), yesH: Math.round(q('#deleteyes').height), noH: Math.round(q('#deleteno').height) }; })()`);
  655. check('MN phone delete question: text on the editor edge, then Delete and Keep side by side, equal, >= 44 px, below the text',
  656. Math.abs(g2.qLeft - g2.edLeft) <= 1 && Math.abs(g2.rowLeft - g2.edLeft) <= 1 && Math.abs(g2.rowRight - g2.edRight) <= 1 && g2.yesTop >= g2.qBottom - 1 && Math.abs(g2.yesTop - g2.noTop) <= 1 && Math.abs(g2.yesW - g2.noW) <= 2 && g2.yesW >= 100 && g2.yesH >= 43 && g2.noH >= 43 && await noOverflow(a), J(g2));
  657. await shot(a, 'phone-delete-ask');
  658. await a.click('#deleteno');
  659. await a.waitFor(`getComputedStyle(document.querySelector('#deleteask')).display === 'none'`, { label: 'delete question closed' });
  660. await a.click('.back');
  661. await a.waitFor(`location.pathname === '/' && document.querySelector('note-list').getBoundingClientRect().width > 0`, { label: 'phone: back to the list' });
  662. check('phone: "All notes" brings the list back', await visible(a, 'note-list') && !(await visible(a, 'note-reader')));
  663. await viewport(a, 1280, 900);
  664. await a.click('#notes a');
  665. await editorReady(a, 'desktop editor');
  666. check('desktop: list and note side by side, no "All notes" link', await visible(a, 'note-list') && await visible(a, 'note-editor') && !(await visible(a, '.back')) && await noOverflow(a));
  667. await shot(a, 'desktop-two');
  668. // ---- log out: the browser forgets the notes ---------------------------------------------------------------------------------------
  669. // mission 011: Log out is in the theme's user menu (the icon at the header's right end opens it)
  670. await a.click('button.user-toggle');
  671. await a.waitFor(`document.querySelector('#user-menu').matches(':popover-open')`, { label: 'user menu open' });
  672. await a.click('#logout');
  673. await a.waitForSelector('#loginhint');
  674. check('log out: the notes are gone from the page, the login hint shows', !(await has(a, '#notes')) && await has(a, '#loginbutton'));
  675. await sleep(1500);
  676. const after = await keptCopy(a);
  677. const leak = (x) => /Groceries|milk and bread|Zebra facts|Written offline/.test(x);
  678. check("log out: this browser deleted its copy of the notes (hl:web's kept state, queue and kept documents)",
  679. !leak(after.state) && after.queue === 0 && !after.docs.some(d => leak(d.html)), J({ state: after.state.slice(0, 300), q: after.queue, docs: after.docs.map(d => d.path + (leak(d.html) ? ' LEAK' : '')) }));
  680. check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));
  681. } catch (e) {
  682. if (process.env.NOTES_GATE_DEBUG) { for (const b of browsers) { try { for (const t of (await b.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'page')) console.log('DEBUG page', t.url); } catch {} } }
  683. for (const [name, dp] of Object.entries(globalThis.__debugPages || {})) if (process.env.NOTES_GATE_DEBUG) { try { console.log('DEBUG ' + name, await dp.evaluate(`JSON.stringify({ path: location.pathname, hrefs: [...document.querySelectorAll('#notes a')].map(a => a.getAttribute('href') + ' ' + a.textContent), sock: window.__hl && window.__hl.socket && window.__hl.socket.readyState, sync: (document.getElementById('syncstate')||{}).textContent })`), JSON.stringify(await keptCopy(dp)).slice(0, 1500)); console.log(dp.dumpConsole().split('\n').filter(l => !/debug|ERR_INTERNET|ERR_FAILED/.test(l)).slice(-40).join('\n')); } catch (x) { console.log('debug failed', x); } }
  684. if (e && e.until) { console.log('---- ' + e.message + ' (NOTES_GATE_UNTIL)'); failures += 0; } else {
  685. console.log('FAIL gate crashed — ' + (e && e.stack || e));
  686. failures++;
  687. console.log(log.slice(-1500));
  688. }
  689. } finally {
  690. for (const b of browsers) { try { await b.close(); } catch {} }
  691. await stopServer();
  692. if (ident) await ident.stop();
  693. console.log(`${passes} passed, ${failures} failed`);
  694. process.exit(failures ? 1 : 0);
  695. }

Branches

Latest commits

  • c37488b1MN report: alignment updatemre
  • 4fb35a0enotes mobile: Delete note and the delete row exactly on the editor's edges; gate asserts 1 pxmre
  • 91736270MN report and logmre
  • 15667425notes: delete confirmation buttons at most 12rem wide on the desktopmre
  • 8f7a6a95gate: MN phone checks (list header gutter, back gap, delete question)mre
  • 90c73ed3notes mobile: back link gapmre
  • 72bd4f83notes mobile: list header on the gutter, delete confirmation as a question + two equal buttons, Delete note under the editor edgemre
  • ba1e73f8notes: a sent edit is done once the server's version is not older, so a second writer's text shows in the first tab; gate: two writers both waysmre
  • c69ef9ebsync components.hybriel 134b4e3: MdEditor builds an editor put into the page at once, redraws a surface put in anew (F5, hybriel#211)mre
  • 2eb783f5sync components 9a: shared Icon (icons/icons.hl), md-editor toolbar icons + single focus ring (components f4-icons ba96735)mre
  • 4dd46dadsync-components: copy icons/icons.hl + README (F4); testsmre
  • c92e4a0ftests/e2e-outside.mjs: real-Chrome E2E, a note pushed from another device while open, then typingmre
  • 0516b4ccmd-editor.hl: verbatim copy of components f3-mdvalue (an older text handed back is kept)mre
  • 38cc11ecmd-editor.hl: verbatim copy of components f3-mdvalue (an outside value change is shown by the editor)mre
  • 3e7e79f5reports/H1-hydrate.mdmre
  • d98775e8tests/browser.mjs: wait for hydration before the clicks after a goto('/') (tables new note, phone sidebar)mre
  • 1f3198b6tests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
  • 39cf9fdfre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • db07aa84tests: short-id-switch ports from env (NOTES_SWITCH_IDENT_PORT/_PORT), defaults unchangedmre
  • ef9f9feere-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre