feat: chat layer tracer: bootstrap, channel list, messages, composer

- createChatClient: bearer auth, one refresh-and-retry on 401, 422 field errors
- useChat over useState: host bootstrap, open a channel, send
- ChatPage, ChatChannelList, ChatMessageList, ChatComposer
- runtime config chat.apiBase, public.chat.{apiBase,channelsApiBase,botsApiBase,hostApiBase}
This commit is contained in:
Jakub Zych
2026-10-31 13:40:39 +01:00
commit fa6f9950a6
21 changed files with 9328 additions and 0 deletions

7
.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
node_modules/
.nuxt/
.output/
.data/
.playground/.nuxt/
.playground/.output/
.env

1
.nvmrc Normal file
View File

@@ -0,0 +1 @@
22.22.0

5
.playground/app/app.vue Normal file
View File

@@ -0,0 +1,5 @@
<template>
<ClientOnly>
<ChatPage />
</ClientOnly>
</template>

View File

@@ -0,0 +1,17 @@
// Local playground: an app that only extends the layer and renders the chat
// (app.vue), with en as the default locale and pl prefixed. Run a SummerCMS
// application with the chat plugins and a host bootstrap on 127.0.0.1:8096,
// proxy its paths here (or serve both from one origin) and set
// NUXT_PUBLIC_CHAT_HOST_API_BASE.
export default defineNuxtConfig({
extends: ['..'],
compatibilityDate: '2025-07-15',
i18n: {
strategy: 'prefix_except_default',
defaultLocale: 'en',
locales: [
{ code: 'en', language: 'en-US' },
{ code: 'pl', language: 'pl-PL' },
],
},
})

View File

@@ -0,0 +1,25 @@
<script setup lang="ts">
// The seeded channels of the community. There is no create button: members
// join and leave the channels the host has.
const { t } = useI18n()
const chat = useChat()
</script>
<template>
<nav class="chat-sidebar" :aria-label="t('chat.channels')">
<h2 class="chat-sidebar-title">{{ t('chat.channels') }}</h2>
<ul class="chat-channels">
<li v-for="c in chat.channels.value" :key="c.id">
<button
class="chat-channel"
type="button"
:data-channel-slug="c.slug"
:aria-current="chat.activeId.value === c.conversation_id ? 'true' : undefined"
@click="chat.open(c)"
>
# {{ c.name }}
</button>
</li>
</ul>
</nav>
</template>

View File

@@ -0,0 +1,28 @@
<script setup lang="ts">
// The message form: Enter sends, Shift+Enter adds a line.
const props = defineProps<{ conversationId: number }>()
const { t } = useI18n()
const chat = useChat()
const text = computed({
get: () => chat.drafts.value[props.conversationId] ?? '',
set: (v: string) => (chat.drafts.value[props.conversationId] = v),
})
async function submit() {
await chat.send(text.value)
}
function onKeydown(e: KeyboardEvent) {
if (e.isComposing || e.key !== 'Enter' || e.shiftKey) return
e.preventDefault()
void submit()
}
</script>
<template>
<form class="chat-composer" @submit.prevent="submit">
<textarea v-model="text" class="chat-composer-input" rows="2" :aria-label="t('chat.message')" :readonly="chat.sending.value" @keydown="onKeydown"></textarea>
<button class="chat-send" type="submit" :disabled="!text.trim() || chat.sending.value">{{ t('chat.send') }}</button>
</form>
</template>

View File

@@ -0,0 +1,16 @@
<script setup lang="ts">
// The messages of one conversation, oldest first, as plain text.
const props = defineProps<{ conversationId: number }>()
const { t } = useI18n()
const chat = useChat()
const list = computed(() => chat.messages.value[props.conversationId] ?? [])
</script>
<template>
<div class="chat-list" role="log" :aria-label="t('chat.messages')">
<article v-for="m in list" :key="m.id" class="chat-msg" :data-message-id="m.id">
<span class="chat-msg-name">{{ m.sender_name }}</span>
<p class="chat-msg-body">{{ m.content }}</p>
</article>
</div>
</template>

