/*! @azure/msal-common v16.6.2 2026-05-19 */
'use strict';
import { CcsCredentialType } from '../account/CcsCredential.mjs';
import { buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs';
import { URL_FORM_CONTENT_TYPE, HeaderNames } from '../utils/Constants.mjs';
import { addBrokerParameters, addExtraParameters, addCorrelationId, instrumentBrokerParams } from '../request/RequestParameterBuilder.mjs';
import { mapToQueryString } from '../utils/UrlUtils.mjs';
import { ThrottlingUtils } from '../network/ThrottlingUtils.mjs';
import { NetworkError } from '../error/NetworkError.mjs';
import { AuthError } from '../error/AuthError.mjs';
import { createClientAuthError } from '../error/ClientAuthError.mjs';
import { invokeAsync } from '../utils/FunctionWrappers.mjs';
import { NetworkClientSendPostRequestAsync } from '../telemetry/performance/PerformanceEvents.mjs';
import { networkError } from '../error/ClientAuthErrorCodes.mjs';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
/**
 * Creates default headers for requests to token endpoint
 */
function createTokenRequestHeaders(logger, preventCorsPreflight, ccsCred) {
    const headers = {};
    headers[HeaderNames.CONTENT_TYPE] = URL_FORM_CONTENT_TYPE;
    if (!preventCorsPreflight && ccsCred) {
        switch (ccsCred.type) {
            case CcsCredentialType.HOME_ACCOUNT_ID:
                try {
                    const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
                    headers[HeaderNames.CCS_HEADER] = `Oid:${clientInfo.uid}@${clientInfo.utid}`;
                }
                catch (e) {
                    logger.verbose("1qhtee", "");
                }
                break;
            case CcsCredentialType.UPN:
                headers[HeaderNames.CCS_HEADER] = `UPN: ${ccsCred.credential}`;
                break;
        }
    }
    return headers;
}
/**
 * Creates query string for the /token request
 * @param request
 */
function createTokenQueryParameters(request, clientId, redirectUri, performanceClient) {
    const parameters = new Map();
    if (request.embeddedClientId) {
        addBrokerParameters(parameters, clientId, redirectUri);
    }
    if (request.extraQueryParameters) {
        addExtraParameters(parameters, request.extraQueryParameters);
    }
    addCorrelationId(parameters, request.correlationId);
    instrumentBrokerParams(parameters, request.correlationId, performanceClient);
    return mapToQueryString(parameters);
}
/**
 * Http post to token endpoint
 * @param tokenEndpoint
 * @param queryString
 * @param headers
 * @param thumbprint
 */
async function executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, cacheManager, networkClient, logger, performanceClient, serverTelemetryManager) {
    const response = await sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers: headers }, correlationId, cacheManager, networkClient, logger, performanceClient);
    if (serverTelemetryManager &&
        response.status < 500 &&
        response.status !== 429) {
        // Telemetry data successfully logged by server, clear Telemetry cache
        serverTelemetryManager.clearTelemetryCache();
    }
    return response;
}
/**
 * Wraps sendPostRequestAsync with necessary preflight and postflight logic
 * @param thumbprint - Request thumbprint for throttling
 * @param tokenEndpoint - Endpoint to make the POST to
 * @param options - Body and Headers to include on the POST request
 * @param correlationId - CorrelationId for telemetry
 * @param cacheManager - Cache manager instance
 * @param networkClient - Network module instance
 * @param logger - Logger instance
 * @param performanceClient - Performance client instance
 */
async function sendPostRequest(thumbprint, tokenEndpoint, options, correlationId, cacheManager, networkClient, logger, performanceClient) {
    ThrottlingUtils.preProcess(cacheManager, thumbprint, correlationId);
    let response;
    try {
        response = await invokeAsync((networkClient.sendPostRequestAsync.bind(networkClient)), NetworkClientSendPostRequestAsync, logger, performanceClient, correlationId)(tokenEndpoint, options);
        const responseHeaders = response.headers || {};
        performanceClient?.addFields({
            refreshTokenSize: response.body.refresh_token?.length || 0,
            httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "",
            requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "",
        }, correlationId);
    }
    catch (e) {
        if (e instanceof NetworkError) {
            const responseHeaders = e.responseHeaders;
            if (responseHeaders) {
                performanceClient?.addFields({
                    httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] ||
                        "",
                    requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "",
                    contentTypeHeader: responseHeaders[HeaderNames.CONTENT_TYPE] ||
                        undefined,
                    contentLengthHeader: responseHeaders[HeaderNames.CONTENT_LENGTH] ||
                        undefined,
                    httpStatus: e.httpStatus,
                }, correlationId);
            }
            throw e.error;
        }
        if (e instanceof AuthError) {
            throw e;
        }
        else {
            throw createClientAuthError(networkError);
        }
    }
    ThrottlingUtils.postProcess(cacheManager, thumbprint, response, correlationId);
    return response;
}

export { createTokenQueryParameters, createTokenRequestHeaders, executePostToTokenEndpoint, sendPostRequest };
//# sourceMappingURL=Token.mjs.map
