function createOAuthTokenManager({ oauth2Service, persistTokens, now = Date.now }) { const refreshOperations = new Map(); async function getAccessToken(account) { if (account?.authMethod !== 'oauth2') throw new Error('This account does not use OAuth2.'); if (account.oauthAccessToken && Number(account.oauthAccessTokenExpiresAt) > now() + 60_000) { return account.oauthAccessToken; } if (!account.oauthRefreshToken) { throw new Error('Reconnect this OAuth2 account to continue.'); } const key = String(account.id || `${account.oauthProvider}:${account.email}`); let pending = refreshOperations.get(key); if (!pending) { pending = (async () => { const tokens = await oauth2Service.refresh(account.oauthProvider, account.oauthRefreshToken); await persistTokens(account.id, tokens); return tokens; })(); refreshOperations.set(key, pending); pending.finally(() => { if (refreshOperations.get(key) === pending) refreshOperations.delete(key); }).catch(() => {}); } const tokens = await pending; Object.assign(account, tokens); return tokens.oauthAccessToken; } return Object.freeze({ getAccessToken }); } module.exports = { createOAuthTokenManager };