import { createAsyncContext } from './asyncContext' import type { AuthData, MutatorContext } from '../types' type AsyncContext = ReturnType> const contextStore = globalThis as typeof globalThis & { __onZeroMutatorContext__?: AsyncContext __onZeroAuthScopeContext__?: AsyncContext } const asyncContext = contextStore.__onZeroMutatorContext__ ?? (contextStore.__onZeroMutatorContext__ = createAsyncContext()) // lightweight auth-only scope for async tasks (where mutation context is gone but authData is needed) const authScopeContext = contextStore.__onZeroAuthScopeContext__ ?? (contextStore.__onZeroAuthScopeContext__ = createAsyncContext()) export function mutatorContext(): MutatorContext { const currentContext = asyncContext.get() if (!currentContext) { throw new Error('mutatorContext must be called within a mutator') } return currentContext } export function isInZeroMutation() { return !!asyncContext.get() } export function runWithContext( context: MutatorContext, fn: () => T | Promise ): Promise { return asyncContext.run(context, fn) } // auto-resolve authData from mutation context or auth scope export function getScopedAuthData(): AuthData | null | undefined { if (isInZeroMutation()) { return mutatorContext().authData } return authScopeContext.get() ?? undefined } export function runWithAuthScope( authData: AuthData | null, fn: () => T | Promise ): Promise { return authScopeContext.run(authData, fn) }