"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.setRequestTimeout = exports.setBasicAuthorization = exports.headersIncludeAuthMethod = void 0;
const core_common_1 = require("@itwin/core-common");
/**
 * Check whether or not one of the requested authentication method is listed in the HTTP 'WWW-Authenticate' response header
 * @param headers Headers object
 * @param query List of authentication method to lookup (case-insensitive)
 * @note For CORS requests, the 'Access-Control-Expose-Headers' header from the server must make the 'WWW-Authenticate' available to the browser, otherwise this won't work.
 * @internal
 */
function headersIncludeAuthMethod(headers, query) {
    const wwwAuthenticate = headers.get("WWW-authenticate");
    const lowerCaseQuery = query.map(((value) => value.toLowerCase())); // not case-sensitive
    if (wwwAuthenticate !== null) {
        const authMethods = wwwAuthenticate.split(",").map(((value) => value.toLowerCase().trim()));
        for (const queryValue of lowerCaseQuery) {
            if (authMethods.includes(queryValue))
                return true;
        }
    }
    return false;
}
exports.headersIncludeAuthMethod = headersIncludeAuthMethod;
/** @internal */
function setBasicAuthorization(headers, userOrCreds, password) {
    let username;
    let pwd;
    if (typeof userOrCreds === "string") {
        username = userOrCreds;
        pwd = password;
    }
    else {
        username = userOrCreds.user;
        pwd = userOrCreds.password;
    }
    if (username !== undefined && pwd !== undefined)
        headers.set("Authorization", `Basic ${core_common_1.Base64EncodedString.encode(`${username}:${pwd}`)}`);
}
exports.setBasicAuthorization = setBasicAuthorization;
/**
 * Set number of milliseconds a request can take before automatically being terminated
 * @internal
 */
function setRequestTimeout(opts, ms, abortController) {
    const controller = abortController ?? new AbortController();
    setTimeout(() => controller.abort(), ms);
    opts.signal = controller.signal;
}
exports.setRequestTimeout = setRequestTimeout;
//# sourceMappingURL=utils.js.map