// The chat layer's HTTP client: golem15.chat (/_chat/api/v1), the host // bootstrap ({hostApiBase}/chat), and later chatchannels and chatbots. Pure // and Nuxt-free, so tests drive it with a stub fetch; useChatApi binds it to // runtime config and the app's $chatAuth hook. // // Every request carries `Authorization: Bearer {auth.token()}`. A 401 on a // request that carried a token refreshes once through auth.refresh() (one // refresh at a time; concurrent 401s share it) and retries; a second 401, or // a refresh that yields no token, calls auth.unauthorized(). The layer never // stores the token. import type { ChatBootstrap, ChatConversation, ChatMember, ChatMessage, ChatSendBody, } from './types' /** The app's auth hook ($chatAuth): the user's JWT, its renewal and the signed-out callback. */ export interface ChatAuth { token(): string | null | undefined /** Renews the token and answers the new one, or null when the session cannot be renewed. */ refresh?(): Promise /** Called once a request failed with 401 and the refresh did not help. */ unauthorized?(): void } /** The API bases: same-origin paths in the browser. */ export interface ChatBases { /** golem15.chat, e.g. /_chat/api/v1. */ chat: string /** golem15.chatchannels, e.g. /_chatchannels/api/v1. */ channels: string /** golem15.chatbots, e.g. /_chatbots/api/v1. */ bots: string /** The host's bootstrap routes ({host}/chat, {host}/chat/members). */ host: string } export type ChatFetch = (url: string, init: { method: string; headers: Record; body?: string | FormData }) => Promise export interface ChatClientOptions { bases: ChatBases auth: ChatAuth fetch?: ChatFetch } /** A refused request: the HTTP status (0 without a connection), the message and the 422 field errors. */ export class ChatApiError extends Error { status: number errors: Record constructor(status: number, message: string, errors: Record = {}) { super(message) this.name = 'ChatApiError' this.status = status this.errors = errors } /** The first error of a field, or ''. */ field(name: string): string { return this.errors[name]?.[0] ?? '' } } export interface RequestOptions { method?: string query?: Record body?: unknown } export interface MessagePage { limit?: number /** Only messages older than this id. */ before?: number } function joinUrl(base: string, path: string): string { return `${base.replace(/\/+$/, '')}${path}` } function withQuery(url: string, query?: RequestOptions['query']): string { if (!query) return url const qs = new URLSearchParams() for (const [k, v] of Object.entries(query)) { if (v !== undefined && v !== null && v !== '') qs.set(k, String(v)) } const s = qs.toString() return s ? `${url}?${s}` : url } function errorsOf(v: unknown): Record { if (!v || typeof v !== 'object' || Array.isArray(v)) return {} const out: Record = {} for (const [k, list] of Object.entries(v as Record)) { if (Array.isArray(list)) out[k] = list.filter((x): x is string => typeof x === 'string') else if (typeof list === 'string') out[k] = [list] } return out } /** toError maps an error body ({"error": msg, "errors": {field: [msg]}}) to a ChatApiError. */ export function toError(status: number, json: unknown): ChatApiError { const j = (json && typeof json === 'object' ? json : {}) as { error?: unknown; message?: unknown; errors?: unknown } const msg = (typeof j.error === 'string' && j.error) || (typeof j.message === 'string' && j.message) || `HTTP ${status}` return new ChatApiError(status, msg, errorsOf(j.errors)) } /** The payload: `data` of a wrapped body, the body itself otherwise. */ function unwrap(json: unknown): T { if (json && typeof json === 'object' && !Array.isArray(json) && 'data' in json) return (json as { data: T }).data return json as T } export function createChatClient(opts: ChatClientOptions) { const { bases, auth } = opts const doFetch: ChatFetch = opts.fetch ?? ((url, init) => fetch(url, init)) let refreshing: Promise | null = null function token(): string | null { try { return auth.token() || null } catch { return null } } function headers(extra: Record = {}): Record { const h: Record = { Accept: 'application/json', ...extra } const t = token() if (t) h.Authorization = `Bearer ${t}` return h } /** One refresh at a time; concurrent 401s share it. */ function refresh(): Promise { if (!refreshing) { refreshing = (async () => { try { return (await auth.refresh?.()) || null } catch { return null } finally { // Cleared after the awaiting callers resumed. queueMicrotask(() => { refreshing = null }) } })() } return refreshing } /** send, then one refresh-and-retry on 401 for a request that carried a token. */ async function authorized(send: () => Promise): Promise { const used = token() let res: Response try { res = await send() } catch { throw new ChatApiError(0, 'network error') } if (res.status !== 401 || !used) return res // Another request may have refreshed the token meanwhile: just retry. const current = token() const renewed = current && current !== used ? current : await refresh() if (renewed) { try { res = await send() } catch { throw new ChatApiError(0, 'network error') } } if (res.status === 401) auth.unauthorized?.() return res } async function parse(res: Response): Promise { const text = await res.text() if (!text) return null try { return JSON.parse(text) } catch { return null } } /** The parsed payload of a JSON request against a full URL. */ async function request(url: string, o: RequestOptions = {}): Promise { const res = await authorized(() => { const init: Parameters[1] = { method: o.method ?? 'GET', headers: headers() } if (o.body !== undefined) { init.headers['Content-Type'] = 'application/json' init.body = JSON.stringify(o.body) } return doFetch(withQuery(url, o.query), init) }) const json = await parse(res) if (!res.ok) throw toError(res.status, json) return unwrap(json) } const chat = (path: string) => joinUrl(bases.chat, path) const host = (path: string) => { if (!bases.host) throw new ChatApiError(0, 'public.chat.hostApiBase is not set') return joinUrl(bases.host, path) } return { request, /** GET {host}/chat: membership, channels, DMs and limits. */ bootstrap: () => request(host('/chat')), /** GET {host}/chat/members: the other members (pickers and mentions). */ members: () => request<{ members: ChatMember[] } | ChatMember[]>(host('/chat/members')).then((r) => (Array.isArray(r) ? r : (r?.members ?? []))), /** The conversation of a context; opening a channel's makes the caller a participant. */ openConversation: (type: string, id: number) => request(chat(`/contexts/${encodeURIComponent(type)}/${id}/conversation`)), /** A page of messages (thread roots and plain messages), oldest first. */ messages: (conversationId: number, { limit = 50, before }: MessagePage = {}) => request(chat(`/conversations/${conversationId}/messages`), { query: { limit, before } }), /** 201 with the message itself. */ send: (conversationId: number, body: ChatSendBody) => request(chat(`/conversations/${conversationId}/messages`), { method: 'POST', body }), } } export type ChatClient = ReturnType