import * 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: "
Hi
", }), { 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: "Visible
", 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