View File

@@ -0,0 +1,26 @@
<script setup lang="ts">
// The full chat: the channel sidebar and the open conversation. Render it
// inside <ClientOnly> (it uses window and the DOM).
const { t } = useI18n()
const chat = useChat()
onMounted(() => {
void chat.start()
})
const active = computed(() => chat.channels.value.find((c) => c.conversation_id === chat.activeId.value) ?? null)
</script>
<template>
<div class="chat-page">
<ChatChannelList />
<section class="chat-pane" :aria-label="active ? `# ${active.name}` : t('chat.name')">
<template v-if="chat.activeId.value !== null">
<ChatMessageList :conversation-id="chat.activeId.value" />
<ChatComposer :conversation-id="chat.activeId.value" />
</template>
<p v-else class="chat-pane-empty">{{ t('chat.pickChannel') }}</p>
<p v-if="chat.error.value" class="chat-error" role="alert">{{ t(`chat.error.${chat.error.value}`) }}</p>
</section>
</div>
</template>

View File

@@ -0,0 +1,72 @@
// The chat store: membership, channels, the open conversation, messages and
// drafts, as useState keys prefixed chat: (no Pinia). Every component that
// calls useChat() shares the same state.
import type { ChatChannel, ChatMessage } from '../lib/types'
/** The fallback page size of the message list. */
export const MESSAGE_PAGE = 50
export function useChat() {
const api = useChatApi()
const config = useChatConfig()
/** undefined: not known yet; false: outside the community. */
const member = useState<boolean | undefined>('chat:member', () => undefined)
const channels = useState<ChatChannel[]>('chat:channels', () => [])
/** The open conversation id. */
const activeId = useState<number | null>('chat:activeId', () => null)
const messages = useState<Record<number, ChatMessage[]>>('chat:messages', () => ({}))
const drafts = useState<Record<number, string>>('chat:drafts', () => ({}))
const error = useState<string>('chat:error', () => '')
const sending = useState<boolean>('chat:sending', () => false)
/** Loads the bootstrap; without public.chat.hostApiBase it logs an error and stops. */
async function start(): Promise<void> {
if (!config.hostApiBase) {
console.error('vue-chat-layer: runtimeConfig.public.chat.hostApiBase is not set; the chat does not start')
return
}
try {
const b = await api.bootstrap()
if (!b.member) {
member.value = false
channels.value = []
return
}
member.value = true
channels.value = b.channels.map((c) => ({ ...c }))
} catch {
error.value = 'bootstrap'
}
}
/** Opens a channel: the conversation route joins it, then the latest page loads. */
async function open(channel: ChatChannel): Promise<void> {
error.value = ''
await api.openConversation('channel', channel.id)
activeId.value = channel.conversation_id
messages.value[channel.conversation_id] = await api.messages(channel.conversation_id, { limit: MESSAGE_PAGE })
}
/** Sends text to the open conversation; the message appears once the API answers. */
async function send(text: string): Promise<boolean> {
const id = activeId.value
const content = text.trim()
if (id === null || !content || sending.value) return false
sending.value = true
try {
const m = await api.send(id, { content })
const list = messages.value[id] ?? (messages.value[id] = [])
if (!list.some((x) => x.id === m.id)) list.push(m)
drafts.value[id] = ''
return true
} catch {
error.value = 'send'
return false
} finally {
sending.value = false
}
}
return { member, channels, activeId, messages, drafts, error, sending, start, open, send }
}

View File

