import type { BootstrapResponse, User } from '~/types' interface SessionState { loaded: boolean needsSetup: boolean user: User | null allowRegistration: boolean publicUrl: string previewOrigin: string } let inflight: Promise | null = null export function useSession() { const state = useState('session', () => ({ loaded: false, needsSetup: false, user: null, allowRegistration: false, publicUrl: '', previewOrigin: '', })) const api = useApi() function apply(boot: BootstrapResponse) { state.value = { loaded: true, needsSetup: boot.needs_setup, user: boot.user, allowRegistration: boot.allow_registration, publicUrl: boot.public_url, previewOrigin: boot.preview_origin, } return state.value } async function load(force = false): Promise { if (state.value.loaded && !force) return state.value if (!inflight) { inflight = api .get('/bootstrap') .then((boot) => apply(boot)) .finally(() => { inflight = null }) } return inflight } async function signOut() { try { await api.post('/logout') } catch { // The cookie is cleared server-side when the session is still valid. } state.value = { ...state.value, user: null } await navigateTo('/login') } return { session: state, user: computed(() => state.value.user), load, signOut, } }