@aws-amplify/core
Version:
Core category of aws-amplify
71 lines (70 loc) • 2.99 kB
JavaScript
// 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;
var types_1 = require("./types");
var detection_1 = require("./detection");
// We want to cache detection since the framework won't change
var frameworkCache;
exports.frameworkChangeObservers = [];
// Setup the detection reset tracking / timeout delays
var resetTriggered = false;
var SSR_RESET_TIMEOUT = 10; // ms
var WEB_RESET_TIMEOUT = 10; // ms
var PRIME_FRAMEWORK_DELAY = 1000; // ms
var detectFramework = function () {
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(function (fcn) { return 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
*/
var observeFrameworkChanges = function (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(function () {
clearCache();
resetTriggered = true;
setTimeout(exports.detectFramework, PRIME_FRAMEWORK_DELAY);
}, delay);
}
}
;