/*! @azure/msal-browser v5.8.0 2026-04-21 */
'use strict';
import { DefaultPackageInfo } from '../../CustomAuthConstants.mjs';
import { ACCOUNT_GET_ACCESS_TOKEN } from '../../core/telemetry/PublicApiId.mjs';
import { CustomAuthInteractionClientBase } from '../../core/interaction_client/CustomAuthInteractionClientBase.mjs';
import { SilentFlowClient, ClientAuthError, ClientAuthErrorCodes, RefreshTokenClient, UrlString } from '@azure/msal-common/browser';
import { ApiId } from '../../../utils/BrowserConstants.mjs';
import { getCurrentUri } from '../../../utils/BrowserUtils.mjs';
import { initializeServerTelemetryManager, clearCacheOnLogout } from '../../../interaction_client/BaseInteractionClient.mjs';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
class CustomAuthSilentCacheClient extends CustomAuthInteractionClientBase {
    /**
     * Acquires a token from the cache if it is not expired. Otherwise, makes a request to renew the token.
     * If forceRresh is set to false, then looks up the access token in cache first.
     *   If access token is expired or not found, then uses refresh token to get a new access token.
     *   If no refresh token is found or it is expired, then throws error.
     * If forceRefresh is set to true, then skips token cache lookup and fetches a new token using refresh token
     *   If no refresh token is found or it is expired, then throws error.
     * @param silentRequest The silent request object.
     * @returns {Promise<AuthenticationResult>} The promise that resolves to an AuthenticationResult.
     */
    async acquireToken(silentRequest) {
        const correlationId = silentRequest.correlationId || this.correlationId;
        const telemetryManager = initializeServerTelemetryManager(ACCOUNT_GET_ACCESS_TOKEN, this.config.auth.clientId, correlationId, this.browserStorage, this.logger, silentRequest.forceRefresh);
        const clientConfig = this.getCustomAuthClientConfiguration(telemetryManager, this.customAuthAuthority, correlationId);
        const silentFlowClient = new SilentFlowClient(clientConfig, this.performanceClient);
        try {
            this.logger.verbose("1arlz4", correlationId);
            const result = await silentFlowClient.acquireCachedToken(silentRequest);
            this.logger.verbose("1dzrjc", correlationId);
            return result[0];
        }
        catch (error) {
            if (error instanceof ClientAuthError &&
                error.errorCode === ClientAuthErrorCodes.tokenRefreshRequired) {
                this.logger.verbose("05sqvp", correlationId);
                const refreshTokenClient = new RefreshTokenClient(clientConfig, this.performanceClient);
                this.logger.verbose("0ogm3j", correlationId);
                const refreshTokenResult = await refreshTokenClient.acquireTokenByRefreshToken(silentRequest, ACCOUNT_GET_ACCESS_TOKEN);
                this.logger.verbose("0vydnd", correlationId);
                return refreshTokenResult;
            }
            throw error;
        }
    }
    async logout(logoutRequest) {
        const validLogoutRequest = this.initializeLogoutRequest(logoutRequest);
        const correlationId = logoutRequest?.correlationId || this.correlationId;
        // Clear the cache
        this.logger.verbose("02fvrq", correlationId);
        await clearCacheOnLogout(this.browserStorage, this.browserCrypto, this.logger, correlationId, validLogoutRequest?.account);
        this.logger.verbose("12w2ul", correlationId);
        const postLogoutRedirectUri = this.config.auth.postLogoutRedirectUri;
        if (postLogoutRedirectUri) {
            const absoluteRedirectUri = UrlString.getAbsoluteUrl(postLogoutRedirectUri, getCurrentUri());
            this.logger.verbose("1fgk77", correlationId);
            // Redirect to post logout redirect uri
            await this.navigationClient.navigateExternal(absoluteRedirectUri, {
                apiId: ApiId.logout,
                timeout: this.config.system.redirectNavigationTimeout,
                noHistory: false,
            });
        }
    }
    getCurrentAccount(correlationId) {
        let account = null;
        this.logger.verbose("1ry0zt", correlationId);
        const allAccounts = this.browserStorage.getAllAccounts({}, correlationId);
        if (allAccounts.length > 0) {
            if (allAccounts.length !== 1) {
                this.logger.warning("0rh9ou", correlationId);
            }
            account = allAccounts[0];
        }
        if (account) {
            this.logger.verbose("1utnrc", correlationId);
        }
        else {
            this.logger.verbose("0w3jks", correlationId);
        }
        return account;
    }
    getCustomAuthClientConfiguration(serverTelemetryManager, customAuthAuthority, correlationId) {
        const logger = this.config.system.loggerOptions;
        return {
            authOptions: {
                clientId: this.config.auth.clientId,
                authority: customAuthAuthority,
                clientCapabilities: this.config.auth.clientCapabilities,
                redirectUri: this.config.auth.redirectUri,
            },
            systemOptions: {
                tokenRenewalOffsetSeconds: this.config.system.tokenRenewalOffsetSeconds,
                preventCorsPreflight: true,
            },
            loggerOptions: {
                loggerCallback: logger.loggerCallback,
                piiLoggingEnabled: logger.piiLoggingEnabled,
                logLevel: logger.logLevel,
                correlationId: correlationId,
            },
            cryptoInterface: this.browserCrypto,
            networkInterface: this.networkClient,
            storageInterface: this.browserStorage,
            serverTelemetryManager: serverTelemetryManager,
            libraryInfo: {
                sku: DefaultPackageInfo.SKU,
                version: DefaultPackageInfo.VERSION,
                cpu: DefaultPackageInfo.CPU,
                os: DefaultPackageInfo.OS,
            },
            telemetry: this.config.telemetry,
        };
    }
}

export { CustomAuthSilentCacheClient };
//# sourceMappingURL=CustomAuthSilentCacheClient.mjs.map
