gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf83571c3f83571c3tracker#18 (mission 067): daily sync by change lists — TMDB /tv|movie/changes (since the stored day, paged) + TVmaze /updates/shows → only our changed titles (followed: full step, unfollowed: light step — changed seasons, no TVmaze), full walk on first run / gap > 14 days / failed list; show record refreshed (title, tmdbSummary, tagline, status, genres …; renamed titles re-indexed); summary = the creator's own text (page: summary > tmdbSummary > tvmazeSummary), one-time clear of copied summaries (9,647 on the live copy); gate 261, tests/realdata-018*.mjs, README + STATUSmref83571c3/tests/browser.mjs

191.8 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, readdirSync, readFileSync, 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. // tracker.worldapi.org#12: TMDB's external_ids — show 1 a DIFFERENT imdb id than the stored tt0000001 (must not overwrite)
  57. // + a tvdb id (fills); show 2 an imdb id (fills) + a different tvdb id than the stored 4002 (must not overwrite). The movie
  58. // 1003 (only via /movie/): an imdb id. The fake TVmaze knows imdb tt0000001 → 501 and thetvdb 4002 → 502 (tt0000002 is unknown).
  59. // tracker.worldapi.org#28: the movie's credits — cast in TMDB's order (one without a character), crew: the director listed twice
  60. // (one entry), also a writer; 8 more writers (9 > 6 → the crew's "Show all"), screenplay, story, the composer; an assistant
  61. // director (not shown) and an adult crew member (left out)
  62. const gateMovieCredits = () => ({
  63. cast: [{ id: 3210, name: 'Movie Star', character: 'Hero', order: 0 }, { id: 3211, name: 'Movie Sidekick', character: 'Sidekick', order: 1 }, { id: 3212, name: 'Uncredited Extra', character: '', order: 2 }],
  64. crew: [{ id: 3201, name: 'Film Director', department: 'Directing', job: 'Director' }, { id: 3201, name: 'Film Director', department: 'Directing', job: 'Director' },
  65. { id: 3201, name: 'Film Director', department: 'Writing', job: 'Writer' }, ...Array.from({ length: 8 }, (_, k) => ({ id: 3221 + k, name: 'Writer Pool ' + (k + 1), department: 'Writing', job: 'Writer' })),
  66. { id: 3202, name: 'Screen Writer', department: 'Writing', job: 'Screenplay' }, { id: 3203, name: 'Story Author', department: 'Writing', job: 'Story' },
  67. { id: 3204, name: 'Film Composer', department: 'Sound', job: 'Original Music Composer' }, { id: 3205, name: 'Assistant Helper', department: 'Directing', job: 'Assistant Director' },
  68. { id: 3206, name: 'Adult Crew', department: 'Directing', job: 'Director', adult: true }] });
  69. const gateTmdbMovies = () => ({ 1003: { id: 1003, title: 'Gate Test Movie', poster_path: '/gate3.png', external_ids: { imdb_id: 'tt0000003', wikidata_id: 'Q1' }, credits: gateMovieCredits() },
  70. // tracker.worldapi.org#14: a movie only TMDB has — imported from the search
  71. 1005: { id: 1005, title: 'Gate Import Movie', poster_path: '/gate5.png', release_date: '2001-05-05', overview: 'an imported movie', genres: [{ id: 18, name: 'Drama' }], external_ids: { imdb_id: 'tt0000005' } },
  72. // mission 054 (tests/seed-adult.hl): what TMDB says about the titles whose adult flag we don't know yet; 1120 is unknown (404)
  73. 1011: { id: 1011, title: 'Adult Gate Movie', adult: true, poster_path: '/flag11.png' },
  74. 1012: { id: 1012, title: 'Flagless Gate Movie', adult: false, poster_path: '/flag12.png', external_ids: { imdb_id: 'tt0001012' } },
  75. 1013: { id: 1013, title: 'Flagless Adult Movie', adult: true, poster_path: '/flag13.png', external_ids: {} },
  76. // (#28: their credits come with the credits job)
  77. ...Object.fromEntries(Array.from({ length: 10 }, (_, k) => [1101 + k, { id: 1101 + k, title: 'Backfill Movie ' + String(k + 1).padStart(2, '0'), adult: false, poster_path: `/bf${k + 1}.png`, external_ids: {},
  78. credits: { cast: [{ id: 3170, name: 'Backfill Cast', character: 'Role ' + (k + 1) }], crew: [{ id: 3171, name: 'Backfill Director', job: 'Director' }] } }])),
  79. // tracker.worldapi.org#26: the full details of titles Test Actor's filmography adds as MINIMAL records (#16) — Person Film One
  80. // (opened in the gate: homepage, tagline, a 2nd genre, IMDb id, poster, cast = Test Actor (we have him), a NEW person and an
  81. // ADULT person (left out)); Directed Only, Announced Film and Bulk Film 01–78 for the repair job; Bulk Film 79/80 are
  82. // unknown to TMDB (404)
  83. 2001: { id: 2001, title: 'Person Film One', poster_path: '/pf1.png', release_date: '2010-05-05', overview: 'TMDB overview of the film', status: 'Released',
  84. homepage: 'https://example.org/pf1', tagline: 'One film.', genres: [{ id: 18, name: 'Drama' }, { id: 35, name: 'Comedy' }], external_ids: { imdb_id: 'tt0002001' },
  85. credits: { cast: [{ id: 3002, name: 'Test Actor', character: 'Hero', order: 0 }, { id: 3010, name: 'New Cast Member', character: 'Partner', order: 1, gender: 1 },
  86. { id: 3011, name: 'Adult Performer', character: 'Z', order: 2, adult: true }], crew: [{ id: 3002, name: 'Test Actor', job: 'Director' }] } },
  87. 2004: { id: 2004, title: 'Announced Film', poster_path: '/af4.png', external_ids: { imdb_id: 'tt0002004' }, credits: { cast: [{ id: 3002, name: 'Test Actor', character: 'Villain' }] } },
  88. 2005: { id: 2005, title: 'Directed Only', poster_path: '/do5.png', release_date: '2018-08-08', external_ids: {}, credits: { cast: [] } },
  89. ...Object.fromEntries(Array.from({ length: 78 }, (_, k) => [2101 + k, { id: 2101 + k, title: 'Bulk Film ' + String(k + 1).padStart(2, '0'), poster_path: `/bulk${k + 1}.png`,
  90. external_ids: { imdb_id: 'tt00' + (2101 + k) }, credits: { cast: [{ id: 3002, name: 'Test Actor', character: 'Extra' }] } }])) });
  91. // tracker.worldapi.org#15: TVmaze's episode lists — at first the SAME as TMDB's (same numbers, same days, + a special without
  92. // a number that must be ignored), so the first syncs take nothing from TVmaze; the "TVmaze merge" block below changes them.
  93. const gateTvmazeEpisodes = () => ({
  94. 501: [{ id: 8001, season: 1, number: 1, name: 'Pilot', airdate: '2020-01-01' }, { id: 8002, season: 1, number: 2, name: 'Second Episode', airdate: '2020-06-15' },
  95. { id: 8003, season: 1, number: 3, name: 'Third', airdate: '2020-09-01' }, { id: 8004, season: 2, number: 1, name: 'Season Two Opener', airdate: '2099-01-01' },
  96. { id: 8005, season: 3, number: 1, name: 'Third Season Start', airdate: '2021-05-05' }, { id: 8006, season: 3, number: 2, name: 'Coming Soon', airdate: '2098-06-01' },
  97. { id: 8099, season: 3, number: null, name: 'A TVmaze Special', airdate: '2021-06-01', type: 'significant_special' }],
  98. 502: [{ id: 8101, season: 1, number: 1, name: 'Brand New', airdate: '2097-01-01' }],
  99. });
  100. // tracker.worldapi.org#26: Person Series (tmdb 2002) is TVmaze 602 (by its imdb id), which has one episode more than TMDB
  101. // tracker.worldapi.org#18: TVmaze's show summaries (HTML, as TVmaze writes them) → tvmazeSummary, HTML stripped
  102. const gateTvmaze = () => ({ imdb: { tt0000001: 501, tt0002002: 602 }, thetvdb: { 4002: 502, 4004: 504 },
  103. summaries: { 501: '<p><b>Gate Test Show</b> on TVmaze &amp; more.</p>', 502: '<p>Unwatched <i>Gate</i> Show,\non TVmaze.</p><p>Second &quot;paragraph&quot;.</p>' }, episodes: { ...gateTvmazeEpisodes(),
  104. 602: [{ id: 60201, season: 1, number: 1, name: 'Series Pilot', airdate: '2015-03-03' }, { id: 60202, season: 1, number: 2, name: 'Series Second', airdate: '2015-03-10' },
  105. { id: 60203, season: 1, number: 3, name: 'Only On TVmaze', airdate: '2015-03-17' }] } });
  106. // tracker.worldapi.org#14: TMDB's search/multi for "gate": the two titles we HAVE (tv 1001, movie 1003 — left out of the web
  107. // list), a person (dropped), and three new ones: tv 1004 + movie 1005 (importable) and tv 1006 (in the search, but its details
  108. // answer 404 — the failed import)
  109. const gateSearch = () => ({ gate: [
  110. { media_type: 'tv', id: 1001, name: 'Gate Test Show', first_air_date: '2024-01-01', poster_path: '/gate1.png', overview: 'have it' },
  111. { media_type: 'tv', id: 1004, name: 'Gate Import Show', first_air_date: '2023-02-02', poster_path: '/gate4.png', overview: 'new series' },
  112. { media_type: 'person', id: 77, name: 'Gate Person' },
  113. { media_type: 'movie', id: 1003, title: 'Gate Test Movie', release_date: '1996-11-18', poster_path: '/gate3.png' },
  114. { media_type: 'movie', id: 1005, title: 'Gate Import Movie', release_date: '2001-05-05', poster_path: null, overview: 'new movie' },
  115. { media_type: 'tv', id: 1006, name: 'Gate Broken Show', first_air_date: '', poster_path: '/gate6.png' },
  116. // mission 054: an ADULT title in TMDB's answer (despite include_adult=false) — never in our web list
  117. { media_type: 'movie', id: 1030, title: 'Gate Adult Web', adult: true, release_date: '2002-02-02', poster_path: '/gate30.png' }] });
  118. // tracker.worldapi.org#16: TMDB's people. Test Actor (3002): facts + a photo; credits = two titles we HAVE (tv 1001, movie 1003),
  119. // new ones — a movie as cast AND crew ("Hero / Director"), a series, an ADULT movie (stored, never shown), an undated one (last),
  120. // a crew-only one, and 80 more movies (87 titles → 3 batches of 40 after the TMDB step). Second Actor (3003): two titles that
  121. // exist by then. Complete Person (3001) must never be asked.
  122. const gatePersons = () => {
  123. const bulk = [];
  124. for (let i = 1; i <= 80; i++) bulk.push({ media_type: 'movie', id: 2100 + i, title: 'Bulk Film ' + String(i).padStart(2, '0'), release_date: '2005-01-01', character: 'Extra', adult: false, poster_path: null, genre_ids: [] });
  125. return {
  126. 3002: { id: 3002, name: 'Test Actor', biography: 'Test Actor bio from TMDB.', birthday: '1970-05-06', deathday: null, place_of_birth: 'Fixture Town', profile_path: '/face2.png', imdb_id: 'nm0000002', adult: false,
  127. combined_credits: {
  128. cast: [
  129. { media_type: 'tv', id: 1001, name: 'Gate Test Show', first_air_date: '2024-01-01', character: 'Someone', poster_path: '/gate1.png' },
  130. { media_type: 'movie', id: 1003, title: 'Gate Test Movie', release_date: '1996-11-18', character: 'Cameo', poster_path: '/gate3.png' },
  131. { media_type: 'movie', id: 2001, title: 'Person Film One', release_date: '2010-05-05', character: 'Hero', adult: false, poster_path: '/pf1.png', genre_ids: [18], overview: 'a film of the person', original_language: 'en' },
  132. { media_type: 'tv', id: 2002, name: 'Person Series', first_air_date: '2015-03-03', character: 'Lead', adult: false, poster_path: null, genre_ids: [18, 10765] },
  133. { media_type: 'movie', id: 2003, title: 'Hidden Adult Film', release_date: '2012-01-01', character: 'X', adult: true, poster_path: null },
  134. { media_type: 'movie', id: 2004, title: 'Announced Film', release_date: '', character: 'Villain', adult: false, poster_path: null },
  135. ...bulk],
  136. crew: [
  137. { media_type: 'movie', id: 2001, title: 'Person Film One', release_date: '2010-05-05', job: 'Director', adult: false, poster_path: '/pf1.png' },
  138. { media_type: 'movie', id: 2005, title: 'Directed Only', release_date: '2018-08-08', job: 'Writer', adult: false, poster_path: null }] } },
  139. 3003: { id: 3003, name: 'Second Actor', biography: '', birthday: null, deathday: null, place_of_birth: null, profile_path: null,
  140. combined_credits: { cast: [{ media_type: 'movie', id: 2001, title: 'Person Film One', release_date: '2010-05-05', character: 'Sidekick', poster_path: '/pf1.png' },
  141. { media_type: 'tv', id: 1001, name: 'Gate Test Show', first_air_date: '2024-01-01', character: 'Guest', poster_path: '/gate1.png' },
  142. // TMDB's credit says not adult, but OUR record of it is (adult = true, stored by Test Actor's fill): still hidden
  143. { media_type: 'movie', id: 2003, title: 'Hidden Adult Film', release_date: '2012-01-01', character: 'Y', adult: false }], crew: [] } },
  144. 3001: { id: 3001, name: 'Complete Person', combined_credits: { cast: [{ media_type: 'movie', id: 2999, title: 'Must Not Appear', release_date: '2000-01-01' }], crew: [] } },
  145. // tracker.worldapi.org#26: a person who came with Person Film One's cast
  146. 3010: { id: 3010, name: 'New Cast Member', biography: '', profile_path: null,
  147. combined_credits: { cast: [{ media_type: 'movie', id: 2001, title: 'Person Film One', release_date: '2010-05-05', character: 'Partner', poster_path: '/pf1.png' }], crew: [] } },
  148. };
  149. };
  150. // tracker.worldapi.org#28: show 1001's cast of ALL seasons (aggregate_credits, by episode count): Lead Player (6), Test Actor (5, we
  151. // have him), Ensemble Player 01–18 (4 each), Late Season Star (3 — only in season 3), then the guests (the show has 6 episodes →
  152. // main cast ≥ 3): Guest Star Two (2), Guest Star One (1); an adult one left out = 23 names, 20 shown. Crew: Show Creator
  153. // (created_by AND writer of 5), two directors, a writer who also has a story credit, the composer; a script supervisor (not shown)
  154. const gateShowCredits = () => ({
  155. // (Lead Player's roles as TMDB writes them on real data: combined, repeated, "(uncredited)", more than 4 → "The Lead / Twin / Mirror / Ghost / …")
  156. cast: [{ id: 3101, name: 'Lead Player', roles: [{ character: 'The Lead / Twin', episode_count: 4 }, { character: 'The Lead (uncredited)', episode_count: 1 }, { character: 'Twin', episode_count: 1 },
  157. { character: 'Mirror', episode_count: 1 }, { character: 'Ghost / The Lead', episode_count: 1 }, { character: 'Narrator', episode_count: 1 }], total_episode_count: 6 },
  158. { id: 3002, name: 'Test Actor', roles: [{ character: 'Someone', episode_count: 5 }], total_episode_count: 5 },
  159. ...Array.from({ length: 18 }, (_, k) => ({ id: 3111 + k, name: 'Ensemble Player ' + String(k + 1).padStart(2, '0'), roles: [{ character: 'Crew Member ' + (k + 1), episode_count: 4 }], total_episode_count: 4 })),
  160. { id: 3140, name: 'Late Season Star', roles: [{ character: 'New Captain', episode_count: 2 }, { character: 'Captain', episode_count: 1 }], total_episode_count: 3 },
  161. { id: 3143, name: 'Adult Cast', adult: true, roles: [{ character: 'Q', episode_count: 3 }], total_episode_count: 3 },
  162. { id: 3141, name: 'Guest Star Two', roles: [{ character: 'Visitor', episode_count: 2 }], total_episode_count: 2 },
  163. { id: 3142, name: 'Guest Star One', roles: [{ character: 'Stranger', episode_count: 1 }], total_episode_count: 1 }],
  164. crew: [{ id: 3151, name: 'Episode Director', department: 'Directing', jobs: [{ job: 'Director', episode_count: 4 }], total_episode_count: 4 },
  165. { id: 3152, name: 'Staff Writer', department: 'Writing', jobs: [{ job: 'Writer', episode_count: 3 }, { job: 'Story', episode_count: 1 }], total_episode_count: 4 },
  166. { id: 3155, name: 'Second Director', department: 'Directing', jobs: [{ job: 'Director', episode_count: 2 }], total_episode_count: 2 },
  167. { id: 3150, name: 'Show Creator', department: 'Writing', jobs: [{ job: 'Writer', episode_count: 5 }], total_episode_count: 5 },
  168. { id: 3153, name: 'Theme Composer', department: 'Sound', jobs: [{ job: 'Original Music Composer', episode_count: 6 }], total_episode_count: 6 },
  169. { id: 3154, name: 'Script Keeper', department: 'Directing', jobs: [{ job: 'Script Supervisor', episode_count: 6 }], total_episode_count: 6 }] });
  170. const gateTmdbShows = () => ({
  171. 1001: { id: 1001, name: 'Gate Test Show', overview: 'TMDB overview', status: 'Returning Series', poster_path: '/gate1.png', external_ids: { imdb_id: 'tt9999999', tvdb_id: 4001, tvrage_id: null },
  172. created_by: [{ id: 3150, name: 'Show Creator' }], aggregate_credits: gateShowCredits(), seasons: [
  173. { 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' }] },
  174. { id: 91, season_number: 1, name: 'Season 1', air_date: '2020-01-01', episodes: [
  175. { id: 5001, episode_number: 1, name: 'Pilot', air_date: '2020-01-01' },
  176. { id: 5002, episode_number: 2, name: 'Second Episode', air_date: '2020-06-15' },
  177. { id: 5003, episode_number: 3, name: 'Third', air_date: '2020-09-01' }] },
  178. { 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' }] },
  179. { id: 93, season_number: 3, name: 'Season 3', air_date: '2021-05-05', episodes: [
  180. { id: 5005, episode_number: 1, name: 'Third Season Start', air_date: '2021-05-05' },
  181. { id: 5006, episode_number: 2, name: 'Coming Soon', air_date: '2098-06-01' }] }] },
  182. // tracker.worldapi.org#14: NOT in our database — imported from the search (no one follows it, the sync never asks for it)
  183. 1004: { id: 1004, name: 'Gate Import Show', overview: 'an imported series', status: 'Returning Series', poster_path: '/gate4.png', first_air_date: '2023-02-02',
  184. original_language: 'en', genres: [{ id: 18, name: 'Drama' }, { id: 10765, name: 'Sci-Fi & Fantasy' }], external_ids: { imdb_id: 'tt0000004', tvdb_id: 4004 },
  185. // tracker.worldapi.org#28: an imported title has its cast + crew at once
  186. created_by: [{ id: 3161, name: 'Import Creator' }], aggregate_credits: { cast: [{ id: 3160, name: 'Imported Lead', roles: [{ character: 'Captain', episode_count: 2 }], total_episode_count: 2 }], crew: [] }, seasons: [
  187. { id: 95, season_number: 1, name: 'Season 1', air_date: '2023-02-02', episodes: [
  188. { id: 8001, episode_number: 1, name: 'Imported One', air_date: '2023-02-02' }, { id: 8002, episode_number: 2, name: 'Imported Two', air_date: '2023-02-09' }] }] },
  189. // mission 054: a series whose adult flag we don't know yet (tests/seed-adult.hl) — TMDB says not adult
  190. 1014: { id: 1014, name: 'Flagless Gate Series', adult: false, overview: 'flagless', status: 'Ended', poster_path: '/flag14.png', external_ids: { imdb_id: 'tt0001014', tvdb_id: 4014 }, seasons: [
  191. { id: 96, season_number: 1, name: 'Season 1', air_date: '2001-03-03', episodes: [{ id: 9601, episode_number: 1, name: 'Flagless Pilot', air_date: '2001-03-03' }] }] },
  192. // tracker.worldapi.org#26: Test Actor's filmography adds it as a MINIMAL record; opened in the gate → its full details
  193. 2002: { id: 2002, name: 'Person Series', overview: 'TMDB overview of the series', status: 'Ended', poster_path: '/ps2.png', first_air_date: '2015-03-03', homepage: 'https://example.org/ps2',
  194. original_language: 'en', genres: [{ id: 18, name: 'Drama' }], external_ids: { imdb_id: 'tt0002002', tvdb_id: 4202 },
  195. aggregate_credits: { cast: [{ id: 3002, name: 'Test Actor', roles: [{ character: 'Lead', episode_count: 2 }, { character: 'Narrator', episode_count: 1 }] },
  196. { id: 3012, name: 'Series Newcomer', roles: [{ character: 'Friend', episode_count: 2 }] }] }, seasons: [
  197. { id: 97, season_number: 1, name: 'Season 1', air_date: '2015-03-03', episodes: [
  198. { id: 9701, episode_number: 1, name: 'Series Pilot', air_date: '2015-03-03' }, { id: 9702, episode_number: 2, name: 'Series Second', air_date: '2015-03-10' }] },
  199. { id: 98, season_number: 2, name: 'Season 2', air_date: '2016-04-04', episodes: [{ id: 9801, episode_number: 1, name: 'Second Season Start', air_date: '2016-04-04' }] }] },
  200. 1002: { id: 1002, name: 'Unwatched Gate Show', overview: 'second', status: 'Returning Series', poster_path: '/gate2.png', external_ids: { imdb_id: 'tt0000002', tvdb_id: 4999 }, seasons: [
  201. { 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' }] }] },
  202. });
  203. async function main() {
  204. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  205. const alice = await ident.signIn('[email protected]');
  206. const APPKEY = await ident.registerApp(alice, 'tracker (gate)', [BASE]);
  207. 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')));
  208. // tracker.worldapi.org#5: learn alice's per-app identity (a throwaway code, consumed here) so the
  209. // fixture below can seed a follow for the SAME user the real login flow will later resolve to
  210. // (users.hl `ensureUser` matches an existing users.db row by `identity`, reusing its id) — this is
  211. // the only way to give /unwatched a known followed show before the browser ever signs in.
  212. const preCode = await ident.selectorCode(alice, APPKEY, BASE);
  213. const aliceIdentity = await ident.exchange(APPKEY, preCode);
  214. // tracker.worldapi.org#4/#5: a tiny fixture show (tests/seed-show.hl) — written BEFORE the server
  215. // starts, self-assigned ids only (never update(), see that file's header)
  216. const MPACKDB = join(STORE, 'mpackdb');
  217. mkdirSync(MPACKDB, { recursive: true });
  218. const seedOut = execFileSync(join(APP, 'bin/hybriel'), ['tests/seed-show.hl'], { cwd: APP, env: { ...process.env, TRACKER_STORAGE: MPACKDB, TRACKER_SEED_IDENTITY: aliceIdentity } }).toString();
  219. check('seed: the fixture show was written, alice follows it', seedOut.includes('gate-test-show') && seedOut.includes('follows it'), seedOut);
  220. // tracker.worldapi.org#8: the fixture show's poster FILE exists (a 1×1 png), the second show has none →
  221. // /my/shows must give the first its own /posters/sh1.png and the second the one placeholder URL /posters/none
  222. mkdirSync(join(MPACKDB, 'posters'), { recursive: true });
  223. writeFileSync(join(MPACKDB, 'posters', 'sh1.png'), Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64'));
  224. // tracker.worldapi.org#9: the fake TMDB. EVERY run of the app/tool in this gate points at it with the gate's own
  225. // token — the runtime loads the project's real .env (TMDB_READ_TOKEN) by itself, the environment given here wins
  226. tmdb = await startFakeTmdb({ port: TMDB_PORT, shows: gateTmdbShows(), movies: gateTmdbMovies(), tvmaze: gateTvmaze(), search: gateSearch(), persons: gatePersons() });
  227. const TMDB_ENV = { TMDB_READ_TOKEN: 'gate-token', TMDB_BASE_URL: tmdb.base + '/3', TMDB_IMAGE_URL: tmdb.base + '/t/p', TVMAZE_BASE_URL: tmdb.base + '/tvmaze' };
  228. const startServer = async (extra = {}) => {
  229. log = '';
  230. 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',
  231. 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', TRACKER_BACKFILL: '0', TRACKER_REPAIR: '0', TRACKER_CREDITS: '0', TRACKER_DETAILS_PART_EPISODES: '1', ...extra }, stdio: ['ignore', 'pipe', 'pipe'] });
  232. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  233. for (let i = 0; ; i++) {
  234. try { if ((await fetch(BASE + '/')).ok) break; } catch {}
  235. if (i > 80) throw new Error('tracker did not come up\n' + log);
  236. await new Promise(r => setTimeout(r, 250));
  237. }
  238. };
  239. await startServer();
  240. check('tracker is up', true);
  241. // tracker.worldapi.org#18, ONCE at the first start: a `summary` that is a copy of tmdbSummary (Gate Test Movie, as the migration
  242. // copied them) is cleared; Gate Test Show's own text stays; the marker file keeps it from running again
  243. check('#18 summaries: the first start clears the 1 copied summary, keeps the 1 own text, writes the marker',
  244. log.includes('summaries: cleared 1 copies of tmdbSummary, kept 1 own texts, errors 0, ') && existsSync(join(MPACKDB, 'summaries-cleared.txt')), log);
  245. browser = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  246. const page = await browser.newPage();
  247. globalThis.__gatePage = page;
  248. page.captureNetwork();
  249. await page.captureWs(); // tracker#17: which faces a season click sends (wsSent)
  250. // tracker#17: a FAKE DELAY for one face — while `window.__delayFace = { name, ms }` is set, an outgoing websocket frame
  251. // naming that face is sent `ms` later (the real socket, only held back), so the gate sees the state BEFORE the answer
  252. await page.addInitScript(`(() => {
  253. const Native = window.WebSocket;
  254. if (!Native) return;
  255. window.WebSocket = class extends Native {
  256. send(d) {
  257. const f = window.__delayFace;
  258. if (f && String(d).includes(f.name)) { setTimeout(() => super.send(d), f.ms); return; }
  259. return super.send(d);
  260. }
  261. };
  262. })()`);
  263. const ev = (e) => page.evaluate(e);
  264. const hydrated = () => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 15000, label: 'hydrated' });
  265. // mission 047: every check icon AND season caret on the page is a real SVG element (not XHTML) and actually drawn
  266. const svgState = () => ev(`JSON.stringify((() => {
  267. const svgs = Array.from(document.querySelectorAll('button.checkicon svg, season-caret svg'));
  268. const shapes = Array.from(document.querySelectorAll('button.checkicon svg circle, button.checkicon svg path, season-caret svg path'));
  269. return { svgs: svgs.length, badNs: svgs.concat(shapes).filter(e => e.namespaceURI !== 'http://www.w3.org/2000/svg').length,
  270. undrawn: Array.from(document.querySelectorAll('button.checkicon svg circle')).filter(c => !(c.getBoundingClientRect().width > 0)).length };
  271. })())`);
  272. const svgOk = (st) => { const v = JSON.parse(st); return v.svgs > 0 && v.badNs === 0 && v.undrawn === 0; };
  273. // the caret's direction per season row, top to bottom (tracker#17): 'down' (closed, no transform) or 'up' (open,
  274. // rotate(180deg) = matrix(-1, 0, 0, -1, 0, 0)); waits out the caret's .15 s transition first
  275. const carets = async () => { await new Promise(r => setTimeout(r, 250)); return ev(`JSON.stringify(Array.from(document.querySelectorAll('season-row')).map(r => {
  276. const t = getComputedStyle(r.querySelector('season-caret')).transform;
  277. if (t === 'none') return 'down';
  278. const m = t.startsWith('matrix(') ? t.slice(7, -1).split(',').map(Number) : [];
  279. return m.length === 6 && Math.abs(m[0] + 1) < 1e-6 && Math.abs(m[3] + 1) < 1e-6 && Math.abs(m[1]) < 1e-6 ? 'up' : t;
  280. }))`); };
  281. // tracker.worldapi.org#12: the header's link icons as [label, href, target, rel], in order
  282. const extLinks = () => ev(`JSON.stringify(Array.from(document.querySelectorAll('show-links a.extlink')).map(a => [a.textContent, a.getAttribute('href'), a.getAttribute('target'), a.getAttribute('rel')]))`);
  283. const linksAre = (got, want) => JSON.stringify(JSON.parse(got)) === JSON.stringify(want.map(([l, h]) => [l, h, '_blank', 'noopener']));
  284. const TMDB_TV = 'https://www.themoviedb.org/tv/', TMDB_MOVIE = 'https://www.themoviedb.org/movie/', IMDB = 'https://www.imdb.com/title/', TVDB = 'https://thetvdb.com/dereferrer/series/', TVMAZE = 'https://www.tvmaze.com/shows/';
  285. // a click on a link icon: a NEW tab opens at that address (no access to this one: noopener), this tab stays where it is.
  286. // The new tab is closed again at once (it would load the real site).
  287. const clickOpensNewTab = async (sel) => {
  288. const seen = new Map();
  289. const off = browser.conn.onEvent((m) => {
  290. if ((m.method === 'Target.targetCreated' || m.method === 'Target.targetInfoChanged') && m.params.targetInfo.type === 'page') seen.set(m.params.targetInfo.targetId, m.params.targetInfo);
  291. });
  292. await browser.conn.send('Target.setDiscoverTargets', { discover: true });
  293. const known = new Set(seen.keys());
  294. const before = await ev('location.href');
  295. await page.click(sel);
  296. const fresh = () => [...seen.values()].find(i => !known.has(i.targetId) && i.url && i.url !== 'about:blank');
  297. for (let i = 0; i < 100 && !fresh(); i++) await new Promise(r => setTimeout(r, 50));
  298. const tab = fresh();
  299. off();
  300. await browser.conn.send('Target.setDiscoverTargets', { discover: false });
  301. if (tab) await browser.conn.send('Target.closeTarget', { targetId: tab.targetId }).catch(() => {});
  302. return { url: tab ? tab.url : null, canAccessOpener: tab ? tab.canAccessOpener : null, stayed: (await ev('location.href')) === before };
  303. };
  304. // tracker.worldapi.org#13: the poster tiles of a row/grid as "title|year|href|poster"
  305. const tilesOf = (sel) => ev(`JSON.stringify(Array.from(document.querySelectorAll(${JSON.stringify(sel)} + ' a.tile')).map(a => [a.querySelector('tile-title').textContent, a.querySelector('tile-year').textContent, a.getAttribute('href'), a.querySelector('img.tile-poster').getAttribute('src')].join('|')))`).then(JSON.parse);
  306. const titlesOf = async (sel) => (await tilesOf(sel)).map(t => t.split('|')[0]);
  307. // tracker.worldapi.org#28: the show page's cast + crew — every cast link [name, data-role, href]; what is VISIBLE, in order
  308. // (labels as "[Guest stars]"); the toggles' visible text; the ::after (character + comma) of a cast link by index
  309. const credits = () => ev(`JSON.stringify((() => {
  310. const vis = (e) => !!e && e.getClientRects().length > 0;
  311. const seq = (sel) => Array.from(document.querySelectorAll(sel)).filter(vis).map(e => /-LABEL$/.test(e.tagName) ? '[' + e.textContent + ']' : e.textContent);
  312. const cast = Array.from(document.querySelectorAll('show-cast a.artist-link'));
  313. const toggle = (id) => { const b = document.getElementById(id); return b && vis(b) ? Array.from(b.children).filter(vis).map(c => c.textContent).join('') : null; };
  314. return { cast: cast.map(a => [a.textContent, a.getAttribute('data-role'), a.getAttribute('href')]), castSeen: seq('show-cast a.artist-link, show-cast cast-label'),
  315. crew: Array.from(document.querySelectorAll('show-crew a.crew-link')).map(a => [a.textContent, a.getAttribute('href')]), crewSeen: seq('show-crew a.crew-link, show-crew crew-label'),
  316. castToggle: toggle('casttoggle'), crewToggle: toggle('crewtoggle'), after: cast.map(a => getComputedStyle(a, '::after').content), scrollW: document.documentElement.scrollWidth };
  317. })())`).then(JSON.parse);
  318. const movieRange = (from, to) => { const o = []; for (let i = from; i >= to; i--) o.push('Pager Movie ' + String(i).padStart(2, '0')); return o; };
  319. const pagerState = () => ev(`JSON.stringify({ items: Array.from(document.querySelectorAll('pagination li')).map(l => l.textContent.trim()), current: (document.querySelector('pagination li.current') || { textContent: '' }).textContent.trim() })`).then(JSON.parse);
  320. // hybriel 64527baa (in the vendored ff51cf46): a face taking `session` also answers with a sync of every member derived
  321. // from session — a handler that ALSO appended the returned row would show it twice. After every face-driven change:
  322. // each row (by its button value) once. Waits 400 ms first so a late sync has landed.
  323. const rowsOnce = async (sel) => { await new Promise(r => setTimeout(r, 400)); return JSON.parse(await ev(`JSON.stringify((() => { const v = Array.from(document.querySelectorAll(${JSON.stringify(sel)})).map(b => b.value); return { n: v.length, unique: new Set(v).size === v.length, values: v }; })())`)); };
  324. const modalOpen = () => ev(`!!(document.querySelector('dialog#signin') && document.querySelector('dialog#signin').open)`);
  325. const loginAs = async (who) => {
  326. const code = await ident.selectorCode(who, APPKEY, BASE);
  327. await page.goto(BASE + '/login/callback?ident_code=' + code);
  328. await page.waitForSelector('#logout');
  329. await hydrated();
  330. };
  331. // ---- signed out: header shows the selector + "Log in with ident", the page itself is empty ----
  332. await page.goto(BASE + '/');
  333. await hydrated();
  334. check('signed out: the identity selector is in the header', await ev(`!!document.querySelector('#selector')`));
  335. check('signed out: "Log in with ident" shows, no "Log out"', (await ev(`!!document.querySelector('#loginbutton')`)) && !(await ev(`!!document.querySelector('#logout')`)));
  336. // mission 056: signed out on a phone the header is ONE row ("choose ident" + "Log in" never wrap); " with ident" from 40rem on
  337. const headerRow = () => ev(`JSON.stringify((() => { const h = document.querySelector('application-header').getBoundingClientRect();
  338. const parts = [document.querySelector('application-header .brand'), document.querySelector('#searchlink'), document.querySelector('#selector'), document.querySelector('#loginbutton')].map(e => e.getBoundingClientRect());
  339. return { h: Math.round(h.height), oneRow: parts.every(r => r.top >= h.top && r.bottom <= h.bottom && r.top < parts[0].bottom && r.bottom > parts[0].top), right: Math.round(Math.max(...parts.map(r => r.right))),
  340. sw: document.documentElement.scrollWidth, text: document.querySelector('#loginbutton').innerText.trim(), choose: document.querySelector('#selector').shadowRoot.querySelector('[part~="button"]').getBoundingClientRect().height }; })())`).then(JSON.parse);
  341. const rows56 = {};
  342. for (const [w, mobile] of [[320, true], [390, true], [1280, false]]) {
  343. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: 800, deviceScaleFactor: mobile ? 2 : 1, mobile });
  344. await page.goto(BASE + '/');
  345. await hydrated();
  346. await page.waitFor(`!!document.querySelector('#selector').shadowRoot && !!document.querySelector('#selector').shadowRoot.querySelector('[part~="button"]')`, { timeout: 5000, label: 'selector drawn' });
  347. rows56[w] = await headerRow();
  348. if (process.env.TRACKER_GATE_SHOTS) writeFileSync(join(process.env.TRACKER_GATE_SHOTS, `header-signed-out-${w}.png`), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  349. }
  350. await page.send('Emulation.clearDeviceMetricsOverride', {});
  351. await page.goto(BASE + '/');
  352. await hydrated();
  353. check('signed out: the header is ONE row at 320/390/1280 px (≤ 56 px high, nothing below the brand, no sideways scroll); a phone says "Log in", a wide screen "Log in with ident"',
  354. [320, 390, 1280].every(w => rows56[w].oneRow && rows56[w].h <= 56 && rows56[w].sw <= w && rows56[w].right <= w && rows56[w].choose <= 40) && rows56[320].text === 'Log in' && rows56[390].text === 'Log in' && rows56[1280].text === 'Log in with ident', JSON.stringify(rows56));
  355. // ---- tracker.worldapi.org#13: the homepage signed OUT — no icon tiles, the text, "Movies" (→ /movies) with the 10
  356. // latest RELEASED movies (not the 2099 one), "Shows" (→ /shows) with the series by newest released episode ----
  357. check('home signed out: no icon tiles, no centered sign-in; the text about the site (with the sign-in hint)', (await ev(`document.querySelectorAll('a.hometile').length`)) === 0
  358. && /keeps track of the series and movies you follow/.test(await ev(`document.querySelector('home-intro').textContent`)) && /Log in with ident/.test(await ev(`document.querySelector('home-intro').textContent`)));
  359. check('home: the headings "Movies" and "Shows" link to /movies and /shows', (await ev(`[document.querySelector('#home-movies h2 a'), document.querySelector('#home-shows h2 a')].map(a => a.textContent + ' ' + a.getAttribute('href')).join(',')`)) === 'Movies /movies,Shows /shows');
  360. let tl = await tilesOf('#home-movies');
  361. check('home: the 10 latest RELEASED movies, newest first (Pager Movie 30…21; the 2099 one is not out yet), each poster + title + year → its page',
  362. JSON.stringify(tl.map(t => t.split('|')[0])) === JSON.stringify(movieRange(30, 21)) && tl[0] === 'Pager Movie 30|2001|/shows/pager-movie-30|/posters/none', JSON.stringify(tl));
  363. tl = await tilesOf('#home-shows');
  364. check('home: the series by newest RELEASED episode (Pager Older Series 2021-01-01, Gate Test Show 2020-06-15; one with no released episode is left out)',
  365. JSON.stringify(tl) === JSON.stringify(['Pager Older Series|2019|/shows/pager-older-series|/posters/none', 'Gate Test Show|2024|/shows/gate-test-show|/posters/sh1.png']), JSON.stringify(tl));
  366. check('home: every tile poster loaded (the placeholder or the real file)', await ev(`new Promise(r => setTimeout(r, 300)).then(() => Array.from(document.querySelectorAll('img.tile-poster')).filter(i => i.getBoundingClientRect().right <= innerWidth).every(i => i.complete && i.naturalWidth > 0))`));
  367. // ---- tracker.worldapi.org#4: /shows/:slug signed OUT — the header/genres/cast show, no checks ----
  368. await page.goto(BASE + '/shows/gate-test-show');
  369. await hydrated();
  370. check('signed out: the show header renders (title, genre, cast)', (await ev(`document.querySelector('show-header h1').textContent`)) === 'Gate Test Show'
  371. && (await ev(`document.querySelector('.genre-pill').textContent`)) === 'Drama'
  372. && (await ev(`document.querySelector('.artist-link').textContent`)) === 'Test Actor');
  373. // ---- tracker.worldapi.org#12: link icons only for the ids the show has (before any sync: show 1 has tmdb + imdb) ----
  374. let lk = await extLinks();
  375. check('link icons: show 1 (tmdbId + imdbId only) has exactly TMDB (tv/1001) and IMDb (tt0000001), each target=_blank rel=noopener',
  376. linksAre(lk, [['TMDB', TMDB_TV + '1001'], ['IMDb', IMDB + 'tt0000001/']]), lk);
  377. check('link icons: monochrome badges (one colour for all, no image), small (≤ 1.6rem high)',
  378. (await ev(`(() => { const a = Array.from(document.querySelectorAll('a.extlink')); const c = a.map(e => getComputedStyle(e)); return a.length > 0 && new Set(c.map(x => x.backgroundColor + x.color)).size === 1 && a.every(e => !e.querySelector('img') && e.getBoundingClientRect().height <= 25.6) })()`)));
  379. const nt = await clickOpensNewTab('a.extlink[data-site="imdb"]');
  380. check('link icons: a click opens the show on IMDb in a NEW tab without access to this one (noopener); this page stays', nt.url === IMDB + 'tt0000001/' && nt.canAccessOpener === false && nt.stayed, JSON.stringify(nt));
  381. await page.goto(BASE + '/shows/unwatched-gate-show');
  382. await hydrated();
  383. lk = await extLinks();
  384. check('link icons: show 2 (tmdbId + tvdbId only) has exactly TMDB and TheTVDB (dereferrer/series/4002)', linksAre(lk, [['TMDB', TMDB_TV + '1002'], ['TVDB', TVDB + '4002']]), lk);
  385. await page.goto(BASE + '/shows/gate-test-movie');
  386. await hydrated();
  387. lk = await extLinks();
  388. check('link icons: a movie (tmdbId only) has exactly TMDB as /movie/1003', linksAre(lk, [['TMDB', TMDB_MOVIE + '1003']]), lk);
  389. await page.goto(BASE + '/shows/gate-test-show');
  390. await hydrated();
  391. check('signed out: the latest season (2) is expanded, season 1 collapsed', (await ev(`document.querySelectorAll('episode-row').length`)) === 1);
  392. // mission 047: signed out the checks and "Follow" are VISIBLE; a click opens the sign-in modal and writes nothing
  393. check('signed out (mission 047): the season + episode checks are visible (drawn SVG) and so is "Follow"',
  394. (await ev(`document.querySelectorAll('button.checkicon').length`)) === 3 && svgOk(await svgState())
  395. && (await ev(`document.querySelector('#follow').textContent`)) === 'Follow' && (await ev(`document.querySelector('#follow').getBoundingClientRect().width > 0`)), await svgState());
  396. check('signed out: the sign-in modal is closed at first', !(await modalOpen()));
  397. await page.click('button.checkicon[value="ep0000000000ep0e3"]');
  398. await page.waitFor(`document.querySelector('dialog#signin').open`, { timeout: 5000, label: 'modal after a check click' }).catch(() => {});
  399. check('signed out: a check click opens the modal "You need to sign in to follow shows and mark episodes" with a sign-in link (ident login) and Close',
  400. (await modalOpen()) && (await ev(`document.querySelector('dialog#signin p').textContent`)) === 'You need to sign in to follow shows and mark episodes.'
  401. && (await ev(`document.querySelector('#signin-link').getAttribute('href')`)).startsWith(ident.base + '/login?key=')
  402. && (await ev(`document.querySelector('#signin-link').getBoundingClientRect().width > 0`))
  403. && (await ev(`Array.from(document.querySelectorAll('dialog#signin footer button')).map(b => b.textContent).join()`)) === 'Close',
  404. await ev(`document.querySelector('dialog#signin') ? document.querySelector('dialog#signin').outerHTML.slice(0, 600) : 'no dialog'`));
  405. if (process.env.TRACKER_GATE_SHOTS) { mkdirSync(process.env.TRACKER_GATE_SHOTS, { recursive: true }); writeFileSync(join(process.env.TRACKER_GATE_SHOTS, 'signed-out-modal-1280.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64')); }
  406. await page.click('dialog#signin footer button');
  407. await page.waitFor(`!document.querySelector('dialog#signin').open`, { timeout: 5000, label: 'modal closed' }).catch(() => {});
  408. check('signed out: Close closes the modal; the check stayed unwatched (nothing written)', !(await modalOpen())
  409. && (await ev(`document.querySelector('button.checkicon[value="ep0000000000ep0e3"]').getAttribute('class')`)) === 'checkicon regular');
  410. await page.click('#follow');
  411. await page.waitFor(`document.querySelector('dialog#signin').open`, { timeout: 5000, label: 'modal after Follow' }).catch(() => {});
  412. check('signed out: "Follow" opens the same modal and stays "Follow"', (await modalOpen()) && (await ev(`document.querySelector('#follow').textContent`)) === 'Follow');
  413. await page.click('dialog#signin footer button');
  414. await page.click('button.checkicon[value="se000000000se0s1"]');
  415. await page.waitFor(`document.querySelector('dialog#signin').open`, { timeout: 5000, label: 'modal after a season check' }).catch(() => {});
  416. check('signed out: a SEASON check opens the modal too', await modalOpen());
  417. await page.click('dialog#signin footer button');
  418. await page.goto(BASE + '/shows/gate-test-show');
  419. await hydrated();
  420. check('signed out: after a reload every check is still unwatched (the clicks wrote nothing)',
  421. (await ev(`Array.from(document.querySelectorAll('button.checkicon')).every(b => b.getAttribute('class') === 'checkicon regular')`)));
  422. // ---- tracker.worldapi.org#5: /my/unwatched signed OUT — no rows, no checks ----
  423. await page.goto(BASE + '/my/unwatched');
  424. await hydrated();
  425. check('signed out: /my/unwatched shows no rows and asks to sign in', (await ev(`document.querySelectorAll('unwatched-row').length`)) === 0
  426. && (await ev(`document.querySelector('.muted').textContent`)) === 'Sign in to see the shows you follow.');
  427. // ---- tracker.worldapi.org#6: /my/schedule signed OUT — no rows, no checks ----
  428. await page.goto(BASE + '/my/schedule');
  429. await hydrated();
  430. check('signed out: /my/schedule shows no rows and asks to sign in', (await ev(`document.querySelectorAll('schedule-row').length`)) === 0
  431. && (await ev(`document.querySelector('.muted').textContent`)) === 'Sign in to see the shows you follow.');
  432. // ---- tracker.worldapi.org#7: /my/shows signed OUT — no rows, the same sign-in message ----
  433. await page.goto(BASE + '/my/shows');
  434. await hydrated();
  435. check('signed out: /my/shows shows no rows and asks to sign in', (await ev(`document.querySelectorAll('my-show-row').length`)) === 0
  436. && (await ev(`document.querySelector('.muted').textContent`)) === 'Sign in to see the shows you follow.');
  437. // ==== tracker.worldapi.org#14: THE SEARCH, signed OUT — the header's magnifier, our database as you type, "Fetch from web"
  438. // (the fake TMDB's search/multi), "Add" → the sign-in modal ====
  439. const searchFor = () => ev(`document.querySelector('search-page') ? document.querySelector('search-page').getAttribute('data-for') : null`);
  440. const searchTitles = () => ev(`JSON.stringify(Array.from(document.querySelectorAll('#titles search-row')).map(r => [r.querySelector('.search-title').textContent, r.querySelector('.search-title').getAttribute('href'), r.querySelector('search-type').textContent]))`);
  441. const searchPeople = () => ev(`JSON.stringify(Array.from(document.querySelectorAll('#people .search-person')).map(a => [a.textContent, a.getAttribute('href')]))`);
  442. const webList = () => ev(`JSON.stringify(Array.from(document.querySelectorAll('web-row')).map(r => [r.querySelector('web-title').textContent, r.querySelector('button.add').value, r.querySelector('search-type').textContent]))`);
  443. const typeSearch = async (text) => {
  444. await page.type('#searchinput', text, { clear: true });
  445. await page.waitFor(`document.querySelector('search-page').getAttribute('data-for') === ${JSON.stringify(text)}`, { timeout: 10000, label: 'results for ' + text });
  446. };
  447. const GATE_TITLES = [['Gate Test Show (2024)', '/shows/gate-test-show', 'Series'], ['Gate Test Movie (1996)', '/shows/gate-test-movie', 'Movie'], ['Unwatched Gate Show (2025)', '/shows/unwatched-gate-show', 'Series']];
  448. check('search: the header has the magnifier (a drawn SVG) linking to /search',
  449. (await ev(`document.querySelector('#searchlink').getAttribute('href')`)) === '/search'
  450. && (await ev(`(() => { const s = document.querySelector('#searchlink svg'); return s.namespaceURI === 'http://www.w3.org/2000/svg' && s.querySelector('circle').getBoundingClientRect().width > 0 })()`)));
  451. await ev(`window.__w052 = 'same document'`);
  452. await page.click('#searchlink');
  453. await page.waitFor(`location.pathname === '/search' && !!document.querySelector('#searchinput')`, { timeout: 10000, label: 'search page' });
  454. check('search: the magnifier opens /search (client-side), an empty search field and "Search our shows, movies and people."',
  455. (await ev('window.__w052')) === 'same document' && (await ev(`document.querySelector('#searchinput').value`)) === ''
  456. && (await ev(`document.querySelector('#searchnote').textContent`)) === 'Search our shows, movies and people.' && !(await ev(`!!document.querySelector('#fetchweb')`)));
  457. await typeSearch('g');
  458. check('search: one letter → "Type at least 2 letters.", no "Fetch from web"', (await ev(`document.querySelector('#searchnote').textContent`)) === 'Type at least 2 letters.' && !(await ev(`!!document.querySelector('#fetchweb')`)));
  459. await page.type('#searchinput', 'ate');
  460. await page.waitFor(`document.querySelector('search-page').getAttribute('data-for') === 'gate'`, { timeout: 10000, label: 'results for gate' });
  461. let st14 = await searchTitles();
  462. check('search: typing "gate" lists our titles at once — name start first, the year, Series/Movie, linking to the show; the address follows (/search/gate)',
  463. st14 === JSON.stringify(GATE_TITLES) && (await ev('location.pathname')) === '/search/gate' && (await ev('window.__w052')) === 'same document', st14);
  464. await typeSearch('test act');
  465. check('search: people too — "test act" finds the person "Test Actor" (/person/Test-Actor) and no title', (await searchPeople()) === JSON.stringify([['Test Actor', '/person/Test-Actor']]) && (await searchTitles()) === '[]', await searchPeople());
  466. await typeSearch('GATE tést');
  467. check('search: case and accents do not matter ("GATE tést" = gate test); the address carries the text encoded',
  468. (await searchTitles()) === JSON.stringify(GATE_TITLES.slice(0, 2)) && (await ev('location.pathname')) === '/search/GATE%20t%C3%A9st', (await searchTitles()) + ' ' + (await ev('location.pathname')));
  469. await typeSearch('zzqq');
  470. check('search: nothing found → "Nothing in our database yet." and "Fetch from web"', (await ev(`document.querySelector('#searchnote').textContent`)) === 'Nothing in our database yet.' && (await ev(`!!document.querySelector('#fetchweb')`)));
  471. await page.goto(BASE + '/search/GATE%20t%C3%A9st');
  472. await hydrated();
  473. check('search: the address alone (reload / shared link) renders the same results on the server, the text in the field',
  474. (await ev(`document.querySelector('#searchinput').value`)) === 'GATE tést' && (await searchTitles()) === JSON.stringify(GATE_TITLES.slice(0, 2)) && (await searchFor()) === 'GATE tést');
  475. const bad14 = await fetch(BASE + '/search/x%zz');
  476. const bad14b = await fetch(BASE + '/search/%E0%80');
  477. check('search: a malformed address is no error — /search/x%zz 200 with the text taken literally, /search/%E0%80 (broken UTF-8) 200',
  478. bad14.status === 200 && (await bad14.text()).includes('value="x%zz"') && bad14b.status === 200 && (await bad14b.text()).includes('<search-page'), bad14.status + ' ' + bad14b.status);
  479. await typeSearch('gate/te');
  480. check('search: a "/" in the text goes into the address as a space (an encoded / would split the path) — and that address reloads to the same titles',
  481. (await ev('location.pathname')) === '/search/gate%20te' && (await searchTitles()) === JSON.stringify(GATE_TITLES.slice(0, 2)), await ev('location.pathname'));
  482. await page.goto(BASE + '/search/gate%20te');
  483. await hydrated();
  484. check('search: … reloaded', (await searchTitles()) === JSON.stringify(GATE_TITLES.slice(0, 2)) && (await ev(`document.querySelector('#searchinput').value`)) === 'gate te');
  485. await page.goto(BASE + '/search/gate');
  486. await hydrated();
  487. const searchesBefore = tmdb.searchRequests.length;
  488. await page.click('#fetchweb');
  489. await page.waitFor(`document.querySelectorAll('web-row').length > 0 || !!document.querySelector('#webnote')`, { timeout: 10000, label: 'web results' });
  490. let wl = await webList();
  491. const GATE_WEB = [['Gate Import Show (2023)', 'tv:1004', 'Series'], ['Gate Import Movie (2001)', 'movie:1005', 'Movie'], ['Gate Broken Show', 'tv:1006', 'Series']];
  492. check('search: "Fetch from web" (signed out too) lists TMDB\'s titles WE DON\'T HAVE — not tv 1001 / movie 1003 (ours), no person; one search/multi request with the token',
  493. wl === JSON.stringify(GATE_WEB) && tmdb.searchRequests.length === searchesBefore + 1 && tmdb.searchRequests[searchesBefore].path === '/3/search/multi?query=gate&include_adult=false&page=1'
  494. && tmdb.searchRequests[searchesBefore].authorization === 'Bearer gate-token', wl + ' ' + JSON.stringify(tmdb.searchRequests));
  495. check('search: the web rows\' small posters come from TMDB\'s image host (w92); one without a poster gets /posters/none',
  496. (await ev(`JSON.stringify(Array.from(document.querySelectorAll('web-row img')).map(i => i.getAttribute('src')))`)) === JSON.stringify([tmdb.base + '/t/p/w92/gate4.png', '/posters/none', tmdb.base + '/t/p/w92/gate6.png']));
  497. const requestsBefore = tmdb.requests.length;
  498. await page.click('web-row button.add[value="tv:1004"]');
  499. await page.waitFor(`document.querySelector('dialog#signin').open`, { timeout: 5000, label: 'modal after Add' }).catch(() => {});
  500. check('search: signed out, "Add" opens the sign-in modal ("You need to sign in to add titles.", sign-in link) and sends nothing',
  501. (await modalOpen()) && (await ev(`document.querySelector('dialog#signin p').textContent`)) === 'You need to sign in to add titles.'
  502. && (await ev(`document.querySelector('#signin-link').getAttribute('href')`)).startsWith(ident.base + '/login?key=') && tmdb.requests.length === requestsBefore);
  503. if (process.env.TRACKER_GATE_SHOTS) writeFileSync(join(process.env.TRACKER_GATE_SHOTS, 'search-signed-out-modal-1280.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  504. await page.click('dialog#signin footer button');
  505. await page.waitFor(`!document.querySelector('dialog#signin').open`, { timeout: 5000, label: 'modal closed' }).catch(() => {});
  506. check('search: Close closes it; the web list is still there', !(await modalOpen()) && (await webList()) === JSON.stringify(GATE_WEB));
  507. // ---- tracker.worldapi.org#3: no bottom border on the header, no border on filled buttons ----
  508. check('the header has no bottom border', (await ev(`getComputedStyle(document.querySelector('application-header')).borderBottomWidth`)) === '0px');
  509. check('"Log in with ident" has no border', (await ev(`getComputedStyle(document.querySelector('#loginbutton')).borderTopWidth`)) === '0px');
  510. check('the ident selector\'s "choose ident" button has no border', (await ev(`getComputedStyle(document.querySelector('#selector').shadowRoot.querySelector('[part~="button"]')).borderTopWidth`)) === '0px');
  511. // ---- tracker.worldapi.org#8: the old addresses answer a permanent redirect to the /my/ ones ----
  512. for (const [from, to] of [['/unwatched', '/my/unwatched'], ['/schedule', '/my/schedule']]) {
  513. const m = await fetch(BASE + from, { redirect: 'manual' });
  514. check(`${from} answers 301 → ${to}`, m.status === 301 && m.headers.get('location') === to, m.status + ' ' + m.headers.get('location'));
  515. }
  516. await page.goto(BASE + '/unwatched');
  517. await hydrated();
  518. check('the browser following /unwatched lands on /my/unwatched', (await ev(`location.pathname`)) === '/my/unwatched' && !!(await ev(`document.querySelector('unwatched-page')`)));
  519. // ---- tracker.worldapi.org#8: the show page says "1 episode" for one, "2 episodes" for two ----
  520. await page.goto(BASE + '/shows/gate-test-show');
  521. await hydrated();
  522. 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']),
  523. JSON.stringify(await ev(`Array.from(document.querySelectorAll('season-count')).map(e => e.textContent)`)));
  524. let r = await fetch(BASE + '/login/callback', { redirect: 'manual' });
  525. check('login: /login/callback without a code → /login/failed', r.status === 302 && r.headers.get('location') === '/login/failed');
  526. // ---- sign in: the header selector flips to signed in, "Log out" appears, page stays empty ----
  527. await loginAs(alice);
  528. 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')`)));
  529. check('signed in: "Log out" shows, no "Log in with ident"', (await ev(`!!document.querySelector('#logout')`)) && !(await ev(`!!document.querySelector('#loginbutton')`)));
  530. check('home signed in: four icon tiles → /my/unwatched, /my/schedule, /my/shows, /my/movies, each with a drawn svg icon; the text + both rows below them, no sign-in hint',
  531. (await ev(`Array.from(document.querySelectorAll('home-nav a.hometile')).map(a => a.textContent.trim() + ' ' + a.getAttribute('href') + ' ' + (a.querySelector('svg').namespaceURI === 'http://www.w3.org/2000/svg' && a.querySelector('svg').getBoundingClientRect().width > 30)).join(',')`))
  532. === 'Unwatched /my/unwatched true,Schedule /my/schedule true,Shows /my/shows true,Movies /my/movies true'
  533. && (await ev(`document.querySelector('home-nav').getBoundingClientRect().bottom <= document.querySelector('home-intro').getBoundingClientRect().top && document.querySelector('home-intro').getBoundingClientRect().bottom <= document.querySelector('#home-movies').getBoundingClientRect().top`))
  534. && !/Log in with ident/.test(await ev(`document.querySelector('home-intro').textContent`)) && (await ev(`document.querySelectorAll('#home-movies a.tile').length`)) === 10);
  535. await ev(`window.__w050 = 'same document'`);
  536. await page.click('a.hometile[href="/my/movies"]');
  537. await page.waitFor(`location.pathname === '/my/movies' && !!document.querySelector('my-movies-page')`, { timeout: 10000, label: 'icon → /my/movies' });
  538. check('home: the Movies icon leads to /my/movies (client-side, no reload); nothing followed yet → "You follow no movies yet."', (await ev('window.__w050')) === 'same document'
  539. && (await ev(`document.querySelector('my-movies-page p.muted').textContent`)) === 'You follow no movies yet.');
  540. check('"Log out" has no border (only inverted buttons have one)', (await ev(`getComputedStyle(document.querySelector('#logout')).borderTopWidth`)) === '0px');
  541. 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');
  542. check('the header brand "tracker" has font weight 100', (await ev(`getComputedStyle(document.querySelector('application-header .brand')).fontWeight`)) === '100');
  543. // ---- tracker.worldapi.org#5: /unwatched signed IN — only already-released, unwatched episodes of
  544. // followed shows, newest release first; a click removes the row. Run BEFORE the show-page checks
  545. // below (which toggle these same fixture episodes watched) so all three still start unwatched here.
  546. await page.goto(BASE + '/my/unwatched');
  547. await hydrated();
  548. const unwatchedRowTexts = () => ev(`Array.from(document.querySelectorAll('.unwatched-show')).map(e => e.textContent)`);
  549. check('signed in: /my/unwatched lists only already-released episodes, newest release first (not the future one), titles with the year',
  550. JSON.stringify(await unwatchedRowTexts()) === JSON.stringify(['Gate Test Show (2024)', 'Gate Test Show (2024)'])
  551. && (await ev(`document.querySelectorAll('unwatched-row').length`)) === 2);
  552. check('signed in: /my/unwatched shows show title, the episode as S01E02 + title and release date, linking to the show',
  553. (await ev(`document.querySelector('unwatched-row unwatched-episode').textContent`)) === 'S01E02 · Second'
  554. && (await ev(`document.querySelector('unwatched-row unwatched-date').textContent`)) === '2020-06-15'
  555. && (await ev(`document.querySelector('unwatched-row .unwatched-show').getAttribute('href')`)) === '/shows/gate-test-show');
  556. check('signed in: /my/unwatched starts with regular (unwatched) check icons', (await ev(`document.querySelectorAll('unwatched-row button.checkicon.regular').length`)) === 2);
  557. await page.click('unwatched-row button.checkicon');
  558. await page.waitFor(`document.querySelectorAll('unwatched-row').length === 1`, { timeout: 10000, label: 'unwatched row removed' });
  559. let once = await rowsOnce('unwatched-row button.checkicon');
  560. check('session-sync: after the /my/unwatched click (face unwatchedToggle) every row appears once', once.unique && once.n === 1, JSON.stringify(once));
  561. check('click an unwatched episode\'s check: it disappears from the list', (await ev(`document.querySelectorAll('unwatched-row').length`)) === 1
  562. && (await ev(`document.querySelector('unwatched-episode').textContent`)) === 'S01E01 · Pilot');
  563. await page.goto(BASE + '/my/unwatched');
  564. await hydrated();
  565. check('reload: the watch from /my/unwatched is server-side, not just client state', (await ev(`document.querySelectorAll('unwatched-row').length`)) === 1
  566. && (await ev(`document.querySelector('unwatched-episode').textContent`)) === 'S01E01 · Pilot');
  567. // ---- tracker.worldapi.org#7: /my/shows signed IN — followed shows, newest follow first, small
  568. // poster, title linking to the show, the last watched episode (only ep 2 "Second" is watched so far)
  569. const myShows = () => ev(`Array.from(document.querySelectorAll('my-show-row')).map(r => ({
  570. title: r.querySelector('.myshow-title') && r.querySelector('.myshow-title').textContent,
  571. href: r.querySelector('.myshow-title') && r.querySelector('.myshow-title').getAttribute('href'),
  572. poster: r.querySelector('img.myshow-poster') && r.querySelector('img.myshow-poster').getAttribute('src'),
  573. posterLoaded: !!(r.querySelector('img.myshow-poster') && r.querySelector('img.myshow-poster').complete && r.querySelector('img.myshow-poster').naturalWidth > 0),
  574. episode: r.querySelector('my-show-episode') ? r.querySelector('my-show-episode').textContent : null }))`);
  575. const waitPostersLoaded = () => page.waitFor(`Array.from(document.querySelectorAll('img.myshow-poster')).every(i => i.complete && i.naturalWidth > 0)`, { timeout: 10000, label: 'posters loaded' });
  576. await page.goto(BASE + '/my/shows');
  577. await hydrated();
  578. await waitPostersLoaded();
  579. let ms = await myShows();
  580. 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));
  581. 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));
  582. 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));
  583. 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));
  584. check('/my/shows: the poster is small (2.5rem wide)', (await ev(`getComputedStyle(document.querySelector('img.myshow-poster')).width`)) === '40px');
  585. // ---- tracker.worldapi.org#6: /schedule signed IN — only NOT-yet-released episodes of followed
  586. // shows, soonest first, no check icons at all (read-only page, unaffected by any watch toggle above)
  587. await page.goto(BASE + '/my/schedule');
  588. await hydrated();
  589. check('signed in: /my/schedule lists only the not-yet-released episode, title with the year', (await ev(`document.querySelectorAll('schedule-row').length`)) === 1
  590. && (await ev(`document.querySelector('.schedule-show').textContent`)) === 'Gate Test Show (2024)');
  591. check('signed in: /my/schedule shows show title, the episode as S02E01 + title, release date, linking to the show, no checks',
  592. (await ev(`document.querySelector('schedule-row schedule-episode').textContent`)) === 'S02E01 · Season Two Opener'
  593. && (await ev(`document.querySelector('schedule-row schedule-date').textContent`)) === '2099-01-01'
  594. && (await ev(`document.querySelector('schedule-row .schedule-show').getAttribute('href')`)) === '/shows/gate-test-show'
  595. && (await ev(`document.querySelectorAll('schedule-row button.checkicon').length`)) === 0);
  596. // ---- tracker.worldapi.org#4: /shows/:slug signed IN — check icons, episode toggle, season toggle,
  597. // collapse/expand, and a reload proves the watch really is server-side ----
  598. const EP3 = 'ep0000000000ep0e3'; // season 2 (expanded by default), episode 1 "Season Two Opener"
  599. const EP1 = 'ep0000000000ep0e1'; // season 1 (collapsed by default), episode 1 "Pilot"
  600. const EP2 = 'ep0000000000ep0e2'; // season 1, episode 2 "Second"
  601. const SEASON1 = 'se000000000se0s1';
  602. const checkClass = (id) => ev(`document.querySelector('button.checkicon[value="${id}"]').getAttribute('class')`);
  603. const clickValue = (sel, id) => page.click(`${sel}[value="${id}"]`);
  604. await page.goto(BASE + '/shows/gate-test-show');
  605. await hydrated();
  606. check('signed in: episode check icons show, starting "regular" (not watched)', (await checkClass(EP3)) === 'checkicon regular');
  607. await clickValue('button.checkicon', EP3);
  608. await page.waitFor(`document.querySelector('button.checkicon[value="${EP3}"]').getAttribute('class') === 'checkicon solid'`, { timeout: 10000, label: 'ep3 solid' });
  609. check('click an episode check: it turns solid', (await checkClass(EP3)) === 'checkicon solid');
  610. check('season 1 starts collapsed (no episode rows of it yet)', (await ev(`document.querySelectorAll('episode-row').length`)) === 1);
  611. await clickValue('button.checkicon', SEASON1);
  612. await page.waitFor(`document.querySelector('button.checkicon[value="${SEASON1}"]').getAttribute('class') === 'checkicon solid'`, { timeout: 10000, label: 'season1 solid' });
  613. check('click a season check: the season itself turns solid', (await checkClass(SEASON1)) === 'checkicon solid');
  614. await clickValue('button.season-toggle', SEASON1);
  615. await page.waitForSelector(`button.checkicon[value="${EP1}"]`, { timeout: 10000 });
  616. check('expanding season 1 shows its episodes already solid (the season check watched them too)',
  617. (await checkClass(EP1)) === 'checkicon solid' && (await checkClass(EP2)) === 'checkicon solid');
  618. await page.goto(BASE + '/shows/gate-test-show');
  619. await hydrated();
  620. check('reload: episode 3\'s watch is server-side, not just client state', (await checkClass(EP3)) === 'checkicon solid');
  621. await clickValue('button.season-toggle', SEASON1);
  622. await page.waitForSelector(`button.checkicon[value="${EP1}"]`, { timeout: 10000 });
  623. 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');
  624. // ---- mission 047, the creator's additions on the show page (signed in) ----
  625. check('episodes are not indented: an episode\'s check is exactly under its season\'s check (same left edge)',
  626. (await ev(`Math.abs(document.querySelector('episode-row button.checkicon').getBoundingClientRect().left - document.querySelector('season-row button.checkicon').getBoundingClientRect().left) < 0.5`)));
  627. check('artist links are orange #ce9178 (not red)', (await ev(`getComputedStyle(document.querySelector('.artist-link')).color`)) === 'rgb(206, 145, 120)');
  628. check('an unwatched check is the inverted solid icon: accent outline circle AND accent check mark; watched = filled accent disc, dark check',
  629. (await ev(`(() => { const b = document.querySelector('button.checkicon.regular'); const c = getComputedStyle(b.querySelector('circle')), p = getComputedStyle(b.querySelector('path'));
  630. return c.stroke === 'rgb(78, 201, 176)' && c.fill !== 'rgb(78, 201, 176)' && p.stroke === 'rgb(78, 201, 176)' })()`))
  631. && (await ev(`(() => { const b = document.querySelector('button.checkicon.solid'); const c = getComputedStyle(b.querySelector('circle')), p = getComputedStyle(b.querySelector('path'));
  632. return c.fill === 'rgb(78, 201, 176)' && p.stroke === 'rgb(15, 20, 25)' })()`)));
  633. // ---- tracker.worldapi.org#7: /my/shows again — S02E01 was watched BEFORE season 1's bulk watch, so
  634. // this proves "last" = the highest season/episode watched, not the most recently watched one
  635. await page.goto(BASE + '/my/shows');
  636. await hydrated();
  637. ms = await myShows();
  638. check('/my/shows: the last episode is the HIGHEST watched (S02E01), not the most recent watch; the other show still none',
  639. ms.length === 2 && ms[1].episode === 'S02E01' && ms[0].episode === null, JSON.stringify(ms));
  640. // ---- mission 047 (the creator: "i dont see the check marks"): a CLIENT-SIDE navigation /my/shows → click the show
  641. // title builds the show page in the browser; its check <svg> must be an SVG element (the old vendored build made it
  642. // in the XHTML namespace: nothing drawn, circle width 0). A window marker proves no full page load happened.
  643. await ev(`window.__w047 = 'same document'`);
  644. await page.click(`a.myshow-title[href="/shows/gate-test-show"]`);
  645. await page.waitFor(`location.pathname === '/shows/gate-test-show' && !!document.querySelector('button.checkicon svg circle')`, { timeout: 10000, label: 'show page after client-side navigation' });
  646. const svgNs = await ev(`JSON.stringify({ marker: window.__w047 || null, ns: document.querySelector('button.checkicon svg').namespaceURI,
  647. circleNs: document.querySelector('button.checkicon svg circle').namespaceURI,
  648. circleWidth: document.querySelector('button.checkicon svg circle').getBoundingClientRect().width })`);
  649. const sv = JSON.parse(svgNs);
  650. check('client-side navigation /my/shows → show page: the check svg is in the SVG namespace and its circle is drawn (width > 0)',
  651. sv.marker === 'same document' && sv.ns === 'http://www.w3.org/2000/svg' && sv.circleNs === 'http://www.w3.org/2000/svg' && sv.circleWidth > 0, svgNs);
  652. lk = await extLinks();
  653. check('client-side navigation: the link icons are there too (TMDB + IMDb)', linksAre(lk, [['TMDB', TMDB_TV + '1001'], ['IMDb', IMDB + 'tt0000001/']]), lk);
  654. // mission 047 #11: the checks also vanished after expanding/collapsing a season — same cause; and the caret flips
  655. let cs = await carets();
  656. check('season caret at the header\'s right edge (tracker#17): UP for the open season 2, DOWN for the closed season 1',
  657. cs === JSON.stringify(['up', 'down']) && (await ev(`(() => { const r = document.querySelector('season-row'); return Math.abs(r.getBoundingClientRect().right - r.querySelector('season-caret').getBoundingClientRect().right) < 2 })()`)), cs);
  658. await clickValue('button.season-toggle', SEASON1);
  659. await page.waitForSelector(`button.checkicon[value="${EP1}"]`, { timeout: 10000 });
  660. let st = await svgState();
  661. cs = await carets();
  662. check('after EXPANDING season 1 (client-side): every check + caret is a drawn SVG, season 1\'s caret now points UP', svgOk(st) && cs === JSON.stringify(['up', 'up']), st + ' ' + cs);
  663. once = await rowsOnce('show-seasons button.checkicon');
  664. check('after EXPANDING (face showSeasonEpisodes) every season/episode row appears once (2 seasons + 3 episodes), no skeleton left', once.unique && once.n === 5 && (await ev(`document.querySelectorAll('skeleton-row').length`)) === 0, JSON.stringify(once));
  665. await clickValue('button.checkicon', EP1);
  666. await page.waitFor(`document.querySelector('button.checkicon[value="${EP1}"]').getAttribute('class') === 'checkicon regular'`, { timeout: 10000, label: 'ep1 regular' });
  667. st = await svgState();
  668. check('after an EPISODE click: every check is still a drawn SVG', svgOk(st), st);
  669. once = await rowsOnce('show-seasons button.checkicon');
  670. check('session-sync: after an EPISODE click (face showToggleEpisode) every row appears once', once.unique && once.n === 5, JSON.stringify(once));
  671. await clickValue('button.checkicon', EP1);
  672. await page.waitFor(`document.querySelector('button.checkicon[value="${EP1}"]').getAttribute('class') === 'checkicon solid'`, { timeout: 10000, label: 'ep1 solid again' });
  673. await clickValue('button.season-toggle', SEASON1);
  674. await page.waitFor(`!document.querySelector('button.checkicon[value="${EP1}"]')`, { timeout: 10000, label: 'season 1 collapsed' });
  675. st = await svgState();
  676. cs = await carets();
  677. check('after COLLAPSING season 1 again: every check + caret is a drawn SVG, its caret points DOWN again', svgOk(st) && cs === JSON.stringify(['up', 'down']), st + ' ' + cs);
  678. // ---- tracker#17: SKELETON rows while a season's episodes load. The face's frame is held back 1.5 s (`__delayFace`), so
  679. // the state right after the click is the one BEFORE the answer. Season 1 has 2 episodes → 2 skeleton rows.
  680. const skeletonState = () => ev(`JSON.stringify((() => { const sk = Array.from(document.querySelectorAll('skeleton-row'));
  681. const ep = document.querySelector('episode-row'), t = sk[0] && sk[0].querySelector('skeleton-title');
  682. return { n: sk.length, ep1: !!document.querySelector('button.checkicon[value="${EP1}"]'), anim: t ? getComputedStyle(t).animationName : null,
  683. parts: sk.every(r => r.querySelector('skeleton-check') && r.querySelector('skeleton-number') && r.querySelector('skeleton-title')),
  684. h: sk[0] ? Math.round(sk[0].getBoundingClientRect().height) : 0, epH: ep ? Math.round(ep.getBoundingClientRect().height) : 0,
  685. checkW: sk[0] ? Math.round(sk[0].querySelector('skeleton-check').getBoundingClientRect().width) : 0,
  686. afterSeason1: sk[0] ? sk[0].previousElementSibling.querySelector('button.season-toggle').value === '${SEASON1}' : false }; })())`).then(JSON.parse);
  687. const delayFace = (ms) => ev(`window.__delayFace = ${ms ? `{ name: 'showSeasonEpisodes', ms: ${ms} }` : 'null'}`);
  688. for (const [w, h, mobile] of [[390, 844, true], [1280, 900, false]]) {
  689. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: mobile ? 2 : 1, mobile });
  690. await delayFace(1500);
  691. await clickValue('button.season-toggle', SEASON1);
  692. await page.waitFor(`document.querySelectorAll('skeleton-row').length > 0`, { timeout: 1000, label: 'skeleton' }).catch(() => {});
  693. await ev(`document.querySelector('skeleton-row') && document.querySelector('skeleton-row').scrollIntoView({ block: 'center' })`);
  694. let sk = await skeletonState();
  695. cs = await carets();
  696. check(`${w} px (tracker#17): right after the click, before the answer — 2 skeleton rows (season 1 has 2 episodes) under season 1, in the episode row's shape (check disc, number, title; same height), shimmering; no episode yet; caret already UP`,
  697. sk.n === 2 && !sk.ep1 && sk.anim === 'tracker-shimmer' && sk.parts && Math.abs(sk.h - sk.epH) <= 1 && sk.checkW === 32 && sk.afterSeason1 && cs === JSON.stringify(['up', 'up']), JSON.stringify(sk) + ' ' + cs);
  698. if (process.env.TRACKER_GATE_SHOTS) { mkdirSync(process.env.TRACKER_GATE_SHOTS, { recursive: true }); writeFileSync(join(process.env.TRACKER_GATE_SHOTS, `show-skeleton-${w}.png`), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64')); }
  699. await page.waitForSelector(`button.checkicon[value="${EP1}"]`, { timeout: 10000 });
  700. sk = await skeletonState();
  701. once = await rowsOnce('show-seasons button.checkicon');
  702. check(`${w} px (tracker#17): after the answer the skeleton is gone and the real rows are there once each (2 seasons + 3 episodes, hybriel#121), still solid`,
  703. sk.n === 0 && once.unique && once.n === 5 && (await checkClass(EP1)) === 'checkicon solid' && (await checkClass(EP2)) === 'checkicon solid', JSON.stringify(sk) + ' ' + JSON.stringify(once));
  704. if (process.env.TRACKER_GATE_SHOTS) writeFileSync(join(process.env.TRACKER_GATE_SHOTS, `show-open-${w}.png`), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  705. await clickValue('button.season-toggle', SEASON1);
  706. await page.waitFor(`!document.querySelector('button.checkicon[value="${EP1}"]')`, { timeout: 10000, label: 'season 1 closed' });
  707. if (process.env.TRACKER_GATE_SHOTS) writeFileSync(join(process.env.TRACKER_GATE_SHOTS, `show-closed-${w}.png`), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  708. }
  709. await page.send('Emulation.clearDeviceMetricsOverride', {});
  710. // closed again WHILE loading: the late answer must not bring the rows back
  711. const sent0 = (await page.wsSent()).length;
  712. await delayFace(1200);
  713. await clickValue('button.season-toggle', SEASON1);
  714. await page.waitFor(`document.querySelectorAll('skeleton-row').length === 2`, { timeout: 1000, label: 'skeleton 2' }).catch(() => {});
  715. await clickValue('button.season-toggle', SEASON1);
  716. await new Promise(r => setTimeout(r, 1800));
  717. once = await rowsOnce('show-seasons button.checkicon');
  718. cs = await carets();
  719. check('tracker#17: a season closed again while loading stays closed after the late answer (only season 2\'s episode, no skeleton, caret down)',
  720. once.n === 3 && !once.values.includes(EP1) && (await ev(`document.querySelectorAll('skeleton-row').length`)) === 0 && cs === JSON.stringify(['up', 'down']), JSON.stringify(once) + ' ' + cs);
  721. await delayFace(0);
  722. // closing asks the server nothing; opening sends exactly the one sessionless face (no showRows)
  723. const sentNow = (await page.wsSent()).slice(sent0);
  724. check('tracker#17: opening sends only showSeasonEpisodes (never the session face showRows), closing sends nothing',
  725. sentNow.filter(f => f.includes('showSeasonEpisodes')).length === 1 && !sentNow.some(f => f.includes('showRows')), JSON.stringify(sentNow));
  726. // ---- mission 047 #12: FOLLOW on the show page — "Following" filled; a click unfollows ("Follow", outlined in the
  727. // accent), the show leaves /my/shows; a click follows again (follow date = now) → the top of /my/shows; reloads keep it
  728. const followState = () => ev(`JSON.stringify((() => { const b = document.querySelector('#follow'); const c = getComputedStyle(b);
  729. return { text: b.textContent, cls: b.getAttribute('class'), bg: c.backgroundColor, border: c.borderTopWidth + ' ' + c.borderTopColor }; })())`);
  730. let fs = JSON.parse(await followState());
  731. check('follow: alice follows the show → "Following", the filled accent button (no border)', fs.text === 'Following' && fs.cls === 'follow' && fs.bg === 'rgb(78, 201, 176)' && fs.border.startsWith('0px'), JSON.stringify(fs));
  732. await page.click('#follow');
  733. await page.waitFor(`document.querySelector('#follow').textContent === 'Follow'`, { timeout: 10000, label: 'unfollowed' }).catch(() => {});
  734. fs = JSON.parse(await followState());
  735. check('follow: a click unfollows → "Follow", outlined (1px accent border, transparent)', fs.text === 'Follow' && fs.cls === 'follow inverted' && fs.border === '1px rgb(78, 201, 176)' && fs.bg === 'rgba(0, 0, 0, 0)', JSON.stringify(fs));
  736. await page.goto(BASE + '/shows/gate-test-show');
  737. await hydrated();
  738. check('follow: the unfollow survives a reload', (await ev(`document.querySelector('#follow').textContent`)) === 'Follow');
  739. await page.goto(BASE + '/my/shows');
  740. await hydrated();
  741. ms = await myShows();
  742. check('follow: the unfollowed show is gone from /my/shows', ms.length === 1 && ms[0].href === '/shows/unwatched-gate-show', JSON.stringify(ms));
  743. await page.goto(BASE + '/shows/gate-test-show');
  744. await hydrated();
  745. await page.click('#follow');
  746. await page.waitFor(`document.querySelector('#follow').textContent === 'Following'`, { timeout: 10000, label: 'followed' }).catch(() => {});
  747. check('follow: a click follows again → "Following"', (await ev(`document.querySelector('#follow').textContent`)) === 'Following');
  748. await new Promise(r => setTimeout(r, 400));
  749. check('session-sync: after the Follow toggles (face showToggleFollow) ONE Follow button, one show header, every season row once',
  750. (await ev(`document.querySelectorAll('#follow').length === 1 && document.querySelectorAll('show-header').length === 1`)) && (await rowsOnce('season-row button.checkicon')).unique);
  751. await page.goto(BASE + '/my/shows');
  752. await hydrated();
  753. ms = await myShows();
  754. check('follow: followed just now → the TOP of /my/shows (newest follow first), after a reload', ms.length === 2 && ms[0].href === '/shows/gate-test-show' && ms[1].href === '/shows/unwatched-gate-show', JSON.stringify(ms));
  755. await page.goto(BASE + '/shows/gate-test-show');
  756. await hydrated();
  757. check('follow: "Following" survives a reload', (await ev(`document.querySelector('#follow').textContent`)) === 'Following');
  758. // ==== tracker.worldapi.org#13: /movies, /shows (24 per page, the copied pagination, the page in the PATH) and
  759. // /my/movies (the Follow button on a movie's page) ====
  760. await page.goto(BASE + '/');
  761. await hydrated();
  762. await ev(`window.__w050 = 'same document'`);
  763. await page.click('#home-movies h2 a');
  764. await page.waitFor(`location.pathname === '/movies' && document.querySelectorAll('a.tile').length === 24`, { timeout: 10000, label: 'heading → /movies' });
  765. let titles = await titlesOf('tile-grid');
  766. check('/movies (the homepage heading, client-side): page 1 = 24 movies, release date desc — the 2099 one first, then Pager Movie 30…08',
  767. (await ev('window.__w050')) === 'same document' && JSON.stringify(titles) === JSON.stringify(['Pager Future Movie', ...movieRange(30, 8)]), JSON.stringify(titles));
  768. let pg = await pagerState();
  769. check('/movies: the pagination says "1 2 Next", 1 current (no Previous on the first page); "33 movies … page 1 of 2"',
  770. JSON.stringify(pg) === JSON.stringify({ items: ['1', '2', 'Next'], current: '1' }) && /^33 movies, newest first · page 1 of 2$/.test(await ev(`document.querySelector('.list-count').textContent`)), JSON.stringify(pg));
  771. await ev(`Array.from(document.querySelectorAll('pagination button')).find(b => b.textContent.trim() === 'Next').click()`);
  772. await page.waitFor(`location.pathname === '/movies/page/2' && document.querySelectorAll('a.tile').length === 9`, { timeout: 10000, label: 'Next → page 2' });
  773. titles = await titlesOf('tile-grid');
  774. pg = await pagerState();
  775. check('/movies "Next": the address is /movies/page/2 (client-side), the last 9: Pager Movie 07…01, the 1996 fixture movie, the undated one last; "Previous 1 2", 2 current; title says page 2',
  776. (await ev('window.__w050')) === 'same document' && JSON.stringify(titles) === JSON.stringify([...movieRange(7, 1), 'Gate Test Movie', 'Pager Undated Movie'])
  777. && JSON.stringify(pg) === JSON.stringify({ items: ['Previous', '1', '2'], current: '2' }) && (await ev('document.title')) === 'Movies, page 2 — tracker', JSON.stringify({ titles, pg }));
  778. await ev(`Array.from(document.querySelectorAll('pagination button')).find(b => b.textContent.trim() === '1').click()`);
  779. await page.waitFor(`location.pathname === '/movies' && document.querySelectorAll('a.tile').length === 24`, { timeout: 10000, label: '1 → /movies' });
  780. check('/movies: the page number "1" goes back to /movies (page 1)', (await pagerState()).current === '1' && (await titlesOf('tile-grid'))[0] === 'Pager Future Movie');
  781. await ev('history.back()');
  782. await page.waitFor(`location.pathname === '/movies/page/2' && document.querySelectorAll('a.tile').length === 9`, { timeout: 10000, label: 'Back → page 2' });
  783. check('/movies: the browser\'s Back returns to /movies/page/2 with page 2 shown', (await pagerState()).current === '2' && (await ev('window.__w050')) === 'same document');
  784. await page.goto(BASE + '/movies/page/2');
  785. await hydrated();
  786. check('/movies/page/2 loaded directly: the same 9 movies, 2 current', (await ev(`document.querySelectorAll('a.tile').length`)) === 9 && (await pagerState()).current === '2');
  787. await page.goto(BASE + '/movies/page/99');
  788. await hydrated();
  789. const p99 = await pagerState();
  790. await page.goto(BASE + '/movies/page/abc');
  791. await hydrated();
  792. check('/movies: a page past the end shows the last page, a page that is no number the first', p99.current === '2' && (await pagerState()).current === '1');
  793. await page.goto(BASE + '/');
  794. await hydrated();
  795. await ev(`window.__w050 = 'same document'`);
  796. await page.click('#home-shows h2 a');
  797. await page.waitFor(`location.pathname === '/shows' && !!document.querySelector('tile-grid a.tile')`, { timeout: 10000, label: 'heading → /shows' });
  798. tl = await tilesOf('tile-grid');
  799. check('/shows (the homepage heading): every series (no movies) by newest released episode, the one with none released last; one page → no pagination at all',
  800. (await ev('window.__w050')) === 'same document' && JSON.stringify(tl.map(t => t.split('|')[0])) === JSON.stringify(['Pager Older Series', 'Gate Test Show', 'Unwatched Gate Show'])
  801. && (await ev(`document.querySelectorAll('pagination').length`)) === 0, JSON.stringify(tl));
  802. // a movie's page has the Follow button (the show page) → /my/movies; /my/shows stays series only
  803. await page.click('a.tile[href="/shows/gate-test-show"]');
  804. await page.waitFor(`location.pathname === '/shows/gate-test-show' && !!document.querySelector('#follow')`, { timeout: 10000, label: 'tile → show page' });
  805. check('/shows: a tile opens the show page (client-side)', (await ev('window.__w050')) === 'same document');
  806. await page.goto(BASE + '/shows/gate-test-movie');
  807. await hydrated();
  808. check('a movie\'s page has the Follow button ("Follow": alice does not follow it yet)', (await ev(`document.querySelector('#follow').textContent`)) === 'Follow');
  809. await page.click('#follow');
  810. await page.waitFor(`document.querySelector('#follow').textContent === 'Following'`, { timeout: 10000, label: 'movie followed' }).catch(() => {});
  811. await page.goto(BASE + '/my/movies');
  812. await hydrated();
  813. const myMovies = await ev(`JSON.stringify(Array.from(document.querySelectorAll('my-show-row')).map(r => [r.querySelector('a.myshow-title').textContent, r.querySelector('a.myshow-title').getAttribute('href'), r.querySelector('img.myshow-poster').getAttribute('src')].join('|')))`);
  814. check('/my/movies: the movie alice just followed — title with year, its page, the poster (placeholder URL)', myMovies === JSON.stringify(['Gate Test Movie (1996)|/shows/gate-test-movie|/posters/none']), myMovies);
  815. await page.goto(BASE + '/my/shows');
  816. await hydrated();
  817. ms = await myShows();
  818. check('/my/shows stays SERIES only: the followed movie is not there', ms.length === 2 && ms.every(m => m.href !== '/shows/gate-test-movie'), JSON.stringify(ms));
  819. // ---- mission 047, MOBILE FIRST: at a phone's 390 px the header is ONE row (brand + ident selector + "Log out"), and
  820. // no page scrolls sideways; at 1280 px the same pages. Screenshots of both widths with TRACKER_GATE_SHOTS.
  821. const pages = [['home', '/'], ['show', '/shows/gate-test-show'], ['my-shows', '/my/shows'], ['my-unwatched', '/my/unwatched'], ['my-schedule', '/my/schedule'],
  822. ['movies', '/movies'], ['movies-page-2', '/movies/page/2'], ['shows-list', '/shows'], ['my-movies', '/my/movies'], ['search', '/search/gate']];
  823. if (process.env.TRACKER_GATE_SHOTS) mkdirSync(process.env.TRACKER_GATE_SHOTS, { recursive: true });
  824. for (const [w, h, mobile] of [[390, 844, true], [1280, 900, false]]) {
  825. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: mobile ? 2 : 1, mobile });
  826. const bad = [];
  827. for (const [name, path] of pages) {
  828. await page.goto(BASE + path);
  829. await hydrated();
  830. const m = JSON.parse(await ev(`JSON.stringify((() => {
  831. const hd = document.querySelector('application-header').getBoundingClientRect();
  832. const mid = (s) => { const r = document.querySelector(s).getBoundingClientRect(); return r.top + r.height / 2; };
  833. const mids = ['application-header .brand', '#selector', '#logout'].map(mid);
  834. const wd = (s) => Math.round(document.querySelector(s).getBoundingClientRect().width);
  835. return { headerH: hd.height, spread: Math.max(...mids) - Math.min(...mids), scrollW: document.documentElement.scrollWidth, widths: ['application-header .brand', '#userbox', '#selector', '#logout'].map(wd) };
  836. })())`));
  837. if (m.spread > 8 || m.headerH > 64 || m.scrollW > w) bad.push(name + ' ' + JSON.stringify(m));
  838. if (name === 'show') {
  839. // mission 047 #8: phone = title first, then the poster at the full content width, then genres/plot/cast;
  840. // desktop unchanged = poster left (10rem), title right of it
  841. const L = JSON.parse(await ev(`JSON.stringify((() => { const b = (s) => { const r = document.querySelector(s).getBoundingClientRect(); return { l: r.left, r: r.right, t: r.top, b: r.bottom, w: r.width }; };
  842. const main = document.querySelector('main'); const cs = getComputedStyle(main);
  843. return { h1: b('show-header h1'), follow: b('#follow'), links: b('show-links'), poster: b('show-poster img'), genres: b('show-genres'), summary: b('show-summary'), cast: b('show-cast'),
  844. content: main.getBoundingClientRect().width - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight) }; })())`));
  845. const ok = mobile
  846. ? L.h1.b <= L.links.t && L.links.b <= L.poster.t && Math.abs(L.poster.w - L.content) < 1 && L.poster.b <= L.genres.t && L.genres.b <= L.summary.t && L.summary.b <= L.cast.t && L.follow.t < L.poster.t
  847. : Math.abs(L.poster.w - 160) < 1 && L.poster.r <= L.h1.l && L.h1.t < L.poster.b && L.poster.t <= L.genres.t && L.poster.r <= L.links.l && L.h1.b <= L.links.t && L.links.b <= L.genres.t;
  848. check(`${w} px: show page layout — ${mobile ? 'title (+ Follow) first, the link icons under it, then the poster at the full content width, then genres, plot, cast' : 'poster left (10rem), the title right of it, the link icons under the title'}`, ok, JSON.stringify(L));
  849. }
  850. if (process.env.TRACKER_GATE_SHOTS) {
  851. if (name === 'my-shows' || name === 'my-movies') await waitPostersLoaded();
  852. // #13: every poster tile in view loaded
  853. await page.waitFor(`Array.from(document.querySelectorAll('img.tile-poster')).filter(i => { const r = i.getBoundingClientRect(); return r.top < innerHeight && r.bottom > 0 && r.left < innerWidth && r.right > 0 }).every(i => i.complete && i.naturalWidth > 0)`, { timeout: 10000, label: 'tiles loaded' });
  854. const shot = await page.send('Page.captureScreenshot', { format: 'png' });
  855. writeFileSync(join(process.env.TRACKER_GATE_SHOTS, `${name}-${w}.png`), Buffer.from(shot.data, 'base64'));
  856. }
  857. }
  858. check(`${w} px: on every page the header is one row (brand, ident selector, "Log out" side by side, ≤ 64 px high) and nothing scrolls sideways`, bad.length === 0, bad.join('; '));
  859. }
  860. await page.send('Emulation.clearDeviceMetricsOverride', {});
  861. // ==== tracker.worldapi.org#9: THE TMDB SYNC, against the fake TMDB — first the tool (app stopped: hl:mpackdb is
  862. // one process per storage), twice (idempotent), then the pages; then the app's own daily run ====
  863. 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);
  864. await page.goto('about:blank'); // leave the app first: an open page would log websocket reconnect errors
  865. await stopServer();
  866. // spawned, not execFileSync: the fake TMDB lives in THIS node process and must keep answering meanwhile
  867. const runTool = () => new Promise((ok) => {
  868. 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'] });
  869. let o = '';
  870. p.stdout.on('data', d => o += d); p.stderr.on('data', d => o += d);
  871. p.on('exit', () => ok(o));
  872. });
  873. let out = await runTool();
  874. const toolRun1 = out;
  875. let done = (out.match(/tmdb sync done: .*/) || [''])[0];
  876. check('sync tool: 3 followed shows (2 series + a movie another user follows) → 2 new seasons (show 1 S3, show 2 S1), 4 new episodes, the 3 fixture episodes updated (tmdbId by S/E number, E2 renamed), 3 posters, 5 ids filled, 3 TVmaze lookups + 2 TVmaze episode lists (#15: they agree with TMDB → nothing taken), 0 errors',
  877. done.includes('shows=3 newSeasons=2 newEpisodes=4 updatedEpisodes=3') && done.includes('posters=3 ids=5') && done.includes('tvmazeRequests=5 errors=0 tvmazeEpisodes=0 tvmazeSeasons=0 tvmazeFilled=0 tvmazeSkipped=0'), out);
  878. // per show, in this order (the order BETWEEN shows follows the follow table, which the follow test above reshuffled)
  879. // (#28: the details request also brings the credits — aggregate_credits / credits)
  880. const perShow = [['/3/tv/1001?append_to_response=external_ids,aggregate_credits', '/3/tv/1001?append_to_response=season/1,season/2,season/3', '/t/p/w342/gate1.png'],
  881. ['/3/tv/1002?append_to_response=external_ids,aggregate_credits', '/3/tv/1002?append_to_response=season/1', '/t/p/w342/gate2.png'], ['/3/movie/1003?append_to_response=external_ids,credits', '/t/p/w342/gate3.png']];
  882. const paths = tmdb.requests.map(q => q.path);
  883. check('sync tool: every TMDB call carried the Bearer token, season 0 was never asked for; per show ONE details request that also brings external_ids + the credits (no extra request), one for its seasons, the poster; the movie only via /movie/, never /tv/1003',
  884. tmdb.requests.filter(q => q.path.startsWith('/3/')).every(q => q.authorization === 'Bearer gate-token') && !paths.some(p => p.includes('season/0'))
  885. && JSON.stringify([...paths].sort()) === JSON.stringify(perShow.flat().sort()) && perShow.every(list => list.every((p, i) => i === 0 || paths.indexOf(list[i - 1]) < paths.indexOf(p))),
  886. JSON.stringify(paths));
  887. check('sync tool: TVmaze asked only for shows without a TVmaze id: show 1 by imdb (hit), show 2 by imdb (404) then by thetvdb (hit); then (#15) each series\' episode list by the found id; never for the movie',
  888. JSON.stringify([...tmdb.tvmazeRequests].sort()) === JSON.stringify(['/tvmaze/lookup/shows?imdb=tt0000001', '/tvmaze/lookup/shows?imdb=tt0000002', '/tvmaze/lookup/shows?thetvdb=4002', '/tvmaze/shows/501', '/tvmaze/shows/502', '/tvmaze/shows/501?embed=episodes', '/tvmaze/shows/502?embed=episodes'].sort()),
  889. JSON.stringify(tmdb.tvmazeRequests));
  890. const tvmazeBefore = tmdb.tvmazeRequests.length;
  891. out = await runTool();
  892. done = (out.match(/tmdb sync done: .*/) || [''])[0];
  893. // tracker.worldapi.org#28: the credits came with the details request — show 1: 23 cast (Test Actor linked, 22 new) + 7 crew
  894. // entries (5 new people); the movie 3 cast + 13 crew (15 new); show 2 none. The second run adds nobody.
  895. check('#28 sync tool: the cast + crew stored from the details request — show 1 cast 23 crew 7 (+27 people), the movie cast 3 crew 13 (+15), show 2 none; the second run adds no person',
  896. toolRun1.includes(', cast 23 crew 7 +27 people') && toolRun1.includes(', cast 3 crew 13 +15 people') && toolRun1.includes(', cast 0 crew 0 +0 people')
  897. && (out.match(/ \+0 people/g) || []).length === 3 && !/ \+[1-9]\d* people/.test(out), toolRun1 + out);
  898. check('sync tool again: idempotent — nothing new, nothing updated, no poster downloaded again, no id filled, no TVmaze lookup (every show has its TVmaze id now) — only the 2 episode lists, nothing taken from them',
  899. done.includes('newSeasons=0 newEpisodes=0 updatedEpisodes=0 updatedSeasons=0 posters=0 ids=0') && done.includes('tvmazeRequests=2 errors=0 tvmazeEpisodes=0 tvmazeSeasons=0 tvmazeFilled=0 tvmazeSkipped=0')
  900. && JSON.stringify(tmdb.tvmazeRequests.slice(tvmazeBefore).sort()) === JSON.stringify(['/tvmaze/shows/501?embed=episodes', '/tvmaze/shows/502?embed=episodes']), out);
  901. await startServer();
  902. await page.goto(BASE + '/my/schedule');
  903. await hydrated();
  904. 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)`);
  905. let rows = await scheduleRows();
  906. check('after the sync: /my/schedule lists the new upcoming episodes of both shows, soonest first', JSON.stringify(rows) === JSON.stringify([
  907. '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));
  908. await page.goto(BASE + '/my/unwatched');
  909. await hydrated();
  910. rows = await ev(`Array.from(document.querySelectorAll('unwatched-row')).map(r => r.querySelector('unwatched-episode').textContent + ' | ' + r.querySelector('unwatched-date').textContent)`);
  911. 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));
  912. await page.goto(BASE + '/my/shows');
  913. await hydrated();
  914. await waitPostersLoaded();
  915. ms = await myShows();
  916. 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/sh1.png' && ms[1].poster === '/posters/sh2.png', JSON.stringify(ms));
  917. r = await fetch(BASE + '/posters/sh2.png');
  918. const posterBytes = Buffer.from(await r.arrayBuffer());
  919. 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')));
  920. await page.goto(BASE + '/shows/gate-test-show');
  921. await hydrated();
  922. const seasonCounts = await ev(`Array.from(document.querySelectorAll('season-row')).map(e => e.querySelector('season-label').textContent + ': ' + e.querySelector('season-count').textContent)`);
  923. 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));
  924. check('after the sync: the latest season shows its new episodes, the poster is the downloaded one',
  925. JSON.stringify(await ev(`Array.from(document.querySelectorAll('episode-row episode-title')).map(e => e.textContent)`)) === JSON.stringify(['Third Season Start', 'Coming Soon'])
  926. && (await ev(`document.querySelector('show-poster img').getAttribute('src')`)) === '/posters/sh1.png' && (await ev(`document.querySelector('show-poster img').naturalWidth`)) > 0);
  927. await clickValue('button.season-toggle', SEASON1);
  928. await page.waitForSelector(`button.checkicon[value="${EP1}"]`, { timeout: 10000 });
  929. 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'))`);
  930. check('after the sync: S1 keeps its episodes (same ids, still watched), E2 renamed from TMDB, E3 new and unwatched',
  931. 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));
  932. // ---- tracker.worldapi.org#12: after the sync every show has the ids it lacked — the stored ones unchanged ----
  933. await page.goto(BASE + '/shows/gate-test-show');
  934. await hydrated();
  935. lk = await extLinks();
  936. check('after the sync: show 1 has all four icons — its OWN imdb id kept (tt0000001, not TMDB\'s tt9999999), tvdb 4001 + TVmaze 501 filled',
  937. linksAre(lk, [['TMDB', TMDB_TV + '1001'], ['IMDb', IMDB + 'tt0000001/'], ['TVDB', TVDB + '4001'], ['TVmaze', TVMAZE + '501']]), lk);
  938. await page.goto(BASE + '/shows/unwatched-gate-show');
  939. await hydrated();
  940. lk = await extLinks();
  941. check('after the sync: show 2 has all four — imdb tt0000002 filled, its OWN tvdb 4002 kept (not 4999), TVmaze 502 (found by thetvdb after imdb missed)',
  942. linksAre(lk, [['TMDB', TMDB_TV + '1002'], ['IMDb', IMDB + 'tt0000002/'], ['TVDB', TVDB + '4002'], ['TVmaze', TVMAZE + '502']]), lk);
  943. await page.goto(BASE + '/shows/gate-test-movie');
  944. await hydrated();
  945. lk = await extLinks();
  946. check('after the sync: the movie has TMDB (/movie/1003) + IMDb (tt0000003 filled), no TheTVDB/TVmaze, no seasons',
  947. linksAre(lk, [['TMDB', TMDB_MOVIE + '1003'], ['IMDb', IMDB + 'tt0000003/']]) && (await ev(`document.querySelectorAll('season-row').length`)) === 0, lk);
  948. // ==== tracker.worldapi.org#28: FULL CAST + CREW (stored by the sync tool above). The movie: TMDB's cast order with the
  949. // characters, the crew grouped by job (director once, a writer too; 9 writers → 6 + "Show all crew (13)", client-side) ====
  950. let cr = await credits();
  951. const pool = (n) => Array.from({ length: n }, (_, k) => 'Writer Pool ' + (k + 1));
  952. check('#28 movie: the whole cast in TMDB\'s order with the characters (none for the extra), each linked to its new person page; no toggle, no "Guest stars"',
  953. JSON.stringify(cr.cast) === JSON.stringify([['Movie Star', ' (Hero)', '/person/Movie-Star'], ['Movie Sidekick', ' (Sidekick)', '/person/Movie-Sidekick'], ['Uncredited Extra', '', '/person/Uncredited-Extra']])
  954. && JSON.stringify(cr.castSeen) === JSON.stringify(['Movie Star', 'Movie Sidekick', 'Uncredited Extra']) && cr.castToggle === null, JSON.stringify(cr));
  955. check('#28 movie: the crew by job — Directed by Film Director (listed twice by TMDB: once), Written by Film Director + the first 5 of the pool (6 shown), Screenplay, Story, Music; the assistant director and the adult crew member not shown; "Show all crew (13)"',
  956. JSON.stringify(cr.crewSeen) === JSON.stringify(['[Directed by]', 'Film Director', '[Written by]', 'Film Director', ...pool(5), '[Screenplay]', 'Screen Writer', '[Story]', 'Story Author', '[Music]', 'Film Composer'])
  957. && cr.crew.length === 13 && cr.crew[0][1] === '/person/Film-Director' && cr.crewToggle === 'Show all crew (13)' && !cr.crew.some(c => /Assistant|Adult/.test(c[0])), JSON.stringify(cr));
  958. let sentBefore28 = (await page.wsSent()).length;
  959. await page.click('#crewtoggle');
  960. await page.waitFor(`document.querySelectorAll('show-crew a.crew-link').length === 13 && Array.from(document.querySelectorAll('show-crew a.crew-link')).every(a => a.getClientRects().length > 0)`, { timeout: 3000, label: 'crew all' }).catch(() => {});
  961. cr = await credits();
  962. check('#28 movie: "Show all crew" shows all 9 writers at once — client-side (no request), the button says "Show less"',
  963. JSON.stringify(cr.crewSeen) === JSON.stringify(['[Directed by]', 'Film Director', '[Written by]', 'Film Director', ...pool(8), '[Screenplay]', 'Screen Writer', '[Story]', 'Story Author', '[Music]', 'Film Composer'])
  964. && cr.crewToggle === 'Show less' && (await page.wsSent()).length === sentBefore28, JSON.stringify(cr));
  965. if (process.env.TRACKER_GATE_SHOTS) writeFileSync(join(process.env.TRACKER_GATE_SHOTS, 'credits-movie-1280.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  966. // the series (aggregate_credits = every season): main cast by episode count, the later-season actor among them, then the guests
  967. await page.goto(BASE + '/shows/gate-test-show');
  968. await hydrated();
  969. cr = await credits();
  970. const ensemble = Array.from({ length: 18 }, (_, k) => 'Ensemble Player ' + String(k + 1).padStart(2, '0'));
  971. check('#28 series: all 23 of every season in TMDB\'s order (by episodes): Lead Player (his roles split, each once, "(uncredited)" dropped, 4 + "…"), Test Actor (linked, not added twice), Ensemble 01–18, Late Season Star (season 3 only, both roles), Guest Star Two, Guest Star One — the adult one left out',
  972. JSON.stringify(cr.cast.map(c => c[0])) === JSON.stringify(['Lead Player', 'Test Actor', ...ensemble, 'Late Season Star', 'Guest Star Two', 'Guest Star One'])
  973. && cr.cast[0][1] === ' (The Lead / Twin / Mirror / Ghost / …)' && cr.cast[1][2] === '/person/Test-Actor' && cr.cast[1][1] === ' (Someone)' && cr.cast[20][1] === ' (New Captain / Captain)' && cr.cast[20][2] === '/person/Late-Season-Star'
  974. && cr.cast[2][1] === ' (Crew Member 1)' && !cr.cast.some(c => /Adult|Test-Actor-2/.test(c[0] + c[2])), JSON.stringify(cr.cast));
  975. check('#28 series: collapsed after 20 — the first 20 names, no guests yet, "Show all (23)"; the character after each name, a comma after the 19th, none after the 20th',
  976. JSON.stringify(cr.castSeen) === JSON.stringify(['Lead Player', 'Test Actor', ...ensemble]) && cr.castToggle === 'Show all (23)'
  977. && cr.after[19] === '" (Crew Member 18)"' && cr.after[18] === '" (Crew Member 17), "', JSON.stringify(cr));
  978. check('#28 series: the crew — Created by Show Creator, Directed by (by episodes) Episode Director + Second Director, Written by Show Creator (5) + Staff Writer (3), Story Staff Writer, Music Theme Composer; the script supervisor not shown, no crew toggle',
  979. JSON.stringify(cr.crewSeen) === JSON.stringify(['[Created by]', 'Show Creator', '[Directed by]', 'Episode Director', 'Second Director', '[Written by]', 'Show Creator', 'Staff Writer', '[Story]', 'Staff Writer', '[Music]', 'Theme Composer'])
  980. && cr.crew[0][1] === '/person/Show-Creator' && cr.crewToggle === null, JSON.stringify(cr));
  981. if (process.env.TRACKER_GATE_SHOTS) {
  982. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  983. await ev(`document.querySelector('show-crew').scrollIntoView()`);
  984. writeFileSync(join(process.env.TRACKER_GATE_SHOTS, 'credits-series-collapsed-390.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  985. }
  986. sentBefore28 = (await page.wsSent()).length;
  987. await page.click('#casttoggle');
  988. await page.waitFor(`document.querySelector('show-cast').className === 'all'`, { timeout: 3000, label: 'cast all' }).catch(() => {});
  989. cr = await credits();
  990. check('#28 series: "Show all (23)" shows every name at once — client-side (no request) — the later-season actor last of the main cast (no comma before the label), then "Guest stars"; "Show less"; no sideways scroll',
  991. JSON.stringify(cr.castSeen) === JSON.stringify(['Lead Player', 'Test Actor', ...ensemble, 'Late Season Star', '[Guest stars]', 'Guest Star Two', 'Guest Star One']) && cr.castToggle === 'Show less'
  992. && (await page.wsSent()).length === sentBefore28 && cr.after[19] === '" (Crew Member 18), "' && cr.after[20] === '" (New Captain / Captain)"' && cr.after[22] === '" (Stranger)"' && cr.scrollW <= (process.env.TRACKER_GATE_SHOTS ? 390 : 1e9), JSON.stringify(cr));
  993. if (process.env.TRACKER_GATE_SHOTS) {
  994. await ev(`document.querySelector('show-cast').scrollIntoView()`);
  995. writeFileSync(join(process.env.TRACKER_GATE_SHOTS, 'credits-series-all-390.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  996. }
  997. await page.click('#casttoggle');
  998. await page.waitFor(`document.querySelector('show-cast').className === 'collapsed'`, { timeout: 3000, label: 'cast collapsed' }).catch(() => {});
  999. cr = await credits();
  1000. check('#28 series: "Show less" collapses it again (20 names)', cr.castSeen.length === 20 && cr.castToggle === 'Show all (23)' && (await page.wsSent()).length === sentBefore28, JSON.stringify(cr.castSeen));
  1001. if (process.env.TRACKER_GATE_SHOTS) {
  1002. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1003. await page.goto(BASE + '/shows/gate-test-show');
  1004. await hydrated();
  1005. writeFileSync(join(process.env.TRACKER_GATE_SHOTS, 'credits-series-1280.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  1006. await page.send('Emulation.clearDeviceMetricsOverride', {});
  1007. }
  1008. const lateHtml = await (await fetch(BASE + '/person/Late-Season-Star')).text();
  1009. check('#28: a new cast person\'s page exists at once (/person/Late-Season-Star)', /<h1>Late Season Star<\/h1>/.test(lateHtml), lateHtml.slice(0, 300));
  1010. // ---- tracker.worldapi.org#13: the public lists are built at start — after the sync (tool, then a restart) show 1's new
  1011. // S03E01 (2021-05-05) puts it before Pager Older Series (2021-01-01); show 2 has only an upcoming episode: still last
  1012. await page.goto(BASE + '/shows');
  1013. await hydrated();
  1014. tl = await titlesOf('tile-grid');
  1015. check('after the sync + restart: /shows by newest released episode — Gate Test Show (S03E01 2021-05-05) first now, its synced poster; Unwatched Gate Show (only upcoming) last',
  1016. JSON.stringify(tl) === JSON.stringify(['Gate Test Show', 'Pager Older Series', 'Unwatched Gate Show']) && (await tilesOf('tile-grid'))[0].endsWith('|/posters/sh1.png'), JSON.stringify(tl));
  1017. if (process.env.TRACKER_GATE_SHOTS) {
  1018. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  1019. for (const [name, path] of [['synced-show-390', '/shows/gate-test-show'], ['synced-movie-390', '/shows/gate-test-movie']]) {
  1020. await page.goto(BASE + path);
  1021. await hydrated();
  1022. writeFileSync(join(process.env.TRACKER_GATE_SHOTS, name + '.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  1023. }
  1024. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1025. for (const [name, path] of [['synced-show', '/shows/gate-test-show'], ['synced-movie', '/shows/gate-test-movie'], ['synced-my-shows', '/my/shows'], ['synced-my-unwatched', '/my/unwatched'], ['synced-my-schedule', '/my/schedule']]) {
  1026. await page.goto(BASE + path);
  1027. await hydrated();
  1028. if (name === 'synced-my-shows') await waitPostersLoaded();
  1029. const shot = await page.send('Page.captureScreenshot', { format: 'png' });
  1030. writeFileSync(join(process.env.TRACKER_GATE_SHOTS, name + '.png'), Buffer.from(shot.data, 'base64'));
  1031. }
  1032. await page.send('Emulation.clearDeviceMetricsOverride', {});
  1033. }
  1034. // ---- THE DAILY RUN INSIDE THE APP: TRACKER_SYNC_HOUR = this very UTC hour, so the app's own clock starts the
  1035. // run right after boot. TMDB now has one more episode and answers slowly (700 ms per request): the run takes
  1036. // seconds, and pages asked for meanwhile must still be answered between two shows, never after the whole run.
  1037. await page.goto('about:blank');
  1038. await stopServer();
  1039. tmdb.shows[1001].seasons[3].episodes.push({ id: 5007, episode_number: 3, name: 'Added Live', air_date: '2096-03-03' });
  1040. // tracker.worldapi.org#13: and show 2 an episode that is ALREADY OUT — the running app must move it to the top of /shows
  1041. tmdb.shows[1002].seasons[0].episodes.push({ id: 7002, episode_number: 2, name: 'Out Already', air_date: '2022-02-02' });
  1042. tmdb.delayMs = 700;
  1043. const before = tmdb.requests.length, tvmazeBeforeRun = tmdb.tvmazeRequests.length;
  1044. await startServer({ TRACKER_SYNC: '1', TRACKER_SYNC_HOUR: String(new Date().getUTCHours()) });
  1045. const lat = [];
  1046. const t0 = Date.now();
  1047. while (!log.includes('tmdb sync done') && Date.now() - t0 < 30000) {
  1048. const a = Date.now();
  1049. await fetch(BASE + '/');
  1050. lat.push({ at: a - t0, ms: Date.now() - a, running: log.includes('tmdb sync: start') && !log.includes('tmdb sync done') });
  1051. await new Promise(r => setTimeout(r, 150));
  1052. }
  1053. const runDone = (log.match(/tmdb sync done: .*/) || [''])[0];
  1054. check('in-app daily run: started by the app\'s own clock at the configured hour — the FULL WALK (#18: no last run yet) — found the 2 new episodes, 0 errors',
  1055. log.includes('tmdb sync: daily at ' + new Date().getUTCHours() + ':00 UTC') && log.includes('tmdb sync: start, 3 followed shows, full walk (no last run)') && runDone.includes('newSeasons=0 newEpisodes=2 updatedEpisodes=0') && runDone.includes('errors=0'), log);
  1056. const during = lat.filter(l => l.running);
  1057. const runSecs = Number((runDone.match(/seconds=([0-9.]+)/) || [0, 0])[1]);
  1058. console.log(` (in-app run ${runSecs} s; ${during.length} pages asked during it, slowest ${Math.max(0, ...during.map(l => l.ms))} ms)`);
  1059. 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',
  1060. runSecs >= 3 && during.length >= 3 && during.every(l => l.ms < 2500), 'run ' + runSecs + ' s, during: ' + JSON.stringify(during));
  1061. check('in-app daily run: the Bearer token on every call, 5 requests (2 per series, 1 for the movie; no poster again: unchanged), no TVmaze lookup, only the 2 episode lists (#15)', tmdb.requests.slice(before).filter(q => q.path.startsWith('/3/')).every(q => q.authorization === 'Bearer gate-token') && tmdb.requests.length - before === 5
  1062. && JSON.stringify(tmdb.tvmazeRequests.slice(tvmazeBeforeRun).sort()) === JSON.stringify(['/tvmaze/shows/501?embed=episodes', '/tvmaze/shows/502?embed=episodes']), JSON.stringify(tmdb.requests.slice(before)) + JSON.stringify(tmdb.tvmazeRequests.slice(tvmazeBeforeRun)));
  1063. await page.goto(BASE + '/my/schedule');
  1064. await hydrated();
  1065. rows = await scheduleRows();
  1066. 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));
  1067. await page.goto(BASE + '/shows');
  1068. await hydrated();
  1069. tl = await titlesOf('tile-grid');
  1070. check('after the in-app run (no restart): /shows has Unwatched Gate Show on top — its new S01E02 (2022-02-02) is out; the homepage row too',
  1071. JSON.stringify(tl) === JSON.stringify(['Unwatched Gate Show', 'Gate Test Show', 'Pager Older Series']), JSON.stringify(tl));
  1072. await page.goto(BASE + '/');
  1073. await hydrated();
  1074. tl = await titlesOf('#home-shows');
  1075. check('after the in-app run: the homepage\'s Shows row has it first as well', JSON.stringify(tl) === JSON.stringify(['Unwatched Gate Show', 'Gate Test Show', 'Pager Older Series']), JSON.stringify(tl));
  1076. // ==== tracker.worldapi.org#15: THE TVMAZE MERGE — TVmaze knows more than TMDB: show 1 (TVmaze 501) gets S3E4's real
  1077. // title + air date (TMDB: "Episode 4", no date), a new S3E5 and a new season 4; TVmaze's other name for S3E1 must NOT
  1078. // replace TMDB's; its S1E1 airs on another day but has the same title (still agrees). Show 2 (502) TVmaze numbers
  1079. // differently (S1E1 another title, 7 years off — like a split pilot) → TVmaze is ignored for it. ====
  1080. await page.goto('about:blank');
  1081. await stopServer();
  1082. tmdb.delayMs = 0;
  1083. tmdb.shows[1001].seasons[3].episodes.push({ id: 5008, episode_number: 4, name: 'Episode 4' });
  1084. const tvm501 = tmdb.tvmaze.episodes[501].filter(e => !(e.season === 3 && e.number === 1));
  1085. tvm501.push({ id: 8005, season: 3, number: 1, name: 'Other Name From TVmaze', airdate: '2021-05-05' }, { id: 8007, season: 3, number: 3, name: 'Added Live', airdate: '2096-03-03' },
  1086. { id: 8008, season: 3, number: 4, name: 'Real Fourth', airdate: '2096-04-04' }, { id: 8009, season: 3, number: 5, name: 'Only On TVmaze', airdate: '2096-05-05' },
  1087. { id: 8010, season: 4, number: 1, name: 'New Season Premiere', airdate: '2096-06-06' });
  1088. tmdb.tvmaze.episodes[501] = tvm501;
  1089. tmdb.tvmaze.episodes[502] = [{ id: 8101, season: 1, number: 1, name: 'Brand New Pre-Pilot', airdate: '2090-01-01' }, { id: 8102, season: 1, number: 2, name: 'Should Not Appear', airdate: '2097-02-01' }];
  1090. // a date that differs (another country's premiere) but the SAME title still counts as the same numbering
  1091. tvm501.find(e => e.season === 1 && e.number === 1).airdate = '2019-12-20';
  1092. out = await runTool();
  1093. done = (out.match(/tmdb sync done: .*/) || [''])[0];
  1094. check('tvmaze merge: TMDB adds S3E4 ("Episode 4", no date); TVmaze adds 2 episodes (S3E5, S4E1) + 1 season (S4), fills 1 episode (S3E4), skips show 2 (numbered differently), 0 errors',
  1095. done.includes('newSeasons=0 newEpisodes=1 updatedEpisodes=0') && done.includes('tvmazeRequests=2 errors=0 tvmazeEpisodes=2 tvmazeSeasons=1 tvmazeFilled=1 tvmazeSkipped=1') && out.includes('SKIPPED (numbered differently)'), out);
  1096. out = await runTool();
  1097. done = (out.match(/tmdb sync done: .*/) || [''])[0];
  1098. check('tvmaze merge again: idempotent — nothing new, nothing filled, no TMDB update (TMDB\'s "Episode 4" does not replace TVmaze\'s "Real Fourth")',
  1099. done.includes('newSeasons=0 newEpisodes=0 updatedEpisodes=0 updatedSeasons=0') && done.includes('errors=0 tvmazeEpisodes=0 tvmazeSeasons=0 tvmazeFilled=0 tvmazeSkipped=1'), out);
  1100. await startServer();
  1101. await page.goto(BASE + '/my/schedule');
  1102. await hydrated();
  1103. rows = await scheduleRows();
  1104. check('tvmaze merge: /my/schedule shows what only TVmaze has (S03E04 with its TVmaze title + date, S03E05, S04E01), in date order; nothing of show 2\'s differently numbered TVmaze list', JSON.stringify(rows) === JSON.stringify([
  1105. 'Gate Test Show (2024) | S03E03 · Added Live | 2096-03-03', 'Gate Test Show (2024) | S03E04 · Real Fourth | 2096-04-04', 'Gate Test Show (2024) | S03E05 · Only On TVmaze | 2096-05-05',
  1106. 'Gate Test Show (2024) | S04E01 · New Season Premiere | 2096-06-06', 'Unwatched Gate Show (2025) | S01E01 · Brand New | 2097-01-01',
  1107. 'Gate Test Show (2024) | S03E02 · Coming Soon | 2098-06-01', 'Gate Test Show (2024) | S02E01 · Season Two Opener | 2099-01-01']), JSON.stringify(rows));
  1108. const seasonsAndTitles = async () => {
  1109. await page.goto(BASE + '/shows/gate-test-show');
  1110. await hydrated();
  1111. const seasons = await ev(`Array.from(document.querySelectorAll('season-row')).map(e => e.querySelector('season-label').textContent + ': ' + e.querySelector('season-count').textContent)`);
  1112. await clickValue('button.season-toggle', await ev(`Array.from(document.querySelectorAll('season-row')).find(e => e.querySelector('season-label').textContent === 'Season 3').querySelector('button.season-toggle').value`));
  1113. await page.waitFor(`document.querySelectorAll('episode-row').length >= 6`, { timeout: 10000, label: 'S3 expanded' });
  1114. const titles = await ev(`Array.from(document.querySelectorAll('episode-row')).map(e => e.querySelector('episode-number').textContent + ' ' + e.querySelector('episode-title').textContent)`);
  1115. return { seasons, titles };
  1116. };
  1117. let tst = await seasonsAndTitles();
  1118. check('tvmaze merge: the show page has the new Season 4 (1 episode) and Season 3 with 5 — S3E1 keeps TMDB\'s title, S3E4 TVmaze\'s',
  1119. JSON.stringify(tst.seasons) === JSON.stringify(['Season 4: 1 episode', 'Season 3: 5 episodes', 'Season 2: 1 episode', 'Season 1: 3 episodes'])
  1120. && JSON.stringify(tst.titles) === JSON.stringify(['1 New Season Premiere', '1 Third Season Start', '2 Coming Soon', '3 Added Live', '4 Real Fourth', '5 Only On TVmaze']), JSON.stringify(tst));
  1121. if (process.env.TRACKER_GATE_SHOTS) {
  1122. for (const [w, h, mobile] of [[390, 844, true], [1280, 900, false]]) {
  1123. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: mobile ? 2 : 1, mobile });
  1124. for (const [name, path] of [['tvmaze-schedule', '/my/schedule'], ['tvmaze-show', '/shows/gate-test-show']]) {
  1125. await page.goto(BASE + path);
  1126. await hydrated();
  1127. writeFileSync(join(process.env.TRACKER_GATE_SHOTS, `${name}-${w}.png`), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  1128. }
  1129. }
  1130. await page.send('Emulation.clearDeviceMetricsOverride', {});
  1131. }
  1132. // TMDB catches up: it now lists S3E5 (its own title) and season 4 — the TMDB step ADOPTS TVmaze's rows by number (no
  1133. // duplicate), TMDB's values win; its "Episode 4" still never replaces "Real Fourth"
  1134. await page.goto('about:blank');
  1135. await stopServer();
  1136. tmdb.shows[1001].seasons[3].episodes.push({ id: 5009, episode_number: 5, name: 'Official Fifth', air_date: '2096-05-05' });
  1137. tmdb.shows[1001].seasons.push({ id: 95, season_number: 4, name: 'Season 4', air_date: '2096-06-06', episodes: [{ id: 5010, episode_number: 1, name: 'New Season Premiere', air_date: '2096-06-06' }] });
  1138. out = await runTool();
  1139. done = (out.match(/tmdb sync done: .*/) || [''])[0];
  1140. check('tvmaze merge, TMDB catches up: TMDB adopts the 2 TVmaze episodes (updatedEpisodes=2: tmdbId set, S3E5 renamed), creates nothing, TVmaze adds nothing',
  1141. done.includes('newSeasons=0 newEpisodes=0 updatedEpisodes=2 updatedSeasons=0') && done.includes('errors=0 tvmazeEpisodes=0 tvmazeSeasons=0 tvmazeFilled=0'), out);
  1142. await startServer();
  1143. tst = await seasonsAndTitles();
  1144. check('tvmaze merge, TMDB caught up: still S4 1 / S3 5 episodes (no duplicates), S3E5 now TMDB\'s "Official Fifth", S3E4 still "Real Fourth"',
  1145. JSON.stringify(tst.seasons) === JSON.stringify(['Season 4: 1 episode', 'Season 3: 5 episodes', 'Season 2: 1 episode', 'Season 1: 3 episodes'])
  1146. && JSON.stringify(tst.titles) === JSON.stringify(['1 New Season Premiere', '1 Third Season Start', '2 Coming Soon', '3 Added Live', '4 Real Fourth', '5 Official Fifth']), JSON.stringify(tst));
  1147. // ==== tracker.worldapi.org#14: THE SEARCH, signed IN — "Add" imports the title like the daily sync and opens its page ====
  1148. tmdb.delayMs = 0;
  1149. await page.goto(BASE + '/search/gate');
  1150. await hydrated();
  1151. await page.click('#fetchweb');
  1152. await page.waitFor(`document.querySelectorAll('web-row').length > 0`, { timeout: 10000, label: 'web results (signed in)' });
  1153. const dbBefore = await searchTitles();
  1154. // hybriel#121/#122: a SESSION face (searchImport) that stays on the page — tv 1006's details answer 404 — must leave every
  1155. // list as it was: each row once, the route-param text still in the field and in data-for
  1156. await page.click('web-row button.add[value="tv:1006"]');
  1157. await page.waitFor(`!!document.querySelector('#importerror')`, { timeout: 10000, label: 'import error' }).catch(() => {});
  1158. await new Promise(r => setTimeout(r, 300));
  1159. check('search import: a failed import (TMDB 404) says so and stays — the database list, the web list and the text are unchanged, no row twice (hybriel#121/#122)',
  1160. (await ev(`document.querySelector('#importerror') ? document.querySelector('#importerror').textContent : ''`)) === 'Could not add it: TMDB: HTTP 404 for /tv/1006?append_to_response=external_ids,aggregate_credits'
  1161. && (await searchTitles()) === dbBefore && dbBefore === JSON.stringify(GATE_TITLES) && (await webList()) === JSON.stringify(GATE_WEB)
  1162. && (await ev(`document.querySelector('#searchinput').value`)) === 'gate' && (await searchFor()) === 'gate' && (await ev('location.pathname')) === '/search/gate',
  1163. (await ev(`document.querySelector('search-page').outerHTML.slice(0, 1500)`)));
  1164. await typeSearch('gate t');
  1165. check('search import: after that session face the page still searches (typing "gate t" → the two "Gate Test" titles)', (await searchTitles()) === JSON.stringify(GATE_TITLES.slice(0, 2)), await searchTitles());
  1166. await typeSearch('gate');
  1167. await page.click('#fetchweb');
  1168. await page.waitFor(`document.querySelectorAll('web-row').length > 0`, { timeout: 10000 });
  1169. const reqBefore = tmdb.requests.length;
  1170. await page.click('web-row button.add[value="tv:1004"]');
  1171. await page.waitFor(`location.pathname !== '/search/gate' && !!document.querySelector('show-header h1')`, { timeout: 15000, label: 'imported show page' });
  1172. await page.waitFor(`!!document.querySelector('show-poster img') && document.querySelector('show-poster img').complete`, { timeout: 5000 }).catch(() => {});
  1173. const imp = JSON.parse(await ev(`JSON.stringify({ path: location.pathname, h1: document.querySelector('show-header h1').textContent,
  1174. seasons: Array.from(document.querySelectorAll('season-row')).map(r => r.querySelector('season-label').textContent + ': ' + r.querySelector('season-count').textContent),
  1175. episodes: Array.from(document.querySelectorAll('episode-row episode-title')).map(e => e.textContent), genres: Array.from(document.querySelectorAll('.genre-pill')).map(g => g.textContent),
  1176. poster: document.querySelector('show-poster img') ? document.querySelector('show-poster img').getAttribute('src') : null,
  1177. posterW: document.querySelector('show-poster img') ? document.querySelector('show-poster img').naturalWidth : 0, summary: document.querySelector('show-summary').textContent })`));
  1178. lk = await extLinks();
  1179. check('search import: "Add" on tv 1004 adds it and opens its page /shows/Gate-Import-Show — season, episodes, poster (downloaded), genres matched by name, the summary',
  1180. imp.path === '/shows/Gate-Import-Show' && imp.h1 === 'Gate Import Show' && JSON.stringify(imp.seasons) === JSON.stringify(['Season 1: 2 episodes'])
  1181. && JSON.stringify(imp.episodes) === JSON.stringify(['Imported One', 'Imported Two']) && JSON.stringify(imp.genres) === JSON.stringify(['Drama'])
  1182. && imp.poster === '/posters/tmdb-tv-1004.png' && imp.posterW > 0 && imp.summary === 'an imported series' && existsSync(join(MPACKDB, 'posters', 'tmdb-tv-1004.png')), JSON.stringify(imp));
  1183. cr = await credits();
  1184. check('#28 search import: the imported series has its cast (Imported Lead as Captain) and crew (Created by Import Creator) at once',
  1185. JSON.stringify(cr.cast) === JSON.stringify([['Imported Lead', ' (Captain)', '/person/Imported-Lead']]) && JSON.stringify(cr.crewSeen) === JSON.stringify(['[Created by]', 'Import Creator'])
  1186. && /search import credits: \/shows\/Gate-Import-Show cast=1 crew=1 people=2 /.test(log), JSON.stringify(cr) + log.split('\n').filter(l => /import/.test(l)).join('\n'));
  1187. check('search import: the ids came like the daily sync\'s — TMDB, IMDb tt0000004, TVDB 4004, TVmaze 504 (looked up by thetvdb)',
  1188. linksAre(lk, [['TMDB', TMDB_TV + '1004'], ['IMDb', IMDB + 'tt0000004/'], ['TVDB', TVDB + '4004'], ['TVmaze', TVMAZE + '504']]), lk);
  1189. const impPaths = tmdb.requests.slice(reqBefore).map(q => q.path);
  1190. // (#28: ONE details request — the record, ids and credits — handed to the sync, no second one)
  1191. check('search import: TMDB asked exactly like the sync (details with external_ids + aggregate_credits, seasons, poster), the details only ONCE, all with the token',
  1192. JSON.stringify(impPaths) === JSON.stringify(['/3/tv/1004?append_to_response=external_ids,aggregate_credits', '/3/tv/1004?append_to_response=season/1', '/t/p/w342/gate4.png'])
  1193. && tmdb.requests.slice(reqBefore).filter(q => q.path.startsWith('/3/')).every(q => q.authorization === 'Bearer gate-token'), JSON.stringify(impPaths));
  1194. await page.goto(BASE + '/search/gate');
  1195. await hydrated();
  1196. st14 = await searchTitles();
  1197. check('search import: our database has it at once (the index too): "gate" now also lists Gate Import Show (2023)',
  1198. st14 === JSON.stringify([GATE_TITLES[0], GATE_TITLES[1], ['Gate Import Show (2023)', '/shows/Gate-Import-Show', 'Series'], GATE_TITLES[2]]), st14);
  1199. await page.click('#fetchweb');
  1200. await page.waitFor(`document.querySelectorAll('web-row').length > 0`, { timeout: 10000 });
  1201. wl = await webList();
  1202. check('search import: the web list leaves it out now (we have it)', wl === JSON.stringify(GATE_WEB.slice(1)), wl);
  1203. await page.click('web-row button.add[value="movie:1005"]');
  1204. await page.waitFor(`location.pathname === '/shows/Gate-Import-Movie' && !!document.querySelector('show-header h1')`, { timeout: 15000, label: 'imported movie page' });
  1205. lk = await extLinks();
  1206. check('search import: a MOVIE (movie 1005) → /shows/Gate-Import-Movie, synced via /movie/ (TMDB /movie/1005 + IMDb), no seasons',
  1207. (await ev(`document.querySelector('show-header h1').textContent`)) === 'Gate Import Movie' && linksAre(lk, [['TMDB', TMDB_MOVIE + '1005'], ['IMDb', IMDB + 'tt0000005/']])
  1208. && (await ev(`document.querySelectorAll('season-row').length`)) === 0 && !tmdb.requests.some(q => q.path.startsWith('/3/tv/1005')), lk);
  1209. await page.goto(BASE + '/search/gate%20import');
  1210. await hydrated();
  1211. st14 = await searchTitles();
  1212. check('search import: both imported titles are found, each once', st14 === JSON.stringify([['Gate Import Show (2023)', '/shows/Gate-Import-Show', 'Series'], ['Gate Import Movie (2001)', '/shows/Gate-Import-Movie', 'Movie']]), st14);
  1213. // merge of #13 + #14: an imported title is in the public lists at once (catalog.hl refreshCatalogShow), no restart
  1214. await page.goto(BASE + '/movies');
  1215. await hydrated();
  1216. titles = await titlesOf('tile-grid');
  1217. await page.goto(BASE + '/shows');
  1218. await hydrated();
  1219. tl = await titlesOf('tile-grid');
  1220. check('search import → the lists at once: /movies has Gate Import Movie (2001-05-05) right after the 2099 one, /shows has Gate Import Show',
  1221. titles[0] === 'Pager Future Movie' && titles[1] === 'Gate Import Movie' && titles.filter(t => t === 'Gate Import Movie').length === 1 && tl.filter(t => t === 'Gate Import Show').length === 1, JSON.stringify({ titles, tl }));
  1222. if (process.env.TRACKER_GATE_SHOTS) {
  1223. for (const [w, h, mobile] of [[390, 844, true], [1280, 900, false]]) {
  1224. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: mobile ? 2 : 1, mobile });
  1225. await page.goto(BASE + '/search/gate');
  1226. await hydrated();
  1227. await page.click('#fetchweb');
  1228. await page.waitFor(`document.querySelectorAll('web-row').length > 0`, { timeout: 10000 });
  1229. await page.waitFor(`Array.from(document.querySelectorAll('img')).every(i => i.complete)`, { timeout: 5000 }).catch(() => {});
  1230. writeFileSync(join(process.env.TRACKER_GATE_SHOTS, `search-web-${w}.png`), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  1231. }
  1232. await page.send('Emulation.clearDeviceMetricsOverride', {});
  1233. }
  1234. check('search: the server log has no error (the imports logged their sync counts)', !/error absorbed/i.test(log) && (log.match(/search import: /g) || []).length === 2, log.split('\n').filter(l => /search|error/i.test(l)).join('\n'));
  1235. // ==== mission 054: ADULT TITLES — the public lists and the search show only titles TMDB says are NOT adult (unknown =
  1236. // hidden); a followed adult title stays on /my/* and its page; the in-app BACKFILL asks TMDB title by title, resumes
  1237. // after a restart, and pages stay fast meanwhile. tests/seed-adult.hl adds the titles (app stopped) ====
  1238. await page.goto('about:blank'); // mission 056: a tab left on a page logs websocket reconnect errors while the server is down
  1239. await stopServer();
  1240. const seedAdult = execFileSync(join(APP, 'bin/hybriel'), ['tests/seed-adult.hl'], { cwd: APP, env: { ...process.env, TRACKER_STORAGE: MPACKDB, TRACKER_SEED_USER: 'gateu0000000000u1' } }).toString();
  1241. check('adult: fixture written (1 adult title alice follows, 14 with an unknown flag)', seedAdult.includes('15 titles') && seedAdult.includes('follows Adult Gate Movie'), seedAdult);
  1242. await startServer();
  1243. const ADULT_ALL = ['Adult Gate Movie', 'Flagless Gate Movie', 'Flagless Adult Movie', 'Flagless Gate Series', 'Gone Gate Movie', 'Backfill Movie'];
  1244. // the signed-OUT HTML of a page (node fetch, no cookie): which of these titles it names
  1245. const namesIn = async (path) => { const h = await (await fetch(BASE + path)).text(); return ADULT_ALL.filter(t => h.includes(t)); };
  1246. const allMoviesHtml = async () => { let h = ''; for (const p of ['/movies', '/movies/page/2']) h += await (await fetch(BASE + p)).text(); return h; };
  1247. const mh = await allMoviesHtml();
  1248. let seen = { home: await namesIn('/'), movies: ADULT_ALL.filter(t => mh.includes(t)), shows: await namesIn('/shows') };
  1249. check('adult (backfill off): signed out, the homepage, every /movies page and /shows list NONE of the adult/unknown titles; the count is unchanged (34 movies)',
  1250. seen.home.length === 0 && seen.movies.length === 0 && seen.shows.length === 0 && mh.includes('34 movies, newest first'), JSON.stringify(seen));
  1251. let sr = await (await fetch(BASE + '/search/flagless')).text();
  1252. const sr2 = await (await fetch(BASE + '/search/adult%20gate')).text();
  1253. check('adult (backfill off): the search finds none of them ("flagless", "adult gate" → "Nothing in our database yet.")',
  1254. sr.includes('Nothing in our database yet.') && !sr.includes('class="search-title"') && sr2.includes('Nothing in our database yet.'), sr.slice(sr.indexOf('<search-page'), sr.indexOf('<search-page') + 600));
  1255. await page.goto(BASE + '/my/movies');
  1256. await hydrated();
  1257. const myMv = await ev(`JSON.stringify(Array.from(document.querySelectorAll('my-show-row')).map(r => r.querySelector('a.myshow-title').textContent))`);
  1258. check('adult: alice follows the adult movie → it IS on her /my/movies (newest follow first)', JSON.parse(myMv)[0] === 'Adult Gate Movie (2001)', myMv);
  1259. await page.click('a.myshow-title[href="/shows/adult-gate-movie"]');
  1260. await page.waitFor(`location.pathname === '/shows/adult-gate-movie' && !!document.querySelector('show-page')`, { timeout: 10000, label: 'adult page (alice)' });
  1261. await page.waitFor(`!!document.querySelector('show-header h1')`, { timeout: 5000 }).catch(() => {});
  1262. check('adult: …and its page opens for her (client-side from /my/movies, and on a reload) with "Following"',
  1263. (await ev(`document.querySelector('show-header h1') ? document.querySelector('show-header h1').textContent : 'none'`)) === 'Adult Gate Movie'
  1264. && (await (async () => { await page.goto(BASE + '/shows/adult-gate-movie'); await hydrated(); return ev(`(document.querySelector('show-header h1') || {}).textContent + '|' + (document.querySelector('#follow') || {}).textContent`); })()) === 'Adult Gate Movie|Following');
  1265. // mission 056: the adult title's PAGE is "Not found" for anyone who does not follow it — signed out (no cookie) here
  1266. const adultOut = await (await fetch(BASE + '/shows/adult-gate-movie')).text();
  1267. const pageH1 = (h) => (h.match(/<show-page[^>]*>[\s\S]*?<h1[^>]*>([^<]*)<\/h1>/) || [])[1];
  1268. check('adult (056): signed out, /shows/adult-gate-movie says "Not found" and names no title (a non-adult page still opens: Flagless Gate Movie is unknown, not hidden)',
  1269. pageH1(adultOut) === 'Not found' && !adultOut.includes('Adult Gate Movie') && pageH1(await (await fetch(BASE + '/shows/flagless-gate-movie')).text()) === 'Flagless Gate Movie', pageH1(adultOut));
  1270. await page.goto(BASE + '/');
  1271. await hydrated();
  1272. const homeIn = await ev(`document.querySelector('home').textContent`);
  1273. check('adult: signed in too, the homepage rows have none of them (only /my/* is personal)', ADULT_ALL.every(t => !homeIn.includes(t)), homeIn);
  1274. await page.goto(BASE + '/search/gate');
  1275. await hydrated();
  1276. const wsBefore = tmdb.searchRequests.length;
  1277. await page.click('#fetchweb');
  1278. await page.waitFor(`document.querySelectorAll('web-row').length > 0 || !!document.querySelector('#webnote')`, { timeout: 10000, label: 'web results (adult)' });
  1279. wl = await webList();
  1280. check('adult: "Fetch from web" asks TMDB with include_adult=false and leaves out the result TMDB marks adult (Gate Adult Web)',
  1281. !wl.includes('Gate Adult Web') && wl.includes('Gate Broken Show') && tmdb.searchRequests.length === wsBefore + 1 && tmdb.searchRequests[wsBefore].path.includes('include_adult=false'), wl);
  1282. check('adult (backfill off): the log says so, no TMDB request was made for the unknown titles', log.includes('adult backfill: off (TRACKER_BACKFILL=0)') && !tmdb.requests.some(q => /\/3\/(movie|tv)\/(1012|1013|1014|1120|11\d\d)/.test(q.path)), log);
  1283. // ---- the BACKFILL: every answer slowed down to 300 ms; stopped after 6 titles, started again → it goes on with the rest ----
  1284. await page.goto('about:blank'); // mission 056: a tab left on a page logs websocket reconnect errors while the server is down
  1285. await stopServer();
  1286. tmdb.delayMs = 300;
  1287. const bfReq = tmdb.requests.length;
  1288. await startServer({ TRACKER_BACKFILL: '1', TRACKER_BACKFILL_LOG_EVERY: '3' });
  1289. const waitLog = async (re, ms) => { const t0 = Date.now(); while (!re.test(log) && Date.now() - t0 < ms) await new Promise(r => setTimeout(r, 100)); return re.test(log); };
  1290. const got6 = await waitLog(/adult backfill: 6\/14 titles/, 30000);
  1291. const log1 = log;
  1292. await page.goto('about:blank'); // mission 056: a tab left on a page logs websocket reconnect errors while the server is down
  1293. await stopServer();
  1294. const asked1 = tmdb.requests.slice(bfReq).map(q => q.path).filter(p => /^\/3\/(movie|tv)\//.test(p));
  1295. check('backfill: started with the 14 unknown titles, logs every 3 (TRACKER_BACKFILL_LOG_EVERY), one details request per title (+ external_ids), with the token',
  1296. got6 && log1.includes('adult backfill: start, 14 titles without an adult flag') && /adult backfill: 3\/14 titles/.test(log1)
  1297. && asked1.every(p => p.endsWith('?append_to_response=external_ids')) && tmdb.requests.slice(bfReq).filter(q => q.path.startsWith('/3/')).every(q => q.authorization === 'Bearer gate-token'), log1.split('\n').filter(l => /backfill/.test(l)).join('\n'));
  1298. const bfReq2 = tmdb.requests.length;
  1299. await startServer({ TRACKER_BACKFILL: '1', TRACKER_BACKFILL_LOG_EVERY: '3' });
  1300. // the start line comes with the clock's first tick, which can be after the first page answer (mission 056: it was)
  1301. await waitLog(/adult backfill: start, \d+ titles/, 5000);
  1302. const left = Number((log.match(/adult backfill: start, (\d+) titles/) || [])[1]);
  1303. // pages DURING the run: signed out, the homepage, /movies and a search, back to back, timed
  1304. const during54 = [];
  1305. const t054 = Date.now();
  1306. while (!/adult backfill done/.test(log) && Date.now() - t054 < 60000) {
  1307. for (const p of ['/', '/movies', '/search/backfill']) { const t = Date.now(); await (await fetch(BASE + p)).text(); during54.push({ p, ms: Date.now() - t }); }
  1308. }
  1309. const bfSecs = (Date.now() - t054) / 1000;
  1310. const asked2 = tmdb.requests.slice(bfReq2).map(q => q.path).filter(p => /^\/3\/(movie|tv)\//.test(p));
  1311. const askedIds = [...asked1, ...asked2].map(p => p.match(/\/3\/(?:movie|tv)\/(\d+)/)[1]);
  1312. const twice = askedIds.filter((x, k) => askedIds.indexOf(x) !== k);
  1313. const doneLine = (log.match(/adult backfill done: .*/) || [''])[0];
  1314. console.log(` (backfill second start: ${left} titles left, ${bfSecs} s; ${during54.length} pages asked during it, slowest ${Math.max(0, ...during54.map(l => l.ms))} ms; ${doneLine})`);
  1315. check('backfill RESUMES after a restart: the second start finds only the titles still unknown (≤ 8 of 14), every one of the 14 was asked, none twice except at most the one cut off by the stop',
  1316. left >= 1 && left <= 8 && new Set(askedIds).size === 14 && twice.length <= 1 && asked1.length + asked2.length - twice.length === 14, JSON.stringify({ left, asked1, asked2, twice }));
  1317. check('backfill: done — it stops when nothing is unknown (the done line with its counts); the 404 (1120) was logged',
  1318. /^adult backfill done: \d+\/\d+ titles, adult=\d+ notAdult=\d+ unknown=\d+ posters=\d+ ids=\d+ requests=\d+ errors=\d+ retries=0 seconds=/.test(doneLine) && (log1 + log).includes('HTTP 404 for /movie/1120'), (log1 + log).split('\n').filter(l => /backfill/.test(l)).join('\n'));
  1319. check('backfill: pages stay fast during the run (300 ms per TMDB answer) — every page < 1.2 s, and pages were asked during it',
  1320. during54.length >= 6 && during54.every(l => l.ms < 1200), JSON.stringify(during54.filter(l => l.ms >= 500)));
  1321. // the lists updated AS the flags arrived (no restart since the run)
  1322. seen = { home: await namesIn('/'), shows: await namesIn('/shows') };
  1323. const mh2 = await allMoviesHtml();
  1324. seen.movies = ADULT_ALL.filter(t => mh2.includes(t));
  1325. check('backfill → the lists at once (no restart): /movies has Flagless Gate Movie + the 10 Backfill Movies (45 movies), NOT the adult ones or the 404; /shows and the homepage have Flagless Gate Series (+ the homepage Flagless Gate Movie)',
  1326. JSON.stringify(seen.movies) === JSON.stringify(['Flagless Gate Movie', 'Backfill Movie']) && mh2.includes('Backfill Movie 10') && mh2.includes('Backfill Movie 01') && mh2.includes('45 movies, newest first')
  1327. && JSON.stringify(seen.shows) === JSON.stringify(['Flagless Gate Series']) && JSON.stringify(seen.home) === JSON.stringify(['Flagless Gate Movie', 'Flagless Gate Series']), JSON.stringify(seen));
  1328. sr = await (await fetch(BASE + '/search/flagless')).text();
  1329. check('backfill → the search at once: "flagless" finds Flagless Gate Series + Flagless Gate Movie, not Flagless Adult Movie',
  1330. sr.includes('Flagless Gate Movie') && sr.includes('Flagless Gate Series') && !sr.includes('Flagless Adult Movie'), sr.slice(sr.indexOf('<search-page'), sr.indexOf('<search-page') + 900));
  1331. check('backfill: the ADULT title\'s poster is NOT downloaded (Flagless Adult Movie: asked, but no /t/p/w342/flag13.png request, no posters/admvfa.* file)',
  1332. !tmdb.requests.some(q => q.path.includes('flag13')) && !readdirSync(join(MPACKDB, 'posters')).some(f => f.startsWith('admvfa.')) && tmdb.requests.some(q => q.path.startsWith('/3/movie/1013?')),
  1333. (log1 + log).split('\n').filter(l => /backfill/.test(l)).join('\n'));
  1334. const pr = await fetch(BASE + '/posters/admvfl.png');
  1335. check('backfill: the poster was downloaded and is served (/posters/admvfl.png, image/png)', pr.status === 200 && pr.headers.get('content-type') === 'image/png' && existsSync(join(MPACKDB, 'posters', 'admvfl.png')));
  1336. // a third start: nothing unknown is left that TMDB can answer (the 404 is marked) → no request at all
  1337. await page.goto('about:blank'); // mission 056: a tab left on a page logs websocket reconnect errors while the server is down
  1338. await stopServer();
  1339. const bfReq3 = tmdb.requests.length;
  1340. tmdb.delayMs = 0;
  1341. await startServer({ TRACKER_BACKFILL: '1' });
  1342. await waitLog(/adult backfill: nothing to do/, 5000);
  1343. await new Promise(r => setTimeout(r, 500));
  1344. check('backfill: a restart afterwards has nothing to do (the 404 title is marked, not asked again) — no TMDB request',
  1345. log.includes('adult backfill: start, 0 titles') && log.includes('adult backfill: nothing to do') && tmdb.requests.length === bfReq3, log.split('\n').filter(l => /backfill/.test(l)).join('\n'));
  1346. check('adult: the server log has no error', !/error absorbed/i.test(log), log);
  1347. await page.goto(BASE + '/');
  1348. await hydrated();
  1349. if (process.env.TRACKER_GATE_SHOTS) writeFileSync(join(process.env.TRACKER_GATE_SHOTS, 'adult-home-1280.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  1350. // mission 056: alice UNFOLLOWS the adult movie on its page (a session face → hl:web's session sync re-derives `found` with
  1351. // the page's slug, hybriel#122): she no longer follows it → "Not found" at once, on a reload, and it leaves /my/movies
  1352. await page.goto(BASE + '/shows/adult-gate-movie');
  1353. await hydrated();
  1354. const adultBefore = await ev(`(document.querySelector('show-header h1') || {}).textContent + '|' + (document.querySelector('#follow') || {}).textContent`);
  1355. await page.click('#follow');
  1356. const adultGone = await page.waitFor(`(document.querySelector('show-page h1') || {}).textContent === 'Not found'`, { timeout: 5000, label: 'adult page hidden after unfollow' }).then(() => true, () => false);
  1357. const adultAfter = await ev(`(document.querySelector('show-page h1') || {}).textContent + '|' + ((document.querySelector('#follow') || {}).textContent || '')`);
  1358. await page.goto(BASE + '/shows/adult-gate-movie');
  1359. await hydrated();
  1360. const adultReload = await ev(`(document.querySelector('show-page h1') || {}).textContent`);
  1361. await page.goto(BASE + '/my/movies');
  1362. await hydrated();
  1363. const myMv2 = await ev(`Array.from(document.querySelectorAll('a.myshow-title')).map(a => a.textContent).join(',')`);
  1364. check('adult (056): alice sees the adult page while she follows it; after Unfollow ON the page it says "Not found" (no reload), on a reload too, and it is off her /my/movies',
  1365. adultBefore === 'Adult Gate Movie|Following' && adultGone && adultAfter === 'Not found|' && adultReload === 'Not found' && !myMv2.includes('Adult Gate Movie'), JSON.stringify({ adultBefore, adultAfter, adultReload, myMv2 }));
  1366. // and a normal show page still works after a session face (mission 054's failure: the browser re-derived `found` → `rows`)
  1367. await page.goto(BASE + '/shows/gate-test-show');
  1368. await hydrated();
  1369. const ep56 = await ev(`(() => { const b = document.querySelector('episode-row button.checkicon'); return b ? b.value + '|' + b.className : null; })()`);
  1370. await page.click('episode-row button.checkicon');
  1371. const ep56ok = await page.waitFor(`document.querySelector('episode-row button.checkicon').className !== ${JSON.stringify((ep56 || '|').split('|')[1])}`, { timeout: 5000, label: 'episode toggled (056)' }).then(() => true, () => false);
  1372. await page.click('episode-row button.checkicon');
  1373. const ep56back = await page.waitFor(`document.querySelector('episode-row button.checkicon').className === ${JSON.stringify((ep56 || '|').split('|')[1])}`, { timeout: 5000, label: 'episode toggled back (056)' }).then(() => true, () => false);
  1374. check('adult (056): on a normal show page an episode check toggles and toggles back (the session face + sync with the new `found`)', ep56 !== null && ep56ok && ep56back, ep56);
  1375. // ==== tracker.worldapi.org#16: PERSON PAGES — a complete person at once; an incomplete one fetches TMDB on the first visit
  1376. // ("Loading filmography…", filled without a reload, step by step), titles added once, adult hidden, the links, client-side
  1377. // navigation show → person → show → Back ====
  1378. const filmRows = () => ev(`JSON.stringify(Array.from(document.querySelectorAll('a.film-row')).map(a => [a.querySelector('film-title').textContent, a.querySelector('film-year').textContent, a.querySelector('film-type').textContent, a.querySelector('film-role').textContent, a.getAttribute('href')]))`).then(JSON.parse);
  1379. const personFacts = () => ev(`JSON.stringify({ h1: (document.querySelector('person-meta h1') || {}).textContent || null, facts: Array.from(document.querySelectorAll('person-fact')).map(f => f.textContent),
  1380. bio: (document.querySelector('person-bio') || {}).textContent || null, photo: (document.querySelector('person-photo img') || { getAttribute: () => null }).getAttribute('src'),
  1381. photoLoaded: !!(document.querySelector('person-photo img') && document.querySelector('person-photo img').complete && document.querySelector('person-photo img').naturalWidth > 0),
  1382. loading: !!document.querySelector('#personloading'), error: (document.querySelector('#fillerror') || {}).textContent || null })`).then(JSON.parse);
  1383. await page.goto(BASE + '/person/Complete-Person');
  1384. await hydrated();
  1385. await new Promise(r => setTimeout(r, 600));
  1386. let pf = await personFacts();
  1387. let fr = await filmRows();
  1388. check('person: a COMPLETE person shows at once — name, born/died, bio, the filmography newest first with roles and years; no loading, TMDB not asked',
  1389. pf.h1 === 'Complete Person' && JSON.stringify(pf.facts) === JSON.stringify(['Born 3 February 1950 in Gate City', 'Died 1 January 2020']) && pf.bio === 'A fixture person who is complete.'
  1390. && pf.photo === null && !pf.loading && JSON.stringify(fr) === JSON.stringify([['Gate Test Show', '2024', 'Series', 'Old Role', '/shows/gate-test-show'], ['Gate Test Movie', '1996', 'Movie', 'Movie Role', '/shows/gate-test-movie']])
  1391. && tmdb.personRequests.length === 0, JSON.stringify({ pf, fr, req: tmdb.personRequests }));
  1392. await page.goto(BASE + '/person/Nobody-Here');
  1393. await hydrated();
  1394. check('person: an unknown slug says "Not found"', (await ev(`document.querySelector('person-page h1').textContent`)) === 'Not found');
  1395. check('person: /profiles/<bad name> answers 400', (await fetch(BASE + '/profiles/..%2Fx')).status === 400 || (await fetch(BASE + '/profiles/a%20b')).status === 400);
  1396. // client-side: the show page's cast link → the person page (a window marker proves no reload); TMDB answers slowly (900 ms)
  1397. // so the loading state is seen; then it fills in by itself
  1398. tmdb.personDelayMs = 900;
  1399. await page.goto(BASE + '/shows/gate-test-show');
  1400. await hydrated();
  1401. await ev(`window.__w055 = 'same document'`);
  1402. const fillT0 = Date.now();
  1403. await page.click('a.artist-link[href="/person/Test-Actor"]');
  1404. await page.waitFor(`location.pathname === '/person/Test-Actor' && !!document.querySelector('person-meta h1')`, { timeout: 10000, label: 'person page after the cast click' });
  1405. pf = await personFacts();
  1406. const rowsBefore = (await filmRows()).length;
  1407. // meanwhile another request: answered while the fill runs (the fetch steps yield)
  1408. check('person: first visit (client-side from the cast link) shows "Loading filmography…" and no rows yet',
  1409. pf.h1 === 'Test Actor' && pf.loading && (await ev(`document.querySelector('#personloading').textContent`)).startsWith('Loading filmography') && rowsBefore === 0, JSON.stringify({ pf, rowsBefore }));
  1410. await page.waitFor(`!document.querySelector('#personloading') && document.querySelectorAll('a.film-row').length > 0`, { timeout: 20000, label: 'filmography filled in' });
  1411. const fillMs = Date.now() - fillT0;
  1412. await page.waitFor(`document.querySelector('person-photo img') && document.querySelector('person-photo img').complete`, { timeout: 5000, label: 'photo' }).catch(() => {});
  1413. pf = await personFacts();
  1414. fr = await filmRows();
  1415. const marker16 = await ev('window.__w055 || null');
  1416. check('person: the filmography filled in WITHOUT a reload (same document) — facts and the photo from TMDB too',
  1417. marker16 === 'same document' && !pf.loading && pf.error === null && JSON.stringify(pf.facts) === JSON.stringify(['Born 6 May 1970 in Fixture Town']) && pf.bio === 'Test Actor bio from TMDB.'
  1418. && pf.photo === '/profiles/p1.png' && pf.photoLoaded, JSON.stringify({ marker16, pf, fillMs }));
  1419. const bio0 = await ev(`document.querySelector('person-bio').className`);
  1420. await page.click('person-bio');
  1421. await page.waitFor(`document.querySelector('person-bio').className === 'full'`, { timeout: 5000, label: 'bio open' }).catch(() => {});
  1422. const bio1 = await ev(`document.querySelector('person-bio').className + '|' + getComputedStyle(document.querySelector('person-bio')).webkitLineClamp`);
  1423. check('person: the bio is SHORT (four lines) until clicked, then whole', bio0 === 'short' && bio1 === 'full|none', bio0 + ' → ' + bio1);
  1424. const titles16 = fr.map(r => r[0]);
  1425. check('person: 86 rows (87 TMDB titles − the adult one), newest first, undated last; roles of cast + crew merged; the adult title hidden',
  1426. fr.length === 86 && JSON.stringify(fr.slice(0, 4)) === JSON.stringify([['Gate Test Show', '2024', 'Series', 'Someone', '/shows/gate-test-show'], ['Directed Only', '2018', 'Movie', 'Writer', '/shows/Directed-Only'],
  1427. ['Person Series', '2015', 'Series', 'Lead', '/shows/Person-Series'], ['Person Film One', '2010', 'Movie', 'Hero / Director', '/shows/Person-Film-One']])
  1428. && titles16[4] === 'Bulk Film 01' && titles16[83] === 'Bulk Film 80' && JSON.stringify(fr[84]) === JSON.stringify(['Gate Test Movie', '1996', 'Movie', 'Cameo', '/shows/gate-test-movie'])
  1429. && JSON.stringify(fr[85]) === JSON.stringify(['Announced Film', '', 'Movie', 'Villain', '/shows/Announced-Film']) && !titles16.includes('Hidden Adult Film'), JSON.stringify(fr.slice(0, 6)) + ' … ' + JSON.stringify(fr.slice(-3)));
  1430. const posters16 = JSON.parse(await ev(`JSON.stringify(Array.from(document.querySelectorAll('a.film-row img.film-poster')).slice(0, 4).map(i => i.getAttribute('src')))`));
  1431. check('person: posters — our file when we have one (show 1), else TMDB\'s small one (w92), else the placeholder',
  1432. posters16[0] === '/posters/sh1.png' && posters16[1] === '/posters/none' && posters16[3] === tmdb.base + '/t/p/w92/pf1.png', JSON.stringify(posters16));
  1433. const pr16 = tmdb.personRequests.map(q => q.path);
  1434. const fillLines = log.split('\n').filter(l => l.startsWith('person fill: '));
  1435. check('person: ONE TMDB request (person + combined_credits, Bearer token) + the photo (w185); the fill ran in 4 steps (TMDB, then 3 × 40 titles) and added 85 titles (2 existed)',
  1436. JSON.stringify(pr16) === JSON.stringify(['/3/person/3002?append_to_response=combined_credits', '/t/p/w185/face2.png']) && tmdb.personRequests[0].authorization === 'Bearer gate-token'
  1437. && fillLines.length === 1 && /^person fill: Test Actor \(tmdb 3002\) credits=87 added=85 requests=2 steps=4 /.test(fillLines[0]), JSON.stringify({ pr16, fillLines }));
  1438. tmdb.personDelayMs = 0;
  1439. // the links: a row → its show page (client-side); Back → the person page, complete now (no loading)
  1440. await page.click('a.film-row[href="/shows/gate-test-show"]');
  1441. await page.waitFor(`location.pathname === '/shows/gate-test-show' && !!document.querySelector('show-header h1')`, { timeout: 10000, label: 'show page from the filmography' });
  1442. const back1 = await ev(`document.querySelector('show-header h1').textContent + '|' + (window.__w055 || '')`);
  1443. await ev('history.back()');
  1444. await page.waitFor(`location.pathname === '/person/Test-Actor' && document.querySelectorAll('a.film-row').length === 86`, { timeout: 10000, label: 'Back to the person' });
  1445. pf = await personFacts();
  1446. check('person: a filmography row → the show page (client-side), Back → the person page, filled, no loading again',
  1447. back1 === 'Gate Test Show|same document' && !pf.loading && (await ev('window.__w055 || null')) === 'same document', JSON.stringify({ back1, pf }));
  1448. // ==== tracker.worldapi.org#26: a title the fill added is MINIMAL — opening it shows what it has + skeletons and completes it
  1449. // without a reload (face showComplete held back 1.5 s so the skeleton state is seen) ====
  1450. const titleParts = () => ev(`JSON.stringify({ h1: (document.querySelector('show-header h1') || {}).textContent || null, summary: (document.querySelector('show-summary') || {}).textContent || null,
  1451. loading: !!document.querySelector('#showloading'), skPoster: !!document.querySelector('skeleton-poster'), skCast: !!document.querySelector('skeleton-cast'),
  1452. skRows: document.querySelectorAll('show-loading skeleton-row').length, poster: (document.querySelector('show-poster img') || { getAttribute: () => null }).getAttribute('src'),
  1453. posterLoaded: !!(document.querySelector('show-poster img') && document.querySelector('show-poster img').complete && document.querySelector('show-poster img').naturalWidth > 0),
  1454. genres: Array.from(document.querySelectorAll('a.genre-pill')).map(a => a.textContent).join(','), cast: Array.from(document.querySelectorAll('a.artist-link')).map(a => a.textContent + ' ' + a.getAttribute('href')).join(','),
  1455. seasons: Array.from(document.querySelectorAll('season-row')).map(r => r.querySelector('season-label').textContent + ': ' + r.querySelector('season-count').textContent),
  1456. episodes: Array.from(document.querySelectorAll('episode-row')).map(r => r.querySelector('episode-number').textContent + ' ' + r.querySelector('episode-title').textContent), marker: window.__w055 || null })`).then(JSON.parse);
  1457. const asked = (re) => tmdb.requests.filter(q => re.test(q.path)).map(q => q.path);
  1458. const sentBefore26 = (await page.wsSent()).length;
  1459. await ev(`window.__delayFace = { name: 'showComplete', ms: 1500 }`);
  1460. await page.click('a.film-row[href="/shows/Person-Film-One"]');
  1461. await page.waitFor(`location.pathname === '/shows/Person-Film-One' && !!document.querySelector('show-header h1')`, { timeout: 10000, label: 'new title page' });
  1462. let tp = await titleParts();
  1463. check('#26: a title the fill added opens (client-side) with what it has — title, the credit\'s overview, TMDB link, genre Drama, Test Actor — plus the skeleton (poster, cast line; a movie: no season rows); TMDB not asked yet',
  1464. tp.h1 === 'Person Film One' && tp.summary === 'a film of the person' && tp.loading && tp.skPoster && tp.skCast && tp.skRows === 0 && tp.poster === null && tp.genres === 'Drama'
  1465. && tp.cast === 'Test Actor /person/Test-Actor' && linksAre(await extLinks(), [['TMDB', TMDB_MOVIE + '2001']]) && asked(/\/3\/movie\/2001/).length === 0 && tp.marker === 'same document', JSON.stringify(tp));
  1466. if (process.env.TRACKER_GATE_SHOTS) writeFileSync(join(process.env.TRACKER_GATE_SHOTS, 'title-skeleton-1280.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  1467. await page.waitFor(`!document.querySelector('#showloading')`, { timeout: 15000, label: 'title complete' });
  1468. await page.waitFor(`document.querySelector('show-poster img') && document.querySelector('show-poster img').complete`, { timeout: 5000, label: 'poster' }).catch(() => {});
  1469. await ev(`window.__delayFace = null`);
  1470. tp = await titleParts();
  1471. lk = await extLinks();
  1472. // (tracker#18: `summary` is the creator's own text — the fill and the completion write tmdbSummary only, so the page shows
  1473. // TMDB's details overview now, not the filmography credit's)
  1474. check('#26: … then complete WITHOUT a reload: poster (downloaded), TMDB + IMDb links, both genres, TMDB\'s overview (#18), cast = Test Actor (linked, no duplicate) + New Cast Member (a new person) — the adult performer left out; skeletons gone',
  1475. tp.marker === 'same document' && !tp.loading && !tp.skPoster && !tp.skCast && tp.poster === '/posters/tmdb-movie-2001.png' && tp.posterLoaded && tp.summary === 'TMDB overview of the film'
  1476. && linksAre(lk, [['TMDB', TMDB_MOVIE + '2001'], ['IMDb', IMDB + 'tt0002001/']]) && tp.genres === 'Drama'
  1477. && tp.cast === 'Test Actor /person/Test-Actor,New Cast Member /person/New-Cast-Member', JSON.stringify(tp) + lk);
  1478. cr = await credits();
  1479. check('#28: the completed title also shows its crew at once (Directed by Test Actor), no toggle', JSON.stringify(cr.crewSeen) === JSON.stringify(['[Directed by]', 'Test Actor']) && cr.castToggle === null, JSON.stringify(cr));
  1480. const sent26 = (await page.wsSent()).slice(sentBefore26).filter(f => /showComplete/.test(f));
  1481. check('#26: ONE TMDB details request (external_ids + credits, Bearer token) + the poster; the face showComplete sent once; the log line',
  1482. JSON.stringify(asked(/\/(movie\/2001|w342\/pf1)/)) === JSON.stringify(['/3/movie/2001?append_to_response=external_ids,credits', '/t/p/w342/pf1.png'])
  1483. && tmdb.requests.filter(q => q.path.startsWith('/3/movie/2001')).every(q => q.authorization === 'Bearer gate-token') && sent26.length === 1
  1484. && /details on open: "Person Film One" steps=1 requests=2 tvmazeRequests=0 cast=2 newSeasons=0 newEpisodes=0 posters=1 ids=1 /.test(log), JSON.stringify({ a: asked(/2001|pf1/), sent26 }) + log.split('\n').filter(l => /details/.test(l)).join('\n'));
  1485. await page.goto(BASE + '/shows/Person-Film-One');
  1486. await hydrated();
  1487. await new Promise(r => setTimeout(r, 500));
  1488. const tpReload = await titleParts();
  1489. check('#26: a reload is complete at once (no skeleton, same parts; Drama only — our genres have no Comedy), TMDB not asked again',
  1490. !tpReload.loading && tpReload.poster === tp.poster && tpReload.cast === tp.cast && tpReload.genres === tp.genres && asked(/\/3\/movie\/2001/).length === 1, JSON.stringify(tpReload));
  1491. await page.click('a.artist-link[href="/person/New-Cast-Member"]');
  1492. await page.waitFor(`location.pathname === '/person/New-Cast-Member' && !!document.querySelector('person-meta h1') && !document.querySelector('#personloading')`, { timeout: 10000, label: 'new person' });
  1493. check('#26: the new cast member has a person page (its slug works at once), filled from TMDB like any other: Person Film One, role Partner',
  1494. (await ev(`document.querySelector('person-meta h1').textContent`)) === 'New Cast Member' && JSON.stringify(await filmRows()) === JSON.stringify([['Person Film One', '2010', 'Movie', 'Partner', '/shows/Person-Film-One']]), JSON.stringify(await filmRows()));
  1495. // a SERIES: skeleton season rows, then its season + episodes (TMDB 2 + TVmaze 1), all four links, cast from aggregate_credits
  1496. await page.goto(BASE + '/person/Test-Actor');
  1497. await hydrated();
  1498. await ev(`window.__w055 = 'same document'`);
  1499. await ev(`window.__delayFace = { name: 'showComplete', ms: 1500 }`);
  1500. await page.click('a.film-row[href="/shows/Person-Series"]');
  1501. await page.waitFor(`location.pathname === '/shows/Person-Series' && !!document.querySelector('show-header h1')`, { timeout: 10000, label: 'series page' });
  1502. tp = await titleParts();
  1503. check('#26: an incomplete SERIES opens with 3 skeleton season rows, no seasons yet', tp.h1 === 'Person Series' && tp.loading && tp.skRows === 3 && tp.seasons.length === 0, JSON.stringify(tp));
  1504. if (process.env.TRACKER_GATE_SHOTS) writeFileSync(join(process.env.TRACKER_GATE_SHOTS, 'series-skeleton-1280.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  1505. await page.waitFor(`!document.querySelector('#showloading')`, { timeout: 15000, label: 'series complete' });
  1506. await ev(`window.__delayFace = null`);
  1507. await page.waitFor(`document.querySelector('show-poster img') && document.querySelector('show-poster img').complete`, { timeout: 5000, label: 'poster' }).catch(() => {});
  1508. tp = await titleParts();
  1509. lk = await extLinks();
  1510. const sentSeries = (await page.wsSent()).filter(f => /showComplete/.test(f)).length; // (wsSent: since this document's load)
  1511. check('#26: … complete without a reload: Season 2 (open) + Season 1 with 3 episodes (2 TMDB + 1 TVmaze, as the daily sync merges), TMDB/IMDb/TVDB/TVmaze links, poster, cast Test Actor + Series Newcomer',
  1512. tp.marker === 'same document' && !tp.loading && JSON.stringify(tp.seasons) === JSON.stringify(['Season 2: 1 episode', 'Season 1: 3 episodes']) && JSON.stringify(tp.episodes) === JSON.stringify(['1 Second Season Start'])
  1513. && linksAre(lk, [['TMDB', TMDB_TV + '2002'], ['IMDb', IMDB + 'tt0002002/'], ['TVDB', TVDB + '4202'], ['TVmaze', TVMAZE + '602']]) && tp.poster === '/posters/tmdb-tv-2002.png' && tp.posterLoaded
  1514. && tp.cast === 'Test Actor /person/Test-Actor,Series Newcomer /person/Series-Newcomer', JSON.stringify(tp) + lk);
  1515. check('#26: a series is completed in STEPS (one face call each; TRACKER_DETAILS_PART_EPISODES=1 → a season per step): details, season 1, season 2, the rest (ids, TVmaze, poster) = 4 calls, ONE season request each',
  1516. sentSeries === 4 && /details on open: "Person Series" steps=4 requests=4 tvmazeRequests=2 cast=2 newSeasons=2 newEpisodes=4 posters=1 ids=3 /.test(log)
  1517. && JSON.stringify(asked(/\/3\/tv\/2002/)) === JSON.stringify(['/3/tv/2002?append_to_response=external_ids,aggregate_credits', '/3/tv/2002?append_to_response=season/1', '/3/tv/2002?append_to_response=season/2']),
  1518. JSON.stringify({ sentSeries, asked: asked(/2002/) }) + log.split('\n').filter(l => /details on open/.test(l)).join('\n'));
  1519. await page.click('season-row:nth-of-type(2) button.season-toggle');
  1520. await page.waitFor(`document.querySelectorAll('episode-row').length === 4 && !document.querySelector('skeleton-row')`, { timeout: 5000, label: 'season 1 open' }).catch(() => {});
  1521. const open26 = (await titleParts()).episodes;
  1522. await page.click('season-row:nth-of-type(2) button.season-toggle');
  1523. await page.waitFor(`document.querySelectorAll('episode-row').length === 1`, { timeout: 5000, label: 'season 1 closed' }).catch(() => {});
  1524. check('#26: the completed series\' season 1 opens (showSeasonEpisodes: its 3 episodes, each once) and closes again', JSON.stringify(open26) === JSON.stringify(['1 Second Season Start', '1 Series Pilot', '2 Series Second', '3 Only On TVmaze'])
  1525. && (await titleParts()).episodes.length === 1, JSON.stringify(open26));
  1526. await page.goto(BASE + '/search/series%20newcomer');
  1527. await hydrated();
  1528. check('#26: the search finds the new cast member', (await ev(`Array.from(document.querySelectorAll('a.search-person')).map(a => a.textContent).join(',')`)) === 'Series Newcomer',
  1529. await ev(`document.querySelector('search-page').textContent.slice(0, 300)`));
  1530. // second visit (full load): complete — TMDB not asked again, nothing added, same rows
  1531. await page.goto(BASE + '/person/Test-Actor');
  1532. await hydrated();
  1533. await new Promise(r => setTimeout(r, 700));
  1534. pf = await personFacts();
  1535. check('person: a SECOND visit is complete at once — no loading, the same 86 rows, TMDB not asked again, no second fill',
  1536. // (#26: + New Cast Member's one request, made above)
  1537. !pf.loading && (await filmRows()).length === 86 && tmdb.personRequests.filter(q => q.path.startsWith('/3/person/3002')).length === 1 && log.split('\n').filter(l => l.startsWith('person fill: Test Actor')).length === 1, JSON.stringify({ pf, req: tmdb.personRequests.length }));
  1538. // another person whose credits we have by now: linked, nothing added (no duplicate titles)
  1539. await page.goto(BASE + '/person/Second-Actor');
  1540. await hydrated();
  1541. await page.waitFor(`!document.querySelector('#personloading')`, { timeout: 15000, label: 'second actor filled' });
  1542. fr = await filmRows();
  1543. const second = log.split('\n').filter(l => l.startsWith('person fill: Second Actor'));
  1544. check('person: a second person with titles we have — linked, added=0, no photo; the title OUR record marks adult hidden though the credit is not',
  1545. JSON.stringify(fr) === JSON.stringify([['Gate Test Show', '2024', 'Series', 'Guest', '/shows/gate-test-show'], ['Person Film One', '2010', 'Movie', 'Sidekick', '/shows/Person-Film-One']])
  1546. && second.length === 1 && / added=0 requests=1 /.test(second[0]) && (await personFacts()).photo === null, JSON.stringify({ fr, second }));
  1547. await page.goto(BASE + '/search/person%20film');
  1548. await hydrated();
  1549. check('person: the search finds the added title once', (await ev(`Array.from(document.querySelectorAll('a.search-title')).filter(a => a.textContent === 'Person Film One (2010)').length`)) === 1);
  1550. check('person: the server log has no error', !/error absorbed|not stored/i.test(log), log.split('\n').filter(l => /person|error/i.test(l)).join('\n'));
  1551. for (const [w, h, mobile] of [[390, 844, true], [1280, 900, false]]) {
  1552. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: mobile ? 2 : 1, mobile });
  1553. for (const [name, path] of [['person', '/person/Test-Actor'], ['person-complete', '/person/Complete-Person']]) {
  1554. await page.goto(BASE + path);
  1555. await hydrated();
  1556. await page.waitFor(`Array.from(document.querySelectorAll('img')).filter(i => i.getBoundingClientRect().top < innerHeight).every(i => i.complete)`, { timeout: 5000 }).catch(() => {});
  1557. check(`person: ${path} at ${w} px — no sideways scroll, header one row`, (await ev('document.documentElement.scrollWidth')) <= w && (await ev(`document.querySelector('application-header').getBoundingClientRect().height`)) <= 64);
  1558. if (process.env.TRACKER_GATE_SHOTS) writeFileSync(join(process.env.TRACKER_GATE_SHOTS, `${name}-${w}.png`), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  1559. }
  1560. }
  1561. await page.send('Emulation.clearDeviceMetricsOverride', {});
  1562. // ==== tracker.worldapi.org#26: THE DETAILS REPAIR — the titles Test Actor's fill added and nobody opened (Directed Only,
  1563. // Announced Film, Bulk Film 01–80 = 82; the adult one is left alone) are completed by a background job: one per step, resumes
  1564. // after a restart, pages stay fast; TMDB 404 (Bulk Film 79/80) marks the title, it is not asked again ====
  1565. await page.goto('about:blank');
  1566. await stopServer();
  1567. tmdb.delayMs = 60;
  1568. const repairAsked = () => tmdb.requests.filter(q => /^\/3\/movie\/(2004|2005|21\d\d)\?/.test(q.path)).map(q => q.path.split('?')[0]);
  1569. await startServer({ TRACKER_REPAIR: '1', TRACKER_REPAIR_FAST: '1', TRACKER_REPAIR_LOG_EVERY: '3' });
  1570. for (let i = 0; i < 200 && !log.includes('details repair: 6/'); i++) await new Promise(r => setTimeout(r, 50));
  1571. const run1Log = log;
  1572. await stopServer();
  1573. const run1Asked = repairAsked();
  1574. check('repair: starts with the 82 incomplete titles (not the adult one, not the 2 opened ones), logs every 3, one details request per title (+ external_ids + credits) with the token',
  1575. /details repair: start, 82 incomplete titles/.test(run1Log) && run1Log.includes('details repair: 6/82 titles') && run1Asked.length >= 6 && run1Asked.length < 82
  1576. && tmdb.requests.filter(q => /^\/3\/movie\/21\d\d\?/.test(q.path)).every(q => q.path.endsWith('?append_to_response=external_ids,credits') && q.authorization === 'Bearer gate-token'),
  1577. run1Log.split('\n').filter(l => /repair/.test(l)).join('\n') + JSON.stringify(run1Asked));
  1578. await startServer({ TRACKER_REPAIR: '1', TRACKER_REPAIR_FAST: '1', TRACKER_REPAIR_LOG_EVERY: '3' });
  1579. for (let i = 0; i < 100 && !/details repair: start/.test(log); i++) await new Promise(r => setTimeout(r, 50));
  1580. const left26 = Number((log.match(/details repair: start, (\d+) incomplete/) || [])[1]);
  1581. const lat26 = [];
  1582. for (let i = 0; i < 600 && !log.includes('details repair done'); i++) { const t = Date.now(); await fetch(BASE + '/movies'); lat26.push(Date.now() - t); await new Promise(r => setTimeout(r, 100)); }
  1583. const allAsked = repairAsked();
  1584. const distinct = new Set(allAsked);
  1585. const repairLine26 = (log.match(/details repair done: .*/) || [''])[0];
  1586. check('repair: after a restart it RESUMES — only what is left (< 82, ≥ 82 − titles asked before), every one of the 82 asked, at most one twice (the step the stop cut off)',
  1587. left26 > 0 && left26 < 82 && left26 >= 82 - run1Asked.length && distinct.size === 82 && allAsked.length <= 83, JSON.stringify({ left26, run1: run1Asked.length, all: allAsked.length, distinct: distinct.size }));
  1588. check('repair: done — Bulk Film 79/80 failed (TMDB 404), the rest complete, posters downloaded, cast linked',
  1589. new RegExp(`details repair done: ${left26}/${left26} titles, complete=${left26 - 2} failed=2 adult=0 newSeasons=0 newEpisodes=0 posters=${left26 - 2} cast=`).test(repairLine26)
  1590. && log.includes('details repair: Bulk Film 80: HTTP 404 for /movie/2180'), repairLine26 + '\n' + log.split('\n').filter(l => /repair/.test(l)).slice(-6).join('\n'));
  1591. check('repair: pages stay fast meanwhile (/movies every 100 ms: max < 1.2 s)', lat26.length > 3 && Math.max(...lat26) < 1200, JSON.stringify({ n: lat26.length, max: Math.max(...lat26) }));
  1592. check('repair: the adult title is never asked', asked(/\/3\/movie\/2003/).length === 0);
  1593. await page.goto(BASE + '/shows/Bulk-Film-05');
  1594. await hydrated();
  1595. await page.waitFor(`document.querySelector('show-poster img') && document.querySelector('show-poster img').complete`, { timeout: 5000, label: 'poster' }).catch(() => {});
  1596. tp = await titleParts();
  1597. lk = await extLinks();
  1598. check('repair: a repaired title opens complete (no skeleton): poster, IMDb link, cast', !tp.loading && tp.poster === '/posters/tmdb-movie-2105.png' && tp.posterLoaded
  1599. && linksAre(lk, [['TMDB', TMDB_MOVIE + '2105'], ['IMDb', IMDB + 'tt002105/']]) && tp.cast === 'Test Actor /person/Test-Actor', JSON.stringify(tp) + lk);
  1600. await page.goto(BASE + '/shows/Bulk-Film-80');
  1601. await hydrated();
  1602. await new Promise(r => setTimeout(r, 400));
  1603. tp = await titleParts();
  1604. check('repair: a title TMDB does not know (404) opens as it is, no skeleton, not asked again', tp.h1 === 'Bulk Film 80' && !tp.loading && asked(/\/3\/movie\/2180/).length === 1, JSON.stringify(tp));
  1605. await page.goto('about:blank');
  1606. await stopServer();
  1607. await startServer({ TRACKER_REPAIR: '1', TRACKER_REPAIR_FAST: '1' });
  1608. for (let i = 0; i < 100 && !/details repair: (nothing|start)/.test(log); i++) await new Promise(r => setTimeout(r, 50));
  1609. check('repair: a third start has nothing to do', log.includes('details repair: start, 0 incomplete titles') && log.includes('details repair: nothing to do'), log.split('\n').filter(l => /repair/.test(l)).join('\n'));
  1610. // ==== tracker.worldapi.org#28: THE CREDITS JOB — every public title without credits (here: the Backfill Movies, the flagless
  1611. // ones, … — not the ones the sync, an import or the repair already did, not adult/unknown ones) gets its cast + crew: one
  1612. // request per title, resumes after a restart, pages stay fast; TMDB 404 marks the title (not asked again) ====
  1613. await page.goto('about:blank');
  1614. await stopServer();
  1615. const creditsAsked = () => tmdb.requests.filter(q => /\?append_to_response=(credits|aggregate_credits)$/.test(q.path)).map(q => q.path.split('?')[0]);
  1616. const credBefore = creditsAsked().length;
  1617. // the memory limit first: above TRACKER_CREDITS_MAX_MB the job pauses before its next title (here 1 MB → before the first)
  1618. await startServer({ TRACKER_CREDITS: '1', TRACKER_CREDITS_FAST: '1', TRACKER_CREDITS_MAX_MB: '1' });
  1619. for (let i = 0; i < 100 && !/credits job: (paused|nothing)/.test(log); i++) await new Promise(r => setTimeout(r, 50));
  1620. await new Promise(r => setTimeout(r, 300));
  1621. check('#28 credits job: above TRACKER_CREDITS_MAX_MB it pauses before the next title (logged with what is left), nothing asked',
  1622. /credits job: paused, RSS \d+ MB > TRACKER_CREDITS_MAX_MB 1 — \d+ titles left for the next start/.test(log) && creditsAsked().length === credBefore, log.split('\n').filter(l => /credits job/.test(l)).join('\n'));
  1623. await stopServer();
  1624. await startServer({ TRACKER_CREDITS: '1', TRACKER_CREDITS_FAST: '1', TRACKER_CREDITS_LOG_EVERY: '3' });
  1625. for (let i = 0; i < 200 && !log.includes('credits job: 6/'); i++) await new Promise(r => setTimeout(r, 50));
  1626. const cred1Log = log;
  1627. await stopServer();
  1628. const cred1 = creditsAsked().slice(credBefore);
  1629. const credTotal = Number((cred1Log.match(/credits job: start, (\d+) titles without credits/) || [])[1]);
  1630. check('#28 credits job: starts with the public titles that have no credits (Backfill Movie 01–10 among them, none the sync/import/repair did, no adult one), logs every 3, one request each (details + credits), the token',
  1631. credTotal >= 10 && cred1Log.includes('credits job: 6/' + credTotal + ' titles') && cred1.length >= 6 && cred1.length < credTotal
  1632. && !cred1.some(p => /\/(1001|1002|1003|1004|1005|2001|2002|2105|1011|1013|2003)$/.test(p)) && tmdb.requests.filter(q => /append_to_response=(credits|aggregate_credits)$/.test(q.path)).every(q => q.authorization === 'Bearer gate-token'),
  1633. cred1Log.split('\n').filter(l => /credits job/.test(l)).join('\n') + JSON.stringify(cred1));
  1634. await startServer({ TRACKER_CREDITS: '1', TRACKER_CREDITS_FAST: '1', TRACKER_CREDITS_LOG_EVERY: '3' });
  1635. for (let i = 0; i < 100 && !/credits job: start/.test(log); i++) await new Promise(r => setTimeout(r, 50));
  1636. const credLeft = Number((log.match(/credits job: start, (\d+) titles without credits/) || [])[1]);
  1637. const lat28 = [];
  1638. for (let i = 0; i < 600 && !log.includes('credits job done'); i++) { const t = Date.now(); await fetch(BASE + '/movies'); lat28.push(Date.now() - t); await new Promise(r => setTimeout(r, 100)); }
  1639. const credAll = creditsAsked().slice(credBefore);
  1640. const credDone = (log.match(/credits job done: .*/) || [''])[0];
  1641. check('#28 credits job: after a restart it RESUMES — only what is left, every title asked, at most one twice (the step the stop cut off); done',
  1642. credLeft > 0 && credLeft < credTotal && credLeft >= credTotal - cred1.length && new Set(credAll).size === credTotal && credAll.length <= credTotal + 1
  1643. && new RegExp(`credits job done: ${credLeft}/${credLeft} titles, done=`).test(credDone), JSON.stringify({ credTotal, credLeft, run1: cred1.length, all: credAll.length, distinct: new Set(credAll).size, credDone }));
  1644. check('#28 credits job: pages stay fast meanwhile (/movies every 100 ms: max < 1.2 s)', lat28.length > 3 && Math.max(...lat28) < 1200, JSON.stringify({ n: lat28.length, max: Math.max(...lat28) }));
  1645. await page.goto(BASE + '/shows/backfill-movie-03');
  1646. await hydrated();
  1647. cr = await credits();
  1648. check('#28 credits job: a title it did shows its cast and crew (Backfill Cast as Role 3, Directed by Backfill Director)',
  1649. JSON.stringify(cr.cast) === JSON.stringify([['Backfill Cast', ' (Role 3)', '/person/Backfill-Cast']]) && JSON.stringify(cr.crewSeen) === JSON.stringify(['[Directed by]', 'Backfill Director']), JSON.stringify(cr));
  1650. await page.goto('about:blank');
  1651. await stopServer();
  1652. await startServer({ TRACKER_CREDITS: '1', TRACKER_CREDITS_FAST: '1' });
  1653. for (let i = 0; i < 100 && !/credits job: (nothing|start)/.test(log); i++) await new Promise(r => setTimeout(r, 50));
  1654. check('#28 credits job: a third start has nothing to do (404 titles marked, not asked again)', log.includes('credits job: start, 0 titles without credits') && log.includes('credits job: nothing to do'),
  1655. log.split('\n').filter(l => /credits job/.test(l)).join('\n'));
  1656. await page.goto('about:blank');
  1657. await stopServer();
  1658. tmdb.delayMs = 0;
  1659. await startServer();
  1660. // ==== tracker.worldapi.org#10: THE INSTALLABLE APP — hl:web's own manifest + service worker (project.hl appIcons /
  1661. // offline = [ Home ]). The manifest and every icon over HTTP; Chrome's own verdict (installability, manifest parse);
  1662. // the worker registered for the whole app; then OFFLINE: the tab loses the network (the note appears), the server
  1663. // is stopped too (CDP's offline emulation does not reach the service worker's own fetches — measured — so only a
  1664. // dead server proves the cache), and `/` still opens: header + the note. A data page gets hl:web's "Unavailable
  1665. // offline" page. A separate tab, so its expected socket errors stay out of the main tab's console check.
  1666. const html = await (await fetch(BASE + '/')).text();
  1667. const mhref = (html.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  1668. check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (the token `darker`)',
  1669. mhref === '/__hl/manifest.webmanifest' && html.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')
  1670. && html.includes('<link rel="icon" href="/icons/favicon.svg">') && html.includes('<meta name="theme-color" content="rgb(15, 20, 25)">'), html.slice(0, 900));
  1671. const mres = await fetch(BASE + mhref);
  1672. const man = await mres.json();
  1673. check('pwa: the manifest is served as application/manifest+json: name "tracker", start_url /, scope /, display standalone, the token colours',
  1674. /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'tracker' && man.short_name === 'tracker' && man.start_url === '/' && man.scope === '/'
  1675. && man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', JSON.stringify(man));
  1676. const iconOk = [];
  1677. for (const ic of man.icons || []) {
  1678. const ir = await fetch(BASE + ic.src);
  1679. const b = Buffer.from(await ir.arrayBuffer());
  1680. 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]));
  1681. }
  1682. check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',
  1683. 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));
  1684. const touch = await fetch(BASE + '/icons/apple-touch-icon.png');
  1685. const touchBytes = Buffer.from(await touch.arrayBuffer());
  1686. const fav = await fetch(BASE + '/icons/favicon.svg');
  1687. const favText = await fav.text();
  1688. const ico = await fetch(BASE + '/favicon.ico');
  1689. const icoBytes = Buffer.from(await ico.arrayBuffer());
  1690. check('pwa: apple-touch-icon is a 180×180 PNG, the favicon an SVG in tracker green, /favicon.ico a real icon file',
  1691. touch.ok && touchBytes.readUInt32BE(16) === 180 && fav.ok && /image\/svg\+xml/.test(fav.headers.get('content-type') || '') && favText.includes('#4ec9b0')
  1692. && ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);
  1693. await page.goto('about:blank'); // the server goes down below: the main tab must not sit on a page meanwhile
  1694. const app = await browser.newPage();
  1695. const aev = (e) => app.evaluate(e);
  1696. const appHydrated = () => app.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 15000, label: 'app tab hydrated' });
  1697. await app.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  1698. await app.goto(BASE + '/');
  1699. await appHydrated();
  1700. await app.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { timeout: 15000, label: 'service worker active' });
  1701. await app.waitFor(`!!navigator.serviceWorker.controller`, { timeout: 10000, label: 'page controlled by the worker' });
  1702. const inst = await app.send('Page.getInstallabilityErrors');
  1703. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, JSON.stringify(inst));
  1704. const am = await app.send('Page.getAppManifest');
  1705. check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, JSON.stringify(am.errors));
  1706. check('pwa: hl:web\'s service worker is registered for the whole app (scope /) and controls the page',
  1707. (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')));
  1708. check('pwa: online, no offline note', !(await aev(`!!document.querySelector('#offline')`)));
  1709. 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'));
  1710. await app.setOffline(true);
  1711. await app.waitFor(`!!document.querySelector('#offline')`, { timeout: 5000, label: 'offline note (live)' }).catch(() => {});
  1712. 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.');
  1713. await stopServer();
  1714. let down = false;
  1715. try { await fetch(BASE + '/'); } catch { down = true; }
  1716. await app.goto(BASE + '/');
  1717. await app.waitFor(`!!document.querySelector('#offline')`, { timeout: 8000, label: 'offline note after reload' }).catch(() => {});
  1718. // the Shows row: 3 fixture series + Gate Import Show (#14's import, in the lists at once since the #13/#14 merge)
  1719. const homeShows = await aev(`Array.from(document.querySelectorAll('#home-shows a.tile')).map(a => a.getAttribute('href')).join(',')`);
  1720. check('offline: with the server gone too, a reload of / still opens the shell from the worker\'s cache — header, brand, the note, the home (#13: its text and both rows — 5 shows since mission 054 added Flagless Gate Series, 6 since #26 completed Person Series: its episodes are released)',
  1721. down && (await aev(`document.querySelector('application-header .brand') ? document.querySelector('application-header .brand').textContent : ''`)) === 'tracker'
  1722. && (await aev(`!!document.querySelector('#offline')`)) && (await aev(`!!document.querySelector('home-intro') && document.querySelectorAll('#home-movies a.tile').length === 10`))
  1723. && homeShows.split(',').length === 6 && homeShows.includes('/shows/Person-Series')
  1724. && (await aev(`getComputedStyle(document.querySelector('application-header')).backgroundColor`)) === 'rgb(15, 20, 25)', 'server down: ' + down + ' ' + homeShows);
  1725. 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'));
  1726. await app.goto(BASE + '/my/shows');
  1727. 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');
  1728. await app.setOffline(false);
  1729. await startServer();
  1730. await app.goto(BASE + '/');
  1731. await appHydrated();
  1732. await app.waitFor(`!document.querySelector('#offline')`, { timeout: 5000, label: 'note gone' }).catch(() => {});
  1733. check('back online: / from the server again, no offline note', !(await aev(`!!document.querySelector('#offline')`)));
  1734. await app.close();
  1735. await page.goto(BASE + '/my/schedule');
  1736. await hydrated();
  1737. // ==== tracker.worldapi.org#18: THE DAILY RUN BY CHANGE LISTS — TMDB /tv/changes + /movie/changes (since the last run, paged)
  1738. // and TVmaze /updates/shows; only the changed titles of ours are synced, their RECORD too (title, overview, tagline …);
  1739. // `summary` (the creator's own text) is never written; after a gap > 14 days (or a failed change list) the full walk ====
  1740. await page.goto('about:blank');
  1741. await stopServer();
  1742. const dayAgo = (n) => new Date(Date.now() - n * 86400000).toISOString().slice(0, 10);
  1743. const STATE = join(MPACKDB, 'sync-state.txt');
  1744. const peek = (ids, extra = {}) => Object.fromEntries(execFileSync(join(APP, 'bin/hybriel'), ['tests/peek-shows.hl'], { cwd: APP, env: { ...process.env, TRACKER_STORAGE: MPACKDB, TRACKER_PEEK: ids, ...extra } }).toString()
  1745. .split('\n').filter(l => l.startsWith('peek ')).map(l => { const [id, title, summary, tmdbSummary, tvmazeSummary, tagline, tmdbSync] = l.slice(5).split('|'); return [id, { title, summary, tmdbSummary, tvmazeSummary, tagline, tmdbSync }]; }));
  1746. check('#18: the first in-app run above (no last run yet: the full walk) stored its day in sync-state.txt; the tool\'s full runs did not touch it',
  1747. existsSync(STATE) && readFileSync(STATE, 'utf8').trim() === dayAgo(0), existsSync(STATE) ? readFileSync(STATE, 'utf8') : 'no state file');
  1748. const before18 = peek('1001,1002,1003,1004,2002');
  1749. // TMDB: show 1001 renamed with a new overview + tagline, the movie renamed with a new overview — both followed; Person Series
  1750. // (2002, #26, nobody follows it) a NEW episode in its newest season 2 — all three in the change lists (2 ids per page → 2 pages
  1751. // each, among ids we don't have). Show 1002 renamed and 1004 a new overview, but in NO TMDB change list → must stay as they
  1752. // are. TVmaze's list: 501 (show 1001 again: once), 504 (= 1004: nobody follows it → TVmaze's list alone does not bring it) and
  1753. // one we don't have.
  1754. tmdb.shows[1001].name = 'Gate Test Show Renamed';
  1755. tmdb.shows[1001].overview = 'TMDB overview, rewritten';
  1756. tmdb.shows[1001].tagline = 'A new tagline.';
  1757. tmdb.movies[1003].title = 'Gate Test Movie Renamed';
  1758. tmdb.movies[1003].overview = 'Fresh TMDB overview of the movie';
  1759. tmdb.shows[1004].overview = 'an imported series, updated';
  1760. tmdb.shows[1002].name = 'Must Stay Unwatched Gate Show';
  1761. tmdb.shows[2002].seasons[1].episodes.push({ id: 9802, episode_number: 2, name: 'Second Season Two', air_date: '2016-04-11' });
  1762. tmdb.changes = { tv: [99001, 1001, 2002, 99002], movie: [99003, 1003, 99004] };
  1763. tmdb.changesPageSize = 2;
  1764. tmdb.tvmaze.updates = { 501: 1759300000, 504: 1759300000, 99999: 1759300000 };
  1765. writeFileSync(STATE, dayAgo(1));
  1766. let req18 = tmdb.requests.length, tvm18 = tmdb.tvmazeRequests.length;
  1767. const syncRun = async () => {
  1768. await startServer({ TRACKER_SYNC: '1', TRACKER_SYNC_HOUR: String(new Date().getUTCHours()) });
  1769. const t0 = Date.now();
  1770. while (!log.includes('tmdb sync done') && Date.now() - t0 < 30000) await new Promise(r => setTimeout(r, 100));
  1771. return (log.match(/tmdb sync done: .*/) || [''])[0];
  1772. };
  1773. let done18 = await syncRun();
  1774. const paths18 = tmdb.requests.slice(req18).map(q => q.path), tvmPaths18 = tmdb.tvmazeRequests.slice(tvm18);
  1775. const range = `start_date=${dayAgo(1)}&end_date=${dayAgo(0)}`;
  1776. check('#18 delta: the run asks the change lists since the stored day — /tv/changes 2 pages, /movie/changes 2 pages (the token), TVmaze /updates/shows?since=day — and finds 3 of our titles (2 followed)',
  1777. log.includes(`tmdb sync: start, changes since ${dayAgo(1)} (1 day)`) && log.includes('tmdb tv=4 movie=3 tvmaze(day)=3 → 3 of our titles (2 followed), changeRequests=4 tvmazeChangeRequests=1')
  1778. && JSON.stringify(paths18.filter(p => p.includes('/changes'))) === JSON.stringify([`/3/tv/changes?${range}&page=1`, `/3/tv/changes?${range}&page=2`, `/3/movie/changes?${range}&page=1`, `/3/movie/changes?${range}&page=2`])
  1779. && tmdb.requests.slice(req18).every(q => q.authorization === 'Bearer gate-token') && tvmPaths18[0] === '/tvmaze/updates/shows?since=day', log + JSON.stringify(paths18) + JSON.stringify(tvmPaths18));
  1780. check('#18 delta: ONLY the changed titles were synced — the followed 1001 (all its seasons + TVmaze 501) and movie 1003; Person Series (nobody follows it) LIGHT: details + only its newest season 2 (season 1 unchanged), no TVmaze; never 1002, never 1004 (only on TVmaze\'s list, unfollowed); 0 errors',
  1781. paths18.filter(p => !p.includes('/changes')).every(p => /^\/3\/(tv\/1001|tv\/2002|movie\/1003)\?/.test(p)) && paths18.includes('/3/tv/2002?append_to_response=external_ids,aggregate_credits')
  1782. && paths18.includes('/3/tv/2002?append_to_response=season/2') && paths18.filter(p => p.startsWith('/3/tv/2002')).length === 2 && paths18.some(p => p.startsWith('/3/movie/1003?'))
  1783. && paths18.includes('/3/tv/1001?append_to_response=season/1,season/2,season/3,season/4')
  1784. && !paths18.some(p => /\/100[24]\b/.test(p)) && JSON.stringify(tvmPaths18.slice(1)) === JSON.stringify(['/tvmaze/shows/501?embed=episodes'])
  1785. && done18.includes('mode=delta changeRequests=5 shows=3') && done18.includes('errors=0'), done18 + JSON.stringify(paths18) + JSON.stringify(tvmPaths18));
  1786. check('#18 delta: the finished run stored today as its day', readFileSync(STATE, 'utf8').trim() === dayAgo(0), readFileSync(STATE, 'utf8'));
  1787. // the pages: the renamed titles under their old address (slugs never change), the creator's own summary kept, the cleared
  1788. // copy now shows TMDB's current text; the title outside the change lists untouched
  1789. const header18 = async (path) => { await page.goto(BASE + path); await hydrated(); return ev(`(document.querySelector('show-header h1') || {}).textContent + ' | ' + (document.querySelector('show-summary') || {}).textContent`); };
  1790. const show18 = await header18('/shows/gate-test-show'), movie18 = await header18('/shows/gate-test-movie'), other18 = await header18('/shows/unwatched-gate-show'), imp18 = await header18('/shows/Gate-Import-Show');
  1791. check('#18 pages: show 1001 renamed ("Gate Test Show Renamed"), still the creator\'s own summary; the movie renamed with TMDB\'s fresh overview (its migrated copy was cleared); 1002 and 1004 untouched (old title / old overview)',
  1792. show18 === 'Gate Test Show Renamed | a fixture show for the gate' && movie18 === 'Gate Test Movie Renamed | Fresh TMDB overview of the movie'
  1793. && imp18 === 'Gate Import Show | an imported series' && other18 === 'Unwatched Gate Show | second', JSON.stringify([show18, movie18, imp18, other18]));
  1794. await page.goto(BASE + '/shows/Person-Series');
  1795. await hydrated();
  1796. const ps18 = await ev(`JSON.stringify(Array.from(document.querySelectorAll('season-row')).map(e => e.querySelector('season-label').textContent + ': ' + e.querySelector('season-count').textContent))`);
  1797. check('#18 pages: Person Series (nobody follows it) has the episode TMDB added to its newest season — Season 2: 2 episodes; Season 1 kept its 3 (2 TMDB + 1 TVmaze)',
  1798. ps18 === JSON.stringify(['Season 2: 2 episodes', 'Season 1: 3 episodes']), ps18);
  1799. if (process.env.TRACKER_GATE_SHOTS) {
  1800. for (const [name, path] of [['delta-show', '/shows/gate-test-show'], ['delta-movie', '/shows/gate-test-movie']]) {
  1801. await page.goto(BASE + path);
  1802. await hydrated();
  1803. writeFileSync(join(process.env.TRACKER_GATE_SHOTS, name + '-1280.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  1804. }
  1805. }
  1806. await page.goto(BASE + '/search/renamed');
  1807. await hydrated();
  1808. let st18 = await searchTitles();
  1809. check('#18 search: the renamed titles are found by their new name at once (no restart)',
  1810. st18 === JSON.stringify([['Gate Test Show Renamed (2024)', '/shows/gate-test-show', 'Series'], ['Gate Test Movie Renamed (1996)', '/shows/gate-test-movie', 'Movie']]), st18);
  1811. await page.goto('about:blank');
  1812. await stopServer();
  1813. const after18 = peek('1001,1002,1003,1004,2002');
  1814. check('#18 records: 1001 tmdbSummary + tagline from TMDB, summary still the creator\'s, tvmazeSummary = TVmaze\'s HTML stripped; the movie\'s summary empty (cleared copy), tmdbSummary new; 1002 and 1004 not written at all (same tmdbSync)',
  1815. after18['1001'].summary === 'a fixture show for the gate' && after18['1001'].tmdbSummary === 'TMDB overview, rewritten' && after18['1001'].tagline === 'A new tagline.'
  1816. && after18['1001'].tvmazeSummary === 'Gate Test Show on TVmaze & more.'
  1817. && after18['1003'].summary === '' && after18['1003'].tmdbSummary === 'Fresh TMDB overview of the movie'
  1818. && after18['1002'].tmdbSync === before18['1002'].tmdbSync && after18['1002'].title === 'Unwatched Gate Show' && after18['1004'].tmdbSync === before18['1004'].tmdbSync
  1819. && after18['1004'].tmdbSummary === 'an imported series' && after18['1001'].tmdbSync !== before18['1001'].tmdbSync && after18['2002'].tmdbSync !== before18['2002'].tmdbSync,
  1820. JSON.stringify({ before18, after18 }));
  1821. // a change list that fails → the old full walk, and the day stays (the next run asks for the missed days again)
  1822. tmdb.changesFail = true;
  1823. writeFileSync(STATE, dayAgo(1));
  1824. req18 = tmdb.requests.length;
  1825. done18 = await syncRun();
  1826. check('#18: a failing change list (TMDB 503) → the full walk of the 3 followed shows instead; the stored day is NOT advanced',
  1827. log.includes('tmdb sync: change list failed, full walk of 3 followed shows instead') && done18.includes('mode=full') && done18.includes('shows=3')
  1828. && readFileSync(STATE, 'utf8').trim() === dayAgo(1) && tmdb.requests.slice(req18).some(q => q.path.startsWith('/3/tv/1002?')), log);
  1829. await page.goto('about:blank');
  1830. await stopServer();
  1831. // more than 14 days since the last run: TMDB's change lists don't reach back that far → the full walk, no change list asked
  1832. tmdb.changesFail = false;
  1833. writeFileSync(STATE, dayAgo(20));
  1834. req18 = tmdb.requests.length;
  1835. done18 = await syncRun();
  1836. check('#18: last run 20 days ago (> 14) → the FULL WALK (3 followed shows, 1002 too), no change list asked; then today is stored',
  1837. log.includes(`tmdb sync: start, 3 followed shows, full walk (last run ${dayAgo(20)}, 20 days ago > 14)`) && done18.includes('mode=full changeRequests=0 shows=3') && done18.includes('errors=0')
  1838. && !tmdb.requests.slice(req18).some(q => q.path.includes('/changes')) && tmdb.requests.slice(req18).some(q => q.path.startsWith('/3/tv/1002?')) && readFileSync(STATE, 'utf8').trim() === dayAgo(0), log);
  1839. await page.goto('about:blank');
  1840. await stopServer();
  1841. // TVmaze's text shows when there is neither our own nor TMDB's (1002's two taken away for this check, the app not syncing)
  1842. const cleared18 = peek('1002', { TRACKER_CLEAR_TEXTS: '1002' });
  1843. await startServer();
  1844. const tvmPage18 = await header18('/shows/unwatched-gate-show');
  1845. check('#18: TVmaze\'s summary, HTML stripped (tags, entities, the line break), is what the page shows when there is no own and no TMDB summary',
  1846. cleared18['1002'].tvmazeSummary === 'Unwatched Gate Show, on TVmaze. Second "paragraph".' && cleared18['1002'].tmdbSummary === '' && cleared18['1002'].summary === ''
  1847. && tvmPage18 === 'Must Stay Unwatched Gate Show | Unwatched Gate Show, on TVmaze. Second "paragraph".', JSON.stringify(cleared18) + tvmPage18);
  1848. await page.goto(BASE + '/my/schedule');
  1849. await hydrated();
  1850. // ---- sign out: back to signed out, a reload confirms the app's own session (not just client state) ----
  1851. await page.click('#logout');
  1852. await page.waitForSelector('#loginbutton', { timeout: 15000 });
  1853. check('sign out returns to the signed-out header', (await ev(`!!document.querySelector('#loginbutton')`)) && !(await ev(`!!document.querySelector('#logout')`)));
  1854. await page.goto(BASE + '/');
  1855. await hydrated();
  1856. check('reload after sign-out stays signed out', (await ev(`!!document.querySelector('#loginbutton')`)) && !(await ev(`!!document.querySelector('#logout')`)));
  1857. const problems = page.problems();
  1858. check('no console errors/warnings', problems.length === 0, page.dumpConsole());
  1859. }
  1860. try {
  1861. await main();
  1862. } catch (e) {
  1863. check('gate ran without throwing', false, (e.stack || String(e)) + (globalThis.__gatePage ? '\nbrowser console:\n' + globalThis.__gatePage.dumpConsole() : '') + '\nserver log (tail):\n' + log.slice(-2000));
  1864. } finally {
  1865. await stop();
  1866. }
  1867. console.log(`\n${passes} passed, ${failures} failed`);
  1868. process.exit(failures === 0 ? 0 : 1);

Branches

Latest commits

  • f83571c3tracker#18 (mission 067): daily sync by change lists — TMDB /tv|movie/changes (since the stored day, paged) + TVmaze /updates/shows → only our changed titles (followed: full step, unfollowed: light step — changed seasons, no TVmaze), full walk on first run / gap > 14 days / failed list; show record refreshed (title, tmdbSummary, tagline, status, genres …; renamed titles re-indexed); summary = the creator's own text (page: summary > tmdbSummary > tvmazeSummary), one-time clear of copied summaries (9,647 on the live copy); gate 261, tests/realdata-018*.mjs, README + STATUSmre
  • 10bb3f93tracker#28 (mission 061): full cast (all seasons, main cast by episodes, guest stars) + crew (created by, directed by, written by, screenplay, story, music) — stored by the details completion, the daily sync, the search import (one details request) and a background credits job (resumes, RSS limit); show page collapsed after 20 with client-side Show all; showBySlug via a slug map; gate 249, tests/realdata-028.mjs, README + STATUSmre
  • 25a50bc4tracker#26 (mission 059): titles from a filmography are completed — on open (skeleton, step-wise face showComplete, no reload) and by the in-app details repair (resumes, TMDB-paced, series in parts); cast from TMDB credits; gate 231, tests/realdata-026.mjs, README + STATUSmre
  • 1704ec45tracker#17 (mission 057): season caret down/up, skeleton rows while a season loads, sessionless showSeasonEpisodes face (no page re-mount), client-only close; gate 214, tests/realdata-057.mjs, README + STATUSmre
  • f2fe3e36mission 056: README + STATUS (merge, fixes, Hybriel 8590df63, real-data check), tests/realdata-056.mjs, tools/check-public-slugs.hlmre
  • f40c250emission 056: re-vendor hybriel master 8590df63 (#121, #122); an adult title's page is Not found for non-followers; gate: leave the page before stopping the servermre
  • 2b7fdd6cmission 056: signed-out header one row on phones ("Log in", nowrap), backfill skips adult titles' posters, gate checksmre
  • 2c53d5efMerge branch 't16-person' (tracker#16 person pages) into main; filmography shows only public titles (054 adult flag), gate race fix (backfill start line)mre
  • c171227emission 054: hide adult/unknown titles from the public lists and the search; in-app adult-flag backfill (TMDB details + poster per title, resumes), gate + real-data proofmre
  • 139fafd8tracker#16: short bio (4 lines, click = all), real-data check script, README + STATUSmre
  • 93be9476tracker#16: person pages /person/<slug> with the filmography fetched from TMDB on the first visit (step by step), gatemre
  • 47a3cae6STATUS: mission 053 merge commit idsmre
  • dcc5eecaMerge branch 't14-search'mre
  • 03edc783Merge branch 't15-tvmaze'mre
  • 71b46345tracker#15: numbering check by date or title, placeholder titles in other languages, docs + real-data proofmre
  • 6bb2daf1tracker#13: homepage (tiles, intro, latest movies/shows), /shows, /movies/page/N, /my/movies; lists cached in memorymre
  • b8bd1157tracker#14: README + STATUS (search, real-data numbers, gate, merge notes)mre
  • 65c694a8tracker#14: search — header magnifier, /search/<text> (in-memory word-prefix index over titles + people), Fetch from web (TMDB search/multi, ours left out), Add = import via syncShow; gate +25 checks, real-data scriptmre
  • 34f2c15btracker#15: TVmaze merge in the sync (gaps only: new episodes/seasons, empty titles/air dates; numbering check), fake TVmaze episodes + gatemre
  • cbdc4ea7tracker#12: link icons TMDB/IMDb/TVDB/TVmaze; sync fills missing ids (TVmaze lookup); movies fetched via /movie/mre