gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit31b758aa31b758aatracker#10: installable app (manifest, service worker, offline shell), own icon + faviconmre31b758aa/tests/browser.mjs

40.4 KB

  1. // tests/browser.mjs — THE GATE of tracker.worldapi.org#1: this app's own server on its own storage, its OWN ident
  2. // (a copy of ident's code without .env, codes to a mail sink: tests/identkit.mjs, same as calendar's gate), a real
  3. // headless Chrome. Proves: signed out (header shows "Log in with ident") -> sign in -> the header selector shows
  4. // signed in, "Log out" appears, the page itself stays empty -> sign out -> signed out again (a reload confirms it).
  5. //
  6. // node tests/browser.mjs (TRACKER_GATE_PORT server, default 8700; TRACKER_GATE_IDENT_PORT ident, default 8701;
  7. // TRACKER_GATE_CHROME "8702-8709" = Chrome debug ports; TRACKER_GATE_TMDB_PORT the fake
  8. // TMDB, default 8710)
  9. import { spawn, execFileSync } from 'node:child_process';
  10. import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
  11. import { dirname, join, resolve } from 'node:path';
  12. import { fileURLToPath } from 'node:url';
  13. import { launchBrowser } from './cdp.mjs';
  14. import { startIdent } from './identkit.mjs';
  15. import { startFakeTmdb, PNG } from './faketmdb.mjs';
  16. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  17. const HERE = dirname(fileURLToPath(import.meta.url));
  18. const APP = resolve(HERE, '..');
  19. const PORT = Number(process.env.TRACKER_GATE_PORT || 8700);
  20. const [CH_FROM, CH_TO] = (process.env.TRACKER_GATE_CHROME || '8702-8709').split('-').map(Number);
  21. const IDENT_PORT = Number(process.env.TRACKER_GATE_IDENT_PORT || 8701);
  22. const TMDB_PORT = Number(process.env.TRACKER_GATE_TMDB_PORT || 8710);
  23. const BASE = `http://127.0.0.1:${PORT}`;
  24. const STORE = join(APP, '.scratch', 'gate-store');
  25. const IDENT_DIR = process.env.TRACKER_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  26. const SCRATCH = join(APP, '.scratch');
  27. const SESSIONS = join(SCRATCH, 'gate-sessions');
  28. rmSync(SESSIONS, { recursive: true, force: true });
  29. rmSync(STORE, { recursive: true, force: true });
  30. mkdirSync(SESSIONS, { recursive: true });
  31. let failures = 0, passes = 0;
  32. function check(label, ok, detail = '') {
  33. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  34. if (ok) passes++; else failures++;
  35. }
  36. let ident = null, server = null, browser = null, log = '', tmdb = null;
  37. async function stopServer() {
  38. if (server) {
  39. const s = server;
  40. try { s.kill('SIGTERM'); } catch {}
  41. await new Promise(r => { if (s.exitCode !== null || s.signalCode !== null) return r(); s.once('exit', r); setTimeout(r, 3000); });
  42. server = null;
  43. }
  44. }
  45. async function stop() {
  46. if (ident) { try { await ident.stop(); } catch {} ident = null; }
  47. if (browser) { try { await browser.close(); } catch {} browser = null; }
  48. await stopServer();
  49. if (tmdb) { try { await tmdb.stop(); } catch {} tmdb = null; }
  50. }
  51. // tracker.worldapi.org#9: what the fake TMDB (tests/faketmdb.mjs) knows about the two fixture shows (tmdbId 1001,
  52. // 1002, tests/seed-show.hl). Show 1: season 0 (must NOT be synced — the show has no season 0), S1 with the two
  53. // fixture episodes (no tmdbId locally → matched by number; E2 renamed "Second Episode") + a new E3 (released),
  54. // S2 unchanged, a NEW S3 (E1 released, E2 upcoming 2098-06-01). Show 2 (no seasons yet): a NEW S1 E1 (upcoming
  55. // 2097-01-01). Both have a poster.
  56. const gateTmdbShows = () => ({
  57. 1001: { id: 1001, name: 'Gate Test Show', overview: 'TMDB overview', status: 'Returning Series', poster_path: '/gate1.png', seasons: [
  58. { id: 90, season_number: 0, name: 'Specials', air_date: '2019-01-01', episodes: [{ id: 5000, episode_number: 1, name: 'A Special', air_date: '2019-01-01' }] },
  59. { id: 91, season_number: 1, name: 'Season 1', air_date: '2020-01-01', episodes: [
  60. { id: 5001, episode_number: 1, name: 'Pilot', air_date: '2020-01-01' },
  61. { id: 5002, episode_number: 2, name: 'Second Episode', air_date: '2020-06-15' },
  62. { id: 5003, episode_number: 3, name: 'Third', air_date: '2020-09-01' }] },
  63. { id: 92, season_number: 2, name: 'Season 2', air_date: '2099-01-01', episodes: [{ id: 5004, episode_number: 1, name: 'Season Two Opener', air_date: '2099-01-01' }] },
  64. { id: 93, season_number: 3, name: 'Season 3', air_date: '2021-05-05', episodes: [
  65. { id: 5005, episode_number: 1, name: 'Third Season Start', air_date: '2021-05-05' },
  66. { id: 5006, episode_number: 2, name: 'Coming Soon', air_date: '2098-06-01' }] }] },
  67. 1002: { id: 1002, name: 'Unwatched Gate Show', overview: 'second', status: 'Returning Series', poster_path: '/gate2.png', seasons: [
  68. { id: 94, season_number: 1, name: 'Season 1', air_date: '2097-01-01', episodes: [{ id: 7001, episode_number: 1, name: 'Brand New', air_date: '2097-01-01' }] }] },
  69. });
  70. async function main() {
  71. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  72. const alice = await ident.signIn('[email protected]');
  73. const APPKEY = await ident.registerApp(alice, 'tracker (gate)', [BASE]);
  74. check('ident: our own ident runs (a copy without .env), tracker is registered', /^pk_[0-9a-f]{32}$/.test(APPKEY.key) && !existsSync(join(STORE, 'ident', 'ident-code', '.env')));
  75. // tracker.worldapi.org#5: learn alice's per-app identity (a throwaway code, consumed here) so the
  76. // fixture below can seed a follow for the SAME user the real login flow will later resolve to
  77. // (users.hl `ensureUser` matches an existing users.db row by `identity`, reusing its id) — this is
  78. // the only way to give /unwatched a known followed show before the browser ever signs in.
  79. const preCode = await ident.selectorCode(alice, APPKEY, BASE);
  80. const aliceIdentity = await ident.exchange(APPKEY, preCode);
  81. // tracker.worldapi.org#4/#5: a tiny fixture show (tests/seed-show.hl) — written BEFORE the server
  82. // starts, self-assigned ids only (never update(), see that file's header)
  83. const MPACKDB = join(STORE, 'mpackdb');
  84. mkdirSync(MPACKDB, { recursive: true });
  85. const seedOut = execFileSync(join(APP, 'bin/hybriel'), ['tests/seed-show.hl'], { cwd: APP, env: { ...process.env, TRACKER_STORAGE: MPACKDB, TRACKER_SEED_IDENTITY: aliceIdentity } }).toString();
  86. check('seed: the fixture show was written, alice follows it', seedOut.includes('gate-test-show') && seedOut.includes('follows it'), seedOut);
  87. // tracker.worldapi.org#8: the fixture show's poster FILE exists (a 1×1 png), the second show has none →
  88. // /my/shows must give the first its own /posters/sh1.png and the second the one placeholder URL /posters/none
  89. mkdirSync(join(MPACKDB, 'posters'), { recursive: true });
  90. writeFileSync(join(MPACKDB, 'posters', 'sh1.png'), Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64'));
  91. // tracker.worldapi.org#9: the fake TMDB. EVERY run of the app/tool in this gate points at it with the gate's own
  92. // token — the runtime loads the project's real .env (TMDB_READ_TOKEN) by itself, the environment given here wins
  93. tmdb = await startFakeTmdb({ port: TMDB_PORT, shows: gateTmdbShows() });
  94. const TMDB_ENV = { TMDB_READ_TOKEN: 'gate-token', TMDB_BASE_URL: tmdb.base + '/3', TMDB_IMAGE_URL: tmdb.base + '/t/p' };
  95. const startServer = async (extra = {}) => {
  96. log = '';
  97. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, env: { ...process.env, TRACKER_PORT: String(PORT), TRACKER_SESSIONS: SESSIONS + '/', TRACKER_STORAGE: MPACKDB, TRACKER_WATCH: '0',
  98. TRACKER_URL: BASE, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, TRACKER_KEY: APPKEY.key, TRACKER_SECRET: APPKEY.secret, ...TMDB_ENV, TRACKER_SYNC: '0', ...extra }, stdio: ['ignore', 'pipe', 'pipe'] });
  99. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  100. for (let i = 0; ; i++) {
  101. try { if ((await fetch(BASE + '/')).ok) break; } catch {}
  102. if (i > 80) throw new Error('tracker did not come up\n' + log);
  103. await new Promise(r => setTimeout(r, 250));
  104. }
  105. };
  106. await startServer();
  107. check('tracker is up', true);
  108. browser = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  109. const page = await browser.newPage();
  110. page.captureNetwork();
  111. const ev = (e) => page.evaluate(e);
  112. const hydrated = () => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 15000, label: 'hydrated' });
  113. const loginAs = async (who) => {
  114. const code = await ident.selectorCode(who, APPKEY, BASE);
  115. await page.goto(BASE + '/login/callback?ident_code=' + code);
  116. await page.waitForSelector('#logout');
  117. await hydrated();
  118. };
  119. // ---- signed out: header shows the selector + "Log in with ident", the page itself is empty ----
  120. await page.goto(BASE + '/');
  121. await hydrated();
  122. check('signed out: the identity selector is in the header', await ev(`!!document.querySelector('#selector')`));
  123. check('signed out: "Log in with ident" shows, no "Log out"', (await ev(`!!document.querySelector('#loginbutton')`)) && !(await ev(`!!document.querySelector('#logout')`)));
  124. check('the page itself stays empty (no centered sign-in)', (await ev(`document.querySelector('main').textContent.trim()`)) === '');
  125. // ---- tracker.worldapi.org#4: /shows/:slug signed OUT — the header/genres/cast show, no checks ----
  126. await page.goto(BASE + '/shows/gate-test-show');
  127. await hydrated();
  128. check('signed out: the show header renders (title, genre, cast)', (await ev(`document.querySelector('show-header h1').textContent`)) === 'Gate Test Show'
  129. && (await ev(`document.querySelector('.genre-pill').textContent`)) === 'Drama'
  130. && (await ev(`document.querySelector('.artist-link').textContent`)) === 'Test Actor');
  131. check('signed out: no check icons at all', (await ev(`document.querySelectorAll('button.checkicon').length`)) === 0);
  132. check('signed out: the latest season (2) is expanded, season 1 collapsed', (await ev(`document.querySelectorAll('episode-row').length`)) === 1);
  133. // ---- tracker.worldapi.org#5: /my/unwatched signed OUT — no rows, no checks ----
  134. await page.goto(BASE + '/my/unwatched');
  135. await hydrated();
  136. check('signed out: /my/unwatched shows no rows and asks to sign in', (await ev(`document.querySelectorAll('unwatched-row').length`)) === 0
  137. && (await ev(`document.querySelector('.muted').textContent`)) === 'Sign in to see the shows you follow.');
  138. // ---- tracker.worldapi.org#6: /my/schedule signed OUT — no rows, no checks ----
  139. await page.goto(BASE + '/my/schedule');
  140. await hydrated();
  141. check('signed out: /my/schedule shows no rows and asks to sign in', (await ev(`document.querySelectorAll('schedule-row').length`)) === 0
  142. && (await ev(`document.querySelector('.muted').textContent`)) === 'Sign in to see the shows you follow.');
  143. // ---- tracker.worldapi.org#7: /my/shows signed OUT — no rows, the same sign-in message ----
  144. await page.goto(BASE + '/my/shows');
  145. await hydrated();
  146. check('signed out: /my/shows shows no rows and asks to sign in', (await ev(`document.querySelectorAll('my-show-row').length`)) === 0
  147. && (await ev(`document.querySelector('.muted').textContent`)) === 'Sign in to see the shows you follow.');
  148. // ---- tracker.worldapi.org#3: no bottom border on the header, no border on filled buttons ----
  149. check('the header has no bottom border', (await ev(`getComputedStyle(document.querySelector('application-header')).borderBottomWidth`)) === '0px');
  150. check('"Log in with ident" has no border', (await ev(`getComputedStyle(document.querySelector('#loginbutton')).borderTopWidth`)) === '0px');
  151. check('the ident selector\'s "choose ident" button has no border', (await ev(`getComputedStyle(document.querySelector('#selector').shadowRoot.querySelector('[part~="button"]')).borderTopWidth`)) === '0px');
  152. // ---- tracker.worldapi.org#8: the old addresses answer a permanent redirect to the /my/ ones ----
  153. for (const [from, to] of [['/unwatched', '/my/unwatched'], ['/schedule', '/my/schedule']]) {
  154. const m = await fetch(BASE + from, { redirect: 'manual' });
  155. check(`${from} answers 301 → ${to}`, m.status === 301 && m.headers.get('location') === to, m.status + ' ' + m.headers.get('location'));
  156. }
  157. await page.goto(BASE + '/unwatched');
  158. await hydrated();
  159. check('the browser following /unwatched lands on /my/unwatched', (await ev(`location.pathname`)) === '/my/unwatched' && !!(await ev(`document.querySelector('unwatched-page')`)));
  160. // ---- tracker.worldapi.org#8: the show page says "1 episode" for one, "2 episodes" for two ----
  161. await page.goto(BASE + '/shows/gate-test-show');
  162. await hydrated();
  163. check('show page: season counts "1 episode" (singular) and "2 episodes"', JSON.stringify(await ev(`Array.from(document.querySelectorAll('season-count')).map(e => e.textContent)`)) === JSON.stringify(['1 episode', '2 episodes']),
  164. JSON.stringify(await ev(`Array.from(document.querySelectorAll('season-count')).map(e => e.textContent)`)));
  165. let r = await fetch(BASE + '/login/callback', { redirect: 'manual' });
  166. check('login: /login/callback without a code → /login/failed', r.status === 302 && r.headers.get('location') === '/login/failed');
  167. // ---- sign in: the header selector flips to signed in, "Log out" appears, page stays empty ----
  168. await loginAs(alice);
  169. check('signed in: the selector is still in the header, now signed in', (await ev(`!!document.querySelector('#selector')`)) && (await ev(`document.querySelector('#selector').classList.contains('in')`)));
  170. check('signed in: "Log out" shows, no "Log in with ident"', (await ev(`!!document.querySelector('#logout')`)) && !(await ev(`!!document.querySelector('#loginbutton')`)));
  171. check('the page itself stays empty while signed in too', (await ev(`document.querySelector('main').textContent.trim()`)) === '');
  172. check('"Log out" has no border (only inverted buttons have one)', (await ev(`getComputedStyle(document.querySelector('#logout')).borderTopWidth`)) === '0px');
  173. check('the ident selector\'s signed-in status has no border', (await ev(`(() => { const e = document.querySelector('#selector').shadowRoot.querySelector('[part~="status"]'); return e ? getComputedStyle(e).borderTopWidth : '0px' })()`)) === '0px');
  174. check('the header brand "tracker" has font weight 100', (await ev(`getComputedStyle(document.querySelector('application-header .brand')).fontWeight`)) === '100');
  175. // ---- tracker.worldapi.org#5: /unwatched signed IN — only already-released, unwatched episodes of
  176. // followed shows, newest release first; a click removes the row. Run BEFORE the show-page checks
  177. // below (which toggle these same fixture episodes watched) so all three still start unwatched here.
  178. await page.goto(BASE + '/my/unwatched');
  179. await hydrated();
  180. const unwatchedRowTexts = () => ev(`Array.from(document.querySelectorAll('.unwatched-show')).map(e => e.textContent)`);
  181. check('signed in: /my/unwatched lists only already-released episodes, newest release first (not the future one), titles with the year',
  182. JSON.stringify(await unwatchedRowTexts()) === JSON.stringify(['Gate Test Show (2024)', 'Gate Test Show (2024)'])
  183. && (await ev(`document.querySelectorAll('unwatched-row').length`)) === 2);
  184. check('signed in: /my/unwatched shows show title, the episode as S01E02 + title and release date, linking to the show',
  185. (await ev(`document.querySelector('unwatched-row unwatched-episode').textContent`)) === 'S01E02 · Second'
  186. && (await ev(`document.querySelector('unwatched-row unwatched-date').textContent`)) === '2020-06-15'
  187. && (await ev(`document.querySelector('unwatched-row .unwatched-show').getAttribute('href')`)) === '/shows/gate-test-show');
  188. check('signed in: /my/unwatched starts with regular (unwatched) check icons', (await ev(`document.querySelectorAll('unwatched-row button.checkicon.regular').length`)) === 2);
  189. await page.click('unwatched-row button.checkicon');
  190. await page.waitFor(`document.querySelectorAll('unwatched-row').length === 1`, { timeout: 10000, label: 'unwatched row removed' });
  191. check('click an unwatched episode\'s check: it disappears from the list', (await ev(`document.querySelectorAll('unwatched-row').length`)) === 1
  192. && (await ev(`document.querySelector('unwatched-episode').textContent`)) === 'S01E01 · Pilot');
  193. await page.goto(BASE + '/my/unwatched');
  194. await hydrated();
  195. check('reload: the watch from /my/unwatched is server-side, not just client state', (await ev(`document.querySelectorAll('unwatched-row').length`)) === 1
  196. && (await ev(`document.querySelector('unwatched-episode').textContent`)) === 'S01E01 · Pilot');
  197. // ---- tracker.worldapi.org#7: /my/shows signed IN — followed shows, newest follow first, small
  198. // poster, title linking to the show, the last watched episode (only ep 2 "Second" is watched so far)
  199. const myShows = () => ev(`Array.from(document.querySelectorAll('my-show-row')).map(r => ({
  200. title: r.querySelector('.myshow-title') && r.querySelector('.myshow-title').textContent,
  201. href: r.querySelector('.myshow-title') && r.querySelector('.myshow-title').getAttribute('href'),
  202. poster: r.querySelector('img.myshow-poster') && r.querySelector('img.myshow-poster').getAttribute('src'),
  203. posterLoaded: !!(r.querySelector('img.myshow-poster') && r.querySelector('img.myshow-poster').complete && r.querySelector('img.myshow-poster').naturalWidth > 0),
  204. episode: r.querySelector('my-show-episode') ? r.querySelector('my-show-episode').textContent : null }))`);
  205. const waitPostersLoaded = () => page.waitFor(`Array.from(document.querySelectorAll('img.myshow-poster')).every(i => i.complete && i.naturalWidth > 0)`, { timeout: 10000, label: 'posters loaded' });
  206. await page.goto(BASE + '/my/shows');
  207. await hydrated();
  208. await waitPostersLoaded();
  209. let ms = await myShows();
  210. check('signed in: /my/shows lists both followed shows, newest follow first, with the year (2025 from `release` — that show has no `year`)', JSON.stringify(ms.map(m => m.title)) === JSON.stringify(['Unwatched Gate Show (2025)', 'Gate Test Show (2024)']), JSON.stringify(ms));
  211. check('signed in: /my/shows titles link to the show pages', ms.length === 2 && ms[0].href === '/shows/unwatched-gate-show' && ms[1].href === '/shows/gate-test-show', JSON.stringify(ms));
  212. check('signed in: /my/shows shows a loaded poster per row (its own file, else the one placeholder URL /posters/none)', ms.length === 2 && ms.every(m => m.posterLoaded) && ms[1].poster === '/posters/sh1.png' && ms[0].poster === '/posters/none', JSON.stringify(ms));
  213. check('signed in: /my/shows shows the last watched episode as S01E02, none for the never-watched show', ms.length === 2 && ms[1].episode === 'S01E02' && ms[0].episode === null, JSON.stringify(ms));
  214. check('/my/shows: the poster is small (2.5rem wide)', (await ev(`getComputedStyle(document.querySelector('img.myshow-poster')).width`)) === '40px');
  215. // ---- tracker.worldapi.org#6: /schedule signed IN — only NOT-yet-released episodes of followed
  216. // shows, soonest first, no check icons at all (read-only page, unaffected by any watch toggle above)
  217. await page.goto(BASE + '/my/schedule');
  218. await hydrated();
  219. check('signed in: /my/schedule lists only the not-yet-released episode, title with the year', (await ev(`document.querySelectorAll('schedule-row').length`)) === 1
  220. && (await ev(`document.querySelector('.schedule-show').textContent`)) === 'Gate Test Show (2024)');
  221. check('signed in: /my/schedule shows show title, the episode as S02E01 + title, release date, linking to the show, no checks',
  222. (await ev(`document.querySelector('schedule-row schedule-episode').textContent`)) === 'S02E01 · Season Two Opener'
  223. && (await ev(`document.querySelector('schedule-row schedule-date').textContent`)) === '2099-01-01'
  224. && (await ev(`document.querySelector('schedule-row .schedule-show').getAttribute('href')`)) === '/shows/gate-test-show'
  225. && (await ev(`document.querySelectorAll('schedule-row button.checkicon').length`)) === 0);
  226. // ---- tracker.worldapi.org#4: /shows/:slug signed IN — check icons, episode toggle, season toggle,
  227. // collapse/expand, and a reload proves the watch really is server-side ----
  228. const EP3 = 'ep0000000000ep0e3'; // season 2 (expanded by default), episode 1 "Season Two Opener"
  229. const EP1 = 'ep0000000000ep0e1'; // season 1 (collapsed by default), episode 1 "Pilot"
  230. const EP2 = 'ep0000000000ep0e2'; // season 1, episode 2 "Second"
  231. const SEASON1 = 'se000000000se0s1';
  232. const checkClass = (id) => ev(`document.querySelector('button.checkicon[value="${id}"]').getAttribute('class')`);
  233. const clickValue = (sel, id) => page.click(`${sel}[value="${id}"]`);
  234. await page.goto(BASE + '/shows/gate-test-show');
  235. await hydrated();
  236. check('signed in: episode check icons show, starting "regular" (not watched)', (await checkClass(EP3)) === 'checkicon regular');
  237. await clickValue('button.checkicon', EP3);
  238. await page.waitFor(`document.querySelector('button.checkicon[value="${EP3}"]').getAttribute('class') === 'checkicon solid'`, { timeout: 10000, label: 'ep3 solid' });
  239. check('click an episode check: it turns solid', (await checkClass(EP3)) === 'checkicon solid');
  240. check('season 1 starts collapsed (no episode rows of it yet)', (await ev(`document.querySelectorAll('episode-row').length`)) === 1);
  241. await clickValue('button.checkicon', SEASON1);
  242. await page.waitFor(`document.querySelector('button.checkicon[value="${SEASON1}"]').getAttribute('class') === 'checkicon solid'`, { timeout: 10000, label: 'season1 solid' });
  243. check('click a season check: the season itself turns solid', (await checkClass(SEASON1)) === 'checkicon solid');
  244. await clickValue('button.season-toggle', SEASON1);
  245. await page.waitForSelector(`button.checkicon[value="${EP1}"]`, { timeout: 10000 });
  246. check('expanding season 1 shows its episodes already solid (the season check watched them too)',
  247. (await checkClass(EP1)) === 'checkicon solid' && (await checkClass(EP2)) === 'checkicon solid');
  248. await page.goto(BASE + '/shows/gate-test-show');
  249. await hydrated();
  250. check('reload: episode 3\'s watch is server-side, not just client state', (await checkClass(EP3)) === 'checkicon solid');
  251. await clickValue('button.season-toggle', SEASON1);
  252. await page.waitForSelector(`button.checkicon[value="${EP1}"]`, { timeout: 10000 });
  253. check('reload: season 1\'s bulk watch is server-side too', (await checkClass(EP1)) === 'checkicon solid' && (await checkClass(EP2)) === 'checkicon solid' && (await checkClass(SEASON1)) === 'checkicon solid');
  254. // ---- tracker.worldapi.org#7: /my/shows again — S02E01 was watched BEFORE season 1's bulk watch, so
  255. // this proves "last" = the highest season/episode watched, not the most recently watched one
  256. await page.goto(BASE + '/my/shows');
  257. await hydrated();
  258. ms = await myShows();
  259. check('/my/shows: the last episode is the HIGHEST watched (S02E01), not the most recent watch; the other show still none',
  260. ms.length === 2 && ms[1].episode === 'S02E01' && ms[0].episode === null, JSON.stringify(ms));
  261. // ---- optional: screenshots of the signed-in pages (TRACKER_GATE_SHOTS=<dir>) so a human/architect can SEE them ----
  262. if (process.env.TRACKER_GATE_SHOTS) {
  263. mkdirSync(process.env.TRACKER_GATE_SHOTS, { recursive: true });
  264. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  265. for (const [name, path] of [['home', '/'], ['show', '/shows/gate-test-show'], ['my-shows', '/my/shows'], ['my-unwatched', '/my/unwatched'], ['my-schedule', '/my/schedule']]) {
  266. await page.goto(BASE + path);
  267. await hydrated();
  268. const shot = await page.send('Page.captureScreenshot', { format: 'png' });
  269. writeFileSync(join(process.env.TRACKER_GATE_SHOTS, name + '.png'), Buffer.from(shot.data, 'base64'));
  270. }
  271. await page.send('Emulation.clearDeviceMetricsOverride', {});
  272. }
  273. // ==== tracker.worldapi.org#9: THE TMDB SYNC, against the fake TMDB — first the tool (app stopped: hl:mpackdb is
  274. // one process per storage), twice (idempotent), then the pages; then the app's own daily run ====
  275. check('sync: the app ran with the daily sync switched off until now (TRACKER_SYNC=0), no TMDB request yet', log.includes('tmdb sync: off (TRACKER_SYNC=0)') && tmdb.requests.length === 0, log);
  276. await page.goto('about:blank'); // leave the app first: an open page would log websocket reconnect errors
  277. await stopServer();
  278. // spawned, not execFileSync: the fake TMDB lives in THIS node process and must keep answering meanwhile
  279. const runTool = () => new Promise((ok) => {
  280. const p = spawn(join(APP, 'bin/hybriel'), ['tools/sync-tmdb.hl', '--limit', '5'], { cwd: APP, env: { ...process.env, TRACKER_STORAGE: MPACKDB, ...TMDB_ENV }, stdio: ['ignore', 'pipe', 'pipe'] });
  281. let o = '';
  282. p.stdout.on('data', d => o += d); p.stderr.on('data', d => o += d);
  283. p.on('exit', () => ok(o));
  284. });
  285. let out = await runTool();
  286. let done = (out.match(/tmdb sync done: .*/) || [''])[0];
  287. check('sync tool: 2 followed shows → 2 new seasons (show 1 S3, show 2 S1), 4 new episodes, the 3 fixture episodes updated (tmdbId by S/E number, E2 renamed), 2 posters, 0 errors',
  288. done.includes('shows=2 newSeasons=2 newEpisodes=4 updatedEpisodes=3') && done.includes('posters=2') && done.includes('errors=0'), out);
  289. check('sync tool: every TMDB call carried the Bearer token, season 0 was never asked for, one request per show for details + one for its seasons',
  290. tmdb.requests.filter(q => q.path.startsWith('/3/')).every(q => q.authorization === 'Bearer gate-token') && !tmdb.requests.some(q => q.path.includes('season/0'))
  291. && JSON.stringify(tmdb.requests.map(q => q.path)) === JSON.stringify(['/3/tv/1001', '/3/tv/1001?append_to_response=season/1,season/2,season/3', '/t/p/w342/gate1.png', '/3/tv/1002', '/3/tv/1002?append_to_response=season/1', '/t/p/w342/gate2.png']),
  292. JSON.stringify(tmdb.requests));
  293. out = await runTool();
  294. done = (out.match(/tmdb sync done: .*/) || [''])[0];
  295. check('sync tool again: idempotent — nothing new, nothing updated, no poster downloaded again', done.includes('newSeasons=0 newEpisodes=0 updatedEpisodes=0 updatedSeasons=0 posters=0') && done.includes('errors=0'), out);
  296. await startServer();
  297. await page.goto(BASE + '/my/schedule');
  298. await hydrated();
  299. const scheduleRows = () => ev(`Array.from(document.querySelectorAll('schedule-row')).map(r => r.querySelector('.schedule-show').textContent + ' | ' + r.querySelector('schedule-episode').textContent + ' | ' + r.querySelector('schedule-date').textContent)`);
  300. let rows = await scheduleRows();
  301. check('after the sync: /my/schedule lists the new upcoming episodes of both shows, soonest first', JSON.stringify(rows) === JSON.stringify([
  302. 'Unwatched Gate Show (2025) | S01E01 · Brand New | 2097-01-01', 'Gate Test Show (2024) | S03E02 · Coming Soon | 2098-06-01', 'Gate Test Show (2024) | S02E01 · Season Two Opener | 2099-01-01']), JSON.stringify(rows));
  303. await page.goto(BASE + '/my/unwatched');
  304. await hydrated();
  305. rows = await ev(`Array.from(document.querySelectorAll('unwatched-row')).map(r => r.querySelector('unwatched-episode').textContent + ' | ' + r.querySelector('unwatched-date').textContent)`);
  306. check('after the sync: /my/unwatched lists the newly released episodes (S03E01, S01E03), newest first', JSON.stringify(rows) === JSON.stringify(['S03E01 · Third Season Start | 2021-05-05', 'S01E03 · Third | 2020-09-01']), JSON.stringify(rows));
  307. await page.goto(BASE + '/my/shows');
  308. await hydrated();
  309. await waitPostersLoaded();
  310. ms = await myShows();
  311. check('after the sync: /my/shows shows both real posters (/posters/sh2.png is new), loaded', ms.length === 2 && ms.every(m => m.posterLoaded) && ms[0].poster === '/posters/sh2.png' && ms[1].poster === '/posters/sh1.png', JSON.stringify(ms));
  312. r = await fetch(BASE + '/posters/sh2.png');
  313. const posterBytes = Buffer.from(await r.arrayBuffer());
  314. check('the downloaded poster is served by /posters/… byte for byte (image/png), stored in storage (mpackdb/posters/)', r.status === 200 && r.headers.get('content-type') === 'image/png' && posterBytes.equals(PNG) && existsSync(join(MPACKDB, 'posters', 'sh2.png')));
  315. await page.goto(BASE + '/shows/gate-test-show');
  316. await hydrated();
  317. const seasonCounts = await ev(`Array.from(document.querySelectorAll('season-row')).map(e => e.querySelector('season-label').textContent + ': ' + e.querySelector('season-count').textContent)`);
  318. check('after the sync: the show page has S3 (new) S2 S1, no season 0, no duplicated episode (S1 has 3)', JSON.stringify(seasonCounts) === JSON.stringify(['Season 3: 2 episodes', 'Season 2: 1 episode', 'Season 1: 3 episodes']), JSON.stringify(seasonCounts));
  319. check('after the sync: the latest season shows its new episodes, the poster is the downloaded one',
  320. JSON.stringify(await ev(`Array.from(document.querySelectorAll('episode-row episode-title')).map(e => e.textContent)`)) === JSON.stringify(['Third Season Start', 'Coming Soon'])
  321. && (await ev(`document.querySelector('show-poster img').getAttribute('src')`)) === '/posters/sh1.png' && (await ev(`document.querySelector('show-poster img').naturalWidth`)) > 0);
  322. await clickValue('button.season-toggle', SEASON1);
  323. await page.waitForSelector(`button.checkicon[value="${EP1}"]`, { timeout: 10000 });
  324. const s1 = await ev(`Array.from(document.querySelectorAll('episode-row')).map(e => e.querySelector('episode-number').textContent + ' ' + e.querySelector('episode-title').textContent + ' ' + e.querySelector('button.checkicon').getAttribute('class'))`);
  325. check('after the sync: S1 keeps its episodes (same ids, still watched), E2 renamed from TMDB, E3 new and unwatched',
  326. s1.includes('1 Pilot checkicon solid') && s1.includes('2 Second Episode checkicon solid') && s1.includes('3 Third checkicon regular') && s1.length === 5, JSON.stringify(s1));
  327. if (process.env.TRACKER_GATE_SHOTS) {
  328. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  329. for (const [name, path] of [['synced-show', '/shows/gate-test-show'], ['synced-my-shows', '/my/shows'], ['synced-my-unwatched', '/my/unwatched'], ['synced-my-schedule', '/my/schedule']]) {
  330. await page.goto(BASE + path);
  331. await hydrated();
  332. if (name === 'synced-my-shows') await waitPostersLoaded();
  333. const shot = await page.send('Page.captureScreenshot', { format: 'png' });
  334. writeFileSync(join(process.env.TRACKER_GATE_SHOTS, name + '.png'), Buffer.from(shot.data, 'base64'));
  335. }
  336. await page.send('Emulation.clearDeviceMetricsOverride', {});
  337. }
  338. // ---- THE DAILY RUN INSIDE THE APP: TRACKER_SYNC_HOUR = this very UTC hour, so the app's own clock starts the
  339. // run right after boot. TMDB now has one more episode and answers slowly (700 ms per request): the run takes
  340. // seconds, and pages asked for meanwhile must still be answered between two shows, never after the whole run.
  341. await page.goto('about:blank');
  342. await stopServer();
  343. tmdb.shows[1001].seasons[3].episodes.push({ id: 5007, episode_number: 3, name: 'Added Live', air_date: '2096-03-03' });
  344. tmdb.delayMs = 700;
  345. const before = tmdb.requests.length;
  346. await startServer({ TRACKER_SYNC: '1', TRACKER_SYNC_HOUR: String(new Date().getUTCHours()) });
  347. const lat = [];
  348. const t0 = Date.now();
  349. while (!log.includes('tmdb sync done') && Date.now() - t0 < 30000) {
  350. const a = Date.now();
  351. await fetch(BASE + '/');
  352. lat.push({ at: a - t0, ms: Date.now() - a, running: log.includes('tmdb sync: start') && !log.includes('tmdb sync done') });
  353. await new Promise(r => setTimeout(r, 150));
  354. }
  355. const runDone = (log.match(/tmdb sync done: .*/) || [''])[0];
  356. check('in-app daily run: started by the app\'s own clock at the configured hour, found the new episode, 0 errors',
  357. log.includes('tmdb sync: daily at ' + new Date().getUTCHours() + ':00 UTC') && log.includes('tmdb sync: start, 2 followed shows') && runDone.includes('newSeasons=0 newEpisodes=1 updatedEpisodes=0') && runDone.includes('errors=0'), log);
  358. const during = lat.filter(l => l.running);
  359. const runSecs = Number((runDone.match(/seconds=([0-9.]+)/) || [0, 0])[1]);
  360. console.log(` (in-app run ${runSecs} s; ${during.length} pages asked during it, slowest ${Math.max(0, ...during.map(l => l.ms))} ms)`);
  361. check('in-app daily run: the server kept answering DURING the run (between shows) — every page < 2.5 s though the run took ≥ 3 s',
  362. runSecs >= 3 && during.length >= 3 && during.every(l => l.ms < 2500), 'run ' + runSecs + ' s, during: ' + JSON.stringify(during));
  363. check('in-app daily run: the Bearer token on every call, 4 requests (no poster again: unchanged)', tmdb.requests.slice(before).filter(q => q.path.startsWith('/3/')).every(q => q.authorization === 'Bearer gate-token') && tmdb.requests.length - before === 4, JSON.stringify(tmdb.requests.slice(before)));
  364. await page.goto(BASE + '/my/schedule');
  365. await hydrated();
  366. rows = await scheduleRows();
  367. check('after the in-app run: /my/schedule has the episode TMDB added meanwhile (S03E03, 2096-03-03) on top', rows.length === 4 && rows[0] === 'Gate Test Show (2024) | S03E03 · Added Live | 2096-03-03', JSON.stringify(rows));
  368. // ==== tracker.worldapi.org#10: THE INSTALLABLE APP — hl:web's own manifest + service worker (project.hl appIcons /
  369. // offline = [ Home ]). The manifest and every icon over HTTP; Chrome's own verdict (installability, manifest parse);
  370. // the worker registered for the whole app; then OFFLINE: the tab loses the network (the note appears), the server
  371. // is stopped too (CDP's offline emulation does not reach the service worker's own fetches — measured — so only a
  372. // dead server proves the cache), and `/` still opens: header + the note. A data page gets hl:web's "Unavailable
  373. // offline" page. A separate tab, so its expected socket errors stay out of the main tab's console check.
  374. const html = await (await fetch(BASE + '/')).text();
  375. const mhref = (html.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  376. check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (the token `darker`)',
  377. mhref === '/__hl/manifest.webmanifest' && html.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')
  378. && html.includes('<link rel="icon" href="/icons/favicon.svg">') && html.includes('<meta name="theme-color" content="rgb(15, 20, 25)">'), html.slice(0, 900));
  379. const mres = await fetch(BASE + mhref);
  380. const man = await mres.json();
  381. check('pwa: the manifest is served as application/manifest+json: name "tracker", start_url /, scope /, display standalone, the token colours',
  382. /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'tracker' && man.short_name === 'tracker' && man.start_url === '/' && man.scope === '/'
  383. && man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', JSON.stringify(man));
  384. const iconOk = [];
  385. for (const ic of man.icons || []) {
  386. const ir = await fetch(BASE + ic.src);
  387. const b = Buffer.from(await ir.arrayBuffer());
  388. iconOk.push(ir.ok && ic.type === 'image/png' && b.readUInt32BE(16) === Number(ic.sizes.split('x')[0]) && b.readUInt32BE(20) === Number(ic.sizes.split('x')[1]));
  389. }
  390. check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',
  391. iconOk.length === 4 && iconOk.every(Boolean) && ['any', 'maskable'].every(pu => ['192x192', '512x512'].every(sz => man.icons.some(i => i.purpose === pu && i.sizes === sz))), JSON.stringify(man.icons) + ' ' + JSON.stringify(iconOk));
  392. const touch = await fetch(BASE + '/icons/apple-touch-icon.png');
  393. const touchBytes = Buffer.from(await touch.arrayBuffer());
  394. const fav = await fetch(BASE + '/icons/favicon.svg');
  395. const favText = await fav.text();
  396. const ico = await fetch(BASE + '/favicon.ico');
  397. const icoBytes = Buffer.from(await ico.arrayBuffer());
  398. check('pwa: apple-touch-icon is a 180×180 PNG, the favicon an SVG in tracker green, /favicon.ico a real icon file',
  399. touch.ok && touchBytes.readUInt32BE(16) === 180 && fav.ok && /image\/svg\+xml/.test(fav.headers.get('content-type') || '') && favText.includes('#4ec9b0')
  400. && ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);
  401. await page.goto('about:blank'); // the server goes down below: the main tab must not sit on a page meanwhile
  402. const app = await browser.newPage();
  403. const aev = (e) => app.evaluate(e);
  404. const appHydrated = () => app.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 15000, label: 'app tab hydrated' });
  405. await app.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  406. await app.goto(BASE + '/');
  407. await appHydrated();
  408. await app.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { timeout: 15000, label: 'service worker active' });
  409. await app.waitFor(`!!navigator.serviceWorker.controller`, { timeout: 10000, label: 'page controlled by the worker' });
  410. const inst = await app.send('Page.getInstallabilityErrors');
  411. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, JSON.stringify(inst));
  412. const am = await app.send('Page.getAppManifest');
  413. check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, JSON.stringify(am.errors));
  414. check('pwa: hl:web\'s service worker is registered for the whole app (scope /) and controls the page',
  415. (await aev(`navigator.serviceWorker.getRegistration().then(r => new URL(r.scope).pathname + ' ' + new URL(r.active.scriptURL).pathname)`)) === '/ /__hl/sw.js' && (await aev('!!navigator.serviceWorker.controller')));
  416. check('pwa: online, no offline note', !(await aev(`!!document.querySelector('#offline')`)));
  417. if (process.env.TRACKER_GATE_SHOTS) writeFileSync(join(process.env.TRACKER_GATE_SHOTS, 'pwa-phone-online.png'), Buffer.from((await app.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  418. await app.setOffline(true);
  419. await app.waitFor(`!!document.querySelector('#offline')`, { timeout: 5000, label: 'offline note (live)' }).catch(() => {});
  420. check('offline: the open page says so within seconds (the shell\'s tick)', (await aev(`document.querySelector('#offline') ? document.querySelector('#offline').textContent : ''`)) === 'You are offline. Your shows and lists need the network.');
  421. await stopServer();
  422. let down = false;
  423. try { await fetch(BASE + '/'); } catch { down = true; }
  424. await app.goto(BASE + '/');
  425. await app.waitFor(`!!document.querySelector('#offline')`, { timeout: 8000, label: 'offline note after reload' }).catch(() => {});
  426. check('offline: with the server gone too, a reload of / still opens the shell from the worker\'s cache — header, brand, the note, the empty home',
  427. down && (await aev(`document.querySelector('application-header .brand') ? document.querySelector('application-header .brand').textContent : ''`)) === 'tracker'
  428. && (await aev(`!!document.querySelector('#offline')`)) && (await aev(`document.querySelector('main').textContent.trim()`)) === ''
  429. && (await aev(`getComputedStyle(document.querySelector('application-header')).backgroundColor`)) === 'rgb(15, 20, 25)', 'server down: ' + down);
  430. if (process.env.TRACKER_GATE_SHOTS) writeFileSync(join(process.env.TRACKER_GATE_SHOTS, 'pwa-phone-offline.png'), Buffer.from((await app.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  431. await app.goto(BASE + '/my/shows');
  432. check('offline: a data page (/my/shows) is not kept — hl:web\'s "Unavailable offline" page', (await aev(`!!document.querySelector('main[data-hl-offline]') && document.querySelector('h1').textContent`)) === 'Unavailable offline');
  433. await app.setOffline(false);
  434. await startServer();
  435. await app.goto(BASE + '/');
  436. await appHydrated();
  437. await app.waitFor(`!document.querySelector('#offline')`, { timeout: 5000, label: 'note gone' }).catch(() => {});
  438. check('back online: / from the server again, no offline note', !(await aev(`!!document.querySelector('#offline')`)));
  439. await app.close();
  440. await page.goto(BASE + '/my/schedule');
  441. await hydrated();
  442. // ---- sign out: back to signed out, a reload confirms the app's own session (not just client state) ----
  443. await page.click('#logout');
  444. await page.waitForSelector('#loginbutton', { timeout: 15000 });
  445. check('sign out returns to the signed-out header', (await ev(`!!document.querySelector('#loginbutton')`)) && !(await ev(`!!document.querySelector('#logout')`)));
  446. await page.goto(BASE + '/');
  447. await hydrated();
  448. check('reload after sign-out stays signed out', (await ev(`!!document.querySelector('#loginbutton')`)) && !(await ev(`!!document.querySelector('#logout')`)));
  449. const problems = page.problems();
  450. check('no console errors/warnings', problems.length === 0, page.dumpConsole());
  451. }
  452. try {
  453. await main();
  454. } catch (e) {
  455. check('gate ran without throwing', false, e.stack || String(e));
  456. } finally {
  457. await stop();
  458. }
  459. console.log(`\n${passes} passed, ${failures} failed`);
  460. process.exit(failures === 0 ? 0 : 1);

Branches

Latest commits

  • 31b758aatracker#10: installable app (manifest, service worker, offline shell), own icon + faviconmre
  • 2fa9d997tracker#9: TMDB sync (followed shows: seasons, episodes, posters), tools/sync-tmdb.hl + daily run 04:00 UTC, fake TMDB in gatemre
  • 49e1f61edeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • 54070a4etracker#8: /my/unwatched + /my/schedule (301 from old), S01E01, title (year), 1 episode, watched-set lookup (unwatched 15s -> 1s)mre
  • 3251488atracker#7: /my/shows (followed shows, newest follow first, poster, title, last watched SxxEyy); gate can take screenshots (TRACKER_GATE_SHOTS)mre
  • 44b7d9f9tracker#6: /schedule — upcoming episodes of followed shows, soonest firstmre
  • 91c9fc8ctracker#5: /unwatched — unwatched released episodes of followed shows, newest firstmre
  • a97c0295tracker#4: show page /shows/:slug (header, seasons, episodes, watch checks) + tools/relink-episode-seasons.hlmre
  • 05f407c5tracker: no border on any button except inverted ones (Log out, ident status and identities too); header brand weight 100mre
  • 17375427tracker#2: tools/migrate.hl + tools/verify.hl — old MongoDB data into mpackdb with new idsmre
  • 31aac936tracker#3: no border on the header and on filled buttons; inverted buttons keep theirsmre
  • 2ad9d29ctracker#1: login exactly like calendar (identity selector in the header, empty homepage)mre
  • 3691e176tracker#1: empty tracker with the ident login (state of 2026-09-27)mre