UNPKG

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