UNPKG

firebase

Version:

Firebase JavaScript library for web and Node.js

3 lines (2 loc) • 32.8 kB
!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(t,e){"use strict";try{(function(){function n(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var r=n(t),o=function(t,e){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])})(t,e)};function i(t,e){for(var n=0,r=e.length,o=t.length;n<r;n++,o++)t[o]=e[n];return t}var a=function(t){function e(n,r,o){var i=t.call(this,r)||this;return i.code=n,i.customData=o,i.name="FirebaseError",Object.setPrototypeOf(i,e.prototype),Error.captureStackTrace&&Error.captureStackTrace(i,s.prototype.create),i}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}(e,t),e}(Error),s=function(){function t(t,e,n){this.service=t,this.serviceName=e,this.errors=n}return t.prototype.create=function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];var r=e[0]||{},o=this.service+"/"+t,i=this.errors[t],s=i?c(i,r):"Error",u=this.serviceName+": "+s+" ("+o+").",l=new a(o,u,r);return l},t}();function c(t,e){return t.replace(u,(function(t,n){var r=e[n];return null!=r?String(r):"<"+n+"?>"}))}var u=/\{\$([^}]+)}/g;var l,p,f=function(){function t(t,e,n){this.name=t,this.instanceFactory=e,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}return t.prototype.setInstantiationMode=function(t){return this.instantiationMode=t,this},t.prototype.setMultipleInstances=function(t){return this.multipleInstances=t,this},t.prototype.setServiceProps=function(t){return this.serviceProps=t,this},t.prototype.setInstanceCreatedCallback=function(t){return this.onInstanceCreated=t,this},t}();!function(t){t[t.DEBUG=0]="DEBUG",t[t.VERBOSE=1]="VERBOSE",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.SILENT=5]="SILENT"}(p||(p={}));var d={debug:p.DEBUG,verbose:p.VERBOSE,info:p.INFO,warn:p.WARN,error:p.ERROR,silent:p.SILENT},h=p.INFO,g=((l={})[p.DEBUG]="log",l[p.VERBOSE]="log",l[p.INFO]="info",l[p.WARN]="warn",l[p.ERROR]="error",l),m=function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];if(!(e<t.logLevel)){var o=(new Date).toISOString(),a=g[e];if(!a)throw new Error("Attempted to log a message with an invalid logType (value: "+e+")");console[a].apply(console,i(["["+o+"] "+t.name+":"],n))}},y=function(){function t(t){this.name=t,this._logLevel=h,this._logHandler=m,this._userLogHandler=null}return Object.defineProperty(t.prototype,"logLevel",{get:function(){return this._logLevel},set:function(t){if(!(t in p))throw new TypeError('Invalid value "'+t+'" assigned to `logLevel`');this._logLevel=t},enumerable:!1,configurable:!0}),t.prototype.setLogLevel=function(t){this._logLevel="string"==typeof t?d[t]:t},Object.defineProperty(t.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(t.prototype,"userLogHandler",{get:function(){return this._userLogHandler},set:function(t){this._userLogHandler=t},enumerable:!1,configurable:!0}),t.prototype.debug=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,i([this,p.DEBUG],t)),this._logHandler.apply(this,i([this,p.DEBUG],t))},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,i([this,p.VERBOSE],t)),this._logHandler.apply(this,i([this,p.VERBOSE],t))},t.prototype.info=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,i([this,p.INFO],t)),this._logHandler.apply(this,i([this,p.INFO],t))},t.prototype.warn=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,i([this,p.WARN],t)),this._logHandler.apply(this,i([this,p.WARN],t))},t.prototype.error=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this._userLogHandler&&this._userLogHandler.apply(this,i([this,p.ERROR],t)),this._logHandler.apply(this,i([this,p.ERROR],t))},t}();function v(t){return Array.prototype.slice.call(t)}function b(t){return new Promise((function(e,n){t.onsuccess=function(){e(t.result)},t.onerror=function(){n(t.error)}}))}function _(t,e,n){var r,o=new Promise((function(o,i){b(r=t[e].apply(t,n)).then(o,i)}));return o.request=r,o}function w(t,e,n){var r=_(t,e,n);return r.then((function(t){if(t)return new O(t,r.request)}))}function E(t,e,n){n.forEach((function(n){Object.defineProperty(t.prototype,n,{get:function(){return this[e][n]},set:function(t){this[e][n]=t}})}))}function I(t,e,n,r){r.forEach((function(r){r in n.prototype&&(t.prototype[r]=function(){return _(this[e],r,arguments)})}))}function T(t,e,n,r){r.forEach((function(r){r in n.prototype&&(t.prototype[r]=function(){return this[e][r].apply(this[e],arguments)})}))}function S(t,e,n,r){r.forEach((function(r){r in n.prototype&&(t.prototype[r]=function(){return w(this[e],r,arguments)})}))}function N(t){this._index=t}function O(t,e){this._cursor=t,this._request=e}function A(t){this._store=t}function k(t){this._tx=t,this.complete=new Promise((function(e,n){t.oncomplete=function(){e()},t.onerror=function(){n(t.error)},t.onabort=function(){n(t.error)}}))}function C(t,e,n){this._db=t,this.oldVersion=e,this.transaction=new k(n)}function P(t){this._db=t}E(N,"_index",["name","keyPath","multiEntry","unique"]),I(N,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),S(N,"_index",IDBIndex,["openCursor","openKeyCursor"]),E(O,"_cursor",["direction","key","primaryKey","value"]),I(O,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach((function(t){t in IDBCursor.prototype&&(O.prototype[t]=function(){var e=this,n=arguments;return Promise.resolve().then((function(){return e._cursor[t].apply(e._cursor,n),b(e._request).then((function(t){if(t)return new O(t,e._request)}))}))})})),A.prototype.createIndex=function(){return new N(this._store.createIndex.apply(this._store,arguments))},A.prototype.index=function(){return new N(this._store.index.apply(this._store,arguments))},E(A,"_store",["name","keyPath","indexNames","autoIncrement"]),I(A,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),S(A,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),T(A,"_store",IDBObjectStore,["deleteIndex"]),k.prototype.objectStore=function(){return new A(this._tx.objectStore.apply(this._tx,arguments))},E(k,"_tx",["objectStoreNames","mode"]),T(k,"_tx",IDBTransaction,["abort"]),C.prototype.createObjectStore=function(){return new A(this._db.createObjectStore.apply(this._db,arguments))},E(C,"_db",["name","version","objectStoreNames"]),T(C,"_db",IDBDatabase,["deleteObjectStore","close"]),P.prototype.transaction=function(){return new k(this._db.transaction.apply(this._db,arguments))},E(P,"_db",["name","version","objectStoreNames"]),T(P,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach((function(t){[A,N].forEach((function(e){t in e.prototype&&(e.prototype[t.replace("open","iterate")]=function(){var e=v(arguments),n=e[e.length-1],r=this._store||this._index,o=r[t].apply(r,e.slice(0,-1));o.onsuccess=function(){n(o.result)}})}))})),[N,A].forEach((function(t){t.prototype.getAll||(t.prototype.getAll=function(t,e){var n=this,r=[];return new Promise((function(o){n.iterateCursor(t,(function(t){t?(r.push(t.value),void 0===e||r.length!=e?t.continue():o(r)):o(r)}))}))})}));const R="0.0.900-exp.6ef484a04",M=1e4,j=`w:${R}`,B="FIS_v2",D=36e5,x=new s("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 L(t){return t instanceof a&&t.code.includes("request-failed")}function U({projectId:t}){return`https://firebaseinstallations.googleapis.com/v1/projects/${t}/installations`}function q(t){return{token:t.token,requestStatus:2,expiresIn:(e=t.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()};var e}async function F(t,e){const n=(await e.json()).error;return x.create("request-failed",{requestName:t,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function $({apiKey:t}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":t})}function H(t,{refreshToken:e}){const n=$(t);return n.append("Authorization",function(t){return`FIS_v2 ${t}`}(e)),n}async function V(t){const e=await t();return e.status>=500&&e.status<600?t():e}function K(t){return new Promise((e=>{setTimeout(e,t)}))}const W=/^[cdef][\w-]{21}$/;function z(){try{const t=new Uint8Array(17);(self.crypto||self.msCrypto).getRandomValues(t),t[0]=112+t[0]%16;const e=function(t){return(e=t,btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_")).substr(0,22);var e}(t);return W.test(e)?e:""}catch(t){return""}}function G(t){return`${t.appName}!${t.appId}`}const J=new Map;function Y(t,e){const n=G(t);Z(n,e),function(t,e){const n=function(){!Q&&"BroadcastChannel"in self&&(Q=new BroadcastChannel("[Firebase] FID Change"),Q.onmessage=t=>{Z(t.data.key,t.data.fid)});return Q}();n&&n.postMessage({key:t,fid:e});0===J.size&&Q&&(Q.close(),Q=null)}(n,e)}function Z(t,e){const n=J.get(t);if(n)for(const t of n)t(e)}let Q=null;const X="firebase-installations-store";let tt=null;function et(){return tt||(tt=function(t,e,n){var r=_(indexedDB,"open",[t,e]),o=r.request;return o&&(o.onupgradeneeded=function(t){n&&n(new C(o.result,t.oldVersion,o.transaction))}),r.then((function(t){return new P(t)}))}("firebase-installations-database",1,(t=>{switch(t.oldVersion){case 0:t.createObjectStore(X)}}))),tt}async function nt(t,e){const n=G(t),r=(await et()).transaction(X,"readwrite"),o=r.objectStore(X),i=await o.get(n);return await o.put(e,n),await r.complete,i&&i.fid===e.fid||Y(t,e.fid),e}async function rt(t){const e=G(t),n=(await et()).transaction(X,"readwrite");await n.objectStore(X).delete(e),await n.complete}async function ot(t,e){const n=G(t),r=(await et()).transaction(X,"readwrite"),o=r.objectStore(X),i=await o.get(n),a=e(i);return void 0===a?await o.delete(n):await o.put(a,n),await r.complete,!a||i&&i.fid===a.fid||Y(t,a.fid),a}async function it(t){let e;const n=await ot(t,(n=>{const r=function(t){return ct(t||{fid:z(),registrationStatus:0})}(n),o=function(t,e){if(0===e.registrationStatus){if(!navigator.onLine){return{installationEntry:e,registrationPromise:Promise.reject(x.create("app-offline"))}}const n={fid:e.fid,registrationStatus:1,registrationTime:Date.now()};return{installationEntry:n,registrationPromise:async function(t,e){try{return nt(t,await async function(t,{fid:e}){const n=U(t),r=$(t),o={fid:e,authVersion:B,appId:t.appId,sdkVersion:j},i={method:"POST",headers:r,body:JSON.stringify(o)},a=await V((()=>fetch(n,i)));if(a.ok){const t=await a.json();return{fid:t.fid||e,registrationStatus:2,refreshToken:t.refreshToken,authToken:q(t.authToken)}}throw await F("Create Installation",a)}(t,e))}catch(n){throw L(n)&&409===n.customData.serverCode?await rt(t):await nt(t,{fid:e.fid,registrationStatus:0}),n}}(t,n)}}return 1===e.registrationStatus?{installationEntry:e,registrationPromise:at(t)}:{installationEntry:e}}(t,r);return e=o.registrationPromise,o.installationEntry}));return""===n.fid?{installationEntry:await e}:{installationEntry:n,registrationPromise:e}}async function at(t){let e=await st(t);for(;1===e.registrationStatus;)await K(100),e=await st(t);if(0===e.registrationStatus){const{installationEntry:e,registrationPromise:n}=await it(t);return n||e}return e}function st(t){return ot(t,(t=>{if(!t)throw x.create("installation-not-found");return ct(t)}))}function ct(t){return 1===(e=t).registrationStatus&&e.registrationTime+M<Date.now()?{fid:t.fid,registrationStatus:0}:t;var e}async function ut({appConfig:t,platformLoggerProvider:e},n){const r=function(t,{fid:e}){return`${U(t)}/${e}/authTokens:generate`}(t,n),o=H(t,n),i=e.getImmediate({optional:!0});i&&o.append("x-firebase-client",i.getPlatformInfoString());const a={installation:{sdkVersion:j}},s={method:"POST",headers:o,body:JSON.stringify(a)},c=await V((()=>fetch(r,s)));if(c.ok){return q(await c.json())}throw await F("Generate Auth Token",c)}async function lt(t,e=!1){let n;const r=await ot(t.appConfig,(r=>{if(!ft(r))throw x.create("not-registered");const o=r.authToken;if(!e&&function(t){return 2===t.requestStatus&&!function(t){const e=Date.now();return e<t.creationTime||t.creationTime+t.expiresIn<e+D}(t)}(o))return r;if(1===o.requestStatus)return n=async function(t,e){let n=await pt(t.appConfig);for(;1===n.authToken.requestStatus;)await K(100),n=await pt(t.appConfig);const r=n.authToken;return 0===r.requestStatus?lt(t,e):r}(t,e),r;{if(!navigator.onLine)throw x.create("app-offline");const e=function(t){const e={requestStatus:1,requestTime:Date.now()};return Object.assign(Object.assign({},t),{authToken:e})}(r);return n=async function(t,e){try{const n=await ut(t,e),r=Object.assign(Object.assign({},e),{authToken:n});return await nt(t.appConfig,r),n}catch(n){if(!L(n)||401!==n.customData.serverCode&&404!==n.customData.serverCode){const n=Object.assign(Object.assign({},e),{authToken:{requestStatus:0}});await nt(t.appConfig,n)}else await rt(t.appConfig);throw n}}(t,e),e}}));return n?await n:r.authToken}function pt(t){return ot(t,(t=>{if(!ft(t))throw x.create("not-registered");const e=t.authToken;return 1===(n=e).requestStatus&&n.requestTime+M<Date.now()?Object.assign(Object.assign({},t),{authToken:{requestStatus:0}}):t;var n}))}function ft(t){return void 0!==t&&2===t.registrationStatus}async function dt(t,e=!1){const n=t;await async function(t){const{registrationPromise:e}=await it(t);e&&await e}(n.appConfig);return(await lt(n,e)).token}function ht(t){return x.create("missing-app-config-values",{valueName:t})}const gt="installations-exp",mt=t=>{const n=t.getProvider("app-exp").getImmediate();return{app:n,appConfig:function(t){if(!t||!t.options)throw ht("App Configuration");if(!t.name)throw ht("App Name");const e=["projectId","apiKey","appId"];for(const n of e)if(!t.options[n])throw ht(n);return{appName:t.name,projectId:t.options.projectId,apiKey:t.options.apiKey,appId:t.options.appId}}(n),platformLoggerProvider:e._getProvider(n,"platform-logger"),_delete:()=>Promise.resolve()}},yt=t=>{const n=t.getProvider("app-exp").getImmediate(),r=e._getProvider(n,gt).getImmediate();return{getId:()=>async function(t){const e=t,{installationEntry:n,registrationPromise:r}=await it(e.appConfig);return r?r.catch(console.error):lt(e).catch(console.error),n.fid}(r),getToken:t=>dt(r,t)}};e._registerComponent(new f(gt,mt,"PUBLIC")),e._registerComponent(new f("installations-exp-internal",yt,"PRIVATE")),e.registerVersion("@firebase/installations-exp",R);const vt="0.0.900-exp.6ef484a04",bt=vt,_t="FB-PERF-TRACE-MEASURE",wt="_wt_",Et="_fcp",It="_fid",Tt="@firebase/performance/config",St="@firebase/performance/configexpire",Nt="Performance",Ot=new s("performance",Nt,{"trace started":"Trace {$traceName} was started before.","trace stopped":"Trace {$traceName} is not running.","nonpositive trace startTime":"Trace {$traceName} startTime should be positive.","nonpositive trace duration":"Trace {$traceName} duration should be positive.","no window":"Window is not available.","no app id":"App id is not available.","no project id":"Project id is not available.","no api key":"Api key is not available.","invalid cc log":"Attempted to queue invalid cc event","FB not default":"Performance can only start when Firebase app instance is the default one.","RC response not ok":"RC response is not ok","invalid attribute name":"Attribute name {$attributeName} is invalid.","invalid attribute value":"Attribute value {$attributeValue} is invalid.","invalid custom metric name":"Custom metric name {$customMetricName} is invalid","invalid String merger input":"Input for String merger is invalid, contact support team to resolve.","already initialized":"Performance can only be initialized once."}),At=new y(Nt);let kt,Ct,Pt,Rt;At.logLevel=p.INFO;class Mt{constructor(t){if(this.window=t,!t)throw Ot.create("no window");this.performance=t.performance,this.PerformanceObserver=t.PerformanceObserver,this.windowLocation=t.location,this.navigator=t.navigator,this.document=t.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=t.localStorage),t.perfMetrics&&t.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=t.perfMetrics.onFirstInputDelay)}getUrl(){return this.windowLocation.href.split("?")[0]}mark(t){this.performance&&this.performance.mark&&this.performance.mark(t)}measure(t,e,n){this.performance&&this.performance.measure&&this.performance.measure(t,e,n)}getEntriesByType(t){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(t):[]}getEntriesByName(t){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(t):[]}getTimeOrigin(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)}requiredApisAvailable(){return fetch&&Promise&&this.navigator&&this.navigator.cookieEnabled?"indexedDB"in self&&null!=indexedDB||(At.info("IndexedDB is not supported by current browswer"),!1):(At.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(t,e){if(!this.PerformanceObserver)return;new this.PerformanceObserver((t=>{for(const n of t.getEntries())e(n)})).observe({entryTypes:[t]})}static getInstance(){return void 0===kt&&(kt=new Mt(Ct)),kt}}function jt(){return Pt}function Bt(t,e){const n=t.length-e.length;if(n<0||n>1)throw Ot.create("invalid String merger input");const r=[];for(let n=0;n<t.length;n++)r.push(t.charAt(n)),e.length>n&&r.push(e.charAt(n));return r.join("")}class Dt{constructor(){this.instrumentationEnabled=!0,this.dataCollectionEnabled=!0,this.loggingEnabled=!1,this.tracesSamplingRate=1,this.networkRequestsSamplingRate=1,this.logEndPointUrl="https://firebaselogging.googleapis.com/v0cc/log?format=json_proto",this.flTransportEndpointUrl=Bt("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=Bt("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return void 0===Rt&&(Rt=new Dt),Rt}}var xt;!function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.VISIBLE=1]="VISIBLE",t[t.HIDDEN=2]="HIDDEN"}(xt||(xt={}));const Lt=["firebase_","google_","ga_"],Ut=new RegExp("^[a-zA-Z]\\w*$");function qt(){const t=Mt.getInstance().navigator;return"serviceWorker"in t?t.serviceWorker.controller?2:3:1}function Ft(){switch(Mt.getInstance().document.visibilityState){case"visible":return xt.VISIBLE;case"hidden":return xt.HIDDEN;default:return xt.UNKNOWN}}function $t(){const t=Mt.getInstance().navigator.connection;switch(t&&t.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}}function Ht(t){var e;const n=null===(e=t.options)||void 0===e?void 0:e.appId;if(!n)throw Ot.create("no app id");return n}const Vt="0.0.1",Kt=!0,Wt="FIREBASE_INSTALLATIONS_AUTH";function zt(t,e){const n=function(){const t=Mt.getInstance().localStorage;if(!t)return;const e=t.getItem(St);if(!(e&&(n=e,Number(n)>Date.now())))return;var n;const r=t.getItem(Tt);if(!r)return;try{return JSON.parse(r)}catch(t){return}}();return n?(Jt(n),Promise.resolve()):function(t,e){return function(t){const e=t.getToken();return e.then((t=>{})),e}(t.installations).then((n=>{const r=function(t){var e;const n=null===(e=t.options)||void 0===e?void 0:e.projectId;if(!n)throw Ot.create("no project id");return n}(t.app),o=function(t){var e;const n=null===(e=t.options)||void 0===e?void 0:e.apiKey;if(!n)throw Ot.create("no api key");return n}(t.app),i=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${r}/namespaces/fireperf:fetch?key=${o}`,{method:"POST",headers:{Authorization:`${Wt} ${n}`},body:JSON.stringify({app_instance_id:e,app_instance_id_token:n,app_id:Ht(t.app),app_version:bt,sdk_version:Vt})});return fetch(i).then((t=>{if(t.ok)return t.json();throw Ot.create("RC response not ok")}))})).catch((()=>{At.info(Gt)}))}(t,e).then(Jt).then((t=>function(t){const e=Mt.getInstance().localStorage;if(!t||!e)return;e.setItem(Tt,JSON.stringify(t)),e.setItem(St,String(Date.now()+60*Dt.getInstance().configTimeToLive*60*1e3))}(t)),(()=>{}))}const Gt="Could not fetch config, will use default configs";function Jt(t){if(!t)return t;const e=Dt.getInstance(),n=t.entries||{};return void 0!==n.fpr_enabled?e.loggingEnabled="true"===String(n.fpr_enabled):e.loggingEnabled=Kt,n.fpr_log_source&&(e.logSource=Number(n.fpr_log_source)),n.fpr_log_endpoint_url&&(e.logEndPointUrl=n.fpr_log_endpoint_url),n.fpr_log_transport_key&&(e.transportKey=n.fpr_log_transport_key),void 0!==n.fpr_vc_network_request_sampling_rate&&(e.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate)),void 0!==n.fpr_vc_trace_sampling_rate&&(e.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate)),e.logTraceAfterSampling=Yt(e.tracesSamplingRate),e.logNetworkAfterSampling=Yt(e.networkRequestsSamplingRate),t}function Yt(t){return Math.random()<=t}let Zt,Qt=1;function Xt(t){return Qt=2,Zt=Zt||function(t){return function(){const t=Mt.getInstance().document;return new Promise((e=>{if(t&&"complete"!==t.readyState){const n=()=>{"complete"===t.readyState&&(t.removeEventListener("readystatechange",n),e())};t.addEventListener("readystatechange",n)}else e()}))}().then((()=>function(t){const e=t.getId();return e.then((t=>{Pt=t})),e}(t.installations))).then((e=>zt(t,e))).then((()=>te()),(()=>te()))}(t),Zt}function te(){Qt=3}const ee=1e4;let ne,re=3,oe=[],ie=!1;function ae(t){setTimeout((()=>{if(0!==re)return oe.length?void function(){const t=oe.splice(0,1e3),e=t.map((t=>({source_extension_json_proto3:t.message,event_time_ms:String(t.eventTime)})));(function(t,e){return function(t){const e=Dt.getInstance().getFlTransportFullUrl();return fetch(e,{method:"POST",body:JSON.stringify(t)})}(t).then((t=>(t.ok||At.info("Call to Firebase backend failed."),t.json()))).then((t=>{const n=Number(t.nextRequestWaitMillis);let r=ee;isNaN(n)||(r=Math.max(n,r));const o=t.logResponseDetails;Array.isArray(o)&&o.length>0&&"RETRY_REQUEST_LATER"===o[0].responseAction&&(oe=[...e,...oe],At.info("Retry transport request later.")),re=3,ae(r)}))})({request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:Dt.getInstance().logSource,log_event:e},t).catch((()=>{oe=[...t,...oe],re--,At.info(`Tries left: ${re}.`),ae(ee)}))}():ae(ee)}),t)}function se(t){return(...e)=>{!function(t){if(!t.eventTime||!t.message)throw Ot.create("invalid cc log");oe=[...oe,t]}({message:t(...e),eventTime:Date.now()})}}function ce(t,e){ne||(ne=se(pe)),ne(t,e)}function ue(t){const e=Dt.getInstance();!e.instrumentationEnabled&&t.isAuto||(e.dataCollectionEnabled||t.isAuto)&&Mt.getInstance().requiredApisAvailable()&&(t.isAuto&&Ft()!==xt.VISIBLE||(3===Qt?le(t):Xt(t.performanceController).then((()=>le(t)),(()=>le(t)))))}function le(t){if(!jt())return;const e=Dt.getInstance();e.loggingEnabled&&e.logTraceAfterSampling&&setTimeout((()=>ce(t,1)),0)}function pe(t,e){return 0===e?function(t){const e={url:t.url,http_method:t.httpMethod||0,http_response_code:200,response_payload_bytes:t.responsePayloadBytes,client_start_time_us:t.startTimeUs,time_to_response_initiated_us:t.timeToResponseInitiatedUs,time_to_response_completed_us:t.timeToResponseCompletedUs},n={application_info:fe(t.performanceController.app),network_request_metric:e};return JSON.stringify(n)}(t):function(t){const e={name:t.name,is_auto:t.isAuto,client_start_time_us:t.startTimeUs,duration_us:t.durationUs};0!==Object.keys(t.counters).length&&(e.counters=t.counters);const n=t.getAttributes();0!==Object.keys(n).length&&(e.custom_attributes=n);const r={application_info:fe(t.performanceController.app),trace_metric:e};return JSON.stringify(r)}(t)}function fe(t){return{google_app_id:Ht(t),app_instance_id:jt(),web_app_info:{sdk_version:bt,page_url:Mt.getInstance().getUrl(),service_worker_status:qt(),visibility_state:Ft(),effective_connection_type:$t()},application_process_state:0}}const de=["_fp",Et,It];class he{constructor(t,e,n=!1,r){this.performanceController=t,this.name=e,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=Mt.getInstance(),this.randomId=Math.floor(1e6*Math.random()),this.isAuto||(this.traceStartMark=`FB-PERF-TRACE-START-${this.randomId}-${this.name}`,this.traceStopMark=`FB-PERF-TRACE-STOP-${this.randomId}-${this.name}`,this.traceMeasure=r||`FB-PERF-TRACE-MEASURE-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw Ot.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw Ot.create("trace stopped",{traceName:this.name});this.state=3,this.api.mark(this.traceStopMark),this.api.measure(this.traceMeasure,this.traceStartMark,this.traceStopMark),this.calculateTraceMetrics(),ue(this)}record(t,e,n){if(t<=0)throw Ot.create("nonpositive trace startTime",{traceName:this.name});if(e<=0)throw Ot.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*e),this.startTimeUs=Math.floor(1e3*t),n&&n.attributes&&(this.customAttributes=Object.assign({},n.attributes)),n&&n.metrics)for(const t of Object.keys(n.metrics))isNaN(Number(n.metrics[t]))||(this.counters[t]=Number(Math.floor(n.metrics[t])));ue(this)}incrementMetric(t,e=1){void 0===this.counters[t]?this.putMetric(t,e):this.putMetric(t,this.counters[t]+e)}putMetric(t,e){if(!function(t,e){return!(0===t.length||t.length>100)&&(e&&e.startsWith(wt)&&de.indexOf(t)>-1||!t.startsWith("_"))}(t,this.name))throw Ot.create("invalid custom metric name",{customMetricName:t});this.counters[t]=function(t){const e=Math.floor(t);return e<t&&At.info(`Metric value should be an Integer, setting the value as : ${e}.`),e}(e)}getMetric(t){return this.counters[t]||0}putAttribute(t,e){const n=function(t){return!(0===t.length||t.length>40)&&(!Lt.some((e=>t.startsWith(e)))&&!!t.match(Ut))}(t),r=function(t){return 0!==t.length&&t.length<=100}(e);if(n&&r)this.customAttributes[t]=e;else{if(!n)throw Ot.create("invalid attribute name",{attributeName:t});if(!r)throw Ot.create("invalid attribute value",{attributeValue:e})}}getAttribute(t){return this.customAttributes[t]}removeAttribute(t){void 0!==this.customAttributes[t]&&delete this.customAttributes[t]}getAttributes(){return Object.assign({},this.customAttributes)}setStartTime(t){this.startTimeUs=t}setDuration(t){this.durationUs=t}calculateTraceMetrics(){const t=this.api.getEntriesByName(this.traceMeasure),e=t&&t[0];e&&(this.durationUs=Math.floor(1e3*e.duration),this.startTimeUs=Math.floor(1e3*(e.startTime+this.api.getTimeOrigin())))}static createOobTrace(t,e,n,r){const o=Mt.getInstance().getUrl();if(!o)return;const i=new he(t,wt+o,!0),a=Math.floor(1e3*Mt.getInstance().getTimeOrigin());i.setStartTime(a),e&&e[0]&&(i.setDuration(Math.floor(1e3*e[0].duration)),i.putMetric("domInteractive",Math.floor(1e3*e[0].domInteractive)),i.putMetric("domContentLoadedEventEnd",Math.floor(1e3*e[0].domContentLoadedEventEnd)),i.putMetric("loadEventEnd",Math.floor(1e3*e[0].loadEventEnd)));if(n){const t=n.find((t=>"first-paint"===t.name));t&&t.startTime&&i.putMetric("_fp",Math.floor(1e3*t.startTime));const e=n.find((t=>"first-contentful-paint"===t.name));e&&e.startTime&&i.putMetric(Et,Math.floor(1e3*e.startTime)),r&&i.putMetric(It,Math.floor(1e3*r))}ue(i)}static createUserTimingTrace(t,e){ue(new he(t,e,!1,e))}}function ge(t,e){const n=e;if(!n||void 0===n.responseStart)return;const r=Mt.getInstance().getTimeOrigin(),o=Math.floor(1e3*(n.startTime+r)),i=n.responseStart?Math.floor(1e3*(n.responseStart-n.startTime)):void 0,a=Math.floor(1e3*(n.responseEnd-n.startTime));!function(t){const e=Dt.getInstance();if(!e.instrumentationEnabled)return;const n=t.url,r=e.logEndPointUrl.split("?")[0],o=e.flTransportEndpointUrl.split("?")[0];n!==r&&n!==o&&e.loggingEnabled&&e.logNetworkAfterSampling&&setTimeout((()=>ce(t,0)),0)}({performanceController:t,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:o,timeToResponseInitiatedUs:i,timeToResponseCompletedUs:a})}function me(t){jt()&&(setTimeout((()=>function(t){const e=Mt.getInstance(),n=e.getEntriesByType("navigation"),r=e.getEntriesByType("paint");if(e.onFirstInputDelay){let o=setTimeout((()=>{he.createOobTrace(t,n,r),o=void 0}),5e3);e.onFirstInputDelay((e=>{o&&(clearTimeout(o),he.createOobTrace(t,n,r,e))}))}else he.createOobTrace(t,n,r)}(t)),0),setTimeout((()=>function(t){const e=Mt.getInstance(),n=e.getEntriesByType("resource");for(const e of n)ge(t,e);e.setupObserver("resource",(e=>ge(t,e)))}(t)),0),setTimeout((()=>function(t){const e=Mt.getInstance(),n=e.getEntriesByType("measure");for(const e of n)ye(t,e);e.setupObserver("measure",(e=>ye(t,e)))}(t)),0))}function ye(t,e){const n=e.name;n.substring(0,_t.length)!==_t&&he.createUserTimingTrace(t,n)}class ve{constructor(t,e){this.app=t,this.installations=e,this.initialized=!1}_init(t){this.initialized||(void 0!==(null==t?void 0:t.dataCollectionEnabled)&&(this.dataCollectionEnabled=t.dataCollectionEnabled),void 0!==(null==t?void 0:t.instrumentationEnabled)&&(this.instrumentationEnabled=t.instrumentationEnabled),Mt.getInstance().requiredApisAvailable()?new Promise((function(t,e){try{var n=!0,r="validate-browser-context-for-indexeddb-analytics-module",o=self.indexedDB.open(r);o.onsuccess=function(){o.result.close(),n||self.indexedDB.deleteDatabase(r),t(!0)},o.onupgradeneeded=function(){n=!1},o.onerror=function(){var t;e((null===(t=o.error)||void 0===t?void 0:t.message)||"")}}catch(t){e(t)}})).then((t=>{t&&(ie||(ae(5500),ie=!0),Xt(this).then((()=>me(this)),(()=>me(this))),this.initialized=!0)})).catch((t=>{At.info(`Environment doesn't support IndexedDB: ${t}`)})):At.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(t){Dt.getInstance().instrumentationEnabled=t}get instrumentationEnabled(){return Dt.getInstance().instrumentationEnabled}set dataCollectionEnabled(t){Dt.getInstance().dataCollectionEnabled=t}get dataCollectionEnabled(){return Dt.getInstance().dataCollectionEnabled}}const be=(t,{options:e})=>{const n=t.getProvider("app-exp").getImmediate(),r=t.getProvider("installations-exp-internal").getImmediate();if("[DEFAULT]"!==n.name)throw Ot.create("FB not default");if("undefined"==typeof window)throw Ot.create("no window");!function(t){Ct=t}(window);const o=new ve(n,r);return o._init(e),o};e._registerComponent(new f("performance-exp",be,"PUBLIC")),e.registerVersion("@firebase/performance-exp",vt);class _e{constructor(t,e){this.app=t,this._delegate=e}get instrumentationEnabled(){return this._delegate.instrumentationEnabled}set instrumentationEnabled(t){this._delegate.instrumentationEnabled=t}get dataCollectionEnabled(){return this._delegate.dataCollectionEnabled}set dataCollectionEnabled(t){this._delegate.dataCollectionEnabled=t}trace(t){return function(t,e){var n;return t=(n=t)&&n._delegate?n._delegate:n,new he(t,e)}(this._delegate,t)}}function we(t){const e=t.getProvider("app-compat").getImmediate(),n=t.getProvider("performance-exp").getImmediate();return new _e(e,n)}var Ee;(Ee=r.default).INTERNAL.registerComponent(new f("performance-compat",we,"PUBLIC")),Ee.registerVersion("@firebase/performance-compat","0.0.900-exp.6ef484a04")}).apply(this,arguments)}catch(t){throw console.error(t),new Error("Cannot instantiate firebase-performance-compat.js - be sure to load firebase-app.js first.")}})); //# sourceMappingURL=firebase-performance-compat.js.map