"use strict";
// tslint:disable:export-name
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRootScope = void 0;
var tslib_1 = require("tslib");
var sp_core_library_1 = require("@microsoft/sp-core-library");
var sp_diagnostics_1 = require("@microsoft/sp-diagnostics");
var sp_dynamic_data_1 = require("@microsoft/sp-dynamic-data");
var sp_http_base_1 = require("@microsoft/sp-http-base");
var sp_page_context_1 = require("@microsoft/sp-page-context");
var flights_1 = require("./flights");
var killSwitches_1 = require("../common/killSwitches");
var KillSwitches_1 = require("../../utilities/KillSwitches");
/**
 * Create a root service scope and initialize with SPFx services:
 *   - PageContext
 *   - DynamicDataManager
 *   - HttpClient
 *   - SPHttpClient
 *   - GraphHttpClientContext
 *   - DigestCache
 *
 * @param pageContext - the current SPPageContext
 *
 * @returns - the root scope
 */
function createRootScope(pageContext) {
    var root = sp_core_library_1.ServiceScope.startNewRoot();
    root.provide(sp_diagnostics_1._logSourceServiceKey, sp_diagnostics_1._LogSource.create('RootServiceScope'));
    root.createDefaultAndProvide(sp_page_context_1.PageContext.serviceKey);
    root.createDefaultAndProvide(sp_dynamic_data_1._DynamicDataUtilities.IDynamicDataManagerServiceKey);
    root.createDefaultAndProvide(sp_http_base_1.HttpClient.serviceKey);
    var spHttpClient = root.createDefaultAndProvide(sp_http_base_1.SPHttpClient.serviceKey);
    var graphContext = root.createDefaultAndProvide(sp_http_base_1._GraphHttpClientContext.serviceKey);
    var digestCache = root.createDefaultAndProvide(sp_http_base_1.DigestCache.serviceKey);
    root.finish();
    initializeGraphHttpClient(pageContext, spHttpClient, graphContext);
    initializeDigestCache(pageContext, digestCache);
    return root;
}
exports.createRootScope = createRootScope;
function initializeGraphHttpClient(pageContext, spHttpClient, graphContext) {
    var _a;
    var aadInstanceUrl = pageContext.aadInstanceUrl, aadSessionId = pageContext.aadSessionId, aadTenantId = pageContext.aadTenantId, aadUserId = pageContext.aadUserId, CorrelationId = pageContext.CorrelationId, env = pageContext.env, isAnonymousGuestUser = pageContext.isAnonymousGuestUser, isExternalGuestUser = pageContext.isExternalGuestUser, msGraphEndpointUrl = pageContext.msGraphEndpointUrl, spfx3rdPartyServicePrincipalId = pageContext.spfx3rdPartyServicePrincipalId, spfx3rdPartyCustomServicePrincipalId = pageContext.spfx3rdPartyCustomServicePrincipalId, userPrincipalName = pageContext.userPrincipalName, webAbsoluteUrl = pageContext.webAbsoluteUrl, webServerRelativeUrl = pageContext.webServerRelativeUrl;
    if (sp_core_library_1.Environment.type !== sp_core_library_1.EnvironmentType.Local) {
        graphContext.initialize(webServerRelativeUrl, msGraphEndpointUrl, webAbsoluteUrl);
    }
    //
    // TODO: remove the var and if after APEXSpfxCustomAppPrincipalClient graduation
    //
    var servicePrincipalId = spfx3rdPartyServicePrincipalId;
    if ((0, flights_1.isAPEXSpfxCustomAppPrincipalClientEnabled)() && spfx3rdPartyCustomServicePrincipalId) {
        servicePrincipalId = spfx3rdPartyCustomServicePrincipalId;
    }
    var defaultAadConfig = {
        aadInstanceUrl: aadInstanceUrl,
        aadSessionId: aadSessionId,
        aadTenantId: aadTenantId,
        aadUserId: aadUserId,
        redirectUri: "".concat(window.location.origin, "/_forms/").concat(sp_http_base_1._AadConstants.SPFX_SINGLE_SIGN_ON_REPLY_URL),
        servicePrincipalId: servicePrincipalId,
        spRequestGuid: CorrelationId,
        userPrincipalName: isAnonymousGuestUser || isExternalGuestUser ? undefined : userPrincipalName
    };
    var oboConfig;
    defaultAadConfig.aadInstanceUrl =
        !env || env.toLowerCase() !== 'edog'
            ? 'https://login.microsoftonline.com'
            : 'https://login.windows-ppe.net';
    if ((((0, flights_1.isOBOForAllTeamsScenariosEnabled)() && sp_core_library_1._BrowserUtilities.isTeamsHosted()) ||
        (!(0, killSwitches_1.useOBOInWebForSecureBrokerKSActivated)() && sp_core_library_1._BrowserUtilities.isUsingSecureBroker())
        ? sp_core_library_1._BrowserUtilities.isTeamsHosted()
        : sp_core_library_1._BrowserUtilities.isWebViewHosted()) ||
        ((0, flights_1.isSafariAuthPatchEnbled)() && /.*AppleWebKit.*Safari/.test(navigator.userAgent))) {
        oboConfig = { spHttpClient: spHttpClient, serverRelativeUrl: webAbsoluteUrl };
    }
    try {
        if (isFirstPartyIsolatedDomain(defaultAadConfig === null || defaultAadConfig === void 0 ? void 0 : defaultAadConfig.servicePrincipalId, (_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.host)) {
            if (!(0, KillSwitches_1.notReadTenantIdAndUserIdFromQueryParametersOnFirstPartyIsloatedDomainKSActivated)() &&
                !(defaultAadConfig === null || defaultAadConfig === void 0 ? void 0 : defaultAadConfig.aadTenantId)) {
                var queryParameters = new URL(window.location.href).searchParams;
                defaultAadConfig.aadTenantId = queryParameters.get('tenantId');
                defaultAadConfig.aadUserId = queryParameters.get('userId');
                defaultAadConfig.userPrincipalName = queryParameters.get('userPrincipalName');
                sp_diagnostics_1._TraceLogger.logVerbose(sp_diagnostics_1._LogSource.create('RootServiceScope'), "reading tenant id ".concat(defaultAadConfig === null || defaultAadConfig === void 0 ? void 0 : defaultAadConfig.aadTenantId, ", user id ").concat(defaultAadConfig === null || defaultAadConfig === void 0 ? void 0 : defaultAadConfig.aadUserId, ", user principal name ").concat(defaultAadConfig === null || defaultAadConfig === void 0 ? void 0 : defaultAadConfig.userPrincipalName, " from query parameter"));
            }
            sp_http_base_1._AadTokenProviders._initialize(new sp_http_base_1.AadTokenProvider(defaultAadConfig, oboConfig), defaultAadConfig);
        }
        else {
            sp_http_base_1._AadTokenProviders._initialize(new sp_http_base_1.AadTokenProvider(defaultAadConfig, oboConfig), tslib_1.__assign(tslib_1.__assign({}, defaultAadConfig), { servicePrincipalId: sp_http_base_1._AadConstants.PRE_AUTHORIZED_APP_PRINCIPAL_ID }));
        }
    }
    catch (e) {
        sp_diagnostics_1._TraceLogger.logVerbose(sp_diagnostics_1._LogSource.create('RootServiceScope'), 'AadTokenProviders: Failed to initialize');
    }
}
function initializeDigestCache(pageContext, digestCache) {
    var formDigestTimeoutSeconds = pageContext.formDigestTimeoutSeconds, formDigestValue = pageContext.formDigestValue, serverTime = pageContext.serverTime, webAbsoluteUrl = pageContext.webAbsoluteUrl, webServerRelativeUrl = pageContext.webServerRelativeUrl;
    // Value of serverTime is same as what comes as part of formDigestValue
    // but is in locale neutral ISO 8601 format. So it will get correctly
    // parsed by Date class irrespective of client locale.
    // serverTime is accurate to the order of ms, while DateTime which comes
    // as part of formDigestValue is trimmed to order of seconds. Subtract
    // 30s from expirationTimeStamp to avoid any timing errors b/w server and client
    var expirationTimestamp = new Date(serverTime).getTime() + 1000 * formDigestTimeoutSeconds - 30000;
    for (var _i = 0, _a = [webAbsoluteUrl, webServerRelativeUrl]; _i < _a.length; _i++) {
        var url = _a[_i];
        digestCache.addDigestToCache(url, formDigestValue, expirationTimestamp);
    }
}
/**
 * Checking if Sharepoint is running on 1st party isolated domain.
 * @param principleId : server principle id
 * @param windowHost : current window host
 * @returns true if the current server is 1st party isolated domain
 */
function isFirstPartyIsolatedDomain(principleId, windowHost) {
    if ((0, killSwitches_1.notUseFirstPartyIsolatedAppIdOnSecurebrokerDomain)()) {
        return false;
    }
    if (!principleId || !windowHost) {
        return false;
    }
    var firstPartyIsolatedAppId = '3bc2296e-aa22-4ed2-9e1e-946d05afa6a2';
    var firstPartyIsolatedDomain = 'securebroker.sharepointonline.com';
    return principleId === firstPartyIsolatedAppId && windowHost === firstPartyIsolatedDomain;
}
//# sourceMappingURL=createRootScope.js.map