// IMPORT ONE PAGE CAPTURE (release 37 S1, `import-page`): one Wayback Machine // capture of a page that is not a video, into a Wayback pages channel // (platform "webpage"), as page records in its posts. // // {slug, url: } web.archive.org/web/[mod]/ // {slug, url: , at} the capture nearest `at` (YYYYMMDD[hhmmss]), // found through the CDX API // // The job: (the nearest capture, through CDX) → the raw `id_` body // (WaybackClient.getCapture: 2 MB cap, html/plain/json only, redirects inside // the archive followed, the FINAL capture recorded) → stored under the // channel's `pages/` → extracted (lib/waybackPages/extract.ts) → page records // upserted into the posts store (the split-record merge) — exactly where a // post fetch writes, and, as for a fetch, the index picks them up on its next // build. One capture per job: nothing here crawls. // // Refused before any request, with the sentence a caller shows: no such // channel; a channel that is not a Wayback pages channel; a URL that names no // capture (a calendar page, a bare URL with no date); a capture of a VIDEO // ("use import-video"); an x.com/twitter.com capture into a channel that does // not target X while `social.x.visibility` is "private" (X captures are // private exactly as X posts are). After the fetch: a body that is not a page // (its mimetype), too large, or a redirect off the archive. // // POLITE: every request goes through the process's Wayback client (one // 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.ph/, //, /newest/ // {slug, url: , 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"; import type { ChannelConfig } from "../lib/channelConfig"; import { readChannelConfig } from "./channels"; import { readAllPosts, upsertPosts } from "../lib/posts-server"; 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, type WaybackClient } from "../lib/waybackClient"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { isWaybackPagesChannel } from "../lib/waybackPages/config"; import { isInstagramHostUrl, 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, writeStoredCapture, type StoredCapture, } from "../lib/waybackPages/store-server"; import { instagramPostsVisibility, isInstagramPostsChannel, isXPostsChannel, xPostsVisibility, } from "../lib/postsVisibility"; import type { Post } from "../lib/posts"; export const IMPORT_PAGE_JOB_KIND = "import-page"; export const IMPORT_PAGE_RESULT_MARKER = "@@import-page "; // Every Wayback request is archive.org's; the page imports run one at a time // on the queue a web.archive.org URL routes to. export const WAYBACK_PAGES_QUEUE = queueKeyForUrl("https://web.archive.org/"); type VisibilitySettings = { social?: { x?: { visibility?: unknown }; instagram?: { visibility?: unknown } } }; export type ImportPagePlan = { config: ChannelConfig; // 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): string { return ask.source === "archive.today" ? ARCHIVE_TODAY_QUEUE : WAYBACK_PAGES_QUEUE; } // The refusal an X capture — or an Instagram one (lane instagram) — meets in // this channel, or null. One question for both platforms: every call site // asks it of a capture's original URL before the capture is written. export function xCaptureRefusal( config: ChannelConfig, slug: string, originalUrl: string, settings: VisibilitySettings, ): string | null { if (isInstagramHostUrl(originalUrl)) { if (instagramPostsVisibility(settings) !== "private") return null; if (isInstagramPostsChannel(config)) return null; return ( `${originalUrl} is on Instagram, whose posts are private here (social.instagram.visibility is not "public"); ` + `import an Instagram capture into a Wayback pages channel whose target is on instagram.com, which a public site leaves out — not into ${slug}` ); } if (!isXHostUrl(originalUrl)) return null; if (xPostsVisibility(settings) !== "private") return null; if (isXPostsChannel(config)) return null; return ( `${originalUrl} is on X, whose posts are private here (social.x.visibility "private"); ` + `import an X capture into a Wayback pages channel whose target is on x.com or twitter.com, which a public site leaves out — not into ${slug}` ); } // Everything checked before a job: the plan, or the refusal. export async function planImportPage( paths: Paths, 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}` }; if (!isWaybackPagesChannel(config)) { return { ok: false, error: `${opts.slug} is not a Wayback pages channel; import-page imports into a channel on platform "webpage"`, }; } const parsed = parseArchiveCaptureAsk(opts.url, opts.at, opts.source); if (!parsed.ok) return parsed; // 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 }; } return { ok: true, plan: { config, ask: parsed.ask } }; } export type ImportPageResult = { ok: boolean; slug: string; url: string; // The capture imported (after the nearest lookup and any redirect). captureTs?: string; originalUrl?: string; waybackUrl?: string; // The capture was already stored; nothing was fetched. already?: boolean; dryRun?: boolean; // What a dry run would fetch. wouldFetch?: string; records?: string[]; written: number; 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; }; // THE CAPTURE'S RECORDS, from its stored body: what an import and a re-extract // both make. Pure but for the extractor registry. export function recordsOfCapture( slug: string, capture: StoredCapture, body: Buffer, ): { posts: Post[]; extractor: { name: string; version: number }; fallback?: StoredCapture["extractorFallback"] } { 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(input); const posts = res.drafts.map((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; 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 | 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 { 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, source: opts.source, settings }); if (!planned.ok) return { ...base, error: planned.error }; 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 { const log = (line: string) => opts.onLog?.(line); const { base } = opts; const { config } = opts.plan; const ask = opts.plan.ask as Extract; const client = opts.client ?? defaultWaybackClient; const channelRoot = path.join(opts.paths.channelsDir, opts.slug); if (opts.dryRun) { const wouldFetch = ask.kind === "capture" ? waybackRawUrl(ask) : `the capture of ${ask.originalUrl} nearest ${ask.at} (one CDX lookup), then its raw body`; const already = ask.kind === "capture" && /^\d{14}$/.test(ask.captureTs) && (await hasStoredCapture(channelRoot, ask.captureTs, ask.originalUrl)); return { ...base, ok: true, dryRun: true, ...(already ? { already: true } : {}), wouldFetch: already ? "nothing (the capture is already stored)" : wouldFetch, ...(ask.kind === "capture" ? { captureTs: ask.captureTs } : {}), originalUrl: 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 }), }; } 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 }), }; } // 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 { 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; const client = opts.archiveTodayClient ?? defaultArchiveTodayClient; const channelRoot = path.join(opts.paths.channelsDir, opts.slug); 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, 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 } : {}), }; } 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, stored: StoredCapture, body: Buffer, ): Promise> { 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 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 { const settings = opts.settings ?? getSettings(); 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: importPageQueueOf(planned.plan.ask), paths: opts.paths, channelSlug: opts.slug, fn: async (onLog, signal) => { 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, }); onLog(`${IMPORT_PAGE_RESULT_MARKER}${JSON.stringify(result)}`); opts.onDone?.(result); if (!result.ok) throw new Error(result.error ?? "Page import failed"); }, }); } export class ImportPageRefusal extends Error { constructor(message: string) { super(message); this.name = "ImportPageRefusal"; } } // 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 }> { const res = await queueImportPage({ ...opts, paths: opts.paths ?? getPaths() }); if (!res.ok) throw new ImportPageRefusal(res.error); void res.stream.cancel(); return { jobId: res.jobId }; } // The capture's stored facts, for a caller holding a record (lane D's moment // page, a re-extract). export async function storedCaptureOf(paths: Paths, slug: string, post: Pick): Promise { if (!post.page) return null; return readStoredCapture(pageCaptureDir(path.join(paths.channelsDir, slug), post.page.captureTs, post.page.originalUrl)); }