暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

index.cjs.js 66KB

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