import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { api, apiFetch, hasServerBase, setApiBase, setAuthToken, setUnauthorizedHandler, } from './api'; // isNativeShell()/hasServerBase() key off window.__TAURI_INTERNALS__. function setShell(on: boolean): void { if (on) (window as unknown as Record).__TAURI_INTERNALS__ = {}; else delete (window as unknown as Record).__TAURI_INTERNALS__; } function jsonResponse(body: unknown, init?: { ok?: boolean; status?: number }) { return { ok: init?.ok ?? true, status: init?.status ?? 200, json: vi.fn().mockResolvedValue(body), } as unknown as Response; } describe('api', () => { beforeEach(() => { globalThis.fetch = vi.fn(); }); afterEach(() => { vi.restoreAllMocks(); }); describe('get', () => { it('returns Ok(parsed JSON) on a 200 response', async () => { const payload = { id: '1', name: 'Denis' }; vi.mocked(fetch).mockResolvedValue(jsonResponse(payload)); const result = await api.get('/api/thing'); expect(result.isOk()).toBe(true); expect(result._unsafeUnwrap()).toEqual(payload); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/thing'); expect(init?.credentials).toBe('include'); }); }); describe('base url and token', () => { afterEach(() => { setApiBase(''); setAuthToken(null); }); it('prefixes paths with the configured base and sends the bearer token', async () => { setApiBase('https://synapse.example/'); setAuthToken('tok-123'); vi.mocked(fetch).mockResolvedValue(jsonResponse({})); await api.get('/api/thing'); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('https://synapse.example/api/thing'); expect((init?.headers as Record).Authorization).toBe('Bearer tok-123'); }); it('keeps relative paths and sends no Authorization header by default', async () => { vi.mocked(fetch).mockResolvedValue(jsonResponse({})); await api.post('/api/thing', {}); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/thing'); expect((init?.headers as Record).Authorization).toBeUndefined(); }); }); describe('post', () => { it('sends the body as JSON with method POST and the right Content-Type header', async () => { const body = { title: 'hello' }; const responseBody = { ok: true }; vi.mocked(fetch).mockResolvedValue(jsonResponse(responseBody)); const result = await api.post('/api/create', body); expect(result._unsafeUnwrap()).toEqual(responseBody); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/create'); expect(init?.method).toBe('POST'); expect((init?.headers as Record)['Content-Type']).toBe('application/json'); expect(init?.body).toBe(JSON.stringify(body)); }); it('sends an empty object body when none is provided', async () => { vi.mocked(fetch).mockResolvedValue(jsonResponse({})); await api.post('/api/create'); const [, init] = vi.mocked(fetch).mock.calls[0]; expect(init?.body).toBe(JSON.stringify({})); }); }); describe('put', () => { it('uses the PUT method and JSON body', async () => { const body = { name: 'updated' }; vi.mocked(fetch).mockResolvedValue(jsonResponse({ done: true })); await api.put('/api/item/1', body); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/item/1'); expect(init?.method).toBe('PUT'); expect((init?.headers as Record)['Content-Type']).toBe('application/json'); expect(init?.body).toBe(JSON.stringify(body)); }); }); describe('del', () => { it('uses the DELETE method', async () => { // A 204 response has no JSON body; parse() short-circuits to null. vi.mocked(fetch).mockResolvedValue({ ok: true, status: 204, json: vi.fn(), } as unknown as Response); const result = await api.del('/api/item/1'); expect(result._unsafeUnwrap()).toBeNull(); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/item/1'); expect(init?.method).toBe('DELETE'); }); }); describe('upload', () => { it('POSTs FormData without a JSON Content-Type header', async () => { const form = new FormData(); form.append('file', 'x'); const responseBody = { uploaded: true }; vi.mocked(fetch).mockResolvedValue(jsonResponse(responseBody)); const result = await api.upload('/api/upload', form); expect(result._unsafeUnwrap()).toEqual(responseBody); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/upload'); expect(init?.method).toBe('POST'); expect(init?.body).toBe(form); expect((init?.headers as Record)['Content-Type']).toBeUndefined(); }); }); describe('error handling', () => { it('returns Err with the message from the JSON body on a non-ok response', async () => { vi.mocked(fetch).mockResolvedValue( jsonResponse({ error: 'Not found' }, { ok: false, status: 404 }), ); const result = await api.get('/api/missing'); expect(result.isErr()).toBe(true); expect(result._unsafeUnwrapErr()).toMatchObject({ message: 'Not found', status: 404 }); }); it('falls back to a status-based message when the body is not JSON', async () => { vi.mocked(fetch).mockResolvedValue({ ok: false, status: 400, json: vi.fn().mockRejectedValue(new Error('not json')), } as unknown as Response); const result = await api.post('/api/bad', {}); expect(result._unsafeUnwrapErr()).toMatchObject({ message: 'Error 400', status: 400 }); }); it('carries the status on the Err for put and del as well', async () => { vi.mocked(fetch).mockResolvedValue( jsonResponse({ error: 'Forbidden' }, { ok: false, status: 403 }), ); expect((await api.put('/api/x', {}))._unsafeUnwrapErr()).toMatchObject({ status: 403 }); expect((await api.del('/api/x'))._unsafeUnwrapErr()).toMatchObject({ status: 403 }); }); }); describe('401 handling', () => { afterEach(() => setUnauthorizedHandler(() => {})); // reset the shared handler it('fires the unauthorized handler on a 401 from the fetch path', async () => { const onUnauthorized = vi.fn(); setUnauthorizedHandler(onUnauthorized); vi.mocked(fetch).mockResolvedValue( jsonResponse({ error: 'Authentication required' }, { ok: false, status: 401 }), ); const result = await api.get('/api/courses'); expect(result._unsafeUnwrapErr().status).toBe(401); expect(onUnauthorized).toHaveBeenCalledTimes(1); }); it('does NOT fire the handler on other error statuses', async () => { const onUnauthorized = vi.fn(); setUnauthorizedHandler(onUnauthorized); vi.mocked(fetch).mockResolvedValue( jsonResponse({ error: 'nope' }, { ok: false, status: 403 }), ); const result = await api.get('/api/courses'); expect(result._unsafeUnwrapErr().status).toBe(403); expect(onUnauthorized).not.toHaveBeenCalled(); }); it('does NOT fire the handler when a post opts out (401 as a domain answer)', async () => { const onUnauthorized = vi.fn(); setUnauthorizedHandler(onUnauthorized); vi.mocked(fetch).mockResolvedValue( jsonResponse({ error: 'The current password is incorrect' }, { ok: false, status: 401 }), ); const result = await api.post( '/api/auth/password', { currentPassword: 'x', newPassword: 'y' }, { handleUnauthorized: false }, ); expect(result._unsafeUnwrapErr().status).toBe(401); expect(onUnauthorized).not.toHaveBeenCalled(); }); it('fires the unauthorized handler on a 401 from the XHR upload path', async () => { const onUnauthorized = vi.fn(); setUnauthorizedHandler(onUnauthorized); // Minimal XMLHttpRequest stand-in: send() invokes onload with a 401. class FakeXhr { status = 401; response: unknown = { error: 'Authentication required' }; upload = { onprogress: null as ((e: ProgressEvent) => void) | null }; onload: (() => void) | null = null; onerror: (() => void) | null = null; open() {} set responseType(_v: string) {} send() { this.onload?.(); } } const original = globalThis.XMLHttpRequest; globalThis.XMLHttpRequest = FakeXhr as unknown as typeof XMLHttpRequest; try { const result = await api.uploadWithProgress('/api/documents', new FormData(), () => {}); expect(result._unsafeUnwrapErr().status).toBe(401); expect(onUnauthorized).toHaveBeenCalledTimes(1); } finally { globalThis.XMLHttpRequest = original; } }); }); describe('hasServerBase', () => { afterEach(() => { setShell(false); setApiBase(''); }); it('is true in the browser (same-origin relative paths work)', () => { setShell(false); expect(hasServerBase()).toBe(true); }); it('is false in a native shell with no configured base', () => { setShell(true); setApiBase(''); expect(hasServerBase()).toBe(false); }); it('is true in a native shell once a base is configured', () => { setShell(true); setApiBase('https://synapse.example'); expect(hasServerBase()).toBe(true); }); }); describe('apiFetch', () => { afterEach(() => setAuthToken(null)); it('fetches with credentials and no JSON content-type, merging caller headers', async () => { vi.mocked(fetch).mockResolvedValue(jsonResponse({})); await apiFetch('/api/blob', { headers: { 'X-Test': '1' } }); const [url, init] = vi.mocked(fetch).mock.calls[0]; expect(url).toBe('/api/blob'); expect(init?.credentials).toBe('include'); const headers = init?.headers as Record; expect(headers['Content-Type']).toBeUndefined(); expect(headers['X-Test']).toBe('1'); }); it('adds the bearer token when one is set', async () => { setAuthToken('tok-xyz'); vi.mocked(fetch).mockResolvedValue(jsonResponse({})); await apiFetch('/api/blob'); const [, init] = vi.mocked(fetch).mock.calls[0]; expect((init?.headers as Record).Authorization).toBe('Bearer tok-xyz'); }); }); describe('uploadWithProgress', () => { it('reports computable progress and resolves on a 2xx', async () => { const seen: number[] = []; // send() drives one progress event then a 201 onload. class FakeXhr { status = 201; response: unknown = { id: 'doc-1' }; upload = { onprogress: null as ((e: ProgressEvent) => void) | null }; onload: (() => void) | null = null; onerror: (() => void) | null = null; open() {} setRequestHeader() {} set responseType(_v: string) {} set withCredentials(_v: boolean) {} send() { this.upload.onprogress?.({ lengthComputable: true, loaded: 50, total: 200, } as ProgressEvent); // A non-computable event is ignored (no NaN percent). this.upload.onprogress?.({ lengthComputable: false, loaded: 0, total: 0, } as ProgressEvent); this.onload?.(); } } const original = globalThis.XMLHttpRequest; globalThis.XMLHttpRequest = FakeXhr as unknown as typeof XMLHttpRequest; try { const result = await api.uploadWithProgress<{ id: string }>( '/api/documents', new FormData(), (p) => seen.push(p), ); expect(result._unsafeUnwrap()).toEqual({ id: 'doc-1' }); expect(seen).toEqual([25]); } finally { globalThis.XMLHttpRequest = original; } }); it('rejects with a network error when the transfer errors', async () => { class FakeXhr { status = 0; response: unknown = null; upload = { onprogress: null }; onload: (() => void) | null = null; onerror: (() => void) | null = null; open() {} setRequestHeader() {} set responseType(_v: string) {} set withCredentials(_v: boolean) {} send() { this.onerror?.(); } } const original = globalThis.XMLHttpRequest; globalThis.XMLHttpRequest = FakeXhr as unknown as typeof XMLHttpRequest; try { const result = await api.uploadWithProgress('/api/documents', new FormData(), () => {}); expect(result._unsafeUnwrapErr()).toMatchObject({ message: 'Network error', status: 0 }); } finally { globalThis.XMLHttpRequest = original; } }); }); });