commit 5ddee2c943da80239b11aa17360814e2b4c7115b
parent 458fbbf518bdae09c1ec17e6e52c33ff58d4934e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 15 Oct 2026 07:15:07 -0400
common, editor: Bluesky captures posts with no login (release 29 E1) — blueskyFetcher.captureByIds: the public AppView's getPosts (25 a request) says which posts are live and where their images are (an absent post is deleted, merged into posts-availability.json as X's capture is), a headless Chromium with a fresh context (no profile, no cookies) opens bsky.app/profile/<handle>/post/<rkey>, waits for postThreadItem-by-<handle> and shoots that element cropped to the post as shot.png, and the images come down beside it as media-<n>; one page at a time, a 3–6 s jittered gap, 429s waited out (Retry-After) then stopped, a timeout per page, cancellable; the AppView, bsky.app and the CDN injectable (blueskyEndpoints.ts; E2E_BLUESKY_ORIGIN_FILE for the e2e suite's fake); unit tests over the fake Bluesky with a stub page and a real headless Chromium; the editor capture-posts spec
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 1125 insertions(+), 7 deletions(-)
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -218,6 +218,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_AUDIO_CHECK_RECOVER_AFTER` | the real count | Likewise, the recovery count. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_BACKOFF_BASE_MS` | `60000` (the real base) | The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse. | common/jobs/platformBackoff.ts |
| `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch. The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts |
+| `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | 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. | common/social/blueskyEndpoints.ts |
| `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts |
| `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs |
| `E2E_FAKE_YTDLP_CHUNK_DELAY_MS` | — | Fake yt-dlp: delay between written chunks. | editor/e2e/fixtures/bin/fake-ytdlp.mjs |
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -215,6 +215,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_AUDIO_CHECK_RECOVER_AFTER", audience: "test", default: "the real count", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery count." },
{ name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." },
{ name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts", doc: "The pause between two clip-window fetches in one batch. The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." },
+ { 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." },
{ name: "E2E_FAKE_YTDLP_CHUNK_DELAY_MS", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: delay between written chunks." },
diff --git a/common/social/blueskyEndpoints.ts b/common/social/blueskyEndpoints.ts
@@ -0,0 +1,58 @@
+// Where Bluesky is: the public AppView (the read API, no login), the web app
+// (bsky.app, the page a post capture screenshots) and the CDN (a post's
+// images). One place, so a test can put all three on a fake.
+//
+// TEST-ONLY: E2E_BLUESKY_ORIGIN_FILE names a file holding ONE loopback origin
+// (`http://127.0.0.1:<port>`). While that file exists, all three hosts are
+// that origin — the editor e2e suite's fake Bluesky
+// (common/testing/social/fakeBluesky.mjs), which a spec starts and names in
+// the file. The file is read per call, so a spec can start its fake after the
+// test server booted. Anything but a loopback origin in it is ignored. Unset
+// everywhere but the editor's e2e server. Unit tests pass endpoints directly.
+
+import { readFileSync } from "node:fs";
+
+export type BlueskyEndpoints = {
+ // The public AppView: com.atproto.identity.resolveHandle,
+ // app.bsky.feed.getPosts, getAuthorFeed, getProfile.
+ appview: string;
+ // The web app: /profile/<handle>/post/<rkey>.
+ web: string;
+ // The image CDN: a post's `embed.images[].fullsize`.
+ cdn: string;
+};
+
+export const BLUESKY_ENDPOINTS: Readonly<BlueskyEndpoints> = Object.freeze({
+ appview: "https://public.api.bsky.app",
+ web: "https://bsky.app",
+ cdn: "https://cdn.bsky.app",
+});
+
+const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/;
+
+export function blueskyEndpoints(
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): BlueskyEndpoints {
+ const file = env.E2E_BLUESKY_ORIGIN_FILE;
+ if (file) {
+ let origin = "";
+ try {
+ origin = readFileSync(file, "utf8").trim().replace(/\/$/, "");
+ } catch {
+ origin = "";
+ }
+ if (LOOPBACK_ORIGIN.test(origin)) return { appview: origin, web: origin, cdn: origin };
+ }
+ return { ...BLUESKY_ENDPOINTS };
+}
+
+// A Bluesky URL (one of the three real hosts) on `endpoints`: the AppView's
+// image URLs name cdn.bsky.app, which a fake must serve. Any other URL is
+// returned as it is.
+export function onBlueskyEndpoints(url: string, endpoints: BlueskyEndpoints): string {
+ for (const key of ["appview", "web", "cdn"] as const) {
+ const real = BLUESKY_ENDPOINTS[key];
+ if (url === real || url.startsWith(`${real}/`)) return endpoints[key] + url.slice(real.length);
+ }
+ return url;
+}
diff --git a/common/social/blueskyFetcher.ts b/common/social/blueskyFetcher.ts
@@ -30,8 +30,11 @@ import {
type SocialFetcher,
type SocialFetcherProbe,
} from "./fetchers";
+import { blueskyEndpoints } from "./blueskyEndpoints";
+import { captureBlueskyPosts, liveBlueskyCaptureDeps } from "./blueskyPostCapture";
-const APPVIEW = "https://public.api.bsky.app";
+// The AppView's origin, read per call (blueskyEndpoints.ts: a test's fake).
+const appview = () => blueskyEndpoints().appview;
const PLC_DIRECTORY = "https://plc.directory";
// getAuthorFeed's documented ceiling.
@@ -293,7 +296,7 @@ export async function resolveHandle(
handle: string,
signal?: AbortSignal,
): Promise<string> {
- const url = `${APPVIEW}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`;
+ const url = `${appview()}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`;
const body = await getJson<{ did?: string }>(url, signal);
if (!body.did) throw new Error(`No DID for handle ${handle}`);
return body.did;
@@ -312,7 +315,7 @@ export async function getProfile(
actor: string,
signal?: AbortSignal,
): Promise<BskyProfile> {
- const url = `${APPVIEW}/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(actor)}`;
+ const url = `${appview()}/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(actor)}`;
return getJson<BskyProfile>(url, signal);
}
@@ -354,7 +357,7 @@ async function getAuthorFeed(
});
if (cursor) params.set("cursor", cursor);
return getJson<BskyFeedResponse>(
- `${APPVIEW}/xrpc/app.bsky.feed.getAuthorFeed?${params.toString()}`,
+ `${appview()}/xrpc/app.bsky.feed.getAuthorFeed?${params.toString()}`,
signal,
);
}
@@ -517,7 +520,7 @@ blueskyFetcher.checkAvailability = async ({ ids, handle, signal, onLog }) => {
}
try {
const body = await getJson<{ posts?: BskyPostView[] }>(
- `${APPVIEW}/xrpc/app.bsky.feed.getPosts?${params.toString()}`,
+ `${appview()}/xrpc/app.bsky.feed.getPosts?${params.toString()}`,
signal,
);
const alive = new Set(
@@ -551,7 +554,7 @@ blueskyFetcher.fetchOne = async ({ post, channelSlug, signal, onLog }: OnePostFe
const uri = `at://${did}/app.bsky.feed.post/${post.id}`;
onLog?.(`Reading ${uri}`);
const body = await getJson<{ posts?: BskyPostView[] }>(
- `${APPVIEW}/xrpc/app.bsky.feed.getPosts?${new URLSearchParams({ uris: uri }).toString()}`,
+ `${appview()}/xrpc/app.bsky.feed.getPosts?${new URLSearchParams({ uris: uri }).toString()}`,
signal,
);
const view = (body.posts ?? []).find((v) => rkeyFromAtUri(v.uri) === post.id);
@@ -561,4 +564,9 @@ blueskyFetcher.fetchOne = async ({ post, channelSlug, signal, onLog }: OnePostFe
}
};
+// A screenshot of each post as bsky.app renders it, and its images (release
+// 29 E1): blueskyPostCapture.ts — the AppView for liveness and image URLs, a
+// headless browser with no login for the shot.
+blueskyFetcher.captureByIds = (input) => captureBlueskyPosts(input, liveBlueskyCaptureDeps(input));
+
registerSocialFetcher(blueskyFetcher);
diff --git a/common/social/blueskyPostCapture.test.ts b/common/social/blueskyPostCapture.test.ts
@@ -0,0 +1,313 @@
+// The Bluesky post capture (release 29 E1), over the fake Bluesky on loopback
+// (common/testing/social/fakeBluesky.mjs): its AppView answers liveness and
+// image URLs, its CDN the images, and its bsky.app-shaped page the shot — in
+// a stub page for the run's logic, and in a real headless Chromium for the
+// crop (skipped, saying why, on a host with no browser). No network.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/blueskyPostCapture.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { PNG as FAKE_PNG, startFakeBluesky } from "../testing/social/fakeBluesky.mjs";
+import { blueskyEndpoints, onBlueskyEndpoints, BLUESKY_ENDPOINTS } from "./blueskyEndpoints";
+import {
+ blueskyPageGapMs,
+ blueskyPostImages,
+ captureBlueskyPosts,
+ openFreshBlueskyPage,
+ shootBlueskyPost,
+ type BlueskyCaptureDeps,
+} from "./blueskyPostCapture";
+import { blueskyFetcher } from "./blueskyFetcher";
+import { capturePostsProblem } from "../controller/capturePosts";
+import { readPostCapture, SHOT_FILENAME } from "./postCapture";
+import type { PageLike } from "./playwrightRuntime";
+import type { PostCaptureInput } from "./fetchers";
+import { pngSize } from "../publish/citedPostCaptures";
+
+const HANDLE = "synthbaker.bsky.social";
+const IMAGE_POST = "3lsynthpost0001";
+const TEXT_POST = "3lsynthpost0002";
+const DELETED_POST = "3lsynthpost0003";
+
+// A page that answers the capture's calls without a browser: the post is
+// there (one thread item by the author), its box a fixed rect, its shot a PNG.
+function stubPage() {
+ const visited: string[] = [];
+ const page: PageLike = {
+ goto: async (url: string) => {
+ visited.push(url);
+ return { status: () => 200 };
+ },
+ waitForSelector: async () => ({}),
+ waitForTimeout: async () => {},
+ evaluate: async (fn: string) =>
+ fn.includes("postThreadItem-by-") ? { count: 1, rect: { x: 220, y: 70, width: 600, height: 300 }, text: "" } : 0,
+ on: () => {},
+ screenshot: async () => new Uint8Array(FAKE_PNG),
+ };
+ return { page, visited };
+}
+
+async function setup(opts: { busyTimes?: number } = {}) {
+ const bsky = await startFakeBluesky(opts);
+ const outDir = await mkdtemp(path.join(os.tmpdir(), "bsky-capture-"));
+ const pauses: number[] = [];
+ const stub = stubPage();
+ let opened = 0;
+ const deps: BlueskyCaptureDeps = {
+ fetch: (url, init) => bsky.fetch(url, init),
+ endpoints: { ...BLUESKY_ENDPOINTS },
+ openPage: async () => {
+ opened++;
+ return { page: stub.page, close: async () => {} };
+ },
+ pageGapMs: () => 3_500,
+ imageGapMs: () => 1_200,
+ pause: async (ms) => {
+ pauses.push(ms);
+ },
+ now: () => new Date("2026-10-15T12:00:00.000Z"),
+ };
+ const input = (ids: string[], extra: Partial<PostCaptureInput> = {}): PostCaptureInput => ({
+ ids,
+ handle: HANDLE,
+ outDir,
+ signal: new AbortController().signal,
+ ...extra,
+ });
+ return {
+ bsky,
+ outDir,
+ pauses,
+ stub,
+ deps,
+ input,
+ opened: () => opened,
+ close: async () => {
+ await bsky.close();
+ await rm(outDir, { recursive: true, force: true });
+ },
+ };
+}
+
+test("endpoints: the real hosts by default; a test's loopback origin from E2E_BLUESKY_ORIGIN_FILE, nothing else", async () => {
+ assert.deepEqual(blueskyEndpoints({}), BLUESKY_ENDPOINTS);
+ const dir = await mkdtemp(path.join(os.tmpdir(), "bsky-origin-"));
+ try {
+ const file = path.join(dir, "origin");
+ assert.deepEqual(blueskyEndpoints({ E2E_BLUESKY_ORIGIN_FILE: file }), BLUESKY_ENDPOINTS, "no file yet");
+ await writeFile(file, "http://127.0.0.1:4567\n");
+ const o = "http://127.0.0.1:4567";
+ assert.deepEqual(blueskyEndpoints({ E2E_BLUESKY_ORIGIN_FILE: file }), { appview: o, web: o, cdn: o });
+ await writeFile(file, "https://evil.example");
+ assert.deepEqual(blueskyEndpoints({ E2E_BLUESKY_ORIGIN_FILE: file }), BLUESKY_ENDPOINTS, "not loopback: ignored");
+ const fake = { appview: o, web: o, cdn: o };
+ assert.equal(onBlueskyEndpoints("https://cdn.bsky.app/img/x/y@jpeg", fake), `${o}/img/x/y@jpeg`);
+ assert.equal(onBlueskyEndpoints("https://bsky.app/profile/a/post/b", fake), `${o}/profile/a/post/b`);
+ assert.equal(onBlueskyEndpoints("https://example.com/a.png", fake), "https://example.com/a.png");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("the fetcher can capture: capturePostsProblem passes a Bluesky channel with no special case", () => {
+ assert.equal(typeof blueskyFetcher.captureByIds, "function");
+ assert.equal(capturePostsProblem(blueskyFetcher), null);
+});
+
+test("images: an images embed, a recordWithMedia's media, the full size first", () => {
+ assert.deepEqual(
+ blueskyPostImages({ embed: { images: [{ fullsize: "https://cdn.bsky.app/a", thumb: "https://cdn.bsky.app/t", alt: "A" }] } }),
+ [{ url: "https://cdn.bsky.app/a", alt: "A" }],
+ );
+ assert.deepEqual(blueskyPostImages({ embed: { media: { images: [{ thumb: "https://cdn.bsky.app/t" }] } } }), [
+ { url: "https://cdn.bsky.app/t" },
+ ]);
+ assert.deepEqual(blueskyPostImages({}), []);
+});
+
+test("the page gap: at least 3 s, jittered up to double; a channel's longer pause raises it", () => {
+ assert.equal(blueskyPageGapMs(() => 0), 3_000);
+ assert.equal(blueskyPageGapMs(() => 0.999), 5_997);
+ assert.equal(blueskyPageGapMs(() => 0, 1_000), 3_000, "never under the floor");
+ assert.equal(blueskyPageGapMs(() => 0.5, 10_000), 15_000);
+});
+
+test("a capture: the image post (shot, 2 images, record), the text post, the deleted post — paced, one page at a time", async () => {
+ const s = await setup();
+ try {
+ const res = await captureBlueskyPosts(s.input([IMAGE_POST, TEXT_POST, DELETED_POST]), s.deps);
+ assert.equal(res.stoppedEarly, undefined);
+ assert.deepEqual(
+ res.outcomes.map((o) => [o.id, o.state, o.availability, o.files]),
+ [
+ [IMAGE_POST, "captured", "available", 3],
+ [TEXT_POST, "captured", "available", 1],
+ [DELETED_POST, "deleted", "deleted", 0],
+ ],
+ );
+
+ const imageDir = path.join(s.outDir, IMAGE_POST);
+ assert.deepEqual((await readdir(imageDir)).sort(), ["capture.json", "media-1.png", "media-2.png", SHOT_FILENAME]);
+ assert.deepEqual(new Uint8Array(await readFile(path.join(imageDir, "media-1.png"))), new Uint8Array(FAKE_PNG));
+ const rec = await readPostCapture(imageDir);
+ assert.equal(rec?.state, "captured");
+ assert.equal(rec?.url, `https://bsky.app/profile/${HANDLE}/post/${IMAGE_POST}`);
+ assert.equal(rec?.shot?.name, SHOT_FILENAME);
+ assert.equal(rec?.mediaState, "ok");
+ assert.deepEqual(
+ rec?.media.map((m) => [m.name, m.url]),
+ [
+ ["media-1.png", "https://cdn.bsky.app/img/did:plc:synthbaker0000000000000/oven.png"],
+ ["media-2.png", "https://cdn.bsky.app/img/did:plc:synthbaker0000000000000/shop.png"],
+ ],
+ );
+
+ const text = await readPostCapture(path.join(s.outDir, TEXT_POST));
+ assert.equal(text?.mediaState, "none");
+ assert.ok(text?.shot);
+
+ const gone = await readPostCapture(path.join(s.outDir, DELETED_POST));
+ assert.equal(gone?.state, "deleted");
+ assert.equal(gone?.shot, undefined);
+
+ // Two pages (never the deleted post's), one browser, the gap before the second.
+ assert.deepEqual(s.stub.visited, [
+ `https://bsky.app/profile/${HANDLE}/post/${IMAGE_POST}`,
+ `https://bsky.app/profile/${HANDLE}/post/${TEXT_POST}`,
+ ]);
+ assert.equal(s.opened(), 1);
+ assert.deepEqual(s.pauses, [1_200, 3_500], "an image gap, then the page gap");
+ // One handle lookup, ONE getPosts for all three.
+ const xrpc = s.bsky.requests.filter((r) => r.startsWith("/xrpc/"));
+ assert.equal(xrpc.length, 2);
+ assert.match(xrpc[1], /getPosts\?uris=.*uris=.*uris=/);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a second run skips what is captured; force asks again; a deleted post is settled", async () => {
+ const s = await setup();
+ try {
+ await captureBlueskyPosts(s.input([IMAGE_POST, DELETED_POST]), s.deps);
+ const before = s.bsky.requests.length;
+ const again = await captureBlueskyPosts(s.input([IMAGE_POST, DELETED_POST]), s.deps);
+ assert.deepEqual(again.outcomes, []);
+ assert.equal(s.bsky.requests.length, before, "nothing asked");
+ const forced = await captureBlueskyPosts(s.input([IMAGE_POST], { force: true }), s.deps);
+ assert.deepEqual(forced.outcomes.map((o) => o.state), ["captured"]);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a 429 from the AppView is waited out (its Retry-After) and asked again", async () => {
+ const s = await setup({ busyTimes: 1 });
+ try {
+ const res = await captureBlueskyPosts(s.input([TEXT_POST], { media: false }), s.deps);
+ assert.deepEqual(res.outcomes.map((o) => o.state), ["captured"]);
+ assert.equal(s.pauses[0], 1_000, "Retry-After: 1");
+ assert.equal(s.bsky.requests.filter((r) => r.includes("resolveHandle")).length, 2);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a 429 that persists stops the run with nothing recorded about the posts", async () => {
+ const s = await setup({ busyTimes: 50 });
+ try {
+ const res = await captureBlueskyPosts(s.input([TEXT_POST]), { ...s.deps, maxAttempts: 3 });
+ assert.deepEqual(res.outcomes, []);
+ assert.match(res.stoppedEarly ?? "", /Could not resolve .*429/);
+ assert.equal(s.pauses.length, 2, "two waits between three attempts");
+ } finally {
+ await s.close();
+ }
+});
+
+test("a cancelled run stops between posts; the rest are left", async () => {
+ const s = await setup();
+ try {
+ const ctl = new AbortController();
+ const deps: BlueskyCaptureDeps = {
+ ...s.deps,
+ pause: async (ms) => {
+ s.pauses.push(ms);
+ ctl.abort();
+ },
+ };
+ const res = await captureBlueskyPosts(s.input([TEXT_POST, IMAGE_POST], { signal: ctl.signal, media: false }), deps);
+ assert.deepEqual(res.outcomes.map((o) => o.id), [TEXT_POST]);
+ assert.match(res.stoppedEarly ?? "", /Cancelled/);
+ } finally {
+ await s.close();
+ }
+});
+
+test("a page that does not show the post is an error; the AppView's liveness stands", async () => {
+ const s = await setup();
+ try {
+ const stub = stubPage();
+ stub.page.waitForSelector = async () => {
+ throw new Error("Timeout 20000ms exceeded");
+ };
+ stub.page.evaluate = async () => ({ count: 0, rect: null, text: "post not found" });
+ const deps: BlueskyCaptureDeps = { ...s.deps, openPage: async () => ({ page: stub.page, close: async () => {} }) };
+ const res = await captureBlueskyPosts(s.input([TEXT_POST], { media: false }), deps);
+ assert.equal(res.outcomes[0].state, "error");
+ assert.equal(res.outcomes[0].availability, "available", "the AppView said it is live");
+ assert.match(res.outcomes[0].error ?? "", /did not render/);
+ } finally {
+ await s.close();
+ }
+});
+
+// ─── A real browser over the fake's page ───
+
+test("a real headless Chromium shoots the post, cropped to it, over the fake page on loopback", async (t) => {
+ let opened;
+ try {
+ opened = await openFreshBlueskyPage();
+ } catch (e) {
+ t.skip(`no headless Chromium on this host: ${(e as Error).message.split("\n")[0].slice(0, 120)}`);
+ return;
+ }
+ const bsky = await startFakeBluesky();
+ const dir = await mkdtemp(path.join(os.tmpdir(), "bsky-shot-"));
+ try {
+ const res = await shootBlueskyPost(opened.page, {
+ url: bsky.pageUrl(HANDLE, IMAGE_POST),
+ canonicalUrl: `https://bsky.app/profile/${HANDLE}/post/${IMAGE_POST}`,
+ handle: HANDLE,
+ text: "The second shop opens in the spring. Small place, big oven.",
+ dir,
+ signal: new AbortController().signal,
+ });
+ assert.equal(res.state, "captured", res.error);
+ const size = await pngSize(path.join(dir, SHOT_FILENAME));
+ assert.ok(size, "a PNG");
+ // The thread item is 600 CSS px wide in a 1280-px window, at 2x: cropped to
+ // the post, not the page (its header, side bar and the reply below).
+ assert.equal(size!.width, 1200);
+ assert.ok(size!.height > 100 && size!.height < 800, `height ${size!.height}`);
+ const gone = await shootBlueskyPost(opened.page, {
+ url: bsky.pageUrl(HANDLE, DELETED_POST),
+ canonicalUrl: "x",
+ handle: HANDLE,
+ text: "",
+ dir: path.join(dir, "gone"),
+ signal: new AbortController().signal,
+ postTimeoutMs: 1_500,
+ });
+ assert.equal(gone.state, "error");
+ } finally {
+ await opened.close();
+ await bsky.close();
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/social/blueskyPostCapture.ts b/common/social/blueskyPostCapture.ts
@@ -0,0 +1,579 @@
+// Capturing specific Bluesky posts (release 29 E1): a screenshot of each post
+// as bsky.app renders it, and its images, into `posts-media/<id>/`
+// (postCapture.ts owns the layout and the record). No login, ever.
+//
+// TWO SOURCES, EACH ASKED AS LITTLE AS IT CAN BE:
+// - the public AppView (`app.bsky.feed.getPosts`, 25 posts a request, the
+// same batch the deleted-post sweep uses) says which posts are live — one
+// absent from the answer is deleted, recorded as X's capture records it —
+// and where each live post's images are (`embed.images[].fullsize`, or a
+// recordWithMedia's `media.images`);
+// - a headless Chromium, ONE fresh context with no profile and no cookies,
+// opens each live post's page (`bsky.app/profile/<handle>/post/<rkey>`),
+// waits for the post (`[data-testid="postThreadItem-by-<handle>"]`) and
+// shoots that element — cropped to the post, not the page — as shot.png.
+//
+// PACED: one page at a time, a real gap (3–6 s, jittered; a channel's
+// `postPagePauseSeconds` raises it) before every page after the first, a
+// timeout per page, cancellable between and during posts. A 429 from the
+// AppView or the CDN is waited out (its Retry-After, else 5 s, 10 s, … capped)
+// and asked again a few times; one that persists stops the run there, the
+// rest left for a later run. A page that answers 429 is waited out once; a
+// second stops the run.
+//
+// What a capture finds, per post:
+// captured live, shot (and its images downloaded)
+// deleted absent from getPosts — the platform says the post is gone; no
+// page is opened, and what an earlier capture took is kept
+// error the page did not show the post (a timeout, an author who
+// shows posts only to signed-in users, a post the page could
+// not tell from others), or an image failed; a later run tries
+// again
+//
+// Base URLs are injectable (deps.endpoints; blueskyEndpoints.ts for the e2e
+// suite's fake), and so is everything that waits or touches the network.
+
+import { mkdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { postPermalink, type PostAvailability } from "../lib/posts";
+import { parseRetryAfterMs } from "../lib/archiveOrgClient";
+import { blueskyEndpoints, onBlueskyEndpoints, type BlueskyEndpoints } from "./blueskyEndpoints";
+import type { PostCaptureInput, PostCaptureOutcome, PostCaptureResult } from "./fetchers";
+import { importPlaywright, type PageLike } from "./playwrightRuntime";
+import {
+ captureWork,
+ describeCapturedFile,
+ postCaptureDir,
+ readPostCapture,
+ SHOT_FILENAME,
+ writePostCapture,
+ type CapturedFile,
+ type CaptureMediaState,
+ type PostCaptureRecord,
+ type PostCaptureState,
+} from "./postCapture";
+
+// ─── The AppView's answer (only what the capture reads) ───
+
+type ImageView = { fullsize?: string; thumb?: string; alt?: string };
+export type BlueskyPostView = {
+ uri?: string;
+ author?: { did?: string; handle?: string };
+ record?: { text?: string };
+ embed?: { $type?: string; images?: ImageView[]; media?: { images?: ImageView[] } };
+};
+
+const rkeyOf = (uri: string | undefined): string | null => {
+ const i = uri?.lastIndexOf("/") ?? -1;
+ return uri && i >= 0 && i < uri.length - 1 ? uri.slice(i + 1) : null;
+};
+
+// A live post's images, as the AppView names them: an images embed, or the
+// media half of a recordWithMedia. The full-size URL, else the thumbnail.
+export function blueskyPostImages(view: BlueskyPostView): { url: string; alt?: string }[] {
+ const list = view.embed?.images ?? view.embed?.media?.images ?? [];
+ const out: { url: string; alt?: string }[] = [];
+ for (const im of list) {
+ const url = im?.fullsize ?? im?.thumb;
+ if (typeof url !== "string" || !/^https?:\/\//.test(url)) continue;
+ out.push({ url, ...(im.alt ? { alt: im.alt } : {}) });
+ }
+ return out;
+}
+
+// getPosts' documented ceiling.
+export const GET_POSTS_BATCH = 25;
+
+// The gap before each page after a run's first: 3–6 s, or the channel's own
+// pause (at least 3 s) jittered to [1, 2) of itself.
+export const MIN_PAGE_GAP_MS = 3_000;
+export function blueskyPageGapMs(random: () => number, baseMs?: number): number {
+ const base = Math.max(MIN_PAGE_GAP_MS, baseMs ?? MIN_PAGE_GAP_MS);
+ return Math.round(base * (1 + random()));
+}
+
+// ─── Deps ───
+
+export type BlueskyCaptureDeps = {
+ fetch: (url: string, init?: RequestInit) => Promise<Response>;
+ endpoints: BlueskyEndpoints;
+ // A page in a fresh browser context: opened on the first shot, closed at the
+ // end of the run.
+ openPage: () => Promise<{ page: PageLike; close: () => Promise<void> }>;
+ // The gap before each page after the first, and between two images.
+ pageGapMs: () => number;
+ imageGapMs: () => number;
+ pause: (ms: number, signal: AbortSignal) => Promise<void>;
+ now?: () => Date;
+ // A 429/503 retry's wait when the answer names none (doubling per attempt),
+ // its cap, and how many attempts a request gets.
+ backoffBaseMs?: number;
+ backoffMaxMs?: number;
+ maxAttempts?: number;
+ // How long a page may take to load, and the post to appear on it.
+ pageTimeoutMs?: number;
+ postTimeoutMs?: number;
+};
+
+export function sleepUnlessAborted(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (ms <= 0 || signal.aborted) return resolve();
+ const timer = setTimeout(done, ms);
+ function done() {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", done);
+ resolve();
+ }
+ signal.addEventListener("abort", done, { once: true });
+ });
+}
+
+// A headless Chromium with a fresh context: no profile directory, no cookies,
+// no stored state — what a logged-out reader sees.
+export async function openFreshBlueskyPage(): Promise<{ page: PageLike; close: () => Promise<void> }> {
+ const { chromium } = await importPlaywright();
+ const browser = await chromium.launch({ headless: true });
+ try {
+ const context = await browser.newContext({
+ viewport: { width: 1280, height: 1600 },
+ deviceScaleFactor: 2,
+ locale: "en-US",
+ colorScheme: "light",
+ });
+ const page = await context.newPage();
+ return {
+ page,
+ close: async () => {
+ await context.close().catch(() => {});
+ await browser.close().catch(() => {});
+ },
+ };
+ } catch (err) {
+ await browser.close().catch(() => {});
+ throw err;
+ }
+}
+
+export function liveBlueskyCaptureDeps(input: Pick<PostCaptureInput, "pagePauseMs">): BlueskyCaptureDeps {
+ return {
+ fetch: (url, init) => fetch(url, init),
+ endpoints: blueskyEndpoints(),
+ openPage: openFreshBlueskyPage,
+ pageGapMs: () => blueskyPageGapMs(Math.random, input.pagePauseMs),
+ imageGapMs: () => 1_000 + Math.round(Math.random() * 1_000),
+ pause: sleepUnlessAborted,
+ };
+}
+
+// ─── Requests, with the 429 back-off ───
+
+type Got =
+ | { ok: true; res: Response }
+ | { ok: false; error: string; rateLimited?: boolean; status?: number };
+
+async function politeGet(
+ deps: BlueskyCaptureDeps,
+ url: string,
+ accept: string,
+ signal: AbortSignal,
+ onLog?: (line: string) => void,
+): Promise<Got> {
+ const attempts = deps.maxAttempts ?? 4;
+ const base = deps.backoffBaseMs ?? 5_000;
+ const cap = deps.backoffMaxMs ?? 120_000;
+ const now = () => (deps.now ?? (() => new Date()))().getTime();
+ let last = "";
+ for (let attempt = 1; attempt <= attempts; attempt++) {
+ let res: Response;
+ try {
+ res = await deps.fetch(url, { signal, headers: { accept } });
+ } catch (err) {
+ if (signal.aborted) return { ok: false, error: "cancelled" };
+ return { ok: false, error: firstLine(err) };
+ }
+ if (res.ok) return { ok: true, res };
+ if (res.status !== 429 && res.status !== 503) {
+ await res.arrayBuffer().catch(() => {});
+ return { ok: false, error: `HTTP ${res.status}`, status: res.status };
+ }
+ last = `HTTP ${res.status}`;
+ await res.arrayBuffer().catch(() => {});
+ if (attempt === attempts) break;
+ const wait = Math.min(cap, parseRetryAfterMs(res.headers.get("retry-after"), now()) ?? base * 2 ** (attempt - 1));
+ onLog?.(`Bluesky answered ${res.status}; waiting ${Math.round(wait / 1000)} s before asking again.`);
+ await deps.pause(wait, signal);
+ if (signal.aborted) return { ok: false, error: "cancelled" };
+ }
+ return { ok: false, error: `Bluesky kept answering ${last} after ${attempts} attempts`, rateLimited: true };
+}
+
+// ─── One page's shot ───
+
+// The post on its page: the thread items by its author (a self-thread's
+// parents and replies share the test id), the one holding the post's text —
+// or the only one. Marked for the shot; its box in document coordinates.
+const SNAPSHOT_SCRIPT = (handle: string, text: string) => `(() => {
+ const sel = ${JSON.stringify(`[data-testid="postThreadItem-by-${handle}"]`)};
+ const norm = (s) => (s || "").replace(/\\s+/g, " ").trim().toLowerCase();
+ const want = norm(${JSON.stringify(text)}).slice(0, 80);
+ const all = Array.from(document.querySelectorAll(sel));
+ let own = all.length === 1 ? all[0] : null;
+ if (!own && want) own = all.find((el) => norm(el.innerText).includes(want)) || null;
+ for (const el of document.querySelectorAll("[data-archilyzer-capture]")) el.removeAttribute("data-archilyzer-capture");
+ if (!own) return { count: all.length, rect: null, text: norm(document.body && document.body.innerText).slice(0, 2000) };
+ own.setAttribute("data-archilyzer-capture", "");
+ const r = own.getBoundingClientRect();
+ return { count: all.length, rect: { x: r.left + window.scrollX, y: r.top + window.scrollY, width: r.width, height: r.height }, text: "" };
+})()`;
+
+// Let the post's images finish loading (each capped), so the shot is not of
+// grey boxes.
+const IMAGES_LOADED_SCRIPT = `(() => {
+ const own = document.querySelector("[data-archilyzer-capture]") || document;
+ const imgs = Array.from(own.querySelectorAll("img")).filter((i) => !i.complete);
+ return Promise.all(imgs.map((i) => new Promise((r) => {
+ i.addEventListener("load", r, { once: true });
+ i.addEventListener("error", r, { once: true });
+ setTimeout(r, 5000);
+ }))).then(() => imgs.length);
+})()`;
+
+type Snapshot = { count: number; rect: { x: number; y: number; width: number; height: number } | null; text: string };
+
+export type BlueskyShotResult = {
+ state: PostCaptureState;
+ shot?: CapturedFile;
+ error?: string;
+ // The page answered 429.
+ rateLimited?: boolean;
+};
+
+function raceAbort<T>(p: Promise<T>, signal: AbortSignal): Promise<T> {
+ if (signal.aborted) return Promise.reject(new Error("cancelled"));
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => reject(new Error("cancelled"));
+ signal.addEventListener("abort", onAbort, { once: true });
+ p.then(
+ (v) => {
+ signal.removeEventListener("abort", onAbort);
+ resolve(v);
+ },
+ (e) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(e);
+ },
+ );
+ });
+}
+
+// One post's screenshot: load its page, wait for the post, shoot that element.
+// Writes `shot.png` into `dir` only for a post that rendered. `url` is the
+// page to open; `canonicalUrl` the bsky.app URL the record names.
+export async function shootBlueskyPost(
+ page: PageLike,
+ o: {
+ url: string;
+ canonicalUrl: string;
+ handle: string;
+ text: string;
+ dir: string;
+ signal: AbortSignal;
+ pageTimeoutMs?: number;
+ postTimeoutMs?: number;
+ },
+): Promise<BlueskyShotResult> {
+ let response: unknown;
+ try {
+ response = await raceAbort(
+ page.goto(o.url, { waitUntil: "domcontentloaded", timeout: o.pageTimeoutMs ?? 45_000 }),
+ o.signal,
+ );
+ } catch (err) {
+ return { state: "error", error: `Could not load ${o.canonicalUrl}: ${firstLine(err)}` };
+ }
+ const status = (response as { status?: () => number } | null)?.status?.();
+ if (status === 429) return { state: "error", error: "bsky.app answered 429", rateLimited: true };
+ const sel = `[data-testid="postThreadItem-by-${o.handle}"]`;
+ const appeared = await raceAbort(
+ page.waitForSelector(sel, { timeout: o.postTimeoutMs ?? 20_000 }).then(
+ () => true,
+ () => false,
+ ),
+ o.signal,
+ ).catch(() => false);
+ if (o.signal.aborted) return { state: "error", error: "cancelled" };
+ if (!appeared) {
+ const snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text)).catch(() => null)) as Snapshot | null;
+ const body = snap?.text ?? "";
+ if (/sign in|log in/.test(body) && /(required|to view|logged-in|signed-in)/.test(body)) {
+ return { state: "error", error: "The author shows their posts only to signed-in users; the capture has no login." };
+ }
+ return { state: "error", error: `The post did not render (no ${sel} on the page).` };
+ }
+ await page.waitForTimeout(1_000);
+ let snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text))) as Snapshot;
+ if (!snap.rect) {
+ return { state: "error", error: `${snap.count} posts by @${o.handle} on the page, none of them this one's text.` };
+ }
+ await page.evaluate(IMAGES_LOADED_SCRIPT).catch(() => {});
+ // Re-read the box: images that loaded may have grown it.
+ snap = (await page.evaluate(SNAPSHOT_SCRIPT(o.handle, o.text))) as Snapshot;
+ const rect = snap.rect;
+ if (!rect || rect.width < 1 || rect.height < 1) {
+ return { state: "error", error: "The post rendered with no size to shoot." };
+ }
+ let png: Uint8Array;
+ try {
+ // fullPage, so a post taller than the window is shot whole; the clip is in
+ // document coordinates, which is what the snapshot measured.
+ png = await page.screenshot({
+ type: "png",
+ fullPage: true,
+ clip: {
+ x: Math.max(0, Math.floor(rect.x)),
+ y: Math.max(0, Math.floor(rect.y)),
+ width: Math.ceil(rect.width),
+ height: Math.ceil(rect.height),
+ },
+ });
+ } catch (err) {
+ return { state: "error", error: `The screenshot failed: ${firstLine(err)}` };
+ }
+ await mkdir(o.dir, { recursive: true });
+ await writeFile(path.join(o.dir, SHOT_FILENAME), png);
+ return { state: "captured", shot: await describeCapturedFile(o.dir, SHOT_FILENAME, o.canonicalUrl) };
+}
+
+// ─── The images ───
+
+const EXT_BY_TYPE: Record<string, string> = {
+ "image/jpeg": "jpg",
+ "image/png": "png",
+ "image/gif": "gif",
+ "image/webp": "webp",
+ "image/avif": "avif",
+};
+
+function imageExt(url: string, contentType: string | null): string {
+ const ct = (contentType ?? "").split(";")[0].trim().toLowerCase();
+ if (EXT_BY_TYPE[ct]) return EXT_BY_TYPE[ct];
+ // The CDN names the format after an "@": …/<cid>@jpeg.
+ const at = /@(jpeg|jpg|png|webp|gif)$/i.exec(url);
+ if (at) return at[1].toLowerCase() === "jpeg" ? "jpg" : at[1].toLowerCase();
+ const m = /\.([a-z0-9]{2,5})(?:[?#]|$)/i.exec(url);
+ return m ? m[1].toLowerCase() : "jpg";
+}
+
+// ─── The run ───
+
+// A run's errors in a row that stop it: a host whose network or browser is
+// failing every post should not page through the rest of the list.
+const STOP_AFTER_ERRORS = 3;
+
+export async function captureBlueskyPosts(
+ input: PostCaptureInput,
+ deps: BlueskyCaptureDeps,
+): Promise<PostCaptureResult> {
+ const { signal, onLog } = input;
+ const wanted = { shots: input.shots ?? true, media: input.media ?? true, force: input.force ?? false };
+ const now = deps.now ?? (() => new Date());
+ const outcomes: PostCaptureOutcome[] = [];
+ const stopped = (why: string): PostCaptureResult => {
+ onLog?.(why);
+ return { outcomes, stoppedEarly: why };
+ };
+
+ // What each post is owed, from what is on disk.
+ const owed: { id: string; dir: string; existing: PostCaptureRecord | null; shot: boolean; media: boolean }[] = [];
+ for (const id of input.ids) {
+ const dir = postCaptureDir(input.outDir, id);
+ const existing = await readPostCapture(dir);
+ const work = captureWork(existing, { ...wanted, articles: false });
+ if (!work.shot && !work.media) {
+ onLog?.(`${id}: already captured (${existing?.state ?? "nothing asked for"}) — skipped.`);
+ continue;
+ }
+ owed.push({ id, dir, existing, shot: work.shot, media: work.media });
+ }
+ if (owed.length === 0) return { outcomes };
+
+ // The account's DID: getPosts takes AT-URIs.
+ const appview = deps.endpoints.appview;
+ let did = input.handle;
+ if (!did.startsWith("did:")) {
+ const got = await politeGet(
+ deps,
+ `${appview}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(input.handle)}`,
+ "application/json",
+ signal,
+ onLog,
+ );
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ if (!got.ok) return stopped(`Could not resolve @${input.handle}: ${got.error}. Nothing was recorded.`);
+ const body = (await got.res.json().catch(() => null)) as { did?: string } | null;
+ if (!body?.did) return stopped(`Could not resolve @${input.handle}: no DID in the answer. Nothing was recorded.`);
+ did = body.did;
+ }
+
+ // Liveness and images, 25 posts a request. A post absent from a batch that
+ // answered is deleted; a batch that failed says nothing about its posts.
+ const views = new Map<string, BlueskyPostView>();
+ const unanswered = new Map<string, string>();
+ for (let i = 0; i < owed.length; i += GET_POSTS_BATCH) {
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ const batch = owed.slice(i, i + GET_POSTS_BATCH);
+ const params = new URLSearchParams();
+ for (const o of batch) params.append("uris", `at://${did}/app.bsky.feed.post/${o.id}`);
+ const got = await politeGet(deps, `${appview}/xrpc/app.bsky.feed.getPosts?${params.toString()}`, "application/json", signal, onLog);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ if (!got.ok) {
+ if (got.rateLimited) return stopped(`${got.error}; stopping — the posts are left for a later run.`);
+ for (const o of batch) unanswered.set(o.id, `getPosts failed: ${got.error}`);
+ continue;
+ }
+ const body = (await got.res.json().catch(() => null)) as { posts?: BlueskyPostView[] } | null;
+ if (!body || !Array.isArray(body.posts)) {
+ for (const o of batch) unanswered.set(o.id, "getPosts answered no post list");
+ continue;
+ }
+ for (const v of body.posts) {
+ const rkey = rkeyOf(v.uri);
+ if (rkey) views.set(rkey, v);
+ }
+ }
+
+ let pages = 0;
+ let errorsInARow = 0;
+ let browser: { page: PageLike; close: () => Promise<void> } | undefined;
+ try {
+ for (const [i, o] of owed.entries()) {
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ if (input.drain?.aborted) return stopped("Drained; the rest are left for a later run.");
+ const { id, dir, existing } = o;
+ onLog?.(`[${i + 1}/${owed.length}] ${id}`);
+ const view = views.get(id);
+ const failedLookup = unanswered.get(id);
+ const author = view?.author?.handle || input.handle;
+ const canonicalUrl = postPermalink("bluesky", author, id);
+
+ let state: PostCaptureState;
+ let availability: PostAvailability | undefined;
+ let shot = existing?.shot;
+ let mediaState: CaptureMediaState = existing?.mediaState ?? "skipped";
+ let media: CapturedFile[] = existing?.media ?? [];
+ let error: string | undefined;
+ let stop: string | undefined;
+
+ if (failedLookup) {
+ // Nothing learned about the post: what is on disk stands.
+ state = "error";
+ error = failedLookup;
+ } else if (!view) {
+ // The platform says it is gone. What an earlier capture took is kept.
+ state = "deleted";
+ availability = "deleted";
+ } else {
+ availability = "available";
+ // A run that does not shoot keeps the shot's verdict on disk.
+ state = o.shot ? "error" : (existing?.state ?? "captured");
+ if (o.shot) {
+ if (pages++ > 0) await deps.pause(deps.pageGapMs(), signal);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ browser ??= await deps.openPage();
+ const shotArgs = {
+ url: onBlueskyEndpoints(`https://bsky.app/profile/${author}/post/${id}`, deps.endpoints),
+ canonicalUrl,
+ handle: author,
+ text: view.record?.text ?? "",
+ dir,
+ signal,
+ ...(deps.pageTimeoutMs ? { pageTimeoutMs: deps.pageTimeoutMs } : {}),
+ ...(deps.postTimeoutMs ? { postTimeoutMs: deps.postTimeoutMs } : {}),
+ };
+ let res = await shootBlueskyPost(browser.page, shotArgs);
+ if (res.rateLimited) {
+ const wait = Math.max(deps.backoffBaseMs ?? 30_000, deps.pageGapMs());
+ onLog?.(`bsky.app answered 429; waiting ${Math.round(wait / 1000)} s before one more try.`);
+ await deps.pause(wait, signal);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ res = await shootBlueskyPost(browser.page, shotArgs);
+ if (res.rateLimited) stop = "bsky.app answered 429 twice; stopping.";
+ }
+ state = res.state;
+ if (res.shot) shot = res.shot;
+ if (res.error) error = res.error;
+ }
+ const postIsThere = state === "captured" || !o.shot;
+ if (o.media && postIsThere && !stop) {
+ const images = blueskyPostImages(view);
+ if (images.length === 0) {
+ mediaState = "none";
+ media = [];
+ } else {
+ media = [];
+ let failed = 0;
+ for (const [n, im] of images.entries()) {
+ if (n > 0) await deps.pause(deps.imageGapMs(), signal);
+ if (signal.aborted) return stopped("Cancelled; the rest are left for a later run.");
+ const got = await politeGet(deps, onBlueskyEndpoints(im.url, deps.endpoints), "image/*", signal, onLog);
+ if (!got.ok) {
+ failed++;
+ onLog?.(`${id}: image ${n + 1} failed: ${got.error}`);
+ if (got.rateLimited) {
+ stop = `${got.error}; stopping.`;
+ break;
+ }
+ continue;
+ }
+ const name = `media-${n + 1}.${imageExt(im.url, got.res.headers.get("content-type"))}`;
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, name), new Uint8Array(await got.res.arrayBuffer()));
+ media.push(await describeCapturedFile(dir, name, im.url));
+ }
+ mediaState = failed > 0 ? "error" : "ok";
+ if (failed > 0) error = error ? `${error}; ${failed} image(s) failed` : `${failed} image(s) failed`;
+ }
+ if (!o.shot && !existing && mediaState === "error") state = "error";
+ }
+ }
+
+ const record: PostCaptureRecord = {
+ version: 1,
+ id,
+ url: canonicalUrl,
+ capturedAt: now().toISOString(),
+ state,
+ ...(shot ? { shot } : {}),
+ mediaState,
+ media,
+ ...(error ? { error } : {}),
+ };
+ await writePostCapture(dir, record);
+ outcomes.push({
+ id,
+ state,
+ ...(availability ? { availability } : {}),
+ files: (shot ? 1 : 0) + media.length,
+ ...(error ? { error } : {}),
+ });
+ onLog?.(
+ `${id}: ${state}` +
+ (state === "captured" && o.shot ? ", shot" : "") +
+ (mediaState === "ok" ? `, ${media.length} image(s)` : mediaState === "none" && view ? ", no images" : "") +
+ (error ? ` — ${error}` : ""),
+ );
+ if (stop) return stopped(`${stop} Stopped at ${id}; the rest are left for a later run.`);
+ errorsInARow = state === "error" ? errorsInARow + 1 : 0;
+ if (errorsInARow >= STOP_AFTER_ERRORS) {
+ return stopped(`${STOP_AFTER_ERRORS} posts in a row failed; stopping rather than paging through the rest.`);
+ }
+ }
+ return { outcomes };
+ } finally {
+ await browser?.close().catch(() => {});
+ }
+}
+
+function firstLine(err: unknown): string {
+ return ((err as Error)?.message ?? String(err)).split("\n")[0];
+}
diff --git a/editor/app/api/ops/capture-posts/route.test.ts b/editor/app/api/ops/capture-posts/route.test.ts
@@ -94,6 +94,16 @@ test("capture-posts refuses what it cannot capture, and an id not in the archive
name: "Example (Bluesky)",
url: "https://bsky.app/profile/example.bsky.social",
});
+ // An X channel on the Nitter fetcher, which has no capture.
+ await channel("example-nitter", {
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "twitter",
+ postFetcher: "x-nitter",
+ socialHandle: "example_user",
+ name: "Example (X, Nitter)",
+ url: "https://x.com/example_user",
+ });
// An X channel with an empty posts archive.
await channel("example-x", {
handling: "transcribe",
@@ -109,9 +119,15 @@ test("capture-posts refuses what it cannot capture, and an id not in the archive
assert.equal(video.status, 400);
assert.equal(video.error, "test-filter is not a social channel.");
+ const nitter = await post({ slug: "example-nitter", ids: ["1"] });
+ assert.equal(nitter.status, 400);
+ assert.match(nitter.error, /cannot capture posts/);
+
+ // Bluesky captures (release 29 E1): its fetcher passes, and the id that is
+ // not in the channel's archive is what is refused.
const bsky = await post({ slug: "example-bsky", ids: ["1"] });
assert.equal(bsky.status, 400);
- assert.match(bsky.error, /cannot capture posts/);
+ assert.equal(bsky.error, "1 id(s) not in example-bsky's posts archive: 1");
const neither = await post({ slug: "example-x", ids: ["1"], shots: false, media: false });
assert.equal(neither.status, 400);
diff --git a/editor/e2e/capture-posts.spec.ts b/editor/e2e/capture-posts.spec.ts
@@ -0,0 +1,130 @@
+// Capture posts for a Bluesky channel (release 29 E1), end to end over the
+// fake Bluesky (common/testing/social/fakeBluesky.mjs): the AppView, the
+// bsky.app-shaped post page and the image CDN all on one loopback origin,
+// named to the test server through E2E_BLUESKY_ORIGIN_FILE (e2e/servers.ts).
+// The real Bluesky is never contacted.
+//
+// The job runs as `pnpm ops capture-posts` runs it: the AppView says which
+// posts are live and where their images are, a headless Chromium with no login
+// shoots each live post cropped to it, the images come down beside the shot,
+// and the deleted post lands in posts-availability.json as deleted.
+
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { startFakeBluesky, BSKY_POSTS, ACCOUNTS } from "yt-dlp-transcript-common/testing/social/fakeBluesky.mjs";
+import { writePosts } from "yt-dlp-transcript-common/lib/posts-server";
+import { uploadDateFromCreatedAt, type Post } from "yt-dlp-transcript-common/lib/posts";
+import { baseUrl } from "./baseUrl";
+import { resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+import { blueskyOriginFile } from "./servers";
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLUG = "synth-bsky";
+const HANDLE = ACCOUNTS[0].handle;
+
+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("capture-posts on a Bluesky channel: shots cropped to the post, its images, and the deleted post recorded", async ({
+ request,
+}) => {
+ test.setTimeout(150_000);
+ await resetData("empty");
+ await writeSettings({ minFreeDiskGB: 0 });
+
+ const channelRoot = resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`);
+ await mkdir(channelRoot, { recursive: true });
+ await writeFile(
+ path.join(channelRoot, "config.json"),
+ JSON.stringify(
+ {
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "bluesky",
+ postFetcher: "bluesky-atproto",
+ socialHandle: HANDLE,
+ name: "Synth Baker (Bluesky)",
+ url: `https://bsky.app/profile/${HANDLE}`,
+ },
+ null,
+ 2,
+ ),
+ );
+ // The three invented posts, archived as a fetch would have left them.
+ const posts: Post[] = BSKY_POSTS.map((p) => ({
+ id: p.rkey,
+ slug: `${SLUG}/${p.rkey}`,
+ channelSlug: SLUG,
+ author: p.handle,
+ createdAt: p.createdAt,
+ uploadDate: uploadDateFromCreatedAt(p.createdAt),
+ text: p.text,
+ url: `https://bsky.app/profile/${p.handle}/post/${p.rkey}`,
+ platform: "bluesky",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ }));
+ await writePosts(channelRoot, posts);
+
+ const bsky = await startFakeBluesky();
+ const originFile = blueskyOriginFile(resolvePath(testPaths().transcriptsDir));
+ await writeFile(originFile, bsky.base);
+ try {
+ const ids = BSKY_POSTS.map((p) => p.rkey);
+ const res = await request.post(`${baseUrl}/api/ops/capture-posts`, { headers: AUTH, data: { slug: SLUG, ids } });
+ const body = (await res.json()) as { ok?: boolean; jobId?: string; error?: string };
+ expect(res.status(), body.error).toBe(200);
+ const job = await waitForJob(request, body.jobId!);
+ expect(job.status, job.tail.join("\n")).toBe("done");
+
+ const media = path.join(channelRoot, "posts-media");
+ const [withImages, textOnly, deleted] = ids;
+ expect((await readdir(path.join(media, withImages))).sort()).toEqual([
+ "capture.json",
+ "media-1.png",
+ "media-2.png",
+ "shot.png",
+ ]);
+ expect((await readdir(path.join(media, textOnly))).sort()).toEqual(["capture.json", "shot.png"]);
+ const gone = JSON.parse(await readFile(path.join(media, deleted, "capture.json"), "utf8")) as { state: string; shot?: unknown };
+ expect(gone.state).toBe("deleted");
+ expect(gone.shot).toBeUndefined();
+
+ // The shot is the post, not the page: the fake's thread item is 600 CSS
+ // px wide in a 1280-px window, shot at 2x.
+ const png = await readFile(path.join(media, withImages, "shot.png"));
+ expect(png.readUInt32BE(16)).toBe(1200);
+
+ const availability = JSON.parse(await readFile(path.join(channelRoot, "posts-availability.json"), "utf8")) as Record<
+ string,
+ { availability: string }
+ >;
+ expect(availability[deleted]?.availability).toBe("deleted");
+ expect(availability[withImages]?.availability).toBe("available");
+
+ // The page was opened for the live posts only; the deleted one never.
+ const pages = bsky.requests.filter((r) => r.startsWith("/profile/"));
+ expect(pages).toEqual([
+ `/profile/${HANDLE}/post/${withImages}`,
+ `/profile/${HANDLE}/post/${textOnly}`,
+ ]);
+ } finally {
+ await rm(originFile, { force: true });
+ await bsky.close();
+ }
+});
diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts
@@ -47,6 +47,11 @@ export const E2E_SERVER_ENV: Record<string, string> = {
EXPORT_NEXT_BIN: join(EDITOR_ROOT, "e2e", "fixtures", "bin", "fake-next.mjs"),
};
+/** The file naming a slot's fake Bluesky (common/social/blueskyEndpoints.ts). */
+export function blueskyOriginFile(transcriptsDir: string): string {
+ return join(transcriptsDir, ".fake-bluesky-origin");
+}
+
/** The start-mode build directory (scripts/e2e-stamp.mjs PACKAGES.editor.distDir). */
export const E2E_DIST_DIR = ".next/e2e";
const EXPORT_SITES_DIR = join(EDITOR_ROOT, "e2e", "fixtures", "sites");
@@ -192,6 +197,9 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env)
const ports = slotPorts(slot, env);
const paths = testPathsFor(slotRoot(slot));
const editorEnv: Record<string, string> = { ...E2E_SERVER_ENV };
+ // Where a spec names its fake Bluesky's origin (capture-posts.spec): the
+ // slot's own test data, so two slots never share one.
+ editorEnv.E2E_BLUESKY_ORIGIN_FILE = blueskyOriginFile(paths.transcriptsDir);
// A start-mode server runs the stamped build (shared, read-only); a second
// `next dev` needs a dist dir of its own (Next locks `<distDir>/dev/lock`).
if (mode === "start" && !env.CI) editorEnv.E2E_NEXT_DIST_DIR = E2E_DIST_DIR;
diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts
@@ -30,6 +30,10 @@ import { currentSlot } from "./e2e/testPaths";
// batch (30–45 s in production; 2 s here), so
// fetch-window.spec sees the one it owes
// (common/controller/fetchWindows.ts)
+// E2E_BLUESKY_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec
+// writes its fake Bluesky's loopback origin into,
+// which the AppView, bsky.app and the image CDN
+// then are (common/social/blueskyEndpoints.ts)
// E2E_MODE `start` (the default): the editor runs under
// `next start` from a build the stamp vouches for
// (scripts/e2e-stamp.mjs — rebuilt through the