Something went wrong. Try again.
The Social Wire — an ATProto publication reader. thesocialwire.app
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336import * as ReadStateRuntime from "@/lib/pdsReadStateRuntime";import { describe, expect, it, mock, spyOn, beforeEach, afterEach } from "bun:test";
const ORIG_ENV = { ...process.env };const ORIG_FETCH = globalThis.fetch;
describe("thinAppViewClient", () => { beforeEach(() => { process.env.NEXT_PUBLIC_SOCIALWIRE_API_URL = "https://api.example.test"; globalThis.fetch = ORIG_FETCH; spyOn(ReadStateRuntime, "usesPDSReadState").mockResolvedValue(false); });
afterEach(() => { process.env = { ...ORIG_ENV }; globalThis.fetch = ORIG_FETCH; mock.restore(); });
it("preserves typed publisher failures but keeps generic enrollment errors as failures", async () => { const { enrollAuthorsInAppView } = await import("@/lib/thinAppViewClient"); const { PublicationSourceRefreshError } = await import("@/lib/publicationSourceRefreshError"); for (const partial of [true, false]) { const session = gatewayOAuthSession(mock(async () => Response.json({ error: "Service Unavailable", message: "Enrollment unavailable", ...(partial ? { articlesUpdated: true, unavailablePublicationIds: ["rss:world"], sourceFailures: [{ category: "rss_backoff", kind: "other", host: "publisher.test", count: 1 }] } : {}), }, { status: 503 }))); const error = await enrollAuthorsInAppView(session, [], ["https://publisher.test/rss"]).catch(error => error); expect(error).toBeInstanceOf(Error); expect(error instanceof PublicationSourceRefreshError).toBe(partial); if (error instanceof PublicationSourceRefreshError) expect(error.unavailablePublicationIds).toEqual(["rss:world"]); } });
it("listEntriesFromAppView requires appViewScope and sends scope params", async () => { const fetchHandler = mock(async (url: string) => { expect(url).toContain("publicationScopeAtUris="); expect(url).toContain("publicationSiteUrls="); expect(url).toContain("filter=unread"); return new Response( JSON.stringify({ entries: [ { entryId: "at://did:plc:alice/site.standard.entry/rkey1", title: "Indexed", publishedAt: "2024-01-01T00:00:00.000Z", }, ], cursor: "next-cursor", }), { status: 200, headers: { "Content-Type": "application/json" } } ); }); const oauthSession = gatewayOAuthSession(fetchHandler);
const { listEntriesFromAppView } = await import("@/lib/thinAppViewClient"); const page = await listEntriesFromAppView({ publicationKey: "at://did:plc:alice/site.standard.publication/main", appViewScope: { authorDid: "did:plc:alice", publicationAtUri: "at://did:plc:alice/site.standard.publication/main", publicationScopeAtUris: [ "at://did:plc:alice/com.standard.publication/main", ], publicationSiteUrls: ["https://example.offprint.app"], }, filter: "unread", oauthSession, });
expect(page.entries).toHaveLength(1); expect(page.entries[0]?.title).toBe("Indexed"); expect(page.cursor).toBe("next-cursor"); expect(fetchHandler).toHaveBeenCalledTimes(1); });
it("listEntriesFromAppView sends maxEntries instead of cursor", async () => { const fetchHandler = mock(async (url: string) => { expect(url).toContain("maxEntries=120"); expect(url).not.toContain("cursor="); return new Response( JSON.stringify({ entries: [], cursor: "more" }), { status: 200, headers: { "Content-Type": "application/json" } } ); }); const oauthSession = gatewayOAuthSession(fetchHandler);
const { listEntriesFromAppView } = await import("@/lib/thinAppViewClient"); await listEntriesFromAppView({ publicationKey: "at://did:plc:alice/site.standard.publication/main", appViewScope: { authorDid: "did:plc:alice", publicationAtUri: "at://did:plc:alice/site.standard.publication/main", publicationScopeAtUris: [], publicationSiteUrls: [], }, maxEntries: 120, oauthSession, }); expect(fetchHandler).toHaveBeenCalledTimes(1); });
it("normalizes numeric Swift dates returned by the aggregate feed", async () => { const fetchHandler = mock(async (url: string) => { expect(url).toContain("/xrpc/app.thesocialwire.appview.getFeed?"); return new Response( JSON.stringify({ entries: [ { entryId: "at://did:plc:alice/site.standard.document/entry1", title: "Indexed", publishedAt: 725_760_000, isRead: false, }, ], }), { status: 200, headers: { "Content-Type": "application/json" } } ); }); const oauthSession = gatewayOAuthSession(fetchHandler);
const { listAggregateFeedFromAppView } = await import( "@/lib/thinAppViewClient" ); const page = await listAggregateFeedFromAppView({ feed: { kind: "subscribed" }, oauthSession, });
expect(page.entries[0]?.publishedAt).toBe("2024-01-01T00:00:00.000Z"); });
it("getEntryFromAppView fetches entry detail from gateway", async () => { const fetchHandler = mock(async (url: string) => { expect(url).toContain("/xrpc/app.thesocialwire.appview.getEntry?"); expect(url).toContain("entryId="); return new Response( JSON.stringify({ entryId: "at://did:plc:alice/site.standard.document/entry1", title: "Detail", summary: "Detail summary", publishedAt: "2024-01-01T00:00:00.000Z", thumbnailUrl: "https://cdn.example/detail.jpg", thumbnailFallbackUrl: "https://cdn.example/detail-fallback.jpg", contentHtml: "<p>Hi</p>", }), { status: 200, headers: { "Content-Type": "application/json" } } ); }); const oauthSession = gatewayOAuthSession(fetchHandler);
const { getEntryFromAppView } = await import("@/lib/thinAppViewClient"); const entry = await getEntryFromAppView( oauthSession, "at://did:plc:alice/site.standard.document/entry1" ); expect(entry?.title).toBe("Detail"); expect(entry?.summary).toBe("Detail summary"); expect(entry?.thumbnailUrl).toBe("https://cdn.example/detail.jpg"); expect(entry?.thumbnailFallbackUrl).toBe( "https://cdn.example/detail-fallback.jpg" ); expect(fetchHandler).toHaveBeenCalledTimes(1); });
it.each(["publication", "aggregate", "detail"] as const)("preserves recognized content labels through the %s mapping without changing legacy responses", async kind => { const api = await import("@/lib/thinAppViewClient"); for (const contentLabels of [undefined, ["sexual", "ai-generated", "unknown", "sexual"]]) { const row = { entryId: "at://did:plc:publisher/site.standard.document/one", title: "Visible Story", contentHtml: "<p>Visible</p>", publishedAt: "2026-11-09", isRead: false, ...(contentLabels ? { contentLabels } : {}) }; const oauthSession = gatewayOAuthSession(mock(async () => Response.json(kind === "detail" ? row : { entries: [row] }))); const entry = kind === "detail" ? await api.getEntryFromAppView(oauthSession, row.entryId) : (kind === "aggregate" ? await api.listAggregateFeedFromAppView({ feed: { kind: "subscribed" }, oauthSession }) : await api.listEntriesFromAppView({ publicationKey: "publisher", appViewScope: { authorDid: "did:plc:publisher", publicationAtUri: null, publicationScopeAtUris: [], publicationSiteUrls: [] }, oauthSession })).entries[0]; expect(entry?.title).toBe("Visible Story"); if (contentLabels) expect(entry?.contentLabels).toEqual(["ai-generated", "sexual"]); else expect(entry).not.toHaveProperty("contentLabels"); } });
it("writeThroughReadMark posts subjectUri and readAt", async () => { const fetchHandler = mock(async (url: string, init?: RequestInit) => { expect(url).toBe( "https://api.example.test/xrpc/app.thesocialwire.appview.putReadMark" ); expect(init?.method).toBe("POST"); const body = JSON.parse(String(init?.body)); expect(body.subjectUri).toBe("at://did:plc:alice/site.standard.entry/rkey1"); expect(body.readAt).toBe("2024-06-01T12:00:00.000Z"); return new Response(null, { status: 200 }); }); const oauthSession = gatewayOAuthSession(fetchHandler);
const { writeThroughReadMark } = await import("@/lib/thinAppViewClient"); await writeThroughReadMark( oauthSession, "at://did:plc:alice/site.standard.entry/rkey1", "2024-06-01T12:00:00.000Z" ); expect(fetchHandler).toHaveBeenCalledTimes(1); });
it("fetchAppViewUnreadCounts returns count snapshot metadata", async () => { const fetchHandler = mock(async (url: string) => { expect(url).toContain( "/xrpc/app.thesocialwire.appview.getUnreadCounts?" ); const request = new URL(url); expect(request.searchParams.getAll("publicationIds")).toEqual([ "did:plc:alice", "at://did:plc:alice/site.standard.publication/main", ]); return new Response( JSON.stringify({ counts: { "did:plc:alice": 2 }, generation: 42, accuracy: "exact", countedAt: "2026-01-01T00:00:00.000Z", }), { status: 200, headers: { "Content-Type": "application/json" } } ); }); const oauthSession = gatewayOAuthSession(fetchHandler);
const { fetchAppViewUnreadCounts } = await import("@/lib/thinAppViewClient"); const snapshot = await fetchAppViewUnreadCounts( oauthSession, [ "did:plc:alice", "at://did:plc:alice/site.standard.publication/main", ] ); expect(snapshot.counts["did:plc:alice"]).toBe(2); expect(snapshot.generation).toBe(42); expect(snapshot.accuracy).toBe("exact"); });
it("fetchAppViewUnreadCounts splits long ID lists into URL-safe requests and merges them", async () => { const publicationIds = Array.from( { length: 120 }, (_, index) => `rss:${"https://publisher.example/feeds/".repeat(3)}${index}.xml` ); const requested: string[][] = []; const fetchHandler = mock(async (url: string) => { expect(url.length).toBeLessThan(7_000); const ids = new URL(url).searchParams.getAll("publicationIds"); requested.push(ids); return Response.json({ counts: Object.fromEntries(ids.map((id) => [id, 1])), generation: requested.length, accuracy: requested.length === 1 ? "estimated" : "exact", countedAt: `2026-01-0${requested.length}T00:00:00.000Z`, }); }); const oauthSession = gatewayOAuthSession(fetchHandler);
const { fetchAppViewUnreadCounts } = await import("@/lib/thinAppViewClient"); const snapshot = await fetchAppViewUnreadCounts(oauthSession, publicationIds);
expect(requested.length).toBeGreaterThan(1); expect(requested.flat().sort()).toEqual([...publicationIds].sort()); expect(Object.keys(snapshot.counts).length).toBe(publicationIds.length); expect(snapshot.generation).toBe(requested.length); expect(snapshot.accuracy).toBe("estimated"); expect(snapshot.countedAt).toBe("2026-01-01T00:00:00.000Z"); });
it("fetchAppViewUnreadCounts keeps at most two chunk requests in flight", async () => { const publicationIds = Array.from( { length: 400 }, (_, index) => `rss:${"https://publisher.example/feeds/".repeat(3)}${index}.xml` ); let inFlight = 0; let peak = 0; let requests = 0; const fetchHandler = mock(async (url: string) => { requests++; peak = Math.max(peak, ++inFlight); await new Promise((resolve) => setTimeout(resolve, 5)); inFlight--; const ids = new URL(url).searchParams.getAll("publicationIds"); return Response.json({ counts: Object.fromEntries(ids.map((id) => [id, 1])) }); }); const oauthSession = gatewayOAuthSession(fetchHandler);
const { fetchAppViewUnreadCounts } = await import("@/lib/thinAppViewClient"); const snapshot = await fetchAppViewUnreadCounts(oauthSession, publicationIds);
expect(requests).toBeGreaterThan(3); expect(peak).toBe(2); expect(Object.keys(snapshot.counts).length).toBe(publicationIds.length); });});
function gatewayOAuthSession( gatewayHandler: (url: string, init?: RequestInit) => Promise<Response>) { globalThis.fetch = (async (url: string, init?: RequestInit) => { const request = new URL(url); if (request.pathname === "/xrpc/app.thesocialwire.appview.listEntries" && request.searchParams.get("authorDid") === "did:plc:viewer" && request.searchParams.get("limit") === "1") { expect(request.searchParams.size).toBe(2); return Response.json({}, { headers: { "X-ATProto-Session-Attestation-Receipt": "reader-receipt" } }); } return gatewayHandler(url, init); }) as unknown as typeof fetch; const nonces = new Map<string, string>(); let nonceIndex = 0; return { did: "did:plc:viewer", getTokenSet: async () => ({ access_token: "access-token", token_type: "DPoP", }), getTokenInfo: async () => ({ aud: "https://pds.example" }), fetchHandler: async () => { const nonce = `pds-nonce-${++nonceIndex}`; nonces.set("https://pds.example", nonce); return new Response(JSON.stringify({ records: [] }), { headers: { "DPoP-Nonce": nonce }, }); }, server: { dpopKey: { bareJwk: { kty: "EC", crv: "P-256", x: "x", y: "y" }, algorithms: ["ES256"], createJwt: async () => "dpop-proof", }, dpopNonces: { get: async (origin: string) => nonces.get(origin), set: async (origin: string, nonce: string) => { nonces.set(origin, nonce); }, }, serverMetadata: { dpop_signing_alg_values_supported: ["ES256"] }, }, } as never;}