@depup/firebase__messaging 0.12.24-depup.0

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