/*! @azure/msal-browser v5.15.0 2026-06-23 */
'use strict';
import { createAuthError, AuthErrorCodes } from '@azure/msal-common/browser';
import { PlatformAuthConstants } from '../../utils/BrowserConstants.mjs';
import { createNativeAuthError } from '../../error/NativeAuthError.mjs';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
class PlatformAuthDOMHandler {
    constructor(logger, performanceClient, correlationId) {
        this.logger = logger;
        this.performanceClient = performanceClient;
        this.correlationId = correlationId;
        this.platformAuthType = PlatformAuthConstants.PLATFORM_DOM_PROVIDER;
    }
    static async createProvider(logger, performanceClient, correlationId) {
        logger.trace("12mj4a", correlationId);
        // @ts-ignore
        if (window.navigator?.platformAuthentication) {
            const supportedContracts = 
            // @ts-ignore
            await window.navigator.platformAuthentication.getSupportedContracts(PlatformAuthConstants.MICROSOFT_ENTRA_BROKERID);
            if (supportedContracts?.includes(PlatformAuthConstants.PLATFORM_DOM_APIS)) {
                logger.trace("1h5q1r", correlationId);
                return new PlatformAuthDOMHandler(logger, performanceClient, correlationId);
            }
        }
        return undefined;
    }
    /**
     * Returns the Id for the broker extension this handler is communicating with
     * @returns
     */
    getExtensionId() {
        return PlatformAuthConstants.MICROSOFT_ENTRA_BROKERID;
    }
    getExtensionVersion() {
        return "";
    }
    getExtensionName() {
        return PlatformAuthConstants.DOM_API_NAME;
    }
    /**
     * Send token request to platform broker via browser DOM API
     * @param request
     * @returns
     */
    async sendMessage(request) {
        this.logger.trace(`02bcil ${this.platformAuthType}`, request.correlationId);
        try {
            const platformDOMRequest = this.initializePlatformDOMRequest(request);
            const response = 
            // @ts-ignore
            await window.navigator.platformAuthentication.executeGetToken(platformDOMRequest);
            return this.validatePlatformBrokerResponse(response, request.correlationId);
        }
        catch (e) {
            this.logger.error(`11im7g ${this.platformAuthType}`, request.correlationId);
            throw e;
        }
    }
    initializePlatformDOMRequest(request) {
        this.logger.trace(`15d6yv ${this.platformAuthType}`, request.correlationId);
        const { accountId, clientId, authority, scope, redirectUri, correlationId, state, storeInCache, embeddedClientId, extraParameters, ...remainingProperties } = request;
        const validExtraParameters = this.getDOMExtraParams(remainingProperties, correlationId);
        const platformDOMRequest = {
            accountId: accountId,
            brokerId: this.getExtensionId(),
            authority: authority,
            clientId: clientId,
            correlationId: correlationId || this.correlationId,
            extraParameters: {
                ...extraParameters,
                ...validExtraParameters,
            },
            isSecurityTokenService: false,
            redirectUri: redirectUri,
            scope: scope,
            state: state,
            storeInCache: storeInCache,
            embeddedClientId: embeddedClientId,
        };
        return platformDOMRequest;
    }
    validatePlatformBrokerResponse(response, correlationId) {
        if (response.hasOwnProperty("isSuccess")) {
            if (response.hasOwnProperty("accessToken") &&
                response.hasOwnProperty("idToken") &&
                response.hasOwnProperty("clientInfo") &&
                response.hasOwnProperty("account") &&
                response.hasOwnProperty("scopes") &&
                response.hasOwnProperty("expiresIn")) {
                this.logger.trace(`0h4vei ${this.platformAuthType}`, correlationId);
                return this.convertToPlatformBrokerResponse(response, correlationId);
            }
            else if (response.hasOwnProperty("error")) {
                const errorResponse = response;
                if (errorResponse.isSuccess === false &&
                    errorResponse.error &&
                    errorResponse.error.code) {
                    this.logger.trace(`0g92vm ${this.platformAuthType}`, correlationId);
                    throw createNativeAuthError(errorResponse.error.code, correlationId, errorResponse.error.description, {
                        error: parseInt(errorResponse.error.errorCode),
                        protocol_error: errorResponse.error.protocolError,
                        status: errorResponse.error.status,
                        properties: errorResponse.error.properties,
                    });
                }
            }
        }
        throw createAuthError(AuthErrorCodes.unexpectedError, correlationId, "Response missing expected properties.");
    }
    convertToPlatformBrokerResponse(response, correlationId) {
        this.logger.trace(`14913t ${this.platformAuthType}`, correlationId);
        const nativeResponse = {
            access_token: response.accessToken,
            id_token: response.idToken,
            client_info: response.clientInfo,
            account: response.account,
            expires_in: response.expiresIn,
            scope: response.scopes,
            state: response.state || "",
            properties: response.properties || {},
            extendedLifetimeToken: response.extendedLifetimeToken ?? false,
            shr: response.proofOfPossessionPayload,
        };
        return nativeResponse;
    }
    getDOMExtraParams(extraParameters, correlationId) {
        try {
            const stringifiedProperties = {};
            for (const [key, value] of Object.entries(extraParameters)) {
                if (!value) {
                    continue;
                }
                if (typeof value === "object") {
                    stringifiedProperties[key] = JSON.stringify(value);
                }
                else {
                    stringifiedProperties[key] = String(value);
                }
            }
            return stringifiedProperties;
        }
        catch (e) {
            this.logger.error(`0eu9o3 ${this.platformAuthType}`, correlationId);
            this.logger.errorPii(`17rpl5 ${this.platformAuthType} ${e}`, correlationId);
            return {};
        }
    }
}

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