@firebase/messaging 0.12.13 → 0.12.14-canary.1294e64c8

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