/** * Staff (admin-ui) and user (app) sessions. * * Logs in once per suite and caches the token, so a bad credential fails once * with a clear message rather than on every request. */ import { apiClient, assertServerUp } from './api' import { adminCredentials, userCredentials } from './env' export interface StaffSession { token: string staffId: number name: string } export interface UserSession { token: string userId: number } let staffPromise: Promise | null = null let userPromise: Promise | null = null export function staffSession(): Promise { staffPromise ??= loginStaff() return staffPromise } export function userSession(): Promise { userPromise ??= loginUser() return userPromise } async function loginStaff(): Promise { await assertServerUp() const { name, password } = adminCredentials() const res = await apiClient().admin.staffUser.login.mutate({ name, password }) if (!res?.token || !res?.staff?.id) { throw new Error('[api-tests] admin.staffUser.login returned no token/staff id') } return { token: res.token, staffId: res.staff.id, name: res.staff.name } } async function loginUser(): Promise { await assertServerUp() const { identifier, password } = userCredentials() const res = await apiClient().user.auth.login.mutate({ identifier, password }) const token = res?.data?.token const userId = res?.data?.user?.id if (!token || !userId) { throw new Error('[api-tests] user.auth.login returned no token/user id') } return { token, userId: Number(userId) } }