// Page records' shots and images (release 37 S4), over the fake Wayback on // loopback (common/testing/web/fakeWayback.mjs): the records come from the // fake's own captures through the real extractors; the run's logic is driven // with a stub page, and the crop with a real headless Chromium (skipped, // saying why, on a host with no browser). No network. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/waybackPageCapture.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readdir, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { IMAGE_PNG, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL, PAGE_SPLIT_POSTS, PAGE_SPLIT_TS, PAGE_SPLIT_URL, startFakeWayback, } from "../testing/web/fakeWayback.mjs"; import type { Post } from "../lib/posts"; import { recordsOfCapture } from "../controller/importPage"; import type { StoredCapture } from "../lib/waybackPages/store-server"; import { WaybackClient } from "../lib/waybackClient"; import { waybackFileUrl, waybackFrameUrl } from "../lib/wayback"; import { captureWaybackPageRecords, openWaybackRenderPage, PAGE_MEDIA_MAX, pageItemTarget, pageRecordImages, shootPageRecord, type WaybackPageCaptureDeps, } from "./waybackPageCapture"; import { readPostCapture, SHOT_FILENAME } from "./postCapture"; import type { PageLike } from "./playwrightRuntime"; import { pngSize } from "../publish/citedPostCaptures"; async function recordsOf(fetchUrl: string, ts: string, original: string): Promise { const res = await fetch(fetchUrl); const body = Buffer.from(await res.arrayBuffer()); const capture = { originalUrl: original, captureTs: ts, mimetype: "text/html", contentType: "text/html; charset=utf-8" } as StoredCapture; return recordsOfCapture("pages", capture, body).posts; } async function fixtureRecords(base: string) { const article = await recordsOf(`${base}/web/${PAGE_ARTICLE_TS}id_/${PAGE_ARTICLE_URL}`, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL); const split = await recordsOf(`${base}/web/${PAGE_SPLIT_TS}id_/${PAGE_SPLIT_URL}`, PAGE_SPLIT_TS, PAGE_SPLIT_URL); return { article: article[0]!, split }; } test("what a record is shot as: the whole page, or its item's element", async () => { const wb = await startFakeWayback(); try { const { article, split } = await fixtureRecords(wb.base); assert.deepEqual(pageItemTarget(article), { scope: "page" }); assert.deepEqual(split.map((p) => p.id).sort(), PAGE_SPLIT_POSTS.map((id) => `tumblr-${id}`).sort()); const t = pageItemTarget(split[0]!); assert.equal(t.scope, "item"); if (t.scope === "item") { assert.equal(t.kind, "tumblr-post"); assert.ok(t.selectors.includes(`#post-${t.nativeId}`)); assert.ok(new RegExp(t.permalink!).test(`/post/${t.nativeId}/on-crusts`)); assert.ok(!new RegExp(t.permalink!).test(`/post/${t.nativeId}9`)); } const tweet = { id: "tweet-123456789012345678", page: { ...article.page!, kind: "tweet" as const } }; const tt = pageItemTarget(tweet); assert.equal(tt.scope, "item"); if (tt.scope === "item") assert.ok(tt.selectors[0]!.includes("123456789012345678")); assert.deepEqual(pageItemTarget({ id: "yt-about-UCx-2014", page: { ...article.page!, kind: "yt-about" } }), { scope: "page" }); assert.deepEqual(pageItemTarget({ id: "x" }), { scope: "page" }); } finally { await wb.close(); } }); test("a record's images go by their own Wayback URLs (im_), deduplicated and capped", () => { const page = { originalUrl: "https://a.example/", captureTs: "20140101000000", waybackUrl: "w", rawUrl: "r", kind: "generic" as const, extractor: "generic", extractorVersion: 1 }; const many = Array.from({ length: PAGE_MEDIA_MAX + 5 }, (_, n) => ({ kind: "image" as const, url: `https://a.example/${n}.jpg` })); const imgs = pageRecordImages({ page, media: [ { kind: "image", url: "https://web.archive.org/web/20130101000000im_/https://a.example/x.png" }, { kind: "image", url: "https://web.archive.org/web/20130101000000im_/https://a.example/x.png" }, { kind: "link-card", url: "https://a.example/card" }, ...many, ], }); assert.equal(imgs[0]!.url, "https://web.archive.org/web/20130101000000im_/https://a.example/x.png"); assert.equal(imgs[1]!.url, "https://web.archive.org/web/20140101000000im_/https://a.example/0.jpg"); assert.equal(imgs.length, PAGE_MEDIA_MAX); assert.equal(waybackFileUrl("2014", "https://web.archive.org/web/2012/https://b.example/i.gif"), "https://web.archive.org/web/2012im_/https://b.example/i.gif"); assert.equal(waybackFrameUrl({ captureTs: "2014", originalUrl: "https://b.example/" }), "https://web.archive.org/web/2014if_/https://b.example/"); }); // A page that answers without a browser: the item is found at a fixed box. function stubPage(o: { itemFound?: boolean; status?: number } = {}) { const visited: string[] = []; const clips: unknown[] = []; const page: PageLike = { goto: async (url: string) => { visited.push(url); return { status: () => o.status ?? 200 }; }, waitForSelector: async () => ({}), waitForTimeout: async () => {}, evaluate: async (fn: string) => { if (fn.includes("data-archilyzer-capture")) return o.itemFound === false ? null : { x: 190, y: 160, width: 534, height: 140 }; if (fn.includes("scrollHeight")) return { width: 1280, height: 9500 }; return 0; }, on: () => {}, screenshot: async (opts) => { clips.push(opts?.clip); return new Uint8Array(IMAGE_PNG); }, }; return { page, visited, clips }; } async function setup(stub = stubPage()) { const wb = await startFakeWayback(); const client = new WaybackClient({ fetch: (u, i) => wb.fetch(u, i), sleep: async () => {} }, { minGapMs: 0 }); const outDir = await mkdtemp(path.join(os.tmpdir(), "page-capture-")); let paced = 0; let opened = 0; const deps: WaybackPageCaptureDeps = { openPage: async () => { opened++; return { page: stub.page, close: async () => {} }; }, paced: (fn, signal) => { paced++; return client.paced(fn, { signal }); }, fetchFile: (url, signal) => client.getArchivedFile(url, { signal }), now: () => new Date("2026-10-20T12:00:00.000Z"), }; const { article, split } = await fixtureRecords(wb.base); const records = new Map([article, ...split].map((p) => [p.id, p])); return { wb, deps, outDir, records, article, split, stub, counts: () => ({ paced, opened }), close: async () => { await wb.close(); await rm(outDir, { recursive: true, force: true }); }, }; } test("a run: the whole page shot to the cap, the item clipped to its box, images saved; nothing said about the original", async () => { const s = await setup(); try { const crumb = s.split.find((p) => p.id === `tumblr-${PAGE_SPLIT_POSTS[1]}`)!; assert.ok(crumb.media?.length, "the second post carries its image"); const logs: string[] = []; const res = await captureWaybackPageRecords( { ids: [s.article.id, crumb.id], records: s.records, outDir: s.outDir, signal: new AbortController().signal, onLog: (l) => logs.push(l) }, s.deps, ); assert.equal(res.stoppedEarly, undefined); assert.deepEqual(res.outcomes.map((o) => o.state), ["captured", "captured"]); assert.ok(res.outcomes.every((o) => o.availability === undefined), "a capture says nothing about the original"); // Each page load inside the client's chain, the frame (`if_`) URL. assert.equal(s.counts().paced, 2); assert.equal(s.counts().opened, 1); assert.deepEqual(s.stub.visited, [waybackFrameUrl(s.article.page!), waybackFrameUrl(crumb.page!)]); // The whole page: cut at 8000 px; the item: its own box. assert.deepEqual(s.stub.clips[0], { x: 0, y: 0, width: 1280, height: 8000 }); assert.deepEqual(s.stub.clips[1], { x: 190, y: 160, width: 534, height: 140 }); const a = await readPostCapture(path.join(s.outDir, s.article.id)); assert.equal(a?.shotScope, "page"); assert.equal(a?.trimmed, true); assert.equal(a?.url, waybackFrameUrl(s.article.page!)); const c = await readPostCapture(path.join(s.outDir, crumb.id)); assert.equal(c?.shotScope, "item"); assert.equal(c?.mediaState, "ok"); assert.equal(c?.media.length, 1); assert.match(c!.media[0]!.url!, /\/web\/20120601000000im_\/http:\/\/24\.media\.tumblr\.com\//); assert.deepEqual((await readdir(path.join(s.outDir, crumb.id))).sort(), ["capture.json", "media-1.png", SHOT_FILENAME]); // The image went through the archive's own URL. assert.ok(s.wb.requests.some((r) => r.path.includes("im_/http://24.media.tumblr.com/"))); // A second run skips both; force shoots again. const again = await captureWaybackPageRecords( { ids: [s.article.id, crumb.id], records: s.records, outDir: s.outDir, signal: new AbortController().signal }, s.deps, ); assert.equal(again.outcomes.length, 0); assert.equal(s.counts().paced, 2); } finally { await s.close(); } }); test("an item the render cannot find is shot as the page; a 429 stops the run", async () => { const s = await setup(stubPage({ itemFound: false })); try { const ids = s.split.map((p) => p.id); const logs: string[] = []; const res = await captureWaybackPageRecords( { ids: [ids[0]!], records: s.records, outDir: s.outDir, media: false, signal: new AbortController().signal, onLog: (l) => logs.push(l) }, s.deps, ); assert.equal(res.outcomes[0]?.state, "captured"); assert.equal((await readPostCapture(path.join(s.outDir, ids[0]!)))?.shotScope, "page"); assert.ok(logs.some((l) => /was not found on the rendered page; shot the whole page/.test(l))); } finally { await s.close(); } const busy = await setup(stubPage({ status: 429 })); try { const ids = busy.split.map((p) => p.id); const res = await captureWaybackPageRecords( { ids, records: busy.records, outDir: busy.outDir, signal: new AbortController().signal }, busy.deps, ); assert.equal(res.outcomes.length, 1); assert.equal(res.outcomes[0]?.state, "error"); assert.match(res.stoppedEarly ?? "", /answered 429; stopping/); } finally { await busy.close(); } }); // ─── A real browser over the fake's captures ─── test("a real headless Chromium: the whole page, and one post clipped to its box", async (t) => { const wb = await startFakeWayback(); let opened; try { opened = await openWaybackRenderPage(wb.base); } catch (e) { await wb.close(); t.skip(`no headless Chromium on this host: ${(e as Error).message.split("\n")[0].slice(0, 120)}`); return; } const dir = await mkdtemp(path.join(os.tmpdir(), "page-shot-")); const client = new WaybackClient({ fetch: (u, i) => wb.fetch(u, i), sleep: async () => {} }, { minGapMs: 0 }); const paced: WaybackPageCaptureDeps["paced"] = (fn, signal) => client.paced(fn, { signal }); const load = (u: string) => u.replace("https://web.archive.org", wb.base); try { const { article, split } = await fixtureRecords(wb.base); const whole = await shootPageRecord(opened.page, { url: load(waybackFrameUrl(article.page!)), canonicalUrl: waybackFrameUrl(article.page!), target: pageItemTarget(article), dir: path.join(dir, "whole"), signal: new AbortController().signal, paced, }); assert.equal(whole.state, "captured", whole.error); assert.equal(whole.shotScope, "page"); const wsize = await pngSize(path.join(dir, "whole", SHOT_FILENAME)); assert.equal(wsize?.width, 1280); const post = split.find((p) => p.id === `tumblr-${PAGE_SPLIT_POSTS[0]}`)!; const item = await shootPageRecord(opened.page, { url: load(waybackFrameUrl(post.page!)), canonicalUrl: waybackFrameUrl(post.page!), target: pageItemTarget(post), dir: path.join(dir, "item"), signal: new AbortController().signal, paced, }); assert.equal(item.state, "captured", item.error); assert.equal(item.shotScope, "item"); const isize = await pngSize(path.join(dir, "item", SHOT_FILENAME)); // The post box is 500 px + padding + border wide: clipped to it, not the page. assert.ok(isize && isize.width > 500 && isize.width < 560, `width ${isize?.width}`); assert.ok(isize!.height < 400, `height ${isize?.height}`); // Nothing but the archive's origin was asked (the tumblr assets were refused). assert.ok(!wb.requests.some((r) => r.path.includes("tumblr.com/iframe"))); } finally { await opened.close(); await wb.close(); await rm(dir, { recursive: true, force: true }); } });