firebase
Version:
Firebase JavaScript library for web and Node.js
4 lines (2 loc) • 45.1 kB
JavaScript
import{registerVersion as e,_registerComponent as t,_getProvider,getApp as i,SDK_VERSION as s}from"https://www.gstatic.com/firebasejs/12.8.0/firebase-app.js";const n="${JSCORE_VERSION}",assert=function(e,t){if(!e)throw assertionError(t)},assertionError=function(e){return new Error("Firebase Database ("+n+") INTERNAL ASSERT FAILED: "+e)};function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}class FirebaseError extends Error{constructor(e,t,i){super(t),this.code=e,this.customData=i,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,i){this.service=e,this.serviceName=t,this.errors=i}create(e,...t){const i=t[0]||{},s=`${this.service}/${e}`,n=this.errors[e],r=n?function replaceTemplate(e,t){return e.replace(a,((e,i)=>{const s=t[i];return null!=s?String(s):`<${i}?>`}))}(n,i):"Error",o=`${this.serviceName}: ${r} (${s}).`;return new FirebaseError(s,o,i)}}const a=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const i=Object.keys(e),s=Object.keys(t);for(const n of i){if(!s.includes(n))return!1;const i=e[n],a=t[n];if(isObject(i)&&isObject(a)){if(!deepEqual(i,a))return!1}else if(i!==a)return!1}for(const e of s)if(!i.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function calculateBackoffMillis(e,t=1e3,i=2){const s=t*Math.pow(i,e),n=Math.round(.5*s*(Math.random()-.5)*2);return Math.min(144e5,s+n)}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,t,i){this.name=e,this.instanceFactory=t,this.type=i,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var r;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(r||(r={}));const o={debug:r.DEBUG,verbose:r.VERBOSE,info:r.INFO,warn:r.WARN,error:r.ERROR,silent:r.SILENT},c=r.INFO,l={[r.DEBUG]:"log",[r.VERBOSE]:"log",[r.INFO]:"info",[r.WARN]:"warn",[r.ERROR]:"error"},defaultLogHandler=(e,t,...i)=>{if(t<e.logLevel)return;const s=(new Date).toISOString(),n=l[t];if(!n)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[n](`[${s}] ${e.name}:`,...i)};class Logger{constructor(e){this.name=e,this._logLevel=c,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in r))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?o[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,r.DEBUG,...e),this._logHandler(this,r.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,r.VERBOSE,...e),this._logHandler(this,r.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,r.INFO,...e),this._logHandler(this,r.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,r.WARN,...e),this._logHandler(this,r.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,r.ERROR,...e),this._logHandler(this,r.ERROR,...e)}}let g,u;const h=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,m=new WeakMap;let w={get(e,t,i){if(e instanceof IDBTransaction){if("done"===t)return d.get(e);if("objectStoreNames"===t)return e.objectStoreNames||f.get(e);if("store"===t)return i.objectStoreNames[1]?void 0:i.objectStore(i.objectStoreNames[0])}return wrap(e[t])},set:(e,t,i)=>(e[t]=i,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function wrapFunction(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?function getCursorAdvanceMethods(){return u||(u=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(e)?function(...t){return e.apply(unwrap(this),t),wrap(h.get(this))}:function(...t){return wrap(e.apply(unwrap(this),t))}:function(t,...i){const s=e.call(unwrap(this),t,...i);return f.set(s,t.sort?t.sort():[t]),wrap(s)}}function transformCachableValue(e){return"function"==typeof e?wrapFunction(e):(e instanceof IDBTransaction&&function cacheDonePromiseForTransaction(e){if(d.has(e))return;const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{t(),unlisten()},error=()=>{i(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)}));d.set(e,t)}(e),t=e,function getIdbProxyableTypes(){return g||(g=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}().some((e=>t instanceof e))?new Proxy(e,w):e);var t}function wrap(e){if(e instanceof IDBRequest)return function promisifyRequest(e){const t=new Promise(((t,i)=>{const unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{t(wrap(e.result)),unlisten()},error=()=>{i(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)}));return t.then((t=>{t instanceof IDBCursor&&h.set(t,e)})).catch((()=>{})),m.set(t,e),t}(e);if(p.has(e))return p.get(e);const t=transformCachableValue(e);return t!==e&&(p.set(e,t),m.set(t,e)),t}const unwrap=e=>m.get(e);const v=["get","getKey","getAll","getAllKeys","count"],y=["put","add","delete","clear"],b=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(b.get(t))return b.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,n=y.includes(i);if(!(i in(s?IDBIndex:IDBObjectStore).prototype)||!n&&!v.includes(i))return;const method=async function(e,...t){const a=this.transaction(e,n?"readwrite":"readonly");let r=a.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),n&&a.done]))[0]};return b.set(t,method),method}!function replaceTraps(e){w=e(w)}((e=>({...e,get:(t,i,s)=>getMethod(t,i)||e.get(t,i,s),has:(t,i)=>!!getMethod(t,i)||e.has(t,i)})));const E="@firebase/installations",C="0.6.19",I=1e4,S=`w:${C}`,T="FIS_v2",_=36e5,R=new ErrorFactory("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function isServerError(e){return e instanceof FirebaseError&&e.code.includes("request-failed")}function getInstallationsEndpoint({projectId:e}){return`https://firebaseinstallations.googleapis.com/v1/projects/${e}/installations`}function extractAuthTokenInfoFromResponse(e){return{token:e.token,requestStatus:2,expiresIn:(t=e.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()};var t}async function getErrorFromResponse(e,t){const i=(await t.json()).error;return R.create("request-failed",{requestName:e,serverCode:i.code,serverMessage:i.message,serverStatus:i.status})}function getHeaders({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function getHeadersWithAuth(e,{refreshToken:t}){const i=getHeaders(e);return i.append("Authorization",function getAuthorizationHeader(e){return`${T} ${e}`}(t)),i}async function retryIfServerError(e){const t=await e();return t.status>=500&&t.status<600?e():t}function sleep(e){return new Promise((t=>{setTimeout(t,e)}))}const k=/^[cdef][\w-]{21}$/;function generateFid(){try{const e=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(e),e[0]=112+e[0]%16;const t=function encode(e){const t=function bufferToBase64UrlSafe(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(e);return k.test(t)?t:""}catch{return""}}function getKey(e){return`${e.appName}!${e.appId}`}const M=new Map;function fidChanged(e,t){const i=getKey(e);callFidChangeCallbacks(i,t),function broadcastFidChange(e,t){const i=function getBroadcastChannel(){!F&&"BroadcastChannel"in self&&(F=new BroadcastChannel("[Firebase] FID Change"),F.onmessage=e=>{callFidChangeCallbacks(e.data.key,e.data.fid)});return F}();i&&i.postMessage({key:e,fid:t});!function closeBroadcastChannel(){0===M.size&&F&&(F.close(),F=null)}()}(i,t)}function callFidChangeCallbacks(e,t){const i=M.get(e);if(i)for(const e of i)e(t)}let F=null;const A="firebase-installations-store";let L=null;function getDbPromise(){return L||(L=function openDB(e,t,{blocked:i,upgrade:s,blocking:n,terminated:a}={}){const r=indexedDB.open(e,t),o=wrap(r);return s&&r.addEventListener("upgradeneeded",(e=>{s(wrap(r.result),e.oldVersion,e.newVersion,wrap(r.transaction),e)})),i&&r.addEventListener("blocked",(e=>i(e.oldVersion,e.newVersion,e))),o.then((e=>{a&&e.addEventListener("close",(()=>a())),n&&e.addEventListener("versionchange",(e=>n(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}("firebase-installations-database",1,{upgrade:(e,t)=>{if(0===t)e.createObjectStore(A)}})),L}async function set(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(A,"readwrite"),n=s.objectStore(A),a=await n.get(i);return await n.put(t,i),await s.done,a&&a.fid===t.fid||fidChanged(e,t.fid),t}async function remove(e){const t=getKey(e),i=(await getDbPromise()).transaction(A,"readwrite");await i.objectStore(A).delete(t),await i.done}async function update(e,t){const i=getKey(e),s=(await getDbPromise()).transaction(A,"readwrite"),n=s.objectStore(A),a=await n.get(i),r=t(a);return void 0===r?await n.delete(i):await n.put(r,i),await s.done,!r||a&&a.fid===r.fid||fidChanged(e,r.fid),r}async function getInstallationEntry(e){let t;const i=await update(e.appConfig,(i=>{const s=function updateOrCreateInstallationEntry(e){const t=e||{fid:generateFid(),registrationStatus:0};return clearTimedOutRequest(t)}(i),n=function triggerRegistrationIfNecessary(e,t){if(0===t.registrationStatus){if(!navigator.onLine){return{installationEntry:t,registrationPromise:Promise.reject(R.create("app-offline"))}}const i={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},s=async function registerInstallation(e,t){try{const i=await async function createInstallationRequest({appConfig:e,heartbeatServiceProvider:t},{fid:i}){const s=getInstallationsEndpoint(e),n=getHeaders(e),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={fid:i,authVersion:T,appId:e.appId,sdkVersion:S},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){const e=await c.json();return{fid:e.fid||i,registrationStatus:2,refreshToken:e.refreshToken,authToken:extractAuthTokenInfoFromResponse(e.authToken)}}throw await getErrorFromResponse("Create Installation",c)}(e,t);return set(e.appConfig,i)}catch(i){throw isServerError(i)&&409===i.customData.serverCode?await remove(e.appConfig):await set(e.appConfig,{fid:t.fid,registrationStatus:0}),i}}(e,i);return{installationEntry:i,registrationPromise:s}}return 1===t.registrationStatus?{installationEntry:t,registrationPromise:waitUntilFidRegistration(e)}:{installationEntry:t}}(e,s);return t=n.registrationPromise,n.installationEntry}));return""===i.fid?{installationEntry:await t}:{installationEntry:i,registrationPromise:t}}async function waitUntilFidRegistration(e){let t=await updateInstallationRequest(e.appConfig);for(;1===t.registrationStatus;)await sleep(100),t=await updateInstallationRequest(e.appConfig);if(0===t.registrationStatus){const{installationEntry:t,registrationPromise:i}=await getInstallationEntry(e);return i||t}return t}function updateInstallationRequest(e){return update(e,(e=>{if(!e)throw R.create("installation-not-found");return clearTimedOutRequest(e)}))}function clearTimedOutRequest(e){return function hasInstallationRequestTimedOut(e){return 1===e.registrationStatus&&e.registrationTime+I<Date.now()}(e)?{fid:e.fid,registrationStatus:0}:e}async function generateAuthTokenRequest({appConfig:e,heartbeatServiceProvider:t},i){const s=function getGenerateAuthTokenEndpoint(e,{fid:t}){return`${getInstallationsEndpoint(e)}/${t}/authTokens:generate`}(e,i),n=getHeadersWithAuth(e,i),a=t.getImmediate({optional:!0});if(a){const e=await a.getHeartbeatsHeader();e&&n.append("x-firebase-client",e)}const r={installation:{sdkVersion:S,appId:e.appId}},o={method:"POST",headers:n,body:JSON.stringify(r)},c=await retryIfServerError((()=>fetch(s,o)));if(c.ok){return extractAuthTokenInfoFromResponse(await c.json())}throw await getErrorFromResponse("Generate Auth Token",c)}async function refreshAuthToken(e,t=!1){let i;const s=await update(e.appConfig,(s=>{if(!isEntryRegistered(s))throw R.create("not-registered");const n=s.authToken;if(!t&&function isAuthTokenValid(e){return 2===e.requestStatus&&!function isAuthTokenExpired(e){const t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+_}(e)}(n))return s;if(1===n.requestStatus)return i=async function waitUntilAuthTokenRequest(e,t){let i=await updateAuthTokenRequest(e.appConfig);for(;1===i.authToken.requestStatus;)await sleep(100),i=await updateAuthTokenRequest(e.appConfig);const s=i.authToken;return 0===s.requestStatus?refreshAuthToken(e,t):s}(e,t),s;{if(!navigator.onLine)throw R.create("app-offline");const t=function makeAuthTokenRequestInProgressEntry(e){const t={requestStatus:1,requestTime:Date.now()};return{...e,authToken:t}}(s);return i=async function fetchAuthTokenFromServer(e,t){try{const i=await generateAuthTokenRequest(e,t),s={...t,authToken:i};return await set(e.appConfig,s),i}catch(i){if(!isServerError(i)||401!==i.customData.serverCode&&404!==i.customData.serverCode){const i={...t,authToken:{requestStatus:0}};await set(e.appConfig,i)}else await remove(e.appConfig);throw i}}(e,t),t}}));return i?await i:s.authToken}function updateAuthTokenRequest(e){return update(e,(e=>{if(!isEntryRegistered(e))throw R.create("not-registered");return function hasAuthTokenRequestTimedOut(e){return 1===e.requestStatus&&e.requestTime+I<Date.now()}(e.authToken)?{...e,authToken:{requestStatus:0}}:e}))}function isEntryRegistered(e){return void 0!==e&&2===e.registrationStatus}async function getToken(e,t=!1){const i=e;await async function completeInstallationRegistration(e){const{registrationPromise:t}=await getInstallationEntry(e);t&&await t}(i);return(await refreshAuthToken(i,t)).token}function getMissingValueError(e){return R.create("missing-app-config-values",{valueName:e})}const D="installations",publicFactory=e=>{const t=e.getProvider("app").getImmediate(),i=function extractAppConfig(e){if(!e||!e.options)throw getMissingValueError("App Configuration");if(!e.name)throw getMissingValueError("App Name");const t=["projectId","apiKey","appId"];for(const i of t)if(!e.options[i])throw getMissingValueError(i);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t);return{app:t,appConfig:i,heartbeatServiceProvider:_getProvider(t,"heartbeat"),_delete:()=>Promise.resolve()}},internalFactory=e=>{const t=e.getProvider("app").getImmediate(),i=_getProvider(t,D).getImmediate();return{getId:()=>async function getId(e){const t=e,{installationEntry:i,registrationPromise:s}=await getInstallationEntry(t);return s?s.catch(console.error):refreshAuthToken(t).catch(console.error),i.fid}(i),getToken:e=>getToken(i,e)}};!function registerInstallations(){t(new Component(D,publicFactory,"PUBLIC")),t(new Component("installations-internal",internalFactory,"PRIVATE"))}(),e(E,C),e(E,C,"esm2020");const x="@firebase/remote-config",B="0.8.0";class RemoteConfigAbortSignal{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach((e=>e()))}}const P="remote-config",O=new ErrorFactory("remoteconfig","Remote Config",{"already-initialized":"Remote Config already initialized","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","custom-signal-max-allowed-signals":"Setting more than {$maxSignals} custom signals is not supported.","stream-error":"The stream was not able to connect to the backend: {$originalErrorMessage}.","realtime-unavailable":"The Realtime service is unavailable: {$originalErrorMessage}","update-message-invalid":"The stream invalidation message was unparsable: {$originalErrorMessage}","update-not-fetched":"Unable to fetch the latest config: {$originalErrorMessage}","analytics-unavailable":"Connection to Firebase Analytics failed: {$originalErrorMessage}"});const N=["1","true","t","yes","y","on"];class Value{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&N.indexOf(this._value.toLowerCase())>=0}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return isNaN(e)&&(e=0),e}getSource(){return this._source}}class Experiment{constructor(e){this.storage=e._storage,this.logger=e._logger,this.analyticsProvider=e._analyticsProvider}async updateActiveExperiments(e){const t=await this.storage.getActiveExperiments()||new Set,i=this.createExperimentInfoMap(e);return this.addActiveExperiments(i),this.removeInactiveExperiments(t,i),this.storage.setActiveExperiments(new Set(i.keys()))}createExperimentInfoMap(e){const t=new Map;for(const i of e)t.set(i.experimentId,i);return t}addActiveExperiments(e){const t={};for(const[i,s]of e.entries())t[`firebase${i}`]=s.variantId;this.addExperimentToAnalytics(t)}removeInactiveExperiments(e,t){const i={};for(const s of e)t.has(s)||(i[`firebase${s}`]=null);this.addExperimentToAnalytics(i)}addExperimentToAnalytics(e){if(0!==Object.keys(e).length)try{const t=this.analyticsProvider.getImmediate({optional:!0});t?(t.setUserProperties(e),t.logEvent("set_firebase_experiment_state")):this.logger.warn("Analytics import failed. Verify if you have imported Firebase Analytics in your app code.")}catch(e){throw O.create("analytics-unavailable",{originalErrorMessage:e?.message})}}}function getRemoteConfig(e=i(),t={}){e=getModularInstance(e);const s=_getProvider(e,P);if(s.isInitialized()){if(deepEqual(s.getOptions(),t))return s.getImmediate();throw O.create("already-initialized")}s.initialize({options:t});const n=s.getImmediate();return t.initialFetchResponse&&(n._initializePromise=Promise.all([n._storage.setLastSuccessfulFetchResponse(t.initialFetchResponse),n._storage.setActiveConfigEtag(t.initialFetchResponse?.eTag||""),n._storage.setActiveConfigTemplateVersion(t.initialFetchResponse.templateVersion||0),n._storageCache.setLastSuccessfulFetchTimestampMillis(Date.now()),n._storageCache.setLastFetchStatus("success"),n._storageCache.setActiveConfig(t.initialFetchResponse?.config||{})]).then(),n._isInitializationComplete=!0),n}async function activate(e){const t=getModularInstance(e),[i,s]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);if(!(i&&i.config&&i.eTag&&i.templateVersion&&i.eTag!==s))return!1;const n=new Experiment(t),a=i.experiments?n.updateActiveExperiments(i.experiments):Promise.resolve();return await Promise.all([t._storageCache.setActiveConfig(i.config),t._storage.setActiveConfigEtag(i.eTag),t._storage.setActiveConfigTemplateVersion(i.templateVersion),a]),!0}function ensureInitialized(e){const t=getModularInstance(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then((()=>{t._isInitializationComplete=!0}))),t._initializePromise}async function fetchConfig(e){const t=getModularInstance(e),i=new RemoteConfigAbortSignal;setTimeout((async()=>{i.abort()}),t.settings.fetchTimeoutMillis);const s=t._storageCache.getCustomSignals();s&&t._logger.debug(`Fetching config with custom signals: ${JSON.stringify(s)}`);try{await t._client.fetch({cacheMaxAgeMillis:t.settings.minimumFetchIntervalMillis,signal:i,customSignals:s}),await t._storageCache.setLastFetchStatus("success")}catch(e){const i=function hasErrorCode(e,t){return e instanceof FirebaseError&&-1!==e.code.indexOf(t)}(e,"fetch-throttle")?"throttle":"failure";throw await t._storageCache.setLastFetchStatus(i),e}}function getAll(e){const t=getModularInstance(e);return function getAllKeys(e={},t={}){return Object.keys({...e,...t})}(t._storageCache.getActiveConfig(),t.defaultConfig).reduce(((t,i)=>(t[i]=getValue(e,i),t)),{})}function getBoolean(e,t){return getValue(getModularInstance(e),t).asBoolean()}function getNumber(e,t){return getValue(getModularInstance(e),t).asNumber()}function getString(e,t){return getValue(getModularInstance(e),t).asString()}function getValue(e,t){const i=getModularInstance(e);i._isInitializationComplete||i._logger.debug(`A value was requested for key "${t}" before SDK initialization completed. Await on ensureInitialized if the intent was to get a previously activated value.`);const s=i._storageCache.getActiveConfig();return s&&void 0!==s[t]?new Value("remote",s[t]):i.defaultConfig&&void 0!==i.defaultConfig[t]?new Value("default",String(i.defaultConfig[t])):(i._logger.debug(`Returning static value for key "${t}". Define a default or remote value if this is unintentional.`),new Value("static"))}function setLogLevel(e,t){const i=getModularInstance(e);switch(t){case"debug":i._logger.logLevel=r.DEBUG;break;case"silent":i._logger.logLevel=r.SILENT;break;default:i._logger.logLevel=r.ERROR}}async function setCustomSignals(e,t){const i=getModularInstance(e);if(0!==Object.keys(t).length){for(const e in t){if(e.length>250)return void i._logger.error(`Custom signal key ${e} is too long, max allowed length is 250.`);const s=t[e];if("string"==typeof s&&s.length>500)return void i._logger.error(`Value supplied for custom signal ${e} is too long, max allowed length is 500.`)}try{await i._storageCache.setCustomSignals(t)}catch(e){i._logger.error(`Error encountered while setting custom signals: ${e}`)}}}function onConfigUpdate(e,t){const i=getModularInstance(e);return i._realtimeHandler.addObserver(t),()=>{i._realtimeHandler.removeObserver(t)}}class CachingClient{constructor(e,t,i,s){this.client=e,this.storage=t,this.storageCache=i,this.logger=s}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;const i=Date.now()-t,s=i<=e;return this.logger.debug(`Config fetch cache check. Cache age millis: ${i}. Cache max age millis (minimumFetchIntervalMillis setting): ${e}. Is cache hit: ${s}.`),s}async fetch(e){const[t,i]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(i&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return i;e.eTag=i&&i.eTag;const s=await this.client.fetch(e),n=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===s.status&&n.push(this.storage.setLastSuccessfulFetchResponse(s)),await Promise.all(n),s}}function getUserLanguage(e=navigator){return e.languages&&e.languages[0]||e.language}class RestClient{constructor(e,t,i,s,n,a){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=i,this.projectId=s,this.apiKey=n,this.appId=a}async fetch(e){const[t,i]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),s=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,n={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":e.eTag||"*"},a={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:i,app_id:this.appId,language_code:getUserLanguage(),custom_signals:e.customSignals},r={method:"POST",headers:n,body:JSON.stringify(a)},o=fetch(s,r),c=new Promise(((t,i)=>{e.signal.addEventListener((()=>{const e=new Error("The operation was aborted.");e.name="AbortError",i(e)}))}));let l;try{await Promise.race([o,c]),l=await o}catch(e){let t="fetch-client-network";throw"AbortError"===e?.name&&(t="fetch-timeout"),O.create(t,{originalErrorMessage:e?.message})}let g=l.status;const u=l.headers.get("ETag")||void 0;let h,d,f,p;if(200===l.status){let e;try{e=await l.json()}catch(e){throw O.create("fetch-client-parse",{originalErrorMessage:e?.message})}h=e.entries,d=e.state,f=e.templateVersion,p=e.experimentDescriptions}if("INSTANCE_STATE_UNSPECIFIED"===d?g=500:"NO_CHANGE"===d?g=304:"NO_TEMPLATE"!==d&&"EMPTY_CONFIG"!==d||(h={},p=[]),304!==g&&200!==g)throw O.create("fetch-status",{httpStatus:g});return{status:g,eTag:u,config:h,templateVersion:f,experiments:p}}}class RetryingClient{constructor(e,t){this.client=e,this.storage=t}async fetch(e){const t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(e,{throttleEndTimeMillis:t,backoffCount:i}){await function setAbortableTimeout(e,t){return new Promise(((i,s)=>{const n=Math.max(t-Date.now(),0),a=setTimeout(i,n);e.addEventListener((()=>{clearTimeout(a),s(O.create("fetch-throttle",{throttleEndTimeMillis:t}))}))}))}(e.signal,t);try{const t=await this.client.fetch(e);return await this.storage.deleteThrottleMetadata(),t}catch(t){if(!function isRetriableError(e){if(!(e instanceof FirebaseError&&e.customData))return!1;const t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}(t))throw t;const s={throttleEndTimeMillis:Date.now()+calculateBackoffMillis(i),backoffCount:i+1};return await this.storage.setThrottleMetadata(s),this.attemptFetch(e,s)}}}class RemoteConfig{get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}constructor(e,t,i,s,n,a,r){this.app=e,this._client=t,this._storageCache=i,this._storage=s,this._logger=n,this._realtimeHandler=a,this._analyticsProvider=r,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}}function toFirebaseError(e,t){const i=e.target.error||void 0;return O.create(t,{originalErrorMessage:i&&i?.message})}const H="app_namespace_store";class Storage{getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getActiveExperiments(){return this.get("active_experiments")}setActiveExperiments(e){return this.set("active_experiments",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}getCustomSignals(){return this.get("custom_signals")}getRealtimeBackoffMetadata(){return this.get("realtime_backoff_metadata")}setRealtimeBackoffMetadata(e){return this.set("realtime_backoff_metadata",e)}getActiveConfigTemplateVersion(){return this.get("last_known_template_version")}setActiveConfigTemplateVersion(e){return this.set("last_known_template_version",e)}}class IndexedDbStorage extends Storage{constructor(e,t,i,s=function openDatabase(){return new Promise(((e,t)=>{try{const i=indexedDB.open("firebase_remote_config",1);i.onerror=e=>{t(toFirebaseError(e,"storage-open"))},i.onsuccess=t=>{e(t.target.result)},i.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(H,{keyPath:"compositeKey"})}}catch(e){t(O.create("storage-open",{originalErrorMessage:e?.message}))}}))}()){super(),this.appId=e,this.appName=t,this.namespace=i,this.openDbPromise=s}async setCustomSignals(e){const t=(await this.openDbPromise).transaction([H],"readwrite"),i=mergeCustomSignals(e,await this.getWithTransaction("custom_signals",t)||{});return await this.setWithTransaction("custom_signals",i,t),i}async getWithTransaction(e,t){return new Promise(((i,s)=>{const n=t.objectStore(H),a=this.createCompositeKey(e);try{const e=n.get(a);e.onerror=e=>{s(toFirebaseError(e,"storage-get"))},e.onsuccess=e=>{const t=e.target.result;i(t?t.value:void 0)}}catch(e){s(O.create("storage-get",{originalErrorMessage:e?.message}))}}))}async setWithTransaction(e,t,i){return new Promise(((s,n)=>{const a=i.objectStore(H),r=this.createCompositeKey(e);try{const e=a.put({compositeKey:r,value:t});e.onerror=e=>{n(toFirebaseError(e,"storage-set"))},e.onsuccess=()=>{s()}}catch(e){n(O.create("storage-set",{originalErrorMessage:e?.message}))}}))}async get(e){const t=(await this.openDbPromise).transaction([H],"readonly");return this.getWithTransaction(e,t)}async set(e,t){const i=(await this.openDbPromise).transaction([H],"readwrite");return this.setWithTransaction(e,t,i)}async delete(e){const t=await this.openDbPromise;return new Promise(((i,s)=>{const n=t.transaction([H],"readwrite").objectStore(H),a=this.createCompositeKey(e);try{const e=n.delete(a);e.onerror=e=>{s(toFirebaseError(e,"storage-delete"))},e.onsuccess=()=>{i()}}catch(e){s(O.create("storage-delete",{originalErrorMessage:e?.message}))}}))}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class InMemoryStorage extends Storage{constructor(){super(...arguments),this.storage={}}async get(e){return Promise.resolve(this.storage[e])}async set(e,t){return this.storage[e]=t,Promise.resolve(void 0)}async delete(e){return this.storage[e]=void 0,Promise.resolve()}async setCustomSignals(e){const t=this.storage.custom_signals||{};return this.storage.custom_signals=mergeCustomSignals(e,t),Promise.resolve(this.storage.custom_signals)}}function mergeCustomSignals(e,t){const i={...t,...e},s=Object.fromEntries(Object.entries(i).filter((([e,t])=>null!==t)).map((([e,t])=>"number"==typeof t?[e,t.toString()]:[e,t])));if(Object.keys(s).length>100)throw O.create("custom-signal-max-allowed-signals",{maxSignals:100});return s}class StorageCache{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}getCustomSignals(){return this.customSignals}async loadFromStorage(){const e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),i=this.storage.getActiveConfig(),s=this.storage.getCustomSignals(),n=await e;n&&(this.lastFetchStatus=n);const a=await t;a&&(this.lastSuccessfulFetchTimestampMillis=a);const r=await i;r&&(this.activeConfig=r);const o=await s;o&&(this.customSignals=o)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}async setCustomSignals(e){this.customSignals=await this.storage.setCustomSignals(e)}}class EventEmitter{constructor(e){this.allowedEvents_=e,this.listeners_={},assert(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const i=[...this.listeners_[e]];for(let e=0;e<i.length;e++)i[e].callback.apply(i[e].context,t)}}on(e,t,i){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:i});const s=this.getInitialEvent(e);s&&t.apply(i,s)}off(e,t,i){this.validateEventType_(e);const s=this.listeners_[e]||[];for(let e=0;e<s.length;e++)if(s[e].callback===t&&(!i||i===s[e].context))return void s.splice(e,1)}validateEventType_(e){assert(this.allowedEvents_.find((t=>t===e)),"Unknown event: "+e)}}class VisibilityMonitor extends EventEmitter{static getInstance(){return new VisibilityMonitor}constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}getInitialEvent(e){return assert("visible"===e,"Unknown event type: "+e),[this.visible_]}}const V="X-Goog-Api-Key",$="X-Goog-Firebase-Installations-Auth",j="featureDisabled",q="retryIntervalSeconds",U="latestTemplateVersionNumber";class RealtimeHandler{constructor(e,t,i,s,n,a,r,o,c,l){this.firebaseInstallations=e,this.storage=t,this.sdkVersion=i,this.namespace=s,this.projectId=n,this.apiKey=a,this.appId=r,this.logger=o,this.storageCache=c,this.cachingClient=l,this.observers=new Set,this.isConnectionActive=!1,this.isRealtimeDisabled=!1,this.httpRetriesRemaining=8,this.isInBackground=!1,this.decoder=new TextDecoder("utf-8"),this.isClosingConnection=!1,this.propagateError=e=>this.observers.forEach((t=>t.error?.(e))),this.isStatusCodeRetryable=e=>!e||[408,429,502,503,504].includes(e),this.setRetriesRemaining(),VisibilityMonitor.getInstance().on("visible",this.onVisibilityChange,this)}async setRetriesRemaining(){const e=await this.storage.getRealtimeBackoffMetadata(),t=e?.numFailedStreams||0;this.httpRetriesRemaining=Math.max(8-t,1)}async updateBackoffMetadataWithLastFailedStreamConnectionTime(e){const t=((await this.storage.getRealtimeBackoffMetadata())?.numFailedStreams||0)+1,i=calculateBackoffMillis(t,6e4,2);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(e.getTime()+i),numFailedStreams:t})}async updateBackoffMetadataWithRetryInterval(e){const t=Date.now(),i=new Date(t+1e3*e);await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:i,numFailedStreams:0}),await this.retryHttpConnectionWhenBackoffEnds()}async closeRealtimeHttpConnection(){if(!this.isClosingConnection){this.isClosingConnection=!0;try{this.reader&&await this.reader.cancel()}catch(e){this.logger.debug("Failed to cancel the reader, connection was lost.")}finally{this.reader=void 0}this.controller&&(await this.controller.abort(),this.controller=void 0),this.isClosingConnection=!1}}async resetRealtimeBackoff(){await this.storage.setRealtimeBackoffMetadata({backoffEndTimeMillis:new Date(-1),numFailedStreams:0})}resetRetryCount(){this.httpRetriesRemaining=8}async establishRealtimeConnection(e,t,i,s){const n=await this.storage.getActiveConfigEtag(),a=await this.storage.getActiveConfigTemplateVersion(),r={[V]:this.apiKey,[$]:i,"Content-Type":"application/json",Accept:"application/json","If-None-Match":n||"*","Content-Encoding":"gzip"},o={project:this.projectId,namespace:this.namespace,lastKnownVersionNumber:a,appId:this.appId,sdkVersion:this.sdkVersion,appInstanceId:t};return await fetch(e,{method:"POST",headers:r,body:JSON.stringify(o),signal:s})}getRealtimeUrl(){const e=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfigrealtime.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:streamFetchInvalidations?key=${this.apiKey}`;return new URL(e)}async createRealtimeConnection(){const[e,t]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken(!1)]);this.controller=new AbortController;const i=this.getRealtimeUrl();return await this.establishRealtimeConnection(i,e,t,this.controller.signal)}async retryHttpConnectionWhenBackoffEnds(){let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=new Date(e.backoffEndTimeMillis).getTime(),i=Date.now(),s=Math.max(0,t-i);await this.makeRealtimeHttpConnection(s)}setIsHttpConnectionRunning(e){this.isConnectionActive=e}checkAndSetHttpConnectionFlagIfNotRunning(){const e=this.canEstablishStreamConnection();return e&&this.setIsHttpConnectionRunning(!0),e}fetchResponseIsUpToDate(e,t){return null!=e.config&&e.templateVersion?e.templateVersion>=t:"success"===this.storageCache.getLastFetchStatus()}parseAndValidateConfigUpdateMessage(e){const t=e.indexOf("{"),i=e.indexOf("}",t);return t<0||i<0||t>=i?"":e.substring(t,i+1)}isEventListenersEmpty(){return 0===this.observers.size}getRandomInt(e){return Math.floor(Math.random()*e)}executeAllListenerCallbacks(e){this.observers.forEach((t=>t.next(e)))}getChangedParams(e,t){const i=new Set,s=new Set(Object.keys(e||{})),n=new Set(Object.keys(t||{}));for(const a of s)n.has(a)&&e[a]===t[a]||i.add(a);for(const e of n)s.has(e)||i.add(e);return i}async fetchLatestConfig(e,t){const i=e-1,s=3-i,n=this.storageCache.getCustomSignals();n&&this.logger.debug(`Fetching config with custom signals: ${JSON.stringify(n)}`);const a=new RemoteConfigAbortSignal;try{const e={cacheMaxAgeMillis:0,signal:a,customSignals:n,fetchType:"REALTIME",fetchAttempt:s},r=await this.cachingClient.fetch(e);let o=await this.storage.getActiveConfig();if(!this.fetchResponseIsUpToDate(r,t))return this.logger.debug("Fetched template version is the same as SDK's current version. Retrying fetch."),void await this.autoFetch(i,t);if(null==r.config)return void this.logger.debug("The fetch succeeded, but the backend had no updates.");null==o&&(o={});const c=this.getChangedParams(r.config,o);if(0===c.size)return void this.logger.debug("Config was fetched, but no params changed.");const l={getUpdatedKeys:()=>new Set(c)};this.executeAllListenerCallbacks(l)}catch(e){const t=e instanceof Error?e.message:String(e),i=O.create("update-not-fetched",{originalErrorMessage:`Failed to auto-fetch config update: ${t}`});this.propagateError(i)}}async autoFetch(e,t){if(0===e){const e=O.create("update-not-fetched",{originalErrorMessage:"Unable to fetch the latest version of the template."});return void this.propagateError(e)}const i=1e3*this.getRandomInt(4);await new Promise((e=>setTimeout(e,i))),await this.fetchLatestConfig(e,t)}async handleNotifications(e){let t,i="";for(;;){const{done:s,value:n}=await e.read();if(s)break;if(t=this.decoder.decode(n,{stream:!0}),i+=t,t.includes("}")){if(i=this.parseAndValidateConfigUpdateMessage(i),0===i.length)continue;try{const e=JSON.parse(i);if(this.isEventListenersEmpty())break;if(j in e&&!0===e[j]){const e=O.create("realtime-unavailable",{originalErrorMessage:"The server is temporarily unavailable. Try again in a few minutes."});this.propagateError(e);break}if(U in e){const t=await this.storage.getActiveConfigTemplateVersion(),i=Number(e[U]);t&&i>t&&await this.autoFetch(3,i)}if(q in e){const t=Number(e[q]);await this.updateBackoffMetadataWithRetryInterval(t)}}catch(e){this.logger.debug("Unable to parse latest config update message.",e);const t=e instanceof Error?e.message:String(e);this.propagateError(O.create("update-message-invalid",{originalErrorMessage:t}))}i=""}}}async listenForNotifications(e){try{await this.handleNotifications(e)}catch(e){this.isInBackground||this.logger.debug("Real-time connection was closed due to an exception.")}}async prepareAndBeginRealtimeHttpStream(){if(!this.checkAndSetHttpConnectionFlagIfNotRunning())return;let e=await this.storage.getRealtimeBackoffMetadata();e||(e={backoffEndTimeMillis:new Date(-1),numFailedStreams:0});const t=e.backoffEndTimeMillis.getTime();if(Date.now()<t)return void await this.retryHttpConnectionWhenBackoffEnds();let i,s;try{if(i=await this.createRealtimeConnection(),s=i.status,i.ok&&i.body){this.resetRetryCount(),await this.resetRealtimeBackoff();const e=i.body.getReader();this.reader=e,await this.listenForNotifications(e)}}catch(e){this.isInBackground?this.resetRetryCount():this.logger.debug("Exception connecting to real-time RC backend. Retrying the connection...:",e)}finally{await this.closeRealtimeHttpConnection(),this.setIsHttpConnectionRunning(!1);const e=!this.isInBackground&&(void 0===s||this.isStatusCodeRetryable(s));if(e&&await this.updateBackoffMetadataWithLastFailedStreamConnectionTime(new Date),e||i?.ok)await this.retryHttpConnectionWhenBackoffEnds();else{const e=`Unable to connect to the server. HTTP status code: ${s}`,t=O.create("stream-error",{originalErrorMessage:e});this.propagateError(t)}}}canEstablishStreamConnection(){const e=this.observers.size>0,t=!this.isRealtimeDisabled,i=!this.isConnectionActive,s=!this.isInBackground;return e&&t&&i&&s}async makeRealtimeHttpConnection(e){if(this.canEstablishStreamConnection())if(this.httpRetriesRemaining>0)this.httpRetriesRemaining--,await new Promise((t=>setTimeout(t,e))),this.prepareAndBeginRealtimeHttpStream();else if(!this.isInBackground){const e=O.create("stream-error",{originalErrorMessage:"Unable to connect to the server. Check your connection and try again."});this.propagateError(e)}}async beginRealtime(){this.observers.size>0&&await this.makeRealtimeHttpConnection(0)}addObserver(e){this.observers.add(e),this.beginRealtime()}removeObserver(e){this.observers.has(e)&&this.observers.delete(e)}async onVisibilityChange(e){this.isInBackground=!e,e?e&&await this.beginRealtime():await this.closeRealtimeHttpConnection()}}async function fetchAndActivate(e){return e=getModularInstance(e),await fetchConfig(e),activate(e)}async function isSupported(){if(!isIndexedDBAvailable())return!1;try{return await function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let i=!0;const s="validate-browser-context-for-indexeddb-analytics-module",n=self.indexedDB.open(s);n.onsuccess=()=>{n.result.close(),i||self.indexedDB.deleteDatabase(s),e(!0)},n.onupgradeneeded=()=>{i=!1},n.onerror=()=>{t(n.error?.message||"")}}catch(e){t(e)}}))}()}catch(e){return!1}}!function registerRemoteConfig(){t(new Component(P,(function remoteConfigFactory(e,{options:t}){const i=e.getProvider("app").getImmediate(),n=e.getProvider("installations-internal").getImmediate(),a=e.getProvider("analytics-internal"),{projectId:o,apiKey:c,appId:l}=i.options;if(!o)throw O.create("registration-project-id");if(!c)throw O.create("registration-api-key");if(!l)throw O.create("registration-app-id");const g=t?.templateId||"firebase",u=isIndexedDBAvailable()?new IndexedDbStorage(l,i.name,g):new InMemoryStorage,h=new StorageCache(u),d=new Logger(x);d.logLevel=r.ERROR;const f=new RestClient(n,s,g,o,c,l),p=new RetryingClient(f,u),m=new CachingClient(p,u,h,d),w=new RealtimeHandler(n,u,s,g,o,c,l,d,h,m),v=new RemoteConfig(i,m,h,u,d,w,a);return ensureInitialized(v),v}),"PUBLIC").setMultipleInstances(!0)),e(x,B),e(x,B,"esm2020")}();export{activate,ensureInitialized,fetchAndActivate,fetchConfig,getAll,getBoolean,getNumber,getRemoteConfig,getString,getValue,isSupported,onConfigUpdate,setCustomSignals,setLogLevel};
//# sourceMappingURL=firebase-remote-config.js.map