firebase
Version:
Firebase JavaScript library for web and Node.js
3 lines (2 loc) • 28.3 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).firebase,t.firebase.INTERNAL.modularAPIs)}(this,function(qt,Ht){"use strict";try{!function(){function t(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var e=t(qt),i=function(t,e){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])})(t,e)};function s(t,e){for(var r=0,i=e.length,n=t.length;r<i;r++,n++)t[n]=e[r];return t}var n,a="FirebaseError",c=(function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function r(){this.constructor=t}i(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}(o,n=Error),o);function o(t,e,r){e=n.call(this,e)||this;return e.code=t,e.customData=r,e.name=a,Object.setPrototypeOf(e,o.prototype),Error.captureStackTrace&&Error.captureStackTrace(e,u.prototype.create),e}var u=(r.prototype.create=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];var i,n=e[0]||{},a=this.service+"/"+t,t=this.errors[t],t=t?(i=n,t.replace(l,function(t,e){var r=i[e];return null!=r?String(r):"<"+e+"?>"})):"Error",t=this.serviceName+": "+t+" ("+a+").";return new c(a,t,n)},r);function r(t,e,r){this.service=t,this.serviceName=e,this.errors=r}var l=/\{\$([^}]+)}/g;function g(t){return t&&t._delegate?t._delegate:t}var h,f=(p.prototype.setInstantiationMode=function(t){return this.instantiationMode=t,this},p.prototype.setMultipleInstances=function(t){return this.multipleInstances=t,this},p.prototype.setServiceProps=function(t){return this.serviceProps=t,this},p.prototype.setInstanceCreatedCallback=function(t){return this.onInstanceCreated=t,this},p);function p(t,e,r){this.name=t,this.instanceFactory=e,this.type=r,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}(k=h=h||{})[k.DEBUG=0]="DEBUG",k[k.VERBOSE=1]="VERBOSE",k[k.INFO=2]="INFO",k[k.WARN=3]="WARN",k[k.ERROR=4]="ERROR",k[k.SILENT=5]="SILENT";function d(t,e){for(var r=[],i=2;i<arguments.length;i++)r[i-2]=arguments[i];if(!(e<t.logLevel)){var n=(new Date).toISOString(),a=y[e];if(!a)throw new Error("Attempted to log a message with an invalid logType (value: "+e+")");console[a].apply(console,s(["["+n+"] "+t.name+":"],r))}}var m={debug:h.DEBUG,verbose:h.VERBOSE,info:h.INFO,warn:h.WARN,error:h.ERROR,silent:h.SILENT},w=h.INFO,y=((k={})[h.DEBUG]="log",k[h.VERBOSE]="log",k[h.INFO]="info",k[h.WARN]="warn",k[h.ERROR]="error",k),_=(Object.defineProperty(v.prototype,"logLevel",{get:function(){return this._logLevel},set:function(t){if(!(t in h))throw new TypeError('Invalid value "'+t+'" assigned to `logLevel`');this._logLevel=t},enumerable:!1,configurable:!0}),v.prototype.setLogLevel=function(t){this._logLevel="string"==typeof t?m[t]:t},Object.defineProperty(v.prototype,"logHandler",{get:function(){return this._logHandler},set:function(t){if("function"!=typeof t)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=t},enumerable:!1,configurable:!0}),Object.defineProperty(v.prototype,"userLogHandler",{get:function(){return this._userLogHandler},set:function(t){this._userLogHandler=t},enumerable:!1,configurable:!0}),v.prototype.debug=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,s([this,h.DEBUG],t)),this._logHandler.apply(this,s([this,h.DEBUG],t))},v.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,s([this,h.VERBOSE],t)),this._logHandler.apply(this,s([this,h.VERBOSE],t))},v.prototype.info=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,s([this,h.INFO],t)),this._logHandler.apply(this,s([this,h.INFO],t))},v.prototype.warn=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,s([this,h.WARN],t)),this._logHandler.apply(this,s([this,h.WARN],t))},v.prototype.error=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,s([this,h.ERROR],t)),this._logHandler.apply(this,s([this,h.ERROR],t))},v);function v(t){this.name=t,this._logLevel=w,this._logHandler=d,this._userLogHandler=null}function b(r){return new Promise(function(t,e){r.onsuccess=function(){t(r.result)},r.onerror=function(){e(r.error)}})}function S(r,i,n){var a,t=new Promise(function(t,e){b(a=r[i].apply(r,n)).then(t,e)});return t.request=a,t}function C(t,r,e){e.forEach(function(e){Object.defineProperty(t.prototype,e,{get:function(){return this[r][e]},set:function(t){this[r][e]=t}})})}function E(e,r,i,t){t.forEach(function(t){t in i.prototype&&(e.prototype[t]=function(){return S(this[r],t,arguments)})})}function I(e,r,i,t){t.forEach(function(t){t in i.prototype&&(e.prototype[t]=function(){return this[r][t].apply(this[r],arguments)})})}function T(t,i,e,r){r.forEach(function(r){r in e.prototype&&(t.prototype[r]=function(){return t=this[i],(e=S(t,r,arguments)).then(function(t){if(t)return new L(t,e.request)});var t,e})})}function P(t){this._index=t}function L(t,e){this._cursor=t,this._request=e}function O(t){this._store=t}function M(r){this._tx=r,this.complete=new Promise(function(t,e){r.oncomplete=function(){t()},r.onerror=function(){e(r.error)},r.onabort=function(){e(r.error)}})}function F(t,e,r){this._db=t,this.oldVersion=e,this.transaction=new M(r)}function j(t){this._db=t}C(P,"_index",["name","keyPath","multiEntry","unique"]),E(P,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),T(P,"_index",IDBIndex,["openCursor","openKeyCursor"]),C(L,"_cursor",["direction","key","primaryKey","value"]),E(L,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach(function(r){r in IDBCursor.prototype&&(L.prototype[r]=function(){var e=this,t=arguments;return Promise.resolve().then(function(){return e._cursor[r].apply(e._cursor,t),b(e._request).then(function(t){if(t)return new L(t,e._request)})})})}),O.prototype.createIndex=function(){return new P(this._store.createIndex.apply(this._store,arguments))},O.prototype.index=function(){return new P(this._store.index.apply(this._store,arguments))},C(O,"_store",["name","keyPath","indexNames","autoIncrement"]),E(O,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),T(O,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),I(O,"_store",IDBObjectStore,["deleteIndex"]),M.prototype.objectStore=function(){return new O(this._tx.objectStore.apply(this._tx,arguments))},C(M,"_tx",["objectStoreNames","mode"]),I(M,"_tx",IDBTransaction,["abort"]),F.prototype.createObjectStore=function(){return new O(this._db.createObjectStore.apply(this._db,arguments))},C(F,"_db",["name","version","objectStoreNames"]),I(F,"_db",IDBDatabase,["deleteObjectStore","close"]),j.prototype.transaction=function(){return new M(this._db.transaction.apply(this._db,arguments))},C(j,"_db",["name","version","objectStoreNames"]),I(j,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach(function(n){[O,P].forEach(function(t){n in t.prototype&&(t.prototype[n.replace("open","iterate")]=function(){var t=(r=arguments,Array.prototype.slice.call(r)),e=t[t.length-1],r=this._store||this._index,i=r[n].apply(r,t.slice(0,-1));i.onsuccess=function(){e(i.result)}})})}),[P,O].forEach(function(t){t.prototype.getAll||(t.prototype.getAll=function(t,r){var i=this,n=[];return new Promise(function(e){i.iterateCursor(t,function(t){t?(n.push(t.value),void 0===r||n.length!=r?t.continue():e(n)):e(n)})})})});var k="0.5.0";const A=1e4,N=`w:${k}`,D="FIS_v2",R="https://firebaseinstallations.googleapis.com/v1",x=36e5;var B;const $=new u("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 q(t){return t instanceof c&&t.code.includes("request-failed")}function H({projectId:t}){return`${R}/projects/${t}/installations`}function K(t){return{token:t.token,requestStatus:2,expiresIn:(t=t.expiresIn,Number(t.replace("s","000"))),creationTime:Date.now()}}async function V(t,e){e=(await e.json()).error;return $.create("request-failed",{requestName:t,serverCode:e.code,serverMessage:e.message,serverStatus:e.status})}function U({apiKey:t}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":t})}function z(t,{refreshToken:e}){const r=U(t);return r.append("Authorization",(e=e,`${D} ${e}`)),r}async function G(t){var e=await t();return 500<=e.status&&e.status<600?t():e}function W(e){return new Promise(t=>{setTimeout(t,e)})}const J=/^[cdef][\w-]{21}$/,Y="";function Z(){try{const e=new Uint8Array(17),r=self.crypto||self.msCrypto;r.getRandomValues(e),e[0]=112+e[0]%16;var t=function(t){const e=function(t){const e=btoa(String.fromCharCode(...t));return e.replace(/\+/g,"-").replace(/\//g,"_")}(t);return e.substr(0,22)}(e);return J.test(t)?t:Y}catch(t){return Y}}function Q(t){return`${t.appName}!${t.appId}`}const X=new Map;function tt(t,e){t=Q(t);et(t,e),function(t,e){const r=function(){!rt&&"BroadcastChannel"in self&&(rt=new BroadcastChannel("[Firebase] FID Change"),rt.onmessage=t=>{et(t.data.key,t.data.fid)});return rt}();r&&r.postMessage({key:t,fid:e});0===X.size&&rt&&(rt.close(),rt=null)}(t,e)}function et(t,e){t=X.get(t);if(t)for(const r of t)r(e)}let rt=null;const it="firebase-installations-database",nt=1,at="firebase-installations-store";let st=null;function ot(){var t,e,r,i;return st=st||(t=it,e=nt,r=t=>{0===t.oldVersion&&t.createObjectStore(at)},(i=(e=S(indexedDB,"open",[t,e])).request)&&(i.onupgradeneeded=function(t){r&&r(new F(i.result,t.oldVersion,i.transaction))}),e.then(function(t){return new j(t)})),st}async function ct(t,e){var r=Q(t);const i=await ot(),n=i.transaction(at,"readwrite"),a=n.objectStore(at);var s=await a.get(r);return await a.put(e,r),await n.complete,s&&s.fid===e.fid||tt(t,e.fid),e}async function ut(t){t=Q(t);const e=await ot(),r=e.transaction(at,"readwrite");await r.objectStore(at).delete(t),await r.complete}async function lt(t,e){var r=Q(t);const i=await ot(),n=i.transaction(at,"readwrite"),a=n.objectStore(at);var s=await a.get(r),e=e(s);return void 0===e?await a.delete(r):await a.put(e,r),await n.complete,!e||s&&s.fid===e.fid||tt(t,e.fid),e}async function gt(e){let r;var t=await lt(e,t=>{t=function(t){t=t||{fid:Z(),registrationStatus:0};return ft(t)}(t),t=function(t,e){{if(0!==e.registrationStatus)return 1===e.registrationStatus?{installationEntry:e,registrationPromise:async function(t){let e=await ht(t);for(;1===e.registrationStatus;)await W(100),e=await ht(t);if(0!==e.registrationStatus)return e;{var{installationEntry:r,registrationPromise:i}=await gt(t);return i||r}}(t)}:{installationEntry:e};if(!navigator.onLine){var r=Promise.reject($.create("app-offline"));return{installationEntry:e,registrationPromise:r}}e={fid:e.fid,registrationStatus:1,registrationTime:Date.now()},t=async function(e,r){try{var t=await async function(t,{fid:e}){const r=H(t);var i=U(t),t={fid:e,authVersion:D,appId:t.appId,sdkVersion:N};const n={method:"POST",headers:i,body:JSON.stringify(t)},a=await G(()=>fetch(r,n));if(a.ok){t=await a.json();return{fid:t.fid||e,registrationStatus:2,refreshToken:t.refreshToken,authToken:K(t.authToken)}}throw await V("Create Installation",a)}(e,r);return ct(e,t)}catch(t){throw q(t)&&409===t.customData.serverCode?await ut(e):await ct(e,{fid:r.fid,registrationStatus:0}),t}}(t,e);return{installationEntry:e,registrationPromise:t}}}(e,t);return r=t.registrationPromise,t.installationEntry});return t.fid===Y?{installationEntry:await r}:{installationEntry:t,registrationPromise:r}}function ht(t){return lt(t,t=>{if(!t)throw $.create("installation-not-found");return ft(t)})}function ft(t){return 1===(e=t).registrationStatus&&e.registrationTime+A<Date.now()?{fid:t.fid,registrationStatus:0}:t;var e}async function pt({appConfig:t,platformLoggerProvider:e},r){const i=([n,{fid:a}]=[t,r],`${H(n)}/${a}/authTokens:generate`);var n,a;const s=z(t,r),o=e.getImmediate({optional:!0});o&&s.append("x-firebase-client",o.getPlatformInfoString());e={installation:{sdkVersion:N}};const c={method:"POST",headers:s,body:JSON.stringify(e)},u=await G(()=>fetch(i,c));if(u.ok)return K(await u.json());throw await V("Generate Auth Token",u)}async function dt(i,n=!1){let a;var t=await lt(i.appConfig,t=>{if(!wt(t))throw $.create("not-registered");var e,r=t.authToken;if(n||2!==(e=r).requestStatus||function(t){var e=Date.now();return e<t.creationTime||t.creationTime+t.expiresIn<e+x}(e)){if(1===r.requestStatus)return a=async function(t,e){let r=await mt(t.appConfig);for(;1===r.authToken.requestStatus;)await W(100),r=await mt(t.appConfig);var i=r.authToken;return 0===i.requestStatus?dt(t,e):i}(i,n),t;if(!navigator.onLine)throw $.create("app-offline");r=(e=t,r={requestStatus:1,requestTime:Date.now()},Object.assign(Object.assign({},e),{authToken:r}));return a=async function(e,r){try{var t=await pt(e,r),i=Object.assign(Object.assign({},r),{authToken:t});return await ct(e.appConfig,i),t}catch(t){throw!q(t)||401!==t.customData.serverCode&&404!==t.customData.serverCode?(r=Object.assign(Object.assign({},r),{authToken:{requestStatus:0}}),await ct(e.appConfig,r)):await ut(e.appConfig),t}}(i,r),r}return t});return a?await a:t.authToken}function mt(t){return lt(t,t=>{if(!wt(t))throw $.create("not-registered");var e=t.authToken;return 1===(e=e).requestStatus&&e.requestTime+A<Date.now()?Object.assign(Object.assign({},t),{authToken:{requestStatus:0}}):t})}function wt(t){return void 0!==t&&2===t.registrationStatus}async function yt(t,e=!1){return await async function(t){var{registrationPromise:t}=await gt(t);t&&await t}(t.appConfig),(await dt(t,e)).token}function _t(t){return $.create("missing-app-config-values",{valueName:t})}const vt="installations";Ht._registerComponent(new f(vt,t=>{t=t.getProvider("app").getImmediate();return{app:t,appConfig:function(t){if(!t||!t.options)throw _t("App Configuration");if(!t.name)throw _t("App Name");for(const e of["projectId","apiKey","appId"])if(!t.options[e])throw _t(e);return{appName:t.name,projectId:t.options.projectId,apiKey:t.options.apiKey,appId:t.options.appId}}(t),platformLoggerProvider:Ht._getProvider(t,"platform-logger"),_delete:()=>Promise.resolve()}},"PUBLIC")),Ht._registerComponent(new f("installations-internal",t=>{t=t.getProvider("app").getImmediate();const e=Ht._getProvider(t,vt).getImmediate();return{getId:()=>async function(t){const{installationEntry:e,registrationPromise:r}=await gt(t.appConfig);return(r||dt(t)).catch(console.error),e.fid}(e),getToken:t=>yt(e,t)}},"PRIVATE")),Ht.registerVersion("@firebase/installations",k);const bt="@firebase/remote-config";class St{constructor(){this.listeners=[]}addEventListener(t){this.listeners.push(t)}abort(){this.listeners.forEach(t=>t())}}const Ct=new u("remoteconfig","Remote Config",{"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}."});const Et=["1","true","t","yes","y","on"];class It{constructor(t,e=""){this._source=t,this._value=e}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=Et.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let t=Number(this._value);return isNaN(t)&&(t=0),t}getSource(){return this._source}}async function Tt(t){const e=g(t);var[r,t]=await Promise.all([e._storage.getLastSuccessfulFetchResponse(),e._storage.getActiveConfigEtag()]);return!!(r&&r.config&&r.eTag&&r.eTag!==t)&&(await Promise.all([e._storageCache.setActiveConfig(r.config),e._storage.setActiveConfigEtag(r.eTag)]),!0)}function Pt(t){const e=g(t);return e._initializePromise||(e._initializePromise=e._storageCache.loadFromStorage().then(()=>{e._isInitializationComplete=!0})),e._initializePromise}async function Lt(e){const r=g(e),t=new St;setTimeout(async()=>{t.abort()},r.settings.fetchTimeoutMillis);try{await r._client.fetch({cacheMaxAgeMillis:r.settings.minimumFetchIntervalMillis,signal:t}),await r._storageCache.setLastFetchStatus("success")}catch(t){i=(i="fetch-throttle",(e=t)instanceof c&&-1!==e.code.indexOf(i)?"throttle":"failure");throw await r._storageCache.setLastFetchStatus(i),t}var i}function Ot(r){const t=g(r);return[e={},i={}]=[t._storageCache.getActiveConfig(),t.defaultConfig],Object.keys(Object.assign(Object.assign({},e),i)).reduce((t,e)=>(t[e]=Mt(r,e),t),{});var e,i}function Mt(t,e){const r=g(t);r._isInitializationComplete||r._logger.debug(`A value was requested for key "${e}" before SDK initialization completed.`+" Await on ensureInitialized if the intent was to get a previously activated value.");t=r._storageCache.getActiveConfig();return t&&void 0!==t[e]?new It("remote",t[e]):r.defaultConfig&&void 0!==r.defaultConfig[e]?new It("default",String(r.defaultConfig[e])):(r._logger.debug(`Returning static value for key "${e}".`+" Define a default or remote value if this is unintentional."),new It("static"))}class Ft{constructor(t,e,r,i){this.client=t,this.storage=e,this.storageCache=r,this.logger=i}isCachedDataFresh(t,e){if(!e)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;var r=Date.now()-e,e=r<=t;return this.logger.debug("Config fetch cache check."+` Cache age millis: ${r}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${t}.`+` Is cache hit: ${e}.`),e}async fetch(t){var[e,r]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(r&&this.isCachedDataFresh(t.cacheMaxAgeMillis,e))return r;t.eTag=r&&r.eTag;t=await this.client.fetch(t);const i=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===t.status&&i.push(this.storage.setLastSuccessfulFetchResponse(t)),await Promise.all(i),t}}class jt{constructor(t,e,r,i,n,a){this.firebaseInstallations=t,this.sdkVersion=e,this.namespace=r,this.projectId=i,this.apiKey=n,this.appId=a}async fetch(r){var[t,e]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),i=`${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":r.eTag||"*"},e={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:e,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language},e={method:"POST",headers:n,body:JSON.stringify(e)},i=fetch(i,e),e=new Promise((t,e)=>{r.signal.addEventListener(()=>{const t=new Error("The operation was aborted.");t.name="AbortError",e(t)})});let a;try{await Promise.race([i,e]),a=await i}catch(t){let e="fetch-client-network";throw"AbortError"===t.name&&(e="fetch-timeout"),Ct.create(e,{originalErrorMessage:t.message})}let s=a.status;i=a.headers.get("ETag")||void 0;let o,c;if(200===a.status){let t;try{t=await a.json()}catch(t){throw Ct.create("fetch-client-parse",{originalErrorMessage:t.message})}o=t.entries,c=t.state}if("INSTANCE_STATE_UNSPECIFIED"===c?s=500:"NO_CHANGE"===c?s=304:"NO_TEMPLATE"!==c&&"EMPTY_CONFIG"!==c||(o={}),304!==s&&200!==s)throw Ct.create("fetch-status",{httpStatus:s});return{status:s,eTag:i,config:o}}}class kt{constructor(t,e){this.client=t,this.storage=e}async fetch(t){var e=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(t,e)}async attemptFetch(e,{throttleEndTimeMillis:t,backoffCount:r}){var n,a,i,s;n=e.signal,a=t,await new Promise((t,e)=>{var r=Math.max(a-Date.now(),0);const i=setTimeout(t,r);n.addEventListener(()=>{clearTimeout(i),e(Ct.create("fetch-throttle",{throttleEndTimeMillis:a}))})});try{var o=await this.client.fetch(e);return await this.storage.deleteThrottleMetadata(),o}catch(t){if(!function(t){if(t instanceof c&&t.customData){t=Number(t.customData.httpStatus);return 429===t||500===t||503===t||504===t}}(t))throw t;r={throttleEndTimeMillis:Date.now()+(o=r,void 0===s&&(s=2),s=(i=void 0===i?1e3:i)*Math.pow(s,o),o=Math.round(.5*s*(Math.random()-.5)*2),Math.min(144e5,s+o)),backoffCount:r+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(e,r)}}}class At{constructor(t,e,r,i,n){this.app=t,this._client=e,this._storageCache=r,this._storage=i,this._logger=n,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}}function Nt(t,e){t=t.target.error||void 0;return Ct.create(e,{originalErrorMessage:t&&t.message})}const Dt="app_namespace_store";class Rt{constructor(t,e,r,i=function(){return new Promise((e,r)=>{const t=indexedDB.open("firebase_remote_config",1);t.onerror=t=>{r(Nt(t,"storage-open"))},t.onsuccess=t=>{e(t.target.result)},t.onupgradeneeded=t=>{const e=t.target.result;0===t.oldVersion&&e.createObjectStore(Dt,{keyPath:"compositeKey"})}})}()){this.appId=t,this.appName=e,this.namespace=r,this.openDbPromise=i}getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(t){return this.set("last_fetch_status",t)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(t){return this.set("last_successful_fetch_timestamp_millis",t)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(t){return this.set("last_successful_fetch_response",t)}getActiveConfig(){return this.get("active_config")}setActiveConfig(t){return this.set("active_config",t)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(t){return this.set("active_config_etag",t)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(t){return this.set("throttle_metadata",t)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}async get(s){const o=await this.openDbPromise;return new Promise((e,r)=>{const t=o.transaction([Dt],"readonly"),i=t.objectStore(Dt);var n=this.createCompositeKey(s);try{const a=i.get(n);a.onerror=t=>{r(Nt(t,"storage-get"))},a.onsuccess=t=>{t=t.target.result;e(t?t.value:void 0)}}catch(t){r(Ct.create("storage-get",{originalErrorMessage:t&&t.message}))}})}async set(s,o){const c=await this.openDbPromise;return new Promise((t,e)=>{const r=c.transaction([Dt],"readwrite"),i=r.objectStore(Dt);var n=this.createCompositeKey(s);try{const a=i.put({compositeKey:n,value:o});a.onerror=t=>{e(Nt(t,"storage-set"))},a.onsuccess=()=>{t()}}catch(t){e(Ct.create("storage-set",{originalErrorMessage:t&&t.message}))}})}async delete(s){const o=await this.openDbPromise;return new Promise((t,e)=>{const r=o.transaction([Dt],"readwrite"),i=r.objectStore(Dt);var n=this.createCompositeKey(s);try{const a=i.delete(n);a.onerror=t=>{e(Nt(t,"storage-delete"))},a.onsuccess=()=>{t()}}catch(t){e(Ct.create("storage-delete",{originalErrorMessage:t&&t.message}))}})}createCompositeKey(t){return[this.appId,this.appName,this.namespace,t].join()}}class xt{constructor(t){this.storage=t}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}async loadFromStorage(){var t=this.storage.getLastFetchStatus(),e=this.storage.getLastSuccessfulFetchTimestampMillis(),r=this.storage.getActiveConfig(),t=await t;t&&(this.lastFetchStatus=t);e=await e;e&&(this.lastSuccessfulFetchTimestampMillis=e);r=await r;r&&(this.activeConfig=r)}setLastFetchStatus(t){return this.lastFetchStatus=t,this.storage.setLastFetchStatus(t)}setLastSuccessfulFetchTimestampMillis(t){return this.lastSuccessfulFetchTimestampMillis=t,this.storage.setLastSuccessfulFetchTimestampMillis(t)}setActiveConfig(t){return this.activeConfig=t,this.storage.setActiveConfig(t)}}Ht._registerComponent(new f("remote-config",function(t,{instanceIdentifier:e}){var r=t.getProvider("app").getImmediate(),i=t.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw Ct.create("registration-window");var{projectId:n,apiKey:a,appId:t}=r.options;if(!n)throw Ct.create("registration-project-id");if(!a)throw Ct.create("registration-api-key");if(!t)throw Ct.create("registration-app-id");e=e||"firebase";const s=new Rt(t,r.name,e),o=new xt(s),c=new _(bt);c.logLevel=h.ERROR;t=new jt(i,Ht.SDK_VERSION,e,n,a,t),t=new kt(t,s),t=new Ft(t,s,o,c),t=new At(r,t,o,s,c);return Pt(t),t},"PUBLIC").setMultipleInstances(!0)),Ht.registerVersion(bt,"0.2.0");class Bt{constructor(t,e){this.app=t,this._delegate=e}get defaultConfig(){return this._delegate.defaultConfig}set defaultConfig(t){this._delegate.defaultConfig=t}get fetchTimeMillis(){return this._delegate.fetchTimeMillis}get lastFetchStatus(){return this._delegate.lastFetchStatus}get settings(){return this._delegate.settings}set settings(t){this._delegate.settings=t}activate(){return Tt(this._delegate)}ensureInitialized(){return Pt(this._delegate)}fetch(){return Lt(this._delegate)}fetchAndActivate(){return async function(t){return await Lt(t=g(t)),Tt(t)}(this._delegate)}getAll(){return Ot(this._delegate)}getBoolean(t){return Mt(g(this._delegate),t).asBoolean()}getNumber(t){return Mt(g(this._delegate),t).asNumber()}getString(t){return Mt(g(this._delegate),t).asString()}getValue(t){return Mt(this._delegate,t)}setLogLevel(t){!function(t,e){const r=g(t);switch(e){case"debug":r._logger.logLevel=h.DEBUG;break;case"silent":r._logger.logLevel=h.SILENT;break;default:r._logger.logLevel=h.ERROR}}(this._delegate,t)}}function $t(t,{instanceIdentifier:e}){var r=t.getProvider("app-compat").getImmediate(),e=t.getProvider("remote-config").getImmediate({identifier:e});return new Bt(r,e)}(B=e.default).INTERNAL.registerComponent(new f("remoteConfig-compat",$t,"PUBLIC").setMultipleInstances(!0)),B.registerVersion("@firebase/remote-config-compat","0.1.0")}.apply(this,arguments)}catch(t){throw console.error(t),new Error("Cannot instantiate firebase-remote-config-compat.js - be sure to load firebase-app.js first.")}});
//# sourceMappingURL=firebase-remote-config-compat.js.map