datastake-daf 0.6.554 → 0.6.555

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