import { createApiClient, type WsClientConfig } from '@blax-software/networking' import { createVueWsClient, type VueWsClient } from '@blax-software/networking/vue' import type { AuthResult } from '~/types/game' import { createMockServer } from '~/mock/server' /** The part of the WS client the game uses. The mock server implements the same surface. */ export type GameWs = Pick< VueWsClient, 'send' | 'listen' | 'listenWhileMounted' | 'is_setup' | 'is_opened' | 'resetConnection' > /** HTTP is only for getting the bearer token; everything else goes over `ws`. */ export interface GameAuth { token(): string | null login(email: string, password: string): Promise register(name: string, email: string, password: string): Promise logout(): void } export interface NetworkingOptions { serverUrl: string wsUrl: string appKey: string mock: boolean notify?: WsClientConfig['notify'] translate?: WsClientConfig['translate'] } // The app's singletons, assigned once by plugins/networking.ts before any page runs. export let ws: GameWs export let gameAuth: GameAuth export let isMockServer = false export function setupNetworking(options: NetworkingOptions) { if (options.mock) { const mock = createMockServer() ws = mock.ws gameAuth = mock.auth isMockServer = true return } const api = createApiClient({ serverUrl: options.serverUrl, notify: options.notify }) api.loadBearerFromStorage() const client = createVueWsClient({ url: options.wsUrl, appKey: options.appKey, getAuthToken: () => api.bearerToken || null, notify: options.notify, translate: options.translate, sendTimeout: 15000, rejectOnDisconnect: true, }) client.setAppReady() ws = client const signIn = (result: AuthResult) => { api.setBearer(result.token) client.resetConnection() return result } gameAuth = { token: () => api.bearerToken || null, login: async (email, password) => signIn((await api.post('auth/login', { email, password })).data), register: async (name, email, password) => signIn((await api.post('auth/register', { name, email, password })).data), logout() { api.setBearer(null) client.resetConnection() }, } }