datastake-daf 0.6.698 → 0.6.700

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