// 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 { ACCOUNTS, 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, apiGapMs: () => 800, pause: async (ms) => { pauses.push(ms); }, now: () => new Date("2026-10-15T12:00:00.000Z"), }; // What capturePosts hands over for a Bluesky channel: each id's archived author. const archived = (ids: string[], author = HANDLE) => new Map(ids.map((id) => [id, { text: "", author }])); const input = (ids: string[], extra: Partial = {}): PostCaptureInput => ({ ids, handle: HANDLE, outDir, signal: new AbortController().signal, archived: archived(ids), ...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, [800, 1_200, 3_500], "the AppView gap (handle → getPosts), 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.pauses[1], 800, "then the gap before getPosts"); 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 ?? "", /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); if (ms === 3_500) ctl.abort(); // during the gap before the second page }, }; 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(); } }); test("a repost is looked up under its original author, never read as deleted under the channel's account", async () => { const FAN = { handle: "synthfan.bsky.social", did: "did:plc:synthfan00000000000000000", displayName: "Synth Fan" }; const bsky = await startFakeBluesky({ accounts: [...ACCOUNTS, FAN] }); const s = await setup(); try { const deps: BlueskyCaptureDeps = { ...s.deps, fetch: (url, init) => bsky.fetch(url, init) }; // The fan's channel archived the baker's post (a repost): its rkey, its author. const res = await captureBlueskyPosts( { ...s.input([TEXT_POST], { media: false }), handle: FAN.handle, archived: new Map([[TEXT_POST, { text: "", author: HANDLE }]]) }, deps, ); assert.deepEqual(res.outcomes.map((o) => [o.state, o.availability]), [["captured", "available"]]); assert.ok(bsky.requests.some((r) => r.includes(encodeURIComponent(`at://${ACCOUNTS[0].did}/app.bsky.feed.post/${TEXT_POST}`)))); assert.ok(!bsky.requests.some((r) => r.includes(encodeURIComponent(FAN.did))), "never asked under the channel's DID"); // An author the archive does not name: nothing learned, never `deleted`. const unknown = await captureBlueskyPosts( { ...s.input([DELETED_POST], { media: false, force: true }), archived: new Map() }, deps, ); assert.deepEqual(unknown.outcomes.map((o) => [o.state, o.availability]), [["error", undefined]]); // The deleted-post sweep leaves a repost as it was rather than read its // absence under the channel's account as a deletion. const before = bsky.requests.length; const swept = await blueskyFetcher.checkAvailability!({ ids: [TEXT_POST], handle: FAN.handle, authors: new Map([[TEXT_POST, HANDLE]]), signal: new AbortController().signal, }); assert.equal(swept.size, 0); assert.equal(bsky.requests.length, before, "nothing asked"); } finally { await bsky.close(); await s.close(); } }); test("the post on a self-thread page: its own link, else its whole text; ambiguous is an error, never the wrong shot", 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 dir = await mkdtemp(path.join(os.tmpdir(), "bsky-thread-")); const item = (text: string, link?: string) => `

${text}

${link ? `2h` : ""}
`; const page = (body: string) => `data:text/html,${encodeURIComponent(`${body}`)}`; const shoot = (html: string, text: string, rkey = "3lreply") => shootBlueskyPost(opened!.page, { url: page(html), canonicalUrl: "x", handle: HANDLE, rkey, text, dir, signal: new AbortController().signal, postTimeoutMs: 2_000 }); const marked = () => opened!.page.evaluate(`document.querySelector("[data-archilyzer-capture] p").innerText`); try { // A short reply under parents that contain its words: the exact text wins. const thread = item("lol that is so true, lol", "https://bsky.app/profile/x/post/3lparent1") + item("lol") + item("lol no", "https://bsky.app/profile/x/post/3lchild"); assert.equal((await shoot(thread, "lol")).state, "captured"); assert.equal(await marked(), "lol"); // An item linking to the post's own permalink wins over text. const linked = item("same words") + item("same words", `https://bsky.app/profile/${HANDLE}/post/3lreply`); assert.equal((await shoot(linked, "same words")).state, "captured"); assert.equal(await opened.page.evaluate(`!!document.querySelector("[data-archilyzer-capture] a")`), true); // Two items with the post's whole text and no link: ambiguous, no shot. const twins = item("lol") + item("lol"); const r = await shoot(twins, "lol", "3lother"); assert.equal(r.state, "error"); assert.match(r.error ?? "", /match this one; none shot/); } finally { await opened.close(); await rm(dir, { recursive: true, force: true }); } }); // ─── 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, rkey: IMAGE_POST, 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, rkey: DELETED_POST, 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 }); } });