12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232 |
- import { _getProvider, getApp, _registerComponent, registerVersion, SDK_VERSION } from '@firebase/app';
- import { ErrorFactory, FirebaseError, getModularInstance, calculateBackoffMillis, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';
- import { Component } from '@firebase/component';
- import { LogLevel, Logger } from '@firebase/logger';
- import '@firebase/installations';
- const name = "@firebase/remote-config";
- const version = "0.4.4";
- class RemoteConfigAbortSignal {
- constructor() {
- this.listeners = [];
- }
- addEventListener(listener) {
- this.listeners.push(listener);
- }
- abort() {
- this.listeners.forEach(listener => listener());
- }
- }
- const RC_COMPONENT_NAME = 'remote-config';
- const ERROR_DESCRIPTION_MAP = {
- ["registration-window" ]: 'Undefined window object. This SDK only supports usage in a browser environment.',
- ["registration-project-id" ]: 'Undefined project identifier. Check Firebase app initialization.',
- ["registration-api-key" ]: 'Undefined API key. Check Firebase app initialization.',
- ["registration-app-id" ]: 'Undefined app identifier. Check Firebase app initialization.',
- ["storage-open" ]: 'Error thrown when opening storage. Original error: {$originalErrorMessage}.',
- ["storage-get" ]: 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',
- ["storage-set" ]: 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',
- ["storage-delete" ]: 'Error thrown when deleting from storage. Original error: {$originalErrorMessage}.',
- ["fetch-client-network" ]: 'Fetch client failed to connect to a network. Check Internet connection.' +
- ' Original error: {$originalErrorMessage}.',
- ["fetch-timeout" ]: 'The config fetch request timed out. ' +
- ' Configure timeout using "fetchTimeoutMillis" SDK setting.',
- ["fetch-throttle" ]: 'The config fetch request timed out while in an exponential backoff state.' +
- ' Configure timeout using "fetchTimeoutMillis" SDK setting.' +
- ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
- ["fetch-client-parse" ]: 'Fetch client could not parse response.' +
- ' Original error: {$originalErrorMessage}.',
- ["fetch-status" ]: 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.',
- ["indexed-db-unavailable" ]: 'Indexed DB is not supported by current browser'
- };
- const ERROR_FACTORY = new ErrorFactory('remoteconfig' , 'Remote Config' , ERROR_DESCRIPTION_MAP);
- function hasErrorCode(e, errorCode) {
- return e instanceof FirebaseError && e.code.indexOf(errorCode) !== -1;
- }
- const DEFAULT_VALUE_FOR_BOOLEAN = false;
- const DEFAULT_VALUE_FOR_STRING = '';
- const DEFAULT_VALUE_FOR_NUMBER = 0;
- const BOOLEAN_TRUTHY_VALUES = ['1', 'true', 't', 'yes', 'y', 'on'];
- class Value {
- constructor(_source, _value = DEFAULT_VALUE_FOR_STRING) {
- this._source = _source;
- this._value = _value;
- }
- asString() {
- return this._value;
- }
- asBoolean() {
- if (this._source === 'static') {
- return DEFAULT_VALUE_FOR_BOOLEAN;
- }
- return BOOLEAN_TRUTHY_VALUES.indexOf(this._value.toLowerCase()) >= 0;
- }
- asNumber() {
- if (this._source === 'static') {
- return DEFAULT_VALUE_FOR_NUMBER;
- }
- let num = Number(this._value);
- if (isNaN(num)) {
- num = DEFAULT_VALUE_FOR_NUMBER;
- }
- return num;
- }
- getSource() {
- return this._source;
- }
- }
- function getRemoteConfig(app = getApp()) {
- app = getModularInstance(app);
- const rcProvider = _getProvider(app, RC_COMPONENT_NAME);
- return rcProvider.getImmediate();
- }
- async function activate(remoteConfig) {
- const rc = getModularInstance(remoteConfig);
- const [lastSuccessfulFetchResponse, activeConfigEtag] = await Promise.all([
- rc._storage.getLastSuccessfulFetchResponse(),
- rc._storage.getActiveConfigEtag()
- ]);
- if (!lastSuccessfulFetchResponse ||
- !lastSuccessfulFetchResponse.config ||
- !lastSuccessfulFetchResponse.eTag ||
- lastSuccessfulFetchResponse.eTag === activeConfigEtag) {
-
-
- return false;
- }
- await Promise.all([
- rc._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config),
- rc._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag)
- ]);
- return true;
- }
- function ensureInitialized(remoteConfig) {
- const rc = getModularInstance(remoteConfig);
- if (!rc._initializePromise) {
- rc._initializePromise = rc._storageCache.loadFromStorage().then(() => {
- rc._isInitializationComplete = true;
- });
- }
- return rc._initializePromise;
- }
- async function fetchConfig(remoteConfig) {
- const rc = getModularInstance(remoteConfig);
-
-
-
-
-
-
-
-
-
-
- const abortSignal = new RemoteConfigAbortSignal();
- setTimeout(async () => {
-
- abortSignal.abort();
- }, rc.settings.fetchTimeoutMillis);
-
- try {
- await rc._client.fetch({
- cacheMaxAgeMillis: rc.settings.minimumFetchIntervalMillis,
- signal: abortSignal
- });
- await rc._storageCache.setLastFetchStatus('success');
- }
- catch (e) {
- const lastFetchStatus = hasErrorCode(e, "fetch-throttle" )
- ? 'throttle'
- : 'failure';
- await rc._storageCache.setLastFetchStatus(lastFetchStatus);
- throw e;
- }
- }
- function getAll(remoteConfig) {
- const rc = getModularInstance(remoteConfig);
- return getAllKeys(rc._storageCache.getActiveConfig(), rc.defaultConfig).reduce((allConfigs, key) => {
- allConfigs[key] = getValue(remoteConfig, key);
- return allConfigs;
- }, {});
- }
- function getBoolean(remoteConfig, key) {
- return getValue(getModularInstance(remoteConfig), key).asBoolean();
- }
- function getNumber(remoteConfig, key) {
- return getValue(getModularInstance(remoteConfig), key).asNumber();
- }
- function getString(remoteConfig, key) {
- return getValue(getModularInstance(remoteConfig), key).asString();
- }
- function getValue(remoteConfig, key) {
- const rc = getModularInstance(remoteConfig);
- if (!rc._isInitializationComplete) {
- rc._logger.debug(`A value was requested for key "${key}" before SDK initialization completed.` +
- ' Await on ensureInitialized if the intent was to get a previously activated value.');
- }
- const activeConfig = rc._storageCache.getActiveConfig();
- if (activeConfig && activeConfig[key] !== undefined) {
- return new Value('remote', activeConfig[key]);
- }
- else if (rc.defaultConfig && rc.defaultConfig[key] !== undefined) {
- return new Value('default', String(rc.defaultConfig[key]));
- }
- rc._logger.debug(`Returning static value for key "${key}".` +
- ' Define a default or remote value if this is unintentional.');
- return new Value('static');
- }
- function setLogLevel(remoteConfig, logLevel) {
- const rc = getModularInstance(remoteConfig);
- switch (logLevel) {
- case 'debug':
- rc._logger.logLevel = LogLevel.DEBUG;
- break;
- case 'silent':
- rc._logger.logLevel = LogLevel.SILENT;
- break;
- default:
- rc._logger.logLevel = LogLevel.ERROR;
- }
- }
- function getAllKeys(obj1 = {}, obj2 = {}) {
- return Object.keys(Object.assign(Object.assign({}, obj1), obj2));
- }
- class CachingClient {
- constructor(client, storage, storageCache, logger) {
- this.client = client;
- this.storage = storage;
- this.storageCache = storageCache;
- this.logger = logger;
- }
-
- isCachedDataFresh(cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis) {
-
- if (!lastSuccessfulFetchTimestampMillis) {
- this.logger.debug('Config fetch cache check. Cache unpopulated.');
- return false;
- }
-
- const cacheAgeMillis = Date.now() - lastSuccessfulFetchTimestampMillis;
- const isCachedDataFresh = cacheAgeMillis <= cacheMaxAgeMillis;
- this.logger.debug('Config fetch cache check.' +
- ` Cache age millis: ${cacheAgeMillis}.` +
- ` Cache max age millis (minimumFetchIntervalMillis setting): ${cacheMaxAgeMillis}.` +
- ` Is cache hit: ${isCachedDataFresh}.`);
- return isCachedDataFresh;
- }
- async fetch(request) {
-
- const [lastSuccessfulFetchTimestampMillis, lastSuccessfulFetchResponse] = await Promise.all([
- this.storage.getLastSuccessfulFetchTimestampMillis(),
- this.storage.getLastSuccessfulFetchResponse()
- ]);
-
- if (lastSuccessfulFetchResponse &&
- this.isCachedDataFresh(request.cacheMaxAgeMillis, lastSuccessfulFetchTimestampMillis)) {
- return lastSuccessfulFetchResponse;
- }
-
-
- request.eTag =
- lastSuccessfulFetchResponse && lastSuccessfulFetchResponse.eTag;
-
- const response = await this.client.fetch(request);
-
- const storageOperations = [
-
- this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())
- ];
- if (response.status === 200) {
-
- storageOperations.push(this.storage.setLastSuccessfulFetchResponse(response));
- }
- await Promise.all(storageOperations);
- return response;
- }
- }
- function getUserLanguage(navigatorLanguage = navigator) {
- return (
-
- (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
-
-
- navigatorLanguage.language
-
- );
- }
- class RestClient {
- constructor(firebaseInstallations, sdkVersion, namespace, projectId, apiKey, appId) {
- this.firebaseInstallations = firebaseInstallations;
- this.sdkVersion = sdkVersion;
- this.namespace = namespace;
- this.projectId = projectId;
- this.apiKey = apiKey;
- this.appId = appId;
- }
-
- async fetch(request) {
- const [installationId, installationToken] = await Promise.all([
- this.firebaseInstallations.getId(),
- this.firebaseInstallations.getToken()
- ]);
- const urlBase = window.FIREBASE_REMOTE_CONFIG_URL_BASE ||
- 'https://firebaseremoteconfig.googleapis.com';
- const url = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`;
- const headers = {
- 'Content-Type': 'application/json',
- 'Content-Encoding': 'gzip',
-
-
- 'If-None-Match': request.eTag || '*'
- };
- const requestBody = {
-
- sdk_version: this.sdkVersion,
- app_instance_id: installationId,
- app_instance_id_token: installationToken,
- app_id: this.appId,
- language_code: getUserLanguage()
-
- };
- const options = {
- method: 'POST',
- headers,
- body: JSON.stringify(requestBody)
- };
-
- const fetchPromise = fetch(url, options);
- const timeoutPromise = new Promise((_resolve, reject) => {
-
- request.signal.addEventListener(() => {
-
- const error = new Error('The operation was aborted.');
- error.name = 'AbortError';
- reject(error);
- });
- });
- let response;
- try {
- await Promise.race([fetchPromise, timeoutPromise]);
- response = await fetchPromise;
- }
- catch (originalError) {
- let errorCode = "fetch-client-network" ;
- if ((originalError === null || originalError === void 0 ? void 0 : originalError.name) === 'AbortError') {
- errorCode = "fetch-timeout" ;
- }
- throw ERROR_FACTORY.create(errorCode, {
- originalErrorMessage: originalError === null || originalError === void 0 ? void 0 : originalError.message
- });
- }
- let status = response.status;
-
- const responseEtag = response.headers.get('ETag') || undefined;
- let config;
- let state;
-
-
- if (response.status === 200) {
- let responseBody;
- try {
- responseBody = await response.json();
- }
- catch (originalError) {
- throw ERROR_FACTORY.create("fetch-client-parse" , {
- originalErrorMessage: originalError === null || originalError === void 0 ? void 0 : originalError.message
- });
- }
- config = responseBody['entries'];
- state = responseBody['state'];
- }
-
- if (state === 'INSTANCE_STATE_UNSPECIFIED') {
- status = 500;
- }
- else if (state === 'NO_CHANGE') {
- status = 304;
- }
- else if (state === 'NO_TEMPLATE' || state === 'EMPTY_CONFIG') {
-
- config = {};
- }
-
-
-
-
- if (status !== 304 && status !== 200) {
- throw ERROR_FACTORY.create("fetch-status" , {
- httpStatus: status
- });
- }
- return { status, eTag: responseEtag, config };
- }
- }
- function setAbortableTimeout(signal, throttleEndTimeMillis) {
- return new Promise((resolve, reject) => {
-
- const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);
- const timeout = setTimeout(resolve, backoffMillis);
-
- signal.addEventListener(() => {
- clearTimeout(timeout);
-
- reject(ERROR_FACTORY.create("fetch-throttle" , {
- throttleEndTimeMillis
- }));
- });
- });
- }
- function isRetriableError(e) {
- if (!(e instanceof FirebaseError) || !e.customData) {
- return false;
- }
-
- const httpStatus = Number(e.customData['httpStatus']);
- return (httpStatus === 429 ||
- httpStatus === 500 ||
- httpStatus === 503 ||
- httpStatus === 504);
- }
- class RetryingClient {
- constructor(client, storage) {
- this.client = client;
- this.storage = storage;
- }
- async fetch(request) {
- const throttleMetadata = (await this.storage.getThrottleMetadata()) || {
- backoffCount: 0,
- throttleEndTimeMillis: Date.now()
- };
- return this.attemptFetch(request, throttleMetadata);
- }
-
- async attemptFetch(request, { throttleEndTimeMillis, backoffCount }) {
-
-
-
- await setAbortableTimeout(request.signal, throttleEndTimeMillis);
- try {
- const response = await this.client.fetch(request);
-
- await this.storage.deleteThrottleMetadata();
- return response;
- }
- catch (e) {
- if (!isRetriableError(e)) {
- throw e;
- }
-
- const throttleMetadata = {
- throttleEndTimeMillis: Date.now() + calculateBackoffMillis(backoffCount),
- backoffCount: backoffCount + 1
- };
-
- await this.storage.setThrottleMetadata(throttleMetadata);
- return this.attemptFetch(request, throttleMetadata);
- }
- }
- }
- const DEFAULT_FETCH_TIMEOUT_MILLIS = 60 * 1000;
- const DEFAULT_CACHE_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000;
- class RemoteConfig {
- constructor(
- // Required by FirebaseServiceFactory interface.
- app,
- // JS doesn't support private yet
- // (https://github.com/tc39/proposal-class-fields#private-fields), so we hint using an
- // underscore prefix.
- /**
- * @internal
- */
- _client,
- /**
- * @internal
- */
- _storageCache,
- /**
- * @internal
- */
- _storage,
- /**
- * @internal
- */
- _logger) {
- this.app = app;
- this._client = _client;
- this._storageCache = _storageCache;
- this._storage = _storage;
- this._logger = _logger;
-
- this._isInitializationComplete = false;
- this.settings = {
- fetchTimeoutMillis: DEFAULT_FETCH_TIMEOUT_MILLIS,
- minimumFetchIntervalMillis: DEFAULT_CACHE_MAX_AGE_MILLIS
- };
- this.defaultConfig = {};
- }
- get fetchTimeMillis() {
- return this._storageCache.getLastSuccessfulFetchTimestampMillis() || -1;
- }
- get lastFetchStatus() {
- return this._storageCache.getLastFetchStatus() || 'no-fetch-yet';
- }
- }
- function toFirebaseError(event, errorCode) {
- const originalError = event.target.error || undefined;
- return ERROR_FACTORY.create(errorCode, {
- originalErrorMessage: originalError && (originalError === null || originalError === void 0 ? void 0 : originalError.message)
- });
- }
- const APP_NAMESPACE_STORE = 'app_namespace_store';
- const DB_NAME = 'firebase_remote_config';
- const DB_VERSION = 1;
- function openDatabase() {
- return new Promise((resolve, reject) => {
- try {
- const request = indexedDB.open(DB_NAME, DB_VERSION);
- request.onerror = event => {
- reject(toFirebaseError(event, "storage-open" ));
- };
- request.onsuccess = event => {
- resolve(event.target.result);
- };
- request.onupgradeneeded = event => {
- const db = event.target.result;
-
-
-
-
-
- switch (event.oldVersion) {
- case 0:
- db.createObjectStore(APP_NAMESPACE_STORE, {
- keyPath: 'compositeKey'
- });
- }
- };
- }
- catch (error) {
- reject(ERROR_FACTORY.create("storage-open" , {
- originalErrorMessage: error === null || error === void 0 ? void 0 : error.message
- }));
- }
- });
- }
- class Storage {
-
- constructor(appId, appName, namespace, openDbPromise = openDatabase()) {
- this.appId = appId;
- this.appName = appName;
- this.namespace = namespace;
- this.openDbPromise = openDbPromise;
- }
- getLastFetchStatus() {
- return this.get('last_fetch_status');
- }
- setLastFetchStatus(status) {
- return this.set('last_fetch_status', status);
- }
-
-
- getLastSuccessfulFetchTimestampMillis() {
- return this.get('last_successful_fetch_timestamp_millis');
- }
- setLastSuccessfulFetchTimestampMillis(timestamp) {
- return this.set('last_successful_fetch_timestamp_millis', timestamp);
- }
- getLastSuccessfulFetchResponse() {
- return this.get('last_successful_fetch_response');
- }
- setLastSuccessfulFetchResponse(response) {
- return this.set('last_successful_fetch_response', response);
- }
- getActiveConfig() {
- return this.get('active_config');
- }
- setActiveConfig(config) {
- return this.set('active_config', config);
- }
- getActiveConfigEtag() {
- return this.get('active_config_etag');
- }
- setActiveConfigEtag(etag) {
- return this.set('active_config_etag', etag);
- }
- getThrottleMetadata() {
- return this.get('throttle_metadata');
- }
- setThrottleMetadata(metadata) {
- return this.set('throttle_metadata', metadata);
- }
- deleteThrottleMetadata() {
- return this.delete('throttle_metadata');
- }
- async get(key) {
- const db = await this.openDbPromise;
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([APP_NAMESPACE_STORE], 'readonly');
- const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
- const compositeKey = this.createCompositeKey(key);
- try {
- const request = objectStore.get(compositeKey);
- request.onerror = event => {
- reject(toFirebaseError(event, "storage-get" ));
- };
- request.onsuccess = event => {
- const result = event.target.result;
- if (result) {
- resolve(result.value);
- }
- else {
- resolve(undefined);
- }
- };
- }
- catch (e) {
- reject(ERROR_FACTORY.create("storage-get" , {
- originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
- }));
- }
- });
- }
- async set(key, value) {
- const db = await this.openDbPromise;
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');
- const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
- const compositeKey = this.createCompositeKey(key);
- try {
- const request = objectStore.put({
- compositeKey,
- value
- });
- request.onerror = (event) => {
- reject(toFirebaseError(event, "storage-set" ));
- };
- request.onsuccess = () => {
- resolve();
- };
- }
- catch (e) {
- reject(ERROR_FACTORY.create("storage-set" , {
- originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
- }));
- }
- });
- }
- async delete(key) {
- const db = await this.openDbPromise;
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');
- const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);
- const compositeKey = this.createCompositeKey(key);
- try {
- const request = objectStore.delete(compositeKey);
- request.onerror = (event) => {
- reject(toFirebaseError(event, "storage-delete" ));
- };
- request.onsuccess = () => {
- resolve();
- };
- }
- catch (e) {
- reject(ERROR_FACTORY.create("storage-delete" , {
- originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
- }));
- }
- });
- }
-
- createCompositeKey(key) {
- return [this.appId, this.appName, this.namespace, key].join();
- }
- }
- class StorageCache {
- constructor(storage) {
- this.storage = storage;
- }
-
- getLastFetchStatus() {
- return this.lastFetchStatus;
- }
- getLastSuccessfulFetchTimestampMillis() {
- return this.lastSuccessfulFetchTimestampMillis;
- }
- getActiveConfig() {
- return this.activeConfig;
- }
-
- async loadFromStorage() {
- const lastFetchStatusPromise = this.storage.getLastFetchStatus();
- const lastSuccessfulFetchTimestampMillisPromise = this.storage.getLastSuccessfulFetchTimestampMillis();
- const activeConfigPromise = this.storage.getActiveConfig();
-
-
-
-
-
- const lastFetchStatus = await lastFetchStatusPromise;
- if (lastFetchStatus) {
- this.lastFetchStatus = lastFetchStatus;
- }
- const lastSuccessfulFetchTimestampMillis = await lastSuccessfulFetchTimestampMillisPromise;
- if (lastSuccessfulFetchTimestampMillis) {
- this.lastSuccessfulFetchTimestampMillis =
- lastSuccessfulFetchTimestampMillis;
- }
- const activeConfig = await activeConfigPromise;
- if (activeConfig) {
- this.activeConfig = activeConfig;
- }
- }
-
- setLastFetchStatus(status) {
- this.lastFetchStatus = status;
- return this.storage.setLastFetchStatus(status);
- }
- setLastSuccessfulFetchTimestampMillis(timestampMillis) {
- this.lastSuccessfulFetchTimestampMillis = timestampMillis;
- return this.storage.setLastSuccessfulFetchTimestampMillis(timestampMillis);
- }
- setActiveConfig(activeConfig) {
- this.activeConfig = activeConfig;
- return this.storage.setActiveConfig(activeConfig);
- }
- }
- function registerRemoteConfig() {
- _registerComponent(new Component(RC_COMPONENT_NAME, remoteConfigFactory, "PUBLIC" ).setMultipleInstances(true));
- registerVersion(name, version);
-
- registerVersion(name, version, 'esm2017');
- function remoteConfigFactory(container, { instanceIdentifier: namespace }) {
-
-
- const app = container.getProvider('app').getImmediate();
-
- const installations = container
- .getProvider('installations-internal')
- .getImmediate();
-
- if (typeof window === 'undefined') {
- throw ERROR_FACTORY.create("registration-window" );
- }
-
- if (!isIndexedDBAvailable()) {
- throw ERROR_FACTORY.create("indexed-db-unavailable" );
- }
-
- const { projectId, apiKey, appId } = app.options;
- if (!projectId) {
- throw ERROR_FACTORY.create("registration-project-id" );
- }
- if (!apiKey) {
- throw ERROR_FACTORY.create("registration-api-key" );
- }
- if (!appId) {
- throw ERROR_FACTORY.create("registration-app-id" );
- }
- namespace = namespace || 'firebase';
- const storage = new Storage(appId, app.name, namespace);
- const storageCache = new StorageCache(storage);
- const logger = new Logger(name);
-
-
- logger.logLevel = LogLevel.ERROR;
- const restClient = new RestClient(installations,
-
- SDK_VERSION, namespace, projectId, apiKey, appId);
- const retryingClient = new RetryingClient(restClient, storage);
- const cachingClient = new CachingClient(retryingClient, storage, storageCache, logger);
- const remoteConfigInstance = new RemoteConfig(app, cachingClient, storageCache, storage, logger);
-
-
- ensureInitialized(remoteConfigInstance);
- return remoteConfigInstance;
- }
- }
- async function fetchAndActivate(remoteConfig) {
- remoteConfig = getModularInstance(remoteConfig);
- await fetchConfig(remoteConfig);
- return activate(remoteConfig);
- }
- async function isSupported() {
- if (!isIndexedDBAvailable()) {
- return false;
- }
- try {
- const isDBOpenable = await validateIndexedDBOpenable();
- return isDBOpenable;
- }
- catch (error) {
- return false;
- }
- }
- registerRemoteConfig();
- export { activate, ensureInitialized, fetchAndActivate, fetchConfig, getAll, getBoolean, getNumber, getRemoteConfig, getString, getValue, isSupported, setLogLevel };
|