Files
vue-chat-layer/app/lib/client.ts
Jakub Zych 269c75b5dd feat: threads, pins, reactions, attachments, link embeds and the command picker
- threads: reply counts, ChatThreadPane with replies, live replies and thread mute
- channel pins in ChatPinsPanel; a refused pin hides the action for the session
- reactions, attachments with upload progress and bearer downloads, inline edits, the delete dialog (moderators also in channels)
- link cards with the registerEmbedRenderer registry; linkify for escaped text
- slash commands: the command picker over chatbots, dispatch with sender-only answers
- slots conversation-actions (DMs only) and sidebar-footer
- chat-tokens.css and chat-base.css, EN and PL copy, README
2026-10-31 14:04:54 +01:00

383 lines
16 KiB
TypeScript

// The chat layer's HTTP client: golem15.chat (/_chat/api/v1), the host
// bootstrap ({hostApiBase}/chat), golem15.chatchannels (joins, pins) and
// golem15.chatbots (slash commands). 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,
ChatCommand,
ChatConversation,
ChatDispatchAnswer,
ChatMember,
ChatMessage,
ChatReactionsAnswer,
ChatSendBody,
ChatThreadMute,
ChatUploadAnswer,
} 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<string | null | undefined>
/** Called once a request failed with 401 and the refresh did not help. */
unauthorized?(): void
/** The caller's user id; without it the chat reads the token's numeric sub claim. */
userId?(): number | null | undefined
}
/** 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<string, string>; body?: string | FormData }) => Promise<Response>
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<string, string[]>
constructor(status: number, message: string, errors: Record<string, string[]> = {}) {
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<string, string | number | undefined | null>
body?: unknown
}
export interface MessagePage {
limit?: number
/** Only messages older than this id. */
before?: number
}
/**
* userIdFromToken reads the numeric sub claim of a JWT without verifying it
* (the server does): the chat needs the caller's id for its user:{id}
* channel and to tell its own messages apart. null for anything else.
*/
export function userIdFromToken(token: string | null | undefined): number | null {
if (!token) return null
const part = token.split('.')[1]
if (!part) return null
try {
const b64 = part.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(part.length / 4) * 4, '=')
const claims = JSON.parse(globalThis.atob(b64)) as { sub?: unknown }
const n = typeof claims.sub === 'string' ? Number(claims.sub.trim()) : claims.sub
return typeof n === 'number' && Number.isInteger(n) && n > 0 ? n : null
} catch {
return null
}
}
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<string, string[]> {
if (!v || typeof v !== 'object' || Array.isArray(v)) return {}
const out: Record<string, string[]> = {}
for (const [k, list] of Object.entries(v as Record<string, unknown>)) {
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<T>(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<string | null> | null = null
function token(): string | null {
try {
return auth.token() || null
} catch {
return null
}
}
function headers(extra: Record<string, string> = {}): Record<string, string> {
const h: Record<string, string> = { 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<string | null> {
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<Response>): Promise<Response> {
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<unknown> {
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<T>(url: string, o: RequestOptions = {}): Promise<T> {
const res = await authorized(() => {
const init: Parameters<ChatFetch>[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<T>(json)
}
const chat = (path: string) => joinUrl(bases.chat, path)
/** Bytes of an authorized GET, with the same refresh as request. */
async function blob(url: string): Promise<Blob> {
const res = await authorized(() => doFetch(url, { method: 'GET', headers: headers({ Accept: '*/*' }) }))
if (!res.ok) throw toError(res.status, await parse(res))
return res.blob()
}
/**
* One multipart upload of a file as the field `file`. With XMLHttpRequest
* (browsers) it reports progress and honours the abort signal; elsewhere
* it falls back to fetch without progress.
*/
function sendUpload(url: string, file: File, onProgress?: (percent: number) => void, signal?: AbortSignal): Promise<ChatUploadAnswer> {
const finish = (status: number, json: unknown): ChatUploadAnswer => {
const body = unwrap<Partial<ChatUploadAnswer> | null>(json)
if (status >= 200 && status < 300 && body && typeof body.id === 'number') {
return { id: body.id, filename: String(body.filename ?? file.name), size: Number(body.size ?? file.size) }
}
throw toError(status, json)
}
if (typeof XMLHttpRequest === 'undefined') {
const form = new FormData()
form.append('file', file, file.name)
return doFetch(url, { method: 'POST', headers: headers(), body: form }).then(async (res) => finish(res.status, await parse(res)))
}
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('POST', url)
for (const [k, v] of Object.entries(headers())) xhr.setRequestHeader(k, v)
xhr.upload.onprogress = (e) => {
if (e.lengthComputable && e.total > 0) onProgress?.(Math.min(100, Math.round((e.loaded / e.total) * 100)))
}
xhr.onload = () => {
let json: unknown = null
try {
json = xhr.responseText ? JSON.parse(xhr.responseText) : null
} catch {
json = null
}
try {
resolve(finish(xhr.status, json))
} catch (e) {
reject(e)
}
}
xhr.onerror = () => reject(new ChatApiError(0, 'network error'))
xhr.onabort = () => reject(new ChatApiError(0, 'aborted'))
if (signal) {
if (signal.aborted) {
reject(new ChatApiError(0, 'aborted'))
return
}
signal.addEventListener('abort', () => xhr.abort(), { once: true })
}
const form = new FormData()
form.append('file', file, file.name)
xhr.send(form)
})
}
/** The upload, with one refresh-and-retry on 401. */
async function upload(file: File, onProgress?: (percent: number) => void, signal?: AbortSignal): Promise<ChatUploadAnswer> {
const url = chat('/attachments')
const used = token()
try {
return await sendUpload(url, file, onProgress, signal)
} catch (e) {
if (!(e instanceof ChatApiError) || e.status !== 401 || !used || signal?.aborted) throw e
const renewed = await refresh()
if (!renewed) {
auth.unauthorized?.()
throw e
}
onProgress?.(0)
return sendUpload(url, file, onProgress, signal)
}
}
const channels = (context: { type: string; id: number }, path: string) =>
joinUrl(bases.channels, `/contexts/${encodeURIComponent(context.type)}/${context.id}${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<ChatBootstrap>(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<ChatConversation>(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<ChatMessage[]>(chat(`/conversations/${conversationId}/messages`), { query: { limit, before } }),
/** 201 with the message itself. */
send: (conversationId: number, body: ChatSendBody) =>
request<ChatMessage>(chat(`/conversations/${conversationId}/messages`), { method: 'POST', body }),
/** One message (content for a created event, which carries ids only). */
message: (id: number) => request<ChatMessage>(chat(`/messages/${id}`)),
/** Marks a conversation read up to now; golem15.chat tells the other participants. */
markRead: (conversationId: number) => request<unknown>(chat(`/conversations/${conversationId}/read`), { method: 'POST' }),
/** Emits typing.chat.message on the conversation channel. */
typing: (conversationId: number) => request<unknown>(chat(`/conversations/${conversationId}/typing`), { method: 'POST' }),
/** Finds or creates the DM with a member of the context (chat-dm bucket, 10/min). */
startDm: (context: { type: string; id: number }, userId: number) =>
request<ChatConversation>(chat(`/contexts/${encodeURIComponent(context.type)}/${context.id}/dm`), { method: 'POST', body: { user_id: userId } }),
/** Joins a public channel of the context (golem15.chatchannels). */
joinChannel: (context: { type: string; id: number }, channelId: number) =>
request<unknown>(channels(context, `/channels/${channelId}/join`), { method: 'POST' }),
/** Leaves a channel; it stays listed with joined false. */
leaveChannel: (context: { type: string; id: number }, channelId: number) =>
request<unknown>(channels(context, `/channels/${channelId}/leave`), { method: 'POST' }),
/** The ids of a channel's pinned messages. */
pins: (context: { type: string; id: number }, channelId: number) =>
request<{ pins?: number[] }>(channels(context, `/channels/${channelId}/pins`)).then((r) => (Array.isArray(r?.pins) ? r.pins : [])),
/** Pins a message of the channel (refused unless the host allows the caller). */
pin: (context: { type: string; id: number }, channelId: number, messageId: number) =>
request<unknown>(channels(context, `/channels/${channelId}/pins`), { method: 'POST', body: { message_id: messageId } }),
unpin: (context: { type: string; id: number }, channelId: number, messageId: number) =>
request<unknown>(channels(context, `/channels/${channelId}/pins/${messageId}`), { method: 'DELETE' }),
/** Edits your own text message; answers the message. */
edit: (id: number, content: string) => request<ChatMessage>(chat(`/messages/${id}`), { method: 'PUT', body: { content } }),
/** Deletes a message: your own, or someone else's for a channel moderator. */
remove: (id: number) => request<{ deleted: boolean }>(chat(`/messages/${id}`), { method: 'DELETE' }),
/** The allowed reaction keys in display order. */
reactions: () => request<string[]>(chat('/reactions')),
/** Adds the user's reaction (idempotent); answers the message's reactions after the change. */
addReaction: (id: number, key: string) => request<ChatReactionsAnswer>(chat(`/messages/${id}/reactions`), { method: 'POST', body: { key } }),
/** Removes the user's reaction; the key is one path segment, so it is encoded. */
removeReaction: (id: number, key: string) =>
request<ChatReactionsAnswer>(chat(`/messages/${id}/reactions/${encodeURIComponent(key)}`), { method: 'DELETE' }),
/** A thread's replies, oldest first. */
replies: (rootId: number) => request<ChatMessage[]>(chat(`/messages/${rootId}/replies`)),
/** Posts a reply in a thread; answers the reply. */
reply: (rootId: number, body: ChatSendBody) => request<ChatMessage>(chat(`/messages/${rootId}/replies`), { method: 'POST', body }),
/** Mutes or unmutes a thread for the caller. */
muteThread: (rootId: number, muted: boolean) => request<ChatThreadMute>(chat(`/threads/${rootId}/mute`), { method: 'PUT', body: { muted } }),
/** Uploads one pending attachment with progress. */
upload,
/** An attachment's bytes (participants only; never a public URL). */
download: (messageId: number, fileId: number) => blob(chat(`/attachments/${messageId}/${fileId}`)),
/** The slash commands available to the caller (golem15.chatbots). */
commands: () =>
request<{ commands?: ChatCommand[] }>(joinUrl(bases.bots, '/commands')).then((r) => (Array.isArray(r?.commands) ? r.commands : [])),
/** Runs a slash command; an ephemeral answer is for the sender only. 422 errors.input for an unknown one. */
dispatch: (input: string) => request<ChatDispatchAnswer>(joinUrl(bases.bots, '/dispatch'), { method: 'POST', body: { input } }),
}
}
export type ChatClient = ReturnType<typeof createChatClient>