@@ -0,0 +1,56 @@
// The chat API client for the layer's components, bound to runtime config
// and the app's auth hook. One client per Nuxt app, so concurrent 401s share
// one token refresh.
//
// The auth hook: the app provides `chatAuth` from a Nuxt plugin. token()
// answers the user's frontend JWT (or null); refresh() renews it and answers
// the new one (or null); unauthorized() signs the user out locally:
//
// export default defineNuxtPlugin(() => ({
// provide: {
// chatAuth: {
// token: () => useCookie('token').value ?? null,
// refresh: async () => { ... return newToken },
// unauthorized: () => { useCookie('token').value = null },
// },
// },
// }))
//
// The token is sent as `Authorization: Bearer` (never as a cookie). The
// bases are always runtime config, never request input.
import { createChatClient, type ChatAuth, type ChatClient } from '../lib/client'
interface ChatPublicConfig {
apiBase: string
channelsApiBase: string
botsApiBase: string
hostApiBase: string
}
const NO_AUTH: ChatAuth = { token: () => null }
/** The app's $chatAuth hook, or a hook without a token. */
export function useChatAuth(): ChatAuth {
const hook = (useNuxtApp() as unknown as { $chatAuth?: Partial<ChatAuth> }).$chatAuth
if (!hook || typeof hook.token !== 'function') return NO_AUTH
return hook as ChatAuth
}
/** The public chat config (public.chat). */
export function useChatConfig(): ChatPublicConfig {
return useRuntimeConfig().public.chat as unknown as ChatPublicConfig
}
export function useChatApi(): ChatClient {
const nuxtApp = useNuxtApp() as unknown as { _chatClient?: ChatClient }
if (nuxtApp._chatClient) return nuxtApp._chatClient
const cfg = useChatConfig()
const chatBase = import.meta.server ? (useRuntimeConfig().chat as { apiBase: string }).apiBase : cfg.apiBase
const client = createChatClient({
bases: { chat: chatBase, channels: cfg.channelsApiBase, bots: cfg.botsApiBase, host: cfg.hostApiBase },
auth: useChatAuth(),
})
nuxtApp._chatClient = client
return client
}

226
app/lib/client.ts Normal file
View File

@@ -0,0 +1,226 @@
// 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<string | null | undefined>
/** 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<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
}
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)
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 }),
}
}
export type ChatClient = ReturnType<typeof createChatClient>

160
app/lib/types.ts Normal file
View File

@@ -0,0 +1,160 @@
// The JSON the chat layer reads: the host bootstrap (README, "Host bootstrap
// contract") and golem15.chat's MessageAPI, reactions and uploads. Ported
// from a Golem15 chat SPA's api/types.ts; the single group channel became a
// list of channels.
/** The composer limits: attachments per message, their total bytes and link cards per message. */
export interface ChatLimits {
max_files: number
max_bytes: number
max_embeds: number
}
/** One public channel of the community, with the caller's counts. */
export interface ChatChannel {
id: number
slug: string
name: string
/** The channel's backing golem15.chat conversation. */
conversation_id: number
/** The caller has not left it. */
joined: boolean
unread: number
mentions: number
}
export interface ChatLastMessage {
id: number
sender_id: number
content: string
created_at: string
}
/** One DM of the current user. */
export interface ChatConversationRow {
id: number
type: string
other_user_id: number
unread: number
last_message: ChatLastMessage | null
}
export interface ChatNonMember {
member: false
}
export interface ChatMemberBootstrap {
member: true
/** May delete other people's messages in channels. */
moderator: boolean
/** The chat context DMs are created in (POST /contexts/{type}/{id}/dm). */
context: { type: string; id: number }
channels: ChatChannel[]
conversations: ChatConversationRow[]
limits: ChatLimits
}
/** GET {hostApiBase}/chat: a non-member learns only that. */
export type ChatBootstrap = ChatNonMember | ChatMemberBootstrap
/** A community member (GET {hostApiBase}/chat/members); no e-mail address. */
export interface ChatMember {
id: number
name: string
surname: string
handle: string
is_bot: boolean
}
export interface ChatAttachment {
id: number
url: string
filename: string
size: number
mime_type: string
kind: string
width: number | null
height: number | null
}
export interface ChatReaction {
key: string
count: number
user_ids: number[]
}
/** The reaction routes' answer: the message's reactions after the change. */
export interface ChatReactionsAnswer {
message_id: number
reactions: ChatReaction[]
}
/** The reply sidecar of a thread root. */
export interface ChatThreadSummary {
root_id: number
reply_count: number
last_reply_at?: string
participant_ids: number[]
}
/** golem15.chat MessageAPI. sender_avatar is never rendered. */
export interface ChatMessage {
id: number
conversation_id: number
sender_id: number
sender_name: string
sender_avatar: string | null
content: string | null
type: string
attachments: ChatAttachment[]
created_at: string
created_at_human: string
edited_at: string | null
deleted_at: string | null
is_mine: boolean
root_id: number | null
thread_summary?: ChatThreadSummary | null
reactions?: ChatReaction[]
metadata?: Record<string, unknown>
}
export interface ChatSendBody {
content: string
attachment_ids?: number[]
metadata?: Record<string, unknown>
}
/** POST /attachments: the pending file. */
export interface ChatUploadAnswer {
id: number
filename: string
size: number
}
/** golem15.chat ConversationJSON (the conversation and DM answers). */
export interface ChatConversation {
id: number
type: string
name?: string | null
context_type?: string | null
context_id?: number | null
created_at?: string
}
/** PUT /threads/{rootId}/mute. */
export interface ChatThreadMute {
root_id: number
is_muted: boolean
}
/** One slash command of GET {botsApiBase}/commands. */
export interface ChatCommand {
trigger: string
description: string
}
/** POST {botsApiBase}/dispatch: ephemeral answers go to the sender only. */
export interface ChatDispatchAnswer {
mode: string
payload: unknown
}

