import type { MeResponse } from '@/api/client' import { captureSessionGeneration, isSessionCurrent } from '@/api/authSession' import { StaleSessionError } from '@/api/errors' type ApplyMe = (data: MeResponse) => boolean let queueEpoch = 0 let queueTail: Promise = Promise.resolve() let applyMe: ApplyMe = () => false export function bindMeMutationApply(fn: ApplyMe): void { applyMe = fn } export function resetMeMutationQueue(): void { queueEpoch += 1 queueTail = Promise.resolve() } export function resetMeMutationQueueForTests(): void { resetMeMutationQueue() } function assertMutationSession(epochAtEnqueue: number, sessionGen: number): void { if (epochAtEnqueue !== queueEpoch) { throw new StaleSessionError() } if (!isSessionCurrent(sessionGen)) { throw new StaleSessionError() } } /** * Serializes state-changing API calls in this tab so a slower response cannot apply before * a later mutation finishes. Does not replace server revision — see docs in sync.ts. */ export async function runMeMutation( fetcher: () => Promise, pickMe: (result: R) => MeResponse = (result) => result as unknown as MeResponse, ): Promise { const sessionGen = captureSessionGeneration() const epochAtEnqueue = queueEpoch const execute = async (): Promise => { assertMutationSession(epochAtEnqueue, sessionGen) const result = await fetcher() assertMutationSession(epochAtEnqueue, sessionGen) applyMe(pickMe(result)) return result } const resultPromise = queueTail.then(execute) queueTail = resultPromise.then( () => undefined, () => undefined, ) return resultPromise }