// Release 37 S1: `import-page` end to end on the fake Wayback — refusals // before any request, a capture stored under pages/ and its records in the // channel's posts, the nearest capture for a date, a capture never fetched // twice, versions of one page — and `reextract-pages` over what is stored. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/importPage.test.ts import test, { after } from "node:test"; import assert from "node:assert/strict"; import { existsSync, mkdtempSync, rmSync } from "node:fs"; import { mkdir, readFile, writeFile } from "node:fs/promises"; import { gunzipSync } from "node:zlib"; import { tmpdir } from "node:os"; import path from "node:path"; import { startFakeWayback, PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL, PAGE_IMAGE_TS, PAGE_IMAGE_URL, PAGE_TOOLBAR_TS, PAGE_TOOLBAR_URL, } from "../testing/web/fakeWayback.mjs"; import type { Paths } from "../lib/paths"; import { WaybackClient } from "../lib/waybackClient"; import { importPage, planImportPage, queueImportPage, WAYBACK_PAGES_QUEUE } from "./importPage"; import { reextractPages } from "./reextractPages"; import { readAllPosts, upsertPosts } from "../lib/posts-server"; import { pageRecordId } from "../lib/waybackPages/types"; import { listStoredCaptures, pageCaptureDir, readStoredCapture, updateStoredCapture } from "../lib/waybackPages/store-server"; import { draftToPost } from "../lib/waybackPages/toPost"; const ROOT = mkdtempSync(path.join(tmpdir(), "import-page-")); after(() => rmSync(ROOT, { recursive: true, force: true })); const paths = { channelsDir: path.join(ROOT, "channels"), transcriptsDir: ROOT, jobsDir: path.join(ROOT, "jobs") } as unknown as Paths; const PUBLIC = { social: { x: { visibility: "public" } } }; const PRIVATE = { social: { x: { visibility: "private" } } }; async function channel(slug: string, config: Record) { const dir = path.join(paths.channelsDir, slug); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", name: slug, ...config })); return dir; } const pagesChannel = (slug: string, target: string, match = "prefix") => channel(slug, { sourceKind: "social", platform: "webpage", socialHandle: "blog.example", url: `https://web.archive.org/web/*/${target}*`, wayback: { targets: [{ url: target, match }] }, }); const replay = (ts: string, url: string) => `https://web.archive.org/web/${ts}/${url}`; test("refused before any request: no channel, not a pages channel, no capture named, a video, an X capture outside an X channel", async () => { await pagesChannel("old-blog", "blog.example/"); await channel("a-video-channel", { url: "https://www.youtube.com/@x/videos" }); await channel("an-x-channel", { sourceKind: "social", platform: "twitter", url: "https://x.com/a", socialHandle: "a" }); const ask = (slug: string, url: string, at?: string, settings = PUBLIC) => planImportPage(paths, { slug, url, ...(at ? { at } : {}), settings }); const err = async (p: ReturnType) => { const r = await p; return r.ok ? "" : r.error; }; assert.match(await err(ask("nope", replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL))), /No such channel: nope/); assert.match(await err(ask("a-video-channel", replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL))), /not a Wayback pages channel/); assert.match(await err(ask("an-x-channel", replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL))), /not a Wayback pages channel/); assert.match(await err(ask("old-blog", "https://web.archive.org/web/*/blog.example/*")), /a Wayback Machine listing, not one capture/); assert.match(await err(ask("old-blog", PAGE_ARTICLE_URL)), /not a Wayback Machine capture/); assert.match( await err(ask("old-blog", replay("20140101000000", "https://www.youtube.com/watch?v=abc"))), /is a video \(YouTube\), not a page: use import-video/, ); // X captures: private X keeps them out of a channel not scoped on X. assert.match(await err(ask("old-blog", replay("2014", "https://twitter.com/someone"), undefined, PRIVATE)), /on X, whose posts are private here/); assert.equal((await ask("old-blog", replay("2014", "https://twitter.com/someone"), undefined, PUBLIC)).ok, true); await pagesChannel("old-x", "twitter.com/someone"); assert.equal((await ask("old-x", replay("2014", "https://twitter.com/someone"), undefined, PRIVATE)).ok, true); // The job door refuses the same way, and starts nothing. const q = await queueImportPage({ paths, slug: "a-video-channel", url: replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), settings: PUBLIC }); assert.equal(q.ok, false); assert.equal(WAYBACK_PAGES_QUEUE, "platform:archive.org"); }); test("a capture by its replay URL: stored raw under pages/, its record in the posts; again = nothing fetched", async () => { const wb = await startFakeWayback(); try { const client = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); const root = await pagesChannel("blog-a", "blog.example/"); const dry = await importPage({ paths, slug: "blog-a", url: replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), dryRun: true, client, settings: PUBLIC }); assert.equal(dry.ok, true); assert.equal(dry.wouldFetch, `https://web.archive.org/web/${PAGE_ARTICLE_TS}id_/${PAGE_ARTICLE_URL}`); assert.equal(wb.requests.length, 0); const logs: string[] = []; const r = await importPage({ paths, slug: "blog-a", url: replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), client, settings: PUBLIC, onLog: (l) => logs.push(l), now: () => new Date("2026-10-20T00:00:00.000Z"), }); assert.equal(r.ok, true, r.error); const id = pageRecordId(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL); assert.deepEqual(r.records, [id]); assert.equal(r.written, 1); assert.equal(r.extractor, "generic v1"); const dir = pageCaptureDir(root, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL); assert.equal(path.basename(dir), id); const stored = await readStoredCapture(dir); assert.equal(stored?.originalUrl, PAGE_ARTICLE_URL); assert.equal(stored?.mimetype, "text/html"); assert.equal(stored?.extractor, "generic"); assert.equal(stored?.fetchedAt, "2026-10-20T00:00:00.000Z"); assert.deepEqual(stored?.records, [id]); const raw = gunzipSync(await readFile(path.join(dir, "raw.html.gz"))).toString("utf8"); assert.ok(raw.includes("A Post About Bread")); assert.equal(stored?.bytes, Buffer.byteLength(raw)); const [post] = await readAllPosts(root); assert.equal(post.id, id); assert.equal(post.platform, "webpage"); assert.equal(post.createdAt, "2014-03-04T18:30:00.000Z"); assert.equal(post.page?.title, "A Post About Bread"); assert.equal(post.page?.waybackUrl, replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL)); assert.ok(post.text.includes("The first loaf came out flat")); assert.ok(post.links.includes("https://blog.example/2014/02/starter.html")); assert.equal(post.media?.[0]?.url, `https://web.archive.org/web/${PAGE_ARTICLE_TS}im_/https://blog.example/images/loaf.jpg`); // The month shard and the posts archive, as a fetch writes them. assert.ok(existsSync(path.join(root, "posts", "2014-03.jsonl"))); assert.match(await readFile(path.join(root, "posts-archive"), "utf8"), new RegExp(`^webpage ${id}$`, "m")); const n = wb.requests.length; const again = await importPage({ paths, slug: "blog-a", url: replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), client, settings: PUBLIC }); assert.equal(again.already, true); assert.equal(wb.requests.length, n, "nothing fetched for a stored capture"); } finally { await wb.close(); } }); test("the nearest capture to a date; a later capture is a version of the first; a toolbar body reads clean", async () => { const wb = await startFakeWayback(); try { const client = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); const root = await pagesChannel("blog-b", "blog.example/"); const later = await importPage({ paths, slug: "blog-b", url: PAGE_ARTICLE_URL, at: "20150601", client, settings: PUBLIC }); assert.equal(later.ok, true, later.error); assert.equal(later.captureTs, PAGE_ARTICLE_LATER_TS); assert.match(wb.requests[0].path, /^\/cdx\/search\/cdx\?.*closest=20150601/); // A replay URL whose timestamp the archive holds nothing at: the // redirect's capture is the one recorded. const first = await importPage({ paths, slug: "blog-b", url: replay("20140301000000", PAGE_ARTICLE_URL), client, settings: PUBLIC }); assert.equal(first.ok, true, first.error); assert.equal(first.captureTs, PAGE_ARTICLE_TS); const firstId = pageRecordId(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL); const laterId = pageRecordId(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL); const stored = await readStoredCapture(pageCaptureDir(root, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL)); assert.equal(stored?.requestedTs, "20140301000000"); const byId = new Map((await readAllPosts(root)).map((p) => [p.id, p])); assert.equal(byId.get(firstId)?.page?.versionOf, undefined); assert.equal(byId.get(laterId)?.page?.versionOf, firstId, "the earlier-imported later capture now names the first"); assert.ok(byId.get(laterId)?.text.includes("the fourth loaf rose")); // Both versions group as one thread. assert.equal(byId.get(firstId)?.threadId, byId.get(laterId)?.threadId); const tb = await importPage({ paths, slug: "blog-b", url: replay(PAGE_TOOLBAR_TS, PAGE_TOOLBAR_URL), client, settings: PUBLIC }); assert.equal(tb.ok, true, tb.error); const about = (await readAllPosts(root)).find((p) => p.page?.originalUrl === PAGE_TOOLBAR_URL)!; assert.ok(!about.text.includes("Wayback Machine"), about.text); assert.ok(about.text.includes("We are a small group")); assert.deepEqual(about.links, ["https://home.example/contact", "https://home.example/links"]); const img = await importPage({ paths, slug: "blog-b", url: replay(PAGE_IMAGE_TS, PAGE_IMAGE_URL), client, settings: PUBLIC }); assert.equal(img.ok, false); assert.match(img.error ?? "", /image\/jpeg, not a page/); } finally { await wb.close(); } }); test("reextract-pages: nothing stale changes nothing; a stale capture is redone; a record its capture no longer makes goes, one with no capture stays", async () => { const wb = await startFakeWayback(); try { const client = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 }); const root = await pagesChannel("blog-c", "blog.example/"); assert.equal((await importPage({ paths, slug: "blog-c", url: replay(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), client, settings: PUBLIC })).ok, true); assert.equal((await importPage({ paths, slug: "blog-c", url: replay(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL), client, settings: PUBLIC })).ok, true); const requests = wb.requests.length; const clean = await reextractPages({ paths, slug: "blog-c" }); assert.equal(clean.ok, true, clean.error); assert.equal(clean.captures, 2); assert.equal(clean.stale, 0); assert.deepEqual(clean.records, { added: 0, changed: 0, removed: 0, unchanged: 2, kept: 0 }); assert.equal(clean.written, false); // A capture made by an older extractor, a stray record of a stored // capture, and a record whose capture is not stored at all. const [entry] = await listStoredCaptures(root); await updateStoredCapture(entry.dir, { ...entry.capture, extractorVersion: 0 }); const stray = draftToPost( { kind: "tumblr-post", itemId: "tumblr-9", text: "an item an old extractor split out", links: [] }, { channelSlug: "blog-c", capture: { originalUrl: PAGE_ARTICLE_URL, captureTs: PAGE_ARTICLE_TS }, extractor: { name: "old", version: 1 } }, ); const orphan = draftToPost( { kind: "generic", text: "imported before its body was kept", links: [] }, { channelSlug: "blog-c", capture: { originalUrl: "https://blog.example/gone", captureTs: "20120101000000" }, extractor: { name: "generic", version: 1 } }, ); await upsertPosts(root, [stray, orphan]); const dry = await reextractPages({ paths, slug: "blog-c", dryRun: true }); assert.equal(dry.stale, 1); assert.deepEqual(dry.records, { added: 0, changed: 0, removed: 1, unchanged: 2, kept: 1 }); assert.equal((await readAllPosts(root)).length, 4, "a dry run writes nothing"); const done = await reextractPages({ paths, slug: "blog-c" }); assert.equal(done.written, true); const ids = (await readAllPosts(root)).map((p) => p.id).sort(); assert.deepEqual(ids, [orphan.id, pageRecordId(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL), pageRecordId(PAGE_ARTICLE_LATER_TS, PAGE_ARTICLE_URL)].sort()); assert.equal((await readStoredCapture(entry.dir))?.extractorVersion, 1); assert.equal(wb.requests.length, requests, "a re-extract asks the archive nothing"); const again = await reextractPages({ paths, slug: "blog-c" }); assert.equal(again.stale, 0); assert.equal(again.written, false); const refused = await reextractPages({ paths, slug: "a-video-channel" }); assert.match(refused.error ?? "", /not a Wayback pages channel/); } finally { await wb.close(); } });