datastake-daf 0.6.737 → 0.6.739

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