datastake-daf 0.6.701 → 0.6.702

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.
@@ -14,6 +14,8 @@ var lodash = require('lodash');
14
14
  var PropTypes = require('prop-types');
15
15
  var reactIs = require('react-is');
16
16
  require('react-dom');
17
+ var app = require('firebase/app');
18
+ var messaging = require('firebase/messaging');
17
19
 
18
20
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
19
21
 
@@ -1212,7 +1214,7 @@ const isProxy = () => {
1212
1214
  }
1213
1215
  return false;
1214
1216
  };
1215
- const getToken$3 = () => isProxy() ? StorageManager.get('proxy_token') : StorageManager.get('token');
1217
+ const getToken = () => isProxy() ? StorageManager.get('proxy_token') : StorageManager.get('token');
1216
1218
 
1217
1219
  /**
1218
1220
  * Custom params serializer to maintain JSON format for nested objects
@@ -1253,7 +1255,7 @@ class BaseHTTPService {
1253
1255
  timeout = 300000,
1254
1256
  customAxiosConfig = {}
1255
1257
  } = config;
1256
- this.getToken = getToken$3 || (() => null);
1258
+ this.getToken = getToken || (() => null);
1257
1259
  this.getHeaders = getHeaders || (() => ({}));
1258
1260
  this.getBaseURL = getBaseURL || (() => null);
1259
1261
  this.onError = onError || (() => null);
@@ -1594,7 +1596,7 @@ class BaseService extends BaseHTTPService {
1594
1596
 
1595
1597
  // Call super with lazy getters that fetch config at runtime
1596
1598
  super({
1597
- getToken: () => getToken$3(),
1599
+ getToken: () => getToken(),
1598
1600
  getHeaders: () => {
1599
1601
  const config = getServicesConfig();
1600
1602
  return {
@@ -1988,7 +1990,7 @@ var platform = 'browser';
1988
1990
  var browser = true;
1989
1991
  var env = {};
1990
1992
  var argv = [];
1991
- var version$3 = ''; // empty string to avoid regexp issues
1993
+ var version = ''; // empty string to avoid regexp issues
1992
1994
  var versions = {};
1993
1995
  var release = {};
1994
1996
  var config = {};
@@ -2052,7 +2054,7 @@ var browser$1 = {
2052
2054
  browser: browser,
2053
2055
  env: env,
2054
2056
  argv: argv,
2055
- version: version$3,
2057
+ version: version,
2056
2058
  versions: versions,
2057
2059
  on: on,
2058
2060
  addListener: addListener,
@@ -2143,4662 +2145,21 @@ const usePermissions = ({
2143
2145
  return value;
2144
2146
  };
2145
2147
 
2146
- const getDefaultsFromPostinstall = () => (undefined);
2147
-
2148
- /**
2149
- * @license
2150
- * Copyright 2017 Google LLC
2151
- *
2152
- * Licensed under the Apache License, Version 2.0 (the "License");
2153
- * you may not use this file except in compliance with the License.
2154
- * You may obtain a copy of the License at
2155
- *
2156
- * http://www.apache.org/licenses/LICENSE-2.0
2157
- *
2158
- * Unless required by applicable law or agreed to in writing, software
2159
- * distributed under the License is distributed on an "AS IS" BASIS,
2160
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2161
- * See the License for the specific language governing permissions and
2162
- * limitations under the License.
2163
- */
2164
- const stringToByteArray$1 = function (str) {
2165
- // TODO(user): Use native implementations if/when available
2166
- const out = [];
2167
- let p = 0;
2168
- for (let i = 0; i < str.length; i++) {
2169
- let c = str.charCodeAt(i);
2170
- if (c < 128) {
2171
- out[p++] = c;
2172
- }
2173
- else if (c < 2048) {
2174
- out[p++] = (c >> 6) | 192;
2175
- out[p++] = (c & 63) | 128;
2176
- }
2177
- else if ((c & 0xfc00) === 0xd800 &&
2178
- i + 1 < str.length &&
2179
- (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
2180
- // Surrogate Pair
2181
- c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);
2182
- out[p++] = (c >> 18) | 240;
2183
- out[p++] = ((c >> 12) & 63) | 128;
2184
- out[p++] = ((c >> 6) & 63) | 128;
2185
- out[p++] = (c & 63) | 128;
2186
- }
2187
- else {
2188
- out[p++] = (c >> 12) | 224;
2189
- out[p++] = ((c >> 6) & 63) | 128;
2190
- out[p++] = (c & 63) | 128;
2191
- }
2192
- }
2193
- return out;
2194
- };
2195
- /**
2196
- * Turns an array of numbers into the string given by the concatenation of the
2197
- * characters to which the numbers correspond.
2198
- * @param bytes Array of numbers representing characters.
2199
- * @return Stringification of the array.
2200
- */
2201
- const byteArrayToString = function (bytes) {
2202
- // TODO(user): Use native implementations if/when available
2203
- const out = [];
2204
- let pos = 0, c = 0;
2205
- while (pos < bytes.length) {
2206
- const c1 = bytes[pos++];
2207
- if (c1 < 128) {
2208
- out[c++] = String.fromCharCode(c1);
2209
- }
2210
- else if (c1 > 191 && c1 < 224) {
2211
- const c2 = bytes[pos++];
2212
- out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
2213
- }
2214
- else if (c1 > 239 && c1 < 365) {
2215
- // Surrogate Pair
2216
- const c2 = bytes[pos++];
2217
- const c3 = bytes[pos++];
2218
- const c4 = bytes[pos++];
2219
- const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -
2220
- 0x10000;
2221
- out[c++] = String.fromCharCode(0xd800 + (u >> 10));
2222
- out[c++] = String.fromCharCode(0xdc00 + (u & 1023));
2223
- }
2224
- else {
2225
- const c2 = bytes[pos++];
2226
- const c3 = bytes[pos++];
2227
- out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
2228
- }
2229
- }
2230
- return out.join('');
2231
- };
2232
- // We define it as an object literal instead of a class because a class compiled down to es5 can't
2233
- // be treeshaked. https://github.com/rollup/rollup/issues/1691
2234
- // Static lookup maps, lazily populated by init_()
2235
- // TODO(dlarocque): Define this as a class, since we no longer target ES5.
2236
- const base64 = {
2237
- /**
2238
- * Maps bytes to characters.
2239
- */
2240
- byteToCharMap_: null,
2241
- /**
2242
- * Maps characters to bytes.
2243
- */
2244
- charToByteMap_: null,
2245
- /**
2246
- * Maps bytes to websafe characters.
2247
- * @private
2248
- */
2249
- byteToCharMapWebSafe_: null,
2250
- /**
2251
- * Maps websafe characters to bytes.
2252
- * @private
2253
- */
2254
- charToByteMapWebSafe_: null,
2255
- /**
2256
- * Our default alphabet, shared between
2257
- * ENCODED_VALS and ENCODED_VALS_WEBSAFE
2258
- */
2259
- ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',
2260
- /**
2261
- * Our default alphabet. Value 64 (=) is special; it means "nothing."
2262
- */
2263
- get ENCODED_VALS() {
2264
- return this.ENCODED_VALS_BASE + '+/=';
2265
- },
2266
- /**
2267
- * Our websafe alphabet.
2268
- */
2269
- get ENCODED_VALS_WEBSAFE() {
2270
- return this.ENCODED_VALS_BASE + '-_.';
2271
- },
2272
- /**
2273
- * Whether this browser supports the atob and btoa functions. This extension
2274
- * started at Mozilla but is now implemented by many browsers. We use the
2275
- * ASSUME_* variables to avoid pulling in the full useragent detection library
2276
- * but still allowing the standard per-browser compilations.
2277
- *
2278
- */
2279
- HAS_NATIVE_SUPPORT: typeof atob === 'function',
2280
- /**
2281
- * Base64-encode an array of bytes.
2282
- *
2283
- * @param input An array of bytes (numbers with
2284
- * value in [0, 255]) to encode.
2285
- * @param webSafe Boolean indicating we should use the
2286
- * alternative alphabet.
2287
- * @return The base64 encoded string.
2288
- */
2289
- encodeByteArray(input, webSafe) {
2290
- if (!Array.isArray(input)) {
2291
- throw Error('encodeByteArray takes an array as a parameter');
2292
- }
2293
- this.init_();
2294
- const byteToCharMap = webSafe
2295
- ? this.byteToCharMapWebSafe_
2296
- : this.byteToCharMap_;
2297
- const output = [];
2298
- for (let i = 0; i < input.length; i += 3) {
2299
- const byte1 = input[i];
2300
- const haveByte2 = i + 1 < input.length;
2301
- const byte2 = haveByte2 ? input[i + 1] : 0;
2302
- const haveByte3 = i + 2 < input.length;
2303
- const byte3 = haveByte3 ? input[i + 2] : 0;
2304
- const outByte1 = byte1 >> 2;
2305
- const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
2306
- let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);
2307
- let outByte4 = byte3 & 0x3f;
2308
- if (!haveByte3) {
2309
- outByte4 = 64;
2310
- if (!haveByte2) {
2311
- outByte3 = 64;
2312
- }
2313
- }
2314
- output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);
2315
- }
2316
- return output.join('');
2317
- },
2318
- /**
2319
- * Base64-encode a string.
2320
- *
2321
- * @param input A string to encode.
2322
- * @param webSafe If true, we should use the
2323
- * alternative alphabet.
2324
- * @return The base64 encoded string.
2325
- */
2326
- encodeString(input, webSafe) {
2327
- // Shortcut for Mozilla browsers that implement
2328
- // a native base64 encoder in the form of "btoa/atob"
2329
- if (this.HAS_NATIVE_SUPPORT && !webSafe) {
2330
- return btoa(input);
2331
- }
2332
- return this.encodeByteArray(stringToByteArray$1(input), webSafe);
2333
- },
2334
- /**
2335
- * Base64-decode a string.
2336
- *
2337
- * @param input to decode.
2338
- * @param webSafe True if we should use the
2339
- * alternative alphabet.
2340
- * @return string representing the decoded value.
2341
- */
2342
- decodeString(input, webSafe) {
2343
- // Shortcut for Mozilla browsers that implement
2344
- // a native base64 encoder in the form of "btoa/atob"
2345
- if (this.HAS_NATIVE_SUPPORT && !webSafe) {
2346
- return atob(input);
2347
- }
2348
- return byteArrayToString(this.decodeStringToByteArray(input, webSafe));
2349
- },
2350
- /**
2351
- * Base64-decode a string.
2352
- *
2353
- * In base-64 decoding, groups of four characters are converted into three
2354
- * bytes. If the encoder did not apply padding, the input length may not
2355
- * be a multiple of 4.
2356
- *
2357
- * In this case, the last group will have fewer than 4 characters, and
2358
- * padding will be inferred. If the group has one or two characters, it decodes
2359
- * to one byte. If the group has three characters, it decodes to two bytes.
2360
- *
2361
- * @param input Input to decode.
2362
- * @param webSafe True if we should use the web-safe alphabet.
2363
- * @return bytes representing the decoded value.
2364
- */
2365
- decodeStringToByteArray(input, webSafe) {
2366
- this.init_();
2367
- const charToByteMap = webSafe
2368
- ? this.charToByteMapWebSafe_
2369
- : this.charToByteMap_;
2370
- const output = [];
2371
- for (let i = 0; i < input.length;) {
2372
- const byte1 = charToByteMap[input.charAt(i++)];
2373
- const haveByte2 = i < input.length;
2374
- const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;
2375
- ++i;
2376
- const haveByte3 = i < input.length;
2377
- const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;
2378
- ++i;
2379
- const haveByte4 = i < input.length;
2380
- const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;
2381
- ++i;
2382
- if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {
2383
- throw new DecodeBase64StringError();
2384
- }
2385
- const outByte1 = (byte1 << 2) | (byte2 >> 4);
2386
- output.push(outByte1);
2387
- if (byte3 !== 64) {
2388
- const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);
2389
- output.push(outByte2);
2390
- if (byte4 !== 64) {
2391
- const outByte3 = ((byte3 << 6) & 0xc0) | byte4;
2392
- output.push(outByte3);
2393
- }
2394
- }
2395
- }
2396
- return output;
2397
- },
2398
- /**
2399
- * Lazy static initialization function. Called before
2400
- * accessing any of the static map variables.
2401
- * @private
2402
- */
2403
- init_() {
2404
- if (!this.byteToCharMap_) {
2405
- this.byteToCharMap_ = {};
2406
- this.charToByteMap_ = {};
2407
- this.byteToCharMapWebSafe_ = {};
2408
- this.charToByteMapWebSafe_ = {};
2409
- // We want quick mappings back and forth, so we precompute two maps.
2410
- for (let i = 0; i < this.ENCODED_VALS.length; i++) {
2411
- this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);
2412
- this.charToByteMap_[this.byteToCharMap_[i]] = i;
2413
- this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);
2414
- this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;
2415
- // Be forgiving when decoding and correctly decode both encodings.
2416
- if (i >= this.ENCODED_VALS_BASE.length) {
2417
- this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;
2418
- this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;
2419
- }
2420
- }
2421
- }
2422
- }
2423
- };
2424
- /**
2425
- * An error encountered while decoding base64 string.
2426
- */
2427
- class DecodeBase64StringError extends Error {
2428
- constructor() {
2429
- super(...arguments);
2430
- this.name = 'DecodeBase64StringError';
2431
- }
2432
- }
2433
- /**
2434
- * URL-safe base64 encoding
2435
- */
2436
- const base64Encode = function (str) {
2437
- const utf8Bytes = stringToByteArray$1(str);
2438
- return base64.encodeByteArray(utf8Bytes, true);
2439
- };
2440
- /**
2441
- * URL-safe base64 encoding (without "." padding in the end).
2442
- * e.g. Used in JSON Web Token (JWT) parts.
2443
- */
2444
- const base64urlEncodeWithoutPadding = function (str) {
2445
- // Use base64url encoding and remove padding in the end (dot characters).
2446
- return base64Encode(str).replace(/\./g, '');
2447
- };
2448
- /**
2449
- * URL-safe base64 decoding
2450
- *
2451
- * NOTE: DO NOT use the global atob() function - it does NOT support the
2452
- * base64Url variant encoding.
2453
- *
2454
- * @param str To be decoded
2455
- * @return Decoded result, if possible
2456
- */
2457
- const base64Decode = function (str) {
2458
- try {
2459
- return base64.decodeString(str, true);
2460
- }
2461
- catch (e) {
2462
- console.error('base64Decode failed: ', e);
2463
- }
2464
- return null;
2465
- };
2466
-
2467
- /**
2468
- * @license
2469
- * Copyright 2022 Google LLC
2470
- *
2471
- * Licensed under the Apache License, Version 2.0 (the "License");
2472
- * you may not use this file except in compliance with the License.
2473
- * You may obtain a copy of the License at
2474
- *
2475
- * http://www.apache.org/licenses/LICENSE-2.0
2476
- *
2477
- * Unless required by applicable law or agreed to in writing, software
2478
- * distributed under the License is distributed on an "AS IS" BASIS,
2479
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2480
- * See the License for the specific language governing permissions and
2481
- * limitations under the License.
2482
- */
2483
- /**
2484
- * Polyfill for `globalThis` object.
2485
- * @returns the `globalThis` object for the given environment.
2486
- * @public
2487
- */
2488
- function getGlobal() {
2489
- if (typeof self !== 'undefined') {
2490
- return self;
2491
- }
2492
- if (typeof window !== 'undefined') {
2493
- return window;
2494
- }
2495
- if (typeof global$1 !== 'undefined') {
2496
- return global$1;
2497
- }
2498
- throw new Error('Unable to locate global object.');
2499
- }
2500
-
2501
- /**
2502
- * @license
2503
- * Copyright 2022 Google LLC
2504
- *
2505
- * Licensed under the Apache License, Version 2.0 (the "License");
2506
- * you may not use this file except in compliance with the License.
2507
- * You may obtain a copy of the License at
2508
- *
2509
- * http://www.apache.org/licenses/LICENSE-2.0
2510
- *
2511
- * Unless required by applicable law or agreed to in writing, software
2512
- * distributed under the License is distributed on an "AS IS" BASIS,
2513
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2514
- * See the License for the specific language governing permissions and
2515
- * limitations under the License.
2516
- */
2517
- const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;
2518
- /**
2519
- * Attempt to read defaults from a JSON string provided to
2520
- * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in
2521
- * process(.)env(.)__FIREBASE_DEFAULTS_PATH__
2522
- * The dots are in parens because certain compilers (Vite?) cannot
2523
- * handle seeing that variable in comments.
2524
- * See https://github.com/firebase/firebase-js-sdk/issues/6838
2525
- */
2526
- const getDefaultsFromEnvVariable = () => {
2527
- if (typeof process === 'undefined' || typeof process.env === 'undefined') {
2528
- return;
2529
- }
2530
- const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;
2531
- if (defaultsJsonString) {
2532
- return JSON.parse(defaultsJsonString);
2533
- }
2534
- };
2535
- const getDefaultsFromCookie = () => {
2536
- if (typeof document === 'undefined') {
2537
- return;
2538
- }
2539
- let match;
2540
- try {
2541
- match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);
2542
- }
2543
- catch (e) {
2544
- // Some environments such as Angular Universal SSR have a
2545
- // `document` object but error on accessing `document.cookie`.
2546
- return;
2547
- }
2548
- const decoded = match && base64Decode(match[1]);
2549
- return decoded && JSON.parse(decoded);
2550
- };
2551
- /**
2552
- * Get the __FIREBASE_DEFAULTS__ object. It checks in order:
2553
- * (1) if such an object exists as a property of `globalThis`
2554
- * (2) if such an object was provided on a shell environment variable
2555
- * (3) if such an object exists in a cookie
2556
- * @public
2557
- */
2558
- const getDefaults = () => {
2559
- try {
2560
- return (getDefaultsFromPostinstall() ||
2561
- getDefaultsFromGlobal() ||
2562
- getDefaultsFromEnvVariable() ||
2563
- getDefaultsFromCookie());
2564
- }
2565
- catch (e) {
2566
- /**
2567
- * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due
2568
- * to any environment case we have not accounted for. Log to
2569
- * info instead of swallowing so we can find these unknown cases
2570
- * and add paths for them if needed.
2571
- */
2572
- console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);
2573
- return;
2574
- }
2575
- };
2576
- /**
2577
- * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.
2578
- * @public
2579
- */
2580
- const getDefaultAppConfig = () => getDefaults()?.config;
2581
-
2582
- /**
2583
- * @license
2584
- * Copyright 2017 Google LLC
2585
- *
2586
- * Licensed under the Apache License, Version 2.0 (the "License");
2587
- * you may not use this file except in compliance with the License.
2588
- * You may obtain a copy of the License at
2589
- *
2590
- * http://www.apache.org/licenses/LICENSE-2.0
2591
- *
2592
- * Unless required by applicable law or agreed to in writing, software
2593
- * distributed under the License is distributed on an "AS IS" BASIS,
2594
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2595
- * See the License for the specific language governing permissions and
2596
- * limitations under the License.
2597
- */
2598
- class Deferred {
2599
- constructor() {
2600
- this.reject = () => { };
2601
- this.resolve = () => { };
2602
- this.promise = new Promise((resolve, reject) => {
2603
- this.resolve = resolve;
2604
- this.reject = reject;
2605
- });
2606
- }
2607
- /**
2608
- * Our API internals are not promisified and cannot because our callback APIs have subtle expectations around
2609
- * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback
2610
- * and returns a node-style callback which will resolve or reject the Deferred's promise.
2611
- */
2612
- wrapCallback(callback) {
2613
- return (error, value) => {
2614
- if (error) {
2615
- this.reject(error);
2616
- }
2617
- else {
2618
- this.resolve(value);
2619
- }
2620
- if (typeof callback === 'function') {
2621
- // Attaching noop handler just in case developer wasn't expecting
2622
- // promises
2623
- this.promise.catch(() => { });
2624
- // Some of our callbacks don't expect a value and our own tests
2625
- // assert that the parameter length is 1
2626
- if (callback.length === 1) {
2627
- callback(error);
2628
- }
2629
- else {
2630
- callback(error, value);
2631
- }
2632
- }
2633
- };
2634
- }
2635
- }
2636
- /**
2637
- * This method checks if indexedDB is supported by current browser/service worker context
2638
- * @return true if indexedDB is supported by current browser/service worker context
2639
- */
2640
- function isIndexedDBAvailable() {
2641
- try {
2642
- return typeof indexedDB === 'object';
2643
- }
2644
- catch (e) {
2645
- return false;
2646
- }
2647
- }
2648
- /**
2649
- * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject
2650
- * if errors occur during the database open operation.
2651
- *
2652
- * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox
2653
- * private browsing)
2654
- */
2655
- function validateIndexedDBOpenable() {
2656
- return new Promise((resolve, reject) => {
2657
- try {
2658
- let preExist = true;
2659
- const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';
2660
- const request = self.indexedDB.open(DB_CHECK_NAME);
2661
- request.onsuccess = () => {
2662
- request.result.close();
2663
- // delete database only when it doesn't pre-exist
2664
- if (!preExist) {
2665
- self.indexedDB.deleteDatabase(DB_CHECK_NAME);
2666
- }
2667
- resolve(true);
2668
- };
2669
- request.onupgradeneeded = () => {
2670
- preExist = false;
2671
- };
2672
- request.onerror = () => {
2673
- reject(request.error?.message || '');
2674
- };
2675
- }
2676
- catch (error) {
2677
- reject(error);
2678
- }
2679
- });
2680
- }
2681
- /**
2682
- *
2683
- * This method checks whether cookie is enabled within current browser
2684
- * @return true if cookie is enabled within current browser
2685
- */
2686
- function areCookiesEnabled() {
2687
- if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {
2688
- return false;
2689
- }
2690
- return true;
2691
- }
2692
-
2693
- /**
2694
- * @license
2695
- * Copyright 2017 Google LLC
2696
- *
2697
- * Licensed under the Apache License, Version 2.0 (the "License");
2698
- * you may not use this file except in compliance with the License.
2699
- * You may obtain a copy of the License at
2700
- *
2701
- * http://www.apache.org/licenses/LICENSE-2.0
2702
- *
2703
- * Unless required by applicable law or agreed to in writing, software
2704
- * distributed under the License is distributed on an "AS IS" BASIS,
2705
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2706
- * See the License for the specific language governing permissions and
2707
- * limitations under the License.
2708
- */
2709
- /**
2710
- * @fileoverview Standardized Firebase Error.
2711
- *
2712
- * Usage:
2713
- *
2714
- * // TypeScript string literals for type-safe codes
2715
- * type Err =
2716
- * 'unknown' |
2717
- * 'object-not-found'
2718
- * ;
2719
- *
2720
- * // Closure enum for type-safe error codes
2721
- * // at-enum {string}
2722
- * var Err = {
2723
- * UNKNOWN: 'unknown',
2724
- * OBJECT_NOT_FOUND: 'object-not-found',
2725
- * }
2726
- *
2727
- * let errors: Map<Err, string> = {
2728
- * 'generic-error': "Unknown error",
2729
- * 'file-not-found': "Could not find file: {$file}",
2730
- * };
2731
- *
2732
- * // Type-safe function - must pass a valid error code as param.
2733
- * let error = new ErrorFactory<Err>('service', 'Service', errors);
2734
- *
2735
- * ...
2736
- * throw error.create(Err.GENERIC);
2737
- * ...
2738
- * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});
2739
- * ...
2740
- * // Service: Could not file file: foo.txt (service/file-not-found).
2741
- *
2742
- * catch (e) {
2743
- * assert(e.message === "Could not find file: foo.txt.");
2744
- * if ((e as FirebaseError)?.code === 'service/file-not-found') {
2745
- * console.log("Could not read file: " + e['file']);
2746
- * }
2747
- * }
2748
- */
2749
- const ERROR_NAME = 'FirebaseError';
2750
- // Based on code from:
2751
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
2752
- class FirebaseError extends Error {
2753
- constructor(
2754
- /** The error code for this error. */
2755
- code, message,
2756
- /** Custom data for this error. */
2757
- customData) {
2758
- super(message);
2759
- this.code = code;
2760
- this.customData = customData;
2761
- /** The custom name for all FirebaseErrors. */
2762
- this.name = ERROR_NAME;
2763
- // Fix For ES5
2764
- // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
2765
- // TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
2766
- // which we can now use since we no longer target ES5.
2767
- Object.setPrototypeOf(this, FirebaseError.prototype);
2768
- // Maintains proper stack trace for where our error was thrown.
2769
- // Only available on V8.
2770
- if (Error.captureStackTrace) {
2771
- Error.captureStackTrace(this, ErrorFactory.prototype.create);
2772
- }
2773
- }
2774
- }
2775
- class ErrorFactory {
2776
- constructor(service, serviceName, errors) {
2777
- this.service = service;
2778
- this.serviceName = serviceName;
2779
- this.errors = errors;
2780
- }
2781
- create(code, ...data) {
2782
- const customData = data[0] || {};
2783
- const fullCode = `${this.service}/${code}`;
2784
- const template = this.errors[code];
2785
- const message = template ? replaceTemplate(template, customData) : 'Error';
2786
- // Service Name: Error message (service/code).
2787
- const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;
2788
- const error = new FirebaseError(fullCode, fullMessage, customData);
2789
- return error;
2790
- }
2791
- }
2792
- function replaceTemplate(template, data) {
2793
- return template.replace(PATTERN, (_, key) => {
2794
- const value = data[key];
2795
- return value != null ? String(value) : `<${key}?>`;
2796
- });
2797
- }
2798
- const PATTERN = /\{\$([^}]+)}/g;
2799
- /**
2800
- * Deep equal two objects. Support Arrays and Objects.
2801
- */
2802
- function deepEqual(a, b) {
2803
- if (a === b) {
2804
- return true;
2805
- }
2806
- const aKeys = Object.keys(a);
2807
- const bKeys = Object.keys(b);
2808
- for (const k of aKeys) {
2809
- if (!bKeys.includes(k)) {
2810
- return false;
2811
- }
2812
- const aProp = a[k];
2813
- const bProp = b[k];
2814
- if (isObject(aProp) && isObject(bProp)) {
2815
- if (!deepEqual(aProp, bProp)) {
2816
- return false;
2817
- }
2818
- }
2819
- else if (aProp !== bProp) {
2820
- return false;
2821
- }
2822
- }
2823
- for (const k of bKeys) {
2824
- if (!aKeys.includes(k)) {
2825
- return false;
2826
- }
2827
- }
2828
- return true;
2829
- }
2830
- function isObject(thing) {
2831
- return thing !== null && typeof thing === 'object';
2832
- }
2833
-
2834
- /**
2835
- * @license
2836
- * Copyright 2021 Google LLC
2837
- *
2838
- * Licensed under the Apache License, Version 2.0 (the "License");
2839
- * you may not use this file except in compliance with the License.
2840
- * You may obtain a copy of the License at
2841
- *
2842
- * http://www.apache.org/licenses/LICENSE-2.0
2843
- *
2844
- * Unless required by applicable law or agreed to in writing, software
2845
- * distributed under the License is distributed on an "AS IS" BASIS,
2846
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2847
- * See the License for the specific language governing permissions and
2848
- * limitations under the License.
2849
- */
2850
- function getModularInstance(service) {
2851
- if (service && service._delegate) {
2852
- return service._delegate;
2853
- }
2854
- else {
2855
- return service;
2856
- }
2857
- }
2858
-
2859
- /**
2860
- * Component for service name T, e.g. `auth`, `auth-internal`
2861
- */
2862
- class Component {
2863
- /**
2864
- *
2865
- * @param name The public service name, e.g. app, auth, firestore, database
2866
- * @param instanceFactory Service factory responsible for creating the public interface
2867
- * @param type whether the service provided by the component is public or private
2868
- */
2869
- constructor(name, instanceFactory, type) {
2870
- this.name = name;
2871
- this.instanceFactory = instanceFactory;
2872
- this.type = type;
2873
- this.multipleInstances = false;
2874
- /**
2875
- * Properties to be added to the service namespace
2876
- */
2877
- this.serviceProps = {};
2878
- this.instantiationMode = "LAZY" /* InstantiationMode.LAZY */;
2879
- this.onInstanceCreated = null;
2880
- }
2881
- setInstantiationMode(mode) {
2882
- this.instantiationMode = mode;
2883
- return this;
2884
- }
2885
- setMultipleInstances(multipleInstances) {
2886
- this.multipleInstances = multipleInstances;
2887
- return this;
2888
- }
2889
- setServiceProps(props) {
2890
- this.serviceProps = props;
2891
- return this;
2892
- }
2893
- setInstanceCreatedCallback(callback) {
2894
- this.onInstanceCreated = callback;
2895
- return this;
2896
- }
2897
- }
2898
-
2899
- /**
2900
- * @license
2901
- * Copyright 2019 Google LLC
2902
- *
2903
- * Licensed under the Apache License, Version 2.0 (the "License");
2904
- * you may not use this file except in compliance with the License.
2905
- * You may obtain a copy of the License at
2906
- *
2907
- * http://www.apache.org/licenses/LICENSE-2.0
2908
- *
2909
- * Unless required by applicable law or agreed to in writing, software
2910
- * distributed under the License is distributed on an "AS IS" BASIS,
2911
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2912
- * See the License for the specific language governing permissions and
2913
- * limitations under the License.
2914
- */
2915
- const DEFAULT_ENTRY_NAME$1 = '[DEFAULT]';
2916
-
2917
- /**
2918
- * @license
2919
- * Copyright 2019 Google LLC
2920
- *
2921
- * Licensed under the Apache License, Version 2.0 (the "License");
2922
- * you may not use this file except in compliance with the License.
2923
- * You may obtain a copy of the License at
2924
- *
2925
- * http://www.apache.org/licenses/LICENSE-2.0
2926
- *
2927
- * Unless required by applicable law or agreed to in writing, software
2928
- * distributed under the License is distributed on an "AS IS" BASIS,
2929
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2930
- * See the License for the specific language governing permissions and
2931
- * limitations under the License.
2932
- */
2933
- /**
2934
- * Provider for instance for service name T, e.g. 'auth', 'auth-internal'
2935
- * NameServiceMapping[T] is an alias for the type of the instance
2936
- */
2937
- class Provider {
2938
- constructor(name, container) {
2939
- this.name = name;
2940
- this.container = container;
2941
- this.component = null;
2942
- this.instances = new Map();
2943
- this.instancesDeferred = new Map();
2944
- this.instancesOptions = new Map();
2945
- this.onInitCallbacks = new Map();
2946
- }
2947
- /**
2948
- * @param identifier A provider can provide multiple instances of a service
2949
- * if this.component.multipleInstances is true.
2950
- */
2951
- get(identifier) {
2952
- // if multipleInstances is not supported, use the default name
2953
- const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
2954
- if (!this.instancesDeferred.has(normalizedIdentifier)) {
2955
- const deferred = new Deferred();
2956
- this.instancesDeferred.set(normalizedIdentifier, deferred);
2957
- if (this.isInitialized(normalizedIdentifier) ||
2958
- this.shouldAutoInitialize()) {
2959
- // initialize the service if it can be auto-initialized
2960
- try {
2961
- const instance = this.getOrInitializeService({
2962
- instanceIdentifier: normalizedIdentifier
2963
- });
2964
- if (instance) {
2965
- deferred.resolve(instance);
2966
- }
2967
- }
2968
- catch (e) {
2969
- // when the instance factory throws an exception during get(), it should not cause
2970
- // a fatal error. We just return the unresolved promise in this case.
2971
- }
2972
- }
2973
- }
2974
- return this.instancesDeferred.get(normalizedIdentifier).promise;
2975
- }
2976
- getImmediate(options) {
2977
- // if multipleInstances is not supported, use the default name
2978
- const normalizedIdentifier = this.normalizeInstanceIdentifier(options?.identifier);
2979
- const optional = options?.optional ?? false;
2980
- if (this.isInitialized(normalizedIdentifier) ||
2981
- this.shouldAutoInitialize()) {
2982
- try {
2983
- return this.getOrInitializeService({
2984
- instanceIdentifier: normalizedIdentifier
2985
- });
2986
- }
2987
- catch (e) {
2988
- if (optional) {
2989
- return null;
2990
- }
2991
- else {
2992
- throw e;
2993
- }
2994
- }
2995
- }
2996
- else {
2997
- // In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw
2998
- if (optional) {
2999
- return null;
3000
- }
3001
- else {
3002
- throw Error(`Service ${this.name} is not available`);
3003
- }
3004
- }
3005
- }
3006
- getComponent() {
3007
- return this.component;
3008
- }
3009
- setComponent(component) {
3010
- if (component.name !== this.name) {
3011
- throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);
3012
- }
3013
- if (this.component) {
3014
- throw Error(`Component for ${this.name} has already been provided`);
3015
- }
3016
- this.component = component;
3017
- // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)
3018
- if (!this.shouldAutoInitialize()) {
3019
- return;
3020
- }
3021
- // if the service is eager, initialize the default instance
3022
- if (isComponentEager(component)) {
3023
- try {
3024
- this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME$1 });
3025
- }
3026
- catch (e) {
3027
- // when the instance factory for an eager Component throws an exception during the eager
3028
- // initialization, it should not cause a fatal error.
3029
- // TODO: Investigate if we need to make it configurable, because some component may want to cause
3030
- // a fatal error in this case?
3031
- }
3032
- }
3033
- // Create service instances for the pending promises and resolve them
3034
- // NOTE: if this.multipleInstances is false, only the default instance will be created
3035
- // and all promises with resolve with it regardless of the identifier.
3036
- for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
3037
- const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
3038
- try {
3039
- // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.
3040
- const instance = this.getOrInitializeService({
3041
- instanceIdentifier: normalizedIdentifier
3042
- });
3043
- instanceDeferred.resolve(instance);
3044
- }
3045
- catch (e) {
3046
- // when the instance factory throws an exception, it should not cause
3047
- // a fatal error. We just leave the promise unresolved.
3048
- }
3049
- }
3050
- }
3051
- clearInstance(identifier = DEFAULT_ENTRY_NAME$1) {
3052
- this.instancesDeferred.delete(identifier);
3053
- this.instancesOptions.delete(identifier);
3054
- this.instances.delete(identifier);
3055
- }
3056
- // app.delete() will call this method on every provider to delete the services
3057
- // TODO: should we mark the provider as deleted?
3058
- async delete() {
3059
- const services = Array.from(this.instances.values());
3060
- await Promise.all([
3061
- ...services
3062
- .filter(service => 'INTERNAL' in service) // legacy services
3063
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3064
- .map(service => service.INTERNAL.delete()),
3065
- ...services
3066
- .filter(service => '_delete' in service) // modularized services
3067
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3068
- .map(service => service._delete())
3069
- ]);
3070
- }
3071
- isComponentSet() {
3072
- return this.component != null;
3073
- }
3074
- isInitialized(identifier = DEFAULT_ENTRY_NAME$1) {
3075
- return this.instances.has(identifier);
3076
- }
3077
- getOptions(identifier = DEFAULT_ENTRY_NAME$1) {
3078
- return this.instancesOptions.get(identifier) || {};
3079
- }
3080
- initialize(opts = {}) {
3081
- const { options = {} } = opts;
3082
- const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);
3083
- if (this.isInitialized(normalizedIdentifier)) {
3084
- throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);
3085
- }
3086
- if (!this.isComponentSet()) {
3087
- throw Error(`Component ${this.name} has not been registered yet`);
3088
- }
3089
- const instance = this.getOrInitializeService({
3090
- instanceIdentifier: normalizedIdentifier,
3091
- options
3092
- });
3093
- // resolve any pending promise waiting for the service instance
3094
- for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
3095
- const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
3096
- if (normalizedIdentifier === normalizedDeferredIdentifier) {
3097
- instanceDeferred.resolve(instance);
3098
- }
3099
- }
3100
- return instance;
3101
- }
3102
- /**
3103
- *
3104
- * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().
3105
- * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.
3106
- *
3107
- * @param identifier An optional instance identifier
3108
- * @returns a function to unregister the callback
3109
- */
3110
- onInit(callback, identifier) {
3111
- const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
3112
- const existingCallbacks = this.onInitCallbacks.get(normalizedIdentifier) ??
3113
- new Set();
3114
- existingCallbacks.add(callback);
3115
- this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);
3116
- const existingInstance = this.instances.get(normalizedIdentifier);
3117
- if (existingInstance) {
3118
- callback(existingInstance, normalizedIdentifier);
3119
- }
3120
- return () => {
3121
- existingCallbacks.delete(callback);
3122
- };
3123
- }
3124
- /**
3125
- * Invoke onInit callbacks synchronously
3126
- * @param instance the service instance`
3127
- */
3128
- invokeOnInitCallbacks(instance, identifier) {
3129
- const callbacks = this.onInitCallbacks.get(identifier);
3130
- if (!callbacks) {
3131
- return;
3132
- }
3133
- for (const callback of callbacks) {
3134
- try {
3135
- callback(instance, identifier);
3136
- }
3137
- catch {
3138
- // ignore errors in the onInit callback
3139
- }
3140
- }
3141
- }
3142
- getOrInitializeService({ instanceIdentifier, options = {} }) {
3143
- let instance = this.instances.get(instanceIdentifier);
3144
- if (!instance && this.component) {
3145
- instance = this.component.instanceFactory(this.container, {
3146
- instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),
3147
- options
3148
- });
3149
- this.instances.set(instanceIdentifier, instance);
3150
- this.instancesOptions.set(instanceIdentifier, options);
3151
- /**
3152
- * Invoke onInit listeners.
3153
- * Note this.component.onInstanceCreated is different, which is used by the component creator,
3154
- * while onInit listeners are registered by consumers of the provider.
3155
- */
3156
- this.invokeOnInitCallbacks(instance, instanceIdentifier);
3157
- /**
3158
- * Order is important
3159
- * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which
3160
- * makes `isInitialized()` return true.
3161
- */
3162
- if (this.component.onInstanceCreated) {
3163
- try {
3164
- this.component.onInstanceCreated(this.container, instanceIdentifier, instance);
3165
- }
3166
- catch {
3167
- // ignore errors in the onInstanceCreatedCallback
3168
- }
3169
- }
3170
- }
3171
- return instance || null;
3172
- }
3173
- normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME$1) {
3174
- if (this.component) {
3175
- return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME$1;
3176
- }
3177
- else {
3178
- return identifier; // assume multiple instances are supported before the component is provided.
3179
- }
3180
- }
3181
- shouldAutoInitialize() {
3182
- return (!!this.component &&
3183
- this.component.instantiationMode !== "EXPLICIT" /* InstantiationMode.EXPLICIT */);
3184
- }
3185
- }
3186
- // undefined should be passed to the service factory for the default instance
3187
- function normalizeIdentifierForFactory(identifier) {
3188
- return identifier === DEFAULT_ENTRY_NAME$1 ? undefined : identifier;
3189
- }
3190
- function isComponentEager(component) {
3191
- return component.instantiationMode === "EAGER" /* InstantiationMode.EAGER */;
3192
- }
3193
-
3194
- /**
3195
- * @license
3196
- * Copyright 2019 Google LLC
3197
- *
3198
- * Licensed under the Apache License, Version 2.0 (the "License");
3199
- * you may not use this file except in compliance with the License.
3200
- * You may obtain a copy of the License at
3201
- *
3202
- * http://www.apache.org/licenses/LICENSE-2.0
3203
- *
3204
- * Unless required by applicable law or agreed to in writing, software
3205
- * distributed under the License is distributed on an "AS IS" BASIS,
3206
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3207
- * See the License for the specific language governing permissions and
3208
- * limitations under the License.
3209
- */
3210
- /**
3211
- * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`
3212
- */
3213
- class ComponentContainer {
3214
- constructor(name) {
3215
- this.name = name;
3216
- this.providers = new Map();
3217
- }
3218
- /**
3219
- *
3220
- * @param component Component being added
3221
- * @param overwrite When a component with the same name has already been registered,
3222
- * if overwrite is true: overwrite the existing component with the new component and create a new
3223
- * provider with the new component. It can be useful in tests where you want to use different mocks
3224
- * for different tests.
3225
- * if overwrite is false: throw an exception
3226
- */
3227
- addComponent(component) {
3228
- const provider = this.getProvider(component.name);
3229
- if (provider.isComponentSet()) {
3230
- throw new Error(`Component ${component.name} has already been registered with ${this.name}`);
3231
- }
3232
- provider.setComponent(component);
3233
- }
3234
- addOrOverwriteComponent(component) {
3235
- const provider = this.getProvider(component.name);
3236
- if (provider.isComponentSet()) {
3237
- // delete the existing provider from the container, so we can register the new component
3238
- this.providers.delete(component.name);
3239
- }
3240
- this.addComponent(component);
3241
- }
3242
- /**
3243
- * getProvider provides a type safe interface where it can only be called with a field name
3244
- * present in NameServiceMapping interface.
3245
- *
3246
- * Firebase SDKs providing services should extend NameServiceMapping interface to register
3247
- * themselves.
3248
- */
3249
- getProvider(name) {
3250
- if (this.providers.has(name)) {
3251
- return this.providers.get(name);
3252
- }
3253
- // create a Provider for a service that hasn't registered with Firebase
3254
- const provider = new Provider(name, this);
3255
- this.providers.set(name, provider);
3256
- return provider;
3257
- }
3258
- getProviders() {
3259
- return Array.from(this.providers.values());
3260
- }
3261
- }
3262
-
3263
- /**
3264
- * @license
3265
- * Copyright 2017 Google LLC
3266
- *
3267
- * Licensed under the Apache License, Version 2.0 (the "License");
3268
- * you may not use this file except in compliance with the License.
3269
- * You may obtain a copy of the License at
3270
- *
3271
- * http://www.apache.org/licenses/LICENSE-2.0
3272
- *
3273
- * Unless required by applicable law or agreed to in writing, software
3274
- * distributed under the License is distributed on an "AS IS" BASIS,
3275
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3276
- * See the License for the specific language governing permissions and
3277
- * limitations under the License.
3278
- */
3279
- /**
3280
- * The JS SDK supports 5 log levels and also allows a user the ability to
3281
- * silence the logs altogether.
3282
- *
3283
- * The order is a follows:
3284
- * DEBUG < VERBOSE < INFO < WARN < ERROR
3285
- *
3286
- * All of the log types above the current log level will be captured (i.e. if
3287
- * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and
3288
- * `VERBOSE` logs will not)
3289
- */
3290
- var LogLevel;
3291
- (function (LogLevel) {
3292
- LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
3293
- LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE";
3294
- LogLevel[LogLevel["INFO"] = 2] = "INFO";
3295
- LogLevel[LogLevel["WARN"] = 3] = "WARN";
3296
- LogLevel[LogLevel["ERROR"] = 4] = "ERROR";
3297
- LogLevel[LogLevel["SILENT"] = 5] = "SILENT";
3298
- })(LogLevel || (LogLevel = {}));
3299
- const levelStringToEnum = {
3300
- 'debug': LogLevel.DEBUG,
3301
- 'verbose': LogLevel.VERBOSE,
3302
- 'info': LogLevel.INFO,
3303
- 'warn': LogLevel.WARN,
3304
- 'error': LogLevel.ERROR,
3305
- 'silent': LogLevel.SILENT
3306
- };
3307
- /**
3308
- * The default log level
3309
- */
3310
- const defaultLogLevel = LogLevel.INFO;
3311
- /**
3312
- * By default, `console.debug` is not displayed in the developer console (in
3313
- * chrome). To avoid forcing users to have to opt-in to these logs twice
3314
- * (i.e. once for firebase, and once in the console), we are sending `DEBUG`
3315
- * logs to the `console.log` function.
3316
- */
3317
- const ConsoleMethod = {
3318
- [LogLevel.DEBUG]: 'log',
3319
- [LogLevel.VERBOSE]: 'log',
3320
- [LogLevel.INFO]: 'info',
3321
- [LogLevel.WARN]: 'warn',
3322
- [LogLevel.ERROR]: 'error'
3323
- };
3324
- /**
3325
- * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR
3326
- * messages on to their corresponding console counterparts (if the log method
3327
- * is supported by the current log level)
3328
- */
3329
- const defaultLogHandler = (instance, logType, ...args) => {
3330
- if (logType < instance.logLevel) {
3331
- return;
3332
- }
3333
- const now = new Date().toISOString();
3334
- const method = ConsoleMethod[logType];
3335
- if (method) {
3336
- console[method](`[${now}] ${instance.name}:`, ...args);
3337
- }
3338
- else {
3339
- throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);
3340
- }
3341
- };
3342
- class Logger {
3343
- /**
3344
- * Gives you an instance of a Logger to capture messages according to
3345
- * Firebase's logging scheme.
3346
- *
3347
- * @param name The name that the logs will be associated with
3348
- */
3349
- constructor(name) {
3350
- this.name = name;
3351
- /**
3352
- * The log level of the given Logger instance.
3353
- */
3354
- this._logLevel = defaultLogLevel;
3355
- /**
3356
- * The main (internal) log handler for the Logger instance.
3357
- * Can be set to a new function in internal package code but not by user.
3358
- */
3359
- this._logHandler = defaultLogHandler;
3360
- /**
3361
- * The optional, additional, user-defined log handler for the Logger instance.
3362
- */
3363
- this._userLogHandler = null;
3364
- }
3365
- get logLevel() {
3366
- return this._logLevel;
3367
- }
3368
- set logLevel(val) {
3369
- if (!(val in LogLevel)) {
3370
- throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``);
3371
- }
3372
- this._logLevel = val;
3373
- }
3374
- // Workaround for setter/getter having to be the same type.
3375
- setLogLevel(val) {
3376
- this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;
3377
- }
3378
- get logHandler() {
3379
- return this._logHandler;
3380
- }
3381
- set logHandler(val) {
3382
- if (typeof val !== 'function') {
3383
- throw new TypeError('Value assigned to `logHandler` must be a function');
3384
- }
3385
- this._logHandler = val;
3386
- }
3387
- get userLogHandler() {
3388
- return this._userLogHandler;
3389
- }
3390
- set userLogHandler(val) {
3391
- this._userLogHandler = val;
3392
- }
3393
- /**
3394
- * The functions below are all based on the `console` interface
3395
- */
3396
- debug(...args) {
3397
- this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);
3398
- this._logHandler(this, LogLevel.DEBUG, ...args);
3399
- }
3400
- log(...args) {
3401
- this._userLogHandler &&
3402
- this._userLogHandler(this, LogLevel.VERBOSE, ...args);
3403
- this._logHandler(this, LogLevel.VERBOSE, ...args);
3404
- }
3405
- info(...args) {
3406
- this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);
3407
- this._logHandler(this, LogLevel.INFO, ...args);
3408
- }
3409
- warn(...args) {
3410
- this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);
3411
- this._logHandler(this, LogLevel.WARN, ...args);
3412
- }
3413
- error(...args) {
3414
- this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);
3415
- this._logHandler(this, LogLevel.ERROR, ...args);
3416
- }
3417
- }
3418
-
3419
- const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);
3420
-
3421
- let idbProxyableTypes;
3422
- let cursorAdvanceMethods;
3423
- // This is a function to prevent it throwing up in node environments.
3424
- function getIdbProxyableTypes() {
3425
- return (idbProxyableTypes ||
3426
- (idbProxyableTypes = [
3427
- IDBDatabase,
3428
- IDBObjectStore,
3429
- IDBIndex,
3430
- IDBCursor,
3431
- IDBTransaction,
3432
- ]));
3433
- }
3434
- // This is a function to prevent it throwing up in node environments.
3435
- function getCursorAdvanceMethods() {
3436
- return (cursorAdvanceMethods ||
3437
- (cursorAdvanceMethods = [
3438
- IDBCursor.prototype.advance,
3439
- IDBCursor.prototype.continue,
3440
- IDBCursor.prototype.continuePrimaryKey,
3441
- ]));
3442
- }
3443
- const cursorRequestMap = new WeakMap();
3444
- const transactionDoneMap = new WeakMap();
3445
- const transactionStoreNamesMap = new WeakMap();
3446
- const transformCache = new WeakMap();
3447
- const reverseTransformCache = new WeakMap();
3448
- function promisifyRequest(request) {
3449
- const promise = new Promise((resolve, reject) => {
3450
- const unlisten = () => {
3451
- request.removeEventListener('success', success);
3452
- request.removeEventListener('error', error);
3453
- };
3454
- const success = () => {
3455
- resolve(wrap(request.result));
3456
- unlisten();
3457
- };
3458
- const error = () => {
3459
- reject(request.error);
3460
- unlisten();
3461
- };
3462
- request.addEventListener('success', success);
3463
- request.addEventListener('error', error);
3464
- });
3465
- promise
3466
- .then((value) => {
3467
- // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
3468
- // (see wrapFunction).
3469
- if (value instanceof IDBCursor) {
3470
- cursorRequestMap.set(value, request);
3471
- }
3472
- // Catching to avoid "Uncaught Promise exceptions"
3473
- })
3474
- .catch(() => { });
3475
- // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
3476
- // is because we create many promises from a single IDBRequest.
3477
- reverseTransformCache.set(promise, request);
3478
- return promise;
3479
- }
3480
- function cacheDonePromiseForTransaction(tx) {
3481
- // Early bail if we've already created a done promise for this transaction.
3482
- if (transactionDoneMap.has(tx))
3483
- return;
3484
- const done = new Promise((resolve, reject) => {
3485
- const unlisten = () => {
3486
- tx.removeEventListener('complete', complete);
3487
- tx.removeEventListener('error', error);
3488
- tx.removeEventListener('abort', error);
3489
- };
3490
- const complete = () => {
3491
- resolve();
3492
- unlisten();
3493
- };
3494
- const error = () => {
3495
- reject(tx.error || new DOMException('AbortError', 'AbortError'));
3496
- unlisten();
3497
- };
3498
- tx.addEventListener('complete', complete);
3499
- tx.addEventListener('error', error);
3500
- tx.addEventListener('abort', error);
3501
- });
3502
- // Cache it for later retrieval.
3503
- transactionDoneMap.set(tx, done);
3504
- }
3505
- let idbProxyTraps = {
3506
- get(target, prop, receiver) {
3507
- if (target instanceof IDBTransaction) {
3508
- // Special handling for transaction.done.
3509
- if (prop === 'done')
3510
- return transactionDoneMap.get(target);
3511
- // Polyfill for objectStoreNames because of Edge.
3512
- if (prop === 'objectStoreNames') {
3513
- return target.objectStoreNames || transactionStoreNamesMap.get(target);
3514
- }
3515
- // Make tx.store return the only store in the transaction, or undefined if there are many.
3516
- if (prop === 'store') {
3517
- return receiver.objectStoreNames[1]
3518
- ? undefined
3519
- : receiver.objectStore(receiver.objectStoreNames[0]);
3520
- }
3521
- }
3522
- // Else transform whatever we get back.
3523
- return wrap(target[prop]);
3524
- },
3525
- set(target, prop, value) {
3526
- target[prop] = value;
3527
- return true;
3528
- },
3529
- has(target, prop) {
3530
- if (target instanceof IDBTransaction &&
3531
- (prop === 'done' || prop === 'store')) {
3532
- return true;
3533
- }
3534
- return prop in target;
3535
- },
3536
- };
3537
- function replaceTraps(callback) {
3538
- idbProxyTraps = callback(idbProxyTraps);
3539
- }
3540
- function wrapFunction(func) {
3541
- // Due to expected object equality (which is enforced by the caching in `wrap`), we
3542
- // only create one new func per func.
3543
- // Edge doesn't support objectStoreNames (booo), so we polyfill it here.
3544
- if (func === IDBDatabase.prototype.transaction &&
3545
- !('objectStoreNames' in IDBTransaction.prototype)) {
3546
- return function (storeNames, ...args) {
3547
- const tx = func.call(unwrap(this), storeNames, ...args);
3548
- transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
3549
- return wrap(tx);
3550
- };
3551
- }
3552
- // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
3553
- // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the
3554
- // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense
3555
- // with real promises, so each advance methods returns a new promise for the cursor object, or
3556
- // undefined if the end of the cursor has been reached.
3557
- if (getCursorAdvanceMethods().includes(func)) {
3558
- return function (...args) {
3559
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
3560
- // the original object.
3561
- func.apply(unwrap(this), args);
3562
- return wrap(cursorRequestMap.get(this));
3563
- };
3564
- }
3565
- return function (...args) {
3566
- // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use
3567
- // the original object.
3568
- return wrap(func.apply(unwrap(this), args));
3569
- };
3570
- }
3571
- function transformCachableValue(value) {
3572
- if (typeof value === 'function')
3573
- return wrapFunction(value);
3574
- // This doesn't return, it just creates a 'done' promise for the transaction,
3575
- // which is later returned for transaction.done (see idbObjectHandler).
3576
- if (value instanceof IDBTransaction)
3577
- cacheDonePromiseForTransaction(value);
3578
- if (instanceOfAny(value, getIdbProxyableTypes()))
3579
- return new Proxy(value, idbProxyTraps);
3580
- // Return the same value back if we're not going to transform it.
3581
- return value;
3582
- }
3583
- function wrap(value) {
3584
- // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
3585
- // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
3586
- if (value instanceof IDBRequest)
3587
- return promisifyRequest(value);
3588
- // If we've already transformed this value before, reuse the transformed value.
3589
- // This is faster, but it also provides object equality.
3590
- if (transformCache.has(value))
3591
- return transformCache.get(value);
3592
- const newValue = transformCachableValue(value);
3593
- // Not all types are transformed.
3594
- // These may be primitive types, so they can't be WeakMap keys.
3595
- if (newValue !== value) {
3596
- transformCache.set(value, newValue);
3597
- reverseTransformCache.set(newValue, value);
3598
- }
3599
- return newValue;
3600
- }
3601
- const unwrap = (value) => reverseTransformCache.get(value);
3602
-
3603
- /**
3604
- * Open a database.
3605
- *
3606
- * @param name Name of the database.
3607
- * @param version Schema version.
3608
- * @param callbacks Additional callbacks.
3609
- */
3610
- function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
3611
- const request = indexedDB.open(name, version);
3612
- const openPromise = wrap(request);
3613
- if (upgrade) {
3614
- request.addEventListener('upgradeneeded', (event) => {
3615
- upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
3616
- });
3617
- }
3618
- if (blocked) {
3619
- request.addEventListener('blocked', (event) => blocked(
3620
- // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
3621
- event.oldVersion, event.newVersion, event));
3622
- }
3623
- openPromise
3624
- .then((db) => {
3625
- if (terminated)
3626
- db.addEventListener('close', () => terminated());
3627
- if (blocking) {
3628
- db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));
3629
- }
3630
- })
3631
- .catch(() => { });
3632
- return openPromise;
3633
- }
3634
- /**
3635
- * Delete a database.
3636
- *
3637
- * @param name Name of the database.
3638
- */
3639
- function deleteDB(name, { blocked } = {}) {
3640
- const request = indexedDB.deleteDatabase(name);
3641
- if (blocked) {
3642
- request.addEventListener('blocked', (event) => blocked(
3643
- // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
3644
- event.oldVersion, event));
3645
- }
3646
- return wrap(request).then(() => undefined);
3647
- }
3648
-
3649
- const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
3650
- const writeMethods = ['put', 'add', 'delete', 'clear'];
3651
- const cachedMethods = new Map();
3652
- function getMethod(target, prop) {
3653
- if (!(target instanceof IDBDatabase &&
3654
- !(prop in target) &&
3655
- typeof prop === 'string')) {
3656
- return;
3657
- }
3658
- if (cachedMethods.get(prop))
3659
- return cachedMethods.get(prop);
3660
- const targetFuncName = prop.replace(/FromIndex$/, '');
3661
- const useIndex = prop !== targetFuncName;
3662
- const isWrite = writeMethods.includes(targetFuncName);
3663
- if (
3664
- // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
3665
- !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
3666
- !(isWrite || readMethods.includes(targetFuncName))) {
3667
- return;
3668
- }
3669
- const method = async function (storeName, ...args) {
3670
- // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(
3671
- const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');
3672
- let target = tx.store;
3673
- if (useIndex)
3674
- target = target.index(args.shift());
3675
- // Must reject if op rejects.
3676
- // If it's a write operation, must reject if tx.done rejects.
3677
- // Must reject with op rejection first.
3678
- // Must resolve with op value.
3679
- // Must handle both promises (no unhandled rejections)
3680
- return (await Promise.all([
3681
- target[targetFuncName](...args),
3682
- isWrite && tx.done,
3683
- ]))[0];
3684
- };
3685
- cachedMethods.set(prop, method);
3686
- return method;
3687
- }
3688
- replaceTraps((oldTraps) => ({
3689
- ...oldTraps,
3690
- get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
3691
- has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),
3692
- }));
3693
-
3694
- /**
3695
- * @license
3696
- * Copyright 2019 Google LLC
3697
- *
3698
- * Licensed under the Apache License, Version 2.0 (the "License");
3699
- * you may not use this file except in compliance with the License.
3700
- * You may obtain a copy of the License at
3701
- *
3702
- * http://www.apache.org/licenses/LICENSE-2.0
3703
- *
3704
- * Unless required by applicable law or agreed to in writing, software
3705
- * distributed under the License is distributed on an "AS IS" BASIS,
3706
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3707
- * See the License for the specific language governing permissions and
3708
- * limitations under the License.
3709
- */
3710
- class PlatformLoggerServiceImpl {
3711
- constructor(container) {
3712
- this.container = container;
3713
- }
3714
- // In initial implementation, this will be called by installations on
3715
- // auth token refresh, and installations will send this string.
3716
- getPlatformInfoString() {
3717
- const providers = this.container.getProviders();
3718
- // Loop through providers and get library/version pairs from any that are
3719
- // version components.
3720
- return providers
3721
- .map(provider => {
3722
- if (isVersionServiceProvider(provider)) {
3723
- const service = provider.getImmediate();
3724
- return `${service.library}/${service.version}`;
3725
- }
3726
- else {
3727
- return null;
3728
- }
3729
- })
3730
- .filter(logString => logString)
3731
- .join(' ');
3732
- }
3733
- }
3734
- /**
3735
- *
3736
- * @param provider check if this provider provides a VersionService
3737
- *
3738
- * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider
3739
- * provides VersionService. The provider is not necessarily a 'app-version'
3740
- * provider.
3741
- */
3742
- function isVersionServiceProvider(provider) {
3743
- const component = provider.getComponent();
3744
- return component?.type === "VERSION" /* ComponentType.VERSION */;
3745
- }
3746
-
3747
- const name$q = "@firebase/app";
3748
- const version$1$1 = "0.14.4";
3749
-
3750
- /**
3751
- * @license
3752
- * Copyright 2019 Google LLC
3753
- *
3754
- * Licensed under the Apache License, Version 2.0 (the "License");
3755
- * you may not use this file except in compliance with the License.
3756
- * You may obtain a copy of the License at
3757
- *
3758
- * http://www.apache.org/licenses/LICENSE-2.0
3759
- *
3760
- * Unless required by applicable law or agreed to in writing, software
3761
- * distributed under the License is distributed on an "AS IS" BASIS,
3762
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3763
- * See the License for the specific language governing permissions and
3764
- * limitations under the License.
3765
- */
3766
- const logger = new Logger('@firebase/app');
3767
-
3768
- const name$p = "@firebase/app-compat";
3769
-
3770
- const name$o = "@firebase/analytics-compat";
3771
-
3772
- const name$n = "@firebase/analytics";
3773
-
3774
- const name$m = "@firebase/app-check-compat";
3775
-
3776
- const name$l = "@firebase/app-check";
3777
-
3778
- const name$k = "@firebase/auth";
3779
-
3780
- const name$j = "@firebase/auth-compat";
3781
-
3782
- const name$i = "@firebase/database";
3783
-
3784
- const name$h = "@firebase/data-connect";
3785
-
3786
- const name$g = "@firebase/database-compat";
3787
-
3788
- const name$f = "@firebase/functions";
3789
-
3790
- const name$e = "@firebase/functions-compat";
3791
-
3792
- const name$d = "@firebase/installations";
3793
-
3794
- const name$c = "@firebase/installations-compat";
3795
-
3796
- const name$b = "@firebase/messaging";
3797
-
3798
- const name$a = "@firebase/messaging-compat";
3799
-
3800
- const name$9 = "@firebase/performance";
3801
-
3802
- const name$8 = "@firebase/performance-compat";
3803
-
3804
- const name$7 = "@firebase/remote-config";
3805
-
3806
- const name$6 = "@firebase/remote-config-compat";
3807
-
3808
- const name$5 = "@firebase/storage";
3809
-
3810
- const name$4 = "@firebase/storage-compat";
3811
-
3812
- const name$3 = "@firebase/firestore";
3813
-
3814
- const name$2$1 = "@firebase/ai";
3815
-
3816
- const name$1$1 = "@firebase/firestore-compat";
3817
-
3818
- const name$r = "firebase";
3819
-
3820
- /**
3821
- * @license
3822
- * Copyright 2019 Google LLC
3823
- *
3824
- * Licensed under the Apache License, Version 2.0 (the "License");
3825
- * you may not use this file except in compliance with the License.
3826
- * You may obtain a copy of the License at
3827
- *
3828
- * http://www.apache.org/licenses/LICENSE-2.0
3829
- *
3830
- * Unless required by applicable law or agreed to in writing, software
3831
- * distributed under the License is distributed on an "AS IS" BASIS,
3832
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3833
- * See the License for the specific language governing permissions and
3834
- * limitations under the License.
3835
- */
3836
- /**
3837
- * The default app name
3838
- *
3839
- * @internal
3840
- */
3841
- const DEFAULT_ENTRY_NAME = '[DEFAULT]';
3842
- const PLATFORM_LOG_STRING = {
3843
- [name$q]: 'fire-core',
3844
- [name$p]: 'fire-core-compat',
3845
- [name$n]: 'fire-analytics',
3846
- [name$o]: 'fire-analytics-compat',
3847
- [name$l]: 'fire-app-check',
3848
- [name$m]: 'fire-app-check-compat',
3849
- [name$k]: 'fire-auth',
3850
- [name$j]: 'fire-auth-compat',
3851
- [name$i]: 'fire-rtdb',
3852
- [name$h]: 'fire-data-connect',
3853
- [name$g]: 'fire-rtdb-compat',
3854
- [name$f]: 'fire-fn',
3855
- [name$e]: 'fire-fn-compat',
3856
- [name$d]: 'fire-iid',
3857
- [name$c]: 'fire-iid-compat',
3858
- [name$b]: 'fire-fcm',
3859
- [name$a]: 'fire-fcm-compat',
3860
- [name$9]: 'fire-perf',
3861
- [name$8]: 'fire-perf-compat',
3862
- [name$7]: 'fire-rc',
3863
- [name$6]: 'fire-rc-compat',
3864
- [name$5]: 'fire-gcs',
3865
- [name$4]: 'fire-gcs-compat',
3866
- [name$3]: 'fire-fst',
3867
- [name$1$1]: 'fire-fst-compat',
3868
- [name$2$1]: 'fire-vertex',
3869
- 'fire-js': 'fire-js', // Platform identifier for JS SDK.
3870
- [name$r]: 'fire-js-all'
3871
- };
3872
-
3873
- /**
3874
- * @license
3875
- * Copyright 2019 Google LLC
3876
- *
3877
- * Licensed under the Apache License, Version 2.0 (the "License");
3878
- * you may not use this file except in compliance with the License.
3879
- * You may obtain a copy of the License at
3880
- *
3881
- * http://www.apache.org/licenses/LICENSE-2.0
3882
- *
3883
- * Unless required by applicable law or agreed to in writing, software
3884
- * distributed under the License is distributed on an "AS IS" BASIS,
3885
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3886
- * See the License for the specific language governing permissions and
3887
- * limitations under the License.
3888
- */
3889
- /**
3890
- * @internal
3891
- */
3892
- const _apps = new Map();
3893
- /**
3894
- * @internal
3895
- */
3896
- const _serverApps = new Map();
3897
- /**
3898
- * Registered components.
3899
- *
3900
- * @internal
3901
- */
3902
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3903
- const _components = new Map();
3904
- /**
3905
- * @param component - the component being added to this app's container
3906
- *
3907
- * @internal
3908
- */
3909
- function _addComponent(app, component) {
3910
- try {
3911
- app.container.addComponent(component);
3912
- }
3913
- catch (e) {
3914
- logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);
3915
- }
3916
- }
3917
- /**
3918
- *
3919
- * @param component - the component to register
3920
- * @returns whether or not the component is registered successfully
3921
- *
3922
- * @internal
3923
- */
3924
- function _registerComponent(component) {
3925
- const componentName = component.name;
3926
- if (_components.has(componentName)) {
3927
- logger.debug(`There were multiple attempts to register component ${componentName}.`);
3928
- return false;
3929
- }
3930
- _components.set(componentName, component);
3931
- // add the component to existing app instances
3932
- for (const app of _apps.values()) {
3933
- _addComponent(app, component);
3934
- }
3935
- for (const serverApp of _serverApps.values()) {
3936
- _addComponent(serverApp, component);
3937
- }
3938
- return true;
3939
- }
3940
- /**
3941
- *
3942
- * @param app - FirebaseApp instance
3943
- * @param name - service name
3944
- *
3945
- * @returns the provider for the service with the matching name
3946
- *
3947
- * @internal
3948
- */
3949
- function _getProvider(app, name) {
3950
- const heartbeatController = app.container
3951
- .getProvider('heartbeat')
3952
- .getImmediate({ optional: true });
3953
- if (heartbeatController) {
3954
- void heartbeatController.triggerHeartbeat();
3955
- }
3956
- return app.container.getProvider(name);
3957
- }
3958
-
3959
- /**
3960
- * @license
3961
- * Copyright 2019 Google LLC
3962
- *
3963
- * Licensed under the Apache License, Version 2.0 (the "License");
3964
- * you may not use this file except in compliance with the License.
3965
- * You may obtain a copy of the License at
3966
- *
3967
- * http://www.apache.org/licenses/LICENSE-2.0
3968
- *
3969
- * Unless required by applicable law or agreed to in writing, software
3970
- * distributed under the License is distributed on an "AS IS" BASIS,
3971
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3972
- * See the License for the specific language governing permissions and
3973
- * limitations under the License.
3974
- */
3975
- const ERRORS = {
3976
- ["no-app" /* AppError.NO_APP */]: "No Firebase App '{$appName}' has been created - " +
3977
- 'call initializeApp() first',
3978
- ["bad-app-name" /* AppError.BAD_APP_NAME */]: "Illegal App name: '{$appName}'",
3979
- ["duplicate-app" /* AppError.DUPLICATE_APP */]: "Firebase App named '{$appName}' already exists with different options or config",
3980
- ["app-deleted" /* AppError.APP_DELETED */]: "Firebase App named '{$appName}' already deleted",
3981
- ["server-app-deleted" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',
3982
- ["no-options" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',
3983
- ["invalid-app-argument" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +
3984
- 'Firebase App instance.',
3985
- ["invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',
3986
- ["idb-open" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',
3987
- ["idb-get" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',
3988
- ["idb-set" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',
3989
- ["idb-delete" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',
3990
- ["finalization-registry-not-supported" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',
3991
- ["invalid-server-app-environment" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'
3992
- };
3993
- const ERROR_FACTORY$2 = new ErrorFactory('app', 'Firebase', ERRORS);
3994
-
3995
- /**
3996
- * @license
3997
- * Copyright 2019 Google LLC
3998
- *
3999
- * Licensed under the Apache License, Version 2.0 (the "License");
4000
- * you may not use this file except in compliance with the License.
4001
- * You may obtain a copy of the License at
4002
- *
4003
- * http://www.apache.org/licenses/LICENSE-2.0
4004
- *
4005
- * Unless required by applicable law or agreed to in writing, software
4006
- * distributed under the License is distributed on an "AS IS" BASIS,
4007
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4008
- * See the License for the specific language governing permissions and
4009
- * limitations under the License.
4010
- */
4011
- class FirebaseAppImpl {
4012
- constructor(options, config, container) {
4013
- this._isDeleted = false;
4014
- this._options = { ...options };
4015
- this._config = { ...config };
4016
- this._name = config.name;
4017
- this._automaticDataCollectionEnabled =
4018
- config.automaticDataCollectionEnabled;
4019
- this._container = container;
4020
- this.container.addComponent(new Component('app', () => this, "PUBLIC" /* ComponentType.PUBLIC */));
4021
- }
4022
- get automaticDataCollectionEnabled() {
4023
- this.checkDestroyed();
4024
- return this._automaticDataCollectionEnabled;
4025
- }
4026
- set automaticDataCollectionEnabled(val) {
4027
- this.checkDestroyed();
4028
- this._automaticDataCollectionEnabled = val;
4029
- }
4030
- get name() {
4031
- this.checkDestroyed();
4032
- return this._name;
4033
- }
4034
- get options() {
4035
- this.checkDestroyed();
4036
- return this._options;
4037
- }
4038
- get config() {
4039
- this.checkDestroyed();
4040
- return this._config;
4041
- }
4042
- get container() {
4043
- return this._container;
4044
- }
4045
- get isDeleted() {
4046
- return this._isDeleted;
4047
- }
4048
- set isDeleted(val) {
4049
- this._isDeleted = val;
4050
- }
4051
- /**
4052
- * This function will throw an Error if the App has already been deleted -
4053
- * use before performing API actions on the App.
4054
- */
4055
- checkDestroyed() {
4056
- if (this.isDeleted) {
4057
- throw ERROR_FACTORY$2.create("app-deleted" /* AppError.APP_DELETED */, { appName: this._name });
4058
- }
4059
- }
4060
- }
4061
- function initializeApp(_options, rawConfig = {}) {
4062
- let options = _options;
4063
- if (typeof rawConfig !== 'object') {
4064
- const name = rawConfig;
4065
- rawConfig = { name };
4066
- }
4067
- const config = {
4068
- name: DEFAULT_ENTRY_NAME,
4069
- automaticDataCollectionEnabled: true,
4070
- ...rawConfig
4071
- };
4072
- const name = config.name;
4073
- if (typeof name !== 'string' || !name) {
4074
- throw ERROR_FACTORY$2.create("bad-app-name" /* AppError.BAD_APP_NAME */, {
4075
- appName: String(name)
4076
- });
4077
- }
4078
- options || (options = getDefaultAppConfig());
4079
- if (!options) {
4080
- throw ERROR_FACTORY$2.create("no-options" /* AppError.NO_OPTIONS */);
4081
- }
4082
- const existingApp = _apps.get(name);
4083
- if (existingApp) {
4084
- // return the existing app if options and config deep equal the ones in the existing app.
4085
- if (deepEqual(options, existingApp.options) &&
4086
- deepEqual(config, existingApp.config)) {
4087
- return existingApp;
4088
- }
4089
- else {
4090
- throw ERROR_FACTORY$2.create("duplicate-app" /* AppError.DUPLICATE_APP */, { appName: name });
4091
- }
4092
- }
4093
- const container = new ComponentContainer(name);
4094
- for (const component of _components.values()) {
4095
- container.addComponent(component);
4096
- }
4097
- const newApp = new FirebaseAppImpl(options, config, container);
4098
- _apps.set(name, newApp);
4099
- return newApp;
4100
- }
4101
- /**
4102
- * Retrieves a {@link @firebase/app#FirebaseApp} instance.
4103
- *
4104
- * When called with no arguments, the default app is returned. When an app name
4105
- * is provided, the app corresponding to that name is returned.
4106
- *
4107
- * An exception is thrown if the app being retrieved has not yet been
4108
- * initialized.
4109
- *
4110
- * @example
4111
- * ```javascript
4112
- * // Return the default app
4113
- * const app = getApp();
4114
- * ```
4115
- *
4116
- * @example
4117
- * ```javascript
4118
- * // Return a named app
4119
- * const otherApp = getApp("otherApp");
4120
- * ```
4121
- *
4122
- * @param name - Optional name of the app to return. If no name is
4123
- * provided, the default is `"[DEFAULT]"`.
4124
- *
4125
- * @returns The app corresponding to the provided app name.
4126
- * If no app name is provided, the default app is returned.
4127
- *
4128
- * @public
4129
- */
4130
- function getApp(name = DEFAULT_ENTRY_NAME) {
4131
- const app = _apps.get(name);
4132
- if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {
4133
- return initializeApp();
4134
- }
4135
- if (!app) {
4136
- throw ERROR_FACTORY$2.create("no-app" /* AppError.NO_APP */, { appName: name });
4137
- }
4138
- return app;
4139
- }
4140
- /**
4141
- * Registers a library's name and version for platform logging purposes.
4142
- * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)
4143
- * @param version - Current version of that library.
4144
- * @param variant - Bundle variant, e.g., node, rn, etc.
4145
- *
4146
- * @public
4147
- */
4148
- function registerVersion(libraryKeyOrName, version, variant) {
4149
- // TODO: We can use this check to whitelist strings when/if we set up
4150
- // a good whitelist system.
4151
- let library = PLATFORM_LOG_STRING[libraryKeyOrName] ?? libraryKeyOrName;
4152
- if (variant) {
4153
- library += `-${variant}`;
4154
- }
4155
- const libraryMismatch = library.match(/\s|\//);
4156
- const versionMismatch = version.match(/\s|\//);
4157
- if (libraryMismatch || versionMismatch) {
4158
- const warning = [
4159
- `Unable to register library "${library}" with version "${version}":`
4160
- ];
4161
- if (libraryMismatch) {
4162
- warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`);
4163
- }
4164
- if (libraryMismatch && versionMismatch) {
4165
- warning.push('and');
4166
- }
4167
- if (versionMismatch) {
4168
- warning.push(`version name "${version}" contains illegal characters (whitespace or "/")`);
4169
- }
4170
- logger.warn(warning.join(' '));
4171
- return;
4172
- }
4173
- _registerComponent(new Component(`${library}-version`, () => ({ library, version }), "VERSION" /* ComponentType.VERSION */));
4174
- }
4175
-
4176
- /**
4177
- * @license
4178
- * Copyright 2021 Google LLC
4179
- *
4180
- * Licensed under the Apache License, Version 2.0 (the "License");
4181
- * you may not use this file except in compliance with the License.
4182
- * You may obtain a copy of the License at
4183
- *
4184
- * http://www.apache.org/licenses/LICENSE-2.0
4185
- *
4186
- * Unless required by applicable law or agreed to in writing, software
4187
- * distributed under the License is distributed on an "AS IS" BASIS,
4188
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4189
- * See the License for the specific language governing permissions and
4190
- * limitations under the License.
4191
- */
4192
- const DB_NAME = 'firebase-heartbeat-database';
4193
- const DB_VERSION = 1;
4194
- const STORE_NAME = 'firebase-heartbeat-store';
4195
- let dbPromise$2 = null;
4196
- function getDbPromise$2() {
4197
- if (!dbPromise$2) {
4198
- dbPromise$2 = openDB(DB_NAME, DB_VERSION, {
4199
- upgrade: (db, oldVersion) => {
4200
- // We don't use 'break' in this switch statement, the fall-through
4201
- // behavior is what we want, because if there are multiple versions between
4202
- // the old version and the current version, we want ALL the migrations
4203
- // that correspond to those versions to run, not only the last one.
4204
- // eslint-disable-next-line default-case
4205
- switch (oldVersion) {
4206
- case 0:
4207
- try {
4208
- db.createObjectStore(STORE_NAME);
4209
- }
4210
- catch (e) {
4211
- // Safari/iOS browsers throw occasional exceptions on
4212
- // db.createObjectStore() that may be a bug. Avoid blocking
4213
- // the rest of the app functionality.
4214
- console.warn(e);
4215
- }
4216
- }
4217
- }
4218
- }).catch(e => {
4219
- throw ERROR_FACTORY$2.create("idb-open" /* AppError.IDB_OPEN */, {
4220
- originalErrorMessage: e.message
4221
- });
4222
- });
4223
- }
4224
- return dbPromise$2;
4225
- }
4226
- async function readHeartbeatsFromIndexedDB(app) {
4227
- try {
4228
- const db = await getDbPromise$2();
4229
- const tx = db.transaction(STORE_NAME);
4230
- const result = await tx.objectStore(STORE_NAME).get(computeKey(app));
4231
- // We already have the value but tx.done can throw,
4232
- // so we need to await it here to catch errors
4233
- await tx.done;
4234
- return result;
4235
- }
4236
- catch (e) {
4237
- if (e instanceof FirebaseError) {
4238
- logger.warn(e.message);
4239
- }
4240
- else {
4241
- const idbGetError = ERROR_FACTORY$2.create("idb-get" /* AppError.IDB_GET */, {
4242
- originalErrorMessage: e?.message
4243
- });
4244
- logger.warn(idbGetError.message);
4245
- }
4246
- }
4247
- }
4248
- async function writeHeartbeatsToIndexedDB(app, heartbeatObject) {
4249
- try {
4250
- const db = await getDbPromise$2();
4251
- const tx = db.transaction(STORE_NAME, 'readwrite');
4252
- const objectStore = tx.objectStore(STORE_NAME);
4253
- await objectStore.put(heartbeatObject, computeKey(app));
4254
- await tx.done;
4255
- }
4256
- catch (e) {
4257
- if (e instanceof FirebaseError) {
4258
- logger.warn(e.message);
4259
- }
4260
- else {
4261
- const idbGetError = ERROR_FACTORY$2.create("idb-set" /* AppError.IDB_WRITE */, {
4262
- originalErrorMessage: e?.message
4263
- });
4264
- logger.warn(idbGetError.message);
4265
- }
4266
- }
4267
- }
4268
- function computeKey(app) {
4269
- return `${app.name}!${app.options.appId}`;
4270
- }
4271
-
4272
- /**
4273
- * @license
4274
- * Copyright 2021 Google LLC
4275
- *
4276
- * Licensed under the Apache License, Version 2.0 (the "License");
4277
- * you may not use this file except in compliance with the License.
4278
- * You may obtain a copy of the License at
4279
- *
4280
- * http://www.apache.org/licenses/LICENSE-2.0
4281
- *
4282
- * Unless required by applicable law or agreed to in writing, software
4283
- * distributed under the License is distributed on an "AS IS" BASIS,
4284
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4285
- * See the License for the specific language governing permissions and
4286
- * limitations under the License.
4287
- */
4288
- const MAX_HEADER_BYTES = 1024;
4289
- const MAX_NUM_STORED_HEARTBEATS = 30;
4290
- class HeartbeatServiceImpl {
4291
- constructor(container) {
4292
- this.container = container;
4293
- /**
4294
- * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate
4295
- * the header string.
4296
- * Stores one record per date. This will be consolidated into the standard
4297
- * format of one record per user agent string before being sent as a header.
4298
- * Populated from indexedDB when the controller is instantiated and should
4299
- * be kept in sync with indexedDB.
4300
- * Leave public for easier testing.
4301
- */
4302
- this._heartbeatsCache = null;
4303
- const app = this.container.getProvider('app').getImmediate();
4304
- this._storage = new HeartbeatStorageImpl(app);
4305
- this._heartbeatsCachePromise = this._storage.read().then(result => {
4306
- this._heartbeatsCache = result;
4307
- return result;
4308
- });
4309
- }
4310
- /**
4311
- * Called to report a heartbeat. The function will generate
4312
- * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
4313
- * to IndexedDB.
4314
- * Note that we only store one heartbeat per day. So if a heartbeat for today is
4315
- * already logged, subsequent calls to this function in the same day will be ignored.
4316
- */
4317
- async triggerHeartbeat() {
4318
- try {
4319
- const platformLogger = this.container
4320
- .getProvider('platform-logger')
4321
- .getImmediate();
4322
- // This is the "Firebase user agent" string from the platform logger
4323
- // service, not the browser user agent.
4324
- const agent = platformLogger.getPlatformInfoString();
4325
- const date = getUTCDateString();
4326
- if (this._heartbeatsCache?.heartbeats == null) {
4327
- this._heartbeatsCache = await this._heartbeatsCachePromise;
4328
- // If we failed to construct a heartbeats cache, then return immediately.
4329
- if (this._heartbeatsCache?.heartbeats == null) {
4330
- return;
4331
- }
4332
- }
4333
- // Do not store a heartbeat if one is already stored for this day
4334
- // or if a header has already been sent today.
4335
- if (this._heartbeatsCache.lastSentHeartbeatDate === date ||
4336
- this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {
4337
- return;
4338
- }
4339
- else {
4340
- // There is no entry for this date. Create one.
4341
- this._heartbeatsCache.heartbeats.push({ date, agent });
4342
- // If the number of stored heartbeats exceeds the maximum number of stored heartbeats, remove the heartbeat with the earliest date.
4343
- // Since this is executed each time a heartbeat is pushed, the limit can only be exceeded by one, so only one needs to be removed.
4344
- if (this._heartbeatsCache.heartbeats.length > MAX_NUM_STORED_HEARTBEATS) {
4345
- const earliestHeartbeatIdx = getEarliestHeartbeatIdx(this._heartbeatsCache.heartbeats);
4346
- this._heartbeatsCache.heartbeats.splice(earliestHeartbeatIdx, 1);
4347
- }
4348
- }
4349
- return this._storage.overwrite(this._heartbeatsCache);
4350
- }
4351
- catch (e) {
4352
- logger.warn(e);
4353
- }
4354
- }
4355
- /**
4356
- * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
4357
- * It also clears all heartbeats from memory as well as in IndexedDB.
4358
- *
4359
- * NOTE: Consuming product SDKs should not send the header if this method
4360
- * returns an empty string.
4361
- */
4362
- async getHeartbeatsHeader() {
4363
- try {
4364
- if (this._heartbeatsCache === null) {
4365
- await this._heartbeatsCachePromise;
4366
- }
4367
- // If it's still null or the array is empty, there is no data to send.
4368
- if (this._heartbeatsCache?.heartbeats == null ||
4369
- this._heartbeatsCache.heartbeats.length === 0) {
4370
- return '';
4371
- }
4372
- const date = getUTCDateString();
4373
- // Extract as many heartbeats from the cache as will fit under the size limit.
4374
- const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);
4375
- const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));
4376
- // Store last sent date to prevent another being logged/sent for the same day.
4377
- this._heartbeatsCache.lastSentHeartbeatDate = date;
4378
- if (unsentEntries.length > 0) {
4379
- // Store any unsent entries if they exist.
4380
- this._heartbeatsCache.heartbeats = unsentEntries;
4381
- // This seems more likely than emptying the array (below) to lead to some odd state
4382
- // since the cache isn't empty and this will be called again on the next request,
4383
- // and is probably safest if we await it.
4384
- await this._storage.overwrite(this._heartbeatsCache);
4385
- }
4386
- else {
4387
- this._heartbeatsCache.heartbeats = [];
4388
- // Do not wait for this, to reduce latency.
4389
- void this._storage.overwrite(this._heartbeatsCache);
4390
- }
4391
- return headerString;
4392
- }
4393
- catch (e) {
4394
- logger.warn(e);
4395
- return '';
4396
- }
4397
- }
4398
- }
4399
- function getUTCDateString() {
4400
- const today = new Date();
4401
- // Returns date format 'YYYY-MM-DD'
4402
- return today.toISOString().substring(0, 10);
4403
- }
4404
- function extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {
4405
- // Heartbeats grouped by user agent in the standard format to be sent in
4406
- // the header.
4407
- const heartbeatsToSend = [];
4408
- // Single date format heartbeats that are not sent.
4409
- let unsentEntries = heartbeatsCache.slice();
4410
- for (const singleDateHeartbeat of heartbeatsCache) {
4411
- // Look for an existing entry with the same user agent.
4412
- const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);
4413
- if (!heartbeatEntry) {
4414
- // If no entry for this user agent exists, create one.
4415
- heartbeatsToSend.push({
4416
- agent: singleDateHeartbeat.agent,
4417
- dates: [singleDateHeartbeat.date]
4418
- });
4419
- if (countBytes(heartbeatsToSend) > maxSize) {
4420
- // If the header would exceed max size, remove the added heartbeat
4421
- // entry and stop adding to the header.
4422
- heartbeatsToSend.pop();
4423
- break;
4424
- }
4425
- }
4426
- else {
4427
- heartbeatEntry.dates.push(singleDateHeartbeat.date);
4428
- // If the header would exceed max size, remove the added date
4429
- // and stop adding to the header.
4430
- if (countBytes(heartbeatsToSend) > maxSize) {
4431
- heartbeatEntry.dates.pop();
4432
- break;
4433
- }
4434
- }
4435
- // Pop unsent entry from queue. (Skipped if adding the entry exceeded
4436
- // quota and the loop breaks early.)
4437
- unsentEntries = unsentEntries.slice(1);
4438
- }
4439
- return {
4440
- heartbeatsToSend,
4441
- unsentEntries
4442
- };
4443
- }
4444
- class HeartbeatStorageImpl {
4445
- constructor(app) {
4446
- this.app = app;
4447
- this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();
4448
- }
4449
- async runIndexedDBEnvironmentCheck() {
4450
- if (!isIndexedDBAvailable()) {
4451
- return false;
4452
- }
4453
- else {
4454
- return validateIndexedDBOpenable()
4455
- .then(() => true)
4456
- .catch(() => false);
4457
- }
4458
- }
4459
- /**
4460
- * Read all heartbeats.
4461
- */
4462
- async read() {
4463
- const canUseIndexedDB = await this._canUseIndexedDBPromise;
4464
- if (!canUseIndexedDB) {
4465
- return { heartbeats: [] };
4466
- }
4467
- else {
4468
- const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);
4469
- if (idbHeartbeatObject?.heartbeats) {
4470
- return idbHeartbeatObject;
4471
- }
4472
- else {
4473
- return { heartbeats: [] };
4474
- }
4475
- }
4476
- }
4477
- // overwrite the storage with the provided heartbeats
4478
- async overwrite(heartbeatsObject) {
4479
- const canUseIndexedDB = await this._canUseIndexedDBPromise;
4480
- if (!canUseIndexedDB) {
4481
- return;
4482
- }
4483
- else {
4484
- const existingHeartbeatsObject = await this.read();
4485
- return writeHeartbeatsToIndexedDB(this.app, {
4486
- lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ??
4487
- existingHeartbeatsObject.lastSentHeartbeatDate,
4488
- heartbeats: heartbeatsObject.heartbeats
4489
- });
4490
- }
4491
- }
4492
- // add heartbeats
4493
- async add(heartbeatsObject) {
4494
- const canUseIndexedDB = await this._canUseIndexedDBPromise;
4495
- if (!canUseIndexedDB) {
4496
- return;
4497
- }
4498
- else {
4499
- const existingHeartbeatsObject = await this.read();
4500
- return writeHeartbeatsToIndexedDB(this.app, {
4501
- lastSentHeartbeatDate: heartbeatsObject.lastSentHeartbeatDate ??
4502
- existingHeartbeatsObject.lastSentHeartbeatDate,
4503
- heartbeats: [
4504
- ...existingHeartbeatsObject.heartbeats,
4505
- ...heartbeatsObject.heartbeats
4506
- ]
4507
- });
4508
- }
4509
- }
4510
- }
4511
- /**
4512
- * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped
4513
- * in a platform logging header JSON object, stringified, and converted
4514
- * to base 64.
4515
- */
4516
- function countBytes(heartbeatsCache) {
4517
- // base64 has a restricted set of characters, all of which should be 1 byte.
4518
- return base64urlEncodeWithoutPadding(
4519
- // heartbeatsCache wrapper properties
4520
- JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;
4521
- }
4522
- /**
4523
- * Returns the index of the heartbeat with the earliest date.
4524
- * If the heartbeats array is empty, -1 is returned.
4525
- */
4526
- function getEarliestHeartbeatIdx(heartbeats) {
4527
- if (heartbeats.length === 0) {
4528
- return -1;
4529
- }
4530
- let earliestHeartbeatIdx = 0;
4531
- let earliestHeartbeatDate = heartbeats[0].date;
4532
- for (let i = 1; i < heartbeats.length; i++) {
4533
- if (heartbeats[i].date < earliestHeartbeatDate) {
4534
- earliestHeartbeatDate = heartbeats[i].date;
4535
- earliestHeartbeatIdx = i;
4536
- }
4537
- }
4538
- return earliestHeartbeatIdx;
4539
- }
4540
-
4541
- /**
4542
- * @license
4543
- * Copyright 2019 Google LLC
4544
- *
4545
- * Licensed under the Apache License, Version 2.0 (the "License");
4546
- * you may not use this file except in compliance with the License.
4547
- * You may obtain a copy of the License at
4548
- *
4549
- * http://www.apache.org/licenses/LICENSE-2.0
4550
- *
4551
- * Unless required by applicable law or agreed to in writing, software
4552
- * distributed under the License is distributed on an "AS IS" BASIS,
4553
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4554
- * See the License for the specific language governing permissions and
4555
- * limitations under the License.
4556
- */
4557
- function registerCoreComponents(variant) {
4558
- _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */));
4559
- _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), "PRIVATE" /* ComponentType.PRIVATE */));
4560
- // Register `app` package.
4561
- registerVersion(name$q, version$1$1, variant);
4562
- // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
4563
- registerVersion(name$q, version$1$1, 'esm2020');
4564
- // Register platform SDK identifier (no version).
4565
- registerVersion('fire-js', '');
4566
- }
4567
-
4568
- /**
4569
- * Firebase App
4570
- *
4571
- * @remarks This package coordinates the communication between the different Firebase components
4572
- * @packageDocumentation
4573
- */
4574
- registerCoreComponents('');
4575
-
4576
- var name$2 = "firebase";
4577
- var version$2 = "12.4.0";
4578
-
4579
- /**
4580
- * @license
4581
- * Copyright 2020 Google LLC
4582
- *
4583
- * Licensed under the Apache License, Version 2.0 (the "License");
4584
- * you may not use this file except in compliance with the License.
4585
- * You may obtain a copy of the License at
4586
- *
4587
- * http://www.apache.org/licenses/LICENSE-2.0
4588
- *
4589
- * Unless required by applicable law or agreed to in writing, software
4590
- * distributed under the License is distributed on an "AS IS" BASIS,
4591
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4592
- * See the License for the specific language governing permissions and
4593
- * limitations under the License.
4594
- */
4595
- registerVersion(name$2, version$2, 'app');
4596
-
4597
- const name$1 = "@firebase/installations";
4598
- const version$1 = "0.6.19";
4599
-
4600
- /**
4601
- * @license
4602
- * Copyright 2019 Google LLC
4603
- *
4604
- * Licensed under the Apache License, Version 2.0 (the "License");
4605
- * you may not use this file except in compliance with the License.
4606
- * You may obtain a copy of the License at
4607
- *
4608
- * http://www.apache.org/licenses/LICENSE-2.0
4609
- *
4610
- * Unless required by applicable law or agreed to in writing, software
4611
- * distributed under the License is distributed on an "AS IS" BASIS,
4612
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4613
- * See the License for the specific language governing permissions and
4614
- * limitations under the License.
4615
- */
4616
- const PENDING_TIMEOUT_MS = 10000;
4617
- const PACKAGE_VERSION = `w:${version$1}`;
4618
- const INTERNAL_AUTH_VERSION = 'FIS_v2';
4619
- const INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';
4620
- const TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour
4621
- const SERVICE = 'installations';
4622
- const SERVICE_NAME = 'Installations';
4623
-
4624
- /**
4625
- * @license
4626
- * Copyright 2019 Google LLC
4627
- *
4628
- * Licensed under the Apache License, Version 2.0 (the "License");
4629
- * you may not use this file except in compliance with the License.
4630
- * You may obtain a copy of the License at
4631
- *
4632
- * http://www.apache.org/licenses/LICENSE-2.0
4633
- *
4634
- * Unless required by applicable law or agreed to in writing, software
4635
- * distributed under the License is distributed on an "AS IS" BASIS,
4636
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4637
- * See the License for the specific language governing permissions and
4638
- * limitations under the License.
4639
- */
4640
- const ERROR_DESCRIPTION_MAP = {
4641
- ["missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: "{$valueName}"',
4642
- ["not-registered" /* ErrorCode.NOT_REGISTERED */]: 'Firebase Installation is not registered.',
4643
- ["installation-not-found" /* ErrorCode.INSTALLATION_NOT_FOUND */]: 'Firebase Installation not found.',
4644
- ["request-failed" /* ErrorCode.REQUEST_FAILED */]: '{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',
4645
- ["app-offline" /* ErrorCode.APP_OFFLINE */]: 'Could not process request. Application offline.',
4646
- ["delete-pending-registration" /* ErrorCode.DELETE_PENDING_REGISTRATION */]: "Can't delete installation while there is a pending registration request."
4647
- };
4648
- const ERROR_FACTORY$1 = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);
4649
- /** Returns true if error is a FirebaseError that is based on an error from the server. */
4650
- function isServerError(error) {
4651
- return (error instanceof FirebaseError &&
4652
- error.code.includes("request-failed" /* ErrorCode.REQUEST_FAILED */));
4653
- }
4654
-
4655
- /**
4656
- * @license
4657
- * Copyright 2019 Google LLC
4658
- *
4659
- * Licensed under the Apache License, Version 2.0 (the "License");
4660
- * you may not use this file except in compliance with the License.
4661
- * You may obtain a copy of the License at
4662
- *
4663
- * http://www.apache.org/licenses/LICENSE-2.0
4664
- *
4665
- * Unless required by applicable law or agreed to in writing, software
4666
- * distributed under the License is distributed on an "AS IS" BASIS,
4667
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4668
- * See the License for the specific language governing permissions and
4669
- * limitations under the License.
4670
- */
4671
- function getInstallationsEndpoint({ projectId }) {
4672
- return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;
4673
- }
4674
- function extractAuthTokenInfoFromResponse(response) {
4675
- return {
4676
- token: response.token,
4677
- requestStatus: 2 /* RequestStatus.COMPLETED */,
4678
- expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),
4679
- creationTime: Date.now()
4680
- };
4681
- }
4682
- async function getErrorFromResponse(requestName, response) {
4683
- const responseJson = await response.json();
4684
- const errorData = responseJson.error;
4685
- return ERROR_FACTORY$1.create("request-failed" /* ErrorCode.REQUEST_FAILED */, {
4686
- requestName,
4687
- serverCode: errorData.code,
4688
- serverMessage: errorData.message,
4689
- serverStatus: errorData.status
4690
- });
4691
- }
4692
- function getHeaders$1({ apiKey }) {
4693
- return new Headers({
4694
- 'Content-Type': 'application/json',
4695
- Accept: 'application/json',
4696
- 'x-goog-api-key': apiKey
4697
- });
4698
- }
4699
- function getHeadersWithAuth(appConfig, { refreshToken }) {
4700
- const headers = getHeaders$1(appConfig);
4701
- headers.append('Authorization', getAuthorizationHeader(refreshToken));
4702
- return headers;
4703
- }
4704
- /**
4705
- * Calls the passed in fetch wrapper and returns the response.
4706
- * If the returned response has a status of 5xx, re-runs the function once and
4707
- * returns the response.
4708
- */
4709
- async function retryIfServerError(fn) {
4710
- const result = await fn();
4711
- if (result.status >= 500 && result.status < 600) {
4712
- // Internal Server Error. Retry request.
4713
- return fn();
4714
- }
4715
- return result;
4716
- }
4717
- function getExpiresInFromResponseExpiresIn(responseExpiresIn) {
4718
- // This works because the server will never respond with fractions of a second.
4719
- return Number(responseExpiresIn.replace('s', '000'));
4720
- }
4721
- function getAuthorizationHeader(refreshToken) {
4722
- return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;
4723
- }
4724
-
4725
- /**
4726
- * @license
4727
- * Copyright 2019 Google LLC
4728
- *
4729
- * Licensed under the Apache License, Version 2.0 (the "License");
4730
- * you may not use this file except in compliance with the License.
4731
- * You may obtain a copy of the License at
4732
- *
4733
- * http://www.apache.org/licenses/LICENSE-2.0
4734
- *
4735
- * Unless required by applicable law or agreed to in writing, software
4736
- * distributed under the License is distributed on an "AS IS" BASIS,
4737
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4738
- * See the License for the specific language governing permissions and
4739
- * limitations under the License.
4740
- */
4741
- async function createInstallationRequest({ appConfig, heartbeatServiceProvider }, { fid }) {
4742
- const endpoint = getInstallationsEndpoint(appConfig);
4743
- const headers = getHeaders$1(appConfig);
4744
- // If heartbeat service exists, add the heartbeat string to the header.
4745
- const heartbeatService = heartbeatServiceProvider.getImmediate({
4746
- optional: true
4747
- });
4748
- if (heartbeatService) {
4749
- const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();
4750
- if (heartbeatsHeader) {
4751
- headers.append('x-firebase-client', heartbeatsHeader);
4752
- }
4753
- }
4754
- const body = {
4755
- fid,
4756
- authVersion: INTERNAL_AUTH_VERSION,
4757
- appId: appConfig.appId,
4758
- sdkVersion: PACKAGE_VERSION
4759
- };
4760
- const request = {
4761
- method: 'POST',
4762
- headers,
4763
- body: JSON.stringify(body)
4764
- };
4765
- const response = await retryIfServerError(() => fetch(endpoint, request));
4766
- if (response.ok) {
4767
- const responseValue = await response.json();
4768
- const registeredInstallationEntry = {
4769
- fid: responseValue.fid || fid,
4770
- registrationStatus: 2 /* RequestStatus.COMPLETED */,
4771
- refreshToken: responseValue.refreshToken,
4772
- authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)
4773
- };
4774
- return registeredInstallationEntry;
4775
- }
4776
- else {
4777
- throw await getErrorFromResponse('Create Installation', response);
4778
- }
4779
- }
4780
-
4781
- /**
4782
- * @license
4783
- * Copyright 2019 Google LLC
4784
- *
4785
- * Licensed under the Apache License, Version 2.0 (the "License");
4786
- * you may not use this file except in compliance with the License.
4787
- * You may obtain a copy of the License at
4788
- *
4789
- * http://www.apache.org/licenses/LICENSE-2.0
4790
- *
4791
- * Unless required by applicable law or agreed to in writing, software
4792
- * distributed under the License is distributed on an "AS IS" BASIS,
4793
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4794
- * See the License for the specific language governing permissions and
4795
- * limitations under the License.
4796
- */
4797
- /** Returns a promise that resolves after given time passes. */
4798
- function sleep(ms) {
4799
- return new Promise(resolve => {
4800
- setTimeout(resolve, ms);
4801
- });
4802
- }
4803
-
4804
- /**
4805
- * @license
4806
- * Copyright 2019 Google LLC
4807
- *
4808
- * Licensed under the Apache License, Version 2.0 (the "License");
4809
- * you may not use this file except in compliance with the License.
4810
- * You may obtain a copy of the License at
4811
- *
4812
- * http://www.apache.org/licenses/LICENSE-2.0
4813
- *
4814
- * Unless required by applicable law or agreed to in writing, software
4815
- * distributed under the License is distributed on an "AS IS" BASIS,
4816
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4817
- * See the License for the specific language governing permissions and
4818
- * limitations under the License.
4819
- */
4820
- function bufferToBase64UrlSafe(array) {
4821
- const b64 = btoa(String.fromCharCode(...array));
4822
- return b64.replace(/\+/g, '-').replace(/\//g, '_');
4823
- }
4824
-
4825
- /**
4826
- * @license
4827
- * Copyright 2019 Google LLC
4828
- *
4829
- * Licensed under the Apache License, Version 2.0 (the "License");
4830
- * you may not use this file except in compliance with the License.
4831
- * You may obtain a copy of the License at
4832
- *
4833
- * http://www.apache.org/licenses/LICENSE-2.0
4834
- *
4835
- * Unless required by applicable law or agreed to in writing, software
4836
- * distributed under the License is distributed on an "AS IS" BASIS,
4837
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4838
- * See the License for the specific language governing permissions and
4839
- * limitations under the License.
4840
- */
4841
- const VALID_FID_PATTERN = /^[cdef][\w-]{21}$/;
4842
- const INVALID_FID = '';
4843
- /**
4844
- * Generates a new FID using random values from Web Crypto API.
4845
- * Returns an empty string if FID generation fails for any reason.
4846
- */
4847
- function generateFid() {
4848
- try {
4849
- // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5
4850
- // bytes. our implementation generates a 17 byte array instead.
4851
- const fidByteArray = new Uint8Array(17);
4852
- const crypto = self.crypto || self.msCrypto;
4853
- crypto.getRandomValues(fidByteArray);
4854
- // Replace the first 4 random bits with the constant FID header of 0b0111.
4855
- fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);
4856
- const fid = encode(fidByteArray);
4857
- return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;
4858
- }
4859
- catch {
4860
- // FID generation errored
4861
- return INVALID_FID;
4862
- }
4863
- }
4864
- /** Converts a FID Uint8Array to a base64 string representation. */
4865
- function encode(fidByteArray) {
4866
- const b64String = bufferToBase64UrlSafe(fidByteArray);
4867
- // Remove the 23rd character that was added because of the extra 4 bits at the
4868
- // end of our 17 byte array, and the '=' padding.
4869
- return b64String.substr(0, 22);
4870
- }
4871
-
4872
- /**
4873
- * @license
4874
- * Copyright 2019 Google LLC
4875
- *
4876
- * Licensed under the Apache License, Version 2.0 (the "License");
4877
- * you may not use this file except in compliance with the License.
4878
- * You may obtain a copy of the License at
4879
- *
4880
- * http://www.apache.org/licenses/LICENSE-2.0
4881
- *
4882
- * Unless required by applicable law or agreed to in writing, software
4883
- * distributed under the License is distributed on an "AS IS" BASIS,
4884
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4885
- * See the License for the specific language governing permissions and
4886
- * limitations under the License.
4887
- */
4888
- /** Returns a string key that can be used to identify the app. */
4889
- function getKey$1(appConfig) {
4890
- return `${appConfig.appName}!${appConfig.appId}`;
4891
- }
4892
-
4893
- /**
4894
- * @license
4895
- * Copyright 2019 Google LLC
4896
- *
4897
- * Licensed under the Apache License, Version 2.0 (the "License");
4898
- * you may not use this file except in compliance with the License.
4899
- * You may obtain a copy of the License at
4900
- *
4901
- * http://www.apache.org/licenses/LICENSE-2.0
4902
- *
4903
- * Unless required by applicable law or agreed to in writing, software
4904
- * distributed under the License is distributed on an "AS IS" BASIS,
4905
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4906
- * See the License for the specific language governing permissions and
4907
- * limitations under the License.
4908
- */
4909
- const fidChangeCallbacks = new Map();
4910
- /**
4911
- * Calls the onIdChange callbacks with the new FID value, and broadcasts the
4912
- * change to other tabs.
4913
- */
4914
- function fidChanged(appConfig, fid) {
4915
- const key = getKey$1(appConfig);
4916
- callFidChangeCallbacks(key, fid);
4917
- broadcastFidChange(key, fid);
4918
- }
4919
- function callFidChangeCallbacks(key, fid) {
4920
- const callbacks = fidChangeCallbacks.get(key);
4921
- if (!callbacks) {
4922
- return;
4923
- }
4924
- for (const callback of callbacks) {
4925
- callback(fid);
4926
- }
4927
- }
4928
- function broadcastFidChange(key, fid) {
4929
- const channel = getBroadcastChannel();
4930
- if (channel) {
4931
- channel.postMessage({ key, fid });
4932
- }
4933
- closeBroadcastChannel();
4934
- }
4935
- let broadcastChannel = null;
4936
- /** Opens and returns a BroadcastChannel if it is supported by the browser. */
4937
- function getBroadcastChannel() {
4938
- if (!broadcastChannel && 'BroadcastChannel' in self) {
4939
- broadcastChannel = new BroadcastChannel('[Firebase] FID Change');
4940
- broadcastChannel.onmessage = e => {
4941
- callFidChangeCallbacks(e.data.key, e.data.fid);
4942
- };
4943
- }
4944
- return broadcastChannel;
4945
- }
4946
- function closeBroadcastChannel() {
4947
- if (fidChangeCallbacks.size === 0 && broadcastChannel) {
4948
- broadcastChannel.close();
4949
- broadcastChannel = null;
4950
- }
4951
- }
4952
-
4953
- /**
4954
- * @license
4955
- * Copyright 2019 Google LLC
4956
- *
4957
- * Licensed under the Apache License, Version 2.0 (the "License");
4958
- * you may not use this file except in compliance with the License.
4959
- * You may obtain a copy of the License at
4960
- *
4961
- * http://www.apache.org/licenses/LICENSE-2.0
4962
- *
4963
- * Unless required by applicable law or agreed to in writing, software
4964
- * distributed under the License is distributed on an "AS IS" BASIS,
4965
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4966
- * See the License for the specific language governing permissions and
4967
- * limitations under the License.
4968
- */
4969
- const DATABASE_NAME$1 = 'firebase-installations-database';
4970
- const DATABASE_VERSION$1 = 1;
4971
- const OBJECT_STORE_NAME$1 = 'firebase-installations-store';
4972
- let dbPromise$1 = null;
4973
- function getDbPromise$1() {
4974
- if (!dbPromise$1) {
4975
- dbPromise$1 = openDB(DATABASE_NAME$1, DATABASE_VERSION$1, {
4976
- upgrade: (db, oldVersion) => {
4977
- // We don't use 'break' in this switch statement, the fall-through
4978
- // behavior is what we want, because if there are multiple versions between
4979
- // the old version and the current version, we want ALL the migrations
4980
- // that correspond to those versions to run, not only the last one.
4981
- // eslint-disable-next-line default-case
4982
- switch (oldVersion) {
4983
- case 0:
4984
- db.createObjectStore(OBJECT_STORE_NAME$1);
4985
- }
4986
- }
4987
- });
4988
- }
4989
- return dbPromise$1;
4990
- }
4991
- /** Assigns or overwrites the record for the given key with the given value. */
4992
- async function set(appConfig, value) {
4993
- const key = getKey$1(appConfig);
4994
- const db = await getDbPromise$1();
4995
- const tx = db.transaction(OBJECT_STORE_NAME$1, 'readwrite');
4996
- const objectStore = tx.objectStore(OBJECT_STORE_NAME$1);
4997
- const oldValue = (await objectStore.get(key));
4998
- await objectStore.put(value, key);
4999
- await tx.done;
5000
- if (!oldValue || oldValue.fid !== value.fid) {
5001
- fidChanged(appConfig, value.fid);
5002
- }
5003
- return value;
5004
- }
5005
- /** Removes record(s) from the objectStore that match the given key. */
5006
- async function remove(appConfig) {
5007
- const key = getKey$1(appConfig);
5008
- const db = await getDbPromise$1();
5009
- const tx = db.transaction(OBJECT_STORE_NAME$1, 'readwrite');
5010
- await tx.objectStore(OBJECT_STORE_NAME$1).delete(key);
5011
- await tx.done;
5012
- }
5013
- /**
5014
- * Atomically updates a record with the result of updateFn, which gets
5015
- * called with the current value. If newValue is undefined, the record is
5016
- * deleted instead.
5017
- * @return Updated value
5018
- */
5019
- async function update(appConfig, updateFn) {
5020
- const key = getKey$1(appConfig);
5021
- const db = await getDbPromise$1();
5022
- const tx = db.transaction(OBJECT_STORE_NAME$1, 'readwrite');
5023
- const store = tx.objectStore(OBJECT_STORE_NAME$1);
5024
- const oldValue = (await store.get(key));
5025
- const newValue = updateFn(oldValue);
5026
- if (newValue === undefined) {
5027
- await store.delete(key);
5028
- }
5029
- else {
5030
- await store.put(newValue, key);
5031
- }
5032
- await tx.done;
5033
- if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {
5034
- fidChanged(appConfig, newValue.fid);
5035
- }
5036
- return newValue;
5037
- }
5038
-
5039
- /**
5040
- * @license
5041
- * Copyright 2019 Google LLC
5042
- *
5043
- * Licensed under the Apache License, Version 2.0 (the "License");
5044
- * you may not use this file except in compliance with the License.
5045
- * You may obtain a copy of the License at
5046
- *
5047
- * http://www.apache.org/licenses/LICENSE-2.0
5048
- *
5049
- * Unless required by applicable law or agreed to in writing, software
5050
- * distributed under the License is distributed on an "AS IS" BASIS,
5051
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5052
- * See the License for the specific language governing permissions and
5053
- * limitations under the License.
5054
- */
5055
- /**
5056
- * Updates and returns the InstallationEntry from the database.
5057
- * Also triggers a registration request if it is necessary and possible.
5058
- */
5059
- async function getInstallationEntry(installations) {
5060
- let registrationPromise;
5061
- const installationEntry = await update(installations.appConfig, oldEntry => {
5062
- const installationEntry = updateOrCreateInstallationEntry(oldEntry);
5063
- const entryWithPromise = triggerRegistrationIfNecessary(installations, installationEntry);
5064
- registrationPromise = entryWithPromise.registrationPromise;
5065
- return entryWithPromise.installationEntry;
5066
- });
5067
- if (installationEntry.fid === INVALID_FID) {
5068
- // FID generation failed. Waiting for the FID from the server.
5069
- return { installationEntry: await registrationPromise };
5070
- }
5071
- return {
5072
- installationEntry,
5073
- registrationPromise
5074
- };
5075
- }
5076
- /**
5077
- * Creates a new Installation Entry if one does not exist.
5078
- * Also clears timed out pending requests.
5079
- */
5080
- function updateOrCreateInstallationEntry(oldEntry) {
5081
- const entry = oldEntry || {
5082
- fid: generateFid(),
5083
- registrationStatus: 0 /* RequestStatus.NOT_STARTED */
5084
- };
5085
- return clearTimedOutRequest(entry);
5086
- }
5087
- /**
5088
- * If the Firebase Installation is not registered yet, this will trigger the
5089
- * registration and return an InProgressInstallationEntry.
5090
- *
5091
- * If registrationPromise does not exist, the installationEntry is guaranteed
5092
- * to be registered.
5093
- */
5094
- function triggerRegistrationIfNecessary(installations, installationEntry) {
5095
- if (installationEntry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {
5096
- if (!navigator.onLine) {
5097
- // Registration required but app is offline.
5098
- const registrationPromiseWithError = Promise.reject(ERROR_FACTORY$1.create("app-offline" /* ErrorCode.APP_OFFLINE */));
5099
- return {
5100
- installationEntry,
5101
- registrationPromise: registrationPromiseWithError
5102
- };
5103
- }
5104
- // Try registering. Change status to IN_PROGRESS.
5105
- const inProgressEntry = {
5106
- fid: installationEntry.fid,
5107
- registrationStatus: 1 /* RequestStatus.IN_PROGRESS */,
5108
- registrationTime: Date.now()
5109
- };
5110
- const registrationPromise = registerInstallation(installations, inProgressEntry);
5111
- return { installationEntry: inProgressEntry, registrationPromise };
5112
- }
5113
- else if (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {
5114
- return {
5115
- installationEntry,
5116
- registrationPromise: waitUntilFidRegistration(installations)
5117
- };
5118
- }
5119
- else {
5120
- return { installationEntry };
5121
- }
5122
- }
5123
- /** This will be executed only once for each new Firebase Installation. */
5124
- async function registerInstallation(installations, installationEntry) {
5125
- try {
5126
- const registeredInstallationEntry = await createInstallationRequest(installations, installationEntry);
5127
- return set(installations.appConfig, registeredInstallationEntry);
5128
- }
5129
- catch (e) {
5130
- if (isServerError(e) && e.customData.serverCode === 409) {
5131
- // Server returned a "FID cannot be used" error.
5132
- // Generate a new ID next time.
5133
- await remove(installations.appConfig);
5134
- }
5135
- else {
5136
- // Registration failed. Set FID as not registered.
5137
- await set(installations.appConfig, {
5138
- fid: installationEntry.fid,
5139
- registrationStatus: 0 /* RequestStatus.NOT_STARTED */
5140
- });
5141
- }
5142
- throw e;
5143
- }
5144
- }
5145
- /** Call if FID registration is pending in another request. */
5146
- async function waitUntilFidRegistration(installations) {
5147
- // Unfortunately, there is no way of reliably observing when a value in
5148
- // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),
5149
- // so we need to poll.
5150
- let entry = await updateInstallationRequest(installations.appConfig);
5151
- while (entry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */) {
5152
- // createInstallation request still in progress.
5153
- await sleep(100);
5154
- entry = await updateInstallationRequest(installations.appConfig);
5155
- }
5156
- if (entry.registrationStatus === 0 /* RequestStatus.NOT_STARTED */) {
5157
- // The request timed out or failed in a different call. Try again.
5158
- const { installationEntry, registrationPromise } = await getInstallationEntry(installations);
5159
- if (registrationPromise) {
5160
- return registrationPromise;
5161
- }
5162
- else {
5163
- // if there is no registrationPromise, entry is registered.
5164
- return installationEntry;
5165
- }
5166
- }
5167
- return entry;
5168
- }
5169
- /**
5170
- * Called only if there is a CreateInstallation request in progress.
5171
- *
5172
- * Updates the InstallationEntry in the DB based on the status of the
5173
- * CreateInstallation request.
5174
- *
5175
- * Returns the updated InstallationEntry.
5176
- */
5177
- function updateInstallationRequest(appConfig) {
5178
- return update(appConfig, oldEntry => {
5179
- if (!oldEntry) {
5180
- throw ERROR_FACTORY$1.create("installation-not-found" /* ErrorCode.INSTALLATION_NOT_FOUND */);
5181
- }
5182
- return clearTimedOutRequest(oldEntry);
5183
- });
5184
- }
5185
- function clearTimedOutRequest(entry) {
5186
- if (hasInstallationRequestTimedOut(entry)) {
5187
- return {
5188
- fid: entry.fid,
5189
- registrationStatus: 0 /* RequestStatus.NOT_STARTED */
5190
- };
5191
- }
5192
- return entry;
5193
- }
5194
- function hasInstallationRequestTimedOut(installationEntry) {
5195
- return (installationEntry.registrationStatus === 1 /* RequestStatus.IN_PROGRESS */ &&
5196
- installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());
5197
- }
5198
-
5199
- /**
5200
- * @license
5201
- * Copyright 2019 Google LLC
5202
- *
5203
- * Licensed under the Apache License, Version 2.0 (the "License");
5204
- * you may not use this file except in compliance with the License.
5205
- * You may obtain a copy of the License at
5206
- *
5207
- * http://www.apache.org/licenses/LICENSE-2.0
5208
- *
5209
- * Unless required by applicable law or agreed to in writing, software
5210
- * distributed under the License is distributed on an "AS IS" BASIS,
5211
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5212
- * See the License for the specific language governing permissions and
5213
- * limitations under the License.
5214
- */
5215
- async function generateAuthTokenRequest({ appConfig, heartbeatServiceProvider }, installationEntry) {
5216
- const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);
5217
- const headers = getHeadersWithAuth(appConfig, installationEntry);
5218
- // If heartbeat service exists, add the heartbeat string to the header.
5219
- const heartbeatService = heartbeatServiceProvider.getImmediate({
5220
- optional: true
5221
- });
5222
- if (heartbeatService) {
5223
- const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();
5224
- if (heartbeatsHeader) {
5225
- headers.append('x-firebase-client', heartbeatsHeader);
5226
- }
5227
- }
5228
- const body = {
5229
- installation: {
5230
- sdkVersion: PACKAGE_VERSION,
5231
- appId: appConfig.appId
5232
- }
5233
- };
5234
- const request = {
5235
- method: 'POST',
5236
- headers,
5237
- body: JSON.stringify(body)
5238
- };
5239
- const response = await retryIfServerError(() => fetch(endpoint, request));
5240
- if (response.ok) {
5241
- const responseValue = await response.json();
5242
- const completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);
5243
- return completedAuthToken;
5244
- }
5245
- else {
5246
- throw await getErrorFromResponse('Generate Auth Token', response);
5247
- }
5248
- }
5249
- function getGenerateAuthTokenEndpoint(appConfig, { fid }) {
5250
- return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;
5251
- }
5252
-
5253
- /**
5254
- * @license
5255
- * Copyright 2019 Google LLC
5256
- *
5257
- * Licensed under the Apache License, Version 2.0 (the "License");
5258
- * you may not use this file except in compliance with the License.
5259
- * You may obtain a copy of the License at
5260
- *
5261
- * http://www.apache.org/licenses/LICENSE-2.0
5262
- *
5263
- * Unless required by applicable law or agreed to in writing, software
5264
- * distributed under the License is distributed on an "AS IS" BASIS,
5265
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5266
- * See the License for the specific language governing permissions and
5267
- * limitations under the License.
5268
- */
5269
- /**
5270
- * Returns a valid authentication token for the installation. Generates a new
5271
- * token if one doesn't exist, is expired or about to expire.
5272
- *
5273
- * Should only be called if the Firebase Installation is registered.
5274
- */
5275
- async function refreshAuthToken(installations, forceRefresh = false) {
5276
- let tokenPromise;
5277
- const entry = await update(installations.appConfig, oldEntry => {
5278
- if (!isEntryRegistered(oldEntry)) {
5279
- throw ERROR_FACTORY$1.create("not-registered" /* ErrorCode.NOT_REGISTERED */);
5280
- }
5281
- const oldAuthToken = oldEntry.authToken;
5282
- if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {
5283
- // There is a valid token in the DB.
5284
- return oldEntry;
5285
- }
5286
- else if (oldAuthToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */) {
5287
- // There already is a token request in progress.
5288
- tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);
5289
- return oldEntry;
5290
- }
5291
- else {
5292
- // No token or token expired.
5293
- if (!navigator.onLine) {
5294
- throw ERROR_FACTORY$1.create("app-offline" /* ErrorCode.APP_OFFLINE */);
5295
- }
5296
- const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);
5297
- tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);
5298
- return inProgressEntry;
5299
- }
5300
- });
5301
- const authToken = tokenPromise
5302
- ? await tokenPromise
5303
- : entry.authToken;
5304
- return authToken;
5305
- }
5306
- /**
5307
- * Call only if FID is registered and Auth Token request is in progress.
5308
- *
5309
- * Waits until the current pending request finishes. If the request times out,
5310
- * tries once in this thread as well.
5311
- */
5312
- async function waitUntilAuthTokenRequest(installations, forceRefresh) {
5313
- // Unfortunately, there is no way of reliably observing when a value in
5314
- // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),
5315
- // so we need to poll.
5316
- let entry = await updateAuthTokenRequest(installations.appConfig);
5317
- while (entry.authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */) {
5318
- // generateAuthToken still in progress.
5319
- await sleep(100);
5320
- entry = await updateAuthTokenRequest(installations.appConfig);
5321
- }
5322
- const authToken = entry.authToken;
5323
- if (authToken.requestStatus === 0 /* RequestStatus.NOT_STARTED */) {
5324
- // The request timed out or failed in a different call. Try again.
5325
- return refreshAuthToken(installations, forceRefresh);
5326
- }
5327
- else {
5328
- return authToken;
5329
- }
5330
- }
5331
- /**
5332
- * Called only if there is a GenerateAuthToken request in progress.
5333
- *
5334
- * Updates the InstallationEntry in the DB based on the status of the
5335
- * GenerateAuthToken request.
5336
- *
5337
- * Returns the updated InstallationEntry.
5338
- */
5339
- function updateAuthTokenRequest(appConfig) {
5340
- return update(appConfig, oldEntry => {
5341
- if (!isEntryRegistered(oldEntry)) {
5342
- throw ERROR_FACTORY$1.create("not-registered" /* ErrorCode.NOT_REGISTERED */);
5343
- }
5344
- const oldAuthToken = oldEntry.authToken;
5345
- if (hasAuthTokenRequestTimedOut(oldAuthToken)) {
5346
- return {
5347
- ...oldEntry,
5348
- authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ }
5349
- };
5350
- }
5351
- return oldEntry;
5352
- });
5353
- }
5354
- async function fetchAuthTokenFromServer(installations, installationEntry) {
5355
- try {
5356
- const authToken = await generateAuthTokenRequest(installations, installationEntry);
5357
- const updatedInstallationEntry = {
5358
- ...installationEntry,
5359
- authToken
5360
- };
5361
- await set(installations.appConfig, updatedInstallationEntry);
5362
- return authToken;
5363
- }
5364
- catch (e) {
5365
- if (isServerError(e) &&
5366
- (e.customData.serverCode === 401 || e.customData.serverCode === 404)) {
5367
- // Server returned a "FID not found" or a "Invalid authentication" error.
5368
- // Generate a new ID next time.
5369
- await remove(installations.appConfig);
5370
- }
5371
- else {
5372
- const updatedInstallationEntry = {
5373
- ...installationEntry,
5374
- authToken: { requestStatus: 0 /* RequestStatus.NOT_STARTED */ }
5375
- };
5376
- await set(installations.appConfig, updatedInstallationEntry);
5377
- }
5378
- throw e;
5379
- }
5380
- }
5381
- function isEntryRegistered(installationEntry) {
5382
- return (installationEntry !== undefined &&
5383
- installationEntry.registrationStatus === 2 /* RequestStatus.COMPLETED */);
5384
- }
5385
- function isAuthTokenValid(authToken) {
5386
- return (authToken.requestStatus === 2 /* RequestStatus.COMPLETED */ &&
5387
- !isAuthTokenExpired(authToken));
5388
- }
5389
- function isAuthTokenExpired(authToken) {
5390
- const now = Date.now();
5391
- return (now < authToken.creationTime ||
5392
- authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);
5393
- }
5394
- /** Returns an updated InstallationEntry with an InProgressAuthToken. */
5395
- function makeAuthTokenRequestInProgressEntry(oldEntry) {
5396
- const inProgressAuthToken = {
5397
- requestStatus: 1 /* RequestStatus.IN_PROGRESS */,
5398
- requestTime: Date.now()
5399
- };
5400
- return {
5401
- ...oldEntry,
5402
- authToken: inProgressAuthToken
5403
- };
5404
- }
5405
- function hasAuthTokenRequestTimedOut(authToken) {
5406
- return (authToken.requestStatus === 1 /* RequestStatus.IN_PROGRESS */ &&
5407
- authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());
5408
- }
5409
-
5410
- /**
5411
- * @license
5412
- * Copyright 2019 Google LLC
5413
- *
5414
- * Licensed under the Apache License, Version 2.0 (the "License");
5415
- * you may not use this file except in compliance with the License.
5416
- * You may obtain a copy of the License at
5417
- *
5418
- * http://www.apache.org/licenses/LICENSE-2.0
5419
- *
5420
- * Unless required by applicable law or agreed to in writing, software
5421
- * distributed under the License is distributed on an "AS IS" BASIS,
5422
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5423
- * See the License for the specific language governing permissions and
5424
- * limitations under the License.
5425
- */
5426
- /**
5427
- * Creates a Firebase Installation if there isn't one for the app and
5428
- * returns the Installation ID.
5429
- * @param installations - The `Installations` instance.
5430
- *
5431
- * @public
5432
- */
5433
- async function getId(installations) {
5434
- const installationsImpl = installations;
5435
- const { installationEntry, registrationPromise } = await getInstallationEntry(installationsImpl);
5436
- if (registrationPromise) {
5437
- registrationPromise.catch(console.error);
5438
- }
5439
- else {
5440
- // If the installation is already registered, update the authentication
5441
- // token if needed.
5442
- refreshAuthToken(installationsImpl).catch(console.error);
5443
- }
5444
- return installationEntry.fid;
5445
- }
5446
-
5447
- /**
5448
- * @license
5449
- * Copyright 2019 Google LLC
5450
- *
5451
- * Licensed under the Apache License, Version 2.0 (the "License");
5452
- * you may not use this file except in compliance with the License.
5453
- * You may obtain a copy of the License at
5454
- *
5455
- * http://www.apache.org/licenses/LICENSE-2.0
5456
- *
5457
- * Unless required by applicable law or agreed to in writing, software
5458
- * distributed under the License is distributed on an "AS IS" BASIS,
5459
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5460
- * See the License for the specific language governing permissions and
5461
- * limitations under the License.
5462
- */
5463
- /**
5464
- * Returns a Firebase Installations auth token, identifying the current
5465
- * Firebase Installation.
5466
- * @param installations - The `Installations` instance.
5467
- * @param forceRefresh - Force refresh regardless of token expiration.
5468
- *
5469
- * @public
5470
- */
5471
- async function getToken$2(installations, forceRefresh = false) {
5472
- const installationsImpl = installations;
5473
- await completeInstallationRegistration(installationsImpl);
5474
- // At this point we either have a Registered Installation in the DB, or we've
5475
- // already thrown an error.
5476
- const authToken = await refreshAuthToken(installationsImpl, forceRefresh);
5477
- return authToken.token;
5478
- }
5479
- async function completeInstallationRegistration(installations) {
5480
- const { registrationPromise } = await getInstallationEntry(installations);
5481
- if (registrationPromise) {
5482
- // A createInstallation request is in progress. Wait until it finishes.
5483
- await registrationPromise;
5484
- }
5485
- }
5486
-
5487
- /**
5488
- * @license
5489
- * Copyright 2019 Google LLC
5490
- *
5491
- * Licensed under the Apache License, Version 2.0 (the "License");
5492
- * you may not use this file except in compliance with the License.
5493
- * You may obtain a copy of the License at
5494
- *
5495
- * http://www.apache.org/licenses/LICENSE-2.0
5496
- *
5497
- * Unless required by applicable law or agreed to in writing, software
5498
- * distributed under the License is distributed on an "AS IS" BASIS,
5499
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5500
- * See the License for the specific language governing permissions and
5501
- * limitations under the License.
5502
- */
5503
- function extractAppConfig$1(app) {
5504
- if (!app || !app.options) {
5505
- throw getMissingValueError$1('App Configuration');
5506
- }
5507
- if (!app.name) {
5508
- throw getMissingValueError$1('App Name');
5509
- }
5510
- // Required app config keys
5511
- const configKeys = [
5512
- 'projectId',
5513
- 'apiKey',
5514
- 'appId'
5515
- ];
5516
- for (const keyName of configKeys) {
5517
- if (!app.options[keyName]) {
5518
- throw getMissingValueError$1(keyName);
5519
- }
5520
- }
5521
- return {
5522
- appName: app.name,
5523
- projectId: app.options.projectId,
5524
- apiKey: app.options.apiKey,
5525
- appId: app.options.appId
5526
- };
5527
- }
5528
- function getMissingValueError$1(valueName) {
5529
- return ERROR_FACTORY$1.create("missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {
5530
- valueName
5531
- });
5532
- }
5533
-
5534
- /**
5535
- * @license
5536
- * Copyright 2020 Google LLC
5537
- *
5538
- * Licensed under the Apache License, Version 2.0 (the "License");
5539
- * you may not use this file except in compliance with the License.
5540
- * You may obtain a copy of the License at
5541
- *
5542
- * http://www.apache.org/licenses/LICENSE-2.0
5543
- *
5544
- * Unless required by applicable law or agreed to in writing, software
5545
- * distributed under the License is distributed on an "AS IS" BASIS,
5546
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5547
- * See the License for the specific language governing permissions and
5548
- * limitations under the License.
5549
- */
5550
- const INSTALLATIONS_NAME = 'installations';
5551
- const INSTALLATIONS_NAME_INTERNAL = 'installations-internal';
5552
- const publicFactory = (container) => {
5553
- const app = container.getProvider('app').getImmediate();
5554
- // Throws if app isn't configured properly.
5555
- const appConfig = extractAppConfig$1(app);
5556
- const heartbeatServiceProvider = _getProvider(app, 'heartbeat');
5557
- const installationsImpl = {
5558
- app,
5559
- appConfig,
5560
- heartbeatServiceProvider,
5561
- _delete: () => Promise.resolve()
5562
- };
5563
- return installationsImpl;
5564
- };
5565
- const internalFactory = (container) => {
5566
- const app = container.getProvider('app').getImmediate();
5567
- // Internal FIS instance relies on public FIS instance.
5568
- const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();
5569
- const installationsInternal = {
5570
- getId: () => getId(installations),
5571
- getToken: (forceRefresh) => getToken$2(installations, forceRefresh)
5572
- };
5573
- return installationsInternal;
5574
- };
5575
- function registerInstallations() {
5576
- _registerComponent(new Component(INSTALLATIONS_NAME, publicFactory, "PUBLIC" /* ComponentType.PUBLIC */));
5577
- _registerComponent(new Component(INSTALLATIONS_NAME_INTERNAL, internalFactory, "PRIVATE" /* ComponentType.PRIVATE */));
5578
- }
5579
-
5580
- /**
5581
- * The Firebase Installations Web SDK.
5582
- * This SDK does not work in a Node.js environment.
5583
- *
5584
- * @packageDocumentation
5585
- */
5586
- registerInstallations();
5587
- registerVersion(name$1, version$1);
5588
- // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
5589
- registerVersion(name$1, version$1, 'esm2020');
5590
-
5591
- /**
5592
- * @license
5593
- * Copyright 2019 Google LLC
5594
- *
5595
- * Licensed under the Apache License, Version 2.0 (the "License");
5596
- * you may not use this file except in compliance with the License.
5597
- * You may obtain a copy of the License at
5598
- *
5599
- * http://www.apache.org/licenses/LICENSE-2.0
5600
- *
5601
- * Unless required by applicable law or agreed to in writing, software
5602
- * distributed under the License is distributed on an "AS IS" BASIS,
5603
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5604
- * See the License for the specific language governing permissions and
5605
- * limitations under the License.
5606
- */
5607
- const DEFAULT_SW_PATH = '/firebase-messaging-sw.js';
5608
- const DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';
5609
- const DEFAULT_VAPID_KEY = 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';
5610
- const ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';
5611
- const CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';
5612
- const CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';
5613
- const CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';
5614
- /** Set to '1' if Analytics is enabled for the campaign */
5615
- const CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';
5616
- const DEFAULT_REGISTRATION_TIMEOUT = 10000;
5617
- var MessageType$1;
5618
- (function (MessageType) {
5619
- MessageType[MessageType["DATA_MESSAGE"] = 1] = "DATA_MESSAGE";
5620
- MessageType[MessageType["DISPLAY_NOTIFICATION"] = 3] = "DISPLAY_NOTIFICATION";
5621
- })(MessageType$1 || (MessageType$1 = {}));
5622
-
5623
- /**
5624
- * @license
5625
- * Copyright 2018 Google LLC
5626
- *
5627
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5628
- * in compliance with the License. You may obtain a copy of the License at
5629
- *
5630
- * http://www.apache.org/licenses/LICENSE-2.0
5631
- *
5632
- * Unless required by applicable law or agreed to in writing, software distributed under the License
5633
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
5634
- * or implied. See the License for the specific language governing permissions and limitations under
5635
- * the License.
5636
- */
5637
- var MessageType;
5638
- (function (MessageType) {
5639
- MessageType["PUSH_RECEIVED"] = "push-received";
5640
- MessageType["NOTIFICATION_CLICKED"] = "notification-clicked";
5641
- })(MessageType || (MessageType = {}));
5642
-
5643
- /**
5644
- * @license
5645
- * Copyright 2017 Google LLC
5646
- *
5647
- * Licensed under the Apache License, Version 2.0 (the "License");
5648
- * you may not use this file except in compliance with the License.
5649
- * You may obtain a copy of the License at
5650
- *
5651
- * http://www.apache.org/licenses/LICENSE-2.0
5652
- *
5653
- * Unless required by applicable law or agreed to in writing, software
5654
- * distributed under the License is distributed on an "AS IS" BASIS,
5655
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5656
- * See the License for the specific language governing permissions and
5657
- * limitations under the License.
5658
- */
5659
- function arrayToBase64(array) {
5660
- const uint8Array = new Uint8Array(array);
5661
- const base64String = btoa(String.fromCharCode(...uint8Array));
5662
- return base64String.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
5663
- }
5664
- function base64ToArray(base64String) {
5665
- const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
5666
- const base64 = (base64String + padding)
5667
- .replace(/\-/g, '+')
5668
- .replace(/_/g, '/');
5669
- const rawData = atob(base64);
5670
- const outputArray = new Uint8Array(rawData.length);
5671
- for (let i = 0; i < rawData.length; ++i) {
5672
- outputArray[i] = rawData.charCodeAt(i);
5673
- }
5674
- return outputArray;
5675
- }
5676
-
5677
- /**
5678
- * @license
5679
- * Copyright 2019 Google LLC
5680
- *
5681
- * Licensed under the Apache License, Version 2.0 (the "License");
5682
- * you may not use this file except in compliance with the License.
5683
- * You may obtain a copy of the License at
5684
- *
5685
- * http://www.apache.org/licenses/LICENSE-2.0
5686
- *
5687
- * Unless required by applicable law or agreed to in writing, software
5688
- * distributed under the License is distributed on an "AS IS" BASIS,
5689
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5690
- * See the License for the specific language governing permissions and
5691
- * limitations under the License.
5692
- */
5693
- const OLD_DB_NAME = 'fcm_token_details_db';
5694
- /**
5695
- * The last DB version of 'fcm_token_details_db' was 4. This is one higher, so that the upgrade
5696
- * callback is called for all versions of the old DB.
5697
- */
5698
- const OLD_DB_VERSION = 5;
5699
- const OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';
5700
- async function migrateOldDatabase(senderId) {
5701
- if ('databases' in indexedDB) {
5702
- // indexedDb.databases() is an IndexedDB v3 API and does not exist in all browsers. TODO: Remove
5703
- // typecast when it lands in TS types.
5704
- const databases = await indexedDB.databases();
5705
- const dbNames = databases.map(db => db.name);
5706
- if (!dbNames.includes(OLD_DB_NAME)) {
5707
- // old DB didn't exist, no need to open.
5708
- return null;
5709
- }
5710
- }
5711
- let tokenDetails = null;
5712
- const db = await openDB(OLD_DB_NAME, OLD_DB_VERSION, {
5713
- upgrade: async (db, oldVersion, newVersion, upgradeTransaction) => {
5714
- if (oldVersion < 2) {
5715
- // Database too old, skip migration.
5716
- return;
5717
- }
5718
- if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {
5719
- // Database did not exist. Nothing to do.
5720
- return;
5721
- }
5722
- const objectStore = upgradeTransaction.objectStore(OLD_OBJECT_STORE_NAME);
5723
- const value = await objectStore.index('fcmSenderId').get(senderId);
5724
- await objectStore.clear();
5725
- if (!value) {
5726
- // No entry in the database, nothing to migrate.
5727
- return;
5728
- }
5729
- if (oldVersion === 2) {
5730
- const oldDetails = value;
5731
- if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {
5732
- return;
5733
- }
5734
- tokenDetails = {
5735
- token: oldDetails.fcmToken,
5736
- createTime: oldDetails.createTime ?? Date.now(),
5737
- subscriptionOptions: {
5738
- auth: oldDetails.auth,
5739
- p256dh: oldDetails.p256dh,
5740
- endpoint: oldDetails.endpoint,
5741
- swScope: oldDetails.swScope,
5742
- vapidKey: typeof oldDetails.vapidKey === 'string'
5743
- ? oldDetails.vapidKey
5744
- : arrayToBase64(oldDetails.vapidKey)
5745
- }
5746
- };
5747
- }
5748
- else if (oldVersion === 3) {
5749
- const oldDetails = value;
5750
- tokenDetails = {
5751
- token: oldDetails.fcmToken,
5752
- createTime: oldDetails.createTime,
5753
- subscriptionOptions: {
5754
- auth: arrayToBase64(oldDetails.auth),
5755
- p256dh: arrayToBase64(oldDetails.p256dh),
5756
- endpoint: oldDetails.endpoint,
5757
- swScope: oldDetails.swScope,
5758
- vapidKey: arrayToBase64(oldDetails.vapidKey)
5759
- }
5760
- };
5761
- }
5762
- else if (oldVersion === 4) {
5763
- const oldDetails = value;
5764
- tokenDetails = {
5765
- token: oldDetails.fcmToken,
5766
- createTime: oldDetails.createTime,
5767
- subscriptionOptions: {
5768
- auth: arrayToBase64(oldDetails.auth),
5769
- p256dh: arrayToBase64(oldDetails.p256dh),
5770
- endpoint: oldDetails.endpoint,
5771
- swScope: oldDetails.swScope,
5772
- vapidKey: arrayToBase64(oldDetails.vapidKey)
5773
- }
5774
- };
5775
- }
5776
- }
5777
- });
5778
- db.close();
5779
- // Delete all old databases.
5780
- await deleteDB(OLD_DB_NAME);
5781
- await deleteDB('fcm_vapid_details_db');
5782
- await deleteDB('undefined');
5783
- return checkTokenDetails(tokenDetails) ? tokenDetails : null;
5784
- }
5785
- function checkTokenDetails(tokenDetails) {
5786
- if (!tokenDetails || !tokenDetails.subscriptionOptions) {
5787
- return false;
5788
- }
5789
- const { subscriptionOptions } = tokenDetails;
5790
- return (typeof tokenDetails.createTime === 'number' &&
5791
- tokenDetails.createTime > 0 &&
5792
- typeof tokenDetails.token === 'string' &&
5793
- tokenDetails.token.length > 0 &&
5794
- typeof subscriptionOptions.auth === 'string' &&
5795
- subscriptionOptions.auth.length > 0 &&
5796
- typeof subscriptionOptions.p256dh === 'string' &&
5797
- subscriptionOptions.p256dh.length > 0 &&
5798
- typeof subscriptionOptions.endpoint === 'string' &&
5799
- subscriptionOptions.endpoint.length > 0 &&
5800
- typeof subscriptionOptions.swScope === 'string' &&
5801
- subscriptionOptions.swScope.length > 0 &&
5802
- typeof subscriptionOptions.vapidKey === 'string' &&
5803
- subscriptionOptions.vapidKey.length > 0);
5804
- }
5805
-
5806
- /**
5807
- * @license
5808
- * Copyright 2019 Google LLC
5809
- *
5810
- * Licensed under the Apache License, Version 2.0 (the "License");
5811
- * you may not use this file except in compliance with the License.
5812
- * You may obtain a copy of the License at
5813
- *
5814
- * http://www.apache.org/licenses/LICENSE-2.0
5815
- *
5816
- * Unless required by applicable law or agreed to in writing, software
5817
- * distributed under the License is distributed on an "AS IS" BASIS,
5818
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5819
- * See the License for the specific language governing permissions and
5820
- * limitations under the License.
5821
- */
5822
- // Exported for tests.
5823
- const DATABASE_NAME = 'firebase-messaging-database';
5824
- const DATABASE_VERSION = 1;
5825
- const OBJECT_STORE_NAME = 'firebase-messaging-store';
5826
- let dbPromise = null;
5827
- function getDbPromise() {
5828
- if (!dbPromise) {
5829
- dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, {
5830
- upgrade: (upgradeDb, oldVersion) => {
5831
- // We don't use 'break' in this switch statement, the fall-through behavior is what we want,
5832
- // because if there are multiple versions between the old version and the current version, we
5833
- // want ALL the migrations that correspond to those versions to run, not only the last one.
5834
- // eslint-disable-next-line default-case
5835
- switch (oldVersion) {
5836
- case 0:
5837
- upgradeDb.createObjectStore(OBJECT_STORE_NAME);
5838
- }
5839
- }
5840
- });
5841
- }
5842
- return dbPromise;
5843
- }
5844
- /** Gets record(s) from the objectStore that match the given key. */
5845
- async function dbGet(firebaseDependencies) {
5846
- const key = getKey(firebaseDependencies);
5847
- const db = await getDbPromise();
5848
- const tokenDetails = (await db
5849
- .transaction(OBJECT_STORE_NAME)
5850
- .objectStore(OBJECT_STORE_NAME)
5851
- .get(key));
5852
- if (tokenDetails) {
5853
- return tokenDetails;
5854
- }
5855
- else {
5856
- // Check if there is a tokenDetails object in the old DB.
5857
- const oldTokenDetails = await migrateOldDatabase(firebaseDependencies.appConfig.senderId);
5858
- if (oldTokenDetails) {
5859
- await dbSet(firebaseDependencies, oldTokenDetails);
5860
- return oldTokenDetails;
5861
- }
5862
- }
5863
- }
5864
- /** Assigns or overwrites the record for the given key with the given value. */
5865
- async function dbSet(firebaseDependencies, tokenDetails) {
5866
- const key = getKey(firebaseDependencies);
5867
- const db = await getDbPromise();
5868
- const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
5869
- await tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key);
5870
- await tx.done;
5871
- return tokenDetails;
5872
- }
5873
- function getKey({ appConfig }) {
5874
- return appConfig.appId;
5875
- }
5876
-
5877
- /**
5878
- * @license
5879
- * Copyright 2017 Google LLC
5880
- *
5881
- * Licensed under the Apache License, Version 2.0 (the "License");
5882
- * you may not use this file except in compliance with the License.
5883
- * You may obtain a copy of the License at
5884
- *
5885
- * http://www.apache.org/licenses/LICENSE-2.0
5886
- *
5887
- * Unless required by applicable law or agreed to in writing, software
5888
- * distributed under the License is distributed on an "AS IS" BASIS,
5889
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5890
- * See the License for the specific language governing permissions and
5891
- * limitations under the License.
5892
- */
5893
- const ERROR_MAP = {
5894
- ["missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: "{$valueName}"',
5895
- ["only-available-in-window" /* ErrorCode.AVAILABLE_IN_WINDOW */]: 'This method is available in a Window context.',
5896
- ["only-available-in-sw" /* ErrorCode.AVAILABLE_IN_SW */]: 'This method is available in a service worker context.',
5897
- ["permission-default" /* ErrorCode.PERMISSION_DEFAULT */]: 'The notification permission was not granted and dismissed instead.',
5898
- ["permission-blocked" /* ErrorCode.PERMISSION_BLOCKED */]: 'The notification permission was not granted and blocked instead.',
5899
- ["unsupported-browser" /* ErrorCode.UNSUPPORTED_BROWSER */]: "This browser doesn't support the API's required to use the Firebase SDK.",
5900
- ["indexed-db-unsupported" /* ErrorCode.INDEXED_DB_UNSUPPORTED */]: "This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)",
5901
- ["failed-service-worker-registration" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */]: 'We are unable to register the default service worker. {$browserErrorMessage}',
5902
- ["token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */]: 'A problem occurred while subscribing the user to FCM: {$errorInfo}',
5903
- ["token-subscribe-no-token" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */]: 'FCM returned no token when subscribing the user to push.',
5904
- ["token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */]: 'A problem occurred while unsubscribing the ' +
5905
- 'user from FCM: {$errorInfo}',
5906
- ["token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */]: 'A problem occurred while updating the user from FCM: {$errorInfo}',
5907
- ["token-update-no-token" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */]: 'FCM returned no token when updating the user to push.',
5908
- ["use-sw-after-get-token" /* ErrorCode.USE_SW_AFTER_GET_TOKEN */]: 'The useServiceWorker() method may only be called once and must be ' +
5909
- 'called before calling getToken() to ensure your service worker is used.',
5910
- ["invalid-sw-registration" /* ErrorCode.INVALID_SW_REGISTRATION */]: 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',
5911
- ["invalid-bg-handler" /* ErrorCode.INVALID_BG_HANDLER */]: 'The input to setBackgroundMessageHandler() must be a function.',
5912
- ["invalid-vapid-key" /* ErrorCode.INVALID_VAPID_KEY */]: 'The public VAPID key must be a string.',
5913
- ["use-vapid-key-after-get-token" /* ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN */]: 'The usePublicVapidKey() method may only be called once and must be ' +
5914
- 'called before calling getToken() to ensure your VAPID key is used.'
5915
- };
5916
- const ERROR_FACTORY = new ErrorFactory('messaging', 'Messaging', ERROR_MAP);
5917
-
5918
- /**
5919
- * @license
5920
- * Copyright 2019 Google LLC
5921
- *
5922
- * Licensed under the Apache License, Version 2.0 (the "License");
5923
- * you may not use this file except in compliance with the License.
5924
- * You may obtain a copy of the License at
5925
- *
5926
- * http://www.apache.org/licenses/LICENSE-2.0
5927
- *
5928
- * Unless required by applicable law or agreed to in writing, software
5929
- * distributed under the License is distributed on an "AS IS" BASIS,
5930
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5931
- * See the License for the specific language governing permissions and
5932
- * limitations under the License.
5933
- */
5934
- async function requestGetToken(firebaseDependencies, subscriptionOptions) {
5935
- const headers = await getHeaders(firebaseDependencies);
5936
- const body = getBody(subscriptionOptions);
5937
- const subscribeOptions = {
5938
- method: 'POST',
5939
- headers,
5940
- body: JSON.stringify(body)
5941
- };
5942
- let responseData;
5943
- try {
5944
- const response = await fetch(getEndpoint(firebaseDependencies.appConfig), subscribeOptions);
5945
- responseData = await response.json();
5946
- }
5947
- catch (err) {
5948
- throw ERROR_FACTORY.create("token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {
5949
- errorInfo: err?.toString()
5950
- });
5951
- }
5952
- if (responseData.error) {
5953
- const message = responseData.error.message;
5954
- throw ERROR_FACTORY.create("token-subscribe-failed" /* ErrorCode.TOKEN_SUBSCRIBE_FAILED */, {
5955
- errorInfo: message
5956
- });
5957
- }
5958
- if (!responseData.token) {
5959
- throw ERROR_FACTORY.create("token-subscribe-no-token" /* ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN */);
5960
- }
5961
- return responseData.token;
5962
- }
5963
- async function requestUpdateToken(firebaseDependencies, tokenDetails) {
5964
- const headers = await getHeaders(firebaseDependencies);
5965
- const body = getBody(tokenDetails.subscriptionOptions);
5966
- const updateOptions = {
5967
- method: 'PATCH',
5968
- headers,
5969
- body: JSON.stringify(body)
5970
- };
5971
- let responseData;
5972
- try {
5973
- const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`, updateOptions);
5974
- responseData = await response.json();
5975
- }
5976
- catch (err) {
5977
- throw ERROR_FACTORY.create("token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */, {
5978
- errorInfo: err?.toString()
5979
- });
5980
- }
5981
- if (responseData.error) {
5982
- const message = responseData.error.message;
5983
- throw ERROR_FACTORY.create("token-update-failed" /* ErrorCode.TOKEN_UPDATE_FAILED */, {
5984
- errorInfo: message
5985
- });
5986
- }
5987
- if (!responseData.token) {
5988
- throw ERROR_FACTORY.create("token-update-no-token" /* ErrorCode.TOKEN_UPDATE_NO_TOKEN */);
5989
- }
5990
- return responseData.token;
5991
- }
5992
- async function requestDeleteToken(firebaseDependencies, token) {
5993
- const headers = await getHeaders(firebaseDependencies);
5994
- const unsubscribeOptions = {
5995
- method: 'DELETE',
5996
- headers
5997
- };
5998
- try {
5999
- const response = await fetch(`${getEndpoint(firebaseDependencies.appConfig)}/${token}`, unsubscribeOptions);
6000
- const responseData = await response.json();
6001
- if (responseData.error) {
6002
- const message = responseData.error.message;
6003
- throw ERROR_FACTORY.create("token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {
6004
- errorInfo: message
6005
- });
6006
- }
6007
- }
6008
- catch (err) {
6009
- throw ERROR_FACTORY.create("token-unsubscribe-failed" /* ErrorCode.TOKEN_UNSUBSCRIBE_FAILED */, {
6010
- errorInfo: err?.toString()
6011
- });
6012
- }
6013
- }
6014
- function getEndpoint({ projectId }) {
6015
- return `${ENDPOINT}/projects/${projectId}/registrations`;
6016
- }
6017
- async function getHeaders({ appConfig, installations }) {
6018
- const authToken = await installations.getToken();
6019
- return new Headers({
6020
- 'Content-Type': 'application/json',
6021
- Accept: 'application/json',
6022
- 'x-goog-api-key': appConfig.apiKey,
6023
- 'x-goog-firebase-installations-auth': `FIS ${authToken}`
6024
- });
6025
- }
6026
- function getBody({ p256dh, auth, endpoint, vapidKey }) {
6027
- const body = {
6028
- web: {
6029
- endpoint,
6030
- auth,
6031
- p256dh
6032
- }
6033
- };
6034
- if (vapidKey !== DEFAULT_VAPID_KEY) {
6035
- body.web.applicationPubKey = vapidKey;
6036
- }
6037
- return body;
6038
- }
6039
-
6040
- /**
6041
- * @license
6042
- * Copyright 2019 Google LLC
6043
- *
6044
- * Licensed under the Apache License, Version 2.0 (the "License");
6045
- * you may not use this file except in compliance with the License.
6046
- * You may obtain a copy of the License at
6047
- *
6048
- * http://www.apache.org/licenses/LICENSE-2.0
6049
- *
6050
- * Unless required by applicable law or agreed to in writing, software
6051
- * distributed under the License is distributed on an "AS IS" BASIS,
6052
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6053
- * See the License for the specific language governing permissions and
6054
- * limitations under the License.
6055
- */
6056
- // UpdateRegistration will be called once every week.
6057
- const TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
6058
- async function getTokenInternal(messaging) {
6059
- const pushSubscription = await getPushSubscription(messaging.swRegistration, messaging.vapidKey);
6060
- const subscriptionOptions = {
6061
- vapidKey: messaging.vapidKey,
6062
- swScope: messaging.swRegistration.scope,
6063
- endpoint: pushSubscription.endpoint,
6064
- auth: arrayToBase64(pushSubscription.getKey('auth')),
6065
- p256dh: arrayToBase64(pushSubscription.getKey('p256dh'))
6066
- };
6067
- const tokenDetails = await dbGet(messaging.firebaseDependencies);
6068
- if (!tokenDetails) {
6069
- // No token, get a new one.
6070
- return getNewToken(messaging.firebaseDependencies, subscriptionOptions);
6071
- }
6072
- else if (!isTokenValid(tokenDetails.subscriptionOptions, subscriptionOptions)) {
6073
- // Invalid token, get a new one.
6074
- try {
6075
- await requestDeleteToken(messaging.firebaseDependencies, tokenDetails.token);
6076
- }
6077
- catch (e) {
6078
- // Suppress errors because of #2364
6079
- console.warn(e);
6080
- }
6081
- return getNewToken(messaging.firebaseDependencies, subscriptionOptions);
6082
- }
6083
- else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {
6084
- // Weekly token refresh
6085
- return updateToken(messaging, {
6086
- token: tokenDetails.token,
6087
- createTime: Date.now(),
6088
- subscriptionOptions
6089
- });
6090
- }
6091
- else {
6092
- // Valid token, nothing to do.
6093
- return tokenDetails.token;
6094
- }
6095
- }
6096
- async function updateToken(messaging, tokenDetails) {
6097
- try {
6098
- const updatedToken = await requestUpdateToken(messaging.firebaseDependencies, tokenDetails);
6099
- const updatedTokenDetails = {
6100
- ...tokenDetails,
6101
- token: updatedToken,
6102
- createTime: Date.now()
6103
- };
6104
- await dbSet(messaging.firebaseDependencies, updatedTokenDetails);
6105
- return updatedToken;
6106
- }
6107
- catch (e) {
6108
- throw e;
6109
- }
6110
- }
6111
- async function getNewToken(firebaseDependencies, subscriptionOptions) {
6112
- const token = await requestGetToken(firebaseDependencies, subscriptionOptions);
6113
- const tokenDetails = {
6114
- token,
6115
- createTime: Date.now(),
6116
- subscriptionOptions
6117
- };
6118
- await dbSet(firebaseDependencies, tokenDetails);
6119
- return tokenDetails.token;
6120
- }
6121
- /**
6122
- * Gets a PushSubscription for the current user.
6123
- */
6124
- async function getPushSubscription(swRegistration, vapidKey) {
6125
- const subscription = await swRegistration.pushManager.getSubscription();
6126
- if (subscription) {
6127
- return subscription;
6128
- }
6129
- return swRegistration.pushManager.subscribe({
6130
- userVisibleOnly: true,
6131
- // Chrome <= 75 doesn't support base64-encoded VAPID key. For backward compatibility, VAPID key
6132
- // submitted to pushManager#subscribe must be of type Uint8Array.
6133
- applicationServerKey: base64ToArray(vapidKey)
6134
- });
6135
- }
6136
- /**
6137
- * Checks if the saved tokenDetails object matches the configuration provided.
6138
- */
6139
- function isTokenValid(dbOptions, currentOptions) {
6140
- const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;
6141
- const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;
6142
- const isAuthEqual = currentOptions.auth === dbOptions.auth;
6143
- const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;
6144
- return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;
6145
- }
6146
-
6147
- /**
6148
- * @license
6149
- * Copyright 2020 Google LLC
6150
- *
6151
- * Licensed under the Apache License, Version 2.0 (the "License");
6152
- * you may not use this file except in compliance with the License.
6153
- * You may obtain a copy of the License at
6154
- *
6155
- * http://www.apache.org/licenses/LICENSE-2.0
6156
- *
6157
- * Unless required by applicable law or agreed to in writing, software
6158
- * distributed under the License is distributed on an "AS IS" BASIS,
6159
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6160
- * See the License for the specific language governing permissions and
6161
- * limitations under the License.
6162
- */
6163
- function externalizePayload(internalPayload) {
6164
- const payload = {
6165
- from: internalPayload.from,
6166
- // eslint-disable-next-line camelcase
6167
- collapseKey: internalPayload.collapse_key,
6168
- // eslint-disable-next-line camelcase
6169
- messageId: internalPayload.fcmMessageId
6170
- };
6171
- propagateNotificationPayload(payload, internalPayload);
6172
- propagateDataPayload(payload, internalPayload);
6173
- propagateFcmOptions(payload, internalPayload);
6174
- return payload;
6175
- }
6176
- function propagateNotificationPayload(payload, messagePayloadInternal) {
6177
- if (!messagePayloadInternal.notification) {
6178
- return;
6179
- }
6180
- payload.notification = {};
6181
- const title = messagePayloadInternal.notification.title;
6182
- if (!!title) {
6183
- payload.notification.title = title;
6184
- }
6185
- const body = messagePayloadInternal.notification.body;
6186
- if (!!body) {
6187
- payload.notification.body = body;
6188
- }
6189
- const image = messagePayloadInternal.notification.image;
6190
- if (!!image) {
6191
- payload.notification.image = image;
6192
- }
6193
- const icon = messagePayloadInternal.notification.icon;
6194
- if (!!icon) {
6195
- payload.notification.icon = icon;
6196
- }
6197
- }
6198
- function propagateDataPayload(payload, messagePayloadInternal) {
6199
- if (!messagePayloadInternal.data) {
6200
- return;
6201
- }
6202
- payload.data = messagePayloadInternal.data;
6203
- }
6204
- function propagateFcmOptions(payload, messagePayloadInternal) {
6205
- // fcmOptions.link value is written into notification.click_action. see more in b/232072111
6206
- if (!messagePayloadInternal.fcmOptions &&
6207
- !messagePayloadInternal.notification?.click_action) {
6208
- return;
6209
- }
6210
- payload.fcmOptions = {};
6211
- const link = messagePayloadInternal.fcmOptions?.link ??
6212
- messagePayloadInternal.notification?.click_action;
6213
- if (!!link) {
6214
- payload.fcmOptions.link = link;
6215
- }
6216
- // eslint-disable-next-line camelcase
6217
- const analyticsLabel = messagePayloadInternal.fcmOptions?.analytics_label;
6218
- if (!!analyticsLabel) {
6219
- payload.fcmOptions.analyticsLabel = analyticsLabel;
6220
- }
6221
- }
6222
-
6223
- /**
6224
- * @license
6225
- * Copyright 2019 Google LLC
6226
- *
6227
- * Licensed under the Apache License, Version 2.0 (the "License");
6228
- * you may not use this file except in compliance with the License.
6229
- * You may obtain a copy of the License at
6230
- *
6231
- * http://www.apache.org/licenses/LICENSE-2.0
6232
- *
6233
- * Unless required by applicable law or agreed to in writing, software
6234
- * distributed under the License is distributed on an "AS IS" BASIS,
6235
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6236
- * See the License for the specific language governing permissions and
6237
- * limitations under the License.
6238
- */
6239
- function isConsoleMessage(data) {
6240
- // This message has a campaign ID, meaning it was sent using the Firebase Console.
6241
- return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;
6242
- }
6243
-
6244
- /**
6245
- * @license
6246
- * Copyright 2019 Google LLC
6247
- *
6248
- * Licensed under the Apache License, Version 2.0 (the "License");
6249
- * you may not use this file except in compliance with the License.
6250
- * You may obtain a copy of the License at
6251
- *
6252
- * http://www.apache.org/licenses/LICENSE-2.0
6253
- *
6254
- * Unless required by applicable law or agreed to in writing, software
6255
- * distributed under the License is distributed on an "AS IS" BASIS,
6256
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6257
- * See the License for the specific language governing permissions and
6258
- * limitations under the License.
6259
- */
6260
- _mergeStrings('AzSCbw63g1R0nCw85jG8', 'Iaya3yLKwmgvh7cF0q4');
6261
- function _mergeStrings(s1, s2) {
6262
- const resultArray = [];
6263
- for (let i = 0; i < s1.length; i++) {
6264
- resultArray.push(s1.charAt(i));
6265
- if (i < s2.length) {
6266
- resultArray.push(s2.charAt(i));
6267
- }
6268
- }
6269
- return resultArray.join('');
6270
- }
6271
-
6272
- /**
6273
- * @license
6274
- * Copyright 2019 Google LLC
6275
- *
6276
- * Licensed under the Apache License, Version 2.0 (the "License");
6277
- * you may not use this file except in compliance with the License.
6278
- * You may obtain a copy of the License at
6279
- *
6280
- * http://www.apache.org/licenses/LICENSE-2.0
6281
- *
6282
- * Unless required by applicable law or agreed to in writing, software
6283
- * distributed under the License is distributed on an "AS IS" BASIS,
6284
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6285
- * See the License for the specific language governing permissions and
6286
- * limitations under the License.
6287
- */
6288
- function extractAppConfig(app) {
6289
- if (!app || !app.options) {
6290
- throw getMissingValueError('App Configuration Object');
6291
- }
6292
- if (!app.name) {
6293
- throw getMissingValueError('App Name');
6294
- }
6295
- // Required app config keys
6296
- const configKeys = [
6297
- 'projectId',
6298
- 'apiKey',
6299
- 'appId',
6300
- 'messagingSenderId'
6301
- ];
6302
- const { options } = app;
6303
- for (const keyName of configKeys) {
6304
- if (!options[keyName]) {
6305
- throw getMissingValueError(keyName);
6306
- }
6307
- }
6308
- return {
6309
- appName: app.name,
6310
- projectId: options.projectId,
6311
- apiKey: options.apiKey,
6312
- appId: options.appId,
6313
- senderId: options.messagingSenderId
6314
- };
6315
- }
6316
- function getMissingValueError(valueName) {
6317
- return ERROR_FACTORY.create("missing-app-config-values" /* ErrorCode.MISSING_APP_CONFIG_VALUES */, {
6318
- valueName
6319
- });
6320
- }
6321
-
6322
- /**
6323
- * @license
6324
- * Copyright 2020 Google LLC
6325
- *
6326
- * Licensed under the Apache License, Version 2.0 (the "License");
6327
- * you may not use this file except in compliance with the License.
6328
- * You may obtain a copy of the License at
6329
- *
6330
- * http://www.apache.org/licenses/LICENSE-2.0
6331
- *
6332
- * Unless required by applicable law or agreed to in writing, software
6333
- * distributed under the License is distributed on an "AS IS" BASIS,
6334
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6335
- * See the License for the specific language governing permissions and
6336
- * limitations under the License.
6337
- */
6338
- class MessagingService {
6339
- constructor(app, installations, analyticsProvider) {
6340
- // logging is only done with end user consent. Default to false.
6341
- this.deliveryMetricsExportedToBigQueryEnabled = false;
6342
- this.onBackgroundMessageHandler = null;
6343
- this.onMessageHandler = null;
6344
- this.logEvents = [];
6345
- this.isLogServiceStarted = false;
6346
- const appConfig = extractAppConfig(app);
6347
- this.firebaseDependencies = {
6348
- app,
6349
- appConfig,
6350
- installations,
6351
- analyticsProvider
6352
- };
6353
- }
6354
- _delete() {
6355
- return Promise.resolve();
6356
- }
6357
- }
6358
-
6359
- /**
6360
- * @license
6361
- * Copyright 2020 Google LLC
6362
- *
6363
- * Licensed under the Apache License, Version 2.0 (the "License");
6364
- * you may not use this file except in compliance with the License.
6365
- * You may obtain a copy of the License at
6366
- *
6367
- * http://www.apache.org/licenses/LICENSE-2.0
6368
- *
6369
- * Unless required by applicable law or agreed to in writing, software
6370
- * distributed under the License is distributed on an "AS IS" BASIS,
6371
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6372
- * See the License for the specific language governing permissions and
6373
- * limitations under the License.
6374
- */
6375
- async function registerDefaultSw(messaging) {
6376
- try {
6377
- messaging.swRegistration = await navigator.serviceWorker.register(DEFAULT_SW_PATH, {
6378
- scope: DEFAULT_SW_SCOPE
6379
- });
6380
- // The timing when browser updates sw when sw has an update is unreliable from experiment. It
6381
- // leads to version conflict when the SDK upgrades to a newer version in the main page, but sw
6382
- // is stuck with the old version. For example,
6383
- // https://github.com/firebase/firebase-js-sdk/issues/2590 The following line reliably updates
6384
- // sw if there was an update.
6385
- messaging.swRegistration.update().catch(() => {
6386
- /* it is non blocking and we don't care if it failed */
6387
- });
6388
- await waitForRegistrationActive(messaging.swRegistration);
6389
- }
6390
- catch (e) {
6391
- throw ERROR_FACTORY.create("failed-service-worker-registration" /* ErrorCode.FAILED_DEFAULT_REGISTRATION */, {
6392
- browserErrorMessage: e?.message
6393
- });
6394
- }
6395
- }
6396
- /**
6397
- * Waits for registration to become active. MDN documentation claims that
6398
- * a service worker registration should be ready to use after awaiting
6399
- * navigator.serviceWorker.register() but that doesn't seem to be the case in
6400
- * practice, causing the SDK to throw errors when calling
6401
- * swRegistration.pushManager.subscribe() too soon after register(). The only
6402
- * solution seems to be waiting for the service worker registration `state`
6403
- * to become "active".
6404
- */
6405
- async function waitForRegistrationActive(registration) {
6406
- return new Promise((resolve, reject) => {
6407
- const rejectTimeout = setTimeout(() => reject(new Error(`Service worker not registered after ${DEFAULT_REGISTRATION_TIMEOUT} ms`)), DEFAULT_REGISTRATION_TIMEOUT);
6408
- const incomingSw = registration.installing || registration.waiting;
6409
- if (registration.active) {
6410
- clearTimeout(rejectTimeout);
6411
- resolve();
6412
- }
6413
- else if (incomingSw) {
6414
- incomingSw.onstatechange = ev => {
6415
- if (ev.target?.state === 'activated') {
6416
- incomingSw.onstatechange = null;
6417
- clearTimeout(rejectTimeout);
6418
- resolve();
6419
- }
6420
- };
6421
- }
6422
- else {
6423
- clearTimeout(rejectTimeout);
6424
- reject(new Error('No incoming service worker found.'));
6425
- }
6426
- });
6427
- }
6428
-
6429
- /**
6430
- * @license
6431
- * Copyright 2020 Google LLC
6432
- *
6433
- * Licensed under the Apache License, Version 2.0 (the "License");
6434
- * you may not use this file except in compliance with the License.
6435
- * You may obtain a copy of the License at
6436
- *
6437
- * http://www.apache.org/licenses/LICENSE-2.0
6438
- *
6439
- * Unless required by applicable law or agreed to in writing, software
6440
- * distributed under the License is distributed on an "AS IS" BASIS,
6441
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6442
- * See the License for the specific language governing permissions and
6443
- * limitations under the License.
6444
- */
6445
- async function updateSwReg(messaging, swRegistration) {
6446
- if (!swRegistration && !messaging.swRegistration) {
6447
- await registerDefaultSw(messaging);
6448
- }
6449
- if (!swRegistration && !!messaging.swRegistration) {
6450
- return;
6451
- }
6452
- if (!(swRegistration instanceof ServiceWorkerRegistration)) {
6453
- throw ERROR_FACTORY.create("invalid-sw-registration" /* ErrorCode.INVALID_SW_REGISTRATION */);
6454
- }
6455
- messaging.swRegistration = swRegistration;
6456
- }
6457
-
6458
- /**
6459
- * @license
6460
- * Copyright 2020 Google LLC
6461
- *
6462
- * Licensed under the Apache License, Version 2.0 (the "License");
6463
- * you may not use this file except in compliance with the License.
6464
- * You may obtain a copy of the License at
6465
- *
6466
- * http://www.apache.org/licenses/LICENSE-2.0
6467
- *
6468
- * Unless required by applicable law or agreed to in writing, software
6469
- * distributed under the License is distributed on an "AS IS" BASIS,
6470
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6471
- * See the License for the specific language governing permissions and
6472
- * limitations under the License.
6473
- */
6474
- async function updateVapidKey(messaging, vapidKey) {
6475
- if (!!vapidKey) {
6476
- messaging.vapidKey = vapidKey;
6477
- }
6478
- else if (!messaging.vapidKey) {
6479
- messaging.vapidKey = DEFAULT_VAPID_KEY;
6480
- }
6481
- }
6482
-
6483
- /**
6484
- * @license
6485
- * Copyright 2020 Google LLC
6486
- *
6487
- * Licensed under the Apache License, Version 2.0 (the "License");
6488
- * you may not use this file except in compliance with the License.
6489
- * You may obtain a copy of the License at
6490
- *
6491
- * http://www.apache.org/licenses/LICENSE-2.0
6492
- *
6493
- * Unless required by applicable law or agreed to in writing, software
6494
- * distributed under the License is distributed on an "AS IS" BASIS,
6495
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6496
- * See the License for the specific language governing permissions and
6497
- * limitations under the License.
6498
- */
6499
- async function getToken$1(messaging, options) {
6500
- if (!navigator) {
6501
- throw ERROR_FACTORY.create("only-available-in-window" /* ErrorCode.AVAILABLE_IN_WINDOW */);
6502
- }
6503
- if (Notification.permission === 'default') {
6504
- await Notification.requestPermission();
6505
- }
6506
- if (Notification.permission !== 'granted') {
6507
- throw ERROR_FACTORY.create("permission-blocked" /* ErrorCode.PERMISSION_BLOCKED */);
6508
- }
6509
- await updateVapidKey(messaging, options?.vapidKey);
6510
- await updateSwReg(messaging, options?.serviceWorkerRegistration);
6511
- return getTokenInternal(messaging);
6512
- }
6513
-
6514
- /**
6515
- * @license
6516
- * Copyright 2019 Google LLC
6517
- *
6518
- * Licensed under the Apache License, Version 2.0 (the "License");
6519
- * you may not use this file except in compliance with the License.
6520
- * You may obtain a copy of the License at
6521
- *
6522
- * http://www.apache.org/licenses/LICENSE-2.0
6523
- *
6524
- * Unless required by applicable law or agreed to in writing, software
6525
- * distributed under the License is distributed on an "AS IS" BASIS,
6526
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6527
- * See the License for the specific language governing permissions and
6528
- * limitations under the License.
6529
- */
6530
- async function logToScion(messaging, messageType, data) {
6531
- const eventType = getEventType(messageType);
6532
- const analytics = await messaging.firebaseDependencies.analyticsProvider.get();
6533
- analytics.logEvent(eventType, {
6534
- /* eslint-disable camelcase */
6535
- message_id: data[CONSOLE_CAMPAIGN_ID],
6536
- message_name: data[CONSOLE_CAMPAIGN_NAME],
6537
- message_time: data[CONSOLE_CAMPAIGN_TIME],
6538
- message_device_time: Math.floor(Date.now() / 1000)
6539
- /* eslint-enable camelcase */
6540
- });
6541
- }
6542
- function getEventType(messageType) {
6543
- switch (messageType) {
6544
- case MessageType.NOTIFICATION_CLICKED:
6545
- return 'notification_open';
6546
- case MessageType.PUSH_RECEIVED:
6547
- return 'notification_foreground';
6548
- default:
6549
- throw new Error();
6550
- }
6551
- }
6552
-
6553
- /**
6554
- * @license
6555
- * Copyright 2017 Google LLC
6556
- *
6557
- * Licensed under the Apache License, Version 2.0 (the "License");
6558
- * you may not use this file except in compliance with the License.
6559
- * You may obtain a copy of the License at
6560
- *
6561
- * http://www.apache.org/licenses/LICENSE-2.0
6562
- *
6563
- * Unless required by applicable law or agreed to in writing, software
6564
- * distributed under the License is distributed on an "AS IS" BASIS,
6565
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6566
- * See the License for the specific language governing permissions and
6567
- * limitations under the License.
6568
- */
6569
- async function messageEventListener(messaging, event) {
6570
- const internalPayload = event.data;
6571
- if (!internalPayload.isFirebaseMessaging) {
6572
- return;
6573
- }
6574
- if (messaging.onMessageHandler &&
6575
- internalPayload.messageType === MessageType.PUSH_RECEIVED) {
6576
- if (typeof messaging.onMessageHandler === 'function') {
6577
- messaging.onMessageHandler(externalizePayload(internalPayload));
6578
- }
6579
- else {
6580
- messaging.onMessageHandler.next(externalizePayload(internalPayload));
6581
- }
6582
- }
6583
- // Log to Scion if applicable
6584
- const dataPayload = internalPayload.data;
6585
- if (isConsoleMessage(dataPayload) &&
6586
- dataPayload[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1') {
6587
- await logToScion(messaging, internalPayload.messageType, dataPayload);
6588
- }
6589
- }
6590
-
6591
- const name = "@firebase/messaging";
6592
- const version = "0.12.23";
6593
-
6594
- /**
6595
- * @license
6596
- * Copyright 2020 Google LLC
6597
- *
6598
- * Licensed under the Apache License, Version 2.0 (the "License");
6599
- * you may not use this file except in compliance with the License.
6600
- * You may obtain a copy of the License at
6601
- *
6602
- * http://www.apache.org/licenses/LICENSE-2.0
6603
- *
6604
- * Unless required by applicable law or agreed to in writing, software
6605
- * distributed under the License is distributed on an "AS IS" BASIS,
6606
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6607
- * See the License for the specific language governing permissions and
6608
- * limitations under the License.
6609
- */
6610
- const WindowMessagingFactory = (container) => {
6611
- const messaging = new MessagingService(container.getProvider('app').getImmediate(), container.getProvider('installations-internal').getImmediate(), container.getProvider('analytics-internal'));
6612
- navigator.serviceWorker.addEventListener('message', e => messageEventListener(messaging, e));
6613
- return messaging;
6614
- };
6615
- const WindowMessagingInternalFactory = (container) => {
6616
- const messaging = container
6617
- .getProvider('messaging')
6618
- .getImmediate();
6619
- const messagingInternal = {
6620
- getToken: (options) => getToken$1(messaging, options)
6621
- };
6622
- return messagingInternal;
6623
- };
6624
- function registerMessagingInWindow() {
6625
- _registerComponent(new Component('messaging', WindowMessagingFactory, "PUBLIC" /* ComponentType.PUBLIC */));
6626
- _registerComponent(new Component('messaging-internal', WindowMessagingInternalFactory, "PRIVATE" /* ComponentType.PRIVATE */));
6627
- registerVersion(name, version);
6628
- // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
6629
- registerVersion(name, version, 'esm2020');
6630
- }
6631
-
6632
- /**
6633
- * @license
6634
- * Copyright 2020 Google LLC
6635
- *
6636
- * Licensed under the Apache License, Version 2.0 (the "License");
6637
- * you may not use this file except in compliance with the License.
6638
- * You may obtain a copy of the License at
6639
- *
6640
- * http://www.apache.org/licenses/LICENSE-2.0
6641
- *
6642
- * Unless required by applicable law or agreed to in writing, software
6643
- * distributed under the License is distributed on an "AS IS" BASIS,
6644
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6645
- * See the License for the specific language governing permissions and
6646
- * limitations under the License.
6647
- */
6648
- /**
6649
- * Checks if all required APIs exist in the browser.
6650
- * @returns a Promise that resolves to a boolean.
6651
- *
6652
- * @public
6653
- */
6654
- async function isWindowSupported() {
6655
- try {
6656
- // This throws if open() is unsupported, so adding it to the conditional
6657
- // statement below can cause an uncaught error.
6658
- await validateIndexedDBOpenable();
6659
- }
6660
- catch (e) {
6661
- return false;
6662
- }
6663
- // firebase-js-sdk/issues/2393 reveals that idb#open in Safari iframe and Firefox private browsing
6664
- // might be prohibited to run. In these contexts, an error would be thrown during the messaging
6665
- // instantiating phase, informing the developers to import/call isSupported for special handling.
6666
- return (typeof window !== 'undefined' &&
6667
- isIndexedDBAvailable() &&
6668
- areCookiesEnabled() &&
6669
- 'serviceWorker' in navigator &&
6670
- 'PushManager' in window &&
6671
- 'Notification' in window &&
6672
- 'fetch' in window &&
6673
- ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&
6674
- PushSubscription.prototype.hasOwnProperty('getKey'));
6675
- }
6676
-
6677
- /**
6678
- * @license
6679
- * Copyright 2020 Google LLC
6680
- *
6681
- * Licensed under the Apache License, Version 2.0 (the "License");
6682
- * you may not use this file except in compliance with the License.
6683
- * You may obtain a copy of the License at
6684
- *
6685
- * http://www.apache.org/licenses/LICENSE-2.0
6686
- *
6687
- * Unless required by applicable law or agreed to in writing, software
6688
- * distributed under the License is distributed on an "AS IS" BASIS,
6689
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6690
- * See the License for the specific language governing permissions and
6691
- * limitations under the License.
6692
- */
6693
- function onMessage$1(messaging, nextOrObserver) {
6694
- if (!navigator) {
6695
- throw ERROR_FACTORY.create("only-available-in-window" /* ErrorCode.AVAILABLE_IN_WINDOW */);
6696
- }
6697
- messaging.onMessageHandler = nextOrObserver;
6698
- return () => {
6699
- messaging.onMessageHandler = null;
6700
- };
6701
- }
6702
-
6703
- /**
6704
- * @license
6705
- * Copyright 2017 Google LLC
6706
- *
6707
- * Licensed under the Apache License, Version 2.0 (the "License");
6708
- * you may not use this file except in compliance with the License.
6709
- * You may obtain a copy of the License at
6710
- *
6711
- * http://www.apache.org/licenses/LICENSE-2.0
6712
- *
6713
- * Unless required by applicable law or agreed to in writing, software
6714
- * distributed under the License is distributed on an "AS IS" BASIS,
6715
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6716
- * See the License for the specific language governing permissions and
6717
- * limitations under the License.
6718
- */
6719
- /**
6720
- * Retrieves a Firebase Cloud Messaging instance.
6721
- *
6722
- * @returns The Firebase Cloud Messaging instance associated with the provided firebase app.
6723
- *
6724
- * @public
6725
- */
6726
- function getMessagingInWindow(app = getApp()) {
6727
- // Conscious decision to make this async check non-blocking during the messaging instance
6728
- // initialization phase for performance consideration. An error would be thrown latter for
6729
- // developer's information. Developers can then choose to import and call `isSupported` for
6730
- // special handling.
6731
- isWindowSupported().then(isSupported => {
6732
- // If `isWindowSupported()` resolved, but returned false.
6733
- if (!isSupported) {
6734
- throw ERROR_FACTORY.create("unsupported-browser" /* ErrorCode.UNSUPPORTED_BROWSER */);
6735
- }
6736
- }, _ => {
6737
- // If `isWindowSupported()` rejected.
6738
- throw ERROR_FACTORY.create("indexed-db-unsupported" /* ErrorCode.INDEXED_DB_UNSUPPORTED */);
6739
- });
6740
- return _getProvider(getModularInstance(app), 'messaging').getImmediate();
6741
- }
6742
- /**
6743
- * Subscribes the {@link Messaging} instance to push notifications. Returns a Firebase Cloud
6744
- * Messaging registration token that can be used to send push messages to that {@link Messaging}
6745
- * instance.
6746
- *
6747
- * If notification permission isn't already granted, this method asks the user for permission. The
6748
- * returned promise rejects if the user does not allow the app to show notifications.
6749
- *
6750
- * @param messaging - The {@link Messaging} instance.
6751
- * @param options - Provides an optional vapid key and an optional service worker registration.
6752
- *
6753
- * @returns The promise resolves with an FCM registration token.
6754
- *
6755
- * @public
6756
- */
6757
- async function getToken(messaging, options) {
6758
- messaging = getModularInstance(messaging);
6759
- return getToken$1(messaging, options);
6760
- }
6761
- /**
6762
- * When a push message is received and the user is currently on a page for your origin, the
6763
- * message is passed to the page and an `onMessage()` event is dispatched with the payload of
6764
- * the push message.
6765
- *
6766
- *
6767
- * @param messaging - The {@link Messaging} instance.
6768
- * @param nextOrObserver - This function, or observer object with `next` defined,
6769
- * is called when a message is received and the user is currently viewing your page.
6770
- * @returns To stop listening for messages execute this returned function.
6771
- *
6772
- * @public
6773
- */
6774
- function onMessage(messaging, nextOrObserver) {
6775
- messaging = getModularInstance(messaging);
6776
- return onMessage$1(messaging, nextOrObserver);
6777
- }
6778
-
6779
- /**
6780
- * The Firebase Cloud Messaging Web SDK.
6781
- * This SDK does not work in a Node.js environment.
6782
- *
6783
- * @packageDocumentation
6784
- */
6785
- registerMessagingInWindow();
6786
-
6787
2148
  const useFirebase = (firebaseConfig, vapidKey, onFirebaseMessage = () => {}) => {
6788
- const [app] = React.useState(initializeApp(firebaseConfig));
6789
- const [messaging, setMessaging] = React.useState();
2149
+ const [app$1] = React.useState(app.initializeApp(firebaseConfig));
2150
+ const [messaging$1, setMessaging] = React.useState();
6790
2151
  const [firebaseToken, setFirebaseToken] = React.useState();
6791
2152
  React.useEffect(() => {
6792
- isWindowSupported().then(supported => {
2153
+ messaging.isSupported().then(supported => {
6793
2154
  if (supported) {
6794
- setMessaging(getMessagingInWindow(app));
2155
+ setMessaging(messaging.getMessaging(app$1));
6795
2156
  }
6796
2157
  });
6797
- }, [setMessaging, app]);
2158
+ }, [setMessaging, app$1]);
6798
2159
  const notificationHandler = function (permission) {
6799
- console.log("Notification permission: ", permission, messaging);
6800
- if (permission === "granted" && messaging) {
6801
- getToken(messaging, {
2160
+ console.log("Notification permission: ", permission, messaging$1);
2161
+ if (permission === "granted" && messaging$1) {
2162
+ messaging.getToken(messaging$1, {
6802
2163
  vapidKey
6803
2164
  }).then(token => {
6804
2165
  setFirebaseToken(token);
@@ -6819,13 +2180,13 @@ const useFirebase = (firebaseConfig, vapidKey, onFirebaseMessage = () => {}) =>
6819
2180
  }
6820
2181
  }
6821
2182
  }
6822
- }, [messaging]);
2183
+ }, [messaging$1]);
6823
2184
  React.useEffect(() => {
6824
- if (messaging) {
6825
- const unsubscribe = onMessage(messaging, onFirebaseMessage);
2185
+ if (messaging$1) {
2186
+ const unsubscribe = messaging.onMessage(messaging$1, onFirebaseMessage);
6826
2187
  return () => unsubscribe();
6827
2188
  }
6828
- }, [messaging, onFirebaseMessage]);
2189
+ }, [messaging$1, onFirebaseMessage]);
6829
2190
  return {
6830
2191
  firebaseToken
6831
2192
  };