14
i18n/locales/en.json Normal file
View File

@@ -0,0 +1,14 @@
{
"chat": {
"name": "Chat",
"channels": "Channels",
"messages": "Messages",
"message": "Message",
"send": "Send",
"pickChannel": "Pick a channel to start.",
"error": {
"bootstrap": "The chat could not load. Check your connection and try again.",
"send": "The message was not sent. Try again."
}
}
}

14
i18n/locales/pl.json Normal file
View File

@@ -0,0 +1,14 @@
{
"chat": {
"name": "Czat",
"channels": "Kanały",
"messages": "Wiadomości",
"message": "Wiadomość",
"send": "Wyślij",
"pickChannel": "Wybierz kanał, aby zacząć.",
"error": {
"bootstrap": "Nie udało się wczytać czatu. Sprawdź połączenie i spróbuj ponownie.",
"send": "Nie wysłano wiadomości. Spróbuj ponownie."
}
}
}

81
nuxt.config.ts Normal file
View File

@@ -0,0 +1,81 @@
// vue-chat-layer: the member chat of the SummerCMS chat plugins
// (golem15.chat /_chat/api/v1, golem15.chatchannels /_chatchannels/api/v1
// and golem15.chatbots /_chatbots/api/v1) as a Nuxt layer: channels, DMs,
// threads, mentions, reactions, attachments, pins, slash commands and live
// updates over the site's one Centrifuge connection.
//
// An app consumes it with `extends: ['vue-chat-layer']`, provides the
// `$chatAuth` hook from a Nuxt plugin (README, "Auth hook"), sets
// `runtimeConfig.public.chat.hostApiBase` to the base of its host bootstrap
// (README, "Host bootstrap contract") and renders <ChatPage> and
// <ChatFloatingPanel>, each inside <ClientOnly>: the components use window,
// WebSocket and the DOM. The layer adds no pages and no route rules; the
// app owns its routes and its copy.
//
// Every path below is absolute and built from this file's directory: a
// relative or ~ path in a layer config resolves against the consuming
// project, not the layer.
import { fileURLToPath } from 'node:url'
const currentDir = fileURLToPath(new URL('.', import.meta.url))
const langDir = `${currentDir}i18n/locales/`
/** Copy locales the layer ships, each in i18n/locales/<code>.json. */
const LAYER_LOCALES = ['pl', 'en'] as const
/** Locale codes the project enables in its i18n config (strings or objects). */
function enabledLocaleCodes(locales: unknown): string[] {
if (!Array.isArray(locales)) return []
return locales
.map((l) => (typeof l === 'string' ? l : l && typeof l === 'object' ? (l as { code?: unknown }).code : undefined))
.filter((c): c is string => typeof c === 'string')
}
export default defineNuxtConfig({
compatibilityDate: '2025-07-15',
devtools: { enabled: false },
// Declared once here, so the app never re-lists @nuxtjs/i18n (two copies
// split locale state). The inline module registers the layer's chat.*
// strings only for the locales the app enables: @nuxtjs/i18n merges every
// locale a layer declares into the app, which would add locales the app
// does not have. An app overrides any chat.* key in its own messages.
modules: [
'@nuxtjs/i18n',
(_options: unknown, nuxt: { options: { i18n?: { locales?: unknown } }; hook: (...args: any[]) => void }) => {
nuxt.hook(
'i18n:registerModule',
(register: (config: { langDir: string; locales: Array<{ code: string; file: string }> }) => void) => {
const enabled = enabledLocaleCodes(nuxt.options.i18n?.locales)
const locales = LAYER_LOCALES.filter((code) => enabled.includes(code)).map((code) => ({ code, file: `${code}.json` }))
if (locales.length > 0) register({ langDir, locales })
},
)
},
],
runtimeConfig: {
chat: {
// Server-only base of the chat API for server-side fetches
// (NUXT_CHAT_API_BASE). The components fetch in the browser only;
// the key exists for an app page that renders chat data on the
// server. It never comes from request input.
apiBase: 'http://127.0.0.1:8096/_chat/api/v1',
},
public: {
chat: {
// Same-origin bases for browser fetches
// (NUXT_PUBLIC_CHAT_API_BASE, NUXT_PUBLIC_CHAT_CHANNELS_API_BASE,
// NUXT_PUBLIC_CHAT_BOTS_API_BASE).
apiBase: '/_chat/api/v1',
channelsApiBase: '/_chatchannels/api/v1',
botsApiBase: '/_chatbots/api/v1',
// The base of the host's bootstrap routes GET {hostApiBase}/chat and
// GET {hostApiBase}/chat/members (NUXT_PUBLIC_CHAT_HOST_API_BASE).
// No default: the host names it, and the chat does not start
// without it.
hostApiBase: '',
},
},
},
})

