import { describe, expect, it, vi } from 'vitest' import { ChatApiError, createChatClient, toError, userIdFromToken, type ChatFetch } from '../app/lib/client' const bases = { chat: '/_chat/api/v1', channels: '/_chatchannels/api/v1', bots: '/_chatbots/api/v1', host: '/_acme/api/v1' } const ctx = { type: 'acme', id: 1 } function json(status: number, body: unknown): Response { return new Response(body === undefined ? '' : JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) } function client(fetch: ChatFetch, auth: Parameters[0]['auth'] = { token: () => 'tok' }) { return createChatClient({ bases, auth, fetch }) } describe('createChatClient endpoints', () => { // Every method: the URL and HTTP method it calls and the JSON body. const cases: Array<{ name: string; call: (c: ReturnType) => Promise; url: string; method: string; body?: unknown; answer?: unknown }> = [ { name: 'bootstrap', call: (c) => c.bootstrap(), url: '/_acme/api/v1/chat', method: 'GET', answer: { member: false } }, { name: 'members', call: (c) => c.members(), url: '/_acme/api/v1/chat/members', method: 'GET', answer: { members: [] } }, { name: 'openConversation', call: (c) => c.openConversation('channel', 3), url: '/_chat/api/v1/contexts/channel/3/conversation', method: 'GET' }, { name: 'messages', call: (c) => c.messages(7), url: '/_chat/api/v1/conversations/7/messages?limit=50', method: 'GET', answer: { data: [] } }, { name: 'messages before', call: (c) => c.messages(7, { limit: 20, before: 99 }), url: '/_chat/api/v1/conversations/7/messages?limit=20&before=99', method: 'GET', answer: { data: [] } }, { name: 'send', call: (c) => c.send(7, { content: 'hi' }), url: '/_chat/api/v1/conversations/7/messages', method: 'POST', body: { content: 'hi' } }, { name: 'message', call: (c) => c.message(5), url: '/_chat/api/v1/messages/5', method: 'GET' }, { name: 'markRead', call: (c) => c.markRead(7), url: '/_chat/api/v1/conversations/7/read', method: 'POST' }, { name: 'typing', call: (c) => c.typing(7), url: '/_chat/api/v1/conversations/7/typing', method: 'POST' }, { name: 'startDm', call: (c) => c.startDm(ctx, 4), url: '/_chat/api/v1/contexts/acme/1/dm', method: 'POST', body: { user_id: 4 } }, { name: 'joinChannel', call: (c) => c.joinChannel(ctx, 2), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/join', method: 'POST' }, { name: 'leaveChannel', call: (c) => c.leaveChannel(ctx, 2), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/leave', method: 'POST' }, { name: 'pins', call: (c) => c.pins(ctx, 2), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/pins', method: 'GET', answer: { pins: [5] } }, { name: 'pin', call: (c) => c.pin(ctx, 2, 5), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/pins', method: 'POST', body: { message_id: 5 } }, { name: 'unpin', call: (c) => c.unpin(ctx, 2, 5), url: '/_chatchannels/api/v1/contexts/acme/1/channels/2/pins/5', method: 'DELETE' }, { name: 'edit', call: (c) => c.edit(5, 'new'), url: '/_chat/api/v1/messages/5', method: 'PUT', body: { content: 'new' } }, { name: 'remove', call: (c) => c.remove(5), url: '/_chat/api/v1/messages/5', method: 'DELETE' }, { name: 'reactions', call: (c) => c.reactions(), url: '/_chat/api/v1/reactions', method: 'GET', answer: { data: ['👍'] } }, { name: 'addReaction', call: (c) => c.addReaction(5, '👍'), url: '/_chat/api/v1/messages/5/reactions', method: 'POST', body: { key: '👍' } }, { name: 'removeReaction', call: (c) => c.removeReaction(5, '👍'), url: `/_chat/api/v1/messages/5/reactions/${encodeURIComponent('👍')}`, method: 'DELETE' }, { name: 'replies', call: (c) => c.replies(5), url: '/_chat/api/v1/messages/5/replies', method: 'GET', answer: { data: [] } }, { name: 'reply', call: (c) => c.reply(5, { content: 'r' }), url: '/_chat/api/v1/messages/5/replies', method: 'POST', body: { content: 'r' } }, { name: 'muteThread', call: (c) => c.muteThread(5, true), url: '/_chat/api/v1/threads/5/mute', method: 'PUT', body: { muted: true } }, { name: 'commands', call: (c) => c.commands(), url: '/_chatbots/api/v1/commands', method: 'GET', answer: { commands: [] } }, { name: 'dispatch', call: (c) => c.dispatch('/demo'), url: '/_chatbots/api/v1/dispatch', method: 'POST', body: { input: '/demo' } }, ] for (const tc of cases) { it(`${tc.name}: ${tc.method} ${tc.url}`, async () => { const fetch = vi.fn(async () => json(200, tc.answer ?? { id: 1 })) await tc.call(client(fetch)) expect(fetch).toHaveBeenCalledTimes(1) const [url, init] = fetch.mock.calls[0] expect(url).toBe(tc.url) expect(init.method).toBe(tc.method) expect(init.headers.Authorization).toBe('Bearer tok') expect(init.headers.Accept).toBe('application/json') if (tc.body === undefined) { expect(init.body).toBeUndefined() } else { expect(init.headers['Content-Type']).toBe('application/json') expect(JSON.parse(init.body as string)).toEqual(tc.body) } }) } it('unwraps data, members and pins and tolerates their absence', async () => { const answers: Record = { '/_chat/api/v1/conversations/1/messages?limit=50': { data: [{ id: 1 }] }, '/_acme/api/v1/chat/members': [{ id: 2 }], '/_chatchannels/api/v1/contexts/acme/1/channels/2/pins': {}, '/_chatbots/api/v1/commands': { other: true }, } const c = client(async (url) => json(200, answers[url])) await expect(c.messages(1)).resolves.toEqual([{ id: 1 }]) await expect(c.members()).resolves.toEqual([{ id: 2 }]) await expect(c.pins(ctx, 2)).resolves.toEqual([]) await expect(c.commands()).resolves.toEqual([]) }) it('sends no Authorization header without a token, and a throwing token getter counts as none', async () => { const fetch = vi.fn(async () => json(200, {})) await client(fetch, { token: () => null }).message(1) await client(fetch, { token: () => { throw new Error('no cookie') }, }).message(1) for (const call of fetch.mock.calls) expect(call[1].headers.Authorization).toBeUndefined() }) it('refuses the host routes without a host base', async () => { const fetch = vi.fn() const c = createChatClient({ bases: { ...bases, host: '' }, auth: { token: () => 'tok' }, fetch }) expect(() => c.bootstrap()).toThrow(ChatApiError) expect(fetch).not.toHaveBeenCalled() }) it('downloads attachment bytes with the bearer token', async () => { const fetch = vi.fn(async () => new Response('bytes', { status: 200 })) const blob = await client(fetch).download(5, 9) expect(await blob.text()).toBe('bytes') expect(fetch.mock.calls[0][0]).toBe('/_chat/api/v1/attachments/5/9') expect(fetch.mock.calls[0][1].headers.Authorization).toBe('Bearer tok') expect(fetch.mock.calls[0][1].headers.Accept).toBe('*/*') }) }) describe('createChatClient auth', () => { it('refreshes once on 401 and retries with the new token', async () => { let current = 'old' const refresh = vi.fn(async () => (current = 'new')) const unauthorized = vi.fn() const fetch = vi.fn().mockResolvedValueOnce(json(401, { error: 'Token expired' })).mockResolvedValueOnce(json(200, { id: 3 })) const m = await client(fetch, { token: () => current, refresh, unauthorized }).message(3) expect(m).toEqual({ id: 3 }) expect(refresh).toHaveBeenCalledTimes(1) expect(unauthorized).not.toHaveBeenCalled() expect(fetch.mock.calls.map((c) => c[1].headers.Authorization)).toEqual(['Bearer old', 'Bearer new']) }) it('calls unauthorized after a failed refresh and throws the 401', async () => { const refresh = vi.fn(async () => null) const unauthorized = vi.fn() const fetch = vi.fn(async () => json(401, { error: 'Unauthorized' })) const err = await client(fetch, { token: () => 'old', refresh, unauthorized }).message(3).catch((e) => e) expect(err).toBeInstanceOf(ChatApiError) expect(err.status).toBe(401) expect(refresh).toHaveBeenCalledTimes(1) expect(unauthorized).toHaveBeenCalledTimes(1) expect(fetch).toHaveBeenCalledTimes(1) }) it('calls unauthorized when the retry is still 401', async () => { let current = 'old' const unauthorized = vi.fn() const fetch = vi.fn(async () => json(401, {})) await expect(client(fetch, { token: () => current, refresh: async () => (current = 'new'), unauthorized }).message(1)).rejects.toMatchObject({ status: 401 }) expect(fetch).toHaveBeenCalledTimes(2) expect(unauthorized).toHaveBeenCalledTimes(1) }) it('does not refresh a request that carried no token', async () => { const refresh = vi.fn(async () => 'new') const unauthorized = vi.fn() const fetch = vi.fn(async () => json(401, {})) await expect(client(fetch, { token: () => null, refresh, unauthorized }).message(1)).rejects.toMatchObject({ status: 401 }) expect(refresh).not.toHaveBeenCalled() expect(unauthorized).not.toHaveBeenCalled() }) it('shares one refresh between concurrent 401s', async () => { let current = 'old' let release!: () => void const gate = new Promise((r) => (release = r)) const refresh = vi.fn(async () => { await gate current = 'new' return current }) const fetch = vi.fn(async (_url, init) => (init.headers.Authorization === 'Bearer new' ? json(200, { ok: true }) : json(401, {}))) const c = client(fetch, { token: () => current, refresh }) const both = Promise.all([c.message(1), c.message(2)]) await new Promise((r) => setTimeout(r, 0)) release() await expect(both).resolves.toEqual([{ ok: true }, { ok: true }]) expect(refresh).toHaveBeenCalledTimes(1) }) it('maps a network failure to status 0', async () => { const fetch = vi.fn(async () => { throw new TypeError('fetch failed') }) await expect(client(fetch).message(1)).rejects.toMatchObject({ status: 0, message: 'network error' }) }) }) describe('errors', () => { it('maps a 422 envelope to field errors', async () => { const fetch = vi.fn(async () => json(422, { error: 'Validation failed', errors: { content: ['The text contains a word that is not allowed.'] } })) const err = (await client(fetch).send(1, { content: 'x' }).catch((e) => e)) as ChatApiError expect(err).toBeInstanceOf(ChatApiError) expect(err.status).toBe(422) expect(err.message).toBe('Validation failed') expect(err.field('content')).toBe('The text contains a word that is not allowed.') expect(err.field('other')).toBe('') }) it('toError reads error, then message, else the status, and normalizes errors', () => { expect(toError(404, { error: 'Not found' }).message).toBe('Not found') expect(toError(500, { message: 'boom' }).message).toBe('boom') expect(toError(503, null).message).toBe('HTTP 503') expect(toError(503, 'text').message).toBe('HTTP 503') expect(toError(422, { errors: { a: 'one', b: ['x', 2, 'y'], c: 5 } }).errors).toEqual({ a: ['one'], b: ['x', 'y'] }) expect(toError(422, { errors: ['x'] }).errors).toEqual({}) }) it('throws on a non-JSON error body with the status', async () => { const fetch = vi.fn(async () => new Response('bad gateway', { status: 502 })) await expect(client(fetch).message(1)).rejects.toMatchObject({ status: 502, message: 'HTTP 502' }) }) }) describe('upload', () => { it('posts the file as multipart field file and answers its id, name and size', async () => { const fetch = vi.fn(async () => json(201, { id: 12, filename: 'a.png', size: 3 })) const file = new File(['abc'], 'a.png', { type: 'image/png' }) await expect(client(fetch).upload(file)).resolves.toEqual({ id: 12, filename: 'a.png', size: 3 }) const [url, init] = fetch.mock.calls[0] expect(url).toBe('/_chat/api/v1/attachments') expect(init.method).toBe('POST') expect(init.headers.Authorization).toBe('Bearer tok') expect(init.headers['Content-Type']).toBeUndefined() const form = init.body as FormData expect(form).toBeInstanceOf(FormData) expect((form.get('file') as File).name).toBe('a.png') }) it('fills a missing name and size from the file', async () => { const fetch = vi.fn(async () => json(201, { data: { id: 4 } })) await expect(client(fetch).upload(new File(['abcd'], 'b.txt'))).resolves.toEqual({ id: 4, filename: 'b.txt', size: 4 }) }) it('maps a refused upload to its field error', async () => { const fetch = vi.fn(async () => json(422, { error: 'Validation failed', errors: { file: ['too large'] } })) const err = (await client(fetch).upload(new File(['x'], 'x.bin')).catch((e) => e)) as ChatApiError expect(err.status).toBe(422) expect(err.field('file')).toBe('too large') }) it('refreshes once on 401 and uploads again', async () => { let current = 'old' const fetch = vi.fn().mockResolvedValueOnce(json(401, {})).mockResolvedValueOnce(json(201, { id: 8, filename: 'c', size: 1 })) const onProgress = vi.fn() const answer = await client(fetch, { token: () => current, refresh: async () => (current = 'new') }).upload(new File(['c'], 'c'), onProgress) expect(answer.id).toBe(8) expect(fetch.mock.calls.map((c) => c[1].headers.Authorization)).toEqual(['Bearer old', 'Bearer new']) expect(onProgress).toHaveBeenCalledWith(0) }) it('calls unauthorized when the upload cannot be renewed', async () => { const unauthorized = vi.fn() const fetch = vi.fn(async () => json(401, {})) await expect(client(fetch, { token: () => 'old', refresh: async () => null, unauthorized }).upload(new File(['c'], 'c'))).rejects.toMatchObject({ status: 401 }) expect(unauthorized).toHaveBeenCalledTimes(1) }) }) describe('userIdFromToken', () => { const token = (claims: unknown) => `h.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.s` it('reads a numeric sub, as a number or a string', () => { expect(userIdFromToken(token({ sub: 42 }))).toBe(42) expect(userIdFromToken(token({ sub: ' 7 ' }))).toBe(7) }) it('answers null for anything else', () => { for (const t of [null, undefined, '', 'x', 'a.b.c', token({}), token({ sub: 'ada' }), token({ sub: 0 }), token({ sub: -3 }), token({ sub: 1.5 })]) { expect(userIdFromToken(t)).toBeNull() } }) })