gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2cce9c962cce9c96code order: plain declarations where never reassigned (letcount 0 never); gate: scan every IndexedDB at log-out, soft mode for old-code runs, drop a check that could not failmre2cce9c96/tests/browser.mjs

47.3 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/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 t = document.getElementById('notetext'); const h = t && t.closest('md-editor'); const r = h && h.shadowRoot; 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.getElementById('notetext').value`);
  148. const editorReady = (page, label) => page.waitFor(mdR(`!!r.querySelector('[part~=editor]')`), { label });
  149. const emitFace = async (event, payload, cookie) => {
  150. const r = await fetch(API + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: 1, event, payload }) });
  151. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  152. return { status: r.status, raw: t, value: j && j.value };
  153. };
  154. // ---- CHROME OFFLINE (notes#4): CDP cuts the page AND its service worker. An open WebSocket survives the cut
  155. // (report 005), so every offline check first RELOADS offline: the page boots from hl:web's worker, no socket opens.
  156. async function workerSessions(page) {
  157. const conn = page.__browser.conn;
  158. page.__workers = page.__workers || new Map();
  159. const { targetInfos } = await conn.send('Target.getTargets');
  160. for (const t of targetInfos) {
  161. if (t.type === 'service_worker' && !page.__workers.has(t.targetId)) {
  162. const { sessionId } = await conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });
  163. await conn.send('Network.enable', {}, sessionId);
  164. page.__workers.set(t.targetId, sessionId);
  165. }
  166. }
  167. return [...page.__workers.values()];
  168. }
  169. async function setOffline(page, off) {
  170. await page.setOffline(off);
  171. for (const s of await workerSessions(page)) await page.__browser.conn.send('Network.emulateNetworkConditions', { offline: off, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, s);
  172. }
  173. const socketOpen = (page) => page.evaluate('!!(window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1)');
  174. const booted = (page, label) => page.waitFor('!!window.__hl', { label });
  175. // what hl:web keeps in this browser (IndexedDB `hl-offline`: `state`, `queue`) and the worker's documents
  176. const keptCopy = (page) => page.evaluate(`(async () => {
  177. const dbs = (await indexedDB.databases()).map(d => d.name);
  178. // every database of this origin, every store (hl:web's \`hl-offline\` and anything else, e.g. the old notes-<user>)
  179. let state = [], queue = [];
  180. for (const name of dbs) {
  181. const db = await new Promise((ok, no) => { const r = indexedDB.open(name); r.onsuccess = () => ok(r.result); r.onerror = () => no(r.error); });
  182. 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([]); } });
  183. 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 }); }
  184. db.close();
  185. }
  186. const docs = [];
  187. 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() }); } }
  188. return { dbs, state: JSON.stringify(state), queue: queue.length, queueText: JSON.stringify(queue), docs };
  189. })()`);
  190. // the editor: <md-editor>'s own surface when the element is defined, else the plain textarea it wraps — real keys either way
  191. const mdDefined = (page) => page.evaluate(`!!customElements.get('md-editor')`);
  192. async function typeAtEnd(page, text) {
  193. if (await mdDefined(page)) {
  194. await editorReady(page, 'editor');
  195. await mdClick(page, '[part~=editor] > :last-child');
  196. await mdPress(page, 'End', CTRL);
  197. } else {
  198. await page.click('#notetext');
  199. await mdPress(page, 'End', CTRL);
  200. }
  201. await mdType(page, text);
  202. }
  203. try {
  204. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  205. const alice = await ident.signIn('[email protected]');
  206. await ident.signIn('[email protected]');
  207. const APPKEY = await ident.registerApp(alice, 'notes (gate)', [BASE]);
  208. 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')));
  209. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  210. await serverUp();
  211. // ---- signed out -------------------------------------------------------------------------------------
  212. let html = await (await fetch(API + '/')).text();
  213. 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));
  214. let r = await fetch(API + '/login/callback', { redirect: 'manual' });
  215. check('login: /login/callback without a code → /login/failed', r.status === 302 && r.headers.get('location') === '/login/failed');
  216. r = await fetch(API + '/api/notes');
  217. check('signed out: the notes API answers 401', r.status === 401);
  218. r = await (await fetch(API + '/api/me')).json();
  219. check('signed out: /api/me says nobody', r.user === null, J(r));
  220. // ---- log in with ident (the button flow) on device A ----------------------------------------------------
  221. const a = await newPage();
  222. globalThis.__debugPages = { A: a };
  223. await viewport(a, 1280, 900);
  224. await identSignIn(a, '[email protected]');
  225. await a.goto(BASE + '/');
  226. await hydrated(a);
  227. check('signed out (browser): "Log in with ident" shows, no "New note"', await has(a, '#loginbutton') && !(await has(a, '#newnote')));
  228. await buttonLogin(a);
  229. await a.waitForSelector('#newnote', { timeout: 15000 });
  230. check('login: alice sees her (empty) list and "New note"', (await txt(a, '#empty')) !== null && (await subjects(a)).length === 0 && await has(a, '#logout'));
  231. const cookieOf = async (page) => (await page.cookies([BASE])).filter(c => c.name === 'notessid').map(c => 'notessid=' + c.value)[0];
  232. const cookieA = await cookieOf(a);
  233. const apiGet = async (path, cookie) => { const x = await fetch(API + path, { headers: { cookie } }); return { status: x.status, json: await x.json().catch(() => null) }; };
  234. 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) }; };
  235. const serverNotes = async (cookie) => {
  236. const list = (await apiGet('/api/notes', cookie)).json.notes.filter(n => !n.gone);
  237. const out = [];
  238. for (const n of list) out.push({ ...n, text: (await apiGet('/api/notes?id=' + n.id, cookie)).json.text });
  239. return out;
  240. };
  241. const untilServer = async (cookie, pred, label) => {
  242. for (let i = 0; i < 80; i++) { const ns = await serverNotes(cookie); if (pred(ns)) return ns; await sleep(250); }
  243. throw new Error('server never showed: ' + label + ' ' + J(await serverNotes(cookie)));
  244. };
  245. // the page has synced when its socket is open and nothing waits in hl:web's queue (the replay is done)
  246. const synced = async (page, label) => {
  247. await page.waitFor('!!(window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1)', { label: label + ' (socket)', timeout: 20000 });
  248. for (let i = 0; i < 120; i++) { if ((await keptCopy(page)).queue === 0) return true; await sleep(250); }
  249. console.log('note: ' + label + ': the queue never emptied'); // the checks after this decide
  250. return false;
  251. };
  252. 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(' '); })()`);
  253. 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; };
  254. await a.waitFor('!!navigator.serviceWorker.controller', { label: 'page controlled by a service worker' });
  255. await shellKept(a);
  256. const kp = await keptPaths(a);
  257. check("offline: hl:web's worker keeps the page document and the shell (runtime, client half, stylesheet, page modules)",
  258. /(^| )\/( |$)/.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);
  259. // ---- THE INSTALLABLE APP (mission 046): hl:web's own manifest from project.hl appIcons, and since notes#4 its own
  260. // generated service worker too (`offline = [Notes]`): notes' /sw.js and /notes-offline.js are gone.
  261. const pwaHtml = await (await fetch(API + '/')).text();
  262. const mhref = (pwaHtml.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  263. check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (the header token `darker`)',
  264. mhref === '/__hl/manifest.webmanifest' && pwaHtml.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')
  265. && pwaHtml.includes('<link rel="icon" href="/icons/favicon.svg">') && pwaHtml.includes('<meta name="theme-color" content="rgb(15, 20, 25)">'), pwaHtml.slice(0, 900));
  266. const mres = await fetch(API + mhref);
  267. const man = await mres.json();
  268. check('pwa: the manifest is served as application/manifest+json: name "notes", start_url /, scope /, display standalone, the token colours',
  269. /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'notes' && man.short_name === 'notes' && man.start_url === '/' && man.scope === '/'
  270. && man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', J(man));
  271. const iconOk = [];
  272. for (const ic of man.icons || []) {
  273. const ir = await fetch(API + ic.src);
  274. const buf = Buffer.from(await ir.arrayBuffer());
  275. 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]));
  276. }
  277. check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',
  278. 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));
  279. const touch = await fetch(API + '/icons/apple-touch-icon.png');
  280. const touchBytes = Buffer.from(await touch.arrayBuffer());
  281. const fav = await fetch(API + '/icons/favicon.svg');
  282. const favText = await fav.text();
  283. const ico = await fetch(API + '/favicon.ico');
  284. const icoBytes = Buffer.from(await ico.arrayBuffer());
  285. check('pwa: apple-touch-icon is a 180×180 PNG, the favicon an SVG in notes yellow, /favicon.ico a real icon file',
  286. touch.ok && touchBytes.readUInt32BE(16) === 180 && fav.ok && /image\/svg\+xml/.test(fav.headers.get('content-type') || '') && favText.includes('#dcdcaa')
  287. && ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);
  288. const am = await a.send('Page.getAppManifest');
  289. check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, J(am.errors));
  290. const inst = await a.send('Page.getInstallabilityErrors');
  291. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));
  292. 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(','))`);
  293. 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)",
  294. regs === '/ /__hl/sw.js' && new URL(await a.evaluate('navigator.serviceWorker.controller.scriptURL')).pathname === '/__hl/sw.js'
  295. && (await fetch(API + '/sw.js')).status === 404 && (await fetch(API + '/notes-offline.js')).status === 404, regs);
  296. const pageJs = await a.evaluate(`[...document.scripts].map(x => x.src ? new URL(x.src).pathname : 'inline').join(' ')`);
  297. check('no hand-written notes JavaScript on the page: only hl:web, ident, login.js and the vendored md-editor.js', !/notes-offline|\/sw\.js/.test(pageJs), pageJs);
  298. // ---- new note: heading and text; saved on the server ------------------------------------------------------
  299. await a.click('#newnote');
  300. await a.waitFor(`/^\\/note\\/l[0-9a-f]+$/.test(location.pathname)`, { label: 'the new note is open' });
  301. await a.waitForSelector('#notetext');
  302. await editorReady(a, 'editor on the new note');
  303. 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)));
  304. await mdClick(a, '[part~=editor]');
  305. await mdType(a, '# Groceries');
  306. await mdPress(a, 'Enter');
  307. await mdType(a, 'milk and bread');
  308. await a.waitFor(`document.querySelector('#notes a').textContent === 'Groceries'`, { label: 'sidebar shows the heading as the subject' });
  309. const t1 = await taVal(a);
  310. check('editor: "# " became a heading, the textarea holds the Markdown', t1 === '# Groceries\n\nmilk and bread' || t1 === '# Groceries\nmilk and bread', J(t1));
  311. check('editor: the heading is formatted (h1 in the editor)', await a.evaluate(mdR(`!!r.querySelector('[part~=editor] h1')`)));
  312. let sn = await untilServer(cookieA, ns => ns.length === 1 && /^# Groceries/.test(ns[0].text) && /milk and bread$/.test(ns[0].text), 'Groceries');
  313. check('online: the note reached the server, which gave it its own id', /^[0-9a-z]{12}$/.test(sn[0].id), J(sn));
  314. await a.waitFor(`location.pathname === '/note/${sn[0].id}'`, { label: 'the address follows the server id' });
  315. const firstUrl = '/note/' + sn[0].id;
  316. await shot(a, 'desktop-one-note');
  317. // ---- a second note; the edited one goes to the top ------------------------------------------------------------
  318. await a.click('#newnote');
  319. await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: 'second note' });
  320. await a.waitFor(`document.getElementById('notetext') && document.getElementById('notetext').value === ''`, { label: 'the second note is empty' });
  321. await editorReady(a, 'editor on the second note');
  322. await mdClick(a, '[part~=editor]');
  323. await mdType(a, 'Zebra facts');
  324. await a.waitFor(`document.querySelector('#notes a').textContent === 'Zebra facts'`, { label: 'Zebra on top' });
  325. check('sidebar: two notes, the newest edited on top', (await subjects(a)).join('|') === 'Zebra facts|Groceries', J(await subjects(a)));
  326. await untilServer(cookieA, ns => ns.length === 2, 'two notes');
  327. await a.click(`#notes a[href="${firstUrl}"]`);
  328. await a.waitFor(`document.getElementById('notetext').value.startsWith('# Groceries')`, { label: 'Groceries text loaded' });
  329. check('sidebar click: the note opens on the right with its text', location_ok(await a.evaluate('location.pathname'), firstUrl));
  330. function location_ok(x, y) { return x === y; }
  331. // ---- device B (another browser, same login) gets the notes -------------------------------------------------------
  332. const b = await newPage();
  333. globalThis.__debugPages.B = b;
  334. await viewport(b, 1280, 900);
  335. await identSignIn(b, '[email protected]');
  336. await b.goto(BASE + '/');
  337. await hydrated(b);
  338. await buttonLogin(b);
  339. await b.waitForSelector('#newnote', { timeout: 15000 });
  340. await b.waitFor(`document.querySelectorAll('#notes a').length === 2`, { label: 'device B pulled the notes' });
  341. check('second device: the same two notes appear after login', (await subjects(b)).join('|') === 'Zebra facts|Groceries', J(await subjects(b)));
  342. await b.goto(BASE + firstUrl);
  343. await b.waitForSelector('#notetext');
  344. await b.waitFor(`document.getElementById('notetext').value.startsWith('# Groceries')`, { label: 'B opened Groceries by its address' });
  345. check('second device: a note address opens the note', true);
  346. const cookieB = await cookieOf(b);
  347. await shellKept(b);
  348. // ---- CHROME OFFLINE on A (notes#4): CDP cuts the page and its worker, then the page is RELOADED offline ---------------
  349. await setOffline(a, true);
  350. await a.goto(BASE + firstUrl);
  351. await booted(a, 'offline: the page boots from the worker');
  352. await a.waitForSelector('#notetext', { timeout: 20000 });
  353. await a.waitFor(`document.getElementById('notetext').value.startsWith('# Groceries')`, { label: 'offline: the note opens from the browser copy' });
  354. 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)));
  355. 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'));
  356. await sleep(1500);
  357. check('chrome offline (new): the Markdown editor is there offline (/md-editor.js kept for offline use)', await mdDefined(a), 'customElements has no md-editor: hl:web keeps no app file route offline (Hybriel gap, report 007)');
  358. await typeAtEnd(a, ' and eggs');
  359. await a.waitFor(`document.querySelector('#notes a').textContent === 'Groceries'`, { label: 'offline edit moves the note to the top' });
  360. await a.click('#newnote');
  361. await a.waitFor(`/^\\/note\\/l[0-9a-f]+$/.test(location.pathname)`, { label: 'offline: new note' });
  362. await a.waitFor(`document.getElementById('notetext') && document.getElementById('notetext').value === ''`, { label: 'offline: the new note is empty' });
  363. await typeAtEnd(a, 'Written offline');
  364. await a.waitFor(`document.querySelector('#notes a').textContent === 'Written offline'`, { label: 'offline note in the list' });
  365. const saysOffline = await a.waitFor(`/Offline/.test((document.getElementById('syncstate') || {}).textContent || '')`, { label: 'the page says it is offline' }).then(() => true, () => false);
  366. check('offline: the sidebar says the changes are kept here', saysOffline, J(await txt(a, '#syncstate')));
  367. await sleep(2500);
  368. const waiting = await keptCopy(a);
  369. const onServer = (await serverNotes(cookieA)).map(n => n.text);
  370. check('chrome offline (new): the edit and the new note wait in the browser (hl:web queue) — the server has neither yet',
  371. 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 }));
  372. await a.goto(BASE + '/');
  373. await booted(a, 'offline / boots');
  374. await a.waitForSelector('#notes a');
  375. await a.waitFor(`/Offline/.test((document.getElementById('syncstate') || {}).textContent || '')`, { label: 'offline / says it is offline' });
  376. check('offline: a reload of / with no network opens the shell (header, brand, logout, the list) and says it is offline (mission 046)',
  377. (await txt(a, 'application-header .brand')) === 'notes' && await has(a, '#logout') && await has(a, 'note-list') && /Offline/.test(await txt(a, '#syncstate')));
  378. await viewport(a, 390, 844);
  379. await shot(a, 'pwa-phone-offline');
  380. await viewport(a, 1280, 900);
  381. check('offline: after another reload the offline edits are all there', (await subjects(a)).join('|') === 'Written offline|Groceries|Zebra facts', J(await subjects(a)));
  382. await a.click('#notes li:nth-child(2) a');
  383. await a.waitFor(`document.getElementById('notetext').value.endsWith('milk and bread and eggs')`, { label: 'the offline edit is in the note' });
  384. check('offline: the edited text survived the reload', true);
  385. until('offline');
  386. // ---- back online: it reaches the server, and device B --------------------------------------------------------------
  387. await setOffline(a, false);
  388. 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');
  389. check('back online: the offline edit and the offline note reached the server', sn.filter(n => n.text === 'Written offline').length === 1, J(sn));
  390. await synced(a, 'A back online');
  391. 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' });
  392. check('back online: the offline note now has a server id', true);
  393. await b.waitFor(`document.querySelectorAll('#notes a').length === 3`, { label: 'B got the offline note' });
  394. await b.waitFor(`document.getElementById('notetext').value.endsWith('and eggs')`, { label: 'B shows the edit in the open note' });
  395. 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)));
  396. until('online');
  397. // ---- the same note edited on two devices while both are offline: nothing is lost -----------------------------------
  398. await b.click('#notes li:nth-child(3) a');
  399. await b.waitFor(`document.getElementById('notetext').value === 'Zebra facts'`, { label: 'B opened Zebra' });
  400. await a.click('#notes li:nth-child(3) a');
  401. await a.waitFor(`document.getElementById('notetext').value === 'Zebra facts'`, { label: 'A opened Zebra' });
  402. await stopServer();
  403. await typeAtEnd(a, ' on A');
  404. await sleep(1200);
  405. await typeAtEnd(b, ' on B');
  406. await sleep(300);
  407. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  408. await serverUp();
  409. await synced(a, 'A after the outage');
  410. await synced(b, 'B after the outage');
  411. sn = await untilServer(cookieA, ns => ns.length === 4, 'the conflict copy');
  412. const texts = sn.map(n => n.text);
  413. 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));
  414. await a.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'A shows the copy' });
  415. await b.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'B shows the copy' });
  416. 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)));
  417. until('conflict');
  418. // ---- delete on A reaches B -------------------------------------------------------------------------------------------------
  419. await a.click('#notes li:nth-child(1) a');
  420. await a.waitFor(`!!document.getElementById('notetext')`, { label: 'A opened a note to delete' });
  421. const doomed = await a.evaluate('document.getElementById("notetext").value');
  422. check('delete: the question is hidden until "Delete note" is clicked', !(await visible(a, '#deleteyes')));
  423. await a.click('#delete');
  424. await a.waitFor(`document.querySelector('#deleteyes').getBoundingClientRect().width > 0`, { label: 'delete question' });
  425. await a.click('#deleteno');
  426. await a.waitFor(`document.querySelector('#deleteyes').getBoundingClientRect().width === 0`, { label: 'kept' });
  427. check('delete: "Keep" changes nothing', (await subjects(a)).length === 4);
  428. await a.click('#delete');
  429. await a.waitFor(`document.querySelector('#deleteyes').getBoundingClientRect().width > 0`, { label: 'delete question again' });
  430. await a.click('#deleteyes');
  431. await a.waitFor(`location.pathname === '/' && document.querySelectorAll('#notes a').length === 3`, { label: 'back to the list, one note less' });
  432. check('delete: the note is gone from the list and the page is the list again', await has(a, '#pick'));
  433. await untilServer(cookieA, ns => ns.length === 3 && !ns.some(n => n.text === doomed), 'the delete');
  434. await b.waitFor(`document.querySelectorAll('#notes a').length === 3`, { label: 'B follows the delete' });
  435. check('delete: the other device follows', true);
  436. until('delete');
  437. // ---- NEW (notes#4): one device OFFLINE (Chrome, reloaded offline), the other online, the same note ----------------------
  438. const pickNote = async (page, subject) => {
  439. await page.evaluate(`[...document.querySelectorAll('#notes a')].find(x => x.textContent === ${J(subject)}).scrollIntoView()`);
  440. const i = await page.evaluate(`[...document.querySelectorAll('#notes a')].findIndex(x => x.textContent === ${J(subject)})`);
  441. await page.click(`#notes li:nth-child(${i + 1}) a`);
  442. };
  443. await pickNote(a, 'Written offline');
  444. await a.waitFor(`location.pathname.startsWith('/note/') && document.getElementById('notetext').value === 'Written offline'`, { label: 'A opened "Written offline"' });
  445. const splitUrl = await a.evaluate('location.pathname');
  446. await setOffline(a, true);
  447. await a.goto(BASE + splitUrl);
  448. await booted(a, 'A offline again');
  449. await a.waitFor(`document.getElementById('notetext') && document.getElementById('notetext').value === 'Written offline'`, { label: 'A offline: the note' });
  450. await typeAtEnd(a, ' / A offline');
  451. await a.waitFor(`document.querySelector('#notes a').textContent === 'Written offline / A offline'`, { label: 'A offline: typed' });
  452. await sleep(2000);
  453. await pickNote(b, 'Written offline');
  454. await b.waitFor(`document.getElementById('notetext').value === 'Written offline'`, { label: 'B opened it' });
  455. await typeAtEnd(b, ' / B online');
  456. await untilServer(cookieA, ns => ns.some(n => n.text === 'Written offline / B online'), 'B online save');
  457. check('one offline (new): while A is offline, B\'s online edit reaches the server and A\'s does not',
  458. !(await serverNotes(cookieA)).some(n => /A offline/.test(n.text)) && (await keptCopy(a)).queue >= 1);
  459. await setOffline(a, false);
  460. sn = await untilServer(cookieA, ns => ns.length === 4, 'the copy of the offline edit');
  461. const split = sn.map(n => n.text);
  462. 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',
  463. split.includes('Written offline / B online') && split.some(t => t.startsWith('Written offline / A offline') && /kept as a copy/.test(t)), J(split));
  464. await synced(a, 'A back after the split');
  465. await a.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'A shows the copy' });
  466. await b.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'B shows the copy' });
  467. await a.waitFor(`document.getElementById('notetext').value === 'Written offline / B online'`, { label: 'A shows the winner in its editor' });
  468. check('one offline (new): both devices list the same four notes; A\'s editor now shows the winning text',
  469. (await subjects(a)).slice().sort().join('|') === (await subjects(b)).slice().sort().join('|'), J(await subjects(a)) + J(await subjects(b)));
  470. until('split');
  471. // ---- somebody else sees nothing of it ----------------------------------------------------------------------------------------
  472. const bob = await newPage();
  473. await viewport(bob, 1280, 900);
  474. await identSignIn(bob, '[email protected]');
  475. await bob.goto(BASE + '/');
  476. await hydrated(bob);
  477. await buttonLogin(bob);
  478. await bob.waitForSelector('#newnote', { timeout: 15000 });
  479. await sleep(800);
  480. check('another user: an empty list', (await subjects(bob)).length === 0);
  481. const cookieBob = await cookieOf(bob);
  482. const alicePick = (await serverNotes(cookieA))[0];
  483. const aliceId = alicePick.id;
  484. 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);
  485. await apiPost({ op: 'save', id: aliceId, local: '', text: 'hacked', base: 0, at: 1 }, cookieBob);
  486. await apiPost({ op: 'delete', id: aliceId, base: 0 }, cookieBob);
  487. 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));
  488. 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);
  489. 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);
  490. // a retried push (the answer was lost) does not make a second note
  491. await apiPost({ op: 'save', id: '', local: 'lretry', text: 'retry me', base: 0, at: 5 }, cookieA);
  492. await apiPost({ op: 'save', id: '', local: 'lretry', text: 'retry me', base: 0, at: 5 }, cookieA);
  493. check('a push repeated after a lost answer makes no second note', (await serverNotes(cookieA)).filter(n => n.text === 'retry me').length === 1);
  494. // ---- MARKDOWN TABLES (notes#5): a table TYPED with real keys becomes a real <table>; a line with pipes stays text --------
  495. await a.goto(BASE + '/');
  496. await a.waitForSelector('#newnote');
  497. await a.click('#newnote');
  498. await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: 'tables: new note' });
  499. await editorReady(a, 'tables: editor');
  500. await mdClick(a, '[part~=editor]');
  501. await mdType(a, 'Shopping table');
  502. await mdPress(a, 'Enter');
  503. await mdType(a, 'a | b stays text');
  504. await mdPress(a, 'Enter');
  505. await mdType(a, '| Item | Qty | Note \\| x |');
  506. await mdPress(a, 'Enter');
  507. await mdType(a, '|:---|:---:|---:|');
  508. await mdPress(a, 'Enter');
  509. await mdType(a, '**milk**');
  510. await mdPress(a, 'Tab');
  511. await mdType(a, '`2`');
  512. await mdPress(a, 'Tab');
  513. await mdType(a, 'a|b');
  514. await mdPress(a, 'Enter');
  515. await mdType(a, 'bread');
  516. await mdPress(a, 'Tab');
  517. await mdType(a, '1');
  518. await mdPress(a, 'Tab');
  519. await mdType(a, 'Donaudampfschifffahrtsgesellschaftskapitaenswitwenrentenversicherung');
  520. await mdPress(a, 'Enter');
  521. await mdPress(a, 'Enter');
  522. await mdType(a, 'after the table');
  523. const tableOf = (page) => page.evaluate(mdR(`(() => {
  524. const t = r.querySelector('[part~=editor] table'); if (!t) return null;
  525. const cell = (c) => ({ text: c.textContent, html: c.innerHTML, align: c.getAttribute('data-align') || '', css: getComputedStyle(c).textAlign });
  526. return { head: [...t.querySelectorAll('thead th')].map(cell), rows: [...t.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(cell)),
  527. ps: [...r.querySelectorAll('[part~=editor] > p')].map(p => p.textContent), order: [...r.querySelector('[part~=editor]').children].map(e => e.tagName).join(' ') };
  528. })()`));
  529. const tableOk = (t) => !!t && t.head.map(c => c.text).join('/') === 'Item/Qty/Note | x'
  530. && t.head.map(c => c.align + ':' + c.css).join(' ') === 'left:left center:center right:right'
  531. && t.rows.length === 2 && /^<strong>milk<\/strong>$/.test(t.rows[0][0].html) && /^<code>2<\/code>$/.test(t.rows[0][1].html) && t.rows[0][2].text === 'a|b'
  532. && t.rows[1].map(c => c.text).join('/').startsWith('bread/1/Donaudampf') && t.rows[1][1].css === 'center';
  533. await a.waitFor(`document.getElementById('notetext').value.endsWith('after the table')`, { label: 'tables: typed to the end' });
  534. let tb = await tableOf(a);
  535. 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));
  536. check('tables: the line with pipes stays a paragraph, text before and after the table too',
  537. !!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]));
  538. const md = await taVal(a);
  539. const mdLines = md.split('\n');
  540. const reparsed = await a.evaluate(`MdEditor.markdown.markdownBlocks(${J(md)}).map(b => b.isTable ? 'table:' + b.cols + 'x' + b.rows.length + ':' + b.aligns.join(',') : b.isP ? 'p' : '?').join(' ')`);
  541. check('tables: the note is GitHub Markdown — pipe rows, `:---`/`:-:`/`--:`, escaped pipes, bold/code kept',
  542. /^\| Item +\| Qty +\| Note \\\| x +\|$/.test(mdLines.find(l => l.startsWith('| Item')) || '') && /^\| :-+ \| :-+: \| -+: \|$/.test(mdLines.find(l => /^\| :-/.test(l)) || '')
  543. && /\| \*\*milk\*\* +\| `2` +\| a\\\|b +\|/.test(md) && reparsed === 'p p table:3x3:left,center,right p', J(md) + ' ' + reparsed);
  544. const tableNote = await untilServer(cookieA, ns => ns.some(n => n.text === md), 'the table note');
  545. const tableId = tableNote.find(n => n.text === md).id;
  546. await a.goto(BASE + '/note/' + tableId);
  547. await a.waitForSelector('#notetext');
  548. await editorReady(a, 'tables: reopened');
  549. await a.waitFor(mdR(`!!r.querySelector('[part~=editor] table')`), { label: 'tables: table after reload' });
  550. tb = await tableOf(a);
  551. check('tables: reopened from the server the note shows the same table, the text is unchanged', tableOk(tb) && (await taVal(a)) === md, J(tb));
  552. await viewport(a, 1280, 900);
  553. await shot(a, 'tables-desktop');
  554. await viewport(a, 390, 844);
  555. await sleep(300);
  556. const scroll = await a.evaluate(mdR(`(() => { const t = r.querySelector('[part~=editor] table'); const box = r.querySelector('[part~=editor]').getBoundingClientRect(); const q = t.getBoundingClientRect(); return { sw: t.scrollWidth, cw: t.clientWidth, inBox: q.right <= box.right + 1, ov: getComputedStyle(t).overflowX }; })()`));
  557. check('tables: on a phone the wide table scrolls inside its box, the page does not scroll sideways',
  558. scroll.sw > scroll.cw && scroll.inBox && /auto|scroll/.test(scroll.ov) && await noOverflow(a), J(scroll));
  559. await shot(a, 'tables-phone');
  560. await viewport(a, 1280, 900);
  561. // a cell edited in place: only that cell changes in the Markdown
  562. await mdClick(a, '[part~=editor] tbody tr:first-child td:nth-child(2)');
  563. await mdPress(a, 'End');
  564. await mdType(a, '0');
  565. await a.waitFor(`document.getElementById('notetext').value !== ${J(md)}`, { label: 'tables: cell edit' });
  566. const md2 = await taVal(a);
  567. const outside = (t) => t.split('\n').filter(l => !l.startsWith('|')).join('\n');
  568. const cellNow = await a.evaluate(`MdEditor.markdown.markdownBlocks(${J(md2)}).filter(b => b.isTable).map(b => b.rows[1][1].map(s => (s.isCode ? 'code:' : '') + s.text).join(''))[0]`);
  569. 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));
  570. // offline: the table renders from the browser copy with the server gone
  571. await untilServer(cookieA, ns => ns.some(n => n.text === md2), 'the cell edit');
  572. await synced(a, 'tables: saved');
  573. await stopServer();
  574. await a.goto(BASE + '/note/' + tableId);
  575. await a.waitForSelector('#notetext', { timeout: 20000 });
  576. await a.waitFor(`document.getElementById('notetext').value === ${J(md2)}`, { label: 'tables: offline text' });
  577. await sleep(1500);
  578. tb = null;
  579. if (await mdDefined(a)) {
  580. await editorReady(a, 'tables: offline');
  581. await a.waitFor(mdR(`!!r.querySelector('[part~=editor] table')`), { label: 'tables: offline table' });
  582. tb = await tableOf(a);
  583. }
  584. 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));
  585. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  586. await serverUp();
  587. await synced(a, 'tables: after the outage');
  588. // ---- phone and desktop layout ----------------------------------------------------------------------------------------------------
  589. await a.goto(BASE + '/');
  590. await a.waitForSelector('#notes a');
  591. await viewport(a, 390, 844);
  592. check('phone: the list alone, no note', await visible(a, 'note-list') && !(await visible(a, 'note-reader')) && await noOverflow(a));
  593. await shot(a, 'phone-list');
  594. await a.click('#notes a');
  595. await a.waitForSelector('#notetext');
  596. await editorReady(a, 'phone editor');
  597. 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));
  598. await shot(a, 'phone-note');
  599. await a.click('.back');
  600. await a.waitFor(`location.pathname === '/' && document.querySelector('note-list').getBoundingClientRect().width > 0`, { label: 'phone: back to the list' });
  601. check('phone: "All notes" brings the list back', await visible(a, 'note-list') && !(await visible(a, 'note-reader')));
  602. await viewport(a, 1280, 900);
  603. await a.click('#notes a');
  604. await editorReady(a, 'desktop editor');
  605. 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));
  606. await shot(a, 'desktop-two');
  607. // ---- log out: the browser forgets the notes ---------------------------------------------------------------------------------------
  608. await a.click('#logout');
  609. await a.waitForSelector('#loginhint');
  610. check('log out: the notes are gone from the page, the login hint shows', !(await has(a, '#notes')) && await has(a, '#loginbutton'));
  611. await sleep(1500);
  612. const after = await keptCopy(a);
  613. const leak = (x) => /Groceries|milk and bread|Zebra facts|Written offline/.test(x);
  614. check("log out: this browser deleted its copy of the notes (hl:web's kept state, queue and kept documents)",
  615. !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' : '')) }));
  616. check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));
  617. } catch (e) {
  618. 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 {} } }
  619. 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); } }
  620. if (e && e.until) { console.log('---- ' + e.message + ' (NOTES_GATE_UNTIL)'); failures += 0; } else {
  621. console.log('FAIL gate crashed — ' + (e && e.stack || e));
  622. failures++;
  623. console.log(log.slice(-1500));
  624. }
  625. } finally {
  626. for (const b of browsers) { try { await b.close(); } catch {} }
  627. await stopServer();
  628. if (ident) await ident.stop();
  629. console.log(`${passes} passed, ${failures} failed`);
  630. process.exit(failures ? 1 : 0);
  631. }

