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.

14484 lines
574 KiB

2 months ago
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var Websocket = require('faye-websocket');
  4. var util = require('@firebase/util');
  5. var tslib = require('tslib');
  6. var logger$1 = require('@firebase/logger');
  7. var app = require('@firebase/app');
  8. var component = require('@firebase/component');
  9. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  10. var Websocket__default = /*#__PURE__*/_interopDefaultLegacy(Websocket);
  11. /**
  12. * @license
  13. * Copyright 2017 Google LLC
  14. *
  15. * Licensed under the Apache License, Version 2.0 (the "License");
  16. * you may not use this file except in compliance with the License.
  17. * You may obtain a copy of the License at
  18. *
  19. * http://www.apache.org/licenses/LICENSE-2.0
  20. *
  21. * Unless required by applicable law or agreed to in writing, software
  22. * distributed under the License is distributed on an "AS IS" BASIS,
  23. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. * See the License for the specific language governing permissions and
  25. * limitations under the License.
  26. */
  27. var PROTOCOL_VERSION = '5';
  28. var VERSION_PARAM = 'v';
  29. var TRANSPORT_SESSION_PARAM = 's';
  30. var REFERER_PARAM = 'r';
  31. var FORGE_REF = 'f';
  32. // Matches console.firebase.google.com, firebase-console-*.corp.google.com and
  33. // firebase.corp.google.com
  34. var FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  35. var LAST_SESSION_PARAM = 'ls';
  36. var APPLICATION_ID_PARAM = 'p';
  37. var APP_CHECK_TOKEN_PARAM = 'ac';
  38. var WEBSOCKET = 'websocket';
  39. var LONG_POLLING = 'long_polling';
  40. /**
  41. * @license
  42. * Copyright 2017 Google LLC
  43. *
  44. * Licensed under the Apache License, Version 2.0 (the "License");
  45. * you may not use this file except in compliance with the License.
  46. * You may obtain a copy of the License at
  47. *
  48. * http://www.apache.org/licenses/LICENSE-2.0
  49. *
  50. * Unless required by applicable law or agreed to in writing, software
  51. * distributed under the License is distributed on an "AS IS" BASIS,
  52. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  53. * See the License for the specific language governing permissions and
  54. * limitations under the License.
  55. */
  56. /**
  57. * Wraps a DOM Storage object and:
  58. * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.
  59. * - prefixes names with "firebase:" to avoid collisions with app data.
  60. *
  61. * We automatically (see storage.js) create two such wrappers, one for sessionStorage,
  62. * and one for localStorage.
  63. *
  64. */
  65. var DOMStorageWrapper = /** @class */ (function () {
  66. /**
  67. * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
  68. */
  69. function DOMStorageWrapper(domStorage_) {
  70. this.domStorage_ = domStorage_;
  71. // Use a prefix to avoid collisions with other stuff saved by the app.
  72. this.prefix_ = 'firebase:';
  73. }
  74. /**
  75. * @param key - The key to save the value under
  76. * @param value - The value being stored, or null to remove the key.
  77. */
  78. DOMStorageWrapper.prototype.set = function (key, value) {
  79. if (value == null) {
  80. this.domStorage_.removeItem(this.prefixedName_(key));
  81. }
  82. else {
  83. this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));
  84. }
  85. };
  86. /**
  87. * @returns The value that was stored under this key, or null
  88. */
  89. DOMStorageWrapper.prototype.get = function (key) {
  90. var storedVal = this.domStorage_.getItem(this.prefixedName_(key));
  91. if (storedVal == null) {
  92. return null;
  93. }
  94. else {
  95. return util.jsonEval(storedVal);
  96. }
  97. };
  98. DOMStorageWrapper.prototype.remove = function (key) {
  99. this.domStorage_.removeItem(this.prefixedName_(key));
  100. };
  101. DOMStorageWrapper.prototype.prefixedName_ = function (name) {
  102. return this.prefix_ + name;
  103. };
  104. DOMStorageWrapper.prototype.toString = function () {
  105. return this.domStorage_.toString();
  106. };
  107. return DOMStorageWrapper;
  108. }());
  109. /**
  110. * @license
  111. * Copyright 2017 Google LLC
  112. *
  113. * Licensed under the Apache License, Version 2.0 (the "License");
  114. * you may not use this file except in compliance with the License.
  115. * You may obtain a copy of the License at
  116. *
  117. * http://www.apache.org/licenses/LICENSE-2.0
  118. *
  119. * Unless required by applicable law or agreed to in writing, software
  120. * distributed under the License is distributed on an "AS IS" BASIS,
  121. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  122. * See the License for the specific language governing permissions and
  123. * limitations under the License.
  124. */
  125. /**
  126. * An in-memory storage implementation that matches the API of DOMStorageWrapper
  127. * (TODO: create interface for both to implement).
  128. */
  129. var MemoryStorage = /** @class */ (function () {
  130. function MemoryStorage() {
  131. this.cache_ = {};
  132. this.isInMemoryStorage = true;
  133. }
  134. MemoryStorage.prototype.set = function (key, value) {
  135. if (value == null) {
  136. delete this.cache_[key];
  137. }
  138. else {
  139. this.cache_[key] = value;
  140. }
  141. };
  142. MemoryStorage.prototype.get = function (key) {
  143. if (util.contains(this.cache_, key)) {
  144. return this.cache_[key];
  145. }
  146. return null;
  147. };
  148. MemoryStorage.prototype.remove = function (key) {
  149. delete this.cache_[key];
  150. };
  151. return MemoryStorage;
  152. }());
  153. /**
  154. * @license
  155. * Copyright 2017 Google LLC
  156. *
  157. * Licensed under the Apache License, Version 2.0 (the "License");
  158. * you may not use this file except in compliance with the License.
  159. * You may obtain a copy of the License at
  160. *
  161. * http://www.apache.org/licenses/LICENSE-2.0
  162. *
  163. * Unless required by applicable law or agreed to in writing, software
  164. * distributed under the License is distributed on an "AS IS" BASIS,
  165. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  166. * See the License for the specific language governing permissions and
  167. * limitations under the License.
  168. */
  169. /**
  170. * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.
  171. * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change
  172. * to reflect this type
  173. *
  174. * @param domStorageName - Name of the underlying storage object
  175. * (e.g. 'localStorage' or 'sessionStorage').
  176. * @returns Turning off type information until a common interface is defined.
  177. */
  178. var createStoragefor = function (domStorageName) {
  179. try {
  180. // NOTE: just accessing "localStorage" or "window['localStorage']" may throw a security exception,
  181. // so it must be inside the try/catch.
  182. if (typeof window !== 'undefined' &&
  183. typeof window[domStorageName] !== 'undefined') {
  184. // Need to test cache. Just because it's here doesn't mean it works
  185. var domStorage = window[domStorageName];
  186. domStorage.setItem('firebase:sentinel', 'cache');
  187. domStorage.removeItem('firebase:sentinel');
  188. return new DOMStorageWrapper(domStorage);
  189. }
  190. }
  191. catch (e) { }
  192. // Failed to create wrapper. Just return in-memory storage.
  193. // TODO: log?
  194. return new MemoryStorage();
  195. };
  196. /** A storage object that lasts across sessions */
  197. var PersistentStorage = createStoragefor('localStorage');
  198. /** A storage object that only lasts one session */
  199. var SessionStorage = createStoragefor('sessionStorage');
  200. /**
  201. * @license
  202. * Copyright 2017 Google LLC
  203. *
  204. * Licensed under the Apache License, Version 2.0 (the "License");
  205. * you may not use this file except in compliance with the License.
  206. * You may obtain a copy of the License at
  207. *
  208. * http://www.apache.org/licenses/LICENSE-2.0
  209. *
  210. * Unless required by applicable law or agreed to in writing, software
  211. * distributed under the License is distributed on an "AS IS" BASIS,
  212. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  213. * See the License for the specific language governing permissions and
  214. * limitations under the License.
  215. */
  216. var logClient = new logger$1.Logger('@firebase/database');
  217. /**
  218. * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
  219. */
  220. var LUIDGenerator = (function () {
  221. var id = 1;
  222. return function () {
  223. return id++;
  224. };
  225. })();
  226. /**
  227. * Sha1 hash of the input string
  228. * @param str - The string to hash
  229. * @returns {!string} The resulting hash
  230. */
  231. var sha1 = function (str) {
  232. var utf8Bytes = util.stringToByteArray(str);
  233. var sha1 = new util.Sha1();
  234. sha1.update(utf8Bytes);
  235. var sha1Bytes = sha1.digest();
  236. return util.base64.encodeByteArray(sha1Bytes);
  237. };
  238. var buildLogMessage_ = function () {
  239. var varArgs = [];
  240. for (var _i = 0; _i < arguments.length; _i++) {
  241. varArgs[_i] = arguments[_i];
  242. }
  243. var message = '';
  244. for (var i = 0; i < varArgs.length; i++) {
  245. var arg = varArgs[i];
  246. if (Array.isArray(arg) ||
  247. (arg &&
  248. typeof arg === 'object' &&
  249. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  250. typeof arg.length === 'number')) {
  251. message += buildLogMessage_.apply(null, arg);
  252. }
  253. else if (typeof arg === 'object') {
  254. message += util.stringify(arg);
  255. }
  256. else {
  257. message += arg;
  258. }
  259. message += ' ';
  260. }
  261. return message;
  262. };
  263. /**
  264. * Use this for all debug messages in Firebase.
  265. */
  266. var logger = null;
  267. /**
  268. * Flag to check for log availability on first log message
  269. */
  270. var firstLog_ = true;
  271. /**
  272. * The implementation of Firebase.enableLogging (defined here to break dependencies)
  273. * @param logger_ - A flag to turn on logging, or a custom logger
  274. * @param persistent - Whether or not to persist logging settings across refreshes
  275. */
  276. var enableLogging$1 = function (logger_, persistent) {
  277. util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
  278. if (logger_ === true) {
  279. logClient.logLevel = logger$1.LogLevel.VERBOSE;
  280. logger = logClient.log.bind(logClient);
  281. if (persistent) {
  282. SessionStorage.set('logging_enabled', true);
  283. }
  284. }
  285. else if (typeof logger_ === 'function') {
  286. logger = logger_;
  287. }
  288. else {
  289. logger = null;
  290. SessionStorage.remove('logging_enabled');
  291. }
  292. };
  293. var log = function () {
  294. var varArgs = [];
  295. for (var _i = 0; _i < arguments.length; _i++) {
  296. varArgs[_i] = arguments[_i];
  297. }
  298. if (firstLog_ === true) {
  299. firstLog_ = false;
  300. if (logger === null && SessionStorage.get('logging_enabled') === true) {
  301. enableLogging$1(true);
  302. }
  303. }
  304. if (logger) {
  305. var message = buildLogMessage_.apply(null, varArgs);
  306. logger(message);
  307. }
  308. };
  309. var logWrapper = function (prefix) {
  310. return function () {
  311. var varArgs = [];
  312. for (var _i = 0; _i < arguments.length; _i++) {
  313. varArgs[_i] = arguments[_i];
  314. }
  315. log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
  316. };
  317. };
  318. var error = function () {
  319. var varArgs = [];
  320. for (var _i = 0; _i < arguments.length; _i++) {
  321. varArgs[_i] = arguments[_i];
  322. }
  323. var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
  324. logClient.error(message);
  325. };
  326. var fatal = function () {
  327. var varArgs = [];
  328. for (var _i = 0; _i < arguments.length; _i++) {
  329. varArgs[_i] = arguments[_i];
  330. }
  331. var message = "FIREBASE FATAL ERROR: ".concat(buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false)));
  332. logClient.error(message);
  333. throw new Error(message);
  334. };
  335. var warn = function () {
  336. var varArgs = [];
  337. for (var _i = 0; _i < arguments.length; _i++) {
  338. varArgs[_i] = arguments[_i];
  339. }
  340. var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
  341. logClient.warn(message);
  342. };
  343. /**
  344. * Logs a warning if the containing page uses https. Called when a call to new Firebase
  345. * does not use https.
  346. */
  347. var warnIfPageIsSecure = function () {
  348. // Be very careful accessing browser globals. Who knows what may or may not exist.
  349. if (typeof window !== 'undefined' &&
  350. window.location &&
  351. window.location.protocol &&
  352. window.location.protocol.indexOf('https:') !== -1) {
  353. warn('Insecure Firebase access from a secure page. ' +
  354. 'Please use https in calls to new Firebase().');
  355. }
  356. };
  357. /**
  358. * Returns true if data is NaN, or +/- Infinity.
  359. */
  360. var isInvalidJSONNumber = function (data) {
  361. return (typeof data === 'number' &&
  362. (data !== data || // NaN
  363. data === Number.POSITIVE_INFINITY ||
  364. data === Number.NEGATIVE_INFINITY));
  365. };
  366. var executeWhenDOMReady = function (fn) {
  367. if (util.isNodeSdk() || document.readyState === 'complete') {
  368. fn();
  369. }
  370. else {
  371. // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
  372. // fire before onload), but fall back to onload.
  373. var called_1 = false;
  374. var wrappedFn_1 = function () {
  375. if (!document.body) {
  376. setTimeout(wrappedFn_1, Math.floor(10));
  377. return;
  378. }
  379. if (!called_1) {
  380. called_1 = true;
  381. fn();
  382. }
  383. };
  384. if (document.addEventListener) {
  385. document.addEventListener('DOMContentLoaded', wrappedFn_1, false);
  386. // fallback to onload.
  387. window.addEventListener('load', wrappedFn_1, false);
  388. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  389. }
  390. else if (document.attachEvent) {
  391. // IE.
  392. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  393. document.attachEvent('onreadystatechange', function () {
  394. if (document.readyState === 'complete') {
  395. wrappedFn_1();
  396. }
  397. });
  398. // fallback to onload.
  399. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  400. window.attachEvent('onload', wrappedFn_1);
  401. // jQuery has an extra hack for IE that we could employ (based on
  402. // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
  403. // I'm hoping we don't need it.
  404. }
  405. }
  406. };
  407. /**
  408. * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
  409. */
  410. var MIN_NAME = '[MIN_NAME]';
  411. /**
  412. * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
  413. */
  414. var MAX_NAME = '[MAX_NAME]';
  415. /**
  416. * Compares valid Firebase key names, plus min and max name
  417. */
  418. var nameCompare = function (a, b) {
  419. if (a === b) {
  420. return 0;
  421. }
  422. else if (a === MIN_NAME || b === MAX_NAME) {
  423. return -1;
  424. }
  425. else if (b === MIN_NAME || a === MAX_NAME) {
  426. return 1;
  427. }
  428. else {
  429. var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
  430. if (aAsInt !== null) {
  431. if (bAsInt !== null) {
  432. return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
  433. }
  434. else {
  435. return -1;
  436. }
  437. }
  438. else if (bAsInt !== null) {
  439. return 1;
  440. }
  441. else {
  442. return a < b ? -1 : 1;
  443. }
  444. }
  445. };
  446. /**
  447. * @returns {!number} comparison result.
  448. */
  449. var stringCompare = function (a, b) {
  450. if (a === b) {
  451. return 0;
  452. }
  453. else if (a < b) {
  454. return -1;
  455. }
  456. else {
  457. return 1;
  458. }
  459. };
  460. var requireKey = function (key, obj) {
  461. if (obj && key in obj) {
  462. return obj[key];
  463. }
  464. else {
  465. throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));
  466. }
  467. };
  468. var ObjectToUniqueKey = function (obj) {
  469. if (typeof obj !== 'object' || obj === null) {
  470. return util.stringify(obj);
  471. }
  472. var keys = [];
  473. // eslint-disable-next-line guard-for-in
  474. for (var k in obj) {
  475. keys.push(k);
  476. }
  477. // Export as json, but with the keys sorted.
  478. keys.sort();
  479. var key = '{';
  480. for (var i = 0; i < keys.length; i++) {
  481. if (i !== 0) {
  482. key += ',';
  483. }
  484. key += util.stringify(keys[i]);
  485. key += ':';
  486. key += ObjectToUniqueKey(obj[keys[i]]);
  487. }
  488. key += '}';
  489. return key;
  490. };
  491. /**
  492. * Splits a string into a number of smaller segments of maximum size
  493. * @param str - The string
  494. * @param segsize - The maximum number of chars in the string.
  495. * @returns The string, split into appropriately-sized chunks
  496. */
  497. var splitStringBySize = function (str, segsize) {
  498. var len = str.length;
  499. if (len <= segsize) {
  500. return [str];
  501. }
  502. var dataSegs = [];
  503. for (var c = 0; c < len; c += segsize) {
  504. if (c + segsize > len) {
  505. dataSegs.push(str.substring(c, len));
  506. }
  507. else {
  508. dataSegs.push(str.substring(c, c + segsize));
  509. }
  510. }
  511. return dataSegs;
  512. };
  513. /**
  514. * Apply a function to each (key, value) pair in an object or
  515. * apply a function to each (index, value) pair in an array
  516. * @param obj - The object or array to iterate over
  517. * @param fn - The function to apply
  518. */
  519. function each(obj, fn) {
  520. for (var key in obj) {
  521. if (obj.hasOwnProperty(key)) {
  522. fn(key, obj[key]);
  523. }
  524. }
  525. }
  526. /**
  527. * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
  528. * I made one modification at the end and removed the NaN / Infinity
  529. * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
  530. * @param v - A double
  531. *
  532. */
  533. var doubleToIEEE754String = function (v) {
  534. util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
  535. var ebits = 11, fbits = 52;
  536. var bias = (1 << (ebits - 1)) - 1;
  537. var s, e, f, ln, i;
  538. // Compute sign, exponent, fraction
  539. // Skip NaN / Infinity handling --MJL.
  540. if (v === 0) {
  541. e = 0;
  542. f = 0;
  543. s = 1 / v === -Infinity ? 1 : 0;
  544. }
  545. else {
  546. s = v < 0;
  547. v = Math.abs(v);
  548. if (v >= Math.pow(2, 1 - bias)) {
  549. // Normalized
  550. ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
  551. e = ln + bias;
  552. f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
  553. }
  554. else {
  555. // Denormalized
  556. e = 0;
  557. f = Math.round(v / Math.pow(2, 1 - bias - fbits));
  558. }
  559. }
  560. // Pack sign, exponent, fraction
  561. var bits = [];
  562. for (i = fbits; i; i -= 1) {
  563. bits.push(f % 2 ? 1 : 0);
  564. f = Math.floor(f / 2);
  565. }
  566. for (i = ebits; i; i -= 1) {
  567. bits.push(e % 2 ? 1 : 0);
  568. e = Math.floor(e / 2);
  569. }
  570. bits.push(s ? 1 : 0);
  571. bits.reverse();
  572. var str = bits.join('');
  573. // Return the data as a hex string. --MJL
  574. var hexByteString = '';
  575. for (i = 0; i < 64; i += 8) {
  576. var hexByte = parseInt(str.substr(i, 8), 2).toString(16);
  577. if (hexByte.length === 1) {
  578. hexByte = '0' + hexByte;
  579. }
  580. hexByteString = hexByteString + hexByte;
  581. }
  582. return hexByteString.toLowerCase();
  583. };
  584. /**
  585. * Used to detect if we're in a Chrome content script (which executes in an
  586. * isolated environment where long-polling doesn't work).
  587. */
  588. var isChromeExtensionContentScript = function () {
  589. return !!(typeof window === 'object' &&
  590. window['chrome'] &&
  591. window['chrome']['extension'] &&
  592. !/^chrome/.test(window.location.href));
  593. };
  594. /**
  595. * Used to detect if we're in a Windows 8 Store app.
  596. */
  597. var isWindowsStoreApp = function () {
  598. // Check for the presence of a couple WinRT globals
  599. return typeof Windows === 'object' && typeof Windows.UI === 'object';
  600. };
  601. /**
  602. * Converts a server error code to a Javascript Error
  603. */
  604. function errorForServerCode(code, query) {
  605. var reason = 'Unknown Error';
  606. if (code === 'too_big') {
  607. reason =
  608. 'The data requested exceeds the maximum size ' +
  609. 'that can be accessed with a single request.';
  610. }
  611. else if (code === 'permission_denied') {
  612. reason = "Client doesn't have permission to access the desired data.";
  613. }
  614. else if (code === 'unavailable') {
  615. reason = 'The service is unavailable';
  616. }
  617. var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
  618. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  619. error.code = code.toUpperCase();
  620. return error;
  621. }
  622. /**
  623. * Used to test for integer-looking strings
  624. */
  625. var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
  626. /**
  627. * For use in keys, the minimum possible 32-bit integer.
  628. */
  629. var INTEGER_32_MIN = -2147483648;
  630. /**
  631. * For use in kyes, the maximum possible 32-bit integer.
  632. */
  633. var INTEGER_32_MAX = 2147483647;
  634. /**
  635. * If the string contains a 32-bit integer, return it. Else return null.
  636. */
  637. var tryParseInt = function (str) {
  638. if (INTEGER_REGEXP_.test(str)) {
  639. var intVal = Number(str);
  640. if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
  641. return intVal;
  642. }
  643. }
  644. return null;
  645. };
  646. /**
  647. * Helper to run some code but catch any exceptions and re-throw them later.
  648. * Useful for preventing user callbacks from breaking internal code.
  649. *
  650. * Re-throwing the exception from a setTimeout is a little evil, but it's very
  651. * convenient (we don't have to try to figure out when is a safe point to
  652. * re-throw it), and the behavior seems reasonable:
  653. *
  654. * * If you aren't pausing on exceptions, you get an error in the console with
  655. * the correct stack trace.
  656. * * If you're pausing on all exceptions, the debugger will pause on your
  657. * exception and then again when we rethrow it.
  658. * * If you're only pausing on uncaught exceptions, the debugger will only pause
  659. * on us re-throwing it.
  660. *
  661. * @param fn - The code to guard.
  662. */
  663. var exceptionGuard = function (fn) {
  664. try {
  665. fn();
  666. }
  667. catch (e) {
  668. // Re-throw exception when it's safe.
  669. setTimeout(function () {
  670. // It used to be that "throw e" would result in a good console error with
  671. // relevant context, but as of Chrome 39, you just get the firebase.js
  672. // file/line number where we re-throw it, which is useless. So we log
  673. // e.stack explicitly.
  674. var stack = e.stack || '';
  675. warn('Exception was thrown by user callback.', stack);
  676. throw e;
  677. }, Math.floor(0));
  678. }
  679. };
  680. /**
  681. * @returns {boolean} true if we think we're currently being crawled.
  682. */
  683. var beingCrawled = function () {
  684. var userAgent = (typeof window === 'object' &&
  685. window['navigator'] &&
  686. window['navigator']['userAgent']) ||
  687. '';
  688. // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
  689. // believe to support JavaScript/AJAX rendering.
  690. // NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
  691. // would have seen the page" is flaky if we don't treat it as a crawler.
  692. return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
  693. };
  694. /**
  695. * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
  696. *
  697. * It is removed with clearTimeout() as normal.
  698. *
  699. * @param fn - Function to run.
  700. * @param time - Milliseconds to wait before running.
  701. * @returns The setTimeout() return value.
  702. */
  703. var setTimeoutNonBlocking = function (fn, time) {
  704. var timeout = setTimeout(fn, time);
  705. // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.
  706. if (typeof timeout === 'number' &&
  707. // @ts-ignore Is only defined in Deno environments.
  708. typeof Deno !== 'undefined' &&
  709. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  710. Deno['unrefTimer']) {
  711. // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
  712. Deno.unrefTimer(timeout);
  713. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  714. }
  715. else if (typeof timeout === 'object' && timeout['unref']) {
  716. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  717. timeout['unref']();
  718. }
  719. return timeout;
  720. };
  721. /**
  722. * @license
  723. * Copyright 2017 Google LLC
  724. *
  725. * Licensed under the Apache License, Version 2.0 (the "License");
  726. * you may not use this file except in compliance with the License.
  727. * You may obtain a copy of the License at
  728. *
  729. * http://www.apache.org/licenses/LICENSE-2.0
  730. *
  731. * Unless required by applicable law or agreed to in writing, software
  732. * distributed under the License is distributed on an "AS IS" BASIS,
  733. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  734. * See the License for the specific language governing permissions and
  735. * limitations under the License.
  736. */
  737. /**
  738. * A class that holds metadata about a Repo object
  739. */
  740. var RepoInfo = /** @class */ (function () {
  741. /**
  742. * @param host - Hostname portion of the url for the repo
  743. * @param secure - Whether or not this repo is accessed over ssl
  744. * @param namespace - The namespace represented by the repo
  745. * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
  746. * @param nodeAdmin - Whether this instance uses Admin SDK credentials
  747. * @param persistenceKey - Override the default session persistence storage key
  748. */
  749. function RepoInfo(host, secure, namespace, webSocketOnly, nodeAdmin, persistenceKey, includeNamespaceInQueryParams) {
  750. if (nodeAdmin === void 0) { nodeAdmin = false; }
  751. if (persistenceKey === void 0) { persistenceKey = ''; }
  752. if (includeNamespaceInQueryParams === void 0) { includeNamespaceInQueryParams = false; }
  753. this.secure = secure;
  754. this.namespace = namespace;
  755. this.webSocketOnly = webSocketOnly;
  756. this.nodeAdmin = nodeAdmin;
  757. this.persistenceKey = persistenceKey;
  758. this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
  759. this._host = host.toLowerCase();
  760. this._domain = this._host.substr(this._host.indexOf('.') + 1);
  761. this.internalHost =
  762. PersistentStorage.get('host:' + host) || this._host;
  763. }
  764. RepoInfo.prototype.isCacheableHost = function () {
  765. return this.internalHost.substr(0, 2) === 's-';
  766. };
  767. RepoInfo.prototype.isCustomHost = function () {
  768. return (this._domain !== 'firebaseio.com' &&
  769. this._domain !== 'firebaseio-demo.com');
  770. };
  771. Object.defineProperty(RepoInfo.prototype, "host", {
  772. get: function () {
  773. return this._host;
  774. },
  775. set: function (newHost) {
  776. if (newHost !== this.internalHost) {
  777. this.internalHost = newHost;
  778. if (this.isCacheableHost()) {
  779. PersistentStorage.set('host:' + this._host, this.internalHost);
  780. }
  781. }
  782. },
  783. enumerable: false,
  784. configurable: true
  785. });
  786. RepoInfo.prototype.toString = function () {
  787. var str = this.toURLString();
  788. if (this.persistenceKey) {
  789. str += '<' + this.persistenceKey + '>';
  790. }
  791. return str;
  792. };
  793. RepoInfo.prototype.toURLString = function () {
  794. var protocol = this.secure ? 'https://' : 'http://';
  795. var query = this.includeNamespaceInQueryParams
  796. ? "?ns=".concat(this.namespace)
  797. : '';
  798. return "".concat(protocol).concat(this.host, "/").concat(query);
  799. };
  800. return RepoInfo;
  801. }());
  802. function repoInfoNeedsQueryParam(repoInfo) {
  803. return (repoInfo.host !== repoInfo.internalHost ||
  804. repoInfo.isCustomHost() ||
  805. repoInfo.includeNamespaceInQueryParams);
  806. }
  807. /**
  808. * Returns the websocket URL for this repo
  809. * @param repoInfo - RepoInfo object
  810. * @param type - of connection
  811. * @param params - list
  812. * @returns The URL for this repo
  813. */
  814. function repoInfoConnectionURL(repoInfo, type, params) {
  815. util.assert(typeof type === 'string', 'typeof type must == string');
  816. util.assert(typeof params === 'object', 'typeof params must == object');
  817. var connURL;
  818. if (type === WEBSOCKET) {
  819. connURL =
  820. (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
  821. }
  822. else if (type === LONG_POLLING) {
  823. connURL =
  824. (repoInfo.secure ? 'https://' : 'http://') +
  825. repoInfo.internalHost +
  826. '/.lp?';
  827. }
  828. else {
  829. throw new Error('Unknown connection type: ' + type);
  830. }
  831. if (repoInfoNeedsQueryParam(repoInfo)) {
  832. params['ns'] = repoInfo.namespace;
  833. }
  834. var pairs = [];
  835. each(params, function (key, value) {
  836. pairs.push(key + '=' + value);
  837. });
  838. return connURL + pairs.join('&');
  839. }
  840. /**
  841. * @license
  842. * Copyright 2017 Google LLC
  843. *
  844. * Licensed under the Apache License, Version 2.0 (the "License");
  845. * you may not use this file except in compliance with the License.
  846. * You may obtain a copy of the License at
  847. *
  848. * http://www.apache.org/licenses/LICENSE-2.0
  849. *
  850. * Unless required by applicable law or agreed to in writing, software
  851. * distributed under the License is distributed on an "AS IS" BASIS,
  852. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  853. * See the License for the specific language governing permissions and
  854. * limitations under the License.
  855. */
  856. /**
  857. * Tracks a collection of stats.
  858. */
  859. var StatsCollection = /** @class */ (function () {
  860. function StatsCollection() {
  861. this.counters_ = {};
  862. }
  863. StatsCollection.prototype.incrementCounter = function (name, amount) {
  864. if (amount === void 0) { amount = 1; }
  865. if (!util.contains(this.counters_, name)) {
  866. this.counters_[name] = 0;
  867. }
  868. this.counters_[name] += amount;
  869. };
  870. StatsCollection.prototype.get = function () {
  871. return util.deepCopy(this.counters_);
  872. };
  873. return StatsCollection;
  874. }());
  875. /**
  876. * @license
  877. * Copyright 2017 Google LLC
  878. *
  879. * Licensed under the Apache License, Version 2.0 (the "License");
  880. * you may not use this file except in compliance with the License.
  881. * You may obtain a copy of the License at
  882. *
  883. * http://www.apache.org/licenses/LICENSE-2.0
  884. *
  885. * Unless required by applicable law or agreed to in writing, software
  886. * distributed under the License is distributed on an "AS IS" BASIS,
  887. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  888. * See the License for the specific language governing permissions and
  889. * limitations under the License.
  890. */
  891. var collections = {};
  892. var reporters = {};
  893. function statsManagerGetCollection(repoInfo) {
  894. var hashString = repoInfo.toString();
  895. if (!collections[hashString]) {
  896. collections[hashString] = new StatsCollection();
  897. }
  898. return collections[hashString];
  899. }
  900. function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
  901. var hashString = repoInfo.toString();
  902. if (!reporters[hashString]) {
  903. reporters[hashString] = creatorFunction();
  904. }
  905. return reporters[hashString];
  906. }
  907. /**
  908. * @license
  909. * Copyright 2019 Google LLC
  910. *
  911. * Licensed under the Apache License, Version 2.0 (the "License");
  912. * you may not use this file except in compliance with the License.
  913. * You may obtain a copy of the License at
  914. *
  915. * http://www.apache.org/licenses/LICENSE-2.0
  916. *
  917. * Unless required by applicable law or agreed to in writing, software
  918. * distributed under the License is distributed on an "AS IS" BASIS,
  919. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  920. * See the License for the specific language governing permissions and
  921. * limitations under the License.
  922. */
  923. /** The semver (www.semver.org) version of the SDK. */
  924. var SDK_VERSION = '';
  925. /**
  926. * SDK_VERSION should be set before any database instance is created
  927. * @internal
  928. */
  929. function setSDKVersion(version) {
  930. SDK_VERSION = version;
  931. }
  932. /**
  933. * @license
  934. * Copyright 2017 Google LLC
  935. *
  936. * Licensed under the Apache License, Version 2.0 (the "License");
  937. * you may not use this file except in compliance with the License.
  938. * You may obtain a copy of the License at
  939. *
  940. * http://www.apache.org/licenses/LICENSE-2.0
  941. *
  942. * Unless required by applicable law or agreed to in writing, software
  943. * distributed under the License is distributed on an "AS IS" BASIS,
  944. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  945. * See the License for the specific language governing permissions and
  946. * limitations under the License.
  947. */
  948. var WEBSOCKET_MAX_FRAME_SIZE = 16384;
  949. var WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
  950. var WebSocketImpl = null;
  951. if (typeof MozWebSocket !== 'undefined') {
  952. WebSocketImpl = MozWebSocket;
  953. }
  954. else if (typeof WebSocket !== 'undefined') {
  955. WebSocketImpl = WebSocket;
  956. }
  957. function setWebSocketImpl(impl) {
  958. WebSocketImpl = impl;
  959. }
  960. /**
  961. * Create a new websocket connection with the given callbacks.
  962. */
  963. var WebSocketConnection = /** @class */ (function () {
  964. /**
  965. * @param connId identifier for this transport
  966. * @param repoInfo The info for the websocket endpoint.
  967. * @param applicationId The Firebase App ID for this project.
  968. * @param appCheckToken The App Check Token for this client.
  969. * @param authToken The Auth Token for this client.
  970. * @param transportSessionId Optional transportSessionId if this is connecting
  971. * to an existing transport session
  972. * @param lastSessionId Optional lastSessionId if there was a previous
  973. * connection
  974. */
  975. function WebSocketConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  976. this.connId = connId;
  977. this.applicationId = applicationId;
  978. this.appCheckToken = appCheckToken;
  979. this.authToken = authToken;
  980. this.keepaliveTimer = null;
  981. this.frames = null;
  982. this.totalFrames = 0;
  983. this.bytesSent = 0;
  984. this.bytesReceived = 0;
  985. this.log_ = logWrapper(this.connId);
  986. this.stats_ = statsManagerGetCollection(repoInfo);
  987. this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
  988. this.nodeAdmin = repoInfo.nodeAdmin;
  989. }
  990. /**
  991. * @param repoInfo - The info for the websocket endpoint.
  992. * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
  993. * session
  994. * @param lastSessionId - Optional lastSessionId if there was a previous connection
  995. * @returns connection url
  996. */
  997. WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
  998. var urlParams = {};
  999. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1000. if (!util.isNodeSdk() &&
  1001. typeof location !== 'undefined' &&
  1002. location.hostname &&
  1003. FORGE_DOMAIN_RE.test(location.hostname)) {
  1004. urlParams[REFERER_PARAM] = FORGE_REF;
  1005. }
  1006. if (transportSessionId) {
  1007. urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
  1008. }
  1009. if (lastSessionId) {
  1010. urlParams[LAST_SESSION_PARAM] = lastSessionId;
  1011. }
  1012. if (appCheckToken) {
  1013. urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
  1014. }
  1015. if (applicationId) {
  1016. urlParams[APPLICATION_ID_PARAM] = applicationId;
  1017. }
  1018. return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
  1019. };
  1020. /**
  1021. * @param onMessage - Callback when messages arrive
  1022. * @param onDisconnect - Callback with connection lost.
  1023. */
  1024. WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {
  1025. var _this = this;
  1026. this.onDisconnect = onDisconnect;
  1027. this.onMessage = onMessage;
  1028. this.log_('Websocket connecting to ' + this.connURL);
  1029. this.everConnected_ = false;
  1030. // Assume failure until proven otherwise.
  1031. PersistentStorage.set('previous_websocket_failure', true);
  1032. try {
  1033. var options = void 0;
  1034. if (util.isNodeSdk()) {
  1035. var device = this.nodeAdmin ? 'AdminNode' : 'Node';
  1036. // UA Format: Firebase/<wire_protocol>/<sdk_version>/<platform>/<device>
  1037. options = {
  1038. headers: {
  1039. 'User-Agent': "Firebase/".concat(PROTOCOL_VERSION, "/").concat(SDK_VERSION, "/").concat(process.platform, "/").concat(device),
  1040. 'X-Firebase-GMPID': this.applicationId || ''
  1041. }
  1042. };
  1043. // If using Node with admin creds, AppCheck-related checks are unnecessary.
  1044. // Note that we send the credentials here even if they aren't admin credentials, which is
  1045. // not a problem.
  1046. // Note that this header is just used to bypass appcheck, and the token should still be sent
  1047. // through the websocket connection once it is established.
  1048. if (this.authToken) {
  1049. options.headers['Authorization'] = "Bearer ".concat(this.authToken);
  1050. }
  1051. if (this.appCheckToken) {
  1052. options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
  1053. }
  1054. // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.
  1055. var env = process['env'];
  1056. var proxy = this.connURL.indexOf('wss://') === 0
  1057. ? env['HTTPS_PROXY'] || env['https_proxy']
  1058. : env['HTTP_PROXY'] || env['http_proxy'];
  1059. if (proxy) {
  1060. options['proxy'] = { origin: proxy };
  1061. }
  1062. }
  1063. this.mySock = new WebSocketImpl(this.connURL, [], options);
  1064. }
  1065. catch (e) {
  1066. this.log_('Error instantiating WebSocket.');
  1067. var error = e.message || e.data;
  1068. if (error) {
  1069. this.log_(error);
  1070. }
  1071. this.onClosed_();
  1072. return;
  1073. }
  1074. this.mySock.onopen = function () {
  1075. _this.log_('Websocket connected.');
  1076. _this.everConnected_ = true;
  1077. };
  1078. this.mySock.onclose = function () {
  1079. _this.log_('Websocket connection was disconnected.');
  1080. _this.mySock = null;
  1081. _this.onClosed_();
  1082. };
  1083. this.mySock.onmessage = function (m) {
  1084. _this.handleIncomingFrame(m);
  1085. };
  1086. this.mySock.onerror = function (e) {
  1087. _this.log_('WebSocket error. Closing connection.');
  1088. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1089. var error = e.message || e.data;
  1090. if (error) {
  1091. _this.log_(error);
  1092. }
  1093. _this.onClosed_();
  1094. };
  1095. };
  1096. /**
  1097. * No-op for websockets, we don't need to do anything once the connection is confirmed as open
  1098. */
  1099. WebSocketConnection.prototype.start = function () { };
  1100. WebSocketConnection.forceDisallow = function () {
  1101. WebSocketConnection.forceDisallow_ = true;
  1102. };
  1103. WebSocketConnection.isAvailable = function () {
  1104. var isOldAndroid = false;
  1105. if (typeof navigator !== 'undefined' && navigator.userAgent) {
  1106. var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
  1107. var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
  1108. if (oldAndroidMatch && oldAndroidMatch.length > 1) {
  1109. if (parseFloat(oldAndroidMatch[1]) < 4.4) {
  1110. isOldAndroid = true;
  1111. }
  1112. }
  1113. }
  1114. return (!isOldAndroid &&
  1115. WebSocketImpl !== null &&
  1116. !WebSocketConnection.forceDisallow_);
  1117. };
  1118. /**
  1119. * Returns true if we previously failed to connect with this transport.
  1120. */
  1121. WebSocketConnection.previouslyFailed = function () {
  1122. // If our persistent storage is actually only in-memory storage,
  1123. // we default to assuming that it previously failed to be safe.
  1124. return (PersistentStorage.isInMemoryStorage ||
  1125. PersistentStorage.get('previous_websocket_failure') === true);
  1126. };
  1127. WebSocketConnection.prototype.markConnectionHealthy = function () {
  1128. PersistentStorage.remove('previous_websocket_failure');
  1129. };
  1130. WebSocketConnection.prototype.appendFrame_ = function (data) {
  1131. this.frames.push(data);
  1132. if (this.frames.length === this.totalFrames) {
  1133. var fullMess = this.frames.join('');
  1134. this.frames = null;
  1135. var jsonMess = util.jsonEval(fullMess);
  1136. //handle the message
  1137. this.onMessage(jsonMess);
  1138. }
  1139. };
  1140. /**
  1141. * @param frameCount - The number of frames we are expecting from the server
  1142. */
  1143. WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {
  1144. this.totalFrames = frameCount;
  1145. this.frames = [];
  1146. };
  1147. /**
  1148. * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
  1149. * @returns Any remaining data to be process, or null if there is none
  1150. */
  1151. WebSocketConnection.prototype.extractFrameCount_ = function (data) {
  1152. util.assert(this.frames === null, 'We already have a frame buffer');
  1153. // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced
  1154. // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508
  1155. if (data.length <= 6) {
  1156. var frameCount = Number(data);
  1157. if (!isNaN(frameCount)) {
  1158. this.handleNewFrameCount_(frameCount);
  1159. return null;
  1160. }
  1161. }
  1162. this.handleNewFrameCount_(1);
  1163. return data;
  1164. };
  1165. /**
  1166. * Process a websocket frame that has arrived from the server.
  1167. * @param mess - The frame data
  1168. */
  1169. WebSocketConnection.prototype.handleIncomingFrame = function (mess) {
  1170. if (this.mySock === null) {
  1171. return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.
  1172. }
  1173. var data = mess['data'];
  1174. this.bytesReceived += data.length;
  1175. this.stats_.incrementCounter('bytes_received', data.length);
  1176. this.resetKeepAlive();
  1177. if (this.frames !== null) {
  1178. // we're buffering
  1179. this.appendFrame_(data);
  1180. }
  1181. else {
  1182. // try to parse out a frame count, otherwise, assume 1 and process it
  1183. var remainingData = this.extractFrameCount_(data);
  1184. if (remainingData !== null) {
  1185. this.appendFrame_(remainingData);
  1186. }
  1187. }
  1188. };
  1189. /**
  1190. * Send a message to the server
  1191. * @param data - The JSON object to transmit
  1192. */
  1193. WebSocketConnection.prototype.send = function (data) {
  1194. this.resetKeepAlive();
  1195. var dataStr = util.stringify(data);
  1196. this.bytesSent += dataStr.length;
  1197. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1198. //We can only fit a certain amount in each websocket frame, so we need to split this request
  1199. //up into multiple pieces if it doesn't fit in one request.
  1200. var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
  1201. //Send the length header
  1202. if (dataSegs.length > 1) {
  1203. this.sendString_(String(dataSegs.length));
  1204. }
  1205. //Send the actual data in segments.
  1206. for (var i = 0; i < dataSegs.length; i++) {
  1207. this.sendString_(dataSegs[i]);
  1208. }
  1209. };
  1210. WebSocketConnection.prototype.shutdown_ = function () {
  1211. this.isClosed_ = true;
  1212. if (this.keepaliveTimer) {
  1213. clearInterval(this.keepaliveTimer);
  1214. this.keepaliveTimer = null;
  1215. }
  1216. if (this.mySock) {
  1217. this.mySock.close();
  1218. this.mySock = null;
  1219. }
  1220. };
  1221. WebSocketConnection.prototype.onClosed_ = function () {
  1222. if (!this.isClosed_) {
  1223. this.log_('WebSocket is closing itself');
  1224. this.shutdown_();
  1225. // since this is an internal close, trigger the close listener
  1226. if (this.onDisconnect) {
  1227. this.onDisconnect(this.everConnected_);
  1228. this.onDisconnect = null;
  1229. }
  1230. }
  1231. };
  1232. /**
  1233. * External-facing close handler.
  1234. * Close the websocket and kill the connection.
  1235. */
  1236. WebSocketConnection.prototype.close = function () {
  1237. if (!this.isClosed_) {
  1238. this.log_('WebSocket is being closed');
  1239. this.shutdown_();
  1240. }
  1241. };
  1242. /**
  1243. * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
  1244. * the last activity.
  1245. */
  1246. WebSocketConnection.prototype.resetKeepAlive = function () {
  1247. var _this = this;
  1248. clearInterval(this.keepaliveTimer);
  1249. this.keepaliveTimer = setInterval(function () {
  1250. //If there has been no websocket activity for a while, send a no-op
  1251. if (_this.mySock) {
  1252. _this.sendString_('0');
  1253. }
  1254. _this.resetKeepAlive();
  1255. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1256. }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
  1257. };
  1258. /**
  1259. * Send a string over the websocket.
  1260. *
  1261. * @param str - String to send.
  1262. */
  1263. WebSocketConnection.prototype.sendString_ = function (str) {
  1264. // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()
  1265. // calls for some unknown reason. We treat these as an error and disconnect.
  1266. // See https://app.asana.com/0/58926111402292/68021340250410
  1267. try {
  1268. this.mySock.send(str);
  1269. }
  1270. catch (e) {
  1271. this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
  1272. setTimeout(this.onClosed_.bind(this), 0);
  1273. }
  1274. };
  1275. /**
  1276. * Number of response before we consider the connection "healthy."
  1277. */
  1278. WebSocketConnection.responsesRequiredToBeHealthy = 2;
  1279. /**
  1280. * Time to wait for the connection te become healthy before giving up.
  1281. */
  1282. WebSocketConnection.healthyTimeout = 30000;
  1283. return WebSocketConnection;
  1284. }());
  1285. var name = "@firebase/database";
  1286. var version = "0.14.1";
  1287. /**
  1288. * @license
  1289. * Copyright 2021 Google LLC
  1290. *
  1291. * Licensed under the Apache License, Version 2.0 (the "License");
  1292. * you may not use this file except in compliance with the License.
  1293. * You may obtain a copy of the License at
  1294. *
  1295. * http://www.apache.org/licenses/LICENSE-2.0
  1296. *
  1297. * Unless required by applicable law or agreed to in writing, software
  1298. * distributed under the License is distributed on an "AS IS" BASIS,
  1299. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1300. * See the License for the specific language governing permissions and
  1301. * limitations under the License.
  1302. */
  1303. /**
  1304. * Abstraction around AppCheck's token fetching capabilities.
  1305. */
  1306. var AppCheckTokenProvider = /** @class */ (function () {
  1307. function AppCheckTokenProvider(appName_, appCheckProvider) {
  1308. var _this = this;
  1309. this.appName_ = appName_;
  1310. this.appCheckProvider = appCheckProvider;
  1311. this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
  1312. if (!this.appCheck) {
  1313. appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); });
  1314. }
  1315. }
  1316. AppCheckTokenProvider.prototype.getToken = function (forceRefresh) {
  1317. var _this = this;
  1318. if (!this.appCheck) {
  1319. return new Promise(function (resolve, reject) {
  1320. // Support delayed initialization of FirebaseAppCheck. This allows our
  1321. // customers to initialize the RTDB SDK before initializing Firebase
  1322. // AppCheck and ensures that all requests are authenticated if a token
  1323. // becomes available before the timoeout below expires.
  1324. setTimeout(function () {
  1325. if (_this.appCheck) {
  1326. _this.getToken(forceRefresh).then(resolve, reject);
  1327. }
  1328. else {
  1329. resolve(null);
  1330. }
  1331. }, 0);
  1332. });
  1333. }
  1334. return this.appCheck.getToken(forceRefresh);
  1335. };
  1336. AppCheckTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1337. var _a;
  1338. (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(function (appCheck) { return appCheck.addTokenListener(listener); });
  1339. };
  1340. AppCheckTokenProvider.prototype.notifyForInvalidToken = function () {
  1341. warn("Provided AppCheck credentials for the app named \"".concat(this.appName_, "\" ") +
  1342. 'are invalid. This usually indicates your app was not initialized correctly.');
  1343. };
  1344. return AppCheckTokenProvider;
  1345. }());
  1346. /**
  1347. * @license
  1348. * Copyright 2017 Google LLC
  1349. *
  1350. * Licensed under the Apache License, Version 2.0 (the "License");
  1351. * you may not use this file except in compliance with the License.
  1352. * You may obtain a copy of the License at
  1353. *
  1354. * http://www.apache.org/licenses/LICENSE-2.0
  1355. *
  1356. * Unless required by applicable law or agreed to in writing, software
  1357. * distributed under the License is distributed on an "AS IS" BASIS,
  1358. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1359. * See the License for the specific language governing permissions and
  1360. * limitations under the License.
  1361. */
  1362. /**
  1363. * Abstraction around FirebaseApp's token fetching capabilities.
  1364. */
  1365. var FirebaseAuthTokenProvider = /** @class */ (function () {
  1366. function FirebaseAuthTokenProvider(appName_, firebaseOptions_, authProvider_) {
  1367. var _this = this;
  1368. this.appName_ = appName_;
  1369. this.firebaseOptions_ = firebaseOptions_;
  1370. this.authProvider_ = authProvider_;
  1371. this.auth_ = null;
  1372. this.auth_ = authProvider_.getImmediate({ optional: true });
  1373. if (!this.auth_) {
  1374. authProvider_.onInit(function (auth) { return (_this.auth_ = auth); });
  1375. }
  1376. }
  1377. FirebaseAuthTokenProvider.prototype.getToken = function (forceRefresh) {
  1378. var _this = this;
  1379. if (!this.auth_) {
  1380. return new Promise(function (resolve, reject) {
  1381. // Support delayed initialization of FirebaseAuth. This allows our
  1382. // customers to initialize the RTDB SDK before initializing Firebase
  1383. // Auth and ensures that all requests are authenticated if a token
  1384. // becomes available before the timoeout below expires.
  1385. setTimeout(function () {
  1386. if (_this.auth_) {
  1387. _this.getToken(forceRefresh).then(resolve, reject);
  1388. }
  1389. else {
  1390. resolve(null);
  1391. }
  1392. }, 0);
  1393. });
  1394. }
  1395. return this.auth_.getToken(forceRefresh).catch(function (error) {
  1396. // TODO: Need to figure out all the cases this is raised and whether
  1397. // this makes sense.
  1398. if (error && error.code === 'auth/token-not-initialized') {
  1399. log('Got auth/token-not-initialized error. Treating as null token.');
  1400. return null;
  1401. }
  1402. else {
  1403. return Promise.reject(error);
  1404. }
  1405. });
  1406. };
  1407. FirebaseAuthTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1408. // TODO: We might want to wrap the listener and call it with no args to
  1409. // avoid a leaky abstraction, but that makes removing the listener harder.
  1410. if (this.auth_) {
  1411. this.auth_.addAuthTokenListener(listener);
  1412. }
  1413. else {
  1414. this.authProvider_
  1415. .get()
  1416. .then(function (auth) { return auth.addAuthTokenListener(listener); });
  1417. }
  1418. };
  1419. FirebaseAuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {
  1420. this.authProvider_
  1421. .get()
  1422. .then(function (auth) { return auth.removeAuthTokenListener(listener); });
  1423. };
  1424. FirebaseAuthTokenProvider.prototype.notifyForInvalidToken = function () {
  1425. var errorMessage = 'Provided authentication credentials for the app named "' +
  1426. this.appName_ +
  1427. '" are invalid. This usually indicates your app was not ' +
  1428. 'initialized correctly. ';
  1429. if ('credential' in this.firebaseOptions_) {
  1430. errorMessage +=
  1431. 'Make sure the "credential" property provided to initializeApp() ' +
  1432. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1433. 'project.';
  1434. }
  1435. else if ('serviceAccount' in this.firebaseOptions_) {
  1436. errorMessage +=
  1437. 'Make sure the "serviceAccount" property provided to initializeApp() ' +
  1438. 'is authorized to access the specified "databaseURL" and is from the correct ' +
  1439. 'project.';
  1440. }
  1441. else {
  1442. errorMessage +=
  1443. 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
  1444. 'initializeApp() match the values provided for your app at ' +
  1445. 'https://console.firebase.google.com/.';
  1446. }
  1447. warn(errorMessage);
  1448. };
  1449. return FirebaseAuthTokenProvider;
  1450. }());
  1451. /* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */
  1452. var EmulatorTokenProvider = /** @class */ (function () {
  1453. function EmulatorTokenProvider(accessToken) {
  1454. this.accessToken = accessToken;
  1455. }
  1456. EmulatorTokenProvider.prototype.getToken = function (forceRefresh) {
  1457. return Promise.resolve({
  1458. accessToken: this.accessToken
  1459. });
  1460. };
  1461. EmulatorTokenProvider.prototype.addTokenChangeListener = function (listener) {
  1462. // Invoke the listener immediately to match the behavior in Firebase Auth
  1463. // (see packages/auth/src/auth.js#L1807)
  1464. listener(this.accessToken);
  1465. };
  1466. EmulatorTokenProvider.prototype.removeTokenChangeListener = function (listener) { };
  1467. EmulatorTokenProvider.prototype.notifyForInvalidToken = function () { };
  1468. /** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */
  1469. EmulatorTokenProvider.OWNER = 'owner';
  1470. return EmulatorTokenProvider;
  1471. }());
  1472. /**
  1473. * @license
  1474. * Copyright 2017 Google LLC
  1475. *
  1476. * Licensed under the Apache License, Version 2.0 (the "License");
  1477. * you may not use this file except in compliance with the License.
  1478. * You may obtain a copy of the License at
  1479. *
  1480. * http://www.apache.org/licenses/LICENSE-2.0
  1481. *
  1482. * Unless required by applicable law or agreed to in writing, software
  1483. * distributed under the License is distributed on an "AS IS" BASIS,
  1484. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1485. * See the License for the specific language governing permissions and
  1486. * limitations under the License.
  1487. */
  1488. /**
  1489. * This class ensures the packets from the server arrive in order
  1490. * This class takes data from the server and ensures it gets passed into the callbacks in order.
  1491. */
  1492. var PacketReceiver = /** @class */ (function () {
  1493. /**
  1494. * @param onMessage_
  1495. */
  1496. function PacketReceiver(onMessage_) {
  1497. this.onMessage_ = onMessage_;
  1498. this.pendingResponses = [];
  1499. this.currentResponseNum = 0;
  1500. this.closeAfterResponse = -1;
  1501. this.onClose = null;
  1502. }
  1503. PacketReceiver.prototype.closeAfter = function (responseNum, callback) {
  1504. this.closeAfterResponse = responseNum;
  1505. this.onClose = callback;
  1506. if (this.closeAfterResponse < this.currentResponseNum) {
  1507. this.onClose();
  1508. this.onClose = null;
  1509. }
  1510. };
  1511. /**
  1512. * Each message from the server comes with a response number, and an array of data. The responseNumber
  1513. * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
  1514. * browsers will respond in the same order as the requests we sent
  1515. */
  1516. PacketReceiver.prototype.handleResponse = function (requestNum, data) {
  1517. var _this = this;
  1518. this.pendingResponses[requestNum] = data;
  1519. var _loop_1 = function () {
  1520. var toProcess = this_1.pendingResponses[this_1.currentResponseNum];
  1521. delete this_1.pendingResponses[this_1.currentResponseNum];
  1522. var _loop_2 = function (i) {
  1523. if (toProcess[i]) {
  1524. exceptionGuard(function () {
  1525. _this.onMessage_(toProcess[i]);
  1526. });
  1527. }
  1528. };
  1529. for (var i = 0; i < toProcess.length; ++i) {
  1530. _loop_2(i);
  1531. }
  1532. if (this_1.currentResponseNum === this_1.closeAfterResponse) {
  1533. if (this_1.onClose) {
  1534. this_1.onClose();
  1535. this_1.onClose = null;
  1536. }
  1537. return "break";
  1538. }
  1539. this_1.currentResponseNum++;
  1540. };
  1541. var this_1 = this;
  1542. while (this.pendingResponses[this.currentResponseNum]) {
  1543. var state_1 = _loop_1();
  1544. if (state_1 === "break")
  1545. break;
  1546. }
  1547. };
  1548. return PacketReceiver;
  1549. }());
  1550. /**
  1551. * @license
  1552. * Copyright 2017 Google LLC
  1553. *
  1554. * Licensed under the Apache License, Version 2.0 (the "License");
  1555. * you may not use this file except in compliance with the License.
  1556. * You may obtain a copy of the License at
  1557. *
  1558. * http://www.apache.org/licenses/LICENSE-2.0
  1559. *
  1560. * Unless required by applicable law or agreed to in writing, software
  1561. * distributed under the License is distributed on an "AS IS" BASIS,
  1562. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1563. * See the License for the specific language governing permissions and
  1564. * limitations under the License.
  1565. */
  1566. // URL query parameters associated with longpolling
  1567. var FIREBASE_LONGPOLL_START_PARAM = 'start';
  1568. var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
  1569. var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
  1570. var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
  1571. var FIREBASE_LONGPOLL_ID_PARAM = 'id';
  1572. var FIREBASE_LONGPOLL_PW_PARAM = 'pw';
  1573. var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
  1574. var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
  1575. var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
  1576. var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
  1577. var FIREBASE_LONGPOLL_DATA_PARAM = 'd';
  1578. var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
  1579. //Data size constants.
  1580. //TODO: Perf: the maximum length actually differs from browser to browser.
  1581. // We should check what browser we're on and set accordingly.
  1582. var MAX_URL_DATA_SIZE = 1870;
  1583. var SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=
  1584. var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  1585. /**
  1586. * Keepalive period
  1587. * send a fresh request at minimum every 25 seconds. Opera has a maximum request
  1588. * length of 30 seconds that we can't exceed.
  1589. */
  1590. var KEEPALIVE_REQUEST_INTERVAL = 25000;
  1591. /**
  1592. * How long to wait before aborting a long-polling connection attempt.
  1593. */
  1594. var LP_CONNECT_TIMEOUT = 30000;
  1595. /**
  1596. * This class manages a single long-polling connection.
  1597. */
  1598. var BrowserPollConnection = /** @class */ (function () {
  1599. /**
  1600. * @param connId An identifier for this connection, used for logging
  1601. * @param repoInfo The info for the endpoint to send data to.
  1602. * @param applicationId The Firebase App ID for this project.
  1603. * @param appCheckToken The AppCheck token for this client.
  1604. * @param authToken The AuthToken to use for this connection.
  1605. * @param transportSessionId Optional transportSessionid if we are
  1606. * reconnecting for an existing transport session
  1607. * @param lastSessionId Optional lastSessionId if the PersistentConnection has
  1608. * already created a connection previously
  1609. */
  1610. function BrowserPollConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
  1611. var _this = this;
  1612. this.connId = connId;
  1613. this.repoInfo = repoInfo;
  1614. this.applicationId = applicationId;
  1615. this.appCheckToken = appCheckToken;
  1616. this.authToken = authToken;
  1617. this.transportSessionId = transportSessionId;
  1618. this.lastSessionId = lastSessionId;
  1619. this.bytesSent = 0;
  1620. this.bytesReceived = 0;
  1621. this.everConnected_ = false;
  1622. this.log_ = logWrapper(connId);
  1623. this.stats_ = statsManagerGetCollection(repoInfo);
  1624. this.urlFn = function (params) {
  1625. // Always add the token if we have one.
  1626. if (_this.appCheckToken) {
  1627. params[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1628. }
  1629. return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
  1630. };
  1631. }
  1632. /**
  1633. * @param onMessage - Callback when messages arrive
  1634. * @param onDisconnect - Callback with connection lost.
  1635. */
  1636. BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {
  1637. var _this = this;
  1638. this.curSegmentNum = 0;
  1639. this.onDisconnect_ = onDisconnect;
  1640. this.myPacketOrderer = new PacketReceiver(onMessage);
  1641. this.isClosed_ = false;
  1642. this.connectTimeoutTimer_ = setTimeout(function () {
  1643. _this.log_('Timed out trying to connect.');
  1644. // Make sure we clear the host cache
  1645. _this.onClosed_();
  1646. _this.connectTimeoutTimer_ = null;
  1647. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1648. }, Math.floor(LP_CONNECT_TIMEOUT));
  1649. // Ensure we delay the creation of the iframe until the DOM is loaded.
  1650. executeWhenDOMReady(function () {
  1651. if (_this.isClosed_) {
  1652. return;
  1653. }
  1654. //Set up a callback that gets triggered once a connection is set up.
  1655. _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {
  1656. var args = [];
  1657. for (var _i = 0; _i < arguments.length; _i++) {
  1658. args[_i] = arguments[_i];
  1659. }
  1660. var _a = tslib.__read(args, 5), command = _a[0], arg1 = _a[1], arg2 = _a[2]; _a[3]; _a[4];
  1661. _this.incrementIncomingBytes_(args);
  1662. if (!_this.scriptTagHolder) {
  1663. return; // we closed the connection.
  1664. }
  1665. if (_this.connectTimeoutTimer_) {
  1666. clearTimeout(_this.connectTimeoutTimer_);
  1667. _this.connectTimeoutTimer_ = null;
  1668. }
  1669. _this.everConnected_ = true;
  1670. if (command === FIREBASE_LONGPOLL_START_PARAM) {
  1671. _this.id = arg1;
  1672. _this.password = arg2;
  1673. }
  1674. else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
  1675. // Don't clear the host cache. We got a response from the server, so we know it's reachable
  1676. if (arg1) {
  1677. // We aren't expecting any more data (other than what the server's already in the process of sending us
  1678. // through our already open polls), so don't send any more.
  1679. _this.scriptTagHolder.sendNewPolls = false;
  1680. // arg1 in this case is the last response number sent by the server. We should try to receive
  1681. // all of the responses up to this one before closing
  1682. _this.myPacketOrderer.closeAfter(arg1, function () {
  1683. _this.onClosed_();
  1684. });
  1685. }
  1686. else {
  1687. _this.onClosed_();
  1688. }
  1689. }
  1690. else {
  1691. throw new Error('Unrecognized command received: ' + command);
  1692. }
  1693. }, function () {
  1694. var args = [];
  1695. for (var _i = 0; _i < arguments.length; _i++) {
  1696. args[_i] = arguments[_i];
  1697. }
  1698. var _a = tslib.__read(args, 2), pN = _a[0], data = _a[1];
  1699. _this.incrementIncomingBytes_(args);
  1700. _this.myPacketOrderer.handleResponse(pN, data);
  1701. }, function () {
  1702. _this.onClosed_();
  1703. }, _this.urlFn);
  1704. //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results
  1705. //from cache.
  1706. var urlParams = {};
  1707. urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
  1708. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
  1709. if (_this.scriptTagHolder.uniqueCallbackIdentifier) {
  1710. urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
  1711. _this.scriptTagHolder.uniqueCallbackIdentifier;
  1712. }
  1713. urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
  1714. if (_this.transportSessionId) {
  1715. urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId;
  1716. }
  1717. if (_this.lastSessionId) {
  1718. urlParams[LAST_SESSION_PARAM] = _this.lastSessionId;
  1719. }
  1720. if (_this.applicationId) {
  1721. urlParams[APPLICATION_ID_PARAM] = _this.applicationId;
  1722. }
  1723. if (_this.appCheckToken) {
  1724. urlParams[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
  1725. }
  1726. if (typeof location !== 'undefined' &&
  1727. location.hostname &&
  1728. FORGE_DOMAIN_RE.test(location.hostname)) {
  1729. urlParams[REFERER_PARAM] = FORGE_REF;
  1730. }
  1731. var connectURL = _this.urlFn(urlParams);
  1732. _this.log_('Connecting via long-poll to ' + connectURL);
  1733. _this.scriptTagHolder.addTag(connectURL, function () {
  1734. /* do nothing */
  1735. });
  1736. });
  1737. };
  1738. /**
  1739. * Call this when a handshake has completed successfully and we want to consider the connection established
  1740. */
  1741. BrowserPollConnection.prototype.start = function () {
  1742. this.scriptTagHolder.startLongPoll(this.id, this.password);
  1743. this.addDisconnectPingFrame(this.id, this.password);
  1744. };
  1745. /**
  1746. * Forces long polling to be considered as a potential transport
  1747. */
  1748. BrowserPollConnection.forceAllow = function () {
  1749. BrowserPollConnection.forceAllow_ = true;
  1750. };
  1751. /**
  1752. * Forces longpolling to not be considered as a potential transport
  1753. */
  1754. BrowserPollConnection.forceDisallow = function () {
  1755. BrowserPollConnection.forceDisallow_ = true;
  1756. };
  1757. // Static method, use string literal so it can be accessed in a generic way
  1758. BrowserPollConnection.isAvailable = function () {
  1759. if (util.isNodeSdk()) {
  1760. return false;
  1761. }
  1762. else if (BrowserPollConnection.forceAllow_) {
  1763. return true;
  1764. }
  1765. else {
  1766. // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in
  1767. // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).
  1768. return (!BrowserPollConnection.forceDisallow_ &&
  1769. typeof document !== 'undefined' &&
  1770. document.createElement != null &&
  1771. !isChromeExtensionContentScript() &&
  1772. !isWindowsStoreApp());
  1773. }
  1774. };
  1775. /**
  1776. * No-op for polling
  1777. */
  1778. BrowserPollConnection.prototype.markConnectionHealthy = function () { };
  1779. /**
  1780. * Stops polling and cleans up the iframe
  1781. */
  1782. BrowserPollConnection.prototype.shutdown_ = function () {
  1783. this.isClosed_ = true;
  1784. if (this.scriptTagHolder) {
  1785. this.scriptTagHolder.close();
  1786. this.scriptTagHolder = null;
  1787. }
  1788. //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.
  1789. if (this.myDisconnFrame) {
  1790. document.body.removeChild(this.myDisconnFrame);
  1791. this.myDisconnFrame = null;
  1792. }
  1793. if (this.connectTimeoutTimer_) {
  1794. clearTimeout(this.connectTimeoutTimer_);
  1795. this.connectTimeoutTimer_ = null;
  1796. }
  1797. };
  1798. /**
  1799. * Triggered when this transport is closed
  1800. */
  1801. BrowserPollConnection.prototype.onClosed_ = function () {
  1802. if (!this.isClosed_) {
  1803. this.log_('Longpoll is closing itself');
  1804. this.shutdown_();
  1805. if (this.onDisconnect_) {
  1806. this.onDisconnect_(this.everConnected_);
  1807. this.onDisconnect_ = null;
  1808. }
  1809. }
  1810. };
  1811. /**
  1812. * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
  1813. * that we've left.
  1814. */
  1815. BrowserPollConnection.prototype.close = function () {
  1816. if (!this.isClosed_) {
  1817. this.log_('Longpoll is being closed.');
  1818. this.shutdown_();
  1819. }
  1820. };
  1821. /**
  1822. * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
  1823. * broken into chunks (since URLs have a small maximum length).
  1824. * @param data - The JSON data to transmit.
  1825. */
  1826. BrowserPollConnection.prototype.send = function (data) {
  1827. var dataStr = util.stringify(data);
  1828. this.bytesSent += dataStr.length;
  1829. this.stats_.incrementCounter('bytes_sent', dataStr.length);
  1830. //first, lets get the base64-encoded data
  1831. var base64data = util.base64Encode(dataStr);
  1832. //We can only fit a certain amount in each URL, so we need to split this request
  1833. //up into multiple pieces if it doesn't fit in one request.
  1834. var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
  1835. //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number
  1836. //of segments so that we can reassemble the packet on the server.
  1837. for (var i = 0; i < dataSegs.length; i++) {
  1838. this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
  1839. this.curSegmentNum++;
  1840. }
  1841. };
  1842. /**
  1843. * This is how we notify the server that we're leaving.
  1844. * We aren't able to send requests with DHTML on a window close event, but we can
  1845. * trigger XHR requests in some browsers (everything but Opera basically).
  1846. */
  1847. BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {
  1848. if (util.isNodeSdk()) {
  1849. return;
  1850. }
  1851. this.myDisconnFrame = document.createElement('iframe');
  1852. var urlParams = {};
  1853. urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
  1854. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
  1855. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
  1856. this.myDisconnFrame.src = this.urlFn(urlParams);
  1857. this.myDisconnFrame.style.display = 'none';
  1858. document.body.appendChild(this.myDisconnFrame);
  1859. };
  1860. /**
  1861. * Used to track the bytes received by this client
  1862. */
  1863. BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {
  1864. // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.
  1865. var bytesReceived = util.stringify(args).length;
  1866. this.bytesReceived += bytesReceived;
  1867. this.stats_.incrementCounter('bytes_received', bytesReceived);
  1868. };
  1869. return BrowserPollConnection;
  1870. }());
  1871. /*********************************************************************************************
  1872. * A wrapper around an iframe that is used as a long-polling script holder.
  1873. *********************************************************************************************/
  1874. var FirebaseIFrameScriptHolder = /** @class */ (function () {
  1875. /**
  1876. * @param commandCB - The callback to be called when control commands are recevied from the server.
  1877. * @param onMessageCB - The callback to be triggered when responses arrive from the server.
  1878. * @param onDisconnect - The callback to be triggered when this tag holder is closed
  1879. * @param urlFn - A function that provides the URL of the endpoint to send data to.
  1880. */
  1881. function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {
  1882. this.onDisconnect = onDisconnect;
  1883. this.urlFn = urlFn;
  1884. //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause
  1885. //problems in some browsers.
  1886. this.outstandingRequests = new Set();
  1887. //A queue of the pending segments waiting for transmission to the server.
  1888. this.pendingSegs = [];
  1889. //A serial number. We use this for two things:
  1890. // 1) A way to ensure the browser doesn't cache responses to polls
  1891. // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The
  1892. // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute
  1893. // JSONP code in the order it was added to the iframe.
  1894. this.currentSerial = Math.floor(Math.random() * 100000000);
  1895. // This gets set to false when we're "closing down" the connection (e.g. we're switching transports but there's still
  1896. // incoming data from the server that we're waiting for).
  1897. this.sendNewPolls = true;
  1898. if (!util.isNodeSdk()) {
  1899. //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the
  1900. //iframes where we put the long-polling script tags. We have two callbacks:
  1901. // 1) Command Callback - Triggered for control issues, like starting a connection.
  1902. // 2) Message Callback - Triggered when new data arrives.
  1903. this.uniqueCallbackIdentifier = LUIDGenerator();
  1904. window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
  1905. window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
  1906. onMessageCB;
  1907. //Create an iframe for us to add script tags to.
  1908. this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
  1909. // Set the iframe's contents.
  1910. var script = '';
  1911. // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient
  1912. // for ie9, but ie8 needs to do it again in the document itself.
  1913. if (this.myIFrame.src &&
  1914. this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
  1915. var currentDomain = document.domain;
  1916. script = '<script>document.domain="' + currentDomain + '";</script>';
  1917. }
  1918. var iframeContents = '<html><body>' + script + '</body></html>';
  1919. try {
  1920. this.myIFrame.doc.open();
  1921. this.myIFrame.doc.write(iframeContents);
  1922. this.myIFrame.doc.close();
  1923. }
  1924. catch (e) {
  1925. log('frame writing exception');
  1926. if (e.stack) {
  1927. log(e.stack);
  1928. }
  1929. log(e);
  1930. }
  1931. }
  1932. else {
  1933. this.commandCB = commandCB;
  1934. this.onMessageCB = onMessageCB;
  1935. }
  1936. }
  1937. /**
  1938. * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
  1939. * actually use.
  1940. */
  1941. FirebaseIFrameScriptHolder.createIFrame_ = function () {
  1942. var iframe = document.createElement('iframe');
  1943. iframe.style.display = 'none';
  1944. // This is necessary in order to initialize the document inside the iframe
  1945. if (document.body) {
  1946. document.body.appendChild(iframe);
  1947. try {
  1948. // If document.domain has been modified in IE, this will throw an error, and we need to set the
  1949. // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute
  1950. // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.
  1951. var a = iframe.contentWindow.document;
  1952. if (!a) {
  1953. // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.
  1954. log('No IE domain setting required');
  1955. }
  1956. }
  1957. catch (e) {
  1958. var domain = document.domain;
  1959. iframe.src =
  1960. "javascript:void((function(){document.open();document.domain='" +
  1961. domain +
  1962. "';document.close();})())";
  1963. }
  1964. }
  1965. else {
  1966. // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this
  1967. // never gets hit.
  1968. throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
  1969. }
  1970. // Get the document of the iframe in a browser-specific way.
  1971. if (iframe.contentDocument) {
  1972. iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari
  1973. }
  1974. else if (iframe.contentWindow) {
  1975. iframe.doc = iframe.contentWindow.document; // Internet Explorer
  1976. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1977. }
  1978. else if (iframe.document) {
  1979. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1980. iframe.doc = iframe.document; //others?
  1981. }
  1982. return iframe;
  1983. };
  1984. /**
  1985. * Cancel all outstanding queries and remove the frame.
  1986. */
  1987. FirebaseIFrameScriptHolder.prototype.close = function () {
  1988. var _this = this;
  1989. //Mark this iframe as dead, so no new requests are sent.
  1990. this.alive = false;
  1991. if (this.myIFrame) {
  1992. //We have to actually remove all of the html inside this iframe before removing it from the
  1993. //window, or IE will continue loading and executing the script tags we've already added, which
  1994. //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.
  1995. this.myIFrame.doc.body.textContent = '';
  1996. setTimeout(function () {
  1997. if (_this.myIFrame !== null) {
  1998. document.body.removeChild(_this.myIFrame);
  1999. _this.myIFrame = null;
  2000. }
  2001. }, Math.floor(0));
  2002. }
  2003. // Protect from being called recursively.
  2004. var onDisconnect = this.onDisconnect;
  2005. if (onDisconnect) {
  2006. this.onDisconnect = null;
  2007. onDisconnect();
  2008. }
  2009. };
  2010. /**
  2011. * Actually start the long-polling session by adding the first script tag(s) to the iframe.
  2012. * @param id - The ID of this connection
  2013. * @param pw - The password for this connection
  2014. */
  2015. FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {
  2016. this.myID = id;
  2017. this.myPW = pw;
  2018. this.alive = true;
  2019. //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.
  2020. while (this.newRequest_()) { }
  2021. };
  2022. /**
  2023. * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
  2024. * too many outstanding requests and we are still alive.
  2025. *
  2026. * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
  2027. * needed.
  2028. */
  2029. FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {
  2030. // We keep one outstanding request open all the time to receive data, but if we need to send data
  2031. // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically
  2032. // close the old request.
  2033. if (this.alive &&
  2034. this.sendNewPolls &&
  2035. this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
  2036. //construct our url
  2037. this.currentSerial++;
  2038. var urlParams = {};
  2039. urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
  2040. urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
  2041. urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
  2042. var theURL = this.urlFn(urlParams);
  2043. //Now add as much data as we can.
  2044. var curDataString = '';
  2045. var i = 0;
  2046. while (this.pendingSegs.length > 0) {
  2047. //first, lets see if the next segment will fit.
  2048. var nextSeg = this.pendingSegs[0];
  2049. if (nextSeg.d.length +
  2050. SEG_HEADER_SIZE +
  2051. curDataString.length <=
  2052. MAX_URL_DATA_SIZE) {
  2053. //great, the segment will fit. Lets append it.
  2054. var theSeg = this.pendingSegs.shift();
  2055. curDataString =
  2056. curDataString +
  2057. '&' +
  2058. FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
  2059. i +
  2060. '=' +
  2061. theSeg.seg +
  2062. '&' +
  2063. FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
  2064. i +
  2065. '=' +
  2066. theSeg.ts +
  2067. '&' +
  2068. FIREBASE_LONGPOLL_DATA_PARAM +
  2069. i +
  2070. '=' +
  2071. theSeg.d;
  2072. i++;
  2073. }
  2074. else {
  2075. break;
  2076. }
  2077. }
  2078. theURL = theURL + curDataString;
  2079. this.addLongPollTag_(theURL, this.currentSerial);
  2080. return true;
  2081. }
  2082. else {
  2083. return false;
  2084. }
  2085. };
  2086. /**
  2087. * Queue a packet for transmission to the server.
  2088. * @param segnum - A sequential id for this packet segment used for reassembly
  2089. * @param totalsegs - The total number of segments in this packet
  2090. * @param data - The data for this segment.
  2091. */
  2092. FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {
  2093. //add this to the queue of segments to send.
  2094. this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
  2095. //send the data immediately if there isn't already data being transmitted, unless
  2096. //startLongPoll hasn't been called yet.
  2097. if (this.alive) {
  2098. this.newRequest_();
  2099. }
  2100. };
  2101. /**
  2102. * Add a script tag for a regular long-poll request.
  2103. * @param url - The URL of the script tag.
  2104. * @param serial - The serial number of the request.
  2105. */
  2106. FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {
  2107. var _this = this;
  2108. //remember that we sent this request.
  2109. this.outstandingRequests.add(serial);
  2110. var doNewRequest = function () {
  2111. _this.outstandingRequests.delete(serial);
  2112. _this.newRequest_();
  2113. };
  2114. // If this request doesn't return on its own accord (by the server sending us some data), we'll
  2115. // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.
  2116. var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
  2117. var readyStateCB = function () {
  2118. // Request completed. Cancel the keepalive.
  2119. clearTimeout(keepaliveTimeout);
  2120. // Trigger a new request so we can continue receiving data.
  2121. doNewRequest();
  2122. };
  2123. this.addTag(url, readyStateCB);
  2124. };
  2125. /**
  2126. * Add an arbitrary script tag to the iframe.
  2127. * @param url - The URL for the script tag source.
  2128. * @param loadCB - A callback to be triggered once the script has loaded.
  2129. */
  2130. FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {
  2131. var _this = this;
  2132. if (util.isNodeSdk()) {
  2133. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2134. this.doNodeLongPoll(url, loadCB);
  2135. }
  2136. else {
  2137. setTimeout(function () {
  2138. try {
  2139. // if we're already closed, don't add this poll
  2140. if (!_this.sendNewPolls) {
  2141. return;
  2142. }
  2143. var newScript_1 = _this.myIFrame.doc.createElement('script');
  2144. newScript_1.type = 'text/javascript';
  2145. newScript_1.async = true;
  2146. newScript_1.src = url;
  2147. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2148. newScript_1.onload = newScript_1.onreadystatechange =
  2149. function () {
  2150. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2151. var rstate = newScript_1.readyState;
  2152. if (!rstate || rstate === 'loaded' || rstate === 'complete') {
  2153. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2154. newScript_1.onload = newScript_1.onreadystatechange = null;
  2155. if (newScript_1.parentNode) {
  2156. newScript_1.parentNode.removeChild(newScript_1);
  2157. }
  2158. loadCB();
  2159. }
  2160. };
  2161. newScript_1.onerror = function () {
  2162. log('Long-poll script failed to load: ' + url);
  2163. _this.sendNewPolls = false;
  2164. _this.close();
  2165. };
  2166. _this.myIFrame.doc.body.appendChild(newScript_1);
  2167. }
  2168. catch (e) {
  2169. // TODO: we should make this error visible somehow
  2170. }
  2171. }, Math.floor(1));
  2172. }
  2173. };
  2174. return FirebaseIFrameScriptHolder;
  2175. }());
  2176. /**
  2177. * @license
  2178. * Copyright 2017 Google LLC
  2179. *
  2180. * Licensed under the Apache License, Version 2.0 (the "License");
  2181. * you may not use this file except in compliance with the License.
  2182. * You may obtain a copy of the License at
  2183. *
  2184. * http://www.apache.org/licenses/LICENSE-2.0
  2185. *
  2186. * Unless required by applicable law or agreed to in writing, software
  2187. * distributed under the License is distributed on an "AS IS" BASIS,
  2188. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2189. * See the License for the specific language governing permissions and
  2190. * limitations under the License.
  2191. */
  2192. /**
  2193. * Currently simplistic, this class manages what transport a Connection should use at various stages of its
  2194. * lifecycle.
  2195. *
  2196. * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if
  2197. * they are available.
  2198. */
  2199. var TransportManager = /** @class */ (function () {
  2200. /**
  2201. * @param repoInfo - Metadata around the namespace we're connecting to
  2202. */
  2203. function TransportManager(repoInfo) {
  2204. this.initTransports_(repoInfo);
  2205. }
  2206. Object.defineProperty(TransportManager, "ALL_TRANSPORTS", {
  2207. get: function () {
  2208. return [BrowserPollConnection, WebSocketConnection];
  2209. },
  2210. enumerable: false,
  2211. configurable: true
  2212. });
  2213. Object.defineProperty(TransportManager, "IS_TRANSPORT_INITIALIZED", {
  2214. /**
  2215. * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
  2216. * TransportManager has already set up transports_
  2217. */
  2218. get: function () {
  2219. return this.globalTransportInitialized_;
  2220. },
  2221. enumerable: false,
  2222. configurable: true
  2223. });
  2224. TransportManager.prototype.initTransports_ = function (repoInfo) {
  2225. var e_1, _a;
  2226. var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
  2227. var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
  2228. if (repoInfo.webSocketOnly) {
  2229. if (!isWebSocketsAvailable) {
  2230. warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
  2231. }
  2232. isSkipPollConnection = true;
  2233. }
  2234. if (isSkipPollConnection) {
  2235. this.transports_ = [WebSocketConnection];
  2236. }
  2237. else {
  2238. var transports = (this.transports_ = []);
  2239. try {
  2240. for (var _b = tslib.__values(TransportManager.ALL_TRANSPORTS), _c = _b.next(); !_c.done; _c = _b.next()) {
  2241. var transport = _c.value;
  2242. if (transport && transport['isAvailable']()) {
  2243. transports.push(transport);
  2244. }
  2245. }
  2246. }
  2247. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  2248. finally {
  2249. try {
  2250. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  2251. }
  2252. finally { if (e_1) throw e_1.error; }
  2253. }
  2254. TransportManager.globalTransportInitialized_ = true;
  2255. }
  2256. };
  2257. /**
  2258. * @returns The constructor for the initial transport to use
  2259. */
  2260. TransportManager.prototype.initialTransport = function () {
  2261. if (this.transports_.length > 0) {
  2262. return this.transports_[0];
  2263. }
  2264. else {
  2265. throw new Error('No transports available');
  2266. }
  2267. };
  2268. /**
  2269. * @returns The constructor for the next transport, or null
  2270. */
  2271. TransportManager.prototype.upgradeTransport = function () {
  2272. if (this.transports_.length > 1) {
  2273. return this.transports_[1];
  2274. }
  2275. else {
  2276. return null;
  2277. }
  2278. };
  2279. // Keeps track of whether the TransportManager has already chosen a transport to use
  2280. TransportManager.globalTransportInitialized_ = false;
  2281. return TransportManager;
  2282. }());
  2283. /**
  2284. * @license
  2285. * Copyright 2017 Google LLC
  2286. *
  2287. * Licensed under the Apache License, Version 2.0 (the "License");
  2288. * you may not use this file except in compliance with the License.
  2289. * You may obtain a copy of the License at
  2290. *
  2291. * http://www.apache.org/licenses/LICENSE-2.0
  2292. *
  2293. * Unless required by applicable law or agreed to in writing, software
  2294. * distributed under the License is distributed on an "AS IS" BASIS,
  2295. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2296. * See the License for the specific language governing permissions and
  2297. * limitations under the License.
  2298. */
  2299. // Abort upgrade attempt if it takes longer than 60s.
  2300. var UPGRADE_TIMEOUT = 60000;
  2301. // For some transports (WebSockets), we need to "validate" the transport by exchanging a few requests and responses.
  2302. // If we haven't sent enough requests within 5s, we'll start sending noop ping requests.
  2303. var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
  2304. // If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)
  2305. // then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout
  2306. // but we've sent/received enough bytes, we don't cancel the connection.
  2307. var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  2308. var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  2309. var MESSAGE_TYPE = 't';
  2310. var MESSAGE_DATA = 'd';
  2311. var CONTROL_SHUTDOWN = 's';
  2312. var CONTROL_RESET = 'r';
  2313. var CONTROL_ERROR = 'e';
  2314. var CONTROL_PONG = 'o';
  2315. var SWITCH_ACK = 'a';
  2316. var END_TRANSMISSION = 'n';
  2317. var PING = 'p';
  2318. var SERVER_HELLO = 'h';
  2319. /**
  2320. * Creates a new real-time connection to the server using whichever method works
  2321. * best in the current browser.
  2322. */
  2323. var Connection = /** @class */ (function () {
  2324. /**
  2325. * @param id - an id for this connection
  2326. * @param repoInfo_ - the info for the endpoint to connect to
  2327. * @param applicationId_ - the Firebase App ID for this project
  2328. * @param appCheckToken_ - The App Check Token for this device.
  2329. * @param authToken_ - The auth token for this session.
  2330. * @param onMessage_ - the callback to be triggered when a server-push message arrives
  2331. * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
  2332. * @param onDisconnect_ - the callback to be triggered when a connection was lost
  2333. * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
  2334. * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
  2335. */
  2336. function Connection(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
  2337. this.id = id;
  2338. this.repoInfo_ = repoInfo_;
  2339. this.applicationId_ = applicationId_;
  2340. this.appCheckToken_ = appCheckToken_;
  2341. this.authToken_ = authToken_;
  2342. this.onMessage_ = onMessage_;
  2343. this.onReady_ = onReady_;
  2344. this.onDisconnect_ = onDisconnect_;
  2345. this.onKill_ = onKill_;
  2346. this.lastSessionId = lastSessionId;
  2347. this.connectionCount = 0;
  2348. this.pendingDataMessages = [];
  2349. this.state_ = 0 /* RealtimeState.CONNECTING */;
  2350. this.log_ = logWrapper('c:' + this.id + ':');
  2351. this.transportManager_ = new TransportManager(repoInfo_);
  2352. this.log_('Connection created');
  2353. this.start_();
  2354. }
  2355. /**
  2356. * Starts a connection attempt
  2357. */
  2358. Connection.prototype.start_ = function () {
  2359. var _this = this;
  2360. var conn = this.transportManager_.initialTransport();
  2361. this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
  2362. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2363. // can consider the transport healthy.
  2364. this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
  2365. var onMessageReceived = this.connReceiver_(this.conn_);
  2366. var onConnectionLost = this.disconnReceiver_(this.conn_);
  2367. this.tx_ = this.conn_;
  2368. this.rx_ = this.conn_;
  2369. this.secondaryConn_ = null;
  2370. this.isHealthy_ = false;
  2371. /*
  2372. * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.
  2373. * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.
  2374. * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should
  2375. * still have the context of your originating frame.
  2376. */
  2377. setTimeout(function () {
  2378. // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it
  2379. _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);
  2380. }, Math.floor(0));
  2381. var healthyTimeoutMS = conn['healthyTimeout'] || 0;
  2382. if (healthyTimeoutMS > 0) {
  2383. this.healthyTimeout_ = setTimeoutNonBlocking(function () {
  2384. _this.healthyTimeout_ = null;
  2385. if (!_this.isHealthy_) {
  2386. if (_this.conn_ &&
  2387. _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
  2388. _this.log_('Connection exceeded healthy timeout but has received ' +
  2389. _this.conn_.bytesReceived +
  2390. ' bytes. Marking connection healthy.');
  2391. _this.isHealthy_ = true;
  2392. _this.conn_.markConnectionHealthy();
  2393. }
  2394. else if (_this.conn_ &&
  2395. _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
  2396. _this.log_('Connection exceeded healthy timeout but has sent ' +
  2397. _this.conn_.bytesSent +
  2398. ' bytes. Leaving connection alive.');
  2399. // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to
  2400. // the server.
  2401. }
  2402. else {
  2403. _this.log_('Closing unhealthy connection after timeout.');
  2404. _this.close();
  2405. }
  2406. }
  2407. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  2408. }, Math.floor(healthyTimeoutMS));
  2409. }
  2410. };
  2411. Connection.prototype.nextTransportId_ = function () {
  2412. return 'c:' + this.id + ':' + this.connectionCount++;
  2413. };
  2414. Connection.prototype.disconnReceiver_ = function (conn) {
  2415. var _this = this;
  2416. return function (everConnected) {
  2417. if (conn === _this.conn_) {
  2418. _this.onConnectionLost_(everConnected);
  2419. }
  2420. else if (conn === _this.secondaryConn_) {
  2421. _this.log_('Secondary connection lost.');
  2422. _this.onSecondaryConnectionLost_();
  2423. }
  2424. else {
  2425. _this.log_('closing an old connection');
  2426. }
  2427. };
  2428. };
  2429. Connection.prototype.connReceiver_ = function (conn) {
  2430. var _this = this;
  2431. return function (message) {
  2432. if (_this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2433. if (conn === _this.rx_) {
  2434. _this.onPrimaryMessageReceived_(message);
  2435. }
  2436. else if (conn === _this.secondaryConn_) {
  2437. _this.onSecondaryMessageReceived_(message);
  2438. }
  2439. else {
  2440. _this.log_('message on old connection');
  2441. }
  2442. }
  2443. };
  2444. };
  2445. /**
  2446. * @param dataMsg - An arbitrary data message to be sent to the server
  2447. */
  2448. Connection.prototype.sendRequest = function (dataMsg) {
  2449. // wrap in a data message envelope and send it on
  2450. var msg = { t: 'd', d: dataMsg };
  2451. this.sendData_(msg);
  2452. };
  2453. Connection.prototype.tryCleanupConnection = function () {
  2454. if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
  2455. this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
  2456. this.conn_ = this.secondaryConn_;
  2457. this.secondaryConn_ = null;
  2458. // the server will shutdown the old connection
  2459. }
  2460. };
  2461. Connection.prototype.onSecondaryControl_ = function (controlData) {
  2462. if (MESSAGE_TYPE in controlData) {
  2463. var cmd = controlData[MESSAGE_TYPE];
  2464. if (cmd === SWITCH_ACK) {
  2465. this.upgradeIfSecondaryHealthy_();
  2466. }
  2467. else if (cmd === CONTROL_RESET) {
  2468. // Most likely the session wasn't valid. Abandon the switch attempt
  2469. this.log_('Got a reset on secondary, closing it');
  2470. this.secondaryConn_.close();
  2471. // If we were already using this connection for something, than we need to fully close
  2472. if (this.tx_ === this.secondaryConn_ ||
  2473. this.rx_ === this.secondaryConn_) {
  2474. this.close();
  2475. }
  2476. }
  2477. else if (cmd === CONTROL_PONG) {
  2478. this.log_('got pong on secondary.');
  2479. this.secondaryResponsesRequired_--;
  2480. this.upgradeIfSecondaryHealthy_();
  2481. }
  2482. }
  2483. };
  2484. Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {
  2485. var layer = requireKey('t', parsedData);
  2486. var data = requireKey('d', parsedData);
  2487. if (layer === 'c') {
  2488. this.onSecondaryControl_(data);
  2489. }
  2490. else if (layer === 'd') {
  2491. // got a data message, but we're still second connection. Need to buffer it up
  2492. this.pendingDataMessages.push(data);
  2493. }
  2494. else {
  2495. throw new Error('Unknown protocol layer: ' + layer);
  2496. }
  2497. };
  2498. Connection.prototype.upgradeIfSecondaryHealthy_ = function () {
  2499. if (this.secondaryResponsesRequired_ <= 0) {
  2500. this.log_('Secondary connection is healthy.');
  2501. this.isHealthy_ = true;
  2502. this.secondaryConn_.markConnectionHealthy();
  2503. this.proceedWithUpgrade_();
  2504. }
  2505. else {
  2506. // Send a ping to make sure the connection is healthy.
  2507. this.log_('sending ping on secondary.');
  2508. this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
  2509. }
  2510. };
  2511. Connection.prototype.proceedWithUpgrade_ = function () {
  2512. // tell this connection to consider itself open
  2513. this.secondaryConn_.start();
  2514. // send ack
  2515. this.log_('sending client ack on secondary');
  2516. this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
  2517. // send end packet on primary transport, switch to sending on this one
  2518. // can receive on this one, buffer responses until end received on primary transport
  2519. this.log_('Ending transmission on primary');
  2520. this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
  2521. this.tx_ = this.secondaryConn_;
  2522. this.tryCleanupConnection();
  2523. };
  2524. Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {
  2525. // Must refer to parsedData properties in quotes, so closure doesn't touch them.
  2526. var layer = requireKey('t', parsedData);
  2527. var data = requireKey('d', parsedData);
  2528. if (layer === 'c') {
  2529. this.onControl_(data);
  2530. }
  2531. else if (layer === 'd') {
  2532. this.onDataMessage_(data);
  2533. }
  2534. };
  2535. Connection.prototype.onDataMessage_ = function (message) {
  2536. this.onPrimaryResponse_();
  2537. // We don't do anything with data messages, just kick them up a level
  2538. this.onMessage_(message);
  2539. };
  2540. Connection.prototype.onPrimaryResponse_ = function () {
  2541. if (!this.isHealthy_) {
  2542. this.primaryResponsesRequired_--;
  2543. if (this.primaryResponsesRequired_ <= 0) {
  2544. this.log_('Primary connection is healthy.');
  2545. this.isHealthy_ = true;
  2546. this.conn_.markConnectionHealthy();
  2547. }
  2548. }
  2549. };
  2550. Connection.prototype.onControl_ = function (controlData) {
  2551. var cmd = requireKey(MESSAGE_TYPE, controlData);
  2552. if (MESSAGE_DATA in controlData) {
  2553. var payload = controlData[MESSAGE_DATA];
  2554. if (cmd === SERVER_HELLO) {
  2555. this.onHandshake_(payload);
  2556. }
  2557. else if (cmd === END_TRANSMISSION) {
  2558. this.log_('recvd end transmission on primary');
  2559. this.rx_ = this.secondaryConn_;
  2560. for (var i = 0; i < this.pendingDataMessages.length; ++i) {
  2561. this.onDataMessage_(this.pendingDataMessages[i]);
  2562. }
  2563. this.pendingDataMessages = [];
  2564. this.tryCleanupConnection();
  2565. }
  2566. else if (cmd === CONTROL_SHUTDOWN) {
  2567. // This was previously the 'onKill' callback passed to the lower-level connection
  2568. // payload in this case is the reason for the shutdown. Generally a human-readable error
  2569. this.onConnectionShutdown_(payload);
  2570. }
  2571. else if (cmd === CONTROL_RESET) {
  2572. // payload in this case is the host we should contact
  2573. this.onReset_(payload);
  2574. }
  2575. else if (cmd === CONTROL_ERROR) {
  2576. error('Server Error: ' + payload);
  2577. }
  2578. else if (cmd === CONTROL_PONG) {
  2579. this.log_('got pong on primary.');
  2580. this.onPrimaryResponse_();
  2581. this.sendPingOnPrimaryIfNecessary_();
  2582. }
  2583. else {
  2584. error('Unknown control packet command: ' + cmd);
  2585. }
  2586. }
  2587. };
  2588. /**
  2589. * @param handshake - The handshake data returned from the server
  2590. */
  2591. Connection.prototype.onHandshake_ = function (handshake) {
  2592. var timestamp = handshake.ts;
  2593. var version = handshake.v;
  2594. var host = handshake.h;
  2595. this.sessionId = handshake.s;
  2596. this.repoInfo_.host = host;
  2597. // if we've already closed the connection, then don't bother trying to progress further
  2598. if (this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2599. this.conn_.start();
  2600. this.onConnectionEstablished_(this.conn_, timestamp);
  2601. if (PROTOCOL_VERSION !== version) {
  2602. warn('Protocol version mismatch detected');
  2603. }
  2604. // TODO: do we want to upgrade? when? maybe a delay?
  2605. this.tryStartUpgrade_();
  2606. }
  2607. };
  2608. Connection.prototype.tryStartUpgrade_ = function () {
  2609. var conn = this.transportManager_.upgradeTransport();
  2610. if (conn) {
  2611. this.startUpgrade_(conn);
  2612. }
  2613. };
  2614. Connection.prototype.startUpgrade_ = function (conn) {
  2615. var _this = this;
  2616. this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
  2617. // For certain transports (WebSockets), we need to send and receive several messages back and forth before we
  2618. // can consider the transport healthy.
  2619. this.secondaryResponsesRequired_ =
  2620. conn['responsesRequiredToBeHealthy'] || 0;
  2621. var onMessage = this.connReceiver_(this.secondaryConn_);
  2622. var onDisconnect = this.disconnReceiver_(this.secondaryConn_);
  2623. this.secondaryConn_.open(onMessage, onDisconnect);
  2624. // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.
  2625. setTimeoutNonBlocking(function () {
  2626. if (_this.secondaryConn_) {
  2627. _this.log_('Timed out trying to upgrade.');
  2628. _this.secondaryConn_.close();
  2629. }
  2630. }, Math.floor(UPGRADE_TIMEOUT));
  2631. };
  2632. Connection.prototype.onReset_ = function (host) {
  2633. this.log_('Reset packet received. New host: ' + host);
  2634. this.repoInfo_.host = host;
  2635. // TODO: if we're already "connected", we need to trigger a disconnect at the next layer up.
  2636. // We don't currently support resets after the connection has already been established
  2637. if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2638. this.close();
  2639. }
  2640. else {
  2641. // Close whatever connections we have open and start again.
  2642. this.closeConnections_();
  2643. this.start_();
  2644. }
  2645. };
  2646. Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {
  2647. var _this = this;
  2648. this.log_('Realtime connection established.');
  2649. this.conn_ = conn;
  2650. this.state_ = 1 /* RealtimeState.CONNECTED */;
  2651. if (this.onReady_) {
  2652. this.onReady_(timestamp, this.sessionId);
  2653. this.onReady_ = null;
  2654. }
  2655. // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,
  2656. // send some pings.
  2657. if (this.primaryResponsesRequired_ === 0) {
  2658. this.log_('Primary connection is healthy.');
  2659. this.isHealthy_ = true;
  2660. }
  2661. else {
  2662. setTimeoutNonBlocking(function () {
  2663. _this.sendPingOnPrimaryIfNecessary_();
  2664. }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
  2665. }
  2666. };
  2667. Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {
  2668. // If the connection isn't considered healthy yet, we'll send a noop ping packet request.
  2669. if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2670. this.log_('sending ping on primary.');
  2671. this.sendData_({ t: 'c', d: { t: PING, d: {} } });
  2672. }
  2673. };
  2674. Connection.prototype.onSecondaryConnectionLost_ = function () {
  2675. var conn = this.secondaryConn_;
  2676. this.secondaryConn_ = null;
  2677. if (this.tx_ === conn || this.rx_ === conn) {
  2678. // we are relying on this connection already in some capacity. Therefore, a failure is real
  2679. this.close();
  2680. }
  2681. };
  2682. /**
  2683. * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
  2684. * we should flush the host cache
  2685. */
  2686. Connection.prototype.onConnectionLost_ = function (everConnected) {
  2687. this.conn_ = null;
  2688. // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting
  2689. // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.
  2690. if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {
  2691. this.log_('Realtime connection failed.');
  2692. // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away
  2693. if (this.repoInfo_.isCacheableHost()) {
  2694. PersistentStorage.remove('host:' + this.repoInfo_.host);
  2695. // reset the internal host to what we would show the user, i.e. <ns>.firebaseio.com
  2696. this.repoInfo_.internalHost = this.repoInfo_.host;
  2697. }
  2698. }
  2699. else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {
  2700. this.log_('Realtime connection lost.');
  2701. }
  2702. this.close();
  2703. };
  2704. Connection.prototype.onConnectionShutdown_ = function (reason) {
  2705. this.log_('Connection shutdown command received. Shutting down...');
  2706. if (this.onKill_) {
  2707. this.onKill_(reason);
  2708. this.onKill_ = null;
  2709. }
  2710. // We intentionally don't want to fire onDisconnect (kill is a different case),
  2711. // so clear the callback.
  2712. this.onDisconnect_ = null;
  2713. this.close();
  2714. };
  2715. Connection.prototype.sendData_ = function (data) {
  2716. if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {
  2717. throw 'Connection is not connected';
  2718. }
  2719. else {
  2720. this.tx_.send(data);
  2721. }
  2722. };
  2723. /**
  2724. * Cleans up this connection, calling the appropriate callbacks
  2725. */
  2726. Connection.prototype.close = function () {
  2727. if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {
  2728. this.log_('Closing realtime connection.');
  2729. this.state_ = 2 /* RealtimeState.DISCONNECTED */;
  2730. this.closeConnections_();
  2731. if (this.onDisconnect_) {
  2732. this.onDisconnect_();
  2733. this.onDisconnect_ = null;
  2734. }
  2735. }
  2736. };
  2737. Connection.prototype.closeConnections_ = function () {
  2738. this.log_('Shutting down all connections');
  2739. if (this.conn_) {
  2740. this.conn_.close();
  2741. this.conn_ = null;
  2742. }
  2743. if (this.secondaryConn_) {
  2744. this.secondaryConn_.close();
  2745. this.secondaryConn_ = null;
  2746. }
  2747. if (this.healthyTimeout_) {
  2748. clearTimeout(this.healthyTimeout_);
  2749. this.healthyTimeout_ = null;
  2750. }
  2751. };
  2752. return Connection;
  2753. }());
  2754. /**
  2755. * @license
  2756. * Copyright 2017 Google LLC
  2757. *
  2758. * Licensed under the Apache License, Version 2.0 (the "License");
  2759. * you may not use this file except in compliance with the License.
  2760. * You may obtain a copy of the License at
  2761. *
  2762. * http://www.apache.org/licenses/LICENSE-2.0
  2763. *
  2764. * Unless required by applicable law or agreed to in writing, software
  2765. * distributed under the License is distributed on an "AS IS" BASIS,
  2766. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2767. * See the License for the specific language governing permissions and
  2768. * limitations under the License.
  2769. */
  2770. /**
  2771. * Interface defining the set of actions that can be performed against the Firebase server
  2772. * (basically corresponds to our wire protocol).
  2773. *
  2774. * @interface
  2775. */
  2776. var ServerActions = /** @class */ (function () {
  2777. function ServerActions() {
  2778. }
  2779. ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };
  2780. ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };
  2781. /**
  2782. * Refreshes the auth token for the current connection.
  2783. * @param token - The authentication token
  2784. */
  2785. ServerActions.prototype.refreshAuthToken = function (token) { };
  2786. /**
  2787. * Refreshes the app check token for the current connection.
  2788. * @param token The app check token
  2789. */
  2790. ServerActions.prototype.refreshAppCheckToken = function (token) { };
  2791. ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };
  2792. ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };
  2793. ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };
  2794. ServerActions.prototype.reportStats = function (stats) { };
  2795. return ServerActions;
  2796. }());
  2797. /**
  2798. * @license
  2799. * Copyright 2017 Google LLC
  2800. *
  2801. * Licensed under the Apache License, Version 2.0 (the "License");
  2802. * you may not use this file except in compliance with the License.
  2803. * You may obtain a copy of the License at
  2804. *
  2805. * http://www.apache.org/licenses/LICENSE-2.0
  2806. *
  2807. * Unless required by applicable law or agreed to in writing, software
  2808. * distributed under the License is distributed on an "AS IS" BASIS,
  2809. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2810. * See the License for the specific language governing permissions and
  2811. * limitations under the License.
  2812. */
  2813. /**
  2814. * Base class to be used if you want to emit events. Call the constructor with
  2815. * the set of allowed event names.
  2816. */
  2817. var EventEmitter = /** @class */ (function () {
  2818. function EventEmitter(allowedEvents_) {
  2819. this.allowedEvents_ = allowedEvents_;
  2820. this.listeners_ = {};
  2821. util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
  2822. }
  2823. /**
  2824. * To be called by derived classes to trigger events.
  2825. */
  2826. EventEmitter.prototype.trigger = function (eventType) {
  2827. var varArgs = [];
  2828. for (var _i = 1; _i < arguments.length; _i++) {
  2829. varArgs[_i - 1] = arguments[_i];
  2830. }
  2831. if (Array.isArray(this.listeners_[eventType])) {
  2832. // Clone the list, since callbacks could add/remove listeners.
  2833. var listeners = tslib.__spreadArray([], tslib.__read(this.listeners_[eventType]), false);
  2834. for (var i = 0; i < listeners.length; i++) {
  2835. listeners[i].callback.apply(listeners[i].context, varArgs);
  2836. }
  2837. }
  2838. };
  2839. EventEmitter.prototype.on = function (eventType, callback, context) {
  2840. this.validateEventType_(eventType);
  2841. this.listeners_[eventType] = this.listeners_[eventType] || [];
  2842. this.listeners_[eventType].push({ callback: callback, context: context });
  2843. var eventData = this.getInitialEvent(eventType);
  2844. if (eventData) {
  2845. callback.apply(context, eventData);
  2846. }
  2847. };
  2848. EventEmitter.prototype.off = function (eventType, callback, context) {
  2849. this.validateEventType_(eventType);
  2850. var listeners = this.listeners_[eventType] || [];
  2851. for (var i = 0; i < listeners.length; i++) {
  2852. if (listeners[i].callback === callback &&
  2853. (!context || context === listeners[i].context)) {
  2854. listeners.splice(i, 1);
  2855. return;
  2856. }
  2857. }
  2858. };
  2859. EventEmitter.prototype.validateEventType_ = function (eventType) {
  2860. util.assert(this.allowedEvents_.find(function (et) {
  2861. return et === eventType;
  2862. }), 'Unknown event: ' + eventType);
  2863. };
  2864. return EventEmitter;
  2865. }());
  2866. /**
  2867. * @license
  2868. * Copyright 2017 Google LLC
  2869. *
  2870. * Licensed under the Apache License, Version 2.0 (the "License");
  2871. * you may not use this file except in compliance with the License.
  2872. * You may obtain a copy of the License at
  2873. *
  2874. * http://www.apache.org/licenses/LICENSE-2.0
  2875. *
  2876. * Unless required by applicable law or agreed to in writing, software
  2877. * distributed under the License is distributed on an "AS IS" BASIS,
  2878. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2879. * See the License for the specific language governing permissions and
  2880. * limitations under the License.
  2881. */
  2882. /**
  2883. * Monitors online state (as reported by window.online/offline events).
  2884. *
  2885. * The expectation is that this could have many false positives (thinks we are online
  2886. * when we're not), but no false negatives. So we can safely use it to determine when
  2887. * we definitely cannot reach the internet.
  2888. */
  2889. var OnlineMonitor = /** @class */ (function (_super) {
  2890. tslib.__extends(OnlineMonitor, _super);
  2891. function OnlineMonitor() {
  2892. var _this = _super.call(this, ['online']) || this;
  2893. _this.online_ = true;
  2894. // We've had repeated complaints that Cordova apps can get stuck "offline", e.g.
  2895. // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810
  2896. // It would seem that the 'online' event does not always fire consistently. So we disable it
  2897. // for Cordova.
  2898. if (typeof window !== 'undefined' &&
  2899. typeof window.addEventListener !== 'undefined' &&
  2900. !util.isMobileCordova()) {
  2901. window.addEventListener('online', function () {
  2902. if (!_this.online_) {
  2903. _this.online_ = true;
  2904. _this.trigger('online', true);
  2905. }
  2906. }, false);
  2907. window.addEventListener('offline', function () {
  2908. if (_this.online_) {
  2909. _this.online_ = false;
  2910. _this.trigger('online', false);
  2911. }
  2912. }, false);
  2913. }
  2914. return _this;
  2915. }
  2916. OnlineMonitor.getInstance = function () {
  2917. return new OnlineMonitor();
  2918. };
  2919. OnlineMonitor.prototype.getInitialEvent = function (eventType) {
  2920. util.assert(eventType === 'online', 'Unknown event type: ' + eventType);
  2921. return [this.online_];
  2922. };
  2923. OnlineMonitor.prototype.currentlyOnline = function () {
  2924. return this.online_;
  2925. };
  2926. return OnlineMonitor;
  2927. }(EventEmitter));
  2928. /**
  2929. * @license
  2930. * Copyright 2017 Google LLC
  2931. *
  2932. * Licensed under the Apache License, Version 2.0 (the "License");
  2933. * you may not use this file except in compliance with the License.
  2934. * You may obtain a copy of the License at
  2935. *
  2936. * http://www.apache.org/licenses/LICENSE-2.0
  2937. *
  2938. * Unless required by applicable law or agreed to in writing, software
  2939. * distributed under the License is distributed on an "AS IS" BASIS,
  2940. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2941. * See the License for the specific language governing permissions and
  2942. * limitations under the License.
  2943. */
  2944. /** Maximum key depth. */
  2945. var MAX_PATH_DEPTH = 32;
  2946. /** Maximum number of (UTF8) bytes in a Firebase path. */
  2947. var MAX_PATH_LENGTH_BYTES = 768;
  2948. /**
  2949. * An immutable object representing a parsed path. It's immutable so that you
  2950. * can pass them around to other functions without worrying about them changing
  2951. * it.
  2952. */
  2953. var Path = /** @class */ (function () {
  2954. /**
  2955. * @param pathOrString - Path string to parse, or another path, or the raw
  2956. * tokens array
  2957. */
  2958. function Path(pathOrString, pieceNum) {
  2959. if (pieceNum === void 0) {
  2960. this.pieces_ = pathOrString.split('/');
  2961. // Remove empty pieces.
  2962. var copyTo = 0;
  2963. for (var i = 0; i < this.pieces_.length; i++) {
  2964. if (this.pieces_[i].length > 0) {
  2965. this.pieces_[copyTo] = this.pieces_[i];
  2966. copyTo++;
  2967. }
  2968. }
  2969. this.pieces_.length = copyTo;
  2970. this.pieceNum_ = 0;
  2971. }
  2972. else {
  2973. this.pieces_ = pathOrString;
  2974. this.pieceNum_ = pieceNum;
  2975. }
  2976. }
  2977. Path.prototype.toString = function () {
  2978. var pathString = '';
  2979. for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
  2980. if (this.pieces_[i] !== '') {
  2981. pathString += '/' + this.pieces_[i];
  2982. }
  2983. }
  2984. return pathString || '/';
  2985. };
  2986. return Path;
  2987. }());
  2988. function newEmptyPath() {
  2989. return new Path('');
  2990. }
  2991. function pathGetFront(path) {
  2992. if (path.pieceNum_ >= path.pieces_.length) {
  2993. return null;
  2994. }
  2995. return path.pieces_[path.pieceNum_];
  2996. }
  2997. /**
  2998. * @returns The number of segments in this path
  2999. */
  3000. function pathGetLength(path) {
  3001. return path.pieces_.length - path.pieceNum_;
  3002. }
  3003. function pathPopFront(path) {
  3004. var pieceNum = path.pieceNum_;
  3005. if (pieceNum < path.pieces_.length) {
  3006. pieceNum++;
  3007. }
  3008. return new Path(path.pieces_, pieceNum);
  3009. }
  3010. function pathGetBack(path) {
  3011. if (path.pieceNum_ < path.pieces_.length) {
  3012. return path.pieces_[path.pieces_.length - 1];
  3013. }
  3014. return null;
  3015. }
  3016. function pathToUrlEncodedString(path) {
  3017. var pathString = '';
  3018. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3019. if (path.pieces_[i] !== '') {
  3020. pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
  3021. }
  3022. }
  3023. return pathString || '/';
  3024. }
  3025. /**
  3026. * Shallow copy of the parts of the path.
  3027. *
  3028. */
  3029. function pathSlice(path, begin) {
  3030. if (begin === void 0) { begin = 0; }
  3031. return path.pieces_.slice(path.pieceNum_ + begin);
  3032. }
  3033. function pathParent(path) {
  3034. if (path.pieceNum_ >= path.pieces_.length) {
  3035. return null;
  3036. }
  3037. var pieces = [];
  3038. for (var i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
  3039. pieces.push(path.pieces_[i]);
  3040. }
  3041. return new Path(pieces, 0);
  3042. }
  3043. function pathChild(path, childPathObj) {
  3044. var pieces = [];
  3045. for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
  3046. pieces.push(path.pieces_[i]);
  3047. }
  3048. if (childPathObj instanceof Path) {
  3049. for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
  3050. pieces.push(childPathObj.pieces_[i]);
  3051. }
  3052. }
  3053. else {
  3054. var childPieces = childPathObj.split('/');
  3055. for (var i = 0; i < childPieces.length; i++) {
  3056. if (childPieces[i].length > 0) {
  3057. pieces.push(childPieces[i]);
  3058. }
  3059. }
  3060. }
  3061. return new Path(pieces, 0);
  3062. }
  3063. /**
  3064. * @returns True if there are no segments in this path
  3065. */
  3066. function pathIsEmpty(path) {
  3067. return path.pieceNum_ >= path.pieces_.length;
  3068. }
  3069. /**
  3070. * @returns The path from outerPath to innerPath
  3071. */
  3072. function newRelativePath(outerPath, innerPath) {
  3073. var outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
  3074. if (outer === null) {
  3075. return innerPath;
  3076. }
  3077. else if (outer === inner) {
  3078. return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
  3079. }
  3080. else {
  3081. throw new Error('INTERNAL ERROR: innerPath (' +
  3082. innerPath +
  3083. ') is not within ' +
  3084. 'outerPath (' +
  3085. outerPath +
  3086. ')');
  3087. }
  3088. }
  3089. /**
  3090. * @returns -1, 0, 1 if left is less, equal, or greater than the right.
  3091. */
  3092. function pathCompare(left, right) {
  3093. var leftKeys = pathSlice(left, 0);
  3094. var rightKeys = pathSlice(right, 0);
  3095. for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
  3096. var cmp = nameCompare(leftKeys[i], rightKeys[i]);
  3097. if (cmp !== 0) {
  3098. return cmp;
  3099. }
  3100. }
  3101. if (leftKeys.length === rightKeys.length) {
  3102. return 0;
  3103. }
  3104. return leftKeys.length < rightKeys.length ? -1 : 1;
  3105. }
  3106. /**
  3107. * @returns true if paths are the same.
  3108. */
  3109. function pathEquals(path, other) {
  3110. if (pathGetLength(path) !== pathGetLength(other)) {
  3111. return false;
  3112. }
  3113. for (var i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
  3114. if (path.pieces_[i] !== other.pieces_[j]) {
  3115. return false;
  3116. }
  3117. }
  3118. return true;
  3119. }
  3120. /**
  3121. * @returns True if this path is a parent of (or the same as) other
  3122. */
  3123. function pathContains(path, other) {
  3124. var i = path.pieceNum_;
  3125. var j = other.pieceNum_;
  3126. if (pathGetLength(path) > pathGetLength(other)) {
  3127. return false;
  3128. }
  3129. while (i < path.pieces_.length) {
  3130. if (path.pieces_[i] !== other.pieces_[j]) {
  3131. return false;
  3132. }
  3133. ++i;
  3134. ++j;
  3135. }
  3136. return true;
  3137. }
  3138. /**
  3139. * Dynamic (mutable) path used to count path lengths.
  3140. *
  3141. * This class is used to efficiently check paths for valid
  3142. * length (in UTF8 bytes) and depth (used in path validation).
  3143. *
  3144. * Throws Error exception if path is ever invalid.
  3145. *
  3146. * The definition of a path always begins with '/'.
  3147. */
  3148. var ValidationPath = /** @class */ (function () {
  3149. /**
  3150. * @param path - Initial Path.
  3151. * @param errorPrefix_ - Prefix for any error messages.
  3152. */
  3153. function ValidationPath(path, errorPrefix_) {
  3154. this.errorPrefix_ = errorPrefix_;
  3155. this.parts_ = pathSlice(path, 0);
  3156. /** Initialize to number of '/' chars needed in path. */
  3157. this.byteLength_ = Math.max(1, this.parts_.length);
  3158. for (var i = 0; i < this.parts_.length; i++) {
  3159. this.byteLength_ += util.stringLength(this.parts_[i]);
  3160. }
  3161. validationPathCheckValid(this);
  3162. }
  3163. return ValidationPath;
  3164. }());
  3165. function validationPathPush(validationPath, child) {
  3166. // Count the needed '/'
  3167. if (validationPath.parts_.length > 0) {
  3168. validationPath.byteLength_ += 1;
  3169. }
  3170. validationPath.parts_.push(child);
  3171. validationPath.byteLength_ += util.stringLength(child);
  3172. validationPathCheckValid(validationPath);
  3173. }
  3174. function validationPathPop(validationPath) {
  3175. var last = validationPath.parts_.pop();
  3176. validationPath.byteLength_ -= util.stringLength(last);
  3177. // Un-count the previous '/'
  3178. if (validationPath.parts_.length > 0) {
  3179. validationPath.byteLength_ -= 1;
  3180. }
  3181. }
  3182. function validationPathCheckValid(validationPath) {
  3183. if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
  3184. throw new Error(validationPath.errorPrefix_ +
  3185. 'has a key path longer than ' +
  3186. MAX_PATH_LENGTH_BYTES +
  3187. ' bytes (' +
  3188. validationPath.byteLength_ +
  3189. ').');
  3190. }
  3191. if (validationPath.parts_.length > MAX_PATH_DEPTH) {
  3192. throw new Error(validationPath.errorPrefix_ +
  3193. 'path specified exceeds the maximum depth that can be written (' +
  3194. MAX_PATH_DEPTH +
  3195. ') or object contains a cycle ' +
  3196. validationPathToErrorString(validationPath));
  3197. }
  3198. }
  3199. /**
  3200. * String for use in error messages - uses '.' notation for path.
  3201. */
  3202. function validationPathToErrorString(validationPath) {
  3203. if (validationPath.parts_.length === 0) {
  3204. return '';
  3205. }
  3206. return "in property '" + validationPath.parts_.join('.') + "'";
  3207. }
  3208. /**
  3209. * @license
  3210. * Copyright 2017 Google LLC
  3211. *
  3212. * Licensed under the Apache License, Version 2.0 (the "License");
  3213. * you may not use this file except in compliance with the License.
  3214. * You may obtain a copy of the License at
  3215. *
  3216. * http://www.apache.org/licenses/LICENSE-2.0
  3217. *
  3218. * Unless required by applicable law or agreed to in writing, software
  3219. * distributed under the License is distributed on an "AS IS" BASIS,
  3220. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3221. * See the License for the specific language governing permissions and
  3222. * limitations under the License.
  3223. */
  3224. var VisibilityMonitor = /** @class */ (function (_super) {
  3225. tslib.__extends(VisibilityMonitor, _super);
  3226. function VisibilityMonitor() {
  3227. var _this = _super.call(this, ['visible']) || this;
  3228. var hidden;
  3229. var visibilityChange;
  3230. if (typeof document !== 'undefined' &&
  3231. typeof document.addEventListener !== 'undefined') {
  3232. if (typeof document['hidden'] !== 'undefined') {
  3233. // Opera 12.10 and Firefox 18 and later support
  3234. visibilityChange = 'visibilitychange';
  3235. hidden = 'hidden';
  3236. }
  3237. else if (typeof document['mozHidden'] !== 'undefined') {
  3238. visibilityChange = 'mozvisibilitychange';
  3239. hidden = 'mozHidden';
  3240. }
  3241. else if (typeof document['msHidden'] !== 'undefined') {
  3242. visibilityChange = 'msvisibilitychange';
  3243. hidden = 'msHidden';
  3244. }
  3245. else if (typeof document['webkitHidden'] !== 'undefined') {
  3246. visibilityChange = 'webkitvisibilitychange';
  3247. hidden = 'webkitHidden';
  3248. }
  3249. }
  3250. // Initially, we always assume we are visible. This ensures that in browsers
  3251. // without page visibility support or in cases where we are never visible
  3252. // (e.g. chrome extension), we act as if we are visible, i.e. don't delay
  3253. // reconnects
  3254. _this.visible_ = true;
  3255. if (visibilityChange) {
  3256. document.addEventListener(visibilityChange, function () {
  3257. var visible = !document[hidden];
  3258. if (visible !== _this.visible_) {
  3259. _this.visible_ = visible;
  3260. _this.trigger('visible', visible);
  3261. }
  3262. }, false);
  3263. }
  3264. return _this;
  3265. }
  3266. VisibilityMonitor.getInstance = function () {
  3267. return new VisibilityMonitor();
  3268. };
  3269. VisibilityMonitor.prototype.getInitialEvent = function (eventType) {
  3270. util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);
  3271. return [this.visible_];
  3272. };
  3273. return VisibilityMonitor;
  3274. }(EventEmitter));
  3275. /**
  3276. * @license
  3277. * Copyright 2017 Google LLC
  3278. *
  3279. * Licensed under the Apache License, Version 2.0 (the "License");
  3280. * you may not use this file except in compliance with the License.
  3281. * You may obtain a copy of the License at
  3282. *
  3283. * http://www.apache.org/licenses/LICENSE-2.0
  3284. *
  3285. * Unless required by applicable law or agreed to in writing, software
  3286. * distributed under the License is distributed on an "AS IS" BASIS,
  3287. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  3288. * See the License for the specific language governing permissions and
  3289. * limitations under the License.
  3290. */
  3291. var RECONNECT_MIN_DELAY = 1000;
  3292. var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)
  3293. var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)
  3294. var RECONNECT_DELAY_MULTIPLIER = 1.3;
  3295. var RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.
  3296. var SERVER_KILL_INTERRUPT_REASON = 'server_kill';
  3297. // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.
  3298. var INVALID_TOKEN_THRESHOLD = 3;
  3299. /**
  3300. * Firebase connection. Abstracts wire protocol and handles reconnecting.
  3301. *
  3302. * NOTE: All JSON objects sent to the realtime connection must have property names enclosed
  3303. * in quotes to make sure the closure compiler does not minify them.
  3304. */
  3305. var PersistentConnection = /** @class */ (function (_super) {
  3306. tslib.__extends(PersistentConnection, _super);
  3307. /**
  3308. * @param repoInfo_ - Data about the namespace we are connecting to
  3309. * @param applicationId_ - The Firebase App ID for this project
  3310. * @param onDataUpdate_ - A callback for new data from the server
  3311. */
  3312. function PersistentConnection(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
  3313. var _this = _super.call(this) || this;
  3314. _this.repoInfo_ = repoInfo_;
  3315. _this.applicationId_ = applicationId_;
  3316. _this.onDataUpdate_ = onDataUpdate_;
  3317. _this.onConnectStatus_ = onConnectStatus_;
  3318. _this.onServerInfoUpdate_ = onServerInfoUpdate_;
  3319. _this.authTokenProvider_ = authTokenProvider_;
  3320. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  3321. _this.authOverride_ = authOverride_;
  3322. // Used for diagnostic logging.
  3323. _this.id = PersistentConnection.nextPersistentConnectionId_++;
  3324. _this.log_ = logWrapper('p:' + _this.id + ':');
  3325. _this.interruptReasons_ = {};
  3326. _this.listens = new Map();
  3327. _this.outstandingPuts_ = [];
  3328. _this.outstandingGets_ = [];
  3329. _this.outstandingPutCount_ = 0;
  3330. _this.outstandingGetCount_ = 0;
  3331. _this.onDisconnectRequestQueue_ = [];
  3332. _this.connected_ = false;
  3333. _this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3334. _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
  3335. _this.securityDebugCallback_ = null;
  3336. _this.lastSessionId = null;
  3337. _this.establishConnectionTimer_ = null;
  3338. _this.visible_ = false;
  3339. // Before we get connected, we keep a queue of pending messages to send.
  3340. _this.requestCBHash_ = {};
  3341. _this.requestNumber_ = 0;
  3342. _this.realtime_ = null;
  3343. _this.authToken_ = null;
  3344. _this.appCheckToken_ = null;
  3345. _this.forceTokenRefresh_ = false;
  3346. _this.invalidAuthTokenCount_ = 0;
  3347. _this.invalidAppCheckTokenCount_ = 0;
  3348. _this.firstConnection_ = true;
  3349. _this.lastConnectionAttemptTime_ = null;
  3350. _this.lastConnectionEstablishedTime_ = null;
  3351. if (authOverride_ && !util.isNodeSdk()) {
  3352. throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
  3353. }
  3354. VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);
  3355. if (repoInfo_.host.indexOf('fblocal') === -1) {
  3356. OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);
  3357. }
  3358. return _this;
  3359. }
  3360. PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {
  3361. var curReqNum = ++this.requestNumber_;
  3362. var msg = { r: curReqNum, a: action, b: body };
  3363. this.log_(util.stringify(msg));
  3364. util.assert(this.connected_, "sendRequest call when we're not connected not allowed.");
  3365. this.realtime_.sendRequest(msg);
  3366. if (onResponse) {
  3367. this.requestCBHash_[curReqNum] = onResponse;
  3368. }
  3369. };
  3370. PersistentConnection.prototype.get = function (query) {
  3371. this.initConnection_();
  3372. var deferred = new util.Deferred();
  3373. var request = {
  3374. p: query._path.toString(),
  3375. q: query._queryObject
  3376. };
  3377. var outstandingGet = {
  3378. action: 'g',
  3379. request: request,
  3380. onComplete: function (message) {
  3381. var payload = message['d'];
  3382. if (message['s'] === 'ok') {
  3383. deferred.resolve(payload);
  3384. }
  3385. else {
  3386. deferred.reject(payload);
  3387. }
  3388. }
  3389. };
  3390. this.outstandingGets_.push(outstandingGet);
  3391. this.outstandingGetCount_++;
  3392. var index = this.outstandingGets_.length - 1;
  3393. if (this.connected_) {
  3394. this.sendGet_(index);
  3395. }
  3396. return deferred.promise;
  3397. };
  3398. PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  3399. this.initConnection_();
  3400. var queryId = query._queryIdentifier;
  3401. var pathString = query._path.toString();
  3402. this.log_('Listen called for ' + pathString + ' ' + queryId);
  3403. if (!this.listens.has(pathString)) {
  3404. this.listens.set(pathString, new Map());
  3405. }
  3406. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
  3407. util.assert(!this.listens.get(pathString).has(queryId), "listen() called twice for same path/queryId.");
  3408. var listenSpec = {
  3409. onComplete: onComplete,
  3410. hashFn: currentHashFn,
  3411. query: query,
  3412. tag: tag
  3413. };
  3414. this.listens.get(pathString).set(queryId, listenSpec);
  3415. if (this.connected_) {
  3416. this.sendListen_(listenSpec);
  3417. }
  3418. };
  3419. PersistentConnection.prototype.sendGet_ = function (index) {
  3420. var _this = this;
  3421. var get = this.outstandingGets_[index];
  3422. this.sendRequest('g', get.request, function (message) {
  3423. delete _this.outstandingGets_[index];
  3424. _this.outstandingGetCount_--;
  3425. if (_this.outstandingGetCount_ === 0) {
  3426. _this.outstandingGets_ = [];
  3427. }
  3428. if (get.onComplete) {
  3429. get.onComplete(message);
  3430. }
  3431. });
  3432. };
  3433. PersistentConnection.prototype.sendListen_ = function (listenSpec) {
  3434. var _this = this;
  3435. var query = listenSpec.query;
  3436. var pathString = query._path.toString();
  3437. var queryId = query._queryIdentifier;
  3438. this.log_('Listen on ' + pathString + ' for ' + queryId);
  3439. var req = { /*path*/ p: pathString };
  3440. var action = 'q';
  3441. // Only bother to send query if it's non-default.
  3442. if (listenSpec.tag) {
  3443. req['q'] = query._queryObject;
  3444. req['t'] = listenSpec.tag;
  3445. }
  3446. req[ /*hash*/'h'] = listenSpec.hashFn();
  3447. this.sendRequest(action, req, function (message) {
  3448. var payload = message[ /*data*/'d'];
  3449. var status = message[ /*status*/'s'];
  3450. // print warnings in any case...
  3451. PersistentConnection.warnOnListenWarnings_(payload, query);
  3452. var currentListenSpec = _this.listens.get(pathString) &&
  3453. _this.listens.get(pathString).get(queryId);
  3454. // only trigger actions if the listen hasn't been removed and readded
  3455. if (currentListenSpec === listenSpec) {
  3456. _this.log_('listen response', message);
  3457. if (status !== 'ok') {
  3458. _this.removeListen_(pathString, queryId);
  3459. }
  3460. if (listenSpec.onComplete) {
  3461. listenSpec.onComplete(status, payload);
  3462. }
  3463. }
  3464. });
  3465. };
  3466. PersistentConnection.warnOnListenWarnings_ = function (payload, query) {
  3467. if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {
  3468. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3469. var warnings = util.safeGet(payload, 'w');
  3470. if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
  3471. var indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
  3472. var indexPath = query._path.toString();
  3473. warn("Using an unspecified index. Your data will be downloaded and " +
  3474. "filtered on the client. Consider adding ".concat(indexSpec, " at ") +
  3475. "".concat(indexPath, " to your security rules for better performance."));
  3476. }
  3477. }
  3478. };
  3479. PersistentConnection.prototype.refreshAuthToken = function (token) {
  3480. this.authToken_ = token;
  3481. this.log_('Auth token refreshed');
  3482. if (this.authToken_) {
  3483. this.tryAuth();
  3484. }
  3485. else {
  3486. //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete
  3487. //the credential so we dont become authenticated next time we connect.
  3488. if (this.connected_) {
  3489. this.sendRequest('unauth', {}, function () { });
  3490. }
  3491. }
  3492. this.reduceReconnectDelayIfAdminCredential_(token);
  3493. };
  3494. PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {
  3495. // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).
  3496. // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.
  3497. var isFirebaseSecret = credential && credential.length === 40;
  3498. if (isFirebaseSecret || util.isAdmin(credential)) {
  3499. this.log_('Admin auth credential detected. Reducing max reconnect time.');
  3500. this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  3501. }
  3502. };
  3503. PersistentConnection.prototype.refreshAppCheckToken = function (token) {
  3504. this.appCheckToken_ = token;
  3505. this.log_('App check token refreshed');
  3506. if (this.appCheckToken_) {
  3507. this.tryAppCheck();
  3508. }
  3509. else {
  3510. //If we're connected we want to let the server know to unauthenticate us.
  3511. //If we're not connected, simply delete the credential so we dont become
  3512. // authenticated next time we connect.
  3513. if (this.connected_) {
  3514. this.sendRequest('unappeck', {}, function () { });
  3515. }
  3516. }
  3517. };
  3518. /**
  3519. * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
  3520. * a auth revoked (the connection is closed).
  3521. */
  3522. PersistentConnection.prototype.tryAuth = function () {
  3523. var _this = this;
  3524. if (this.connected_ && this.authToken_) {
  3525. var token_1 = this.authToken_;
  3526. var authMethod = util.isValidFormat(token_1) ? 'auth' : 'gauth';
  3527. var requestData = { cred: token_1 };
  3528. if (this.authOverride_ === null) {
  3529. requestData['noauth'] = true;
  3530. }
  3531. else if (typeof this.authOverride_ === 'object') {
  3532. requestData['authvar'] = this.authOverride_;
  3533. }
  3534. this.sendRequest(authMethod, requestData, function (res) {
  3535. var status = res[ /*status*/'s'];
  3536. var data = res[ /*data*/'d'] || 'error';
  3537. if (_this.authToken_ === token_1) {
  3538. if (status === 'ok') {
  3539. _this.invalidAuthTokenCount_ = 0;
  3540. }
  3541. else {
  3542. // Triggers reconnect and force refresh for auth token
  3543. _this.onAuthRevoked_(status, data);
  3544. }
  3545. }
  3546. });
  3547. }
  3548. };
  3549. /**
  3550. * Attempts to authenticate with the given token. If the authentication
  3551. * attempt fails, it's triggered like the token was revoked (the connection is
  3552. * closed).
  3553. */
  3554. PersistentConnection.prototype.tryAppCheck = function () {
  3555. var _this = this;
  3556. if (this.connected_ && this.appCheckToken_) {
  3557. this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, function (res) {
  3558. var status = res[ /*status*/'s'];
  3559. var data = res[ /*data*/'d'] || 'error';
  3560. if (status === 'ok') {
  3561. _this.invalidAppCheckTokenCount_ = 0;
  3562. }
  3563. else {
  3564. _this.onAppCheckRevoked_(status, data);
  3565. }
  3566. });
  3567. }
  3568. };
  3569. /**
  3570. * @inheritDoc
  3571. */
  3572. PersistentConnection.prototype.unlisten = function (query, tag) {
  3573. var pathString = query._path.toString();
  3574. var queryId = query._queryIdentifier;
  3575. this.log_('Unlisten called for ' + pathString + ' ' + queryId);
  3576. util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
  3577. var listen = this.removeListen_(pathString, queryId);
  3578. if (listen && this.connected_) {
  3579. this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
  3580. }
  3581. };
  3582. PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {
  3583. this.log_('Unlisten on ' + pathString + ' for ' + queryId);
  3584. var req = { /*path*/ p: pathString };
  3585. var action = 'n';
  3586. // Only bother sending queryId if it's non-default.
  3587. if (tag) {
  3588. req['q'] = queryObj;
  3589. req['t'] = tag;
  3590. }
  3591. this.sendRequest(action, req);
  3592. };
  3593. PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {
  3594. this.initConnection_();
  3595. if (this.connected_) {
  3596. this.sendOnDisconnect_('o', pathString, data, onComplete);
  3597. }
  3598. else {
  3599. this.onDisconnectRequestQueue_.push({
  3600. pathString: pathString,
  3601. action: 'o',
  3602. data: data,
  3603. onComplete: onComplete
  3604. });
  3605. }
  3606. };
  3607. PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {
  3608. this.initConnection_();
  3609. if (this.connected_) {
  3610. this.sendOnDisconnect_('om', pathString, data, onComplete);
  3611. }
  3612. else {
  3613. this.onDisconnectRequestQueue_.push({
  3614. pathString: pathString,
  3615. action: 'om',
  3616. data: data,
  3617. onComplete: onComplete
  3618. });
  3619. }
  3620. };
  3621. PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {
  3622. this.initConnection_();
  3623. if (this.connected_) {
  3624. this.sendOnDisconnect_('oc', pathString, null, onComplete);
  3625. }
  3626. else {
  3627. this.onDisconnectRequestQueue_.push({
  3628. pathString: pathString,
  3629. action: 'oc',
  3630. data: null,
  3631. onComplete: onComplete
  3632. });
  3633. }
  3634. };
  3635. PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {
  3636. var request = { /*path*/ p: pathString, /*data*/ d: data };
  3637. this.log_('onDisconnect ' + action, request);
  3638. this.sendRequest(action, request, function (response) {
  3639. if (onComplete) {
  3640. setTimeout(function () {
  3641. onComplete(response[ /*status*/'s'], response[ /* data */'d']);
  3642. }, Math.floor(0));
  3643. }
  3644. });
  3645. };
  3646. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  3647. this.putInternal('p', pathString, data, onComplete, hash);
  3648. };
  3649. PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {
  3650. this.putInternal('m', pathString, data, onComplete, hash);
  3651. };
  3652. PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {
  3653. this.initConnection_();
  3654. var request = {
  3655. /*path*/ p: pathString,
  3656. /*data*/ d: data
  3657. };
  3658. if (hash !== undefined) {
  3659. request[ /*hash*/'h'] = hash;
  3660. }
  3661. // TODO: Only keep track of the most recent put for a given path?
  3662. this.outstandingPuts_.push({
  3663. action: action,
  3664. request: request,
  3665. onComplete: onComplete
  3666. });
  3667. this.outstandingPutCount_++;
  3668. var index = this.outstandingPuts_.length - 1;
  3669. if (this.connected_) {
  3670. this.sendPut_(index);
  3671. }
  3672. else {
  3673. this.log_('Buffering put: ' + pathString);
  3674. }
  3675. };
  3676. PersistentConnection.prototype.sendPut_ = function (index) {
  3677. var _this = this;
  3678. var action = this.outstandingPuts_[index].action;
  3679. var request = this.outstandingPuts_[index].request;
  3680. var onComplete = this.outstandingPuts_[index].onComplete;
  3681. this.outstandingPuts_[index].queued = this.connected_;
  3682. this.sendRequest(action, request, function (message) {
  3683. _this.log_(action + ' response', message);
  3684. delete _this.outstandingPuts_[index];
  3685. _this.outstandingPutCount_--;
  3686. // Clean up array occasionally.
  3687. if (_this.outstandingPutCount_ === 0) {
  3688. _this.outstandingPuts_ = [];
  3689. }
  3690. if (onComplete) {
  3691. onComplete(message[ /*status*/'s'], message[ /* data */'d']);
  3692. }
  3693. });
  3694. };
  3695. PersistentConnection.prototype.reportStats = function (stats) {
  3696. var _this = this;
  3697. // If we're not connected, we just drop the stats.
  3698. if (this.connected_) {
  3699. var request = { /*counters*/ c: stats };
  3700. this.log_('reportStats', request);
  3701. this.sendRequest(/*stats*/ 's', request, function (result) {
  3702. var status = result[ /*status*/'s'];
  3703. if (status !== 'ok') {
  3704. var errorReason = result[ /* data */'d'];
  3705. _this.log_('reportStats', 'Error sending stats: ' + errorReason);
  3706. }
  3707. });
  3708. }
  3709. };
  3710. PersistentConnection.prototype.onDataMessage_ = function (message) {
  3711. if ('r' in message) {
  3712. // this is a response
  3713. this.log_('from server: ' + util.stringify(message));
  3714. var reqNum = message['r'];
  3715. var onResponse = this.requestCBHash_[reqNum];
  3716. if (onResponse) {
  3717. delete this.requestCBHash_[reqNum];
  3718. onResponse(message[ /*body*/'b']);
  3719. }
  3720. }
  3721. else if ('error' in message) {
  3722. throw 'A server-side error has occurred: ' + message['error'];
  3723. }
  3724. else if ('a' in message) {
  3725. // a and b are action and body, respectively
  3726. this.onDataPush_(message['a'], message['b']);
  3727. }
  3728. };
  3729. PersistentConnection.prototype.onDataPush_ = function (action, body) {
  3730. this.log_('handleServerMessage', action, body);
  3731. if (action === 'd') {
  3732. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3733. /*isMerge*/ false, body['t']);
  3734. }
  3735. else if (action === 'm') {
  3736. this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'],
  3737. /*isMerge=*/ true, body['t']);
  3738. }
  3739. else if (action === 'c') {
  3740. this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);
  3741. }
  3742. else if (action === 'ac') {
  3743. this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3744. }
  3745. else if (action === 'apc') {
  3746. this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);
  3747. }
  3748. else if (action === 'sd') {
  3749. this.onSecurityDebugPacket_(body);
  3750. }
  3751. else {
  3752. error('Unrecognized action received from server: ' +
  3753. util.stringify(action) +
  3754. '\nAre you using the latest client?');
  3755. }
  3756. };
  3757. PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {
  3758. this.log_('connection ready');
  3759. this.connected_ = true;
  3760. this.lastConnectionEstablishedTime_ = new Date().getTime();
  3761. this.handleTimestamp_(timestamp);
  3762. this.lastSessionId = sessionId;
  3763. if (this.firstConnection_) {
  3764. this.sendConnectStats_();
  3765. }
  3766. this.restoreState_();
  3767. this.firstConnection_ = false;
  3768. this.onConnectStatus_(true);
  3769. };
  3770. PersistentConnection.prototype.scheduleConnect_ = function (timeout) {
  3771. var _this = this;
  3772. util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
  3773. if (this.establishConnectionTimer_) {
  3774. clearTimeout(this.establishConnectionTimer_);
  3775. }
  3776. // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating "Security Error" in
  3777. // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).
  3778. this.establishConnectionTimer_ = setTimeout(function () {
  3779. _this.establishConnectionTimer_ = null;
  3780. _this.establishConnection_();
  3781. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  3782. }, Math.floor(timeout));
  3783. };
  3784. PersistentConnection.prototype.initConnection_ = function () {
  3785. if (!this.realtime_ && this.firstConnection_) {
  3786. this.scheduleConnect_(0);
  3787. }
  3788. };
  3789. PersistentConnection.prototype.onVisible_ = function (visible) {
  3790. // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.
  3791. if (visible &&
  3792. !this.visible_ &&
  3793. this.reconnectDelay_ === this.maxReconnectDelay_) {
  3794. this.log_('Window became visible. Reducing delay.');
  3795. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3796. if (!this.realtime_) {
  3797. this.scheduleConnect_(0);
  3798. }
  3799. }
  3800. this.visible_ = visible;
  3801. };
  3802. PersistentConnection.prototype.onOnline_ = function (online) {
  3803. if (online) {
  3804. this.log_('Browser went online.');
  3805. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3806. if (!this.realtime_) {
  3807. this.scheduleConnect_(0);
  3808. }
  3809. }
  3810. else {
  3811. this.log_('Browser went offline. Killing connection.');
  3812. if (this.realtime_) {
  3813. this.realtime_.close();
  3814. }
  3815. }
  3816. };
  3817. PersistentConnection.prototype.onRealtimeDisconnect_ = function () {
  3818. this.log_('data client disconnected');
  3819. this.connected_ = false;
  3820. this.realtime_ = null;
  3821. // Since we don't know if our sent transactions succeeded or not, we need to cancel them.
  3822. this.cancelSentTransactions_();
  3823. // Clear out the pending requests.
  3824. this.requestCBHash_ = {};
  3825. if (this.shouldReconnect_()) {
  3826. if (!this.visible_) {
  3827. this.log_("Window isn't visible. Delaying reconnect.");
  3828. this.reconnectDelay_ = this.maxReconnectDelay_;
  3829. this.lastConnectionAttemptTime_ = new Date().getTime();
  3830. }
  3831. else if (this.lastConnectionEstablishedTime_) {
  3832. // If we've been connected long enough, reset reconnect delay to minimum.
  3833. var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
  3834. if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
  3835. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3836. }
  3837. this.lastConnectionEstablishedTime_ = null;
  3838. }
  3839. var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
  3840. var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
  3841. reconnectDelay = Math.random() * reconnectDelay;
  3842. this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
  3843. this.scheduleConnect_(reconnectDelay);
  3844. // Adjust reconnect delay for next time.
  3845. this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
  3846. }
  3847. this.onConnectStatus_(false);
  3848. };
  3849. PersistentConnection.prototype.establishConnection_ = function () {
  3850. return tslib.__awaiter(this, void 0, void 0, function () {
  3851. var onDataMessage, onReady, onDisconnect_1, connId, lastSessionId, canceled_1, connection_1, closeFn, sendRequestFn, forceRefresh, _a, authToken, appCheckToken, error_1;
  3852. var _this = this;
  3853. return tslib.__generator(this, function (_b) {
  3854. switch (_b.label) {
  3855. case 0:
  3856. if (!this.shouldReconnect_()) return [3 /*break*/, 4];
  3857. this.log_('Making a connection attempt');
  3858. this.lastConnectionAttemptTime_ = new Date().getTime();
  3859. this.lastConnectionEstablishedTime_ = null;
  3860. onDataMessage = this.onDataMessage_.bind(this);
  3861. onReady = this.onReady_.bind(this);
  3862. onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);
  3863. connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
  3864. lastSessionId = this.lastSessionId;
  3865. canceled_1 = false;
  3866. connection_1 = null;
  3867. closeFn = function () {
  3868. if (connection_1) {
  3869. connection_1.close();
  3870. }
  3871. else {
  3872. canceled_1 = true;
  3873. onDisconnect_1();
  3874. }
  3875. };
  3876. sendRequestFn = function (msg) {
  3877. util.assert(connection_1, "sendRequest call when we're not connected not allowed.");
  3878. connection_1.sendRequest(msg);
  3879. };
  3880. this.realtime_ = {
  3881. close: closeFn,
  3882. sendRequest: sendRequestFn
  3883. };
  3884. forceRefresh = this.forceTokenRefresh_;
  3885. this.forceTokenRefresh_ = false;
  3886. _b.label = 1;
  3887. case 1:
  3888. _b.trys.push([1, 3, , 4]);
  3889. return [4 /*yield*/, Promise.all([
  3890. this.authTokenProvider_.getToken(forceRefresh),
  3891. this.appCheckTokenProvider_.getToken(forceRefresh)
  3892. ])];
  3893. case 2:
  3894. _a = tslib.__read.apply(void 0, [_b.sent(), 2]), authToken = _a[0], appCheckToken = _a[1];
  3895. if (!canceled_1) {
  3896. log('getToken() completed. Creating connection.');
  3897. this.authToken_ = authToken && authToken.accessToken;
  3898. this.appCheckToken_ = appCheckToken && appCheckToken.token;
  3899. connection_1 = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect_1,
  3900. /* onKill= */ function (reason) {
  3901. warn(reason + ' (' + _this.repoInfo_.toString() + ')');
  3902. _this.interrupt(SERVER_KILL_INTERRUPT_REASON);
  3903. }, lastSessionId);
  3904. }
  3905. else {
  3906. log('getToken() completed but was canceled');
  3907. }
  3908. return [3 /*break*/, 4];
  3909. case 3:
  3910. error_1 = _b.sent();
  3911. this.log_('Failed to get token: ' + error_1);
  3912. if (!canceled_1) {
  3913. if (this.repoInfo_.nodeAdmin) {
  3914. // This may be a critical error for the Admin Node.js SDK, so log a warning.
  3915. // But getToken() may also just have temporarily failed, so we still want to
  3916. // continue retrying.
  3917. warn(error_1);
  3918. }
  3919. closeFn();
  3920. }
  3921. return [3 /*break*/, 4];
  3922. case 4: return [2 /*return*/];
  3923. }
  3924. });
  3925. });
  3926. };
  3927. PersistentConnection.prototype.interrupt = function (reason) {
  3928. log('Interrupting connection for reason: ' + reason);
  3929. this.interruptReasons_[reason] = true;
  3930. if (this.realtime_) {
  3931. this.realtime_.close();
  3932. }
  3933. else {
  3934. if (this.establishConnectionTimer_) {
  3935. clearTimeout(this.establishConnectionTimer_);
  3936. this.establishConnectionTimer_ = null;
  3937. }
  3938. if (this.connected_) {
  3939. this.onRealtimeDisconnect_();
  3940. }
  3941. }
  3942. };
  3943. PersistentConnection.prototype.resume = function (reason) {
  3944. log('Resuming connection for reason: ' + reason);
  3945. delete this.interruptReasons_[reason];
  3946. if (util.isEmpty(this.interruptReasons_)) {
  3947. this.reconnectDelay_ = RECONNECT_MIN_DELAY;
  3948. if (!this.realtime_) {
  3949. this.scheduleConnect_(0);
  3950. }
  3951. }
  3952. };
  3953. PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {
  3954. var delta = timestamp - new Date().getTime();
  3955. this.onServerInfoUpdate_({ serverTimeOffset: delta });
  3956. };
  3957. PersistentConnection.prototype.cancelSentTransactions_ = function () {
  3958. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  3959. var put = this.outstandingPuts_[i];
  3960. if (put && /*hash*/ 'h' in put.request && put.queued) {
  3961. if (put.onComplete) {
  3962. put.onComplete('disconnect');
  3963. }
  3964. delete this.outstandingPuts_[i];
  3965. this.outstandingPutCount_--;
  3966. }
  3967. }
  3968. // Clean up array occasionally.
  3969. if (this.outstandingPutCount_ === 0) {
  3970. this.outstandingPuts_ = [];
  3971. }
  3972. };
  3973. PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {
  3974. // Remove the listen and manufacture a "permission_denied" error for the failed listen.
  3975. var queryId;
  3976. if (!query) {
  3977. queryId = 'default';
  3978. }
  3979. else {
  3980. queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$');
  3981. }
  3982. var listen = this.removeListen_(pathString, queryId);
  3983. if (listen && listen.onComplete) {
  3984. listen.onComplete('permission_denied');
  3985. }
  3986. };
  3987. PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {
  3988. var normalizedPathString = new Path(pathString).toString(); // normalize path.
  3989. var listen;
  3990. if (this.listens.has(normalizedPathString)) {
  3991. var map = this.listens.get(normalizedPathString);
  3992. listen = map.get(queryId);
  3993. map.delete(queryId);
  3994. if (map.size === 0) {
  3995. this.listens.delete(normalizedPathString);
  3996. }
  3997. }
  3998. else {
  3999. // all listens for this path has already been removed
  4000. listen = undefined;
  4001. }
  4002. return listen;
  4003. };
  4004. PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {
  4005. log('Auth token revoked: ' + statusCode + '/' + explanation);
  4006. this.authToken_ = null;
  4007. this.forceTokenRefresh_ = true;
  4008. this.realtime_.close();
  4009. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4010. // We'll wait a couple times before logging the warning / increasing the
  4011. // retry period since oauth tokens will report as "invalid" if they're
  4012. // just expired. Plus there may be transient issues that resolve themselves.
  4013. this.invalidAuthTokenCount_++;
  4014. if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4015. // Set a long reconnect delay because recovery is unlikely
  4016. this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
  4017. // Notify the auth token provider that the token is invalid, which will log
  4018. // a warning
  4019. this.authTokenProvider_.notifyForInvalidToken();
  4020. }
  4021. }
  4022. };
  4023. PersistentConnection.prototype.onAppCheckRevoked_ = function (statusCode, explanation) {
  4024. log('App check token revoked: ' + statusCode + '/' + explanation);
  4025. this.appCheckToken_ = null;
  4026. this.forceTokenRefresh_ = true;
  4027. // Note: We don't close the connection as the developer may not have
  4028. // enforcement enabled. The backend closes connections with enforcements.
  4029. if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
  4030. // We'll wait a couple times before logging the warning / increasing the
  4031. // retry period since oauth tokens will report as "invalid" if they're
  4032. // just expired. Plus there may be transient issues that resolve themselves.
  4033. this.invalidAppCheckTokenCount_++;
  4034. if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
  4035. this.appCheckTokenProvider_.notifyForInvalidToken();
  4036. }
  4037. }
  4038. };
  4039. PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {
  4040. if (this.securityDebugCallback_) {
  4041. this.securityDebugCallback_(body);
  4042. }
  4043. else {
  4044. if ('msg' in body) {
  4045. console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
  4046. }
  4047. }
  4048. };
  4049. PersistentConnection.prototype.restoreState_ = function () {
  4050. var e_1, _a, e_2, _b;
  4051. //Re-authenticate ourselves if we have a credential stored.
  4052. this.tryAuth();
  4053. this.tryAppCheck();
  4054. try {
  4055. // Puts depend on having received the corresponding data update from the server before they complete, so we must
  4056. // make sure to send listens before puts.
  4057. for (var _c = tslib.__values(this.listens.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
  4058. var queries = _d.value;
  4059. try {
  4060. for (var _e = (e_2 = void 0, tslib.__values(queries.values())), _f = _e.next(); !_f.done; _f = _e.next()) {
  4061. var listenSpec = _f.value;
  4062. this.sendListen_(listenSpec);
  4063. }
  4064. }
  4065. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  4066. finally {
  4067. try {
  4068. if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
  4069. }
  4070. finally { if (e_2) throw e_2.error; }
  4071. }
  4072. }
  4073. }
  4074. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  4075. finally {
  4076. try {
  4077. if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
  4078. }
  4079. finally { if (e_1) throw e_1.error; }
  4080. }
  4081. for (var i = 0; i < this.outstandingPuts_.length; i++) {
  4082. if (this.outstandingPuts_[i]) {
  4083. this.sendPut_(i);
  4084. }
  4085. }
  4086. while (this.onDisconnectRequestQueue_.length) {
  4087. var request = this.onDisconnectRequestQueue_.shift();
  4088. this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
  4089. }
  4090. for (var i = 0; i < this.outstandingGets_.length; i++) {
  4091. if (this.outstandingGets_[i]) {
  4092. this.sendGet_(i);
  4093. }
  4094. }
  4095. };
  4096. /**
  4097. * Sends client stats for first connection
  4098. */
  4099. PersistentConnection.prototype.sendConnectStats_ = function () {
  4100. var stats = {};
  4101. var clientName = 'js';
  4102. if (util.isNodeSdk()) {
  4103. if (this.repoInfo_.nodeAdmin) {
  4104. clientName = 'admin_node';
  4105. }
  4106. else {
  4107. clientName = 'node';
  4108. }
  4109. }
  4110. stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
  4111. if (util.isMobileCordova()) {
  4112. stats['framework.cordova'] = 1;
  4113. }
  4114. else if (util.isReactNative()) {
  4115. stats['framework.reactnative'] = 1;
  4116. }
  4117. this.reportStats(stats);
  4118. };
  4119. PersistentConnection.prototype.shouldReconnect_ = function () {
  4120. var online = OnlineMonitor.getInstance().currentlyOnline();
  4121. return util.isEmpty(this.interruptReasons_) && online;
  4122. };
  4123. PersistentConnection.nextPersistentConnectionId_ = 0;
  4124. /**
  4125. * Counter for number of connections created. Mainly used for tagging in the logs
  4126. */
  4127. PersistentConnection.nextConnectionId_ = 0;
  4128. return PersistentConnection;
  4129. }(ServerActions));
  4130. /**
  4131. * @license
  4132. * Copyright 2017 Google LLC
  4133. *
  4134. * Licensed under the Apache License, Version 2.0 (the "License");
  4135. * you may not use this file except in compliance with the License.
  4136. * You may obtain a copy of the License at
  4137. *
  4138. * http://www.apache.org/licenses/LICENSE-2.0
  4139. *
  4140. * Unless required by applicable law or agreed to in writing, software
  4141. * distributed under the License is distributed on an "AS IS" BASIS,
  4142. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4143. * See the License for the specific language governing permissions and
  4144. * limitations under the License.
  4145. */
  4146. var NamedNode = /** @class */ (function () {
  4147. function NamedNode(name, node) {
  4148. this.name = name;
  4149. this.node = node;
  4150. }
  4151. NamedNode.Wrap = function (name, node) {
  4152. return new NamedNode(name, node);
  4153. };
  4154. return NamedNode;
  4155. }());
  4156. /**
  4157. * @license
  4158. * Copyright 2017 Google LLC
  4159. *
  4160. * Licensed under the Apache License, Version 2.0 (the "License");
  4161. * you may not use this file except in compliance with the License.
  4162. * You may obtain a copy of the License at
  4163. *
  4164. * http://www.apache.org/licenses/LICENSE-2.0
  4165. *
  4166. * Unless required by applicable law or agreed to in writing, software
  4167. * distributed under the License is distributed on an "AS IS" BASIS,
  4168. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4169. * See the License for the specific language governing permissions and
  4170. * limitations under the License.
  4171. */
  4172. var Index = /** @class */ (function () {
  4173. function Index() {
  4174. }
  4175. /**
  4176. * @returns A standalone comparison function for
  4177. * this index
  4178. */
  4179. Index.prototype.getCompare = function () {
  4180. return this.compare.bind(this);
  4181. };
  4182. /**
  4183. * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
  4184. * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
  4185. *
  4186. *
  4187. * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
  4188. */
  4189. Index.prototype.indexedValueChanged = function (oldNode, newNode) {
  4190. var oldWrapped = new NamedNode(MIN_NAME, oldNode);
  4191. var newWrapped = new NamedNode(MIN_NAME, newNode);
  4192. return this.compare(oldWrapped, newWrapped) !== 0;
  4193. };
  4194. /**
  4195. * @returns a node wrapper that will sort equal to or less than
  4196. * any other node wrapper, using this index
  4197. */
  4198. Index.prototype.minPost = function () {
  4199. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4200. return NamedNode.MIN;
  4201. };
  4202. return Index;
  4203. }());
  4204. /**
  4205. * @license
  4206. * Copyright 2017 Google LLC
  4207. *
  4208. * Licensed under the Apache License, Version 2.0 (the "License");
  4209. * you may not use this file except in compliance with the License.
  4210. * You may obtain a copy of the License at
  4211. *
  4212. * http://www.apache.org/licenses/LICENSE-2.0
  4213. *
  4214. * Unless required by applicable law or agreed to in writing, software
  4215. * distributed under the License is distributed on an "AS IS" BASIS,
  4216. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4217. * See the License for the specific language governing permissions and
  4218. * limitations under the License.
  4219. */
  4220. var __EMPTY_NODE;
  4221. var KeyIndex = /** @class */ (function (_super) {
  4222. tslib.__extends(KeyIndex, _super);
  4223. function KeyIndex() {
  4224. return _super !== null && _super.apply(this, arguments) || this;
  4225. }
  4226. Object.defineProperty(KeyIndex, "__EMPTY_NODE", {
  4227. get: function () {
  4228. return __EMPTY_NODE;
  4229. },
  4230. set: function (val) {
  4231. __EMPTY_NODE = val;
  4232. },
  4233. enumerable: false,
  4234. configurable: true
  4235. });
  4236. KeyIndex.prototype.compare = function (a, b) {
  4237. return nameCompare(a.name, b.name);
  4238. };
  4239. KeyIndex.prototype.isDefinedOn = function (node) {
  4240. // We could probably return true here (since every node has a key), but it's never called
  4241. // so just leaving unimplemented for now.
  4242. throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');
  4243. };
  4244. KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  4245. return false; // The key for a node never changes.
  4246. };
  4247. KeyIndex.prototype.minPost = function () {
  4248. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4249. return NamedNode.MIN;
  4250. };
  4251. KeyIndex.prototype.maxPost = function () {
  4252. // TODO: This should really be created once and cached in a static property, but
  4253. // NamedNode isn't defined yet, so I can't use it in a static. Bleh.
  4254. return new NamedNode(MAX_NAME, __EMPTY_NODE);
  4255. };
  4256. KeyIndex.prototype.makePost = function (indexValue, name) {
  4257. util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
  4258. // We just use empty node, but it'll never be compared, since our comparator only looks at name.
  4259. return new NamedNode(indexValue, __EMPTY_NODE);
  4260. };
  4261. /**
  4262. * @returns String representation for inclusion in a query spec
  4263. */
  4264. KeyIndex.prototype.toString = function () {
  4265. return '.key';
  4266. };
  4267. return KeyIndex;
  4268. }(Index));
  4269. var KEY_INDEX = new KeyIndex();
  4270. /**
  4271. * @license
  4272. * Copyright 2017 Google LLC
  4273. *
  4274. * Licensed under the Apache License, Version 2.0 (the "License");
  4275. * you may not use this file except in compliance with the License.
  4276. * You may obtain a copy of the License at
  4277. *
  4278. * http://www.apache.org/licenses/LICENSE-2.0
  4279. *
  4280. * Unless required by applicable law or agreed to in writing, software
  4281. * distributed under the License is distributed on an "AS IS" BASIS,
  4282. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4283. * See the License for the specific language governing permissions and
  4284. * limitations under the License.
  4285. */
  4286. /**
  4287. * An iterator over an LLRBNode.
  4288. */
  4289. var SortedMapIterator = /** @class */ (function () {
  4290. /**
  4291. * @param node - Node to iterate.
  4292. * @param isReverse_ - Whether or not to iterate in reverse
  4293. */
  4294. function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {
  4295. if (resultGenerator_ === void 0) { resultGenerator_ = null; }
  4296. this.isReverse_ = isReverse_;
  4297. this.resultGenerator_ = resultGenerator_;
  4298. this.nodeStack_ = [];
  4299. var cmp = 1;
  4300. while (!node.isEmpty()) {
  4301. node = node;
  4302. cmp = startKey ? comparator(node.key, startKey) : 1;
  4303. // flip the comparison if we're going in reverse
  4304. if (isReverse_) {
  4305. cmp *= -1;
  4306. }
  4307. if (cmp < 0) {
  4308. // This node is less than our start key. ignore it
  4309. if (this.isReverse_) {
  4310. node = node.left;
  4311. }
  4312. else {
  4313. node = node.right;
  4314. }
  4315. }
  4316. else if (cmp === 0) {
  4317. // This node is exactly equal to our start key. Push it on the stack, but stop iterating;
  4318. this.nodeStack_.push(node);
  4319. break;
  4320. }
  4321. else {
  4322. // This node is greater than our start key, add it to the stack and move to the next one
  4323. this.nodeStack_.push(node);
  4324. if (this.isReverse_) {
  4325. node = node.right;
  4326. }
  4327. else {
  4328. node = node.left;
  4329. }
  4330. }
  4331. }
  4332. }
  4333. SortedMapIterator.prototype.getNext = function () {
  4334. if (this.nodeStack_.length === 0) {
  4335. return null;
  4336. }
  4337. var node = this.nodeStack_.pop();
  4338. var result;
  4339. if (this.resultGenerator_) {
  4340. result = this.resultGenerator_(node.key, node.value);
  4341. }
  4342. else {
  4343. result = { key: node.key, value: node.value };
  4344. }
  4345. if (this.isReverse_) {
  4346. node = node.left;
  4347. while (!node.isEmpty()) {
  4348. this.nodeStack_.push(node);
  4349. node = node.right;
  4350. }
  4351. }
  4352. else {
  4353. node = node.right;
  4354. while (!node.isEmpty()) {
  4355. this.nodeStack_.push(node);
  4356. node = node.left;
  4357. }
  4358. }
  4359. return result;
  4360. };
  4361. SortedMapIterator.prototype.hasNext = function () {
  4362. return this.nodeStack_.length > 0;
  4363. };
  4364. SortedMapIterator.prototype.peek = function () {
  4365. if (this.nodeStack_.length === 0) {
  4366. return null;
  4367. }
  4368. var node = this.nodeStack_[this.nodeStack_.length - 1];
  4369. if (this.resultGenerator_) {
  4370. return this.resultGenerator_(node.key, node.value);
  4371. }
  4372. else {
  4373. return { key: node.key, value: node.value };
  4374. }
  4375. };
  4376. return SortedMapIterator;
  4377. }());
  4378. /**
  4379. * Represents a node in a Left-leaning Red-Black tree.
  4380. */
  4381. var LLRBNode = /** @class */ (function () {
  4382. /**
  4383. * @param key - Key associated with this node.
  4384. * @param value - Value associated with this node.
  4385. * @param color - Whether this node is red.
  4386. * @param left - Left child.
  4387. * @param right - Right child.
  4388. */
  4389. function LLRBNode(key, value, color, left, right) {
  4390. this.key = key;
  4391. this.value = value;
  4392. this.color = color != null ? color : LLRBNode.RED;
  4393. this.left =
  4394. left != null ? left : SortedMap.EMPTY_NODE;
  4395. this.right =
  4396. right != null ? right : SortedMap.EMPTY_NODE;
  4397. }
  4398. /**
  4399. * Returns a copy of the current node, optionally replacing pieces of it.
  4400. *
  4401. * @param key - New key for the node, or null.
  4402. * @param value - New value for the node, or null.
  4403. * @param color - New color for the node, or null.
  4404. * @param left - New left child for the node, or null.
  4405. * @param right - New right child for the node, or null.
  4406. * @returns The node copy.
  4407. */
  4408. LLRBNode.prototype.copy = function (key, value, color, left, right) {
  4409. return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
  4410. };
  4411. /**
  4412. * @returns The total number of nodes in the tree.
  4413. */
  4414. LLRBNode.prototype.count = function () {
  4415. return this.left.count() + 1 + this.right.count();
  4416. };
  4417. /**
  4418. * @returns True if the tree is empty.
  4419. */
  4420. LLRBNode.prototype.isEmpty = function () {
  4421. return false;
  4422. };
  4423. /**
  4424. * Traverses the tree in key order and calls the specified action function
  4425. * for each node.
  4426. *
  4427. * @param action - Callback function to be called for each
  4428. * node. If it returns true, traversal is aborted.
  4429. * @returns The first truthy value returned by action, or the last falsey
  4430. * value returned by action
  4431. */
  4432. LLRBNode.prototype.inorderTraversal = function (action) {
  4433. return (this.left.inorderTraversal(action) ||
  4434. !!action(this.key, this.value) ||
  4435. this.right.inorderTraversal(action));
  4436. };
  4437. /**
  4438. * Traverses the tree in reverse key order and calls the specified action function
  4439. * for each node.
  4440. *
  4441. * @param action - Callback function to be called for each
  4442. * node. If it returns true, traversal is aborted.
  4443. * @returns True if traversal was aborted.
  4444. */
  4445. LLRBNode.prototype.reverseTraversal = function (action) {
  4446. return (this.right.reverseTraversal(action) ||
  4447. action(this.key, this.value) ||
  4448. this.left.reverseTraversal(action));
  4449. };
  4450. /**
  4451. * @returns The minimum node in the tree.
  4452. */
  4453. LLRBNode.prototype.min_ = function () {
  4454. if (this.left.isEmpty()) {
  4455. return this;
  4456. }
  4457. else {
  4458. return this.left.min_();
  4459. }
  4460. };
  4461. /**
  4462. * @returns The maximum key in the tree.
  4463. */
  4464. LLRBNode.prototype.minKey = function () {
  4465. return this.min_().key;
  4466. };
  4467. /**
  4468. * @returns The maximum key in the tree.
  4469. */
  4470. LLRBNode.prototype.maxKey = function () {
  4471. if (this.right.isEmpty()) {
  4472. return this.key;
  4473. }
  4474. else {
  4475. return this.right.maxKey();
  4476. }
  4477. };
  4478. /**
  4479. * @param key - Key to insert.
  4480. * @param value - Value to insert.
  4481. * @param comparator - Comparator.
  4482. * @returns New tree, with the key/value added.
  4483. */
  4484. LLRBNode.prototype.insert = function (key, value, comparator) {
  4485. var n = this;
  4486. var cmp = comparator(key, n.key);
  4487. if (cmp < 0) {
  4488. n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
  4489. }
  4490. else if (cmp === 0) {
  4491. n = n.copy(null, value, null, null, null);
  4492. }
  4493. else {
  4494. n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
  4495. }
  4496. return n.fixUp_();
  4497. };
  4498. /**
  4499. * @returns New tree, with the minimum key removed.
  4500. */
  4501. LLRBNode.prototype.removeMin_ = function () {
  4502. if (this.left.isEmpty()) {
  4503. return SortedMap.EMPTY_NODE;
  4504. }
  4505. var n = this;
  4506. if (!n.left.isRed_() && !n.left.left.isRed_()) {
  4507. n = n.moveRedLeft_();
  4508. }
  4509. n = n.copy(null, null, null, n.left.removeMin_(), null);
  4510. return n.fixUp_();
  4511. };
  4512. /**
  4513. * @param key - The key of the item to remove.
  4514. * @param comparator - Comparator.
  4515. * @returns New tree, with the specified item removed.
  4516. */
  4517. LLRBNode.prototype.remove = function (key, comparator) {
  4518. var n, smallest;
  4519. n = this;
  4520. if (comparator(key, n.key) < 0) {
  4521. if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
  4522. n = n.moveRedLeft_();
  4523. }
  4524. n = n.copy(null, null, null, n.left.remove(key, comparator), null);
  4525. }
  4526. else {
  4527. if (n.left.isRed_()) {
  4528. n = n.rotateRight_();
  4529. }
  4530. if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
  4531. n = n.moveRedRight_();
  4532. }
  4533. if (comparator(key, n.key) === 0) {
  4534. if (n.right.isEmpty()) {
  4535. return SortedMap.EMPTY_NODE;
  4536. }
  4537. else {
  4538. smallest = n.right.min_();
  4539. n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
  4540. }
  4541. }
  4542. n = n.copy(null, null, null, null, n.right.remove(key, comparator));
  4543. }
  4544. return n.fixUp_();
  4545. };
  4546. /**
  4547. * @returns Whether this is a RED node.
  4548. */
  4549. LLRBNode.prototype.isRed_ = function () {
  4550. return this.color;
  4551. };
  4552. /**
  4553. * @returns New tree after performing any needed rotations.
  4554. */
  4555. LLRBNode.prototype.fixUp_ = function () {
  4556. var n = this;
  4557. if (n.right.isRed_() && !n.left.isRed_()) {
  4558. n = n.rotateLeft_();
  4559. }
  4560. if (n.left.isRed_() && n.left.left.isRed_()) {
  4561. n = n.rotateRight_();
  4562. }
  4563. if (n.left.isRed_() && n.right.isRed_()) {
  4564. n = n.colorFlip_();
  4565. }
  4566. return n;
  4567. };
  4568. /**
  4569. * @returns New tree, after moveRedLeft.
  4570. */
  4571. LLRBNode.prototype.moveRedLeft_ = function () {
  4572. var n = this.colorFlip_();
  4573. if (n.right.left.isRed_()) {
  4574. n = n.copy(null, null, null, null, n.right.rotateRight_());
  4575. n = n.rotateLeft_();
  4576. n = n.colorFlip_();
  4577. }
  4578. return n;
  4579. };
  4580. /**
  4581. * @returns New tree, after moveRedRight.
  4582. */
  4583. LLRBNode.prototype.moveRedRight_ = function () {
  4584. var n = this.colorFlip_();
  4585. if (n.left.left.isRed_()) {
  4586. n = n.rotateRight_();
  4587. n = n.colorFlip_();
  4588. }
  4589. return n;
  4590. };
  4591. /**
  4592. * @returns New tree, after rotateLeft.
  4593. */
  4594. LLRBNode.prototype.rotateLeft_ = function () {
  4595. var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
  4596. return this.right.copy(null, null, this.color, nl, null);
  4597. };
  4598. /**
  4599. * @returns New tree, after rotateRight.
  4600. */
  4601. LLRBNode.prototype.rotateRight_ = function () {
  4602. var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
  4603. return this.left.copy(null, null, this.color, null, nr);
  4604. };
  4605. /**
  4606. * @returns Newt ree, after colorFlip.
  4607. */
  4608. LLRBNode.prototype.colorFlip_ = function () {
  4609. var left = this.left.copy(null, null, !this.left.color, null, null);
  4610. var right = this.right.copy(null, null, !this.right.color, null, null);
  4611. return this.copy(null, null, !this.color, left, right);
  4612. };
  4613. /**
  4614. * For testing.
  4615. *
  4616. * @returns True if all is well.
  4617. */
  4618. LLRBNode.prototype.checkMaxDepth_ = function () {
  4619. var blackDepth = this.check_();
  4620. return Math.pow(2.0, blackDepth) <= this.count() + 1;
  4621. };
  4622. LLRBNode.prototype.check_ = function () {
  4623. if (this.isRed_() && this.left.isRed_()) {
  4624. throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
  4625. }
  4626. if (this.right.isRed_()) {
  4627. throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
  4628. }
  4629. var blackDepth = this.left.check_();
  4630. if (blackDepth !== this.right.check_()) {
  4631. throw new Error('Black depths differ');
  4632. }
  4633. else {
  4634. return blackDepth + (this.isRed_() ? 0 : 1);
  4635. }
  4636. };
  4637. LLRBNode.RED = true;
  4638. LLRBNode.BLACK = false;
  4639. return LLRBNode;
  4640. }());
  4641. /**
  4642. * Represents an empty node (a leaf node in the Red-Black Tree).
  4643. */
  4644. var LLRBEmptyNode = /** @class */ (function () {
  4645. function LLRBEmptyNode() {
  4646. }
  4647. /**
  4648. * Returns a copy of the current node.
  4649. *
  4650. * @returns The node copy.
  4651. */
  4652. LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {
  4653. return this;
  4654. };
  4655. /**
  4656. * Returns a copy of the tree, with the specified key/value added.
  4657. *
  4658. * @param key - Key to be added.
  4659. * @param value - Value to be added.
  4660. * @param comparator - Comparator.
  4661. * @returns New tree, with item added.
  4662. */
  4663. LLRBEmptyNode.prototype.insert = function (key, value, comparator) {
  4664. return new LLRBNode(key, value, null);
  4665. };
  4666. /**
  4667. * Returns a copy of the tree, with the specified key removed.
  4668. *
  4669. * @param key - The key to remove.
  4670. * @param comparator - Comparator.
  4671. * @returns New tree, with item removed.
  4672. */
  4673. LLRBEmptyNode.prototype.remove = function (key, comparator) {
  4674. return this;
  4675. };
  4676. /**
  4677. * @returns The total number of nodes in the tree.
  4678. */
  4679. LLRBEmptyNode.prototype.count = function () {
  4680. return 0;
  4681. };
  4682. /**
  4683. * @returns True if the tree is empty.
  4684. */
  4685. LLRBEmptyNode.prototype.isEmpty = function () {
  4686. return true;
  4687. };
  4688. /**
  4689. * Traverses the tree in key order and calls the specified action function
  4690. * for each node.
  4691. *
  4692. * @param action - Callback function to be called for each
  4693. * node. If it returns true, traversal is aborted.
  4694. * @returns True if traversal was aborted.
  4695. */
  4696. LLRBEmptyNode.prototype.inorderTraversal = function (action) {
  4697. return false;
  4698. };
  4699. /**
  4700. * Traverses the tree in reverse key order and calls the specified action function
  4701. * for each node.
  4702. *
  4703. * @param action - Callback function to be called for each
  4704. * node. If it returns true, traversal is aborted.
  4705. * @returns True if traversal was aborted.
  4706. */
  4707. LLRBEmptyNode.prototype.reverseTraversal = function (action) {
  4708. return false;
  4709. };
  4710. LLRBEmptyNode.prototype.minKey = function () {
  4711. return null;
  4712. };
  4713. LLRBEmptyNode.prototype.maxKey = function () {
  4714. return null;
  4715. };
  4716. LLRBEmptyNode.prototype.check_ = function () {
  4717. return 0;
  4718. };
  4719. /**
  4720. * @returns Whether this node is red.
  4721. */
  4722. LLRBEmptyNode.prototype.isRed_ = function () {
  4723. return false;
  4724. };
  4725. return LLRBEmptyNode;
  4726. }());
  4727. /**
  4728. * An immutable sorted map implementation, based on a Left-leaning Red-Black
  4729. * tree.
  4730. */
  4731. var SortedMap = /** @class */ (function () {
  4732. /**
  4733. * @param comparator_ - Key comparator.
  4734. * @param root_ - Optional root node for the map.
  4735. */
  4736. function SortedMap(comparator_, root_) {
  4737. if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }
  4738. this.comparator_ = comparator_;
  4739. this.root_ = root_;
  4740. }
  4741. /**
  4742. * Returns a copy of the map, with the specified key/value added or replaced.
  4743. * (TODO: We should perhaps rename this method to 'put')
  4744. *
  4745. * @param key - Key to be added.
  4746. * @param value - Value to be added.
  4747. * @returns New map, with item added.
  4748. */
  4749. SortedMap.prototype.insert = function (key, value) {
  4750. return new SortedMap(this.comparator_, this.root_
  4751. .insert(key, value, this.comparator_)
  4752. .copy(null, null, LLRBNode.BLACK, null, null));
  4753. };
  4754. /**
  4755. * Returns a copy of the map, with the specified key removed.
  4756. *
  4757. * @param key - The key to remove.
  4758. * @returns New map, with item removed.
  4759. */
  4760. SortedMap.prototype.remove = function (key) {
  4761. return new SortedMap(this.comparator_, this.root_
  4762. .remove(key, this.comparator_)
  4763. .copy(null, null, LLRBNode.BLACK, null, null));
  4764. };
  4765. /**
  4766. * Returns the value of the node with the given key, or null.
  4767. *
  4768. * @param key - The key to look up.
  4769. * @returns The value of the node with the given key, or null if the
  4770. * key doesn't exist.
  4771. */
  4772. SortedMap.prototype.get = function (key) {
  4773. var cmp;
  4774. var node = this.root_;
  4775. while (!node.isEmpty()) {
  4776. cmp = this.comparator_(key, node.key);
  4777. if (cmp === 0) {
  4778. return node.value;
  4779. }
  4780. else if (cmp < 0) {
  4781. node = node.left;
  4782. }
  4783. else if (cmp > 0) {
  4784. node = node.right;
  4785. }
  4786. }
  4787. return null;
  4788. };
  4789. /**
  4790. * Returns the key of the item *before* the specified key, or null if key is the first item.
  4791. * @param key - The key to find the predecessor of
  4792. * @returns The predecessor key.
  4793. */
  4794. SortedMap.prototype.getPredecessorKey = function (key) {
  4795. var cmp, node = this.root_, rightParent = null;
  4796. while (!node.isEmpty()) {
  4797. cmp = this.comparator_(key, node.key);
  4798. if (cmp === 0) {
  4799. if (!node.left.isEmpty()) {
  4800. node = node.left;
  4801. while (!node.right.isEmpty()) {
  4802. node = node.right;
  4803. }
  4804. return node.key;
  4805. }
  4806. else if (rightParent) {
  4807. return rightParent.key;
  4808. }
  4809. else {
  4810. return null; // first item.
  4811. }
  4812. }
  4813. else if (cmp < 0) {
  4814. node = node.left;
  4815. }
  4816. else if (cmp > 0) {
  4817. rightParent = node;
  4818. node = node.right;
  4819. }
  4820. }
  4821. throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
  4822. };
  4823. /**
  4824. * @returns True if the map is empty.
  4825. */
  4826. SortedMap.prototype.isEmpty = function () {
  4827. return this.root_.isEmpty();
  4828. };
  4829. /**
  4830. * @returns The total number of nodes in the map.
  4831. */
  4832. SortedMap.prototype.count = function () {
  4833. return this.root_.count();
  4834. };
  4835. /**
  4836. * @returns The minimum key in the map.
  4837. */
  4838. SortedMap.prototype.minKey = function () {
  4839. return this.root_.minKey();
  4840. };
  4841. /**
  4842. * @returns The maximum key in the map.
  4843. */
  4844. SortedMap.prototype.maxKey = function () {
  4845. return this.root_.maxKey();
  4846. };
  4847. /**
  4848. * Traverses the map in key order and calls the specified action function
  4849. * for each key/value pair.
  4850. *
  4851. * @param action - Callback function to be called
  4852. * for each key/value pair. If action returns true, traversal is aborted.
  4853. * @returns The first truthy value returned by action, or the last falsey
  4854. * value returned by action
  4855. */
  4856. SortedMap.prototype.inorderTraversal = function (action) {
  4857. return this.root_.inorderTraversal(action);
  4858. };
  4859. /**
  4860. * Traverses the map in reverse key order and calls the specified action function
  4861. * for each key/value pair.
  4862. *
  4863. * @param action - Callback function to be called
  4864. * for each key/value pair. If action returns true, traversal is aborted.
  4865. * @returns True if the traversal was aborted.
  4866. */
  4867. SortedMap.prototype.reverseTraversal = function (action) {
  4868. return this.root_.reverseTraversal(action);
  4869. };
  4870. /**
  4871. * Returns an iterator over the SortedMap.
  4872. * @returns The iterator.
  4873. */
  4874. SortedMap.prototype.getIterator = function (resultGenerator) {
  4875. return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
  4876. };
  4877. SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {
  4878. return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
  4879. };
  4880. SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {
  4881. return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
  4882. };
  4883. SortedMap.prototype.getReverseIterator = function (resultGenerator) {
  4884. return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
  4885. };
  4886. /**
  4887. * Always use the same empty node, to reduce memory.
  4888. */
  4889. SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  4890. return SortedMap;
  4891. }());
  4892. /**
  4893. * @license
  4894. * Copyright 2017 Google LLC
  4895. *
  4896. * Licensed under the Apache License, Version 2.0 (the "License");
  4897. * you may not use this file except in compliance with the License.
  4898. * You may obtain a copy of the License at
  4899. *
  4900. * http://www.apache.org/licenses/LICENSE-2.0
  4901. *
  4902. * Unless required by applicable law or agreed to in writing, software
  4903. * distributed under the License is distributed on an "AS IS" BASIS,
  4904. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4905. * See the License for the specific language governing permissions and
  4906. * limitations under the License.
  4907. */
  4908. function NAME_ONLY_COMPARATOR(left, right) {
  4909. return nameCompare(left.name, right.name);
  4910. }
  4911. function NAME_COMPARATOR(left, right) {
  4912. return nameCompare(left, right);
  4913. }
  4914. /**
  4915. * @license
  4916. * Copyright 2017 Google LLC
  4917. *
  4918. * Licensed under the Apache License, Version 2.0 (the "License");
  4919. * you may not use this file except in compliance with the License.
  4920. * You may obtain a copy of the License at
  4921. *
  4922. * http://www.apache.org/licenses/LICENSE-2.0
  4923. *
  4924. * Unless required by applicable law or agreed to in writing, software
  4925. * distributed under the License is distributed on an "AS IS" BASIS,
  4926. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4927. * See the License for the specific language governing permissions and
  4928. * limitations under the License.
  4929. */
  4930. var MAX_NODE$2;
  4931. function setMaxNode$1(val) {
  4932. MAX_NODE$2 = val;
  4933. }
  4934. var priorityHashText = function (priority) {
  4935. if (typeof priority === 'number') {
  4936. return 'number:' + doubleToIEEE754String(priority);
  4937. }
  4938. else {
  4939. return 'string:' + priority;
  4940. }
  4941. };
  4942. /**
  4943. * Validates that a priority snapshot Node is valid.
  4944. */
  4945. var validatePriorityNode = function (priorityNode) {
  4946. if (priorityNode.isLeafNode()) {
  4947. var val = priorityNode.val();
  4948. util.assert(typeof val === 'string' ||
  4949. typeof val === 'number' ||
  4950. (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');
  4951. }
  4952. else {
  4953. util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
  4954. }
  4955. // Don't call getPriority() on MAX_NODE to avoid hitting assertion.
  4956. util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  4957. };
  4958. /**
  4959. * @license
  4960. * Copyright 2017 Google LLC
  4961. *
  4962. * Licensed under the Apache License, Version 2.0 (the "License");
  4963. * you may not use this file except in compliance with the License.
  4964. * You may obtain a copy of the License at
  4965. *
  4966. * http://www.apache.org/licenses/LICENSE-2.0
  4967. *
  4968. * Unless required by applicable law or agreed to in writing, software
  4969. * distributed under the License is distributed on an "AS IS" BASIS,
  4970. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  4971. * See the License for the specific language governing permissions and
  4972. * limitations under the License.
  4973. */
  4974. var __childrenNodeConstructor;
  4975. /**
  4976. * LeafNode is a class for storing leaf nodes in a DataSnapshot. It
  4977. * implements Node and stores the value of the node (a string,
  4978. * number, or boolean) accessible via getValue().
  4979. */
  4980. var LeafNode = /** @class */ (function () {
  4981. /**
  4982. * @param value_ - The value to store in this leaf node. The object type is
  4983. * possible in the event of a deferred value
  4984. * @param priorityNode_ - The priority of this node.
  4985. */
  4986. function LeafNode(value_, priorityNode_) {
  4987. if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }
  4988. this.value_ = value_;
  4989. this.priorityNode_ = priorityNode_;
  4990. this.lazyHash_ = null;
  4991. util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
  4992. validatePriorityNode(this.priorityNode_);
  4993. }
  4994. Object.defineProperty(LeafNode, "__childrenNodeConstructor", {
  4995. get: function () {
  4996. return __childrenNodeConstructor;
  4997. },
  4998. set: function (val) {
  4999. __childrenNodeConstructor = val;
  5000. },
  5001. enumerable: false,
  5002. configurable: true
  5003. });
  5004. /** @inheritDoc */
  5005. LeafNode.prototype.isLeafNode = function () {
  5006. return true;
  5007. };
  5008. /** @inheritDoc */
  5009. LeafNode.prototype.getPriority = function () {
  5010. return this.priorityNode_;
  5011. };
  5012. /** @inheritDoc */
  5013. LeafNode.prototype.updatePriority = function (newPriorityNode) {
  5014. return new LeafNode(this.value_, newPriorityNode);
  5015. };
  5016. /** @inheritDoc */
  5017. LeafNode.prototype.getImmediateChild = function (childName) {
  5018. // Hack to treat priority as a regular child
  5019. if (childName === '.priority') {
  5020. return this.priorityNode_;
  5021. }
  5022. else {
  5023. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5024. }
  5025. };
  5026. /** @inheritDoc */
  5027. LeafNode.prototype.getChild = function (path) {
  5028. if (pathIsEmpty(path)) {
  5029. return this;
  5030. }
  5031. else if (pathGetFront(path) === '.priority') {
  5032. return this.priorityNode_;
  5033. }
  5034. else {
  5035. return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
  5036. }
  5037. };
  5038. LeafNode.prototype.hasChild = function () {
  5039. return false;
  5040. };
  5041. /** @inheritDoc */
  5042. LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {
  5043. return null;
  5044. };
  5045. /** @inheritDoc */
  5046. LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5047. if (childName === '.priority') {
  5048. return this.updatePriority(newChildNode);
  5049. }
  5050. else if (newChildNode.isEmpty() && childName !== '.priority') {
  5051. return this;
  5052. }
  5053. else {
  5054. return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
  5055. }
  5056. };
  5057. /** @inheritDoc */
  5058. LeafNode.prototype.updateChild = function (path, newChildNode) {
  5059. var front = pathGetFront(path);
  5060. if (front === null) {
  5061. return newChildNode;
  5062. }
  5063. else if (newChildNode.isEmpty() && front !== '.priority') {
  5064. return this;
  5065. }
  5066. else {
  5067. util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5068. return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
  5069. }
  5070. };
  5071. /** @inheritDoc */
  5072. LeafNode.prototype.isEmpty = function () {
  5073. return false;
  5074. };
  5075. /** @inheritDoc */
  5076. LeafNode.prototype.numChildren = function () {
  5077. return 0;
  5078. };
  5079. /** @inheritDoc */
  5080. LeafNode.prototype.forEachChild = function (index, action) {
  5081. return false;
  5082. };
  5083. LeafNode.prototype.val = function (exportFormat) {
  5084. if (exportFormat && !this.getPriority().isEmpty()) {
  5085. return {
  5086. '.value': this.getValue(),
  5087. '.priority': this.getPriority().val()
  5088. };
  5089. }
  5090. else {
  5091. return this.getValue();
  5092. }
  5093. };
  5094. /** @inheritDoc */
  5095. LeafNode.prototype.hash = function () {
  5096. if (this.lazyHash_ === null) {
  5097. var toHash = '';
  5098. if (!this.priorityNode_.isEmpty()) {
  5099. toHash +=
  5100. 'priority:' +
  5101. priorityHashText(this.priorityNode_.val()) +
  5102. ':';
  5103. }
  5104. var type = typeof this.value_;
  5105. toHash += type + ':';
  5106. if (type === 'number') {
  5107. toHash += doubleToIEEE754String(this.value_);
  5108. }
  5109. else {
  5110. toHash += this.value_;
  5111. }
  5112. this.lazyHash_ = sha1(toHash);
  5113. }
  5114. return this.lazyHash_;
  5115. };
  5116. /**
  5117. * Returns the value of the leaf node.
  5118. * @returns The value of the node.
  5119. */
  5120. LeafNode.prototype.getValue = function () {
  5121. return this.value_;
  5122. };
  5123. LeafNode.prototype.compareTo = function (other) {
  5124. if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
  5125. return 1;
  5126. }
  5127. else if (other instanceof LeafNode.__childrenNodeConstructor) {
  5128. return -1;
  5129. }
  5130. else {
  5131. util.assert(other.isLeafNode(), 'Unknown node type');
  5132. return this.compareToLeafNode_(other);
  5133. }
  5134. };
  5135. /**
  5136. * Comparison specifically for two leaf nodes
  5137. */
  5138. LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {
  5139. var otherLeafType = typeof otherLeaf.value_;
  5140. var thisLeafType = typeof this.value_;
  5141. var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
  5142. var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
  5143. util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
  5144. util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
  5145. if (otherIndex === thisIndex) {
  5146. // Same type, compare values
  5147. if (thisLeafType === 'object') {
  5148. // Deferred value nodes are all equal, but we should also never get to this point...
  5149. return 0;
  5150. }
  5151. else {
  5152. // Note that this works because true > false, all others are number or string comparisons
  5153. if (this.value_ < otherLeaf.value_) {
  5154. return -1;
  5155. }
  5156. else if (this.value_ === otherLeaf.value_) {
  5157. return 0;
  5158. }
  5159. else {
  5160. return 1;
  5161. }
  5162. }
  5163. }
  5164. else {
  5165. return thisIndex - otherIndex;
  5166. }
  5167. };
  5168. LeafNode.prototype.withIndex = function () {
  5169. return this;
  5170. };
  5171. LeafNode.prototype.isIndexed = function () {
  5172. return true;
  5173. };
  5174. LeafNode.prototype.equals = function (other) {
  5175. if (other === this) {
  5176. return true;
  5177. }
  5178. else if (other.isLeafNode()) {
  5179. var otherLeaf = other;
  5180. return (this.value_ === otherLeaf.value_ &&
  5181. this.priorityNode_.equals(otherLeaf.priorityNode_));
  5182. }
  5183. else {
  5184. return false;
  5185. }
  5186. };
  5187. /**
  5188. * The sort order for comparing leaf nodes of different types. If two leaf nodes have
  5189. * the same type, the comparison falls back to their value
  5190. */
  5191. LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
  5192. return LeafNode;
  5193. }());
  5194. /**
  5195. * @license
  5196. * Copyright 2017 Google LLC
  5197. *
  5198. * Licensed under the Apache License, Version 2.0 (the "License");
  5199. * you may not use this file except in compliance with the License.
  5200. * You may obtain a copy of the License at
  5201. *
  5202. * http://www.apache.org/licenses/LICENSE-2.0
  5203. *
  5204. * Unless required by applicable law or agreed to in writing, software
  5205. * distributed under the License is distributed on an "AS IS" BASIS,
  5206. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5207. * See the License for the specific language governing permissions and
  5208. * limitations under the License.
  5209. */
  5210. var nodeFromJSON$1;
  5211. var MAX_NODE$1;
  5212. function setNodeFromJSON(val) {
  5213. nodeFromJSON$1 = val;
  5214. }
  5215. function setMaxNode(val) {
  5216. MAX_NODE$1 = val;
  5217. }
  5218. var PriorityIndex = /** @class */ (function (_super) {
  5219. tslib.__extends(PriorityIndex, _super);
  5220. function PriorityIndex() {
  5221. return _super !== null && _super.apply(this, arguments) || this;
  5222. }
  5223. PriorityIndex.prototype.compare = function (a, b) {
  5224. var aPriority = a.node.getPriority();
  5225. var bPriority = b.node.getPriority();
  5226. var indexCmp = aPriority.compareTo(bPriority);
  5227. if (indexCmp === 0) {
  5228. return nameCompare(a.name, b.name);
  5229. }
  5230. else {
  5231. return indexCmp;
  5232. }
  5233. };
  5234. PriorityIndex.prototype.isDefinedOn = function (node) {
  5235. return !node.getPriority().isEmpty();
  5236. };
  5237. PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  5238. return !oldNode.getPriority().equals(newNode.getPriority());
  5239. };
  5240. PriorityIndex.prototype.minPost = function () {
  5241. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5242. return NamedNode.MIN;
  5243. };
  5244. PriorityIndex.prototype.maxPost = function () {
  5245. return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
  5246. };
  5247. PriorityIndex.prototype.makePost = function (indexValue, name) {
  5248. var priorityNode = nodeFromJSON$1(indexValue);
  5249. return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
  5250. };
  5251. /**
  5252. * @returns String representation for inclusion in a query spec
  5253. */
  5254. PriorityIndex.prototype.toString = function () {
  5255. return '.priority';
  5256. };
  5257. return PriorityIndex;
  5258. }(Index));
  5259. var PRIORITY_INDEX = new PriorityIndex();
  5260. /**
  5261. * @license
  5262. * Copyright 2017 Google LLC
  5263. *
  5264. * Licensed under the Apache License, Version 2.0 (the "License");
  5265. * you may not use this file except in compliance with the License.
  5266. * You may obtain a copy of the License at
  5267. *
  5268. * http://www.apache.org/licenses/LICENSE-2.0
  5269. *
  5270. * Unless required by applicable law or agreed to in writing, software
  5271. * distributed under the License is distributed on an "AS IS" BASIS,
  5272. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5273. * See the License for the specific language governing permissions and
  5274. * limitations under the License.
  5275. */
  5276. var LOG_2 = Math.log(2);
  5277. var Base12Num = /** @class */ (function () {
  5278. function Base12Num(length) {
  5279. var logBase2 = function (num) {
  5280. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5281. return parseInt((Math.log(num) / LOG_2), 10);
  5282. };
  5283. var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };
  5284. this.count = logBase2(length + 1);
  5285. this.current_ = this.count - 1;
  5286. var mask = bitMask(this.count);
  5287. this.bits_ = (length + 1) & mask;
  5288. }
  5289. Base12Num.prototype.nextBitIsOne = function () {
  5290. //noinspection JSBitwiseOperatorUsage
  5291. var result = !(this.bits_ & (0x1 << this.current_));
  5292. this.current_--;
  5293. return result;
  5294. };
  5295. return Base12Num;
  5296. }());
  5297. /**
  5298. * Takes a list of child nodes and constructs a SortedSet using the given comparison
  5299. * function
  5300. *
  5301. * Uses the algorithm described in the paper linked here:
  5302. * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458
  5303. *
  5304. * @param childList - Unsorted list of children
  5305. * @param cmp - The comparison method to be used
  5306. * @param keyFn - An optional function to extract K from a node wrapper, if K's
  5307. * type is not NamedNode
  5308. * @param mapSortFn - An optional override for comparator used by the generated sorted map
  5309. */
  5310. var buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
  5311. childList.sort(cmp);
  5312. var buildBalancedTree = function (low, high) {
  5313. var length = high - low;
  5314. var namedNode;
  5315. var key;
  5316. if (length === 0) {
  5317. return null;
  5318. }
  5319. else if (length === 1) {
  5320. namedNode = childList[low];
  5321. key = keyFn ? keyFn(namedNode) : namedNode;
  5322. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
  5323. }
  5324. else {
  5325. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5326. var middle = parseInt((length / 2), 10) + low;
  5327. var left = buildBalancedTree(low, middle);
  5328. var right = buildBalancedTree(middle + 1, high);
  5329. namedNode = childList[middle];
  5330. key = keyFn ? keyFn(namedNode) : namedNode;
  5331. return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
  5332. }
  5333. };
  5334. var buildFrom12Array = function (base12) {
  5335. var node = null;
  5336. var root = null;
  5337. var index = childList.length;
  5338. var buildPennant = function (chunkSize, color) {
  5339. var low = index - chunkSize;
  5340. var high = index;
  5341. index -= chunkSize;
  5342. var childTree = buildBalancedTree(low + 1, high);
  5343. var namedNode = childList[low];
  5344. var key = keyFn ? keyFn(namedNode) : namedNode;
  5345. attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
  5346. };
  5347. var attachPennant = function (pennant) {
  5348. if (node) {
  5349. node.left = pennant;
  5350. node = pennant;
  5351. }
  5352. else {
  5353. root = pennant;
  5354. node = pennant;
  5355. }
  5356. };
  5357. for (var i = 0; i < base12.count; ++i) {
  5358. var isOne = base12.nextBitIsOne();
  5359. // The number of nodes taken in each slice is 2^(arr.length - (i + 1))
  5360. var chunkSize = Math.pow(2, base12.count - (i + 1));
  5361. if (isOne) {
  5362. buildPennant(chunkSize, LLRBNode.BLACK);
  5363. }
  5364. else {
  5365. // current == 2
  5366. buildPennant(chunkSize, LLRBNode.BLACK);
  5367. buildPennant(chunkSize, LLRBNode.RED);
  5368. }
  5369. }
  5370. return root;
  5371. };
  5372. var base12 = new Base12Num(childList.length);
  5373. var root = buildFrom12Array(base12);
  5374. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  5375. return new SortedMap(mapSortFn || cmp, root);
  5376. };
  5377. /**
  5378. * @license
  5379. * Copyright 2017 Google LLC
  5380. *
  5381. * Licensed under the Apache License, Version 2.0 (the "License");
  5382. * you may not use this file except in compliance with the License.
  5383. * You may obtain a copy of the License at
  5384. *
  5385. * http://www.apache.org/licenses/LICENSE-2.0
  5386. *
  5387. * Unless required by applicable law or agreed to in writing, software
  5388. * distributed under the License is distributed on an "AS IS" BASIS,
  5389. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5390. * See the License for the specific language governing permissions and
  5391. * limitations under the License.
  5392. */
  5393. var _defaultIndexMap;
  5394. var fallbackObject = {};
  5395. var IndexMap = /** @class */ (function () {
  5396. function IndexMap(indexes_, indexSet_) {
  5397. this.indexes_ = indexes_;
  5398. this.indexSet_ = indexSet_;
  5399. }
  5400. Object.defineProperty(IndexMap, "Default", {
  5401. /**
  5402. * The default IndexMap for nodes without a priority
  5403. */
  5404. get: function () {
  5405. util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
  5406. _defaultIndexMap =
  5407. _defaultIndexMap ||
  5408. new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
  5409. return _defaultIndexMap;
  5410. },
  5411. enumerable: false,
  5412. configurable: true
  5413. });
  5414. IndexMap.prototype.get = function (indexKey) {
  5415. var sortedMap = util.safeGet(this.indexes_, indexKey);
  5416. if (!sortedMap) {
  5417. throw new Error('No index defined for ' + indexKey);
  5418. }
  5419. if (sortedMap instanceof SortedMap) {
  5420. return sortedMap;
  5421. }
  5422. else {
  5423. // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the
  5424. // regular child map
  5425. return null;
  5426. }
  5427. };
  5428. IndexMap.prototype.hasIndex = function (indexDefinition) {
  5429. return util.contains(this.indexSet_, indexDefinition.toString());
  5430. };
  5431. IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {
  5432. util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
  5433. var childList = [];
  5434. var sawIndexedValue = false;
  5435. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5436. var next = iter.getNext();
  5437. while (next) {
  5438. sawIndexedValue =
  5439. sawIndexedValue || indexDefinition.isDefinedOn(next.node);
  5440. childList.push(next);
  5441. next = iter.getNext();
  5442. }
  5443. var newIndex;
  5444. if (sawIndexedValue) {
  5445. newIndex = buildChildSet(childList, indexDefinition.getCompare());
  5446. }
  5447. else {
  5448. newIndex = fallbackObject;
  5449. }
  5450. var indexName = indexDefinition.toString();
  5451. var newIndexSet = tslib.__assign({}, this.indexSet_);
  5452. newIndexSet[indexName] = indexDefinition;
  5453. var newIndexes = tslib.__assign({}, this.indexes_);
  5454. newIndexes[indexName] = newIndex;
  5455. return new IndexMap(newIndexes, newIndexSet);
  5456. };
  5457. /**
  5458. * Ensure that this node is properly tracked in any indexes that we're maintaining
  5459. */
  5460. IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {
  5461. var _this = this;
  5462. var newIndexes = util.map(this.indexes_, function (indexedChildren, indexName) {
  5463. var index = util.safeGet(_this.indexSet_, indexName);
  5464. util.assert(index, 'Missing index implementation for ' + indexName);
  5465. if (indexedChildren === fallbackObject) {
  5466. // Check to see if we need to index everything
  5467. if (index.isDefinedOn(namedNode.node)) {
  5468. // We need to build this index
  5469. var childList = [];
  5470. var iter = existingChildren.getIterator(NamedNode.Wrap);
  5471. var next = iter.getNext();
  5472. while (next) {
  5473. if (next.name !== namedNode.name) {
  5474. childList.push(next);
  5475. }
  5476. next = iter.getNext();
  5477. }
  5478. childList.push(namedNode);
  5479. return buildChildSet(childList, index.getCompare());
  5480. }
  5481. else {
  5482. // No change, this remains a fallback
  5483. return fallbackObject;
  5484. }
  5485. }
  5486. else {
  5487. var existingSnap = existingChildren.get(namedNode.name);
  5488. var newChildren = indexedChildren;
  5489. if (existingSnap) {
  5490. newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5491. }
  5492. return newChildren.insert(namedNode, namedNode.node);
  5493. }
  5494. });
  5495. return new IndexMap(newIndexes, this.indexSet_);
  5496. };
  5497. /**
  5498. * Create a new IndexMap instance with the given value removed
  5499. */
  5500. IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {
  5501. var newIndexes = util.map(this.indexes_, function (indexedChildren) {
  5502. if (indexedChildren === fallbackObject) {
  5503. // This is the fallback. Just return it, nothing to do in this case
  5504. return indexedChildren;
  5505. }
  5506. else {
  5507. var existingSnap = existingChildren.get(namedNode.name);
  5508. if (existingSnap) {
  5509. return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
  5510. }
  5511. else {
  5512. // No record of this child
  5513. return indexedChildren;
  5514. }
  5515. }
  5516. });
  5517. return new IndexMap(newIndexes, this.indexSet_);
  5518. };
  5519. return IndexMap;
  5520. }());
  5521. /**
  5522. * @license
  5523. * Copyright 2017 Google LLC
  5524. *
  5525. * Licensed under the Apache License, Version 2.0 (the "License");
  5526. * you may not use this file except in compliance with the License.
  5527. * You may obtain a copy of the License at
  5528. *
  5529. * http://www.apache.org/licenses/LICENSE-2.0
  5530. *
  5531. * Unless required by applicable law or agreed to in writing, software
  5532. * distributed under the License is distributed on an "AS IS" BASIS,
  5533. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5534. * See the License for the specific language governing permissions and
  5535. * limitations under the License.
  5536. */
  5537. // TODO: For memory savings, don't store priorityNode_ if it's empty.
  5538. var EMPTY_NODE;
  5539. /**
  5540. * ChildrenNode is a class for storing internal nodes in a DataSnapshot
  5541. * (i.e. nodes with children). It implements Node and stores the
  5542. * list of children in the children property, sorted by child name.
  5543. */
  5544. var ChildrenNode = /** @class */ (function () {
  5545. /**
  5546. * @param children_ - List of children of this node..
  5547. * @param priorityNode_ - The priority of this node (as a snapshot node).
  5548. */
  5549. function ChildrenNode(children_, priorityNode_, indexMap_) {
  5550. this.children_ = children_;
  5551. this.priorityNode_ = priorityNode_;
  5552. this.indexMap_ = indexMap_;
  5553. this.lazyHash_ = null;
  5554. /**
  5555. * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use
  5556. * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own
  5557. * class instead of an empty ChildrenNode.
  5558. */
  5559. if (this.priorityNode_) {
  5560. validatePriorityNode(this.priorityNode_);
  5561. }
  5562. if (this.children_.isEmpty()) {
  5563. util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
  5564. }
  5565. }
  5566. Object.defineProperty(ChildrenNode, "EMPTY_NODE", {
  5567. get: function () {
  5568. return (EMPTY_NODE ||
  5569. (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
  5570. },
  5571. enumerable: false,
  5572. configurable: true
  5573. });
  5574. /** @inheritDoc */
  5575. ChildrenNode.prototype.isLeafNode = function () {
  5576. return false;
  5577. };
  5578. /** @inheritDoc */
  5579. ChildrenNode.prototype.getPriority = function () {
  5580. return this.priorityNode_ || EMPTY_NODE;
  5581. };
  5582. /** @inheritDoc */
  5583. ChildrenNode.prototype.updatePriority = function (newPriorityNode) {
  5584. if (this.children_.isEmpty()) {
  5585. // Don't allow priorities on empty nodes
  5586. return this;
  5587. }
  5588. else {
  5589. return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
  5590. }
  5591. };
  5592. /** @inheritDoc */
  5593. ChildrenNode.prototype.getImmediateChild = function (childName) {
  5594. // Hack to treat priority as a regular child
  5595. if (childName === '.priority') {
  5596. return this.getPriority();
  5597. }
  5598. else {
  5599. var child = this.children_.get(childName);
  5600. return child === null ? EMPTY_NODE : child;
  5601. }
  5602. };
  5603. /** @inheritDoc */
  5604. ChildrenNode.prototype.getChild = function (path) {
  5605. var front = pathGetFront(path);
  5606. if (front === null) {
  5607. return this;
  5608. }
  5609. return this.getImmediateChild(front).getChild(pathPopFront(path));
  5610. };
  5611. /** @inheritDoc */
  5612. ChildrenNode.prototype.hasChild = function (childName) {
  5613. return this.children_.get(childName) !== null;
  5614. };
  5615. /** @inheritDoc */
  5616. ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {
  5617. util.assert(newChildNode, 'We should always be passing snapshot nodes');
  5618. if (childName === '.priority') {
  5619. return this.updatePriority(newChildNode);
  5620. }
  5621. else {
  5622. var namedNode = new NamedNode(childName, newChildNode);
  5623. var newChildren = void 0, newIndexMap = void 0;
  5624. if (newChildNode.isEmpty()) {
  5625. newChildren = this.children_.remove(childName);
  5626. newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
  5627. }
  5628. else {
  5629. newChildren = this.children_.insert(childName, newChildNode);
  5630. newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
  5631. }
  5632. var newPriority = newChildren.isEmpty()
  5633. ? EMPTY_NODE
  5634. : this.priorityNode_;
  5635. return new ChildrenNode(newChildren, newPriority, newIndexMap);
  5636. }
  5637. };
  5638. /** @inheritDoc */
  5639. ChildrenNode.prototype.updateChild = function (path, newChildNode) {
  5640. var front = pathGetFront(path);
  5641. if (front === null) {
  5642. return newChildNode;
  5643. }
  5644. else {
  5645. util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
  5646. var newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
  5647. return this.updateImmediateChild(front, newImmediateChild);
  5648. }
  5649. };
  5650. /** @inheritDoc */
  5651. ChildrenNode.prototype.isEmpty = function () {
  5652. return this.children_.isEmpty();
  5653. };
  5654. /** @inheritDoc */
  5655. ChildrenNode.prototype.numChildren = function () {
  5656. return this.children_.count();
  5657. };
  5658. /** @inheritDoc */
  5659. ChildrenNode.prototype.val = function (exportFormat) {
  5660. if (this.isEmpty()) {
  5661. return null;
  5662. }
  5663. var obj = {};
  5664. var numKeys = 0, maxKey = 0, allIntegerKeys = true;
  5665. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5666. obj[key] = childNode.val(exportFormat);
  5667. numKeys++;
  5668. if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
  5669. maxKey = Math.max(maxKey, Number(key));
  5670. }
  5671. else {
  5672. allIntegerKeys = false;
  5673. }
  5674. });
  5675. if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
  5676. // convert to array.
  5677. var array = [];
  5678. // eslint-disable-next-line guard-for-in
  5679. for (var key in obj) {
  5680. array[key] = obj[key];
  5681. }
  5682. return array;
  5683. }
  5684. else {
  5685. if (exportFormat && !this.getPriority().isEmpty()) {
  5686. obj['.priority'] = this.getPriority().val();
  5687. }
  5688. return obj;
  5689. }
  5690. };
  5691. /** @inheritDoc */
  5692. ChildrenNode.prototype.hash = function () {
  5693. if (this.lazyHash_ === null) {
  5694. var toHash_1 = '';
  5695. if (!this.getPriority().isEmpty()) {
  5696. toHash_1 +=
  5697. 'priority:' +
  5698. priorityHashText(this.getPriority().val()) +
  5699. ':';
  5700. }
  5701. this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  5702. var childHash = childNode.hash();
  5703. if (childHash !== '') {
  5704. toHash_1 += ':' + key + ':' + childHash;
  5705. }
  5706. });
  5707. this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1);
  5708. }
  5709. return this.lazyHash_;
  5710. };
  5711. /** @inheritDoc */
  5712. ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {
  5713. var idx = this.resolveIndex_(index);
  5714. if (idx) {
  5715. var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
  5716. return predecessor ? predecessor.name : null;
  5717. }
  5718. else {
  5719. return this.children_.getPredecessorKey(childName);
  5720. }
  5721. };
  5722. ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {
  5723. var idx = this.resolveIndex_(indexDefinition);
  5724. if (idx) {
  5725. var minKey = idx.minKey();
  5726. return minKey && minKey.name;
  5727. }
  5728. else {
  5729. return this.children_.minKey();
  5730. }
  5731. };
  5732. ChildrenNode.prototype.getFirstChild = function (indexDefinition) {
  5733. var minKey = this.getFirstChildName(indexDefinition);
  5734. if (minKey) {
  5735. return new NamedNode(minKey, this.children_.get(minKey));
  5736. }
  5737. else {
  5738. return null;
  5739. }
  5740. };
  5741. /**
  5742. * Given an index, return the key name of the largest value we have, according to that index
  5743. */
  5744. ChildrenNode.prototype.getLastChildName = function (indexDefinition) {
  5745. var idx = this.resolveIndex_(indexDefinition);
  5746. if (idx) {
  5747. var maxKey = idx.maxKey();
  5748. return maxKey && maxKey.name;
  5749. }
  5750. else {
  5751. return this.children_.maxKey();
  5752. }
  5753. };
  5754. ChildrenNode.prototype.getLastChild = function (indexDefinition) {
  5755. var maxKey = this.getLastChildName(indexDefinition);
  5756. if (maxKey) {
  5757. return new NamedNode(maxKey, this.children_.get(maxKey));
  5758. }
  5759. else {
  5760. return null;
  5761. }
  5762. };
  5763. ChildrenNode.prototype.forEachChild = function (index, action) {
  5764. var idx = this.resolveIndex_(index);
  5765. if (idx) {
  5766. return idx.inorderTraversal(function (wrappedNode) {
  5767. return action(wrappedNode.name, wrappedNode.node);
  5768. });
  5769. }
  5770. else {
  5771. return this.children_.inorderTraversal(action);
  5772. }
  5773. };
  5774. ChildrenNode.prototype.getIterator = function (indexDefinition) {
  5775. return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
  5776. };
  5777. ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {
  5778. var idx = this.resolveIndex_(indexDefinition);
  5779. if (idx) {
  5780. return idx.getIteratorFrom(startPost, function (key) { return key; });
  5781. }
  5782. else {
  5783. var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
  5784. var next = iterator.peek();
  5785. while (next != null && indexDefinition.compare(next, startPost) < 0) {
  5786. iterator.getNext();
  5787. next = iterator.peek();
  5788. }
  5789. return iterator;
  5790. }
  5791. };
  5792. ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {
  5793. return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
  5794. };
  5795. ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {
  5796. var idx = this.resolveIndex_(indexDefinition);
  5797. if (idx) {
  5798. return idx.getReverseIteratorFrom(endPost, function (key) {
  5799. return key;
  5800. });
  5801. }
  5802. else {
  5803. var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
  5804. var next = iterator.peek();
  5805. while (next != null && indexDefinition.compare(next, endPost) > 0) {
  5806. iterator.getNext();
  5807. next = iterator.peek();
  5808. }
  5809. return iterator;
  5810. }
  5811. };
  5812. ChildrenNode.prototype.compareTo = function (other) {
  5813. if (this.isEmpty()) {
  5814. if (other.isEmpty()) {
  5815. return 0;
  5816. }
  5817. else {
  5818. return -1;
  5819. }
  5820. }
  5821. else if (other.isLeafNode() || other.isEmpty()) {
  5822. return 1;
  5823. }
  5824. else if (other === MAX_NODE) {
  5825. return -1;
  5826. }
  5827. else {
  5828. // Must be another node with children.
  5829. return 0;
  5830. }
  5831. };
  5832. ChildrenNode.prototype.withIndex = function (indexDefinition) {
  5833. if (indexDefinition === KEY_INDEX ||
  5834. this.indexMap_.hasIndex(indexDefinition)) {
  5835. return this;
  5836. }
  5837. else {
  5838. var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
  5839. return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
  5840. }
  5841. };
  5842. ChildrenNode.prototype.isIndexed = function (index) {
  5843. return index === KEY_INDEX || this.indexMap_.hasIndex(index);
  5844. };
  5845. ChildrenNode.prototype.equals = function (other) {
  5846. if (other === this) {
  5847. return true;
  5848. }
  5849. else if (other.isLeafNode()) {
  5850. return false;
  5851. }
  5852. else {
  5853. var otherChildrenNode = other;
  5854. if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
  5855. return false;
  5856. }
  5857. else if (this.children_.count() === otherChildrenNode.children_.count()) {
  5858. var thisIter = this.getIterator(PRIORITY_INDEX);
  5859. var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
  5860. var thisCurrent = thisIter.getNext();
  5861. var otherCurrent = otherIter.getNext();
  5862. while (thisCurrent && otherCurrent) {
  5863. if (thisCurrent.name !== otherCurrent.name ||
  5864. !thisCurrent.node.equals(otherCurrent.node)) {
  5865. return false;
  5866. }
  5867. thisCurrent = thisIter.getNext();
  5868. otherCurrent = otherIter.getNext();
  5869. }
  5870. return thisCurrent === null && otherCurrent === null;
  5871. }
  5872. else {
  5873. return false;
  5874. }
  5875. }
  5876. };
  5877. /**
  5878. * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
  5879. * instead.
  5880. *
  5881. */
  5882. ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {
  5883. if (indexDefinition === KEY_INDEX) {
  5884. return null;
  5885. }
  5886. else {
  5887. return this.indexMap_.get(indexDefinition.toString());
  5888. }
  5889. };
  5890. ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  5891. return ChildrenNode;
  5892. }());
  5893. var MaxNode = /** @class */ (function (_super) {
  5894. tslib.__extends(MaxNode, _super);
  5895. function MaxNode() {
  5896. return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this;
  5897. }
  5898. MaxNode.prototype.compareTo = function (other) {
  5899. if (other === this) {
  5900. return 0;
  5901. }
  5902. else {
  5903. return 1;
  5904. }
  5905. };
  5906. MaxNode.prototype.equals = function (other) {
  5907. // Not that we every compare it, but MAX_NODE is only ever equal to itself
  5908. return other === this;
  5909. };
  5910. MaxNode.prototype.getPriority = function () {
  5911. return this;
  5912. };
  5913. MaxNode.prototype.getImmediateChild = function (childName) {
  5914. return ChildrenNode.EMPTY_NODE;
  5915. };
  5916. MaxNode.prototype.isEmpty = function () {
  5917. return false;
  5918. };
  5919. return MaxNode;
  5920. }(ChildrenNode));
  5921. /**
  5922. * Marker that will sort higher than any other snapshot.
  5923. */
  5924. var MAX_NODE = new MaxNode();
  5925. Object.defineProperties(NamedNode, {
  5926. MIN: {
  5927. value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
  5928. },
  5929. MAX: {
  5930. value: new NamedNode(MAX_NAME, MAX_NODE)
  5931. }
  5932. });
  5933. /**
  5934. * Reference Extensions
  5935. */
  5936. KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  5937. LeafNode.__childrenNodeConstructor = ChildrenNode;
  5938. setMaxNode$1(MAX_NODE);
  5939. setMaxNode(MAX_NODE);
  5940. /**
  5941. * @license
  5942. * Copyright 2017 Google LLC
  5943. *
  5944. * Licensed under the Apache License, Version 2.0 (the "License");
  5945. * you may not use this file except in compliance with the License.
  5946. * You may obtain a copy of the License at
  5947. *
  5948. * http://www.apache.org/licenses/LICENSE-2.0
  5949. *
  5950. * Unless required by applicable law or agreed to in writing, software
  5951. * distributed under the License is distributed on an "AS IS" BASIS,
  5952. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  5953. * See the License for the specific language governing permissions and
  5954. * limitations under the License.
  5955. */
  5956. var USE_HINZE = true;
  5957. /**
  5958. * Constructs a snapshot node representing the passed JSON and returns it.
  5959. * @param json - JSON to create a node for.
  5960. * @param priority - Optional priority to use. This will be ignored if the
  5961. * passed JSON contains a .priority property.
  5962. */
  5963. function nodeFromJSON(json, priority) {
  5964. if (priority === void 0) { priority = null; }
  5965. if (json === null) {
  5966. return ChildrenNode.EMPTY_NODE;
  5967. }
  5968. if (typeof json === 'object' && '.priority' in json) {
  5969. priority = json['.priority'];
  5970. }
  5971. util.assert(priority === null ||
  5972. typeof priority === 'string' ||
  5973. typeof priority === 'number' ||
  5974. (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
  5975. if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
  5976. json = json['.value'];
  5977. }
  5978. // Valid leaf nodes include non-objects or server-value wrapper objects
  5979. if (typeof json !== 'object' || '.sv' in json) {
  5980. var jsonLeaf = json;
  5981. return new LeafNode(jsonLeaf, nodeFromJSON(priority));
  5982. }
  5983. if (!(json instanceof Array) && USE_HINZE) {
  5984. var children_1 = [];
  5985. var childrenHavePriority_1 = false;
  5986. var hinzeJsonObj = json;
  5987. each(hinzeJsonObj, function (key, child) {
  5988. if (key.substring(0, 1) !== '.') {
  5989. // Ignore metadata nodes
  5990. var childNode = nodeFromJSON(child);
  5991. if (!childNode.isEmpty()) {
  5992. childrenHavePriority_1 =
  5993. childrenHavePriority_1 || !childNode.getPriority().isEmpty();
  5994. children_1.push(new NamedNode(key, childNode));
  5995. }
  5996. }
  5997. });
  5998. if (children_1.length === 0) {
  5999. return ChildrenNode.EMPTY_NODE;
  6000. }
  6001. var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR);
  6002. if (childrenHavePriority_1) {
  6003. var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare());
  6004. return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
  6005. }
  6006. else {
  6007. return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
  6008. }
  6009. }
  6010. else {
  6011. var node_1 = ChildrenNode.EMPTY_NODE;
  6012. each(json, function (key, childData) {
  6013. if (util.contains(json, key)) {
  6014. if (key.substring(0, 1) !== '.') {
  6015. // ignore metadata nodes.
  6016. var childNode = nodeFromJSON(childData);
  6017. if (childNode.isLeafNode() || !childNode.isEmpty()) {
  6018. node_1 = node_1.updateImmediateChild(key, childNode);
  6019. }
  6020. }
  6021. }
  6022. });
  6023. return node_1.updatePriority(nodeFromJSON(priority));
  6024. }
  6025. }
  6026. setNodeFromJSON(nodeFromJSON);
  6027. /**
  6028. * @license
  6029. * Copyright 2017 Google LLC
  6030. *
  6031. * Licensed under the Apache License, Version 2.0 (the "License");
  6032. * you may not use this file except in compliance with the License.
  6033. * You may obtain a copy of the License at
  6034. *
  6035. * http://www.apache.org/licenses/LICENSE-2.0
  6036. *
  6037. * Unless required by applicable law or agreed to in writing, software
  6038. * distributed under the License is distributed on an "AS IS" BASIS,
  6039. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6040. * See the License for the specific language governing permissions and
  6041. * limitations under the License.
  6042. */
  6043. var PathIndex = /** @class */ (function (_super) {
  6044. tslib.__extends(PathIndex, _super);
  6045. function PathIndex(indexPath_) {
  6046. var _this = _super.call(this) || this;
  6047. _this.indexPath_ = indexPath_;
  6048. util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
  6049. return _this;
  6050. }
  6051. PathIndex.prototype.extractChild = function (snap) {
  6052. return snap.getChild(this.indexPath_);
  6053. };
  6054. PathIndex.prototype.isDefinedOn = function (node) {
  6055. return !node.getChild(this.indexPath_).isEmpty();
  6056. };
  6057. PathIndex.prototype.compare = function (a, b) {
  6058. var aChild = this.extractChild(a.node);
  6059. var bChild = this.extractChild(b.node);
  6060. var indexCmp = aChild.compareTo(bChild);
  6061. if (indexCmp === 0) {
  6062. return nameCompare(a.name, b.name);
  6063. }
  6064. else {
  6065. return indexCmp;
  6066. }
  6067. };
  6068. PathIndex.prototype.makePost = function (indexValue, name) {
  6069. var valueNode = nodeFromJSON(indexValue);
  6070. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
  6071. return new NamedNode(name, node);
  6072. };
  6073. PathIndex.prototype.maxPost = function () {
  6074. var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
  6075. return new NamedNode(MAX_NAME, node);
  6076. };
  6077. PathIndex.prototype.toString = function () {
  6078. return pathSlice(this.indexPath_, 0).join('/');
  6079. };
  6080. return PathIndex;
  6081. }(Index));
  6082. /**
  6083. * @license
  6084. * Copyright 2017 Google LLC
  6085. *
  6086. * Licensed under the Apache License, Version 2.0 (the "License");
  6087. * you may not use this file except in compliance with the License.
  6088. * You may obtain a copy of the License at
  6089. *
  6090. * http://www.apache.org/licenses/LICENSE-2.0
  6091. *
  6092. * Unless required by applicable law or agreed to in writing, software
  6093. * distributed under the License is distributed on an "AS IS" BASIS,
  6094. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6095. * See the License for the specific language governing permissions and
  6096. * limitations under the License.
  6097. */
  6098. var ValueIndex = /** @class */ (function (_super) {
  6099. tslib.__extends(ValueIndex, _super);
  6100. function ValueIndex() {
  6101. return _super !== null && _super.apply(this, arguments) || this;
  6102. }
  6103. ValueIndex.prototype.compare = function (a, b) {
  6104. var indexCmp = a.node.compareTo(b.node);
  6105. if (indexCmp === 0) {
  6106. return nameCompare(a.name, b.name);
  6107. }
  6108. else {
  6109. return indexCmp;
  6110. }
  6111. };
  6112. ValueIndex.prototype.isDefinedOn = function (node) {
  6113. return true;
  6114. };
  6115. ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
  6116. return !oldNode.equals(newNode);
  6117. };
  6118. ValueIndex.prototype.minPost = function () {
  6119. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6120. return NamedNode.MIN;
  6121. };
  6122. ValueIndex.prototype.maxPost = function () {
  6123. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  6124. return NamedNode.MAX;
  6125. };
  6126. ValueIndex.prototype.makePost = function (indexValue, name) {
  6127. var valueNode = nodeFromJSON(indexValue);
  6128. return new NamedNode(name, valueNode);
  6129. };
  6130. /**
  6131. * @returns String representation for inclusion in a query spec
  6132. */
  6133. ValueIndex.prototype.toString = function () {
  6134. return '.value';
  6135. };
  6136. return ValueIndex;
  6137. }(Index));
  6138. var VALUE_INDEX = new ValueIndex();
  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. function changeValue(snapshotNode) {
  6156. return { type: "value" /* ChangeType.VALUE */, snapshotNode: snapshotNode };
  6157. }
  6158. function changeChildAdded(childName, snapshotNode) {
  6159. return { type: "child_added" /* ChangeType.CHILD_ADDED */, snapshotNode: snapshotNode, childName: childName };
  6160. }
  6161. function changeChildRemoved(childName, snapshotNode) {
  6162. return { type: "child_removed" /* ChangeType.CHILD_REMOVED */, snapshotNode: snapshotNode, childName: childName };
  6163. }
  6164. function changeChildChanged(childName, snapshotNode, oldSnap) {
  6165. return {
  6166. type: "child_changed" /* ChangeType.CHILD_CHANGED */,
  6167. snapshotNode: snapshotNode,
  6168. childName: childName,
  6169. oldSnap: oldSnap
  6170. };
  6171. }
  6172. function changeChildMoved(childName, snapshotNode) {
  6173. return { type: "child_moved" /* ChangeType.CHILD_MOVED */, snapshotNode: snapshotNode, childName: childName };
  6174. }
  6175. /**
  6176. * @license
  6177. * Copyright 2017 Google LLC
  6178. *
  6179. * Licensed under the Apache License, Version 2.0 (the "License");
  6180. * you may not use this file except in compliance with the License.
  6181. * You may obtain a copy of the License at
  6182. *
  6183. * http://www.apache.org/licenses/LICENSE-2.0
  6184. *
  6185. * Unless required by applicable law or agreed to in writing, software
  6186. * distributed under the License is distributed on an "AS IS" BASIS,
  6187. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6188. * See the License for the specific language governing permissions and
  6189. * limitations under the License.
  6190. */
  6191. /**
  6192. * Doesn't really filter nodes but applies an index to the node and keeps track of any changes
  6193. */
  6194. var IndexedFilter = /** @class */ (function () {
  6195. function IndexedFilter(index_) {
  6196. this.index_ = index_;
  6197. }
  6198. IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6199. util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
  6200. var oldChild = snap.getImmediateChild(key);
  6201. // Check if anything actually changed.
  6202. if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
  6203. // There's an edge case where a child can enter or leave the view because affectedPath was set to null.
  6204. // In this case, affectedPath will appear null in both the old and new snapshots. So we need
  6205. // to avoid treating these cases as "nothing changed."
  6206. if (oldChild.isEmpty() === newChild.isEmpty()) {
  6207. // Nothing changed.
  6208. // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.
  6209. //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');
  6210. return snap;
  6211. }
  6212. }
  6213. if (optChangeAccumulator != null) {
  6214. if (newChild.isEmpty()) {
  6215. if (snap.hasChild(key)) {
  6216. optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
  6217. }
  6218. else {
  6219. util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
  6220. }
  6221. }
  6222. else if (oldChild.isEmpty()) {
  6223. optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
  6224. }
  6225. else {
  6226. optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
  6227. }
  6228. }
  6229. if (snap.isLeafNode() && newChild.isEmpty()) {
  6230. return snap;
  6231. }
  6232. else {
  6233. // Make sure the node is indexed
  6234. return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
  6235. }
  6236. };
  6237. IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6238. if (optChangeAccumulator != null) {
  6239. if (!oldSnap.isLeafNode()) {
  6240. oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6241. if (!newSnap.hasChild(key)) {
  6242. optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
  6243. }
  6244. });
  6245. }
  6246. if (!newSnap.isLeafNode()) {
  6247. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6248. if (oldSnap.hasChild(key)) {
  6249. var oldChild = oldSnap.getImmediateChild(key);
  6250. if (!oldChild.equals(childNode)) {
  6251. optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
  6252. }
  6253. }
  6254. else {
  6255. optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
  6256. }
  6257. });
  6258. }
  6259. }
  6260. return newSnap.withIndex(this.index_);
  6261. };
  6262. IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6263. if (oldSnap.isEmpty()) {
  6264. return ChildrenNode.EMPTY_NODE;
  6265. }
  6266. else {
  6267. return oldSnap.updatePriority(newPriority);
  6268. }
  6269. };
  6270. IndexedFilter.prototype.filtersNodes = function () {
  6271. return false;
  6272. };
  6273. IndexedFilter.prototype.getIndexedFilter = function () {
  6274. return this;
  6275. };
  6276. IndexedFilter.prototype.getIndex = function () {
  6277. return this.index_;
  6278. };
  6279. return IndexedFilter;
  6280. }());
  6281. /**
  6282. * @license
  6283. * Copyright 2017 Google LLC
  6284. *
  6285. * Licensed under the Apache License, Version 2.0 (the "License");
  6286. * you may not use this file except in compliance with the License.
  6287. * You may obtain a copy of the License at
  6288. *
  6289. * http://www.apache.org/licenses/LICENSE-2.0
  6290. *
  6291. * Unless required by applicable law or agreed to in writing, software
  6292. * distributed under the License is distributed on an "AS IS" BASIS,
  6293. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6294. * See the License for the specific language governing permissions and
  6295. * limitations under the License.
  6296. */
  6297. /**
  6298. * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node
  6299. */
  6300. var RangedFilter = /** @class */ (function () {
  6301. function RangedFilter(params) {
  6302. this.indexedFilter_ = new IndexedFilter(params.getIndex());
  6303. this.index_ = params.getIndex();
  6304. this.startPost_ = RangedFilter.getStartPost_(params);
  6305. this.endPost_ = RangedFilter.getEndPost_(params);
  6306. this.startIsInclusive_ = !params.startAfterSet_;
  6307. this.endIsInclusive_ = !params.endBeforeSet_;
  6308. }
  6309. RangedFilter.prototype.getStartPost = function () {
  6310. return this.startPost_;
  6311. };
  6312. RangedFilter.prototype.getEndPost = function () {
  6313. return this.endPost_;
  6314. };
  6315. RangedFilter.prototype.matches = function (node) {
  6316. var isWithinStart = this.startIsInclusive_
  6317. ? this.index_.compare(this.getStartPost(), node) <= 0
  6318. : this.index_.compare(this.getStartPost(), node) < 0;
  6319. var isWithinEnd = this.endIsInclusive_
  6320. ? this.index_.compare(node, this.getEndPost()) <= 0
  6321. : this.index_.compare(node, this.getEndPost()) < 0;
  6322. return isWithinStart && isWithinEnd;
  6323. };
  6324. RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6325. if (!this.matches(new NamedNode(key, newChild))) {
  6326. newChild = ChildrenNode.EMPTY_NODE;
  6327. }
  6328. return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6329. };
  6330. RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6331. if (newSnap.isLeafNode()) {
  6332. // Make sure we have a children node with the correct index, not a leaf node;
  6333. newSnap = ChildrenNode.EMPTY_NODE;
  6334. }
  6335. var filtered = newSnap.withIndex(this.index_);
  6336. // Don't support priorities on queries
  6337. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6338. var self = this;
  6339. newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  6340. if (!self.matches(new NamedNode(key, childNode))) {
  6341. filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
  6342. }
  6343. });
  6344. return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6345. };
  6346. RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6347. // Don't support priorities on queries
  6348. return oldSnap;
  6349. };
  6350. RangedFilter.prototype.filtersNodes = function () {
  6351. return true;
  6352. };
  6353. RangedFilter.prototype.getIndexedFilter = function () {
  6354. return this.indexedFilter_;
  6355. };
  6356. RangedFilter.prototype.getIndex = function () {
  6357. return this.index_;
  6358. };
  6359. RangedFilter.getStartPost_ = function (params) {
  6360. if (params.hasStart()) {
  6361. var startName = params.getIndexStartName();
  6362. return params.getIndex().makePost(params.getIndexStartValue(), startName);
  6363. }
  6364. else {
  6365. return params.getIndex().minPost();
  6366. }
  6367. };
  6368. RangedFilter.getEndPost_ = function (params) {
  6369. if (params.hasEnd()) {
  6370. var endName = params.getIndexEndName();
  6371. return params.getIndex().makePost(params.getIndexEndValue(), endName);
  6372. }
  6373. else {
  6374. return params.getIndex().maxPost();
  6375. }
  6376. };
  6377. return RangedFilter;
  6378. }());
  6379. /**
  6380. * @license
  6381. * Copyright 2017 Google LLC
  6382. *
  6383. * Licensed under the Apache License, Version 2.0 (the "License");
  6384. * you may not use this file except in compliance with the License.
  6385. * You may obtain a copy of the License at
  6386. *
  6387. * http://www.apache.org/licenses/LICENSE-2.0
  6388. *
  6389. * Unless required by applicable law or agreed to in writing, software
  6390. * distributed under the License is distributed on an "AS IS" BASIS,
  6391. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6392. * See the License for the specific language governing permissions and
  6393. * limitations under the License.
  6394. */
  6395. /**
  6396. * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible
  6397. */
  6398. var LimitedFilter = /** @class */ (function () {
  6399. function LimitedFilter(params) {
  6400. var _this = this;
  6401. this.withinDirectionalStart = function (node) {
  6402. return _this.reverse_ ? _this.withinEndPost(node) : _this.withinStartPost(node);
  6403. };
  6404. this.withinDirectionalEnd = function (node) {
  6405. return _this.reverse_ ? _this.withinStartPost(node) : _this.withinEndPost(node);
  6406. };
  6407. this.withinStartPost = function (node) {
  6408. var compareRes = _this.index_.compare(_this.rangedFilter_.getStartPost(), node);
  6409. return _this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6410. };
  6411. this.withinEndPost = function (node) {
  6412. var compareRes = _this.index_.compare(node, _this.rangedFilter_.getEndPost());
  6413. return _this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
  6414. };
  6415. this.rangedFilter_ = new RangedFilter(params);
  6416. this.index_ = params.getIndex();
  6417. this.limit_ = params.getLimit();
  6418. this.reverse_ = !params.isViewFromLeft();
  6419. this.startIsInclusive_ = !params.startAfterSet_;
  6420. this.endIsInclusive_ = !params.endBeforeSet_;
  6421. }
  6422. LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
  6423. if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
  6424. newChild = ChildrenNode.EMPTY_NODE;
  6425. }
  6426. if (snap.getImmediateChild(key).equals(newChild)) {
  6427. // No change
  6428. return snap;
  6429. }
  6430. else if (snap.numChildren() < this.limit_) {
  6431. return this.rangedFilter_
  6432. .getIndexedFilter()
  6433. .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
  6434. }
  6435. else {
  6436. return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
  6437. }
  6438. };
  6439. LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
  6440. var filtered;
  6441. if (newSnap.isLeafNode() || newSnap.isEmpty()) {
  6442. // Make sure we have a children node with the correct index, not a leaf node;
  6443. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6444. }
  6445. else {
  6446. if (this.limit_ * 2 < newSnap.numChildren() &&
  6447. newSnap.isIndexed(this.index_)) {
  6448. // Easier to build up a snapshot, since what we're given has more than twice the elements we want
  6449. filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
  6450. // anchor to the startPost, endPost, or last element as appropriate
  6451. var iterator = void 0;
  6452. if (this.reverse_) {
  6453. iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
  6454. }
  6455. else {
  6456. iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
  6457. }
  6458. var count = 0;
  6459. while (iterator.hasNext() && count < this.limit_) {
  6460. var next = iterator.getNext();
  6461. if (!this.withinDirectionalStart(next)) {
  6462. // if we have not reached the start, skip to the next element
  6463. continue;
  6464. }
  6465. else if (!this.withinDirectionalEnd(next)) {
  6466. // if we have reached the end, stop adding elements
  6467. break;
  6468. }
  6469. else {
  6470. filtered = filtered.updateImmediateChild(next.name, next.node);
  6471. count++;
  6472. }
  6473. }
  6474. }
  6475. else {
  6476. // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one
  6477. filtered = newSnap.withIndex(this.index_);
  6478. // Don't support priorities on queries
  6479. filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
  6480. var iterator = void 0;
  6481. if (this.reverse_) {
  6482. iterator = filtered.getReverseIterator(this.index_);
  6483. }
  6484. else {
  6485. iterator = filtered.getIterator(this.index_);
  6486. }
  6487. var count = 0;
  6488. while (iterator.hasNext()) {
  6489. var next = iterator.getNext();
  6490. var inRange = count < this.limit_ &&
  6491. this.withinDirectionalStart(next) &&
  6492. this.withinDirectionalEnd(next);
  6493. if (inRange) {
  6494. count++;
  6495. }
  6496. else {
  6497. filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
  6498. }
  6499. }
  6500. }
  6501. }
  6502. return this.rangedFilter_
  6503. .getIndexedFilter()
  6504. .updateFullNode(oldSnap, filtered, optChangeAccumulator);
  6505. };
  6506. LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
  6507. // Don't support priorities on queries
  6508. return oldSnap;
  6509. };
  6510. LimitedFilter.prototype.filtersNodes = function () {
  6511. return true;
  6512. };
  6513. LimitedFilter.prototype.getIndexedFilter = function () {
  6514. return this.rangedFilter_.getIndexedFilter();
  6515. };
  6516. LimitedFilter.prototype.getIndex = function () {
  6517. return this.index_;
  6518. };
  6519. LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {
  6520. // TODO: rename all cache stuff etc to general snap terminology
  6521. var cmp;
  6522. if (this.reverse_) {
  6523. var indexCmp_1 = this.index_.getCompare();
  6524. cmp = function (a, b) { return indexCmp_1(b, a); };
  6525. }
  6526. else {
  6527. cmp = this.index_.getCompare();
  6528. }
  6529. var oldEventCache = snap;
  6530. util.assert(oldEventCache.numChildren() === this.limit_, '');
  6531. var newChildNamedNode = new NamedNode(childKey, childSnap);
  6532. var windowBoundary = this.reverse_
  6533. ? oldEventCache.getFirstChild(this.index_)
  6534. : oldEventCache.getLastChild(this.index_);
  6535. var inRange = this.rangedFilter_.matches(newChildNamedNode);
  6536. if (oldEventCache.hasChild(childKey)) {
  6537. var oldChildSnap = oldEventCache.getImmediateChild(childKey);
  6538. var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
  6539. while (nextChild != null &&
  6540. (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
  6541. // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't
  6542. // been applied to the limited filter yet. Ignore this next child which will be updated later in
  6543. // the limited filter...
  6544. nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
  6545. }
  6546. var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
  6547. var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
  6548. if (remainsInWindow) {
  6549. if (changeAccumulator != null) {
  6550. changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
  6551. }
  6552. return oldEventCache.updateImmediateChild(childKey, childSnap);
  6553. }
  6554. else {
  6555. if (changeAccumulator != null) {
  6556. changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
  6557. }
  6558. var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
  6559. var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
  6560. if (nextChildInRange) {
  6561. if (changeAccumulator != null) {
  6562. changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
  6563. }
  6564. return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
  6565. }
  6566. else {
  6567. return newEventCache;
  6568. }
  6569. }
  6570. }
  6571. else if (childSnap.isEmpty()) {
  6572. // we're deleting a node, but it was not in the window, so ignore it
  6573. return snap;
  6574. }
  6575. else if (inRange) {
  6576. if (cmp(windowBoundary, newChildNamedNode) >= 0) {
  6577. if (changeAccumulator != null) {
  6578. changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
  6579. changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
  6580. }
  6581. return oldEventCache
  6582. .updateImmediateChild(childKey, childSnap)
  6583. .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
  6584. }
  6585. else {
  6586. return snap;
  6587. }
  6588. }
  6589. else {
  6590. return snap;
  6591. }
  6592. };
  6593. return LimitedFilter;
  6594. }());
  6595. /**
  6596. * @license
  6597. * Copyright 2017 Google LLC
  6598. *
  6599. * Licensed under the Apache License, Version 2.0 (the "License");
  6600. * you may not use this file except in compliance with the License.
  6601. * You may obtain a copy of the License at
  6602. *
  6603. * http://www.apache.org/licenses/LICENSE-2.0
  6604. *
  6605. * Unless required by applicable law or agreed to in writing, software
  6606. * distributed under the License is distributed on an "AS IS" BASIS,
  6607. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6608. * See the License for the specific language governing permissions and
  6609. * limitations under the License.
  6610. */
  6611. /**
  6612. * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a
  6613. * range to be returned for a particular location. It is assumed that validation of parameters is done at the
  6614. * user-facing API level, so it is not done here.
  6615. *
  6616. * @internal
  6617. */
  6618. var QueryParams = /** @class */ (function () {
  6619. function QueryParams() {
  6620. this.limitSet_ = false;
  6621. this.startSet_ = false;
  6622. this.startNameSet_ = false;
  6623. this.startAfterSet_ = false; // can only be true if startSet_ is true
  6624. this.endSet_ = false;
  6625. this.endNameSet_ = false;
  6626. this.endBeforeSet_ = false; // can only be true if endSet_ is true
  6627. this.limit_ = 0;
  6628. this.viewFrom_ = '';
  6629. this.indexStartValue_ = null;
  6630. this.indexStartName_ = '';
  6631. this.indexEndValue_ = null;
  6632. this.indexEndName_ = '';
  6633. this.index_ = PRIORITY_INDEX;
  6634. }
  6635. QueryParams.prototype.hasStart = function () {
  6636. return this.startSet_;
  6637. };
  6638. /**
  6639. * @returns True if it would return from left.
  6640. */
  6641. QueryParams.prototype.isViewFromLeft = function () {
  6642. if (this.viewFrom_ === '') {
  6643. // limit(), rather than limitToFirst or limitToLast was called.
  6644. // This means that only one of startSet_ and endSet_ is true. Use them
  6645. // to calculate which side of the view to anchor to. If neither is set,
  6646. // anchor to the end.
  6647. return this.startSet_;
  6648. }
  6649. else {
  6650. return this.viewFrom_ === "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6651. }
  6652. };
  6653. /**
  6654. * Only valid to call if hasStart() returns true
  6655. */
  6656. QueryParams.prototype.getIndexStartValue = function () {
  6657. util.assert(this.startSet_, 'Only valid if start has been set');
  6658. return this.indexStartValue_;
  6659. };
  6660. /**
  6661. * Only valid to call if hasStart() returns true.
  6662. * Returns the starting key name for the range defined by these query parameters
  6663. */
  6664. QueryParams.prototype.getIndexStartName = function () {
  6665. util.assert(this.startSet_, 'Only valid if start has been set');
  6666. if (this.startNameSet_) {
  6667. return this.indexStartName_;
  6668. }
  6669. else {
  6670. return MIN_NAME;
  6671. }
  6672. };
  6673. QueryParams.prototype.hasEnd = function () {
  6674. return this.endSet_;
  6675. };
  6676. /**
  6677. * Only valid to call if hasEnd() returns true.
  6678. */
  6679. QueryParams.prototype.getIndexEndValue = function () {
  6680. util.assert(this.endSet_, 'Only valid if end has been set');
  6681. return this.indexEndValue_;
  6682. };
  6683. /**
  6684. * Only valid to call if hasEnd() returns true.
  6685. * Returns the end key name for the range defined by these query parameters
  6686. */
  6687. QueryParams.prototype.getIndexEndName = function () {
  6688. util.assert(this.endSet_, 'Only valid if end has been set');
  6689. if (this.endNameSet_) {
  6690. return this.indexEndName_;
  6691. }
  6692. else {
  6693. return MAX_NAME;
  6694. }
  6695. };
  6696. QueryParams.prototype.hasLimit = function () {
  6697. return this.limitSet_;
  6698. };
  6699. /**
  6700. * @returns True if a limit has been set and it has been explicitly anchored
  6701. */
  6702. QueryParams.prototype.hasAnchoredLimit = function () {
  6703. return this.limitSet_ && this.viewFrom_ !== '';
  6704. };
  6705. /**
  6706. * Only valid to call if hasLimit() returns true
  6707. */
  6708. QueryParams.prototype.getLimit = function () {
  6709. util.assert(this.limitSet_, 'Only valid if limit has been set');
  6710. return this.limit_;
  6711. };
  6712. QueryParams.prototype.getIndex = function () {
  6713. return this.index_;
  6714. };
  6715. QueryParams.prototype.loadsAllData = function () {
  6716. return !(this.startSet_ || this.endSet_ || this.limitSet_);
  6717. };
  6718. QueryParams.prototype.isDefault = function () {
  6719. return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
  6720. };
  6721. QueryParams.prototype.copy = function () {
  6722. var copy = new QueryParams();
  6723. copy.limitSet_ = this.limitSet_;
  6724. copy.limit_ = this.limit_;
  6725. copy.startSet_ = this.startSet_;
  6726. copy.startAfterSet_ = this.startAfterSet_;
  6727. copy.indexStartValue_ = this.indexStartValue_;
  6728. copy.startNameSet_ = this.startNameSet_;
  6729. copy.indexStartName_ = this.indexStartName_;
  6730. copy.endSet_ = this.endSet_;
  6731. copy.endBeforeSet_ = this.endBeforeSet_;
  6732. copy.indexEndValue_ = this.indexEndValue_;
  6733. copy.endNameSet_ = this.endNameSet_;
  6734. copy.indexEndName_ = this.indexEndName_;
  6735. copy.index_ = this.index_;
  6736. copy.viewFrom_ = this.viewFrom_;
  6737. return copy;
  6738. };
  6739. return QueryParams;
  6740. }());
  6741. function queryParamsGetNodeFilter(queryParams) {
  6742. if (queryParams.loadsAllData()) {
  6743. return new IndexedFilter(queryParams.getIndex());
  6744. }
  6745. else if (queryParams.hasLimit()) {
  6746. return new LimitedFilter(queryParams);
  6747. }
  6748. else {
  6749. return new RangedFilter(queryParams);
  6750. }
  6751. }
  6752. function queryParamsLimitToFirst(queryParams, newLimit) {
  6753. var newParams = queryParams.copy();
  6754. newParams.limitSet_ = true;
  6755. newParams.limit_ = newLimit;
  6756. newParams.viewFrom_ = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6757. return newParams;
  6758. }
  6759. function queryParamsLimitToLast(queryParams, newLimit) {
  6760. var newParams = queryParams.copy();
  6761. newParams.limitSet_ = true;
  6762. newParams.limit_ = newLimit;
  6763. newParams.viewFrom_ = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6764. return newParams;
  6765. }
  6766. function queryParamsStartAt(queryParams, indexValue, key) {
  6767. var newParams = queryParams.copy();
  6768. newParams.startSet_ = true;
  6769. if (indexValue === undefined) {
  6770. indexValue = null;
  6771. }
  6772. newParams.indexStartValue_ = indexValue;
  6773. if (key != null) {
  6774. newParams.startNameSet_ = true;
  6775. newParams.indexStartName_ = key;
  6776. }
  6777. else {
  6778. newParams.startNameSet_ = false;
  6779. newParams.indexStartName_ = '';
  6780. }
  6781. return newParams;
  6782. }
  6783. function queryParamsStartAfter(queryParams, indexValue, key) {
  6784. var params;
  6785. if (queryParams.index_ === KEY_INDEX || !!key) {
  6786. params = queryParamsStartAt(queryParams, indexValue, key);
  6787. }
  6788. else {
  6789. params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
  6790. }
  6791. params.startAfterSet_ = true;
  6792. return params;
  6793. }
  6794. function queryParamsEndAt(queryParams, indexValue, key) {
  6795. var newParams = queryParams.copy();
  6796. newParams.endSet_ = true;
  6797. if (indexValue === undefined) {
  6798. indexValue = null;
  6799. }
  6800. newParams.indexEndValue_ = indexValue;
  6801. if (key !== undefined) {
  6802. newParams.endNameSet_ = true;
  6803. newParams.indexEndName_ = key;
  6804. }
  6805. else {
  6806. newParams.endNameSet_ = false;
  6807. newParams.indexEndName_ = '';
  6808. }
  6809. return newParams;
  6810. }
  6811. function queryParamsEndBefore(queryParams, indexValue, key) {
  6812. var params;
  6813. if (queryParams.index_ === KEY_INDEX || !!key) {
  6814. params = queryParamsEndAt(queryParams, indexValue, key);
  6815. }
  6816. else {
  6817. params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
  6818. }
  6819. params.endBeforeSet_ = true;
  6820. return params;
  6821. }
  6822. function queryParamsOrderBy(queryParams, index) {
  6823. var newParams = queryParams.copy();
  6824. newParams.index_ = index;
  6825. return newParams;
  6826. }
  6827. /**
  6828. * Returns a set of REST query string parameters representing this query.
  6829. *
  6830. * @returns query string parameters
  6831. */
  6832. function queryParamsToRestQueryStringParameters(queryParams) {
  6833. var qs = {};
  6834. if (queryParams.isDefault()) {
  6835. return qs;
  6836. }
  6837. var orderBy;
  6838. if (queryParams.index_ === PRIORITY_INDEX) {
  6839. orderBy = "$priority" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;
  6840. }
  6841. else if (queryParams.index_ === VALUE_INDEX) {
  6842. orderBy = "$value" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;
  6843. }
  6844. else if (queryParams.index_ === KEY_INDEX) {
  6845. orderBy = "$key" /* REST_QUERY_CONSTANTS.KEY_INDEX */;
  6846. }
  6847. else {
  6848. util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
  6849. orderBy = queryParams.index_.toString();
  6850. }
  6851. qs["orderBy" /* REST_QUERY_CONSTANTS.ORDER_BY */] = util.stringify(orderBy);
  6852. if (queryParams.startSet_) {
  6853. var startParam = queryParams.startAfterSet_
  6854. ? "startAfter" /* REST_QUERY_CONSTANTS.START_AFTER */
  6855. : "startAt" /* REST_QUERY_CONSTANTS.START_AT */;
  6856. qs[startParam] = util.stringify(queryParams.indexStartValue_);
  6857. if (queryParams.startNameSet_) {
  6858. qs[startParam] += ',' + util.stringify(queryParams.indexStartName_);
  6859. }
  6860. }
  6861. if (queryParams.endSet_) {
  6862. var endParam = queryParams.endBeforeSet_
  6863. ? "endBefore" /* REST_QUERY_CONSTANTS.END_BEFORE */
  6864. : "endAt" /* REST_QUERY_CONSTANTS.END_AT */;
  6865. qs[endParam] = util.stringify(queryParams.indexEndValue_);
  6866. if (queryParams.endNameSet_) {
  6867. qs[endParam] += ',' + util.stringify(queryParams.indexEndName_);
  6868. }
  6869. }
  6870. if (queryParams.limitSet_) {
  6871. if (queryParams.isViewFromLeft()) {
  6872. qs["limitToFirst" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;
  6873. }
  6874. else {
  6875. qs["limitToLast" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;
  6876. }
  6877. }
  6878. return qs;
  6879. }
  6880. function queryParamsGetQueryObject(queryParams) {
  6881. var obj = {};
  6882. if (queryParams.startSet_) {
  6883. obj["sp" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =
  6884. queryParams.indexStartValue_;
  6885. if (queryParams.startNameSet_) {
  6886. obj["sn" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =
  6887. queryParams.indexStartName_;
  6888. }
  6889. obj["sin" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =
  6890. !queryParams.startAfterSet_;
  6891. }
  6892. if (queryParams.endSet_) {
  6893. obj["ep" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;
  6894. if (queryParams.endNameSet_) {
  6895. obj["en" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;
  6896. }
  6897. obj["ein" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =
  6898. !queryParams.endBeforeSet_;
  6899. }
  6900. if (queryParams.limitSet_) {
  6901. obj["l" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;
  6902. var viewFrom = queryParams.viewFrom_;
  6903. if (viewFrom === '') {
  6904. if (queryParams.isViewFromLeft()) {
  6905. viewFrom = "l" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;
  6906. }
  6907. else {
  6908. viewFrom = "r" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;
  6909. }
  6910. }
  6911. obj["vf" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;
  6912. }
  6913. // For now, priority index is the default, so we only specify if it's some other index
  6914. if (queryParams.index_ !== PRIORITY_INDEX) {
  6915. obj["i" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();
  6916. }
  6917. return obj;
  6918. }
  6919. /**
  6920. * @license
  6921. * Copyright 2017 Google LLC
  6922. *
  6923. * Licensed under the Apache License, Version 2.0 (the "License");
  6924. * you may not use this file except in compliance with the License.
  6925. * You may obtain a copy of the License at
  6926. *
  6927. * http://www.apache.org/licenses/LICENSE-2.0
  6928. *
  6929. * Unless required by applicable law or agreed to in writing, software
  6930. * distributed under the License is distributed on an "AS IS" BASIS,
  6931. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  6932. * See the License for the specific language governing permissions and
  6933. * limitations under the License.
  6934. */
  6935. /**
  6936. * An implementation of ServerActions that communicates with the server via REST requests.
  6937. * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full
  6938. * persistent connection (using WebSockets or long-polling)
  6939. */
  6940. var ReadonlyRestClient = /** @class */ (function (_super) {
  6941. tslib.__extends(ReadonlyRestClient, _super);
  6942. /**
  6943. * @param repoInfo_ - Data about the namespace we are connecting to
  6944. * @param onDataUpdate_ - A callback for new data from the server
  6945. */
  6946. function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
  6947. var _this = _super.call(this) || this;
  6948. _this.repoInfo_ = repoInfo_;
  6949. _this.onDataUpdate_ = onDataUpdate_;
  6950. _this.authTokenProvider_ = authTokenProvider_;
  6951. _this.appCheckTokenProvider_ = appCheckTokenProvider_;
  6952. /** @private {function(...[*])} */
  6953. _this.log_ = logWrapper('p:rest:');
  6954. /**
  6955. * We don't actually need to track listens, except to prevent us calling an onComplete for a listen
  6956. * that's been removed. :-/
  6957. */
  6958. _this.listens_ = {};
  6959. return _this;
  6960. }
  6961. ReadonlyRestClient.prototype.reportStats = function (stats) {
  6962. throw new Error('Method not implemented.');
  6963. };
  6964. ReadonlyRestClient.getListenId_ = function (query, tag) {
  6965. if (tag !== undefined) {
  6966. return 'tag$' + tag;
  6967. }
  6968. else {
  6969. util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
  6970. return query._path.toString();
  6971. }
  6972. };
  6973. /** @inheritDoc */
  6974. ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {
  6975. var _this = this;
  6976. var pathString = query._path.toString();
  6977. this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
  6978. // Mark this listener so we can tell if it's removed.
  6979. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  6980. var thisListen = {};
  6981. this.listens_[listenId] = thisListen;
  6982. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  6983. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  6984. var data = result;
  6985. if (error === 404) {
  6986. data = null;
  6987. error = null;
  6988. }
  6989. if (error === null) {
  6990. _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);
  6991. }
  6992. if (util.safeGet(_this.listens_, listenId) === thisListen) {
  6993. var status_1;
  6994. if (!error) {
  6995. status_1 = 'ok';
  6996. }
  6997. else if (error === 401) {
  6998. status_1 = 'permission_denied';
  6999. }
  7000. else {
  7001. status_1 = 'rest_error:' + error;
  7002. }
  7003. onComplete(status_1, null);
  7004. }
  7005. });
  7006. };
  7007. /** @inheritDoc */
  7008. ReadonlyRestClient.prototype.unlisten = function (query, tag) {
  7009. var listenId = ReadonlyRestClient.getListenId_(query, tag);
  7010. delete this.listens_[listenId];
  7011. };
  7012. ReadonlyRestClient.prototype.get = function (query) {
  7013. var _this = this;
  7014. var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
  7015. var pathString = query._path.toString();
  7016. var deferred = new util.Deferred();
  7017. this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
  7018. var data = result;
  7019. if (error === 404) {
  7020. data = null;
  7021. error = null;
  7022. }
  7023. if (error === null) {
  7024. _this.onDataUpdate_(pathString, data,
  7025. /*isMerge=*/ false,
  7026. /*tag=*/ null);
  7027. deferred.resolve(data);
  7028. }
  7029. else {
  7030. deferred.reject(new Error(data));
  7031. }
  7032. });
  7033. return deferred.promise;
  7034. };
  7035. /** @inheritDoc */
  7036. ReadonlyRestClient.prototype.refreshAuthToken = function (token) {
  7037. // no-op since we just always call getToken.
  7038. };
  7039. /**
  7040. * Performs a REST request to the given path, with the provided query string parameters,
  7041. * and any auth credentials we have.
  7042. */
  7043. ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {
  7044. var _this = this;
  7045. if (queryStringParameters === void 0) { queryStringParameters = {}; }
  7046. queryStringParameters['format'] = 'export';
  7047. return Promise.all([
  7048. this.authTokenProvider_.getToken(/*forceRefresh=*/ false),
  7049. this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)
  7050. ]).then(function (_a) {
  7051. var _b = tslib.__read(_a, 2), authToken = _b[0], appCheckToken = _b[1];
  7052. if (authToken && authToken.accessToken) {
  7053. queryStringParameters['auth'] = authToken.accessToken;
  7054. }
  7055. if (appCheckToken && appCheckToken.token) {
  7056. queryStringParameters['ac'] = appCheckToken.token;
  7057. }
  7058. var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +
  7059. _this.repoInfo_.host +
  7060. pathString +
  7061. '?' +
  7062. 'ns=' +
  7063. _this.repoInfo_.namespace +
  7064. util.querystring(queryStringParameters);
  7065. _this.log_('Sending REST request for ' + url);
  7066. var xhr = new XMLHttpRequest();
  7067. xhr.onreadystatechange = function () {
  7068. if (callback && xhr.readyState === 4) {
  7069. _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
  7070. var res = null;
  7071. if (xhr.status >= 200 && xhr.status < 300) {
  7072. try {
  7073. res = util.jsonEval(xhr.responseText);
  7074. }
  7075. catch (e) {
  7076. warn('Failed to parse JSON response for ' +
  7077. url +
  7078. ': ' +
  7079. xhr.responseText);
  7080. }
  7081. callback(null, res);
  7082. }
  7083. else {
  7084. // 401 and 404 are expected.
  7085. if (xhr.status !== 401 && xhr.status !== 404) {
  7086. warn('Got unsuccessful REST response for ' +
  7087. url +
  7088. ' Status: ' +
  7089. xhr.status);
  7090. }
  7091. callback(xhr.status);
  7092. }
  7093. callback = null;
  7094. }
  7095. };
  7096. xhr.open('GET', url, /*asynchronous=*/ true);
  7097. xhr.send();
  7098. });
  7099. };
  7100. return ReadonlyRestClient;
  7101. }(ServerActions));
  7102. /**
  7103. * @license
  7104. * Copyright 2017 Google LLC
  7105. *
  7106. * Licensed under the Apache License, Version 2.0 (the "License");
  7107. * you may not use this file except in compliance with the License.
  7108. * You may obtain a copy of the License at
  7109. *
  7110. * http://www.apache.org/licenses/LICENSE-2.0
  7111. *
  7112. * Unless required by applicable law or agreed to in writing, software
  7113. * distributed under the License is distributed on an "AS IS" BASIS,
  7114. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7115. * See the License for the specific language governing permissions and
  7116. * limitations under the License.
  7117. */
  7118. /**
  7119. * Mutable object which basically just stores a reference to the "latest" immutable snapshot.
  7120. */
  7121. var SnapshotHolder = /** @class */ (function () {
  7122. function SnapshotHolder() {
  7123. this.rootNode_ = ChildrenNode.EMPTY_NODE;
  7124. }
  7125. SnapshotHolder.prototype.getNode = function (path) {
  7126. return this.rootNode_.getChild(path);
  7127. };
  7128. SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {
  7129. this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
  7130. };
  7131. return SnapshotHolder;
  7132. }());
  7133. /**
  7134. * @license
  7135. * Copyright 2017 Google LLC
  7136. *
  7137. * Licensed under the Apache License, Version 2.0 (the "License");
  7138. * you may not use this file except in compliance with the License.
  7139. * You may obtain a copy of the License at
  7140. *
  7141. * http://www.apache.org/licenses/LICENSE-2.0
  7142. *
  7143. * Unless required by applicable law or agreed to in writing, software
  7144. * distributed under the License is distributed on an "AS IS" BASIS,
  7145. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7146. * See the License for the specific language governing permissions and
  7147. * limitations under the License.
  7148. */
  7149. function newSparseSnapshotTree() {
  7150. return {
  7151. value: null,
  7152. children: new Map()
  7153. };
  7154. }
  7155. /**
  7156. * Stores the given node at the specified path. If there is already a node
  7157. * at a shallower path, it merges the new data into that snapshot node.
  7158. *
  7159. * @param path - Path to look up snapshot for.
  7160. * @param data - The new data, or null.
  7161. */
  7162. function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
  7163. if (pathIsEmpty(path)) {
  7164. sparseSnapshotTree.value = data;
  7165. sparseSnapshotTree.children.clear();
  7166. }
  7167. else if (sparseSnapshotTree.value !== null) {
  7168. sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
  7169. }
  7170. else {
  7171. var childKey = pathGetFront(path);
  7172. if (!sparseSnapshotTree.children.has(childKey)) {
  7173. sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
  7174. }
  7175. var child = sparseSnapshotTree.children.get(childKey);
  7176. path = pathPopFront(path);
  7177. sparseSnapshotTreeRemember(child, path, data);
  7178. }
  7179. }
  7180. /**
  7181. * Purge the data at path from the cache.
  7182. *
  7183. * @param path - Path to look up snapshot for.
  7184. * @returns True if this node should now be removed.
  7185. */
  7186. function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
  7187. if (pathIsEmpty(path)) {
  7188. sparseSnapshotTree.value = null;
  7189. sparseSnapshotTree.children.clear();
  7190. return true;
  7191. }
  7192. else {
  7193. if (sparseSnapshotTree.value !== null) {
  7194. if (sparseSnapshotTree.value.isLeafNode()) {
  7195. // We're trying to forget a node that doesn't exist
  7196. return false;
  7197. }
  7198. else {
  7199. var value = sparseSnapshotTree.value;
  7200. sparseSnapshotTree.value = null;
  7201. value.forEachChild(PRIORITY_INDEX, function (key, tree) {
  7202. sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
  7203. });
  7204. return sparseSnapshotTreeForget(sparseSnapshotTree, path);
  7205. }
  7206. }
  7207. else if (sparseSnapshotTree.children.size > 0) {
  7208. var childKey = pathGetFront(path);
  7209. path = pathPopFront(path);
  7210. if (sparseSnapshotTree.children.has(childKey)) {
  7211. var safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
  7212. if (safeToRemove) {
  7213. sparseSnapshotTree.children.delete(childKey);
  7214. }
  7215. }
  7216. return sparseSnapshotTree.children.size === 0;
  7217. }
  7218. else {
  7219. return true;
  7220. }
  7221. }
  7222. }
  7223. /**
  7224. * Recursively iterates through all of the stored tree and calls the
  7225. * callback on each one.
  7226. *
  7227. * @param prefixPath - Path to look up node for.
  7228. * @param func - The function to invoke for each tree.
  7229. */
  7230. function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
  7231. if (sparseSnapshotTree.value !== null) {
  7232. func(prefixPath, sparseSnapshotTree.value);
  7233. }
  7234. else {
  7235. sparseSnapshotTreeForEachChild(sparseSnapshotTree, function (key, tree) {
  7236. var path = new Path(prefixPath.toString() + '/' + key);
  7237. sparseSnapshotTreeForEachTree(tree, path, func);
  7238. });
  7239. }
  7240. }
  7241. /**
  7242. * Iterates through each immediate child and triggers the callback.
  7243. * Only seems to be used in tests.
  7244. *
  7245. * @param func - The function to invoke for each child.
  7246. */
  7247. function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
  7248. sparseSnapshotTree.children.forEach(function (tree, key) {
  7249. func(key, tree);
  7250. });
  7251. }
  7252. /**
  7253. * @license
  7254. * Copyright 2017 Google LLC
  7255. *
  7256. * Licensed under the Apache License, Version 2.0 (the "License");
  7257. * you may not use this file except in compliance with the License.
  7258. * You may obtain a copy of the License at
  7259. *
  7260. * http://www.apache.org/licenses/LICENSE-2.0
  7261. *
  7262. * Unless required by applicable law or agreed to in writing, software
  7263. * distributed under the License is distributed on an "AS IS" BASIS,
  7264. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7265. * See the License for the specific language governing permissions and
  7266. * limitations under the License.
  7267. */
  7268. /**
  7269. * Returns the delta from the previous call to get stats.
  7270. *
  7271. * @param collection_ - The collection to "listen" to.
  7272. */
  7273. var StatsListener = /** @class */ (function () {
  7274. function StatsListener(collection_) {
  7275. this.collection_ = collection_;
  7276. this.last_ = null;
  7277. }
  7278. StatsListener.prototype.get = function () {
  7279. var newStats = this.collection_.get();
  7280. var delta = tslib.__assign({}, newStats);
  7281. if (this.last_) {
  7282. each(this.last_, function (stat, value) {
  7283. delta[stat] = delta[stat] - value;
  7284. });
  7285. }
  7286. this.last_ = newStats;
  7287. return delta;
  7288. };
  7289. return StatsListener;
  7290. }());
  7291. /**
  7292. * @license
  7293. * Copyright 2017 Google LLC
  7294. *
  7295. * Licensed under the Apache License, Version 2.0 (the "License");
  7296. * you may not use this file except in compliance with the License.
  7297. * You may obtain a copy of the License at
  7298. *
  7299. * http://www.apache.org/licenses/LICENSE-2.0
  7300. *
  7301. * Unless required by applicable law or agreed to in writing, software
  7302. * distributed under the License is distributed on an "AS IS" BASIS,
  7303. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7304. * See the License for the specific language governing permissions and
  7305. * limitations under the License.
  7306. */
  7307. // Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably
  7308. // happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10
  7309. // seconds to try to ensure the Firebase connection is established / settled.
  7310. var FIRST_STATS_MIN_TIME = 10 * 1000;
  7311. var FIRST_STATS_MAX_TIME = 30 * 1000;
  7312. // We'll continue to report stats on average every 5 minutes.
  7313. var REPORT_STATS_INTERVAL = 5 * 60 * 1000;
  7314. var StatsReporter = /** @class */ (function () {
  7315. function StatsReporter(collection, server_) {
  7316. this.server_ = server_;
  7317. this.statsToReport_ = {};
  7318. this.statsListener_ = new StatsListener(collection);
  7319. var timeout = FIRST_STATS_MIN_TIME +
  7320. (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
  7321. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
  7322. }
  7323. StatsReporter.prototype.reportStats_ = function () {
  7324. var _this = this;
  7325. var stats = this.statsListener_.get();
  7326. var reportedStats = {};
  7327. var haveStatsToReport = false;
  7328. each(stats, function (stat, value) {
  7329. if (value > 0 && util.contains(_this.statsToReport_, stat)) {
  7330. reportedStats[stat] = value;
  7331. haveStatsToReport = true;
  7332. }
  7333. });
  7334. if (haveStatsToReport) {
  7335. this.server_.reportStats(reportedStats);
  7336. }
  7337. // queue our next run.
  7338. setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
  7339. };
  7340. return StatsReporter;
  7341. }());
  7342. /**
  7343. * @license
  7344. * Copyright 2017 Google LLC
  7345. *
  7346. * Licensed under the Apache License, Version 2.0 (the "License");
  7347. * you may not use this file except in compliance with the License.
  7348. * You may obtain a copy of the License at
  7349. *
  7350. * http://www.apache.org/licenses/LICENSE-2.0
  7351. *
  7352. * Unless required by applicable law or agreed to in writing, software
  7353. * distributed under the License is distributed on an "AS IS" BASIS,
  7354. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7355. * See the License for the specific language governing permissions and
  7356. * limitations under the License.
  7357. */
  7358. /**
  7359. *
  7360. * @enum
  7361. */
  7362. var OperationType;
  7363. (function (OperationType) {
  7364. OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
  7365. OperationType[OperationType["MERGE"] = 1] = "MERGE";
  7366. OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
  7367. OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  7368. })(OperationType || (OperationType = {}));
  7369. function newOperationSourceUser() {
  7370. return {
  7371. fromUser: true,
  7372. fromServer: false,
  7373. queryId: null,
  7374. tagged: false
  7375. };
  7376. }
  7377. function newOperationSourceServer() {
  7378. return {
  7379. fromUser: false,
  7380. fromServer: true,
  7381. queryId: null,
  7382. tagged: false
  7383. };
  7384. }
  7385. function newOperationSourceServerTaggedQuery(queryId) {
  7386. return {
  7387. fromUser: false,
  7388. fromServer: true,
  7389. queryId: queryId,
  7390. tagged: true
  7391. };
  7392. }
  7393. /**
  7394. * @license
  7395. * Copyright 2017 Google LLC
  7396. *
  7397. * Licensed under the Apache License, Version 2.0 (the "License");
  7398. * you may not use this file except in compliance with the License.
  7399. * You may obtain a copy of the License at
  7400. *
  7401. * http://www.apache.org/licenses/LICENSE-2.0
  7402. *
  7403. * Unless required by applicable law or agreed to in writing, software
  7404. * distributed under the License is distributed on an "AS IS" BASIS,
  7405. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7406. * See the License for the specific language governing permissions and
  7407. * limitations under the License.
  7408. */
  7409. var AckUserWrite = /** @class */ (function () {
  7410. /**
  7411. * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
  7412. */
  7413. function AckUserWrite(
  7414. /** @inheritDoc */ path,
  7415. /** @inheritDoc */ affectedTree,
  7416. /** @inheritDoc */ revert) {
  7417. this.path = path;
  7418. this.affectedTree = affectedTree;
  7419. this.revert = revert;
  7420. /** @inheritDoc */
  7421. this.type = OperationType.ACK_USER_WRITE;
  7422. /** @inheritDoc */
  7423. this.source = newOperationSourceUser();
  7424. }
  7425. AckUserWrite.prototype.operationForChild = function (childName) {
  7426. if (!pathIsEmpty(this.path)) {
  7427. util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
  7428. return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
  7429. }
  7430. else if (this.affectedTree.value != null) {
  7431. util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
  7432. // All child locations are affected as well; just return same operation.
  7433. return this;
  7434. }
  7435. else {
  7436. var childTree = this.affectedTree.subtree(new Path(childName));
  7437. return new AckUserWrite(newEmptyPath(), childTree, this.revert);
  7438. }
  7439. };
  7440. return AckUserWrite;
  7441. }());
  7442. /**
  7443. * @license
  7444. * Copyright 2017 Google LLC
  7445. *
  7446. * Licensed under the Apache License, Version 2.0 (the "License");
  7447. * you may not use this file except in compliance with the License.
  7448. * You may obtain a copy of the License at
  7449. *
  7450. * http://www.apache.org/licenses/LICENSE-2.0
  7451. *
  7452. * Unless required by applicable law or agreed to in writing, software
  7453. * distributed under the License is distributed on an "AS IS" BASIS,
  7454. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7455. * See the License for the specific language governing permissions and
  7456. * limitations under the License.
  7457. */
  7458. var ListenComplete = /** @class */ (function () {
  7459. function ListenComplete(source, path) {
  7460. this.source = source;
  7461. this.path = path;
  7462. /** @inheritDoc */
  7463. this.type = OperationType.LISTEN_COMPLETE;
  7464. }
  7465. ListenComplete.prototype.operationForChild = function (childName) {
  7466. if (pathIsEmpty(this.path)) {
  7467. return new ListenComplete(this.source, newEmptyPath());
  7468. }
  7469. else {
  7470. return new ListenComplete(this.source, pathPopFront(this.path));
  7471. }
  7472. };
  7473. return ListenComplete;
  7474. }());
  7475. /**
  7476. * @license
  7477. * Copyright 2017 Google LLC
  7478. *
  7479. * Licensed under the Apache License, Version 2.0 (the "License");
  7480. * you may not use this file except in compliance with the License.
  7481. * You may obtain a copy of the License at
  7482. *
  7483. * http://www.apache.org/licenses/LICENSE-2.0
  7484. *
  7485. * Unless required by applicable law or agreed to in writing, software
  7486. * distributed under the License is distributed on an "AS IS" BASIS,
  7487. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7488. * See the License for the specific language governing permissions and
  7489. * limitations under the License.
  7490. */
  7491. var Overwrite = /** @class */ (function () {
  7492. function Overwrite(source, path, snap) {
  7493. this.source = source;
  7494. this.path = path;
  7495. this.snap = snap;
  7496. /** @inheritDoc */
  7497. this.type = OperationType.OVERWRITE;
  7498. }
  7499. Overwrite.prototype.operationForChild = function (childName) {
  7500. if (pathIsEmpty(this.path)) {
  7501. return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
  7502. }
  7503. else {
  7504. return new Overwrite(this.source, pathPopFront(this.path), this.snap);
  7505. }
  7506. };
  7507. return Overwrite;
  7508. }());
  7509. /**
  7510. * @license
  7511. * Copyright 2017 Google LLC
  7512. *
  7513. * Licensed under the Apache License, Version 2.0 (the "License");
  7514. * you may not use this file except in compliance with the License.
  7515. * You may obtain a copy of the License at
  7516. *
  7517. * http://www.apache.org/licenses/LICENSE-2.0
  7518. *
  7519. * Unless required by applicable law or agreed to in writing, software
  7520. * distributed under the License is distributed on an "AS IS" BASIS,
  7521. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7522. * See the License for the specific language governing permissions and
  7523. * limitations under the License.
  7524. */
  7525. var Merge = /** @class */ (function () {
  7526. function Merge(
  7527. /** @inheritDoc */ source,
  7528. /** @inheritDoc */ path,
  7529. /** @inheritDoc */ children) {
  7530. this.source = source;
  7531. this.path = path;
  7532. this.children = children;
  7533. /** @inheritDoc */
  7534. this.type = OperationType.MERGE;
  7535. }
  7536. Merge.prototype.operationForChild = function (childName) {
  7537. if (pathIsEmpty(this.path)) {
  7538. var childTree = this.children.subtree(new Path(childName));
  7539. if (childTree.isEmpty()) {
  7540. // This child is unaffected
  7541. return null;
  7542. }
  7543. else if (childTree.value) {
  7544. // We have a snapshot for the child in question. This becomes an overwrite of the child.
  7545. return new Overwrite(this.source, newEmptyPath(), childTree.value);
  7546. }
  7547. else {
  7548. // This is a merge at a deeper level
  7549. return new Merge(this.source, newEmptyPath(), childTree);
  7550. }
  7551. }
  7552. else {
  7553. util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
  7554. return new Merge(this.source, pathPopFront(this.path), this.children);
  7555. }
  7556. };
  7557. Merge.prototype.toString = function () {
  7558. return ('Operation(' +
  7559. this.path +
  7560. ': ' +
  7561. this.source.toString() +
  7562. ' merge: ' +
  7563. this.children.toString() +
  7564. ')');
  7565. };
  7566. return Merge;
  7567. }());
  7568. /**
  7569. * @license
  7570. * Copyright 2017 Google LLC
  7571. *
  7572. * Licensed under the Apache License, Version 2.0 (the "License");
  7573. * you may not use this file except in compliance with the License.
  7574. * You may obtain a copy of the License at
  7575. *
  7576. * http://www.apache.org/licenses/LICENSE-2.0
  7577. *
  7578. * Unless required by applicable law or agreed to in writing, software
  7579. * distributed under the License is distributed on an "AS IS" BASIS,
  7580. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7581. * See the License for the specific language governing permissions and
  7582. * limitations under the License.
  7583. */
  7584. /**
  7585. * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
  7586. * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
  7587. * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
  7588. * whether a node potentially had children removed due to a filter.
  7589. */
  7590. var CacheNode = /** @class */ (function () {
  7591. function CacheNode(node_, fullyInitialized_, filtered_) {
  7592. this.node_ = node_;
  7593. this.fullyInitialized_ = fullyInitialized_;
  7594. this.filtered_ = filtered_;
  7595. }
  7596. /**
  7597. * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
  7598. */
  7599. CacheNode.prototype.isFullyInitialized = function () {
  7600. return this.fullyInitialized_;
  7601. };
  7602. /**
  7603. * Returns whether this node is potentially missing children due to a filter applied to the node
  7604. */
  7605. CacheNode.prototype.isFiltered = function () {
  7606. return this.filtered_;
  7607. };
  7608. CacheNode.prototype.isCompleteForPath = function (path) {
  7609. if (pathIsEmpty(path)) {
  7610. return this.isFullyInitialized() && !this.filtered_;
  7611. }
  7612. var childKey = pathGetFront(path);
  7613. return this.isCompleteForChild(childKey);
  7614. };
  7615. CacheNode.prototype.isCompleteForChild = function (key) {
  7616. return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
  7617. };
  7618. CacheNode.prototype.getNode = function () {
  7619. return this.node_;
  7620. };
  7621. return CacheNode;
  7622. }());
  7623. /**
  7624. * @license
  7625. * Copyright 2017 Google LLC
  7626. *
  7627. * Licensed under the Apache License, Version 2.0 (the "License");
  7628. * you may not use this file except in compliance with the License.
  7629. * You may obtain a copy of the License at
  7630. *
  7631. * http://www.apache.org/licenses/LICENSE-2.0
  7632. *
  7633. * Unless required by applicable law or agreed to in writing, software
  7634. * distributed under the License is distributed on an "AS IS" BASIS,
  7635. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7636. * See the License for the specific language governing permissions and
  7637. * limitations under the License.
  7638. */
  7639. /**
  7640. * An EventGenerator is used to convert "raw" changes (Change) as computed by the
  7641. * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
  7642. * for details.
  7643. *
  7644. */
  7645. var EventGenerator = /** @class */ (function () {
  7646. function EventGenerator(query_) {
  7647. this.query_ = query_;
  7648. this.index_ = this.query_._queryParams.getIndex();
  7649. }
  7650. return EventGenerator;
  7651. }());
  7652. /**
  7653. * Given a set of raw changes (no moved events and prevName not specified yet), and a set of
  7654. * EventRegistrations that should be notified of these changes, generate the actual events to be raised.
  7655. *
  7656. * Notes:
  7657. * - child_moved events will be synthesized at this time for any child_changed events that affect
  7658. * our index.
  7659. * - prevName will be calculated based on the index ordering.
  7660. */
  7661. function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
  7662. var events = [];
  7663. var moves = [];
  7664. changes.forEach(function (change) {
  7665. if (change.type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  7666. eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
  7667. moves.push(changeChildMoved(change.childName, change.snapshotNode));
  7668. }
  7669. });
  7670. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);
  7671. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);
  7672. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);
  7673. eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);
  7674. eventGeneratorGenerateEventsForType(eventGenerator, events, "value" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);
  7675. return events;
  7676. }
  7677. /**
  7678. * Given changes of a single change type, generate the corresponding events.
  7679. */
  7680. function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
  7681. var filteredChanges = changes.filter(function (change) { return change.type === eventType; });
  7682. filteredChanges.sort(function (a, b) {
  7683. return eventGeneratorCompareChanges(eventGenerator, a, b);
  7684. });
  7685. filteredChanges.forEach(function (change) {
  7686. var materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
  7687. registrations.forEach(function (registration) {
  7688. if (registration.respondsTo(change.type)) {
  7689. events.push(registration.createEvent(materializedChange, eventGenerator.query_));
  7690. }
  7691. });
  7692. });
  7693. }
  7694. function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
  7695. if (change.type === 'value' || change.type === 'child_removed') {
  7696. return change;
  7697. }
  7698. else {
  7699. change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
  7700. return change;
  7701. }
  7702. }
  7703. function eventGeneratorCompareChanges(eventGenerator, a, b) {
  7704. if (a.childName == null || b.childName == null) {
  7705. throw util.assertionError('Should only compare child_ events.');
  7706. }
  7707. var aWrapped = new NamedNode(a.childName, a.snapshotNode);
  7708. var bWrapped = new NamedNode(b.childName, b.snapshotNode);
  7709. return eventGenerator.index_.compare(aWrapped, bWrapped);
  7710. }
  7711. /**
  7712. * @license
  7713. * Copyright 2017 Google LLC
  7714. *
  7715. * Licensed under the Apache License, Version 2.0 (the "License");
  7716. * you may not use this file except in compliance with the License.
  7717. * You may obtain a copy of the License at
  7718. *
  7719. * http://www.apache.org/licenses/LICENSE-2.0
  7720. *
  7721. * Unless required by applicable law or agreed to in writing, software
  7722. * distributed under the License is distributed on an "AS IS" BASIS,
  7723. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7724. * See the License for the specific language governing permissions and
  7725. * limitations under the License.
  7726. */
  7727. function newViewCache(eventCache, serverCache) {
  7728. return { eventCache: eventCache, serverCache: serverCache };
  7729. }
  7730. function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
  7731. return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  7732. }
  7733. function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
  7734. return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  7735. }
  7736. function viewCacheGetCompleteEventSnap(viewCache) {
  7737. return viewCache.eventCache.isFullyInitialized()
  7738. ? viewCache.eventCache.getNode()
  7739. : null;
  7740. }
  7741. function viewCacheGetCompleteServerSnap(viewCache) {
  7742. return viewCache.serverCache.isFullyInitialized()
  7743. ? viewCache.serverCache.getNode()
  7744. : null;
  7745. }
  7746. /**
  7747. * @license
  7748. * Copyright 2017 Google LLC
  7749. *
  7750. * Licensed under the Apache License, Version 2.0 (the "License");
  7751. * you may not use this file except in compliance with the License.
  7752. * You may obtain a copy of the License at
  7753. *
  7754. * http://www.apache.org/licenses/LICENSE-2.0
  7755. *
  7756. * Unless required by applicable law or agreed to in writing, software
  7757. * distributed under the License is distributed on an "AS IS" BASIS,
  7758. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7759. * See the License for the specific language governing permissions and
  7760. * limitations under the License.
  7761. */
  7762. var emptyChildrenSingleton;
  7763. /**
  7764. * Singleton empty children collection.
  7765. *
  7766. */
  7767. var EmptyChildren = function () {
  7768. if (!emptyChildrenSingleton) {
  7769. emptyChildrenSingleton = new SortedMap(stringCompare);
  7770. }
  7771. return emptyChildrenSingleton;
  7772. };
  7773. /**
  7774. * A tree with immutable elements.
  7775. */
  7776. var ImmutableTree = /** @class */ (function () {
  7777. function ImmutableTree(value, children) {
  7778. if (children === void 0) { children = EmptyChildren(); }
  7779. this.value = value;
  7780. this.children = children;
  7781. }
  7782. ImmutableTree.fromObject = function (obj) {
  7783. var tree = new ImmutableTree(null);
  7784. each(obj, function (childPath, childSnap) {
  7785. tree = tree.set(new Path(childPath), childSnap);
  7786. });
  7787. return tree;
  7788. };
  7789. /**
  7790. * True if the value is empty and there are no children
  7791. */
  7792. ImmutableTree.prototype.isEmpty = function () {
  7793. return this.value === null && this.children.isEmpty();
  7794. };
  7795. /**
  7796. * Given a path and predicate, return the first node and the path to that node
  7797. * where the predicate returns true.
  7798. *
  7799. * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
  7800. * objects on the way back out, it may be better to pass down a pathSoFar obj.
  7801. *
  7802. * @param relativePath - The remainder of the path
  7803. * @param predicate - The predicate to satisfy to return a node
  7804. */
  7805. ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {
  7806. if (this.value != null && predicate(this.value)) {
  7807. return { path: newEmptyPath(), value: this.value };
  7808. }
  7809. else {
  7810. if (pathIsEmpty(relativePath)) {
  7811. return null;
  7812. }
  7813. else {
  7814. var front = pathGetFront(relativePath);
  7815. var child = this.children.get(front);
  7816. if (child !== null) {
  7817. var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
  7818. if (childExistingPathAndValue != null) {
  7819. var fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
  7820. return { path: fullPath, value: childExistingPathAndValue.value };
  7821. }
  7822. else {
  7823. return null;
  7824. }
  7825. }
  7826. else {
  7827. return null;
  7828. }
  7829. }
  7830. }
  7831. };
  7832. /**
  7833. * Find, if it exists, the shortest subpath of the given path that points a defined
  7834. * value in the tree
  7835. */
  7836. ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {
  7837. return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });
  7838. };
  7839. /**
  7840. * @returns The subtree at the given path
  7841. */
  7842. ImmutableTree.prototype.subtree = function (relativePath) {
  7843. if (pathIsEmpty(relativePath)) {
  7844. return this;
  7845. }
  7846. else {
  7847. var front = pathGetFront(relativePath);
  7848. var childTree = this.children.get(front);
  7849. if (childTree !== null) {
  7850. return childTree.subtree(pathPopFront(relativePath));
  7851. }
  7852. else {
  7853. return new ImmutableTree(null);
  7854. }
  7855. }
  7856. };
  7857. /**
  7858. * Sets a value at the specified path.
  7859. *
  7860. * @param relativePath - Path to set value at.
  7861. * @param toSet - Value to set.
  7862. * @returns Resulting tree.
  7863. */
  7864. ImmutableTree.prototype.set = function (relativePath, toSet) {
  7865. if (pathIsEmpty(relativePath)) {
  7866. return new ImmutableTree(toSet, this.children);
  7867. }
  7868. else {
  7869. var front = pathGetFront(relativePath);
  7870. var child = this.children.get(front) || new ImmutableTree(null);
  7871. var newChild = child.set(pathPopFront(relativePath), toSet);
  7872. var newChildren = this.children.insert(front, newChild);
  7873. return new ImmutableTree(this.value, newChildren);
  7874. }
  7875. };
  7876. /**
  7877. * Removes the value at the specified path.
  7878. *
  7879. * @param relativePath - Path to value to remove.
  7880. * @returns Resulting tree.
  7881. */
  7882. ImmutableTree.prototype.remove = function (relativePath) {
  7883. if (pathIsEmpty(relativePath)) {
  7884. if (this.children.isEmpty()) {
  7885. return new ImmutableTree(null);
  7886. }
  7887. else {
  7888. return new ImmutableTree(null, this.children);
  7889. }
  7890. }
  7891. else {
  7892. var front = pathGetFront(relativePath);
  7893. var child = this.children.get(front);
  7894. if (child) {
  7895. var newChild = child.remove(pathPopFront(relativePath));
  7896. var newChildren = void 0;
  7897. if (newChild.isEmpty()) {
  7898. newChildren = this.children.remove(front);
  7899. }
  7900. else {
  7901. newChildren = this.children.insert(front, newChild);
  7902. }
  7903. if (this.value === null && newChildren.isEmpty()) {
  7904. return new ImmutableTree(null);
  7905. }
  7906. else {
  7907. return new ImmutableTree(this.value, newChildren);
  7908. }
  7909. }
  7910. else {
  7911. return this;
  7912. }
  7913. }
  7914. };
  7915. /**
  7916. * Gets a value from the tree.
  7917. *
  7918. * @param relativePath - Path to get value for.
  7919. * @returns Value at path, or null.
  7920. */
  7921. ImmutableTree.prototype.get = function (relativePath) {
  7922. if (pathIsEmpty(relativePath)) {
  7923. return this.value;
  7924. }
  7925. else {
  7926. var front = pathGetFront(relativePath);
  7927. var child = this.children.get(front);
  7928. if (child) {
  7929. return child.get(pathPopFront(relativePath));
  7930. }
  7931. else {
  7932. return null;
  7933. }
  7934. }
  7935. };
  7936. /**
  7937. * Replace the subtree at the specified path with the given new tree.
  7938. *
  7939. * @param relativePath - Path to replace subtree for.
  7940. * @param newTree - New tree.
  7941. * @returns Resulting tree.
  7942. */
  7943. ImmutableTree.prototype.setTree = function (relativePath, newTree) {
  7944. if (pathIsEmpty(relativePath)) {
  7945. return newTree;
  7946. }
  7947. else {
  7948. var front = pathGetFront(relativePath);
  7949. var child = this.children.get(front) || new ImmutableTree(null);
  7950. var newChild = child.setTree(pathPopFront(relativePath), newTree);
  7951. var newChildren = void 0;
  7952. if (newChild.isEmpty()) {
  7953. newChildren = this.children.remove(front);
  7954. }
  7955. else {
  7956. newChildren = this.children.insert(front, newChild);
  7957. }
  7958. return new ImmutableTree(this.value, newChildren);
  7959. }
  7960. };
  7961. /**
  7962. * Performs a depth first fold on this tree. Transforms a tree into a single
  7963. * value, given a function that operates on the path to a node, an optional
  7964. * current value, and a map of child names to folded subtrees
  7965. */
  7966. ImmutableTree.prototype.fold = function (fn) {
  7967. return this.fold_(newEmptyPath(), fn);
  7968. };
  7969. /**
  7970. * Recursive helper for public-facing fold() method
  7971. */
  7972. ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {
  7973. var accum = {};
  7974. this.children.inorderTraversal(function (childKey, childTree) {
  7975. accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
  7976. });
  7977. return fn(pathSoFar, this.value, accum);
  7978. };
  7979. /**
  7980. * Find the first matching value on the given path. Return the result of applying f to it.
  7981. */
  7982. ImmutableTree.prototype.findOnPath = function (path, f) {
  7983. return this.findOnPath_(path, newEmptyPath(), f);
  7984. };
  7985. ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {
  7986. var result = this.value ? f(pathSoFar, this.value) : false;
  7987. if (result) {
  7988. return result;
  7989. }
  7990. else {
  7991. if (pathIsEmpty(pathToFollow)) {
  7992. return null;
  7993. }
  7994. else {
  7995. var front = pathGetFront(pathToFollow);
  7996. var nextChild = this.children.get(front);
  7997. if (nextChild) {
  7998. return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
  7999. }
  8000. else {
  8001. return null;
  8002. }
  8003. }
  8004. }
  8005. };
  8006. ImmutableTree.prototype.foreachOnPath = function (path, f) {
  8007. return this.foreachOnPath_(path, newEmptyPath(), f);
  8008. };
  8009. ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {
  8010. if (pathIsEmpty(pathToFollow)) {
  8011. return this;
  8012. }
  8013. else {
  8014. if (this.value) {
  8015. f(currentRelativePath, this.value);
  8016. }
  8017. var front = pathGetFront(pathToFollow);
  8018. var nextChild = this.children.get(front);
  8019. if (nextChild) {
  8020. return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
  8021. }
  8022. else {
  8023. return new ImmutableTree(null);
  8024. }
  8025. }
  8026. };
  8027. /**
  8028. * Calls the given function for each node in the tree that has a value.
  8029. *
  8030. * @param f - A function to be called with the path from the root of the tree to
  8031. * a node, and the value at that node. Called in depth-first order.
  8032. */
  8033. ImmutableTree.prototype.foreach = function (f) {
  8034. this.foreach_(newEmptyPath(), f);
  8035. };
  8036. ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {
  8037. this.children.inorderTraversal(function (childName, childTree) {
  8038. childTree.foreach_(pathChild(currentRelativePath, childName), f);
  8039. });
  8040. if (this.value) {
  8041. f(currentRelativePath, this.value);
  8042. }
  8043. };
  8044. ImmutableTree.prototype.foreachChild = function (f) {
  8045. this.children.inorderTraversal(function (childName, childTree) {
  8046. if (childTree.value) {
  8047. f(childName, childTree.value);
  8048. }
  8049. });
  8050. };
  8051. return ImmutableTree;
  8052. }());
  8053. /**
  8054. * @license
  8055. * Copyright 2017 Google LLC
  8056. *
  8057. * Licensed under the Apache License, Version 2.0 (the "License");
  8058. * you may not use this file except in compliance with the License.
  8059. * You may obtain a copy of the License at
  8060. *
  8061. * http://www.apache.org/licenses/LICENSE-2.0
  8062. *
  8063. * Unless required by applicable law or agreed to in writing, software
  8064. * distributed under the License is distributed on an "AS IS" BASIS,
  8065. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8066. * See the License for the specific language governing permissions and
  8067. * limitations under the License.
  8068. */
  8069. /**
  8070. * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
  8071. * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
  8072. * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
  8073. * to reflect the write added.
  8074. */
  8075. var CompoundWrite = /** @class */ (function () {
  8076. function CompoundWrite(writeTree_) {
  8077. this.writeTree_ = writeTree_;
  8078. }
  8079. CompoundWrite.empty = function () {
  8080. return new CompoundWrite(new ImmutableTree(null));
  8081. };
  8082. return CompoundWrite;
  8083. }());
  8084. function compoundWriteAddWrite(compoundWrite, path, node) {
  8085. if (pathIsEmpty(path)) {
  8086. return new CompoundWrite(new ImmutableTree(node));
  8087. }
  8088. else {
  8089. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8090. if (rootmost != null) {
  8091. var rootMostPath = rootmost.path;
  8092. var value = rootmost.value;
  8093. var relativePath = newRelativePath(rootMostPath, path);
  8094. value = value.updateChild(relativePath, node);
  8095. return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
  8096. }
  8097. else {
  8098. var subtree = new ImmutableTree(node);
  8099. var newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
  8100. return new CompoundWrite(newWriteTree);
  8101. }
  8102. }
  8103. }
  8104. function compoundWriteAddWrites(compoundWrite, path, updates) {
  8105. var newWrite = compoundWrite;
  8106. each(updates, function (childKey, node) {
  8107. newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
  8108. });
  8109. return newWrite;
  8110. }
  8111. /**
  8112. * Will remove a write at the given path and deeper paths. This will <em>not</em> modify a write at a higher
  8113. * location, which must be removed by calling this method with that path.
  8114. *
  8115. * @param compoundWrite - The CompoundWrite to remove.
  8116. * @param path - The path at which a write and all deeper writes should be removed
  8117. * @returns The new CompoundWrite with the removed path
  8118. */
  8119. function compoundWriteRemoveWrite(compoundWrite, path) {
  8120. if (pathIsEmpty(path)) {
  8121. return CompoundWrite.empty();
  8122. }
  8123. else {
  8124. var newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
  8125. return new CompoundWrite(newWriteTree);
  8126. }
  8127. }
  8128. /**
  8129. * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be
  8130. * considered "complete".
  8131. *
  8132. * @param compoundWrite - The CompoundWrite to check.
  8133. * @param path - The path to check for
  8134. * @returns Whether there is a complete write at that path
  8135. */
  8136. function compoundWriteHasCompleteWrite(compoundWrite, path) {
  8137. return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  8138. }
  8139. /**
  8140. * Returns a node for a path if and only if the node is a "complete" overwrite at that path. This will not aggregate
  8141. * writes from deeper paths, but will return child nodes from a more shallow path.
  8142. *
  8143. * @param compoundWrite - The CompoundWrite to get the node from.
  8144. * @param path - The path to get a complete write
  8145. * @returns The node if complete at that path, or null otherwise.
  8146. */
  8147. function compoundWriteGetCompleteNode(compoundWrite, path) {
  8148. var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
  8149. if (rootmost != null) {
  8150. return compoundWrite.writeTree_
  8151. .get(rootmost.path)
  8152. .getChild(newRelativePath(rootmost.path, path));
  8153. }
  8154. else {
  8155. return null;
  8156. }
  8157. }
  8158. /**
  8159. * Returns all children that are guaranteed to be a complete overwrite.
  8160. *
  8161. * @param compoundWrite - The CompoundWrite to get children from.
  8162. * @returns A list of all complete children.
  8163. */
  8164. function compoundWriteGetCompleteChildren(compoundWrite) {
  8165. var children = [];
  8166. var node = compoundWrite.writeTree_.value;
  8167. if (node != null) {
  8168. // If it's a leaf node, it has no children; so nothing to do.
  8169. if (!node.isLeafNode()) {
  8170. node.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8171. children.push(new NamedNode(childName, childNode));
  8172. });
  8173. }
  8174. }
  8175. else {
  8176. compoundWrite.writeTree_.children.inorderTraversal(function (childName, childTree) {
  8177. if (childTree.value != null) {
  8178. children.push(new NamedNode(childName, childTree.value));
  8179. }
  8180. });
  8181. }
  8182. return children;
  8183. }
  8184. function compoundWriteChildCompoundWrite(compoundWrite, path) {
  8185. if (pathIsEmpty(path)) {
  8186. return compoundWrite;
  8187. }
  8188. else {
  8189. var shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
  8190. if (shadowingNode != null) {
  8191. return new CompoundWrite(new ImmutableTree(shadowingNode));
  8192. }
  8193. else {
  8194. return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
  8195. }
  8196. }
  8197. }
  8198. /**
  8199. * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.
  8200. * @returns Whether this CompoundWrite is empty
  8201. */
  8202. function compoundWriteIsEmpty(compoundWrite) {
  8203. return compoundWrite.writeTree_.isEmpty();
  8204. }
  8205. /**
  8206. * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the
  8207. * node
  8208. * @param node - The node to apply this CompoundWrite to
  8209. * @returns The node with all writes applied
  8210. */
  8211. function compoundWriteApply(compoundWrite, node) {
  8212. return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  8213. }
  8214. function applySubtreeWrite(relativePath, writeTree, node) {
  8215. if (writeTree.value != null) {
  8216. // Since there a write is always a leaf, we're done here
  8217. return node.updateChild(relativePath, writeTree.value);
  8218. }
  8219. else {
  8220. var priorityWrite_1 = null;
  8221. writeTree.children.inorderTraversal(function (childKey, childTree) {
  8222. if (childKey === '.priority') {
  8223. // Apply priorities at the end so we don't update priorities for either empty nodes or forget
  8224. // to apply priorities to empty nodes that are later filled
  8225. util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
  8226. priorityWrite_1 = childTree.value;
  8227. }
  8228. else {
  8229. node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
  8230. }
  8231. });
  8232. // If there was a priority write, we only apply it if the node is not empty
  8233. if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {
  8234. node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite_1);
  8235. }
  8236. return node;
  8237. }
  8238. }
  8239. /**
  8240. * @license
  8241. * Copyright 2017 Google LLC
  8242. *
  8243. * Licensed under the Apache License, Version 2.0 (the "License");
  8244. * you may not use this file except in compliance with the License.
  8245. * You may obtain a copy of the License at
  8246. *
  8247. * http://www.apache.org/licenses/LICENSE-2.0
  8248. *
  8249. * Unless required by applicable law or agreed to in writing, software
  8250. * distributed under the License is distributed on an "AS IS" BASIS,
  8251. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8252. * See the License for the specific language governing permissions and
  8253. * limitations under the License.
  8254. */
  8255. /**
  8256. * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.
  8257. *
  8258. */
  8259. function writeTreeChildWrites(writeTree, path) {
  8260. return newWriteTreeRef(path, writeTree);
  8261. }
  8262. /**
  8263. * Record a new overwrite from user code.
  8264. *
  8265. * @param visible - This is set to false by some transactions. It should be excluded from event caches
  8266. */
  8267. function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
  8268. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
  8269. if (visible === undefined) {
  8270. visible = true;
  8271. }
  8272. writeTree.allWrites.push({
  8273. path: path,
  8274. snap: snap,
  8275. writeId: writeId,
  8276. visible: visible
  8277. });
  8278. if (visible) {
  8279. writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
  8280. }
  8281. writeTree.lastWriteId = writeId;
  8282. }
  8283. /**
  8284. * Record a new merge from user code.
  8285. */
  8286. function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
  8287. util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
  8288. writeTree.allWrites.push({
  8289. path: path,
  8290. children: changedChildren,
  8291. writeId: writeId,
  8292. visible: true
  8293. });
  8294. writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
  8295. writeTree.lastWriteId = writeId;
  8296. }
  8297. function writeTreeGetWrite(writeTree, writeId) {
  8298. for (var i = 0; i < writeTree.allWrites.length; i++) {
  8299. var record = writeTree.allWrites[i];
  8300. if (record.writeId === writeId) {
  8301. return record;
  8302. }
  8303. }
  8304. return null;
  8305. }
  8306. /**
  8307. * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates
  8308. * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.
  8309. *
  8310. * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise
  8311. * events as a result).
  8312. */
  8313. function writeTreeRemoveWrite(writeTree, writeId) {
  8314. // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied
  8315. // out of order.
  8316. //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;
  8317. //assert(validClear, "Either we don't have this write, or it's the first one in the queue");
  8318. var idx = writeTree.allWrites.findIndex(function (s) {
  8319. return s.writeId === writeId;
  8320. });
  8321. util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
  8322. var writeToRemove = writeTree.allWrites[idx];
  8323. writeTree.allWrites.splice(idx, 1);
  8324. var removedWriteWasVisible = writeToRemove.visible;
  8325. var removedWriteOverlapsWithOtherWrites = false;
  8326. var i = writeTree.allWrites.length - 1;
  8327. while (removedWriteWasVisible && i >= 0) {
  8328. var currentWrite = writeTree.allWrites[i];
  8329. if (currentWrite.visible) {
  8330. if (i >= idx &&
  8331. writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
  8332. // The removed write was completely shadowed by a subsequent write.
  8333. removedWriteWasVisible = false;
  8334. }
  8335. else if (pathContains(writeToRemove.path, currentWrite.path)) {
  8336. // Either we're covering some writes or they're covering part of us (depending on which came first).
  8337. removedWriteOverlapsWithOtherWrites = true;
  8338. }
  8339. }
  8340. i--;
  8341. }
  8342. if (!removedWriteWasVisible) {
  8343. return false;
  8344. }
  8345. else if (removedWriteOverlapsWithOtherWrites) {
  8346. // There's some shadowing going on. Just rebuild the visible writes from scratch.
  8347. writeTreeResetTree_(writeTree);
  8348. return true;
  8349. }
  8350. else {
  8351. // There's no shadowing. We can safely just remove the write(s) from visibleWrites.
  8352. if (writeToRemove.snap) {
  8353. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
  8354. }
  8355. else {
  8356. var children = writeToRemove.children;
  8357. each(children, function (childName) {
  8358. writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
  8359. });
  8360. }
  8361. return true;
  8362. }
  8363. }
  8364. function writeTreeRecordContainsPath_(writeRecord, path) {
  8365. if (writeRecord.snap) {
  8366. return pathContains(writeRecord.path, path);
  8367. }
  8368. else {
  8369. for (var childName in writeRecord.children) {
  8370. if (writeRecord.children.hasOwnProperty(childName) &&
  8371. pathContains(pathChild(writeRecord.path, childName), path)) {
  8372. return true;
  8373. }
  8374. }
  8375. return false;
  8376. }
  8377. }
  8378. /**
  8379. * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots
  8380. */
  8381. function writeTreeResetTree_(writeTree) {
  8382. writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
  8383. if (writeTree.allWrites.length > 0) {
  8384. writeTree.lastWriteId =
  8385. writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
  8386. }
  8387. else {
  8388. writeTree.lastWriteId = -1;
  8389. }
  8390. }
  8391. /**
  8392. * The default filter used when constructing the tree. Keep everything that's visible.
  8393. */
  8394. function writeTreeDefaultFilter_(write) {
  8395. return write.visible;
  8396. }
  8397. /**
  8398. * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of
  8399. * event data at that path.
  8400. */
  8401. function writeTreeLayerTree_(writes, filter, treeRoot) {
  8402. var compoundWrite = CompoundWrite.empty();
  8403. for (var i = 0; i < writes.length; ++i) {
  8404. var write = writes[i];
  8405. // Theory, a later set will either:
  8406. // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction
  8407. // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction
  8408. if (filter(write)) {
  8409. var writePath = write.path;
  8410. var relativePath = void 0;
  8411. if (write.snap) {
  8412. if (pathContains(treeRoot, writePath)) {
  8413. relativePath = newRelativePath(treeRoot, writePath);
  8414. compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
  8415. }
  8416. else if (pathContains(writePath, treeRoot)) {
  8417. relativePath = newRelativePath(writePath, treeRoot);
  8418. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
  8419. }
  8420. else ;
  8421. }
  8422. else if (write.children) {
  8423. if (pathContains(treeRoot, writePath)) {
  8424. relativePath = newRelativePath(treeRoot, writePath);
  8425. compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
  8426. }
  8427. else if (pathContains(writePath, treeRoot)) {
  8428. relativePath = newRelativePath(writePath, treeRoot);
  8429. if (pathIsEmpty(relativePath)) {
  8430. compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
  8431. }
  8432. else {
  8433. var child = util.safeGet(write.children, pathGetFront(relativePath));
  8434. if (child) {
  8435. // There exists a child in this node that matches the root path
  8436. var deepNode = child.getChild(pathPopFront(relativePath));
  8437. compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
  8438. }
  8439. }
  8440. }
  8441. else ;
  8442. }
  8443. else {
  8444. throw util.assertionError('WriteRecord should have .snap or .children');
  8445. }
  8446. }
  8447. }
  8448. return compoundWrite;
  8449. }
  8450. /**
  8451. * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden
  8452. * writes), attempt to calculate a complete snapshot for the given path
  8453. *
  8454. * @param writeIdsToExclude - An optional set to be excluded
  8455. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8456. */
  8457. function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8458. if (!writeIdsToExclude && !includeHiddenWrites) {
  8459. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8460. if (shadowingNode != null) {
  8461. return shadowingNode;
  8462. }
  8463. else {
  8464. var subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8465. if (compoundWriteIsEmpty(subMerge)) {
  8466. return completeServerCache;
  8467. }
  8468. else if (completeServerCache == null &&
  8469. !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
  8470. // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow
  8471. return null;
  8472. }
  8473. else {
  8474. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8475. return compoundWriteApply(subMerge, layeredCache);
  8476. }
  8477. }
  8478. }
  8479. else {
  8480. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8481. if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
  8482. return completeServerCache;
  8483. }
  8484. else {
  8485. // If the server cache is null, and we don't have a complete cache, we need to return null
  8486. if (!includeHiddenWrites &&
  8487. completeServerCache == null &&
  8488. !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
  8489. return null;
  8490. }
  8491. else {
  8492. var filter = function (write) {
  8493. return ((write.visible || includeHiddenWrites) &&
  8494. (!writeIdsToExclude ||
  8495. !~writeIdsToExclude.indexOf(write.writeId)) &&
  8496. (pathContains(write.path, treePath) ||
  8497. pathContains(treePath, write.path)));
  8498. };
  8499. var mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
  8500. var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
  8501. return compoundWriteApply(mergeAtPath, layeredCache);
  8502. }
  8503. }
  8504. }
  8505. }
  8506. /**
  8507. * With optional, underlying server data, attempt to return a children node of children that we have complete data for.
  8508. * Used when creating new views, to pre-fill their complete event children snapshot.
  8509. */
  8510. function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
  8511. var completeChildren = ChildrenNode.EMPTY_NODE;
  8512. var topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
  8513. if (topLevelSet) {
  8514. if (!topLevelSet.isLeafNode()) {
  8515. // we're shadowing everything. Return the children.
  8516. topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) {
  8517. completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
  8518. });
  8519. }
  8520. return completeChildren;
  8521. }
  8522. else if (completeServerChildren) {
  8523. // Layer any children we have on top of this
  8524. // We know we don't have a top-level set, so just enumerate existing children
  8525. var merge_1 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8526. completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  8527. var node = compoundWriteApply(compoundWriteChildCompoundWrite(merge_1, new Path(childName)), childNode);
  8528. completeChildren = completeChildren.updateImmediateChild(childName, node);
  8529. });
  8530. // Add any complete children we have from the set
  8531. compoundWriteGetCompleteChildren(merge_1).forEach(function (namedNode) {
  8532. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8533. });
  8534. return completeChildren;
  8535. }
  8536. else {
  8537. // We don't have anything to layer on top of. Layer on any children we have
  8538. // Note that we can return an empty snap if we have a defined delete
  8539. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8540. compoundWriteGetCompleteChildren(merge).forEach(function (namedNode) {
  8541. completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
  8542. });
  8543. return completeChildren;
  8544. }
  8545. }
  8546. /**
  8547. * Given that the underlying server data has updated, determine what, if anything, needs to be
  8548. * applied to the event cache.
  8549. *
  8550. * Possibilities:
  8551. *
  8552. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8553. *
  8554. * 2. Some write is completely shadowing. No events to be raised
  8555. *
  8556. * 3. Is partially shadowed. Events
  8557. *
  8558. * Either existingEventSnap or existingServerSnap must exist
  8559. */
  8560. function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
  8561. util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
  8562. var path = pathChild(treePath, childPath);
  8563. if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
  8564. // At this point we can probably guarantee that we're in case 2, meaning no events
  8565. // May need to check visibility while doing the findRootMostValueAndPath call
  8566. return null;
  8567. }
  8568. else {
  8569. // No complete shadowing. We're either partially shadowing or not shadowing at all.
  8570. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8571. if (compoundWriteIsEmpty(childMerge)) {
  8572. // We're not shadowing at all. Case 1
  8573. return existingServerSnap.getChild(childPath);
  8574. }
  8575. else {
  8576. // This could be more efficient if the serverNode + updates doesn't change the eventSnap
  8577. // However this is tricky to find out, since user updates don't necessary change the server
  8578. // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server
  8579. // adds nodes, but doesn't change any existing writes. It is therefore not enough to
  8580. // only check if the updates change the serverNode.
  8581. // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?
  8582. return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
  8583. }
  8584. }
  8585. }
  8586. /**
  8587. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8588. * complete child for this ChildKey.
  8589. */
  8590. function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
  8591. var path = pathChild(treePath, childKey);
  8592. var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8593. if (shadowingNode != null) {
  8594. return shadowingNode;
  8595. }
  8596. else {
  8597. if (existingServerSnap.isCompleteForChild(childKey)) {
  8598. var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
  8599. return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
  8600. }
  8601. else {
  8602. return null;
  8603. }
  8604. }
  8605. }
  8606. /**
  8607. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8608. * a higher path, this will return the child of that write relative to the write and this path.
  8609. * Returns null if there is no write at this path.
  8610. */
  8611. function writeTreeShadowingWrite(writeTree, path) {
  8612. return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  8613. }
  8614. /**
  8615. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8616. * the window, but may now be in the window.
  8617. */
  8618. function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
  8619. var toIterate;
  8620. var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
  8621. var shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
  8622. if (shadowingNode != null) {
  8623. toIterate = shadowingNode;
  8624. }
  8625. else if (completeServerData != null) {
  8626. toIterate = compoundWriteApply(merge, completeServerData);
  8627. }
  8628. else {
  8629. // no children to iterate on
  8630. return [];
  8631. }
  8632. toIterate = toIterate.withIndex(index);
  8633. if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
  8634. var nodes = [];
  8635. var cmp = index.getCompare();
  8636. var iter = reverse
  8637. ? toIterate.getReverseIteratorFrom(startPost, index)
  8638. : toIterate.getIteratorFrom(startPost, index);
  8639. var next = iter.getNext();
  8640. while (next && nodes.length < count) {
  8641. if (cmp(next, startPost) !== 0) {
  8642. nodes.push(next);
  8643. }
  8644. next = iter.getNext();
  8645. }
  8646. return nodes;
  8647. }
  8648. else {
  8649. return [];
  8650. }
  8651. }
  8652. function newWriteTree() {
  8653. return {
  8654. visibleWrites: CompoundWrite.empty(),
  8655. allWrites: [],
  8656. lastWriteId: -1
  8657. };
  8658. }
  8659. /**
  8660. * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used
  8661. * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node
  8662. * can lead to a more expensive calculation.
  8663. *
  8664. * @param writeIdsToExclude - Optional writes to exclude.
  8665. * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false
  8666. */
  8667. function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
  8668. return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  8669. }
  8670. /**
  8671. * If possible, returns a children node containing all of the complete children we have data for. The returned data is a
  8672. * mix of the given server data and write data.
  8673. *
  8674. */
  8675. function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
  8676. return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  8677. }
  8678. /**
  8679. * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,
  8680. * if anything, needs to be applied to the event cache.
  8681. *
  8682. * Possibilities:
  8683. *
  8684. * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data
  8685. *
  8686. * 2. Some write is completely shadowing. No events to be raised
  8687. *
  8688. * 3. Is partially shadowed. Events should be raised
  8689. *
  8690. * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert
  8691. *
  8692. *
  8693. */
  8694. function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
  8695. return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  8696. }
  8697. /**
  8698. * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at
  8699. * a higher path, this will return the child of that write relative to the write and this path.
  8700. * Returns null if there is no write at this path.
  8701. *
  8702. */
  8703. function writeTreeRefShadowingWrite(writeTreeRef, path) {
  8704. return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  8705. }
  8706. /**
  8707. * This method is used when processing child remove events on a query. If we can, we pull in children that were outside
  8708. * the window, but may now be in the window
  8709. */
  8710. function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
  8711. return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
  8712. }
  8713. /**
  8714. * Returns a complete child for a given server snap after applying all user writes or null if there is no
  8715. * complete child for this ChildKey.
  8716. */
  8717. function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
  8718. return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  8719. }
  8720. /**
  8721. * Return a WriteTreeRef for a child.
  8722. */
  8723. function writeTreeRefChild(writeTreeRef, childName) {
  8724. return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  8725. }
  8726. function newWriteTreeRef(path, writeTree) {
  8727. return {
  8728. treePath: path,
  8729. writeTree: writeTree
  8730. };
  8731. }
  8732. /**
  8733. * @license
  8734. * Copyright 2017 Google LLC
  8735. *
  8736. * Licensed under the Apache License, Version 2.0 (the "License");
  8737. * you may not use this file except in compliance with the License.
  8738. * You may obtain a copy of the License at
  8739. *
  8740. * http://www.apache.org/licenses/LICENSE-2.0
  8741. *
  8742. * Unless required by applicable law or agreed to in writing, software
  8743. * distributed under the License is distributed on an "AS IS" BASIS,
  8744. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8745. * See the License for the specific language governing permissions and
  8746. * limitations under the License.
  8747. */
  8748. var ChildChangeAccumulator = /** @class */ (function () {
  8749. function ChildChangeAccumulator() {
  8750. this.changeMap = new Map();
  8751. }
  8752. ChildChangeAccumulator.prototype.trackChildChange = function (change) {
  8753. var type = change.type;
  8754. var childKey = change.childName;
  8755. util.assert(type === "child_added" /* ChangeType.CHILD_ADDED */ ||
  8756. type === "child_changed" /* ChangeType.CHILD_CHANGED */ ||
  8757. type === "child_removed" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');
  8758. util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
  8759. var oldChange = this.changeMap.get(childKey);
  8760. if (oldChange) {
  8761. var oldType = oldChange.type;
  8762. if (type === "child_added" /* ChangeType.CHILD_ADDED */ &&
  8763. oldType === "child_removed" /* ChangeType.CHILD_REMOVED */) {
  8764. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
  8765. }
  8766. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8767. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8768. this.changeMap.delete(childKey);
  8769. }
  8770. else if (type === "child_removed" /* ChangeType.CHILD_REMOVED */ &&
  8771. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8772. this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
  8773. }
  8774. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8775. oldType === "child_added" /* ChangeType.CHILD_ADDED */) {
  8776. this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
  8777. }
  8778. else if (type === "child_changed" /* ChangeType.CHILD_CHANGED */ &&
  8779. oldType === "child_changed" /* ChangeType.CHILD_CHANGED */) {
  8780. this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
  8781. }
  8782. else {
  8783. throw util.assertionError('Illegal combination of changes: ' +
  8784. change +
  8785. ' occurred after ' +
  8786. oldChange);
  8787. }
  8788. }
  8789. else {
  8790. this.changeMap.set(childKey, change);
  8791. }
  8792. };
  8793. ChildChangeAccumulator.prototype.getChanges = function () {
  8794. return Array.from(this.changeMap.values());
  8795. };
  8796. return ChildChangeAccumulator;
  8797. }());
  8798. /**
  8799. * @license
  8800. * Copyright 2017 Google LLC
  8801. *
  8802. * Licensed under the Apache License, Version 2.0 (the "License");
  8803. * you may not use this file except in compliance with the License.
  8804. * You may obtain a copy of the License at
  8805. *
  8806. * http://www.apache.org/licenses/LICENSE-2.0
  8807. *
  8808. * Unless required by applicable law or agreed to in writing, software
  8809. * distributed under the License is distributed on an "AS IS" BASIS,
  8810. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8811. * See the License for the specific language governing permissions and
  8812. * limitations under the License.
  8813. */
  8814. /**
  8815. * An implementation of CompleteChildSource that never returns any additional children
  8816. */
  8817. // eslint-disable-next-line @typescript-eslint/naming-convention
  8818. var NoCompleteChildSource_ = /** @class */ (function () {
  8819. function NoCompleteChildSource_() {
  8820. }
  8821. NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {
  8822. return null;
  8823. };
  8824. NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {
  8825. return null;
  8826. };
  8827. return NoCompleteChildSource_;
  8828. }());
  8829. /**
  8830. * Singleton instance.
  8831. */
  8832. var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  8833. /**
  8834. * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or
  8835. * old event caches available to calculate complete children.
  8836. */
  8837. var WriteTreeCompleteChildSource = /** @class */ (function () {
  8838. function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {
  8839. if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }
  8840. this.writes_ = writes_;
  8841. this.viewCache_ = viewCache_;
  8842. this.optCompleteServerCache_ = optCompleteServerCache_;
  8843. }
  8844. WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {
  8845. var node = this.viewCache_.eventCache;
  8846. if (node.isCompleteForChild(childKey)) {
  8847. return node.getNode().getImmediateChild(childKey);
  8848. }
  8849. else {
  8850. var serverNode = this.optCompleteServerCache_ != null
  8851. ? new CacheNode(this.optCompleteServerCache_, true, false)
  8852. : this.viewCache_.serverCache;
  8853. return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
  8854. }
  8855. };
  8856. WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {
  8857. var completeServerData = this.optCompleteServerCache_ != null
  8858. ? this.optCompleteServerCache_
  8859. : viewCacheGetCompleteServerSnap(this.viewCache_);
  8860. var nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
  8861. if (nodes.length === 0) {
  8862. return null;
  8863. }
  8864. else {
  8865. return nodes[0];
  8866. }
  8867. };
  8868. return WriteTreeCompleteChildSource;
  8869. }());
  8870. /**
  8871. * @license
  8872. * Copyright 2017 Google LLC
  8873. *
  8874. * Licensed under the Apache License, Version 2.0 (the "License");
  8875. * you may not use this file except in compliance with the License.
  8876. * You may obtain a copy of the License at
  8877. *
  8878. * http://www.apache.org/licenses/LICENSE-2.0
  8879. *
  8880. * Unless required by applicable law or agreed to in writing, software
  8881. * distributed under the License is distributed on an "AS IS" BASIS,
  8882. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8883. * See the License for the specific language governing permissions and
  8884. * limitations under the License.
  8885. */
  8886. function newViewProcessor(filter) {
  8887. return { filter: filter };
  8888. }
  8889. function viewProcessorAssertIndexed(viewProcessor, viewCache) {
  8890. util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
  8891. util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
  8892. }
  8893. function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
  8894. var accumulator = new ChildChangeAccumulator();
  8895. var newViewCache, filterServerNode;
  8896. if (operation.type === OperationType.OVERWRITE) {
  8897. var overwrite = operation;
  8898. if (overwrite.source.fromUser) {
  8899. newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
  8900. }
  8901. else {
  8902. util.assert(overwrite.source.fromServer, 'Unknown source.');
  8903. // We filter the node if it's a tagged update or the node has been previously filtered and the
  8904. // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered
  8905. // again
  8906. filterServerNode =
  8907. overwrite.source.tagged ||
  8908. (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
  8909. newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
  8910. }
  8911. }
  8912. else if (operation.type === OperationType.MERGE) {
  8913. var merge = operation;
  8914. if (merge.source.fromUser) {
  8915. newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
  8916. }
  8917. else {
  8918. util.assert(merge.source.fromServer, 'Unknown source.');
  8919. // We filter the node if it's a tagged update or the node has been previously filtered
  8920. filterServerNode =
  8921. merge.source.tagged || oldViewCache.serverCache.isFiltered();
  8922. newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
  8923. }
  8924. }
  8925. else if (operation.type === OperationType.ACK_USER_WRITE) {
  8926. var ackUserWrite = operation;
  8927. if (!ackUserWrite.revert) {
  8928. newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
  8929. }
  8930. else {
  8931. newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
  8932. }
  8933. }
  8934. else if (operation.type === OperationType.LISTEN_COMPLETE) {
  8935. newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
  8936. }
  8937. else {
  8938. throw util.assertionError('Unknown operation type: ' + operation.type);
  8939. }
  8940. var changes = accumulator.getChanges();
  8941. viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
  8942. return { viewCache: newViewCache, changes: changes };
  8943. }
  8944. function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
  8945. var eventSnap = newViewCache.eventCache;
  8946. if (eventSnap.isFullyInitialized()) {
  8947. var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
  8948. var oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
  8949. if (accumulator.length > 0 ||
  8950. !oldViewCache.eventCache.isFullyInitialized() ||
  8951. (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
  8952. !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
  8953. accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
  8954. }
  8955. }
  8956. }
  8957. function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
  8958. var oldEventSnap = viewCache.eventCache;
  8959. if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
  8960. // we have a shadowing write, ignore changes
  8961. return viewCache;
  8962. }
  8963. else {
  8964. var newEventCache = void 0, serverNode = void 0;
  8965. if (pathIsEmpty(changePath)) {
  8966. // TODO: figure out how this plays with "sliding ack windows"
  8967. util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
  8968. if (viewCache.serverCache.isFiltered()) {
  8969. // We need to special case this, because we need to only apply writes to complete children, or
  8970. // we might end up raising events for incomplete children. If the server data is filtered deep
  8971. // writes cannot be guaranteed to be complete
  8972. var serverCache = viewCacheGetCompleteServerSnap(viewCache);
  8973. var completeChildren = serverCache instanceof ChildrenNode
  8974. ? serverCache
  8975. : ChildrenNode.EMPTY_NODE;
  8976. var completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
  8977. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
  8978. }
  8979. else {
  8980. var completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  8981. newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
  8982. }
  8983. }
  8984. else {
  8985. var childKey = pathGetFront(changePath);
  8986. if (childKey === '.priority') {
  8987. util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
  8988. var oldEventNode = oldEventSnap.getNode();
  8989. serverNode = viewCache.serverCache.getNode();
  8990. // we might have overwrites for this priority
  8991. var updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
  8992. if (updatedPriority != null) {
  8993. newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
  8994. }
  8995. else {
  8996. // priority didn't change, keep old node
  8997. newEventCache = oldEventSnap.getNode();
  8998. }
  8999. }
  9000. else {
  9001. var childChangePath = pathPopFront(changePath);
  9002. // update child
  9003. var newEventChild = void 0;
  9004. if (oldEventSnap.isCompleteForChild(childKey)) {
  9005. serverNode = viewCache.serverCache.getNode();
  9006. var eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
  9007. if (eventChildUpdate != null) {
  9008. newEventChild = oldEventSnap
  9009. .getNode()
  9010. .getImmediateChild(childKey)
  9011. .updateChild(childChangePath, eventChildUpdate);
  9012. }
  9013. else {
  9014. // Nothing changed, just keep the old child
  9015. newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9016. }
  9017. }
  9018. else {
  9019. newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9020. }
  9021. if (newEventChild != null) {
  9022. newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
  9023. }
  9024. else {
  9025. // no complete child available or no change
  9026. newEventCache = oldEventSnap.getNode();
  9027. }
  9028. }
  9029. }
  9030. return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
  9031. }
  9032. }
  9033. function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
  9034. var oldServerSnap = oldViewCache.serverCache;
  9035. var newServerCache;
  9036. var serverFilter = filterServerNode
  9037. ? viewProcessor.filter
  9038. : viewProcessor.filter.getIndexedFilter();
  9039. if (pathIsEmpty(changePath)) {
  9040. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
  9041. }
  9042. else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
  9043. // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update
  9044. var newServerNode = oldServerSnap
  9045. .getNode()
  9046. .updateChild(changePath, changedSnap);
  9047. newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
  9048. }
  9049. else {
  9050. var childKey = pathGetFront(changePath);
  9051. if (!oldServerSnap.isCompleteForPath(changePath) &&
  9052. pathGetLength(changePath) > 1) {
  9053. // We don't update incomplete nodes with updates intended for other listeners
  9054. return oldViewCache;
  9055. }
  9056. var childChangePath = pathPopFront(changePath);
  9057. var childNode = oldServerSnap.getNode().getImmediateChild(childKey);
  9058. var newChildNode = childNode.updateChild(childChangePath, changedSnap);
  9059. if (childKey === '.priority') {
  9060. newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
  9061. }
  9062. else {
  9063. newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
  9064. }
  9065. }
  9066. var newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
  9067. var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
  9068. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
  9069. }
  9070. function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
  9071. var oldEventSnap = oldViewCache.eventCache;
  9072. var newViewCache, newEventCache;
  9073. var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
  9074. if (pathIsEmpty(changePath)) {
  9075. newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
  9076. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
  9077. }
  9078. else {
  9079. var childKey = pathGetFront(changePath);
  9080. if (childKey === '.priority') {
  9081. newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
  9082. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
  9083. }
  9084. else {
  9085. var childChangePath = pathPopFront(changePath);
  9086. var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
  9087. var newChild = void 0;
  9088. if (pathIsEmpty(childChangePath)) {
  9089. // Child overwrite, we can replace the child
  9090. newChild = changedSnap;
  9091. }
  9092. else {
  9093. var childNode = source.getCompleteChild(childKey);
  9094. if (childNode != null) {
  9095. if (pathGetBack(childChangePath) === '.priority' &&
  9096. childNode.getChild(pathParent(childChangePath)).isEmpty()) {
  9097. // This is a priority update on an empty node. If this node exists on the server, the
  9098. // server will send down the priority in the update, so ignore for now
  9099. newChild = childNode;
  9100. }
  9101. else {
  9102. newChild = childNode.updateChild(childChangePath, changedSnap);
  9103. }
  9104. }
  9105. else {
  9106. // There is no complete child node available
  9107. newChild = ChildrenNode.EMPTY_NODE;
  9108. }
  9109. }
  9110. if (!oldChild.equals(newChild)) {
  9111. var newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
  9112. newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
  9113. }
  9114. else {
  9115. newViewCache = oldViewCache;
  9116. }
  9117. }
  9118. }
  9119. return newViewCache;
  9120. }
  9121. function viewProcessorCacheHasChild(viewCache, childKey) {
  9122. return viewCache.eventCache.isCompleteForChild(childKey);
  9123. }
  9124. function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
  9125. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9126. // window leaving room for new items. It's important we process these changes first, so we
  9127. // iterate the changes twice, first processing any that affect items currently in view.
  9128. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9129. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9130. // not the other.
  9131. var curViewCache = viewCache;
  9132. changedChildren.foreach(function (relativePath, childNode) {
  9133. var writePath = pathChild(path, relativePath);
  9134. if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9135. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9136. }
  9137. });
  9138. changedChildren.foreach(function (relativePath, childNode) {
  9139. var writePath = pathChild(path, relativePath);
  9140. if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
  9141. curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
  9142. }
  9143. });
  9144. return curViewCache;
  9145. }
  9146. function viewProcessorApplyMerge(viewProcessor, node, merge) {
  9147. merge.foreach(function (relativePath, childNode) {
  9148. node = node.updateChild(relativePath, childNode);
  9149. });
  9150. return node;
  9151. }
  9152. function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
  9153. // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and
  9154. // wait for the complete data update coming soon.
  9155. if (viewCache.serverCache.getNode().isEmpty() &&
  9156. !viewCache.serverCache.isFullyInitialized()) {
  9157. return viewCache;
  9158. }
  9159. // HACK: In the case of a limit query, there may be some changes that bump things out of the
  9160. // window leaving room for new items. It's important we process these changes first, so we
  9161. // iterate the changes twice, first processing any that affect items currently in view.
  9162. // TODO: I consider an item "in view" if cacheHasChild is true, which checks both the server
  9163. // and event snap. I'm not sure if this will result in edge cases when a child is in one but
  9164. // not the other.
  9165. var curViewCache = viewCache;
  9166. var viewMergeTree;
  9167. if (pathIsEmpty(path)) {
  9168. viewMergeTree = changedChildren;
  9169. }
  9170. else {
  9171. viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
  9172. }
  9173. var serverNode = viewCache.serverCache.getNode();
  9174. viewMergeTree.children.inorderTraversal(function (childKey, childTree) {
  9175. if (serverNode.hasChild(childKey)) {
  9176. var serverChild = viewCache.serverCache
  9177. .getNode()
  9178. .getImmediateChild(childKey);
  9179. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
  9180. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9181. }
  9182. });
  9183. viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {
  9184. var isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
  9185. childMergeTree.value === null;
  9186. if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
  9187. var serverChild = viewCache.serverCache
  9188. .getNode()
  9189. .getImmediateChild(childKey);
  9190. var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
  9191. curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
  9192. }
  9193. });
  9194. return curViewCache;
  9195. }
  9196. function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
  9197. if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
  9198. return viewCache;
  9199. }
  9200. // Only filter server node if it is currently filtered
  9201. var filterServerNode = viewCache.serverCache.isFiltered();
  9202. // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update
  9203. // now that it won't be shadowed.
  9204. var serverCache = viewCache.serverCache;
  9205. if (affectedTree.value != null) {
  9206. // This is an overwrite.
  9207. if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
  9208. serverCache.isCompleteForPath(ackPath)) {
  9209. return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
  9210. }
  9211. else if (pathIsEmpty(ackPath)) {
  9212. // This is a goofy edge case where we are acking data at this location but don't have full data. We
  9213. // should just re-apply whatever we have in our cache as a merge.
  9214. var changedChildren_1 = new ImmutableTree(null);
  9215. serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) {
  9216. changedChildren_1 = changedChildren_1.set(new Path(name), node);
  9217. });
  9218. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);
  9219. }
  9220. else {
  9221. return viewCache;
  9222. }
  9223. }
  9224. else {
  9225. // This is a merge.
  9226. var changedChildren_2 = new ImmutableTree(null);
  9227. affectedTree.foreach(function (mergePath, value) {
  9228. var serverCachePath = pathChild(ackPath, mergePath);
  9229. if (serverCache.isCompleteForPath(serverCachePath)) {
  9230. changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));
  9231. }
  9232. });
  9233. return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);
  9234. }
  9235. }
  9236. function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
  9237. var oldServerNode = viewCache.serverCache;
  9238. var newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
  9239. return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  9240. }
  9241. function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
  9242. var complete;
  9243. if (writeTreeRefShadowingWrite(writesCache, path) != null) {
  9244. return viewCache;
  9245. }
  9246. else {
  9247. var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
  9248. var oldEventCache = viewCache.eventCache.getNode();
  9249. var newEventCache = void 0;
  9250. if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
  9251. var newNode = void 0;
  9252. if (viewCache.serverCache.isFullyInitialized()) {
  9253. newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9254. }
  9255. else {
  9256. var serverChildren = viewCache.serverCache.getNode();
  9257. util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
  9258. newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
  9259. }
  9260. newNode = newNode;
  9261. newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
  9262. }
  9263. else {
  9264. var childKey = pathGetFront(path);
  9265. var newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
  9266. if (newChild == null &&
  9267. viewCache.serverCache.isCompleteForChild(childKey)) {
  9268. newChild = oldEventCache.getImmediateChild(childKey);
  9269. }
  9270. if (newChild != null) {
  9271. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
  9272. }
  9273. else if (viewCache.eventCache.getNode().hasChild(childKey)) {
  9274. // No complete child available, delete the existing one, if any
  9275. newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
  9276. }
  9277. else {
  9278. newEventCache = oldEventCache;
  9279. }
  9280. if (newEventCache.isEmpty() &&
  9281. viewCache.serverCache.isFullyInitialized()) {
  9282. // We might have reverted all child writes. Maybe the old event was a leaf node
  9283. complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
  9284. if (complete.isLeafNode()) {
  9285. newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
  9286. }
  9287. }
  9288. }
  9289. complete =
  9290. viewCache.serverCache.isFullyInitialized() ||
  9291. writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
  9292. return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
  9293. }
  9294. }
  9295. /**
  9296. * @license
  9297. * Copyright 2017 Google LLC
  9298. *
  9299. * Licensed under the Apache License, Version 2.0 (the "License");
  9300. * you may not use this file except in compliance with the License.
  9301. * You may obtain a copy of the License at
  9302. *
  9303. * http://www.apache.org/licenses/LICENSE-2.0
  9304. *
  9305. * Unless required by applicable law or agreed to in writing, software
  9306. * distributed under the License is distributed on an "AS IS" BASIS,
  9307. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9308. * See the License for the specific language governing permissions and
  9309. * limitations under the License.
  9310. */
  9311. /**
  9312. * A view represents a specific location and query that has 1 or more event registrations.
  9313. *
  9314. * It does several things:
  9315. * - Maintains the list of event registrations for this location/query.
  9316. * - Maintains a cache of the data visible for this location/query.
  9317. * - Applies new operations (via applyOperation), updates the cache, and based on the event
  9318. * registrations returns the set of events to be raised.
  9319. */
  9320. var View = /** @class */ (function () {
  9321. function View(query_, initialViewCache) {
  9322. this.query_ = query_;
  9323. this.eventRegistrations_ = [];
  9324. var params = this.query_._queryParams;
  9325. var indexFilter = new IndexedFilter(params.getIndex());
  9326. var filter = queryParamsGetNodeFilter(params);
  9327. this.processor_ = newViewProcessor(filter);
  9328. var initialServerCache = initialViewCache.serverCache;
  9329. var initialEventCache = initialViewCache.eventCache;
  9330. // Don't filter server node with other filter than index, wait for tagged listen
  9331. var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
  9332. var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
  9333. var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
  9334. var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
  9335. this.viewCache_ = newViewCache(newEventCache, newServerCache);
  9336. this.eventGenerator_ = new EventGenerator(this.query_);
  9337. }
  9338. Object.defineProperty(View.prototype, "query", {
  9339. get: function () {
  9340. return this.query_;
  9341. },
  9342. enumerable: false,
  9343. configurable: true
  9344. });
  9345. return View;
  9346. }());
  9347. function viewGetServerCache(view) {
  9348. return view.viewCache_.serverCache.getNode();
  9349. }
  9350. function viewGetCompleteNode(view) {
  9351. return viewCacheGetCompleteEventSnap(view.viewCache_);
  9352. }
  9353. function viewGetCompleteServerCache(view, path) {
  9354. var cache = viewCacheGetCompleteServerSnap(view.viewCache_);
  9355. if (cache) {
  9356. // If this isn't a "loadsAllData" view, then cache isn't actually a complete cache and
  9357. // we need to see if it contains the child we're interested in.
  9358. if (view.query._queryParams.loadsAllData() ||
  9359. (!pathIsEmpty(path) &&
  9360. !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
  9361. return cache.getChild(path);
  9362. }
  9363. }
  9364. return null;
  9365. }
  9366. function viewIsEmpty(view) {
  9367. return view.eventRegistrations_.length === 0;
  9368. }
  9369. function viewAddEventRegistration(view, eventRegistration) {
  9370. view.eventRegistrations_.push(eventRegistration);
  9371. }
  9372. /**
  9373. * @param eventRegistration - If null, remove all callbacks.
  9374. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9375. * @returns Cancel events, if cancelError was provided.
  9376. */
  9377. function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
  9378. var cancelEvents = [];
  9379. if (cancelError) {
  9380. util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
  9381. var path_1 = view.query._path;
  9382. view.eventRegistrations_.forEach(function (registration) {
  9383. var maybeEvent = registration.createCancelEvent(cancelError, path_1);
  9384. if (maybeEvent) {
  9385. cancelEvents.push(maybeEvent);
  9386. }
  9387. });
  9388. }
  9389. if (eventRegistration) {
  9390. var remaining = [];
  9391. for (var i = 0; i < view.eventRegistrations_.length; ++i) {
  9392. var existing = view.eventRegistrations_[i];
  9393. if (!existing.matches(eventRegistration)) {
  9394. remaining.push(existing);
  9395. }
  9396. else if (eventRegistration.hasAnyCallback()) {
  9397. // We're removing just this one
  9398. remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
  9399. break;
  9400. }
  9401. }
  9402. view.eventRegistrations_ = remaining;
  9403. }
  9404. else {
  9405. view.eventRegistrations_ = [];
  9406. }
  9407. return cancelEvents;
  9408. }
  9409. /**
  9410. * Applies the given Operation, updates our cache, and returns the appropriate events.
  9411. */
  9412. function viewApplyOperation(view, operation, writesCache, completeServerCache) {
  9413. if (operation.type === OperationType.MERGE &&
  9414. operation.source.queryId !== null) {
  9415. util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
  9416. util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
  9417. }
  9418. var oldViewCache = view.viewCache_;
  9419. var result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
  9420. viewProcessorAssertIndexed(view.processor_, result.viewCache);
  9421. util.assert(result.viewCache.serverCache.isFullyInitialized() ||
  9422. !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
  9423. view.viewCache_ = result.viewCache;
  9424. return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  9425. }
  9426. function viewGetInitialEvents(view, registration) {
  9427. var eventSnap = view.viewCache_.eventCache;
  9428. var initialChanges = [];
  9429. if (!eventSnap.getNode().isLeafNode()) {
  9430. var eventNode = eventSnap.getNode();
  9431. eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) {
  9432. initialChanges.push(changeChildAdded(key, childNode));
  9433. });
  9434. }
  9435. if (eventSnap.isFullyInitialized()) {
  9436. initialChanges.push(changeValue(eventSnap.getNode()));
  9437. }
  9438. return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  9439. }
  9440. function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
  9441. var registrations = eventRegistration
  9442. ? [eventRegistration]
  9443. : view.eventRegistrations_;
  9444. return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  9445. }
  9446. /**
  9447. * @license
  9448. * Copyright 2017 Google LLC
  9449. *
  9450. * Licensed under the Apache License, Version 2.0 (the "License");
  9451. * you may not use this file except in compliance with the License.
  9452. * You may obtain a copy of the License at
  9453. *
  9454. * http://www.apache.org/licenses/LICENSE-2.0
  9455. *
  9456. * Unless required by applicable law or agreed to in writing, software
  9457. * distributed under the License is distributed on an "AS IS" BASIS,
  9458. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9459. * See the License for the specific language governing permissions and
  9460. * limitations under the License.
  9461. */
  9462. var referenceConstructor$1;
  9463. /**
  9464. * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to
  9465. * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes
  9466. * and user writes (set, transaction, update).
  9467. *
  9468. * It's responsible for:
  9469. * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).
  9470. * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,
  9471. * applyUserOverwrite, etc.)
  9472. */
  9473. var SyncPoint = /** @class */ (function () {
  9474. function SyncPoint() {
  9475. /**
  9476. * The Views being tracked at this location in the tree, stored as a map where the key is a
  9477. * queryId and the value is the View for that query.
  9478. *
  9479. * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).
  9480. */
  9481. this.views = new Map();
  9482. }
  9483. return SyncPoint;
  9484. }());
  9485. function syncPointSetReferenceConstructor(val) {
  9486. util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
  9487. referenceConstructor$1 = val;
  9488. }
  9489. function syncPointGetReferenceConstructor() {
  9490. util.assert(referenceConstructor$1, 'Reference.ts has not been loaded');
  9491. return referenceConstructor$1;
  9492. }
  9493. function syncPointIsEmpty(syncPoint) {
  9494. return syncPoint.views.size === 0;
  9495. }
  9496. function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
  9497. var e_1, _a;
  9498. var queryId = operation.source.queryId;
  9499. if (queryId !== null) {
  9500. var view = syncPoint.views.get(queryId);
  9501. util.assert(view != null, 'SyncTree gave us an op for an invalid query.');
  9502. return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
  9503. }
  9504. else {
  9505. var events = [];
  9506. try {
  9507. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9508. var view = _c.value;
  9509. events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
  9510. }
  9511. }
  9512. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  9513. finally {
  9514. try {
  9515. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9516. }
  9517. finally { if (e_1) throw e_1.error; }
  9518. }
  9519. return events;
  9520. }
  9521. }
  9522. /**
  9523. * Get a view for the specified query.
  9524. *
  9525. * @param query - The query to return a view for
  9526. * @param writesCache
  9527. * @param serverCache
  9528. * @param serverCacheComplete
  9529. * @returns Events to raise.
  9530. */
  9531. function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
  9532. var queryId = query._queryIdentifier;
  9533. var view = syncPoint.views.get(queryId);
  9534. if (!view) {
  9535. // TODO: make writesCache take flag for complete server node
  9536. var eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
  9537. var eventCacheComplete = false;
  9538. if (eventCache) {
  9539. eventCacheComplete = true;
  9540. }
  9541. else if (serverCache instanceof ChildrenNode) {
  9542. eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
  9543. eventCacheComplete = false;
  9544. }
  9545. else {
  9546. eventCache = ChildrenNode.EMPTY_NODE;
  9547. eventCacheComplete = false;
  9548. }
  9549. var viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
  9550. return new View(query, viewCache);
  9551. }
  9552. return view;
  9553. }
  9554. /**
  9555. * Add an event callback for the specified query.
  9556. *
  9557. * @param query
  9558. * @param eventRegistration
  9559. * @param writesCache
  9560. * @param serverCache - Complete server cache, if we have it.
  9561. * @param serverCacheComplete
  9562. * @returns Events to raise.
  9563. */
  9564. function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
  9565. var view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
  9566. if (!syncPoint.views.has(query._queryIdentifier)) {
  9567. syncPoint.views.set(query._queryIdentifier, view);
  9568. }
  9569. // This is guaranteed to exist now, we just created anything that was missing
  9570. viewAddEventRegistration(view, eventRegistration);
  9571. return viewGetInitialEvents(view, eventRegistration);
  9572. }
  9573. /**
  9574. * Remove event callback(s). Return cancelEvents if a cancelError is specified.
  9575. *
  9576. * If query is the default query, we'll check all views for the specified eventRegistration.
  9577. * If eventRegistration is null, we'll remove all callbacks for the specified view(s).
  9578. *
  9579. * @param eventRegistration - If null, remove all callbacks.
  9580. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9581. * @returns removed queries and any cancel events
  9582. */
  9583. function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
  9584. var e_2, _a;
  9585. var queryId = query._queryIdentifier;
  9586. var removed = [];
  9587. var cancelEvents = [];
  9588. var hadCompleteView = syncPointHasCompleteView(syncPoint);
  9589. if (queryId === 'default') {
  9590. try {
  9591. // When you do ref.off(...), we search all views for the registration to remove.
  9592. for (var _b = tslib.__values(syncPoint.views.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9593. var _d = tslib.__read(_c.value, 2), viewQueryId = _d[0], view = _d[1];
  9594. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9595. if (viewIsEmpty(view)) {
  9596. syncPoint.views.delete(viewQueryId);
  9597. // We'll deal with complete views later.
  9598. if (!view.query._queryParams.loadsAllData()) {
  9599. removed.push(view.query);
  9600. }
  9601. }
  9602. }
  9603. }
  9604. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  9605. finally {
  9606. try {
  9607. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9608. }
  9609. finally { if (e_2) throw e_2.error; }
  9610. }
  9611. }
  9612. else {
  9613. // remove the callback from the specific view.
  9614. var view = syncPoint.views.get(queryId);
  9615. if (view) {
  9616. cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
  9617. if (viewIsEmpty(view)) {
  9618. syncPoint.views.delete(queryId);
  9619. // We'll deal with complete views later.
  9620. if (!view.query._queryParams.loadsAllData()) {
  9621. removed.push(view.query);
  9622. }
  9623. }
  9624. }
  9625. }
  9626. if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
  9627. // We removed our last complete view.
  9628. removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
  9629. }
  9630. return { removed: removed, events: cancelEvents };
  9631. }
  9632. function syncPointGetQueryViews(syncPoint) {
  9633. var e_3, _a;
  9634. var result = [];
  9635. try {
  9636. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9637. var view = _c.value;
  9638. if (!view.query._queryParams.loadsAllData()) {
  9639. result.push(view);
  9640. }
  9641. }
  9642. }
  9643. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  9644. finally {
  9645. try {
  9646. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9647. }
  9648. finally { if (e_3) throw e_3.error; }
  9649. }
  9650. return result;
  9651. }
  9652. /**
  9653. * @param path - The path to the desired complete snapshot
  9654. * @returns A complete cache, if it exists
  9655. */
  9656. function syncPointGetCompleteServerCache(syncPoint, path) {
  9657. var e_4, _a;
  9658. var serverCache = null;
  9659. try {
  9660. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9661. var view = _c.value;
  9662. serverCache = serverCache || viewGetCompleteServerCache(view, path);
  9663. }
  9664. }
  9665. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  9666. finally {
  9667. try {
  9668. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9669. }
  9670. finally { if (e_4) throw e_4.error; }
  9671. }
  9672. return serverCache;
  9673. }
  9674. function syncPointViewForQuery(syncPoint, query) {
  9675. var params = query._queryParams;
  9676. if (params.loadsAllData()) {
  9677. return syncPointGetCompleteView(syncPoint);
  9678. }
  9679. else {
  9680. var queryId = query._queryIdentifier;
  9681. return syncPoint.views.get(queryId);
  9682. }
  9683. }
  9684. function syncPointViewExistsForQuery(syncPoint, query) {
  9685. return syncPointViewForQuery(syncPoint, query) != null;
  9686. }
  9687. function syncPointHasCompleteView(syncPoint) {
  9688. return syncPointGetCompleteView(syncPoint) != null;
  9689. }
  9690. function syncPointGetCompleteView(syncPoint) {
  9691. var e_5, _a;
  9692. try {
  9693. for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  9694. var view = _c.value;
  9695. if (view.query._queryParams.loadsAllData()) {
  9696. return view;
  9697. }
  9698. }
  9699. }
  9700. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  9701. finally {
  9702. try {
  9703. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  9704. }
  9705. finally { if (e_5) throw e_5.error; }
  9706. }
  9707. return null;
  9708. }
  9709. /**
  9710. * @license
  9711. * Copyright 2017 Google LLC
  9712. *
  9713. * Licensed under the Apache License, Version 2.0 (the "License");
  9714. * you may not use this file except in compliance with the License.
  9715. * You may obtain a copy of the License at
  9716. *
  9717. * http://www.apache.org/licenses/LICENSE-2.0
  9718. *
  9719. * Unless required by applicable law or agreed to in writing, software
  9720. * distributed under the License is distributed on an "AS IS" BASIS,
  9721. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9722. * See the License for the specific language governing permissions and
  9723. * limitations under the License.
  9724. */
  9725. var referenceConstructor;
  9726. function syncTreeSetReferenceConstructor(val) {
  9727. util.assert(!referenceConstructor, '__referenceConstructor has already been defined');
  9728. referenceConstructor = val;
  9729. }
  9730. function syncTreeGetReferenceConstructor() {
  9731. util.assert(referenceConstructor, 'Reference.ts has not been loaded');
  9732. return referenceConstructor;
  9733. }
  9734. /**
  9735. * Static tracker for next query tag.
  9736. */
  9737. var syncTreeNextQueryTag_ = 1;
  9738. /**
  9739. * SyncTree is the central class for managing event callback registration, data caching, views
  9740. * (query processing), and event generation. There are typically two SyncTree instances for
  9741. * each Repo, one for the normal Firebase data, and one for the .info data.
  9742. *
  9743. * It has a number of responsibilities, including:
  9744. * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).
  9745. * - Applying and caching data changes for user set(), transaction(), and update() calls
  9746. * (applyUserOverwrite(), applyUserMerge()).
  9747. * - Applying and caching data changes for server data changes (applyServerOverwrite(),
  9748. * applyServerMerge()).
  9749. * - Generating user-facing events for server and user changes (all of the apply* methods
  9750. * return the set of events that need to be raised as a result).
  9751. * - Maintaining the appropriate set of server listens to ensure we are always subscribed
  9752. * to the correct set of paths and queries to satisfy the current set of user event
  9753. * callbacks (listens are started/stopped using the provided listenProvider).
  9754. *
  9755. * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual
  9756. * events are returned to the caller rather than raised synchronously.
  9757. *
  9758. */
  9759. var SyncTree = /** @class */ (function () {
  9760. /**
  9761. * @param listenProvider_ - Used by SyncTree to start / stop listening
  9762. * to server data.
  9763. */
  9764. function SyncTree(listenProvider_) {
  9765. this.listenProvider_ = listenProvider_;
  9766. /**
  9767. * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.
  9768. */
  9769. this.syncPointTree_ = new ImmutableTree(null);
  9770. /**
  9771. * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).
  9772. */
  9773. this.pendingWriteTree_ = newWriteTree();
  9774. this.tagToQueryMap = new Map();
  9775. this.queryToTagMap = new Map();
  9776. }
  9777. return SyncTree;
  9778. }());
  9779. /**
  9780. * Apply the data changes for a user-generated set() or transaction() call.
  9781. *
  9782. * @returns Events to raise.
  9783. */
  9784. function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
  9785. // Record pending write.
  9786. writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
  9787. if (!visible) {
  9788. return [];
  9789. }
  9790. else {
  9791. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
  9792. }
  9793. }
  9794. /**
  9795. * Apply the data from a user-generated update() call
  9796. *
  9797. * @returns Events to raise.
  9798. */
  9799. function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
  9800. // Record pending merge.
  9801. writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
  9802. var changeTree = ImmutableTree.fromObject(changedChildren);
  9803. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
  9804. }
  9805. /**
  9806. * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().
  9807. *
  9808. * @param revert - True if the given write failed and needs to be reverted
  9809. * @returns Events to raise.
  9810. */
  9811. function syncTreeAckUserWrite(syncTree, writeId, revert) {
  9812. if (revert === void 0) { revert = false; }
  9813. var write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
  9814. var needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
  9815. if (!needToReevaluate) {
  9816. return [];
  9817. }
  9818. else {
  9819. var affectedTree_1 = new ImmutableTree(null);
  9820. if (write.snap != null) {
  9821. // overwrite
  9822. affectedTree_1 = affectedTree_1.set(newEmptyPath(), true);
  9823. }
  9824. else {
  9825. each(write.children, function (pathString) {
  9826. affectedTree_1 = affectedTree_1.set(new Path(pathString), true);
  9827. });
  9828. }
  9829. return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree_1, revert));
  9830. }
  9831. }
  9832. /**
  9833. * Apply new server data for the specified path..
  9834. *
  9835. * @returns Events to raise.
  9836. */
  9837. function syncTreeApplyServerOverwrite(syncTree, path, newData) {
  9838. return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  9839. }
  9840. /**
  9841. * Apply new server data to be merged in at the specified path.
  9842. *
  9843. * @returns Events to raise.
  9844. */
  9845. function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
  9846. var changeTree = ImmutableTree.fromObject(changedChildren);
  9847. return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  9848. }
  9849. /**
  9850. * Apply a listen complete for a query
  9851. *
  9852. * @returns Events to raise.
  9853. */
  9854. function syncTreeApplyListenComplete(syncTree, path) {
  9855. return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  9856. }
  9857. /**
  9858. * Apply a listen complete for a tagged query
  9859. *
  9860. * @returns Events to raise.
  9861. */
  9862. function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
  9863. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9864. if (queryKey) {
  9865. var r = syncTreeParseQueryKey_(queryKey);
  9866. var queryPath = r.path, queryId = r.queryId;
  9867. var relativePath = newRelativePath(queryPath, path);
  9868. var op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
  9869. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9870. }
  9871. else {
  9872. // We've already removed the query. No big deal, ignore the update
  9873. return [];
  9874. }
  9875. }
  9876. /**
  9877. * Remove event callback(s).
  9878. *
  9879. * If query is the default query, we'll check all queries for the specified eventRegistration.
  9880. * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.
  9881. *
  9882. * @param eventRegistration - If null, all callbacks are removed.
  9883. * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.
  9884. * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no
  9885. * deduping needs to take place. This flag allows toggling of that behavior
  9886. * @returns Cancel events, if cancelError was provided.
  9887. */
  9888. function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup) {
  9889. if (skipListenerDedup === void 0) { skipListenerDedup = false; }
  9890. // Find the syncPoint first. Then deal with whether or not it has matching listeners
  9891. var path = query._path;
  9892. var maybeSyncPoint = syncTree.syncPointTree_.get(path);
  9893. var cancelEvents = [];
  9894. // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without
  9895. // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and
  9896. // not loadsAllData().
  9897. if (maybeSyncPoint &&
  9898. (query._queryIdentifier === 'default' ||
  9899. syncPointViewExistsForQuery(maybeSyncPoint, query))) {
  9900. var removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
  9901. if (syncPointIsEmpty(maybeSyncPoint)) {
  9902. syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
  9903. }
  9904. var removed = removedAndEvents.removed;
  9905. cancelEvents = removedAndEvents.events;
  9906. if (!skipListenerDedup) {
  9907. /**
  9908. * We may have just removed one of many listeners and can short-circuit this whole process
  9909. * We may also not have removed a default listener, in which case all of the descendant listeners should already be
  9910. * properly set up.
  9911. */
  9912. // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of
  9913. // queryId === 'default'
  9914. var removingDefault = -1 !==
  9915. removed.findIndex(function (query) {
  9916. return query._queryParams.loadsAllData();
  9917. });
  9918. var covered = syncTree.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {
  9919. return syncPointHasCompleteView(parentSyncPoint);
  9920. });
  9921. if (removingDefault && !covered) {
  9922. var subtree = syncTree.syncPointTree_.subtree(path);
  9923. // There are potentially child listeners. Determine what if any listens we need to send before executing the
  9924. // removal
  9925. if (!subtree.isEmpty()) {
  9926. // We need to fold over our subtree and collect the listeners to send
  9927. var newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
  9928. // Ok, we've collected all the listens we need. Set them up.
  9929. for (var i = 0; i < newViews.length; ++i) {
  9930. var view = newViews[i], newQuery = view.query;
  9931. var listener = syncTreeCreateListenerForView_(syncTree, view);
  9932. syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
  9933. }
  9934. }
  9935. // Otherwise there's nothing below us, so nothing we need to start listening on
  9936. }
  9937. // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query
  9938. // The above block has us covered in terms of making sure we're set up on listens lower in the tree.
  9939. // Also, note that if we have a cancelError, it's already been removed at the provider level.
  9940. if (!covered && removed.length > 0 && !cancelError) {
  9941. // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one
  9942. // default. Otherwise, we need to iterate through and cancel each individual query
  9943. if (removingDefault) {
  9944. // We don't tag default listeners
  9945. var defaultTag = null;
  9946. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
  9947. }
  9948. else {
  9949. removed.forEach(function (queryToRemove) {
  9950. var tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
  9951. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
  9952. });
  9953. }
  9954. }
  9955. }
  9956. // Now, clear all of the tags we're tracking for the removed listens
  9957. syncTreeRemoveTags_(syncTree, removed);
  9958. }
  9959. return cancelEvents;
  9960. }
  9961. /**
  9962. * Apply new server data for the specified tagged query.
  9963. *
  9964. * @returns Events to raise.
  9965. */
  9966. function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
  9967. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9968. if (queryKey != null) {
  9969. var r = syncTreeParseQueryKey_(queryKey);
  9970. var queryPath = r.path, queryId = r.queryId;
  9971. var relativePath = newRelativePath(queryPath, path);
  9972. var op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
  9973. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9974. }
  9975. else {
  9976. // Query must have been removed already
  9977. return [];
  9978. }
  9979. }
  9980. /**
  9981. * Apply server data to be merged in for the specified tagged query.
  9982. *
  9983. * @returns Events to raise.
  9984. */
  9985. function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
  9986. var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
  9987. if (queryKey) {
  9988. var r = syncTreeParseQueryKey_(queryKey);
  9989. var queryPath = r.path, queryId = r.queryId;
  9990. var relativePath = newRelativePath(queryPath, path);
  9991. var changeTree = ImmutableTree.fromObject(changedChildren);
  9992. var op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
  9993. return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
  9994. }
  9995. else {
  9996. // We've already removed the query. No big deal, ignore the update
  9997. return [];
  9998. }
  9999. }
  10000. /**
  10001. * Add an event callback for the specified query.
  10002. *
  10003. * @returns Events to raise.
  10004. */
  10005. function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener) {
  10006. if (skipSetupListener === void 0) { skipSetupListener = false; }
  10007. var path = query._path;
  10008. var serverCache = null;
  10009. var foundAncestorDefaultView = false;
  10010. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10011. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10012. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10013. var relativePath = newRelativePath(pathToSyncPoint, path);
  10014. serverCache =
  10015. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10016. foundAncestorDefaultView =
  10017. foundAncestorDefaultView || syncPointHasCompleteView(sp);
  10018. });
  10019. var syncPoint = syncTree.syncPointTree_.get(path);
  10020. if (!syncPoint) {
  10021. syncPoint = new SyncPoint();
  10022. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10023. }
  10024. else {
  10025. foundAncestorDefaultView =
  10026. foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
  10027. serverCache =
  10028. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10029. }
  10030. var serverCacheComplete;
  10031. if (serverCache != null) {
  10032. serverCacheComplete = true;
  10033. }
  10034. else {
  10035. serverCacheComplete = false;
  10036. serverCache = ChildrenNode.EMPTY_NODE;
  10037. var subtree = syncTree.syncPointTree_.subtree(path);
  10038. subtree.foreachChild(function (childName, childSyncPoint) {
  10039. var completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
  10040. if (completeCache) {
  10041. serverCache = serverCache.updateImmediateChild(childName, completeCache);
  10042. }
  10043. });
  10044. }
  10045. var viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
  10046. if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
  10047. // We need to track a tag for this query
  10048. var queryKey = syncTreeMakeQueryKey_(query);
  10049. util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
  10050. var tag = syncTreeGetNextQueryTag_();
  10051. syncTree.queryToTagMap.set(queryKey, tag);
  10052. syncTree.tagToQueryMap.set(tag, queryKey);
  10053. }
  10054. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
  10055. var events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
  10056. if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
  10057. var view = syncPointViewForQuery(syncPoint, query);
  10058. events = events.concat(syncTreeSetupListener_(syncTree, query, view));
  10059. }
  10060. return events;
  10061. }
  10062. /**
  10063. * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a
  10064. * listener above it, we will get a false "null". This shouldn't be a problem because transactions will always
  10065. * have a listener above, and atomic operations would correctly show a jitter of <increment value> ->
  10066. * <incremented total> as the write is applied locally and then acknowledged at the server.
  10067. *
  10068. * Note: this method will *include* hidden writes from transaction with applyLocally set to false.
  10069. *
  10070. * @param path - The path to the data we want
  10071. * @param writeIdsToExclude - A specific set to be excluded
  10072. */
  10073. function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
  10074. var includeHiddenSets = true;
  10075. var writeTree = syncTree.pendingWriteTree_;
  10076. var serverCache = syncTree.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {
  10077. var relativePath = newRelativePath(pathSoFar, path);
  10078. var serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
  10079. if (serverCache) {
  10080. return serverCache;
  10081. }
  10082. });
  10083. return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  10084. }
  10085. function syncTreeGetServerValue(syncTree, query) {
  10086. var path = query._path;
  10087. var serverCache = null;
  10088. // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.
  10089. // Consider optimizing this once there's a better understanding of what actual behavior will be.
  10090. syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
  10091. var relativePath = newRelativePath(pathToSyncPoint, path);
  10092. serverCache =
  10093. serverCache || syncPointGetCompleteServerCache(sp, relativePath);
  10094. });
  10095. var syncPoint = syncTree.syncPointTree_.get(path);
  10096. if (!syncPoint) {
  10097. syncPoint = new SyncPoint();
  10098. syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
  10099. }
  10100. else {
  10101. serverCache =
  10102. serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10103. }
  10104. var serverCacheComplete = serverCache != null;
  10105. var serverCacheNode = serverCacheComplete
  10106. ? new CacheNode(serverCache, true, false)
  10107. : null;
  10108. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
  10109. var view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
  10110. return viewGetCompleteNode(view);
  10111. }
  10112. /**
  10113. * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.
  10114. *
  10115. * NOTES:
  10116. * - Descendant SyncPoints will be visited first (since we raise events depth-first).
  10117. *
  10118. * - We call applyOperation() on each SyncPoint passing three things:
  10119. * 1. A version of the Operation that has been made relative to the SyncPoint location.
  10120. * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.
  10121. * 3. A snapshot Node with cached server data, if we have it.
  10122. *
  10123. * - We concatenate all of the events returned by each SyncPoint and return the result.
  10124. */
  10125. function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
  10126. return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
  10127. /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
  10128. }
  10129. /**
  10130. * Recursive helper for applyOperationToSyncPoints_
  10131. */
  10132. function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
  10133. if (pathIsEmpty(operation.path)) {
  10134. return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
  10135. }
  10136. else {
  10137. var syncPoint = syncPointTree.get(newEmptyPath());
  10138. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10139. if (serverCache == null && syncPoint != null) {
  10140. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10141. }
  10142. var events = [];
  10143. var childName = pathGetFront(operation.path);
  10144. var childOperation = operation.operationForChild(childName);
  10145. var childTree = syncPointTree.children.get(childName);
  10146. if (childTree && childOperation) {
  10147. var childServerCache = serverCache
  10148. ? serverCache.getImmediateChild(childName)
  10149. : null;
  10150. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10151. events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10152. }
  10153. if (syncPoint) {
  10154. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10155. }
  10156. return events;
  10157. }
  10158. }
  10159. /**
  10160. * Recursive helper for applyOperationToSyncPoints_
  10161. */
  10162. function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
  10163. var syncPoint = syncPointTree.get(newEmptyPath());
  10164. // If we don't have cached server data, see if we can get it from this SyncPoint.
  10165. if (serverCache == null && syncPoint != null) {
  10166. serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
  10167. }
  10168. var events = [];
  10169. syncPointTree.children.inorderTraversal(function (childName, childTree) {
  10170. var childServerCache = serverCache
  10171. ? serverCache.getImmediateChild(childName)
  10172. : null;
  10173. var childWritesCache = writeTreeRefChild(writesCache, childName);
  10174. var childOperation = operation.operationForChild(childName);
  10175. if (childOperation) {
  10176. events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
  10177. }
  10178. });
  10179. if (syncPoint) {
  10180. events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
  10181. }
  10182. return events;
  10183. }
  10184. function syncTreeCreateListenerForView_(syncTree, view) {
  10185. var query = view.query;
  10186. var tag = syncTreeTagForQuery(syncTree, query);
  10187. return {
  10188. hashFn: function () {
  10189. var cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
  10190. return cache.hash();
  10191. },
  10192. onComplete: function (status) {
  10193. if (status === 'ok') {
  10194. if (tag) {
  10195. return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
  10196. }
  10197. else {
  10198. return syncTreeApplyListenComplete(syncTree, query._path);
  10199. }
  10200. }
  10201. else {
  10202. // If a listen failed, kill all of the listeners here, not just the one that triggered the error.
  10203. // Note that this may need to be scoped to just this listener if we change permissions on filtered children
  10204. var error = errorForServerCode(status, query);
  10205. return syncTreeRemoveEventRegistration(syncTree, query,
  10206. /*eventRegistration*/ null, error);
  10207. }
  10208. }
  10209. };
  10210. }
  10211. /**
  10212. * Return the tag associated with the given query.
  10213. */
  10214. function syncTreeTagForQuery(syncTree, query) {
  10215. var queryKey = syncTreeMakeQueryKey_(query);
  10216. return syncTree.queryToTagMap.get(queryKey);
  10217. }
  10218. /**
  10219. * Given a query, computes a "queryKey" suitable for use in our queryToTagMap_.
  10220. */
  10221. function syncTreeMakeQueryKey_(query) {
  10222. return query._path.toString() + '$' + query._queryIdentifier;
  10223. }
  10224. /**
  10225. * Return the query associated with the given tag, if we have one
  10226. */
  10227. function syncTreeQueryKeyForTag_(syncTree, tag) {
  10228. return syncTree.tagToQueryMap.get(tag);
  10229. }
  10230. /**
  10231. * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.
  10232. */
  10233. function syncTreeParseQueryKey_(queryKey) {
  10234. var splitIndex = queryKey.indexOf('$');
  10235. util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
  10236. return {
  10237. queryId: queryKey.substr(splitIndex + 1),
  10238. path: new Path(queryKey.substr(0, splitIndex))
  10239. };
  10240. }
  10241. /**
  10242. * A helper method to apply tagged operations
  10243. */
  10244. function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
  10245. var syncPoint = syncTree.syncPointTree_.get(queryPath);
  10246. util.assert(syncPoint, "Missing sync point for query tag that we're tracking");
  10247. var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
  10248. return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  10249. }
  10250. /**
  10251. * This collapses multiple unfiltered views into a single view, since we only need a single
  10252. * listener for them.
  10253. */
  10254. function syncTreeCollectDistinctViewsForSubTree_(subtree) {
  10255. return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10256. if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
  10257. var completeView = syncPointGetCompleteView(maybeChildSyncPoint);
  10258. return [completeView];
  10259. }
  10260. else {
  10261. // No complete view here, flatten any deeper listens into an array
  10262. var views_1 = [];
  10263. if (maybeChildSyncPoint) {
  10264. views_1 = syncPointGetQueryViews(maybeChildSyncPoint);
  10265. }
  10266. each(childMap, function (_key, childViews) {
  10267. views_1 = views_1.concat(childViews);
  10268. });
  10269. return views_1;
  10270. }
  10271. });
  10272. }
  10273. /**
  10274. * Normalizes a query to a query we send the server for listening
  10275. *
  10276. * @returns The normalized query
  10277. */
  10278. function syncTreeQueryForListening_(query) {
  10279. if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
  10280. // We treat queries that load all data as default queries
  10281. // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits
  10282. // from Query
  10283. return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
  10284. }
  10285. else {
  10286. return query;
  10287. }
  10288. }
  10289. function syncTreeRemoveTags_(syncTree, queries) {
  10290. for (var j = 0; j < queries.length; ++j) {
  10291. var removedQuery = queries[j];
  10292. if (!removedQuery._queryParams.loadsAllData()) {
  10293. // We should have a tag for this
  10294. var removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
  10295. var removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
  10296. syncTree.queryToTagMap.delete(removedQueryKey);
  10297. syncTree.tagToQueryMap.delete(removedQueryTag);
  10298. }
  10299. }
  10300. }
  10301. /**
  10302. * Static accessor for query tags.
  10303. */
  10304. function syncTreeGetNextQueryTag_() {
  10305. return syncTreeNextQueryTag_++;
  10306. }
  10307. /**
  10308. * For a given new listen, manage the de-duplication of outstanding subscriptions.
  10309. *
  10310. * @returns This method can return events to support synchronous data sources
  10311. */
  10312. function syncTreeSetupListener_(syncTree, query, view) {
  10313. var path = query._path;
  10314. var tag = syncTreeTagForQuery(syncTree, query);
  10315. var listener = syncTreeCreateListenerForView_(syncTree, view);
  10316. var events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
  10317. var subtree = syncTree.syncPointTree_.subtree(path);
  10318. // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we
  10319. // may need to shadow other listens as well.
  10320. if (tag) {
  10321. util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
  10322. }
  10323. else {
  10324. // Shadow everything at or below this location, this is a default listener.
  10325. var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
  10326. if (!pathIsEmpty(relativePath) &&
  10327. maybeChildSyncPoint &&
  10328. syncPointHasCompleteView(maybeChildSyncPoint)) {
  10329. return [syncPointGetCompleteView(maybeChildSyncPoint).query];
  10330. }
  10331. else {
  10332. // No default listener here, flatten any deeper queries into an array
  10333. var queries_1 = [];
  10334. if (maybeChildSyncPoint) {
  10335. queries_1 = queries_1.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(function (view) { return view.query; }));
  10336. }
  10337. each(childMap, function (_key, childQueries) {
  10338. queries_1 = queries_1.concat(childQueries);
  10339. });
  10340. return queries_1;
  10341. }
  10342. });
  10343. for (var i = 0; i < queriesToStop.length; ++i) {
  10344. var queryToStop = queriesToStop[i];
  10345. syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
  10346. }
  10347. }
  10348. return events;
  10349. }
  10350. /**
  10351. * @license
  10352. * Copyright 2017 Google LLC
  10353. *
  10354. * Licensed under the Apache License, Version 2.0 (the "License");
  10355. * you may not use this file except in compliance with the License.
  10356. * You may obtain a copy of the License at
  10357. *
  10358. * http://www.apache.org/licenses/LICENSE-2.0
  10359. *
  10360. * Unless required by applicable law or agreed to in writing, software
  10361. * distributed under the License is distributed on an "AS IS" BASIS,
  10362. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10363. * See the License for the specific language governing permissions and
  10364. * limitations under the License.
  10365. */
  10366. var ExistingValueProvider = /** @class */ (function () {
  10367. function ExistingValueProvider(node_) {
  10368. this.node_ = node_;
  10369. }
  10370. ExistingValueProvider.prototype.getImmediateChild = function (childName) {
  10371. var child = this.node_.getImmediateChild(childName);
  10372. return new ExistingValueProvider(child);
  10373. };
  10374. ExistingValueProvider.prototype.node = function () {
  10375. return this.node_;
  10376. };
  10377. return ExistingValueProvider;
  10378. }());
  10379. var DeferredValueProvider = /** @class */ (function () {
  10380. function DeferredValueProvider(syncTree, path) {
  10381. this.syncTree_ = syncTree;
  10382. this.path_ = path;
  10383. }
  10384. DeferredValueProvider.prototype.getImmediateChild = function (childName) {
  10385. var childPath = pathChild(this.path_, childName);
  10386. return new DeferredValueProvider(this.syncTree_, childPath);
  10387. };
  10388. DeferredValueProvider.prototype.node = function () {
  10389. return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
  10390. };
  10391. return DeferredValueProvider;
  10392. }());
  10393. /**
  10394. * Generate placeholders for deferred values.
  10395. */
  10396. var generateWithValues = function (values) {
  10397. values = values || {};
  10398. values['timestamp'] = values['timestamp'] || new Date().getTime();
  10399. return values;
  10400. };
  10401. /**
  10402. * Value to use when firing local events. When writing server values, fire
  10403. * local events with an approximate value, otherwise return value as-is.
  10404. */
  10405. var resolveDeferredLeafValue = function (value, existingVal, serverValues) {
  10406. if (!value || typeof value !== 'object') {
  10407. return value;
  10408. }
  10409. util.assert('.sv' in value, 'Unexpected leaf node or priority contents');
  10410. if (typeof value['.sv'] === 'string') {
  10411. return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
  10412. }
  10413. else if (typeof value['.sv'] === 'object') {
  10414. return resolveComplexDeferredValue(value['.sv'], existingVal);
  10415. }
  10416. else {
  10417. util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
  10418. }
  10419. };
  10420. var resolveScalarDeferredValue = function (op, existing, serverValues) {
  10421. switch (op) {
  10422. case 'timestamp':
  10423. return serverValues['timestamp'];
  10424. default:
  10425. util.assert(false, 'Unexpected server value: ' + op);
  10426. }
  10427. };
  10428. var resolveComplexDeferredValue = function (op, existing, unused) {
  10429. if (!op.hasOwnProperty('increment')) {
  10430. util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
  10431. }
  10432. var delta = op['increment'];
  10433. if (typeof delta !== 'number') {
  10434. util.assert(false, 'Unexpected increment value: ' + delta);
  10435. }
  10436. var existingNode = existing.node();
  10437. util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
  10438. // Incrementing a non-number sets the value to the incremented amount
  10439. if (!existingNode.isLeafNode()) {
  10440. return delta;
  10441. }
  10442. var leaf = existingNode;
  10443. var existingVal = leaf.getValue();
  10444. if (typeof existingVal !== 'number') {
  10445. return delta;
  10446. }
  10447. // No need to do over/underflow arithmetic here because JS only handles floats under the covers
  10448. return existingVal + delta;
  10449. };
  10450. /**
  10451. * Recursively replace all deferred values and priorities in the tree with the
  10452. * specified generated replacement values.
  10453. * @param path - path to which write is relative
  10454. * @param node - new data written at path
  10455. * @param syncTree - current data
  10456. */
  10457. var resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
  10458. return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  10459. };
  10460. /**
  10461. * Recursively replace all deferred values and priorities in the node with the
  10462. * specified generated replacement values. If there are no server values in the node,
  10463. * it'll be returned as-is.
  10464. */
  10465. var resolveDeferredValueSnapshot = function (node, existing, serverValues) {
  10466. return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  10467. };
  10468. function resolveDeferredValue(node, existingVal, serverValues) {
  10469. var rawPri = node.getPriority().val();
  10470. var priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
  10471. var newNode;
  10472. if (node.isLeafNode()) {
  10473. var leafNode = node;
  10474. var value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
  10475. if (value !== leafNode.getValue() ||
  10476. priority !== leafNode.getPriority().val()) {
  10477. return new LeafNode(value, nodeFromJSON(priority));
  10478. }
  10479. else {
  10480. return node;
  10481. }
  10482. }
  10483. else {
  10484. var childrenNode = node;
  10485. newNode = childrenNode;
  10486. if (priority !== childrenNode.getPriority().val()) {
  10487. newNode = newNode.updatePriority(new LeafNode(priority));
  10488. }
  10489. childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
  10490. var newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
  10491. if (newChildNode !== childNode) {
  10492. newNode = newNode.updateImmediateChild(childName, newChildNode);
  10493. }
  10494. });
  10495. return newNode;
  10496. }
  10497. }
  10498. /**
  10499. * @license
  10500. * Copyright 2017 Google LLC
  10501. *
  10502. * Licensed under the Apache License, Version 2.0 (the "License");
  10503. * you may not use this file except in compliance with the License.
  10504. * You may obtain a copy of the License at
  10505. *
  10506. * http://www.apache.org/licenses/LICENSE-2.0
  10507. *
  10508. * Unless required by applicable law or agreed to in writing, software
  10509. * distributed under the License is distributed on an "AS IS" BASIS,
  10510. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10511. * See the License for the specific language governing permissions and
  10512. * limitations under the License.
  10513. */
  10514. /**
  10515. * A light-weight tree, traversable by path. Nodes can have both values and children.
  10516. * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty
  10517. * children.
  10518. */
  10519. var Tree = /** @class */ (function () {
  10520. /**
  10521. * @param name - Optional name of the node.
  10522. * @param parent - Optional parent node.
  10523. * @param node - Optional node to wrap.
  10524. */
  10525. function Tree(name, parent, node) {
  10526. if (name === void 0) { name = ''; }
  10527. if (parent === void 0) { parent = null; }
  10528. if (node === void 0) { node = { children: {}, childCount: 0 }; }
  10529. this.name = name;
  10530. this.parent = parent;
  10531. this.node = node;
  10532. }
  10533. return Tree;
  10534. }());
  10535. /**
  10536. * Returns a sub-Tree for the given path.
  10537. *
  10538. * @param pathObj - Path to look up.
  10539. * @returns Tree for path.
  10540. */
  10541. function treeSubTree(tree, pathObj) {
  10542. // TODO: Require pathObj to be Path?
  10543. var path = pathObj instanceof Path ? pathObj : new Path(pathObj);
  10544. var child = tree, next = pathGetFront(path);
  10545. while (next !== null) {
  10546. var childNode = util.safeGet(child.node.children, next) || {
  10547. children: {},
  10548. childCount: 0
  10549. };
  10550. child = new Tree(next, child, childNode);
  10551. path = pathPopFront(path);
  10552. next = pathGetFront(path);
  10553. }
  10554. return child;
  10555. }
  10556. /**
  10557. * Returns the data associated with this tree node.
  10558. *
  10559. * @returns The data or null if no data exists.
  10560. */
  10561. function treeGetValue(tree) {
  10562. return tree.node.value;
  10563. }
  10564. /**
  10565. * Sets data to this tree node.
  10566. *
  10567. * @param value - Value to set.
  10568. */
  10569. function treeSetValue(tree, value) {
  10570. tree.node.value = value;
  10571. treeUpdateParents(tree);
  10572. }
  10573. /**
  10574. * @returns Whether the tree has any children.
  10575. */
  10576. function treeHasChildren(tree) {
  10577. return tree.node.childCount > 0;
  10578. }
  10579. /**
  10580. * @returns Whethe rthe tree is empty (no value or children).
  10581. */
  10582. function treeIsEmpty(tree) {
  10583. return treeGetValue(tree) === undefined && !treeHasChildren(tree);
  10584. }
  10585. /**
  10586. * Calls action for each child of this tree node.
  10587. *
  10588. * @param action - Action to be called for each child.
  10589. */
  10590. function treeForEachChild(tree, action) {
  10591. each(tree.node.children, function (child, childTree) {
  10592. action(new Tree(child, tree, childTree));
  10593. });
  10594. }
  10595. /**
  10596. * Does a depth-first traversal of this node's descendants, calling action for each one.
  10597. *
  10598. * @param action - Action to be called for each child.
  10599. * @param includeSelf - Whether to call action on this node as well. Defaults to
  10600. * false.
  10601. * @param childrenFirst - Whether to call action on children before calling it on
  10602. * parent.
  10603. */
  10604. function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
  10605. if (includeSelf && !childrenFirst) {
  10606. action(tree);
  10607. }
  10608. treeForEachChild(tree, function (child) {
  10609. treeForEachDescendant(child, action, true, childrenFirst);
  10610. });
  10611. if (includeSelf && childrenFirst) {
  10612. action(tree);
  10613. }
  10614. }
  10615. /**
  10616. * Calls action on each ancestor node.
  10617. *
  10618. * @param action - Action to be called on each parent; return
  10619. * true to abort.
  10620. * @param includeSelf - Whether to call action on this node as well.
  10621. * @returns true if the action callback returned true.
  10622. */
  10623. function treeForEachAncestor(tree, action, includeSelf) {
  10624. var node = includeSelf ? tree : tree.parent;
  10625. while (node !== null) {
  10626. if (action(node)) {
  10627. return true;
  10628. }
  10629. node = node.parent;
  10630. }
  10631. return false;
  10632. }
  10633. /**
  10634. * @returns The path of this tree node, as a Path.
  10635. */
  10636. function treeGetPath(tree) {
  10637. return new Path(tree.parent === null
  10638. ? tree.name
  10639. : treeGetPath(tree.parent) + '/' + tree.name);
  10640. }
  10641. /**
  10642. * Adds or removes this child from its parent based on whether it's empty or not.
  10643. */
  10644. function treeUpdateParents(tree) {
  10645. if (tree.parent !== null) {
  10646. treeUpdateChild(tree.parent, tree.name, tree);
  10647. }
  10648. }
  10649. /**
  10650. * Adds or removes the passed child to this tree node, depending on whether it's empty.
  10651. *
  10652. * @param childName - The name of the child to update.
  10653. * @param child - The child to update.
  10654. */
  10655. function treeUpdateChild(tree, childName, child) {
  10656. var childEmpty = treeIsEmpty(child);
  10657. var childExists = util.contains(tree.node.children, childName);
  10658. if (childEmpty && childExists) {
  10659. delete tree.node.children[childName];
  10660. tree.node.childCount--;
  10661. treeUpdateParents(tree);
  10662. }
  10663. else if (!childEmpty && !childExists) {
  10664. tree.node.children[childName] = child.node;
  10665. tree.node.childCount++;
  10666. treeUpdateParents(tree);
  10667. }
  10668. }
  10669. /**
  10670. * @license
  10671. * Copyright 2017 Google LLC
  10672. *
  10673. * Licensed under the Apache License, Version 2.0 (the "License");
  10674. * you may not use this file except in compliance with the License.
  10675. * You may obtain a copy of the License at
  10676. *
  10677. * http://www.apache.org/licenses/LICENSE-2.0
  10678. *
  10679. * Unless required by applicable law or agreed to in writing, software
  10680. * distributed under the License is distributed on an "AS IS" BASIS,
  10681. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10682. * See the License for the specific language governing permissions and
  10683. * limitations under the License.
  10684. */
  10685. /**
  10686. * True for invalid Firebase keys
  10687. */
  10688. var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  10689. /**
  10690. * True for invalid Firebase paths.
  10691. * Allows '/' in paths.
  10692. */
  10693. var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  10694. /**
  10695. * Maximum number of characters to allow in leaf value
  10696. */
  10697. var MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  10698. var isValidKey = function (key) {
  10699. return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
  10700. };
  10701. var isValidPathString = function (pathString) {
  10702. return (typeof pathString === 'string' &&
  10703. pathString.length !== 0 &&
  10704. !INVALID_PATH_REGEX_.test(pathString));
  10705. };
  10706. var isValidRootPathString = function (pathString) {
  10707. if (pathString) {
  10708. // Allow '/.info/' at the beginning.
  10709. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10710. }
  10711. return isValidPathString(pathString);
  10712. };
  10713. var isValidPriority = function (priority) {
  10714. return (priority === null ||
  10715. typeof priority === 'string' ||
  10716. (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
  10717. (priority &&
  10718. typeof priority === 'object' &&
  10719. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  10720. util.contains(priority, '.sv')));
  10721. };
  10722. /**
  10723. * Pre-validate a datum passed as an argument to Firebase function.
  10724. */
  10725. var validateFirebaseDataArg = function (fnName, value, path, optional) {
  10726. if (optional && value === undefined) {
  10727. return;
  10728. }
  10729. validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path);
  10730. };
  10731. /**
  10732. * Validate a data object client-side before sending to server.
  10733. */
  10734. var validateFirebaseData = function (errorPrefix, data, path_) {
  10735. var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
  10736. if (data === undefined) {
  10737. throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
  10738. }
  10739. if (typeof data === 'function') {
  10740. throw new Error(errorPrefix +
  10741. 'contains a function ' +
  10742. validationPathToErrorString(path) +
  10743. ' with contents = ' +
  10744. data.toString());
  10745. }
  10746. if (isInvalidJSONNumber(data)) {
  10747. throw new Error(errorPrefix +
  10748. 'contains ' +
  10749. data.toString() +
  10750. ' ' +
  10751. validationPathToErrorString(path));
  10752. }
  10753. // Check max leaf size, but try to avoid the utf8 conversion if we can.
  10754. if (typeof data === 'string' &&
  10755. data.length > MAX_LEAF_SIZE_ / 3 &&
  10756. util.stringLength(data) > MAX_LEAF_SIZE_) {
  10757. throw new Error(errorPrefix +
  10758. 'contains a string greater than ' +
  10759. MAX_LEAF_SIZE_ +
  10760. ' utf8 bytes ' +
  10761. validationPathToErrorString(path) +
  10762. " ('" +
  10763. data.substring(0, 50) +
  10764. "...')");
  10765. }
  10766. // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON
  10767. // to save extra walking of large objects.
  10768. if (data && typeof data === 'object') {
  10769. var hasDotValue_1 = false;
  10770. var hasActualChild_1 = false;
  10771. each(data, function (key, value) {
  10772. if (key === '.value') {
  10773. hasDotValue_1 = true;
  10774. }
  10775. else if (key !== '.priority' && key !== '.sv') {
  10776. hasActualChild_1 = true;
  10777. if (!isValidKey(key)) {
  10778. throw new Error(errorPrefix +
  10779. ' contains an invalid key (' +
  10780. key +
  10781. ') ' +
  10782. validationPathToErrorString(path) +
  10783. '. Keys must be non-empty strings ' +
  10784. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10785. }
  10786. }
  10787. validationPathPush(path, key);
  10788. validateFirebaseData(errorPrefix, value, path);
  10789. validationPathPop(path);
  10790. });
  10791. if (hasDotValue_1 && hasActualChild_1) {
  10792. throw new Error(errorPrefix +
  10793. ' contains ".value" child ' +
  10794. validationPathToErrorString(path) +
  10795. ' in addition to actual children.');
  10796. }
  10797. }
  10798. };
  10799. /**
  10800. * Pre-validate paths passed in the firebase function.
  10801. */
  10802. var validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
  10803. var i, curPath;
  10804. for (i = 0; i < mergePaths.length; i++) {
  10805. curPath = mergePaths[i];
  10806. var keys = pathSlice(curPath);
  10807. for (var j = 0; j < keys.length; j++) {
  10808. if (keys[j] === '.priority' && j === keys.length - 1) ;
  10809. else if (!isValidKey(keys[j])) {
  10810. throw new Error(errorPrefix +
  10811. 'contains an invalid key (' +
  10812. keys[j] +
  10813. ') in path ' +
  10814. curPath.toString() +
  10815. '. Keys must be non-empty strings ' +
  10816. 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
  10817. }
  10818. }
  10819. }
  10820. // Check that update keys are not descendants of each other.
  10821. // We rely on the property that sorting guarantees that ancestors come
  10822. // right before descendants.
  10823. mergePaths.sort(pathCompare);
  10824. var prevPath = null;
  10825. for (i = 0; i < mergePaths.length; i++) {
  10826. curPath = mergePaths[i];
  10827. if (prevPath !== null && pathContains(prevPath, curPath)) {
  10828. throw new Error(errorPrefix +
  10829. 'contains a path ' +
  10830. prevPath.toString() +
  10831. ' that is ancestor of another path ' +
  10832. curPath.toString());
  10833. }
  10834. prevPath = curPath;
  10835. }
  10836. };
  10837. /**
  10838. * pre-validate an object passed as an argument to firebase function (
  10839. * must be an object - e.g. for firebase.update()).
  10840. */
  10841. var validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
  10842. if (optional && data === undefined) {
  10843. return;
  10844. }
  10845. var errorPrefix = util.errorPrefix(fnName, 'values');
  10846. if (!(data && typeof data === 'object') || Array.isArray(data)) {
  10847. throw new Error(errorPrefix + ' must be an object containing the children to replace.');
  10848. }
  10849. var mergePaths = [];
  10850. each(data, function (key, value) {
  10851. var curPath = new Path(key);
  10852. validateFirebaseData(errorPrefix, value, pathChild(path, curPath));
  10853. if (pathGetBack(curPath) === '.priority') {
  10854. if (!isValidPriority(value)) {
  10855. throw new Error(errorPrefix +
  10856. "contains an invalid value for '" +
  10857. curPath.toString() +
  10858. "', which must be a valid " +
  10859. 'Firebase priority (a string, finite number, server value, or null).');
  10860. }
  10861. }
  10862. mergePaths.push(curPath);
  10863. });
  10864. validateFirebaseMergePaths(errorPrefix, mergePaths);
  10865. };
  10866. var validatePriority = function (fnName, priority, optional) {
  10867. if (optional && priority === undefined) {
  10868. return;
  10869. }
  10870. if (isInvalidJSONNumber(priority)) {
  10871. throw new Error(util.errorPrefix(fnName, 'priority') +
  10872. 'is ' +
  10873. priority.toString() +
  10874. ', but must be a valid Firebase priority (a string, finite number, ' +
  10875. 'server value, or null).');
  10876. }
  10877. // Special case to allow importing data with a .sv.
  10878. if (!isValidPriority(priority)) {
  10879. throw new Error(util.errorPrefix(fnName, 'priority') +
  10880. 'must be a valid Firebase priority ' +
  10881. '(a string, finite number, server value, or null).');
  10882. }
  10883. };
  10884. var validateKey = function (fnName, argumentName, key, optional) {
  10885. if (optional && key === undefined) {
  10886. return;
  10887. }
  10888. if (!isValidKey(key)) {
  10889. throw new Error(util.errorPrefix(fnName, argumentName) +
  10890. 'was an invalid key = "' +
  10891. key +
  10892. '". Firebase keys must be non-empty strings and ' +
  10893. 'can\'t contain ".", "#", "$", "/", "[", or "]").');
  10894. }
  10895. };
  10896. /**
  10897. * @internal
  10898. */
  10899. var validatePathString = function (fnName, argumentName, pathString, optional) {
  10900. if (optional && pathString === undefined) {
  10901. return;
  10902. }
  10903. if (!isValidPathString(pathString)) {
  10904. throw new Error(util.errorPrefix(fnName, argumentName) +
  10905. 'was an invalid path = "' +
  10906. pathString +
  10907. '". Paths must be non-empty strings and ' +
  10908. 'can\'t contain ".", "#", "$", "[", or "]"');
  10909. }
  10910. };
  10911. var validateRootPathString = function (fnName, argumentName, pathString, optional) {
  10912. if (pathString) {
  10913. // Allow '/.info/' at the beginning.
  10914. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
  10915. }
  10916. validatePathString(fnName, argumentName, pathString, optional);
  10917. };
  10918. /**
  10919. * @internal
  10920. */
  10921. var validateWritablePath = function (fnName, path) {
  10922. if (pathGetFront(path) === '.info') {
  10923. throw new Error(fnName + " failed = Can't modify data under /.info/");
  10924. }
  10925. };
  10926. var validateUrl = function (fnName, parsedUrl) {
  10927. // TODO = Validate server better.
  10928. var pathString = parsedUrl.path.toString();
  10929. if (!(typeof parsedUrl.repoInfo.host === 'string') ||
  10930. parsedUrl.repoInfo.host.length === 0 ||
  10931. (!isValidKey(parsedUrl.repoInfo.namespace) &&
  10932. parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
  10933. (pathString.length !== 0 && !isValidRootPathString(pathString))) {
  10934. throw new Error(util.errorPrefix(fnName, 'url') +
  10935. 'must be a valid firebase URL and ' +
  10936. 'the path can\'t contain ".", "#", "$", "[", or "]".');
  10937. }
  10938. };
  10939. /**
  10940. * @license
  10941. * Copyright 2017 Google LLC
  10942. *
  10943. * Licensed under the Apache License, Version 2.0 (the "License");
  10944. * you may not use this file except in compliance with the License.
  10945. * You may obtain a copy of the License at
  10946. *
  10947. * http://www.apache.org/licenses/LICENSE-2.0
  10948. *
  10949. * Unless required by applicable law or agreed to in writing, software
  10950. * distributed under the License is distributed on an "AS IS" BASIS,
  10951. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10952. * See the License for the specific language governing permissions and
  10953. * limitations under the License.
  10954. */
  10955. /**
  10956. * The event queue serves a few purposes:
  10957. * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
  10958. * events being queued.
  10959. * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
  10960. * raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
  10961. * left off, ensuring that the events are still raised synchronously and in order.
  10962. * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
  10963. * events are raised synchronously.
  10964. *
  10965. * NOTE: This can all go away if/when we move to async events.
  10966. *
  10967. */
  10968. var EventQueue = /** @class */ (function () {
  10969. function EventQueue() {
  10970. this.eventLists_ = [];
  10971. /**
  10972. * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
  10973. */
  10974. this.recursionDepth_ = 0;
  10975. }
  10976. return EventQueue;
  10977. }());
  10978. /**
  10979. * @param eventDataList - The new events to queue.
  10980. */
  10981. function eventQueueQueueEvents(eventQueue, eventDataList) {
  10982. // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.
  10983. var currList = null;
  10984. for (var i = 0; i < eventDataList.length; i++) {
  10985. var data = eventDataList[i];
  10986. var path = data.getPath();
  10987. if (currList !== null && !pathEquals(path, currList.path)) {
  10988. eventQueue.eventLists_.push(currList);
  10989. currList = null;
  10990. }
  10991. if (currList === null) {
  10992. currList = { events: [], path: path };
  10993. }
  10994. currList.events.push(data);
  10995. }
  10996. if (currList) {
  10997. eventQueue.eventLists_.push(currList);
  10998. }
  10999. }
  11000. /**
  11001. * Queues the specified events and synchronously raises all events (including previously queued ones)
  11002. * for the specified path.
  11003. *
  11004. * It is assumed that the new events are all for the specified path.
  11005. *
  11006. * @param path - The path to raise events for.
  11007. * @param eventDataList - The new events to raise.
  11008. */
  11009. function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
  11010. eventQueueQueueEvents(eventQueue, eventDataList);
  11011. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11012. return pathEquals(eventPath, path);
  11013. });
  11014. }
  11015. /**
  11016. * Queues the specified events and synchronously raises all events (including previously queued ones) for
  11017. * locations related to the specified change path (i.e. all ancestors and descendants).
  11018. *
  11019. * It is assumed that the new events are all related (ancestor or descendant) to the specified path.
  11020. *
  11021. * @param changedPath - The path to raise events for.
  11022. * @param eventDataList - The events to raise
  11023. */
  11024. function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
  11025. eventQueueQueueEvents(eventQueue, eventDataList);
  11026. eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
  11027. return pathContains(eventPath, changedPath) ||
  11028. pathContains(changedPath, eventPath);
  11029. });
  11030. }
  11031. function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
  11032. eventQueue.recursionDepth_++;
  11033. var sentAll = true;
  11034. for (var i = 0; i < eventQueue.eventLists_.length; i++) {
  11035. var eventList = eventQueue.eventLists_[i];
  11036. if (eventList) {
  11037. var eventPath = eventList.path;
  11038. if (predicate(eventPath)) {
  11039. eventListRaise(eventQueue.eventLists_[i]);
  11040. eventQueue.eventLists_[i] = null;
  11041. }
  11042. else {
  11043. sentAll = false;
  11044. }
  11045. }
  11046. }
  11047. if (sentAll) {
  11048. eventQueue.eventLists_ = [];
  11049. }
  11050. eventQueue.recursionDepth_--;
  11051. }
  11052. /**
  11053. * Iterates through the list and raises each event
  11054. */
  11055. function eventListRaise(eventList) {
  11056. for (var i = 0; i < eventList.events.length; i++) {
  11057. var eventData = eventList.events[i];
  11058. if (eventData !== null) {
  11059. eventList.events[i] = null;
  11060. var eventFn = eventData.getEventRunner();
  11061. if (logger) {
  11062. log('event: ' + eventData.toString());
  11063. }
  11064. exceptionGuard(eventFn);
  11065. }
  11066. }
  11067. }
  11068. /**
  11069. * @license
  11070. * Copyright 2017 Google LLC
  11071. *
  11072. * Licensed under the Apache License, Version 2.0 (the "License");
  11073. * you may not use this file except in compliance with the License.
  11074. * You may obtain a copy of the License at
  11075. *
  11076. * http://www.apache.org/licenses/LICENSE-2.0
  11077. *
  11078. * Unless required by applicable law or agreed to in writing, software
  11079. * distributed under the License is distributed on an "AS IS" BASIS,
  11080. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11081. * See the License for the specific language governing permissions and
  11082. * limitations under the License.
  11083. */
  11084. var INTERRUPT_REASON = 'repo_interrupt';
  11085. /**
  11086. * If a transaction does not succeed after 25 retries, we abort it. Among other
  11087. * things this ensure that if there's ever a bug causing a mismatch between
  11088. * client / server hashes for some data, we won't retry indefinitely.
  11089. */
  11090. var MAX_TRANSACTION_RETRIES = 25;
  11091. /**
  11092. * A connection to a single data repository.
  11093. */
  11094. var Repo = /** @class */ (function () {
  11095. function Repo(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
  11096. this.repoInfo_ = repoInfo_;
  11097. this.forceRestClient_ = forceRestClient_;
  11098. this.authTokenProvider_ = authTokenProvider_;
  11099. this.appCheckProvider_ = appCheckProvider_;
  11100. this.dataUpdateCount = 0;
  11101. this.statsListener_ = null;
  11102. this.eventQueue_ = new EventQueue();
  11103. this.nextWriteId_ = 1;
  11104. this.interceptServerDataCallback_ = null;
  11105. /** A list of data pieces and paths to be set when this client disconnects. */
  11106. this.onDisconnect_ = newSparseSnapshotTree();
  11107. /** Stores queues of outstanding transactions for Firebase locations. */
  11108. this.transactionQueueTree_ = new Tree();
  11109. // TODO: This should be @private but it's used by test_access.js and internal.js
  11110. this.persistentConnection_ = null;
  11111. // This key is intentionally not updated if RepoInfo is later changed or replaced
  11112. this.key = this.repoInfo_.toURLString();
  11113. }
  11114. /**
  11115. * @returns The URL corresponding to the root of this Firebase.
  11116. */
  11117. Repo.prototype.toString = function () {
  11118. return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
  11119. };
  11120. return Repo;
  11121. }());
  11122. function repoStart(repo, appId, authOverride) {
  11123. repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
  11124. if (repo.forceRestClient_ || beingCrawled()) {
  11125. repo.server_ = new ReadonlyRestClient(repo.repoInfo_, function (pathString, data, isMerge, tag) {
  11126. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11127. }, repo.authTokenProvider_, repo.appCheckProvider_);
  11128. // Minor hack: Fire onConnect immediately, since there's no actual connection.
  11129. setTimeout(function () { return repoOnConnectStatus(repo, /* connectStatus= */ true); }, 0);
  11130. }
  11131. else {
  11132. // Validate authOverride
  11133. if (typeof authOverride !== 'undefined' && authOverride !== null) {
  11134. if (typeof authOverride !== 'object') {
  11135. throw new Error('Only objects are supported for option databaseAuthVariableOverride');
  11136. }
  11137. try {
  11138. util.stringify(authOverride);
  11139. }
  11140. catch (e) {
  11141. throw new Error('Invalid authOverride provided: ' + e);
  11142. }
  11143. }
  11144. repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, function (pathString, data, isMerge, tag) {
  11145. repoOnDataUpdate(repo, pathString, data, isMerge, tag);
  11146. }, function (connectStatus) {
  11147. repoOnConnectStatus(repo, connectStatus);
  11148. }, function (updates) {
  11149. repoOnServerInfoUpdate(repo, updates);
  11150. }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
  11151. repo.server_ = repo.persistentConnection_;
  11152. }
  11153. repo.authTokenProvider_.addTokenChangeListener(function (token) {
  11154. repo.server_.refreshAuthToken(token);
  11155. });
  11156. repo.appCheckProvider_.addTokenChangeListener(function (result) {
  11157. repo.server_.refreshAppCheckToken(result.token);
  11158. });
  11159. // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),
  11160. // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.
  11161. repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, function () { return new StatsReporter(repo.stats_, repo.server_); });
  11162. // Used for .info.
  11163. repo.infoData_ = new SnapshotHolder();
  11164. repo.infoSyncTree_ = new SyncTree({
  11165. startListening: function (query, tag, currentHashFn, onComplete) {
  11166. var infoEvents = [];
  11167. var node = repo.infoData_.getNode(query._path);
  11168. // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events
  11169. // on initial data...
  11170. if (!node.isEmpty()) {
  11171. infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
  11172. setTimeout(function () {
  11173. onComplete('ok');
  11174. }, 0);
  11175. }
  11176. return infoEvents;
  11177. },
  11178. stopListening: function () { }
  11179. });
  11180. repoUpdateInfo(repo, 'connected', false);
  11181. repo.serverSyncTree_ = new SyncTree({
  11182. startListening: function (query, tag, currentHashFn, onComplete) {
  11183. repo.server_.listen(query, currentHashFn, tag, function (status, data) {
  11184. var events = onComplete(status, data);
  11185. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11186. });
  11187. // No synchronous events for network-backed sync trees
  11188. return [];
  11189. },
  11190. stopListening: function (query, tag) {
  11191. repo.server_.unlisten(query, tag);
  11192. }
  11193. });
  11194. }
  11195. /**
  11196. * @returns The time in milliseconds, taking the server offset into account if we have one.
  11197. */
  11198. function repoServerTime(repo) {
  11199. var offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
  11200. var offset = offsetNode.val() || 0;
  11201. return new Date().getTime() + offset;
  11202. }
  11203. /**
  11204. * Generate ServerValues using some variables from the repo object.
  11205. */
  11206. function repoGenerateServerValues(repo) {
  11207. return generateWithValues({
  11208. timestamp: repoServerTime(repo)
  11209. });
  11210. }
  11211. /**
  11212. * Called by realtime when we get new messages from the server.
  11213. */
  11214. function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
  11215. // For testing.
  11216. repo.dataUpdateCount++;
  11217. var path = new Path(pathString);
  11218. data = repo.interceptServerDataCallback_
  11219. ? repo.interceptServerDataCallback_(pathString, data)
  11220. : data;
  11221. var events = [];
  11222. if (tag) {
  11223. if (isMerge) {
  11224. var taggedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
  11225. events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
  11226. }
  11227. else {
  11228. var taggedSnap = nodeFromJSON(data);
  11229. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
  11230. }
  11231. }
  11232. else if (isMerge) {
  11233. var changedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
  11234. events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
  11235. }
  11236. else {
  11237. var snap = nodeFromJSON(data);
  11238. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
  11239. }
  11240. var affectedPath = path;
  11241. if (events.length > 0) {
  11242. // Since we have a listener outstanding for each transaction, receiving any events
  11243. // is a proxy for some change having occurred.
  11244. affectedPath = repoRerunTransactions(repo, path);
  11245. }
  11246. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
  11247. }
  11248. function repoOnConnectStatus(repo, connectStatus) {
  11249. repoUpdateInfo(repo, 'connected', connectStatus);
  11250. if (connectStatus === false) {
  11251. repoRunOnDisconnectEvents(repo);
  11252. }
  11253. }
  11254. function repoOnServerInfoUpdate(repo, updates) {
  11255. each(updates, function (key, value) {
  11256. repoUpdateInfo(repo, key, value);
  11257. });
  11258. }
  11259. function repoUpdateInfo(repo, pathString, value) {
  11260. var path = new Path('/.info/' + pathString);
  11261. var newNode = nodeFromJSON(value);
  11262. repo.infoData_.updateSnapshot(path, newNode);
  11263. var events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
  11264. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11265. }
  11266. function repoGetNextWriteId(repo) {
  11267. return repo.nextWriteId_++;
  11268. }
  11269. /**
  11270. * The purpose of `getValue` is to return the latest known value
  11271. * satisfying `query`.
  11272. *
  11273. * This method will first check for in-memory cached values
  11274. * belonging to active listeners. If they are found, such values
  11275. * are considered to be the most up-to-date.
  11276. *
  11277. * If the client is not connected, this method will wait until the
  11278. * repo has established a connection and then request the value for `query`.
  11279. * If the client is not able to retrieve the query result for another reason,
  11280. * it reports an error.
  11281. *
  11282. * @param query - The query to surface a value for.
  11283. */
  11284. function repoGetValue(repo, query, eventRegistration) {
  11285. // Only active queries are cached. There is no persisted cache.
  11286. var cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
  11287. if (cached != null) {
  11288. return Promise.resolve(cached);
  11289. }
  11290. return repo.server_.get(query).then(function (payload) {
  11291. var node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
  11292. /**
  11293. * Below we simulate the actions of an `onlyOnce` `onValue()` event where:
  11294. * Add an event registration,
  11295. * Update data at the path,
  11296. * Raise any events,
  11297. * Cleanup the SyncTree
  11298. */
  11299. syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
  11300. var events;
  11301. if (query._queryParams.loadsAllData()) {
  11302. events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
  11303. }
  11304. else {
  11305. var tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
  11306. events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
  11307. }
  11308. /*
  11309. * We need to raise events in the scenario where `get()` is called at a parent path, and
  11310. * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting
  11311. * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree
  11312. * and its corresponding serverCache, including the child location where `onValue` is called. Then,
  11313. * `onValue` will receive the event from the server, but look at the syncTree and see that the data received
  11314. * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.
  11315. * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and
  11316. * ensure the corresponding child events will get fired.
  11317. */
  11318. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
  11319. syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
  11320. return node;
  11321. }, function (err) {
  11322. repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err);
  11323. return Promise.reject(new Error(err));
  11324. });
  11325. }
  11326. function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
  11327. repoLog(repo, 'set', {
  11328. path: path.toString(),
  11329. value: newVal,
  11330. priority: newPriority
  11331. });
  11332. // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or
  11333. // (b) store unresolved paths on JSON parse
  11334. var serverValues = repoGenerateServerValues(repo);
  11335. var newNodeUnresolved = nodeFromJSON(newVal, newPriority);
  11336. var existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
  11337. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
  11338. var writeId = repoGetNextWriteId(repo);
  11339. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
  11340. eventQueueQueueEvents(repo.eventQueue_, events);
  11341. repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {
  11342. var success = status === 'ok';
  11343. if (!success) {
  11344. warn('set at ' + path + ' failed: ' + status);
  11345. }
  11346. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
  11347. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
  11348. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11349. });
  11350. var affectedPath = repoAbortTransactions(repo, path);
  11351. repoRerunTransactions(repo, affectedPath);
  11352. // We queued the events above, so just flush the queue here
  11353. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  11354. }
  11355. function repoUpdate(repo, path, childrenToMerge, onComplete) {
  11356. repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
  11357. // Start with our existing data and merge each child into it.
  11358. var empty = true;
  11359. var serverValues = repoGenerateServerValues(repo);
  11360. var changedChildren = {};
  11361. each(childrenToMerge, function (changedKey, changedValue) {
  11362. empty = false;
  11363. changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
  11364. });
  11365. if (!empty) {
  11366. var writeId_1 = repoGetNextWriteId(repo);
  11367. var events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId_1);
  11368. eventQueueQueueEvents(repo.eventQueue_, events);
  11369. repo.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {
  11370. var success = status === 'ok';
  11371. if (!success) {
  11372. warn('update at ' + path + ' failed: ' + status);
  11373. }
  11374. var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId_1, !success);
  11375. var affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
  11376. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
  11377. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11378. });
  11379. each(childrenToMerge, function (changedPath) {
  11380. var affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
  11381. repoRerunTransactions(repo, affectedPath);
  11382. });
  11383. // We queued the events above, so just flush the queue here
  11384. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
  11385. }
  11386. else {
  11387. log("update() called with empty data. Don't do anything.");
  11388. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11389. }
  11390. }
  11391. /**
  11392. * Applies all of the changes stored up in the onDisconnect_ tree.
  11393. */
  11394. function repoRunOnDisconnectEvents(repo) {
  11395. repoLog(repo, 'onDisconnectEvents');
  11396. var serverValues = repoGenerateServerValues(repo);
  11397. var resolvedOnDisconnectTree = newSparseSnapshotTree();
  11398. sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), function (path, node) {
  11399. var resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
  11400. sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
  11401. });
  11402. var events = [];
  11403. sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), function (path, snap) {
  11404. events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
  11405. var affectedPath = repoAbortTransactions(repo, path);
  11406. repoRerunTransactions(repo, affectedPath);
  11407. });
  11408. repo.onDisconnect_ = newSparseSnapshotTree();
  11409. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
  11410. }
  11411. function repoOnDisconnectCancel(repo, path, onComplete) {
  11412. repo.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {
  11413. if (status === 'ok') {
  11414. sparseSnapshotTreeForget(repo.onDisconnect_, path);
  11415. }
  11416. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11417. });
  11418. }
  11419. function repoOnDisconnectSet(repo, path, value, onComplete) {
  11420. var newNode = nodeFromJSON(value);
  11421. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11422. if (status === 'ok') {
  11423. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11424. }
  11425. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11426. });
  11427. }
  11428. function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
  11429. var newNode = nodeFromJSON(value, priority);
  11430. repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {
  11431. if (status === 'ok') {
  11432. sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
  11433. }
  11434. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11435. });
  11436. }
  11437. function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
  11438. if (util.isEmpty(childrenToMerge)) {
  11439. log("onDisconnect().update() called with empty data. Don't do anything.");
  11440. repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
  11441. return;
  11442. }
  11443. repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {
  11444. if (status === 'ok') {
  11445. each(childrenToMerge, function (childName, childNode) {
  11446. var newChildNode = nodeFromJSON(childNode);
  11447. sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
  11448. });
  11449. }
  11450. repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
  11451. });
  11452. }
  11453. function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
  11454. var events;
  11455. if (pathGetFront(query._path) === '.info') {
  11456. events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11457. }
  11458. else {
  11459. events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11460. }
  11461. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11462. }
  11463. function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
  11464. // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof
  11465. // a little bit by handling the return values anyways.
  11466. var events;
  11467. if (pathGetFront(query._path) === '.info') {
  11468. events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
  11469. }
  11470. else {
  11471. events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
  11472. }
  11473. eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
  11474. }
  11475. function repoInterrupt(repo) {
  11476. if (repo.persistentConnection_) {
  11477. repo.persistentConnection_.interrupt(INTERRUPT_REASON);
  11478. }
  11479. }
  11480. function repoResume(repo) {
  11481. if (repo.persistentConnection_) {
  11482. repo.persistentConnection_.resume(INTERRUPT_REASON);
  11483. }
  11484. }
  11485. function repoLog(repo) {
  11486. var varArgs = [];
  11487. for (var _i = 1; _i < arguments.length; _i++) {
  11488. varArgs[_i - 1] = arguments[_i];
  11489. }
  11490. var prefix = '';
  11491. if (repo.persistentConnection_) {
  11492. prefix = repo.persistentConnection_.id + ':';
  11493. }
  11494. log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
  11495. }
  11496. function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
  11497. if (callback) {
  11498. exceptionGuard(function () {
  11499. if (status === 'ok') {
  11500. callback(null);
  11501. }
  11502. else {
  11503. var code = (status || 'error').toUpperCase();
  11504. var message = code;
  11505. if (errorReason) {
  11506. message += ': ' + errorReason;
  11507. }
  11508. var error = new Error(message);
  11509. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11510. error.code = code;
  11511. callback(error);
  11512. }
  11513. });
  11514. }
  11515. }
  11516. /**
  11517. * Creates a new transaction, adds it to the transactions we're tracking, and
  11518. * sends it to the server if possible.
  11519. *
  11520. * @param path - Path at which to do transaction.
  11521. * @param transactionUpdate - Update callback.
  11522. * @param onComplete - Completion callback.
  11523. * @param unwatcher - Function that will be called when the transaction no longer
  11524. * need data updates for `path`.
  11525. * @param applyLocally - Whether or not to make intermediate results visible
  11526. */
  11527. function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
  11528. repoLog(repo, 'transaction on ' + path);
  11529. // Initialize transaction.
  11530. var transaction = {
  11531. path: path,
  11532. update: transactionUpdate,
  11533. onComplete: onComplete,
  11534. // One of TransactionStatus enums.
  11535. status: null,
  11536. // Used when combining transactions at different locations to figure out
  11537. // which one goes first.
  11538. order: LUIDGenerator(),
  11539. // Whether to raise local events for this transaction.
  11540. applyLocally: applyLocally,
  11541. // Count of how many times we've retried the transaction.
  11542. retryCount: 0,
  11543. // Function to call to clean up our .on() listener.
  11544. unwatcher: unwatcher,
  11545. // Stores why a transaction was aborted.
  11546. abortReason: null,
  11547. currentWriteId: null,
  11548. currentInputSnapshot: null,
  11549. currentOutputSnapshotRaw: null,
  11550. currentOutputSnapshotResolved: null
  11551. };
  11552. // Run transaction initially.
  11553. var currentState = repoGetLatestState(repo, path, undefined);
  11554. transaction.currentInputSnapshot = currentState;
  11555. var newVal = transaction.update(currentState.val());
  11556. if (newVal === undefined) {
  11557. // Abort transaction.
  11558. transaction.unwatcher();
  11559. transaction.currentOutputSnapshotRaw = null;
  11560. transaction.currentOutputSnapshotResolved = null;
  11561. if (transaction.onComplete) {
  11562. transaction.onComplete(null, false, transaction.currentInputSnapshot);
  11563. }
  11564. }
  11565. else {
  11566. validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
  11567. // Mark as run and add to our queue.
  11568. transaction.status = 0 /* TransactionStatus.RUN */;
  11569. var queueNode = treeSubTree(repo.transactionQueueTree_, path);
  11570. var nodeQueue = treeGetValue(queueNode) || [];
  11571. nodeQueue.push(transaction);
  11572. treeSetValue(queueNode, nodeQueue);
  11573. // Update visibleData and raise events
  11574. // Note: We intentionally raise events after updating all of our
  11575. // transaction state, since the user could start new transactions from the
  11576. // event callbacks.
  11577. var priorityForNode = void 0;
  11578. if (typeof newVal === 'object' &&
  11579. newVal !== null &&
  11580. util.contains(newVal, '.priority')) {
  11581. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  11582. priorityForNode = util.safeGet(newVal, '.priority');
  11583. util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
  11584. 'Priority must be a valid string, finite number, server value, or null.');
  11585. }
  11586. else {
  11587. var currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
  11588. ChildrenNode.EMPTY_NODE;
  11589. priorityForNode = currentNode.getPriority().val();
  11590. }
  11591. var serverValues = repoGenerateServerValues(repo);
  11592. var newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
  11593. var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
  11594. transaction.currentOutputSnapshotRaw = newNodeUnresolved;
  11595. transaction.currentOutputSnapshotResolved = newNode;
  11596. transaction.currentWriteId = repoGetNextWriteId(repo);
  11597. var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
  11598. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11599. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11600. }
  11601. }
  11602. /**
  11603. * @param excludeSets - A specific set to exclude
  11604. */
  11605. function repoGetLatestState(repo, path, excludeSets) {
  11606. return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
  11607. ChildrenNode.EMPTY_NODE);
  11608. }
  11609. /**
  11610. * Sends any already-run transactions that aren't waiting for outstanding
  11611. * transactions to complete.
  11612. *
  11613. * Externally it's called with no arguments, but it calls itself recursively
  11614. * with a particular transactionQueueTree node to recurse through the tree.
  11615. *
  11616. * @param node - transactionQueueTree node to start at.
  11617. */
  11618. function repoSendReadyTransactions(repo, node) {
  11619. if (node === void 0) { node = repo.transactionQueueTree_; }
  11620. // Before recursing, make sure any completed transactions are removed.
  11621. if (!node) {
  11622. repoPruneCompletedTransactionsBelowNode(repo, node);
  11623. }
  11624. if (treeGetValue(node)) {
  11625. var queue = repoBuildTransactionQueue(repo, node);
  11626. util.assert(queue.length > 0, 'Sending zero length transaction queue');
  11627. var allRun = queue.every(function (transaction) { return transaction.status === 0 /* TransactionStatus.RUN */; });
  11628. // If they're all run (and not sent), we can send them. Else, we must wait.
  11629. if (allRun) {
  11630. repoSendTransactionQueue(repo, treeGetPath(node), queue);
  11631. }
  11632. }
  11633. else if (treeHasChildren(node)) {
  11634. treeForEachChild(node, function (childNode) {
  11635. repoSendReadyTransactions(repo, childNode);
  11636. });
  11637. }
  11638. }
  11639. /**
  11640. * Given a list of run transactions, send them to the server and then handle
  11641. * the result (success or failure).
  11642. *
  11643. * @param path - The location of the queue.
  11644. * @param queue - Queue of transactions under the specified location.
  11645. */
  11646. function repoSendTransactionQueue(repo, path, queue) {
  11647. // Mark transactions as sent and increment retry count!
  11648. var setsToIgnore = queue.map(function (txn) {
  11649. return txn.currentWriteId;
  11650. });
  11651. var latestState = repoGetLatestState(repo, path, setsToIgnore);
  11652. var snapToSend = latestState;
  11653. var latestHash = latestState.hash();
  11654. for (var i = 0; i < queue.length; i++) {
  11655. var txn = queue[i];
  11656. util.assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');
  11657. txn.status = 1 /* TransactionStatus.SENT */;
  11658. txn.retryCount++;
  11659. var relativePath = newRelativePath(path, txn.path);
  11660. // If we've gotten to this point, the output snapshot must be defined.
  11661. snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);
  11662. }
  11663. var dataToSend = snapToSend.val(true);
  11664. var pathToSend = path;
  11665. // Send the put.
  11666. repo.server_.put(pathToSend.toString(), dataToSend, function (status) {
  11667. repoLog(repo, 'transaction put response', {
  11668. path: pathToSend.toString(),
  11669. status: status
  11670. });
  11671. var events = [];
  11672. if (status === 'ok') {
  11673. // Queue up the callbacks and fire them after cleaning up all of our
  11674. // transaction state, since the callback could trigger more
  11675. // transactions or sets.
  11676. var callbacks = [];
  11677. var _loop_1 = function (i) {
  11678. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11679. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
  11680. if (queue[i].onComplete) {
  11681. // We never unset the output snapshot, and given that this
  11682. // transaction is complete, it should be set
  11683. callbacks.push(function () {
  11684. return queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved);
  11685. });
  11686. }
  11687. queue[i].unwatcher();
  11688. };
  11689. for (var i = 0; i < queue.length; i++) {
  11690. _loop_1(i);
  11691. }
  11692. // Now remove the completed transactions.
  11693. repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
  11694. // There may be pending transactions that we can now send.
  11695. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11696. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11697. // Finally, trigger onComplete callbacks.
  11698. for (var i = 0; i < callbacks.length; i++) {
  11699. exceptionGuard(callbacks[i]);
  11700. }
  11701. }
  11702. else {
  11703. // transactions are no longer sent. Update their status appropriately.
  11704. if (status === 'datastale') {
  11705. for (var i = 0; i < queue.length; i++) {
  11706. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {
  11707. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11708. }
  11709. else {
  11710. queue[i].status = 0 /* TransactionStatus.RUN */;
  11711. }
  11712. }
  11713. }
  11714. else {
  11715. warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
  11716. for (var i = 0; i < queue.length; i++) {
  11717. queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;
  11718. queue[i].abortReason = status;
  11719. }
  11720. }
  11721. repoRerunTransactions(repo, path);
  11722. }
  11723. }, latestHash);
  11724. }
  11725. /**
  11726. * Finds all transactions dependent on the data at changedPath and reruns them.
  11727. *
  11728. * Should be called any time cached data changes.
  11729. *
  11730. * Return the highest path that was affected by rerunning transactions. This
  11731. * is the path at which events need to be raised for.
  11732. *
  11733. * @param changedPath - The path in mergedData that changed.
  11734. * @returns The rootmost path that was affected by rerunning transactions.
  11735. */
  11736. function repoRerunTransactions(repo, changedPath) {
  11737. var rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
  11738. var path = treeGetPath(rootMostTransactionNode);
  11739. var queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
  11740. repoRerunTransactionQueue(repo, queue, path);
  11741. return path;
  11742. }
  11743. /**
  11744. * Does all the work of rerunning transactions (as well as cleans up aborted
  11745. * transactions and whatnot).
  11746. *
  11747. * @param queue - The queue of transactions to run.
  11748. * @param path - The path the queue is for.
  11749. */
  11750. function repoRerunTransactionQueue(repo, queue, path) {
  11751. if (queue.length === 0) {
  11752. return; // Nothing to do!
  11753. }
  11754. // Queue up the callbacks and fire them after cleaning up all of our
  11755. // transaction state, since the callback could trigger more transactions or
  11756. // sets.
  11757. var callbacks = [];
  11758. var events = [];
  11759. // Ignore all of the sets we're going to re-run.
  11760. var txnsToRerun = queue.filter(function (q) {
  11761. return q.status === 0 /* TransactionStatus.RUN */;
  11762. });
  11763. var setsToIgnore = txnsToRerun.map(function (q) {
  11764. return q.currentWriteId;
  11765. });
  11766. var _loop_2 = function (i) {
  11767. var transaction = queue[i];
  11768. var relativePath = newRelativePath(path, transaction.path);
  11769. var abortTransaction = false, abortReason;
  11770. util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
  11771. if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {
  11772. abortTransaction = true;
  11773. abortReason = transaction.abortReason;
  11774. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11775. }
  11776. else if (transaction.status === 0 /* TransactionStatus.RUN */) {
  11777. if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
  11778. abortTransaction = true;
  11779. abortReason = 'maxretry';
  11780. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11781. }
  11782. else {
  11783. // This code reruns a transaction
  11784. var currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
  11785. transaction.currentInputSnapshot = currentNode;
  11786. var newData = queue[i].update(currentNode.val());
  11787. if (newData !== undefined) {
  11788. validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
  11789. var newDataNode = nodeFromJSON(newData);
  11790. var hasExplicitPriority = typeof newData === 'object' &&
  11791. newData != null &&
  11792. util.contains(newData, '.priority');
  11793. if (!hasExplicitPriority) {
  11794. // Keep the old priority if there wasn't a priority explicitly specified.
  11795. newDataNode = newDataNode.updatePriority(currentNode.getPriority());
  11796. }
  11797. var oldWriteId = transaction.currentWriteId;
  11798. var serverValues = repoGenerateServerValues(repo);
  11799. var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
  11800. transaction.currentOutputSnapshotRaw = newDataNode;
  11801. transaction.currentOutputSnapshotResolved = newNodeResolved;
  11802. transaction.currentWriteId = repoGetNextWriteId(repo);
  11803. // Mutates setsToIgnore in place
  11804. setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
  11805. events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
  11806. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
  11807. }
  11808. else {
  11809. abortTransaction = true;
  11810. abortReason = 'nodata';
  11811. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
  11812. }
  11813. }
  11814. }
  11815. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
  11816. events = [];
  11817. if (abortTransaction) {
  11818. // Abort.
  11819. queue[i].status = 2 /* TransactionStatus.COMPLETED */;
  11820. // Removing a listener can trigger pruning which can muck with
  11821. // mergedData/visibleData (as it prunes data). So defer the unwatcher
  11822. // until we're done.
  11823. (function (unwatcher) {
  11824. setTimeout(unwatcher, Math.floor(0));
  11825. })(queue[i].unwatcher);
  11826. if (queue[i].onComplete) {
  11827. if (abortReason === 'nodata') {
  11828. callbacks.push(function () {
  11829. return queue[i].onComplete(null, false, queue[i].currentInputSnapshot);
  11830. });
  11831. }
  11832. else {
  11833. callbacks.push(function () {
  11834. return queue[i].onComplete(new Error(abortReason), false, null);
  11835. });
  11836. }
  11837. }
  11838. }
  11839. };
  11840. for (var i = 0; i < queue.length; i++) {
  11841. _loop_2(i);
  11842. }
  11843. // Clean up completed transactions.
  11844. repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
  11845. // Now fire callbacks, now that we're in a good, known state.
  11846. for (var i = 0; i < callbacks.length; i++) {
  11847. exceptionGuard(callbacks[i]);
  11848. }
  11849. // Try to send the transaction result to the server.
  11850. repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  11851. }
  11852. /**
  11853. * Returns the rootmost ancestor node of the specified path that has a pending
  11854. * transaction on it, or just returns the node for the given path if there are
  11855. * no pending transactions on any ancestor.
  11856. *
  11857. * @param path - The location to start at.
  11858. * @returns The rootmost node with a transaction.
  11859. */
  11860. function repoGetAncestorTransactionNode(repo, path) {
  11861. var front;
  11862. // Start at the root and walk deeper into the tree towards path until we
  11863. // find a node with pending transactions.
  11864. var transactionNode = repo.transactionQueueTree_;
  11865. front = pathGetFront(path);
  11866. while (front !== null && treeGetValue(transactionNode) === undefined) {
  11867. transactionNode = treeSubTree(transactionNode, front);
  11868. path = pathPopFront(path);
  11869. front = pathGetFront(path);
  11870. }
  11871. return transactionNode;
  11872. }
  11873. /**
  11874. * Builds the queue of all transactions at or below the specified
  11875. * transactionNode.
  11876. *
  11877. * @param transactionNode
  11878. * @returns The generated queue.
  11879. */
  11880. function repoBuildTransactionQueue(repo, transactionNode) {
  11881. // Walk any child transaction queues and aggregate them into a single queue.
  11882. var transactionQueue = [];
  11883. repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
  11884. // Sort them by the order the transactions were created.
  11885. transactionQueue.sort(function (a, b) { return a.order - b.order; });
  11886. return transactionQueue;
  11887. }
  11888. function repoAggregateTransactionQueuesForNode(repo, node, queue) {
  11889. var nodeQueue = treeGetValue(node);
  11890. if (nodeQueue) {
  11891. for (var i = 0; i < nodeQueue.length; i++) {
  11892. queue.push(nodeQueue[i]);
  11893. }
  11894. }
  11895. treeForEachChild(node, function (child) {
  11896. repoAggregateTransactionQueuesForNode(repo, child, queue);
  11897. });
  11898. }
  11899. /**
  11900. * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.
  11901. */
  11902. function repoPruneCompletedTransactionsBelowNode(repo, node) {
  11903. var queue = treeGetValue(node);
  11904. if (queue) {
  11905. var to = 0;
  11906. for (var from = 0; from < queue.length; from++) {
  11907. if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {
  11908. queue[to] = queue[from];
  11909. to++;
  11910. }
  11911. }
  11912. queue.length = to;
  11913. treeSetValue(node, queue.length > 0 ? queue : undefined);
  11914. }
  11915. treeForEachChild(node, function (childNode) {
  11916. repoPruneCompletedTransactionsBelowNode(repo, childNode);
  11917. });
  11918. }
  11919. /**
  11920. * Aborts all transactions on ancestors or descendants of the specified path.
  11921. * Called when doing a set() or update() since we consider them incompatible
  11922. * with transactions.
  11923. *
  11924. * @param path - Path for which we want to abort related transactions.
  11925. */
  11926. function repoAbortTransactions(repo, path) {
  11927. var affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
  11928. var transactionNode = treeSubTree(repo.transactionQueueTree_, path);
  11929. treeForEachAncestor(transactionNode, function (node) {
  11930. repoAbortTransactionsOnNode(repo, node);
  11931. });
  11932. repoAbortTransactionsOnNode(repo, transactionNode);
  11933. treeForEachDescendant(transactionNode, function (node) {
  11934. repoAbortTransactionsOnNode(repo, node);
  11935. });
  11936. return affectedPath;
  11937. }
  11938. /**
  11939. * Abort transactions stored in this transaction queue node.
  11940. *
  11941. * @param node - Node to abort transactions for.
  11942. */
  11943. function repoAbortTransactionsOnNode(repo, node) {
  11944. var queue = treeGetValue(node);
  11945. if (queue) {
  11946. // Queue up the callbacks and fire them after cleaning up all of our
  11947. // transaction state, since the callback could trigger more transactions
  11948. // or sets.
  11949. var callbacks = [];
  11950. // Go through queue. Any already-sent transactions must be marked for
  11951. // abort, while the unsent ones can be immediately aborted and removed.
  11952. var events = [];
  11953. var lastSent = -1;
  11954. for (var i = 0; i < queue.length; i++) {
  11955. if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;
  11956. else if (queue[i].status === 1 /* TransactionStatus.SENT */) {
  11957. util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
  11958. lastSent = i;
  11959. // Mark transaction for abort when it comes back.
  11960. queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;
  11961. queue[i].abortReason = 'set';
  11962. }
  11963. else {
  11964. util.assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');
  11965. // We can abort it immediately.
  11966. queue[i].unwatcher();
  11967. events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
  11968. if (queue[i].onComplete) {
  11969. callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
  11970. }
  11971. }
  11972. }
  11973. if (lastSent === -1) {
  11974. // We're not waiting for any sent transactions. We can clear the queue.
  11975. treeSetValue(node, undefined);
  11976. }
  11977. else {
  11978. // Remove the transactions we aborted.
  11979. queue.length = lastSent + 1;
  11980. }
  11981. // Now fire the callbacks.
  11982. eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
  11983. for (var i = 0; i < callbacks.length; i++) {
  11984. exceptionGuard(callbacks[i]);
  11985. }
  11986. }
  11987. }
  11988. /**
  11989. * @license
  11990. * Copyright 2017 Google LLC
  11991. *
  11992. * Licensed under the Apache License, Version 2.0 (the "License");
  11993. * you may not use this file except in compliance with the License.
  11994. * You may obtain a copy of the License at
  11995. *
  11996. * http://www.apache.org/licenses/LICENSE-2.0
  11997. *
  11998. * Unless required by applicable law or agreed to in writing, software
  11999. * distributed under the License is distributed on an "AS IS" BASIS,
  12000. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12001. * See the License for the specific language governing permissions and
  12002. * limitations under the License.
  12003. */
  12004. function decodePath(pathString) {
  12005. var pathStringDecoded = '';
  12006. var pieces = pathString.split('/');
  12007. for (var i = 0; i < pieces.length; i++) {
  12008. if (pieces[i].length > 0) {
  12009. var piece = pieces[i];
  12010. try {
  12011. piece = decodeURIComponent(piece.replace(/\+/g, ' '));
  12012. }
  12013. catch (e) { }
  12014. pathStringDecoded += '/' + piece;
  12015. }
  12016. }
  12017. return pathStringDecoded;
  12018. }
  12019. /**
  12020. * @returns key value hash
  12021. */
  12022. function decodeQuery(queryString) {
  12023. var e_1, _a;
  12024. var results = {};
  12025. if (queryString.charAt(0) === '?') {
  12026. queryString = queryString.substring(1);
  12027. }
  12028. try {
  12029. for (var _b = tslib.__values(queryString.split('&')), _c = _b.next(); !_c.done; _c = _b.next()) {
  12030. var segment = _c.value;
  12031. if (segment.length === 0) {
  12032. continue;
  12033. }
  12034. var kv = segment.split('=');
  12035. if (kv.length === 2) {
  12036. results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
  12037. }
  12038. else {
  12039. warn("Invalid query segment '".concat(segment, "' in query '").concat(queryString, "'"));
  12040. }
  12041. }
  12042. }
  12043. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  12044. finally {
  12045. try {
  12046. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  12047. }
  12048. finally { if (e_1) throw e_1.error; }
  12049. }
  12050. return results;
  12051. }
  12052. var parseRepoInfo = function (dataURL, nodeAdmin) {
  12053. var parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
  12054. if (parsedUrl.domain === 'firebase.com') {
  12055. fatal(parsedUrl.host +
  12056. ' is no longer supported. ' +
  12057. 'Please use <YOUR FIREBASE>.firebaseio.com instead');
  12058. }
  12059. // Catch common error of uninitialized namespace value.
  12060. if ((!namespace || namespace === 'undefined') &&
  12061. parsedUrl.domain !== 'localhost') {
  12062. fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
  12063. }
  12064. if (!parsedUrl.secure) {
  12065. warnIfPageIsSecure();
  12066. }
  12067. var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
  12068. return {
  12069. repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
  12070. /*persistenceKey=*/ '',
  12071. /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),
  12072. path: new Path(parsedUrl.pathString)
  12073. };
  12074. };
  12075. var parseDatabaseURL = function (dataURL) {
  12076. // Default to empty strings in the event of a malformed string.
  12077. var host = '', domain = '', subdomain = '', pathString = '', namespace = '';
  12078. // Always default to SSL, unless otherwise specified.
  12079. var secure = true, scheme = 'https', port = 443;
  12080. // Don't do any validation here. The caller is responsible for validating the result of parsing.
  12081. if (typeof dataURL === 'string') {
  12082. // Parse scheme.
  12083. var colonInd = dataURL.indexOf('//');
  12084. if (colonInd >= 0) {
  12085. scheme = dataURL.substring(0, colonInd - 1);
  12086. dataURL = dataURL.substring(colonInd + 2);
  12087. }
  12088. // Parse host, path, and query string.
  12089. var slashInd = dataURL.indexOf('/');
  12090. if (slashInd === -1) {
  12091. slashInd = dataURL.length;
  12092. }
  12093. var questionMarkInd = dataURL.indexOf('?');
  12094. if (questionMarkInd === -1) {
  12095. questionMarkInd = dataURL.length;
  12096. }
  12097. host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
  12098. if (slashInd < questionMarkInd) {
  12099. // For pathString, questionMarkInd will always come after slashInd
  12100. pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
  12101. }
  12102. var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
  12103. // If we have a port, use scheme for determining if it's secure.
  12104. colonInd = host.indexOf(':');
  12105. if (colonInd >= 0) {
  12106. secure = scheme === 'https' || scheme === 'wss';
  12107. port = parseInt(host.substring(colonInd + 1), 10);
  12108. }
  12109. else {
  12110. colonInd = host.length;
  12111. }
  12112. var hostWithoutPort = host.slice(0, colonInd);
  12113. if (hostWithoutPort.toLowerCase() === 'localhost') {
  12114. domain = 'localhost';
  12115. }
  12116. else if (hostWithoutPort.split('.').length <= 2) {
  12117. domain = hostWithoutPort;
  12118. }
  12119. else {
  12120. // Interpret the subdomain of a 3 or more component URL as the namespace name.
  12121. var dotInd = host.indexOf('.');
  12122. subdomain = host.substring(0, dotInd).toLowerCase();
  12123. domain = host.substring(dotInd + 1);
  12124. // Normalize namespaces to lowercase to share storage / connection.
  12125. namespace = subdomain;
  12126. }
  12127. // Always treat the value of the `ns` as the namespace name if it is present.
  12128. if ('ns' in queryParams) {
  12129. namespace = queryParams['ns'];
  12130. }
  12131. }
  12132. return {
  12133. host: host,
  12134. port: port,
  12135. domain: domain,
  12136. subdomain: subdomain,
  12137. secure: secure,
  12138. scheme: scheme,
  12139. pathString: pathString,
  12140. namespace: namespace
  12141. };
  12142. };
  12143. /**
  12144. * @license
  12145. * Copyright 2017 Google LLC
  12146. *
  12147. * Licensed under the Apache License, Version 2.0 (the "License");
  12148. * you may not use this file except in compliance with the License.
  12149. * You may obtain a copy of the License at
  12150. *
  12151. * http://www.apache.org/licenses/LICENSE-2.0
  12152. *
  12153. * Unless required by applicable law or agreed to in writing, software
  12154. * distributed under the License is distributed on an "AS IS" BASIS,
  12155. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12156. * See the License for the specific language governing permissions and
  12157. * limitations under the License.
  12158. */
  12159. // Modeled after base64 web-safe chars, but ordered by ASCII.
  12160. var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
  12161. /**
  12162. * Fancy ID generator that creates 20-character string identifiers with the
  12163. * following properties:
  12164. *
  12165. * 1. They're based on timestamp so that they sort *after* any existing ids.
  12166. * 2. They contain 72-bits of random data after the timestamp so that IDs won't
  12167. * collide with other clients' IDs.
  12168. * 3. They sort *lexicographically* (so the timestamp is converted to characters
  12169. * that will sort properly).
  12170. * 4. They're monotonically increasing. Even if you generate more than one in
  12171. * the same timestamp, the latter ones will sort after the former ones. We do
  12172. * this by using the previous random bits but "incrementing" them by 1 (only
  12173. * in the case of a timestamp collision).
  12174. */
  12175. var nextPushId = (function () {
  12176. // Timestamp of last push, used to prevent local collisions if you push twice
  12177. // in one ms.
  12178. var lastPushTime = 0;
  12179. // We generate 72-bits of randomness which get turned into 12 characters and
  12180. // appended to the timestamp to prevent collisions with other clients. We
  12181. // store the last characters we generated because in the event of a collision,
  12182. // we'll use those same characters except "incremented" by one.
  12183. var lastRandChars = [];
  12184. return function (now) {
  12185. var duplicateTime = now === lastPushTime;
  12186. lastPushTime = now;
  12187. var i;
  12188. var timeStampChars = new Array(8);
  12189. for (i = 7; i >= 0; i--) {
  12190. timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
  12191. // NOTE: Can't use << here because javascript will convert to int and lose
  12192. // the upper bits.
  12193. now = Math.floor(now / 64);
  12194. }
  12195. util.assert(now === 0, 'Cannot push at time == 0');
  12196. var id = timeStampChars.join('');
  12197. if (!duplicateTime) {
  12198. for (i = 0; i < 12; i++) {
  12199. lastRandChars[i] = Math.floor(Math.random() * 64);
  12200. }
  12201. }
  12202. else {
  12203. // If the timestamp hasn't changed since last push, use the same random
  12204. // number, except incremented by 1.
  12205. for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
  12206. lastRandChars[i] = 0;
  12207. }
  12208. lastRandChars[i]++;
  12209. }
  12210. for (i = 0; i < 12; i++) {
  12211. id += PUSH_CHARS.charAt(lastRandChars[i]);
  12212. }
  12213. util.assert(id.length === 20, 'nextPushId: Length should be 20.');
  12214. return id;
  12215. };
  12216. })();
  12217. /**
  12218. * @license
  12219. * Copyright 2017 Google LLC
  12220. *
  12221. * Licensed under the Apache License, Version 2.0 (the "License");
  12222. * you may not use this file except in compliance with the License.
  12223. * You may obtain a copy of the License at
  12224. *
  12225. * http://www.apache.org/licenses/LICENSE-2.0
  12226. *
  12227. * Unless required by applicable law or agreed to in writing, software
  12228. * distributed under the License is distributed on an "AS IS" BASIS,
  12229. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12230. * See the License for the specific language governing permissions and
  12231. * limitations under the License.
  12232. */
  12233. /**
  12234. * Encapsulates the data needed to raise an event
  12235. */
  12236. var DataEvent = /** @class */ (function () {
  12237. /**
  12238. * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
  12239. * @param eventRegistration - The function to call to with the event data. User provided
  12240. * @param snapshot - The data backing the event
  12241. * @param prevName - Optional, the name of the previous child for child_* events.
  12242. */
  12243. function DataEvent(eventType, eventRegistration, snapshot, prevName) {
  12244. this.eventType = eventType;
  12245. this.eventRegistration = eventRegistration;
  12246. this.snapshot = snapshot;
  12247. this.prevName = prevName;
  12248. }
  12249. DataEvent.prototype.getPath = function () {
  12250. var ref = this.snapshot.ref;
  12251. if (this.eventType === 'value') {
  12252. return ref._path;
  12253. }
  12254. else {
  12255. return ref.parent._path;
  12256. }
  12257. };
  12258. DataEvent.prototype.getEventType = function () {
  12259. return this.eventType;
  12260. };
  12261. DataEvent.prototype.getEventRunner = function () {
  12262. return this.eventRegistration.getEventRunner(this);
  12263. };
  12264. DataEvent.prototype.toString = function () {
  12265. return (this.getPath().toString() +
  12266. ':' +
  12267. this.eventType +
  12268. ':' +
  12269. util.stringify(this.snapshot.exportVal()));
  12270. };
  12271. return DataEvent;
  12272. }());
  12273. var CancelEvent = /** @class */ (function () {
  12274. function CancelEvent(eventRegistration, error, path) {
  12275. this.eventRegistration = eventRegistration;
  12276. this.error = error;
  12277. this.path = path;
  12278. }
  12279. CancelEvent.prototype.getPath = function () {
  12280. return this.path;
  12281. };
  12282. CancelEvent.prototype.getEventType = function () {
  12283. return 'cancel';
  12284. };
  12285. CancelEvent.prototype.getEventRunner = function () {
  12286. return this.eventRegistration.getEventRunner(this);
  12287. };
  12288. CancelEvent.prototype.toString = function () {
  12289. return this.path.toString() + ':cancel';
  12290. };
  12291. return CancelEvent;
  12292. }());
  12293. /**
  12294. * @license
  12295. * Copyright 2017 Google LLC
  12296. *
  12297. * Licensed under the Apache License, Version 2.0 (the "License");
  12298. * you may not use this file except in compliance with the License.
  12299. * You may obtain a copy of the License at
  12300. *
  12301. * http://www.apache.org/licenses/LICENSE-2.0
  12302. *
  12303. * Unless required by applicable law or agreed to in writing, software
  12304. * distributed under the License is distributed on an "AS IS" BASIS,
  12305. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12306. * See the License for the specific language governing permissions and
  12307. * limitations under the License.
  12308. */
  12309. /**
  12310. * A wrapper class that converts events from the database@exp SDK to the legacy
  12311. * Database SDK. Events are not converted directly as event registration relies
  12312. * on reference comparison of the original user callback (see `matches()`) and
  12313. * relies on equality of the legacy SDK's `context` object.
  12314. */
  12315. var CallbackContext = /** @class */ (function () {
  12316. function CallbackContext(snapshotCallback, cancelCallback) {
  12317. this.snapshotCallback = snapshotCallback;
  12318. this.cancelCallback = cancelCallback;
  12319. }
  12320. CallbackContext.prototype.onValue = function (expDataSnapshot, previousChildName) {
  12321. this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
  12322. };
  12323. CallbackContext.prototype.onCancel = function (error) {
  12324. util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
  12325. return this.cancelCallback.call(null, error);
  12326. };
  12327. Object.defineProperty(CallbackContext.prototype, "hasCancelCallback", {
  12328. get: function () {
  12329. return !!this.cancelCallback;
  12330. },
  12331. enumerable: false,
  12332. configurable: true
  12333. });
  12334. CallbackContext.prototype.matches = function (other) {
  12335. return (this.snapshotCallback === other.snapshotCallback ||
  12336. (this.snapshotCallback.userCallback !== undefined &&
  12337. this.snapshotCallback.userCallback ===
  12338. other.snapshotCallback.userCallback &&
  12339. this.snapshotCallback.context === other.snapshotCallback.context));
  12340. };
  12341. return CallbackContext;
  12342. }());
  12343. /**
  12344. * @license
  12345. * Copyright 2021 Google LLC
  12346. *
  12347. * Licensed under the Apache License, Version 2.0 (the "License");
  12348. * you may not use this file except in compliance with the License.
  12349. * You may obtain a copy of the License at
  12350. *
  12351. * http://www.apache.org/licenses/LICENSE-2.0
  12352. *
  12353. * Unless required by applicable law or agreed to in writing, software
  12354. * distributed under the License is distributed on an "AS IS" BASIS,
  12355. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12356. * See the License for the specific language governing permissions and
  12357. * limitations under the License.
  12358. */
  12359. /**
  12360. * The `onDisconnect` class allows you to write or clear data when your client
  12361. * disconnects from the Database server. These updates occur whether your
  12362. * client disconnects cleanly or not, so you can rely on them to clean up data
  12363. * even if a connection is dropped or a client crashes.
  12364. *
  12365. * The `onDisconnect` class is most commonly used to manage presence in
  12366. * applications where it is useful to detect how many clients are connected and
  12367. * when other clients disconnect. See
  12368. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12369. * for more information.
  12370. *
  12371. * To avoid problems when a connection is dropped before the requests can be
  12372. * transferred to the Database server, these functions should be called before
  12373. * writing any data.
  12374. *
  12375. * Note that `onDisconnect` operations are only triggered once. If you want an
  12376. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12377. * the `onDisconnect` operations each time you reconnect.
  12378. */
  12379. var OnDisconnect = /** @class */ (function () {
  12380. /** @hideconstructor */
  12381. function OnDisconnect(_repo, _path) {
  12382. this._repo = _repo;
  12383. this._path = _path;
  12384. }
  12385. /**
  12386. * Cancels all previously queued `onDisconnect()` set or update events for this
  12387. * location and all children.
  12388. *
  12389. * If a write has been queued for this location via a `set()` or `update()` at a
  12390. * parent location, the write at this location will be canceled, though writes
  12391. * to sibling locations will still occur.
  12392. *
  12393. * @returns Resolves when synchronization to the server is complete.
  12394. */
  12395. OnDisconnect.prototype.cancel = function () {
  12396. var deferred = new util.Deferred();
  12397. repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(function () { }));
  12398. return deferred.promise;
  12399. };
  12400. /**
  12401. * Ensures the data at this location is deleted when the client is disconnected
  12402. * (due to closing the browser, navigating to a new page, or network issues).
  12403. *
  12404. * @returns Resolves when synchronization to the server is complete.
  12405. */
  12406. OnDisconnect.prototype.remove = function () {
  12407. validateWritablePath('OnDisconnect.remove', this._path);
  12408. var deferred = new util.Deferred();
  12409. repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(function () { }));
  12410. return deferred.promise;
  12411. };
  12412. /**
  12413. * Ensures the data at this location is set to the specified value when the
  12414. * client is disconnected (due to closing the browser, navigating to a new page,
  12415. * or network issues).
  12416. *
  12417. * `set()` is especially useful for implementing "presence" systems, where a
  12418. * value should be changed or cleared when a user disconnects so that they
  12419. * appear "offline" to other users. See
  12420. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12421. * for more information.
  12422. *
  12423. * Note that `onDisconnect` operations are only triggered once. If you want an
  12424. * operation to occur each time a disconnect occurs, you'll need to re-establish
  12425. * the `onDisconnect` operations each time.
  12426. *
  12427. * @param value - The value to be written to this location on disconnect (can
  12428. * be an object, array, string, number, boolean, or null).
  12429. * @returns Resolves when synchronization to the Database is complete.
  12430. */
  12431. OnDisconnect.prototype.set = function (value) {
  12432. validateWritablePath('OnDisconnect.set', this._path);
  12433. validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
  12434. var deferred = new util.Deferred();
  12435. repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(function () { }));
  12436. return deferred.promise;
  12437. };
  12438. /**
  12439. * Ensures the data at this location is set to the specified value and priority
  12440. * when the client is disconnected (due to closing the browser, navigating to a
  12441. * new page, or network issues).
  12442. *
  12443. * @param value - The value to be written to this location on disconnect (can
  12444. * be an object, array, string, number, boolean, or null).
  12445. * @param priority - The priority to be written (string, number, or null).
  12446. * @returns Resolves when synchronization to the Database is complete.
  12447. */
  12448. OnDisconnect.prototype.setWithPriority = function (value, priority) {
  12449. validateWritablePath('OnDisconnect.setWithPriority', this._path);
  12450. validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
  12451. validatePriority('OnDisconnect.setWithPriority', priority, false);
  12452. var deferred = new util.Deferred();
  12453. repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(function () { }));
  12454. return deferred.promise;
  12455. };
  12456. /**
  12457. * Writes multiple values at this location when the client is disconnected (due
  12458. * to closing the browser, navigating to a new page, or network issues).
  12459. *
  12460. * The `values` argument contains multiple property-value pairs that will be
  12461. * written to the Database together. Each child property can either be a simple
  12462. * property (for example, "name") or a relative path (for example, "name/first")
  12463. * from the current location to the data to update.
  12464. *
  12465. * As opposed to the `set()` method, `update()` can be use to selectively update
  12466. * only the referenced properties at the current location (instead of replacing
  12467. * all the child properties at the current location).
  12468. *
  12469. * @param values - Object containing multiple values.
  12470. * @returns Resolves when synchronization to the Database is complete.
  12471. */
  12472. OnDisconnect.prototype.update = function (values) {
  12473. validateWritablePath('OnDisconnect.update', this._path);
  12474. validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
  12475. var deferred = new util.Deferred();
  12476. repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(function () { }));
  12477. return deferred.promise;
  12478. };
  12479. return OnDisconnect;
  12480. }());
  12481. /**
  12482. * @license
  12483. * Copyright 2020 Google LLC
  12484. *
  12485. * Licensed under the Apache License, Version 2.0 (the "License");
  12486. * you may not use this file except in compliance with the License.
  12487. * You may obtain a copy of the License at
  12488. *
  12489. * http://www.apache.org/licenses/LICENSE-2.0
  12490. *
  12491. * Unless required by applicable law or agreed to in writing, software
  12492. * distributed under the License is distributed on an "AS IS" BASIS,
  12493. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12494. * See the License for the specific language governing permissions and
  12495. * limitations under the License.
  12496. */
  12497. /**
  12498. * @internal
  12499. */
  12500. var QueryImpl = /** @class */ (function () {
  12501. /**
  12502. * @hideconstructor
  12503. */
  12504. function QueryImpl(_repo, _path, _queryParams, _orderByCalled) {
  12505. this._repo = _repo;
  12506. this._path = _path;
  12507. this._queryParams = _queryParams;
  12508. this._orderByCalled = _orderByCalled;
  12509. }
  12510. Object.defineProperty(QueryImpl.prototype, "key", {
  12511. get: function () {
  12512. if (pathIsEmpty(this._path)) {
  12513. return null;
  12514. }
  12515. else {
  12516. return pathGetBack(this._path);
  12517. }
  12518. },
  12519. enumerable: false,
  12520. configurable: true
  12521. });
  12522. Object.defineProperty(QueryImpl.prototype, "ref", {
  12523. get: function () {
  12524. return new ReferenceImpl(this._repo, this._path);
  12525. },
  12526. enumerable: false,
  12527. configurable: true
  12528. });
  12529. Object.defineProperty(QueryImpl.prototype, "_queryIdentifier", {
  12530. get: function () {
  12531. var obj = queryParamsGetQueryObject(this._queryParams);
  12532. var id = ObjectToUniqueKey(obj);
  12533. return id === '{}' ? 'default' : id;
  12534. },
  12535. enumerable: false,
  12536. configurable: true
  12537. });
  12538. Object.defineProperty(QueryImpl.prototype, "_queryObject", {
  12539. /**
  12540. * An object representation of the query parameters used by this Query.
  12541. */
  12542. get: function () {
  12543. return queryParamsGetQueryObject(this._queryParams);
  12544. },
  12545. enumerable: false,
  12546. configurable: true
  12547. });
  12548. QueryImpl.prototype.isEqual = function (other) {
  12549. other = util.getModularInstance(other);
  12550. if (!(other instanceof QueryImpl)) {
  12551. return false;
  12552. }
  12553. var sameRepo = this._repo === other._repo;
  12554. var samePath = pathEquals(this._path, other._path);
  12555. var sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
  12556. return sameRepo && samePath && sameQueryIdentifier;
  12557. };
  12558. QueryImpl.prototype.toJSON = function () {
  12559. return this.toString();
  12560. };
  12561. QueryImpl.prototype.toString = function () {
  12562. return this._repo.toString() + pathToUrlEncodedString(this._path);
  12563. };
  12564. return QueryImpl;
  12565. }());
  12566. /**
  12567. * Validates that no other order by call has been made
  12568. */
  12569. function validateNoPreviousOrderByCall(query, fnName) {
  12570. if (query._orderByCalled === true) {
  12571. throw new Error(fnName + ": You can't combine multiple orderBy calls.");
  12572. }
  12573. }
  12574. /**
  12575. * Validates start/end values for queries.
  12576. */
  12577. function validateQueryEndpoints(params) {
  12578. var startNode = null;
  12579. var endNode = null;
  12580. if (params.hasStart()) {
  12581. startNode = params.getIndexStartValue();
  12582. }
  12583. if (params.hasEnd()) {
  12584. endNode = params.getIndexEndValue();
  12585. }
  12586. if (params.getIndex() === KEY_INDEX) {
  12587. var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
  12588. 'startAt(), endAt(), or equalTo().';
  12589. var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
  12590. 'endAt(), endBefore(), or equalTo() must be a string.';
  12591. if (params.hasStart()) {
  12592. var startName = params.getIndexStartName();
  12593. if (startName !== MIN_NAME) {
  12594. throw new Error(tooManyArgsError);
  12595. }
  12596. else if (typeof startNode !== 'string') {
  12597. throw new Error(wrongArgTypeError);
  12598. }
  12599. }
  12600. if (params.hasEnd()) {
  12601. var endName = params.getIndexEndName();
  12602. if (endName !== MAX_NAME) {
  12603. throw new Error(tooManyArgsError);
  12604. }
  12605. else if (typeof endNode !== 'string') {
  12606. throw new Error(wrongArgTypeError);
  12607. }
  12608. }
  12609. }
  12610. else if (params.getIndex() === PRIORITY_INDEX) {
  12611. if ((startNode != null && !isValidPriority(startNode)) ||
  12612. (endNode != null && !isValidPriority(endNode))) {
  12613. throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
  12614. 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
  12615. '(null, a number, or a string).');
  12616. }
  12617. }
  12618. else {
  12619. util.assert(params.getIndex() instanceof PathIndex ||
  12620. params.getIndex() === VALUE_INDEX, 'unknown index type.');
  12621. if ((startNode != null && typeof startNode === 'object') ||
  12622. (endNode != null && typeof endNode === 'object')) {
  12623. throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
  12624. 'equalTo() cannot be an object.');
  12625. }
  12626. }
  12627. }
  12628. /**
  12629. * Validates that limit* has been called with the correct combination of parameters
  12630. */
  12631. function validateLimit(params) {
  12632. if (params.hasStart() &&
  12633. params.hasEnd() &&
  12634. params.hasLimit() &&
  12635. !params.hasAnchoredLimit()) {
  12636. throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
  12637. 'limitToFirst() or limitToLast() instead.');
  12638. }
  12639. }
  12640. /**
  12641. * @internal
  12642. */
  12643. var ReferenceImpl = /** @class */ (function (_super) {
  12644. tslib.__extends(ReferenceImpl, _super);
  12645. /** @hideconstructor */
  12646. function ReferenceImpl(repo, path) {
  12647. return _super.call(this, repo, path, new QueryParams(), false) || this;
  12648. }
  12649. Object.defineProperty(ReferenceImpl.prototype, "parent", {
  12650. get: function () {
  12651. var parentPath = pathParent(this._path);
  12652. return parentPath === null
  12653. ? null
  12654. : new ReferenceImpl(this._repo, parentPath);
  12655. },
  12656. enumerable: false,
  12657. configurable: true
  12658. });
  12659. Object.defineProperty(ReferenceImpl.prototype, "root", {
  12660. get: function () {
  12661. var ref = this;
  12662. while (ref.parent !== null) {
  12663. ref = ref.parent;
  12664. }
  12665. return ref;
  12666. },
  12667. enumerable: false,
  12668. configurable: true
  12669. });
  12670. return ReferenceImpl;
  12671. }(QueryImpl));
  12672. /**
  12673. * A `DataSnapshot` contains data from a Database location.
  12674. *
  12675. * Any time you read data from the Database, you receive the data as a
  12676. * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
  12677. * with `on()` or `once()`. You can extract the contents of the snapshot as a
  12678. * JavaScript object by calling the `val()` method. Alternatively, you can
  12679. * traverse into the snapshot by calling `child()` to return child snapshots
  12680. * (which you could then call `val()` on).
  12681. *
  12682. * A `DataSnapshot` is an efficiently generated, immutable copy of the data at
  12683. * a Database location. It cannot be modified and will never change (to modify
  12684. * data, you always call the `set()` method on a `Reference` directly).
  12685. */
  12686. var DataSnapshot = /** @class */ (function () {
  12687. /**
  12688. * @param _node - A SnapshotNode to wrap.
  12689. * @param ref - The location this snapshot came from.
  12690. * @param _index - The iteration order for this snapshot
  12691. * @hideconstructor
  12692. */
  12693. function DataSnapshot(_node,
  12694. /**
  12695. * The location of this DataSnapshot.
  12696. */
  12697. ref, _index) {
  12698. this._node = _node;
  12699. this.ref = ref;
  12700. this._index = _index;
  12701. }
  12702. Object.defineProperty(DataSnapshot.prototype, "priority", {
  12703. /**
  12704. * Gets the priority value of the data in this `DataSnapshot`.
  12705. *
  12706. * Applications need not use priority but can order collections by
  12707. * ordinary properties (see
  12708. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
  12709. * ).
  12710. */
  12711. get: function () {
  12712. // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)
  12713. return this._node.getPriority().val();
  12714. },
  12715. enumerable: false,
  12716. configurable: true
  12717. });
  12718. Object.defineProperty(DataSnapshot.prototype, "key", {
  12719. /**
  12720. * The key (last part of the path) of the location of this `DataSnapshot`.
  12721. *
  12722. * The last token in a Database location is considered its key. For example,
  12723. * "ada" is the key for the /users/ada/ node. Accessing the key on any
  12724. * `DataSnapshot` will return the key for the location that generated it.
  12725. * However, accessing the key on the root URL of a Database will return
  12726. * `null`.
  12727. */
  12728. get: function () {
  12729. return this.ref.key;
  12730. },
  12731. enumerable: false,
  12732. configurable: true
  12733. });
  12734. Object.defineProperty(DataSnapshot.prototype, "size", {
  12735. /** Returns the number of child properties of this `DataSnapshot`. */
  12736. get: function () {
  12737. return this._node.numChildren();
  12738. },
  12739. enumerable: false,
  12740. configurable: true
  12741. });
  12742. /**
  12743. * Gets another `DataSnapshot` for the location at the specified relative path.
  12744. *
  12745. * Passing a relative path to the `child()` method of a DataSnapshot returns
  12746. * another `DataSnapshot` for the location at the specified relative path. The
  12747. * relative path can either be a simple child name (for example, "ada") or a
  12748. * deeper, slash-separated path (for example, "ada/name/first"). If the child
  12749. * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
  12750. * whose value is `null`) is returned.
  12751. *
  12752. * @param path - A relative path to the location of child data.
  12753. */
  12754. DataSnapshot.prototype.child = function (path) {
  12755. var childPath = new Path(path);
  12756. var childRef = child(this.ref, path);
  12757. return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
  12758. };
  12759. /**
  12760. * Returns true if this `DataSnapshot` contains any data. It is slightly more
  12761. * efficient than using `snapshot.val() !== null`.
  12762. */
  12763. DataSnapshot.prototype.exists = function () {
  12764. return !this._node.isEmpty();
  12765. };
  12766. /**
  12767. * Exports the entire contents of the DataSnapshot as a JavaScript object.
  12768. *
  12769. * The `exportVal()` method is similar to `val()`, except priority information
  12770. * is included (if available), making it suitable for backing up your data.
  12771. *
  12772. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12773. * Array, string, number, boolean, or `null`).
  12774. */
  12775. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12776. DataSnapshot.prototype.exportVal = function () {
  12777. return this._node.val(true);
  12778. };
  12779. /**
  12780. * Enumerates the top-level children in the `DataSnapshot`.
  12781. *
  12782. * Because of the way JavaScript objects work, the ordering of data in the
  12783. * JavaScript object returned by `val()` is not guaranteed to match the
  12784. * ordering on the server nor the ordering of `onChildAdded()` events. That is
  12785. * where `forEach()` comes in handy. It guarantees the children of a
  12786. * `DataSnapshot` will be iterated in their query order.
  12787. *
  12788. * If no explicit `orderBy*()` method is used, results are returned
  12789. * ordered by key (unless priorities are used, in which case, results are
  12790. * returned by priority).
  12791. *
  12792. * @param action - A function that will be called for each child DataSnapshot.
  12793. * The callback can return true to cancel further enumeration.
  12794. * @returns true if enumeration was canceled due to your callback returning
  12795. * true.
  12796. */
  12797. DataSnapshot.prototype.forEach = function (action) {
  12798. var _this = this;
  12799. if (this._node.isLeafNode()) {
  12800. return false;
  12801. }
  12802. var childrenNode = this._node;
  12803. // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...
  12804. return !!childrenNode.forEachChild(this._index, function (key, node) {
  12805. return action(new DataSnapshot(node, child(_this.ref, key), PRIORITY_INDEX));
  12806. });
  12807. };
  12808. /**
  12809. * Returns true if the specified child path has (non-null) data.
  12810. *
  12811. * @param path - A relative path to the location of a potential child.
  12812. * @returns `true` if data exists at the specified child path; else
  12813. * `false`.
  12814. */
  12815. DataSnapshot.prototype.hasChild = function (path) {
  12816. var childPath = new Path(path);
  12817. return !this._node.getChild(childPath).isEmpty();
  12818. };
  12819. /**
  12820. * Returns whether or not the `DataSnapshot` has any non-`null` child
  12821. * properties.
  12822. *
  12823. * You can use `hasChildren()` to determine if a `DataSnapshot` has any
  12824. * children. If it does, you can enumerate them using `forEach()`. If it
  12825. * doesn't, then either this snapshot contains a primitive value (which can be
  12826. * retrieved with `val()`) or it is empty (in which case, `val()` will return
  12827. * `null`).
  12828. *
  12829. * @returns true if this snapshot has any children; else false.
  12830. */
  12831. DataSnapshot.prototype.hasChildren = function () {
  12832. if (this._node.isLeafNode()) {
  12833. return false;
  12834. }
  12835. else {
  12836. return !this._node.isEmpty();
  12837. }
  12838. };
  12839. /**
  12840. * Returns a JSON-serializable representation of this object.
  12841. */
  12842. DataSnapshot.prototype.toJSON = function () {
  12843. return this.exportVal();
  12844. };
  12845. /**
  12846. * Extracts a JavaScript value from a `DataSnapshot`.
  12847. *
  12848. * Depending on the data in a `DataSnapshot`, the `val()` method may return a
  12849. * scalar type (string, number, or boolean), an array, or an object. It may
  12850. * also return null, indicating that the `DataSnapshot` is empty (contains no
  12851. * data).
  12852. *
  12853. * @returns The DataSnapshot's contents as a JavaScript value (Object,
  12854. * Array, string, number, boolean, or `null`).
  12855. */
  12856. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  12857. DataSnapshot.prototype.val = function () {
  12858. return this._node.val();
  12859. };
  12860. return DataSnapshot;
  12861. }());
  12862. /**
  12863. *
  12864. * Returns a `Reference` representing the location in the Database
  12865. * corresponding to the provided path. If no path is provided, the `Reference`
  12866. * will point to the root of the Database.
  12867. *
  12868. * @param db - The database instance to obtain a reference for.
  12869. * @param path - Optional path representing the location the returned
  12870. * `Reference` will point. If not provided, the returned `Reference` will
  12871. * point to the root of the Database.
  12872. * @returns If a path is provided, a `Reference`
  12873. * pointing to the provided path. Otherwise, a `Reference` pointing to the
  12874. * root of the Database.
  12875. */
  12876. function ref(db, path) {
  12877. db = util.getModularInstance(db);
  12878. db._checkNotDeleted('ref');
  12879. return path !== undefined ? child(db._root, path) : db._root;
  12880. }
  12881. /**
  12882. * Returns a `Reference` representing the location in the Database
  12883. * corresponding to the provided Firebase URL.
  12884. *
  12885. * An exception is thrown if the URL is not a valid Firebase Database URL or it
  12886. * has a different domain than the current `Database` instance.
  12887. *
  12888. * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored
  12889. * and are not applied to the returned `Reference`.
  12890. *
  12891. * @param db - The database instance to obtain a reference for.
  12892. * @param url - The Firebase URL at which the returned `Reference` will
  12893. * point.
  12894. * @returns A `Reference` pointing to the provided
  12895. * Firebase URL.
  12896. */
  12897. function refFromURL(db, url) {
  12898. db = util.getModularInstance(db);
  12899. db._checkNotDeleted('refFromURL');
  12900. var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
  12901. validateUrl('refFromURL', parsedURL);
  12902. var repoInfo = parsedURL.repoInfo;
  12903. if (!db._repo.repoInfo_.isCustomHost() &&
  12904. repoInfo.host !== db._repo.repoInfo_.host) {
  12905. fatal('refFromURL' +
  12906. ': Host name does not match the current database: ' +
  12907. '(found ' +
  12908. repoInfo.host +
  12909. ' but expected ' +
  12910. db._repo.repoInfo_.host +
  12911. ')');
  12912. }
  12913. return ref(db, parsedURL.path.toString());
  12914. }
  12915. /**
  12916. * Gets a `Reference` for the location at the specified relative path.
  12917. *
  12918. * The relative path can either be a simple child name (for example, "ada") or
  12919. * a deeper slash-separated path (for example, "ada/name/first").
  12920. *
  12921. * @param parent - The parent location.
  12922. * @param path - A relative path from this location to the desired child
  12923. * location.
  12924. * @returns The specified child location.
  12925. */
  12926. function child(parent, path) {
  12927. parent = util.getModularInstance(parent);
  12928. if (pathGetFront(parent._path) === null) {
  12929. validateRootPathString('child', 'path', path, false);
  12930. }
  12931. else {
  12932. validatePathString('child', 'path', path, false);
  12933. }
  12934. return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  12935. }
  12936. /**
  12937. * Returns an `OnDisconnect` object - see
  12938. * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}
  12939. * for more information on how to use it.
  12940. *
  12941. * @param ref - The reference to add OnDisconnect triggers for.
  12942. */
  12943. function onDisconnect(ref) {
  12944. ref = util.getModularInstance(ref);
  12945. return new OnDisconnect(ref._repo, ref._path);
  12946. }
  12947. /**
  12948. * Generates a new child location using a unique key and returns its
  12949. * `Reference`.
  12950. *
  12951. * This is the most common pattern for adding data to a collection of items.
  12952. *
  12953. * If you provide a value to `push()`, the value is written to the
  12954. * generated location. If you don't pass a value, nothing is written to the
  12955. * database and the child remains empty (but you can use the `Reference`
  12956. * elsewhere).
  12957. *
  12958. * The unique keys generated by `push()` are ordered by the current time, so the
  12959. * resulting list of items is chronologically sorted. The keys are also
  12960. * designed to be unguessable (they contain 72 random bits of entropy).
  12961. *
  12962. * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.
  12963. * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.
  12964. *
  12965. * @param parent - The parent location.
  12966. * @param value - Optional value to be written at the generated location.
  12967. * @returns Combined `Promise` and `Reference`; resolves when write is complete,
  12968. * but can be used immediately as the `Reference` to the child location.
  12969. */
  12970. function push(parent, value) {
  12971. parent = util.getModularInstance(parent);
  12972. validateWritablePath('push', parent._path);
  12973. validateFirebaseDataArg('push', value, parent._path, true);
  12974. var now = repoServerTime(parent._repo);
  12975. var name = nextPushId(now);
  12976. // push() returns a ThennableReference whose promise is fulfilled with a
  12977. // regular Reference. We use child() to create handles to two different
  12978. // references. The first is turned into a ThennableReference below by adding
  12979. // then() and catch() methods and is used as the return value of push(). The
  12980. // second remains a regular Reference and is used as the fulfilled value of
  12981. // the first ThennableReference.
  12982. var thennablePushRef = child(parent, name);
  12983. var pushRef = child(parent, name);
  12984. var promise;
  12985. if (value != null) {
  12986. promise = set(pushRef, value).then(function () { return pushRef; });
  12987. }
  12988. else {
  12989. promise = Promise.resolve(pushRef);
  12990. }
  12991. thennablePushRef.then = promise.then.bind(promise);
  12992. thennablePushRef.catch = promise.then.bind(promise, undefined);
  12993. return thennablePushRef;
  12994. }
  12995. /**
  12996. * Removes the data at this Database location.
  12997. *
  12998. * Any data at child locations will also be deleted.
  12999. *
  13000. * The effect of the remove will be visible immediately and the corresponding
  13001. * event 'value' will be triggered. Synchronization of the remove to the
  13002. * Firebase servers will also be started, and the returned Promise will resolve
  13003. * when complete. If provided, the onComplete callback will be called
  13004. * asynchronously after synchronization has finished.
  13005. *
  13006. * @param ref - The location to remove.
  13007. * @returns Resolves when remove on server is complete.
  13008. */
  13009. function remove(ref) {
  13010. validateWritablePath('remove', ref._path);
  13011. return set(ref, null);
  13012. }
  13013. /**
  13014. * Writes data to this Database location.
  13015. *
  13016. * This will overwrite any data at this location and all child locations.
  13017. *
  13018. * The effect of the write will be visible immediately, and the corresponding
  13019. * events ("value", "child_added", etc.) will be triggered. Synchronization of
  13020. * the data to the Firebase servers will also be started, and the returned
  13021. * Promise will resolve when complete. If provided, the `onComplete` callback
  13022. * will be called asynchronously after synchronization has finished.
  13023. *
  13024. * Passing `null` for the new value is equivalent to calling `remove()`; namely,
  13025. * all data at this location and all child locations will be deleted.
  13026. *
  13027. * `set()` will remove any priority stored at this location, so if priority is
  13028. * meant to be preserved, you need to use `setWithPriority()` instead.
  13029. *
  13030. * Note that modifying data with `set()` will cancel any pending transactions
  13031. * at that location, so extreme care should be taken if mixing `set()` and
  13032. * `transaction()` to modify the same data.
  13033. *
  13034. * A single `set()` will generate a single "value" event at the location where
  13035. * the `set()` was performed.
  13036. *
  13037. * @param ref - The location to write to.
  13038. * @param value - The value to be written (string, number, boolean, object,
  13039. * array, or null).
  13040. * @returns Resolves when write to server is complete.
  13041. */
  13042. function set(ref, value) {
  13043. ref = util.getModularInstance(ref);
  13044. validateWritablePath('set', ref._path);
  13045. validateFirebaseDataArg('set', value, ref._path, false);
  13046. var deferred = new util.Deferred();
  13047. repoSetWithPriority(ref._repo, ref._path, value,
  13048. /*priority=*/ null, deferred.wrapCallback(function () { }));
  13049. return deferred.promise;
  13050. }
  13051. /**
  13052. * Sets a priority for the data at this Database location.
  13053. *
  13054. * Applications need not use priority but can order collections by
  13055. * ordinary properties (see
  13056. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13057. * ).
  13058. *
  13059. * @param ref - The location to write to.
  13060. * @param priority - The priority to be written (string, number, or null).
  13061. * @returns Resolves when write to server is complete.
  13062. */
  13063. function setPriority(ref, priority) {
  13064. ref = util.getModularInstance(ref);
  13065. validateWritablePath('setPriority', ref._path);
  13066. validatePriority('setPriority', priority, false);
  13067. var deferred = new util.Deferred();
  13068. repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(function () { }));
  13069. return deferred.promise;
  13070. }
  13071. /**
  13072. * Writes data the Database location. Like `set()` but also specifies the
  13073. * priority for that data.
  13074. *
  13075. * Applications need not use priority but can order collections by
  13076. * ordinary properties (see
  13077. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}
  13078. * ).
  13079. *
  13080. * @param ref - The location to write to.
  13081. * @param value - The value to be written (string, number, boolean, object,
  13082. * array, or null).
  13083. * @param priority - The priority to be written (string, number, or null).
  13084. * @returns Resolves when write to server is complete.
  13085. */
  13086. function setWithPriority(ref, value, priority) {
  13087. validateWritablePath('setWithPriority', ref._path);
  13088. validateFirebaseDataArg('setWithPriority', value, ref._path, false);
  13089. validatePriority('setWithPriority', priority, false);
  13090. if (ref.key === '.length' || ref.key === '.keys') {
  13091. throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
  13092. }
  13093. var deferred = new util.Deferred();
  13094. repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(function () { }));
  13095. return deferred.promise;
  13096. }
  13097. /**
  13098. * Writes multiple values to the Database at once.
  13099. *
  13100. * The `values` argument contains multiple property-value pairs that will be
  13101. * written to the Database together. Each child property can either be a simple
  13102. * property (for example, "name") or a relative path (for example,
  13103. * "name/first") from the current location to the data to update.
  13104. *
  13105. * As opposed to the `set()` method, `update()` can be use to selectively update
  13106. * only the referenced properties at the current location (instead of replacing
  13107. * all the child properties at the current location).
  13108. *
  13109. * The effect of the write will be visible immediately, and the corresponding
  13110. * events ('value', 'child_added', etc.) will be triggered. Synchronization of
  13111. * the data to the Firebase servers will also be started, and the returned
  13112. * Promise will resolve when complete. If provided, the `onComplete` callback
  13113. * will be called asynchronously after synchronization has finished.
  13114. *
  13115. * A single `update()` will generate a single "value" event at the location
  13116. * where the `update()` was performed, regardless of how many children were
  13117. * modified.
  13118. *
  13119. * Note that modifying data with `update()` will cancel any pending
  13120. * transactions at that location, so extreme care should be taken if mixing
  13121. * `update()` and `transaction()` to modify the same data.
  13122. *
  13123. * Passing `null` to `update()` will remove the data at this location.
  13124. *
  13125. * See
  13126. * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.
  13127. *
  13128. * @param ref - The location to write to.
  13129. * @param values - Object containing multiple values.
  13130. * @returns Resolves when update on server is complete.
  13131. */
  13132. function update(ref, values) {
  13133. validateFirebaseMergeDataArg('update', values, ref._path, false);
  13134. var deferred = new util.Deferred();
  13135. repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(function () { }));
  13136. return deferred.promise;
  13137. }
  13138. /**
  13139. * Gets the most up-to-date result for this query.
  13140. *
  13141. * @param query - The query to run.
  13142. * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
  13143. * available, or rejects if the client is unable to return a value (e.g., if the
  13144. * server is unreachable and there is nothing cached).
  13145. */
  13146. function get(query) {
  13147. query = util.getModularInstance(query);
  13148. var callbackContext = new CallbackContext(function () { });
  13149. var container = new ValueEventRegistration(callbackContext);
  13150. return repoGetValue(query._repo, query, container).then(function (node) {
  13151. return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
  13152. });
  13153. }
  13154. /**
  13155. * Represents registration for 'value' events.
  13156. */
  13157. var ValueEventRegistration = /** @class */ (function () {
  13158. function ValueEventRegistration(callbackContext) {
  13159. this.callbackContext = callbackContext;
  13160. }
  13161. ValueEventRegistration.prototype.respondsTo = function (eventType) {
  13162. return eventType === 'value';
  13163. };
  13164. ValueEventRegistration.prototype.createEvent = function (change, query) {
  13165. var index = query._queryParams.getIndex();
  13166. return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
  13167. };
  13168. ValueEventRegistration.prototype.getEventRunner = function (eventData) {
  13169. var _this = this;
  13170. if (eventData.getEventType() === 'cancel') {
  13171. return function () {
  13172. return _this.callbackContext.onCancel(eventData.error);
  13173. };
  13174. }
  13175. else {
  13176. return function () {
  13177. return _this.callbackContext.onValue(eventData.snapshot, null);
  13178. };
  13179. }
  13180. };
  13181. ValueEventRegistration.prototype.createCancelEvent = function (error, path) {
  13182. if (this.callbackContext.hasCancelCallback) {
  13183. return new CancelEvent(this, error, path);
  13184. }
  13185. else {
  13186. return null;
  13187. }
  13188. };
  13189. ValueEventRegistration.prototype.matches = function (other) {
  13190. if (!(other instanceof ValueEventRegistration)) {
  13191. return false;
  13192. }
  13193. else if (!other.callbackContext || !this.callbackContext) {
  13194. // If no callback specified, we consider it to match any callback.
  13195. return true;
  13196. }
  13197. else {
  13198. return other.callbackContext.matches(this.callbackContext);
  13199. }
  13200. };
  13201. ValueEventRegistration.prototype.hasAnyCallback = function () {
  13202. return this.callbackContext !== null;
  13203. };
  13204. return ValueEventRegistration;
  13205. }());
  13206. /**
  13207. * Represents the registration of a child_x event.
  13208. */
  13209. var ChildEventRegistration = /** @class */ (function () {
  13210. function ChildEventRegistration(eventType, callbackContext) {
  13211. this.eventType = eventType;
  13212. this.callbackContext = callbackContext;
  13213. }
  13214. ChildEventRegistration.prototype.respondsTo = function (eventType) {
  13215. var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
  13216. eventToCheck =
  13217. eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
  13218. return this.eventType === eventToCheck;
  13219. };
  13220. ChildEventRegistration.prototype.createCancelEvent = function (error, path) {
  13221. if (this.callbackContext.hasCancelCallback) {
  13222. return new CancelEvent(this, error, path);
  13223. }
  13224. else {
  13225. return null;
  13226. }
  13227. };
  13228. ChildEventRegistration.prototype.createEvent = function (change, query) {
  13229. util.assert(change.childName != null, 'Child events should have a childName.');
  13230. var childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
  13231. var index = query._queryParams.getIndex();
  13232. return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
  13233. };
  13234. ChildEventRegistration.prototype.getEventRunner = function (eventData) {
  13235. var _this = this;
  13236. if (eventData.getEventType() === 'cancel') {
  13237. return function () {
  13238. return _this.callbackContext.onCancel(eventData.error);
  13239. };
  13240. }
  13241. else {
  13242. return function () {
  13243. return _this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
  13244. };
  13245. }
  13246. };
  13247. ChildEventRegistration.prototype.matches = function (other) {
  13248. if (other instanceof ChildEventRegistration) {
  13249. return (this.eventType === other.eventType &&
  13250. (!this.callbackContext ||
  13251. !other.callbackContext ||
  13252. this.callbackContext.matches(other.callbackContext)));
  13253. }
  13254. return false;
  13255. };
  13256. ChildEventRegistration.prototype.hasAnyCallback = function () {
  13257. return !!this.callbackContext;
  13258. };
  13259. return ChildEventRegistration;
  13260. }());
  13261. function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
  13262. var cancelCallback;
  13263. if (typeof cancelCallbackOrListenOptions === 'object') {
  13264. cancelCallback = undefined;
  13265. options = cancelCallbackOrListenOptions;
  13266. }
  13267. if (typeof cancelCallbackOrListenOptions === 'function') {
  13268. cancelCallback = cancelCallbackOrListenOptions;
  13269. }
  13270. if (options && options.onlyOnce) {
  13271. var userCallback_1 = callback;
  13272. var onceCallback = function (dataSnapshot, previousChildName) {
  13273. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13274. userCallback_1(dataSnapshot, previousChildName);
  13275. };
  13276. onceCallback.userCallback = callback.userCallback;
  13277. onceCallback.context = callback.context;
  13278. callback = onceCallback;
  13279. }
  13280. var callbackContext = new CallbackContext(callback, cancelCallback || undefined);
  13281. var container = eventType === 'value'
  13282. ? new ValueEventRegistration(callbackContext)
  13283. : new ChildEventRegistration(eventType, callbackContext);
  13284. repoAddEventCallbackForQuery(query._repo, query, container);
  13285. return function () { return repoRemoveEventCallbackForQuery(query._repo, query, container); };
  13286. }
  13287. function onValue(query, callback, cancelCallbackOrListenOptions, options) {
  13288. return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
  13289. }
  13290. function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
  13291. return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
  13292. }
  13293. function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
  13294. return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
  13295. }
  13296. function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
  13297. return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
  13298. }
  13299. function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
  13300. return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
  13301. }
  13302. /**
  13303. * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
  13304. * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
  13305. * the respective `on*` callbacks.
  13306. *
  13307. * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
  13308. * will not automatically remove listeners registered on child nodes, `off()`
  13309. * must also be called on any child listeners to remove the callback.
  13310. *
  13311. * If a callback is not specified, all callbacks for the specified eventType
  13312. * will be removed. Similarly, if no eventType is specified, all callbacks
  13313. * for the `Reference` will be removed.
  13314. *
  13315. * Individual listeners can also be removed by invoking their unsubscribe
  13316. * callbacks.
  13317. *
  13318. * @param query - The query that the listener was registered with.
  13319. * @param eventType - One of the following strings: "value", "child_added",
  13320. * "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
  13321. * for the `Reference` will be removed.
  13322. * @param callback - The callback function that was passed to `on()` or
  13323. * `undefined` to remove all callbacks.
  13324. */
  13325. function off(query, eventType, callback) {
  13326. var container = null;
  13327. var expCallback = callback ? new CallbackContext(callback) : null;
  13328. if (eventType === 'value') {
  13329. container = new ValueEventRegistration(expCallback);
  13330. }
  13331. else if (eventType) {
  13332. container = new ChildEventRegistration(eventType, expCallback);
  13333. }
  13334. repoRemoveEventCallbackForQuery(query._repo, query, container);
  13335. }
  13336. /**
  13337. * A `QueryConstraint` is used to narrow the set of documents returned by a
  13338. * Database query. `QueryConstraint`s are created by invoking {@link endAt},
  13339. * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link
  13340. * limitToFirst}, {@link limitToLast}, {@link orderByChild},
  13341. * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,
  13342. * {@link orderByValue} or {@link equalTo} and
  13343. * can then be passed to {@link query} to create a new query instance that
  13344. * also contains this `QueryConstraint`.
  13345. */
  13346. var QueryConstraint = /** @class */ (function () {
  13347. function QueryConstraint() {
  13348. }
  13349. return QueryConstraint;
  13350. }());
  13351. var QueryEndAtConstraint = /** @class */ (function (_super) {
  13352. tslib.__extends(QueryEndAtConstraint, _super);
  13353. function QueryEndAtConstraint(_value, _key) {
  13354. var _this = _super.call(this) || this;
  13355. _this._value = _value;
  13356. _this._key = _key;
  13357. return _this;
  13358. }
  13359. QueryEndAtConstraint.prototype._apply = function (query) {
  13360. validateFirebaseDataArg('endAt', this._value, query._path, true);
  13361. var newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
  13362. validateLimit(newParams);
  13363. validateQueryEndpoints(newParams);
  13364. if (query._queryParams.hasEnd()) {
  13365. throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
  13366. 'endBefore or equalTo).');
  13367. }
  13368. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13369. };
  13370. return QueryEndAtConstraint;
  13371. }(QueryConstraint));
  13372. /**
  13373. * Creates a `QueryConstraint` with the specified ending point.
  13374. *
  13375. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13376. * allows you to choose arbitrary starting and ending points for your queries.
  13377. *
  13378. * The ending point is inclusive, so children with exactly the specified value
  13379. * will be included in the query. The optional key argument can be used to
  13380. * further limit the range of the query. If it is specified, then children that
  13381. * have exactly the specified value must also have a key name less than or equal
  13382. * to the specified key.
  13383. *
  13384. * You can read more about `endAt()` in
  13385. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13386. *
  13387. * @param value - The value to end at. The argument type depends on which
  13388. * `orderBy*()` function was used in this query. Specify a value that matches
  13389. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13390. * value must be a string.
  13391. * @param key - The child key to end at, among the children with the previously
  13392. * specified priority. This argument is only allowed if ordering by child,
  13393. * value, or priority.
  13394. */
  13395. function endAt(value, key) {
  13396. validateKey('endAt', 'key', key, true);
  13397. return new QueryEndAtConstraint(value, key);
  13398. }
  13399. var QueryEndBeforeConstraint = /** @class */ (function (_super) {
  13400. tslib.__extends(QueryEndBeforeConstraint, _super);
  13401. function QueryEndBeforeConstraint(_value, _key) {
  13402. var _this = _super.call(this) || this;
  13403. _this._value = _value;
  13404. _this._key = _key;
  13405. return _this;
  13406. }
  13407. QueryEndBeforeConstraint.prototype._apply = function (query) {
  13408. validateFirebaseDataArg('endBefore', this._value, query._path, false);
  13409. var newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
  13410. validateLimit(newParams);
  13411. validateQueryEndpoints(newParams);
  13412. if (query._queryParams.hasEnd()) {
  13413. throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
  13414. 'endBefore or equalTo).');
  13415. }
  13416. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13417. };
  13418. return QueryEndBeforeConstraint;
  13419. }(QueryConstraint));
  13420. /**
  13421. * Creates a `QueryConstraint` with the specified ending point (exclusive).
  13422. *
  13423. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13424. * allows you to choose arbitrary starting and ending points for your queries.
  13425. *
  13426. * The ending point is exclusive. If only a value is provided, children
  13427. * with a value less than the specified value will be included in the query.
  13428. * If a key is specified, then children must have a value less than or equal
  13429. * to the specified value and a key name less than the specified key.
  13430. *
  13431. * @param value - The value to end before. The argument type depends on which
  13432. * `orderBy*()` function was used in this query. Specify a value that matches
  13433. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13434. * value must be a string.
  13435. * @param key - The child key to end before, among the children with the
  13436. * previously specified priority. This argument is only allowed if ordering by
  13437. * child, value, or priority.
  13438. */
  13439. function endBefore(value, key) {
  13440. validateKey('endBefore', 'key', key, true);
  13441. return new QueryEndBeforeConstraint(value, key);
  13442. }
  13443. var QueryStartAtConstraint = /** @class */ (function (_super) {
  13444. tslib.__extends(QueryStartAtConstraint, _super);
  13445. function QueryStartAtConstraint(_value, _key) {
  13446. var _this = _super.call(this) || this;
  13447. _this._value = _value;
  13448. _this._key = _key;
  13449. return _this;
  13450. }
  13451. QueryStartAtConstraint.prototype._apply = function (query) {
  13452. validateFirebaseDataArg('startAt', this._value, query._path, true);
  13453. var newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
  13454. validateLimit(newParams);
  13455. validateQueryEndpoints(newParams);
  13456. if (query._queryParams.hasStart()) {
  13457. throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
  13458. 'startBefore or equalTo).');
  13459. }
  13460. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13461. };
  13462. return QueryStartAtConstraint;
  13463. }(QueryConstraint));
  13464. /**
  13465. * Creates a `QueryConstraint` with the specified starting point.
  13466. *
  13467. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13468. * allows you to choose arbitrary starting and ending points for your queries.
  13469. *
  13470. * The starting point is inclusive, so children with exactly the specified value
  13471. * will be included in the query. The optional key argument can be used to
  13472. * further limit the range of the query. If it is specified, then children that
  13473. * have exactly the specified value must also have a key name greater than or
  13474. * equal to the specified key.
  13475. *
  13476. * You can read more about `startAt()` in
  13477. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13478. *
  13479. * @param value - The value to start at. The argument type depends on which
  13480. * `orderBy*()` function was used in this query. Specify a value that matches
  13481. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13482. * value must be a string.
  13483. * @param key - The child key to start at. This argument is only allowed if
  13484. * ordering by child, value, or priority.
  13485. */
  13486. function startAt(value, key) {
  13487. if (value === void 0) { value = null; }
  13488. validateKey('startAt', 'key', key, true);
  13489. return new QueryStartAtConstraint(value, key);
  13490. }
  13491. var QueryStartAfterConstraint = /** @class */ (function (_super) {
  13492. tslib.__extends(QueryStartAfterConstraint, _super);
  13493. function QueryStartAfterConstraint(_value, _key) {
  13494. var _this = _super.call(this) || this;
  13495. _this._value = _value;
  13496. _this._key = _key;
  13497. return _this;
  13498. }
  13499. QueryStartAfterConstraint.prototype._apply = function (query) {
  13500. validateFirebaseDataArg('startAfter', this._value, query._path, false);
  13501. var newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
  13502. validateLimit(newParams);
  13503. validateQueryEndpoints(newParams);
  13504. if (query._queryParams.hasStart()) {
  13505. throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
  13506. 'startAfter, or equalTo).');
  13507. }
  13508. return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
  13509. };
  13510. return QueryStartAfterConstraint;
  13511. }(QueryConstraint));
  13512. /**
  13513. * Creates a `QueryConstraint` with the specified starting point (exclusive).
  13514. *
  13515. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13516. * allows you to choose arbitrary starting and ending points for your queries.
  13517. *
  13518. * The starting point is exclusive. If only a value is provided, children
  13519. * with a value greater than the specified value will be included in the query.
  13520. * If a key is specified, then children must have a value greater than or equal
  13521. * to the specified value and a a key name greater than the specified key.
  13522. *
  13523. * @param value - The value to start after. The argument type depends on which
  13524. * `orderBy*()` function was used in this query. Specify a value that matches
  13525. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13526. * value must be a string.
  13527. * @param key - The child key to start after. This argument is only allowed if
  13528. * ordering by child, value, or priority.
  13529. */
  13530. function startAfter(value, key) {
  13531. validateKey('startAfter', 'key', key, true);
  13532. return new QueryStartAfterConstraint(value, key);
  13533. }
  13534. var QueryLimitToFirstConstraint = /** @class */ (function (_super) {
  13535. tslib.__extends(QueryLimitToFirstConstraint, _super);
  13536. function QueryLimitToFirstConstraint(_limit) {
  13537. var _this = _super.call(this) || this;
  13538. _this._limit = _limit;
  13539. return _this;
  13540. }
  13541. QueryLimitToFirstConstraint.prototype._apply = function (query) {
  13542. if (query._queryParams.hasLimit()) {
  13543. throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
  13544. 'or limitToLast).');
  13545. }
  13546. return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
  13547. };
  13548. return QueryLimitToFirstConstraint;
  13549. }(QueryConstraint));
  13550. /**
  13551. * Creates a new `QueryConstraint` that if limited to the first specific number
  13552. * of children.
  13553. *
  13554. * The `limitToFirst()` method is used to set a maximum number of children to be
  13555. * synced for a given callback. If we set a limit of 100, we will initially only
  13556. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13557. * stored in our Database, a `child_added` event will fire for each message.
  13558. * However, if we have over 100 messages, we will only receive a `child_added`
  13559. * event for the first 100 ordered messages. As items change, we will receive
  13560. * `child_removed` events for each item that drops out of the active list so
  13561. * that the total number stays at 100.
  13562. *
  13563. * You can read more about `limitToFirst()` in
  13564. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13565. *
  13566. * @param limit - The maximum number of nodes to include in this query.
  13567. */
  13568. function limitToFirst(limit) {
  13569. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13570. throw new Error('limitToFirst: First argument must be a positive integer.');
  13571. }
  13572. return new QueryLimitToFirstConstraint(limit);
  13573. }
  13574. var QueryLimitToLastConstraint = /** @class */ (function (_super) {
  13575. tslib.__extends(QueryLimitToLastConstraint, _super);
  13576. function QueryLimitToLastConstraint(_limit) {
  13577. var _this = _super.call(this) || this;
  13578. _this._limit = _limit;
  13579. return _this;
  13580. }
  13581. QueryLimitToLastConstraint.prototype._apply = function (query) {
  13582. if (query._queryParams.hasLimit()) {
  13583. throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
  13584. 'or limitToLast).');
  13585. }
  13586. return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
  13587. };
  13588. return QueryLimitToLastConstraint;
  13589. }(QueryConstraint));
  13590. /**
  13591. * Creates a new `QueryConstraint` that is limited to return only the last
  13592. * specified number of children.
  13593. *
  13594. * The `limitToLast()` method is used to set a maximum number of children to be
  13595. * synced for a given callback. If we set a limit of 100, we will initially only
  13596. * receive up to 100 `child_added` events. If we have fewer than 100 messages
  13597. * stored in our Database, a `child_added` event will fire for each message.
  13598. * However, if we have over 100 messages, we will only receive a `child_added`
  13599. * event for the last 100 ordered messages. As items change, we will receive
  13600. * `child_removed` events for each item that drops out of the active list so
  13601. * that the total number stays at 100.
  13602. *
  13603. * You can read more about `limitToLast()` in
  13604. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13605. *
  13606. * @param limit - The maximum number of nodes to include in this query.
  13607. */
  13608. function limitToLast(limit) {
  13609. if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
  13610. throw new Error('limitToLast: First argument must be a positive integer.');
  13611. }
  13612. return new QueryLimitToLastConstraint(limit);
  13613. }
  13614. var QueryOrderByChildConstraint = /** @class */ (function (_super) {
  13615. tslib.__extends(QueryOrderByChildConstraint, _super);
  13616. function QueryOrderByChildConstraint(_path) {
  13617. var _this = _super.call(this) || this;
  13618. _this._path = _path;
  13619. return _this;
  13620. }
  13621. QueryOrderByChildConstraint.prototype._apply = function (query) {
  13622. validateNoPreviousOrderByCall(query, 'orderByChild');
  13623. var parsedPath = new Path(this._path);
  13624. if (pathIsEmpty(parsedPath)) {
  13625. throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
  13626. }
  13627. var index = new PathIndex(parsedPath);
  13628. var newParams = queryParamsOrderBy(query._queryParams, index);
  13629. validateQueryEndpoints(newParams);
  13630. return new QueryImpl(query._repo, query._path, newParams,
  13631. /*orderByCalled=*/ true);
  13632. };
  13633. return QueryOrderByChildConstraint;
  13634. }(QueryConstraint));
  13635. /**
  13636. * Creates a new `QueryConstraint` that orders by the specified child key.
  13637. *
  13638. * Queries can only order by one key at a time. Calling `orderByChild()`
  13639. * multiple times on the same query is an error.
  13640. *
  13641. * Firebase queries allow you to order your data by any child key on the fly.
  13642. * However, if you know in advance what your indexes will be, you can define
  13643. * them via the .indexOn rule in your Security Rules for better performance. See
  13644. * the{@link https://firebase.google.com/docs/database/security/indexing-data}
  13645. * rule for more information.
  13646. *
  13647. * You can read more about `orderByChild()` in
  13648. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13649. *
  13650. * @param path - The path to order by.
  13651. */
  13652. function orderByChild(path) {
  13653. if (path === '$key') {
  13654. throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
  13655. }
  13656. else if (path === '$priority') {
  13657. throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
  13658. }
  13659. else if (path === '$value') {
  13660. throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
  13661. }
  13662. validatePathString('orderByChild', 'path', path, false);
  13663. return new QueryOrderByChildConstraint(path);
  13664. }
  13665. var QueryOrderByKeyConstraint = /** @class */ (function (_super) {
  13666. tslib.__extends(QueryOrderByKeyConstraint, _super);
  13667. function QueryOrderByKeyConstraint() {
  13668. return _super !== null && _super.apply(this, arguments) || this;
  13669. }
  13670. QueryOrderByKeyConstraint.prototype._apply = function (query) {
  13671. validateNoPreviousOrderByCall(query, 'orderByKey');
  13672. var newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
  13673. validateQueryEndpoints(newParams);
  13674. return new QueryImpl(query._repo, query._path, newParams,
  13675. /*orderByCalled=*/ true);
  13676. };
  13677. return QueryOrderByKeyConstraint;
  13678. }(QueryConstraint));
  13679. /**
  13680. * Creates a new `QueryConstraint` that orders by the key.
  13681. *
  13682. * Sorts the results of a query by their (ascending) key values.
  13683. *
  13684. * You can read more about `orderByKey()` in
  13685. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13686. */
  13687. function orderByKey() {
  13688. return new QueryOrderByKeyConstraint();
  13689. }
  13690. var QueryOrderByPriorityConstraint = /** @class */ (function (_super) {
  13691. tslib.__extends(QueryOrderByPriorityConstraint, _super);
  13692. function QueryOrderByPriorityConstraint() {
  13693. return _super !== null && _super.apply(this, arguments) || this;
  13694. }
  13695. QueryOrderByPriorityConstraint.prototype._apply = function (query) {
  13696. validateNoPreviousOrderByCall(query, 'orderByPriority');
  13697. var newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
  13698. validateQueryEndpoints(newParams);
  13699. return new QueryImpl(query._repo, query._path, newParams,
  13700. /*orderByCalled=*/ true);
  13701. };
  13702. return QueryOrderByPriorityConstraint;
  13703. }(QueryConstraint));
  13704. /**
  13705. * Creates a new `QueryConstraint` that orders by priority.
  13706. *
  13707. * Applications need not use priority but can order collections by
  13708. * ordinary properties (see
  13709. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}
  13710. * for alternatives to priority.
  13711. */
  13712. function orderByPriority() {
  13713. return new QueryOrderByPriorityConstraint();
  13714. }
  13715. var QueryOrderByValueConstraint = /** @class */ (function (_super) {
  13716. tslib.__extends(QueryOrderByValueConstraint, _super);
  13717. function QueryOrderByValueConstraint() {
  13718. return _super !== null && _super.apply(this, arguments) || this;
  13719. }
  13720. QueryOrderByValueConstraint.prototype._apply = function (query) {
  13721. validateNoPreviousOrderByCall(query, 'orderByValue');
  13722. var newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
  13723. validateQueryEndpoints(newParams);
  13724. return new QueryImpl(query._repo, query._path, newParams,
  13725. /*orderByCalled=*/ true);
  13726. };
  13727. return QueryOrderByValueConstraint;
  13728. }(QueryConstraint));
  13729. /**
  13730. * Creates a new `QueryConstraint` that orders by value.
  13731. *
  13732. * If the children of a query are all scalar values (string, number, or
  13733. * boolean), you can order the results by their (ascending) values.
  13734. *
  13735. * You can read more about `orderByValue()` in
  13736. * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.
  13737. */
  13738. function orderByValue() {
  13739. return new QueryOrderByValueConstraint();
  13740. }
  13741. var QueryEqualToValueConstraint = /** @class */ (function (_super) {
  13742. tslib.__extends(QueryEqualToValueConstraint, _super);
  13743. function QueryEqualToValueConstraint(_value, _key) {
  13744. var _this = _super.call(this) || this;
  13745. _this._value = _value;
  13746. _this._key = _key;
  13747. return _this;
  13748. }
  13749. QueryEqualToValueConstraint.prototype._apply = function (query) {
  13750. validateFirebaseDataArg('equalTo', this._value, query._path, false);
  13751. if (query._queryParams.hasStart()) {
  13752. throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
  13753. 'equalTo).');
  13754. }
  13755. if (query._queryParams.hasEnd()) {
  13756. throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
  13757. 'equalTo).');
  13758. }
  13759. return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
  13760. };
  13761. return QueryEqualToValueConstraint;
  13762. }(QueryConstraint));
  13763. /**
  13764. * Creates a `QueryConstraint` that includes children that match the specified
  13765. * value.
  13766. *
  13767. * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
  13768. * allows you to choose arbitrary starting and ending points for your queries.
  13769. *
  13770. * The optional key argument can be used to further limit the range of the
  13771. * query. If it is specified, then children that have exactly the specified
  13772. * value must also have exactly the specified key as their key name. This can be
  13773. * used to filter result sets with many matches for the same value.
  13774. *
  13775. * You can read more about `equalTo()` in
  13776. * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
  13777. *
  13778. * @param value - The value to match for. The argument type depends on which
  13779. * `orderBy*()` function was used in this query. Specify a value that matches
  13780. * the `orderBy*()` type. When used in combination with `orderByKey()`, the
  13781. * value must be a string.
  13782. * @param key - The child key to start at, among the children with the
  13783. * previously specified priority. This argument is only allowed if ordering by
  13784. * child, value, or priority.
  13785. */
  13786. function equalTo(value, key) {
  13787. validateKey('equalTo', 'key', key, true);
  13788. return new QueryEqualToValueConstraint(value, key);
  13789. }
  13790. /**
  13791. * Creates a new immutable instance of `Query` that is extended to also include
  13792. * additional query constraints.
  13793. *
  13794. * @param query - The Query instance to use as a base for the new constraints.
  13795. * @param queryConstraints - The list of `QueryConstraint`s to apply.
  13796. * @throws if any of the provided query constraints cannot be combined with the
  13797. * existing or new constraints.
  13798. */
  13799. function query(query) {
  13800. var e_1, _a;
  13801. var queryConstraints = [];
  13802. for (var _i = 1; _i < arguments.length; _i++) {
  13803. queryConstraints[_i - 1] = arguments[_i];
  13804. }
  13805. var queryImpl = util.getModularInstance(query);
  13806. try {
  13807. for (var queryConstraints_1 = tslib.__values(queryConstraints), queryConstraints_1_1 = queryConstraints_1.next(); !queryConstraints_1_1.done; queryConstraints_1_1 = queryConstraints_1.next()) {
  13808. var constraint = queryConstraints_1_1.value;
  13809. queryImpl = constraint._apply(queryImpl);
  13810. }
  13811. }
  13812. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  13813. finally {
  13814. try {
  13815. if (queryConstraints_1_1 && !queryConstraints_1_1.done && (_a = queryConstraints_1.return)) _a.call(queryConstraints_1);
  13816. }
  13817. finally { if (e_1) throw e_1.error; }
  13818. }
  13819. return queryImpl;
  13820. }
  13821. /**
  13822. * Define reference constructor in various modules
  13823. *
  13824. * We are doing this here to avoid several circular
  13825. * dependency issues
  13826. */
  13827. syncPointSetReferenceConstructor(ReferenceImpl);
  13828. syncTreeSetReferenceConstructor(ReferenceImpl);
  13829. /**
  13830. * This variable is also defined in the firebase Node.js Admin SDK. Before
  13831. * modifying this definition, consult the definition in:
  13832. *
  13833. * https://github.com/firebase/firebase-admin-node
  13834. *
  13835. * and make sure the two are consistent.
  13836. */
  13837. var FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
  13838. /**
  13839. * Creates and caches `Repo` instances.
  13840. */
  13841. var repos = {};
  13842. /**
  13843. * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).
  13844. */
  13845. var useRestClient = false;
  13846. /**
  13847. * Update an existing `Repo` in place to point to a new host/port.
  13848. */
  13849. function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
  13850. repo.repoInfo_ = new RepoInfo("".concat(host, ":").concat(port),
  13851. /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams);
  13852. if (tokenProvider) {
  13853. repo.authTokenProvider_ = tokenProvider;
  13854. }
  13855. }
  13856. /**
  13857. * This function should only ever be called to CREATE a new database instance.
  13858. * @internal
  13859. */
  13860. function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
  13861. var dbUrl = url || app.options.databaseURL;
  13862. if (dbUrl === undefined) {
  13863. if (!app.options.projectId) {
  13864. fatal("Can't determine Firebase Database URL. Be sure to include " +
  13865. ' a Project ID when calling firebase.initializeApp().');
  13866. }
  13867. log('Using default host for project ', app.options.projectId);
  13868. dbUrl = "".concat(app.options.projectId, "-default-rtdb.firebaseio.com");
  13869. }
  13870. var parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13871. var repoInfo = parsedUrl.repoInfo;
  13872. var isEmulator;
  13873. var dbEmulatorHost = undefined;
  13874. if (typeof process !== 'undefined' && process.env) {
  13875. dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
  13876. }
  13877. if (dbEmulatorHost) {
  13878. isEmulator = true;
  13879. dbUrl = "http://".concat(dbEmulatorHost, "?ns=").concat(repoInfo.namespace);
  13880. parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
  13881. repoInfo = parsedUrl.repoInfo;
  13882. }
  13883. else {
  13884. isEmulator = !parsedUrl.repoInfo.secure;
  13885. }
  13886. var authTokenProvider = nodeAdmin && isEmulator
  13887. ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
  13888. : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
  13889. validateUrl('Invalid Firebase Database URL', parsedUrl);
  13890. if (!pathIsEmpty(parsedUrl.path)) {
  13891. fatal('Database URL must point to the root of a Firebase Database ' +
  13892. '(not including a child path).');
  13893. }
  13894. var repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
  13895. return new Database(repo, app);
  13896. }
  13897. /**
  13898. * Remove the repo and make sure it is disconnected.
  13899. *
  13900. */
  13901. function repoManagerDeleteRepo(repo, appName) {
  13902. var appRepos = repos[appName];
  13903. // This should never happen...
  13904. if (!appRepos || appRepos[repo.key] !== repo) {
  13905. fatal("Database ".concat(appName, "(").concat(repo.repoInfo_, ") has already been deleted."));
  13906. }
  13907. repoInterrupt(repo);
  13908. delete appRepos[repo.key];
  13909. }
  13910. /**
  13911. * Ensures a repo doesn't already exist and then creates one using the
  13912. * provided app.
  13913. *
  13914. * @param repoInfo - The metadata about the Repo
  13915. * @returns The Repo object for the specified server / repoName.
  13916. */
  13917. function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
  13918. var appRepos = repos[app.name];
  13919. if (!appRepos) {
  13920. appRepos = {};
  13921. repos[app.name] = appRepos;
  13922. }
  13923. var repo = appRepos[repoInfo.toURLString()];
  13924. if (repo) {
  13925. fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
  13926. }
  13927. repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
  13928. appRepos[repoInfo.toURLString()] = repo;
  13929. return repo;
  13930. }
  13931. /**
  13932. * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.
  13933. */
  13934. function repoManagerForceRestClient(forceRestClient) {
  13935. useRestClient = forceRestClient;
  13936. }
  13937. /**
  13938. * Class representing a Firebase Realtime Database.
  13939. */
  13940. var Database = /** @class */ (function () {
  13941. /** @hideconstructor */
  13942. function Database(_repoInternal,
  13943. /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
  13944. app) {
  13945. this._repoInternal = _repoInternal;
  13946. this.app = app;
  13947. /** Represents a `Database` instance. */
  13948. this['type'] = 'database';
  13949. /** Track if the instance has been used (root or repo accessed) */
  13950. this._instanceStarted = false;
  13951. }
  13952. Object.defineProperty(Database.prototype, "_repo", {
  13953. get: function () {
  13954. if (!this._instanceStarted) {
  13955. repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
  13956. this._instanceStarted = true;
  13957. }
  13958. return this._repoInternal;
  13959. },
  13960. enumerable: false,
  13961. configurable: true
  13962. });
  13963. Object.defineProperty(Database.prototype, "_root", {
  13964. get: function () {
  13965. if (!this._rootInternal) {
  13966. this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
  13967. }
  13968. return this._rootInternal;
  13969. },
  13970. enumerable: false,
  13971. configurable: true
  13972. });
  13973. Database.prototype._delete = function () {
  13974. if (this._rootInternal !== null) {
  13975. repoManagerDeleteRepo(this._repo, this.app.name);
  13976. this._repoInternal = null;
  13977. this._rootInternal = null;
  13978. }
  13979. return Promise.resolve();
  13980. };
  13981. Database.prototype._checkNotDeleted = function (apiName) {
  13982. if (this._rootInternal === null) {
  13983. fatal('Cannot call ' + apiName + ' on a deleted database.');
  13984. }
  13985. };
  13986. return Database;
  13987. }());
  13988. function checkTransportInit() {
  13989. if (TransportManager.IS_TRANSPORT_INITIALIZED) {
  13990. warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
  13991. }
  13992. }
  13993. /**
  13994. * Force the use of websockets instead of longPolling.
  13995. */
  13996. function forceWebSockets() {
  13997. checkTransportInit();
  13998. BrowserPollConnection.forceDisallow();
  13999. }
  14000. /**
  14001. * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
  14002. */
  14003. function forceLongPolling() {
  14004. checkTransportInit();
  14005. WebSocketConnection.forceDisallow();
  14006. BrowserPollConnection.forceAllow();
  14007. }
  14008. /**
  14009. * Returns the instance of the Realtime Database SDK that is associated
  14010. * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with
  14011. * with default settings if no instance exists or if the existing instance uses
  14012. * a custom database URL.
  14013. *
  14014. * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
  14015. * Database instance is associated with.
  14016. * @param url - The URL of the Realtime Database instance to connect to. If not
  14017. * provided, the SDK connects to the default instance of the Firebase App.
  14018. * @returns The `Database` instance of the provided app.
  14019. */
  14020. function getDatabase(app$1, url) {
  14021. if (app$1 === void 0) { app$1 = app.getApp(); }
  14022. var db = app._getProvider(app$1, 'database').getImmediate({
  14023. identifier: url
  14024. });
  14025. if (!db._instanceStarted) {
  14026. var emulator = util.getDefaultEmulatorHostnameAndPort('database');
  14027. if (emulator) {
  14028. connectDatabaseEmulator.apply(void 0, tslib.__spreadArray([db], tslib.__read(emulator), false));
  14029. }
  14030. }
  14031. return db;
  14032. }
  14033. /**
  14034. * Modify the provided instance to communicate with the Realtime Database
  14035. * emulator.
  14036. *
  14037. * <p>Note: This method must be called before performing any other operation.
  14038. *
  14039. * @param db - The instance to modify.
  14040. * @param host - The emulator host (ex: localhost)
  14041. * @param port - The emulator port (ex: 8080)
  14042. * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
  14043. */
  14044. function connectDatabaseEmulator(db, host, port, options) {
  14045. if (options === void 0) { options = {}; }
  14046. db = util.getModularInstance(db);
  14047. db._checkNotDeleted('useEmulator');
  14048. if (db._instanceStarted) {
  14049. fatal('Cannot call useEmulator() after instance has already been initialized.');
  14050. }
  14051. var repo = db._repoInternal;
  14052. var tokenProvider = undefined;
  14053. if (repo.repoInfo_.nodeAdmin) {
  14054. if (options.mockUserToken) {
  14055. fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
  14056. }
  14057. tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
  14058. }
  14059. else if (options.mockUserToken) {
  14060. var token = typeof options.mockUserToken === 'string'
  14061. ? options.mockUserToken
  14062. : util.createMockUserToken(options.mockUserToken, db.app.options.projectId);
  14063. tokenProvider = new EmulatorTokenProvider(token);
  14064. }
  14065. // Modify the repo to apply emulator settings
  14066. repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  14067. }
  14068. /**
  14069. * Disconnects from the server (all Database operations will be completed
  14070. * offline).
  14071. *
  14072. * The client automatically maintains a persistent connection to the Database
  14073. * server, which will remain active indefinitely and reconnect when
  14074. * disconnected. However, the `goOffline()` and `goOnline()` methods may be used
  14075. * to control the client connection in cases where a persistent connection is
  14076. * undesirable.
  14077. *
  14078. * While offline, the client will no longer receive data updates from the
  14079. * Database. However, all Database operations performed locally will continue to
  14080. * immediately fire events, allowing your application to continue behaving
  14081. * normally. Additionally, each operation performed locally will automatically
  14082. * be queued and retried upon reconnection to the Database server.
  14083. *
  14084. * To reconnect to the Database and begin receiving remote events, see
  14085. * `goOnline()`.
  14086. *
  14087. * @param db - The instance to disconnect.
  14088. */
  14089. function goOffline(db) {
  14090. db = util.getModularInstance(db);
  14091. db._checkNotDeleted('goOffline');
  14092. repoInterrupt(db._repo);
  14093. }
  14094. /**
  14095. * Reconnects to the server and synchronizes the offline Database state
  14096. * with the server state.
  14097. *
  14098. * This method should be used after disabling the active connection with
  14099. * `goOffline()`. Once reconnected, the client will transmit the proper data
  14100. * and fire the appropriate events so that your client "catches up"
  14101. * automatically.
  14102. *
  14103. * @param db - The instance to reconnect.
  14104. */
  14105. function goOnline(db) {
  14106. db = util.getModularInstance(db);
  14107. db._checkNotDeleted('goOnline');
  14108. repoResume(db._repo);
  14109. }
  14110. function enableLogging(logger, persistent) {
  14111. enableLogging$1(logger, persistent);
  14112. }
  14113. /**
  14114. * @license
  14115. * Copyright 2021 Google LLC
  14116. *
  14117. * Licensed under the Apache License, Version 2.0 (the "License");
  14118. * you may not use this file except in compliance with the License.
  14119. * You may obtain a copy of the License at
  14120. *
  14121. * http://www.apache.org/licenses/LICENSE-2.0
  14122. *
  14123. * Unless required by applicable law or agreed to in writing, software
  14124. * distributed under the License is distributed on an "AS IS" BASIS,
  14125. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14126. * See the License for the specific language governing permissions and
  14127. * limitations under the License.
  14128. */
  14129. function registerDatabase(variant) {
  14130. setSDKVersion(app.SDK_VERSION);
  14131. app._registerComponent(new component.Component('database', function (container, _a) {
  14132. var url = _a.instanceIdentifier;
  14133. var app = container.getProvider('app').getImmediate();
  14134. var authProvider = container.getProvider('auth-internal');
  14135. var appCheckProvider = container.getProvider('app-check-internal');
  14136. return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
  14137. }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  14138. app.registerVersion(name, version, variant);
  14139. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  14140. app.registerVersion(name, version, 'cjs5');
  14141. }
  14142. /**
  14143. * @license
  14144. * Copyright 2020 Google LLC
  14145. *
  14146. * Licensed under the Apache License, Version 2.0 (the "License");
  14147. * you may not use this file except in compliance with the License.
  14148. * You may obtain a copy of the License at
  14149. *
  14150. * http://www.apache.org/licenses/LICENSE-2.0
  14151. *
  14152. * Unless required by applicable law or agreed to in writing, software
  14153. * distributed under the License is distributed on an "AS IS" BASIS,
  14154. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14155. * See the License for the specific language governing permissions and
  14156. * limitations under the License.
  14157. */
  14158. var SERVER_TIMESTAMP = {
  14159. '.sv': 'timestamp'
  14160. };
  14161. /**
  14162. * Returns a placeholder value for auto-populating the current timestamp (time
  14163. * since the Unix epoch, in milliseconds) as determined by the Firebase
  14164. * servers.
  14165. */
  14166. function serverTimestamp() {
  14167. return SERVER_TIMESTAMP;
  14168. }
  14169. /**
  14170. * Returns a placeholder value that can be used to atomically increment the
  14171. * current database value by the provided delta.
  14172. *
  14173. * @param delta - the amount to modify the current value atomically.
  14174. * @returns A placeholder value for modifying data atomically server-side.
  14175. */
  14176. function increment(delta) {
  14177. return {
  14178. '.sv': {
  14179. 'increment': delta
  14180. }
  14181. };
  14182. }
  14183. /**
  14184. * @license
  14185. * Copyright 2020 Google LLC
  14186. *
  14187. * Licensed under the Apache License, Version 2.0 (the "License");
  14188. * you may not use this file except in compliance with the License.
  14189. * You may obtain a copy of the License at
  14190. *
  14191. * http://www.apache.org/licenses/LICENSE-2.0
  14192. *
  14193. * Unless required by applicable law or agreed to in writing, software
  14194. * distributed under the License is distributed on an "AS IS" BASIS,
  14195. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14196. * See the License for the specific language governing permissions and
  14197. * limitations under the License.
  14198. */
  14199. /**
  14200. * A type for the resolve value of {@link runTransaction}.
  14201. */
  14202. var TransactionResult = /** @class */ (function () {
  14203. /** @hideconstructor */
  14204. function TransactionResult(
  14205. /** Whether the transaction was successfully committed. */
  14206. committed,
  14207. /** The resulting data snapshot. */
  14208. snapshot) {
  14209. this.committed = committed;
  14210. this.snapshot = snapshot;
  14211. }
  14212. /** Returns a JSON-serializable representation of this object. */
  14213. TransactionResult.prototype.toJSON = function () {
  14214. return { committed: this.committed, snapshot: this.snapshot.toJSON() };
  14215. };
  14216. return TransactionResult;
  14217. }());
  14218. /**
  14219. * Atomically modifies the data at this location.
  14220. *
  14221. * Atomically modify the data at this location. Unlike a normal `set()`, which
  14222. * just overwrites the data regardless of its previous value, `runTransaction()` is
  14223. * used to modify the existing value to a new value, ensuring there are no
  14224. * conflicts with other clients writing to the same location at the same time.
  14225. *
  14226. * To accomplish this, you pass `runTransaction()` an update function which is
  14227. * used to transform the current value into a new value. If another client
  14228. * writes to the location before your new value is successfully written, your
  14229. * update function will be called again with the new current value, and the
  14230. * write will be retried. This will happen repeatedly until your write succeeds
  14231. * without conflict or you abort the transaction by not returning a value from
  14232. * your update function.
  14233. *
  14234. * Note: Modifying data with `set()` will cancel any pending transactions at
  14235. * that location, so extreme care should be taken if mixing `set()` and
  14236. * `runTransaction()` to update the same data.
  14237. *
  14238. * Note: When using transactions with Security and Firebase Rules in place, be
  14239. * aware that a client needs `.read` access in addition to `.write` access in
  14240. * order to perform a transaction. This is because the client-side nature of
  14241. * transactions requires the client to read the data in order to transactionally
  14242. * update it.
  14243. *
  14244. * @param ref - The location to atomically modify.
  14245. * @param transactionUpdate - A developer-supplied function which will be passed
  14246. * the current data stored at this location (as a JavaScript object). The
  14247. * function should return the new value it would like written (as a JavaScript
  14248. * object). If `undefined` is returned (i.e. you return with no arguments) the
  14249. * transaction will be aborted and the data at this location will not be
  14250. * modified.
  14251. * @param options - An options object to configure transactions.
  14252. * @returns A `Promise` that can optionally be used instead of the `onComplete`
  14253. * callback to handle success and failure.
  14254. */
  14255. function runTransaction(ref,
  14256. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14257. transactionUpdate, options) {
  14258. var _a;
  14259. ref = util.getModularInstance(ref);
  14260. validateWritablePath('Reference.transaction', ref._path);
  14261. if (ref.key === '.length' || ref.key === '.keys') {
  14262. throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
  14263. }
  14264. var applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
  14265. var deferred = new util.Deferred();
  14266. var promiseComplete = function (error, committed, node) {
  14267. var dataSnapshot = null;
  14268. if (error) {
  14269. deferred.reject(error);
  14270. }
  14271. else {
  14272. dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
  14273. deferred.resolve(new TransactionResult(committed, dataSnapshot));
  14274. }
  14275. };
  14276. // Add a watch to make sure we get server updates.
  14277. var unwatcher = onValue(ref, function () { });
  14278. repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
  14279. return deferred.promise;
  14280. }
  14281. /**
  14282. * @license
  14283. * Copyright 2017 Google LLC
  14284. *
  14285. * Licensed under the Apache License, Version 2.0 (the "License");
  14286. * you may not use this file except in compliance with the License.
  14287. * You may obtain a copy of the License at
  14288. *
  14289. * http://www.apache.org/licenses/LICENSE-2.0
  14290. *
  14291. * Unless required by applicable law or agreed to in writing, software
  14292. * distributed under the License is distributed on an "AS IS" BASIS,
  14293. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14294. * See the License for the specific language governing permissions and
  14295. * limitations under the License.
  14296. */
  14297. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14298. PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
  14299. this.sendRequest('q', { p: pathString }, onComplete);
  14300. };
  14301. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  14302. PersistentConnection.prototype.echo = function (data, onEcho) {
  14303. this.sendRequest('echo', { d: data }, onEcho);
  14304. };
  14305. /**
  14306. * @internal
  14307. */
  14308. var hijackHash = function (newHash) {
  14309. var oldPut = PersistentConnection.prototype.put;
  14310. PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
  14311. if (hash !== undefined) {
  14312. hash = newHash();
  14313. }
  14314. oldPut.call(this, pathString, data, onComplete, hash);
  14315. };
  14316. return function () {
  14317. PersistentConnection.prototype.put = oldPut;
  14318. };
  14319. };
  14320. /**
  14321. * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.
  14322. * @internal
  14323. */
  14324. var forceRestClient = function (forceRestClient) {
  14325. repoManagerForceRestClient(forceRestClient);
  14326. };
  14327. /**
  14328. * @license
  14329. * Copyright 2021 Google LLC
  14330. *
  14331. * Licensed under the Apache License, Version 2.0 (the "License");
  14332. * you may not use this file except in compliance with the License.
  14333. * You may obtain a copy of the License at
  14334. *
  14335. * http://www.apache.org/licenses/LICENSE-2.0
  14336. *
  14337. * Unless required by applicable law or agreed to in writing, software
  14338. * distributed under the License is distributed on an "AS IS" BASIS,
  14339. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14340. * See the License for the specific language governing permissions and
  14341. * limitations under the License.
  14342. */
  14343. setWebSocketImpl(Websocket__default["default"].Client);
  14344. registerDatabase('node');
  14345. exports.DataSnapshot = DataSnapshot;
  14346. exports.Database = Database;
  14347. exports.OnDisconnect = OnDisconnect;
  14348. exports.QueryConstraint = QueryConstraint;
  14349. exports.TransactionResult = TransactionResult;
  14350. exports._QueryImpl = QueryImpl;
  14351. exports._QueryParams = QueryParams;
  14352. exports._ReferenceImpl = ReferenceImpl;
  14353. exports._TEST_ACCESS_forceRestClient = forceRestClient;
  14354. exports._TEST_ACCESS_hijackHash = hijackHash;
  14355. exports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp;
  14356. exports._setSDKVersion = setSDKVersion;
  14357. exports._validatePathString = validatePathString;
  14358. exports._validateWritablePath = validateWritablePath;
  14359. exports.child = child;
  14360. exports.connectDatabaseEmulator = connectDatabaseEmulator;
  14361. exports.enableLogging = enableLogging;
  14362. exports.endAt = endAt;
  14363. exports.endBefore = endBefore;
  14364. exports.equalTo = equalTo;
  14365. exports.forceLongPolling = forceLongPolling;
  14366. exports.forceWebSockets = forceWebSockets;
  14367. exports.get = get;
  14368. exports.getDatabase = getDatabase;
  14369. exports.goOffline = goOffline;
  14370. exports.goOnline = goOnline;
  14371. exports.increment = increment;
  14372. exports.limitToFirst = limitToFirst;
  14373. exports.limitToLast = limitToLast;
  14374. exports.off = off;
  14375. exports.onChildAdded = onChildAdded;
  14376. exports.onChildChanged = onChildChanged;
  14377. exports.onChildMoved = onChildMoved;
  14378. exports.onChildRemoved = onChildRemoved;
  14379. exports.onDisconnect = onDisconnect;
  14380. exports.onValue = onValue;
  14381. exports.orderByChild = orderByChild;
  14382. exports.orderByKey = orderByKey;
  14383. exports.orderByPriority = orderByPriority;
  14384. exports.orderByValue = orderByValue;
  14385. exports.push = push;
  14386. exports.query = query;
  14387. exports.ref = ref;
  14388. exports.refFromURL = refFromURL;
  14389. exports.remove = remove;
  14390. exports.runTransaction = runTransaction;
  14391. exports.serverTimestamp = serverTimestamp;
  14392. exports.set = set;
  14393. exports.setPriority = setPriority;
  14394. exports.setWithPriority = setWithPriority;
  14395. exports.startAfter = startAfter;
  14396. exports.startAt = startAt;
  14397. exports.update = update;
  14398. //# sourceMappingURL=index.node.cjs.js.map