GSI - Employe Self Service Mobile
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2103 lines
70 KiB

2 months ago
  1. /**
  2. * @license
  3. * Copyright 2017 Google LLC
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /**
  18. * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.
  19. */
  20. const CONSTANTS = {
  21. /**
  22. * @define {boolean} Whether this is the client Node.js SDK.
  23. */
  24. NODE_CLIENT: false,
  25. /**
  26. * @define {boolean} Whether this is the Admin Node.js SDK.
  27. */
  28. NODE_ADMIN: false,
  29. /**
  30. * Firebase SDK Version
  31. */
  32. SDK_VERSION: '${JSCORE_VERSION}'
  33. };
  34. /**
  35. * @license
  36. * Copyright 2017 Google LLC
  37. *
  38. * Licensed under the Apache License, Version 2.0 (the "License");
  39. * you may not use this file except in compliance with the License.
  40. * You may obtain a copy of the License at
  41. *
  42. * http://www.apache.org/licenses/LICENSE-2.0
  43. *
  44. * Unless required by applicable law or agreed to in writing, software
  45. * distributed under the License is distributed on an "AS IS" BASIS,
  46. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  47. * See the License for the specific language governing permissions and
  48. * limitations under the License.
  49. */
  50. /**
  51. * Throws an error if the provided assertion is falsy
  52. */
  53. const assert = function (assertion, message) {
  54. if (!assertion) {
  55. throw assertionError(message);
  56. }
  57. };
  58. /**
  59. * Returns an Error object suitable for throwing.
  60. */
  61. const assertionError = function (message) {
  62. return new Error('Firebase Database (' +
  63. CONSTANTS.SDK_VERSION +
  64. ') INTERNAL ASSERT FAILED: ' +
  65. message);
  66. };
  67. /**
  68. * @license
  69. * Copyright 2017 Google LLC
  70. *
  71. * Licensed under the Apache License, Version 2.0 (the "License");
  72. * you may not use this file except in compliance with the License.
  73. * You may obtain a copy of the License at
  74. *
  75. * http://www.apache.org/licenses/LICENSE-2.0
  76. *
  77. * Unless required by applicable law or agreed to in writing, software
  78. * distributed under the License is distributed on an "AS IS" BASIS,
  79. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  80. * See the License for the specific language governing permissions and
  81. * limitations under the License.
  82. */
  83. const stringToByteArray$1 = function (str) {
  84. // TODO(user): Use native implementations if/when available
  85. const out = [];
  86. let p = 0;
  87. for (let i = 0; i < str.length; i++) {
  88. let c = str.charCodeAt(i);
  89. if (c < 128) {
  90. out[p++] = c;
  91. }
  92. else if (c < 2048) {
  93. out[p++] = (c >> 6) | 192;
  94. out[p++] = (c & 63) | 128;
  95. }
  96. else if ((c & 0xfc00) === 0xd800 &&
  97. i + 1 < str.length &&
  98. (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
  99. // Surrogate Pair
  100. c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);
  101. out[p++] = (c >> 18) | 240;
  102. out[p++] = ((c >> 12) & 63) | 128;
  103. out[p++] = ((c >> 6) & 63) | 128;
  104. out[p++] = (c & 63) | 128;
  105. }
  106. else {
  107. out[p++] = (c >> 12) | 224;
  108. out[p++] = ((c >> 6) & 63) | 128;
  109. out[p++] = (c & 63) | 128;
  110. }
  111. }
  112. return out;
  113. };
  114. /**
  115. * Turns an array of numbers into the string given by the concatenation of the
  116. * characters to which the numbers correspond.
  117. * @param bytes Array of numbers representing characters.
  118. * @return Stringification of the array.
  119. */
  120. const byteArrayToString = function (bytes) {
  121. // TODO(user): Use native implementations if/when available
  122. const out = [];
  123. let pos = 0, c = 0;
  124. while (pos < bytes.length) {
  125. const c1 = bytes[pos++];
  126. if (c1 < 128) {
  127. out[c++] = String.fromCharCode(c1);
  128. }
  129. else if (c1 > 191 && c1 < 224) {
  130. const c2 = bytes[pos++];
  131. out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
  132. }
  133. else if (c1 > 239 && c1 < 365) {
  134. // Surrogate Pair
  135. const c2 = bytes[pos++];
  136. const c3 = bytes[pos++];
  137. const c4 = bytes[pos++];
  138. const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -
  139. 0x10000;
  140. out[c++] = String.fromCharCode(0xd800 + (u >> 10));
  141. out[c++] = String.fromCharCode(0xdc00 + (u & 1023));
  142. }
  143. else {
  144. const c2 = bytes[pos++];
  145. const c3 = bytes[pos++];
  146. out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  147. }
  148. }
  149. return out.join('');
  150. };
  151. // We define it as an object literal instead of a class because a class compiled down to es5 can't
  152. // be treeshaked. https://github.com/rollup/rollup/issues/1691
  153. // Static lookup maps, lazily populated by init_()
  154. const base64 = {
  155. /**
  156. * Maps bytes to characters.
  157. */
  158. byteToCharMap_: null,
  159. /**
  160. * Maps characters to bytes.
  161. */
  162. charToByteMap_: null,
  163. /**
  164. * Maps bytes to websafe characters.
  165. * @private
  166. */
  167. byteToCharMapWebSafe_: null,
  168. /**
  169. * Maps websafe characters to bytes.
  170. * @private
  171. */
  172. charToByteMapWebSafe_: null,
  173. /**
  174. * Our default alphabet, shared between
  175. * ENCODED_VALS and ENCODED_VALS_WEBSAFE
  176. */
  177. ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',
  178. /**
  179. * Our default alphabet. Value 64 (=) is special; it means "nothing."
  180. */
  181. get ENCODED_VALS() {
  182. return this.ENCODED_VALS_BASE + '+/=';
  183. },
  184. /**
  185. * Our websafe alphabet.
  186. */
  187. get ENCODED_VALS_WEBSAFE() {
  188. return this.ENCODED_VALS_BASE + '-_.';
  189. },
  190. /**
  191. * Whether this browser supports the atob and btoa functions. This extension
  192. * started at Mozilla but is now implemented by many browsers. We use the
  193. * ASSUME_* variables to avoid pulling in the full useragent detection library
  194. * but still allowing the standard per-browser compilations.
  195. *
  196. */
  197. HAS_NATIVE_SUPPORT: typeof atob === 'function',
  198. /**
  199. * Base64-encode an array of bytes.
  200. *
  201. * @param input An array of bytes (numbers with
  202. * value in [0, 255]) to encode.
  203. * @param webSafe Boolean indicating we should use the
  204. * alternative alphabet.
  205. * @return The base64 encoded string.
  206. */
  207. encodeByteArray(input, webSafe) {
  208. if (!Array.isArray(input)) {
  209. throw Error('encodeByteArray takes an array as a parameter');
  210. }
  211. this.init_();
  212. const byteToCharMap = webSafe
  213. ? this.byteToCharMapWebSafe_
  214. : this.byteToCharMap_;
  215. const output = [];
  216. for (let i = 0; i < input.length; i += 3) {
  217. const byte1 = input[i];
  218. const haveByte2 = i + 1 < input.length;
  219. const byte2 = haveByte2 ? input[i + 1] : 0;
  220. const haveByte3 = i + 2 < input.length;
  221. const byte3 = haveByte3 ? input[i + 2] : 0;
  222. const outByte1 = byte1 >> 2;
  223. const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
  224. let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);
  225. let outByte4 = byte3 & 0x3f;
  226. if (!haveByte3) {
  227. outByte4 = 64;
  228. if (!haveByte2) {
  229. outByte3 = 64;
  230. }
  231. }
  232. output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);
  233. }
  234. return output.join('');
  235. },
  236. /**
  237. * Base64-encode a string.
  238. *
  239. * @param input A string to encode.
  240. * @param webSafe If true, we should use the
  241. * alternative alphabet.
  242. * @return The base64 encoded string.
  243. */
  244. encodeString(input, webSafe) {
  245. // Shortcut for Mozilla browsers that implement
  246. // a native base64 encoder in the form of "btoa/atob"
  247. if (this.HAS_NATIVE_SUPPORT && !webSafe) {
  248. return btoa(input);
  249. }
  250. return this.encodeByteArray(stringToByteArray$1(input), webSafe);
  251. },
  252. /**
  253. * Base64-decode a string.
  254. *
  255. * @param input to decode.
  256. * @param webSafe True if we should use the
  257. * alternative alphabet.
  258. * @return string representing the decoded value.
  259. */
  260. decodeString(input, webSafe) {
  261. // Shortcut for Mozilla browsers that implement
  262. // a native base64 encoder in the form of "btoa/atob"
  263. if (this.HAS_NATIVE_SUPPORT && !webSafe) {
  264. return atob(input);
  265. }
  266. return byteArrayToString(this.decodeStringToByteArray(input, webSafe));
  267. },
  268. /**
  269. * Base64-decode a string.
  270. *
  271. * In base-64 decoding, groups of four characters are converted into three
  272. * bytes. If the encoder did not apply padding, the input length may not
  273. * be a multiple of 4.
  274. *
  275. * In this case, the last group will have fewer than 4 characters, and
  276. * padding will be inferred. If the group has one or two characters, it decodes
  277. * to one byte. If the group has three characters, it decodes to two bytes.
  278. *
  279. * @param input Input to decode.
  280. * @param webSafe True if we should use the web-safe alphabet.
  281. * @return bytes representing the decoded value.
  282. */
  283. decodeStringToByteArray(input, webSafe) {
  284. this.init_();
  285. const charToByteMap = webSafe
  286. ? this.charToByteMapWebSafe_
  287. : this.charToByteMap_;
  288. const output = [];
  289. for (let i = 0; i < input.length;) {
  290. const byte1 = charToByteMap[input.charAt(i++)];
  291. const haveByte2 = i < input.length;
  292. const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;
  293. ++i;
  294. const haveByte3 = i < input.length;
  295. const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;
  296. ++i;
  297. const haveByte4 = i < input.length;
  298. const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;
  299. ++i;
  300. if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {
  301. throw Error();
  302. }
  303. const outByte1 = (byte1 << 2) | (byte2 >> 4);
  304. output.push(outByte1);
  305. if (byte3 !== 64) {
  306. const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);
  307. output.push(outByte2);
  308. if (byte4 !== 64) {
  309. const outByte3 = ((byte3 << 6) & 0xc0) | byte4;
  310. output.push(outByte3);
  311. }
  312. }
  313. }
  314. return output;
  315. },
  316. /**
  317. * Lazy static initialization function. Called before
  318. * accessing any of the static map variables.
  319. * @private
  320. */
  321. init_() {
  322. if (!this.byteToCharMap_) {
  323. this.byteToCharMap_ = {};
  324. this.charToByteMap_ = {};
  325. this.byteToCharMapWebSafe_ = {};
  326. this.charToByteMapWebSafe_ = {};
  327. // We want quick mappings back and forth, so we precompute two maps.
  328. for (let i = 0; i < this.ENCODED_VALS.length; i++) {
  329. this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);
  330. this.charToByteMap_[this.byteToCharMap_[i]] = i;
  331. this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);
  332. this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;
  333. // Be forgiving when decoding and correctly decode both encodings.
  334. if (i >= this.ENCODED_VALS_BASE.length) {
  335. this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;
  336. this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;
  337. }
  338. }
  339. }
  340. }
  341. };
  342. /**
  343. * URL-safe base64 encoding
  344. */
  345. const base64Encode = function (str) {
  346. const utf8Bytes = stringToByteArray$1(str);
  347. return base64.encodeByteArray(utf8Bytes, true);
  348. };
  349. /**
  350. * URL-safe base64 encoding (without "." padding in the end).
  351. * e.g. Used in JSON Web Token (JWT) parts.
  352. */
  353. const base64urlEncodeWithoutPadding = function (str) {
  354. // Use base64url encoding and remove padding in the end (dot characters).
  355. return base64Encode(str).replace(/\./g, '');
  356. };
  357. /**
  358. * URL-safe base64 decoding
  359. *
  360. * NOTE: DO NOT use the global atob() function - it does NOT support the
  361. * base64Url variant encoding.
  362. *
  363. * @param str To be decoded
  364. * @return Decoded result, if possible
  365. */
  366. const base64Decode = function (str) {
  367. try {
  368. return base64.decodeString(str, true);
  369. }
  370. catch (e) {
  371. console.error('base64Decode failed: ', e);
  372. }
  373. return null;
  374. };
  375. /**
  376. * @license
  377. * Copyright 2017 Google LLC
  378. *
  379. * Licensed under the Apache License, Version 2.0 (the "License");
  380. * you may not use this file except in compliance with the License.
  381. * You may obtain a copy of the License at
  382. *
  383. * http://www.apache.org/licenses/LICENSE-2.0
  384. *
  385. * Unless required by applicable law or agreed to in writing, software
  386. * distributed under the License is distributed on an "AS IS" BASIS,
  387. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  388. * See the License for the specific language governing permissions and
  389. * limitations under the License.
  390. */
  391. /**
  392. * Do a deep-copy of basic JavaScript Objects or Arrays.
  393. */
  394. function deepCopy(value) {
  395. return deepExtend(undefined, value);
  396. }
  397. /**
  398. * Copy properties from source to target (recursively allows extension
  399. * of Objects and Arrays). Scalar values in the target are over-written.
  400. * If target is undefined, an object of the appropriate type will be created
  401. * (and returned).
  402. *
  403. * We recursively copy all child properties of plain Objects in the source- so
  404. * that namespace- like dictionaries are merged.
  405. *
  406. * Note that the target can be a function, in which case the properties in
  407. * the source Object are copied onto it as static properties of the Function.
  408. *
  409. * Note: we don't merge __proto__ to prevent prototype pollution
  410. */
  411. function deepExtend(target, source) {
  412. if (!(source instanceof Object)) {
  413. return source;
  414. }
  415. switch (source.constructor) {
  416. case Date:
  417. // Treat Dates like scalars; if the target date object had any child
  418. // properties - they will be lost!
  419. const dateValue = source;
  420. return new Date(dateValue.getTime());
  421. case Object:
  422. if (target === undefined) {
  423. target = {};
  424. }
  425. break;
  426. case Array:
  427. // Always copy the array source and overwrite the target.
  428. target = [];
  429. break;
  430. default:
  431. // Not a plain Object - treat it as a scalar.
  432. return source;
  433. }
  434. for (const prop in source) {
  435. // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202
  436. if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {
  437. continue;
  438. }
  439. target[prop] = deepExtend(target[prop], source[prop]);
  440. }
  441. return target;
  442. }
  443. function isValidKey(key) {
  444. return key !== '__proto__';
  445. }
  446. /**
  447. * @license
  448. * Copyright 2022 Google LLC
  449. *
  450. * Licensed under the Apache License, Version 2.0 (the "License");
  451. * you may not use this file except in compliance with the License.
  452. * You may obtain a copy of the License at
  453. *
  454. * http://www.apache.org/licenses/LICENSE-2.0
  455. *
  456. * Unless required by applicable law or agreed to in writing, software
  457. * distributed under the License is distributed on an "AS IS" BASIS,
  458. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  459. * See the License for the specific language governing permissions and
  460. * limitations under the License.
  461. */
  462. /**
  463. * Polyfill for `globalThis` object.
  464. * @returns the `globalThis` object for the given environment.
  465. * @public
  466. */
  467. function getGlobal() {
  468. if (typeof self !== 'undefined') {
  469. return self;
  470. }
  471. if (typeof window !== 'undefined') {
  472. return window;
  473. }
  474. if (typeof global !== 'undefined') {
  475. return global;
  476. }
  477. throw new Error('Unable to locate global object.');
  478. }
  479. /**
  480. * @license
  481. * Copyright 2022 Google LLC
  482. *
  483. * Licensed under the Apache License, Version 2.0 (the "License");
  484. * you may not use this file except in compliance with the License.
  485. * You may obtain a copy of the License at
  486. *
  487. * http://www.apache.org/licenses/LICENSE-2.0
  488. *
  489. * Unless required by applicable law or agreed to in writing, software
  490. * distributed under the License is distributed on an "AS IS" BASIS,
  491. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  492. * See the License for the specific language governing permissions and
  493. * limitations under the License.
  494. */
  495. const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;
  496. /**
  497. * Attempt to read defaults from a JSON string provided to
  498. * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in
  499. * process(.)env(.)__FIREBASE_DEFAULTS_PATH__
  500. * The dots are in parens because certain compilers (Vite?) cannot
  501. * handle seeing that variable in comments.
  502. * See https://github.com/firebase/firebase-js-sdk/issues/6838
  503. */
  504. const getDefaultsFromEnvVariable = () => {
  505. if (typeof process === 'undefined' || typeof process.env === 'undefined') {
  506. return;
  507. }
  508. const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;
  509. if (defaultsJsonString) {
  510. return JSON.parse(defaultsJsonString);
  511. }
  512. };
  513. const getDefaultsFromCookie = () => {
  514. if (typeof document === 'undefined') {
  515. return;
  516. }
  517. let match;
  518. try {
  519. match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);
  520. }
  521. catch (e) {
  522. // Some environments such as Angular Universal SSR have a
  523. // `document` object but error on accessing `document.cookie`.
  524. return;
  525. }
  526. const decoded = match && base64Decode(match[1]);
  527. return decoded && JSON.parse(decoded);
  528. };
  529. /**
  530. * Get the __FIREBASE_DEFAULTS__ object. It checks in order:
  531. * (1) if such an object exists as a property of `globalThis`
  532. * (2) if such an object was provided on a shell environment variable
  533. * (3) if such an object exists in a cookie
  534. * @public
  535. */
  536. const getDefaults = () => {
  537. try {
  538. return (getDefaultsFromGlobal() ||
  539. getDefaultsFromEnvVariable() ||
  540. getDefaultsFromCookie());
  541. }
  542. catch (e) {
  543. /**
  544. * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due
  545. * to any environment case we have not accounted for. Log to
  546. * info instead of swallowing so we can find these unknown cases
  547. * and add paths for them if needed.
  548. */
  549. console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);
  550. return;
  551. }
  552. };
  553. /**
  554. * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object
  555. * for the given product.
  556. * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available
  557. * @public
  558. */
  559. const getDefaultEmulatorHost = (productName) => { var _a, _b; return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; };
  560. /**
  561. * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object
  562. * for the given product.
  563. * @returns a pair of hostname and port like `["::1", 4000]` if available
  564. * @public
  565. */
  566. const getDefaultEmulatorHostnameAndPort = (productName) => {
  567. const host = getDefaultEmulatorHost(productName);
  568. if (!host) {
  569. return undefined;
  570. }
  571. const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.
  572. if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {
  573. throw new Error(`Invalid host ${host} with no separate hostname and port!`);
  574. }
  575. // eslint-disable-next-line no-restricted-globals
  576. const port = parseInt(host.substring(separatorIndex + 1), 10);
  577. if (host[0] === '[') {
  578. // Bracket-quoted `[ipv6addr]:port` => return "ipv6addr" (without brackets).
  579. return [host.substring(1, separatorIndex - 1), port];
  580. }
  581. else {
  582. return [host.substring(0, separatorIndex), port];
  583. }
  584. };
  585. /**
  586. * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.
  587. * @public
  588. */
  589. const getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };
  590. /**
  591. * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties
  592. * prefixed by "_")
  593. * @public
  594. */
  595. const getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };
  596. /**
  597. * @license
  598. * Copyright 2017 Google LLC
  599. *
  600. * Licensed under the Apache License, Version 2.0 (the "License");
  601. * you may not use this file except in compliance with the License.
  602. * You may obtain a copy of the License at
  603. *
  604. * http://www.apache.org/licenses/LICENSE-2.0
  605. *
  606. * Unless required by applicable law or agreed to in writing, software
  607. * distributed under the License is distributed on an "AS IS" BASIS,
  608. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  609. * See the License for the specific language governing permissions and
  610. * limitations under the License.
  611. */
  612. class Deferred {
  613. constructor() {
  614. this.reject = () => { };
  615. this.resolve = () => { };
  616. this.promise = new Promise((resolve, reject) => {
  617. this.resolve = resolve;
  618. this.reject = reject;
  619. });
  620. }
  621. /**
  622. * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around
  623. * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback
  624. * and returns a node-style callback which will resolve or reject the Deferred's promise.
  625. */
  626. wrapCallback(callback) {
  627. return (error, value) => {
  628. if (error) {
  629. this.reject(error);
  630. }
  631. else {
  632. this.resolve(value);
  633. }
  634. if (typeof callback === 'function') {
  635. // Attaching noop handler just in case developer wasn't expecting
  636. // promises
  637. this.promise.catch(() => { });
  638. // Some of our callbacks don't expect a value and our own tests
  639. // assert that the parameter length is 1
  640. if (callback.length === 1) {
  641. callback(error);
  642. }
  643. else {
  644. callback(error, value);
  645. }
  646. }
  647. };
  648. }
  649. }
  650. /**
  651. * @license
  652. * Copyright 2021 Google LLC
  653. *
  654. * Licensed under the Apache License, Version 2.0 (the "License");
  655. * you may not use this file except in compliance with the License.
  656. * You may obtain a copy of the License at
  657. *
  658. * http://www.apache.org/licenses/LICENSE-2.0
  659. *
  660. * Unless required by applicable law or agreed to in writing, software
  661. * distributed under the License is distributed on an "AS IS" BASIS,
  662. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  663. * See the License for the specific language governing permissions and
  664. * limitations under the License.
  665. */
  666. function createMockUserToken(token, projectId) {
  667. if (token.uid) {
  668. throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');
  669. }
  670. // Unsecured JWTs use "none" as the algorithm.
  671. const header = {
  672. alg: 'none',
  673. type: 'JWT'
  674. };
  675. const project = projectId || 'demo-project';
  676. const iat = token.iat || 0;
  677. const sub = token.sub || token.user_id;
  678. if (!sub) {
  679. throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");
  680. }
  681. const payload = Object.assign({
  682. // Set all required fields to decent defaults
  683. iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {
  684. sign_in_provider: 'custom',
  685. identities: {}
  686. } }, token);
  687. // Unsecured JWTs use the empty string as a signature.
  688. const signature = '';
  689. return [
  690. base64urlEncodeWithoutPadding(JSON.stringify(header)),
  691. base64urlEncodeWithoutPadding(JSON.stringify(payload)),
  692. signature
  693. ].join('.');
  694. }
  695. /**
  696. * @license
  697. * Copyright 2017 Google LLC
  698. *
  699. * Licensed under the Apache License, Version 2.0 (the "License");
  700. * you may not use this file except in compliance with the License.
  701. * You may obtain a copy of the License at
  702. *
  703. * http://www.apache.org/licenses/LICENSE-2.0
  704. *
  705. * Unless required by applicable law or agreed to in writing, software
  706. * distributed under the License is distributed on an "AS IS" BASIS,
  707. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  708. * See the License for the specific language governing permissions and
  709. * limitations under the License.
  710. */
  711. /**
  712. * Returns navigator.userAgent string or '' if it's not defined.
  713. * @return user agent string
  714. */
  715. function getUA() {
  716. if (typeof navigator !== 'undefined' &&
  717. typeof navigator['userAgent'] === 'string') {
  718. return navigator['userAgent'];
  719. }
  720. else {
  721. return '';
  722. }
  723. }
  724. /**
  725. * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.
  726. *
  727. * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap
  728. * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally
  729. * wait for a callback.
  730. */
  731. function isMobileCordova() {
  732. return (typeof window !== 'undefined' &&
  733. // @ts-ignore Setting up an broadly applicable index signature for Window
  734. // just to deal with this case would probably be a bad idea.
  735. !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&
  736. /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));
  737. }
  738. /**
  739. * Detect Node.js.
  740. *
  741. * @return true if Node.js environment is detected or specified.
  742. */
  743. // Node detection logic from: https://github.com/iliakan/detect-node/
  744. function isNode() {
  745. var _a;
  746. const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;
  747. if (forceEnvironment === 'node') {
  748. return true;
  749. }
  750. else if (forceEnvironment === 'browser') {
  751. return false;
  752. }
  753. try {
  754. return (Object.prototype.toString.call(global.process) === '[object process]');
  755. }
  756. catch (e) {
  757. return false;
  758. }
  759. }
  760. /**
  761. * Detect Browser Environment
  762. */
  763. function isBrowser() {
  764. return typeof self === 'object' && self.self === self;
  765. }
  766. function isBrowserExtension() {
  767. const runtime = typeof chrome === 'object'
  768. ? chrome.runtime
  769. : typeof browser === 'object'
  770. ? browser.runtime
  771. : undefined;
  772. return typeof runtime === 'object' && runtime.id !== undefined;
  773. }
  774. /**
  775. * Detect React Native.
  776. *
  777. * @return true if ReactNative environment is detected.
  778. */
  779. function isReactNative() {
  780. return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');
  781. }
  782. /** Detects Electron apps. */
  783. function isElectron() {
  784. return getUA().indexOf('Electron/') >= 0;
  785. }
  786. /** Detects Internet Explorer. */
  787. function isIE() {
  788. const ua = getUA();
  789. return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;
  790. }
  791. /** Detects Universal Windows Platform apps. */
  792. function isUWP() {
  793. return getUA().indexOf('MSAppHost/') >= 0;
  794. }
  795. /**
  796. * Detect whether the current SDK build is the Node version.
  797. *
  798. * @return true if it's the Node SDK build.
  799. */
  800. function isNodeSdk() {
  801. return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;
  802. }
  803. /** Returns true if we are running in Safari. */
  804. function isSafari() {
  805. return (!isNode() &&
  806. navigator.userAgent.includes('Safari') &&
  807. !navigator.userAgent.includes('Chrome'));
  808. }
  809. /**
  810. * This method checks if indexedDB is supported by current browser/service worker context
  811. * @return true if indexedDB is supported by current browser/service worker context
  812. */
  813. function isIndexedDBAvailable() {
  814. try {
  815. return typeof indexedDB === 'object';
  816. }
  817. catch (e) {
  818. return false;
  819. }
  820. }
  821. /**
  822. * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject
  823. * if errors occur during the database open operation.
  824. *
  825. * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox
  826. * private browsing)
  827. */
  828. function validateIndexedDBOpenable() {
  829. return new Promise((resolve, reject) => {
  830. try {
  831. let preExist = true;
  832. const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';
  833. const request = self.indexedDB.open(DB_CHECK_NAME);
  834. request.onsuccess = () => {
  835. request.result.close();
  836. // delete database only when it doesn't pre-exist
  837. if (!preExist) {
  838. self.indexedDB.deleteDatabase(DB_CHECK_NAME);
  839. }
  840. resolve(true);
  841. };
  842. request.onupgradeneeded = () => {
  843. preExist = false;
  844. };
  845. request.onerror = () => {
  846. var _a;
  847. reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');
  848. };
  849. }
  850. catch (error) {
  851. reject(error);
  852. }
  853. });
  854. }
  855. /**
  856. *
  857. * This method checks whether cookie is enabled within current browser
  858. * @return true if cookie is enabled within current browser
  859. */
  860. function areCookiesEnabled() {
  861. if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {
  862. return false;
  863. }
  864. return true;
  865. }
  866. /**
  867. * @license
  868. * Copyright 2017 Google LLC
  869. *
  870. * Licensed under the Apache License, Version 2.0 (the "License");
  871. * you may not use this file except in compliance with the License.
  872. * You may obtain a copy of the License at
  873. *
  874. * http://www.apache.org/licenses/LICENSE-2.0
  875. *
  876. * Unless required by applicable law or agreed to in writing, software
  877. * distributed under the License is distributed on an "AS IS" BASIS,
  878. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  879. * See the License for the specific language governing permissions and
  880. * limitations under the License.
  881. */
  882. /**
  883. * @fileoverview Standardized Firebase Error.
  884. *
  885. * Usage:
  886. *
  887. * // Typescript string literals for type-safe codes
  888. * type Err =
  889. * 'unknown' |
  890. * 'object-not-found'
  891. * ;
  892. *
  893. * // Closure enum for type-safe error codes
  894. * // at-enum {string}
  895. * var Err = {
  896. * UNKNOWN: 'unknown',
  897. * OBJECT_NOT_FOUND: 'object-not-found',
  898. * }
  899. *
  900. * let errors: Map<Err, string> = {
  901. * 'generic-error': "Unknown error",
  902. * 'file-not-found': "Could not find file: {$file}",
  903. * };
  904. *
  905. * // Type-safe function - must pass a valid error code as param.
  906. * let error = new ErrorFactory<Err>('service', 'Service', errors);
  907. *
  908. * ...
  909. * throw error.create(Err.GENERIC);
  910. * ...
  911. * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});
  912. * ...
  913. * // Service: Could not file file: foo.txt (service/file-not-found).
  914. *
  915. * catch (e) {
  916. * assert(e.message === "Could not find file: foo.txt.");
  917. * if ((e as FirebaseError)?.code === 'service/file-not-found') {
  918. * console.log("Could not read file: " + e['file']);
  919. * }
  920. * }
  921. */
  922. const ERROR_NAME = 'FirebaseError';
  923. // Based on code from:
  924. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
  925. class FirebaseError extends Error {
  926. constructor(
  927. /** The error code for this error. */
  928. code, message,
  929. /** Custom data for this error. */
  930. customData) {
  931. super(message);
  932. this.code = code;
  933. this.customData = customData;
  934. /** The custom name for all FirebaseErrors. */
  935. this.name = ERROR_NAME;
  936. // Fix For ES5
  937. // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
  938. Object.setPrototypeOf(this, FirebaseError.prototype);
  939. // Maintains proper stack trace for where our error was thrown.
  940. // Only available on V8.
  941. if (Error.captureStackTrace) {
  942. Error.captureStackTrace(this, ErrorFactory.prototype.create);
  943. }
  944. }
  945. }
  946. class ErrorFactory {
  947. constructor(service, serviceName, errors) {
  948. this.service = service;
  949. this.serviceName = serviceName;
  950. this.errors = errors;
  951. }
  952. create(code, ...data) {
  953. const customData = data[0] || {};
  954. const fullCode = `${this.service}/${code}`;
  955. const template = this.errors[code];
  956. const message = template ? replaceTemplate(template, customData) : 'Error';
  957. // Service Name: Error message (service/code).
  958. const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;
  959. const error = new FirebaseError(fullCode, fullMessage, customData);
  960. return error;
  961. }
  962. }
  963. function replaceTemplate(template, data) {
  964. return template.replace(PATTERN, (_, key) => {
  965. const value = data[key];
  966. return value != null ? String(value) : `<${key}?>`;
  967. });
  968. }
  969. const PATTERN = /\{\$([^}]+)}/g;
  970. /**
  971. * @license
  972. * Copyright 2017 Google LLC
  973. *
  974. * Licensed under the Apache License, Version 2.0 (the "License");
  975. * you may not use this file except in compliance with the License.
  976. * You may obtain a copy of the License at
  977. *
  978. * http://www.apache.org/licenses/LICENSE-2.0
  979. *
  980. * Unless required by applicable law or agreed to in writing, software
  981. * distributed under the License is distributed on an "AS IS" BASIS,
  982. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  983. * See the License for the specific language governing permissions and
  984. * limitations under the License.
  985. */
  986. /**
  987. * Evaluates a JSON string into a javascript object.
  988. *
  989. * @param {string} str A string containing JSON.
  990. * @return {*} The javascript object representing the specified JSON.
  991. */
  992. function jsonEval(str) {
  993. return JSON.parse(str);
  994. }
  995. /**
  996. * Returns JSON representing a javascript object.
  997. * @param {*} data Javascript object to be stringified.
  998. * @return {string} The JSON contents of the object.
  999. */
  1000. function stringify(data) {
  1001. return JSON.stringify(data);
  1002. }
  1003. /**
  1004. * @license
  1005. * Copyright 2017 Google LLC
  1006. *
  1007. * Licensed under the Apache License, Version 2.0 (the "License");
  1008. * you may not use this file except in compliance with the License.
  1009. * You may obtain a copy of the License at
  1010. *
  1011. * http://www.apache.org/licenses/LICENSE-2.0
  1012. *
  1013. * Unless required by applicable law or agreed to in writing, software
  1014. * distributed under the License is distributed on an "AS IS" BASIS,
  1015. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1016. * See the License for the specific language governing permissions and
  1017. * limitations under the License.
  1018. */
  1019. /**
  1020. * Decodes a Firebase auth. token into constituent parts.
  1021. *
  1022. * Notes:
  1023. * - May return with invalid / incomplete claims if there's no native base64 decoding support.
  1024. * - Doesn't check if the token is actually valid.
  1025. */
  1026. const decode = function (token) {
  1027. let header = {}, claims = {}, data = {}, signature = '';
  1028. try {
  1029. const parts = token.split('.');
  1030. header = jsonEval(base64Decode(parts[0]) || '');
  1031. claims = jsonEval(base64Decode(parts[1]) || '');
  1032. signature = parts[2];
  1033. data = claims['d'] || {};
  1034. delete claims['d'];
  1035. }
  1036. catch (e) { }
  1037. return {
  1038. header,
  1039. claims,
  1040. data,
  1041. signature
  1042. };
  1043. };
  1044. /**
  1045. * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the
  1046. * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.
  1047. *
  1048. * Notes:
  1049. * - May return a false negative if there's no native base64 decoding support.
  1050. * - Doesn't check if the token is actually valid.
  1051. */
  1052. const isValidTimestamp = function (token) {
  1053. const claims = decode(token).claims;
  1054. const now = Math.floor(new Date().getTime() / 1000);
  1055. let validSince = 0, validUntil = 0;
  1056. if (typeof claims === 'object') {
  1057. if (claims.hasOwnProperty('nbf')) {
  1058. validSince = claims['nbf'];
  1059. }
  1060. else if (claims.hasOwnProperty('iat')) {
  1061. validSince = claims['iat'];
  1062. }
  1063. if (claims.hasOwnProperty('exp')) {
  1064. validUntil = claims['exp'];
  1065. }
  1066. else {
  1067. // token will expire after 24h by default
  1068. validUntil = validSince + 86400;
  1069. }
  1070. }
  1071. return (!!now &&
  1072. !!validSince &&
  1073. !!validUntil &&
  1074. now >= validSince &&
  1075. now <= validUntil);
  1076. };
  1077. /**
  1078. * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.
  1079. *
  1080. * Notes:
  1081. * - May return null if there's no native base64 decoding support.
  1082. * - Doesn't check if the token is actually valid.
  1083. */
  1084. const issuedAtTime = function (token) {
  1085. const claims = decode(token).claims;
  1086. if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {
  1087. return claims['iat'];
  1088. }
  1089. return null;
  1090. };
  1091. /**
  1092. * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.
  1093. *
  1094. * Notes:
  1095. * - May return a false negative if there's no native base64 decoding support.
  1096. * - Doesn't check if the token is actually valid.
  1097. */
  1098. const isValidFormat = function (token) {
  1099. const decoded = decode(token), claims = decoded.claims;
  1100. return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');
  1101. };
  1102. /**
  1103. * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.
  1104. *
  1105. * Notes:
  1106. * - May return a false negative if there's no native base64 decoding support.
  1107. * - Doesn't check if the token is actually valid.
  1108. */
  1109. const isAdmin = function (token) {
  1110. const claims = decode(token).claims;
  1111. return typeof claims === 'object' && claims['admin'] === true;
  1112. };
  1113. /**
  1114. * @license
  1115. * Copyright 2017 Google LLC
  1116. *
  1117. * Licensed under the Apache License, Version 2.0 (the "License");
  1118. * you may not use this file except in compliance with the License.
  1119. * You may obtain a copy of the License at
  1120. *
  1121. * http://www.apache.org/licenses/LICENSE-2.0
  1122. *
  1123. * Unless required by applicable law or agreed to in writing, software
  1124. * distributed under the License is distributed on an "AS IS" BASIS,
  1125. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1126. * See the License for the specific language governing permissions and
  1127. * limitations under the License.
  1128. */
  1129. function contains(obj, key) {
  1130. return Object.prototype.hasOwnProperty.call(obj, key);
  1131. }
  1132. function safeGet(obj, key) {
  1133. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1134. return obj[key];
  1135. }
  1136. else {
  1137. return undefined;
  1138. }
  1139. }
  1140. function isEmpty(obj) {
  1141. for (const key in obj) {
  1142. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1143. return false;
  1144. }
  1145. }
  1146. return true;
  1147. }
  1148. function map(obj, fn, contextObj) {
  1149. const res = {};
  1150. for (const key in obj) {
  1151. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1152. res[key] = fn.call(contextObj, obj[key], key, obj);
  1153. }
  1154. }
  1155. return res;
  1156. }
  1157. /**
  1158. * Deep equal two objects. Support Arrays and Objects.
  1159. */
  1160. function deepEqual(a, b) {
  1161. if (a === b) {
  1162. return true;
  1163. }
  1164. const aKeys = Object.keys(a);
  1165. const bKeys = Object.keys(b);
  1166. for (const k of aKeys) {
  1167. if (!bKeys.includes(k)) {
  1168. return false;
  1169. }
  1170. const aProp = a[k];
  1171. const bProp = b[k];
  1172. if (isObject(aProp) && isObject(bProp)) {
  1173. if (!deepEqual(aProp, bProp)) {
  1174. return false;
  1175. }
  1176. }
  1177. else if (aProp !== bProp) {
  1178. return false;
  1179. }
  1180. }
  1181. for (const k of bKeys) {
  1182. if (!aKeys.includes(k)) {
  1183. return false;
  1184. }
  1185. }
  1186. return true;
  1187. }
  1188. function isObject(thing) {
  1189. return thing !== null && typeof thing === 'object';
  1190. }
  1191. /**
  1192. * @license
  1193. * Copyright 2022 Google LLC
  1194. *
  1195. * Licensed under the Apache License, Version 2.0 (the "License");
  1196. * you may not use this file except in compliance with the License.
  1197. * You may obtain a copy of the License at
  1198. *
  1199. * http://www.apache.org/licenses/LICENSE-2.0
  1200. *
  1201. * Unless required by applicable law or agreed to in writing, software
  1202. * distributed under the License is distributed on an "AS IS" BASIS,
  1203. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1204. * See the License for the specific language governing permissions and
  1205. * limitations under the License.
  1206. */
  1207. /**
  1208. * Rejects if the given promise doesn't resolve in timeInMS milliseconds.
  1209. * @internal
  1210. */
  1211. function promiseWithTimeout(promise, timeInMS = 2000) {
  1212. const deferredPromise = new Deferred();
  1213. setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);
  1214. promise.then(deferredPromise.resolve, deferredPromise.reject);
  1215. return deferredPromise.promise;
  1216. }
  1217. /**
  1218. * @license
  1219. * Copyright 2017 Google LLC
  1220. *
  1221. * Licensed under the Apache License, Version 2.0 (the "License");
  1222. * you may not use this file except in compliance with the License.
  1223. * You may obtain a copy of the License at
  1224. *
  1225. * http://www.apache.org/licenses/LICENSE-2.0
  1226. *
  1227. * Unless required by applicable law or agreed to in writing, software
  1228. * distributed under the License is distributed on an "AS IS" BASIS,
  1229. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1230. * See the License for the specific language governing permissions and
  1231. * limitations under the License.
  1232. */
  1233. /**
  1234. * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a
  1235. * params object (e.g. {arg: 'val', arg2: 'val2'})
  1236. * Note: You must prepend it with ? when adding it to a URL.
  1237. */
  1238. function querystring(querystringParams) {
  1239. const params = [];
  1240. for (const [key, value] of Object.entries(querystringParams)) {
  1241. if (Array.isArray(value)) {
  1242. value.forEach(arrayVal => {
  1243. params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));
  1244. });
  1245. }
  1246. else {
  1247. params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  1248. }
  1249. }
  1250. return params.length ? '&' + params.join('&') : '';
  1251. }
  1252. /**
  1253. * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object
  1254. * (e.g. {arg: 'val', arg2: 'val2'})
  1255. */
  1256. function querystringDecode(querystring) {
  1257. const obj = {};
  1258. const tokens = querystring.replace(/^\?/, '').split('&');
  1259. tokens.forEach(token => {
  1260. if (token) {
  1261. const [key, value] = token.split('=');
  1262. obj[decodeURIComponent(key)] = decodeURIComponent(value);
  1263. }
  1264. });
  1265. return obj;
  1266. }
  1267. /**
  1268. * Extract the query string part of a URL, including the leading question mark (if present).
  1269. */
  1270. function extractQuerystring(url) {
  1271. const queryStart = url.indexOf('?');
  1272. if (!queryStart) {
  1273. return '';
  1274. }
  1275. const fragmentStart = url.indexOf('#', queryStart);
  1276. return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);
  1277. }
  1278. /**
  1279. * @license
  1280. * Copyright 2017 Google LLC
  1281. *
  1282. * Licensed under the Apache License, Version 2.0 (the "License");
  1283. * you may not use this file except in compliance with the License.
  1284. * You may obtain a copy of the License at
  1285. *
  1286. * http://www.apache.org/licenses/LICENSE-2.0
  1287. *
  1288. * Unless required by applicable law or agreed to in writing, software
  1289. * distributed under the License is distributed on an "AS IS" BASIS,
  1290. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1291. * See the License for the specific language governing permissions and
  1292. * limitations under the License.
  1293. */
  1294. /**
  1295. * @fileoverview SHA-1 cryptographic hash.
  1296. * Variable names follow the notation in FIPS PUB 180-3:
  1297. * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.
  1298. *
  1299. * Usage:
  1300. * var sha1 = new sha1();
  1301. * sha1.update(bytes);
  1302. * var hash = sha1.digest();
  1303. *
  1304. * Performance:
  1305. * Chrome 23: ~400 Mbit/s
  1306. * Firefox 16: ~250 Mbit/s
  1307. *
  1308. */
  1309. /**
  1310. * SHA-1 cryptographic hash constructor.
  1311. *
  1312. * The properties declared here are discussed in the above algorithm document.
  1313. * @constructor
  1314. * @final
  1315. * @struct
  1316. */
  1317. class Sha1 {
  1318. constructor() {
  1319. /**
  1320. * Holds the previous values of accumulated variables a-e in the compress_
  1321. * function.
  1322. * @private
  1323. */
  1324. this.chain_ = [];
  1325. /**
  1326. * A buffer holding the partially computed hash result.
  1327. * @private
  1328. */
  1329. this.buf_ = [];
  1330. /**
  1331. * An array of 80 bytes, each a part of the message to be hashed. Referred to
  1332. * as the message schedule in the docs.
  1333. * @private
  1334. */
  1335. this.W_ = [];
  1336. /**
  1337. * Contains data needed to pad messages less than 64 bytes.
  1338. * @private
  1339. */
  1340. this.pad_ = [];
  1341. /**
  1342. * @private {number}
  1343. */
  1344. this.inbuf_ = 0;
  1345. /**
  1346. * @private {number}
  1347. */
  1348. this.total_ = 0;
  1349. this.blockSize = 512 / 8;
  1350. this.pad_[0] = 128;
  1351. for (let i = 1; i < this.blockSize; ++i) {
  1352. this.pad_[i] = 0;
  1353. }
  1354. this.reset();
  1355. }
  1356. reset() {
  1357. this.chain_[0] = 0x67452301;
  1358. this.chain_[1] = 0xefcdab89;
  1359. this.chain_[2] = 0x98badcfe;
  1360. this.chain_[3] = 0x10325476;
  1361. this.chain_[4] = 0xc3d2e1f0;
  1362. this.inbuf_ = 0;
  1363. this.total_ = 0;
  1364. }
  1365. /**
  1366. * Internal compress helper function.
  1367. * @param buf Block to compress.
  1368. * @param offset Offset of the block in the buffer.
  1369. * @private
  1370. */
  1371. compress_(buf, offset) {
  1372. if (!offset) {
  1373. offset = 0;
  1374. }
  1375. const W = this.W_;
  1376. // get 16 big endian words
  1377. if (typeof buf === 'string') {
  1378. for (let i = 0; i < 16; i++) {
  1379. // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS
  1380. // have a bug that turns the post-increment ++ operator into pre-increment
  1381. // during JIT compilation. We have code that depends heavily on SHA-1 for
  1382. // correctness and which is affected by this bug, so I've removed all uses
  1383. // of post-increment ++ in which the result value is used. We can revert
  1384. // this change once the Safari bug
  1385. // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and
  1386. // most clients have been updated.
  1387. W[i] =
  1388. (buf.charCodeAt(offset) << 24) |
  1389. (buf.charCodeAt(offset + 1) << 16) |
  1390. (buf.charCodeAt(offset + 2) << 8) |
  1391. buf.charCodeAt(offset + 3);
  1392. offset += 4;
  1393. }
  1394. }
  1395. else {
  1396. for (let i = 0; i < 16; i++) {
  1397. W[i] =
  1398. (buf[offset] << 24) |
  1399. (buf[offset + 1] << 16) |
  1400. (buf[offset + 2] << 8) |
  1401. buf[offset + 3];
  1402. offset += 4;
  1403. }
  1404. }
  1405. // expand to 80 words
  1406. for (let i = 16; i < 80; i++) {
  1407. const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
  1408. W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;
  1409. }
  1410. let a = this.chain_[0];
  1411. let b = this.chain_[1];
  1412. let c = this.chain_[2];
  1413. let d = this.chain_[3];
  1414. let e = this.chain_[4];
  1415. let f, k;
  1416. // TODO(user): Try to unroll this loop to speed up the computation.
  1417. for (let i = 0; i < 80; i++) {
  1418. if (i < 40) {
  1419. if (i < 20) {
  1420. f = d ^ (b & (c ^ d));
  1421. k = 0x5a827999;
  1422. }
  1423. else {
  1424. f = b ^ c ^ d;
  1425. k = 0x6ed9eba1;
  1426. }
  1427. }
  1428. else {
  1429. if (i < 60) {
  1430. f = (b & c) | (d & (b | c));
  1431. k = 0x8f1bbcdc;
  1432. }
  1433. else {
  1434. f = b ^ c ^ d;
  1435. k = 0xca62c1d6;
  1436. }
  1437. }
  1438. const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;
  1439. e = d;
  1440. d = c;
  1441. c = ((b << 30) | (b >>> 2)) & 0xffffffff;
  1442. b = a;
  1443. a = t;
  1444. }
  1445. this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;
  1446. this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;
  1447. this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;
  1448. this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;
  1449. this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;
  1450. }
  1451. update(bytes, length) {
  1452. // TODO(johnlenz): tighten the function signature and remove this check
  1453. if (bytes == null) {
  1454. return;
  1455. }
  1456. if (length === undefined) {
  1457. length = bytes.length;
  1458. }
  1459. const lengthMinusBlock = length - this.blockSize;
  1460. let n = 0;
  1461. // Using local instead of member variables gives ~5% speedup on Firefox 16.
  1462. const buf = this.buf_;
  1463. let inbuf = this.inbuf_;
  1464. // The outer while loop should execute at most twice.
  1465. while (n < length) {
  1466. // When we have no data in the block to top up, we can directly process the
  1467. // input buffer (assuming it contains sufficient data). This gives ~25%
  1468. // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that
  1469. // the data is provided in large chunks (or in multiples of 64 bytes).
  1470. if (inbuf === 0) {
  1471. while (n <= lengthMinusBlock) {
  1472. this.compress_(bytes, n);
  1473. n += this.blockSize;
  1474. }
  1475. }
  1476. if (typeof bytes === 'string') {
  1477. while (n < length) {
  1478. buf[inbuf] = bytes.charCodeAt(n);
  1479. ++inbuf;
  1480. ++n;
  1481. if (inbuf === this.blockSize) {
  1482. this.compress_(buf);
  1483. inbuf = 0;
  1484. // Jump to the outer loop so we use the full-block optimization.
  1485. break;
  1486. }
  1487. }
  1488. }
  1489. else {
  1490. while (n < length) {
  1491. buf[inbuf] = bytes[n];
  1492. ++inbuf;
  1493. ++n;
  1494. if (inbuf === this.blockSize) {
  1495. this.compress_(buf);
  1496. inbuf = 0;
  1497. // Jump to the outer loop so we use the full-block optimization.
  1498. break;
  1499. }
  1500. }
  1501. }
  1502. }
  1503. this.inbuf_ = inbuf;
  1504. this.total_ += length;
  1505. }
  1506. /** @override */
  1507. digest() {
  1508. const digest = [];
  1509. let totalBits = this.total_ * 8;
  1510. // Add pad 0x80 0x00*.
  1511. if (this.inbuf_ < 56) {
  1512. this.update(this.pad_, 56 - this.inbuf_);
  1513. }
  1514. else {
  1515. this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));
  1516. }
  1517. // Add # bits.
  1518. for (let i = this.blockSize - 1; i >= 56; i--) {
  1519. this.buf_[i] = totalBits & 255;
  1520. totalBits /= 256; // Don't use bit-shifting here!
  1521. }
  1522. this.compress_(this.buf_);
  1523. let n = 0;
  1524. for (let i = 0; i < 5; i++) {
  1525. for (let j = 24; j >= 0; j -= 8) {
  1526. digest[n] = (this.chain_[i] >> j) & 255;
  1527. ++n;
  1528. }
  1529. }
  1530. return digest;
  1531. }
  1532. }
  1533. /**
  1534. * Helper to make a Subscribe function (just like Promise helps make a
  1535. * Thenable).
  1536. *
  1537. * @param executor Function which can make calls to a single Observer
  1538. * as a proxy.
  1539. * @param onNoObservers Callback when count of Observers goes to zero.
  1540. */
  1541. function createSubscribe(executor, onNoObservers) {
  1542. const proxy = new ObserverProxy(executor, onNoObservers);
  1543. return proxy.subscribe.bind(proxy);
  1544. }
  1545. /**
  1546. * Implement fan-out for any number of Observers attached via a subscribe
  1547. * function.
  1548. */
  1549. class ObserverProxy {
  1550. /**
  1551. * @param executor Function which can make calls to a single Observer
  1552. * as a proxy.
  1553. * @param onNoObservers Callback when count of Observers goes to zero.
  1554. */
  1555. constructor(executor, onNoObservers) {
  1556. this.observers = [];
  1557. this.unsubscribes = [];
  1558. this.observerCount = 0;
  1559. // Micro-task scheduling by calling task.then().
  1560. this.task = Promise.resolve();
  1561. this.finalized = false;
  1562. this.onNoObservers = onNoObservers;
  1563. // Call the executor asynchronously so subscribers that are called
  1564. // synchronously after the creation of the subscribe function
  1565. // can still receive the very first value generated in the executor.
  1566. this.task
  1567. .then(() => {
  1568. executor(this);
  1569. })
  1570. .catch(e => {
  1571. this.error(e);
  1572. });
  1573. }
  1574. next(value) {
  1575. this.forEachObserver((observer) => {
  1576. observer.next(value);
  1577. });
  1578. }
  1579. error(error) {
  1580. this.forEachObserver((observer) => {
  1581. observer.error(error);
  1582. });
  1583. this.close(error);
  1584. }
  1585. complete() {
  1586. this.forEachObserver((observer) => {
  1587. observer.complete();
  1588. });
  1589. this.close();
  1590. }
  1591. /**
  1592. * Subscribe function that can be used to add an Observer to the fan-out list.
  1593. *
  1594. * - We require that no event is sent to a subscriber sychronously to their
  1595. * call to subscribe().
  1596. */
  1597. subscribe(nextOrObserver, error, complete) {
  1598. let observer;
  1599. if (nextOrObserver === undefined &&
  1600. error === undefined &&
  1601. complete === undefined) {
  1602. throw new Error('Missing Observer.');
  1603. }
  1604. // Assemble an Observer object when passed as callback functions.
  1605. if (implementsAnyMethods(nextOrObserver, [
  1606. 'next',
  1607. 'error',
  1608. 'complete'
  1609. ])) {
  1610. observer = nextOrObserver;
  1611. }
  1612. else {
  1613. observer = {
  1614. next: nextOrObserver,
  1615. error,
  1616. complete
  1617. };
  1618. }
  1619. if (observer.next === undefined) {
  1620. observer.next = noop;
  1621. }
  1622. if (observer.error === undefined) {
  1623. observer.error = noop;
  1624. }
  1625. if (observer.complete === undefined) {
  1626. observer.complete = noop;
  1627. }
  1628. const unsub = this.unsubscribeOne.bind(this, this.observers.length);
  1629. // Attempt to subscribe to a terminated Observable - we
  1630. // just respond to the Observer with the final error or complete
  1631. // event.
  1632. if (this.finalized) {
  1633. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1634. this.task.then(() => {
  1635. try {
  1636. if (this.finalError) {
  1637. observer.error(this.finalError);
  1638. }
  1639. else {
  1640. observer.complete();
  1641. }
  1642. }
  1643. catch (e) {
  1644. // nothing
  1645. }
  1646. return;
  1647. });
  1648. }
  1649. this.observers.push(observer);
  1650. return unsub;
  1651. }
  1652. // Unsubscribe is synchronous - we guarantee that no events are sent to
  1653. // any unsubscribed Observer.
  1654. unsubscribeOne(i) {
  1655. if (this.observers === undefined || this.observers[i] === undefined) {
  1656. return;
  1657. }
  1658. delete this.observers[i];
  1659. this.observerCount -= 1;
  1660. if (this.observerCount === 0 && this.onNoObservers !== undefined) {
  1661. this.onNoObservers(this);
  1662. }
  1663. }
  1664. forEachObserver(fn) {
  1665. if (this.finalized) {
  1666. // Already closed by previous event....just eat the additional values.
  1667. return;
  1668. }
  1669. // Since sendOne calls asynchronously - there is no chance that
  1670. // this.observers will become undefined.
  1671. for (let i = 0; i < this.observers.length; i++) {
  1672. this.sendOne(i, fn);
  1673. }
  1674. }
  1675. // Call the Observer via one of it's callback function. We are careful to
  1676. // confirm that the observe has not been unsubscribed since this asynchronous
  1677. // function had been queued.
  1678. sendOne(i, fn) {
  1679. // Execute the callback asynchronously
  1680. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1681. this.task.then(() => {
  1682. if (this.observers !== undefined && this.observers[i] !== undefined) {
  1683. try {
  1684. fn(this.observers[i]);
  1685. }
  1686. catch (e) {
  1687. // Ignore exceptions raised in Observers or missing methods of an
  1688. // Observer.
  1689. // Log error to console. b/31404806
  1690. if (typeof console !== 'undefined' && console.error) {
  1691. console.error(e);
  1692. }
  1693. }
  1694. }
  1695. });
  1696. }
  1697. close(err) {
  1698. if (this.finalized) {
  1699. return;
  1700. }
  1701. this.finalized = true;
  1702. if (err !== undefined) {
  1703. this.finalError = err;
  1704. }
  1705. // Proxy is no longer needed - garbage collect references
  1706. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1707. this.task.then(() => {
  1708. this.observers = undefined;
  1709. this.onNoObservers = undefined;
  1710. });
  1711. }
  1712. }
  1713. /** Turn synchronous function into one called asynchronously. */
  1714. // eslint-disable-next-line @typescript-eslint/ban-types
  1715. function async(fn, onError) {
  1716. return (...args) => {
  1717. Promise.resolve(true)
  1718. .then(() => {
  1719. fn(...args);
  1720. })
  1721. .catch((error) => {
  1722. if (onError) {
  1723. onError(error);
  1724. }
  1725. });
  1726. };
  1727. }
  1728. /**
  1729. * Return true if the object passed in implements any of the named methods.
  1730. */
  1731. function implementsAnyMethods(obj, methods) {
  1732. if (typeof obj !== 'object' || obj === null) {
  1733. return false;
  1734. }
  1735. for (const method of methods) {
  1736. if (method in obj && typeof obj[method] === 'function') {
  1737. return true;
  1738. }
  1739. }
  1740. return false;
  1741. }
  1742. function noop() {
  1743. // do nothing
  1744. }
  1745. /**
  1746. * @license
  1747. * Copyright 2017 Google LLC
  1748. *
  1749. * Licensed under the Apache License, Version 2.0 (the "License");
  1750. * you may not use this file except in compliance with the License.
  1751. * You may obtain a copy of the License at
  1752. *
  1753. * http://www.apache.org/licenses/LICENSE-2.0
  1754. *
  1755. * Unless required by applicable law or agreed to in writing, software
  1756. * distributed under the License is distributed on an "AS IS" BASIS,
  1757. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1758. * See the License for the specific language governing permissions and
  1759. * limitations under the License.
  1760. */
  1761. /**
  1762. * Check to make sure the appropriate number of arguments are provided for a public function.
  1763. * Throws an error if it fails.
  1764. *
  1765. * @param fnName The function name
  1766. * @param minCount The minimum number of arguments to allow for the function call
  1767. * @param maxCount The maximum number of argument to allow for the function call
  1768. * @param argCount The actual number of arguments provided.
  1769. */
  1770. const validateArgCount = function (fnName, minCount, maxCount, argCount) {
  1771. let argError;
  1772. if (argCount < minCount) {
  1773. argError = 'at least ' + minCount;
  1774. }
  1775. else if (argCount > maxCount) {
  1776. argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;
  1777. }
  1778. if (argError) {
  1779. const error = fnName +
  1780. ' failed: Was called with ' +
  1781. argCount +
  1782. (argCount === 1 ? ' argument.' : ' arguments.') +
  1783. ' Expects ' +
  1784. argError +
  1785. '.';
  1786. throw new Error(error);
  1787. }
  1788. };
  1789. /**
  1790. * Generates a string to prefix an error message about failed argument validation
  1791. *
  1792. * @param fnName The function name
  1793. * @param argName The name of the argument
  1794. * @return The prefix to add to the error thrown for validation.
  1795. */
  1796. function errorPrefix(fnName, argName) {
  1797. return `${fnName} failed: ${argName} argument `;
  1798. }
  1799. /**
  1800. * @param fnName
  1801. * @param argumentNumber
  1802. * @param namespace
  1803. * @param optional
  1804. */
  1805. function validateNamespace(fnName, namespace, optional) {
  1806. if (optional && !namespace) {
  1807. return;
  1808. }
  1809. if (typeof namespace !== 'string') {
  1810. //TODO: I should do more validation here. We only allow certain chars in namespaces.
  1811. throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');
  1812. }
  1813. }
  1814. function validateCallback(fnName, argumentName,
  1815. // eslint-disable-next-line @typescript-eslint/ban-types
  1816. callback, optional) {
  1817. if (optional && !callback) {
  1818. return;
  1819. }
  1820. if (typeof callback !== 'function') {
  1821. throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');
  1822. }
  1823. }
  1824. function validateContextObject(fnName, argumentName, context, optional) {
  1825. if (optional && !context) {
  1826. return;
  1827. }
  1828. if (typeof context !== 'object' || context === null) {
  1829. throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');
  1830. }
  1831. }
  1832. /**
  1833. * @license
  1834. * Copyright 2017 Google LLC
  1835. *
  1836. * Licensed under the Apache License, Version 2.0 (the "License");
  1837. * you may not use this file except in compliance with the License.
  1838. * You may obtain a copy of the License at
  1839. *
  1840. * http://www.apache.org/licenses/LICENSE-2.0
  1841. *
  1842. * Unless required by applicable law or agreed to in writing, software
  1843. * distributed under the License is distributed on an "AS IS" BASIS,
  1844. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1845. * See the License for the specific language governing permissions and
  1846. * limitations under the License.
  1847. */
  1848. // Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they
  1849. // automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs,
  1850. // so it's been modified.
  1851. // Note that not all Unicode characters appear as single characters in JavaScript strings.
  1852. // fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters
  1853. // use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first
  1854. // character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate
  1855. // pair).
  1856. // See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3
  1857. /**
  1858. * @param {string} str
  1859. * @return {Array}
  1860. */
  1861. const stringToByteArray = function (str) {
  1862. const out = [];
  1863. let p = 0;
  1864. for (let i = 0; i < str.length; i++) {
  1865. let c = str.charCodeAt(i);
  1866. // Is this the lead surrogate in a surrogate pair?
  1867. if (c >= 0xd800 && c <= 0xdbff) {
  1868. const high = c - 0xd800; // the high 10 bits.
  1869. i++;
  1870. assert(i < str.length, 'Surrogate pair missing trail surrogate.');
  1871. const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.
  1872. c = 0x10000 + (high << 10) + low;
  1873. }
  1874. if (c < 128) {
  1875. out[p++] = c;
  1876. }
  1877. else if (c < 2048) {
  1878. out[p++] = (c >> 6) | 192;
  1879. out[p++] = (c & 63) | 128;
  1880. }
  1881. else if (c < 65536) {
  1882. out[p++] = (c >> 12) | 224;
  1883. out[p++] = ((c >> 6) & 63) | 128;
  1884. out[p++] = (c & 63) | 128;
  1885. }
  1886. else {
  1887. out[p++] = (c >> 18) | 240;
  1888. out[p++] = ((c >> 12) & 63) | 128;
  1889. out[p++] = ((c >> 6) & 63) | 128;
  1890. out[p++] = (c & 63) | 128;
  1891. }
  1892. }
  1893. return out;
  1894. };
  1895. /**
  1896. * Calculate length without actually converting; useful for doing cheaper validation.
  1897. * @param {string} str
  1898. * @return {number}
  1899. */
  1900. const stringLength = function (str) {
  1901. let p = 0;
  1902. for (let i = 0; i < str.length; i++) {
  1903. const c = str.charCodeAt(i);
  1904. if (c < 128) {
  1905. p++;
  1906. }
  1907. else if (c < 2048) {
  1908. p += 2;
  1909. }
  1910. else if (c >= 0xd800 && c <= 0xdbff) {
  1911. // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.
  1912. p += 4;
  1913. i++; // skip trail surrogate.
  1914. }
  1915. else {
  1916. p += 3;
  1917. }
  1918. }
  1919. return p;
  1920. };
  1921. /**
  1922. * @license
  1923. * Copyright 2022 Google LLC
  1924. *
  1925. * Licensed under the Apache License, Version 2.0 (the "License");
  1926. * you may not use this file except in compliance with the License.
  1927. * You may obtain a copy of the License at
  1928. *
  1929. * http://www.apache.org/licenses/LICENSE-2.0
  1930. *
  1931. * Unless required by applicable law or agreed to in writing, software
  1932. * distributed under the License is distributed on an "AS IS" BASIS,
  1933. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1934. * See the License for the specific language governing permissions and
  1935. * limitations under the License.
  1936. */
  1937. /**
  1938. * Copied from https://stackoverflow.com/a/2117523
  1939. * Generates a new uuid.
  1940. * @public
  1941. */
  1942. const uuidv4 = function () {
  1943. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
  1944. const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;
  1945. return v.toString(16);
  1946. });
  1947. };
  1948. /**
  1949. * @license
  1950. * Copyright 2019 Google LLC
  1951. *
  1952. * Licensed under the Apache License, Version 2.0 (the "License");
  1953. * you may not use this file except in compliance with the License.
  1954. * You may obtain a copy of the License at
  1955. *
  1956. * http://www.apache.org/licenses/LICENSE-2.0
  1957. *
  1958. * Unless required by applicable law or agreed to in writing, software
  1959. * distributed under the License is distributed on an "AS IS" BASIS,
  1960. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1961. * See the License for the specific language governing permissions and
  1962. * limitations under the License.
  1963. */
  1964. /**
  1965. * The amount of milliseconds to exponentially increase.
  1966. */
  1967. const DEFAULT_INTERVAL_MILLIS = 1000;
  1968. /**
  1969. * The factor to backoff by.
  1970. * Should be a number greater than 1.
  1971. */
  1972. const DEFAULT_BACKOFF_FACTOR = 2;
  1973. /**
  1974. * The maximum milliseconds to increase to.
  1975. *
  1976. * <p>Visible for testing
  1977. */
  1978. const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.
  1979. /**
  1980. * The percentage of backoff time to randomize by.
  1981. * See
  1982. * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic
  1983. * for context.
  1984. *
  1985. * <p>Visible for testing
  1986. */
  1987. const RANDOM_FACTOR = 0.5;
  1988. /**
  1989. * Based on the backoff method from
  1990. * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.
  1991. * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.
  1992. */
  1993. function calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {
  1994. // Calculates an exponentially increasing value.
  1995. // Deviation: calculates value from count and a constant interval, so we only need to save value
  1996. // and count to restore state.
  1997. const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);
  1998. // A random "fuzz" to avoid waves of retries.
  1999. // Deviation: randomFactor is required.
  2000. const randomWait = Math.round(
  2001. // A fraction of the backoff value to add/subtract.
  2002. // Deviation: changes multiplication order to improve readability.
  2003. RANDOM_FACTOR *
  2004. currBaseValue *
  2005. // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines
  2006. // if we add or subtract.
  2007. (Math.random() - 0.5) *
  2008. 2);
  2009. // Limits backoff to max to avoid effectively permanent backoff.
  2010. return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);
  2011. }
  2012. /**
  2013. * @license
  2014. * Copyright 2020 Google LLC
  2015. *
  2016. * Licensed under the Apache License, Version 2.0 (the "License");
  2017. * you may not use this file except in compliance with the License.
  2018. * You may obtain a copy of the License at
  2019. *
  2020. * http://www.apache.org/licenses/LICENSE-2.0
  2021. *
  2022. * Unless required by applicable law or agreed to in writing, software
  2023. * distributed under the License is distributed on an "AS IS" BASIS,
  2024. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2025. * See the License for the specific language governing permissions and
  2026. * limitations under the License.
  2027. */
  2028. /**
  2029. * Provide English ordinal letters after a number
  2030. */
  2031. function ordinal(i) {
  2032. if (!Number.isFinite(i)) {
  2033. return `${i}`;
  2034. }
  2035. return i + indicator(i);
  2036. }
  2037. function indicator(i) {
  2038. i = Math.abs(i);
  2039. const cent = i % 100;
  2040. if (cent >= 10 && cent <= 20) {
  2041. return 'th';
  2042. }
  2043. const dec = i % 10;
  2044. if (dec === 1) {
  2045. return 'st';
  2046. }
  2047. if (dec === 2) {
  2048. return 'nd';
  2049. }
  2050. if (dec === 3) {
  2051. return 'rd';
  2052. }
  2053. return 'th';
  2054. }
  2055. /**
  2056. * @license
  2057. * Copyright 2021 Google LLC
  2058. *
  2059. * Licensed under the Apache License, Version 2.0 (the "License");
  2060. * you may not use this file except in compliance with the License.
  2061. * You may obtain a copy of the License at
  2062. *
  2063. * http://www.apache.org/licenses/LICENSE-2.0
  2064. *
  2065. * Unless required by applicable law or agreed to in writing, software
  2066. * distributed under the License is distributed on an "AS IS" BASIS,
  2067. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2068. * See the License for the specific language governing permissions and
  2069. * limitations under the License.
  2070. */
  2071. function getModularInstance(service) {
  2072. if (service && service._delegate) {
  2073. return service._delegate;
  2074. }
  2075. else {
  2076. return service;
  2077. }
  2078. }
  2079. export { CONSTANTS, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };
  2080. //# sourceMappingURL=index.esm2017.js.map