Branches

Latest commits

  • 2cce9c96code order: plain declarations where never reassigned (letcount 0 never); gate: scan every IndexedDB at log-out, soft mode for old-code runs, drop a check that could not failmre
  • 7f6a4090README: offline in Hybriel (hl:web offline, continuation, known md-editor gap); gate waits report instead of crash; realdata-offline checkmre
  • 632223f2notes#4: delete notes-offline.js and sw.js (hl:web's generated worker and kept state replace them)mre
  • 52a2acadgate: offline checks on hl:web's worker/queue, Chrome offline via CDP (reload offline first), one-offline conflict, log-out forgets the kept copymre
  • e5785b03notes#4: the notes page in Hybriel — hl:web offline = [Notes], queued faces notesPut/notesDrop, push notesChanged, value-form notesPull on a tick; notes-offline.js/sw.js no longer loaded or routedmre
  • 510aff75notes#4: server continues a run of saves of one login (by + since), loser keeps writing into its copy; notesFor listmre
  • 0176c4b5mission brief 007mre
  • 06cfa870notes mission 006: re-vendor hybriel 0f396652 (static), reportmre
  • 6c07bd91mission brief w6mre
  • cf64d3d5notes mission 005: stopped at a Hybriel gap (for list repainted during hl:web boot throws, rowKidless); report, LOG, STATUSmre
  • a43b5d2dmission brief 005mre
  • 04a625edmission 004: re-vendor hybriel a832f73b (native bin + plugins as tickets), compose HL_CACHE_DIR volume + tmpfs /tmp, deploy URL wait 120 s, tests wait 120 s per start; gate 57/0 old and new; real-data same output. Not deployed.mre
  • aefb9d44mission brief w4mre
  • 202098b3docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 304f6a9dnotes mission 003 (#5): report, STATUS, LOGmre
  • 9acc27f8notes mission 003 (#5): GitHub pipe tables in md-editor (parse, render, type, write) + gate checksmre
  • 2149e902notes mission 002 (4/4): code order — README file map + same-output test, STATUS, LOG, report; tests/letcount.py, tests/realdata-baseline.mjs, tests/realdata-compare.pymre
  • 47db4fc1notes mission 002 (3/4): code order — let only where reassigned (58 dropped; 34 left: 19 reassigned, 15 loop-bound); gates 50/0 + 18/0, live-data run = step 2mre
  • 3f8cb383notes mission 002 (2/4): code order — topics, map, thin wrappers: lib/util.hl, lib/notes(-helpers).hl, lib/users.hl (+userOfLoginCode, tagOf), lib/api(-helpers).hl; project.hl = map; login routes take &req/&sessions (failed-login reason now kept); dead notes#1 functions removed; gates 50/0 + 18/0mre
  • 8cda5412notes mission 002 (1/4): code order — files moved: lib/notes.hl, lib/users.hl, lib/jsoncheck.hl, components/styles.hl (imports only); gates 50/0 + 18/0, live-data run identicalmre