GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1590 lines
68 KiB

2 months ago
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. require('@firebase/installations');
  4. var component = require('@firebase/component');
  5. var tslib = require('tslib');
  6. var idb = require('idb');
  7. var util = require('@firebase/util');
  8. var app = require('@firebase/app');
  9. /**
  10. * @license
  11. * Copyright 2019 Google LLC
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License");
  14. * you may not use this file except in compliance with the License.
  15. * You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS,
  21. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. * See the License for the specific language governing permissions and
  23. * limitations under the License.
  24. */
  25. var DEFAULT_VAPID_KEY = 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';
  26. var ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';
  27. /** Key of FCM Payload in Notification's data field. */
  28. var FCM_MSG = 'FCM_MSG';
  29. var CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';
  30. // Defined as in proto/messaging_event.proto. Neglecting fields that are supported.
  31. var SDK_PLATFORM_WEB = 3;
  32. var EVENT_MESSAGE_DELIVERED = 1;
  33. var MessageType$1;
  34. (function (MessageType) {
  35. MessageType[MessageType["DATA_MESSAGE"] = 1] = "DATA_MESSAGE";
  36. MessageType[MessageType["DISPLAY_NOTIFICATION"] = 3] = "DISPLAY_NOTIFICATION";
  37. })(MessageType$1 || (MessageType$1 = {}));
  38. /**
  39. * @license
  40. * Copyright 2018 Google LLC
  41. *
  42. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
  43. * in compliance with the License. You may obtain a copy of the License at
  44. *
  45. * http://www.apache.org/licenses/LICENSE-2.0
  46. *
  47. * Unless required by applicable law or agreed to in writing, software distributed under the License
  48. * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
  49. * or implied. See the License for the specific language governing permissions and limitations under
  50. * the License.
  51. */
  52. var MessageType;
  53. (function (MessageType) {
  54. MessageType["PUSH_RECEIVED"] = "push-received";
  55. MessageType["NOTIFICATION_CLICKED"] = "notification-clicked";
  56. })(MessageType || (MessageType = {}));
  57. /**
  58. * @license
  59. * Copyright 2017 Google LLC
  60. *
  61. * Licensed under the Apache License, Version 2.0 (the "License");
  62. * you may not use this file except in compliance with the License.
  63. * You may obtain a copy of the License at
  64. *
  65. * http://www.apache.org/licenses/LICENSE-2.0
  66. *
  67. * Unless required by applicable law or agreed to in writing, software
  68. * distributed under the License is distributed on an "AS IS" BASIS,
  69. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  70. * See the License for the specific language governing permissions and
  71. * limitations under the License.
  72. */
  73. function arrayToBase64(array) {
  74. var uint8Array = new Uint8Array(array);
  75. var base64String = btoa(String.fromCharCode.apply(String, tslib.__spreadArray([], tslib.__read(uint8Array), false)));
  76. return base64String.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
  77. }
  78. function base64ToArray(base64String) {
  79. var padding = '='.repeat((4 - (base64String.length % 4)) % 4);
  80. var base64 = (base64String + padding)
  81. .replace(/\-/g, '+')
  82. .replace(/_/g, '/');
  83. var rawData = atob(base64);
  84. var outputArray = new Uint8Array(rawData.length);
  85. for (var i = 0; i < rawData.length; ++i) {
  86. outputArray[i] = rawData.charCodeAt(i);
  87. }
  88. return outputArray;
  89. }
  90. /**
  91. * @license
  92. * Copyright 2019 Google LLC
  93. *
  94. * Licensed under the Apache License, Version 2.0 (the "License");
  95. * you may not use this file except in compliance with the License.
  96. * You may obtain a copy of the License at
  97. *
  98. * http://www.apache.org/licenses/LICENSE-2.0
  99. *
  100. * Unless required by applicable law or agreed to in writing, software
  101. * distributed under the License is distributed on an "AS IS" BASIS,
  102. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  103. * See the License for the specific language governing permissions and
  104. * limitations under the License.
  105. */
  106. var OLD_DB_NAME = 'fcm_token_details_db';
  107. /**
  108. * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade
  109. * callback is called for all versions of the old DB.
  110. */
  111. var OLD_DB_VERSION = 5;
  112. var OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';
  113. function migrateOldDatabase(senderId) {
  114. return tslib.__awaiter(this, void 0, void 0, function () {
  115. var databases, dbNames, tokenDetails, db;
  116. var _this = this;
  117. return tslib.__generator(this, function (_a) {
  118. switch (_a.label) {
  119. case 0:
  120. if (!('databases' in indexedDB)) return [3 /*break*/, 2];
  121. return [4 /*yield*/, indexedDB.databases()];
  122. case 1:
  123. databases = _a.sent();
  124. dbNames = databases.map(function (db) { return db.name; });
  125. if (!dbNames.includes(OLD_DB_NAME)) {
  126. // old DB didn't exist, no need to open.
  127. return [2 /*return*/, null];
  128. }
  129. _a.label = 2;
  130. case 2:
  131. tokenDetails = null;
  132. return [4 /*yield*/, idb.openDB(OLD_DB_NAME, OLD_DB_VERSION, {
  133. upgrade: function (db, oldVersion, newVersion, upgradeTransaction) { return tslib.__awaiter(_this, void 0, void 0, function () {
  134. var objectStore, value, oldDetails, oldDetails, oldDetails;
  135. var _a;
  136. return tslib.__generator(this, function (_b) {
  137. switch (_b.label) {
  138. case 0:
  139. if (oldVersion < 2) {
  140. // Database too old, skip migration.
  141. return [2 /*return*/];
  142. }
  143. if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {
  144. // Database did not exist. Nothing to do.
  145. return [2 /*return*/];
  146. }
  147. objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);
  148. return [4 /*yield*/, objectStore.index('fcmSenderId').get(senderId)];
  149. case 1:
  150. value = _b.sent();
  151. return [4 /*yield*/, objectStore.clear()];
  152. case 2:
  153. _b.sent();
  154. if (!value) {
  155. // No entry in the database, nothing to migrate.
  156. return [2 /*return*/];
  157. }
  158. if (oldVersion === 2) {
  159. oldDetails = value;
  160. if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {
  161. return [2 /*return*/];
  162. }
  163. tokenDetails = {
  164. token: oldDetails.fcmToken,
  165. createTime: (_a = oldDetails.createTime) !== null && _a !== void 0 ? _a : Date.now(),
  166. subscriptionOptions: {
  167. auth: oldDetails.auth,
  168. p256dh: oldDetails.p256dh,
  169. endpoint: oldDetails.endpoint,
  170. swScope: oldDetails.swScope,
  171. vapidKey: typeof oldDetails.vapidKey === 'string'
  172. ? oldDetails.vapidKey
  173. : arrayToBase64(oldDetails.vapidKey)
  174. }
  175. };
  176. }
  177. else if (oldVersion === 3) {
  178. oldDetails = value;
  179. tokenDetails = {
  180. token: oldDetails.fcmToken,
  181. createTime: oldDetails.createTime,
  182. subscriptionOptions: {
  183. auth: arrayToBase64(oldDetails.auth),
  184. p256dh: arrayToBase64(oldDetails.p256dh),
  185. endpoint: oldDetails.endpoint,
  186. swScope: oldDetails.swScope,
  187. vapidKey: arrayToBase64(oldDetails.vapidKey)
  188. }
  189. };
  190. }
  191. else if (oldVersion === 4) {
  192. oldDetails = value;
  193. tokenDetails = {
  194. token: oldDetails.fcmToken,
  195. createTime: oldDetails.createTime,
  196. subscriptionOptions: {
  197. auth: arrayToBase64(oldDetails.auth),
  198. p256dh: arrayToBase64(oldDetails.p256dh),
  199. endpoint: oldDetails.endpoint,
  200. swScope: oldDetails.swScope,
  201. vapidKey: arrayToBase64(oldDetails.vapidKey)
  202. }
  203. };
  204. }
  205. return [2 /*return*/];
  206. }
  207. });
  208. }); }
  209. })];
  210. case 3:
  211. db = _a.sent();
  212. db.close();
  213. // Delete all old databases.
  214. return [4 /*yield*/, idb.deleteDB(OLD_DB_NAME)];
  215. case 4:
  216. // Delete all old databases.
  217. _a.sent();
  218. return [4 /*yield*/, idb.deleteDB('fcm_vapid_details_db')];
  219. case 5:
  220. _a.sent();
  221. return [4 /*yield*/, idb.deleteDB('undefined')];
  222. case 6:
  223. _a.sent();
  224. return [2 /*return*/, checkTokenDetails(tokenDetails) ? tokenDetails : null];
  225. }
  226. });
  227. });
  228. }
  229. function checkTokenDetails(tokenDetails) {
  230. if (!tokenDetails || !tokenDetails.subscriptionOptions) {
  231. return false;
  232. }
  233. var subscriptionOptions = tokenDetails.subscriptionOptions;
  234. return (typeof tokenDetails.createTime === 'number' &&
  235. tokenDetails.createTime > 0 &&
  236. typeof tokenDetails.token === 'string' &&
  237. tokenDetails.token.length > 0 &&
  238. typeof subscriptionOptions.auth === 'string' &&
  239. subscriptionOptions.auth.length > 0 &&
  240. typeof subscriptionOptions.p256dh === 'string' &&
  241. subscriptionOptions.p256dh.length > 0 &&
  242. typeof subscriptionOptions.endpoint === 'string' &&
  243. subscriptionOptions.endpoint.length > 0 &&
  244. typeof subscriptionOptions.swScope === 'string' &&
  245. subscriptionOptions.swScope.length > 0 &&
  246. typeof subscriptionOptions.vapidKey === 'string' &&
  247. subscriptionOptions.vapidKey.length > 0);
  248. }
  249. /**
  250. * @license
  251. * Copyright 2019 Google LLC
  252. *
  253. * Licensed under the Apache License, Version 2.0 (the "License");
  254. * you may not use this file except in compliance with the License.
  255. * You may obtain a copy of the License at
  256. *
  257. * http://www.apache.org/licenses/LICENSE-2.0
  258. *
  259. * Unless required by applicable law or agreed to in writing, software
  260. * distributed under the License is distributed on an "AS IS" BASIS,
  261. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  262. * See the License for the specific language governing permissions and
  263. * limitations under the License.
  264. */
  265. // Exported for tests.
  266. var DATABASE_NAME = 'firebase-messaging-database';
  267. var DATABASE_VERSION = 1;
  268. var OBJECT_STORE_NAME = 'firebase-messaging-store';
  269. var dbPromise = null;
  270. function getDbPromise() {
  271. if (!dbPromise) {
  272. dbPromise = idb.openDB(DATABASE_NAME, DATABASE_VERSION, {
  273. upgrade: function (upgradeDb, oldVersion) {
  274. // We don't use 'break' in this switch statement, the fall-through behavior is what we want,
  275. // because if there are multiple versions between the old version and the current version, we
  276. // want ALL the migrations that correspond to those versions to run, not only the last one.
  277. // eslint-disable-next-line default-case
  278. switch (oldVersion) {
  279. case 0:
  280. upgradeDb.createObjectStore(OBJECT_STORE_NAME);
  281. }
  282. }
  283. });
  284. }
  285. return dbPromise;
  286. }
  287. /** Gets record(s) from the objectStore that match the given key. */
  288. function dbGet(firebaseDependencies) {
  289. return tslib.__awaiter(this, void 0, void 0, function () {
  290. var key, db, tokenDetails, oldTokenDetails;
  291. return tslib.__generator(this, function (_a) {
  292. switch (_a.label) {
  293. case 0:
  294. key = getKey(firebaseDependencies);
  295. return [4 /*yield*/, getDbPromise()];
  296. case 1:
  297. db = _a.sent();
  298. return [4 /*yield*/, db
  299. .transaction(OBJECT_STORE_NAME)
  300. .objectStore(OBJECT_STORE_NAME)
  301. .get(key)];
  302. case 2:
  303. tokenDetails = (_a.sent());
  304. if (!tokenDetails) return [3 /*break*/, 3];
  305. return [2 /*return*/, tokenDetails];
  306. case 3: return [4 /*yield*/, migrateOldDatabase(firebaseDependencies.appConfig.senderId)];
  307. case 4:
  308. oldTokenDetails = _a.sent();
  309. if (!oldTokenDetails) return [3 /*break*/, 6];
  310. return [4 /*yield*/, dbSet(firebaseDependencies, oldTokenDetails)];
  311. case 5:
  312. _a.sent();
  313. return [2 /*return*/, oldTokenDetails];
  314. case 6: return [2 /*return*/];
  315. }
  316. });
  317. });
  318. }
  319. /** Assigns or overwrites the record for the given key with the given value. */
  320. function dbSet(firebaseDependencies, tokenDetails) {
  321. return tslib.__awaiter(this, void 0, void 0, function () {
  322. var key, db, tx;
  323. return tslib.__generator(this, function (_a) {
  324. switch (_a.label) {
  325. case 0:
  326. key = getKey(firebaseDependencies);
  327. return [4 /*yield*/, getDbPromise()];
  328. case 1:
  329. db = _a.sent();
  330. tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
  331. return [4 /*yield*/, tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key)];
  332. case 2:
  333. _a.sent();
  334. return [4 /*yield*/, tx.done];
  335. case 3:
  336. _a.sent();
  337. return [2 /*return*/, tokenDetails];
  338. }
  339. });
  340. });
  341. }
  342. /** Removes record(s) from the objectStore that match the given key. */
  343. function dbRemove(firebaseDependencies) {
  344. return tslib.__awaiter(this, void 0, void 0, function () {
  345. var key, db, tx;
  346. return tslib.__generator(this, function (_a) {
  347. switch (_a.label) {
  348. case 0:
  349. key = getKey(firebaseDependencies);
  350. return [4 /*yield*/, getDbPromise()];
  351. case 1:
  352. db = _a.sent();
  353. tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
  354. return [4 /*yield*/, tx.objectStore(OBJECT_STORE_NAME).delete(key)];
  355. case 2:
  356. _a.sent();
  357. return [4 /*yield*/, tx.done];
  358. case 3:
  359. _a.sent();
  360. return [2 /*return*/];
  361. }
  362. });
  363. });
  364. }
  365. function getKey(_a) {
  366. var appConfig = _a.appConfig;
  367. return appConfig.appId;
  368. }
  369. /**
  370. * @license
  371. * Copyright 2017 Google LLC
  372. *
  373. * Licensed under the Apache License, Version 2.0 (the "License");
  374. * you may not use this file except in compliance with the License.
  375. * You may obtain a copy of the License at
  376. *
  377. * http://www.apache.org/licenses/LICENSE-2.0
  378. *
  379. * Unless required by applicable law or agreed to in writing, software
  380. * distributed under the License is distributed on an "AS IS" BASIS,
  381. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  382. * See the License for the specific language governing permissions and
  383. * limitations under the License.
  384. */
  385. var _a;
  386. var ERROR_MAP = (_a = {},
  387. _a["missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */] = 'Missing App configuration value: "{$valueName}"',
  388. _a["only-available-in-window" /* ErrorCode.AVAILABLE_IN_WINDOW */] = 'This method is available in a Window context.',
  389. _a["only-available-in-sw" /* ErrorCode.AVAILABLE_IN_SW */] = 'This method is available in a service worker context.',
  390. _a["permission-default" /* ErrorCode.PERMISSION_DEFAULT */] = 'The notification permission was not granted and dismissed instead.',
  391. _a["permission-blocked" /* ErrorCode.PERMISSION_BLOCKED */] = 'The notification permission was not granted and blocked instead.',
  392. _a["unsupported-browser" /* ErrorCode.UNSUPPORTED_BROWSER */] = "This browser doesn't support the API's required to use the Firebase SDK.",
  393. _a["indexed-db-unsupported" /* ErrorCode.INDEXED_DB_UNSUPPORTED */] = "This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)",
  394. _a["failed-service-worker-registration" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */] = 'We are unable to register the default service worker. {$browserErrorMessage}',
  395. _a["token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */] = 'A problem occurred while subscribing the user to FCM: {$errorInfo}',
  396. _a["token-subscribe-no-token" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */] = 'FCM returned no token when subscribing the user to push.',
  397. _a["token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */] = 'A problem occurred while unsubscribing the ' +
  398. 'user from FCM: {$errorInfo}',
  399. _a["token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */] = 'A problem occurred while updating the user from FCM: {$errorInfo}',
  400. _a["token-update-no-token" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */] = 'FCM returned no token when updating the user to push.',
  401. _a["use-sw-after-get-token" /* ErrorCode.USE_SW_AFTER_GET_TOKEN */] = 'The useServiceWorker() method may only be called once and must be ' +
  402. 'called before calling getToken() to ensure your service worker is used.',
  403. _a["invalid-sw-registration" /* ErrorCode.INVALID_SW_REGISTRATION */] = 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',
  404. _a["invalid-bg-handler" /* ErrorCode.INVALID_BG_HANDLER */] = 'The input to setBackgroundMessageHandler() must be a function.',
  405. _a["invalid-vapid-key" /* ErrorCode.INVALID_VAPID_KEY */] = 'The public VAPID key must be a string.',
  406. _a["use-vapid-key-after-get-token" /* ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN */] = 'The usePublicVapidKey() method may only be called once and must be ' +
  407. 'called before calling getToken() to ensure your VAPID key is used.',
  408. _a);
  409. var ERROR_FACTORY = new util.ErrorFactory('messaging', 'Messaging', ERROR_MAP);
  410. /**
  411. * @license
  412. * Copyright 2019 Google LLC
  413. *
  414. * Licensed under the Apache License, Version 2.0 (the "License");
  415. * you may not use this file except in compliance with the License.
  416. * You may obtain a copy of the License at
  417. *
  418. * http://www.apache.org/licenses/LICENSE-2.0
  419. *
  420. * Unless required by applicable law or agreed to in writing, software
  421. * distributed under the License is distributed on an "AS IS" BASIS,
  422. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  423. * See the License for the specific language governing permissions and
  424. * limitations under the License.
  425. */
  426. function requestGetToken(firebaseDependencies, subscriptionOptions) {
  427. return tslib.__awaiter(this, void 0, void 0, function () {
  428. var headers, body, subscribeOptions, responseData, response, err_1, message;
  429. return tslib.__generator(this, function (_a) {
  430. switch (_a.label) {
  431. case 0: return [4 /*yield*/, getHeaders(firebaseDependencies)];
  432. case 1:
  433. headers = _a.sent();
  434. body = getBody(subscriptionOptions);
  435. subscribeOptions = {
  436. method: 'POST',
  437. headers: headers,
  438. body: JSON.stringify(body)
  439. };
  440. _a.label = 2;
  441. case 2:
  442. _a.trys.push([2, 5, , 6]);
  443. return [4 /*yield*/, fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions)];
  444. case 3:
  445. response = _a.sent();
  446. return [4 /*yield*/, response.json()];
  447. case 4:
  448. responseData = _a.sent();
  449. return [3 /*break*/, 6];
  450. case 5:
  451. err_1 = _a.sent();
  452. throw ERROR_FACTORY.create("token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {
  453. errorInfo: err_1 === null || err_1 === void 0 ? void 0 : err_1.toString()
  454. });
  455. case 6:
  456. if (responseData.error) {
  457. message = responseData.error.message;
  458. throw ERROR_FACTORY.create("token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {
  459. errorInfo: message
  460. });
  461. }
  462. if (!responseData.token) {
  463. throw ERROR_FACTORY.create("token-subscribe-no-token" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */);
  464. }
  465. return [2 /*return*/, responseData.token];
  466. }
  467. });
  468. });
  469. }
  470. function requestUpdateToken(firebaseDependencies, tokenDetails) {
  471. return tslib.__awaiter(this, void 0, void 0, function () {
  472. var headers, body, updateOptions, responseData, response, err_2, message;
  473. return tslib.__generator(this, function (_a) {
  474. switch (_a.label) {
  475. case 0: return [4 /*yield*/, getHeaders(firebaseDependencies)];
  476. case 1:
  477. headers = _a.sent();
  478. body = getBody(tokenDetails.subscriptionOptions);
  479. updateOptions = {
  480. method: 'PATCH',
  481. headers: headers,
  482. body: JSON.stringify(body)
  483. };
  484. _a.label = 2;
  485. case 2:
  486. _a.trys.push([2, 5, , 6]);
  487. return [4 /*yield*/, fetch("".concat(getEndpoint(firebaseDependencies.appConfig), "/").concat(tokenDetails.token), updateOptions)];
  488. case 3:
  489. response = _a.sent();
  490. return [4 /*yield*/, response.json()];
  491. case 4:
  492. responseData = _a.sent();
  493. return [3 /*break*/, 6];
  494. case 5:
  495. err_2 = _a.sent();
  496. throw ERROR_FACTORY.create("token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */, {
  497. errorInfo: err_2 === null || err_2 === void 0 ? void 0 : err_2.toString()
  498. });
  499. case 6:
  500. if (responseData.error) {
  501. message = responseData.error.message;
  502. throw ERROR_FACTORY.create("token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */, {
  503. errorInfo: message
  504. });
  505. }
  506. if (!responseData.token) {
  507. throw ERROR_FACTORY.create("token-update-no-token" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */);
  508. }
  509. return [2 /*return*/, responseData.token];
  510. }
  511. });
  512. });
  513. }
  514. function requestDeleteToken(firebaseDependencies, token) {
  515. return tslib.__awaiter(this, void 0, void 0, function () {
  516. var headers, unsubscribeOptions, response, responseData, message, err_3;
  517. return tslib.__generator(this, function (_a) {
  518. switch (_a.label) {
  519. case 0: return [4 /*yield*/, getHeaders(firebaseDependencies)];
  520. case 1:
  521. headers = _a.sent();
  522. unsubscribeOptions = {
  523. method: 'DELETE',
  524. headers: headers
  525. };
  526. _a.label = 2;
  527. case 2:
  528. _a.trys.push([2, 5, , 6]);
  529. return [4 /*yield*/, fetch("".concat(getEndpoint(firebaseDependencies.appConfig), "/").concat(token), unsubscribeOptions)];
  530. case 3:
  531. response = _a.sent();
  532. return [4 /*yield*/, response.json()];
  533. case 4:
  534. responseData = _a.sent();
  535. if (responseData.error) {
  536. message = responseData.error.message;
  537. throw ERROR_FACTORY.create("token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {
  538. errorInfo: message
  539. });
  540. }
  541. return [3 /*break*/, 6];
  542. case 5:
  543. err_3 = _a.sent();
  544. throw ERROR_FACTORY.create("token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {
  545. errorInfo: err_3 === null || err_3 === void 0 ? void 0 : err_3.toString()
  546. });
  547. case 6: return [2 /*return*/];
  548. }
  549. });
  550. });
  551. }
  552. function getEndpoint(_a) {
  553. var projectId = _a.projectId;
  554. return "".concat(ENDPOINT, "/projects/").concat(projectId, "/registrations");
  555. }
  556. function getHeaders(_a) {
  557. var appConfig = _a.appConfig, installations = _a.installations;
  558. return tslib.__awaiter(this, void 0, void 0, function () {
  559. var authToken;
  560. return tslib.__generator(this, function (_b) {
  561. switch (_b.label) {
  562. case 0: return [4 /*yield*/, installations.getToken()];
  563. case 1:
  564. authToken = _b.sent();
  565. return [2 /*return*/, new Headers({
  566. 'Content-Type': 'application/json',
  567. Accept: 'application/json',
  568. 'x-goog-api-key': appConfig.apiKey,
  569. 'x-goog-firebase-installations-auth': "FIS ".concat(authToken)
  570. })];
  571. }
  572. });
  573. });
  574. }
  575. function getBody(_a) {
  576. var p256dh = _a.p256dh, auth = _a.auth, endpoint = _a.endpoint, vapidKey = _a.vapidKey;
  577. var body = {
  578. web: {
  579. endpoint: endpoint,
  580. auth: auth,
  581. p256dh: p256dh
  582. }
  583. };
  584. if (vapidKey !== DEFAULT_VAPID_KEY) {
  585. body.web.applicationPubKey = vapidKey;
  586. }
  587. return body;
  588. }
  589. /**
  590. * @license
  591. * Copyright 2019 Google LLC
  592. *
  593. * Licensed under the Apache License, Version 2.0 (the "License");
  594. * you may not use this file except in compliance with the License.
  595. * You may obtain a copy of the License at
  596. *
  597. * http://www.apache.org/licenses/LICENSE-2.0
  598. *
  599. * Unless required by applicable law or agreed to in writing, software
  600. * distributed under the License is distributed on an "AS IS" BASIS,
  601. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  602. * See the License for the specific language governing permissions and
  603. * limitations under the License.
  604. */
  605. // UpdateRegistration will be called once every week.
  606. var TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
  607. function getTokenInternal(messaging) {
  608. return tslib.__awaiter(this, void 0, void 0, function () {
  609. var pushSubscription, subscriptionOptions, tokenDetails, e_1;
  610. return tslib.__generator(this, function (_a) {
  611. switch (_a.label) {
  612. case 0: return [4 /*yield*/, getPushSubscription(messaging.swRegistration, messaging.vapidKey)];
  613. case 1:
  614. pushSubscription = _a.sent();
  615. subscriptionOptions = {
  616. vapidKey: messaging.vapidKey,
  617. swScope: messaging.swRegistration.scope,
  618. endpoint: pushSubscription.endpoint,
  619. auth: arrayToBase64(pushSubscription.getKey('auth')),
  620. p256dh: arrayToBase64(pushSubscription.getKey('p256dh'))
  621. };
  622. return [4 /*yield*/, dbGet(messaging.firebaseDependencies)];
  623. case 2:
  624. tokenDetails = _a.sent();
  625. if (!!tokenDetails) return [3 /*break*/, 3];
  626. // No token, get a new one.
  627. return [2 /*return*/, getNewToken(messaging.firebaseDependencies, subscriptionOptions)];
  628. case 3:
  629. if (!!isTokenValid(tokenDetails.subscriptionOptions, subscriptionOptions)) return [3 /*break*/, 8];
  630. _a.label = 4;
  631. case 4:
  632. _a.trys.push([4, 6, , 7]);
  633. return [4 /*yield*/, requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token)];
  634. case 5:
  635. _a.sent();
  636. return [3 /*break*/, 7];
  637. case 6:
  638. e_1 = _a.sent();
  639. // Suppress errors because of #2364
  640. console.warn(e_1);
  641. return [3 /*break*/, 7];
  642. case 7: return [2 /*return*/, getNewToken(messaging.firebaseDependencies, subscriptionOptions)];
  643. case 8:
  644. if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {
  645. // Weekly token refresh
  646. return [2 /*return*/, updateToken(messaging, {
  647. token: tokenDetails.token,
  648. createTime: Date.now(),
  649. subscriptionOptions: subscriptionOptions
  650. })];
  651. }
  652. else {
  653. // Valid token, nothing to do.
  654. return [2 /*return*/, tokenDetails.token];
  655. }
  656. case 9: return [2 /*return*/];
  657. }
  658. });
  659. });
  660. }
  661. /**
  662. * This method deletes the token from the database, unsubscribes the token from FCM, and unregisters
  663. * the push subscription if it exists.
  664. */
  665. function deleteTokenInternal(messaging) {
  666. return tslib.__awaiter(this, void 0, void 0, function () {
  667. var tokenDetails, pushSubscription;
  668. return tslib.__generator(this, function (_a) {
  669. switch (_a.label) {
  670. case 0: return [4 /*yield*/, dbGet(messaging.firebaseDependencies)];
  671. case 1:
  672. tokenDetails = _a.sent();
  673. if (!tokenDetails) return [3 /*break*/, 4];
  674. return [4 /*yield*/, requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token)];
  675. case 2:
  676. _a.sent();
  677. return [4 /*yield*/, dbRemove(messaging.firebaseDependencies)];
  678. case 3:
  679. _a.sent();
  680. _a.label = 4;
  681. case 4: return [4 /*yield*/, messaging.swRegistration.pushManager.getSubscription()];
  682. case 5:
  683. pushSubscription = _a.sent();
  684. if (pushSubscription) {
  685. return [2 /*return*/, pushSubscription.unsubscribe()];
  686. }
  687. // If there's no SW, consider it a success.
  688. return [2 /*return*/, true];
  689. }
  690. });
  691. });
  692. }
  693. function updateToken(messaging, tokenDetails) {
  694. return tslib.__awaiter(this, void 0, void 0, function () {
  695. var updatedToken, updatedTokenDetails, e_2;
  696. return tslib.__generator(this, function (_a) {
  697. switch (_a.label) {
  698. case 0:
  699. _a.trys.push([0, 3, , 5]);
  700. return [4 /*yield*/, requestUpdateToken(messaging.firebaseDependencies, tokenDetails)];
  701. case 1:
  702. updatedToken = _a.sent();
  703. updatedTokenDetails = tslib.__assign(tslib.__assign({}, tokenDetails), { token: updatedToken, createTime: Date.now() });
  704. return [4 /*yield*/, dbSet(messaging.firebaseDependencies, updatedTokenDetails)];
  705. case 2:
  706. _a.sent();
  707. return [2 /*return*/, updatedToken];
  708. case 3:
  709. e_2 = _a.sent();
  710. return [4 /*yield*/, deleteTokenInternal(messaging)];
  711. case 4:
  712. _a.sent();
  713. throw e_2;
  714. case 5: return [2 /*return*/];
  715. }
  716. });
  717. });
  718. }
  719. function getNewToken(firebaseDependencies, subscriptionOptions) {
  720. return tslib.__awaiter(this, void 0, void 0, function () {
  721. var token, tokenDetails;
  722. return tslib.__generator(this, function (_a) {
  723. switch (_a.label) {
  724. case 0: return [4 /*yield*/, requestGetToken(firebaseDependencies, subscriptionOptions)];
  725. case 1:
  726. token = _a.sent();
  727. tokenDetails = {
  728. token: token,
  729. createTime: Date.now(),
  730. subscriptionOptions: subscriptionOptions
  731. };
  732. return [4 /*yield*/, dbSet(firebaseDependencies, tokenDetails)];
  733. case 2:
  734. _a.sent();
  735. return [2 /*return*/, tokenDetails.token];
  736. }
  737. });
  738. });
  739. }
  740. /**
  741. * Gets a PushSubscription for the current user.
  742. */
  743. function getPushSubscription(swRegistration, vapidKey) {
  744. return tslib.__awaiter(this, void 0, void 0, function () {
  745. var subscription;
  746. return tslib.__generator(this, function (_a) {
  747. switch (_a.label) {
  748. case 0: return [4 /*yield*/, swRegistration.pushManager.getSubscription()];
  749. case 1:
  750. subscription = _a.sent();
  751. if (subscription) {
  752. return [2 /*return*/, subscription];
  753. }
  754. return [2 /*return*/, swRegistration.pushManager.subscribe({
  755. userVisibleOnly: true,
  756. // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key
  757. // submitted to pushManager#subscribe must be of type Uint8Array.
  758. applicationServerKey: base64ToArray(vapidKey)
  759. })];
  760. }
  761. });
  762. });
  763. }
  764. /**
  765. * Checks if the saved tokenDetails object matches the configuration provided.
  766. */
  767. function isTokenValid(dbOptions, currentOptions) {
  768. var isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;
  769. var isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;
  770. var isAuthEqual = currentOptions.auth === dbOptions.auth;
  771. var isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;
  772. return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;
  773. }
  774. /**
  775. * @license
  776. * Copyright 2020 Google LLC
  777. *
  778. * Licensed under the Apache License, Version 2.0 (the "License");
  779. * you may not use this file except in compliance with the License.
  780. * You may obtain a copy of the License at
  781. *
  782. * http://www.apache.org/licenses/LICENSE-2.0
  783. *
  784. * Unless required by applicable law or agreed to in writing, software
  785. * distributed under the License is distributed on an "AS IS" BASIS,
  786. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  787. * See the License for the specific language governing permissions and
  788. * limitations under the License.
  789. */
  790. function externalizePayload(internalPayload) {
  791. var payload = {
  792. from: internalPayload.from,
  793. // eslint-disable-next-line camelcase
  794. collapseKey: internalPayload.collapse_key,
  795. // eslint-disable-next-line camelcase
  796. messageId: internalPayload.fcmMessageId
  797. };
  798. propagateNotificationPayload(payload, internalPayload);
  799. propagateDataPayload(payload, internalPayload);
  800. propagateFcmOptions(payload, internalPayload);
  801. return payload;
  802. }
  803. function propagateNotificationPayload(payload, messagePayloadInternal) {
  804. if (!messagePayloadInternal.notification) {
  805. return;
  806. }
  807. payload.notification = {};
  808. var title = messagePayloadInternal.notification.title;
  809. if (!!title) {
  810. payload.notification.title = title;
  811. }
  812. var body = messagePayloadInternal.notification.body;
  813. if (!!body) {
  814. payload.notification.body = body;
  815. }
  816. var image = messagePayloadInternal.notification.image;
  817. if (!!image) {
  818. payload.notification.image = image;
  819. }
  820. var icon = messagePayloadInternal.notification.icon;
  821. if (!!icon) {
  822. payload.notification.icon = icon;
  823. }
  824. }
  825. function propagateDataPayload(payload, messagePayloadInternal) {
  826. if (!messagePayloadInternal.data) {
  827. return;
  828. }
  829. payload.data = messagePayloadInternal.data;
  830. }
  831. function propagateFcmOptions(payload, messagePayloadInternal) {
  832. var _a, _b, _c, _d, _e;
  833. // fcmOptions.link value is written into notification.click_action. see more in b/232072111
  834. if (!messagePayloadInternal.fcmOptions &&
  835. !((_a = messagePayloadInternal.notification) === null || _a === void 0 ? void 0 : _a.click_action)) {
  836. return;
  837. }
  838. payload.fcmOptions = {};
  839. var link = (_c = (_b = messagePayloadInternal.fcmOptions) === null || _b === void 0 ? void 0 : _b.link) !== null && _c !== void 0 ? _c : (_d = messagePayloadInternal.notification) === null || _d === void 0 ? void 0 : _d.click_action;
  840. if (!!link) {
  841. payload.fcmOptions.link = link;
  842. }
  843. // eslint-disable-next-line camelcase
  844. var analyticsLabel = (_e = messagePayloadInternal.fcmOptions) === null || _e === void 0 ? void 0 : _e.analytics_label;
  845. if (!!analyticsLabel) {
  846. payload.fcmOptions.analyticsLabel = analyticsLabel;
  847. }
  848. }
  849. /**
  850. * @license
  851. * Copyright 2019 Google LLC
  852. *
  853. * Licensed under the Apache License, Version 2.0 (the "License");
  854. * you may not use this file except in compliance with the License.
  855. * You may obtain a copy of the License at
  856. *
  857. * http://www.apache.org/licenses/LICENSE-2.0
  858. *
  859. * Unless required by applicable law or agreed to in writing, software
  860. * distributed under the License is distributed on an "AS IS" BASIS,
  861. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  862. * See the License for the specific language governing permissions and
  863. * limitations under the License.
  864. */
  865. function isConsoleMessage(data) {
  866. // This message has a campaign ID, meaning it was sent using the Firebase Console.
  867. return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;
  868. }
  869. /**
  870. * @license
  871. * Copyright 2019 Google LLC
  872. *
  873. * Licensed under the Apache License, Version 2.0 (the "License");
  874. * you may not use this file except in compliance with the License.
  875. * You may obtain a copy of the License at
  876. *
  877. * http://www.apache.org/licenses/LICENSE-2.0
  878. *
  879. * Unless required by applicable law or agreed to in writing, software
  880. * distributed under the License is distributed on an "AS IS" BASIS,
  881. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  882. * See the License for the specific language governing permissions and
  883. * limitations under the License.
  884. */
  885. /** Returns a promise that resolves after given time passes. */
  886. function sleep(ms) {
  887. return new Promise(function (resolve) {
  888. setTimeout(resolve, ms);
  889. });
  890. }
  891. /**
  892. * @license
  893. * Copyright 2019 Google LLC
  894. *
  895. * Licensed under the Apache License, Version 2.0 (the "License");
  896. * you may not use this file except in compliance with the License.
  897. * You may obtain a copy of the License at
  898. *
  899. * http://www.apache.org/licenses/LICENSE-2.0
  900. *
  901. * Unless required by applicable law or agreed to in writing, software
  902. * distributed under the License is distributed on an "AS IS" BASIS,
  903. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  904. * See the License for the specific language governing permissions and
  905. * limitations under the License.
  906. */
  907. _mergeStrings('hts/frbslgigp.ogepscmv/ieo/eaylg', 'tp:/ieaeogn-agolai.o/1frlglgc/o');
  908. _mergeStrings('AzSCbw63g1R0nCw85jG8', 'Iaya3yLKwmgvh7cF0q4');
  909. function stageLog(messaging, internalPayload) {
  910. return tslib.__awaiter(this, void 0, void 0, function () {
  911. var fcmEvent, _a, _b;
  912. return tslib.__generator(this, function (_c) {
  913. switch (_c.label) {
  914. case 0:
  915. _a = createFcmEvent;
  916. _b = [internalPayload];
  917. return [4 /*yield*/, messaging.firebaseDependencies.installations.getId()];
  918. case 1:
  919. fcmEvent = _a.apply(void 0, _b.concat([_c.sent()]));
  920. createAndEnqueueLogEvent(messaging, fcmEvent);
  921. return [2 /*return*/];
  922. }
  923. });
  924. });
  925. }
  926. function createFcmEvent(internalPayload, fid) {
  927. var _a, _b;
  928. var fcmEvent = {};
  929. /* eslint-disable camelcase */
  930. // some fields should always be non-null. Still check to ensure.
  931. if (!!internalPayload.from) {
  932. fcmEvent.project_number = internalPayload.from;
  933. }
  934. if (!!internalPayload.fcmMessageId) {
  935. fcmEvent.message_id = internalPayload.fcmMessageId;
  936. }
  937. fcmEvent.instance_id = fid;
  938. if (!!internalPayload.notification) {
  939. fcmEvent.message_type = MessageType$1.DISPLAY_NOTIFICATION.toString();
  940. }
  941. else {
  942. fcmEvent.message_type = MessageType$1.DATA_MESSAGE.toString();
  943. }
  944. fcmEvent.sdk_platform = SDK_PLATFORM_WEB.toString();
  945. fcmEvent.package_name = self.origin.replace(/(^\w+:|^)\/\//, '');
  946. if (!!internalPayload.collapse_key) {
  947. fcmEvent.collapse_key = internalPayload.collapse_key;
  948. }
  949. fcmEvent.event = EVENT_MESSAGE_DELIVERED.toString();
  950. if (!!((_a = internalPayload.fcmOptions) === null || _a === void 0 ? void 0 : _a.analytics_label)) {
  951. fcmEvent.analytics_label = (_b = internalPayload.fcmOptions) === null || _b === void 0 ? void 0 : _b.analytics_label;
  952. }
  953. /* eslint-enable camelcase */
  954. return fcmEvent;
  955. }
  956. function createAndEnqueueLogEvent(messaging, fcmEvent) {
  957. var logEvent = {};
  958. /* eslint-disable camelcase */
  959. logEvent.event_time_ms = Math.floor(Date.now()).toString();
  960. logEvent.source_extension_json_proto3 = JSON.stringify(fcmEvent);
  961. // eslint-disable-next-line camelcase
  962. messaging.logEvents.push(logEvent);
  963. }
  964. function _mergeStrings(s1, s2) {
  965. var resultArray = [];
  966. for (var i = 0; i < s1.length; i++) {
  967. resultArray.push(s1.charAt(i));
  968. if (i < s2.length) {
  969. resultArray.push(s2.charAt(i));
  970. }
  971. }
  972. return resultArray.join('');
  973. }
  974. /**
  975. * @license
  976. * Copyright 2017 Google LLC
  977. *
  978. * Licensed under the Apache License, Version 2.0 (the "License");
  979. * you may not use this file except in compliance with the License.
  980. * You may obtain a copy of the License at
  981. *
  982. * http://www.apache.org/licenses/LICENSE-2.0
  983. *
  984. * Unless required by applicable law or agreed to in writing, software
  985. * distributed under the License is distributed on an "AS IS" BASIS,
  986. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  987. * See the License for the specific language governing permissions and
  988. * limitations under the License.
  989. */
  990. function onSubChange(event, messaging) {
  991. var _a, _b;
  992. return tslib.__awaiter(this, void 0, void 0, function () {
  993. var newSubscription, tokenDetails;
  994. return tslib.__generator(this, function (_c) {
  995. switch (_c.label) {
  996. case 0:
  997. newSubscription = event.newSubscription;
  998. if (!!newSubscription) return [3 /*break*/, 2];
  999. // Subscription revoked, delete token
  1000. return [4 /*yield*/, deleteTokenInternal(messaging)];
  1001. case 1:
  1002. // Subscription revoked, delete token
  1003. _c.sent();
  1004. return [2 /*return*/];
  1005. case 2: return [4 /*yield*/, dbGet(messaging.firebaseDependencies)];
  1006. case 3:
  1007. tokenDetails = _c.sent();
  1008. return [4 /*yield*/, deleteTokenInternal(messaging)];
  1009. case 4:
  1010. _c.sent();
  1011. messaging.vapidKey =
  1012. (_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;
  1013. return [4 /*yield*/, getTokenInternal(messaging)];
  1014. case 5:
  1015. _c.sent();
  1016. return [2 /*return*/];
  1017. }
  1018. });
  1019. });
  1020. }
  1021. function onPush(event, messaging) {
  1022. return tslib.__awaiter(this, void 0, void 0, function () {
  1023. var internalPayload, clientList, payload;
  1024. return tslib.__generator(this, function (_a) {
  1025. switch (_a.label) {
  1026. case 0:
  1027. internalPayload = getMessagePayloadInternal(event);
  1028. if (!internalPayload) {
  1029. // Failed to get parsed MessagePayload from the PushEvent. Skip handling the push.
  1030. return [2 /*return*/];
  1031. }
  1032. if (!messaging.deliveryMetricsExportedToBigQueryEnabled) return [3 /*break*/, 2];
  1033. return [4 /*yield*/, stageLog(messaging, internalPayload)];
  1034. case 1:
  1035. _a.sent();
  1036. _a.label = 2;
  1037. case 2: return [4 /*yield*/, getClientList()];
  1038. case 3:
  1039. clientList = _a.sent();
  1040. if (hasVisibleClients(clientList)) {
  1041. return [2 /*return*/, sendMessagePayloadInternalToWindows(clientList, internalPayload)];
  1042. }
  1043. if (!!!internalPayload.notification) return [3 /*break*/, 5];
  1044. return [4 /*yield*/, showNotification(wrapInternalPayload(internalPayload))];
  1045. case 4:
  1046. _a.sent();
  1047. _a.label = 5;
  1048. case 5:
  1049. if (!messaging) {
  1050. return [2 /*return*/];
  1051. }
  1052. if (!!!messaging.onBackgroundMessageHandler) return [3 /*break*/, 8];
  1053. payload = externalizePayload(internalPayload);
  1054. if (!(typeof messaging.onBackgroundMessageHandler === 'function')) return [3 /*break*/, 7];
  1055. return [4 /*yield*/, messaging.onBackgroundMessageHandler(payload)];
  1056. case 6:
  1057. _a.sent();
  1058. return [3 /*break*/, 8];
  1059. case 7:
  1060. messaging.onBackgroundMessageHandler.next(payload);
  1061. _a.label = 8;
  1062. case 8: return [2 /*return*/];
  1063. }
  1064. });
  1065. });
  1066. }
  1067. function onNotificationClick(event) {
  1068. var _a, _b;
  1069. return tslib.__awaiter(this, void 0, void 0, function () {
  1070. var internalPayload, link, url, originUrl, client;
  1071. return tslib.__generator(this, function (_c) {
  1072. switch (_c.label) {
  1073. case 0:
  1074. internalPayload = (_b = (_a = event.notification) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b[FCM_MSG];
  1075. if (!internalPayload) {
  1076. return [2 /*return*/];
  1077. }
  1078. else if (event.action) {
  1079. // User clicked on an action button. This will allow developers to act on action button clicks
  1080. // by using a custom onNotificationClick listener that they define.
  1081. return [2 /*return*/];
  1082. }
  1083. // Prevent other listeners from receiving the event
  1084. event.stopImmediatePropagation();
  1085. event.notification.close();
  1086. link = getLink(internalPayload);
  1087. if (!link) {
  1088. return [2 /*return*/];
  1089. }
  1090. url = new URL(link, self.location.href);
  1091. originUrl = new URL(self.location.origin);
  1092. if (url.host !== originUrl.host) {
  1093. return [2 /*return*/];
  1094. }
  1095. return [4 /*yield*/, getWindowClient(url)];
  1096. case 1:
  1097. client = _c.sent();
  1098. if (!!client) return [3 /*break*/, 4];
  1099. return [4 /*yield*/, self.clients.openWindow(link)];
  1100. case 2:
  1101. client = _c.sent();
  1102. // Wait three seconds for the client to initialize and set up the message handler so that it
  1103. // can receive the message.
  1104. return [4 /*yield*/, sleep(3000)];
  1105. case 3:
  1106. // Wait three seconds for the client to initialize and set up the message handler so that it
  1107. // can receive the message.
  1108. _c.sent();
  1109. return [3 /*break*/, 6];
  1110. case 4: return [4 /*yield*/, client.focus()];
  1111. case 5:
  1112. client = _c.sent();
  1113. _c.label = 6;
  1114. case 6:
  1115. if (!client) {
  1116. // Window Client will not be returned if it's for a third party origin.
  1117. return [2 /*return*/];
  1118. }
  1119. internalPayload.messageType = MessageType.NOTIFICATION_CLICKED;
  1120. internalPayload.isFirebaseMessaging = true;
  1121. return [2 /*return*/, client.postMessage(internalPayload)];
  1122. }
  1123. });
  1124. });
  1125. }
  1126. function wrapInternalPayload(internalPayload) {
  1127. var _a;
  1128. var wrappedInternalPayload = tslib.__assign({}, internalPayload.notification);
  1129. // Put the message payload under FCM_MSG name so we can identify the notification as being an FCM
  1130. // notification vs a notification from somewhere else (i.e. normal web push or developer generated
  1131. // notification).
  1132. wrappedInternalPayload.data = (_a = {},
  1133. _a[FCM_MSG] = internalPayload,
  1134. _a);
  1135. return wrappedInternalPayload;
  1136. }
  1137. function getMessagePayloadInternal(_a) {
  1138. var data = _a.data;
  1139. if (!data) {
  1140. return null;
  1141. }
  1142. try {
  1143. return data.json();
  1144. }
  1145. catch (err) {
  1146. // Not JSON so not an FCM message.
  1147. return null;
  1148. }
  1149. }
  1150. /**
  1151. * @param url The URL to look for when focusing a client.
  1152. * @return Returns an existing window client or a newly opened WindowClient.
  1153. */
  1154. function getWindowClient(url) {
  1155. return tslib.__awaiter(this, void 0, void 0, function () {
  1156. var clientList, clientList_1, clientList_1_1, client, clientUrl;
  1157. var e_1, _a;
  1158. return tslib.__generator(this, function (_b) {
  1159. switch (_b.label) {
  1160. case 0: return [4 /*yield*/, getClientList()];
  1161. case 1:
  1162. clientList = _b.sent();
  1163. try {
  1164. for (clientList_1 = tslib.__values(clientList), clientList_1_1 = clientList_1.next(); !clientList_1_1.done; clientList_1_1 = clientList_1.next()) {
  1165. client = clientList_1_1.value;
  1166. clientUrl = new URL(client.url, self.location.href);
  1167. if (url.host === clientUrl.host) {
  1168. return [2 /*return*/, client];
  1169. }
  1170. }
  1171. }
  1172. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  1173. finally {
  1174. try {
  1175. if (clientList_1_1 && !clientList_1_1.done && (_a = clientList_1.return)) _a.call(clientList_1);
  1176. }
  1177. finally { if (e_1) throw e_1.error; }
  1178. }
  1179. return [2 /*return*/, null];
  1180. }
  1181. });
  1182. });
  1183. }
  1184. /**
  1185. * @returns If there is currently a visible WindowClient, this method will resolve to true,
  1186. * otherwise false.
  1187. */
  1188. function hasVisibleClients(clientList) {
  1189. return clientList.some(function (client) {
  1190. return client.visibilityState === 'visible' &&
  1191. // Ignore chrome-extension clients as that matches the background pages of extensions, which
  1192. // are always considered visible for some reason.
  1193. !client.url.startsWith('chrome-extension://');
  1194. });
  1195. }
  1196. function sendMessagePayloadInternalToWindows(clientList, internalPayload) {
  1197. var e_2, _a;
  1198. internalPayload.isFirebaseMessaging = true;
  1199. internalPayload.messageType = MessageType.PUSH_RECEIVED;
  1200. try {
  1201. for (var clientList_2 = tslib.__values(clientList), clientList_2_1 = clientList_2.next(); !clientList_2_1.done; clientList_2_1 = clientList_2.next()) {
  1202. var client = clientList_2_1.value;
  1203. client.postMessage(internalPayload);
  1204. }
  1205. }
  1206. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  1207. finally {
  1208. try {
  1209. if (clientList_2_1 && !clientList_2_1.done && (_a = clientList_2.return)) _a.call(clientList_2);
  1210. }
  1211. finally { if (e_2) throw e_2.error; }
  1212. }
  1213. }
  1214. function getClientList() {
  1215. return self.clients.matchAll({
  1216. type: 'window',
  1217. includeUncontrolled: true
  1218. // TS doesn't know that "type: 'window'" means it'll return WindowClient[]
  1219. });
  1220. }
  1221. function showNotification(notificationPayloadInternal) {
  1222. var _a;
  1223. // Note: Firefox does not support the maxActions property.
  1224. // https://developer.mozilla.org/en-US/docs/Web/API/notification/maxActions
  1225. var actions = notificationPayloadInternal.actions;
  1226. var maxActions = Notification.maxActions;
  1227. if (actions && maxActions && actions.length > maxActions) {
  1228. console.warn("This browser only supports ".concat(maxActions, " actions. The remaining actions will not be displayed."));
  1229. }
  1230. return self.registration.showNotification(
  1231. /* title= */ (_a = notificationPayloadInternal.title) !== null && _a !== void 0 ? _a : '', notificationPayloadInternal);
  1232. }
  1233. function getLink(payload) {
  1234. var _a, _b, _c;
  1235. // eslint-disable-next-line camelcase
  1236. 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;
  1237. if (link) {
  1238. return link;
  1239. }
  1240. if (isConsoleMessage(payload.data)) {
  1241. // Notification created in the Firebase Console. Redirect to origin.
  1242. return self.location.origin;
  1243. }
  1244. else {
  1245. return null;
  1246. }
  1247. }
  1248. /**
  1249. * @license
  1250. * Copyright 2019 Google LLC
  1251. *
  1252. * Licensed under the Apache License, Version 2.0 (the "License");
  1253. * you may not use this file except in compliance with the License.
  1254. * You may obtain a copy of the License at
  1255. *
  1256. * http://www.apache.org/licenses/LICENSE-2.0
  1257. *
  1258. * Unless required by applicable law or agreed to in writing, software
  1259. * distributed under the License is distributed on an "AS IS" BASIS,
  1260. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1261. * See the License for the specific language governing permissions and
  1262. * limitations under the License.
  1263. */
  1264. function extractAppConfig(app) {
  1265. var e_1, _a;
  1266. if (!app || !app.options) {
  1267. throw getMissingValueError('App Configuration Object');
  1268. }
  1269. if (!app.name) {
  1270. throw getMissingValueError('App Name');
  1271. }
  1272. // Required app config keys
  1273. var configKeys = [
  1274. 'projectId',
  1275. 'apiKey',
  1276. 'appId',
  1277. 'messagingSenderId'
  1278. ];
  1279. var options = app.options;
  1280. try {
  1281. for (var configKeys_1 = tslib.__values(configKeys), configKeys_1_1 = configKeys_1.next(); !configKeys_1_1.done; configKeys_1_1 = configKeys_1.next()) {
  1282. var keyName = configKeys_1_1.value;
  1283. if (!options[keyName]) {
  1284. throw getMissingValueError(keyName);
  1285. }
  1286. }
  1287. }
  1288. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  1289. finally {
  1290. try {
  1291. if (configKeys_1_1 && !configKeys_1_1.done && (_a = configKeys_1.return)) _a.call(configKeys_1);
  1292. }
  1293. finally { if (e_1) throw e_1.error; }
  1294. }
  1295. return {
  1296. appName: app.name,
  1297. projectId: options.projectId,
  1298. apiKey: options.apiKey,
  1299. appId: options.appId,
  1300. senderId: options.messagingSenderId
  1301. };
  1302. }
  1303. function getMissingValueError(valueName) {
  1304. return ERROR_FACTORY.create("missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {
  1305. valueName: valueName
  1306. });
  1307. }
  1308. /**
  1309. * @license
  1310. * Copyright 2020 Google LLC
  1311. *
  1312. * Licensed under the Apache License, Version 2.0 (the "License");
  1313. * you may not use this file except in compliance with the License.
  1314. * You may obtain a copy of the License at
  1315. *
  1316. * http://www.apache.org/licenses/LICENSE-2.0
  1317. *
  1318. * Unless required by applicable law or agreed to in writing, software
  1319. * distributed under the License is distributed on an "AS IS" BASIS,
  1320. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1321. * See the License for the specific language governing permissions and
  1322. * limitations under the License.
  1323. */
  1324. var MessagingService = /** @class */ (function () {
  1325. function MessagingService(app, installations, analyticsProvider) {
  1326. // logging is only done with end user consent. Default to false.
  1327. this.deliveryMetricsExportedToBigQueryEnabled = false;
  1328. this.onBackgroundMessageHandler = null;
  1329. this.onMessageHandler = null;
  1330. this.logEvents = [];
  1331. this.isLogServiceStarted = false;
  1332. var appConfig = extractAppConfig(app);
  1333. this.firebaseDependencies = {
  1334. app: app,
  1335. appConfig: appConfig,
  1336. installations: installations,
  1337. analyticsProvider: analyticsProvider
  1338. };
  1339. }
  1340. MessagingService.prototype._delete = function () {
  1341. return Promise.resolve();
  1342. };
  1343. return MessagingService;
  1344. }());
  1345. /**
  1346. * @license
  1347. * Copyright 2020 Google LLC
  1348. *
  1349. * Licensed under the Apache License, Version 2.0 (the "License");
  1350. * you may not use this file except in compliance with the License.
  1351. * You may obtain a copy of the License at
  1352. *
  1353. * http://www.apache.org/licenses/LICENSE-2.0
  1354. *
  1355. * Unless required by applicable law or agreed to in writing, software
  1356. * distributed under the License is distributed on an "AS IS" BASIS,
  1357. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1358. * See the License for the specific language governing permissions and
  1359. * limitations under the License.
  1360. */
  1361. var SwMessagingFactory = function (container) {
  1362. var messaging = new MessagingService(container.getProvider('app').getImmediate(), container.getProvider('installations-internal').getImmediate(), container.getProvider('analytics-internal'));
  1363. self.addEventListener('push', function (e) {
  1364. e.waitUntil(onPush(e, messaging));
  1365. });
  1366. self.addEventListener('pushsubscriptionchange', function (e) {
  1367. e.waitUntil(onSubChange(e, messaging));
  1368. });
  1369. self.addEventListener('notificationclick', function (e) {
  1370. e.waitUntil(onNotificationClick(e));
  1371. });
  1372. return messaging;
  1373. };
  1374. /**
  1375. * The messaging instance registered in sw is named differently than that of in client. This is
  1376. * because both `registerMessagingInWindow` and `registerMessagingInSw` would be called in
  1377. * `messaging-compat` and component with the same name can only be registered once.
  1378. */
  1379. function registerMessagingInSw() {
  1380. app._registerComponent(new component.Component('messaging-sw', SwMessagingFactory, "PUBLIC" /* ComponentType.PUBLIC */));
  1381. }
  1382. /**
  1383. * @license
  1384. * Copyright 2020 Google LLC
  1385. *
  1386. * Licensed under the Apache License, Version 2.0 (the "License");
  1387. * you may not use this file except in compliance with the License.
  1388. * You may obtain a copy of the License at
  1389. *
  1390. * http://www.apache.org/licenses/LICENSE-2.0
  1391. *
  1392. * Unless required by applicable law or agreed to in writing, software
  1393. * distributed under the License is distributed on an "AS IS" BASIS,
  1394. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1395. * See the License for the specific language governing permissions and
  1396. * limitations under the License.
  1397. */
  1398. /**
  1399. * Checks whether all required APIs exist within SW Context
  1400. * @returns a Promise that resolves to a boolean.
  1401. *
  1402. * @public
  1403. */
  1404. function isSwSupported() {
  1405. return tslib.__awaiter(this, void 0, void 0, function () {
  1406. var _a;
  1407. return tslib.__generator(this, function (_b) {
  1408. switch (_b.label) {
  1409. case 0:
  1410. _a = util.isIndexedDBAvailable();
  1411. if (!_a) return [3 /*break*/, 2];
  1412. return [4 /*yield*/, util.validateIndexedDBOpenable()];
  1413. case 1:
  1414. _a = (_b.sent());
  1415. _b.label = 2;
  1416. case 2:
  1417. // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing
  1418. // might be prohibited to run. In these contexts, an error would be thrown during the messaging
  1419. // instantiating phase, informing the developers to import/call isSupported for special handling.
  1420. return [2 /*return*/, (_a &&
  1421. 'PushManager' in self &&
  1422. 'Notification' in self &&
  1423. ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&
  1424. PushSubscription.prototype.hasOwnProperty('getKey'))];
  1425. }
  1426. });
  1427. });
  1428. }
  1429. /**
  1430. * @license
  1431. * Copyright 2020 Google LLC
  1432. *
  1433. * Licensed under the Apache License, Version 2.0 (the "License");
  1434. * you may not use this file except in compliance with the License.
  1435. * You may obtain a copy of the License at
  1436. *
  1437. * http://www.apache.org/licenses/LICENSE-2.0
  1438. *
  1439. * Unless required by applicable law or agreed to in writing, software
  1440. * distributed under the License is distributed on an "AS IS" BASIS,
  1441. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1442. * See the License for the specific language governing permissions and
  1443. * limitations under the License.
  1444. */
  1445. function onBackgroundMessage$1(messaging, nextOrObserver) {
  1446. if (self.document !== undefined) {
  1447. throw ERROR_FACTORY.create("only-available-in-sw" /* ErrorCode.AVAILABLE_IN_SW */);
  1448. }
  1449. messaging.onBackgroundMessageHandler = nextOrObserver;
  1450. return function () {
  1451. messaging.onBackgroundMessageHandler = null;
  1452. };
  1453. }
  1454. /**
  1455. * @license
  1456. * Copyright 2020 Google LLC
  1457. *
  1458. * Licensed under the Apache License, Version 2.0 (the "License");
  1459. * you may not use this file except in compliance with the License.
  1460. * You may obtain a copy of the License at
  1461. *
  1462. * http://www.apache.org/licenses/LICENSE-2.0
  1463. *
  1464. * Unless required by applicable law or agreed to in writing, software
  1465. * distributed under the License is distributed on an "AS IS" BASIS,
  1466. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1467. * See the License for the specific language governing permissions and
  1468. * limitations under the License.
  1469. */
  1470. function _setDeliveryMetricsExportedToBigQueryEnabled(messaging, enable) {
  1471. messaging.deliveryMetricsExportedToBigQueryEnabled =
  1472. enable;
  1473. }
  1474. /**
  1475. * @license
  1476. * Copyright 2017 Google LLC
  1477. *
  1478. * Licensed under the Apache License, Version 2.0 (the "License");
  1479. * you may not use this file except in compliance with the License.
  1480. * You may obtain a copy of the License at
  1481. *
  1482. * http://www.apache.org/licenses/LICENSE-2.0
  1483. *
  1484. * Unless required by applicable law or agreed to in writing, software
  1485. * distributed under the License is distributed on an "AS IS" BASIS,
  1486. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1487. * See the License for the specific language governing permissions and
  1488. * limitations under the License.
  1489. */
  1490. /**
  1491. * Retrieves a Firebase Cloud Messaging instance.
  1492. *
  1493. * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.
  1494. *
  1495. * @public
  1496. */
  1497. function getMessagingInSw(app$1) {
  1498. if (app$1 === void 0) { app$1 = app.getApp(); }
  1499. // Conscious decision to make this async check non-blocking during the messaging instance
  1500. // initialization phase for performance consideration. An error would be thrown latter for
  1501. // developer's information. Developers can then choose to import and call `isSupported` for
  1502. // special handling.
  1503. isSwSupported().then(function (isSupported) {
  1504. // If `isSwSupported()` resolved, but returned false.
  1505. if (!isSupported) {
  1506. throw ERROR_FACTORY.create("unsupported-browser" /* ErrorCode.UNSUPPORTED_BROWSER */);
  1507. }
  1508. }, function (_) {
  1509. // If `isSwSupported()` rejected.
  1510. throw ERROR_FACTORY.create("indexed-db-unsupported" /* ErrorCode.INDEXED_DB_UNSUPPORTED */);
  1511. });
  1512. return app._getProvider(util.getModularInstance(app$1), 'messaging-sw').getImmediate();
  1513. }
  1514. /**
  1515. * Called when a message is received while the app is in the background. An app is considered to be
  1516. * in the background if no active window is displayed.
  1517. *
  1518. * @param messaging - The {@link Messaging} instance.
  1519. * @param nextOrObserver - This function, or observer object with `next` defined, is called when a
  1520. * message is received and the app is currently in the background.
  1521. *
  1522. * @returns To stop listening for messages execute this returned function
  1523. *
  1524. * @public
  1525. */
  1526. function onBackgroundMessage(messaging, nextOrObserver) {
  1527. messaging = util.getModularInstance(messaging);
  1528. return onBackgroundMessage$1(messaging, nextOrObserver);
  1529. }
  1530. /**
  1531. * Enables or disables Firebase Cloud Messaging message delivery metrics export to BigQuery. By
  1532. * default, message delivery metrics are not exported to BigQuery. Use this method to enable or
  1533. * disable the export at runtime.
  1534. *
  1535. * @param messaging - The `FirebaseMessaging` instance.
  1536. * @param enable - Whether Firebase Cloud Messaging should export message delivery metrics to
  1537. * BigQuery.
  1538. *
  1539. * @public
  1540. */
  1541. function experimentalSetDeliveryMetricsExportedToBigQueryEnabled(messaging, enable) {
  1542. messaging = util.getModularInstance(messaging);
  1543. return _setDeliveryMetricsExportedToBigQueryEnabled(messaging, enable);
  1544. }
  1545. /**
  1546. * @license
  1547. * Copyright 2017 Google LLC
  1548. *
  1549. * Licensed under the Apache License, Version 2.0 (the "License");
  1550. * you may not use this file except in compliance with the License.
  1551. * You may obtain a copy of the License at
  1552. *
  1553. * http://www.apache.org/licenses/LICENSE-2.0
  1554. *
  1555. * Unless required by applicable law or agreed to in writing, software
  1556. * distributed under the License is distributed on an "AS IS" BASIS,
  1557. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1558. * See the License for the specific language governing permissions and
  1559. * limitations under the License.
  1560. */
  1561. registerMessagingInSw();
  1562. exports.experimentalSetDeliveryMetricsExportedToBigQueryEnabled = experimentalSetDeliveryMetricsExportedToBigQueryEnabled;
  1563. exports.getMessaging = getMessagingInSw;
  1564. exports.isSupported = isSwSupported;
  1565. exports.onBackgroundMessage = onBackgroundMessage;
  1566. //# sourceMappingURL=index.sw.cjs.map