UNPKG

@aws-amplify/core

Version:
75 lines (73 loc) 3.04 kB
'use strict'; // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 Object.defineProperty(exports, "__esModule", { value: true }); exports.clearCache = exports.observeFrameworkChanges = exports.detectFramework = exports.frameworkChangeObservers = void 0; const types_1 = require("./types"); const detection_1 = require("./detection"); // We want to cache detection since the framework won't change let frameworkCache; exports.frameworkChangeObservers = []; // Setup the detection reset tracking / timeout delays let resetTriggered = false; const SSR_RESET_TIMEOUT = 10; // ms const WEB_RESET_TIMEOUT = 10; // ms const PRIME_FRAMEWORK_DELAY = 1000; // ms const detectFramework = () => { if (!frameworkCache) { frameworkCache = (0, detection_1.detect)(); if (resetTriggered) { // The final run of detectFramework: // Starting from this point, the `frameworkCache` becomes "final". // So we don't need to notify the observers again so the observer // can be removed after the final notice. while (exports.frameworkChangeObservers.length) { exports.frameworkChangeObservers.pop()?.(); } } else { // The first run of detectFramework: // Every time we update the cache, call each observer function exports.frameworkChangeObservers.forEach(fcn => { fcn(); }); } // Retry once for either Unknown type after a delay (explained below) resetTimeout(types_1.Framework.ServerSideUnknown, SSR_RESET_TIMEOUT); resetTimeout(types_1.Framework.WebUnknown, WEB_RESET_TIMEOUT); } return frameworkCache; }; exports.detectFramework = detectFramework; /** * @internal Setup observer callback that will be called everytime the framework changes */ const observeFrameworkChanges = (fcn) => { // When the `frameworkCache` won't be updated again, we ignore all incoming // observers. if (resetTriggered) { return; } exports.frameworkChangeObservers.push(fcn); }; exports.observeFrameworkChanges = observeFrameworkChanges; function clearCache() { frameworkCache = undefined; } exports.clearCache = clearCache; // For a framework type and a delay amount, setup the event to re-detect // During the runtime boot, it is possible that framework detection will // be triggered before the framework has made modifications to the // global/window/etc needed for detection. When no framework is detected // we will reset and try again to ensure we don't use a cached // non-framework detection result for all requests. function resetTimeout(framework, delay) { if (frameworkCache === framework && !resetTriggered) { setTimeout(() => { clearCache(); resetTriggered = true; setTimeout(exports.detectFramework, PRIME_FRAMEWORK_DELAY); }, delay); } } //# sourceMappingURL=detectFramework.js.map