import { afterEach, describe, expect, it, vi } from 'vitest' import { fetchThread } from './thread' const ROOT = 'at://did:plc:root/app.bsky.feed.post/3kroot' const author = (n: string) => ({ did: `did:plc:${n}`, handle: `${n}.example.com`, displayName: n, avatar: `https://cdn.example.com/${n}.png`, }) const post = (n: string, replies: unknown[] = []) => ({ $type: 'app.bsky.feed.defs#threadViewPost', post: { uri: `at://did:plc:${n}/app.bsky.feed.post/3k${n}`, author: author(n), record: { $type: 'app.bsky.feed.post', text: `hello from ${n}` }, likeCount: 2, repostCount: 1, replyCount: replies.length, }, replies, }) function stub(thread: unknown) { const fetchMock = vi.fn( async (_input: string) => new Response(JSON.stringify({ thread }), { status: 200 }), ) vi.stubGlobal('fetch', fetchMock) return fetchMock } afterEach(() => { vi.unstubAllGlobals() }) describe('fetchThread', () => { it('maps the root and its replies, with a budget and a depth', async () => { const nested = post('grandchild') const child = post('child', [nested]) const root = post('root', Array.from({ length: 6 }, (_, i) => post(`r${i}`, [child]))) stub(root) const view = await fetchThread({ uri: ROOT }) expect(view?.root.author.handle).toBe('root.example.com') expect(view?.root.text).toBe('hello from root') // The root keeps at most five replies; the sixth is why `more` is true. expect(view?.root.replies).toHaveLength(5) expect(view?.more).toBe(true) // Each child keeps its own child, and the grandchild's replies stop there. expect(view?.root.replies[0]?.replies).toHaveLength(1) expect(view?.root.replies[0]?.replies[0]?.replies).toHaveLength(0) }) it('asks the public appview for two levels below the root', async () => { const fetchMock = stub(post('root')) await fetchThread({ uri: ROOT }) const url = new URL(String(fetchMock.mock.calls[0]?.[0])) expect(url.origin + url.pathname).toBe( 'https://public.api.bsky.app/xrpc/app.bsky.feed.getPostThread', ) expect(url.searchParams.get('uri')).toBe(ROOT) expect(url.searchParams.get('depth')).toBe('2') expect(url.searchParams.get('parentHeight')).toBe('0') }) it('answers null when the thread has no drawable root', async () => { stub({ $type: 'app.bsky.feed.defs#notFoundPost', uri: ROOT, notFound: true }) await expect(fetchThread({ uri: ROOT })).resolves.toBeNull() }) it('skips nodes that are not thread views', async () => { const root = post('root', [ { $type: 'app.bsky.feed.defs#blockedPost', uri: 'at://blocked', blocked: true }, { $type: 'app.bsky.feed.defs#notFoundPost', uri: 'at://gone', notFound: true }, post('kept'), ]) stub(root) const view = await fetchThread({ uri: ROOT }) expect(view?.root.replies.map((r) => r.author.handle)).toEqual(['kept.example.com']) }) it('lets a failed request reach the caller', async () => { vi.stubGlobal( 'fetch', vi.fn(async () => new Response('no', { status: 503, statusText: 'Unavailable' })), ) await expect(fetchThread({ uri: ROOT })).rejects.toThrow() }) })