{"version":3,"sources":["webpack:///./node_modules/@firebase/installations/dist/index.esm.js","webpack:///./node_modules/@firebase/messaging/dist/index.esm.js","webpack:///./node_modules/@firebase/util/dist/index.esm.js","webpack:///./node_modules/@firebase/logger/dist/index.esm.js","webpack:///./node_modules/@firebase/component/dist/index.esm.js"],"names":["version","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","INSTALLATIONS_API_URL","TOKEN_EXPIRATION_BUFFER","SERVICE","SERVICE_NAME","ERROR_DESCRIPTION_MAP","ERROR_FACTORY","isServerError","error","code","includes","getInstallationsEndpoint","_a","projectId","extractAuthTokenInfoFromResponse","response","token","requestStatus","expiresIn","getExpiresInFromResponseExpiresIn","creationTime","Date","now","getErrorFromResponse","requestName","this","responseJson","errorData","label","json","sent","create","serverCode","serverMessage","message","serverStatus","status","getHeaders","apiKey","Headers","Accept","getHeadersWithAuth","appConfig","refreshToken","headers","append","getAuthorizationHeader","retryIfServerError","fn","result","responseExpiresIn","Number","replace","createInstallationRequest","fid","endpoint","body","request","responseValue","registeredInstallationEntry","_b","authVersion","appId","sdkVersion","method","JSON","stringify","fetch","ok","registrationStatus","authToken","sleep","ms","Promise","resolve","setTimeout","bufferToBase64UrlSafe","array","b64","btoa","String","fromCharCode","apply","VALID_FID_PATTERN","INVALID_FID","generateFid","fidByteArray","Uint8Array","crypto_1","self","crypto","msCrypto","getRandomValues","encode","test","b64String","substr","getKey","appName","fidChangeCallbacks","Map","fidChanged","key","callFidChangeCallbacks","broadcastFidChange","addCallback","callback","getBroadcastChannel","callbackSet","get","Set","set","add","removeCallback","delete","size","closeBroadcastChannel","e_1","callbacks","callbacks_1","callbacks_1_1","next","done","value","e_1_1","return","call","channel","postMessage","broadcastChannel","BroadcastChannel","onmessage","e","data","close","DATABASE_NAME","DATABASE_VERSION","OBJECT_STORE_NAME","dbPromise","getDbPromise","upgradeDB","oldVersion","createObjectStore","db","tx","objectStore","oldValue","transaction","put","complete","remove","update","updateFn","store","newValue","undefined","getInstallationEntry","registrationPromise","installationEntry","oldEntry","updateOrCreateInstallationEntry","entryWithPromise","triggerRegistrationIfNecessary","entry","clearTimedOutRequest","navigator","onLine","registrationPromiseWithError","reject","inProgressEntry","registrationTime","registerInstallation","waitUntilFidRegistration","trys","push","customData","updateInstallationRequest","hasInstallationRequestTimedOut","generateAuthTokenRequest","platformLoggerProvider","platformLogger","completedAuthToken","getGenerateAuthTokenEndpoint","getImmediate","optional","getPlatformInfoString","installation","refreshAuthToken","dependencies","forceRefresh","tokenPromise","isEntryRegistered","oldAuthToken","isAuthTokenValid","waitUntilAuthTokenRequest","makeAuthTokenRequestInProgressEntry","fetchAuthTokenFromServer","updateAuthTokenRequest","hasAuthTokenRequestTimedOut","updatedInstallationEntry","isAuthTokenExpired","inProgressAuthToken","requestTime","getId","catch","console","getToken","completeInstallationRegistration","deleteInstallationRequest","getDeleteEndpoint","deleteInstallation","onIdChange","extractAppConfig","app","options","getMissingValueError","name","configKeys","configKeys_1","configKeys_1_1","keyName","valueName","registerInstallations","instance","installationsName","INTERNAL","registerComponent","container","getProvider","installations","registerVersion","MessageType","ERROR_MAP","DEFAULT_SW_PATH","DEFAULT_SW_SCOPE","DEFAULT_VAPID_KEY","ENDPOINT","FCM_MSG","TAG","CONSOLE_CAMPAIGN_ANALYTICS_ENABLED","CONSOLE_CAMPAIGN_ID","CONSOLE_CAMPAIGN_TIME","CONSOLE_CAMPAIGN_NAME","BACKGROUND_HANDLE_EXECUTION_TIME_LIMIT_MS","FOREGROUND_HANDLE_PREPARATION_TIME_MS","arrayToBase64","uint8Array","base64String","base64ToArray","padding","repeat","length","base64","rawData","atob","outputArray","i","charCodeAt","OLD_DB_NAME","OLD_DB_VERSION","OLD_OBJECT_STORE_NAME","migrateOldDatabase","senderId","databases","dbNames","tokenDetails","_this","indexedDB","map","oldDetails","objectStoreNames","contains","index","clear","auth","p256dh","fcmToken","createTime","subscriptionOptions","swScope","vapidKey","checkTokenDetails","upgradeDb","dbGet","firebaseDependencies","oldTokenDetails","dbSet","dbRemove","requestGetToken","subscribeOptions","responseData","err_1","getBody","getEndpoint","errorInfo","requestUpdateToken","updateOptions","err_2","requestDeleteToken","unsubscribeOptions","err_3","web","applicationPubKey","TOKEN_EXPIRATION_MS","swRegistration","pushSubscription","Notification","permission","getPushSubscription","scope","getNewToken","isTokenValid","warn","updateToken","deleteToken","pushManager","getSubscription","unsubscribe","updatedToken","updatedTokenDetails","e_2","subscription","subscribe","userVisibleOnly","applicationServerKey","dbOptions","currentOptions","isVapidKeyEqual","isEndpointEqual","isAuthEqual","isP256dhEqual","externalizePayload","internalPayload","payload","from","collapseKey","collapse_key","messageId","fcm_message_id","propagateNotificationPayload","propagateDataPayload","propagateFcmOptions","messagePayloadInternal","notification","title","image","fcmOptions","link","analyticsLabel","analytics_label","isConsoleMessage","SwController","isOnBackgroundMessageUsed","bgMessageHandler","addEventListener","waitUntil","onPush","onSubChange","onNotificationClick","Object","defineProperty","prototype","enumerable","configurable","setBackgroundMessageHandler","onBackgroundMessage","nextOrObserver","_c","registration","requestPermission","usePublicVapidKey","useServiceWorker","onMessage","onTokenRefresh","event","clientList","isNotificationShown","getMessagePayloadInternal","getClientList","debug","hasVisibleClients","sendMessagePayloadInternalToWindows","showNotification","wrapInternalPayload","newSubscription","url","originUrl","client","action","stopImmediatePropagation","getLink","URL","location","href","origin","host","getWindowClient","clients","openWindow","focus","messageType","NOTIFICATION_CLICKED","isFirebaseMessaging","wrappedInternalPayload","err","clientList_1","clientList_1_1","clientUrl","some","visibilityState","startsWith","PUSH_RECEIVED","clientList_2","clientList_2_1","e_2_1","matchAll","type","includeUncontrolled","notificationPayloadInternal","actions","maxActions","click_action","WindowController","onMessageCallback","serviceWorker","messageEventListener","dataPayload","stripInternalFields","assign","logEvent","getVapidKey","getSwReg","updateVapidKey","updateSwReg","serviceWorkerRegistration","registerDefaultSw","ServiceWorkerRegistration","register","browserErrorMessage","permissionResult","eventType","analytics","getEventType","analyticsProvider","message_id","message_name","message_time","message_device_time","Math","floor","Error","messagingSenderId","MESSAGING_NAME","factoryMethod","isSupported","NAMESPACE_EXPORTS","isSWControllerSupported","isWindowControllerSupported","window","cookieEnabled","hasOwnProperty","PushSubscription","setServiceProps","stringToByteArray$1","str","out","p","c","byteArrayToString","bytes","pos","c1","c2","c3","c4","u","join","deepCopy","deepExtend","target","source","constructor","dateValue","getTime","Array","prop","isValidKey","Deferred","promise","wrapCallback","isNode","toString","global","process","isBrowser","ERROR_NAME","FirebaseError","_super","setPrototypeOf","captureStackTrace","ErrorFactory","service","serviceName","errors","_i","arguments","fullCode","template","replaceTemplate","fullMessage","PATTERN","_","obj","Sha1","chain_","buf_","W_","pad_","inbuf_","total_","blockSize","reset","compress_","buf","offset","W","t","f","k","a","b","d","lengthMinusBlock","n","inbuf","digest","totalBits","j","createSubscribe","executor","onNoObservers","proxy","ObserverProxy","bind","observers","unsubscribes","observerCount","task","finalized","then","forEachObserver","observer","implementsAnyMethods","noop","unsub","unsubscribeOne","finalError","sendOne","methods","methods_1","__spreadArrays","s","il","r","jl","LogLevel","instances","levelStringToEnum","DEBUG","VERBOSE","INFO","WARN","ERROR","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","args","logLevel","toISOString","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","log","info","level","forEach","inst","setUserLogHandler","logCallback","_loop_1","customLogLevel","userLogHandler","arg","ignored","filter","toLowerCase","instances_1","Component","instanceFactory","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","props","setInstanceCreatedCallback","DEFAULT_ENTRY_NAME","Provider","component","instancesDeferred","instancesOptions","onInitCallbacks","identifier","normalizedIdentifier","normalizeInstanceIdentifier","has","deferred","isInitialized","shouldAutoInitialize","getOrInitializeService","instanceIdentifier","getComponent","setComponent","isComponentEager","entries","_d","instanceDeferred","clearInstance","services","values","all","_delete","isComponentSet","getOptions","initialize","opts","_e","normalizedDeferredIdentifier","onInit","existingCallbacks","existingInstance","invokeOnInitCallbacks","e_3","e_3_1","normalizeIdentifierForFactory","ComponentContainer","providers","addComponent","provider","addOrOverwriteComponent","getProviders"],"mappings":"mJAiDI,E,4DA3CA,EAAO,0BACPA,EAAU,SAkBVC,EAAqB,IACrBC,EAAkB,KAAOF,EACzBG,EAAwB,SACxBC,EAAwB,kDACxBC,EAA0B,KAC1BC,EAAU,gBACVC,EAAe,gBAmBfC,GAAyB,EAAK,GAC9B,EAAG,6BAA+D,kDAClE,EAAG,kBAAyC,2CAC5C,EAAG,0BAAyD,mCAC5D,EAAG,kBAAyC,6FAC5C,EAAG,eAAmC,kDACtC,EAAG,+BAAmE,2EACtE,GACAC,EAAgB,IAAI,OAAaH,EAASC,EAAcC,GAE5D,SAASE,EAAcC,GACnB,OAAQA,aAAiB,QACrBA,EAAMC,KAAKC,SAAS;;;;;;;;;;;;;;;;GAmB5B,SAASC,EAAyBC,GAC9B,IAAIC,EAAYD,EAAGC,UACnB,OAAOZ,EAAwB,aAAeY,EAAY,iBAE9D,SAASC,EAAiCC,GACtC,MAAO,CACHC,MAAOD,EAASC,MAChBC,cAAe,EACfC,UAAWC,EAAkCJ,EAASG,WACtDE,aAAcC,KAAKC,OAG3B,SAASC,EAAqBC,EAAaT,GACvC,OAAO,eAAUU,UAAM,OAAQ,GAAQ,WACnC,IAAIC,EAAcC,EAClB,OAAO,eAAYF,MAAM,SAAUb,GAC/B,OAAQA,EAAGgB,OACP,KAAK,EAAG,MAAO,CAAC,EAAab,EAASc,QACtC,KAAK,EAGD,OAFAH,EAAed,EAAGkB,OAClBH,EAAYD,EAAalB,MAClB,CAAC,EAAcF,EAAcyB,OAAO,iBAAuC,CAC1EP,YAAaA,EACbQ,WAAYL,EAAUlB,KACtBwB,cAAeN,EAAUO,QACzBC,aAAcR,EAAUS,iBAMpD,SAASC,EAAWzB,GAChB,IAAI0B,EAAS1B,EAAG0B,OAChB,OAAO,IAAIC,QAAQ,CACf,eAAgB,mBAChBC,OAAQ,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AAOsf,EAAUhZ,MAEpC/L,KAAKsnB,aAAavC,IAStBqC,EAAmBpS,UAAUrI,YAAc,SAAUZ,GACjD,GAAI/L,KAAKqnB,UAAU/B,IAAIvZ,GACnB,OAAO/L,KAAKqnB,UAAUjiB,IAAI2G,GAG9B,IAAIwb,EAAW,IAAIzC,EAAS/Y,EAAM/L,MAElC,OADAA,KAAKqnB,UAAU/hB,IAAIyG,EAAMwb,GAClBA,GAEXH,EAAmBpS,UAAUyS,aAAe,WACxC,OAAO9K,MAAMtJ,KAAKrT,KAAKqnB,UAAUjB,WAE9BgB,EAhD4B","file":"js/chunk-vendors~8a6c828a.23380962.js","sourcesContent":["import firebase from '@firebase/app';\nimport { Component } from '@firebase/component';\nimport { __awaiter, __generator, __spreadArray, __read, __values, __assign } from 'tslib';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { openDb } from 'idb';\n\nvar name = \"@firebase/installations\";\nvar version = \"0.4.32\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar PENDING_TIMEOUT_MS = 10000;\r\nvar PACKAGE_VERSION = \"w:\" + version;\r\nvar INTERNAL_AUTH_VERSION = 'FIS_v2';\r\nvar INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';\r\nvar TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\r\nvar SERVICE = 'installations';\r\nvar SERVICE_NAME = 'Installations';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar _a;\r\nvar ERROR_DESCRIPTION_MAP = (_a = {},\r\n _a[\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */] = 'Missing App configuration value: \"{$valueName}\"',\r\n _a[\"not-registered\" /* NOT_REGISTERED */] = 'Firebase Installation is not registered.',\r\n _a[\"installation-not-found\" /* INSTALLATION_NOT_FOUND */] = 'Firebase Installation not found.',\r\n _a[\"request-failed\" /* REQUEST_FAILED */] = '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\r\n _a[\"app-offline\" /* APP_OFFLINE */] = 'Could not process request. Application offline.',\r\n _a[\"delete-pending-registration\" /* DELETE_PENDING_REGISTRATION */] = \"Can't delete installation while there is a pending registration request.\",\r\n _a);\r\nvar ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);\r\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\r\nfunction isServerError(error) {\r\n return (error instanceof FirebaseError &&\r\n error.code.includes(\"request-failed\" /* REQUEST_FAILED */));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getInstallationsEndpoint(_a) {\r\n var projectId = _a.projectId;\r\n return INSTALLATIONS_API_URL + \"/projects/\" + projectId + \"/installations\";\r\n}\r\nfunction extractAuthTokenInfoFromResponse(response) {\r\n return {\r\n token: response.token,\r\n requestStatus: 2 /* COMPLETED */,\r\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\r\n creationTime: Date.now()\r\n };\r\n}\r\nfunction getErrorFromResponse(requestName, response) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var responseJson, errorData;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, response.json()];\r\n case 1:\r\n responseJson = _a.sent();\r\n errorData = responseJson.error;\r\n return [2 /*return*/, ERROR_FACTORY.create(\"request-failed\" /* REQUEST_FAILED */, {\r\n requestName: requestName,\r\n serverCode: errorData.code,\r\n serverMessage: errorData.message,\r\n serverStatus: errorData.status\r\n })];\r\n }\r\n });\r\n });\r\n}\r\nfunction getHeaders(_a) {\r\n var apiKey = _a.apiKey;\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': apiKey\r\n });\r\n}\r\nfunction getHeadersWithAuth(appConfig, _a) {\r\n var refreshToken = _a.refreshToken;\r\n var headers = getHeaders(appConfig);\r\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\r\n return headers;\r\n}\r\n/**\r\n * Calls the passed in fetch wrapper and returns the response.\r\n * If the returned response has a status of 5xx, re-runs the function once and\r\n * returns the response.\r\n */\r\nfunction retryIfServerError(fn) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var result;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, fn()];\r\n case 1:\r\n result = _a.sent();\r\n if (result.status >= 500 && result.status < 600) {\r\n // Internal Server Error. Retry request.\r\n return [2 /*return*/, fn()];\r\n }\r\n return [2 /*return*/, result];\r\n }\r\n });\r\n });\r\n}\r\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn) {\r\n // This works because the server will never respond with fractions of a second.\r\n return Number(responseExpiresIn.replace('s', '000'));\r\n}\r\nfunction getAuthorizationHeader(refreshToken) {\r\n return INTERNAL_AUTH_VERSION + \" \" + refreshToken;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createInstallationRequest(appConfig, _a) {\r\n var fid = _a.fid;\r\n return __awaiter(this, void 0, void 0, function () {\r\n var endpoint, headers, body, request, response, responseValue, registeredInstallationEntry;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n endpoint = getInstallationsEndpoint(appConfig);\r\n headers = getHeaders(appConfig);\r\n body = {\r\n fid: fid,\r\n authVersion: INTERNAL_AUTH_VERSION,\r\n appId: appConfig.appId,\r\n sdkVersion: PACKAGE_VERSION\r\n };\r\n request = {\r\n method: 'POST',\r\n headers: headers,\r\n body: JSON.stringify(body)\r\n };\r\n return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })];\r\n case 1:\r\n response = _b.sent();\r\n if (!response.ok) return [3 /*break*/, 3];\r\n return [4 /*yield*/, response.json()];\r\n case 2:\r\n responseValue = _b.sent();\r\n registeredInstallationEntry = {\r\n fid: responseValue.fid || fid,\r\n registrationStatus: 2 /* COMPLETED */,\r\n refreshToken: responseValue.refreshToken,\r\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\r\n };\r\n return [2 /*return*/, registeredInstallationEntry];\r\n case 3: return [4 /*yield*/, getErrorFromResponse('Create Installation', response)];\r\n case 4: throw _b.sent();\r\n }\r\n });\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a promise that resolves after given time passes. */\r\nfunction sleep(ms) {\r\n return new Promise(function (resolve) {\r\n setTimeout(resolve, ms);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction bufferToBase64UrlSafe(array) {\r\n var b64 = btoa(String.fromCharCode.apply(String, __spreadArray([], __read(array))));\r\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\r\nvar INVALID_FID = '';\r\n/**\r\n * Generates a new FID using random values from Web Crypto API.\r\n * Returns an empty string if FID generation fails for any reason.\r\n */\r\nfunction generateFid() {\r\n try {\r\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\r\n // bytes. our implementation generates a 17 byte array instead.\r\n var fidByteArray = new Uint8Array(17);\r\n var crypto_1 = self.crypto || self.msCrypto;\r\n crypto_1.getRandomValues(fidByteArray);\r\n // Replace the first 4 random bits with the constant FID header of 0b0111.\r\n fidByteArray[0] = 112 + (fidByteArray[0] % 16);\r\n var fid = encode(fidByteArray);\r\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\r\n }\r\n catch (_a) {\r\n // FID generation errored\r\n return INVALID_FID;\r\n }\r\n}\r\n/** Converts a FID Uint8Array to a base64 string representation. */\r\nfunction encode(fidByteArray) {\r\n var b64String = bufferToBase64UrlSafe(fidByteArray);\r\n // Remove the 23rd character that was added because of the extra 4 bits at the\r\n // end of our 17 byte array, and the '=' padding.\r\n return b64String.substr(0, 22);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a string key that can be used to identify the app. */\r\nfunction getKey(appConfig) {\r\n return appConfig.appName + \"!\" + appConfig.appId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar fidChangeCallbacks = new Map();\r\n/**\r\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\r\n * change to other tabs.\r\n */\r\nfunction fidChanged(appConfig, fid) {\r\n var key = getKey(appConfig);\r\n callFidChangeCallbacks(key, fid);\r\n broadcastFidChange(key, fid);\r\n}\r\nfunction addCallback(appConfig, callback) {\r\n // Open the broadcast channel if it's not already open,\r\n // to be able to listen to change events from other tabs.\r\n getBroadcastChannel();\r\n var key = getKey(appConfig);\r\n var callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n callbackSet = new Set();\r\n fidChangeCallbacks.set(key, callbackSet);\r\n }\r\n callbackSet.add(callback);\r\n}\r\nfunction removeCallback(appConfig, callback) {\r\n var key = getKey(appConfig);\r\n var callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n return;\r\n }\r\n callbackSet.delete(callback);\r\n if (callbackSet.size === 0) {\r\n fidChangeCallbacks.delete(key);\r\n }\r\n // Close broadcast channel if there are no more callbacks.\r\n closeBroadcastChannel();\r\n}\r\nfunction callFidChangeCallbacks(key, fid) {\r\n var e_1, _a;\r\n var callbacks = fidChangeCallbacks.get(key);\r\n if (!callbacks) {\r\n return;\r\n }\r\n try {\r\n for (var callbacks_1 = __values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) {\r\n var callback = callbacks_1_1.value;\r\n callback(fid);\r\n }\r\n }\r\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\r\n finally {\r\n try {\r\n if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1);\r\n }\r\n finally { if (e_1) throw e_1.error; }\r\n }\r\n}\r\nfunction broadcastFidChange(key, fid) {\r\n var channel = getBroadcastChannel();\r\n if (channel) {\r\n channel.postMessage({ key: key, fid: fid });\r\n }\r\n closeBroadcastChannel();\r\n}\r\nvar broadcastChannel = null;\r\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\r\nfunction getBroadcastChannel() {\r\n if (!broadcastChannel && 'BroadcastChannel' in self) {\r\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\r\n broadcastChannel.onmessage = function (e) {\r\n callFidChangeCallbacks(e.data.key, e.data.fid);\r\n };\r\n }\r\n return broadcastChannel;\r\n}\r\nfunction closeBroadcastChannel() {\r\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\r\n broadcastChannel.close();\r\n broadcastChannel = null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DATABASE_NAME = 'firebase-installations-database';\r\nvar DATABASE_VERSION = 1;\r\nvar OBJECT_STORE_NAME = 'firebase-installations-store';\r\nvar dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDb(DATABASE_NAME, DATABASE_VERSION, function (upgradeDB) {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (upgradeDB.oldVersion) {\r\n case 0:\r\n upgradeDB.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nfunction set(appConfig, value) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var key, db, tx, objectStore, oldValue;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n key = getKey(appConfig);\r\n return [4 /*yield*/, getDbPromise()];\r\n case 1:\r\n db = _a.sent();\r\n tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n objectStore = tx.objectStore(OBJECT_STORE_NAME);\r\n return [4 /*yield*/, objectStore.get(key)];\r\n case 2:\r\n oldValue = _a.sent();\r\n return [4 /*yield*/, objectStore.put(value, key)];\r\n case 3:\r\n _a.sent();\r\n return [4 /*yield*/, tx.complete];\r\n case 4:\r\n _a.sent();\r\n if (!oldValue || oldValue.fid !== value.fid) {\r\n fidChanged(appConfig, value.fid);\r\n }\r\n return [2 /*return*/, value];\r\n }\r\n });\r\n });\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nfunction remove(appConfig) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var key, db, tx;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n key = getKey(appConfig);\r\n return [4 /*yield*/, getDbPromise()];\r\n case 1:\r\n db = _a.sent();\r\n tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n return [4 /*yield*/, tx.objectStore(OBJECT_STORE_NAME).delete(key)];\r\n case 2:\r\n _a.sent();\r\n return [4 /*yield*/, tx.complete];\r\n case 3:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * Atomically updates a record with the result of updateFn, which gets\r\n * called with the current value. If newValue is undefined, the record is\r\n * deleted instead.\r\n * @return Updated value\r\n */\r\nfunction update(appConfig, updateFn) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var key, db, tx, store, oldValue, newValue;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n key = getKey(appConfig);\r\n return [4 /*yield*/, getDbPromise()];\r\n case 1:\r\n db = _a.sent();\r\n tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n store = tx.objectStore(OBJECT_STORE_NAME);\r\n return [4 /*yield*/, store.get(key)];\r\n case 2:\r\n oldValue = _a.sent();\r\n newValue = updateFn(oldValue);\r\n if (!(newValue === undefined)) return [3 /*break*/, 4];\r\n return [4 /*yield*/, store.delete(key)];\r\n case 3:\r\n _a.sent();\r\n return [3 /*break*/, 6];\r\n case 4: return [4 /*yield*/, store.put(newValue, key)];\r\n case 5:\r\n _a.sent();\r\n _a.label = 6;\r\n case 6: return [4 /*yield*/, tx.complete];\r\n case 7:\r\n _a.sent();\r\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\r\n fidChanged(appConfig, newValue.fid);\r\n }\r\n return [2 /*return*/, newValue];\r\n }\r\n });\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates and returns the InstallationEntry from the database.\r\n * Also triggers a registration request if it is necessary and possible.\r\n */\r\nfunction getInstallationEntry(appConfig) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var registrationPromise, installationEntry;\r\n var _a;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0: return [4 /*yield*/, update(appConfig, function (oldEntry) {\r\n var installationEntry = updateOrCreateInstallationEntry(oldEntry);\r\n var entryWithPromise = triggerRegistrationIfNecessary(appConfig, installationEntry);\r\n registrationPromise = entryWithPromise.registrationPromise;\r\n return entryWithPromise.installationEntry;\r\n })];\r\n case 1:\r\n installationEntry = _b.sent();\r\n if (!(installationEntry.fid === INVALID_FID)) return [3 /*break*/, 3];\r\n _a = {};\r\n return [4 /*yield*/, registrationPromise];\r\n case 2: \r\n // FID generation failed. Waiting for the FID from the server.\r\n return [2 /*return*/, (_a.installationEntry = _b.sent(), _a)];\r\n case 3: return [2 /*return*/, {\r\n installationEntry: installationEntry,\r\n registrationPromise: registrationPromise\r\n }];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * Creates a new Installation Entry if one does not exist.\r\n * Also clears timed out pending requests.\r\n */\r\nfunction updateOrCreateInstallationEntry(oldEntry) {\r\n var entry = oldEntry || {\r\n fid: generateFid(),\r\n registrationStatus: 0 /* NOT_STARTED */\r\n };\r\n return clearTimedOutRequest(entry);\r\n}\r\n/**\r\n * If the Firebase Installation is not registered yet, this will trigger the\r\n * registration and return an InProgressInstallationEntry.\r\n *\r\n * If registrationPromise does not exist, the installationEntry is guaranteed\r\n * to be registered.\r\n */\r\nfunction triggerRegistrationIfNecessary(appConfig, installationEntry) {\r\n if (installationEntry.registrationStatus === 0 /* NOT_STARTED */) {\r\n if (!navigator.onLine) {\r\n // Registration required but app is offline.\r\n var registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */));\r\n return {\r\n installationEntry: installationEntry,\r\n registrationPromise: registrationPromiseWithError\r\n };\r\n }\r\n // Try registering. Change status to IN_PROGRESS.\r\n var inProgressEntry = {\r\n fid: installationEntry.fid,\r\n registrationStatus: 1 /* IN_PROGRESS */,\r\n registrationTime: Date.now()\r\n };\r\n var registrationPromise = registerInstallation(appConfig, inProgressEntry);\r\n return { installationEntry: inProgressEntry, registrationPromise: registrationPromise };\r\n }\r\n else if (installationEntry.registrationStatus === 1 /* IN_PROGRESS */) {\r\n return {\r\n installationEntry: installationEntry,\r\n registrationPromise: waitUntilFidRegistration(appConfig)\r\n };\r\n }\r\n else {\r\n return { installationEntry: installationEntry };\r\n }\r\n}\r\n/** This will be executed only once for each new Firebase Installation. */\r\nfunction registerInstallation(appConfig, installationEntry) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var registeredInstallationEntry, e_1;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n _a.trys.push([0, 2, , 7]);\r\n return [4 /*yield*/, createInstallationRequest(appConfig, installationEntry)];\r\n case 1:\r\n registeredInstallationEntry = _a.sent();\r\n return [2 /*return*/, set(appConfig, registeredInstallationEntry)];\r\n case 2:\r\n e_1 = _a.sent();\r\n if (!(isServerError(e_1) && e_1.customData.serverCode === 409)) return [3 /*break*/, 4];\r\n // Server returned a \"FID can not be used\" error.\r\n // Generate a new ID next time.\r\n return [4 /*yield*/, remove(appConfig)];\r\n case 3:\r\n // Server returned a \"FID can not be used\" error.\r\n // Generate a new ID next time.\r\n _a.sent();\r\n return [3 /*break*/, 6];\r\n case 4: \r\n // Registration failed. Set FID as not registered.\r\n return [4 /*yield*/, set(appConfig, {\r\n fid: installationEntry.fid,\r\n registrationStatus: 0 /* NOT_STARTED */\r\n })];\r\n case 5:\r\n // Registration failed. Set FID as not registered.\r\n _a.sent();\r\n _a.label = 6;\r\n case 6: throw e_1;\r\n case 7: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\n/** Call if FID registration is pending in another request. */\r\nfunction waitUntilFidRegistration(appConfig) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var entry, _a, installationEntry, registrationPromise;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0: return [4 /*yield*/, updateInstallationRequest(appConfig)];\r\n case 1:\r\n entry = _b.sent();\r\n _b.label = 2;\r\n case 2:\r\n if (!(entry.registrationStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 5];\r\n // createInstallation request still in progress.\r\n return [4 /*yield*/, sleep(100)];\r\n case 3:\r\n // createInstallation request still in progress.\r\n _b.sent();\r\n return [4 /*yield*/, updateInstallationRequest(appConfig)];\r\n case 4:\r\n entry = _b.sent();\r\n return [3 /*break*/, 2];\r\n case 5:\r\n if (!(entry.registrationStatus === 0 /* NOT_STARTED */)) return [3 /*break*/, 7];\r\n return [4 /*yield*/, getInstallationEntry(appConfig)];\r\n case 6:\r\n _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise;\r\n if (registrationPromise) {\r\n return [2 /*return*/, registrationPromise];\r\n }\r\n else {\r\n // if there is no registrationPromise, entry is registered.\r\n return [2 /*return*/, installationEntry];\r\n }\r\n case 7: return [2 /*return*/, entry];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * Called only if there is a CreateInstallation request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * CreateInstallation request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateInstallationRequest(appConfig) {\r\n return update(appConfig, function (oldEntry) {\r\n if (!oldEntry) {\r\n throw ERROR_FACTORY.create(\"installation-not-found\" /* INSTALLATION_NOT_FOUND */);\r\n }\r\n return clearTimedOutRequest(oldEntry);\r\n });\r\n}\r\nfunction clearTimedOutRequest(entry) {\r\n if (hasInstallationRequestTimedOut(entry)) {\r\n return {\r\n fid: entry.fid,\r\n registrationStatus: 0 /* NOT_STARTED */\r\n };\r\n }\r\n return entry;\r\n}\r\nfunction hasInstallationRequestTimedOut(installationEntry) {\r\n return (installationEntry.registrationStatus === 1 /* IN_PROGRESS */ &&\r\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction generateAuthTokenRequest(_a, installationEntry) {\r\n var appConfig = _a.appConfig, platformLoggerProvider = _a.platformLoggerProvider;\r\n return __awaiter(this, void 0, void 0, function () {\r\n var endpoint, headers, platformLogger, body, request, response, responseValue, completedAuthToken;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\r\n headers = getHeadersWithAuth(appConfig, installationEntry);\r\n platformLogger = platformLoggerProvider.getImmediate({\r\n optional: true\r\n });\r\n if (platformLogger) {\r\n headers.append('x-firebase-client', platformLogger.getPlatformInfoString());\r\n }\r\n body = {\r\n installation: {\r\n sdkVersion: PACKAGE_VERSION\r\n }\r\n };\r\n request = {\r\n method: 'POST',\r\n headers: headers,\r\n body: JSON.stringify(body)\r\n };\r\n return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })];\r\n case 1:\r\n response = _b.sent();\r\n if (!response.ok) return [3 /*break*/, 3];\r\n return [4 /*yield*/, response.json()];\r\n case 2:\r\n responseValue = _b.sent();\r\n completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);\r\n return [2 /*return*/, completedAuthToken];\r\n case 3: return [4 /*yield*/, getErrorFromResponse('Generate Auth Token', response)];\r\n case 4: throw _b.sent();\r\n }\r\n });\r\n });\r\n}\r\nfunction getGenerateAuthTokenEndpoint(appConfig, _a) {\r\n var fid = _a.fid;\r\n return getInstallationsEndpoint(appConfig) + \"/\" + fid + \"/authTokens:generate\";\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a valid authentication token for the installation. Generates a new\r\n * token if one doesn't exist, is expired or about to expire.\r\n *\r\n * Should only be called if the Firebase Installation is registered.\r\n */\r\nfunction refreshAuthToken(dependencies, forceRefresh) {\r\n if (forceRefresh === void 0) { forceRefresh = false; }\r\n return __awaiter(this, void 0, void 0, function () {\r\n var tokenPromise, entry, authToken, _a;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0: return [4 /*yield*/, update(dependencies.appConfig, function (oldEntry) {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* NOT_REGISTERED */);\r\n }\r\n var oldAuthToken = oldEntry.authToken;\r\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\r\n // There is a valid token in the DB.\r\n return oldEntry;\r\n }\r\n else if (oldAuthToken.requestStatus === 1 /* IN_PROGRESS */) {\r\n // There already is a token request in progress.\r\n tokenPromise = waitUntilAuthTokenRequest(dependencies, forceRefresh);\r\n return oldEntry;\r\n }\r\n else {\r\n // No token or token expired.\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */);\r\n }\r\n var inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\r\n tokenPromise = fetchAuthTokenFromServer(dependencies, inProgressEntry);\r\n return inProgressEntry;\r\n }\r\n })];\r\n case 1:\r\n entry = _b.sent();\r\n if (!tokenPromise) return [3 /*break*/, 3];\r\n return [4 /*yield*/, tokenPromise];\r\n case 2:\r\n _a = _b.sent();\r\n return [3 /*break*/, 4];\r\n case 3:\r\n _a = entry.authToken;\r\n _b.label = 4;\r\n case 4:\r\n authToken = _a;\r\n return [2 /*return*/, authToken];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * Call only if FID is registered and Auth Token request is in progress.\r\n *\r\n * Waits until the current pending request finishes. If the request times out,\r\n * tries once in this thread as well.\r\n */\r\nfunction waitUntilAuthTokenRequest(dependencies, forceRefresh) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var entry, authToken;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, updateAuthTokenRequest(dependencies.appConfig)];\r\n case 1:\r\n entry = _a.sent();\r\n _a.label = 2;\r\n case 2:\r\n if (!(entry.authToken.requestStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 5];\r\n // generateAuthToken still in progress.\r\n return [4 /*yield*/, sleep(100)];\r\n case 3:\r\n // generateAuthToken still in progress.\r\n _a.sent();\r\n return [4 /*yield*/, updateAuthTokenRequest(dependencies.appConfig)];\r\n case 4:\r\n entry = _a.sent();\r\n return [3 /*break*/, 2];\r\n case 5:\r\n authToken = entry.authToken;\r\n if (authToken.requestStatus === 0 /* NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n return [2 /*return*/, refreshAuthToken(dependencies, forceRefresh)];\r\n }\r\n else {\r\n return [2 /*return*/, authToken];\r\n }\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * Called only if there is a GenerateAuthToken request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * GenerateAuthToken request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateAuthTokenRequest(appConfig) {\r\n return update(appConfig, function (oldEntry) {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* NOT_REGISTERED */);\r\n }\r\n var oldAuthToken = oldEntry.authToken;\r\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\r\n return __assign(__assign({}, oldEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });\r\n }\r\n return oldEntry;\r\n });\r\n}\r\nfunction fetchAuthTokenFromServer(dependencies, installationEntry) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var authToken, updatedInstallationEntry, e_1, updatedInstallationEntry;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n _a.trys.push([0, 3, , 8]);\r\n return [4 /*yield*/, generateAuthTokenRequest(dependencies, installationEntry)];\r\n case 1:\r\n authToken = _a.sent();\r\n updatedInstallationEntry = __assign(__assign({}, installationEntry), { authToken: authToken });\r\n return [4 /*yield*/, set(dependencies.appConfig, updatedInstallationEntry)];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/, authToken];\r\n case 3:\r\n e_1 = _a.sent();\r\n if (!(isServerError(e_1) &&\r\n (e_1.customData.serverCode === 401 || e_1.customData.serverCode === 404))) return [3 /*break*/, 5];\r\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\r\n // Generate a new ID next time.\r\n return [4 /*yield*/, remove(dependencies.appConfig)];\r\n case 4:\r\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\r\n // Generate a new ID next time.\r\n _a.sent();\r\n return [3 /*break*/, 7];\r\n case 5:\r\n updatedInstallationEntry = __assign(__assign({}, installationEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });\r\n return [4 /*yield*/, set(dependencies.appConfig, updatedInstallationEntry)];\r\n case 6:\r\n _a.sent();\r\n _a.label = 7;\r\n case 7: throw e_1;\r\n case 8: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\nfunction isEntryRegistered(installationEntry) {\r\n return (installationEntry !== undefined &&\r\n installationEntry.registrationStatus === 2 /* COMPLETED */);\r\n}\r\nfunction isAuthTokenValid(authToken) {\r\n return (authToken.requestStatus === 2 /* COMPLETED */ &&\r\n !isAuthTokenExpired(authToken));\r\n}\r\nfunction isAuthTokenExpired(authToken) {\r\n var now = Date.now();\r\n return (now < authToken.creationTime ||\r\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);\r\n}\r\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\r\nfunction makeAuthTokenRequestInProgressEntry(oldEntry) {\r\n var inProgressAuthToken = {\r\n requestStatus: 1 /* IN_PROGRESS */,\r\n requestTime: Date.now()\r\n };\r\n return __assign(__assign({}, oldEntry), { authToken: inProgressAuthToken });\r\n}\r\nfunction hasAuthTokenRequestTimedOut(authToken) {\r\n return (authToken.requestStatus === 1 /* IN_PROGRESS */ &&\r\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getId(dependencies) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var _a, installationEntry, registrationPromise;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0: return [4 /*yield*/, getInstallationEntry(dependencies.appConfig)];\r\n case 1:\r\n _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise;\r\n if (registrationPromise) {\r\n registrationPromise.catch(console.error);\r\n }\r\n else {\r\n // If the installation is already registered, update the authentication\r\n // token if needed.\r\n refreshAuthToken(dependencies).catch(console.error);\r\n }\r\n return [2 /*return*/, installationEntry.fid];\r\n }\r\n });\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getToken(dependencies, forceRefresh) {\r\n if (forceRefresh === void 0) { forceRefresh = false; }\r\n return __awaiter(this, void 0, void 0, function () {\r\n var authToken;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, completeInstallationRegistration(dependencies.appConfig)];\r\n case 1:\r\n _a.sent();\r\n return [4 /*yield*/, refreshAuthToken(dependencies, forceRefresh)];\r\n case 2:\r\n authToken = _a.sent();\r\n return [2 /*return*/, authToken.token];\r\n }\r\n });\r\n });\r\n}\r\nfunction completeInstallationRegistration(appConfig) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var registrationPromise;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, getInstallationEntry(appConfig)];\r\n case 1:\r\n registrationPromise = (_a.sent()).registrationPromise;\r\n if (!registrationPromise) return [3 /*break*/, 3];\r\n // A createInstallation request is in progress. Wait until it finishes.\r\n return [4 /*yield*/, registrationPromise];\r\n case 2:\r\n // A createInstallation request is in progress. Wait until it finishes.\r\n _a.sent();\r\n _a.label = 3;\r\n case 3: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction deleteInstallationRequest(appConfig, installationEntry) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var endpoint, headers, request, response;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n endpoint = getDeleteEndpoint(appConfig, installationEntry);\r\n headers = getHeadersWithAuth(appConfig, installationEntry);\r\n request = {\r\n method: 'DELETE',\r\n headers: headers\r\n };\r\n return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })];\r\n case 1:\r\n response = _a.sent();\r\n if (!!response.ok) return [3 /*break*/, 3];\r\n return [4 /*yield*/, getErrorFromResponse('Delete Installation', response)];\r\n case 2: throw _a.sent();\r\n case 3: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\nfunction getDeleteEndpoint(appConfig, _a) {\r\n var fid = _a.fid;\r\n return getInstallationsEndpoint(appConfig) + \"/\" + fid;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction deleteInstallation(dependencies) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var appConfig, entry;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n appConfig = dependencies.appConfig;\r\n return [4 /*yield*/, update(appConfig, function (oldEntry) {\r\n if (oldEntry && oldEntry.registrationStatus === 0 /* NOT_STARTED */) {\r\n // Delete the unregistered entry without sending a deleteInstallation request.\r\n return undefined;\r\n }\r\n return oldEntry;\r\n })];\r\n case 1:\r\n entry = _a.sent();\r\n if (!entry) return [3 /*break*/, 6];\r\n if (!(entry.registrationStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 2];\r\n // Can't delete while trying to register.\r\n throw ERROR_FACTORY.create(\"delete-pending-registration\" /* DELETE_PENDING_REGISTRATION */);\r\n case 2:\r\n if (!(entry.registrationStatus === 2 /* COMPLETED */)) return [3 /*break*/, 6];\r\n if (!!navigator.onLine) return [3 /*break*/, 3];\r\n throw ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */);\r\n case 3: return [4 /*yield*/, deleteInstallationRequest(appConfig, entry)];\r\n case 4:\r\n _a.sent();\r\n return [4 /*yield*/, remove(appConfig)];\r\n case 5:\r\n _a.sent();\r\n _a.label = 6;\r\n case 6: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sets a new callback that will get called when Installation ID changes.\r\n * Returns an unsubscribe function that will remove the callback when called.\r\n */\r\nfunction onIdChange(_a, callback) {\r\n var appConfig = _a.appConfig;\r\n addCallback(appConfig, callback);\r\n return function () {\r\n removeCallback(appConfig, callback);\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n var e_1, _a;\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n var configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId'\r\n ];\r\n try {\r\n for (var configKeys_1 = __values(configKeys), configKeys_1_1 = configKeys_1.next(); !configKeys_1_1.done; configKeys_1_1 = configKeys_1.next()) {\r\n var keyName = configKeys_1_1.value;\r\n if (!app.options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n }\r\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\r\n finally {\r\n try {\r\n if (configKeys_1_1 && !configKeys_1_1.done && (_a = configKeys_1.return)) _a.call(configKeys_1);\r\n }\r\n finally { if (e_1) throw e_1.error; }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: app.options.projectId,\r\n apiKey: app.options.apiKey,\r\n appId: app.options.appId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */, {\r\n valueName: valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerInstallations(instance) {\r\n var installationsName = 'installations';\r\n instance.INTERNAL.registerComponent(new Component(installationsName, function (container) {\r\n var app = container.getProvider('app').getImmediate();\r\n // Throws if app isn't configured properly.\r\n var appConfig = extractAppConfig(app);\r\n var platformLoggerProvider = container.getProvider('platform-logger');\r\n var dependencies = {\r\n appConfig: appConfig,\r\n platformLoggerProvider: platformLoggerProvider\r\n };\r\n var installations = {\r\n app: app,\r\n getId: function () { return getId(dependencies); },\r\n getToken: function (forceRefresh) {\r\n return getToken(dependencies, forceRefresh);\r\n },\r\n delete: function () { return deleteInstallation(dependencies); },\r\n onIdChange: function (callback) {\r\n return onIdChange(dependencies, callback);\r\n }\r\n };\r\n return installations;\r\n }, \"PUBLIC\" /* PUBLIC */));\r\n instance.registerVersion(name, version);\r\n}\r\nregisterInstallations(firebase);\n\nexport { registerInstallations };\n//# sourceMappingURL=index.esm.js.map\n","import '@firebase/installations';\nimport { Component } from '@firebase/component';\nimport { ErrorFactory } from '@firebase/util';\nimport { __spreadArray, __read, __awaiter, __generator, __assign, __values } from 'tslib';\nimport { deleteDb, openDb } from 'idb';\nimport firebase from '@firebase/app';\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar _a;\r\nvar ERROR_MAP = (_a = {},\r\n _a[\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */] = 'Missing App configuration value: \"{$valueName}\"',\r\n _a[\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */] = 'This method is available in a Window context.',\r\n _a[\"only-available-in-sw\" /* AVAILABLE_IN_SW */] = 'This method is available in a service worker context.',\r\n _a[\"permission-default\" /* PERMISSION_DEFAULT */] = 'The notification permission was not granted and dismissed instead.',\r\n _a[\"permission-blocked\" /* PERMISSION_BLOCKED */] = 'The notification permission was not granted and blocked instead.',\r\n _a[\"unsupported-browser\" /* UNSUPPORTED_BROWSER */] = \"This browser doesn't support the API's required to use the firebase SDK.\",\r\n _a[\"failed-service-worker-registration\" /* FAILED_DEFAULT_REGISTRATION */] = 'We are unable to register the default service worker. {$browserErrorMessage}',\r\n _a[\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */] = 'A problem occurred while subscribing the user to FCM: {$errorInfo}',\r\n _a[\"token-subscribe-no-token\" /* TOKEN_SUBSCRIBE_NO_TOKEN */] = 'FCM returned no token when subscribing the user to push.',\r\n _a[\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */] = 'A problem occurred while unsubscribing the ' +\r\n 'user from FCM: {$errorInfo}',\r\n _a[\"token-update-failed\" /* TOKEN_UPDATE_FAILED */] = 'A problem occurred while updating the user from FCM: {$errorInfo}',\r\n _a[\"token-update-no-token\" /* TOKEN_UPDATE_NO_TOKEN */] = 'FCM returned no token when updating the user to push.',\r\n _a[\"use-sw-after-get-token\" /* USE_SW_AFTER_GET_TOKEN */] = 'The useServiceWorker() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your service worker is used.',\r\n _a[\"invalid-sw-registration\" /* INVALID_SW_REGISTRATION */] = 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',\r\n _a[\"invalid-bg-handler\" /* INVALID_BG_HANDLER */] = 'The input to setBackgroundMessageHandler() must be a function.',\r\n _a[\"invalid-vapid-key\" /* INVALID_VAPID_KEY */] = 'The public VAPID key must be a string.',\r\n _a[\"use-vapid-key-after-get-token\" /* USE_VAPID_KEY_AFTER_GET_TOKEN */] = 'The usePublicVapidKey() method may only be called once and must be ' +\r\n 'called before calling getToken() to ensure your VAPID key is used.',\r\n _a);\r\nvar ERROR_FACTORY = new ErrorFactory('messaging', 'Messaging', ERROR_MAP);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\r\nvar DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\r\nvar DEFAULT_VAPID_KEY = 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';\r\nvar ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';\r\n// Key of FCM Payload in Notification's data field.\r\nvar FCM_MSG = 'FCM_MSG';\r\nvar TAG = 'FirebaseMessaging: ';\r\n// Set to '1' if Analytics is enabled for the campaign\r\nvar CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';\r\nvar CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';\r\nvar CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';\r\nvar CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';\r\n// Due to the fact that onBackgroundMessage can't be awaited (to support rxjs), a silent push\r\n// warning might be shown by the browser if the callback fails to completes by the end of onPush.\r\n// Experiments were ran to determine the majority onBackground message clock time. This brief\r\n// blocking time would allow majority of the onBackgroundMessage callback to finish.\r\nvar BACKGROUND_HANDLE_EXECUTION_TIME_LIMIT_MS = 1000;\r\n// Preparation time for client to initialize and set up the message handler.\r\nvar FOREGROUND_HANDLE_PREPARATION_TIME_MS = 3000;\n\n/**\r\n * @license\r\n * Copyright 2018 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except\r\n * in compliance with the License. You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software distributed under the License\r\n * is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\r\n * or implied. See the License for the specific language governing permissions and limitations under\r\n * the License.\r\n */\r\nvar MessageType;\r\n(function (MessageType) {\r\n MessageType[\"PUSH_RECEIVED\"] = \"push-received\";\r\n MessageType[\"NOTIFICATION_CLICKED\"] = \"notification-clicked\";\r\n})(MessageType || (MessageType = {}));\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction arrayToBase64(array) {\r\n var uint8Array = new Uint8Array(array);\r\n var base64String = btoa(String.fromCharCode.apply(String, __spreadArray([], __read(uint8Array))));\r\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\r\nfunction base64ToArray(base64String) {\r\n var padding = '='.repeat((4 - (base64String.length % 4)) % 4);\r\n var base64 = (base64String + padding)\r\n .replace(/\\-/g, '+')\r\n .replace(/_/g, '/');\r\n var rawData = atob(base64);\r\n var outputArray = new Uint8Array(rawData.length);\r\n for (var i = 0; i < rawData.length; ++i) {\r\n outputArray[i] = rawData.charCodeAt(i);\r\n }\r\n return outputArray;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar OLD_DB_NAME = 'fcm_token_details_db';\r\n/**\r\n * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade\r\n * callback is called for all versions of the old DB.\r\n */\r\nvar OLD_DB_VERSION = 5;\r\nvar OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\r\nfunction migrateOldDatabase(senderId) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var databases, dbNames, tokenDetails, db;\r\n var _this = this;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!('databases' in indexedDB)) return [3 /*break*/, 2];\r\n return [4 /*yield*/, indexedDB.databases()];\r\n case 1:\r\n databases = _a.sent();\r\n dbNames = databases.map(function (db) { return db.name; });\r\n if (!dbNames.includes(OLD_DB_NAME)) {\r\n // old DB didn't exist, no need to open.\r\n return [2 /*return*/, null];\r\n }\r\n _a.label = 2;\r\n case 2:\r\n tokenDetails = null;\r\n return [4 /*yield*/, openDb(OLD_DB_NAME, OLD_DB_VERSION, function (db) { return __awaiter(_this, void 0, void 0, function () {\r\n var objectStore, value, oldDetails, oldDetails, oldDetails;\r\n var _a;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n if (db.oldVersion < 2) {\r\n // Database too old, skip migration.\r\n return [2 /*return*/];\r\n }\r\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\r\n // Database did not exist. Nothing to do.\r\n return [2 /*return*/];\r\n }\r\n objectStore = db.transaction.objectStore(OLD_OBJECT_STORE_NAME);\r\n return [4 /*yield*/, objectStore.index('fcmSenderId').get(senderId)];\r\n case 1:\r\n value = _b.sent();\r\n return [4 /*yield*/, objectStore.clear()];\r\n case 2:\r\n _b.sent();\r\n if (!value) {\r\n // No entry in the database, nothing to migrate.\r\n return [2 /*return*/];\r\n }\r\n if (db.oldVersion === 2) {\r\n oldDetails = value;\r\n if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {\r\n return [2 /*return*/];\r\n }\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: (_a = oldDetails.createTime) !== null && _a !== void 0 ? _a : Date.now(),\r\n subscriptionOptions: {\r\n auth: oldDetails.auth,\r\n p256dh: oldDetails.p256dh,\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: typeof oldDetails.vapidKey === 'string'\r\n ? oldDetails.vapidKey\r\n : arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (db.oldVersion === 3) {\r\n oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n else if (db.oldVersion === 4) {\r\n oldDetails = value;\r\n tokenDetails = {\r\n token: oldDetails.fcmToken,\r\n createTime: oldDetails.createTime,\r\n subscriptionOptions: {\r\n auth: arrayToBase64(oldDetails.auth),\r\n p256dh: arrayToBase64(oldDetails.p256dh),\r\n endpoint: oldDetails.endpoint,\r\n swScope: oldDetails.swScope,\r\n vapidKey: arrayToBase64(oldDetails.vapidKey)\r\n }\r\n };\r\n }\r\n return [2 /*return*/];\r\n }\r\n });\r\n }); })];\r\n case 3:\r\n db = _a.sent();\r\n db.close();\r\n // Delete all old databases.\r\n return [4 /*yield*/, deleteDb(OLD_DB_NAME)];\r\n case 4:\r\n // Delete all old databases.\r\n _a.sent();\r\n return [4 /*yield*/, deleteDb('fcm_vapid_details_db')];\r\n case 5:\r\n _a.sent();\r\n return [4 /*yield*/, deleteDb('undefined')];\r\n case 6:\r\n _a.sent();\r\n return [2 /*return*/, checkTokenDetails(tokenDetails) ? tokenDetails : null];\r\n }\r\n });\r\n });\r\n}\r\nfunction checkTokenDetails(tokenDetails) {\r\n if (!tokenDetails || !tokenDetails.subscriptionOptions) {\r\n return false;\r\n }\r\n var subscriptionOptions = tokenDetails.subscriptionOptions;\r\n return (typeof tokenDetails.createTime === 'number' &&\r\n tokenDetails.createTime > 0 &&\r\n typeof tokenDetails.token === 'string' &&\r\n tokenDetails.token.length > 0 &&\r\n typeof subscriptionOptions.auth === 'string' &&\r\n subscriptionOptions.auth.length > 0 &&\r\n typeof subscriptionOptions.p256dh === 'string' &&\r\n subscriptionOptions.p256dh.length > 0 &&\r\n typeof subscriptionOptions.endpoint === 'string' &&\r\n subscriptionOptions.endpoint.length > 0 &&\r\n typeof subscriptionOptions.swScope === 'string' &&\r\n subscriptionOptions.swScope.length > 0 &&\r\n typeof subscriptionOptions.vapidKey === 'string' &&\r\n subscriptionOptions.vapidKey.length > 0);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Exported for tests.\r\nvar DATABASE_NAME = 'firebase-messaging-database';\r\nvar DATABASE_VERSION = 1;\r\nvar OBJECT_STORE_NAME = 'firebase-messaging-store';\r\nvar dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDb(DATABASE_NAME, DATABASE_VERSION, function (upgradeDb) {\r\n // We don't use 'break' in this switch statement, the fall-through behavior is what we want,\r\n // because if there are multiple versions between the old version and the current version, we\r\n // want ALL the migrations that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (upgradeDb.oldVersion) {\r\n case 0:\r\n upgradeDb.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Gets record(s) from the objectStore that match the given key. */\r\nfunction dbGet(firebaseDependencies) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var key, db, tokenDetails, oldTokenDetails;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n key = getKey(firebaseDependencies);\r\n return [4 /*yield*/, getDbPromise()];\r\n case 1:\r\n db = _a.sent();\r\n return [4 /*yield*/, db\r\n .transaction(OBJECT_STORE_NAME)\r\n .objectStore(OBJECT_STORE_NAME)\r\n .get(key)];\r\n case 2:\r\n tokenDetails = _a.sent();\r\n if (!tokenDetails) return [3 /*break*/, 3];\r\n return [2 /*return*/, tokenDetails];\r\n case 3: return [4 /*yield*/, migrateOldDatabase(firebaseDependencies.appConfig.senderId)];\r\n case 4:\r\n oldTokenDetails = _a.sent();\r\n if (!oldTokenDetails) return [3 /*break*/, 6];\r\n return [4 /*yield*/, dbSet(firebaseDependencies, oldTokenDetails)];\r\n case 5:\r\n _a.sent();\r\n return [2 /*return*/, oldTokenDetails];\r\n case 6: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nfunction dbSet(firebaseDependencies, tokenDetails) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var key, db, tx;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n key = getKey(firebaseDependencies);\r\n return [4 /*yield*/, getDbPromise()];\r\n case 1:\r\n db = _a.sent();\r\n tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n return [4 /*yield*/, tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key)];\r\n case 2:\r\n _a.sent();\r\n return [4 /*yield*/, tx.complete];\r\n case 3:\r\n _a.sent();\r\n return [2 /*return*/, tokenDetails];\r\n }\r\n });\r\n });\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nfunction dbRemove(firebaseDependencies) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var key, db, tx;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n key = getKey(firebaseDependencies);\r\n return [4 /*yield*/, getDbPromise()];\r\n case 1:\r\n db = _a.sent();\r\n tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n return [4 /*yield*/, tx.objectStore(OBJECT_STORE_NAME).delete(key)];\r\n case 2:\r\n _a.sent();\r\n return [4 /*yield*/, tx.complete];\r\n case 3:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\nfunction getKey(_a) {\r\n var appConfig = _a.appConfig;\r\n return appConfig.appId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction requestGetToken(firebaseDependencies, subscriptionOptions) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var headers, body, subscribeOptions, responseData, response, err_1, message;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, getHeaders(firebaseDependencies)];\r\n case 1:\r\n headers = _a.sent();\r\n body = getBody(subscriptionOptions);\r\n subscribeOptions = {\r\n method: 'POST',\r\n headers: headers,\r\n body: JSON.stringify(body)\r\n };\r\n _a.label = 2;\r\n case 2:\r\n _a.trys.push([2, 5, , 6]);\r\n return [4 /*yield*/, fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions)];\r\n case 3:\r\n response = _a.sent();\r\n return [4 /*yield*/, response.json()];\r\n case 4:\r\n responseData = _a.sent();\r\n return [3 /*break*/, 6];\r\n case 5:\r\n err_1 = _a.sent();\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: err_1\r\n });\r\n case 6:\r\n if (responseData.error) {\r\n message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-subscribe-failed\" /* TOKEN_SUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-subscribe-no-token\" /* TOKEN_SUBSCRIBE_NO_TOKEN */);\r\n }\r\n return [2 /*return*/, responseData.token];\r\n }\r\n });\r\n });\r\n}\r\nfunction requestUpdateToken(firebaseDependencies, tokenDetails) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var headers, body, updateOptions, responseData, response, err_2, message;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, getHeaders(firebaseDependencies)];\r\n case 1:\r\n headers = _a.sent();\r\n body = getBody(tokenDetails.subscriptionOptions);\r\n updateOptions = {\r\n method: 'PATCH',\r\n headers: headers,\r\n body: JSON.stringify(body)\r\n };\r\n _a.label = 2;\r\n case 2:\r\n _a.trys.push([2, 5, , 6]);\r\n return [4 /*yield*/, fetch(getEndpoint(firebaseDependencies.appConfig) + \"/\" + tokenDetails.token, updateOptions)];\r\n case 3:\r\n response = _a.sent();\r\n return [4 /*yield*/, response.json()];\r\n case 4:\r\n responseData = _a.sent();\r\n return [3 /*break*/, 6];\r\n case 5:\r\n err_2 = _a.sent();\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* TOKEN_UPDATE_FAILED */, {\r\n errorInfo: err_2\r\n });\r\n case 6:\r\n if (responseData.error) {\r\n message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-update-failed\" /* TOKEN_UPDATE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n if (!responseData.token) {\r\n throw ERROR_FACTORY.create(\"token-update-no-token\" /* TOKEN_UPDATE_NO_TOKEN */);\r\n }\r\n return [2 /*return*/, responseData.token];\r\n }\r\n });\r\n });\r\n}\r\nfunction requestDeleteToken(firebaseDependencies, token) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var headers, unsubscribeOptions, response, responseData, message, err_3;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, getHeaders(firebaseDependencies)];\r\n case 1:\r\n headers = _a.sent();\r\n unsubscribeOptions = {\r\n method: 'DELETE',\r\n headers: headers\r\n };\r\n _a.label = 2;\r\n case 2:\r\n _a.trys.push([2, 5, , 6]);\r\n return [4 /*yield*/, fetch(getEndpoint(firebaseDependencies.appConfig) + \"/\" + token, unsubscribeOptions)];\r\n case 3:\r\n response = _a.sent();\r\n return [4 /*yield*/, response.json()];\r\n case 4:\r\n responseData = _a.sent();\r\n if (responseData.error) {\r\n message = responseData.error.message;\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: message\r\n });\r\n }\r\n return [3 /*break*/, 6];\r\n case 5:\r\n err_3 = _a.sent();\r\n throw ERROR_FACTORY.create(\"token-unsubscribe-failed\" /* TOKEN_UNSUBSCRIBE_FAILED */, {\r\n errorInfo: err_3\r\n });\r\n case 6: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\nfunction getEndpoint(_a) {\r\n var projectId = _a.projectId;\r\n return ENDPOINT + \"/projects/\" + projectId + \"/registrations\";\r\n}\r\nfunction getHeaders(_a) {\r\n var appConfig = _a.appConfig, installations = _a.installations;\r\n return __awaiter(this, void 0, void 0, function () {\r\n var authToken;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0: return [4 /*yield*/, installations.getToken()];\r\n case 1:\r\n authToken = _b.sent();\r\n return [2 /*return*/, new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': appConfig.apiKey,\r\n 'x-goog-firebase-installations-auth': \"FIS \" + authToken\r\n })];\r\n }\r\n });\r\n });\r\n}\r\nfunction getBody(_a) {\r\n var p256dh = _a.p256dh, auth = _a.auth, endpoint = _a.endpoint, vapidKey = _a.vapidKey;\r\n var body = {\r\n web: {\r\n endpoint: endpoint,\r\n auth: auth,\r\n p256dh: p256dh\r\n }\r\n };\r\n if (vapidKey !== DEFAULT_VAPID_KEY) {\r\n body.web.applicationPubKey = vapidKey;\r\n }\r\n return body;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** UpdateRegistration will be called once every week. */\r\nvar TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\r\nfunction getToken(firebaseDependencies, swRegistration, vapidKey) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var pushSubscription, tokenDetails, subscriptionOptions, e_1;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (Notification.permission !== 'granted') {\r\n throw ERROR_FACTORY.create(\"permission-blocked\" /* PERMISSION_BLOCKED */);\r\n }\r\n return [4 /*yield*/, getPushSubscription(swRegistration, vapidKey)];\r\n case 1:\r\n pushSubscription = _a.sent();\r\n return [4 /*yield*/, dbGet(firebaseDependencies)];\r\n case 2:\r\n tokenDetails = _a.sent();\r\n subscriptionOptions = {\r\n vapidKey: vapidKey,\r\n swScope: swRegistration.scope,\r\n endpoint: pushSubscription.endpoint,\r\n auth: arrayToBase64(pushSubscription.getKey('auth')),\r\n p256dh: arrayToBase64(pushSubscription.getKey('p256dh'))\r\n };\r\n if (!!tokenDetails) return [3 /*break*/, 3];\r\n // No token, get a new one.\r\n return [2 /*return*/, getNewToken(firebaseDependencies, subscriptionOptions)];\r\n case 3:\r\n if (!!isTokenValid(tokenDetails.subscriptionOptions, subscriptionOptions)) return [3 /*break*/, 8];\r\n _a.label = 4;\r\n case 4:\r\n _a.trys.push([4, 6, , 7]);\r\n return [4 /*yield*/, requestDeleteToken(firebaseDependencies, tokenDetails.token)];\r\n case 5:\r\n _a.sent();\r\n return [3 /*break*/, 7];\r\n case 6:\r\n e_1 = _a.sent();\r\n // Suppress errors because of #2364\r\n console.warn(e_1);\r\n return [3 /*break*/, 7];\r\n case 7: return [2 /*return*/, getNewToken(firebaseDependencies, subscriptionOptions)];\r\n case 8:\r\n if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {\r\n // Weekly token refresh\r\n return [2 /*return*/, updateToken({\r\n token: tokenDetails.token,\r\n createTime: Date.now(),\r\n subscriptionOptions: subscriptionOptions\r\n }, firebaseDependencies, swRegistration)];\r\n }\r\n else {\r\n // Valid token, nothing to do.\r\n return [2 /*return*/, tokenDetails.token];\r\n }\r\n case 9: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * This method deletes the token from the database, unsubscribes the token from FCM, and unregisters\r\n * the push subscription if it exists.\r\n */\r\nfunction deleteToken(firebaseDependencies, swRegistration) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var tokenDetails, pushSubscription;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, dbGet(firebaseDependencies)];\r\n case 1:\r\n tokenDetails = _a.sent();\r\n if (!tokenDetails) return [3 /*break*/, 4];\r\n return [4 /*yield*/, requestDeleteToken(firebaseDependencies, tokenDetails.token)];\r\n case 2:\r\n _a.sent();\r\n return [4 /*yield*/, dbRemove(firebaseDependencies)];\r\n case 3:\r\n _a.sent();\r\n _a.label = 4;\r\n case 4: return [4 /*yield*/, swRegistration.pushManager.getSubscription()];\r\n case 5:\r\n pushSubscription = _a.sent();\r\n if (pushSubscription) {\r\n return [2 /*return*/, pushSubscription.unsubscribe()];\r\n }\r\n // If there's no SW, consider it a success.\r\n return [2 /*return*/, true];\r\n }\r\n });\r\n });\r\n}\r\nfunction updateToken(tokenDetails, firebaseDependencies, swRegistration) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var updatedToken, updatedTokenDetails, e_2;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n _a.trys.push([0, 3, , 5]);\r\n return [4 /*yield*/, requestUpdateToken(firebaseDependencies, tokenDetails)];\r\n case 1:\r\n updatedToken = _a.sent();\r\n updatedTokenDetails = __assign(__assign({}, tokenDetails), { token: updatedToken, createTime: Date.now() });\r\n return [4 /*yield*/, dbSet(firebaseDependencies, updatedTokenDetails)];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/, updatedToken];\r\n case 3:\r\n e_2 = _a.sent();\r\n return [4 /*yield*/, deleteToken(firebaseDependencies, swRegistration)];\r\n case 4:\r\n _a.sent();\r\n throw e_2;\r\n case 5: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n}\r\nfunction getNewToken(firebaseDependencies, subscriptionOptions) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var token, tokenDetails;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, requestGetToken(firebaseDependencies, subscriptionOptions)];\r\n case 1:\r\n token = _a.sent();\r\n tokenDetails = {\r\n token: token,\r\n createTime: Date.now(),\r\n subscriptionOptions: subscriptionOptions\r\n };\r\n return [4 /*yield*/, dbSet(firebaseDependencies, tokenDetails)];\r\n case 2:\r\n _a.sent();\r\n return [2 /*return*/, tokenDetails.token];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * Gets a PushSubscription for the current user.\r\n */\r\nfunction getPushSubscription(swRegistration, vapidKey) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var subscription;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0: return [4 /*yield*/, swRegistration.pushManager.getSubscription()];\r\n case 1:\r\n subscription = _a.sent();\r\n if (subscription) {\r\n return [2 /*return*/, subscription];\r\n }\r\n return [2 /*return*/, swRegistration.pushManager.subscribe({\r\n userVisibleOnly: true,\r\n // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key\r\n // submitted to pushManager#subscribe must be of type Uint8Array.\r\n applicationServerKey: base64ToArray(vapidKey)\r\n })];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * Checks if the saved tokenDetails object matches the configuration provided.\r\n */\r\nfunction isTokenValid(dbOptions, currentOptions) {\r\n var isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;\r\n var isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;\r\n var isAuthEqual = currentOptions.auth === dbOptions.auth;\r\n var isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;\r\n return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction externalizePayload(internalPayload) {\r\n var payload = {\r\n from: internalPayload.from,\r\n // eslint-disable-next-line camelcase\r\n collapseKey: internalPayload.collapse_key,\r\n // eslint-disable-next-line camelcase\r\n messageId: internalPayload.fcm_message_id\r\n };\r\n propagateNotificationPayload(payload, internalPayload);\r\n propagateDataPayload(payload, internalPayload);\r\n propagateFcmOptions(payload, internalPayload);\r\n return payload;\r\n}\r\nfunction propagateNotificationPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.notification) {\r\n return;\r\n }\r\n payload.notification = {};\r\n var title = messagePayloadInternal.notification.title;\r\n if (!!title) {\r\n payload.notification.title = title;\r\n }\r\n var body = messagePayloadInternal.notification.body;\r\n if (!!body) {\r\n payload.notification.body = body;\r\n }\r\n var image = messagePayloadInternal.notification.image;\r\n if (!!image) {\r\n payload.notification.image = image;\r\n }\r\n}\r\nfunction propagateDataPayload(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.data) {\r\n return;\r\n }\r\n payload.data = messagePayloadInternal.data;\r\n}\r\nfunction propagateFcmOptions(payload, messagePayloadInternal) {\r\n if (!messagePayloadInternal.fcmOptions) {\r\n return;\r\n }\r\n payload.fcmOptions = {};\r\n var link = messagePayloadInternal.fcmOptions.link;\r\n if (!!link) {\r\n payload.fcmOptions.link = link;\r\n }\r\n // eslint-disable-next-line camelcase\r\n var analyticsLabel = messagePayloadInternal.fcmOptions.analytics_label;\r\n if (!!analyticsLabel) {\r\n payload.fcmOptions.analyticsLabel = analyticsLabel;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isConsoleMessage(data) {\r\n // This message has a campaign ID, meaning it was sent using the Firebase Console.\r\n return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a promise that resolves after given time passes. */\r\nfunction sleep(ms) {\r\n return new Promise(function (resolve) {\r\n setTimeout(resolve, ms);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar SwController = /** @class */ (function () {\r\n function SwController(firebaseDependencies) {\r\n var _this = this;\r\n this.firebaseDependencies = firebaseDependencies;\r\n // A boolean flag to determine wether an app is using onBackgroundMessage or\r\n // setBackgroundMessageHandler. onBackgroundMessage will receive a MessagePayload regardless of if\r\n // a notification is displayed. Whereas, setBackgroundMessageHandler will swallow the\r\n // MessagePayload if a NotificationPayload is included.\r\n this.isOnBackgroundMessageUsed = null;\r\n this.vapidKey = null;\r\n this.bgMessageHandler = null;\r\n self.addEventListener('push', function (e) {\r\n e.waitUntil(_this.onPush(e));\r\n });\r\n self.addEventListener('pushsubscriptionchange', function (e) {\r\n e.waitUntil(_this.onSubChange(e));\r\n });\r\n self.addEventListener('notificationclick', function (e) {\r\n e.waitUntil(_this.onNotificationClick(e));\r\n });\r\n }\r\n Object.defineProperty(SwController.prototype, \"app\", {\r\n get: function () {\r\n return this.firebaseDependencies.app;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n /**\r\n * @deprecated. Use onBackgroundMessage(nextOrObserver: NextFn | Observer):\r\n * Unsubscribe instead.\r\n *\r\n * Calling setBackgroundMessageHandler will opt in to some specific behaviors.\r\n *\r\n * 1.) If a notification doesn't need to be shown due to a window already being visible, then push\r\n * messages will be sent to the page. 2.) If a notification needs to be shown, and the message\r\n * contains no notification data this method will be called and the promise it returns will be\r\n * passed to event.waitUntil. If you do not set this callback then all push messages will let and\r\n * the developer can handle them in a their own 'push' event callback\r\n *\r\n * @param callback The callback to be called when a push message is received and a notification\r\n * must be shown. The callback will be given the data from the push message.\r\n */\r\n SwController.prototype.setBackgroundMessageHandler = function (callback) {\r\n this.isOnBackgroundMessageUsed = false;\r\n if (!callback || typeof callback !== 'function') {\r\n throw ERROR_FACTORY.create(\"invalid-bg-handler\" /* INVALID_BG_HANDLER */);\r\n }\r\n this.bgMessageHandler = callback;\r\n };\r\n SwController.prototype.onBackgroundMessage = function (nextOrObserver) {\r\n var _this = this;\r\n this.isOnBackgroundMessageUsed = true;\r\n this.bgMessageHandler = nextOrObserver;\r\n return function () {\r\n _this.bgMessageHandler = null;\r\n };\r\n };\r\n // TODO: Remove getToken from SW Controller. Calling this from an old SW can cause all kinds of\r\n // trouble.\r\n SwController.prototype.getToken = function () {\r\n var _a, _b;\r\n return __awaiter(this, void 0, void 0, function () {\r\n var tokenDetails;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n if (!!this.vapidKey) return [3 /*break*/, 2];\r\n return [4 /*yield*/, dbGet(this.firebaseDependencies)];\r\n case 1:\r\n tokenDetails = _c.sent();\r\n this.vapidKey =\r\n (_b = (_a = tokenDetails === null || tokenDetails === void 0 ? void 0 : tokenDetails.subscriptionOptions) === null || _a === void 0 ? void 0 : _a.vapidKey) !== null && _b !== void 0 ? _b : DEFAULT_VAPID_KEY;\r\n _c.label = 2;\r\n case 2: return [2 /*return*/, getToken(this.firebaseDependencies, self.registration, this.vapidKey)];\r\n }\r\n });\r\n });\r\n };\r\n // TODO: Remove deleteToken from SW Controller. Calling this from an old SW can cause all kinds of\r\n // trouble.\r\n SwController.prototype.deleteToken = function () {\r\n return deleteToken(this.firebaseDependencies, self.registration);\r\n };\r\n SwController.prototype.requestPermission = function () {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n };\r\n // TODO: Remove this together with getToken from SW Controller.\r\n SwController.prototype.usePublicVapidKey = function (vapidKey) {\r\n if (this.vapidKey !== null) {\r\n throw ERROR_FACTORY.create(\"use-vapid-key-after-get-token\" /* USE_VAPID_KEY_AFTER_GET_TOKEN */);\r\n }\r\n if (typeof vapidKey !== 'string' || vapidKey.length === 0) {\r\n throw ERROR_FACTORY.create(\"invalid-vapid-key\" /* INVALID_VAPID_KEY */);\r\n }\r\n this.vapidKey = vapidKey;\r\n };\r\n SwController.prototype.useServiceWorker = function () {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n };\r\n SwController.prototype.onMessage = function () {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n };\r\n SwController.prototype.onTokenRefresh = function () {\r\n throw ERROR_FACTORY.create(\"only-available-in-window\" /* AVAILABLE_IN_WINDOW */);\r\n };\r\n /**\r\n * A handler for push events that shows notifications based on the content of the payload.\r\n *\r\n * The payload must be a JSON-encoded Object with a `notification` key. The value of the\r\n * `notification` property will be used as the NotificationOptions object passed to\r\n * showNotification. Additionally, the `title` property of the notification object will be used as\r\n * the title.\r\n *\r\n * If there is no notification data in the payload then no notification will be shown.\r\n */\r\n SwController.prototype.onPush = function (event) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var internalPayload, clientList, isNotificationShown, payload;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n internalPayload = getMessagePayloadInternal(event);\r\n if (!internalPayload) {\r\n console.debug(TAG +\r\n 'failed to get parsed MessagePayload from the PushEvent. Skip handling the push.');\r\n return [2 /*return*/];\r\n }\r\n return [4 /*yield*/, getClientList()];\r\n case 1:\r\n clientList = _a.sent();\r\n if (hasVisibleClients(clientList)) {\r\n return [2 /*return*/, sendMessagePayloadInternalToWindows(clientList, internalPayload)];\r\n }\r\n isNotificationShown = false;\r\n if (!!!internalPayload.notification) return [3 /*break*/, 3];\r\n return [4 /*yield*/, showNotification(wrapInternalPayload(internalPayload))];\r\n case 2:\r\n _a.sent();\r\n isNotificationShown = true;\r\n _a.label = 3;\r\n case 3:\r\n // MessagePayload is only passed to `onBackgroundMessage`. Skip passing MessagePayload for\r\n // the legacy `setBackgroundMessageHandler` to preserve the SDK behaviors.\r\n if (isNotificationShown === true &&\r\n this.isOnBackgroundMessageUsed === false) {\r\n return [2 /*return*/];\r\n }\r\n if (!!this.bgMessageHandler) {\r\n payload = externalizePayload(internalPayload);\r\n if (typeof this.bgMessageHandler === 'function') {\r\n this.bgMessageHandler(payload);\r\n }\r\n else {\r\n this.bgMessageHandler.next(payload);\r\n }\r\n }\r\n // wait briefly to allow onBackgroundMessage to complete\r\n return [4 /*yield*/, sleep(BACKGROUND_HANDLE_EXECUTION_TIME_LIMIT_MS)];\r\n case 4:\r\n // wait briefly to allow onBackgroundMessage to complete\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n SwController.prototype.onSubChange = function (event) {\r\n var _a, _b;\r\n return __awaiter(this, void 0, void 0, function () {\r\n var newSubscription, tokenDetails;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n newSubscription = event.newSubscription;\r\n if (!!newSubscription) return [3 /*break*/, 2];\r\n // Subscription revoked, delete token\r\n return [4 /*yield*/, deleteToken(this.firebaseDependencies, self.registration)];\r\n case 1:\r\n // Subscription revoked, delete token\r\n _c.sent();\r\n return [2 /*return*/];\r\n case 2: return [4 /*yield*/, dbGet(this.firebaseDependencies)];\r\n case 3:\r\n tokenDetails = _c.sent();\r\n return [4 /*yield*/, deleteToken(this.firebaseDependencies, self.registration)];\r\n case 4:\r\n _c.sent();\r\n return [4 /*yield*/, getToken(this.firebaseDependencies, self.registration, (_b = (_a = tokenDetails === null || tokenDetails === void 0 ? void 0 : tokenDetails.subscriptionOptions) === null || _a === void 0 ? void 0 : _a.vapidKey) !== null && _b !== void 0 ? _b : DEFAULT_VAPID_KEY)];\r\n case 5:\r\n _c.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n SwController.prototype.onNotificationClick = function (event) {\r\n var _a, _b;\r\n return __awaiter(this, void 0, void 0, function () {\r\n var internalPayload, link, url, originUrl, client;\r\n return __generator(this, function (_c) {\r\n switch (_c.label) {\r\n case 0:\r\n internalPayload = (_b = (_a = event.notification) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b[FCM_MSG];\r\n if (!internalPayload) {\r\n return [2 /*return*/];\r\n }\r\n else if (event.action) {\r\n // User clicked on an action button. This will allow developers to act on action button clicks\r\n // by using a custom onNotificationClick listener that they define.\r\n return [2 /*return*/];\r\n }\r\n // Prevent other listeners from receiving the event\r\n event.stopImmediatePropagation();\r\n event.notification.close();\r\n link = getLink(internalPayload);\r\n if (!link) {\r\n return [2 /*return*/];\r\n }\r\n url = new URL(link, self.location.href);\r\n originUrl = new URL(self.location.origin);\r\n if (url.host !== originUrl.host) {\r\n return [2 /*return*/];\r\n }\r\n return [4 /*yield*/, getWindowClient(url)];\r\n case 1:\r\n client = _c.sent();\r\n if (!!client) return [3 /*break*/, 4];\r\n return [4 /*yield*/, self.clients.openWindow(link)];\r\n case 2:\r\n client = _c.sent();\r\n // Wait three seconds for the client to initialize and set up the message handler so that it\r\n // can receive the message.\r\n return [4 /*yield*/, sleep(FOREGROUND_HANDLE_PREPARATION_TIME_MS)];\r\n case 3:\r\n // Wait three seconds for the client to initialize and set up the message handler so that it\r\n // can receive the message.\r\n _c.sent();\r\n return [3 /*break*/, 6];\r\n case 4: return [4 /*yield*/, client.focus()];\r\n case 5:\r\n client = _c.sent();\r\n _c.label = 6;\r\n case 6:\r\n if (!client) {\r\n // Window Client will not be returned if it's for a third party origin.\r\n return [2 /*return*/];\r\n }\r\n internalPayload.messageType = MessageType.NOTIFICATION_CLICKED;\r\n internalPayload.isFirebaseMessaging = true;\r\n return [2 /*return*/, client.postMessage(internalPayload)];\r\n }\r\n });\r\n });\r\n };\r\n return SwController;\r\n}());\r\nfunction wrapInternalPayload(internalPayload) {\r\n var _a;\r\n var wrappedInternalPayload = __assign({}, internalPayload.notification);\r\n // Put the message payload under FCM_MSG name so we can identify the notification as being an FCM\r\n // notification vs a notification from somewhere else (i.e. normal web push or developer generated\r\n // notification).\r\n wrappedInternalPayload.data = (_a = {},\r\n _a[FCM_MSG] = internalPayload,\r\n _a);\r\n return wrappedInternalPayload;\r\n}\r\nfunction getMessagePayloadInternal(_a) {\r\n var data = _a.data;\r\n if (!data) {\r\n return null;\r\n }\r\n try {\r\n return data.json();\r\n }\r\n catch (err) {\r\n // Not JSON so not an FCM message.\r\n return null;\r\n }\r\n}\r\n/**\r\n * @param url The URL to look for when focusing a client.\r\n * @return Returns an existing window client or a newly opened WindowClient.\r\n */\r\nfunction getWindowClient(url) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var clientList, clientList_1, clientList_1_1, client, clientUrl;\r\n var e_1, _a;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0: return [4 /*yield*/, getClientList()];\r\n case 1:\r\n clientList = _b.sent();\r\n try {\r\n for (clientList_1 = __values(clientList), clientList_1_1 = clientList_1.next(); !clientList_1_1.done; clientList_1_1 = clientList_1.next()) {\r\n client = clientList_1_1.value;\r\n clientUrl = new URL(client.url, self.location.href);\r\n if (url.host === clientUrl.host) {\r\n return [2 /*return*/, client];\r\n }\r\n }\r\n }\r\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\r\n finally {\r\n try {\r\n if (clientList_1_1 && !clientList_1_1.done && (_a = clientList_1.return)) _a.call(clientList_1);\r\n }\r\n finally { if (e_1) throw e_1.error; }\r\n }\r\n return [2 /*return*/, null];\r\n }\r\n });\r\n });\r\n}\r\n/**\r\n * @returns If there is currently a visible WindowClient, this method will resolve to true,\r\n * otherwise false.\r\n */\r\nfunction hasVisibleClients(clientList) {\r\n return clientList.some(function (client) {\r\n return client.visibilityState === 'visible' &&\r\n // Ignore chrome-extension clients as that matches the background pages of extensions, which\r\n // are always considered visible for some reason.\r\n !client.url.startsWith('chrome-extension://');\r\n });\r\n}\r\nfunction sendMessagePayloadInternalToWindows(clientList, internalPayload) {\r\n var e_2, _a;\r\n internalPayload.isFirebaseMessaging = true;\r\n internalPayload.messageType = MessageType.PUSH_RECEIVED;\r\n try {\r\n for (var clientList_2 = __values(clientList), clientList_2_1 = clientList_2.next(); !clientList_2_1.done; clientList_2_1 = clientList_2.next()) {\r\n var client = clientList_2_1.value;\r\n client.postMessage(internalPayload);\r\n }\r\n }\r\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\r\n finally {\r\n try {\r\n if (clientList_2_1 && !clientList_2_1.done && (_a = clientList_2.return)) _a.call(clientList_2);\r\n }\r\n finally { if (e_2) throw e_2.error; }\r\n }\r\n}\r\nfunction getClientList() {\r\n return self.clients.matchAll({\r\n type: 'window',\r\n includeUncontrolled: true\r\n // TS doesn't know that \"type: 'window'\" means it'll return WindowClient[]\r\n });\r\n}\r\nfunction showNotification(notificationPayloadInternal) {\r\n var _a;\r\n // Note: Firefox does not support the maxActions property.\r\n // https://developer.mozilla.org/en-US/docs/Web/API/notification/maxActions\r\n var actions = notificationPayloadInternal.actions;\r\n var maxActions = Notification.maxActions;\r\n if (actions && maxActions && actions.length > maxActions) {\r\n console.warn(\"This browser only supports \" + maxActions + \" actions. The remaining actions will not be displayed.\");\r\n }\r\n return self.registration.showNotification(\r\n /* title= */ (_a = notificationPayloadInternal.title) !== null && _a !== void 0 ? _a : '', notificationPayloadInternal);\r\n}\r\nfunction getLink(payload) {\r\n var _a, _b, _c;\r\n // eslint-disable-next-line camelcase\r\n var link = (_b = (_a = payload.fcmOptions) === null || _a === void 0 ? void 0 : _a.link) !== null && _b !== void 0 ? _b : (_c = payload.notification) === null || _c === void 0 ? void 0 : _c.click_action;\r\n if (link) {\r\n return link;\r\n }\r\n if (isConsoleMessage(payload.data)) {\r\n // Notification created in the Firebase Console. Redirect to origin.\r\n return self.location.origin;\r\n }\r\n else {\r\n return null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar WindowController = /** @class */ (function () {\r\n function WindowController(firebaseDependencies) {\r\n var _this = this;\r\n this.firebaseDependencies = firebaseDependencies;\r\n this.vapidKey = null;\r\n this.onMessageCallback = null;\r\n navigator.serviceWorker.addEventListener('message', function (e) {\r\n return _this.messageEventListener(e);\r\n });\r\n }\r\n Object.defineProperty(WindowController.prototype, \"app\", {\r\n get: function () {\r\n return this.firebaseDependencies.app;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n WindowController.prototype.messageEventListener = function (event) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var internalPayload, dataPayload;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n internalPayload = event.data;\r\n if (!internalPayload.isFirebaseMessaging) {\r\n return [2 /*return*/];\r\n }\r\n // onMessageCallback is either a function or observer/subscriber.\r\n // TODO: in the modularization release, have onMessage handle type MessagePayload as supposed to\r\n // the legacy payload where some fields are in snake cases.\r\n if (this.onMessageCallback &&\r\n internalPayload.messageType === MessageType.PUSH_RECEIVED) {\r\n if (typeof this.onMessageCallback === 'function') {\r\n this.onMessageCallback(stripInternalFields(Object.assign({}, internalPayload)));\r\n }\r\n else {\r\n this.onMessageCallback.next(Object.assign({}, internalPayload));\r\n }\r\n }\r\n dataPayload = internalPayload.data;\r\n if (!(isConsoleMessage(dataPayload) &&\r\n dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1')) return [3 /*break*/, 2];\r\n return [4 /*yield*/, this.logEvent(internalPayload.messageType, dataPayload)];\r\n case 1:\r\n _a.sent();\r\n _a.label = 2;\r\n case 2: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n WindowController.prototype.getVapidKey = function () {\r\n return this.vapidKey;\r\n };\r\n WindowController.prototype.getSwReg = function () {\r\n return this.swRegistration;\r\n };\r\n WindowController.prototype.getToken = function (options) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!(Notification.permission === 'default')) return [3 /*break*/, 2];\r\n return [4 /*yield*/, Notification.requestPermission()];\r\n case 1:\r\n _a.sent();\r\n _a.label = 2;\r\n case 2:\r\n if (Notification.permission !== 'granted') {\r\n throw ERROR_FACTORY.create(\"permission-blocked\" /* PERMISSION_BLOCKED */);\r\n }\r\n return [4 /*yield*/, this.updateVapidKey(options === null || options === void 0 ? void 0 : options.vapidKey)];\r\n case 3:\r\n _a.sent();\r\n return [4 /*yield*/, this.updateSwReg(options === null || options === void 0 ? void 0 : options.serviceWorkerRegistration)];\r\n case 4:\r\n _a.sent();\r\n return [2 /*return*/, getToken(this.firebaseDependencies, this.swRegistration, this.vapidKey)];\r\n }\r\n });\r\n });\r\n };\r\n WindowController.prototype.updateVapidKey = function (vapidKey) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n if (!!vapidKey) {\r\n this.vapidKey = vapidKey;\r\n }\r\n else if (!this.vapidKey) {\r\n this.vapidKey = DEFAULT_VAPID_KEY;\r\n }\r\n return [2 /*return*/];\r\n });\r\n });\r\n };\r\n WindowController.prototype.updateSwReg = function (swRegistration) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!(!swRegistration && !this.swRegistration)) return [3 /*break*/, 2];\r\n return [4 /*yield*/, this.registerDefaultSw()];\r\n case 1:\r\n _a.sent();\r\n _a.label = 2;\r\n case 2:\r\n if (!swRegistration && !!this.swRegistration) {\r\n return [2 /*return*/];\r\n }\r\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\r\n throw ERROR_FACTORY.create(\"invalid-sw-registration\" /* INVALID_SW_REGISTRATION */);\r\n }\r\n this.swRegistration = swRegistration;\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n WindowController.prototype.registerDefaultSw = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var _a, e_1;\r\n return __generator(this, function (_b) {\r\n switch (_b.label) {\r\n case 0:\r\n _b.trys.push([0, 2, , 3]);\r\n _a = this;\r\n return [4 /*yield*/, navigator.serviceWorker.register(DEFAULT_SW_PATH, {\r\n scope: DEFAULT_SW_SCOPE\r\n })];\r\n case 1:\r\n _a.swRegistration = _b.sent();\r\n // The timing when browser updates sw when sw has an update is unreliable by my experiment. It\r\n // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw\r\n // is stuck with the old version. For example,\r\n // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates\r\n // sw if there was an update.\r\n this.swRegistration.update().catch(function () {\r\n /* it is non blocking and we don't care if it failed */\r\n });\r\n return [3 /*break*/, 3];\r\n case 2:\r\n e_1 = _b.sent();\r\n throw ERROR_FACTORY.create(\"failed-service-worker-registration\" /* FAILED_DEFAULT_REGISTRATION */, {\r\n browserErrorMessage: e_1.message\r\n });\r\n case 3: return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n WindowController.prototype.deleteToken = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (!!this.swRegistration) return [3 /*break*/, 2];\r\n return [4 /*yield*/, this.registerDefaultSw()];\r\n case 1:\r\n _a.sent();\r\n _a.label = 2;\r\n case 2: return [2 /*return*/, deleteToken(this.firebaseDependencies, this.swRegistration)];\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * Request permission if it is not currently granted.\r\n *\r\n * @return Resolves if the permission was granted, rejects otherwise.\r\n *\r\n * @deprecated Use Notification.requestPermission() instead.\r\n * https://developer.mozilla.org/en-US/docs/Web/API/Notification/requestPermission\r\n */\r\n WindowController.prototype.requestPermission = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var permissionResult;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n if (Notification.permission === 'granted') {\r\n return [2 /*return*/];\r\n }\r\n return [4 /*yield*/, Notification.requestPermission()];\r\n case 1:\r\n permissionResult = _a.sent();\r\n if (permissionResult === 'granted') {\r\n return [2 /*return*/];\r\n }\r\n else if (permissionResult === 'denied') {\r\n throw ERROR_FACTORY.create(\"permission-blocked\" /* PERMISSION_BLOCKED */);\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"permission-default\" /* PERMISSION_DEFAULT */);\r\n }\r\n }\r\n });\r\n });\r\n };\r\n /**\r\n * @deprecated. Use getToken(options?: {vapidKey?: string; serviceWorkerRegistration?:\r\n * ServiceWorkerRegistration;}): Promise instead.\r\n */\r\n WindowController.prototype.usePublicVapidKey = function (vapidKey) {\r\n if (this.vapidKey !== null) {\r\n throw ERROR_FACTORY.create(\"use-vapid-key-after-get-token\" /* USE_VAPID_KEY_AFTER_GET_TOKEN */);\r\n }\r\n if (typeof vapidKey !== 'string' || vapidKey.length === 0) {\r\n throw ERROR_FACTORY.create(\"invalid-vapid-key\" /* INVALID_VAPID_KEY */);\r\n }\r\n this.vapidKey = vapidKey;\r\n };\r\n /**\r\n * @deprecated. Use getToken(options?: {vapidKey?: string; serviceWorkerRegistration?:\r\n * ServiceWorkerRegistration;}): Promise instead.\r\n */\r\n WindowController.prototype.useServiceWorker = function (swRegistration) {\r\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\r\n throw ERROR_FACTORY.create(\"invalid-sw-registration\" /* INVALID_SW_REGISTRATION */);\r\n }\r\n if (this.swRegistration) {\r\n throw ERROR_FACTORY.create(\"use-sw-after-get-token\" /* USE_SW_AFTER_GET_TOKEN */);\r\n }\r\n this.swRegistration = swRegistration;\r\n };\r\n /**\r\n * @param nextOrObserver An observer object or a function triggered on message.\r\n *\r\n * @return The unsubscribe function for the observer.\r\n */\r\n WindowController.prototype.onMessage = function (nextOrObserver) {\r\n var _this = this;\r\n this.onMessageCallback = nextOrObserver;\r\n return function () {\r\n _this.onMessageCallback = null;\r\n };\r\n };\r\n WindowController.prototype.setBackgroundMessageHandler = function () {\r\n throw ERROR_FACTORY.create(\"only-available-in-sw\" /* AVAILABLE_IN_SW */);\r\n };\r\n WindowController.prototype.onBackgroundMessage = function () {\r\n throw ERROR_FACTORY.create(\"only-available-in-sw\" /* AVAILABLE_IN_SW */);\r\n };\r\n /**\r\n * @deprecated No-op. It was initially designed with token rotation requests from server in mind.\r\n * However, the plan to implement such feature was abandoned.\r\n */\r\n WindowController.prototype.onTokenRefresh = function () {\r\n return function () { };\r\n };\r\n WindowController.prototype.logEvent = function (messageType, data) {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var eventType, analytics;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n eventType = getEventType(messageType);\r\n return [4 /*yield*/, this.firebaseDependencies.analyticsProvider.get()];\r\n case 1:\r\n analytics = _a.sent();\r\n analytics.logEvent(eventType, {\r\n /* eslint-disable camelcase */\r\n message_id: data[CONSOLE_CAMPAIGN_ID],\r\n message_name: data[CONSOLE_CAMPAIGN_NAME],\r\n message_time: data[CONSOLE_CAMPAIGN_TIME],\r\n message_device_time: Math.floor(Date.now() / 1000)\r\n /* eslint-enable camelcase */\r\n });\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n return WindowController;\r\n}());\r\nfunction getEventType(messageType) {\r\n switch (messageType) {\r\n case MessageType.NOTIFICATION_CLICKED:\r\n return 'notification_open';\r\n case MessageType.PUSH_RECEIVED:\r\n return 'notification_foreground';\r\n default:\r\n throw new Error();\r\n }\r\n}\r\nfunction stripInternalFields(internalPayload) {\r\n delete internalPayload.messageType;\r\n delete internalPayload.isFirebaseMessaging;\r\n return internalPayload;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n var e_1, _a;\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration Object');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n var configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId',\r\n 'messagingSenderId'\r\n ];\r\n var options = app.options;\r\n try {\r\n for (var configKeys_1 = __values(configKeys), configKeys_1_1 = configKeys_1.next(); !configKeys_1_1.done; configKeys_1_1 = configKeys_1.next()) {\r\n var keyName = configKeys_1_1.value;\r\n if (!options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n }\r\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\r\n finally {\r\n try {\r\n if (configKeys_1_1 && !configKeys_1_1.done && (_a = configKeys_1.return)) _a.call(configKeys_1);\r\n }\r\n finally { if (e_1) throw e_1.error; }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: options.projectId,\r\n apiKey: options.apiKey,\r\n appId: options.appId,\r\n senderId: options.messagingSenderId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */, {\r\n valueName: valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar MESSAGING_NAME = 'messaging';\r\nfunction factoryMethod(container) {\r\n // Dependencies.\r\n var app = container.getProvider('app').getImmediate();\r\n var appConfig = extractAppConfig(app);\r\n var installations = container.getProvider('installations').getImmediate();\r\n var analyticsProvider = container.getProvider('analytics-internal');\r\n var firebaseDependencies = {\r\n app: app,\r\n appConfig: appConfig,\r\n installations: installations,\r\n analyticsProvider: analyticsProvider\r\n };\r\n if (!isSupported()) {\r\n throw ERROR_FACTORY.create(\"unsupported-browser\" /* UNSUPPORTED_BROWSER */);\r\n }\r\n if (self && 'ServiceWorkerGlobalScope' in self) {\r\n // Running in ServiceWorker context\r\n return new SwController(firebaseDependencies);\r\n }\r\n else {\r\n // Assume we are in the window context.\r\n return new WindowController(firebaseDependencies);\r\n }\r\n}\r\nvar NAMESPACE_EXPORTS = {\r\n isSupported: isSupported\r\n};\r\nfirebase.INTERNAL.registerComponent(new Component(MESSAGING_NAME, factoryMethod, \"PUBLIC\" /* PUBLIC */).setServiceProps(NAMESPACE_EXPORTS));\r\nfunction isSupported() {\r\n if (self && 'ServiceWorkerGlobalScope' in self) {\r\n // Running in ServiceWorker context\r\n return isSWControllerSupported();\r\n }\r\n else {\r\n // Assume we are in the window context.\r\n return isWindowControllerSupported();\r\n }\r\n}\r\n/**\r\n * Checks to see if the required APIs exist.\r\n */\r\nfunction isWindowControllerSupported() {\r\n return ('indexedDB' in window &&\r\n indexedDB !== null &&\r\n navigator.cookieEnabled &&\r\n 'serviceWorker' in navigator &&\r\n 'PushManager' in window &&\r\n 'Notification' in window &&\r\n 'fetch' in window &&\r\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\r\n PushSubscription.prototype.hasOwnProperty('getKey'));\r\n}\r\n/**\r\n * Checks to see if the required APIs exist within SW Context.\r\n */\r\nfunction isSWControllerSupported() {\r\n return ('indexedDB' in self &&\r\n indexedDB !== null &&\r\n 'PushManager' in self &&\r\n 'Notification' in self &&\r\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\r\n PushSubscription.prototype.hasOwnProperty('getKey'));\r\n}\n//# sourceMappingURL=index.esm.js.map\n","import { __assign, __extends } from 'tslib';\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\r\n */\r\nvar CONSTANTS = {\r\n /**\r\n * @define {boolean} Whether this is the client Node.js SDK.\r\n */\r\n NODE_CLIENT: false,\r\n /**\r\n * @define {boolean} Whether this is the Admin Node.js SDK.\r\n */\r\n NODE_ADMIN: false,\r\n /**\r\n * Firebase SDK Version\r\n */\r\n SDK_VERSION: '${JSCORE_VERSION}'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws an error if the provided assertion is falsy\r\n */\r\nvar assert = function (assertion, message) {\r\n if (!assertion) {\r\n throw assertionError(message);\r\n }\r\n};\r\n/**\r\n * Returns an Error object suitable for throwing.\r\n */\r\nvar assertionError = function (message) {\r\n return new Error('Firebase Database (' +\r\n CONSTANTS.SDK_VERSION +\r\n ') INTERNAL ASSERT FAILED: ' +\r\n message);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar stringToByteArray$1 = function (str) {\r\n // TODO(user): Use native implementations if/when available\r\n var out = [];\r\n var p = 0;\r\n for (var i = 0; i < str.length; i++) {\r\n var c = str.charCodeAt(i);\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if ((c & 0xfc00) === 0xd800 &&\r\n i + 1 < str.length &&\r\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\r\n // Surrogate Pair\r\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Turns an array of numbers into the string given by the concatenation of the\r\n * characters to which the numbers correspond.\r\n * @param bytes Array of numbers representing characters.\r\n * @return Stringification of the array.\r\n */\r\nvar byteArrayToString = function (bytes) {\r\n // TODO(user): Use native implementations if/when available\r\n var out = [];\r\n var pos = 0, c = 0;\r\n while (pos < bytes.length) {\r\n var c1 = bytes[pos++];\r\n if (c1 < 128) {\r\n out[c++] = String.fromCharCode(c1);\r\n }\r\n else if (c1 > 191 && c1 < 224) {\r\n var c2 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\r\n }\r\n else if (c1 > 239 && c1 < 365) {\r\n // Surrogate Pair\r\n var c2 = bytes[pos++];\r\n var c3 = bytes[pos++];\r\n var c4 = bytes[pos++];\r\n var u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\r\n 0x10000;\r\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\r\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\r\n }\r\n else {\r\n var c2 = bytes[pos++];\r\n var c3 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\r\n }\r\n }\r\n return out.join('');\r\n};\r\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\r\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\r\n// Static lookup maps, lazily populated by init_()\r\nvar base64 = {\r\n /**\r\n * Maps bytes to characters.\r\n */\r\n byteToCharMap_: null,\r\n /**\r\n * Maps characters to bytes.\r\n */\r\n charToByteMap_: null,\r\n /**\r\n * Maps bytes to websafe characters.\r\n * @private\r\n */\r\n byteToCharMapWebSafe_: null,\r\n /**\r\n * Maps websafe characters to bytes.\r\n * @private\r\n */\r\n charToByteMapWebSafe_: null,\r\n /**\r\n * Our default alphabet, shared between\r\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\r\n */\r\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\r\n /**\r\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\r\n */\r\n get ENCODED_VALS() {\r\n return this.ENCODED_VALS_BASE + '+/=';\r\n },\r\n /**\r\n * Our websafe alphabet.\r\n */\r\n get ENCODED_VALS_WEBSAFE() {\r\n return this.ENCODED_VALS_BASE + '-_.';\r\n },\r\n /**\r\n * Whether this browser supports the atob and btoa functions. This extension\r\n * started at Mozilla but is now implemented by many browsers. We use the\r\n * ASSUME_* variables to avoid pulling in the full useragent detection library\r\n * but still allowing the standard per-browser compilations.\r\n *\r\n */\r\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\r\n /**\r\n * Base64-encode an array of bytes.\r\n *\r\n * @param input An array of bytes (numbers with\r\n * value in [0, 255]) to encode.\r\n * @param webSafe Boolean indicating we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeByteArray: function (input, webSafe) {\r\n if (!Array.isArray(input)) {\r\n throw Error('encodeByteArray takes an array as a parameter');\r\n }\r\n this.init_();\r\n var byteToCharMap = webSafe\r\n ? this.byteToCharMapWebSafe_\r\n : this.byteToCharMap_;\r\n var output = [];\r\n for (var i = 0; i < input.length; i += 3) {\r\n var byte1 = input[i];\r\n var haveByte2 = i + 1 < input.length;\r\n var byte2 = haveByte2 ? input[i + 1] : 0;\r\n var haveByte3 = i + 2 < input.length;\r\n var byte3 = haveByte3 ? input[i + 2] : 0;\r\n var outByte1 = byte1 >> 2;\r\n var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\r\n var outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\r\n var outByte4 = byte3 & 0x3f;\r\n if (!haveByte3) {\r\n outByte4 = 64;\r\n if (!haveByte2) {\r\n outByte3 = 64;\r\n }\r\n }\r\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\r\n }\r\n return output.join('');\r\n },\r\n /**\r\n * Base64-encode a string.\r\n *\r\n * @param input A string to encode.\r\n * @param webSafe If true, we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeString: function (input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return btoa(input);\r\n }\r\n return this.encodeByteArray(stringToByteArray$1(input), webSafe);\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * @param input to decode.\r\n * @param webSafe True if we should use the\r\n * alternative alphabet.\r\n * @return string representing the decoded value.\r\n */\r\n decodeString: function (input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return atob(input);\r\n }\r\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * In base-64 decoding, groups of four characters are converted into three\r\n * bytes. If the encoder did not apply padding, the input length may not\r\n * be a multiple of 4.\r\n *\r\n * In this case, the last group will have fewer than 4 characters, and\r\n * padding will be inferred. If the group has one or two characters, it decodes\r\n * to one byte. If the group has three characters, it decodes to two bytes.\r\n *\r\n * @param input Input to decode.\r\n * @param webSafe True if we should use the web-safe alphabet.\r\n * @return bytes representing the decoded value.\r\n */\r\n decodeStringToByteArray: function (input, webSafe) {\r\n this.init_();\r\n var charToByteMap = webSafe\r\n ? this.charToByteMapWebSafe_\r\n : this.charToByteMap_;\r\n var output = [];\r\n for (var i = 0; i < input.length;) {\r\n var byte1 = charToByteMap[input.charAt(i++)];\r\n var haveByte2 = i < input.length;\r\n var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\r\n ++i;\r\n var haveByte3 = i < input.length;\r\n var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n var haveByte4 = i < input.length;\r\n var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\r\n throw Error();\r\n }\r\n var outByte1 = (byte1 << 2) | (byte2 >> 4);\r\n output.push(outByte1);\r\n if (byte3 !== 64) {\r\n var outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\r\n output.push(outByte2);\r\n if (byte4 !== 64) {\r\n var outByte3 = ((byte3 << 6) & 0xc0) | byte4;\r\n output.push(outByte3);\r\n }\r\n }\r\n }\r\n return output;\r\n },\r\n /**\r\n * Lazy static initialization function. Called before\r\n * accessing any of the static map variables.\r\n * @private\r\n */\r\n init_: function () {\r\n if (!this.byteToCharMap_) {\r\n this.byteToCharMap_ = {};\r\n this.charToByteMap_ = {};\r\n this.byteToCharMapWebSafe_ = {};\r\n this.charToByteMapWebSafe_ = {};\r\n // We want quick mappings back and forth, so we precompute two maps.\r\n for (var i = 0; i < this.ENCODED_VALS.length; i++) {\r\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\r\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\r\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\r\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\r\n // Be forgiving when decoding and correctly decode both encodings.\r\n if (i >= this.ENCODED_VALS_BASE.length) {\r\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\r\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\r\n }\r\n }\r\n }\r\n }\r\n};\r\n/**\r\n * URL-safe base64 encoding\r\n */\r\nvar base64Encode = function (str) {\r\n var utf8Bytes = stringToByteArray$1(str);\r\n return base64.encodeByteArray(utf8Bytes, true);\r\n};\r\n/**\r\n * URL-safe base64 encoding (without \".\" padding in the end).\r\n * e.g. Used in JSON Web Token (JWT) parts.\r\n */\r\nvar base64urlEncodeWithoutPadding = function (str) {\r\n // Use base64url encoding and remove padding in the end (dot characters).\r\n return base64Encode(str).replace(/\\./g, '');\r\n};\r\n/**\r\n * URL-safe base64 decoding\r\n *\r\n * NOTE: DO NOT use the global atob() function - it does NOT support the\r\n * base64Url variant encoding.\r\n *\r\n * @param str To be decoded\r\n * @return Decoded result, if possible\r\n */\r\nvar base64Decode = function (str) {\r\n try {\r\n return base64.decodeString(str, true);\r\n }\r\n catch (e) {\r\n console.error('base64Decode failed: ', e);\r\n }\r\n return null;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\r\nfunction deepCopy(value) {\r\n return deepExtend(undefined, value);\r\n}\r\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays). Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n *\r\n * Note: we don't merge __proto__ to prevent prototype pollution\r\n */\r\nfunction deepExtend(target, source) {\r\n if (!(source instanceof Object)) {\r\n return source;\r\n }\r\n switch (source.constructor) {\r\n case Date:\r\n // Treat Dates like scalars; if the target date object had any child\r\n // properties - they will be lost!\r\n var dateValue = source;\r\n return new Date(dateValue.getTime());\r\n case Object:\r\n if (target === undefined) {\r\n target = {};\r\n }\r\n break;\r\n case Array:\r\n // Always copy the array source and overwrite the target.\r\n target = [];\r\n break;\r\n default:\r\n // Not a plain Object - treat it as a scalar.\r\n return source;\r\n }\r\n for (var prop in source) {\r\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\r\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\r\n continue;\r\n }\r\n target[prop] = deepExtend(target[prop], source[prop]);\r\n }\r\n return target;\r\n}\r\nfunction isValidKey(key) {\r\n return key !== '__proto__';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar Deferred = /** @class */ (function () {\r\n function Deferred() {\r\n var _this = this;\r\n this.reject = function () { };\r\n this.resolve = function () { };\r\n this.promise = new Promise(function (resolve, reject) {\r\n _this.resolve = resolve;\r\n _this.reject = reject;\r\n });\r\n }\r\n /**\r\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n */\r\n Deferred.prototype.wrapCallback = function (callback) {\r\n var _this = this;\r\n return function (error, value) {\r\n if (error) {\r\n _this.reject(error);\r\n }\r\n else {\r\n _this.resolve(value);\r\n }\r\n if (typeof callback === 'function') {\r\n // Attaching noop handler just in case developer wasn't expecting\r\n // promises\r\n _this.promise.catch(function () { });\r\n // Some of our callbacks don't expect a value and our own tests\r\n // assert that the parameter length is 1\r\n if (callback.length === 1) {\r\n callback(error);\r\n }\r\n else {\r\n callback(error, value);\r\n }\r\n }\r\n };\r\n };\r\n return Deferred;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createMockUserToken(token, projectId) {\r\n if (token.uid) {\r\n throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\r\n }\r\n // Unsecured JWTs use \"none\" as the algorithm.\r\n var header = {\r\n alg: 'none',\r\n type: 'JWT'\r\n };\r\n var project = projectId || 'demo-project';\r\n var iat = token.iat || 0;\r\n var sub = token.sub || token.user_id;\r\n if (!sub) {\r\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\r\n }\r\n var payload = __assign({ \r\n // Set all required fields to decent defaults\r\n iss: \"https://securetoken.google.com/\" + project, aud: project, iat: iat, exp: iat + 3600, auth_time: iat, sub: sub, user_id: sub, firebase: {\r\n sign_in_provider: 'custom',\r\n identities: {}\r\n } }, token);\r\n // Unsecured JWTs use the empty string as a signature.\r\n var signature = '';\r\n return [\r\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\r\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\r\n signature\r\n ].join('.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns navigator.userAgent string or '' if it's not defined.\r\n * @return user agent string\r\n */\r\nfunction getUA() {\r\n if (typeof navigator !== 'undefined' &&\r\n typeof navigator['userAgent'] === 'string') {\r\n return navigator['userAgent'];\r\n }\r\n else {\r\n return '';\r\n }\r\n}\r\n/**\r\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\r\n *\r\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\r\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\r\n * wait for a callback.\r\n */\r\nfunction isMobileCordova() {\r\n return (typeof window !== 'undefined' &&\r\n // @ts-ignore Setting up an broadly applicable index signature for Window\r\n // just to deal with this case would probably be a bad idea.\r\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\r\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\r\n}\r\n/**\r\n * Detect Node.js.\r\n *\r\n * @return true if Node.js environment is detected.\r\n */\r\n// Node detection logic from: https://github.com/iliakan/detect-node/\r\nfunction isNode() {\r\n try {\r\n return (Object.prototype.toString.call(global.process) === '[object process]');\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Detect Browser Environment\r\n */\r\nfunction isBrowser() {\r\n return typeof self === 'object' && self.self === self;\r\n}\r\nfunction isBrowserExtension() {\r\n var runtime = typeof chrome === 'object'\r\n ? chrome.runtime\r\n : typeof browser === 'object'\r\n ? browser.runtime\r\n : undefined;\r\n return typeof runtime === 'object' && runtime.id !== undefined;\r\n}\r\n/**\r\n * Detect React Native.\r\n *\r\n * @return true if ReactNative environment is detected.\r\n */\r\nfunction isReactNative() {\r\n return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\r\n}\r\n/** Detects Electron apps. */\r\nfunction isElectron() {\r\n return getUA().indexOf('Electron/') >= 0;\r\n}\r\n/** Detects Internet Explorer. */\r\nfunction isIE() {\r\n var ua = getUA();\r\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\r\n}\r\n/** Detects Universal Windows Platform apps. */\r\nfunction isUWP() {\r\n return getUA().indexOf('MSAppHost/') >= 0;\r\n}\r\n/**\r\n * Detect whether the current SDK build is the Node version.\r\n *\r\n * @return true if it's the Node SDK build.\r\n */\r\nfunction isNodeSdk() {\r\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\r\n}\r\n/** Returns true if we are running in Safari. */\r\nfunction isSafari() {\r\n return (!isNode() &&\r\n navigator.userAgent.includes('Safari') &&\r\n !navigator.userAgent.includes('Chrome'));\r\n}\r\n/**\r\n * This method checks if indexedDB is supported by current browser/service worker context\r\n * @return true if indexedDB is supported by current browser/service worker context\r\n */\r\nfunction isIndexedDBAvailable() {\r\n return 'indexedDB' in self && indexedDB != null;\r\n}\r\n/**\r\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\r\n * if errors occur during the database open operation.\r\n *\r\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\r\n * private browsing)\r\n */\r\nfunction validateIndexedDBOpenable() {\r\n return new Promise(function (resolve, reject) {\r\n try {\r\n var preExist_1 = true;\r\n var DB_CHECK_NAME_1 = 'validate-browser-context-for-indexeddb-analytics-module';\r\n var request_1 = self.indexedDB.open(DB_CHECK_NAME_1);\r\n request_1.onsuccess = function () {\r\n request_1.result.close();\r\n // delete database only when it doesn't pre-exist\r\n if (!preExist_1) {\r\n self.indexedDB.deleteDatabase(DB_CHECK_NAME_1);\r\n }\r\n resolve(true);\r\n };\r\n request_1.onupgradeneeded = function () {\r\n preExist_1 = false;\r\n };\r\n request_1.onerror = function () {\r\n var _a;\r\n reject(((_a = request_1.error) === null || _a === void 0 ? void 0 : _a.message) || '');\r\n };\r\n }\r\n catch (error) {\r\n reject(error);\r\n }\r\n });\r\n}\r\n/**\r\n *\r\n * This method checks whether cookie is enabled within current browser\r\n * @return true if cookie is enabled within current browser\r\n */\r\nfunction areCookiesEnabled() {\r\n if (!navigator || !navigator.cookieEnabled) {\r\n return false;\r\n }\r\n return true;\r\n}\r\n/**\r\n * Polyfill for `globalThis` object.\r\n * @returns the `globalThis` object for the given environment.\r\n */\r\nfunction getGlobal() {\r\n if (typeof self !== 'undefined') {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined') {\r\n return window;\r\n }\r\n if (typeof global !== 'undefined') {\r\n return global;\r\n }\r\n throw new Error('Unable to locate global object.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar ERROR_NAME = 'FirebaseError';\r\n// Based on code from:\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\r\nvar FirebaseError = /** @class */ (function (_super) {\r\n __extends(FirebaseError, _super);\r\n function FirebaseError(code, message, customData) {\r\n var _this = _super.call(this, message) || this;\r\n _this.code = code;\r\n _this.customData = customData;\r\n _this.name = ERROR_NAME;\r\n // Fix For ES5\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(_this, FirebaseError.prototype);\r\n // Maintains proper stack trace for where our error was thrown.\r\n // Only available on V8.\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(_this, ErrorFactory.prototype.create);\r\n }\r\n return _this;\r\n }\r\n return FirebaseError;\r\n}(Error));\r\nvar ErrorFactory = /** @class */ (function () {\r\n function ErrorFactory(service, serviceName, errors) {\r\n this.service = service;\r\n this.serviceName = serviceName;\r\n this.errors = errors;\r\n }\r\n ErrorFactory.prototype.create = function (code) {\r\n var data = [];\r\n for (var _i = 1; _i < arguments.length; _i++) {\r\n data[_i - 1] = arguments[_i];\r\n }\r\n var customData = data[0] || {};\r\n var fullCode = this.service + \"/\" + code;\r\n var template = this.errors[code];\r\n var message = template ? replaceTemplate(template, customData) : 'Error';\r\n // Service Name: Error message (service/code).\r\n var fullMessage = this.serviceName + \": \" + message + \" (\" + fullCode + \").\";\r\n var error = new FirebaseError(fullCode, fullMessage, customData);\r\n return error;\r\n };\r\n return ErrorFactory;\r\n}());\r\nfunction replaceTemplate(template, data) {\r\n return template.replace(PATTERN, function (_, key) {\r\n var value = data[key];\r\n return value != null ? String(value) : \"<\" + key + \"?>\";\r\n });\r\n}\r\nvar PATTERN = /\\{\\$([^}]+)}/g;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n return JSON.stringify(data);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nvar decode = function (token) {\r\n var header = {}, claims = {}, data = {}, signature = '';\r\n try {\r\n var parts = token.split('.');\r\n header = jsonEval(base64Decode(parts[0]) || '');\r\n claims = jsonEval(base64Decode(parts[1]) || '');\r\n signature = parts[2];\r\n data = claims['d'] || {};\r\n delete claims['d'];\r\n }\r\n catch (e) { }\r\n return {\r\n header: header,\r\n claims: claims,\r\n data: data,\r\n signature: signature\r\n };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nvar isValidTimestamp = function (token) {\r\n var claims = decode(token).claims;\r\n var now = Math.floor(new Date().getTime() / 1000);\r\n var validSince = 0, validUntil = 0;\r\n if (typeof claims === 'object') {\r\n if (claims.hasOwnProperty('nbf')) {\r\n validSince = claims['nbf'];\r\n }\r\n else if (claims.hasOwnProperty('iat')) {\r\n validSince = claims['iat'];\r\n }\r\n if (claims.hasOwnProperty('exp')) {\r\n validUntil = claims['exp'];\r\n }\r\n else {\r\n // token will expire after 24h by default\r\n validUntil = validSince + 86400;\r\n }\r\n }\r\n return (!!now &&\r\n !!validSince &&\r\n !!validUntil &&\r\n now >= validSince &&\r\n now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nvar issuedAtTime = function (token) {\r\n var claims = decode(token).claims;\r\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n return claims['iat'];\r\n }\r\n return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nvar isValidFormat = function (token) {\r\n var decoded = decode(token), claims = decoded.claims;\r\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nvar isAdmin = function (token) {\r\n var claims = decode(token).claims;\r\n return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction contains(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction safeGet(obj, key) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return obj[key];\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\nfunction isEmpty(obj) {\r\n for (var key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction map(obj, fn, contextObj) {\r\n var res = {};\r\n for (var key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n res[key] = fn.call(contextObj, obj[key], key, obj);\r\n }\r\n }\r\n return res;\r\n}\r\n/**\r\n * Deep equal two objects. Support Arrays and Objects.\r\n */\r\nfunction deepEqual(a, b) {\r\n if (a === b) {\r\n return true;\r\n }\r\n var aKeys = Object.keys(a);\r\n var bKeys = Object.keys(b);\r\n for (var _i = 0, aKeys_1 = aKeys; _i < aKeys_1.length; _i++) {\r\n var k = aKeys_1[_i];\r\n if (!bKeys.includes(k)) {\r\n return false;\r\n }\r\n var aProp = a[k];\r\n var bProp = b[k];\r\n if (isObject(aProp) && isObject(bProp)) {\r\n if (!deepEqual(aProp, bProp)) {\r\n return false;\r\n }\r\n }\r\n else if (aProp !== bProp) {\r\n return false;\r\n }\r\n }\r\n for (var _a = 0, bKeys_1 = bKeys; _a < bKeys_1.length; _a++) {\r\n var k = bKeys_1[_a];\r\n if (!aKeys.includes(k)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isObject(thing) {\r\n return thing !== null && typeof thing === 'object';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\r\n * params object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n */\r\nfunction querystring(querystringParams) {\r\n var params = [];\r\n var _loop_1 = function (key, value) {\r\n if (Array.isArray(value)) {\r\n value.forEach(function (arrayVal) {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n });\r\n }\r\n else {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n }\r\n };\r\n for (var _i = 0, _a = Object.entries(querystringParams); _i < _a.length; _i++) {\r\n var _b = _a[_i], key = _b[0], value = _b[1];\r\n _loop_1(key, value);\r\n }\r\n return params.length ? '&' + params.join('&') : '';\r\n}\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\r\n * (e.g. {arg: 'val', arg2: 'val2'})\r\n */\r\nfunction querystringDecode(querystring) {\r\n var obj = {};\r\n var tokens = querystring.replace(/^\\?/, '').split('&');\r\n tokens.forEach(function (token) {\r\n if (token) {\r\n var _a = token.split('='), key = _a[0], value = _a[1];\r\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\r\n }\r\n });\r\n return obj;\r\n}\r\n/**\r\n * Extract the query string part of a URL, including the leading question mark (if present).\r\n */\r\nfunction extractQuerystring(url) {\r\n var queryStart = url.indexOf('?');\r\n if (!queryStart) {\r\n return '';\r\n }\r\n var fragmentStart = url.indexOf('#', queryStart);\r\n return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\nvar Sha1 = /** @class */ (function () {\r\n function Sha1() {\r\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @private\r\n */\r\n this.chain_ = [];\r\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @private\r\n */\r\n this.buf_ = [];\r\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @private\r\n */\r\n this.W_ = [];\r\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @private\r\n */\r\n this.pad_ = [];\r\n /**\r\n * @private {number}\r\n */\r\n this.inbuf_ = 0;\r\n /**\r\n * @private {number}\r\n */\r\n this.total_ = 0;\r\n this.blockSize = 512 / 8;\r\n this.pad_[0] = 128;\r\n for (var i = 1; i < this.blockSize; ++i) {\r\n this.pad_[i] = 0;\r\n }\r\n this.reset();\r\n }\r\n Sha1.prototype.reset = function () {\r\n this.chain_[0] = 0x67452301;\r\n this.chain_[1] = 0xefcdab89;\r\n this.chain_[2] = 0x98badcfe;\r\n this.chain_[3] = 0x10325476;\r\n this.chain_[4] = 0xc3d2e1f0;\r\n this.inbuf_ = 0;\r\n this.total_ = 0;\r\n };\r\n /**\r\n * Internal compress helper function.\r\n * @param buf Block to compress.\r\n * @param offset Offset of the block in the buffer.\r\n * @private\r\n */\r\n Sha1.prototype.compress_ = function (buf, offset) {\r\n if (!offset) {\r\n offset = 0;\r\n }\r\n var W = this.W_;\r\n // get 16 big endian words\r\n if (typeof buf === 'string') {\r\n for (var i = 0; i < 16; i++) {\r\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n // have a bug that turns the post-increment ++ operator into pre-increment\r\n // during JIT compilation. We have code that depends heavily on SHA-1 for\r\n // correctness and which is affected by this bug, so I've removed all uses\r\n // of post-increment ++ in which the result value is used. We can revert\r\n // this change once the Safari bug\r\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n // most clients have been updated.\r\n W[i] =\r\n (buf.charCodeAt(offset) << 24) |\r\n (buf.charCodeAt(offset + 1) << 16) |\r\n (buf.charCodeAt(offset + 2) << 8) |\r\n buf.charCodeAt(offset + 3);\r\n offset += 4;\r\n }\r\n }\r\n else {\r\n for (var i = 0; i < 16; i++) {\r\n W[i] =\r\n (buf[offset] << 24) |\r\n (buf[offset + 1] << 16) |\r\n (buf[offset + 2] << 8) |\r\n buf[offset + 3];\r\n offset += 4;\r\n }\r\n }\r\n // expand to 80 words\r\n for (var i = 16; i < 80; i++) {\r\n var t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n }\r\n var a = this.chain_[0];\r\n var b = this.chain_[1];\r\n var c = this.chain_[2];\r\n var d = this.chain_[3];\r\n var e = this.chain_[4];\r\n var f, k;\r\n // TODO(user): Try to unroll this loop to speed up the computation.\r\n for (var i = 0; i < 80; i++) {\r\n if (i < 40) {\r\n if (i < 20) {\r\n f = d ^ (b & (c ^ d));\r\n k = 0x5a827999;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0x6ed9eba1;\r\n }\r\n }\r\n else {\r\n if (i < 60) {\r\n f = (b & c) | (d & (b | c));\r\n k = 0x8f1bbcdc;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0xca62c1d6;\r\n }\r\n }\r\n var t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n e = d;\r\n d = c;\r\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n b = a;\r\n a = t;\r\n }\r\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n };\r\n Sha1.prototype.update = function (bytes, length) {\r\n // TODO(johnlenz): tighten the function signature and remove this check\r\n if (bytes == null) {\r\n return;\r\n }\r\n if (length === undefined) {\r\n length = bytes.length;\r\n }\r\n var lengthMinusBlock = length - this.blockSize;\r\n var n = 0;\r\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n var buf = this.buf_;\r\n var inbuf = this.inbuf_;\r\n // The outer while loop should execute at most twice.\r\n while (n < length) {\r\n // When we have no data in the block to top up, we can directly process the\r\n // input buffer (assuming it contains sufficient data). This gives ~25%\r\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n // the data is provided in large chunks (or in multiples of 64 bytes).\r\n if (inbuf === 0) {\r\n while (n <= lengthMinusBlock) {\r\n this.compress_(bytes, n);\r\n n += this.blockSize;\r\n }\r\n }\r\n if (typeof bytes === 'string') {\r\n while (n < length) {\r\n buf[inbuf] = bytes.charCodeAt(n);\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n while (n < length) {\r\n buf[inbuf] = bytes[n];\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n this.inbuf_ = inbuf;\r\n this.total_ += length;\r\n };\r\n /** @override */\r\n Sha1.prototype.digest = function () {\r\n var digest = [];\r\n var totalBits = this.total_ * 8;\r\n // Add pad 0x80 0x00*.\r\n if (this.inbuf_ < 56) {\r\n this.update(this.pad_, 56 - this.inbuf_);\r\n }\r\n else {\r\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n }\r\n // Add # bits.\r\n for (var i = this.blockSize - 1; i >= 56; i--) {\r\n this.buf_[i] = totalBits & 255;\r\n totalBits /= 256; // Don't use bit-shifting here!\r\n }\r\n this.compress_(this.buf_);\r\n var n = 0;\r\n for (var i = 0; i < 5; i++) {\r\n for (var j = 24; j >= 0; j -= 8) {\r\n digest[n] = (this.chain_[i] >> j) & 255;\r\n ++n;\r\n }\r\n }\r\n return digest;\r\n };\r\n return Sha1;\r\n}());\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n var proxy = new ObserverProxy(executor, onNoObservers);\r\n return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nvar ObserverProxy = /** @class */ (function () {\r\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\n function ObserverProxy(executor, onNoObservers) {\r\n var _this = this;\r\n this.observers = [];\r\n this.unsubscribes = [];\r\n this.observerCount = 0;\r\n // Micro-task scheduling by calling task.then().\r\n this.task = Promise.resolve();\r\n this.finalized = false;\r\n this.onNoObservers = onNoObservers;\r\n // Call the executor asynchronously so subscribers that are called\r\n // synchronously after the creation of the subscribe function\r\n // can still receive the very first value generated in the executor.\r\n this.task\r\n .then(function () {\r\n executor(_this);\r\n })\r\n .catch(function (e) {\r\n _this.error(e);\r\n });\r\n }\r\n ObserverProxy.prototype.next = function (value) {\r\n this.forEachObserver(function (observer) {\r\n observer.next(value);\r\n });\r\n };\r\n ObserverProxy.prototype.error = function (error) {\r\n this.forEachObserver(function (observer) {\r\n observer.error(error);\r\n });\r\n this.close(error);\r\n };\r\n ObserverProxy.prototype.complete = function () {\r\n this.forEachObserver(function (observer) {\r\n observer.complete();\r\n });\r\n this.close();\r\n };\r\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\r\n ObserverProxy.prototype.subscribe = function (nextOrObserver, error, complete) {\r\n var _this = this;\r\n var observer;\r\n if (nextOrObserver === undefined &&\r\n error === undefined &&\r\n complete === undefined) {\r\n throw new Error('Missing Observer.');\r\n }\r\n // Assemble an Observer object when passed as callback functions.\r\n if (implementsAnyMethods(nextOrObserver, [\r\n 'next',\r\n 'error',\r\n 'complete'\r\n ])) {\r\n observer = nextOrObserver;\r\n }\r\n else {\r\n observer = {\r\n next: nextOrObserver,\r\n error: error,\r\n complete: complete\r\n };\r\n }\r\n if (observer.next === undefined) {\r\n observer.next = noop;\r\n }\r\n if (observer.error === undefined) {\r\n observer.error = noop;\r\n }\r\n if (observer.complete === undefined) {\r\n observer.complete = noop;\r\n }\r\n var unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n // Attempt to subscribe to a terminated Observable - we\r\n // just respond to the Observer with the final error or complete\r\n // event.\r\n if (this.finalized) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(function () {\r\n try {\r\n if (_this.finalError) {\r\n observer.error(_this.finalError);\r\n }\r\n else {\r\n observer.complete();\r\n }\r\n }\r\n catch (e) {\r\n // nothing\r\n }\r\n return;\r\n });\r\n }\r\n this.observers.push(observer);\r\n return unsub;\r\n };\r\n // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n // any unsubscribed Observer.\r\n ObserverProxy.prototype.unsubscribeOne = function (i) {\r\n if (this.observers === undefined || this.observers[i] === undefined) {\r\n return;\r\n }\r\n delete this.observers[i];\r\n this.observerCount -= 1;\r\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n this.onNoObservers(this);\r\n }\r\n };\r\n ObserverProxy.prototype.forEachObserver = function (fn) {\r\n if (this.finalized) {\r\n // Already closed by previous event....just eat the additional values.\r\n return;\r\n }\r\n // Since sendOne calls asynchronously - there is no chance that\r\n // this.observers will become undefined.\r\n for (var i = 0; i < this.observers.length; i++) {\r\n this.sendOne(i, fn);\r\n }\r\n };\r\n // Call the Observer via one of it's callback function. We are careful to\r\n // confirm that the observe has not been unsubscribed since this asynchronous\r\n // function had been queued.\r\n ObserverProxy.prototype.sendOne = function (i, fn) {\r\n var _this = this;\r\n // Execute the callback asynchronously\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(function () {\r\n if (_this.observers !== undefined && _this.observers[i] !== undefined) {\r\n try {\r\n fn(_this.observers[i]);\r\n }\r\n catch (e) {\r\n // Ignore exceptions raised in Observers or missing methods of an\r\n // Observer.\r\n // Log error to console. b/31404806\r\n if (typeof console !== 'undefined' && console.error) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n });\r\n };\r\n ObserverProxy.prototype.close = function (err) {\r\n var _this = this;\r\n if (this.finalized) {\r\n return;\r\n }\r\n this.finalized = true;\r\n if (err !== undefined) {\r\n this.finalError = err;\r\n }\r\n // Proxy is no longer needed - garbage collect references\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(function () {\r\n _this.observers = undefined;\r\n _this.onNoObservers = undefined;\r\n });\r\n };\r\n return ObserverProxy;\r\n}());\r\n/** Turn synchronous function into one called asynchronously. */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(fn, onError) {\r\n return function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n Promise.resolve(true)\r\n .then(function () {\r\n fn.apply(void 0, args);\r\n })\r\n .catch(function (error) {\r\n if (onError) {\r\n onError(error);\r\n }\r\n });\r\n };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\r\n var method = methods_1[_i];\r\n if (method in obj && typeof obj[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction noop() {\r\n // do nothing\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param fnName The function name\r\n * @param minCount The minimum number of arguments to allow for the function call\r\n * @param maxCount The maximum number of argument to allow for the function call\r\n * @param argCount The actual number of arguments provided.\r\n */\r\nvar validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n var argError;\r\n if (argCount < minCount) {\r\n argError = 'at least ' + minCount;\r\n }\r\n else if (argCount > maxCount) {\r\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n }\r\n if (argError) {\r\n var error = fnName +\r\n ' failed: Was called with ' +\r\n argCount +\r\n (argCount === 1 ? ' argument.' : ' arguments.') +\r\n ' Expects ' +\r\n argError +\r\n '.';\r\n throw new Error(error);\r\n }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param fnName The function name\r\n * @param argName The name of the argument\r\n * @return The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argName) {\r\n return fnName + \" failed: \" + argName + \" argument \";\r\n}\r\n/**\r\n * @param fnName\r\n * @param argumentNumber\r\n * @param namespace\r\n * @param optional\r\n */\r\nfunction validateNamespace(fnName, namespace, optional) {\r\n if (optional && !namespace) {\r\n return;\r\n }\r\n if (typeof namespace !== 'string') {\r\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\r\n }\r\n}\r\nfunction validateCallback(fnName, argumentName, \r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\ncallback, optional) {\r\n if (optional && !callback) {\r\n return;\r\n }\r\n if (typeof callback !== 'function') {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\r\n }\r\n}\r\nfunction validateContextObject(fnName, argumentName, context, optional) {\r\n if (optional && !context) {\r\n return;\r\n }\r\n if (typeof context !== 'object' || context === null) {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nvar stringToByteArray = function (str) {\r\n var out = [];\r\n var p = 0;\r\n for (var i = 0; i < str.length; i++) {\r\n var c = str.charCodeAt(i);\r\n // Is this the lead surrogate in a surrogate pair?\r\n if (c >= 0xd800 && c <= 0xdbff) {\r\n var high = c - 0xd800; // the high 10 bits.\r\n i++;\r\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n var low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n c = 0x10000 + (high << 10) + low;\r\n }\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if (c < 65536) {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nvar stringLength = function (str) {\r\n var p = 0;\r\n for (var i = 0; i < str.length; i++) {\r\n var c = str.charCodeAt(i);\r\n if (c < 128) {\r\n p++;\r\n }\r\n else if (c < 2048) {\r\n p += 2;\r\n }\r\n else if (c >= 0xd800 && c <= 0xdbff) {\r\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\r\n p += 4;\r\n i++; // skip trail surrogate.\r\n }\r\n else {\r\n p += 3;\r\n }\r\n }\r\n return p;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The amount of milliseconds to exponentially increase.\r\n */\r\nvar DEFAULT_INTERVAL_MILLIS = 1000;\r\n/**\r\n * The factor to backoff by.\r\n * Should be a number greater than 1.\r\n */\r\nvar DEFAULT_BACKOFF_FACTOR = 2;\r\n/**\r\n * The maximum milliseconds to increase to.\r\n *\r\n *

Visible for testing\r\n */\r\nvar MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n *

Visible for testing\r\n */\r\nvar RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis, backoffFactor) {\r\n if (intervalMillis === void 0) { intervalMillis = DEFAULT_INTERVAL_MILLIS; }\r\n if (backoffFactor === void 0) { backoffFactor = DEFAULT_BACKOFF_FACTOR; }\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n var currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n var randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return \"\" + i;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n var cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n var dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm.js.map\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n\r\nfunction __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar _a;\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nvar instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\nvar levelStringToEnum = {\r\n 'debug': LogLevel.DEBUG,\r\n 'verbose': LogLevel.VERBOSE,\r\n 'info': LogLevel.INFO,\r\n 'warn': LogLevel.WARN,\r\n 'error': LogLevel.ERROR,\r\n 'silent': LogLevel.SILENT\r\n};\r\n/**\r\n * The default log level\r\n */\r\nvar defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\nvar ConsoleMethod = (_a = {},\r\n _a[LogLevel.DEBUG] = 'log',\r\n _a[LogLevel.VERBOSE] = 'log',\r\n _a[LogLevel.INFO] = 'info',\r\n _a[LogLevel.WARN] = 'warn',\r\n _a[LogLevel.ERROR] = 'error',\r\n _a);\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nvar defaultLogHandler = function (instance, logType) {\r\n var args = [];\r\n for (var _i = 2; _i < arguments.length; _i++) {\r\n args[_i - 2] = arguments[_i];\r\n }\r\n if (logType < instance.logLevel) {\r\n return;\r\n }\r\n var now = new Date().toISOString();\r\n var method = ConsoleMethod[logType];\r\n if (method) {\r\n console[method].apply(console, __spreadArrays([\"[\" + now + \"] \" + instance.name + \":\"], args));\r\n }\r\n else {\r\n throw new Error(\"Attempted to log a message with an invalid logType (value: \" + logType + \")\");\r\n }\r\n};\r\nvar Logger = /** @class */ (function () {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n function Logger(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The main (internal) log handler for the Logger instance.\r\n * Can be set to a new function in internal package code but not by user.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * The optional, additional, user-defined log handler for the Logger instance.\r\n */\r\n this._userLogHandler = null;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n Object.defineProperty(Logger.prototype, \"logLevel\", {\r\n get: function () {\r\n return this._logLevel;\r\n },\r\n set: function (val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError(\"Invalid value \\\"\" + val + \"\\\" assigned to `logLevel`\");\r\n }\r\n this._logLevel = val;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n // Workaround for setter/getter having to be the same type.\r\n Logger.prototype.setLogLevel = function (val) {\r\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\r\n };\r\n Object.defineProperty(Logger.prototype, \"logHandler\", {\r\n get: function () {\r\n return this._logHandler;\r\n },\r\n set: function (val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(Logger.prototype, \"userLogHandler\", {\r\n get: function () {\r\n return this._userLogHandler;\r\n },\r\n set: function (val) {\r\n this._userLogHandler = val;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n Logger.prototype.debug = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._userLogHandler && this._userLogHandler.apply(this, __spreadArrays([this, LogLevel.DEBUG], args));\r\n this._logHandler.apply(this, __spreadArrays([this, LogLevel.DEBUG], args));\r\n };\r\n Logger.prototype.log = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._userLogHandler && this._userLogHandler.apply(this, __spreadArrays([this, LogLevel.VERBOSE], args));\r\n this._logHandler.apply(this, __spreadArrays([this, LogLevel.VERBOSE], args));\r\n };\r\n Logger.prototype.info = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._userLogHandler && this._userLogHandler.apply(this, __spreadArrays([this, LogLevel.INFO], args));\r\n this._logHandler.apply(this, __spreadArrays([this, LogLevel.INFO], args));\r\n };\r\n Logger.prototype.warn = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._userLogHandler && this._userLogHandler.apply(this, __spreadArrays([this, LogLevel.WARN], args));\r\n this._logHandler.apply(this, __spreadArrays([this, LogLevel.WARN], args));\r\n };\r\n Logger.prototype.error = function () {\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n this._userLogHandler && this._userLogHandler.apply(this, __spreadArrays([this, LogLevel.ERROR], args));\r\n this._logHandler.apply(this, __spreadArrays([this, LogLevel.ERROR], args));\r\n };\r\n return Logger;\r\n}());\r\nfunction setLogLevel(level) {\r\n instances.forEach(function (inst) {\r\n inst.setLogLevel(level);\r\n });\r\n}\r\nfunction setUserLogHandler(logCallback, options) {\r\n var _loop_1 = function (instance) {\r\n var customLogLevel = null;\r\n if (options && options.level) {\r\n customLogLevel = levelStringToEnum[options.level];\r\n }\r\n if (logCallback === null) {\r\n instance.userLogHandler = null;\r\n }\r\n else {\r\n instance.userLogHandler = function (instance, level) {\r\n var args = [];\r\n for (var _i = 2; _i < arguments.length; _i++) {\r\n args[_i - 2] = arguments[_i];\r\n }\r\n var message = args\r\n .map(function (arg) {\r\n if (arg == null) {\r\n return null;\r\n }\r\n else if (typeof arg === 'string') {\r\n return arg;\r\n }\r\n else if (typeof arg === 'number' || typeof arg === 'boolean') {\r\n return arg.toString();\r\n }\r\n else if (arg instanceof Error) {\r\n return arg.message;\r\n }\r\n else {\r\n try {\r\n return JSON.stringify(arg);\r\n }\r\n catch (ignored) {\r\n return null;\r\n }\r\n }\r\n })\r\n .filter(function (arg) { return arg; })\r\n .join(' ');\r\n if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\r\n logCallback({\r\n level: LogLevel[level].toLowerCase(),\r\n message: message,\r\n args: args,\r\n type: instance.name\r\n });\r\n }\r\n };\r\n }\r\n };\r\n for (var _i = 0, instances_1 = instances; _i < instances_1.length; _i++) {\r\n var instance = instances_1[_i];\r\n _loop_1(instance);\r\n }\r\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm.js.map\n","import { __values, __read, __awaiter, __generator, __spreadArray } from 'tslib';\nimport { Deferred } from '@firebase/util';\n\n/**\r\n * Component for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nvar Component = /** @class */ (function () {\r\n /**\r\n *\r\n * @param name The public service name, e.g. app, auth, firestore, database\r\n * @param instanceFactory Service factory responsible for creating the public interface\r\n * @param type whether the service provided by the component is public or private\r\n */\r\n function Component(name, instanceFactory, type) {\r\n this.name = name;\r\n this.instanceFactory = instanceFactory;\r\n this.type = type;\r\n this.multipleInstances = false;\r\n /**\r\n * Properties to be added to the service namespace\r\n */\r\n this.serviceProps = {};\r\n this.instantiationMode = \"LAZY\" /* LAZY */;\r\n this.onInstanceCreated = null;\r\n }\r\n Component.prototype.setInstantiationMode = function (mode) {\r\n this.instantiationMode = mode;\r\n return this;\r\n };\r\n Component.prototype.setMultipleInstances = function (multipleInstances) {\r\n this.multipleInstances = multipleInstances;\r\n return this;\r\n };\r\n Component.prototype.setServiceProps = function (props) {\r\n this.serviceProps = props;\r\n return this;\r\n };\r\n Component.prototype.setInstanceCreatedCallback = function (callback) {\r\n this.onInstanceCreated = callback;\r\n return this;\r\n };\r\n return Component;\r\n}());\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nvar DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\r\n * NameServiceMapping[T] is an alias for the type of the instance\r\n */\r\nvar Provider = /** @class */ (function () {\r\n function Provider(name, container) {\r\n this.name = name;\r\n this.container = container;\r\n this.component = null;\r\n this.instances = new Map();\r\n this.instancesDeferred = new Map();\r\n this.instancesOptions = new Map();\r\n this.onInitCallbacks = new Map();\r\n }\r\n /**\r\n * @param identifier A provider can provide mulitple instances of a service\r\n * if this.component.multipleInstances is true.\r\n */\r\n Provider.prototype.get = function (identifier) {\r\n // if multipleInstances is not supported, use the default name\r\n var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\r\n var deferred = new Deferred();\r\n this.instancesDeferred.set(normalizedIdentifier, deferred);\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n // initialize the service if it can be auto-initialized\r\n try {\r\n var instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n if (instance) {\r\n deferred.resolve(instance);\r\n }\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception during get(), it should not cause\r\n // a fatal error. We just return the unresolved promise in this case.\r\n }\r\n }\r\n }\r\n return this.instancesDeferred.get(normalizedIdentifier).promise;\r\n };\r\n Provider.prototype.getImmediate = function (options) {\r\n var _a;\r\n // if multipleInstances is not supported, use the default name\r\n var normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\r\n var optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n try {\r\n return this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n }\r\n catch (e) {\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw e;\r\n }\r\n }\r\n }\r\n else {\r\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw Error(\"Service \" + this.name + \" is not available\");\r\n }\r\n }\r\n };\r\n Provider.prototype.getComponent = function () {\r\n return this.component;\r\n };\r\n Provider.prototype.setComponent = function (component) {\r\n var e_1, _a;\r\n if (component.name !== this.name) {\r\n throw Error(\"Mismatching Component \" + component.name + \" for Provider \" + this.name + \".\");\r\n }\r\n if (this.component) {\r\n throw Error(\"Component for \" + this.name + \" has already been provided\");\r\n }\r\n this.component = component;\r\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\r\n if (!this.shouldAutoInitialize()) {\r\n return;\r\n }\r\n // if the service is eager, initialize the default instance\r\n if (isComponentEager(component)) {\r\n try {\r\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\r\n }\r\n catch (e) {\r\n // when the instance factory for an eager Component throws an exception during the eager\r\n // initialization, it should not cause a fatal error.\r\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\r\n // a fatal error in this case?\r\n }\r\n }\r\n try {\r\n // Create service instances for the pending promises and resolve them\r\n // NOTE: if this.multipleInstances is false, only the default instance will be created\r\n // and all promises with resolve with it regardless of the identifier.\r\n for (var _b = __values(this.instancesDeferred.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {\r\n var _d = __read(_c.value, 2), instanceIdentifier = _d[0], instanceDeferred = _d[1];\r\n var normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n try {\r\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\r\n var instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n instanceDeferred.resolve(instance);\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception, it should not cause\r\n // a fatal error. We just leave the promise unresolved.\r\n }\r\n }\r\n }\r\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\r\n finally {\r\n try {\r\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\r\n }\r\n finally { if (e_1) throw e_1.error; }\r\n }\r\n };\r\n Provider.prototype.clearInstance = function (identifier) {\r\n if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }\r\n this.instancesDeferred.delete(identifier);\r\n this.instancesOptions.delete(identifier);\r\n this.instances.delete(identifier);\r\n };\r\n // app.delete() will call this method on every provider to delete the services\r\n // TODO: should we mark the provider as deleted?\r\n Provider.prototype.delete = function () {\r\n return __awaiter(this, void 0, void 0, function () {\r\n var services;\r\n return __generator(this, function (_a) {\r\n switch (_a.label) {\r\n case 0:\r\n services = Array.from(this.instances.values());\r\n return [4 /*yield*/, Promise.all(__spreadArray(__spreadArray([], __read(services\r\n .filter(function (service) { return 'INTERNAL' in service; }) // legacy services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(function (service) { return service.INTERNAL.delete(); }))), __read(services\r\n .filter(function (service) { return '_delete' in service; }) // modularized services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(function (service) { return service._delete(); }))))];\r\n case 1:\r\n _a.sent();\r\n return [2 /*return*/];\r\n }\r\n });\r\n });\r\n };\r\n Provider.prototype.isComponentSet = function () {\r\n return this.component != null;\r\n };\r\n Provider.prototype.isInitialized = function (identifier) {\r\n if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }\r\n return this.instances.has(identifier);\r\n };\r\n Provider.prototype.getOptions = function (identifier) {\r\n if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }\r\n return this.instancesOptions.get(identifier) || {};\r\n };\r\n Provider.prototype.initialize = function (opts) {\r\n var e_2, _a;\r\n if (opts === void 0) { opts = {}; }\r\n var _b = opts.options, options = _b === void 0 ? {} : _b;\r\n var normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\r\n if (this.isInitialized(normalizedIdentifier)) {\r\n throw Error(this.name + \"(\" + normalizedIdentifier + \") has already been initialized\");\r\n }\r\n if (!this.isComponentSet()) {\r\n throw Error(\"Component \" + this.name + \" has not been registered yet\");\r\n }\r\n var instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier,\r\n options: options\r\n });\r\n try {\r\n // resolve any pending promise waiting for the service instance\r\n for (var _c = __values(this.instancesDeferred.entries()), _d = _c.next(); !_d.done; _d = _c.next()) {\r\n var _e = __read(_d.value, 2), instanceIdentifier = _e[0], instanceDeferred = _e[1];\r\n var normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\r\n instanceDeferred.resolve(instance);\r\n }\r\n }\r\n }\r\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\r\n finally {\r\n try {\r\n if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\r\n }\r\n finally { if (e_2) throw e_2.error; }\r\n }\r\n return instance;\r\n };\r\n /**\r\n *\r\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\r\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\r\n *\r\n * @param identifier An optional instance identifier\r\n * @returns a function to unregister the callback\r\n */\r\n Provider.prototype.onInit = function (callback, identifier) {\r\n var _a;\r\n var normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n var existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\r\n existingCallbacks.add(callback);\r\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\r\n var existingInstance = this.instances.get(normalizedIdentifier);\r\n if (existingInstance) {\r\n callback(existingInstance, normalizedIdentifier);\r\n }\r\n return function () {\r\n existingCallbacks.delete(callback);\r\n };\r\n };\r\n /**\r\n * Invoke onInit callbacks synchronously\r\n * @param instance the service instance`\r\n */\r\n Provider.prototype.invokeOnInitCallbacks = function (instance, identifier) {\r\n var e_3, _a;\r\n var callbacks = this.onInitCallbacks.get(identifier);\r\n if (!callbacks) {\r\n return;\r\n }\r\n try {\r\n for (var callbacks_1 = __values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) {\r\n var callback = callbacks_1_1.value;\r\n try {\r\n callback(instance, identifier);\r\n }\r\n catch (_b) {\r\n // ignore errors in the onInit callback\r\n }\r\n }\r\n }\r\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\r\n finally {\r\n try {\r\n if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1);\r\n }\r\n finally { if (e_3) throw e_3.error; }\r\n }\r\n };\r\n Provider.prototype.getOrInitializeService = function (_a) {\r\n var instanceIdentifier = _a.instanceIdentifier, _b = _a.options, options = _b === void 0 ? {} : _b;\r\n var instance = this.instances.get(instanceIdentifier);\r\n if (!instance && this.component) {\r\n instance = this.component.instanceFactory(this.container, {\r\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\r\n options: options\r\n });\r\n this.instances.set(instanceIdentifier, instance);\r\n this.instancesOptions.set(instanceIdentifier, options);\r\n /**\r\n * Invoke onInit listeners.\r\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\r\n * while onInit listeners are registered by consumers of the provider.\r\n */\r\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\r\n /**\r\n * Order is important\r\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\r\n * makes `isInitialized()` return true.\r\n */\r\n if (this.component.onInstanceCreated) {\r\n try {\r\n this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\r\n }\r\n catch (_c) {\r\n // ignore errors in the onInstanceCreatedCallback\r\n }\r\n }\r\n }\r\n return instance || null;\r\n };\r\n Provider.prototype.normalizeInstanceIdentifier = function (identifier) {\r\n if (identifier === void 0) { identifier = DEFAULT_ENTRY_NAME; }\r\n if (this.component) {\r\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\r\n }\r\n else {\r\n return identifier; // assume multiple instances are supported before the component is provided.\r\n }\r\n };\r\n Provider.prototype.shouldAutoInitialize = function () {\r\n return (!!this.component &&\r\n this.component.instantiationMode !== \"EXPLICIT\" /* EXPLICIT */);\r\n };\r\n return Provider;\r\n}());\r\n// undefined should be passed to the service factory for the default instance\r\nfunction normalizeIdentifierForFactory(identifier) {\r\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\r\n}\r\nfunction isComponentEager(component) {\r\n return component.instantiationMode === \"EAGER\" /* EAGER */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nvar ComponentContainer = /** @class */ (function () {\r\n function ComponentContainer(name) {\r\n this.name = name;\r\n this.providers = new Map();\r\n }\r\n /**\r\n *\r\n * @param component Component being added\r\n * @param overwrite When a component with the same name has already been registered,\r\n * if overwrite is true: overwrite the existing component with the new component and create a new\r\n * provider with the new component. It can be useful in tests where you want to use different mocks\r\n * for different tests.\r\n * if overwrite is false: throw an exception\r\n */\r\n ComponentContainer.prototype.addComponent = function (component) {\r\n var provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n throw new Error(\"Component \" + component.name + \" has already been registered with \" + this.name);\r\n }\r\n provider.setComponent(component);\r\n };\r\n ComponentContainer.prototype.addOrOverwriteComponent = function (component) {\r\n var provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n // delete the existing provider from the container, so we can register the new component\r\n this.providers.delete(component.name);\r\n }\r\n this.addComponent(component);\r\n };\r\n /**\r\n * getProvider provides a type safe interface where it can only be called with a field name\r\n * present in NameServiceMapping interface.\r\n *\r\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\r\n * themselves.\r\n */\r\n ComponentContainer.prototype.getProvider = function (name) {\r\n if (this.providers.has(name)) {\r\n return this.providers.get(name);\r\n }\r\n // create a Provider for a service that hasn't registered with Firebase\r\n var provider = new Provider(name, this);\r\n this.providers.set(name, provider);\r\n return provider;\r\n };\r\n ComponentContainer.prototype.getProviders = function () {\r\n return Array.from(this.providers.values());\r\n };\r\n return ComponentContainer;\r\n}());\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm.js.map\n"],"sourceRoot":""}