commit 366250afde0b935222d21a1fdb9ca44a6949ecc7
parent 9104da3d941dc02d70ff396445ca862f3190241f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 20 Oct 2026 14:19:41 -0400
archives: an archive-source layer — Wayback as an adapter, archive.today as the second source
common/lib/archives/: ArchiveSource + ArchiveRefusal, the registry (ARCHIVE_SOURCES,
sourceForUrl, archiveRefusalOf, archiveLookup), the Wayback adapter over the existing
client, archive.today's timemap/copy facts/check page/unwrap (pure) and its paced client
(one chain, 8 s jittered gap, a 429 stops and rests it, a check refused or read once
through the archive session's headless profile, never solved), the session (Connect).
import-page takes an archive.today copy or {url, at, source}; the copy is stored as served
with source + mementoUrl and unwrapped on every read (re-extract too). PagePostInfo.source /
archiveUrl, target sources, settings.archives, a typed "excluded" refusal for a Wayback
403, archive-lookup + `archilyzer archive lookup`, the fake archive.today, unit tests.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
36 files changed, 3444 insertions(+), 150 deletions(-)
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -679,8 +679,8 @@ export const COMMANDS: Command[] = [
{
path: ["wayback", "pages", "import"],
usage:
- "<slug> <url> [--at YYYYMMDD] [--dry-run] import ONE Wayback Machine capture of a page that is not a video into a Wayback pages channel: a capture's replay URL, or the page's URL and --at for the capture nearest that date; the raw body stored under pages/, its records in the channel's posts. In-process, through this process's own paced client — while an editor runs, prefer `pnpm ops import-page`",
- flags: { at: "string", "dry-run": "boolean" },
+ "<slug> <url> [--at YYYYMMDD] [--source archive.today] [--dry-run] import ONE Wayback Machine capture (or archive.today copy) of a page that is not a video into a Wayback pages channel: a capture's replay URL, an archive.today copy's URL (archive.ph/<id>), or the page's URL and --at for the capture nearest that date (--source archive.today: its archive.today copy); the body stored under pages/, its records in the channel's posts. In-process, through this process's own paced clients — while an editor runs, prefer `pnpm ops import-page`",
+ flags: { at: "string", source: "string", "dry-run": "boolean" },
maxPositionals: 2,
run: async ({ positionals, flags }) => {
const [slug, url] = positionals;
@@ -692,11 +692,32 @@ export const COMMANDS: Command[] = [
slug,
url,
...(typeof flags.at === "string" ? { at: flags.at } : {}),
+ ...(typeof flags.source === "string" ? { source: flags.source } : {}),
dryRun: flags["dry-run"] === true,
signal: interrupted(),
});
},
},
+ // Release 37 lane F: the copies of a page across archive sources.
+ {
+ path: ["archive", "lookup"],
+ usage:
+ "<url> [--source wayback|archive.today] [--limit N] the copies of a page each archive source holds (the Wayback Machine's CDX, archive.today's timemap), oldest first, at most N per source (50): read only, each source through its own paced client. A source that refuses says why (excluded from the Wayback Machine, a check, a 429). While an editor runs, `pnpm ops archive-lookup` shares its clients",
+ flags: { source: "string", limit: "string" },
+ maxPositionals: 1,
+ run: async ({ positionals, flags }) => {
+ const [url] = positionals;
+ if (!url || !/^https?:\/\//.test(url)) {
+ console.error("archive lookup: pass a page's own http(s) URL.");
+ return 2;
+ }
+ return (await import("./wayback-pages")).lookupMain({
+ url,
+ ...(typeof flags.source === "string" ? { source: flags.source } : {}),
+ ...(typeof flags.limit === "string" ? { limit: Number(flags.limit) } : {}),
+ });
+ },
+ },
{
path: ["wayback", "pages", "reextract"],
usage:
diff --git a/common/bin/wayback-pages.ts b/common/bin/wayback-pages.ts
@@ -1,4 +1,4 @@
-// `archilyzer wayback pages import <slug> <url> [--at YYYYMMDD] [--dry-run]`
+// `archilyzer wayback pages import <slug> <url> [--at YYYYMMDD] [--source archive.today] [--dry-run]`
// and `archilyzer wayback pages reextract <slug> [--dry-run]` — a Wayback pages
// channel (release 37 S1) from the command line, in-process.
//
@@ -21,6 +21,7 @@ export async function importMain(opts: {
slug: string;
url: string;
at?: string;
+ source?: string;
dryRun: boolean;
paths?: Paths;
signal?: AbortSignal;
@@ -34,6 +35,7 @@ export async function importMain(opts: {
slug: opts.slug,
url: opts.url,
...(opts.at ? { at: opts.at } : {}),
+ ...(opts.source ? { source: opts.source } : {}),
dryRun: opts.dryRun,
onLog: (line) => console.log(line),
...(opts.signal ? { signal: opts.signal } : {}),
@@ -65,3 +67,25 @@ export async function reextractMain(opts: { slug: string; dryRun: boolean; paths
}
return 0;
}
+
+// `archilyzer archive lookup <url>` (release 37 lane F): the copies each archive
+// source holds of a page, read only.
+export async function lookupMain(opts: { url: string; source?: string; limit?: number }): Promise<number> {
+ const { archiveLookup } = await import("../lib/archives/index");
+ const { isArchiveSourceId } = await import("../lib/archives/types");
+ if (opts.source && !isArchiveSourceId(opts.source)) {
+ console.error(`archive lookup: --source must be "wayback" or "archive.today", not "${opts.source}"`);
+ return 2;
+ }
+ const limit = opts.limit && Number.isInteger(opts.limit) && opts.limit > 0 ? Math.min(opts.limit, 500) : 50;
+ const r = await archiveLookup(opts.url, { ...(opts.source ? { source: opts.source as "wayback" | "archive.today" } : {}), limit });
+ for (const s of r.sources) {
+ if (!s.ok) {
+ console.log(`${s.label}: ${s.error}`);
+ continue;
+ }
+ console.log(`${s.label}: ${s.captures.length} cop${s.captures.length === 1 ? "y" : "ies"}`);
+ for (const c of s.captures) console.log(` ${c.captureTs} ${c.mementoUrl}`);
+ }
+ return r.sources.some((s) => s.ok) ? 0 : 1;
+}
diff --git a/common/controller/importPage.archiveToday.test.ts b/common/controller/importPage.archiveToday.test.ts
@@ -0,0 +1,208 @@
+// Release 37 lane F: `import-page` of an archive.today copy end to end on the
+// fake archive.today — the copy by its short id and nearest a date, stored AS
+// SERVED with its source, records that say where they are from, never fetched
+// twice, a check refused with its code and nothing written, and a re-extract
+// that reads the stored copy unwrapped. Also the Wayback exclusion (a CDX 403)
+// as an import's typed refusal.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/importPage.archiveToday.test.ts
+
+import test, { after } from "node:test";
+import assert from "node:assert/strict";
+import { 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 {
+ startFakeArchiveToday,
+ fixtureCopy,
+ COPIES,
+ AT_ARTICLE_ID,
+ AT_ARTICLE_LATER_ID,
+ AT_ARTICLE_LATER_TS,
+ AT_ARTICLE_TS,
+ AT_ARTICLE_URL,
+ AT_CHECKED_ID,
+} from "../testing/web/fakeArchiveToday.mjs";
+import { startFakeWayback } from "../testing/web/fakeWayback.mjs";
+import type { Paths } from "../lib/paths";
+import { ArchiveTodayClient } from "../lib/archives/archiveTodayClient";
+import { WaybackClient } from "../lib/waybackClient";
+import { importPage, importPageQueueOf, planImportPage } from "./importPage";
+import { reextractPages } from "./reextractPages";
+import { readAllPosts } from "../lib/posts-server";
+import { pageRecordId } from "../lib/waybackPages/types";
+import { listStoredCaptures, pageCaptureDir } from "../lib/waybackPages/store-server";
+import { pageArchiveLink } from "../lib/archives/mementos";
+
+const ROOT = mkdtempSync(path.join(tmpdir(), "import-page-at-"));
+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" } } };
+
+async function pagesChannel(slug: string, target: string) {
+ 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,
+ sourceKind: "social",
+ platform: "webpage",
+ socialHandle: target.split("/")[0],
+ url: `https://web.archive.org/web/*/${target}*`,
+ wayback: { targets: [{ url: target, match: "prefix", sources: ["wayback", "archive.today"] }] },
+ }),
+ );
+ return dir;
+}
+
+const TWEET_URL = "https://twitter.com/TeapotFan/status/697374449464250369";
+const TWEET_ID = "Tw33t";
+const TWEET_TS = "20160211000000";
+
+async function withFake(fn: (client: ArchiveTodayClient, at: Awaited<ReturnType<typeof startFakeArchiveToday>>) => Promise<void>, opts: Parameters<typeof startFakeArchiveToday>[0] = {}) {
+ const at = await startFakeArchiveToday({
+ copies: [...COPIES, fixtureCopy("x-2016-status.html", { id: TWEET_ID, original: TWEET_URL, timestamp: TWEET_TS })],
+ ...opts,
+ });
+ try {
+ await fn(new ArchiveTodayClient({ fetch: at.fetch, sleep: async () => {} }, { minGapMs: 0 }), at);
+ } finally {
+ await at.close();
+ }
+}
+
+test("planned per source: an archive.today copy runs on its own queue; a short id is checked again after the read", async () => {
+ await pagesChannel("deleted-journal", "journal.example/");
+ const p = await planImportPage(paths, { slug: "deleted-journal", url: `https://archive.ph/${AT_ARTICLE_ID}`, settings: PUBLIC });
+ assert.ok(p.ok);
+ assert.equal(importPageQueueOf(p.plan.ask), "platform:archive.today");
+ const w = await planImportPage(paths, { slug: "deleted-journal", url: "https://web.archive.org/web/2019/https://journal.example/", settings: PUBLIC });
+ assert.ok(w.ok);
+ assert.equal(importPageQueueOf(w.plan.ask), "platform:archive.org");
+ const video = await planImportPage(paths, { slug: "deleted-journal", url: "https://archive.ph/newest/https://www.youtube.com/watch?v=abcdefghijk", settings: PUBLIC });
+ assert.equal(video.ok, false);
+ assert.match(video.ok ? "" : video.error, /use import-video/);
+});
+
+test("a copy by its short id: stored as served with its source, records that name archive.today, never fetched twice", async () => {
+ const channelRoot = await pagesChannel("deleted-journal", "journal.example/");
+ await withFake(async (client, at) => {
+ const dry = await importPage({ paths, slug: "deleted-journal", url: `https://archive.is/${AT_ARTICLE_ID}`, dryRun: true, archiveTodayClient: client, settings: PUBLIC });
+ assert.equal(dry.ok, true);
+ assert.match(String(dry.wouldFetch), new RegExp(`https://archive\\.ph/${AT_ARTICLE_ID}`));
+ assert.equal(at.requests.length, 0, "a dry run asks nothing");
+
+ const res = await importPage({ paths, slug: "deleted-journal", url: `https://archive.is/${AT_ARTICLE_ID}`, archiveTodayClient: client, settings: PUBLIC });
+ assert.equal(res.ok, true, res.error);
+ assert.equal(res.source, "archive.today");
+ assert.equal(res.captureTs, AT_ARTICLE_TS);
+ assert.equal(res.originalUrl, AT_ARTICLE_URL);
+ assert.equal(res.mementoUrl, `https://archive.ph/${AT_ARTICLE_ID}`);
+ assert.equal(res.written, 1);
+
+ const dir = pageCaptureDir(channelRoot, AT_ARTICLE_TS, AT_ARTICLE_URL);
+ const capture = JSON.parse(await readFile(path.join(dir, "capture.json"), "utf8")) as Record<string, unknown>;
+ assert.equal(capture.source, "archive.today");
+ assert.equal(capture.mementoUrl, `https://archive.ph/${AT_ARTICLE_ID}`);
+ assert.equal(capture.extractor, "generic");
+ const raw = gunzipSync(await readFile(path.join(dir, "raw.html.gz"))).toString("utf8");
+ assert.match(raw, /id="HEADER"/, "the copy as served, bar and all");
+
+ const [post] = (await readAllPosts(channelRoot)).filter((p) => p.page);
+ assert.equal(post.id, pageRecordId(AT_ARTICLE_TS, AT_ARTICLE_URL));
+ assert.equal(post.platform, "webpage");
+ assert.equal(post.url, AT_ARTICLE_URL);
+ assert.equal(post.author, "Sam Example");
+ assert.doesNotMatch(post.text, /webpage capture|Saved from/);
+ assert.equal(post.page?.source, "archive.today");
+ assert.equal(post.page?.archiveUrl, `https://archive.ph/${AT_ARTICLE_ID}`);
+ assert.equal(post.page?.waybackUrl, `https://archive.ph/${AT_ARTICLE_ID}`);
+ assert.deepEqual(pageArchiveLink(post.page!), { source: "archive.today", label: "archive.today", url: `https://archive.ph/${AT_ARTICLE_ID}` });
+ assert.match(String(post.media?.[0]?.url), new RegExp(`^https://archive\\.ph/${AT_ARTICLE_ID}/`), "the image is archive.today's cached copy");
+ assert.deepEqual(post.links, ["https://journal.example/2019/05/minutes.html", "https://other.example/account"]);
+
+ // Again, by another of its names: nothing fetched.
+ const n = at.requests.length;
+ const again = await importPage({ paths, slug: "deleted-journal", url: `https://archive.ph/${AT_ARTICLE_ID}`, archiveTodayClient: client, settings: PUBLIC });
+ assert.equal(again.already, true);
+ assert.equal(at.requests.length, n);
+ const dryAgain = await importPage({ paths, slug: "deleted-journal", url: `https://archive.li/${AT_ARTICLE_ID}`, dryRun: true, archiveTodayClient: client, settings: PUBLIC });
+ assert.equal(dryAgain.already, true);
+ });
+});
+
+test("the copy nearest a date (one timemap request), a later version of the page; re-extract reads the stored copy unwrapped", async () => {
+ const channelRoot = await pagesChannel("deleted-journal", "journal.example/");
+ await withFake(async (client, at) => {
+ const res = await importPage({ paths, slug: "deleted-journal", url: AT_ARTICLE_URL, at: "20191201", source: "archive.today", archiveTodayClient: client, settings: PUBLIC });
+ assert.equal(res.ok, true, res.error);
+ assert.equal(res.captureTs, AT_ARTICLE_LATER_TS);
+ assert.equal(res.mementoUrl, `https://archive.ph/${AT_ARTICLE_LATER_ID}`);
+ assert.deepEqual(at.requests.map((r) => r.path), [`/timemap/${AT_ARTICLE_URL}`, `/${AT_ARTICLE_LATER_ID}`]);
+ const posts = (await readAllPosts(channelRoot)).filter((p) => p.page);
+ const later = posts.find((p) => p.page!.captureTs === AT_ARTICLE_LATER_TS)!;
+ assert.equal(later.page?.versionOf, pageRecordId(AT_ARTICLE_TS, AT_ARTICLE_URL), "a later copy is a version of the first held");
+ assert.match(later.text, /a second meeting is planned/);
+
+ const re = await reextractPages({ paths, slug: "deleted-journal" });
+ assert.equal(re.ok, true, re.error);
+ assert.equal(re.stale, 0, "nothing stale: the stored copies read the same unwrapped");
+ assert.equal(re.records.changed, 0);
+ assert.equal(re.records.removed, 0);
+ assert.equal((await listStoredCaptures(channelRoot)).every((e) => e.capture.source === "archive.today"), true);
+ });
+});
+
+test("a tweet held by archive.today goes to the X extractor, as from the Wayback Machine", async () => {
+ const channelRoot = await pagesChannel("teapot-x", "twitter.com/TeapotFan");
+ await withFake(async (client) => {
+ const res = await importPage({ paths, slug: "teapot-x", url: `https://archive.ph/${TWEET_ID}`, archiveTodayClient: client, settings: PUBLIC });
+ assert.equal(res.ok, true, res.error);
+ assert.match(String(res.extractor), /^x v\d+$/);
+ const tweets = (await readAllPosts(channelRoot)).filter((p) => p.page?.kind === "tweet");
+ assert.ok(tweets.length > 0);
+ assert.ok(tweets.every((t) => t.page?.source === "archive.today"));
+ });
+});
+
+test("a check: refused with its code, nothing stored; a 429 refused as rate-limited", async () => {
+ const channelRoot = await pagesChannel("checked-pages", "checked.example/");
+ await withFake(
+ async (client) => {
+ const res = await importPage({ paths, slug: "checked-pages", url: `https://archive.ph/${AT_CHECKED_ID}`, archiveTodayClient: client, settings: PUBLIC });
+ assert.equal(res.ok, false);
+ assert.equal(res.refusal, "challenge");
+ assert.equal(res.source, "archive.today");
+ assert.match(String(res.error), /Connect archive session/);
+ assert.deepEqual(await listStoredCaptures(channelRoot), []);
+ assert.deepEqual(await readAllPosts(channelRoot), []);
+ },
+ { challenge: [AT_CHECKED_ID] },
+ );
+ await withFake(
+ async (client) => {
+ const res = await importPage({ paths, slug: "checked-pages", url: `https://archive.ph/${AT_CHECKED_ID}`, archiveTodayClient: client, settings: PUBLIC });
+ assert.equal(res.refusal, "rate-limited");
+ assert.match(String(res.error), /too many requests/);
+ },
+ { busyTimes: 1 },
+ );
+});
+
+test("a Wayback exclusion (a CDX 403) is an import's typed refusal", async () => {
+ await pagesChannel("excluded-pages", "gone.example/");
+ const wb = await startFakeWayback({ excluded: ["https://gone.example/profile"] });
+ try {
+ const client = new WaybackClient({ fetch: wb.fetch }, { minGapMs: 0 });
+ const res = await importPage({ paths, slug: "excluded-pages", url: "https://gone.example/profile", at: "2014", client, settings: PUBLIC });
+ assert.equal(res.ok, false);
+ assert.equal(res.refusal, "excluded");
+ assert.match(String(res.error), /excluded from the Wayback Machine \(cause unknown\)/);
+ } finally {
+ await wb.close();
+ }
+});
diff --git a/common/controller/importPage.ts b/common/controller/importPage.ts
@@ -26,6 +26,18 @@
// stream, the 2 s gap, 429/503 waited out), and the job runs on the
// `platform:archive.org` queue — one import at a time. A capture already
// stored is not fetched again.
+//
+// ARCHIVE.TODAY (release 37 lane F, lib/archives/): the same pipeline for a
+// copy on archive.today —
+// {slug, url: <archive.today copy>} archive.ph/<id>, /<ts>/<page>, /newest/<page>
+// {slug, url: <original>, at, source: "archive.today"} the copy nearest `at` (its timemap)
+// — through the archive.today client (one stream, an 8 s gap, a 429 stops
+// the job and rests the client, a check page is refused or read once through
+// the archive session's browser, never solved), on the
+// `platform:archive.today` queue. The copy is stored AS SERVED with
+// `source` and its URL in capture.json, and unwrapped for the extractors each
+// time it is read. A refusal's code is in the result (`refusal`: "excluded"
+// for a Wayback 403, "challenge", "rate-limited", …).
import path from "node:path";
import { getPaths, type Paths } from "../lib/paths";
@@ -36,17 +48,18 @@ import { getSettings } from "../lib/settings";
import { queueKeyForUrl } from "../lib/platform";
import { waybackPageUrl, waybackRawUrl } from "../lib/wayback";
import { ArchiveOrgRequestError } from "../lib/archiveOrgClient";
-import {
- waybackClient as defaultWaybackClient,
- WaybackCaptureRefusal,
- type WaybackClient,
-} from "../lib/waybackClient";
+import { waybackClient as defaultWaybackClient, type WaybackClient } from "../lib/waybackClient";
import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
-import { isXHostUrl, parsePageCaptureAsk, videoPageOf, type PageCaptureAsk } from "../lib/waybackPages/urls";
+import { isXHostUrl, videoPageOf } from "../lib/waybackPages/urls";
+import { parseArchiveCaptureAsk, type ArchiveCaptureAsk } from "../lib/archives/ask";
+import { unwrapArchiveTodayHtml, mapArchiveTodayMedia } from "../lib/archives/archiveToday";
+import { ARCHIVE_TODAY_QUEUE, ArchiveTodayRequestError, type ArchiveTodayClient } from "../lib/archives/archiveTodayClient";
+import { archiveRefusalOf, archiveTodayClient as defaultArchiveTodayClient, type ArchiveRefusalCode } from "../lib/archives/index";
import { decodeCaptureBody, extractPage } from "../lib/waybackPages/extract";
import { assignPageVersions, draftToPost } from "../lib/waybackPages/toPost";
import {
+ findStoredCaptureByMemento,
hasStoredCapture,
pageCaptureDir,
readStoredCapture,
@@ -67,9 +80,16 @@ type VisibilitySettings = { social?: { x?: { visibility?: unknown } } };
export type ImportPagePlan = {
config: ChannelConfig;
- ask: PageCaptureAsk;
+ // Release 37 lane F: the ask names its source ("wayback", or
+ // "archive.today" — lib/archives/ask.ts).
+ ask: ArchiveCaptureAsk;
};
+// The queue an import of this ask runs on: its source's.
+export function importPageQueueOf(ask: Pick<ArchiveCaptureAsk, "source">): string {
+ return ask.source === "archive.today" ? ARCHIVE_TODAY_QUEUE : WAYBACK_PAGES_QUEUE;
+}
+
// The refusal an X capture meets in this channel, or null.
export function xCaptureRefusal(
config: ChannelConfig,
@@ -89,7 +109,7 @@ export function xCaptureRefusal(
// Everything checked before a job: the plan, or the refusal.
export async function planImportPage(
paths: Paths,
- opts: { slug: string; url: string; at?: string; settings?: VisibilitySettings },
+ opts: { slug: string; url: string; at?: string; source?: string; settings?: VisibilitySettings },
): Promise<{ ok: true; plan: ImportPagePlan } | { ok: false; error: string }> {
const config = await readChannelConfig(paths, opts.slug);
if (!config) return { ok: false, error: `No such channel: ${opts.slug}` };
@@ -99,17 +119,22 @@ export async function planImportPage(
error: `${opts.slug} is not a Wayback pages channel; import-page imports into a channel on platform "webpage"`,
};
}
- const parsed = parsePageCaptureAsk(opts.url, opts.at);
+ const parsed = parseArchiveCaptureAsk(opts.url, opts.at, opts.source);
if (!parsed.ok) return parsed;
- const video = videoPageOf(parsed.ask.originalUrl);
- if (video) {
- return {
- ok: false,
- error: `${parsed.ask.originalUrl} is a video (${video}), not a page: use import-video for a capture of a video`,
- };
+ // An archive.today short id names no page: these two are asked again of
+ // the copy once it is read.
+ const original = parsed.ask.originalUrl;
+ if (original) {
+ const video = videoPageOf(original);
+ if (video) {
+ return {
+ ok: false,
+ error: `${original} is a video (${video}), not a page: use import-video for a capture of a video`,
+ };
+ }
+ const x = xCaptureRefusal(config, opts.slug, original, opts.settings ?? getSettings());
+ if (x) return { ok: false, error: x };
}
- const x = xCaptureRefusal(config, opts.slug, parsed.ask.originalUrl, opts.settings ?? getSettings());
- if (x) return { ok: false, error: x };
return { ok: true, plan: { config, ask: parsed.ask } };
}
@@ -131,6 +156,12 @@ export type ImportPageResult = {
updated: number;
unchanged: number;
extractor?: string;
+ // Release 37 lane F: the source the copy is from ("wayback",
+ // "archive.today"), the copy's URL there, and — when the source refused —
+ // the refusal's code ("excluded", "challenge", "rate-limited", …).
+ source?: string;
+ mementoUrl?: string;
+ refusal?: ArchiveRefusalCode;
error?: string;
};
@@ -141,50 +172,113 @@ export function recordsOfCapture(
capture: StoredCapture,
body: Buffer,
): { posts: Post[]; extractor: { name: string; version: number }; fallback?: StoredCapture["extractorFallback"] } {
- const html = decodeCaptureBody(body, capture.contentType ?? capture.mimetype);
+ const { input, images, source } = extractInputOfCapture(capture, body);
const facts = {
originalUrl: capture.originalUrl,
captureTs: capture.captureTs,
mimetype: capture.mimetype,
...(capture.digest ? { digest: capture.digest } : {}),
};
- const res = extractPage({
- html,
- capture: {
- ...facts,
- waybackUrl: waybackPageUrl(facts),
- rawUrl: waybackRawUrl(facts),
- },
- });
+ const res = extractPage(input);
const posts = res.drafts.map((d) =>
- draftToPost(d, {
+ draftToPost(images ? { ...d, ...(d.media ? { media: mapArchiveTodayMedia(d.media, images) } : {}) } : d, {
channelSlug: slug,
capture: facts,
extractor: res.extractor,
...(res.fallback ? { fallback: res.fallback } : {}),
+ ...(source ? { source } : {}),
}),
);
return { posts, extractor: res.extractor, ...(res.fallback ? { fallback: res.fallback } : {}) };
}
+// WHAT THE EXTRACTORS READ of a stored capture (release 37 lane F): its body
+// decoded and — for a copy from archive.today — unwrapped (its header bar off,
+// its rewritten links put back; lib/archives/archiveToday.ts), with the
+// capture's provenance. Shared by an import, a re-extract and its staleness
+// check. `images`: archive.today's cached copy of each image the copy names.
+export function extractInputOfCapture(
+ capture: StoredCapture,
+ body: Buffer,
+): {
+ input: { html: string; capture: { originalUrl: string; captureTs: string; mimetype?: string; digest?: string; waybackUrl: string; rawUrl: string } };
+ images?: ReadonlyMap<string, string>;
+ source?: { id: string; mementoUrl: string };
+} {
+ let html = decodeCaptureBody(body, capture.contentType ?? capture.mimetype);
+ const facts = {
+ originalUrl: capture.originalUrl,
+ captureTs: capture.captureTs,
+ mimetype: capture.mimetype,
+ ...(capture.digest ? { digest: capture.digest } : {}),
+ };
+ if (capture.source && capture.source !== "wayback") {
+ const memento = capture.mementoUrl ?? capture.originalUrl;
+ let images: ReadonlyMap<string, string> | undefined;
+ if (capture.source === "archive.today") {
+ const un = unwrapArchiveTodayHtml(html, memento);
+ html = un.html;
+ images = un.images;
+ }
+ return {
+ input: { html, capture: { ...facts, waybackUrl: memento, rawUrl: memento } },
+ ...(images ? { images } : {}),
+ source: { id: capture.source, mementoUrl: memento },
+ };
+ }
+ return { input: { html, capture: { ...facts, waybackUrl: waybackPageUrl(facts), rawUrl: waybackRawUrl(facts) } } };
+}
+
export async function importPage(opts: {
paths: Paths;
slug: string;
url: string;
at?: string;
+ // Release 37 lane F: "archive.today" with a page's own URL and `at`; a
+ // copy's URL names its source itself.
+ source?: string;
dryRun?: boolean;
settings?: VisibilitySettings;
client?: WaybackClient;
+ archiveTodayClient?: ArchiveTodayClient;
onLog?: (line: string) => void;
signal?: AbortSignal;
now?: () => Date;
}): Promise<ImportPageResult> {
- const log = (line: string) => opts.onLog?.(line);
const base: ImportPageResult = { ok: false, slug: opts.slug, url: opts.url, written: 0, updated: 0, unchanged: 0 };
const settings = opts.settings ?? getSettings();
- const planned = await planImportPage(opts.paths, { slug: opts.slug, url: opts.url, at: opts.at, settings });
+ const planned = await planImportPage(opts.paths, { slug: opts.slug, url: opts.url, at: opts.at, source: opts.source, settings });
if (!planned.ok) return { ...base, error: planned.error };
- const { config, ask } = planned.plan;
+ const { ask } = planned.plan;
+ try {
+ if (ask.source === "archive.today") return await importArchiveTodayCopy({ ...opts, settings, base, plan: planned.plan });
+ return await importWaybackCapture({ ...opts, settings, base, plan: planned.plan });
+ } catch (e) {
+ const refusal = archiveRefusalOf(e);
+ if (refusal) return { ...base, source: refusal.source, refusal: refusal.code, error: refusal.message };
+ if (e instanceof ArchiveOrgRequestError) return { ...base, error: e.message };
+ if (e instanceof ArchiveTodayRequestError) return { ...base, source: "archive.today", error: e.message };
+ throw e;
+ }
+}
+
+type ImportCtx = {
+ paths: Paths;
+ slug: string;
+ settings: VisibilitySettings;
+ base: ImportPageResult;
+ plan: ImportPagePlan;
+ dryRun?: boolean;
+ onLog?: (line: string) => void;
+ signal?: AbortSignal;
+ now?: () => Date;
+};
+
+async function importWaybackCapture(opts: ImportCtx & { client?: WaybackClient }): Promise<ImportPageResult> {
+ const log = (line: string) => opts.onLog?.(line);
+ const { base } = opts;
+ const { config } = opts.plan;
+ const ask = opts.plan.ask as Extract<ArchiveCaptureAsk, { source: "wayback" }>;
const client = opts.client ?? defaultWaybackClient;
const channelRoot = path.join(opts.paths.channelsDir, opts.slug);
@@ -205,134 +299,247 @@ export async function importPage(opts: {
};
}
- try {
- let ts: string;
- // The URL as the archive captured it: CDX's `original` for a nearest
- // lookup (it may differ from the one typed: http/https, a trailing slash).
- let original = ask.originalUrl;
- if (ask.kind === "nearest") {
- log(`Looking up the capture of ${ask.originalUrl} nearest ${ask.at} (CDX).`);
- const near = await client.closestCapture(ask.originalUrl, ask.at, { signal: opts.signal });
- if (!near) return { ...base, error: `the Wayback Machine holds no capture of ${ask.originalUrl} that recorded a page (HTTP 200)` };
- ts = near.timestamp;
- original = near.original;
- log(`Nearest capture: ${near.timestamp} (${near.original}).`);
- } else {
- ts = ask.captureTs;
- }
- if (/^\d{14}$/.test(ts) && (await hasStoredCapture(channelRoot, ts, original))) {
- log(`The capture ${ts} of ${original} is already in ${opts.slug}; nothing fetched.`);
- return {
- ...base,
- ok: true,
- already: true,
- captureTs: ts,
- originalUrl: original,
- waybackUrl: waybackPageUrl({ captureTs: ts, originalUrl: original }),
- };
- }
- log(`Fetching ${waybackRawUrl({ captureTs: ts, originalUrl: original })}`);
- const cap = await client.getCapture(ts, original, { raw: true, signal: opts.signal });
- if (cap.finalTs !== ts || cap.originalUrl !== ask.originalUrl) {
- log(`The archive answered with the capture ${cap.finalTs} of ${cap.originalUrl}.`);
- const video = videoPageOf(cap.originalUrl);
- if (video) return { ...base, error: `the capture redirects to a video (${video}, ${cap.originalUrl}): use import-video for it` };
- const x = xCaptureRefusal(config, opts.slug, cap.originalUrl, settings);
- if (x) return { ...base, error: x };
- }
- const fetchedAt = (opts.now?.() ?? new Date()).toISOString();
- const stored: StoredCapture = {
- originalUrl: cap.originalUrl,
- captureTs: cap.finalTs,
- mimetype: cap.mimetype,
- contentType: cap.contentType,
- bytes: cap.bytes,
- sha256: cap.sha256,
- fetchedAt,
- extractor: "",
- extractorVersion: 0,
- ...(cap.finalTs !== ts ? { requestedTs: ts } : {}),
- ...(cap.originalUrl !== ask.originalUrl ? { requestedUrl: ask.originalUrl } : {}),
+ let ts: string;
+ // The URL as the archive captured it: CDX's `original` for a nearest
+ // lookup (it may differ from the one typed: http/https, a trailing slash).
+ let original = ask.originalUrl;
+ if (ask.kind === "nearest") {
+ log(`Looking up the capture of ${ask.originalUrl} nearest ${ask.at} (CDX).`);
+ const near = await client.closestCapture(ask.originalUrl, ask.at, { signal: opts.signal });
+ if (!near) return { ...base, error: `the Wayback Machine holds no capture of ${ask.originalUrl} that recorded a page (HTTP 200)` };
+ ts = near.timestamp;
+ original = near.original;
+ log(`Nearest capture: ${near.timestamp} (${near.original}).`);
+ } else {
+ ts = ask.captureTs;
+ }
+ if (/^\d{14}$/.test(ts) && (await hasStoredCapture(channelRoot, ts, original))) {
+ log(`The capture ${ts} of ${original} is already in ${opts.slug}; nothing fetched.`);
+ return {
+ ...base,
+ ok: true,
+ already: true,
+ captureTs: ts,
+ originalUrl: original,
+ waybackUrl: waybackPageUrl({ captureTs: ts, originalUrl: original }),
};
- const made = recordsOfCapture(opts.slug, stored, cap.body);
- stored.extractor = made.extractor.name;
- stored.extractorVersion = made.extractor.version;
- if (made.fallback) {
- stored.extractorFallback = made.fallback;
- log(`The ${made.fallback.from} extractor failed (${made.fallback.error}); the generic extractor read the page.`);
- }
- stored.records = made.posts.map((p) => p.id);
- const dir = await writeStoredCapture(channelRoot, stored, cap.body);
- log(`Stored ${cap.bytes} bytes (${cap.mimetype}) in ${path.relative(opts.paths.channelsDir, dir)}.`);
+ }
+ log(`Fetching ${waybackRawUrl({ captureTs: ts, originalUrl: original })}`);
+ const cap = await client.getCapture(ts, original, { raw: true, signal: opts.signal });
+ if (cap.finalTs !== ts || cap.originalUrl !== ask.originalUrl) {
+ log(`The archive answered with the capture ${cap.finalTs} of ${cap.originalUrl}.`);
+ const video = videoPageOf(cap.originalUrl);
+ if (video) return { ...base, error: `the capture redirects to a video (${video}, ${cap.originalUrl}): use import-video for it` };
+ const x = xCaptureRefusal(config, opts.slug, cap.originalUrl, opts.settings);
+ if (x) return { ...base, error: x };
+ }
+ const stored: StoredCapture = {
+ originalUrl: cap.originalUrl,
+ captureTs: cap.finalTs,
+ mimetype: cap.mimetype,
+ contentType: cap.contentType,
+ bytes: cap.bytes,
+ sha256: cap.sha256,
+ fetchedAt: (opts.now?.() ?? new Date()).toISOString(),
+ extractor: "",
+ extractorVersion: 0,
+ ...(cap.finalTs !== ts ? { requestedTs: ts } : {}),
+ ...(cap.originalUrl !== ask.originalUrl ? { requestedUrl: ask.originalUrl } : {}),
+ };
+ const res = await storeAndUpsert(opts, stored, cap.body);
+ return {
+ ...base,
+ ...res,
+ ok: true,
+ captureTs: cap.finalTs,
+ originalUrl: cap.originalUrl,
+ waybackUrl: waybackPageUrl({ captureTs: cap.finalTs, originalUrl: cap.originalUrl }),
+ };
+}
- // Versions of one page: the earliest held capture of the original is the
- // one the others are versions of.
- const held = (await readAllPosts(channelRoot)).filter((p) => p.page);
- const byId = new Map(held.map((p) => [p.id, p]));
- for (const p of made.posts) byId.set(p.id, { ...(byId.get(p.id) ?? {}), ...p } as Post);
- const versioned = new Map(assignPageVersions([...byId.values()]).map((p) => [p.id, p]));
- const own = new Set(made.posts.map((p) => p.id));
- const batch = made.posts.map((p) => {
- const v = versioned.get(p.id);
- return v ? { ...p, page: v.page } : p;
- });
- // Earlier-held versions that now point at a new first capture.
- for (const v of versioned.values()) if (!own.has(v.id)) batch.push(v);
+// ONE archive.today COPY (release 37 lane F): its URL, or the copy of a page
+// nearest a date (one timemap request), then its bytes — through the paced
+// archive.today client (one stream, a long gap, a 429 stops the job, a check
+// is refused or read once through the archive session's browser). Stored AS
+// SERVED (its rewritten snapshot) with `source: "archive.today"` and the
+// copy's URL; unwrapped for the extractors each time it is read.
+async function importArchiveTodayCopy(opts: ImportCtx & { archiveTodayClient?: ArchiveTodayClient }): Promise<ImportPageResult> {
+ const log = (line: string) => opts.onLog?.(line);
+ const base: ImportPageResult = { ...opts.base, source: "archive.today" };
+ const { config } = opts.plan;
+ const ask = opts.plan.ask as Extract<ArchiveCaptureAsk, { source: "archive.today" }>;
+ const client = opts.archiveTodayClient ?? defaultArchiveTodayClient;
+ const channelRoot = path.join(opts.paths.channelsDir, opts.slug);
- const res = await upsertPosts(channelRoot, batch);
- log(
- `${made.posts.length} record(s) from the capture (${made.extractor.name} v${made.extractor.version}): ` +
- `${res.written} new, ${res.updated} updated, ${res.unchanged} unchanged. The index picks them up on its next build.`,
- );
+ const storedByMemento = async (mementoUrl: string) => {
+ const hit = await findStoredCaptureByMemento(channelRoot, mementoUrl);
+ return hit
+ ? {
+ ...base,
+ ok: true,
+ already: true,
+ captureTs: hit.capture.captureTs,
+ originalUrl: hit.capture.originalUrl,
+ mementoUrl: hit.capture.mementoUrl ?? mementoUrl,
+ waybackUrl: hit.capture.mementoUrl ?? mementoUrl,
+ }
+ : null;
+ };
+
+ if (opts.dryRun) {
+ const held = ask.kind === "memento" ? await storedByMemento(ask.ref.mementoUrl) : null;
return {
...base,
ok: true,
- captureTs: cap.finalTs,
- originalUrl: cap.originalUrl,
- waybackUrl: waybackPageUrl({ captureTs: cap.finalTs, originalUrl: cap.originalUrl }),
- records: made.posts.map((p) => p.id),
- written: res.written,
- updated: res.updated,
- unchanged: res.unchanged,
- extractor: `${made.extractor.name} v${made.extractor.version}`,
+ dryRun: true,
+ ...(held ? { already: true, captureTs: held.captureTs } : {}),
+ wouldFetch: held
+ ? "nothing (the copy is already stored)"
+ : ask.kind === "memento"
+ ? `${client.canonical(ask.ref.mementoUrl)} (archive.today, at its pace)`
+ : `the archive.today copy of ${ask.originalUrl} nearest ${ask.at} (one timemap request), then the copy`,
+ ...(ask.originalUrl ? { originalUrl: ask.originalUrl } : {}),
};
- } catch (e) {
- if (e instanceof WaybackCaptureRefusal) return { ...base, error: e.message };
- if (e instanceof ArchiveOrgRequestError) return { ...base, error: e.message };
- throw e;
}
+
+ let memento: string;
+ if (ask.kind === "nearest") {
+ log(`Looking up the archive.today copy of ${ask.originalUrl} nearest ${ask.at} (its timemap).`);
+ const near = await client.closestCapture(ask.originalUrl, ask.at, { signal: opts.signal });
+ if (!near) return { ...base, error: `archive.today holds no copy of ${ask.originalUrl}` };
+ memento = near.mementoUrl;
+ log(`Nearest copy: ${near.captureTs} (${near.mementoUrl}).`);
+ } else {
+ memento = ask.ref.mementoUrl;
+ }
+ const already = await storedByMemento(memento);
+ if (already) {
+ log(`The copy ${memento} is already in ${opts.slug}; nothing fetched.`);
+ return already;
+ }
+ log(`Fetching ${client.canonical(memento)} (archive.today).`);
+ const cap = await client.getCapture(memento, { signal: opts.signal });
+ if (cap.viaBrowser) log("archive.today answered with a check; the copy was read through the archive session's headless browser.");
+ log(`The copy is of ${cap.originalUrl}, captured ${cap.finalTs} (${cap.mementoUrl}).`);
+ const video = videoPageOf(cap.originalUrl);
+ if (video) return { ...base, error: `the copy is of a video (${video}, ${cap.originalUrl}): use import-video for it` };
+ const x = xCaptureRefusal(config, opts.slug, cap.originalUrl, opts.settings);
+ if (x) return { ...base, error: x };
+ if (await hasStoredCapture(channelRoot, cap.finalTs, cap.originalUrl)) {
+ log(`A capture of ${cap.originalUrl} at ${cap.finalTs} is already in ${opts.slug}; not stored again.`);
+ return { ...base, ok: true, already: true, captureTs: cap.finalTs, originalUrl: cap.originalUrl, mementoUrl: cap.mementoUrl, waybackUrl: cap.mementoUrl };
+ }
+ const stored: StoredCapture = {
+ originalUrl: cap.originalUrl,
+ captureTs: cap.finalTs,
+ mimetype: cap.mimetype,
+ contentType: cap.contentType,
+ bytes: cap.bytes,
+ sha256: cap.sha256,
+ fetchedAt: (opts.now?.() ?? new Date()).toISOString(),
+ extractor: "",
+ extractorVersion: 0,
+ source: "archive.today",
+ mementoUrl: cap.mementoUrl,
+ ...(ask.kind === "memento" && client.canonical(ask.ref.mementoUrl) !== cap.mementoUrl ? { requestedUrl: ask.ref.mementoUrl } : {}),
+ };
+ const res = await storeAndUpsert(opts, stored, cap.body);
+ return {
+ ...base,
+ ...res,
+ ok: true,
+ captureTs: cap.finalTs,
+ originalUrl: cap.originalUrl,
+ mementoUrl: cap.mementoUrl,
+ waybackUrl: cap.mementoUrl,
+ };
+}
+
+// The capture stored, extracted and its records upserted (with versions).
+async function storeAndUpsert(
+ opts: Pick<ImportCtx, "paths" | "slug" | "onLog">,
+ stored: StoredCapture,
+ body: Buffer,
+): Promise<Pick<ImportPageResult, "records" | "written" | "updated" | "unchanged" | "extractor">> {
+ const log = (line: string) => opts.onLog?.(line);
+ const channelRoot = path.join(opts.paths.channelsDir, opts.slug);
+ const made = recordsOfCapture(opts.slug, stored, body);
+ stored.extractor = made.extractor.name;
+ stored.extractorVersion = made.extractor.version;
+ if (made.fallback) {
+ stored.extractorFallback = made.fallback;
+ log(`The ${made.fallback.from} extractor failed (${made.fallback.error}); the generic extractor read the page.`);
+ }
+ stored.records = made.posts.map((p) => p.id);
+ const dir = await writeStoredCapture(channelRoot, stored, body);
+ log(`Stored ${stored.bytes} bytes (${stored.mimetype}) in ${path.relative(opts.paths.channelsDir, dir)}.`);
+
+ // Versions of one page: the earliest held capture of the original is the
+ // one the others are versions of.
+ const held = (await readAllPosts(channelRoot)).filter((p) => p.page);
+ const byId = new Map(held.map((p) => [p.id, p]));
+ for (const p of made.posts) byId.set(p.id, { ...(byId.get(p.id) ?? {}), ...p } as Post);
+ const versioned = new Map(assignPageVersions([...byId.values()]).map((p) => [p.id, p]));
+ const own = new Set(made.posts.map((p) => p.id));
+ const batch = made.posts.map((p) => {
+ const v = versioned.get(p.id);
+ return v ? { ...p, page: v.page } : p;
+ });
+ // Earlier-held versions that now point at a new first capture.
+ for (const v of versioned.values()) if (!own.has(v.id)) batch.push(v);
+
+ const res = await upsertPosts(channelRoot, batch);
+ log(
+ `${made.posts.length} record(s) from the capture (${made.extractor.name} v${made.extractor.version}): ` +
+ `${res.written} new, ${res.updated} updated, ${res.unchanged} unchanged. The index picks them up on its next build.`,
+ );
+ return {
+ records: made.posts.map((p) => p.id),
+ written: res.written,
+ updated: res.updated,
+ unchanged: res.unchanged,
+ extractor: `${made.extractor.name} v${made.extractor.version}`,
+ };
}
-// THE JOB: an `import-page` job on the archive.org queue, refused (no job)
-// with the plan's sentence. What the channel page's field, the ops action and
-// lane B's batch all start. The job's log ends with `@@import-page {…}`.
+// THE JOB: an `import-page` job on its source's queue (the archive.org queue
+// for the Wayback Machine, `platform:archive.today` for archive.today),
+// refused (no job) with the plan's sentence. What the channel page's field,
+// the ops action and lane B's batch all start. The job's log ends with
+// `@@import-page {…}`.
export async function queueImportPage(opts: {
paths: Paths;
slug: string;
url: string;
at?: string;
+ source?: string;
requestedBy?: string;
settings?: VisibilitySettings;
client?: WaybackClient;
+ archiveTodayClient?: ArchiveTodayClient;
onDone?: (result: ImportPageResult) => void;
}): Promise<StreamActionResult> {
const settings = opts.settings ?? getSettings();
- const planned = await planImportPage(opts.paths, { slug: opts.slug, url: opts.url, at: opts.at, settings });
+ const planned = await planImportPage(opts.paths, { slug: opts.slug, url: opts.url, at: opts.at, source: opts.source, settings });
if (!planned.ok) return { ok: false, error: planned.error };
return runManagedFunction({
kind: IMPORT_PAGE_JOB_KIND,
- queueKey: WAYBACK_PAGES_QUEUE,
+ queueKey: importPageQueueOf(planned.plan.ask),
paths: opts.paths,
channelSlug: opts.slug,
fn: async (onLog, signal) => {
- onLog(`Import page: ${opts.url}${opts.at ? ` nearest ${opts.at}` : ""} into ${opts.slug}${opts.requestedBy ? ` for ${opts.requestedBy}` : ""}`);
+ onLog(
+ `Import page: ${opts.url}${opts.at ? ` nearest ${opts.at}` : ""}${planned.plan.ask.source === "archive.today" ? " (archive.today)" : ""} into ${opts.slug}${opts.requestedBy ? ` for ${opts.requestedBy}` : ""}`,
+ );
const result = await importPage({
paths: opts.paths,
slug: opts.slug,
url: opts.url,
...(opts.at ? { at: opts.at } : {}),
+ ...(opts.source ? { source: opts.source } : {}),
settings,
...(opts.client ? { client: opts.client } : {}),
+ ...(opts.archiveTodayClient ? { archiveTodayClient: opts.archiveTodayClient } : {}),
onLog,
signal,
});
@@ -352,10 +559,13 @@ export class ImportPageRefusal extends Error {
// LANE B's DOOR (release 37 S2, "Import selected"): one `import-page` job for
// one capture. Throws ImportPageRefusal with the sentence when it is refused.
+// Release 37 lane F: `url` may be an archive.today copy's URL, or a page's
+// own URL with `at` and `source: "archive.today"`.
export async function startImportPageJob(opts: {
slug: string;
url: string;
at?: string;
+ source?: string;
requestedBy?: string;
paths?: Paths;
}): Promise<{ jobId: string }> {
diff --git a/common/controller/reextractPages.ts b/common/controller/reextractPages.ts
@@ -22,7 +22,7 @@ import type { Post } from "../lib/posts";
import { readAllPosts, replaceChannelPosts } from "../lib/posts-server";
import { readChannelConfig } from "./channels";
import { isWaybackPagesChannel } from "../lib/waybackPages/config";
-import { chooseExtractor, decodeCaptureBody } from "../lib/waybackPages/extract";
+import { chooseExtractor } from "../lib/waybackPages/extract";
import { asStored, assignPageVersions, mergePageRecord, stableRecordJson } from "../lib/waybackPages/toPost";
import {
listStoredCaptures,
@@ -30,9 +30,8 @@ import {
readStoredCaptureBody,
updateStoredCapture,
} from "../lib/waybackPages/store-server";
-import { waybackPageUrl, waybackRawUrl } from "../lib/wayback";
import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
-import { recordsOfCapture, WAYBACK_PAGES_QUEUE } from "./importPage";
+import { extractInputOfCapture, recordsOfCapture, WAYBACK_PAGES_QUEUE } from "./importPage";
export const REEXTRACT_PAGES_JOB_KIND = "reextract-pages";
export const REEXTRACT_PAGES_RESULT_MARKER = "@@reextract-pages ";
@@ -96,12 +95,9 @@ export async function reextractPages(opts: {
continue;
}
derivable.add(name);
- const html = decodeCaptureBody(body, capture.contentType ?? capture.mimetype);
- const facts = { originalUrl: capture.originalUrl, captureTs: capture.captureTs };
- const now = chooseExtractor({
- html,
- capture: { ...facts, mimetype: capture.mimetype, waybackUrl: waybackPageUrl(facts), rawUrl: waybackRawUrl(facts) },
- });
+ // Release 37 lane F: what the extractors read (an archive.today copy
+ // unwrapped), as an import reads it.
+ const now = chooseExtractor(extractInputOfCapture(capture, body).input);
const isStale =
now.name !== capture.extractor || now.version !== capture.extractorVersion || !!capture.extractorFallback;
if (isStale) out.stale++;
diff --git a/common/lib/archives/archiveToday.test.ts b/common/lib/archives/archiveToday.test.ts
@@ -0,0 +1,140 @@
+// Release 37 lane F: archive.today's answers read — its timemap, a copy's facts,
+// its check page, and a copy unwrapped so the extractors read it as they read a
+// raw Wayback body: lane C's synthetic tweet and Tumblr pages, wrapped the way
+// archive.today wraps a copy, give the SAME records.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/archives/archiveToday.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ blockById,
+ copyFactsFromHeaders,
+ copyFactsFromHtml,
+ isArchiveTodayChallenge,
+ mapArchiveTodayMedia,
+ nearestCapture,
+ parseArchiveTodayTimemap,
+ parseLinkFormat,
+ unwrapArchiveTodayHtml,
+ withinCaptureRange,
+} from "./archiveToday";
+import { CHALLENGE_HTML, COPIES, wrapLikeArchiveToday, AT_ARTICLE_URL, AT_ARTICLE_ID, AT_ARTICLE_TS } from "../../testing/web/fakeArchiveToday.mjs";
+import { extractPage } from "../waybackPages/extract";
+import { captureOf, fixture } from "../waybackPages/extractors/__fixtures__/capture";
+
+test("the timemap's copies, oldest first; URLs with commas survive; the original is rel=original", () => {
+ const text = [
+ `<https://journal.example/a,b.html>; rel="original"`,
+ `<https://archive.ph/timegate/https://journal.example/a,b.html>; rel="timegate"`,
+ `<https://archive.ph/timemap/https://journal.example/a,b.html>; rel="self"; type="application/link-format"`,
+ `<https://archive.ph/Fg7hJ>; rel="last memento"; datetime="Wed, 01 Jan 2020 10:15:00 GMT"`,
+ `<https://archive.ph/Ab3dE>; rel="first memento"; datetime="Sun, 12 May 2019 08:30:00 GMT"`,
+ ].join(",\n");
+ assert.equal(parseLinkFormat(text).length, 5);
+ assert.deepEqual(parseArchiveTodayTimemap(text, "https://ignored.example/"), [
+ { source: "archive.today", captureTs: "20190512083000", originalUrl: "https://journal.example/a,b.html", mementoUrl: "https://archive.ph/Ab3dE", status: "200", mimetype: "text/html" },
+ { source: "archive.today", captureTs: "20200101101500", originalUrl: "https://journal.example/a,b.html", mementoUrl: "https://archive.ph/Fg7hJ", status: "200", mimetype: "text/html" },
+ ]);
+ assert.equal(withinCaptureRange("20190512083000", "2019", "2019"), true);
+ assert.equal(withinCaptureRange("20200101101500", "2019", "2019"), false);
+ assert.equal(withinCaptureRange("20190512083000", "201906"), false);
+ const rows = parseArchiveTodayTimemap(text, "");
+ assert.equal(nearestCapture(rows, "20191201")?.mementoUrl, "https://archive.ph/Fg7hJ");
+ assert.equal(nearestCapture(rows, "2019")?.mementoUrl, "https://archive.ph/Ab3dE");
+ assert.equal(nearestCapture([], "2019"), null);
+});
+
+test("a copy's facts: from its Memento headers, else from its header bar", () => {
+ const h = new Headers({
+ "memento-datetime": "Sun, 12 May 2019 08:30:00 GMT",
+ link: `<${AT_ARTICLE_URL}>; rel="original", <https://archive.ph/${AT_ARTICLE_ID}>; rel="memento"; datetime="Sun, 12 May 2019 08:30:00 GMT"`,
+ });
+ assert.deepEqual(copyFactsFromHeaders(h), { captureTs: "20190512083000", originalUrl: AT_ARTICLE_URL });
+ const wrapped = wrapLikeArchiveToday(COPIES[0].page(), { id: AT_ARTICLE_ID, original: AT_ARTICLE_URL, timestamp: AT_ARTICLE_TS });
+ assert.deepEqual(copyFactsFromHtml(wrapped), { originalUrl: AT_ARTICLE_URL, captureTs: AT_ARTICLE_TS });
+ assert.deepEqual(copyFactsFromHtml("<html><body><p>no bar</p></body></html>"), {});
+});
+
+test("a check page is told apart from a copy — and a copy OF a page with a captcha form is still a copy", () => {
+ assert.equal(isArchiveTodayChallenge(CHALLENGE_HTML), true);
+ assert.equal(isArchiveTodayChallenge("<html><head><title>Just a moment...</title></head><body>Checking your browser</body></html>"), true);
+ const page = wrapLikeArchiveToday(COPIES[0].page(), { id: AT_ARTICLE_ID, original: AT_ARTICLE_URL, timestamp: AT_ARTICLE_TS });
+ assert.equal(isArchiveTodayChallenge(page), false);
+ const signup = wrapLikeArchiveToday(
+ '<html><head><title>Sign up</title></head><body><form><div class="g-recaptcha" data-sitekey="k"></div></form><p>Join us.</p></body></html>',
+ { id: "Zz9yX", original: "https://club.example/signup", timestamp: "20180101000000" },
+ );
+ assert.equal(isArchiveTodayChallenge(signup), false);
+});
+
+test("blockById matches its own element's close, not a nested one's, and not a longer id", () => {
+ const html = '<div id="CONTENTS">no</div><div id="CONTENT"><div><div>in</div></div><p>x</p></div><div>after</div>';
+ const b = blockById(html, "CONTENT");
+ assert.equal(b?.inner, "<div><div>in</div></div><p>x</p>");
+});
+
+test("unwrapped: the bar gone, links out restored to the original, images back to their originals with the cached copies kept", () => {
+ const wrapped = wrapLikeArchiveToday(COPIES[0].page(), { id: AT_ARTICLE_ID, original: AT_ARTICLE_URL, timestamp: AT_ARTICLE_TS });
+ const un = unwrapArchiveTodayHtml(wrapped, `https://archive.ph/${AT_ARTICLE_ID}`);
+ assert.equal(un.framed, true);
+ assert.doesNotMatch(un.html, /webpage capture|id="HEADER"|archive\.ph\/o\//);
+ assert.match(un.html, /<title>Notes I Later Deleted \| Journal<\/title>/);
+ assert.match(un.html, /property="og:title"/);
+ assert.doesNotMatch(un.html, /og:url/);
+ assert.match(un.html, /href="https:\/\/journal\.example\/2019\/05\/minutes\.html"/);
+ assert.match(un.html, /href="https:\/\/other\.example\/account"/);
+ assert.match(un.html, /src="https:\/\/journal\.example\/img\/whiteboard\.png"/);
+ assert.doesNotMatch(un.html, /old-src/);
+ const cached = un.images.get("https://journal.example/img/whiteboard.png");
+ assert.match(String(cached), /^https:\/\/archive\.ph\/Ab3dE\/[0-9a-f]{8}\.png$/);
+
+ // The generic extractor reads it as the page it is, and the record's image
+ // is archive.today's cached copy — never a Wayback URL it was not checked against.
+ const res = extractPage({ html: un.html, capture: { ...captureOf(AT_ARTICLE_URL, AT_ARTICLE_TS), mimetype: "text/html" } });
+ assert.equal(res.extractor.name, "generic");
+ const [draft] = res.drafts;
+ assert.equal(draft.title, "Notes I Later Deleted");
+ assert.equal(draft.author, "Sam Example");
+ assert.match(draft.text, /written down the same night/);
+ assert.doesNotMatch(draft.text, /webpage capture|Saved from/);
+ assert.deepEqual(draft.links, ["https://journal.example/2019/05/minutes.html", "https://other.example/account"]);
+ assert.deepEqual(mapArchiveTodayMedia(draft.media, un.images), [{ kind: "image", url: cached, name: "The whiteboard after the meeting" }]);
+});
+
+test("lane C's tweet and Tumblr pages, wrapped like archive.today, make the same records as raw", () => {
+ const cases: [string, string, string, string][] = [
+ ["x-2016-status.html", "https://twitter.com/TeapotFan/status/697374449464250369", "20160211000000", "x"],
+ ["tumblr-2012-classic-post.html", "http://teapot-notes.tumblr.com/post/20000000001/on-spouts", "20120601000000", "tumblr"],
+ ["tumblr-2012-classic-index.html", "http://teapot-notes.tumblr.com/", "20120601000000", "tumblr"],
+ ];
+ for (const [name, url, ts, extractor] of cases) {
+ const raw = extractPage({ html: fixture(name), capture: captureOf(url, ts) });
+ assert.equal(raw.extractor.name, extractor, name);
+ const wrapped = wrapLikeArchiveToday(fixture(name), { id: "Qr5sT", original: url, timestamp: ts });
+ const un = unwrapArchiveTodayHtml(wrapped, "https://archive.ph/Qr5sT");
+ const viaArchive = extractPage({ html: un.html, capture: { ...captureOf(url, ts), waybackUrl: "https://archive.ph/Qr5sT", rawUrl: "https://archive.ph/Qr5sT" } });
+ assert.equal(viaArchive.extractor.name, extractor, `${name}: the site extractor still claims it`);
+ assert.equal(viaArchive.fallback, undefined, name);
+ assert.deepEqual(viaArchive.drafts, raw.drafts, name);
+ // Each image a record names becomes archive.today's cached copy.
+ for (const d of viaArchive.drafts) {
+ for (const m of mapArchiveTodayMedia(d.media, un.images) ?? []) {
+ assert.match(m.url, /^https:\/\/archive\.ph\/Qr5sT\/|^https?:\/\/(?!web\.archive\.org)/, `${name}: ${m.url}`);
+ }
+ }
+ }
+});
+
+test("a body that is not archive.today's frame passes through, its links still restored", () => {
+ const un = unwrapArchiveTodayHtml('<html><body><a href="https://archive.ph/o/Ab3dE/https://a.example/x">x</a></body></html>', "https://archive.ph/Ab3dE");
+ assert.equal(un.framed, false);
+ assert.match(un.html, /href="https:\/\/a\.example\/x"/);
+});
+
+test("media: a Wayback image form of an uncached original becomes the original", () => {
+ assert.deepEqual(
+ mapArchiveTodayMedia([{ kind: "image", url: "https://web.archive.org/web/2019im_/https://journal.example/a.png" }], new Map()),
+ [{ kind: "image", url: "https://journal.example/a.png" }],
+ );
+});
diff --git a/common/lib/archives/archiveToday.ts b/common/lib/archives/archiveToday.ts
@@ -0,0 +1,310 @@
+// archive.today's ANSWERS, read (release 37 lane F). Pure: no network, no disk,
+// no clock — the client (archiveTodayClient.ts) fetches, this reads.
+//
+// - its TIMEMAP (the Memento protocol's link format) as capture rows;
+// - a copy's FACTS from its answer's headers (Memento-Datetime, Link
+// rel="original") or, when a copy was read through a browser and has no
+// headers, from the copy's own header bar;
+// - its CHECK PAGE (a CAPTCHA, "one more step", a browser check) told apart
+// from a copy, so a check is a typed refusal and never a parsed record;
+// - a copy UNWRAPPED: archive.today serves its snapshot rewritten — its own
+// header bar on top, the page inside `#CONTENT`, links out of it as
+// `/o/<id>/<url>`, images as its own cached copies (the original kept as
+// `old-src` where it keeps it). Unwrapping takes the bar off, puts the
+// original hrefs (and image srcs) back, and keeps the title and the page's
+// own <meta>s, so the extractors (generic, and the site ones) read it the
+// way they read a raw Wayback body. The images a record names afterwards
+// are archive.today's cached copies (`mapArchiveTodayMedia`).
+//
+// The layout is archive.today's as known on 2026-10-20 (no live copy was read
+// to write this: synthetic fixtures only). The stored body is the copy AS
+// SERVED, so a better unwrap re-derives every record offline (reextract-pages).
+
+import { isArchiveTodayHost, timestampOfDate, unwrapArchiveTodayOutlink } from "./mementos";
+import { parseWaybackUrl } from "../wayback";
+import type { PostMedia } from "../posts";
+import type { ArchiveCaptureRow } from "./types";
+
+// ─── The timemap ───
+
+export type LinkEntry = { url: string; params: Record<string, string> };
+
+// RFC 6690 link format: `<url>; rel="…"; datetime="…", <url>; …`. URLs may
+// hold commas, so entries are read by their `<…>` brackets, not split.
+export function parseLinkFormat(text: string): LinkEntry[] {
+ const out: LinkEntry[] = [];
+ const re = /<([^>]*)>((?:\s*;\s*[A-Za-z][\w-]*\s*=\s*(?:"[^"]*"|[^;,<]*))*)/g;
+ for (const m of text.matchAll(re)) {
+ const params: Record<string, string> = {};
+ for (const p of m[2].matchAll(/;\s*([A-Za-z][\w-]*)\s*=\s*(?:"([^"]*)"|([^;,<]*))/g)) {
+ params[p[1].toLowerCase()] = (p[2] ?? p[3] ?? "").trim();
+ }
+ out.push({ url: m[1].trim(), params });
+ }
+ return out;
+}
+
+const relsOf = (e: LinkEntry) => (e.params.rel ?? "").toLowerCase().split(/\s+/).filter(Boolean);
+
+// A timemap's copies, oldest first. The original is the entry rel="original"
+// (else `fallbackOriginal`).
+export function parseArchiveTodayTimemap(text: string, fallbackOriginal: string): ArchiveCaptureRow[] {
+ const entries = parseLinkFormat(text);
+ const original = entries.find((e) => relsOf(e).includes("original"))?.url || fallbackOriginal;
+ const rows: ArchiveCaptureRow[] = [];
+ const seen = new Set<string>();
+ for (const e of entries) {
+ if (!relsOf(e).includes("memento")) continue;
+ const ts = timestampOfDate(e.params.datetime);
+ if (!ts || seen.has(e.url)) continue;
+ seen.add(e.url);
+ rows.push({ source: "archive.today", captureTs: ts, originalUrl: original, mementoUrl: e.url, status: "200", mimetype: "text/html" });
+ }
+ return rows.sort((a, b) => a.captureTs.localeCompare(b.captureTs) || a.mementoUrl.localeCompare(b.mementoUrl));
+}
+
+// The rows within capture-time prefixes `from`/`to` (inclusive), like CDX's.
+export function withinCaptureRange(ts: string, from?: string, to?: string): boolean {
+ if (from && ts.slice(0, from.length) < from) return false;
+ if (to && ts.slice(0, to.length) > to) return false;
+ return true;
+}
+
+// The row nearest `at` (4–14 digits), the earlier of two as near.
+export function nearestCapture<T extends { captureTs: string }>(rows: readonly T[], at: string): T | null {
+ const want = Number(at.padEnd(14, "0"));
+ let best: T | null = null;
+ let bestD = Infinity;
+ for (const r of rows) {
+ const d = Math.abs(Number(r.captureTs.padEnd(14, "0")) - want);
+ if (d < bestD || (d === bestD && best && r.captureTs < best.captureTs)) {
+ best = r;
+ bestD = d;
+ }
+ }
+ return best;
+}
+
+// ─── A copy's facts ───
+
+export type CopyFacts = { captureTs?: string; originalUrl?: string };
+
+// From the answer's headers: Memento-Datetime, and the Link header's
+// rel="original".
+export function copyFactsFromHeaders(headers: { get(name: string): string | null }): CopyFacts {
+ const out: CopyFacts = {};
+ const ts = timestampOfDate(headers.get("memento-datetime"));
+ if (ts) out.captureTs = ts;
+ const link = headers.get("link");
+ if (link) {
+ const orig = parseLinkFormat(link).find((e) => relsOf(e).includes("original"))?.url;
+ if (orig && /^https?:\/\//i.test(orig)) out.originalUrl = orig;
+ }
+ return out;
+}
+
+const attr = (tag: string, name: string): string | undefined => {
+ const m = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i").exec(tag);
+ return m ? decodeEntities(m[1] ?? m[2] ?? m[3] ?? "") : undefined;
+};
+
+function decodeEntities(s: string): string {
+ return s
+ .replace(/"/g, '"')
+ .replace(/'|'/gi, "'")
+ .replace(/</g, "<")
+ .replace(/>/g, ">")
+ .replace(/&/g, "&");
+}
+
+// From the copy's own header bar (a copy read through a browser has no
+// headers): the "saved from" URL box and the capture's <time datetime>.
+export function copyFactsFromHtml(html: string): CopyFacts {
+ const out: CopyFacts = {};
+ const header = blockById(html, "HEADER")?.outer ?? "";
+ if (!header) return out;
+ for (const m of header.matchAll(/<input\b[^>]*>/gi)) {
+ const value = attr(m[0], "value");
+ if (value && /^https?:\/\//i.test(value)) {
+ try {
+ if (!isArchiveTodayHost(new URL(value).hostname)) {
+ out.originalUrl = value;
+ break;
+ }
+ } catch {
+ // not a URL
+ }
+ }
+ }
+ const time = /<time\b[^>]*\sdatetime\s*=\s*["']([^"']+)["']/i.exec(header)?.[1];
+ const ts = timestampOfDate(time);
+ if (ts) out.captureTs = ts;
+ return out;
+}
+
+// ─── The check page ───
+
+const CHALLENGE_MARKERS: RegExp[] = [
+ /\bg-recaptcha\b/i,
+ /\bh-captcha\b/i,
+ /hcaptcha\.com\/1\/api\.js/i,
+ /google\.com\/recaptcha\//i,
+ /challenges\.cloudflare\.com/i,
+ /\bcf-chl-/i,
+ /<title>\s*(?:just a moment|attention required|one more step)/i,
+ /please complete the security check/i,
+ /checking (?:if the site connection is secure|your browser)/i,
+];
+
+// Whether an answer is a CHECK in front of the copy, not the copy: a
+// CAPTCHA, a "one more step" page, a browser check. A copy holds archive.today's
+// header bar and its content block; a check holds neither.
+export function isArchiveTodayChallenge(html: string): boolean {
+ const head = html.slice(0, 64 * 1024);
+ if (!CHALLENGE_MARKERS.some((re) => re.test(head))) return false;
+ // A copy OF a page that itself carried a captcha (a sign-up form) keeps
+ // archive.today's own frame around it.
+ return !(blockById(html, "CONTENT") && blockById(html, "HEADER"));
+}
+
+// A short phrase for a check page, for the refusal sentence.
+export function challengeDetail(html: string): string {
+ if (/recaptcha|hcaptcha|h-captcha/i.test(html)) return "a CAPTCHA";
+ if (/challenges\.cloudflare\.com|cf-chl-/i.test(html)) return "a browser check";
+ return "a check page";
+}
+
+// ─── Unwrapping ───
+
+// The element with `id="<id>"`: its outer HTML, inner HTML and offsets, by
+// counting its tag's opens and closes.
+export function blockById(html: string, id: string): { outer: string; inner: string; start: number; end: number } | null {
+ const open = new RegExp(`<([a-zA-Z][\\w-]*)\\b[^>]*\\sid\\s*=\\s*(?:"${id}"|'${id}'|${id}(?=[\\s/>]))[^>]*>`, "i").exec(html);
+ if (!open) return null;
+ const tag = open[1].toLowerCase();
+ const start = open.index;
+ const innerStart = start + open[0].length;
+ const re = new RegExp(`<(/?)${tag}\\b[^>]*>`, "gi");
+ re.lastIndex = innerStart;
+ let depth = 1;
+ for (let m = re.exec(html); m; m = re.exec(html)) {
+ if (m[0].endsWith("/>")) continue;
+ depth += m[1] ? -1 : 1;
+ if (depth === 0) {
+ return { outer: html.slice(start, m.index + m[0].length), inner: html.slice(innerStart, m.index), start, end: m.index + m[0].length };
+ }
+ }
+ return { outer: html.slice(start), inner: html.slice(innerStart), start, end: html.length };
+}
+
+export type UnwrappedCopy = {
+ // The copy as a page: <head> with the title and the page's own metas,
+ // <body> the copied page.
+ html: string;
+ // An image's original URL → archive.today's cached copy, for each image the
+ // copy names both of.
+ images: Map<string, string>;
+ // Whether the copy carried archive.today's frame (a body without one is
+ // passed through as it is).
+ framed: boolean;
+};
+
+function absolute(href: string, base: string): string {
+ try {
+ return new URL(href, base).toString();
+ } catch {
+ return href;
+ }
+}
+
+// One tag with its href/src restored: `/o/<id>/<url>` → <url>, `old-href` /
+// `old-src` → the attribute, a relative cached image made absolute on the
+// copy's host.
+function restoreTag(tag: string, mementoUrl: string, images: Map<string, string>): string {
+ let out = tag;
+ const name = /^<([a-zA-Z][\w-]*)/.exec(tag)?.[1].toLowerCase() ?? "";
+ const oldHref = attr(tag, "old-href");
+ const href = attr(tag, "href");
+ if (oldHref && /^https?:\/\//i.test(oldHref)) {
+ out = setAttr(out, "href", oldHref);
+ } else if (href) {
+ const un = unwrapArchiveTodayOutlink(href);
+ if (un !== href) out = setAttr(out, "href", un);
+ }
+ if (name === "img" || name === "source") {
+ const src = attr(tag, "src");
+ const oldSrc = attr(tag, "old-src");
+ const cached = src ? absolute(src, mementoUrl) : undefined;
+ if (oldSrc && /^https?:\/\//i.test(oldSrc)) {
+ out = setAttr(out, "src", oldSrc);
+ if (cached && cached !== oldSrc) images.set(oldSrc, cached);
+ } else if (cached && src !== cached) {
+ out = setAttr(out, "src", cached);
+ }
+ }
+ return out.replace(/\s(?:old-href|old-src)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "");
+}
+
+function setAttr(tag: string, name: string, value: string): string {
+ const v = value.replace(/&/g, "&").replace(/"/g, """);
+ const re = new RegExp(`(\\s${name}\\s*=\\s*)(?:"[^"]*"|'[^']*'|[^\\s>]+)`, "i");
+ if (re.test(tag)) return tag.replace(re, `$1"${v}"`);
+ return tag.replace(/^(<[a-zA-Z][\w-]*)/, `$1 ${name}="${v}"`);
+}
+
+// The <meta>s of the copy's head that are the PAGE's (archive.today's own —
+// anything naming one of its hosts — left out).
+function pageMetas(head: string): string[] {
+ const out: string[] = [];
+ for (const m of head.matchAll(/<meta\b[^>]*>/gi)) {
+ const content = attr(m[0], "content") ?? "";
+ if (/archive\.(?:ph|today|is|li|vn|fo|md)\b/i.test(content)) continue;
+ if (/\bhttp-equiv\s*=/i.test(m[0])) continue;
+ out.push(m[0]);
+ }
+ return out;
+}
+
+const SCRIPT_RE = /<script\b[\s\S]*?<\/script\s*>/gi;
+
+// THE COPY AS A PAGE (see the head of this file). A body that is not an
+// archive.today frame (no #CONTENT) keeps its markup, with the hrefs and
+// srcs restored all the same.
+export function unwrapArchiveTodayHtml(html: string, mementoUrl: string): UnwrappedCopy {
+ const images = new Map<string, string>();
+ const content = blockById(html, "CONTENT");
+ const headEnd = /<\/head\s*>/i.exec(html);
+ const head = headEnd ? html.slice(0, headEnd.index) : "";
+ const title = /<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(head || html)?.[1]?.trim() ?? "";
+ const restore = (s: string) => s.replace(/<(?:a|area|link|img|source)\b[^>]*>/gi, (tag) => restoreTag(tag, mementoUrl, images));
+ if (!content) {
+ return { html: restore(html), images, framed: false };
+ }
+ const metas = pageMetas(head);
+ const body = restore(content.inner.replace(SCRIPT_RE, ""));
+ const out =
+ "<!doctype html>\n<html><head>" +
+ '<meta charset="utf-8">' +
+ (title ? `<title>${title}</title>` : "") +
+ metas.join("") +
+ `</head><body>${body}</body></html>`;
+ return { html: out, images, framed: true };
+}
+
+// A record's media, as archive.today holds them: an image the copy cached is
+// its cached copy (an original the extractor named, or a Wayback form the
+// generic extractor gave it), an archive.today URL stays, and a Wayback image
+// URL of anything else becomes the original it wraps — a record from
+// archive.today links no Wayback copy it was never checked against.
+export function mapArchiveTodayMedia(media: PostMedia[] | undefined, images: ReadonlyMap<string, string>): PostMedia[] | undefined {
+ if (!media) return media;
+ const out: PostMedia[] = [];
+ for (const m of media) {
+ let url = m.url;
+ const wb = parseWaybackUrl(url);
+ if (wb) url = wb.originalUrl;
+ url = images.get(url) ?? url;
+ if (!out.some((x) => x.url === url && x.kind === m.kind)) out.push({ ...m, url });
+ }
+ return out;
+}
diff --git a/common/lib/archives/archiveTodayClient.test.ts b/common/lib/archives/archiveTodayClient.test.ts
@@ -0,0 +1,231 @@
+// Release 37 lane F: the archive.today client on the fake archive.today —
+// timemaps, copies in every URL form, one canonical host, the long gap, a 429
+// that stops and rests the client, a check page refused (never parsed), and a
+// check read once more through a (fake) browser.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/archives/archiveTodayClient.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ startFakeArchiveToday,
+ wrapLikeArchiveToday,
+ CHALLENGE_HTML,
+ COPIES,
+ AT_ARTICLE_ID,
+ AT_ARTICLE_LATER_ID,
+ AT_ARTICLE_LATER_TS,
+ AT_ARTICLE_TS,
+ AT_ARTICLE_URL,
+ AT_CHECKED_ID,
+ AT_CHECKED_TS,
+ AT_CHECKED_URL,
+} from "../../testing/web/fakeArchiveToday.mjs";
+import { ArchiveTodayClient, ARCHIVE_TODAY_USER_AGENT, type ArchiveTodayBrowser } from "./archiveTodayClient";
+import { ArchiveRefusal } from "./types";
+
+// A clock the client's sleeps move, so the gap is measured, not waited.
+function fakeClock() {
+ let t = 1_000_000;
+ const sleeps: number[] = [];
+ return {
+ now: () => t,
+ sleep: async (ms: number) => {
+ sleeps.push(ms);
+ t += ms;
+ },
+ sleeps,
+ };
+}
+
+async function withFake(
+ opts: Parameters<typeof startFakeArchiveToday>[0],
+ fn: (at: Awaited<ReturnType<typeof startFakeArchiveToday>>, clock: ReturnType<typeof fakeClock>) => Promise<void>,
+) {
+ const at = await startFakeArchiveToday(opts);
+ const clock = fakeClock();
+ try {
+ await fn(at, clock);
+ } finally {
+ await at.close();
+ }
+}
+
+const refusalOf = async (p: Promise<unknown>) => {
+ try {
+ await p;
+ } catch (e) {
+ if (e instanceof ArchiveRefusal) return e;
+ throw e;
+ }
+ assert.fail("expected a refusal");
+};
+
+test("the timemap's copies, oldest first, bounded; a page it holds nothing of is none; the nearest copy", async () => {
+ await withFake({}, async (at, clock) => {
+ const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0 });
+ const rows = await c.listCaptures(AT_ARTICLE_URL);
+ assert.deepEqual(
+ rows.map((r) => [r.captureTs, r.mementoUrl]),
+ [
+ [AT_ARTICLE_TS, `https://archive.ph/${AT_ARTICLE_ID}`],
+ [AT_ARTICLE_LATER_TS, `https://archive.ph/${AT_ARTICLE_LATER_ID}`],
+ ],
+ );
+ assert.deepEqual((await c.listCaptures(AT_ARTICLE_URL, { from: "2020" })).map((r) => r.captureTs), [AT_ARTICLE_LATER_TS]);
+ assert.equal((await c.listCaptures(AT_ARTICLE_URL, { limit: 1 })).length, 1);
+ assert.deepEqual(await c.listCaptures("https://nothing.example/"), []);
+ assert.equal((await c.closestCapture(AT_ARTICLE_URL, "20191215"))?.mementoUrl, `https://archive.ph/${AT_ARTICLE_LATER_ID}`);
+ assert.equal(await c.closestCapture("https://nothing.example/", "2019"), null);
+ assert.ok(at.requests.every((r) => r.ua === ARCHIVE_TODAY_USER_AGENT), "identified on every request");
+ });
+});
+
+test("one copy by its short id, its time and page from its Memento headers; the bytes as served, the page unwrapped", async () => {
+ await withFake({}, async (at, clock) => {
+ const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0 });
+ const cap = await c.getCapture(`https://archive.is/${AT_ARTICLE_ID}`);
+ assert.equal(cap.source, "archive.today");
+ assert.equal(cap.finalTs, AT_ARTICLE_TS);
+ assert.equal(cap.originalUrl, AT_ARTICLE_URL);
+ assert.equal(cap.mementoUrl, `https://archive.ph/${AT_ARTICLE_ID}`);
+ assert.equal(cap.mimetype, "text/html");
+ assert.equal(cap.unwrapped, true);
+ assert.match(cap.body.toString("utf8"), /id="HEADER"/, "the body is the copy as served");
+ assert.doesNotMatch(cap.page, /id="HEADER"/, "the page is unwrapped");
+ assert.equal(cap.bytes, cap.body.byteLength);
+ assert.match(cap.sha256, /^[0-9a-f]{64}$/);
+ // Asked on archive.ph whatever name the URL used.
+ assert.deepEqual(at.requests.map((r) => r.path), [`/${AT_ARTICLE_ID}`]);
+ });
+});
+
+test("a timestamp URL, newest and oldest: redirected inside archive.today to the copy", async () => {
+ await withFake({}, async (at, clock) => {
+ const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0 });
+ assert.equal((await c.getCapture(`https://archive.ph/2019.12.20-000000/${AT_ARTICLE_URL}`)).mementoUrl, `https://archive.ph/${AT_ARTICLE_LATER_ID}`);
+ assert.equal((await c.getCapture(`https://archive.ph/oldest/${AT_ARTICLE_URL}`)).finalTs, AT_ARTICLE_TS);
+ assert.equal((await c.getCapture(`https://archive.ph/newest/${AT_ARTICLE_URL}`)).finalTs, AT_ARTICLE_LATER_TS);
+ const none = await refusalOf(c.getCapture("https://archive.ph/Zz0zZ"));
+ assert.equal(none.code, "not-archived");
+ });
+});
+
+test("ONE stream, the long gap from the end of one request to the start of the next, jittered", async () => {
+ await withFake({}, async (at, clock) => {
+ const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0.5 }, { minGapMs: 8_000, jitter: 0.25 });
+ await Promise.all([c.listCaptures(AT_ARTICLE_URL), c.getCapture(`https://archive.ph/${AT_ARTICLE_ID}`), c.getCapture(`https://archive.ph/${AT_ARTICLE_LATER_ID}`)]);
+ assert.equal(c.requests, 3);
+ // The first request waits for nothing; each later one 8 s × (1 + 0.5 × 0.25).
+ assert.deepEqual(clock.sleeps, [9_000, 9_000]);
+ });
+});
+
+test("a 429 stops the run with a sentence and rests the client: nothing more is sent until the cool-down ends", async () => {
+ await withFake({ busyTimes: 1 }, async (at, clock) => {
+ const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0 }, { cooldownMs: 30 * 60_000 });
+ const r = await refusalOf(c.getCapture(`https://archive.ph/${AT_ARTICLE_ID}`));
+ assert.equal(r.code, "rate-limited");
+ assert.match(r.message, /HTTP 429 \(too many requests\).*stopped.*30 min/);
+ assert.equal(at.requests.length, 1, "no retry of a 429");
+ const again = await refusalOf(c.listCaptures(AT_ARTICLE_URL));
+ assert.equal(again.code, "rate-limited");
+ assert.match(again.message, /was not asked/);
+ assert.equal(at.requests.length, 1, "nothing sent during the cool-down");
+ assert.ok(c.cooldownUntil > clock.now());
+ await clock.sleep(31 * 60_000);
+ assert.equal((await c.listCaptures(AT_ARTICLE_URL)).length, 2);
+ });
+});
+
+test("a check page is a typed refusal and never a record; it names Connect archive session", async () => {
+ for (const challengeStatus of [200, 429, 503]) {
+ await withFake({ challenge: [AT_CHECKED_ID], challengeStatus }, async (at, clock) => {
+ const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0 });
+ const r = await refusalOf(c.getCapture(`https://archive.ph/${AT_CHECKED_ID}`));
+ assert.equal(r.code, "challenge", `status ${challengeStatus}`);
+ assert.match(r.message, /a CAPTCHA instead of the copy; nothing was read\. Connect archive session/);
+ assert.equal(c.cooldownUntil, 0, "a check is not a rate limit");
+ });
+ }
+});
+
+test("a check read once more through the browser: cleared there, the copy is read from the page; still there, refused", async () => {
+ await withFake({ challenge: [AT_CHECKED_ID] }, async (at, clock) => {
+ const wrapped = wrapLikeArchiveToday(COPIES[2].page(), { id: AT_CHECKED_ID, original: AT_CHECKED_URL, timestamp: AT_CHECKED_TS });
+ let opened = 0;
+ let closed = 0;
+ const cleared = async (): Promise<ArchiveTodayBrowser> => {
+ opened++;
+ return {
+ load: async (url) => ({ html: wrapped, text: "", url }),
+ close: async () => {
+ closed++;
+ },
+ };
+ };
+ const c = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0, openBrowser: cleared });
+ const cap = await c.getCapture(`https://archive.ph/${AT_CHECKED_ID}`);
+ assert.equal(cap.viaBrowser, true);
+ assert.equal(cap.finalTs, AT_CHECKED_TS, "time read from the copy's header bar");
+ assert.equal(cap.originalUrl, AT_CHECKED_URL);
+ assert.match(cap.page, /A page held behind a check/);
+ assert.equal(c.browserLoads, 1);
+ assert.deepEqual([opened, closed], [1, 1], "the browser is closed after the one read");
+
+ const stillChecked = new ArchiveTodayClient({
+ fetch: at.fetch,
+ now: clock.now,
+ sleep: clock.sleep,
+ random: () => 0,
+ openBrowser: async () => ({ load: async (url) => ({ html: CHALLENGE_HTML, text: "", url }), close: async () => {} }),
+ });
+ const r = await refusalOf(stillChecked.getCapture(`https://archive.ph/${AT_CHECKED_ID}`));
+ assert.equal(r.code, "challenge");
+ assert.match(r.message, /in the headless browser too/);
+
+ const off = new ArchiveTodayClient({ fetch: at.fetch, now: clock.now, sleep: clock.sleep, random: () => 0, openBrowser: cleared, browserEnabled: () => false });
+ assert.equal((await refusalOf(off.getCapture(`https://archive.ph/${AT_CHECKED_ID}`))).code, "challenge");
+ assert.equal(opened, 1, "a browser turned off in settings is not opened");
+ });
+});
+
+test("the canonical host comes from settings; every name is sent there", async () => {
+ await withFake({}, async (at, clock) => {
+ const hosts: string[] = [];
+ const c = new ArchiveTodayClient({
+ fetch: (url, init) => {
+ hosts.push(new URL(url).hostname);
+ return at.fetch(url, init);
+ },
+ now: clock.now,
+ sleep: clock.sleep,
+ random: () => 0,
+ host: () => "archive.li",
+ });
+ const cap = await c.getCapture(`https://archive.vn/oldest/${AT_ARTICLE_URL}`);
+ assert.equal(cap.mementoUrl, `https://archive.li/${AT_ARTICLE_ID}`);
+ assert.deepEqual([...new Set(hosts)], ["archive.li"]);
+ });
+});
+
+test("an answer that is not a page, and one over the cap, are refused", async () => {
+ const fetchOf = (body: string, type: string) => async () => new Response(body, { status: 200, headers: { "content-type": type, "memento-datetime": "Sun, 12 May 2019 08:30:00 GMT" } });
+ const clock = fakeClock();
+ const img = new ArchiveTodayClient({ fetch: fetchOf("x", "image/png"), now: clock.now, sleep: clock.sleep });
+ assert.equal((await refusalOf(img.getCapture("https://archive.ph/Ab3dE"))).code, "mimetype");
+ const big = new ArchiveTodayClient({ fetch: fetchOf("x".repeat(5000), "text/html"), now: clock.now, sleep: clock.sleep });
+ assert.equal((await refusalOf(big.getCapture("https://archive.ph/Ab3dE", { maxBytes: 1000 }))).code, "too-large");
+ const nameless = new ArchiveTodayClient({
+ fetch: async () => new Response("<html><body>a page</body></html>", { status: 200, headers: { "content-type": "text/html" } }),
+ now: clock.now,
+ sleep: clock.sleep,
+ });
+ assert.equal((await refusalOf(nameless.getCapture("https://archive.ph/Ab3dE"))).code, "unreadable");
+ const away = new ArchiveTodayClient({
+ fetch: async () => new Response("", { status: 302, headers: { location: "https://elsewhere.example/" } }),
+ now: clock.now,
+ sleep: clock.sleep,
+ });
+ assert.equal((await refusalOf(away.getCapture("https://archive.ph/Ab3dE"))).code, "offsite-redirect");
+});
diff --git a/common/lib/archives/archiveTodayClient.ts b/common/lib/archives/archiveTodayClient.ts
@@ -0,0 +1,537 @@
+// THE POLITE archive.today CLIENT (release 37 lane F): every request this app
+// makes to archive.today — a page's timemap, one copy's bytes. archive.today is
+// one person's service and says so; the rules here are the operator's "polite
+// scraping", made mechanical:
+//
+// ONE AT A TIME requests are chained: a second caller waits for the first
+// to finish, and then for the gap.
+// A LONG GAP at least `minGapMs` (8 s; settings.archives) between the
+// end of one request and the start of the next, plus up to
+// a quarter more at random.
+// IDENTIFIED a User-Agent naming the project and its URL.
+// STOPS AT A 429 "too many requests" is not waited out and retried: the
+// run stops with a sentence (ArchiveRefusal
+// "rate-limited"), and the client sends NOTHING to
+// archive.today for `cooldownMs` (30 min) or the
+// Retry-After, whichever is longer. A 502/503/504 (or a
+// dropped connection) is retried after an exponential
+// wait, a few times.
+// NEVER SOLVES archive.today often answers a client that is not a
+// browser with a check (a CAPTCHA, a browser check). That
+// is told apart from a copy (lib/archives/archiveToday.ts
+// isArchiveTodayChallenge) and never parsed as one. With a
+// browser (`openBrowser`), the copy is read once more
+// through the headless browser on the archive session's
+// profile — a check the operator cleared in Connect
+// archive session stays cleared there — and a check that
+// still stands is refused ("challenge"). Nothing is ever
+// clicked or answered by code.
+//
+// Every URL is sent to ONE canonical host (settings.archives.archiveTodayHost,
+// default archive.ph), whichever of archive.today's names a copy's URL used.
+
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { PROJECT_NAME, PROJECT_URL } from "../project";
+import { bareMimetype, isPageMimetype, PAGE_MIMETYPES } from "../waybackPages/urls";
+import {
+ archiveTodayHostOf,
+ isArchiveTodayHost,
+ parseArchiveTodayUrl,
+} from "./mementos";
+import {
+ challengeDetail,
+ copyFactsFromHeaders,
+ copyFactsFromHtml,
+ isArchiveTodayChallenge,
+ nearestCapture,
+ parseArchiveTodayTimemap,
+ unwrapArchiveTodayHtml,
+ withinCaptureRange,
+} from "./archiveToday";
+import { ArchiveRefusal, type ArchiveCaptureRow, type ArchiveMementoRef, type ArchiveRawCapture } from "./types";
+
+export const ARCHIVE_TODAY_QUEUE = "platform:archive.today";
+export const ARCHIVE_TODAY_USER_AGENT = `${PROJECT_NAME} archive.today import (+${PROJECT_URL})`;
+export const ARCHIVE_TODAY_MAX_REDIRECTS = 5;
+// A copy's body is read up to this (the Wayback page cap's size).
+export const ARCHIVE_TODAY_PAGE_MAX_BYTES = 2 * 1024 * 1024;
+// A non-200 answer's body is read this far (enough to tell a check page).
+const ERROR_BODY_BYTES = 256 * 1024;
+
+const PAGE_ACCEPT = "text/html,application/xhtml+xml;q=0.9,*/*;q=0.1";
+const RETRYABLE = new Set([502, 503, 504]);
+
+// The connect sentence every challenge refusal ends with.
+export const CONNECT_ARCHIVE_SESSION_HINT =
+ "Connect archive session (the channel page's Archived pages panel, or Settings), pass the check once in the window, then try again";
+
+export class ArchiveTodayRequestError extends Error {
+ readonly status: number | null;
+ constructor(message: string, status: number | null) {
+ super(message);
+ this.name = "ArchiveTodayRequestError";
+ this.status = status;
+ }
+}
+
+// What the headless browser hands back for one URL.
+export type ArchiveTodayBrowserLoad = { html: string; text: string; url: string; status?: number };
+export type ArchiveTodayBrowser = {
+ load(url: string, signal?: AbortSignal): Promise<ArchiveTodayBrowserLoad>;
+ close(): Promise<void>;
+};
+
+export type ArchiveTodayClientDeps = {
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
+ now?: () => number;
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
+ random?: () => number;
+ // The headless browser on the archive session's profile, opened only when a
+ // check stands in the way; null/absent = refuse at the check.
+ openBrowser?: (() => Promise<ArchiveTodayBrowser>) | null;
+ // Read per check: false = refuse at the check (settings can change while
+ // the editor runs).
+ browserEnabled?: () => boolean;
+ // The canonical host, read per request (settings can change while the
+ // editor runs).
+ host?: () => string;
+};
+
+export type ArchiveTodayClientOpts = {
+ minGapMs?: number | (() => number);
+ // Up to this fraction of the gap again, at random.
+ jitter?: number;
+ cooldownMs?: number | (() => number);
+ maxAttempts?: number;
+ baseBackoffMs?: number;
+ maxBackoffMs?: number;
+ timeoutMs?: number;
+};
+
+type Answer = {
+ status: number;
+ headers: Headers;
+ location: string | null;
+ body: Buffer | null;
+ bytes: number;
+ tooLarge: boolean;
+ url: string;
+};
+
+function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) return reject(signal.reason ?? new Error("aborted"));
+ const t = setTimeout(() => {
+ signal?.removeEventListener("abort", onAbort);
+ resolve();
+ }, ms);
+ const onAbort = () => {
+ clearTimeout(t);
+ reject(signal?.reason ?? new Error("aborted"));
+ };
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+}
+
+function retryAfterMs(value: string | null, nowMs: number): number | null {
+ if (!value) return null;
+ const v = value.trim();
+ if (/^\d+$/.test(v)) return Number(v) * 1000;
+ const at = Date.parse(v);
+ return Number.isFinite(at) ? Math.max(0, at - nowMs) : null;
+}
+
+const minutes = (ms: number) => Math.max(1, Math.round(ms / 60_000));
+
+export class ArchiveTodayClient {
+ private readonly deps: Required<Omit<ArchiveTodayClientDeps, "openBrowser" | "host" | "browserEnabled">> &
+ Pick<ArchiveTodayClientDeps, "openBrowser" | "host" | "browserEnabled">;
+ private readonly opts: Required<Omit<ArchiveTodayClientOpts, "minGapMs" | "cooldownMs">> & {
+ minGapMs: () => number;
+ cooldownMs: () => number;
+ };
+ private chain: Promise<unknown> = Promise.resolve();
+ private lastDoneAt = -Infinity;
+ private coolUntil = 0;
+ // Requests actually sent (each attempt), and copies read through the
+ // browser — for tests and logs.
+ requests = 0;
+ browserLoads = 0;
+
+ constructor(deps: ArchiveTodayClientDeps = {}, opts: ArchiveTodayClientOpts = {}) {
+ this.deps = {
+ fetch: deps.fetch ?? ((url, init) => fetch(url, init)),
+ now: deps.now ?? (() => Date.now()),
+ sleep: deps.sleep ?? defaultSleep,
+ random: deps.random ?? Math.random,
+ ...(deps.openBrowser ? { openBrowser: deps.openBrowser } : {}),
+ ...(deps.host ? { host: deps.host } : {}),
+ ...(deps.browserEnabled ? { browserEnabled: deps.browserEnabled } : {}),
+ };
+ const gap = opts.minGapMs ?? 8_000;
+ const cool = opts.cooldownMs ?? 30 * 60_000;
+ this.opts = {
+ minGapMs: typeof gap === "function" ? gap : () => gap,
+ cooldownMs: typeof cool === "function" ? cool : () => cool,
+ jitter: opts.jitter ?? 0.25,
+ maxAttempts: opts.maxAttempts ?? 3,
+ baseBackoffMs: opts.baseBackoffMs ?? 10_000,
+ maxBackoffMs: opts.maxBackoffMs ?? 120_000,
+ timeoutMs: opts.timeoutMs ?? 60_000,
+ };
+ }
+
+ get host(): string {
+ return archiveTodayHostOf(this.deps.host?.() ?? undefined);
+ }
+
+ // When the client will next send a request after a 429 (epoch ms), or 0.
+ get cooldownUntil(): number {
+ return this.coolUntil > this.deps.now() ? this.coolUntil : 0;
+ }
+
+ // Any archive.today URL on the canonical host.
+ canonical(url: string): string {
+ const u = new URL(url);
+ if (isArchiveTodayHost(u.hostname)) {
+ u.hostname = this.host;
+ u.protocol = "https:";
+ u.port = "";
+ }
+ return u.toString();
+ }
+
+ private serial<T>(fn: () => Promise<T>): Promise<T> {
+ const run = this.chain.then(fn, fn);
+ this.chain = run.catch(() => {});
+ return run;
+ }
+
+ private assertNotCooling(url: string): void {
+ const now = this.deps.now();
+ if (this.coolUntil > now) {
+ throw new ArchiveRefusal(
+ "archive.today",
+ "rate-limited",
+ `archive.today answered "too many requests" earlier; nothing is sent to it before ${new Date(this.coolUntil).toISOString()} ` +
+ `(${minutes(this.coolUntil - now)} min) — ${url} was not asked`,
+ { retryAt: this.coolUntil },
+ );
+ }
+ }
+
+ private async waitGap(signal?: AbortSignal): Promise<void> {
+ const gap = this.opts.minGapMs() * (1 + this.deps.random() * this.opts.jitter);
+ const wait = this.lastDoneAt + gap - this.deps.now();
+ if (wait > 0) await this.deps.sleep(Math.round(wait), signal);
+ }
+
+ // ONE GET (no redirect followed), the gap before it, its body read up to
+ // `maxBytes` (an error answer's to 256 KB). 502/503/504 and a dropped
+ // connection are retried; a 429 that is not a check page starts the
+ // cool-down and throws. Every other status is answered for the caller.
+ private async send(url: string, o: { accept: string; maxBytes: number; signal?: AbortSignal }): Promise<Answer> {
+ let lastError = "";
+ for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) {
+ this.assertNotCooling(url);
+ await this.waitGap(o.signal);
+ this.requests++;
+ let res: Response | null = null;
+ let answer: Answer | null = null;
+ try {
+ const timeout = AbortSignal.timeout(this.opts.timeoutMs);
+ res = await this.deps.fetch(url, {
+ signal: o.signal ? AbortSignal.any([o.signal, timeout]) : timeout,
+ redirect: "manual",
+ headers: { accept: o.accept, "user-agent": ARCHIVE_TODAY_USER_AGENT },
+ });
+ answer = await readAnswer(res, url, res.status >= 200 && res.status < 300 ? o.maxBytes : ERROR_BODY_BYTES);
+ } catch (err) {
+ if (o.signal?.aborted) throw err;
+ lastError = (err as Error).message;
+ } finally {
+ this.lastDoneAt = this.deps.now();
+ }
+ if (answer) {
+ if (answer.status === 429 && !(answer.body && isArchiveTodayChallenge(answer.body.toString("utf8")))) {
+ const wait = Math.max(this.opts.cooldownMs(), retryAfterMs(answer.headers.get("retry-after"), this.deps.now()) ?? 0);
+ this.coolUntil = this.deps.now() + wait;
+ throw new ArchiveRefusal(
+ "archive.today",
+ "rate-limited",
+ `archive.today answered HTTP 429 (too many requests) for ${url}; stopped, and nothing is sent to it for ` +
+ `${minutes(wait)} min (until ${new Date(this.coolUntil).toISOString()})`,
+ { retryAt: this.coolUntil },
+ );
+ }
+ if (!RETRYABLE.has(answer.status) || (answer.body && isArchiveTodayChallenge(answer.body.toString("utf8")))) return answer;
+ lastError = `HTTP ${answer.status}`;
+ }
+ if (attempt === this.opts.maxAttempts) break;
+ const exp = Math.min(this.opts.maxBackoffMs, this.opts.baseBackoffMs * 2 ** (attempt - 1));
+ await this.deps.sleep(Math.round(exp * (1 + (this.deps.random() * 0.4 - 0.2))), o.signal);
+ }
+ throw new ArchiveTodayRequestError(
+ `archive.today did not answer ${url} after ${this.opts.maxAttempts} attempts (${lastError}); stopping`,
+ null,
+ );
+ }
+
+ // The same URL through the headless browser, in the chain and after the
+ // gap. Null when no browser is offered.
+ private async viaBrowser(url: string, signal?: AbortSignal): Promise<ArchiveTodayBrowserLoad | null> {
+ if (!this.deps.openBrowser || this.deps.browserEnabled?.() === false) return null;
+ this.assertNotCooling(url);
+ await this.waitGap(signal);
+ this.browserLoads++;
+ let browser: ArchiveTodayBrowser | null = null;
+ try {
+ browser = await this.deps.openBrowser();
+ return await browser.load(url, signal);
+ } finally {
+ await browser?.close().catch(() => {});
+ this.lastDoneAt = this.deps.now();
+ }
+ }
+
+ private challengeRefusal(url: string, html: string, triedBrowser: boolean): ArchiveRefusal {
+ return new ArchiveRefusal(
+ "archive.today",
+ "challenge",
+ `archive.today answered ${url} with ${challengeDetail(html)} instead of the copy` +
+ (triedBrowser ? ", in the headless browser too" : "") +
+ `; nothing was read. ${CONNECT_ARCHIVE_SESSION_HINT}`,
+ );
+ }
+
+ // THE COPIES OF A PAGE, oldest first: its timemap
+ // (`/timemap/<original>`, one request). A 404 is "none". Within
+ // `from`/`to` (capture-time prefixes), at most `limit`.
+ listCaptures(
+ originalUrl: string,
+ o: { from?: string; to?: string; limit?: number; signal?: AbortSignal } = {},
+ ): Promise<ArchiveCaptureRow[]> {
+ return this.serial(async () => {
+ const url = `https://${this.host}/timemap/${originalUrl}`;
+ const res = await this.send(url, { accept: "application/link-format,text/plain;q=0.9,*/*;q=0.1", maxBytes: 8 * 1024 * 1024, signal: o.signal });
+ let text: string;
+ if (res.status === 404 || res.status === 410) return [];
+ const body = res.body?.toString("utf8") ?? "";
+ if (isArchiveTodayChallenge(body)) {
+ const b = await this.viaBrowser(url, o.signal);
+ if (!b || isArchiveTodayChallenge(b.html)) throw this.challengeRefusal(url, b?.html ?? body, !!b);
+ text = b.text;
+ } else if (res.status >= 200 && res.status < 300) {
+ if (res.tooLarge) throw new ArchiveTodayRequestError(`archive.today's timemap of ${originalUrl} is over 8 MB; not read`, res.status);
+ text = body;
+ } else {
+ throw new ArchiveTodayRequestError(`archive.today answered HTTP ${res.status} for ${url}`, res.status);
+ }
+ const rows = parseArchiveTodayTimemap(text, originalUrl)
+ .map((r) => ({ ...r, mementoUrl: this.canonical(r.mementoUrl) }))
+ .filter((r) => withinCaptureRange(r.captureTs, o.from, o.to));
+ return o.limit ? rows.slice(0, o.limit) : rows;
+ });
+ }
+
+ // The copy nearest `at` (4–14 digits) — one timemap request — or null.
+ async closestCapture(url: string, at: string, o: { signal?: AbortSignal } = {}): Promise<ArchiveCaptureRow | null> {
+ return nearestCapture(await this.listCaptures(url, { signal: o.signal }), at);
+ }
+
+ // ONE COPY: its bytes as served (what a page import stores), and the copy
+ // unwrapped as a page (`page`, what the extractors read). A memento URL in
+ // any of its forms; redirects followed inside archive.today only (a
+ // `/<ts>/<url>`, `/newest/` or `/oldest/` answer is a redirect to the copy),
+ // at most ARCHIVE_TODAY_MAX_REDIRECTS. The copy's time and page come from
+ // the answer's Memento headers, else its header bar, else the URL.
+ // Refused (ArchiveRefusal): no such copy ("not-archived"); a check that
+ // stands ("challenge"); not HTML ("mimetype"); over `maxBytes`
+ // ("too-large"); off archive.today or round in circles; no time or page
+ // to name it by ("unreadable"); a 429 ("rate-limited").
+ getCapture(
+ memento: string | ArchiveMementoRef,
+ o: { maxBytes?: number; signal?: AbortSignal } = {},
+ ): Promise<ArchiveRawCapture> {
+ return this.serial(async () => {
+ const maxBytes = o.maxBytes ?? ARCHIVE_TODAY_PAGE_MAX_BYTES;
+ const ref = typeof memento === "string" ? parseArchiveTodayUrl(memento, this.host) : memento;
+ if (!ref) {
+ throw new ArchiveRefusal("archive.today", "not-archived", `${String(memento)} is not an archive.today copy's URL`);
+ }
+ let at = this.canonical(ref.mementoUrl);
+ const seen = new Set<string>();
+ for (let hop = 0; hop <= ARCHIVE_TODAY_MAX_REDIRECTS; hop++) {
+ seen.add(at);
+ const res = await this.send(at, { accept: PAGE_ACCEPT, maxBytes, signal: o.signal });
+ if (res.status >= 300 && res.status < 400) {
+ const next = res.location;
+ let host = "";
+ try {
+ host = next ? new URL(next).hostname : "";
+ } catch {
+ host = "";
+ }
+ if (!next || !isArchiveTodayHost(host)) {
+ throw new ArchiveRefusal(
+ "archive.today",
+ "offsite-redirect",
+ `archive.today answered ${at} with a redirect off archive.today (${next ?? "no URL"}); only its own are followed`,
+ );
+ }
+ at = this.canonical(next);
+ if (seen.has(at)) throw new ArchiveRefusal("archive.today", "redirect-loop", `archive.today redirects ${ref.mementoUrl} in a loop (${at})`);
+ continue;
+ }
+ const text = res.body?.toString("utf8") ?? "";
+ if (res.body && isArchiveTodayChallenge(text)) {
+ const b = await this.viaBrowser(at, o.signal);
+ if (!b || isArchiveTodayChallenge(b.html)) throw this.challengeRefusal(at, b?.html ?? text, !!b);
+ return this.copyOf(Buffer.from(b.html, "utf8"), "text/html; charset=utf-8", b.url && isArchiveTodayHost(safeHost(b.url)) ? this.canonical(b.url) : at, null, ref, true);
+ }
+ if (res.status === 404 || res.status === 410) {
+ throw new ArchiveRefusal("archive.today", "not-archived", `archive.today holds no copy at ${at}`);
+ }
+ if (res.status < 200 || res.status >= 300) {
+ throw new ArchiveTodayRequestError(`archive.today answered HTTP ${res.status} for ${at}`, res.status);
+ }
+ const contentType = res.headers.get("content-type") ?? "text/html";
+ if (!isPageMimetype(contentType) || bareMimetype(contentType) !== "text/html") {
+ throw new ArchiveRefusal(
+ "archive.today",
+ "mimetype",
+ `archive.today's answer for ${at} is ${bareMimetype(contentType) || "of no stated type"}, not a copied page (${PAGE_MIMETYPES[0]})`,
+ );
+ }
+ if (res.tooLarge || !res.body) {
+ throw new ArchiveRefusal("archive.today", "too-large", `archive.today's copy at ${at} is over ${Math.round(maxBytes / 1024)} KB; not read`);
+ }
+ return this.copyOf(res.body, contentType, at, res.headers, ref, false);
+ }
+ throw new ArchiveRefusal("archive.today", "redirect-loop", `archive.today redirected ${ref.mementoUrl} more than ${ARCHIVE_TODAY_MAX_REDIRECTS} times`);
+ });
+ }
+
+ private copyOf(
+ body: Buffer,
+ contentType: string,
+ finalUrl: string,
+ headers: Headers | null,
+ ref: ArchiveMementoRef,
+ viaBrowser: boolean,
+ ): ArchiveRawCapture {
+ const html = body.toString("utf8");
+ const fromHeaders = headers ? copyFactsFromHeaders(headers) : {};
+ const fromHtml = copyFactsFromHtml(html);
+ const finalRef = parseArchiveTodayUrl(finalUrl, this.host);
+ const captureTs = fromHeaders.captureTs ?? fromHtml.captureTs ?? (finalRef?.captureTs?.length === 14 ? finalRef.captureTs : undefined) ?? (ref.captureTs?.length === 14 ? ref.captureTs : undefined);
+ const originalUrl = fromHeaders.originalUrl ?? fromHtml.originalUrl ?? finalRef?.originalUrl ?? ref.originalUrl;
+ if (!captureTs || !originalUrl) {
+ throw new ArchiveRefusal(
+ "archive.today",
+ "unreadable",
+ `archive.today's answer for ${finalUrl} names no ${!captureTs ? "capture time" : "page"} (no Memento headers, no header bar)`,
+ );
+ }
+ // A copy is named by its short id when the answer gives one.
+ const mementoUrl = finalRef?.id ? finalRef.mementoUrl : (headers ? mementoOfLink(headers, this) : null) ?? finalUrl;
+ const page = unwrapArchiveTodayHtml(html, mementoUrl).html;
+ return {
+ source: "archive.today",
+ body,
+ mimetype: bareMimetype(contentType) || "text/html",
+ contentType,
+ finalTs: captureTs,
+ originalUrl,
+ mementoUrl,
+ bytes: body.byteLength,
+ sha256: createHash("sha256").update(body).digest("hex"),
+ unwrapped: true,
+ page,
+ ...(viaBrowser ? { viaBrowser: true } : {}),
+ };
+ }
+}
+
+function safeHost(url: string): string {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return "";
+ }
+}
+
+// The Link header's rel="memento" self link (a copy answered at its timestamp
+// URL names its short-id URL there), on the canonical host.
+function mementoOfLink(headers: Headers, client: ArchiveTodayClient): string | null {
+ const link = headers.get("link");
+ if (!link) return null;
+ const m = /<([^>]+)>\s*;[^,]*\brel\s*=\s*"?[^",]*\bmemento\b/i.exec(link);
+ if (!m) return null;
+ const ref = parseArchiveTodayUrl(m[1], client.host);
+ return ref?.id ? ref.mementoUrl : null;
+}
+
+async function readAnswer(res: Response, url: string, maxBytes: number): Promise<Answer> {
+ const base = { status: res.status, headers: res.headers, url };
+ if (res.status >= 300 && res.status < 400) {
+ await res.body?.cancel().catch(() => {});
+ const loc = res.headers.get("location");
+ let location: string | null = null;
+ if (loc) {
+ try {
+ location = new URL(loc, url).toString();
+ } catch {
+ location = null;
+ }
+ }
+ return { ...base, location, body: null, bytes: 0, tooLarge: false };
+ }
+ const declared = Number(res.headers.get("content-length"));
+ if (Number.isFinite(declared) && declared > maxBytes && res.status >= 200 && res.status < 300) {
+ await res.body?.cancel().catch(() => {});
+ return { ...base, location: null, body: null, bytes: declared, tooLarge: true };
+ }
+ const reader = res.body?.getReader();
+ const chunks: Buffer[] = [];
+ let bytes = 0;
+ if (reader) {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ bytes += value.byteLength;
+ if (bytes > maxBytes) {
+ await reader.cancel().catch(() => {});
+ if (res.status >= 200 && res.status < 300) return { ...base, location: null, body: null, bytes, tooLarge: true };
+ break;
+ }
+ chunks.push(Buffer.from(value));
+ }
+ }
+ return { ...base, location: null, body: Buffer.concat(chunks), bytes, tooLarge: false };
+}
+
+// TEST-ONLY: E2E_ARCHIVE_TODAY_ORIGIN_FILE names a file holding ONE loopback
+// origin; while it exists, the process's archive.today client sends every
+// request for any archive.today host there — the fake archive.today a spec
+// starts (common/testing/web/fakeArchiveToday.mjs) — and opens no browser.
+// Anything but a loopback origin is ignored.
+const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/;
+
+export function archiveTodayTestOrigin(env: Readonly<Record<string, string | undefined>> = process.env): string | null {
+ const file = env.E2E_ARCHIVE_TODAY_ORIGIN_FILE;
+ if (!file) return null;
+ let origin = "";
+ try {
+ origin = readFileSync(file, "utf8").trim().replace(/\/$/, "");
+ } catch {
+ return null;
+ }
+ return LOOPBACK_ORIGIN.test(origin) ? origin : null;
+}
+
+export function processArchiveTodayFetch(url: string, init: RequestInit): Promise<Response> {
+ const origin = archiveTodayTestOrigin();
+ return fetch(origin ? url.replace(/^https?:\/\/(?:www\.)?archive\.(?:ph|today|is|li|vn|fo|md)/, origin) : url, init);
+}
diff --git a/common/lib/archives/archiveTodaySession.ts b/common/lib/archives/archiveTodaySession.ts
@@ -0,0 +1,205 @@
+// THE ARCHIVE SESSION (release 37 lane F): one persistent Chromium profile for
+// archive.today, opened HEADLESS by the client when archive.today answers a
+// plain request with a check, and HEADED by Connect archive session.
+//
+// The forum browser's model (social/forumSession.ts), for one service: a check
+// a person passes once in a real window sets a clearance cookie the profile
+// keeps, so later reads through the headless profile go through. A window
+// opens only on the operator's explicit action (the channel page's Archived
+// pages panel, or Settings), never from a job; the headless read waits a check
+// out (its own script may clear it) and never clicks, types or solves
+// anything. A check that still stands is refused with a sentence.
+//
+// Layout: transcripts/.archive-session/archive.today/profile/ (the profile),
+// transcripts/.archive-session/archive.today/session.json (the last Connect).
+
+import path from "node:path";
+import { mkdir, stat } from "node:fs/promises";
+import type { Paths } from "../paths";
+import { readJsonFile, writeJsonAtomic } from "../jsonFile-server";
+import { importPlaywright, type BrowserContextLike, type ChromiumLike, type PageLike } from "../../social/playwrightRuntime";
+import { openForumProfile } from "../../social/forumSession";
+import { buildXBrowserLaunchOptions, describeXBrowser, findXBrowser, writeXBrowserRecord } from "../../social/xBrowser";
+import { isArchiveTodayChallenge } from "./archiveToday";
+import type { ArchiveTodayBrowser, ArchiveTodayBrowserLoad } from "./archiveTodayClient";
+
+export const ARCHIVE_SESSION_SERVICE = "archive.today";
+
+export function archiveSessionDir(paths: Pick<Paths, "transcriptsDir">): string {
+ return path.join(paths.transcriptsDir, ".archive-session", ARCHIVE_SESSION_SERVICE);
+}
+
+export function archiveProfileDir(paths: Pick<Paths, "transcriptsDir">): string {
+ return path.join(archiveSessionDir(paths), "profile");
+}
+
+export type ArchiveSessionRecord = {
+ service: string;
+ host: string;
+ connectedAt: string;
+ // The window's last look before it closed: was a page showing that is not a
+ // check, and how many cookies archive.today had set.
+ cleared: boolean;
+ cookies: number;
+ browser?: string;
+};
+
+export type ArchiveSessionStatus = {
+ service: string;
+ hasProfile: boolean;
+ lastConnect?: ArchiveSessionRecord;
+};
+
+export async function readArchiveSessionStatus(paths: Pick<Paths, "transcriptsDir">): Promise<ArchiveSessionStatus> {
+ const dir = archiveSessionDir(paths);
+ const hasProfile = await stat(path.join(dir, "profile")).then(() => true, () => false);
+ const read = await readJsonFile(path.join(dir, "session.json"));
+ const rec = read.ok ? (read.value as ArchiveSessionRecord | null) : null;
+ return {
+ service: ARCHIVE_SESSION_SERVICE,
+ hasProfile,
+ ...(rec && typeof rec.connectedAt === "string" ? { lastConnect: rec } : {}),
+ };
+}
+
+const firstLine = (err: unknown) => ((err as Error)?.message ?? String(err)).split("\n")[0];
+const OUTER_HTML = "document.documentElement ? document.documentElement.outerHTML : ''";
+const INNER_TEXT = "document.body ? document.body.innerText : ''";
+
+export const ARCHIVE_CHALLENGE_WAIT_MS = 45_000;
+
+// Go to `url` and read what the page shows, waiting a check out (up to
+// `timeoutMs`; its own script may clear it and reload). Nothing is clicked.
+export async function loadArchivePage(
+ page: PageLike,
+ url: string,
+ o: { signal?: AbortSignal; timeoutMs?: number; pollMs?: number; now?: () => number; onLog?: (l: string) => void } = {},
+): Promise<ArchiveTodayBrowserLoad> {
+ const now = o.now ?? Date.now;
+ let status: number | undefined;
+ try {
+ const res = (await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 })) as { status?: () => number } | null;
+ status = typeof res?.status === "function" ? res.status() : undefined;
+ } catch (err) {
+ if (!/interrupted|ERR_ABORTED|frame was detached/i.test(firstLine(err))) throw new Error(`Could not load ${url}: ${firstLine(err)}`);
+ }
+ const read = async () => {
+ try {
+ return { html: String(await page.evaluate(OUTER_HTML)), text: String(await page.evaluate(INNER_TEXT)) };
+ } catch {
+ return null;
+ }
+ };
+ let got = (await read()) ?? { html: "", text: "" };
+ if (isArchiveTodayChallenge(got.html)) {
+ o.onLog?.(`archive.today showed a check in the headless browser; waiting up to ${Math.round((o.timeoutMs ?? ARCHIVE_CHALLENGE_WAIT_MS) / 1000)} s for it to clear by itself.`);
+ const started = now();
+ while (now() - started < (o.timeoutMs ?? ARCHIVE_CHALLENGE_WAIT_MS)) {
+ if (o.signal?.aborted) break;
+ await page.waitForTimeout(o.pollMs ?? 2_000);
+ const next = await read();
+ if (!next) continue;
+ got = next;
+ if (!isArchiveTodayChallenge(got.html)) break;
+ }
+ }
+ let href = url;
+ try {
+ const h = String(await page.evaluate("location.href"));
+ if (h && h !== "about:blank") href = h;
+ } catch {
+ // keep the asked URL
+ }
+ return { ...got, url: href, ...(status !== undefined ? { status } : {}) };
+}
+
+// The client's `openBrowser`: the archive profile, headless, one page; closed
+// by the client after the one read.
+export function archiveSessionBrowser(
+ paths: Pick<Paths, "transcriptsDir">,
+ o: { onLog?: (l: string) => void; chromium?: ChromiumLike; timeoutMs?: number } = {},
+): () => Promise<ArchiveTodayBrowser> {
+ return async () => {
+ const context: BrowserContextLike = await openForumProfile(archiveProfileDir(paths), { onLog: o.onLog, chromium: o.chromium });
+ const page = context.pages()[0] ?? (await context.newPage());
+ return {
+ load: (url, signal) => loadArchivePage(page, url, { signal, onLog: o.onLog, timeoutMs: o.timeoutMs }),
+ close: () => context.close(),
+ };
+ };
+}
+
+// CONNECT: a HEADED window on the archive profile at `url` (archive.today's
+// front page by default), on the display of the machine running the editor,
+// for the operator to pass the check once and close it. Resolves when the
+// window closes, with its last look.
+export async function connectArchiveSession(
+ paths: Pick<Paths, "transcriptsDir">,
+ url: string,
+ o: { onLog?: (l: string) => void; timeoutMs?: number; env?: Record<string, string | undefined> } = {},
+): Promise<ArchiveSessionRecord> {
+ const log = o.onLog ?? (() => {});
+ const host = new URL(url).hostname.toLowerCase();
+ const profileDir = archiveProfileDir(paths);
+ await mkdir(profileDir, { recursive: true });
+ const browser = findXBrowser({ env: o.env });
+ const label = describeXBrowser(browser);
+ const { chromium } = await importPlaywright();
+ log(`Opening ${label} at ${host}. Pass the check if one shows, wait for the page, then close the window.`);
+ let context: BrowserContextLike;
+ try {
+ context = await chromium.launchPersistentContext(profileDir, buildXBrowserLaunchOptions({ browser, headless: false, sandbox: true }));
+ } catch (err) {
+ log(`The sandboxed launch failed (${firstLine(err)}); opening without the sandbox.`);
+ context = await chromium.launchPersistentContext(profileDir, buildXBrowserLaunchOptions({ browser, headless: false, sandbox: false }));
+ }
+ await writeXBrowserRecord(profileDir, browser).catch(() => {});
+ let cleared = false;
+ let cookies = 0;
+ const look = async () => {
+ try {
+ const page = context.pages()[0];
+ if (page) cleared = !isArchiveTodayChallenge(String(await page.evaluate(OUTER_HTML)));
+ cookies = ((await context.cookies()) as { domain?: string }[]).filter((c) =>
+ /archive\.(?:ph|today|is|li|vn|fo|md)$/i.test((c.domain ?? "").replace(/^\./, "")),
+ ).length;
+ } catch {
+ // closing, or mid-navigation
+ }
+ };
+ try {
+ const page = context.pages()[0] ?? (await context.newPage());
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 }).catch((err: unknown) => {
+ log(`The first load did not finish (${firstLine(err)}); the window stays open.`);
+ });
+ await new Promise<void>((resolve) => {
+ let settled = false;
+ const timer = setInterval(() => void look(), 2_000);
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ clearInterval(timer);
+ resolve();
+ };
+ context.on("close", finish);
+ if (o.timeoutMs) setTimeout(finish, o.timeoutMs);
+ });
+ } finally {
+ await context.close().catch(() => {});
+ }
+ const record: ArchiveSessionRecord = {
+ service: ARCHIVE_SESSION_SERVICE,
+ host,
+ connectedAt: new Date().toISOString(),
+ cleared,
+ cookies,
+ browser: label,
+ };
+ await writeJsonAtomic(path.join(archiveSessionDir(paths), "session.json"), record, { mkdir: true });
+ log(
+ cleared
+ ? `A page that is not a check showed before the window closed; ${cookies} cookie(s) for archive.today kept in the profile.`
+ : `The window closed with a check still showing; ${cookies} cookie(s) for archive.today in the profile.`,
+ );
+ return record;
+}
diff --git a/common/lib/archives/ask.ts b/common/lib/archives/ask.ts
@@ -0,0 +1,73 @@
+// WHAT A PAGE IMPORT IS ASKED FOR, across archive sources (release 37 lane F):
+// a copy's URL on any source, or a page's own URL with a date and (optionally)
+// the source to look in. Client-safe (no node imports).
+//
+// {url: <Wayback capture>} that capture (lib/waybackPages/urls.ts)
+// {url: <page>, at} the Wayback capture nearest `at`
+// {url: <archive.today copy>} that copy (archive.ph/<id>, /<ts>/<page>, /newest/<page>)
+// {url: <page>, at, source: "archive.today"} the archive.today copy nearest `at` (its timemap)
+
+import { parsePageCaptureAsk, isCaptureAt, NOT_A_CAPTURE_URL, type PageCaptureAsk } from "../waybackPages/urls";
+import { isArchiveTodayUrl, parseArchiveTodayUrl } from "./mementos";
+import { isArchiveSourceId, type ArchiveMementoRef, type ArchiveSourceId } from "./types";
+
+export type ArchiveCaptureAsk =
+ | (PageCaptureAsk & { source: "wayback" })
+ // One archive.today copy by its URL. `originalUrl` when the URL names the
+ // page (/<ts>/<page>, /newest/<page>); a short id names none.
+ | { kind: "memento"; source: "archive.today"; ref: ArchiveMementoRef; originalUrl?: string }
+ // The archive.today copy of `originalUrl` nearest `at`.
+ | { kind: "nearest"; source: "archive.today"; at: string; originalUrl: string };
+
+export const NOT_A_COPY_URL =
+ `${NOT_A_CAPTURE_URL}; or an archive.today copy's URL (https://archive.ph/<id>), ` +
+ 'or the page\'s own URL, a date and "source": "archive.today"';
+
+export function parseArchiveCaptureAsk(
+ url: string,
+ at?: string,
+ source?: string,
+): { ok: true; ask: ArchiveCaptureAsk } | { ok: false; error: string } {
+ const given = url.trim();
+ const when = (at ?? "").trim();
+ const want = (source ?? "").trim();
+ if (want && !isArchiveSourceId(want)) {
+ return { ok: false, error: `"source" must be "wayback" or "archive.today", not "${want}"` };
+ }
+ const asked = (want || undefined) as ArchiveSourceId | undefined;
+ if (given && isArchiveTodayUrl(given)) {
+ if (asked && asked !== "archive.today") {
+ return { ok: false, error: `${given} is an archive.today copy, not the ${asked === "wayback" ? "Wayback Machine's" : asked}` };
+ }
+ const ref = parseArchiveTodayUrl(given);
+ if (!ref) {
+ return { ok: false, error: `${given} is an archive.today listing or link, not one copy: ${NOT_A_COPY_URL}` };
+ }
+ if (when) {
+ return { ok: false, error: `"at" goes with a page's own URL; ${given} already names its copy` };
+ }
+ return {
+ ok: true,
+ ask: { kind: "memento", source: "archive.today", ref, ...(ref.originalUrl ? { originalUrl: ref.originalUrl } : {}) },
+ };
+ }
+ if (asked === "archive.today") {
+ let u: URL;
+ try {
+ u = new URL(given);
+ } catch {
+ return { ok: false, error: `"${given}" is not a URL: ${NOT_A_COPY_URL}` };
+ }
+ if (u.protocol !== "http:" && u.protocol !== "https:") return { ok: false, error: `"${given}" is not an http(s) URL` };
+ const wb = parsePageCaptureAsk(given);
+ if (wb.ok) return { ok: false, error: `${given} is a Wayback Machine capture, not an archive.today copy` };
+ if (!when) {
+ return { ok: false, error: `give "at" (YYYYMMDD) with a page's own URL to import its archive.today copy nearest that date` };
+ }
+ if (!isCaptureAt(when)) return { ok: false, error: `"at" must be a date as YYYYMMDD (or YYYYMMDDhhmmss), not "${when}"` };
+ return { ok: true, ask: { kind: "nearest", source: "archive.today", at: when, originalUrl: given } };
+ }
+ const wb = parsePageCaptureAsk(given, at);
+ if (!wb.ok) return wb;
+ return { ok: true, ask: { ...wb.ask, source: "wayback" } };
+}
diff --git a/common/lib/archives/index.ts b/common/lib/archives/index.ts
@@ -0,0 +1,145 @@
+// THE ARCHIVE SOURCES (release 37 lane F): the registry every caller asks — the
+// page import, the lookup across sources, the channel page — and the process's
+// clients. One entry per source, in the order a lookup lists them. ADDING A
+// SOURCE is one module (its client + its `ArchiveSource`) and one entry here:
+// see plans/release-37/archive-sources.md, "Adding an archive source".
+//
+// Server-only (the clients). What a URL says without a request is
+// lib/archives/mementos.ts, client-safe.
+
+import { getSettings } from "../settings";
+import { getPaths } from "../paths";
+import { ArchiveOrgRequestError } from "../archiveOrgClient";
+import { isWaybackExcluded, WAYBACK_EXCLUDED_PHRASE, WaybackCaptureRefusal } from "../waybackClient";
+import { archiveSourceLabel, parseArchiveTodayUrl } from "./mementos";
+import { waybackSource } from "./wayback";
+import {
+ ARCHIVE_TODAY_QUEUE,
+ ArchiveTodayClient,
+ ArchiveTodayRequestError,
+ archiveTodayTestOrigin,
+ processArchiveTodayFetch,
+} from "./archiveTodayClient";
+import { archiveSessionBrowser } from "./archiveTodaySession";
+import { ArchiveRefusal, type ArchiveCaptureRow, type ArchiveRefusalCode, type ArchiveSource, type ArchiveSourceId } from "./types";
+
+export * from "./types";
+
+const archivesSettings = () => {
+ try {
+ return getSettings().archives;
+ } catch {
+ return undefined;
+ }
+};
+
+// THE process's archive.today client: one chain, one gap, one cool-down, the
+// host and pace read from settings per request. Under the e2e fake
+// (E2E_ARCHIVE_TODAY_ORIGIN_FILE) no browser is ever opened.
+export const archiveTodayClient = new ArchiveTodayClient(
+ {
+ fetch: processArchiveTodayFetch,
+ host: () => archivesSettings()?.archiveTodayHost ?? "archive.ph",
+ openBrowser: () => archiveSessionBrowser(getPaths(), { onLog: (l) => console.log(`[archive-session] ${l}`) })(),
+ browserEnabled: () => archivesSettings()?.archiveTodayBrowser !== false && archiveTodayTestOrigin() === null,
+ },
+ {
+ minGapMs: () => (archivesSettings()?.archiveTodayGapSeconds ?? 8) * 1000,
+ cooldownMs: () => (archivesSettings()?.archiveTodayCooldownMinutes ?? 30) * 60_000,
+ },
+);
+
+export function archiveTodaySource(client: ArchiveTodayClient = archiveTodayClient): ArchiveSource {
+ return {
+ id: "archive.today",
+ label: "archive.today",
+ queueKey: ARCHIVE_TODAY_QUEUE,
+ matchesUrl: (url) => parseArchiveTodayUrl(url) !== null,
+ parseMementoUrl: (url) => parseArchiveTodayUrl(url, client.host),
+ listCaptures: (url, o) => client.listCaptures(url, o),
+ closestCapture: (url, at, o) => client.closestCapture(url, at, o),
+ getCapture: (memento, o) => client.getCapture(memento, o),
+ };
+}
+
+export const ARCHIVE_SOURCES: readonly ArchiveSource[] = [waybackSource(), archiveTodaySource()];
+
+export function archiveSource(id: string | undefined, sources: readonly ArchiveSource[] = ARCHIVE_SOURCES): ArchiveSource | null {
+ return sources.find((s) => s.id === (id ?? "wayback")) ?? null;
+}
+
+// The source a COPY's URL is on, or null (a listing, an original page).
+export function sourceForUrl(url: string, sources: readonly ArchiveSource[] = ARCHIVE_SOURCES): ArchiveSource | null {
+ return sources.find((s) => s.matchesUrl(url)) ?? null;
+}
+
+// An error as an archive refusal (its code, source and sentence), or null
+// when it is not one: ArchiveRefusal, WaybackCaptureRefusal, and the Wayback
+// Machine's exclusion (a CDX 403).
+export function archiveRefusalOf(e: unknown): { source: ArchiveSourceId; code: ArchiveRefusalCode; message: string } | null {
+ if (e instanceof ArchiveRefusal) return { source: e.source, code: e.code, message: e.message };
+ if (isWaybackExcluded(e)) return { source: "wayback", code: "excluded", message: (e as Error).message };
+ if (e instanceof WaybackCaptureRefusal) return { source: "wayback", code: e.code, message: e.message };
+ return null;
+}
+
+export type ArchiveLookupEntry = {
+ source: ArchiveSourceId;
+ label: string;
+ ok: boolean;
+ captures: ArchiveCaptureRow[];
+ // The refusal's code ("excluded", "challenge", "rate-limited", …), when
+ // the source refused.
+ refusal?: ArchiveRefusalCode;
+ error?: string;
+};
+
+export type ArchiveLookup = {
+ url: string;
+ found: number;
+ sources: ArchiveLookupEntry[];
+};
+
+// THE COPIES OF A PAGE across sources (`archive-lookup`): each source asked
+// in turn (each through its own paced client), its copies oldest first, at
+// most `limit` per source. A source that refuses or fails is its own entry's
+// sentence; the others still answer. Read only.
+export async function archiveLookup(
+ url: string,
+ o: {
+ source?: ArchiveSourceId;
+ sources?: readonly ArchiveSource[];
+ limit?: number;
+ from?: string;
+ to?: string;
+ signal?: AbortSignal;
+ } = {},
+): Promise<ArchiveLookup> {
+ const all = o.sources ?? ARCHIVE_SOURCES;
+ const chosen = o.source ? all.filter((s) => s.id === o.source) : all;
+ const entries: ArchiveLookupEntry[] = [];
+ for (const s of chosen) {
+ try {
+ const captures = await s.listCaptures(url, {
+ ...(o.limit ? { limit: o.limit } : {}),
+ ...(o.from ? { from: o.from } : {}),
+ ...(o.to ? { to: o.to } : {}),
+ ...(o.signal ? { signal: o.signal } : {}),
+ });
+ entries.push({ source: s.id, label: s.label, ok: true, captures });
+ } catch (e) {
+ if (o.signal?.aborted) throw e;
+ const refusal = archiveRefusalOf(e);
+ if (refusal) {
+ entries.push({ source: s.id, label: s.label, ok: false, captures: [], refusal: refusal.code, error: refusal.message });
+ } else if (e instanceof ArchiveOrgRequestError || e instanceof ArchiveTodayRequestError) {
+ entries.push({ source: s.id, label: s.label, ok: false, captures: [], error: e.message });
+ } else {
+ throw e;
+ }
+ }
+ }
+ return { url, found: entries.reduce((n, e) => n + e.captures.length, 0), sources: entries };
+}
+
+export { archiveSourceLabel, WAYBACK_EXCLUDED_PHRASE };
diff --git a/common/lib/archives/mementos.test.ts b/common/lib/archives/mementos.test.ts
@@ -0,0 +1,125 @@
+// Release 37 lane F: what a memento URL says, with no request.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/archives/mementos.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ archiveTodayHostOf,
+ archiveTodayTs,
+ httpDateOfTimestamp,
+ mementoSourceOf,
+ pageArchiveLink,
+ parseArchiveTodayUrl,
+ timestampOfDate,
+ unwrapArchiveTodayOutlink,
+} from "./mementos";
+import { parseArchiveCaptureAsk } from "./ask";
+
+test("archive.today copies in every form, on the canonical host; listings and links out are not copies", () => {
+ assert.deepEqual(parseArchiveTodayUrl("https://archive.ph/Ab3dE"), { source: "archive.today", mementoUrl: "https://archive.ph/Ab3dE", id: "Ab3dE" });
+ // Any of its names, read as the canonical host; a copy's sub-page is the copy.
+ assert.equal(parseArchiveTodayUrl("http://archive.is/Ab3dE/image")?.mementoUrl, "https://archive.ph/Ab3dE");
+ assert.equal(parseArchiveTodayUrl("https://archive.today/Ab3dE", "archive.li")?.mementoUrl, "https://archive.li/Ab3dE");
+ assert.deepEqual(parseArchiveTodayUrl("https://archive.ph/2019.05.12-083000/https://journal.example/a.html"), {
+ source: "archive.today",
+ mementoUrl: "https://archive.ph/20190512083000/https://journal.example/a.html",
+ originalUrl: "https://journal.example/a.html",
+ captureTs: "20190512083000",
+ });
+ assert.equal(parseArchiveTodayUrl("https://archive.ph/20190512/journal.example/a.html?x=1")?.originalUrl, "http://journal.example/a.html?x=1");
+ assert.deepEqual(parseArchiveTodayUrl("https://archive.vn/newest/https://journal.example/a.html"), {
+ source: "archive.today",
+ mementoUrl: "https://archive.ph/newest/https://journal.example/a.html",
+ originalUrl: "https://journal.example/a.html",
+ pick: "newest",
+ });
+ for (const notACopy of [
+ "https://archive.ph/",
+ "https://archive.ph/journal.example",
+ "https://archive.ph/https://journal.example/*",
+ "https://archive.ph/o/Ab3dE/https://journal.example/b.html",
+ "https://archive.ph/timemap/https://journal.example/",
+ "https://archive.ph/search/?q=journal",
+ "https://archive.ph/submit/",
+ "https://web.archive.org/web/2019/https://journal.example/",
+ "https://journal.example/Ab3dE",
+ ]) {
+ assert.equal(parseArchiveTodayUrl(notACopy), null, notACopy);
+ }
+});
+
+test("timestamps: dotted and digit forms, HTTP dates both ways; the canonical host is one of its names", () => {
+ assert.equal(archiveTodayTs("2019.05.12-083000"), "20190512083000");
+ assert.equal(timestampOfDate("Sun, 12 May 2019 08:30:00 GMT"), "20190512083000");
+ assert.equal(timestampOfDate("2019-05-12T08:30:00Z"), "20190512083000");
+ assert.equal(timestampOfDate("not a date"), null);
+ assert.equal(httpDateOfTimestamp("20190512083000"), "Sun, 12 May 2019 08:30:00 GMT");
+ assert.equal(archiveTodayHostOf("ARCHIVE.IS"), "archive.is");
+ assert.equal(archiveTodayHostOf("evil.example"), "archive.ph");
+ assert.equal(archiveTodayHostOf(undefined), "archive.ph");
+});
+
+test("a link out of a copy is the URL it points at", () => {
+ assert.equal(unwrapArchiveTodayOutlink("https://archive.ph/o/Ab3dE/https://other.example/account"), "https://other.example/account");
+ assert.equal(unwrapArchiveTodayOutlink("/o/Ab3dE/https://other.example/x?y=1"), "https://other.example/x?y=1");
+ assert.equal(unwrapArchiveTodayOutlink("https://other.example/x"), "https://other.example/x");
+});
+
+test("which source a URL is a copy on", () => {
+ assert.equal(mementoSourceOf("https://web.archive.org/web/20140305120000/https://blog.example/"), "wayback");
+ assert.equal(mementoSourceOf("https://archive.ph/Ab3dE"), "archive.today");
+ assert.equal(mementoSourceOf("https://blog.example/"), null);
+ assert.equal(mementoSourceOf("https://web.archive.org/web/*/blog.example/*"), null);
+});
+
+test("a record's copy is cited by its source's URL and name; a record with no source is the Wayback Machine's", () => {
+ assert.deepEqual(
+ pageArchiveLink({ captureTs: "20140305120000", originalUrl: "https://blog.example/", waybackUrl: "https://web.archive.org/web/20140305120000/https://blog.example/" }),
+ { source: "wayback", label: "Wayback Machine", url: "https://web.archive.org/web/20140305120000/https://blog.example/" },
+ );
+ assert.deepEqual(
+ pageArchiveLink({ source: "archive.today", archiveUrl: "https://archive.ph/Ab3dE", waybackUrl: "https://archive.ph/Ab3dE", captureTs: "20190512083000", originalUrl: "https://journal.example/a.html" }),
+ { source: "archive.today", label: "archive.today", url: "https://archive.ph/Ab3dE" },
+ );
+});
+
+test("an import's ask across sources: a copy's URL names its source; a page's URL takes `at` and a source", () => {
+ const ok = (url: string, at?: string, source?: string) => {
+ const r = parseArchiveCaptureAsk(url, at, source);
+ assert.ok(r.ok, r.ok ? "" : r.error);
+ return r.ask;
+ };
+ const err = (url: string, at?: string, source?: string) => {
+ const r = parseArchiveCaptureAsk(url, at, source);
+ assert.equal(r.ok, false);
+ return r.ok ? "" : r.error;
+ };
+ assert.deepEqual(ok("https://web.archive.org/web/20140305120000/https://blog.example/"), {
+ kind: "capture",
+ captureTs: "20140305120000",
+ originalUrl: "https://blog.example/",
+ source: "wayback",
+ });
+ assert.deepEqual(ok("https://blog.example/", "2014"), { kind: "nearest", at: "2014", originalUrl: "https://blog.example/", source: "wayback" });
+ assert.deepEqual(ok("https://archive.is/Ab3dE"), {
+ kind: "memento",
+ source: "archive.today",
+ ref: { source: "archive.today", mementoUrl: "https://archive.ph/Ab3dE", id: "Ab3dE" },
+ });
+ assert.equal(ok("https://archive.ph/newest/https://journal.example/a.html").originalUrl, "https://journal.example/a.html");
+ assert.deepEqual(ok("https://journal.example/a.html", "20190601", "archive.today"), {
+ kind: "nearest",
+ source: "archive.today",
+ at: "20190601",
+ originalUrl: "https://journal.example/a.html",
+ });
+ assert.match(err("https://archive.ph/https://journal.example/*"), /archive\.today listing or link, not one copy/);
+ assert.match(err("https://archive.ph/Ab3dE", "2019"), /"at" goes with a page's own URL/);
+ assert.match(err("https://archive.ph/Ab3dE", undefined, "wayback"), /is an archive\.today copy/);
+ assert.match(err("https://journal.example/a.html", undefined, "archive.today"), /give "at"/);
+ assert.match(err("https://web.archive.org/web/2014/https://blog.example/", "2014", "archive.today"), /is a Wayback Machine capture/);
+ assert.match(err("https://journal.example/a.html", "2019", "ghostarchive"), /"source" must be/);
+ // The Wayback Machine's own sentences, unchanged.
+ assert.match(err("https://blog.example/"), /not a Wayback Machine capture/);
+});
diff --git a/common/lib/archives/mementos.ts b/common/lib/archives/mementos.ts
@@ -0,0 +1,183 @@
+// WHAT A MEMENTO URL SAYS (release 37 lane F), for every archive source, with
+// no request: which source a URL is a copy on, the page and time it names, and
+// how a record links its copy. Client-safe (no node imports): the channel form
+// and the channel page read it too.
+//
+// archive.today (one service under several names: archive.ph, archive.today,
+// archive.is, archive.li, archive.vn, archive.fo, archive.md) names a copy as
+// https://archive.ph/<id> a copy, by its short id (AbCdE)
+// https://archive.ph/<ts>/<original> the copy of <original> nearest <ts>
+// (<ts>: YYYYMMDDhhmmss, or YYYY.MM.DD-hhmmss)
+// https://archive.ph/newest/<original> its newest copy
+// https://archive.ph/oldest/<original> its oldest copy
+// and lists them at /timemap/<original> (the Memento protocol's link format).
+// `/o/<id>/<url>` is a link OUT of a copy (to <url>), and a bare
+// `/<original>` or `/search/` a listing: neither is a copy.
+
+import { parseWaybackUrl, waybackPageUrl } from "../wayback";
+import type { ArchiveMementoRef, ArchiveSourceId } from "./types";
+
+export const ARCHIVE_TODAY_HOSTS = [
+ "archive.ph",
+ "archive.today",
+ "archive.is",
+ "archive.li",
+ "archive.vn",
+ "archive.fo",
+ "archive.md",
+] as const;
+
+export const DEFAULT_ARCHIVE_TODAY_HOST = "archive.ph";
+
+export const ARCHIVE_SOURCE_LABELS: Record<ArchiveSourceId, string> = {
+ wayback: "Wayback Machine",
+ "archive.today": "archive.today",
+};
+
+export function archiveSourceLabel(id: string | undefined): string {
+ return ARCHIVE_SOURCE_LABELS[(id ?? "wayback") as ArchiveSourceId] ?? id ?? "Wayback Machine";
+}
+
+export function isArchiveTodayHost(host: string): boolean {
+ const h = host.toLowerCase().replace(/^www\./, "");
+ return (ARCHIVE_TODAY_HOSTS as readonly string[]).includes(h);
+}
+
+// The canonical host a setting names, or the default: one of the known names,
+// nothing else (a typo never sends requests somewhere new).
+export function archiveTodayHostOf(setting: unknown): string {
+ const h = typeof setting === "string" ? setting.trim().toLowerCase().replace(/^www\./, "") : "";
+ return isArchiveTodayHost(h) ? h : DEFAULT_ARCHIVE_TODAY_HOST;
+}
+
+const SHORT_ID_RE = /^[A-Za-z0-9]{4,6}$/;
+// YYYYMMDDhhmmss (or a whole-unit prefix), or archive.today's dotted
+// YYYY.MM.DD-hhmmss (or YYYY.MM.DD).
+const TS_SEG_RE = /^(?:\d{4}(?:\d{2}){0,5}|\d{4}\.\d{2}\.\d{2}(?:-\d{6})?)$/;
+const RESERVED = new Set(["o", "timemap", "timegate", "search", "submit", "wip", "faq", "newest", "oldest", "about", "donate"]);
+
+// "2019.01.02-030405" → "20190102030405"; a digit timestamp as it is.
+export function archiveTodayTs(seg: string): string {
+ return seg.replace(/[.-]/g, "");
+}
+
+// An HTTP date (Memento-Datetime: "Tue, 01 Jan 2019 12:34:56 GMT") or an
+// ISO-8601 instant as a 14-digit UTC timestamp, or null.
+export function timestampOfDate(value: string | null | undefined): string | null {
+ if (!value) return null;
+ const ms = Date.parse(value.trim());
+ if (!Number.isFinite(ms)) return null;
+ return new Date(ms).toISOString().replace(/[-:T]/g, "").slice(0, 14);
+}
+
+// A 14-digit timestamp as an HTTP date (what a timegate's Accept-Datetime takes).
+export function httpDateOfTimestamp(ts: string): string {
+ const p = ts.padEnd(14, "0");
+ const ms = Date.UTC(+p.slice(0, 4), +p.slice(4, 6) - 1 || 0, +p.slice(6, 8) || 1, +p.slice(8, 10), +p.slice(10, 12), +p.slice(12, 14));
+ return new Date(ms).toUTCString();
+}
+
+function originalOf(rest: string, search: string): string | null {
+ let r = rest;
+ if (/^https?%3a/i.test(r)) {
+ try {
+ r = decodeURIComponent(r);
+ } catch {
+ return null;
+ }
+ }
+ r = r.replace(/^(https?):\/(?!\/)/i, "$1://");
+ if (!/^https?:\/\//i.test(r)) r = `http://${r}`;
+ const out = `${r}${search}`;
+ try {
+ const u = new URL(out);
+ if (!u.hostname.includes(".")) return null;
+ if (isArchiveTodayHost(u.hostname)) return null;
+ } catch {
+ return null;
+ }
+ return out;
+}
+
+// An archive.today COPY's parts (on the canonical `host`), or null for
+// anything else: another host, a listing, a search, a link out of a copy.
+export function parseArchiveTodayUrl(url: string | null | undefined, host: string = DEFAULT_ARCHIVE_TODAY_HOST): ArchiveMementoRef | null {
+ if (!url) return null;
+ let u: URL;
+ try {
+ u = new URL(url.trim());
+ } catch {
+ return null;
+ }
+ if (u.protocol !== "http:" && u.protocol !== "https:") return null;
+ if (!isArchiveTodayHost(u.hostname)) return null;
+ const canon = archiveTodayHostOf(host);
+ const path = u.pathname.replace(/^\/+/, "");
+ const segs = path.split("/");
+ const first = segs[0] ?? "";
+ if (!first) return null;
+ if (first === "newest" || first === "oldest") {
+ const original = originalOf(segs.slice(1).join("/"), u.search);
+ if (!original) return null;
+ return { source: "archive.today", mementoUrl: `https://${canon}/${first}/${original}`, originalUrl: original, pick: first };
+ }
+ if (TS_SEG_RE.test(first) && segs.length > 1) {
+ const original = originalOf(segs.slice(1).join("/"), u.search);
+ if (!original) return null;
+ const ts = archiveTodayTs(first);
+ return { source: "archive.today", mementoUrl: `https://${canon}/${ts}/${original}`, originalUrl: original, captureTs: ts };
+ }
+ if (RESERVED.has(first.toLowerCase())) return null;
+ // `/<id>`, `/<id>/`, and the copy's own sub-pages (`/<id>/image`) name the copy.
+ if (SHORT_ID_RE.test(first) && (segs.length === 1 || segs.slice(1).every((s) => s === "" || /^[a-z]+$/.test(s)))) {
+ return { source: "archive.today", mementoUrl: `https://${canon}/${first}`, id: first };
+ }
+ return null;
+}
+
+// Any URL on an archive.today host (a copy, a listing, a search).
+export function isArchiveTodayUrl(url: string): boolean {
+ try {
+ return isArchiveTodayHost(new URL(url.trim()).hostname);
+ } catch {
+ return false;
+ }
+}
+
+// `/o/<id>/<url>` (a link out of an archive.today copy) as <url>; any other
+// URL as given.
+export function unwrapArchiveTodayOutlink(href: string): string {
+ const m = /^(?:https?:)?\/\/(?:www\.)?(?:archive\.(?:ph|today|is|li|vn|fo|md))\/o\/[A-Za-z0-9]+\/(.+)$/i.exec(href.trim())
+ ?? /^\/o\/[A-Za-z0-9]+\/(https?:\/\/.+)$/i.exec(href.trim());
+ if (!m) return href;
+ return m[1].replace(/^(https?):\/(?!\/)/i, "$1://");
+}
+
+// Which source a URL is a COPY on, or null (a listing, an original page).
+export function mementoSourceOf(url: string): ArchiveSourceId | null {
+ if (parseWaybackUrl(url)) return "wayback";
+ if (parseArchiveTodayUrl(url)) return "archive.today";
+ return null;
+}
+
+// THE LINK A RECORD'S COPY IS CITED BY (lane D: shots, the moment page,
+// citation labels, the MCP): `page.archiveUrl` for a record from a source that
+// is not the Wayback Machine, else its Wayback replay URL — and the source's
+// name for the label.
+export function pageArchiveLink(page: {
+ source?: string;
+ archiveUrl?: string;
+ waybackUrl?: string;
+ captureTs: string;
+ originalUrl: string;
+}): { source: ArchiveSourceId; label: string; url: string } {
+ const source = (page.source ?? "wayback") as ArchiveSourceId;
+ if (source !== "wayback" && page.archiveUrl) {
+ return { source, label: archiveSourceLabel(source), url: page.archiveUrl };
+ }
+ return {
+ source: "wayback",
+ label: ARCHIVE_SOURCE_LABELS.wayback,
+ url: page.waybackUrl || waybackPageUrl({ captureTs: page.captureTs, originalUrl: page.originalUrl }),
+ };
+}
diff --git a/common/lib/archives/settings.ts b/common/lib/archives/settings.ts
@@ -0,0 +1,54 @@
+// settings.archives — the archive sources a page import reads (release 37
+// lane F). Pure: the type, its defaults, the sanitizer settingsSchema.ts runs
+// it through and the per-field docs SETTINGS.md renders.
+
+import type { FieldDocs } from "../fieldDocs";
+import { archiveTodayHostOf, DEFAULT_ARCHIVE_TODAY_HOST } from "./mementos";
+
+export type ArchivesSettings = {
+ archiveTodayHost: string;
+ archiveTodayGapSeconds: number;
+ archiveTodayCooldownMinutes: number;
+ archiveTodayBrowser: boolean;
+};
+
+export const DEFAULT_ARCHIVES_SETTINGS: ArchivesSettings = {
+ archiveTodayHost: DEFAULT_ARCHIVE_TODAY_HOST,
+ archiveTodayGapSeconds: 8,
+ archiveTodayCooldownMinutes: 30,
+ archiveTodayBrowser: true,
+};
+
+export const ARCHIVES_SETTINGS_FIELD_DOCS: FieldDocs<ArchivesSettings> = {
+ archiveTodayHost:
+ "The archive.today name every request goes to (archive.ph, archive.today, archive.is, archive.li, archive.vn, " +
+ "archive.fo or archive.md — one service). A copy's URL on any of them is read from this one. Anything else " +
+ "falls back to archive.ph.",
+ archiveTodayGapSeconds:
+ "The least time between two archive.today requests, seconds, from the end of one to the start of the next, " +
+ "with up to a quarter more at random. One request at a time, always. Clamped to [4, 120]; default 8.",
+ archiveTodayCooldownMinutes:
+ "After archive.today answers HTTP 429 (too many requests) the run stops, and no request goes to it for this " +
+ "long (or its Retry-After, when longer). Clamped to [5, 1440]; default 30.",
+ archiveTodayBrowser:
+ "When archive.today answers with a check (a CAPTCHA, a browser check) instead of a copy, read the copy once " +
+ "more through the headless browser on the archive session's profile (Connect archive session keeps a cleared " +
+ "check there). Nothing is ever solved by code: a check the browser cannot pass is refused with a sentence. " +
+ "False = refuse at the check.",
+};
+
+const clamp = (v: unknown, d: number, min: number, max: number): number => {
+ const n = typeof v === "number" && Number.isFinite(v) ? v : d;
+ return Math.min(max, Math.max(min, n));
+};
+
+export function sanitizeArchives(value: unknown): ArchivesSettings {
+ const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>;
+ const d = DEFAULT_ARCHIVES_SETTINGS;
+ return {
+ archiveTodayHost: archiveTodayHostOf(r.archiveTodayHost),
+ archiveTodayGapSeconds: clamp(r.archiveTodayGapSeconds, d.archiveTodayGapSeconds, 4, 120),
+ archiveTodayCooldownMinutes: Math.round(clamp(r.archiveTodayCooldownMinutes, d.archiveTodayCooldownMinutes, 5, 1440)),
+ archiveTodayBrowser: r.archiveTodayBrowser !== false,
+ };
+}
diff --git a/common/lib/archives/types.ts b/common/lib/archives/types.ts
@@ -0,0 +1,140 @@
+// ARCHIVE SOURCES (release 37 lane F, plans/release-37/archive-sources.md): a
+// service that holds copies of web pages — the Wayback Machine, archive.today,
+// and whichever comes next — read the same way. A source answers four
+// questions: is this URL one of my copies (a "memento"), which copies do I
+// hold of a page, which one is nearest a time, and what are a copy's bytes.
+// Each source is ONE module (lib/archives/<source>.ts) registered in
+// lib/archives/index.ts; the page import, the lookup and the citation code ask
+// the registry, never a source by name.
+//
+// Types and the refusal only; client-safe (no node imports).
+
+// The sources this build knows. A record's `page.source` is one of these
+// (absent = "wayback", the records made before sources existed).
+export const ARCHIVE_SOURCE_IDS = ["wayback", "archive.today"] as const;
+export type ArchiveSourceId = (typeof ARCHIVE_SOURCE_IDS)[number];
+
+export function isArchiveSourceId(v: unknown): v is ArchiveSourceId {
+ return typeof v === "string" && (ARCHIVE_SOURCE_IDS as readonly string[]).includes(v);
+}
+
+// What a memento URL says before anything is fetched. archive.today's short
+// form (`archive.ph/AbCdE`) names neither the page nor the time: those are
+// learned from the copy itself.
+export type ArchiveMementoRef = {
+ source: ArchiveSourceId;
+ // The copy's URL, on the source's canonical host.
+ mementoUrl: string;
+ // The page it is a copy of, when the URL names it.
+ originalUrl?: string;
+ // The capture time (4–14 digits, a Wayback timestamp's form), when the URL
+ // names it. A short one is "the copy nearest this".
+ captureTs?: string;
+ // The bytes as captured, when the source has such a form (Wayback's `id_`).
+ rawUrl?: string;
+ // archive.today: the short id (`AbCdE`).
+ id?: string;
+ // archive.today: `newest` / `oldest` — the URL names a page, and the source
+ // picks the copy.
+ pick?: "newest" | "oldest";
+};
+
+// One copy a source lists (a lookup's row).
+export type ArchiveCaptureRow = {
+ source: ArchiveSourceId;
+ // YYYYMMDDhhmmss
+ captureTs: string;
+ originalUrl: string;
+ // The copy as a page a reader opens.
+ mementoUrl: string;
+ // The status the capture recorded, when the source says ("200", "302").
+ status?: string;
+ mimetype?: string;
+};
+
+// One copy's bytes (getCapture). `body` is what the source served — what the
+// page import stores — and `page` the same copy as a page the extractors read
+// (`unwrapped`): Wayback's `id_` body as it is, archive.today's snapshot with
+// its own header taken off and its rewritten links put back.
+export type ArchiveRawCapture = {
+ source: ArchiveSourceId;
+ body: Buffer;
+ // The bare mimetype ("text/html") and the Content-Type as served.
+ mimetype: string;
+ contentType: string;
+ // The copy the answer is (after any redirect).
+ finalTs: string;
+ originalUrl: string;
+ mementoUrl: string;
+ bytes: number;
+ sha256: string;
+ unwrapped: true;
+ page: string;
+ // archive.today: the copy was read through the headless browser (its check
+ // stood in the way of a plain request).
+ viaBrowser?: boolean;
+};
+
+export type ArchiveRefusalCode =
+ // The source answered, and holds nothing of this page for anyone: a Wayback
+ // CDX 403 ("excluded from the Wayback Machine (cause unknown)").
+ | "excluded"
+ // The source put a check (a CAPTCHA, a "one more step" page) in front of
+ // the copy. Never solved by code: Connect archive session, then again.
+ | "challenge"
+ // The source said "too many requests" (HTTP 429): the run stops, and the
+ // client leaves the source alone for a while.
+ | "rate-limited"
+ // No such copy.
+ | "not-archived"
+ // A body that is not a page, or over the cap.
+ | "mimetype"
+ | "too-large"
+ // Redirects that leave the source or go round.
+ | "offsite-redirect"
+ | "redirect-loop"
+ // An answer that names no capture time or page.
+ | "unreadable";
+
+// A copy (or a listing) a source will not hand back, with the sentence a
+// caller shows. Thrown by the archive.today client and by the registry's
+// lookups; Wayback's own refusals (WaybackCaptureRefusal, WaybackExcludedError)
+// are read as these by `archiveRefusalOf` (lib/archives/index.ts).
+export class ArchiveRefusal extends Error {
+ readonly code: ArchiveRefusalCode;
+ readonly source: ArchiveSourceId;
+ // rate-limited: when the client will ask again (epoch ms).
+ readonly retryAt?: number;
+ constructor(source: ArchiveSourceId, code: ArchiveRefusalCode, message: string, o: { retryAt?: number } = {}) {
+ super(message);
+ this.name = "ArchiveRefusal";
+ this.source = source;
+ this.code = code;
+ if (o.retryAt !== undefined) this.retryAt = o.retryAt;
+ }
+}
+
+// THE SOURCE. Every request goes through the source's own paced client; a job
+// that reads a source runs on its `queueKey`.
+export type ArchiveSource = {
+ id: ArchiveSourceId;
+ // "Wayback Machine", "archive.today".
+ label: string;
+ // The job queue its requests run on ("platform:archive.org",
+ // "platform:archive.today").
+ queueKey: string;
+ // Is this a memento URL of mine (a copy, not a listing)?
+ matchesUrl(url: string): boolean;
+ parseMementoUrl(url: string): ArchiveMementoRef | null;
+ // The copies held of `originalUrl`, oldest first; `from`/`to` are
+ // capture-time prefixes (inclusive), `limit` at most this many. Paced.
+ listCaptures(
+ originalUrl: string,
+ o?: { from?: string; to?: string; limit?: number; signal?: AbortSignal },
+ ): Promise<ArchiveCaptureRow[]>;
+ // The copy nearest `at` (4–14 digits), or null when there is none.
+ closestCapture(url: string, at: string, o?: { signal?: AbortSignal }): Promise<ArchiveCaptureRow | null>;
+ // One copy's bytes, at most `maxBytes`. Throws ArchiveRefusal (or the
+ // source's own typed refusal) for what it will not hand back.
+ getCapture(memento: string | ArchiveMementoRef, o?: { maxBytes?: number; signal?: AbortSignal }): Promise<ArchiveRawCapture>;
+};
diff --git a/common/lib/archives/wayback.test.ts b/common/lib/archives/wayback.test.ts
@@ -0,0 +1,119 @@
+// Release 37 lane F: the Wayback Machine as an archive source answers exactly
+// what its client answers (the same requests, rows and bytes); a CDX 403 is
+// the typed "excluded" refusal on every path; the lookup across sources gives
+// each source its own entry.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/archives/wayback.test.ts
+
+import test from "node:test";
+import assert from "node:assert/strict";
+import { startFakeWayback, PAGE_ARTICLE_TS, PAGE_ARTICLE_URL, PAGE_ARTICLE_LATER_TS } from "../../testing/web/fakeWayback.mjs";
+import { startFakeArchiveToday, AT_ARTICLE_URL, AT_ARTICLE_TS } from "../../testing/web/fakeArchiveToday.mjs";
+import { ArchiveOrgRequestError } from "../archiveOrgClient";
+import { isWaybackExcluded, WaybackCaptureRefusal, WaybackClient, WaybackExcludedError, waybackCdxUrl } from "../waybackClient";
+import { parseWaybackMemento, waybackSource } from "./wayback";
+import { archiveLookup, archiveRefusalOf, archiveSource, archiveTodaySource, sourceForUrl } from "./index";
+import { ArchiveTodayClient } from "./archiveTodayClient";
+
+const fast = { minGapMs: 0, baseBackoffMs: 1, maxBackoffMs: 2 };
+
+test("the adapter's rows, nearest and bytes are the client's, request for request", async () => {
+ const wb = await startFakeWayback();
+ try {
+ const direct = new WaybackClient({ fetch: wb.fetch }, fast);
+ const viaSource = waybackSource(new WaybackClient({ fetch: wb.fetch }, fast));
+ const rows = await direct.captures(PAGE_ARTICLE_URL);
+ const before = wb.requests.length;
+ const listed = await viaSource.listCaptures(PAGE_ARTICLE_URL);
+ assert.deepEqual(
+ listed,
+ rows.map((r) => ({ source: "wayback", captureTs: r.timestamp, originalUrl: r.original, mementoUrl: r.replayUrl, status: r.status, ...(r.mimetype ? { mimetype: r.mimetype } : {}) })),
+ );
+ assert.equal(wb.requests.at(-1)?.path, wb.requests[before - 1]?.path, "the same CDX request");
+ const near = await direct.closestCapture(PAGE_ARTICLE_URL, "20150601");
+ assert.equal((await viaSource.closestCapture(PAGE_ARTICLE_URL, "20150601"))?.captureTs, near?.timestamp);
+ assert.equal(near?.timestamp, PAGE_ARTICLE_LATER_TS);
+ const raw = await direct.getCapture(PAGE_ARTICLE_TS, PAGE_ARTICLE_URL, { raw: true });
+ const copy = await viaSource.getCapture(`https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`);
+ assert.equal(copy.sha256, raw.sha256);
+ assert.equal(copy.finalTs, raw.finalTs);
+ assert.equal(copy.mementoUrl, `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`);
+ assert.equal(copy.page, raw.body.toString("utf8"));
+ assert.equal(copy.unwrapped, true);
+ // Capture-time bounds go to CDX as its own from/to.
+ await viaSource.listCaptures(PAGE_ARTICLE_URL, { from: "2015", to: "2016" });
+ assert.match(String(wb.requests.at(-1)?.path), /from=2015&to=2016/);
+ assert.match(waybackCdxUrl("https://a.example/", { from: "2014" }), /from=2014/);
+ } finally {
+ await wb.close();
+ }
+});
+
+test("memento URLs: a Wayback capture's parts; the registry knows which source a copy is on", () => {
+ assert.deepEqual(parseWaybackMemento(`https://web.archive.org/web/${PAGE_ARTICLE_TS}id_/${PAGE_ARTICLE_URL}`), {
+ source: "wayback",
+ mementoUrl: `https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`,
+ originalUrl: PAGE_ARTICLE_URL,
+ captureTs: PAGE_ARTICLE_TS,
+ rawUrl: `https://web.archive.org/web/${PAGE_ARTICLE_TS}id_/${PAGE_ARTICLE_URL}`,
+ });
+ assert.equal(sourceForUrl(`https://web.archive.org/web/${PAGE_ARTICLE_TS}/${PAGE_ARTICLE_URL}`)?.id, "wayback");
+ assert.equal(sourceForUrl("https://archive.md/Ab3dE")?.id, "archive.today");
+ assert.equal(sourceForUrl(PAGE_ARTICLE_URL), null);
+ assert.equal(archiveSource(undefined)?.label, "Wayback Machine");
+ assert.equal(archiveSource("archive.today")?.queueKey, "platform:archive.today");
+ assert.equal(archiveSource("wayback")?.queueKey, "platform:archive.org");
+});
+
+test("a CDX 403 while the archive answers other URLs: EXCLUDED, typed, on the listing, the nearest and the capture", async () => {
+ const gone = "https://x.example/someone";
+ const wb = await startFakeWayback({ excluded: [gone] });
+ try {
+ const client = new WaybackClient({ fetch: wb.fetch }, fast);
+ await assert.rejects(client.captures(gone), (e: unknown) => {
+ assert.ok(e instanceof WaybackExcludedError);
+ assert.ok(e instanceof ArchiveOrgRequestError, "still an ArchiveOrgRequestError for every older catch");
+ assert.equal((e as ArchiveOrgRequestError).status, 403);
+ assert.match((e as Error).message, /excluded from the Wayback Machine \(cause unknown\)/);
+ return true;
+ });
+ await assert.rejects(client.closestCapture(gone, "2014"), (e: unknown) => isWaybackExcluded(e));
+ await assert.rejects(client.getCapture("20140101000000", gone, { raw: true }), (e: unknown) => {
+ assert.ok(e instanceof WaybackCaptureRefusal);
+ assert.equal((e as WaybackCaptureRefusal).code, "excluded");
+ return true;
+ });
+ // Another URL, same archive: answered as usual.
+ assert.ok((await client.captures(PAGE_ARTICLE_URL)).length > 0);
+ assert.equal(archiveRefusalOf(new WaybackExcludedError(gone))?.code, "excluded");
+ } finally {
+ await wb.close();
+ }
+});
+
+test("the lookup across sources: each source its own entry — an exclusion one, the other's copies still listed", async () => {
+ const wb = await startFakeWayback({ excluded: [AT_ARTICLE_URL] });
+ const at = await startFakeArchiveToday();
+ try {
+ const sources = [
+ waybackSource(new WaybackClient({ fetch: wb.fetch }, fast)),
+ archiveTodaySource(new ArchiveTodayClient({ fetch: at.fetch, sleep: async () => {} }, { minGapMs: 0 })),
+ ];
+ const r = await archiveLookup(AT_ARTICLE_URL, { sources });
+ assert.equal(r.found, 2);
+ assert.deepEqual(
+ r.sources.map((s) => [s.source, s.ok, s.refusal ?? null, s.captures.length]),
+ [
+ ["wayback", false, "excluded", 0],
+ ["archive.today", true, null, 2],
+ ],
+ );
+ assert.match(String(r.sources[0].error), /excluded from the Wayback Machine \(cause unknown\)/);
+ assert.equal(r.sources[1].captures[0].captureTs, AT_ARTICLE_TS);
+ const one = await archiveLookup(AT_ARTICLE_URL, { sources, source: "archive.today", limit: 1 });
+ assert.deepEqual(one.sources.map((s) => [s.source, s.captures.length]), [["archive.today", 1]]);
+ } finally {
+ await wb.close();
+ await at.close();
+ }
+});
diff --git a/common/lib/archives/wayback.ts b/common/lib/archives/wayback.ts
@@ -0,0 +1,83 @@
+// THE WAYBACK MACHINE AS AN ARCHIVE SOURCE (release 37 lane F): an adapter
+// over the existing client (lib/waybackClient.ts) — the same requests, the
+// same pacing (archive.org's: one at a time, 2 s apart, 429/503 waited out),
+// the same refusals. Nothing here changes what the client does.
+
+import { parseWaybackUrl, waybackPageUrl, waybackRawUrl } from "../wayback";
+import { waybackClient as processWaybackClient, type WaybackCapture, type WaybackClient } from "../waybackClient";
+import { queueKeyForUrl } from "../platform";
+import { decodeCaptureBody } from "../waybackPages/extract";
+import { ArchiveRefusal, type ArchiveCaptureRow, type ArchiveMementoRef, type ArchiveSource } from "./types";
+
+export const WAYBACK_QUEUE = queueKeyForUrl("https://web.archive.org/");
+
+export function parseWaybackMemento(url: string): ArchiveMementoRef | null {
+ const ref = parseWaybackUrl(url);
+ if (!ref) return null;
+ return {
+ source: "wayback",
+ mementoUrl: waybackPageUrl(ref),
+ originalUrl: ref.originalUrl,
+ captureTs: ref.captureTs,
+ rawUrl: waybackRawUrl(ref),
+ };
+}
+
+export function waybackRow(c: WaybackCapture): ArchiveCaptureRow {
+ return {
+ source: "wayback",
+ captureTs: c.timestamp,
+ originalUrl: c.original,
+ mementoUrl: c.replayUrl,
+ ...(c.status ? { status: c.status } : {}),
+ ...(c.mimetype ? { mimetype: c.mimetype } : {}),
+ };
+}
+
+export function waybackSource(client: Pick<WaybackClient, "captures" | "closestCapture" | "getCapture"> = processWaybackClient): ArchiveSource {
+ return {
+ id: "wayback",
+ label: "Wayback Machine",
+ queueKey: WAYBACK_QUEUE,
+ matchesUrl: (url) => parseWaybackUrl(url) !== null,
+ parseMementoUrl: parseWaybackMemento,
+ async listCaptures(originalUrl, o = {}) {
+ const rows = await client.captures(originalUrl, {
+ ...(o.limit ? { limit: o.limit } : {}),
+ ...(o.from ? { from: o.from } : {}),
+ ...(o.to ? { to: o.to } : {}),
+ ...(o.signal ? { signal: o.signal } : {}),
+ });
+ return rows.map(waybackRow);
+ },
+ async closestCapture(url, at, o = {}) {
+ const c = await client.closestCapture(url, at, o.signal ? { signal: o.signal } : {});
+ return c ? waybackRow(c) : null;
+ },
+ async getCapture(memento, o = {}) {
+ const ref = typeof memento === "string" ? parseWaybackMemento(memento) : memento;
+ if (!ref?.captureTs || !ref.originalUrl) {
+ throw new ArchiveRefusal("wayback", "not-archived", `${typeof memento === "string" ? memento : memento.mementoUrl} is not a Wayback Machine capture's URL`);
+ }
+ const cap = await client.getCapture(ref.captureTs, ref.originalUrl, {
+ raw: true,
+ ...(o.maxBytes ? { maxBytes: o.maxBytes } : {}),
+ ...(o.signal ? { signal: o.signal } : {}),
+ });
+ const final = { captureTs: cap.finalTs, originalUrl: cap.originalUrl };
+ return {
+ source: "wayback",
+ body: cap.body,
+ mimetype: cap.mimetype,
+ contentType: cap.contentType,
+ finalTs: cap.finalTs,
+ originalUrl: cap.originalUrl,
+ mementoUrl: waybackPageUrl(final),
+ bytes: cap.bytes,
+ sha256: cap.sha256,
+ unwrapped: true,
+ page: decodeCaptureBody(cap.body, cap.contentType),
+ };
+ },
+ };
+}
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -227,7 +227,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
mirror:
"For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped.",
wayback:
- 'A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest"}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture\'s original URL. Each capture imported (`pnpm ops import-page`, the channel page\'s **Import a capture**) becomes a page record in the channel\'s posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped.',
+ 'A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest"}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture\'s original URL. Each capture imported (`pnpm ops import-page`, the channel page\'s **Import a capture**) becomes a page record in the channel\'s posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. Release 37 lane F: a target\'s `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages".',
};
// Every key a config.json may carry, in emission order. The unknown-key oracle:
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -232,6 +232,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." },
{ name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." },
{ name: "E2E_WAYBACK_ORIGIN_FILE", audience: "test", default: "unset (the real Wayback Machine)", readBy: "common/lib/waybackClient.ts", doc: "A file holding one loopback origin; while it exists, the editor's Wayback client sends every web.archive.org request (CDX, captures, the video index) there — the fake Wayback a spec starts (`common/testing/web/fakeWayback.mjs`). The editor's e2e server names a file in each slot's test data (`wayback-pages.spec`); anything but a loopback origin in it is ignored." },
+ { name: "E2E_ARCHIVE_TODAY_ORIGIN_FILE", audience: "test", default: "unset (the real archive.today)", readBy: "common/lib/archives/archiveTodayClient.ts, common/lib/archives/index.ts", doc: "A file holding one loopback origin; while it exists, the editor's archive.today client sends every request for any archive.today name (archive.ph, archive.today, archive.is, …) there — the fake archive.today a spec starts (`common/testing/web/fakeArchiveToday.mjs`) — and never opens the archive session's browser. The editor's e2e server names a file in each slot's test data (`archive-today-pages.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." },
{ name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." },
{ name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." },
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -12,6 +12,7 @@
import {
ARCHIVE_ORG_SETTINGS_FIELD_DOCS,
+ ARCHIVES_SETTINGS_FIELD_DOCS,
ARCHIVE_STORAGE_SETTINGS_FIELD_DOCS,
ATTRIBUTION_SETTINGS_FIELD_DOCS,
BACKFILL_SETTINGS_FIELD_DOCS,
@@ -261,6 +262,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
defaults: fromObject(d.archiveOrg),
},
],
+ archives: [
+ {
+ path: "archives",
+ docs: ARCHIVES_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.archives),
+ },
+ ],
publish: [
{
path: "publish",
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -32,6 +32,7 @@ import type { StorageSettings } from "./storageLocations";
import type { ArchiveOrgFetchSettings } from "./archiveOrgTorrent";
import type { SeederSettings } from "./seederSettings";
import type { TtsSettings } from "./ttsSettings";
+import type { ArchivesSettings } from "./archives/settings";
import type { GenerationSettings } from "./generationSettings";
import type {
AttributionSettings,
@@ -105,6 +106,7 @@ type PreSchemaSiteSettings = {
attribution: AttributionSettings;
// How archive.org files are fetched: BitTorrent with seeding, else direct.
archiveOrg: ArchiveOrgFetchSettings;
+ archives: ArchivesSettings;
// The publish lane (release 18).
publish: PublishSettings;
// The recurring reports' lane (umtool R5).
@@ -121,7 +123,7 @@ type PreSchemaSiteSettings = {
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 40 fields, in file order", () => {
+test("SiteSettings keeps its 41 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -159,6 +161,7 @@ test("SiteSettings keeps its 40 fields, in file order", () => {
"backfill",
"attribution",
"archiveOrg",
+ "archives",
"publish",
"reportSchedule",
"seeder",
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -79,6 +79,7 @@ import {
import { sanitizeSeeder, type SeederSettings } from "./seederSettings";
export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSettings";
import { sanitizeTts, type TtsSettings } from "./ttsSettings";
+import { sanitizeArchives, type ArchivesSettings } from "./archives/settings";
import { sanitizeGeneration, type GenerationSettings } from "./generationSettings";
export {
GENERATION_CAPS_FIELD_DOCS,
@@ -96,6 +97,7 @@ export {
type GenerationSettings,
} from "./generationSettings";
export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings";
+export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings";
import {
DEFAULT_COOKIE_MODE,
isCookieMode,
@@ -1856,6 +1858,9 @@ export const siteSettingsSchema = z.object({
archiveOrg: settingsField((v): ArchiveOrgFetchSettings => sanitizeArchiveOrg(v)).describe(
"How archive.org files are fetched (controller/archiveOrgDownload.ts). Over BitTorrent with aria2c when the item's torrent carries the file — archive.org is the torrent's web seed, so the swarm takes load off archive.org — then seeded for a while; otherwise, or when the torrent stalls, a direct download from archive.org. Either way the file is verified against archive.org's sha1/md5. No yt-dlp.",
),
+ archives: settingsField((v): ArchivesSettings => sanitizeArchives(v)).describe(
+ "The archive sources a page import reads besides the Wayback Machine (release 37 lane F, lib/archives/): archive.today's one canonical host, its pace (one request at a time, a long gap, a rest after a 429) and whether a check it answers with is read once more through the archive session's headless browser. The Wayback Machine keeps archive.org's own client and pace. See ArchivesSettings.",
+ ),
publish: settingsField((v): PublishSettings => sanitizePublish(v)).describe(
"The publish LANE (release 18): a runner that, when the index is stale, updates it and then builds — and, where a site's own `publish.auto` (site.json) says so, deploys — what changed, one stage at a time on the `publish` queue. OFF by default; the manual stages (Publish now, Build, Deploy) work either way. See PublishSettings and common/publish/publishRunner.ts.",
),
diff --git a/common/lib/waybackClient.ts b/common/lib/waybackClient.ts
@@ -43,13 +43,16 @@ export function waybackReplayUrl(timestamp: string, original: string): string {
export function waybackCdxUrl(
url: string,
- o: { limit?: number; okOnly?: boolean; closest?: string } = {},
+ o: { limit?: number; okOnly?: boolean; closest?: string; from?: string; to?: string } = {},
): string {
const q = new URLSearchParams();
q.set("url", url);
q.set("output", "json");
if (o.okOnly) q.set("filter", "statuscode:200");
if (o.limit) q.set("limit", String(o.limit));
+ // Release 37 lane F: capture-time bounds (timestamp prefixes, inclusive).
+ if (o.from) q.set("from", o.from);
+ if (o.to) q.set("to", o.to);
// Release 37: the captures nearest a time first (the page import's
// `{url, at}` form).
if (o.closest) {
@@ -177,7 +180,15 @@ export type WaybackRawCapture = {
sha256: string;
};
-export type WaybackCaptureRefusalCode = "mimetype" | "too-large" | "offsite-redirect" | "redirect-loop" | "not-archived";
+export type WaybackCaptureRefusalCode =
+ | "mimetype"
+ | "too-large"
+ | "offsite-redirect"
+ | "redirect-loop"
+ | "not-archived"
+ // Release 37 lane F: the archive answered 403 for the capture (see
+ // WaybackExcludedError).
+ | "excluded";
// A capture getCapture will not hand back, with the sentence a caller shows.
export class WaybackCaptureRefusal extends Error {
@@ -191,6 +202,40 @@ export class WaybackCaptureRefusal extends Error {
}
}
+// AN EXCLUDED URL (release 37 lane F): the Wayback Machine answers HTTP 403 —
+// at its CDX API, or for a capture — for a URL it will not show anyone (a site
+// owner's request, a legal one, a policy: it does not say which), while it
+// answers every other URL as usual. That is a fact about the URL, not an
+// outage, and every surface says it in these words. The error stays an
+// ArchiveOrgRequestError (status 403), so every catch written before it reads
+// it as it always did.
+export const WAYBACK_EXCLUDED_PHRASE = "excluded from the Wayback Machine (cause unknown)";
+
+export class WaybackExcludedError extends ArchiveOrgRequestError {
+ readonly excluded = true as const;
+ readonly url: string;
+ constructor(url: string) {
+ super(`${url} is ${WAYBACK_EXCLUDED_PHRASE}: the Wayback Machine answered HTTP 403 for it`, 403, false);
+ this.name = "WaybackExcludedError";
+ this.url = url;
+ }
+}
+
+// Whether `e` is the Wayback Machine refusing a URL as excluded (a CDX 403, or
+// getCapture's "excluded").
+export function isWaybackExcluded(e: unknown): boolean {
+ return e instanceof WaybackExcludedError || (e instanceof WaybackCaptureRefusal && e.code === "excluded");
+}
+
+// A CDX request's error as the exclusion it is (a 403), else as it was: what a
+// caller that builds its own CDX request (lane B's scan pages) wraps its
+// request in.
+export function waybackExcludedOf(e: unknown, url: string): unknown {
+ return e instanceof ArchiveOrgRequestError && !(e instanceof WaybackExcludedError) && e.status === 403
+ ? new WaybackExcludedError(url)
+ : e;
+}
+
export class WaybackClient {
private readonly http: ArchiveOrgClient;
@@ -248,11 +293,12 @@ export class WaybackClient {
// Null when the Wayback Machine holds no capture of `url` that recorded a
// 200.
async closestCapture(url: string, at: string, o: { signal?: AbortSignal } = {}): Promise<WaybackCapture | null> {
- const body = await this.http.getText(
- waybackCdxUrl(url, { okOnly: true, limit: 5, closest: at }),
- "application/json",
- o.signal,
- );
+ let body: string;
+ try {
+ body = await this.http.getText(waybackCdxUrl(url, { okOnly: true, limit: 5, closest: at }), "application/json", o.signal);
+ } catch (e) {
+ throw waybackExcludedOf(e, url);
+ }
let rows: WaybackCapture[];
try {
rows = parseCdxJson(body);
@@ -301,6 +347,9 @@ export class WaybackClient {
if (e instanceof ArchiveOrgRequestError && (e.status === 404 || e.status === 410)) {
throw new WaybackCaptureRefusal("not-archived", `the Wayback Machine holds no capture of ${url} at ${ts}`);
}
+ if (e instanceof ArchiveOrgRequestError && e.status === 403) {
+ throw new WaybackCaptureRefusal("excluded", `${url} is ${WAYBACK_EXCLUDED_PHRASE}: it answered HTTP 403 for the capture at ${ts}`);
+ }
throw e;
}
if (res.location !== null || (res.status >= 300 && res.status < 400)) {
@@ -358,9 +407,14 @@ export class WaybackClient {
// refusing (`rateLimited`) or answered an error.
async captures(
url: string,
- o: { limit?: number; okOnly?: boolean; signal?: AbortSignal } = {},
+ o: { limit?: number; okOnly?: boolean; from?: string; to?: string; signal?: AbortSignal } = {},
): Promise<WaybackCapture[]> {
- const body = await this.http.getText(waybackCdxUrl(url, o), "application/json", o.signal);
+ let body: string;
+ try {
+ body = await this.http.getText(waybackCdxUrl(url, o), "application/json", o.signal);
+ } catch (e) {
+ throw waybackExcludedOf(e, url);
+ }
try {
return parseCdxJson(body);
} catch (e) {
diff --git a/common/lib/waybackPages/config.ts b/common/lib/waybackPages/config.ts
@@ -27,8 +27,22 @@ export type WaybackTarget = {
// `include` (if set) and not `exclude`.
include?: string;
exclude?: string;
+ // Release 37 lane F: the archive sources that hold this target's copies
+ // ("wayback", "archive.today"; lib/archives/). Absent = ["wayback"].
+ sources?: WaybackTargetSource[];
};
+// The archive sources a target may name (lib/archives/types.ts
+// ARCHIVE_SOURCE_IDS; repeated here because this file is a leaf).
+export const WAYBACK_TARGET_SOURCES = ["wayback", "archive.today"] as const;
+export type WaybackTargetSource = (typeof WAYBACK_TARGET_SOURCES)[number];
+
+// The sources a target's copies are looked for on: its own, else the
+// Wayback Machine alone.
+export function targetSources(target: Pick<WaybackTarget, "sources">): WaybackTargetSource[] {
+ return target.sources?.length ? [...target.sources] : ["wayback"];
+}
+
export type WaybackPagesConfig = {
targets: WaybackTarget[];
// How a scan folds repeated captures: "digest" = one row per distinct body.
@@ -64,6 +78,11 @@ export function coerceWaybackTarget(v: unknown): WaybackTarget | undefined {
if (include) out.include = include;
const exclude = trimmed(r.exclude);
if (exclude) out.exclude = exclude;
+ if (Array.isArray(r.sources)) {
+ const sources = [...new Set(r.sources.filter((x): x is WaybackTargetSource => (WAYBACK_TARGET_SOURCES as readonly unknown[]).includes(x)))];
+ // ["wayback"] alone is the default: not written.
+ if (sources.length > 0 && !(sources.length === 1 && sources[0] === "wayback")) out.sources = sources;
+ }
return out;
}
@@ -99,9 +118,20 @@ const WAYBACK_HOST_RE = /^(?:web|wayback)\.archive\.org$/i;
// exactly. A URL that is not on the Wayback Machine is taken as the target
// itself: a trailing `*` makes it a prefix, a leading `*.` a domain.
// Null for anything that names no target.
+// Release 37 lane F: an archive.today copy that names its page
+// (archive.ph/<ts>/<page>, /newest/<page>, /oldest/<page>) is that page,
+// exactly, on archive.today; a short id (archive.ph/<id>) names no page.
+const ARCHIVE_TODAY_COPY_RE =
+ /^https?:\/\/(?:www\.)?archive\.(?:ph|today|is|li|vn|fo|md)\/(?:newest|oldest|\d{4,14}|\d{4}\.\d{2}\.\d{2}(?:-\d{6})?)\/(.+)$/i;
+
export function waybackTargetFromUrl(input: string): WaybackTarget | null {
const raw = input.trim();
if (!raw) return null;
+ const at = ARCHIVE_TODAY_COPY_RE.exec(raw);
+ if (at) {
+ const inner = waybackTargetFromUrl(at[1].replace(/^(https?):\/(?!\/)/i, "$1://"));
+ return inner ? { url: inner.url, match: "exact", sources: ["archive.today"] } : null;
+ }
let rest = raw;
let from: string | undefined;
let to: string | undefined;
diff --git a/common/lib/waybackPages/parse.ts b/common/lib/waybackPages/parse.ts
@@ -58,6 +58,12 @@ export function parsePagePostInfo(raw: unknown): PagePostInfo | null {
out.extractorFallback = { from, fromVersion: f.fromVersion, error: typeof f.error === "string" ? f.error : "" };
}
}
+ // Release 37 lane F: the archive source (a word; absent = the Wayback
+ // Machine) and its copy's URL.
+ const source = str(r.source);
+ if (source && KIND_RE.test(source.replace(/\./g, "-")) && source !== "wayback") out.source = source;
+ const archiveUrl = str(r.archiveUrl);
+ if (archiveUrl && /^https?:\/\//i.test(archiveUrl)) out.archiveUrl = archiveUrl;
if (Array.isArray(r.tags)) {
const tags = r.tags.filter((t): t is string => typeof t === "string" && t.trim() !== "");
if (tags.length > 0) out.tags = tags;
diff --git a/common/lib/waybackPages/store-server.ts b/common/lib/waybackPages/store-server.ts
@@ -44,6 +44,12 @@ export type StoredCapture = {
requestedUrl?: string;
// The record ids this capture made, at the last extraction.
records?: string[];
+ // Release 37 lane F: the archive source the copy is from (absent = the
+ // Wayback Machine), and the copy's URL there (archive.today's
+ // `https://archive.ph/<id>`). The body is the copy AS SERVED — for
+ // archive.today its rewritten snapshot, unwrapped each time it is read.
+ source?: string;
+ mementoUrl?: string;
};
export function channelPagesDir(channelRoot: string): string {
@@ -95,6 +101,10 @@ function parseStoredCapture(raw: unknown): StoredCapture | null {
out.extractorFallback = { from: fb.from, fromVersion: fb.fromVersion, error: typeof fb.error === "string" ? fb.error : "" };
}
if (Array.isArray(r.records)) out.records = r.records.filter((x): x is string => typeof x === "string");
+ const source = s("source");
+ if (source && source !== "wayback") out.source = source;
+ const mementoUrl = s("mementoUrl");
+ if (mementoUrl) out.mementoUrl = mementoUrl;
return out;
}
@@ -169,3 +179,24 @@ export async function countStoredCaptures(channelRoot: string): Promise<number>
return 0;
}
}
+
+// The stored capture of a copy by its URL at its source (release 37 lane F:
+// an archive.today short-id URL names neither page nor time, so "already
+// stored" is asked by the copy's URL before anything is fetched), or null.
+export async function findStoredCaptureByMemento(channelRoot: string, mementoUrl: string): Promise<StoredCaptureEntry | null> {
+ const want = mementoKey(mementoUrl);
+ for (const e of await listStoredCaptures(channelRoot)) {
+ if (e.capture.mementoUrl && mementoKey(e.capture.mementoUrl) === want) return e;
+ }
+ return null;
+}
+
+// A copy's URL compared host-blind (archive.today's names are one service).
+function mementoKey(url: string): string {
+ try {
+ const u = new URL(url);
+ return `${u.pathname}${u.search}`.replace(/\/+$/, "");
+ } catch {
+ return url;
+ }
+}
diff --git a/common/lib/waybackPages/toPost.ts b/common/lib/waybackPages/toPost.ts
@@ -35,6 +35,11 @@ export type DraftToPostContext = {
capture: PageCaptureFacts;
extractor: { name: string; version: number };
fallback?: { from: string; fromVersion: number; error: string };
+ // Release 37 lane F: the capture is a copy on another archive source (not
+ // the Wayback Machine): its id and the copy's URL there. The record's
+ // `page.source` / `page.archiveUrl` say so, and its waybackUrl / rawUrl
+ // are that URL (types.ts).
+ source?: { id: string; mementoUrl: string };
};
function hostOf(url: string): string {
@@ -60,15 +65,20 @@ export function draftToPost(draft: PageRecordDraft, ctx: DraftToPostContext): Po
: undefined;
const createdAt = published ?? (captureTsIso(capture.captureTs) || new Date(0).toISOString());
const ref = { captureTs: capture.captureTs, originalUrl: capture.originalUrl };
+ const other = ctx.source && ctx.source.id !== "wayback" ? ctx.source : null;
const page: PagePostInfo = {
originalUrl: capture.originalUrl,
captureTs: capture.captureTs,
- waybackUrl: waybackPageUrl(ref),
- rawUrl: waybackRawUrl(ref),
+ waybackUrl: other ? other.mementoUrl : waybackPageUrl(ref),
+ rawUrl: other ? other.mementoUrl : waybackRawUrl(ref),
kind: draft.kind,
extractor: ctx.extractor.name,
extractorVersion: ctx.extractor.version,
};
+ if (other) {
+ page.source = other.id;
+ page.archiveUrl = other.mementoUrl;
+ }
const title = draft.title ?? capture.title;
if (title) page.title = title;
if (capture.mimetype) page.mimetype = capture.mimetype;
diff --git a/common/lib/waybackPages/types.ts b/common/lib/waybackPages/types.ts
@@ -54,6 +54,16 @@ export type PagePostInfo = WaybackProvenance & {
extractorFallback?: { from: string; fromVersion: number; error: string };
// Tags the page gives the item (Tumblr tags).
tags?: string[];
+ // Release 37 lane F (lib/archives/): the archive source the capture is
+ // from — "archive.today", … — absent for the Wayback Machine (every record
+ // made before sources existed). For a source that is not the Wayback
+ // Machine, `archiveUrl` is the copy's URL (archive.today's
+ // `https://archive.ph/<id>`), and `waybackUrl` / `rawUrl` hold that same
+ // URL (they are required, and a reader that knows no source still links
+ // the copy): cite by `pageArchiveLink(page)` (lib/archives/mementos.ts),
+ // which names the source.
+ source?: string;
+ archiveUrl?: string;
};
// What an extractor hands back per record, before it becomes a Post. The
diff --git a/common/lib/waybackPages/urls.ts b/common/lib/waybackPages/urls.ts
@@ -4,6 +4,7 @@
// it. Client-safe: no node imports.
import { isWaybackHost, parseWaybackUrl } from "../wayback";
+import { isArchiveTodayHost, parseArchiveTodayUrl } from "../archives/mementos";
// The bodies a page import keeps. Anything else is refused by its mimetype.
export const PAGE_MIMETYPES = ["text/html", "text/plain", "application/json"] as const;
@@ -154,6 +155,12 @@ export function isWaybackPagesUrl(url: string): boolean {
} catch {
return false;
}
+ // Release 37 lane F: an archive.today copy is an archived page too (a
+ // short id names no page; one that names a video is import-video's).
+ if (isArchiveTodayHost(u.hostname)) {
+ const ref = parseArchiveTodayUrl(url);
+ return ref !== null && (!ref.originalUrl || videoPageOf(ref.originalUrl) === null);
+ }
if (!isWaybackHost(u.hostname)) return false;
const m = /^\/(?:web\/)?\d{0,14}\*?(?:[a-z]{2}_)?\/(.+)$/s.exec(u.pathname + u.search);
if (!m) return false;
diff --git a/common/testing/web/fakeArchiveToday.d.mts b/common/testing/web/fakeArchiveToday.d.mts
@@ -0,0 +1,33 @@
+export type FakeArchiveTodayCopy = { id: string; original: string; timestamp: string; page: () => string };
+
+export const COPIES: FakeArchiveTodayCopy[];
+export const AT_ARTICLE_URL: string;
+export const AT_ARTICLE_ID: string;
+export const AT_ARTICLE_TS: string;
+export const AT_ARTICLE_LATER_ID: string;
+export const AT_ARTICLE_LATER_TS: string;
+export const AT_CHECKED_URL: string;
+export const AT_CHECKED_ID: string;
+export const AT_CHECKED_TS: string;
+export const CHALLENGE_HTML: string;
+
+export function httpDateOf(ts: string): string;
+export function wrapLikeArchiveToday(
+ html: string,
+ o: { id: string; original: string; timestamp: string; host?: string },
+): string;
+export function fixtureCopy(name: string, o: { id: string; original: string; timestamp: string }): FakeArchiveTodayCopy;
+
+export type FakeArchiveToday = {
+ base: string;
+ requests: { path: string; at: number; ua: string }[];
+ fetch(url: string | URL, init?: RequestInit): Promise<Response>;
+ close(): Promise<void>;
+};
+
+export function startFakeArchiveToday(opts?: {
+ copies?: FakeArchiveTodayCopy[];
+ challenge?: string[] | "all";
+ challengeStatus?: number;
+ busyTimes?: number;
+}): Promise<FakeArchiveToday>;
diff --git a/common/testing/web/fakeArchiveToday.mjs b/common/testing/web/fakeArchiveToday.mjs
@@ -0,0 +1,235 @@
+// A fake archive.today on loopback (release 37 lane F): timemaps, copies
+// wrapped the way archive.today serves them, its redirects, a check page and
+// "too many requests". No test reaches the real archive.today.
+//
+// const at = await startFakeArchiveToday();
+// at.fetch a fetch that sends https://archive.ph/… (any of its names) here
+// at.base the loopback origin
+// at.requests every request path, in order, with its time (`at`)
+// await at.close()
+//
+// Routes (every name — archive.ph, archive.today, archive.is, … — is one):
+// GET /timemap/<original> link format: rel="original", then one rel="memento"
+// (first/last marked) per copy of <original>, oldest
+// first; 404 when it holds none
+// GET /<id> the copy, wrapped (wrapLikeArchiveToday), with
+// Memento-Datetime and Link (rel="original",
+// rel="memento") headers; 404 for an unknown id
+// GET /<ts>/<original> 302 to the copy of <original> nearest <ts>
+// GET /newest/<original> 302 to its newest copy; /oldest/ to its oldest
+// opts.challenge: ids (or "all") answered with a CAPTCHA page instead of the
+// copy (opts.challengeStatus, default 200 — archive.today also uses 429/503)
+// opts.busyTimes: the first N requests answer a plain 429 (Retry-After: 2)
+// opts.copies: the copies held (default COPIES)
+
+import http from "node:http";
+import { readFileSync } from "node:fs";
+
+// ─── Wrapping a page the way archive.today serves its copy ───
+//
+// archive.today's snapshot (as known 2026-10-20; synthetic): its own header
+// bar (`#HEADER`: the "saved from" URL box, the capture's <time>) above
+// `#CONTENT`, which holds the page; scripts gone; every link out of the copy
+// rewritten to `https://<host>/o/<id>/<absolute url>`; every image served
+// from its own cache (`https://<host>/<id>/<hash>.<ext>`) with the original
+// kept as `old-src`. The page's title and <meta>s stay in the <head>.
+
+const abs = (href, base) => {
+ try {
+ return new URL(href, base).toString();
+ } catch {
+ return href;
+ }
+};
+
+const hash = (s) => {
+ let h = 2166136261;
+ for (const ch of s) h = Math.imul(h ^ ch.codePointAt(0), 16777619) >>> 0;
+ return h.toString(16).padStart(8, "0");
+};
+
+const isoOf = (ts) => `${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)}T${ts.slice(8, 10)}:${ts.slice(10, 12)}:${ts.slice(12, 14)}Z`;
+export const httpDateOf = (ts) => new Date(isoOf(ts)).toUTCString();
+
+export function wrapLikeArchiveToday(html, { id, original, timestamp, host = "archive.ph" }) {
+ const headEnd = html.search(/<\/head\s*>/i);
+ const head = headEnd >= 0 ? html.slice(0, headEnd) : "";
+ const title = /<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(head)?.[1] ?? "";
+ const metas = (head.match(/<meta\b[^>]*>/gi) ?? []).filter((m) => !/charset/i.test(m)).join("\n");
+ const bodyMatch = /<body\b[^>]*>([\s\S]*?)<\/body\s*>/i.exec(html);
+ let body = bodyMatch ? bodyMatch[1] : html;
+ body = body.replace(/<script\b[\s\S]*?<\/script\s*>/gi, "");
+ body = body.replace(/(<a\b[^>]*?\shref\s*=\s*)(["'])(.*?)\2/gi, (m, pre, q, href) => {
+ if (href.startsWith("#") || /^(?:javascript|mailto):/i.test(href)) return m;
+ return `${pre}${q}https://${host}/o/${id}/${abs(href.replace(/&/g, "&"), original).replace(/&/g, "&")}${q}`;
+ });
+ body = body.replace(/(<img\b[^>]*?)\ssrc\s*=\s*(["'])(.*?)\2/gi, (m, pre, q, src) => {
+ const orig = abs(src, original);
+ const ext = (/\.(jpe?g|png|gif|webp)(?:[?#]|$)/i.exec(orig)?.[1] ?? "jpg").toLowerCase();
+ return `${pre} old-src=${q}${orig}${q} src=${q}https://${host}/${id}/${hash(orig)}.${ext}${q}`;
+ });
+ return `<!DOCTYPE html>
+<html prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article#" itemscope="" itemtype="http://schema.org/Article" style="background-color:#eee">
+<head>
+<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
+<meta name="robots" content="index,noarchive">
+<link rel="canonical" href="https://${host}/${id}">
+<meta property="og:url" content="https://${host}/${id}">
+<title>${title}</title>
+${metas}
+</head>
+<body style="margin:0">
+<center><div id="HEADER" style="background-color:#eee;padding:8px">
+<table style="width:1028px"><tr>
+<td><a href="https://${host}/" style="display:block"><img alt="archive.today" src="https://${host}/apple-touch-icon.png" style="width:48px"></a></td>
+<td>
+<form action="https://${host}/search/" method="get" style="display:inline">
+<input type="text" name="q" value="${original.replace(/&/g, "&").replace(/"/g, """)}" style="width:600px">
+</form>
+<div>webpage capture</div>
+<div>Saved from <a href="https://${host}/o/${id}/${original}">${new URL(original).hostname}</a> · <time itemprop="pubdate" datetime="${isoOf(timestamp)}">${httpDateOf(timestamp)}</time></div>
+<div><a href="https://${host}/${id}/image">screenshot</a> · <a href="https://${host}/newest/${original}">all snapshots from host</a></div>
+</td></tr></table>
+</div></center>
+<div id="CONTENT" style="position:relative">
+<div class="html" style="text-align:left">
+${body}
+</div>
+</div>
+<div id="FOOTER" style="text-align:center;color:#888">archive.today</div>
+</body>
+</html>`;
+}
+
+// ─── The copies it holds ───
+
+export const AT_ARTICLE_URL = "https://journal.example/2019/05/deleted-notes.html";
+export const AT_ARTICLE_ID = "Ab3dE";
+export const AT_ARTICLE_TS = "20190512083000";
+export const AT_ARTICLE_LATER_ID = "Fg7hJ";
+export const AT_ARTICLE_LATER_TS = "20200101101500";
+// A copy held only behind a check (opts.challenge default: none).
+export const AT_CHECKED_URL = "https://checked.example/page.html";
+export const AT_CHECKED_ID = "Kl9mN";
+export const AT_CHECKED_TS = "20210303030303";
+
+const articleHtml = (version) => `<!doctype html>
+<html lang="en"><head><meta charset="utf-8">
+<title>Notes I Later Deleted | Journal</title>
+<meta property="og:title" content="Notes I Later Deleted">
+<meta property="article:published_time" content="2019-05-11T20:00:00Z">
+<meta name="author" content="Sam Example">
+<script>var tracker = 1;</script>
+</head><body>
+<nav><a href="/">Home</a> <a href="/archive">Archive</a></nav>
+<article>
+<header><h1>Notes I Later Deleted</h1><time datetime="2019-05-11T20:00:00Z">May 11, 2019</time></header>
+<p>These are the notes from the meeting, written down the same night so that nothing would be lost to memory.</p>
+<p>The minutes themselves are on <a href="/2019/05/minutes.html">the minutes page</a>, and the group's own account is at <a href="https://other.example/account">other.example</a>.</p>
+<img src="/img/whiteboard.png" alt="The whiteboard after the meeting">
+${version > 1 ? "<p>Edit: a second meeting is planned.</p>" : ""}
+</article>
+<footer>Journal, 2019</footer>
+</body></html>`;
+
+export const COPIES = [
+ { id: AT_ARTICLE_ID, original: AT_ARTICLE_URL, timestamp: AT_ARTICLE_TS, page: () => articleHtml(1) },
+ { id: AT_ARTICLE_LATER_ID, original: AT_ARTICLE_URL, timestamp: AT_ARTICLE_LATER_TS, page: () => articleHtml(2) },
+ {
+ id: AT_CHECKED_ID,
+ original: AT_CHECKED_URL,
+ timestamp: AT_CHECKED_TS,
+ page: () => "<html><head><title>Checked</title></head><body><main><p>A page held behind a check, every word invented for a test.</p></main></body></html>",
+ },
+];
+
+// Lane C's synthetic fixtures (a 2016 status page, a 2012 Tumblr post) as
+// copies, for the "same records either way" checks.
+const FIXTURES = new URL("../../lib/waybackPages/extractors/__fixtures__/", import.meta.url);
+export function fixtureCopy(name, { id, original, timestamp }) {
+ return { id, original, timestamp, page: () => readFileSync(/* turbopackIgnore: true */ new URL(name, FIXTURES), "utf8") };
+}
+
+export const CHALLENGE_HTML = `<!DOCTYPE html><html><head><title>archive.ph</title>
+<script src="https://www.google.com/recaptcha/api.js" async defer></script></head>
+<body><form method="post" action="/"><p>Please complete the security check to access archive.ph</p>
+<div class="g-recaptcha" data-sitekey="synthetic-site-key"></div><input type="submit" value="Submit"></form></body></html>`;
+
+// ─── The server ───
+
+const linkTs = (c) => httpDateOf(c.timestamp);
+
+export async function startFakeArchiveToday(opts = {}) {
+ const copies = opts.copies ?? COPIES;
+ const challenge = opts.challenge ?? [];
+ const challengeStatus = opts.challengeStatus ?? 200;
+ let busy = opts.busyTimes ?? 0;
+ const requests = [];
+ const host = "archive.ph";
+ const checked = (id) => challenge === "all" || (Array.isArray(challenge) && challenge.includes(id));
+ const of = (original) => copies.filter((c) => c.original === original).sort((a, b) => a.timestamp.localeCompare(b.timestamp));
+ const server = http.createServer((req, res) => {
+ const u = new URL(req.url ?? "/", "http://fake");
+ const pathAndQuery = decodeURI(u.pathname) + u.search;
+ requests.push({ path: pathAndQuery, at: Date.now(), ua: String(req.headers["user-agent"] ?? "") });
+ const send = (status, type, body, headers = {}) => {
+ res.writeHead(status, { "content-type": type, ...headers });
+ res.end(body);
+ };
+ if (busy > 0) {
+ busy--;
+ return send(429, "text/html", "<html><body><h1>429 Too Many Requests</h1></body></html>", { "retry-after": "2" });
+ }
+ if (challenge === "all") return send(challengeStatus, "text/html; charset=utf-8", CHALLENGE_HTML);
+ const rest = pathAndQuery.replace(/^\/+/, "");
+ const tm = /^timemap\/(.+)$/.exec(rest);
+ if (tm) {
+ const list = of(tm[1]);
+ if (list.length === 0) return send(404, "text/plain", "not found");
+ const lines = [
+ `<${tm[1]}>; rel="original"`,
+ `<https://${host}/timegate/${tm[1]}>; rel="timegate"`,
+ `<https://${host}/timemap/${tm[1]}>; rel="self"; type="application/link-format"; from="${linkTs(list[0])}"; until="${linkTs(list[list.length - 1])}"`,
+ ...list.map((c, i) => {
+ const rel = list.length === 1 ? "first last memento" : i === 0 ? "first memento" : i === list.length - 1 ? "last memento" : "memento";
+ return `<https://${host}/${c.id}>; rel="${rel}"; datetime="${linkTs(c)}"`;
+ }),
+ ];
+ return send(200, "application/link-format", lines.join(",\n") + "\n");
+ }
+ const pick = /^(newest|oldest)\/(.+)$/.exec(rest);
+ if (pick) {
+ const list = of(pick[2]);
+ if (list.length === 0) return send(404, "text/plain", "not found");
+ const c = pick[1] === "newest" ? list[list.length - 1] : list[0];
+ return send(302, "text/html", "", { location: `https://${host}/${c.id}` });
+ }
+ const near = /^(\d{4,14}|\d{4}\.\d{2}\.\d{2}(?:-\d{6})?)\/(.+)$/.exec(rest);
+ if (near) {
+ const list = of(near[2]);
+ if (list.length === 0) return send(404, "text/plain", "not found");
+ const want = Number(near[1].replace(/[.-]/g, "").padEnd(14, "0"));
+ const c = [...list].sort((a, b) => Math.abs(Number(a.timestamp) - want) - Math.abs(Number(b.timestamp) - want))[0];
+ return send(302, "text/html", "", { location: `https://${host}/${c.id}` });
+ }
+ const one = /^([A-Za-z0-9]{4,6})$/.exec(rest);
+ if (one) {
+ const c = copies.find((x) => x.id === one[1]);
+ if (!c) return send(404, "text/html", "<html><body>No such page</body></html>");
+ if (checked(c.id)) return send(challengeStatus, "text/html; charset=utf-8", CHALLENGE_HTML);
+ return send(200, "text/html; charset=utf-8", wrapLikeArchiveToday(c.page(), { id: c.id, original: c.original, timestamp: c.timestamp, host }), {
+ "memento-datetime": linkTs(c),
+ link: `<${c.original}>; rel="original", <https://${host}/timemap/${c.original}>; rel="timemap"; type="application/link-format", <https://${host}/${c.id}>; rel="memento"; datetime="${linkTs(c)}"`,
+ });
+ }
+ return send(404, "text/plain", "not found");
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const base = `http://127.0.0.1:${server.address().port}`;
+ return {
+ base,
+ requests,
+ fetch: (url, init) => fetch(String(url).replace(/^https?:\/\/(?:www\.)?archive\.(?:ph|today|is|li|vn|fo|md)/, base), init),
+ close: () => new Promise((r) => server.close(() => r())),
+ };
+}
diff --git a/common/testing/web/fakeWayback.d.mts b/common/testing/web/fakeWayback.d.mts
@@ -37,4 +37,6 @@ export function startFakeWayback(opts?: {
streamBusyTimes?: number;
// (release 37) the page captures served raw (default PAGE_CAPTURES).
pageCaptures?: FakePageCapture[];
+ // (release 37 lane F) originals CDX and their captures answer 403 for.
+ excluded?: string[];
}): Promise<FakeWayback>;
diff --git a/common/testing/web/fakeWayback.mjs b/common/testing/web/fakeWayback.mjs
@@ -27,6 +27,8 @@
// known page answers 302 to the nearest one; a capture with `offsite` answers 302 there
// opts.busyTimes: the first N CDX requests answer 429 (Retry-After: 1); opts.downTimes: then 503s.
// opts.streamBusyTimes: the first N stream requests answer 429 (Retry-After: 1).
+// opts.excluded: (release 37 lane F) originals the archive answers 403 for — CDX and
+// their captures — while every other URL answers as usual.
import http from "node:http";
@@ -180,6 +182,7 @@ export async function startFakeWayback(opts = {}) {
const requests = [];
let busy = opts.busyTimes ?? 0;
let down = opts.downTimes ?? 0;
+ const excluded = opts.excluded ?? [];
const server = http.createServer((req, res) => {
const u = new URL(req.url ?? "/", "http://fake");
requests.push({ path: u.pathname + u.search, at: Date.now() });
@@ -187,6 +190,15 @@ export async function startFakeWayback(opts = {}) {
res.writeHead(status, { "content-type": type, ...headers });
res.end(body);
};
+ // ─── Release 37 (lane F): an EXCLUDED URL — CDX and its captures answer
+ // 403, as the Wayback Machine does for a URL it will not show anyone
+ // (opts.excluded: the originals). Every other URL answers as usual.
+ if (excluded.length > 0) {
+ const asked = u.pathname === "/cdx/search/cdx" ? (u.searchParams.get("url") ?? "") : /^\/web\/\d{1,14}(?:[a-z]{2}_)?\/(.+)$/.exec(u.pathname + u.search)?.[1] ?? "";
+ if (asked && excluded.includes(asked)) {
+ return send(403, "text/html", "<p>Sorry. This URL has been excluded from the Wayback Machine.</p>");
+ }
+ }
if (u.pathname === "/cdx/search/cdx") {
if (busy > 0) {
busy--;
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -121,6 +121,9 @@
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://web.archive.org/web/20140305120000/https://blog.example/a-post.html","dryRun":true}'
// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20140301"}' --wait
// pnpm ops reextract-pages --json '{"slug":"demo-pages","dryRun":true}' --wait
+// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://archive.ph/AbCdE","dryRun":true}'
+// pnpm ops import-page --json '{"slug":"demo-pages","url":"https://blog.example/a-post.html","at":"20190601","source":"archive.today"}' --wait
+// pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}'
// pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait
// pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'
// pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait
@@ -449,6 +452,10 @@ const ACTIONS = [
// re-derived from its stored captures ({slug, dryRun?}), offline, as a job.
"import-page",
"reextract-pages",
+ // ARCHIVE SOURCES (release 37 lane F): the copies of a page across archive
+ // sources — the Wayback Machine and archive.today — read only and paced
+ // ({url, source?, limit?}).
+ "archive-lookup",
// EVIDENCE GAPS (release 29 E2): the Wayback Machine's captures of a page
// ({url} or a record's {slug, id}), read only and paced; and find-copy — a
// copy of every gone recording a report cites (Wayback, then archive.org),
@@ -1409,7 +1416,9 @@ export function usage() {
' captures that recorded a 200, "limit"?: 100 (at most 500) -> {url,',
' found, captures: [{timestamp, status, mimetype?, replayUrl}]}, oldest',
" first. One request through the editor's Wayback client, with archive.org's",
- " manners (one at a time, 2 s apart, 429s waited out). Read only.",
+ " manners (one at a time, 2 s apart, 429s waited out). Read only. A URL",
+ ' the Wayback Machine answers 403 for is excluded: HTTP 403, "refusal":',
+ ' "excluded" ("excluded from the Wayback Machine (cause unknown)").',
"",
'find-copy looks for a copy of every gone recording (deleted or private) a',
' report cites, and fetches the cited windows from it, as a find-copy job:',
@@ -1477,6 +1486,26 @@ export function usage() {
' fetched again. "dryRun" answers what it would fetch and starts nothing.',
" The log ends with @@import-page {ok, slug, url, captureTs, originalUrl,",
" records, written, updated, unchanged, extractor, already?, error?}.",
+ ' archive.today (release 37 lane F): "url" may be an archive.today copy',
+ " (archive.ph/<id>, /<timestamp>/<page>, /newest/<page>), or the page's",
+ ' own URL with "at" and "source": "archive.today" for its copy nearest that',
+ " date (one timemap request); the job runs on the platform:archive.today",
+ " queue at archive.today's pace (one request at a time, 8 s apart; a 429",
+ " stops it and rests the client). The copy is stored as served with its",
+ " source and URL. A check page (a CAPTCHA) is refused, never solved:",
+ " Connect archive session on the channel page or Settings, then again.",
+ ' The result carries "source", "mementoUrl" and, for a refusal, "refusal":',
+ ' "excluded" (the Wayback Machine answered 403 for the page), "challenge",',
+ ' "rate-limited", ….',
+ "",
+ 'archive-lookup answers the copies of a page each archive source holds:',
+ ' {"url"} (the page\'s own URL), "source"?: "wayback" | "archive.today"',
+ ' (default both), "limit"?: 50 per source (at most 500) -> {url, found,',
+ " sources: [{source, label, ok, captures: [{source, captureTs, originalUrl,",
+ " mementoUrl, status?, mimetype?}], refusal?, error?}]}, oldest first. Each",
+ " source through its own paced client; one that refuses is its own entry's",
+ ' sentence (refusal "excluded": excluded from the Wayback Machine (cause',
+ ' unknown); "challenge"; "rate-limited"). Read only. wayback-lookup stays.',
"",
"reextract-pages re-derives a Wayback pages channel's records from the raw",
' captures it stores: {"slug", "dryRun"?}. No request. A reextract-pages job',
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -910,3 +910,17 @@ test("import-page and reextract-pages are POSTs to their routes, named in the us
assert.match(usage(), /Actions:.*import-post, import-page, reextract-pages/);
assert.match(usage(), /import-page imports ONE Wayback Machine capture/);
});
+
+// Release 37 lane F: the copies of a page across archive sources, and an
+// archive.today copy's import, are POSTs to their routes.
+test("archive-lookup is a POST to its route; import-page passes source through; both named in the usage", () => {
+ const p = parseArgs(["archive-lookup", "--json", '{"url":"https://blog.example/a.html","source":"archive.today","limit":5}']);
+ assert.equal(p.method, "POST");
+ assert.equal(p.path, "/api/ops/archive-lookup");
+ assert.deepEqual(p.body, { url: "https://blog.example/a.html", source: "archive.today", limit: 5 });
+ const i = parseArgs(["import-page", "--json", '{"slug":"old-blog","url":"https://blog.example/a.html","at":"2019","source":"archive.today"}']);
+ assert.deepEqual(i.body, { slug: "old-blog", url: "https://blog.example/a.html", at: "2019", source: "archive.today" });
+ assert.match(usage(), /Actions:.*reextract-pages, archive-lookup/);
+ assert.match(usage(), /archive-lookup answers the copies of a page each archive source holds/);
+ assert.match(usage(), /excluded from the Wayback Machine \(cause/);
+});