29
package.json Normal file
View File

@@ -0,0 +1,29 @@
{
"name": "vue-chat-layer",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "./nuxt.config.ts",
"scripts": {
"dev": "nuxi dev .playground",
"build:playground": "nuxt build .playground",
"test": "vitest run",
"dev:prepare": "nuxt prepare .playground"
},
"engines": {
"node": ">=22.18"
},
"dependencies": {
"@nuxtjs/i18n": "10.4.0",
"centrifuge": "5.7.3"
},
"peerDependencies": {
"nuxt": "4.4.8"
},
"devDependencies": {
"nuxt": "4.4.8",
"typescript": "5.9.3",
"vitest": "3.2.7",
"vue": "3.5.35"
}
}

8444
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

7
pnpm-workspace.yaml Normal file
View File

@@ -0,0 +1,7 @@
allowBuilds:
'@parcel/watcher': true
esbuild: true
# centrifuge's protobufjs: its postinstall only prints a version warning;
# it never runs.
protobufjs: false
vue-demi: true

74
tests/smoke.test.ts Normal file
View File

@@ -0,0 +1,74 @@
import { describe, expect, it, vi } from 'vitest'
import { ChatApiError, createChatClient, type ChatFetch } from '../app/lib/client'
const bases = { chat: '/_chat/api/v1', channels: '/_chatchannels/api/v1', bots: '/_chatbots/api/v1', host: '/_acme/api/v1' }
function json(status: number, body: unknown): Response {
return new Response(body === undefined ? '' : JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })
}
describe('createChatClient', () => {
it('builds the messages URL and sends the bearer token', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(200, { data: [] }))
const client = createChatClient({ bases, auth: { token: () => 'tok' }, fetch })
await client.messages(7)
const [url, init] = fetch.mock.calls[0]
expect(url).toBe('/_chat/api/v1/conversations/7/messages?limit=50')
expect(init.headers.Authorization).toBe('Bearer tok')
})
it('reads the bootstrap and the members from the host base', async () => {
const fetch = vi.fn<ChatFetch>(async (url) =>
url.endsWith('/members') ? json(200, { members: [{ id: 2, name: 'Ada', surname: 'H', handle: 'ada', is_bot: false }] }) : json(200, { member: false }),
)
const client = createChatClient({ bases, auth: { token: () => 'tok' }, fetch })
await expect(client.bootstrap()).resolves.toEqual({ member: false })
await expect(client.members()).resolves.toHaveLength(1)
expect(fetch.mock.calls.map((c) => c[0])).toEqual(['/_acme/api/v1/chat', '/_acme/api/v1/chat/members'])
})
it('retries once after a refresh on 401', async () => {
let current = 'old'
const refresh = vi.fn(async () => (current = 'new'))
const unauthorized = vi.fn()
const fetch = vi
.fn<ChatFetch>()
.mockResolvedValueOnce(json(401, { error: 'Token expired' }))
.mockResolvedValueOnce(json(201, { id: 9, conversation_id: 7 }))
const client = createChatClient({ bases, auth: { token: () => current, refresh, unauthorized }, fetch })
const m = await client.send(7, { content: 'hi' })
expect(m.id).toBe(9)
expect(refresh).toHaveBeenCalledOnce()
expect(fetch).toHaveBeenCalledTimes(2)
expect(fetch.mock.calls[1][1].headers.Authorization).toBe('Bearer new')
expect(JSON.parse(String(fetch.mock.calls[1][1].body))).toEqual({ content: 'hi' })
expect(unauthorized).not.toHaveBeenCalled()
})
it('calls unauthorized when the refresh does not help', async () => {
const unauthorized = vi.fn()
const fetch = vi.fn<ChatFetch>(async () => json(401, { error: 'Unauthorized' }))
const client = createChatClient({ bases, auth: { token: () => 'tok', refresh: async () => null, unauthorized }, fetch })
await expect(client.messages(7)).rejects.toMatchObject({ status: 401 })
expect(fetch).toHaveBeenCalledOnce()
expect(unauthorized).toHaveBeenCalledOnce()
})
it('maps a 422 body to field errors', async () => {
const fetch = vi.fn<ChatFetch>(async () => json(422, { error: 'Validation failed', errors: { content: ['Banned word'] } }))
const client = createChatClient({ bases, auth: { token: () => 'tok' }, fetch })
const err = await client.send(7, { content: 'x' }).catch((e: unknown) => e)
expect(err).toBeInstanceOf(ChatApiError)
expect((err as ChatApiError).status).toBe(422)
expect((err as ChatApiError).field('content')).toBe('Banned word')
expect((err as ChatApiError).message).toBe('Validation failed')
})
it('answers status 0 without a connection', async () => {
const fetch = vi.fn<ChatFetch>(async () => {
throw new TypeError('fetch failed')
})
const client = createChatClient({ bases, auth: { token: () => null }, fetch })
await expect(client.messages(7)).rejects.toMatchObject({ status: 0 })
})
})

16
tsconfig.json Normal file
View File

@@ -0,0 +1,16 @@
{
// Self-contained on purpose: Vite reads this file when it compiles the
// layer's .vue and .ts files, also from a consumer's node_modules, where no
// generated .nuxt/tsconfig.json exists. For editor types of Nuxt
// auto-imports, run `pnpm dev:prepare` and open .playground.
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"noEmit": true,
"strict": true,
"skipLibCheck": true,
"lib": ["ESNext", "DOM", "DOM.Iterable"]
}
}

10
vitest.config.ts Normal file
View File

@@ -0,0 +1,10 @@
import { defineConfig } from 'vitest/config'
// Unit tests of the layer's pure modules (app/lib) in Node. Components are
// covered by the consuming app's browser checks.
export default defineConfig({
test: {
environment: 'node',
include: ['tests/**/*.test.ts'],
},
})