Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 7ebc4df24e999bb868f801a7dc9c8002175c8bac
parent 366250afde0b935222d21a1fdb9ca44a6949ecc7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 14:19:41 -0400

editor: Archived pages — archive.today imports, Look up a page, Connect archive session, archive-lookup

The New channel form's kind reads "Archived pages" and takes an archive.today copy's URL;
target rows choose their sources; Import a capture takes a source; Look up a page lists each
source's copies with an Import per copy; Connect archive session on the panel and in
Settings → Archive sources; POST /api/ops/archive-lookup; import-page takes source;
wayback-lookup answers an exclusion as 403 refusal "excluded"; the e2e fake wiring and
archive-today-pages.spec; OPERATING, FACTS, CHANGELOG, the record (draft).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MOPERATING.md | 34++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 2++
Aeditor/app/api/ops/archive-lookup/route.ts | 34++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/import-page/route.ts | 14+++++++++++---
Meditor/app/api/ops/wayback-lookup/route.ts | 7+++++++
Meditor/app/channels/[slug]/components/WaybackPagesPanel.tsx | 141++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Meditor/app/channels/[slug]/page.tsx | 7++++++-
Meditor/app/channels/[slug]/waybackPagesActions.ts | 35+++++++++++++++++++++++++++++++++--
Meditor/app/channels/components/ChannelForm.tsx | 4++--
Meditor/app/channels/components/WaybackTargetsField.tsx | 37++++++++++++++++++++++++++++++++++---
Aeditor/app/settings/archiveSessionActions.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/settings/components/ArchiveSessionSection.tsx | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/settings/page.tsx | 7+++++++
Aeditor/e2e/archive-today-pages.spec.ts | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/servers.ts | 8++++++++
Meditor/playwright.config.ts | 3+++
Mplans/FACTS.md | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/release-37/archive-sources.md | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
18 files changed, 839 insertions(+), 16 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -111,6 +111,40 @@ pnpm ops reextract-pages --json '{"slug":"old-blog","dryRun":true}' --wait `pnpm archilyzer wayback pages reextract <slug> --dry-run`. - An x.com / twitter.com capture is private exactly as X posts are (`social.x.visibility`): while X is private, only a Wayback pages channel whose target is on X takes one, and a public site leaves that channel out. +- A URL the Wayback Machine answers 403 for (while it answers others) is **excluded** — "excluded from the Wayback + Machine (cause unknown)": `wayback-lookup` answers 403 with `refusal: "excluded"`, `import-page` and + `archive-lookup` carry the same code and sentence. + +### Archived pages: the Wayback Machine and archive.today + +```sh +pnpm ops archive-lookup --json '{"url":"https://blog.example/a-post.html"}' +pnpm ops import-page --json '{"slug":"old-blog","url":"https://archive.ph/<id>","dryRun":true}' +pnpm ops import-page --json '{"slug":"old-blog","url":"https://archive.ph/<id>"}' --wait +pnpm ops import-page --json '{"slug":"old-blog","url":"https://blog.example/a-post.html","at":"20190601","source":"archive.today"}' --wait +pnpm archilyzer archive lookup https://blog.example/a-post.html --source archive.today +``` + +- The channel kind is **Archived pages** in the New channel form (the config key stays `wayback`). A target names + where its copies are looked for: `sources: ["wayback", "archive.today"]` (absent = the Wayback Machine alone); an + archive.today copy's URL in the form (`archive.ph/newest/<page>`) makes a channel whose target is that page on + archive.today. +- `import-page` takes an archive.today copy (`archive.ph/<id>`, `/<timestamp>/<page>`, `/newest/<page>`; any of its + names — archive.ph, .today, .is, .li, .vn, .fo, .md — is read from the one in `settings.archives`), or the page's + own URL with `at` and `source: "archive.today"` (its timemap, one request). The job runs on + `platform:archive.today`, one request at a time, 8 s apart (jittered); a 429 stops it and nothing is sent to + archive.today for 30 minutes. The copy is stored as served (`capture.json` gains `source` and `mementoUrl`) and + unwrapped each time it is read, so `reextract-pages` re-reads it offline like any capture. Its records carry + `page.source: "archive.today"` and `page.archiveUrl`; their images are archive.today's cached copies. +- **A check is never solved.** archive.today often answers a client that is not a browser with a CAPTCHA: the + import is refused (`refusal: "challenge"`), never parsed. With `settings.archives.archiveTodayBrowser` (the + default) the copy is read once more through the headless browser on the archive session's profile; when that + check still stands, open **Connect archive session** (the channel page, or Settings → Archive sources), pass the + check once in the window on the editor's machine and close it, then import again — the profile keeps the + clearance (`transcripts/.archive-session/archive.today/`). +- The channel page's **Look up a page** (and `archive-lookup`) lists each source's copies of a page, with an Import + button per copy; a source that refuses says why in its own line. +- Adding another archive service is one module: `plans/release-37/archive-sources.md`, "Adding an archive source". ## Fetch and capture posts diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## [Unreleased] +- **archive.today copies are page records too, like Wayback captures.** The channel kind is now **Archived pages** on the New channel form (paste an archive.today copy's URL, `archive.ph/newest/<page>`, and the channel's target is that page on archive.today), and each target says where its copies are looked for: the Wayback Machine, archive.today, or both. The channel page's **Import a capture** takes an archive.today copy's URL (`archive.ph/<id>`, or any of its other names), or the page's own URL, a date and **on archive.today** for the copy nearest that date; the copy is kept as archive.today served it and read without its header bar, links back to the pages they pointed at, so a tweet, a Tumblr post or an article gives the same records it would from the Wayback Machine — each saying it came from archive.today and linking that copy, its images archive.today's own copies. archive.today is asked one request at a time, eight seconds apart; when it says "too many requests" the import stops with a sentence and nothing more is asked of it for half an hour. When it answers with a CAPTCHA instead of the copy, the import is refused and never reads the CAPTCHA as a page: **Connect archive session** (on the channel page, and in Settings → Archive sources) opens a window on the editor's machine to pass the check once, and the next import reads through it; nothing is ever solved for you. **Look up a page** lists every copy each archive holds of a page, with an Import button on each. From a terminal: `pnpm ops import-page` takes `"source": "archive.today"`, `pnpm ops archive-lookup` lists the copies, and `pnpm archilyzer archive lookup <url>` runs without the editor. Needs a restart of the editor. +- **A page the Wayback Machine will not show says so.** When the Wayback Machine answers "forbidden" for one page while it answers others, that page is excluded from it, and Wayback lookups, page imports and archive lookups now say "excluded from the Wayback Machine (cause unknown)" instead of reporting an error. - **Wayback Machine captures of pages are records of their own.** A capture of a page that is not a video — an old blog post, a group's site, a channel's About page, a document taken down — goes into a **Wayback pages** channel: on the New channel form, paste a Wayback URL of such a page (`web.archive.org/web/*/example.com/blog*` scopes every capture under that path, `*.example.com` a whole domain, one capture's URL that page) or choose **Wayback pages** as the platform, and edit its targets (a URL, how it matches, optional dates). The channel page's **Import a capture** takes a capture's URL, or the page's own URL and a date for the capture nearest it, and imports it as one job at archive.org's pace: the page as captured is kept, its readable text, title, author, date, links and images become a record — searchable, in the MCP and on a built site like any post — dated by the page's own date when it gives one. A later capture of the same page is kept as a version of the first. **Re-extract** reads every kept capture again with no request. A capture of a video is still Import video's, and is refused here with a sentence saying so. An x.com or twitter.com capture is private exactly as X posts are. From a terminal: `pnpm ops import-page` (`dryRun` says what it would fetch) and `pnpm ops reextract-pages`; `pnpm archilyzer wayback pages import|reextract` run without the editor. Needs a restart of the editor. - **Wayback captures of Tumblr, Twitter, forums, Google Docs and YouTube About pages are read as their posts.** A Tumblr blog's post, index, tagged or archive page becomes one record per post (its date, tags, images and what it reblogged), and the same post seen on an index and on its own page is one record. An old Twitter profile or status page becomes one record per tweet — replies, retweets and quotes pointing at the tweets they answer, and the profile's bio, website and counts as one more — and a capture of X's later JavaScript app says it holds no posts. A captured XenForo thread page gives the same posts, with the same ids, that a forum channel of the thread holds. A Google Doc's mobilebasic or published page gives the document's text with its headings; its edit page says it holds no text and names the mobilebasic address to look for. A YouTube channel's About page gives how the channel described itself at that capture: description, links, joined date and counts. Nothing calls a model. - **Focus the queues on a site, or on some channels, from a terminal.** `pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"<id>"}}'` does what the /channels focus bar's **Focus site** does: that site's channels lead every lane, and the focus follows the site's membership. `{"kind":"channels","slugs":[…]}` focuses a list and `{"kind":"none"}` ends the focus. `focus` goes alone in the body. Needs a restart of the editor. diff --git a/editor/app/api/ops/archive-lookup/route.ts b/editor/app/api/ops/archive-lookup/route.ts @@ -0,0 +1,34 @@ +import { NextResponse } from "next/server"; +import { archiveLookupAction } from "../../../channels/[slug]/waybackPagesActions"; +import { OpsInputError, ops, opsFail, optPositiveInt, optString, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { url, source?, limit? } -> { ok: true, url, found, sources: [{ source, +// label, ok, captures: [{ source, captureTs, originalUrl, mementoUrl, +// status?, mimetype? }], refusal?, error? }] } +// +// THE COPIES OF A PAGE across archive sources (release 37 lane F, +// common/lib/archives/): the Wayback Machine (its CDX API, archive.org's pace) +// and archive.today (its timemap, one request at a time with a long gap), in +// that order, or only `source` ("wayback" | "archive.today"). At most `limit` +// per source (default 50, at most 500), oldest first. A source that refuses is +// its own entry's sentence — `refusal: "excluded"` (the Wayback Machine +// answered 403 for the URL: "excluded from the Wayback Machine (cause +// unknown)"), "challenge" (archive.today put a check in front: Connect archive +// session), "rate-limited" (a 429: the client rests) — and the others still +// answer. Read only; nothing is stored. `wayback-lookup` stays as it is. +const MAX_LIMIT = 500; + +export async function POST(request: Request) { + return ops(request, ["url", "source", "limit"], async (body) => { + const url = reqString(body, "url"); + if (!/^https?:\/\/[^\s]+$/.test(url)) throw new OpsInputError(`"url" must be an http(s) URL`); + const source = optString(body, "source")?.trim() || undefined; + const limit = optPositiveInt(body, "limit") ?? 50; + if (limit > MAX_LIMIT) throw new OpsInputError(`"limit" is at most ${MAX_LIMIT}`); + const r = await archiveLookupAction(url, source, limit); + if (!r.ok) return opsFail(r.error, 400); + return NextResponse.json({ ok: true, ...r.lookup }); + }); +} diff --git a/editor/app/api/ops/import-page/route.ts b/editor/app/api/ops/import-page/route.ts @@ -19,16 +19,24 @@ export const dynamic = "force-dynamic"; // Every refusal is the controller's sentence: no such channel, not a Wayback // pages channel, a URL that names no capture, a video ("use import-video"), // an X capture outside an X channel while X is private. +// +// Release 37 lane F: `url` may be an archive.today copy (https://archive.ph/<id>, +// /<ts>/<page>, /newest/<page>), or the page's own URL with `at` and +// `source: "archive.today"` for its copy nearest that date — an import-page +// job on the `platform:archive.today` queue, at archive.today's pace. A +// refusal at the source is in the log's result as `refusal` ("excluded", +// "challenge", "rate-limited", …). export async function POST(request: Request) { - return ops(request, ["slug", "url", "at", "dryRun"], async (body) => { + return ops(request, ["slug", "url", "at", "source", "dryRun"], async (body) => { const slug = reqSlug(body, "slug"); const url = reqString(body, "url"); const at = optString(body, "at")?.trim() || undefined; + const source = optString(body, "source")?.trim() || undefined; if (optBool(body, "dryRun") === true) { - const r = await importPageDryRunAction(slug, url, at); + const r = await importPageDryRunAction(slug, url, at, source); if (!r.ok) return NextResponse.json({ ok: false, error: r.error }, { status: 400 }); return NextResponse.json(r); } - return jobResponse(await importPageAction(slug, url, at, "ops")); + return jobResponse(await importPageAction(slug, url, at, "ops", source)); }); } diff --git a/editor/app/api/ops/wayback-lookup/route.ts b/editor/app/api/ops/wayback-lookup/route.ts @@ -1,5 +1,6 @@ import { NextResponse } from "next/server"; import { ArchiveOrgRequestError } from "yt-dlp-transcript-common/lib/archiveOrgClient"; +import { isWaybackExcluded } from "yt-dlp-transcript-common/lib/waybackClient"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { recordWebpageUrl, waybackLookup } from "yt-dlp-transcript-common/publish/findCopy"; import { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqSlug, reqVideoId } from "../_lib"; @@ -17,6 +18,9 @@ export const dynamic = "force-dynamic"; // archive.org's manners (one at a time, a 2 s gap, the project's User-Agent, // 429s waited out a few times, then a 502). Read only; nothing is fetched. // `find-copy` is what fetches a gone recording's windows from a capture. +// Release 37 lane F: a URL the Wayback Machine answers 403 for is EXCLUDED +// ("excluded from the Wayback Machine (cause unknown)"): a 403 with +// `refusal: "excluded"`. `archive-lookup` asks every archive source. const MAX_LIMIT = 500; export async function POST(request: Request) { @@ -43,6 +47,9 @@ export async function POST(request: Request) { const r = await waybackLookup(url, { okOnly: optBool(body, "okOnly") === true, limit }); return NextResponse.json({ ok: true, url, found: r.captures.length, captures: r.captures }); } catch (e) { + // Release 37 lane F: a 403 for this URL while the archive answers is an + // exclusion — a fact about the URL, not an outage. + if (isWaybackExcluded(e)) return opsFail((e as Error).message, 403, { refusal: "excluded" }); if (e instanceof ArchiveOrgRequestError) return opsFail(e.message, 502); throw e; } diff --git a/editor/app/channels/[slug]/components/WaybackPagesPanel.tsx b/editor/app/channels/[slug]/components/WaybackPagesPanel.tsx @@ -9,7 +9,11 @@ import { useState } from "react"; import Link from "next/link"; import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; import { cancelJobAction } from "../../../jobs/actions"; -import { importPageAction, reextractPagesAction } from "../waybackPagesActions"; +import { archiveLookupAction, importPageAction, reextractPagesAction } from "../waybackPagesActions"; +import { ConnectArchiveSession } from "../../../settings/components/ArchiveSessionSection"; +import type { ArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; +import type { ArchiveLookup } from "yt-dlp-transcript-common/lib/archives/index"; +import { archiveSourceLabel, isArchiveTodayUrl } from "yt-dlp-transcript-common/lib/archives/mementos"; export type WaybackPagesRecordRow = { id: string; @@ -19,14 +23,18 @@ export type WaybackPagesRecordRow = { captureDate: string; originalUrl: string; waybackUrl: string; + // Release 37 lane F: the archive source, when it is not the Wayback Machine. + source?: string; noContent?: boolean; }; export type WaybackPagesState = { recordCount: number; captureCount: number; - targets: { url: string; match: string; from?: string; to?: string }[]; + targets: { url: string; match: string; from?: string; to?: string; sources?: string[] }[]; recent: WaybackPagesRecordRow[]; + // Release 37 lane F: archive.today's check, passed once in Connect. + archiveSession?: ArchiveSessionStatus; }; const MATCH_LABEL: Record<string, string> = { @@ -45,6 +53,9 @@ function atFromDate(v: string): string { export function WaybackPagesPanel({ slug, state }: { slug: string; state: WaybackPagesState }) { const [url, setUrl] = useState(""); const [date, setDate] = useState(""); + // Release 37 lane F: where the capture nearest a date is looked for (a + // copy's URL names its own source). + const [source, setSource] = useState("wayback"); const [importJob, setImportJob] = useState<string | null>(null); const [reextractJob, setReextractJob] = useState<string | null>(null); const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono"; @@ -66,6 +77,9 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac {t.from || t.to ? ( <span className="text-muted-foreground"> · captured {t.from ?? "…"}–{t.to ?? "…"}</span> ) : null} + {t.sources?.length ? ( + <span className="text-muted-foreground"> · on {t.sources.map((x) => archiveSourceLabel(x)).join(" and ")}</span> + ) : null} </li> ))} </ul> @@ -93,6 +107,7 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac <a href={r.waybackUrl} target="_blank" rel="noreferrer" className="font-mono text-xs underline underline-offset-2"> {r.captureDate} </a> + {r.source && <span className="ml-2 text-xs text-muted-foreground">{archiveSourceLabel(r.source)}</span>} </td> </tr> ))} @@ -106,10 +121,10 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac value={url} onChange={(e) => setUrl(e.target.value)} aria-label="capture URL" - placeholder="https://web.archive.org/web/20140305120000/https://…" + placeholder="https://web.archive.org/web/20140305120000/https://… or https://archive.ph/…" className={`${input} w-[36rem] max-w-full`} /> - <label className="flex items-center gap-2 text-sm"> + <label className="flex flex-wrap items-center gap-2 text-sm"> <span>Nearest to</span> <input type="date" @@ -118,10 +133,29 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac aria-label="capture date" className="rounded border border-border bg-card px-2 py-1 text-sm" /> + <span>on</span> + <select + value={source} + onChange={(e) => setSource(e.target.value)} + aria-label="capture source" + disabled={isArchiveTodayUrl(url)} + className="rounded border border-border bg-card px-2 py-1 text-sm" + > + <option value="wayback">the Wayback Machine</option> + <option value="archive.today">archive.today</option> + </select> <span className="text-xs text-muted-foreground">with the page&apos;s own URL</span> </label> <StreamActionLog - trigger={() => importPageAction(slug, url.trim(), date ? atFromDate(date) : undefined)} + trigger={() => + importPageAction( + slug, + url.trim(), + date ? atFromDate(date) : undefined, + undefined, + date && source !== "wayback" && !isArchiveTodayUrl(url) ? source : undefined, + ) + } cancelAction={cancelJobAction} buttonLabel="Import capture" runningLabel="Importing…" @@ -135,6 +169,13 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac </Link> )} </section> + <ArchiveLookupSection slug={slug} /> + {state.archiveSession && ( + <section aria-label="archive session" className="flex flex-col gap-2 rounded-lg border border-border p-3"> + <h4 className="text-sm font-semibold">archive.today check</h4> + <ConnectArchiveSession initial={state.archiveSession} /> + </section> + )} <section aria-label="re-extract" className="flex flex-col gap-2 rounded-lg border border-border p-3"> <h4 className="text-sm font-semibold">Re-extract</h4> <span className="text-xs text-muted-foreground"> @@ -158,3 +199,93 @@ export function WaybackPagesPanel({ slug, state }: { slug: string; state: Waybac </div> ); } + +// LOOK UP A PAGE across archive sources (release 37 lane F, `archive-lookup`): +// the copies each source holds, read only; each row imports that one copy. +function ArchiveLookupSection({ slug }: { slug: string }) { + const [page, setPage] = useState(""); + const [lookup, setLookup] = useState<ArchiveLookup | null>(null); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const [jobs, setJobs] = useState<Record<string, string>>({}); + const [refusals, setRefusals] = useState<Record<string, string>>({}); + const input = "rounded border border-border bg-card px-2 py-1 text-sm font-mono"; + return ( + <section aria-label="look up a page" className="flex flex-col gap-2 rounded-lg border border-border p-3"> + <h4 className="text-sm font-semibold">Look up a page</h4> + <div className="flex flex-wrap items-center gap-2"> + <input + value={page} + onChange={(e) => setPage(e.target.value)} + aria-label="page URL" + placeholder="https://… (the page's own URL)" + className={`${input} w-[30rem] max-w-full`} + /> + <button + type="button" + disabled={busy || !page.trim()} + onClick={async () => { + setBusy(true); + setError(null); + try { + const r = await archiveLookupAction(page.trim()); + if (r.ok) setLookup(r.lookup); + else setError(r.error); + } finally { + setBusy(false); + } + }} + className="rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50" + > + {busy ? "Looking…" : "Look up"} + </button> + </div> + {error && ( + <span role="alert" aria-label="lookup error" className="text-xs text-destructive"> + {error} + </span> + )} + {lookup && + lookup.sources.map((s) => ( + <div key={s.source} data-archive-source={s.source} className="flex flex-col gap-1"> + <span role="status" aria-label={`${s.label} copies`} className="text-sm"> + {s.label}: {s.ok ? `${s.captures.length} cop${s.captures.length === 1 ? "y" : "ies"}` : s.error} + </span> + {s.captures.length > 0 && ( + <ul className="flex flex-col gap-1 text-xs"> + {s.captures.map((c) => ( + <li key={c.mementoUrl} className="flex flex-wrap items-center gap-2 font-mono"> + <a href={c.mementoUrl} target="_blank" rel="noreferrer" className="underline underline-offset-2"> + {c.captureTs} + </a> + <span className="text-muted-foreground">{c.status ?? ""}</span> + {jobs[c.mementoUrl] ? ( + <Link href={`/jobs/${jobs[c.mementoUrl]}`} className="underline underline-offset-2"> + import job + </Link> + ) : ( + <button + type="button" + aria-label={`import ${s.source} ${c.captureTs}`} + onClick={async () => { + const r = await importPageAction(slug, c.mementoUrl); + if (r.ok) { + setJobs((j) => ({ ...j, [c.mementoUrl]: r.jobId })); + void r.stream.cancel(); + } else setRefusals((x) => ({ ...x, [c.mementoUrl]: r.error })); + }} + className="rounded border border-border px-1.5 py-0.5 hover:bg-muted" + > + Import + </button> + )} + {refusals[c.mementoUrl] && <span className="text-destructive">{refusals[c.mementoUrl]}</span>} + </li> + ))} + </ul> + )} + </div> + ))} + </section> + ); +} diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -24,6 +24,7 @@ import { SocialChannelPanel } from "./components/SocialChannelPanel"; import { WaybackPagesPanel } from "./components/WaybackPagesPanel"; import { isWaybackPagesChannel } from "yt-dlp-transcript-common/lib/waybackPages/config"; import { countStoredCaptures } from "yt-dlp-transcript-common/lib/waybackPages/store-server"; +import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; import { waybackCaptureDate } from "yt-dlp-transcript-common/lib/wayback"; import { listPostFetchersFor } from "./socialActions"; import { NoReportYet } from "./components/NoReportYet"; @@ -200,9 +201,12 @@ export default async function ChannelDetailPage({ captureTs: p.page!.captureTs, captureDate: waybackCaptureDate(p.page!.captureTs), originalUrl: p.page!.originalUrl, - waybackUrl: p.page!.waybackUrl, + waybackUrl: p.page!.archiveUrl ?? p.page!.waybackUrl, + ...(p.page!.source ? { source: p.page!.source } : {}), ...(p.page!.noContent ? { noContent: true } : {}), })), + // Release 37 lane F: archive.today's check, passed once in Connect. + archiveSession: await readArchiveSessionStatus(paths), } : null; return ( @@ -216,6 +220,7 @@ export default async function ChannelDetailPage({ captureCount: wayback.captureCount, targets: config.wayback?.targets ?? [], recent: wayback.recent, + archiveSession: wayback.archiveSession, }} /> ) : ( diff --git a/editor/app/channels/[slug]/waybackPagesActions.ts b/editor/app/channels/[slug]/waybackPagesActions.ts @@ -11,26 +11,57 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; import { importPage, queueImportPage, type ImportPageResult } from "yt-dlp-transcript-common/controller/importPage"; import { queueReextractPages } from "yt-dlp-transcript-common/controller/reextractPages"; +import { archiveLookup, type ArchiveLookup } from "yt-dlp-transcript-common/lib/archives/index"; +import { isArchiveSourceId, type ArchiveSourceId } from "yt-dlp-transcript-common/lib/archives/types"; +// Release 37 lane F: `source` ("archive.today") with a page's own URL and +// `at`; a copy's URL (Wayback or archive.today) names its source itself. export async function importPageAction( slug: string, url: string, at?: string, requestedBy?: string, + source?: string, ): Promise<StreamActionResult> { return queueImportPage({ paths: getPaths(), slug, url: url.trim(), ...(at?.trim() ? { at: at.trim() } : {}), + ...(source?.trim() ? { source: source.trim() } : {}), ...(requestedBy ? { requestedBy } : {}), onDone: () => safeRevalidate([`/channels/${slug}`]), }); } // What an import WOULD fetch, answered now (no job, no request). -export async function importPageDryRunAction(slug: string, url: string, at?: string): Promise<ImportPageResult> { - return importPage({ paths: getPaths(), slug, url: url.trim(), ...(at?.trim() ? { at: at.trim() } : {}), dryRun: true }); +export async function importPageDryRunAction(slug: string, url: string, at?: string, source?: string): Promise<ImportPageResult> { + return importPage({ + paths: getPaths(), + slug, + url: url.trim(), + ...(at?.trim() ? { at: at.trim() } : {}), + ...(source?.trim() ? { source: source.trim() } : {}), + dryRun: true, + }); +} + +// THE COPIES OF A PAGE across archive sources (release 37 lane F, +// `archive-lookup`): read only, each source through its own paced client; a +// source that refuses (excluded, a check, a 429) is its own entry's sentence. +export async function archiveLookupAction( + url: string, + source?: string, + limit?: number, +): Promise<{ ok: true; lookup: ArchiveLookup } | { ok: false; error: string }> { + const given = url.trim(); + if (!/^https?:\/\/[^\s]+$/.test(given)) return { ok: false, error: "give a page's own http(s) URL" }; + if (source && !isArchiveSourceId(source)) return { ok: false, error: `"source" must be "wayback" or "archive.today", not "${source}"` }; + const lookup = await archiveLookup(given, { + ...(source ? { source: source as ArchiveSourceId } : {}), + limit: Math.min(Math.max(1, limit ?? 50), 500), + }); + return { ok: true, lookup }; } export async function reextractPagesAction(slug: string, dryRun?: boolean): Promise<StreamActionResult> { diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -400,7 +400,7 @@ export function ChannelForm({ <option value="twitter">X / Twitter (posts)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> - <option value="webpage">Wayback pages (captures of pages)</option> + <option value="webpage">Archived pages (Wayback Machine, archive.today)</option> </SeededSelect> <span className="text-xs text-muted-foreground"> Used as the default job queue, so all channels on the same @@ -523,7 +523,7 @@ export function ChannelForm({ <option value="twitter">X / Twitter (posts)</option> <option value="bluesky">Bluesky (posts)</option> <option value="xenforo">Forum thread — XenForo (posts)</option> - <option value="webpage">Wayback pages (captures of pages)</option> + <option value="webpage">Archived pages (Wayback Machine, archive.today)</option> </ControlledSelect> <span className="text-xs text-muted-foreground"> Used as the default job queue, so all channels on the same diff --git a/editor/app/channels/components/WaybackTargetsField.tsx b/editor/app/channels/components/WaybackTargetsField.tsx @@ -11,7 +11,25 @@ import { type WaybackTarget, } from "yt-dlp-transcript-common/lib/waybackPages/config"; -type Row = { url: string; match: string; from: string; to: string }; +// `sources` (release 37 lane F): "wayback", "archive.today" or "both" — +// where the target's copies are looked for. +type Row = { url: string; match: string; from: string; to: string; sources?: string }; + +const SOURCE_LABELS: Record<string, string> = { + wayback: "Wayback Machine", + "archive.today": "archive.today", + both: "Both", +}; + +const sourcesOf = (t: WaybackTarget): string => { + const s = t.sources ?? []; + if (s.includes("wayback") && s.includes("archive.today")) return "both"; + if (s.includes("archive.today")) return "archive.today"; + return "wayback"; +}; + +const sourcesList = (v: string | undefined): string[] | undefined => + v === "both" ? ["wayback", "archive.today"] : v === "archive.today" ? ["archive.today"] : undefined; const LABELS: Record<string, string> = { exact: "Exact page", @@ -20,7 +38,7 @@ const LABELS: Record<string, string> = { domain: "Domain (and subdomains)", }; -const toRow = (t: WaybackTarget): Row => ({ url: t.url, match: t.match, from: t.from ?? "", to: t.to ?? "" }); +const toRow = (t: WaybackTarget): Row => ({ url: t.url, match: t.match, from: t.from ?? "", to: t.to ?? "", sources: sourcesOf(t) }); export function WaybackTargetsField({ initial, @@ -51,6 +69,7 @@ export function WaybackTargetsField({ match: r.match, ...(r.from.trim() ? { from: r.from.trim() } : {}), ...(r.to.trim() ? { to: r.to.trim() } : {}), + ...(sourcesList(r.sources) ? { sources: sourcesList(r.sources) } : {}), })), ); const input = "rounded border border-border bg-card px-2 py-1 text-sm"; @@ -93,6 +112,18 @@ export function WaybackTargetsField({ placeholder="to (2016)" className={`${input} w-28 font-mono`} /> + <select + value={r.sources ?? "wayback"} + onChange={(e) => edit(i, { sources: e.target.value })} + aria-label={`target ${i + 1} sources`} + className={input} + > + {Object.entries(SOURCE_LABELS).map(([v, label]) => ( + <option key={v} value={v}> + {label} + </option> + ))} + </select> <button type="button" onClick={() => { @@ -119,7 +150,7 @@ export function WaybackTargetsField({ </button> </div> <span className="text-xs text-muted-foreground"> - Which captures are in scope. Dates are Wayback timestamps or their start (2014, 201403, 20140305). + Which captures are in scope, and on which archive. Dates are capture timestamps or their start (2014, 201403, 20140305). </span> </fieldset> ); diff --git a/editor/app/settings/archiveSessionActions.ts b/editor/app/settings/archiveSessionActions.ts @@ -0,0 +1,57 @@ +"use server"; + +// THE ARCHIVE SESSION (release 37 lane F, common/lib/archives/archiveTodaySession.ts): +// archive.today's check, passed once by the operator in a HEADED window on the +// archive profile, so the headless reads behind a check go through. Only this +// explicit action opens a window; an import that meets a check it cannot pass +// stops and says to come here. Nothing is ever solved by code. +// +// And settings.archives (host, pace, the browser fallback), saved as a patch. + +import { revalidatePath } from "next/cache"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { + connectArchiveSession, + readArchiveSessionStatus, + type ArchiveSessionRecord, + type ArchiveSessionStatus, +} from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; +import { isArchiveTodayUrl } from "yt-dlp-transcript-common/lib/archives/mementos"; +import { sanitizeArchives, type ArchivesSettings } from "yt-dlp-transcript-common/lib/archives/settings"; +import { saveSettings } from "./saveSettings"; + +export async function archiveSessionStatusAction(): Promise<ArchiveSessionStatus> { + return readArchiveSessionStatus(getPaths()); +} + +// Open the window at `url` (an archive.today copy the check stood in front +// of), else at archive.today's front page on the canonical host. +export async function connectArchiveSessionAction( + url?: string, +): Promise<{ ok: true; record: ArchiveSessionRecord } | { ok: false; error: string }> { + const host = getSettings().archives.archiveTodayHost; + const at = url?.trim() && isArchiveTodayUrl(url.trim()) ? url.trim() : `https://${host}/`; + try { + const record = await connectArchiveSession(getPaths(), at, { + onLog: (line) => console.log(`[archive-session] ${line}`), + }); + revalidatePath("/settings"); + return { ok: true, record }; + } catch (e) { + return { ok: false, error: (e as Error).message }; + } +} + +export async function saveArchivesSettingsAction( + patch: Partial<ArchivesSettings>, +): Promise<{ ok: true; archives: ArchivesSettings } | { ok: false; error: string }> { + try { + const archives = sanitizeArchives({ ...getSettings().archives, ...patch }); + await saveSettings({ archives }); + revalidatePath("/settings"); + return { ok: true, archives }; + } catch (e) { + return { ok: false, error: (e as Error).message }; + } +} diff --git a/editor/app/settings/components/ArchiveSessionSection.tsx b/editor/app/settings/components/ArchiveSessionSection.tsx @@ -0,0 +1,138 @@ +"use client"; + +// ARCHIVE SOURCES on the settings page (release 37 lane F): archive.today's +// host, pace and browser fallback (settings.archives), and the archive +// session — Connect opens a window on the editor's machine for the operator to +// pass archive.today's check once; the headless reads reuse it. The same +// Connect control sits on an Archived pages channel's panel. + +import { useState, useTransition } from "react"; +import { ARCHIVE_TODAY_HOSTS } from "yt-dlp-transcript-common/lib/archives/mementos"; +import type { ArchivesSettings } from "yt-dlp-transcript-common/lib/archives/settings"; +import type { ArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; +import { connectArchiveSessionAction, saveArchivesSettingsAction } from "../archiveSessionActions"; + +function sessionLine(status: ArchiveSessionStatus): string { + const last = status.lastConnect; + if (!last) return status.hasProfile ? "Profile kept; never connected by hand" : "Not connected"; + const when = last.connectedAt.slice(0, 16).replace("T", " "); + return `Connected ${when} UTC — ${last.cleared ? "the page showed" : "a check was still showing"}, ${last.cookies} cookie${last.cookies === 1 ? "" : "s"}`; +} + +// The status line and Connect, alone (the channel panel's). +export function ConnectArchiveSession({ initial, url }: { initial: ArchiveSessionStatus; url?: string }) { + const [status, setStatus] = useState(initial); + const [error, setError] = useState<string | null>(null); + const [pending, start] = useTransition(); + return ( + <div className="flex flex-wrap items-center gap-2 text-sm"> + <span role="status" aria-label="archive session" className="text-muted-foreground"> + archive.today session: {sessionLine(status)} + </span> + <button + type="button" + disabled={pending} + onClick={() => + start(async () => { + setError(null); + const r = await connectArchiveSessionAction(url); + if (r.ok) setStatus({ ...status, hasProfile: true, lastConnect: r.record }); + else setError(r.error); + }) + } + className="rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50" + > + {pending ? "Window open… close it when done" : "Connect archive session"} + </button> + {error && ( + <span role="alert" aria-label="archive session error" className="text-xs text-destructive"> + {error} + </span> + )} + </div> + ); +} + +export function ArchiveSourcesSection({ initial, session }: { initial: ArchivesSettings; session: ArchiveSessionStatus }) { + const [form, setForm] = useState(initial); + const [note, setNote] = useState<string | null>(null); + const [pending, start] = useTransition(); + const input = "rounded border border-border bg-card px-2 py-1 text-sm"; + return ( + <div aria-label="archive sources" className="flex flex-col gap-3"> + <h2 className="text-lg font-semibold">Archive sources</h2> + <ConnectArchiveSession initial={session} /> + <div className="flex flex-wrap items-end gap-3 text-sm"> + <label className="flex flex-col gap-1"> + <span>archive.today host</span> + <select + aria-label="archive.today host" + value={form.archiveTodayHost} + onChange={(e) => setForm({ ...form, archiveTodayHost: e.target.value })} + className={input} + > + {ARCHIVE_TODAY_HOSTS.map((h) => ( + <option key={h} value={h}> + {h} + </option> + ))} + </select> + </label> + <label className="flex flex-col gap-1"> + <span>Gap between requests (s)</span> + <input + type="number" + min={4} + max={120} + aria-label="archive.today gap seconds" + value={form.archiveTodayGapSeconds} + onChange={(e) => setForm({ ...form, archiveTodayGapSeconds: Number(e.target.value) })} + className={`${input} w-24`} + /> + </label> + <label className="flex flex-col gap-1"> + <span>Rest after a 429 (min)</span> + <input + type="number" + min={5} + max={1440} + aria-label="archive.today cooldown minutes" + value={form.archiveTodayCooldownMinutes} + onChange={(e) => setForm({ ...form, archiveTodayCooldownMinutes: Number(e.target.value) })} + className={`${input} w-24`} + /> + </label> + <label className="flex items-center gap-2"> + <input + type="checkbox" + aria-label="read a check through the browser" + checked={form.archiveTodayBrowser} + onChange={(e) => setForm({ ...form, archiveTodayBrowser: e.target.checked })} + /> + Read past a check with the session&apos;s browser (never solves one) + </label> + <button + type="button" + disabled={pending} + onClick={() => + start(async () => { + const r = await saveArchivesSettingsAction(form); + if (r.ok) { + setForm(r.archives); + setNote("Saved."); + } else setNote(r.error); + }) + } + className="rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50" + > + Save archive sources + </button> + {note && ( + <span role="status" aria-label="archive sources saved" className="text-xs text-muted-foreground"> + {note} + </span> + )} + </div> + </div> + ); +} diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx @@ -8,6 +8,8 @@ import { xCookieSourceView } from "yt-dlp-transcript-common/social/xCookieSource import { xPostsVisibility } from "yt-dlp-transcript-common/lib/postsVisibility"; import { SettingsForm } from "./components/SettingsForm"; import { XSessionSection } from "./components/XSessionSection"; +import { ArchiveSourcesSection } from "./components/ArchiveSessionSection"; +import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; export const dynamic = "force-dynamic"; @@ -101,6 +103,11 @@ export default async function SettingsPage() { /> </section> + {/* Release 37 lane F: archive.today's host, pace and session. */} + <section className="flex flex-col gap-3 border-t border-border pt-6"> + <ArchiveSourcesSection initial={settings.archives} session={await readArchiveSessionStatus(paths)} /> + </section> + <section className="flex flex-col gap-3 border-t border-border pt-6"> <details> <summary className="cursor-pointer text-lg font-semibold"> diff --git a/editor/e2e/archive-today-pages.spec.ts b/editor/e2e/archive-today-pages.spec.ts @@ -0,0 +1,175 @@ +// archive.today copies as page records (release 37 lane F), end to end over the +// fake archive.today (common/testing/web/fakeArchiveToday.mjs) and the fake +// Wayback Machine, named to the test server through E2E_ARCHIVE_TODAY_ORIGIN_FILE +// and E2E_WAYBACK_ORIGIN_FILE (e2e/servers.ts). Neither real service is ever +// contacted, and no archive-session browser opens under the fake. +// +// The New channel form makes an "Archived pages" channel of an archive.today +// copy's URL (its target on archive.today); Import a capture takes a copy's URL +// and, with a date, the copy nearest it on archive.today; the copy is stored +// as served with its source; Look up a page lists each source's copies — the +// Wayback Machine's exclusion said in its words; a copy behind a check is +// refused with its code, and Connect archive session is offered (never +// clicked here: it opens a window). + +import { test, expect, type APIRequestContext } from "@playwright/test"; +import { readFile, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { + startFakeArchiveToday, + AT_ARTICLE_ID, + AT_ARTICLE_LATER_ID, + AT_ARTICLE_LATER_TS, + AT_ARTICLE_TS, + AT_ARTICLE_URL, + AT_CHECKED_ID, +} from "yt-dlp-transcript-common/testing/web/fakeArchiveToday.mjs"; +import { startFakeWayback } from "yt-dlp-transcript-common/testing/web/fakeWayback.mjs"; +import { pageRecordId } from "yt-dlp-transcript-common/lib/waybackPages/types"; +import { baseUrl } from "./baseUrl"; +import { generateReport, pathExists, readJson, resetData, resolvePath, testPaths, writeSettings } from "./helpers"; +import { archiveTodayOriginFile, waybackOriginFile } from "./servers"; + +const AUTH = { authorization: "Bearer test-worker-token" }; +const SLUG = "deleted-journal"; + +async function waitForJob(request: APIRequestContext, jobId: string): Promise<{ status: string; tail: string[] }> { + let last = { status: "", tail: [] as string[] }; + await expect + .poll( + async () => { + const res = await request.get(`${baseUrl}/api/ops/job/${jobId}?tail=40`, { headers: AUTH }); + const body = (await res.json()) as { job: { status: string }; tail?: string[] }; + last = { status: body.job.status, tail: body.tail ?? [] }; + return last.status; + }, + { timeout: 90_000, intervals: [1_000] }, + ) + .toMatch(/^(done|failed|cancelled)$/); + return last; +} + +test("an Archived pages channel from an archive.today copy, its copies imported, looked up and refused at a check", async ({ page, request }) => { + test.setTimeout(240_000); + await resetData("empty"); + // archive.today's least gap (4 s): the spec's few requests stay paced. + await writeSettings({ minFreeDiskGB: 0, archives: { archiveTodayGapSeconds: 4, archiveTodayBrowser: true } }); + await generateReport(page, "new"); + + await page.goto("/channels/new"); + await page.locator('input[name="url"]').fill(`https://archive.ph/newest/${AT_ARTICLE_URL}`); + // Offline: an archive.today copy of a page is an Archived pages channel. + await expect(page.locator('select[name="platform"]')).toHaveValue("webpage"); + await expect(page.locator('select[name="platform"] option[value="webpage"]')).toHaveText(/Archived pages/); + await expect(page.getByLabel("target 1 URL")).toHaveValue(AT_ARTICLE_URL); + await expect(page.getByLabel("target 1 match")).toHaveValue("exact"); + await expect(page.getByLabel("target 1 sources")).toHaveValue("archive.today"); + // Widen it: the whole journal, on both archives. + await page.getByLabel("target 1 URL").fill("journal.example/"); + await page.getByLabel("target 1 match").selectOption("prefix"); + await page.getByLabel("target 1 sources").selectOption("both"); + await page.locator('input[name="name"]').fill("Deleted journal"); + await page.locator('input[name="slug"]').fill(SLUG); + await page.getByRole("button", { name: /create|add channel|save/i }).first().click(); + + const configFile = `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`; + await expect + .poll(async () => ((await pathExists(configFile)) ? await readJson(configFile) : null), { timeout: 15_000 }) + .toMatchObject({ + sourceKind: "social", + platform: "webpage", + wayback: { targets: [{ url: "journal.example/", match: "prefix", sources: ["wayback", "archive.today"] }] }, + }); + + const at = await startFakeArchiveToday({ challenge: [AT_CHECKED_ID] }); + const wb = await startFakeWayback({ excluded: [AT_ARTICLE_URL] }); + const atFile = archiveTodayOriginFile(resolvePath(testPaths().transcriptsDir)); + const wbFile = waybackOriginFile(resolvePath(testPaths().transcriptsDir)); + await writeFile(atFile, at.base); + await writeFile(wbFile, wb.base); + try { + await page.goto(`/channels/${SLUG}`); + const pages = page.getByRole("region", { name: "Wayback pages" }); + await expect(pages.getByLabel("pages held")).toHaveText("0 records from 0 captures"); + await expect(page.getByRole("button", { name: "Connect archive session" })).toBeVisible(); + + // One copy by its short id (on another of archive.today's names). + await page.getByLabel("capture URL").fill(`https://archive.is/${AT_ARTICLE_ID}`); + await expect(page.getByLabel("capture source")).toBeDisabled(); + await page.getByRole("button", { name: "Import capture" }).click(); + await expect(page.getByRole("log", { name: `Import a capture into ${SLUG} output` })).toContainText('"ok":true', { timeout: 60_000 }); + const id = pageRecordId(AT_ARTICLE_TS, AT_ARTICLE_URL); + const channelRoot = resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`); + const capture = JSON.parse(await readFile(path.join(channelRoot, "pages", id, "capture.json"), "utf8")) as Record<string, unknown>; + expect(capture).toMatchObject({ + originalUrl: AT_ARTICLE_URL, + captureTs: AT_ARTICLE_TS, + source: "archive.today", + mementoUrl: `https://archive.ph/${AT_ARTICLE_ID}`, + extractor: "generic", + }); + expect(at.requests.map((r) => r.path)).toEqual([`/${AT_ARTICLE_ID}`]); + + await page.reload(); + await expect(pages.getByLabel("pages held")).toHaveText("1 record from 1 capture"); + const row = page.locator(`[data-page-record="${id}"]`); + await expect(row.getByRole("link", { name: "Notes I Later Deleted" })).toHaveAttribute("href", AT_ARTICLE_URL); + await expect(row.getByRole("link", { name: "2019-05-12" })).toHaveAttribute("href", `https://archive.ph/${AT_ARTICLE_ID}`); + await expect(row).toContainText("archive.today"); + + // The copy nearest a date, on archive.today (one timemap request). + await page.getByLabel("capture URL").fill(AT_ARTICLE_URL); + await page.getByLabel("capture date").fill("2019-12-01"); + await page.getByLabel("capture source").selectOption("archive.today"); + await page.getByRole("button", { name: "Import capture" }).click(); + await expect(page.getByRole("log", { name: `Import a capture into ${SLUG} output` })).toContainText(`"captureTs":"${AT_ARTICLE_LATER_TS}"`, { + timeout: 60_000, + }); + expect(at.requests.map((r) => r.path).slice(1)).toEqual([`/timemap/${AT_ARTICLE_URL}`, `/${AT_ARTICLE_LATER_ID}`]); + await page.reload(); + await expect(pages.getByLabel("pages held")).toHaveText("2 records from 2 captures"); + + // Look up a page across sources: the Wayback Machine excludes it (its + // words), archive.today lists its two copies — each importable. + await page.getByLabel("page URL").fill(AT_ARTICLE_URL); + await page.getByRole("button", { name: "Look up" }).click(); + await expect(page.getByLabel("Wayback Machine copies")).toContainText("excluded from the Wayback Machine (cause unknown)", { timeout: 60_000 }); + await expect(page.getByLabel("archive.today copies")).toHaveText("archive.today: 2 copies"); + await expect(page.getByRole("button", { name: `import archive.today ${AT_ARTICLE_TS}` })).toBeVisible(); + + // The ops door: the same lookup; a copy behind a check refused with its code. + const look = await request.post(`${baseUrl}/api/ops/archive-lookup`, { headers: AUTH, data: { url: AT_ARTICLE_URL } }); + const lookBody = (await look.json()) as { ok: boolean; found: number; sources: { source: string; ok: boolean; refusal?: string }[] }; + expect(lookBody).toMatchObject({ ok: true, found: 2 }); + expect(lookBody.sources.map((s) => [s.source, s.ok, s.refusal ?? null])).toEqual([ + ["wayback", false, "excluded"], + ["archive.today", true, null], + ]); + const wl = await request.post(`${baseUrl}/api/ops/wayback-lookup`, { headers: AUTH, data: { url: AT_ARTICLE_URL } }); + expect(wl.status()).toBe(403); + expect(await wl.json()).toMatchObject({ ok: false, refusal: "excluded" }); + + const dry = await request.post(`${baseUrl}/api/ops/import-page`, { + headers: AUTH, + data: { slug: SLUG, url: `https://archive.ph/${AT_ARTICLE_ID}`, dryRun: true }, + }); + expect(await dry.json()).toMatchObject({ ok: true, dryRun: true, already: true, source: "archive.today" }); + + const checked = await request.post(`${baseUrl}/api/ops/import-page`, { headers: AUTH, data: { slug: SLUG, url: `https://archive.ph/${AT_CHECKED_ID}` } }); + const checkedBody = (await checked.json()) as { jobId?: string; error?: string }; + expect(checked.status(), checkedBody.error).toBe(200); + const job = await waitForJob(request, checkedBody.jobId!); + expect(job.status).toBe("failed"); + const tail = job.tail.join("\n"); + expect(tail).toContain('"refusal":"challenge"'); + expect(tail).toContain("Connect archive session"); + // Nothing of the checked copy was stored. + await page.reload(); + await expect(pages.getByLabel("pages held")).toHaveText("2 records from 2 captures"); + } finally { + await rm(atFile, { force: true }); + await rm(wbFile, { force: true }); + await at.close(); + await wb.close(); + } +}); diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -57,6 +57,11 @@ export function waybackOriginFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-wayback-origin"); } +/** The file naming a slot's fake archive.today (common/lib/archives/archiveTodayClient.ts; archive-today-pages.spec). */ +export function archiveTodayOriginFile(transcriptsDir: string): string { + return join(transcriptsDir, ".fake-archive-today-origin"); +} + /** The file naming a slot's stub umtool (common/lib/umtoolUrl.ts; find-clips.spec). */ export function umtoolOriginFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-umtool-origin"); @@ -218,6 +223,9 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env) // The same for the fake Wayback Machine wayback-pages.spec starts // (lib/waybackClient.ts: the process's client sends web.archive.org there). editorEnv.E2E_WAYBACK_ORIGIN_FILE = waybackOriginFile(paths.transcriptsDir); + // The same for the fake archive.today archive-today-pages.spec starts + // (lib/archives/archiveTodayClient.ts; no archive session browser under it). + editorEnv.E2E_ARCHIVE_TODAY_ORIGIN_FILE = archiveTodayOriginFile(paths.transcriptsDir); // The same for the stub umtool find-clips.spec starts (lib/umtoolUrl.ts). editorEnv.E2E_UMTOOL_ORIGIN_FILE = umtoolOriginFile(paths.transcriptsDir); // The browser lookup's recorded page reads (browser-lookup.spec): set on diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -39,6 +39,9 @@ import { currentSlot } from "./e2e/testPaths"; // into, where the editor's Wayback client then sends // every web.archive.org request // (common/lib/waybackClient.ts; wayback-pages.spec) +// E2E_ARCHIVE_TODAY_ORIGIN_FILE the same for the fake archive.today +// (common/lib/archives/archiveTodayClient.ts; +// archive-today-pages.spec); no browser opens under it // E2E_UMTOOL_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec // writes its stub umtool's loopback origin into, // which Find clips then posts to diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -11138,3 +11138,61 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri brace-matched string-aware and `JSON.parse`d, or — when assigned as a JS string — unescaped (`\xNN`, `\uNNNN`) then parsed; renderers found by key anywhere (`channelAboutFullMetadataRenderer` | `aboutChannelViewModel`, `c4TabbedHeaderRenderer` | `pageHeaderViewModel`, `channelMetadataRenderer`). + +## Release 37 lane F: archive sources — archive.today like Wayback (verified 2026-10-20, branch `r37/archive-sources`) + +- **The layer** is `common/lib/archives/`: `types.ts` (`ArchiveSource` = `{id, label, queueKey, matchesUrl, + parseMementoUrl, listCaptures, closestCapture, getCapture}`, `ArchiveRefusal` with codes `excluded | challenge | + rate-limited | not-archived | mimetype | too-large | offsite-redirect | redirect-loop | unreadable`), `mementos.ts` + (client-safe: `parseArchiveTodayUrl`, `mementoSourceOf`, `pageArchiveLink`, `ARCHIVE_TODAY_HOSTS`), `ask.ts` + (client-safe `parseArchiveCaptureAsk(url, at?, source?)`), `wayback.ts` (the adapter over `WaybackClient`, no + behaviour change), `archiveToday.ts` (pure: timemap, copy facts, check page, unwrap, media map), + `archiveTodayClient.ts`, `archiveTodaySession.ts`, `settings.ts`, and `index.ts` (server: `ARCHIVE_SOURCES` = + [wayback, archive.today], `sourceForUrl`, `archiveSource(id)`, `archiveRefusalOf(e)`, `archiveLookup`, the + process `archiveTodayClient`). Callers ask the registry, never a source by name. +- **archive.today** is one service under seven names (archive.ph .today .is .li .vn .fo .md); every request goes to + `settings.archives.archiveTodayHost` (default archive.ph; anything else → archive.ph). Copies: `/<id>` (4–6 + alphanumerics, names no page or time), `/<ts>/<page>` (14 digits or `YYYY.MM.DD-hhmmss`), `/newest|oldest/<page>` + (both redirect to `/<id>`); `/timemap/<page>` is link format (404 = none); `/o/<id>/<url>` is a link OUT of a copy. + A copy's time and page come from `Memento-Datetime` + `Link rel="original"`, else its header bar (`#HEADER`'s + URL box and `<time datetime>`), else the URL. Shapes as known 2026-10-20 — no live copy was read (synthetic + fixtures only): the stored body is the copy AS SERVED, so a better unwrap is a `reextract-pages`. +- **The client** (`ArchiveTodayClient`): one chain, gap `archiveTodayGapSeconds` (8, clamp 4–120) + up to 25 % + jitter from the END of one request; manual redirects inside archive.today only (≤ 5); 502/503/504 retried (3); + **a 429 is never retried**: `ArchiveRefusal("rate-limited")` and nothing is sent for + `archiveTodayCooldownMinutes` (30) or Retry-After; **a check page** (`isArchiveTodayChallenge`: recaptcha / + hcaptcha / cloudflare markers with no `#HEADER`+`#CONTENT` frame, at any status) is `ArchiveRefusal("challenge")`, + after ONE read through `openBrowser` (the headless archive profile, `archiveTodaySession.ts`, which waits a check + out and never clicks) when `archiveTodayBrowser` (true) and no test origin. Queue `platform:archive.today`. + `E2E_ARCHIVE_TODAY_ORIGIN_FILE` sends every archive.today name to the fake and turns the browser off. +- **Unwrap** (`unwrapArchiveTodayHtml`): `#CONTENT`'s inner HTML (scripts dropped) as `<body>`, the copy's `<title>` + and its page `<meta>`s (none naming an archive host, no http-equiv) as `<head>`; `/o/<id>/<url>` and `old-href` → + the href; `old-src` → the img src, the cached copy kept in `images` (original → cached); a body with no frame + passes through, hrefs restored. Lane C's tweet and Tumblr fixtures wrapped like archive.today (the fake's + `wrapLikeArchiveToday`) give deep-equal drafts. `mapArchiveTodayMedia`: a record's image is the cached copy, a + Wayback `im_` form of an uncached original becomes the original. +- **Records and storage (additive):** `PagePostInfo.source?` ("archive.today"; absent = Wayback, "wayback" is + normalised away by `parsePagePostInfo`) and `archiveUrl?` (the copy's URL); for such a record `waybackUrl` and + `rawUrl` ARE that copy's URL (required fields). Cite with `pageArchiveLink(page)`. `StoredCapture.source?` / + `mementoUrl?`; `findStoredCaptureByMemento` answers "already stored" for a short id before any request (host- + blind). The record id and dir are `pageRecordId(captureTs, originalUrl)` as for Wayback — a Wayback capture and + an archive.today copy of the same page at the same second share one (a stored one is not stored again). +- **import-page** (`controller/importPage.ts`): `planImportPage` takes `source`; `importPageQueueOf(ask)` is the + job's queue; `extractInputOfCapture(capture, body)` (shared with reextract's staleness check) unwraps an + archive.today copy; `ImportPageResult` gains `source`, `mementoUrl`, `refusal`. A short id's video/X checks run + after the read. `startImportPageJob` takes `source`. +- **Excluded:** `WaybackExcludedError` (an `ArchiveOrgRequestError`, status 403, so older catches still read it) from + `captures` / `closestCapture`; `WaybackCaptureRefusal("excluded")` from `getCapture`; `isWaybackExcluded(e)`; + `waybackExcludedOf(e, url)` for a caller building its own CDX request (lane B's `cdxPage`); + `WAYBACK_EXCLUDED_PHRASE` = "excluded from the Wayback Machine (cause unknown)". `wayback-lookup` answers 403 + `{refusal: "excluded"}`. The fake Wayback's `excluded: [originals]` answers 403 for CDX and captures. +- **Config:** a target's `sources?: ("wayback" | "archive.today")[]` (`["wayback"]` alone is not written; + `targetSources(t)`). `waybackTargetFromUrl` reads `archive.ph/newest|oldest|<ts>/<page>` as that page, exact, on + archive.today; `isWaybackPagesUrl` is true for an archive.today copy that is not of a video. The form's platform + option reads "Archived pages (Wayback Machine, archive.today)"; the panel region's label stays "Wayback pages". +- **Settings:** `settings.archives` = `{archiveTodayHost, archiveTodayGapSeconds, archiveTodayCooldownMinutes, + archiveTodayBrowser}` (41 settings fields). The session: `transcripts/.archive-session/archive.today/{profile/, + session.json}`; Connect only on the operator's click (channel panel, Settings → Archive sources). +- **Ops / CLI:** `archive-lookup {url, source?, limit?}` (read only) → `{url, found, sources: [{source, label, ok, + captures, refusal?, error?}]}`; `import-page` takes `source`; `archilyzer archive lookup <url>` and `wayback pages + import --source`. diff --git a/plans/release-37/archive-sources.md b/plans/release-37/archive-sources.md @@ -0,0 +1,94 @@ +# Release 37 lane F — `r37/archive-sources`: archive.today, and any archive service, like Wayback (as shipped) + +The plan of record is [`wayback-pages.md`](wayback-pages.md) ("Added 2026-10-20 — lane F"). Operator, 2026-10-20: +"include archive.today support like wayback, which we'll do on any other archive service we need to read". This lane +puts an **archive-source layer** under the page import: the Wayback Machine becomes one source (an adapter over its +existing client, no behaviour change) and archive.today the second — its timemap, its copies in every URL form, its +rewritten snapshot unwrapped so the same extractors read it, its own paced client, and a headless-browser session for +its check, never CAPTCHA solving. A page record says which source it came from (`page.source`, `page.archiveUrl`), +`import-page` and a new read-only `archive-lookup` work across sources, the channel kind reads "Archived pages" in the +UI, and a Wayback CDX 403 is a typed `excluded` refusal. Rulings followed: no model anywhere; every operation has a +button (Import a capture with a source, Look up a page, Connect archive session, Settings → Archive sources); polite +(one stream per source, archive.today 8 s apart and stopped by a 429); synthetic fixtures only; no real network in any +test; commits end with the one Co-Authored-By trailer. + +## Shared-shape changes (additive) + +- `PagePostInfo` (`lib/waybackPages/types.ts`): `source?: string` (absent = the Wayback Machine) and `archiveUrl?: + string` (the copy's URL on that source). For such a record `waybackUrl` and `rawUrl` hold the copy's URL too (they + are required): cite with `pageArchiveLink(page)` (`lib/archives/mementos.ts`), which names the source. + `parsePagePostInfo` keeps both (a stored `"wayback"` is normalised away). +- `StoredCapture` (`store-server.ts`): `source?`, `mementoUrl?`; `findStoredCaptureByMemento`. +- `WaybackTarget` (`config.ts`): `sources?: ("wayback" | "archive.today")[]` (`targetSources(t)`; `["wayback"]` + alone is not written). +- `WaybackCaptureRefusalCode` gains `"excluded"`; `waybackCdxUrl` / `WaybackClient.captures` take `from`/`to`. +- `DraftToPostContext.source?`, `ImportPageResult.{source, mementoUrl, refusal}`, `planImportPage`/ + `queueImportPage`/`startImportPageJob`/`importPage` take `source`. +- `settings.archives` (a 41st settings field). + +## What + +1. **The layer** `common/lib/archives/`: `ArchiveSource` (`id, label, queueKey, matchesUrl, parseMementoUrl, + listCaptures, closestCapture, getCapture`), `ArchiveRefusal` (typed codes), the registry `ARCHIVE_SOURCES` + + `sourceForUrl` + `archiveSource(id)` + `archiveRefusalOf(e)` + `archiveLookup` (`index.ts`), the Wayback adapter + (`wayback.ts`), client-safe URL reading (`mementos.ts`, `ask.ts`). +2. **archive.today**: `archiveToday.ts` (pure: timemap link format, copy facts from Memento headers else the header + bar, the check page, the unwrap, the media map) and `archiveTodayClient.ts` (one chain; gap 8 s + up to 25 % + jitter; manual redirects inside archive.today; 502/503/504 retried; a 429 stops with a sentence and rests the client + 30 min; a check is refused, after one read through the headless archive profile when allowed). One canonical host + from settings for all seven names. `archiveTodaySession.ts`: the profile, `connectArchiveSession` (headed, only on + the operator's click), `archiveSessionBrowser` (headless; waits a check out, never clicks). +3. **Import**: `import-page` takes an archive.today copy (`/<id>`, `/<ts>/<page>`, `/newest|oldest/<page>`) or + `{url, at, source: "archive.today"}` (one timemap request), on `platform:archive.today`; the copy is stored AS + SERVED with `source` + `mementoUrl` in `capture.json` and unwrapped each time it is read + (`extractInputOfCapture`, shared with `reextract-pages`' staleness check); a short id is checked against the stored + copies before any request, and for video / X after the read. The New channel form's kind reads **Archived pages** + and reads an archive.today copy's URL as a target on archive.today; each target row has a sources choice. +4. **Excluded**: `WaybackExcludedError` (an `ArchiveOrgRequestError` 403) from `captures`/`closestCapture`, + `WaybackCaptureRefusal("excluded")` from `getCapture`, `isWaybackExcluded`, `waybackExcludedOf` — surfaced by + `wayback-lookup` (403, `refusal: "excluded"`), `import-page` and `archive-lookup` as "excluded from the Wayback + Machine (cause unknown)". +5. **Ops / CLI / UI**: `archive-lookup {url, source?, limit?}`; `import-page` `source`; `archilyzer archive lookup`, + `wayback pages import --source`; the channel page's Import a capture (a source select), **Look up a page** (each + source's copies, an Import per copy), **Connect archive session**; Settings → **Archive sources** (host, gap, + cool-down, the browser fallback, the session line and Connect). +6. **The fake**: `common/testing/web/fakeArchiveToday.mjs` (timemaps, copies wrapped as archive.today wraps them — + `wrapLikeArchiveToday` — its redirects, a CAPTCHA page at any status, a plain 429; lane C's fixtures as copies via + `fixtureCopy`), and `fakeWayback.mjs`'s `excluded` option (its own block). + +## Adding an archive source + +One module and one registry entry; nothing else names a source. + +1. `common/lib/archives/<source>.ts` (pure reading: its listing format, a copy's facts, an unwrap if its copies are + rewritten) and `<source>Client.ts` (its paced client: one chain, its own gap, a 429 that stops, `E2E_<SOURCE>_ + ORIGIN_FILE` for the e2e fake). Implement `ArchiveSource` (`types.ts`): `matchesUrl`, `parseMementoUrl`, + `listCaptures`, `closestCapture`, `getCapture` — `getCapture` answers the body AS SERVED (what is stored) and + `page`, the copy as the extractors read it; refusals are `ArchiveRefusal` with the existing codes. +2. Add its id to `ARCHIVE_SOURCE_IDS` (`types.ts`), its label to `ARCHIVE_SOURCE_LABELS` (`mementos.ts`), its URL + form to `mementoSourceOf`, its id to `WAYBACK_TARGET_SOURCES` (`waybackPages/config.ts`, a leaf), and its entry to + `ARCHIVE_SOURCES` (`index.ts`). +3. Teach `parseArchiveCaptureAsk` (`ask.ts`) its copy URLs, `importPage` a branch like `importArchiveTodayCopy` (or + generalise that one: it already only uses the `ArchiveSource` surface plus the store), and `extractInputOfCapture` + its unwrap; `importPageQueueOf` its queue. +4. A fake under `common/testing/web/`, unit tests (URL forms, listing parse, unwrap parity on lane C's fixtures, + pacing, its 429 and its check), and its settings in `archives/settings.ts`. + +## Interfaces (for lanes B, D, E after merge) + +- **B (scan/Captures):** `targetSources(target)` to know which sources a target scans; `archiveSource(id).listCaptures(url, + {from, to, limit})` for a source other than Wayback; wrap `cdxPage` errors with `waybackExcludedOf(e, url)` (or check + `isWaybackExcluded`) to show "excluded from the Wayback Machine (cause unknown)"; Import selected passes a row's + `mementoUrl` to `startImportPageJob({slug, url: mementoUrl})` (an archive.today copy URL routes itself). +- **D (cite):** `pageArchiveLink(page)` → `{source, label, url}` for every citation, shot and moment page of a page + record — never `page.waybackUrl` as "Wayback" alone; `archiveSourceLabel(page.source)`. +- **E (live):** `archiveLookup(url, {source?})` for availability across sources; `ARCHIVE_SOURCES` / + `archiveSource("archive.today")` for find-copy; `archiveRefusalOf(e)` to read any source's refusal. + +## Gates + +(filled below with numbers) + +## Rulings followed / decisions + +(filled below)