1 | 'use strict';
|
2 |
|
3 | Object.defineProperty(exports, '__esModule', { value: true });
|
4 |
|
5 | var Websocket = require('faye-websocket');
|
6 | var util = require('@firebase/util');
|
7 | var tslib = require('tslib');
|
8 | var logger$1 = require('@firebase/logger');
|
9 | var app = require('@firebase/app');
|
10 | var component = require('@firebase/component');
|
11 |
|
12 | function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
13 |
|
14 | var Websocket__default = _interopDefaultLegacy(Websocket);
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 | var PROTOCOL_VERSION = '5';
|
33 | var VERSION_PARAM = 'v';
|
34 | var TRANSPORT_SESSION_PARAM = 's';
|
35 | var REFERER_PARAM = 'r';
|
36 | var FORGE_REF = 'f';
|
37 |
|
38 |
|
39 | var FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
|
40 | var LAST_SESSION_PARAM = 'ls';
|
41 | var APPLICATION_ID_PARAM = 'p';
|
42 | var APP_CHECK_TOKEN_PARAM = 'ac';
|
43 | var WEBSOCKET = 'websocket';
|
44 | var LONG_POLLING = 'long_polling';
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | var DOMStorageWrapper = (function () {
|
72 | |
73 |
|
74 |
|
75 | function DOMStorageWrapper(domStorage_) {
|
76 | this.domStorage_ = domStorage_;
|
77 |
|
78 | this.prefix_ = 'firebase:';
|
79 | }
|
80 | |
81 |
|
82 |
|
83 |
|
84 | DOMStorageWrapper.prototype.set = function (key, value) {
|
85 | if (value == null) {
|
86 | this.domStorage_.removeItem(this.prefixedName_(key));
|
87 | }
|
88 | else {
|
89 | this.domStorage_.setItem(this.prefixedName_(key), util.stringify(value));
|
90 | }
|
91 | };
|
92 | |
93 |
|
94 |
|
95 | DOMStorageWrapper.prototype.get = function (key) {
|
96 | var storedVal = this.domStorage_.getItem(this.prefixedName_(key));
|
97 | if (storedVal == null) {
|
98 | return null;
|
99 | }
|
100 | else {
|
101 | return util.jsonEval(storedVal);
|
102 | }
|
103 | };
|
104 | DOMStorageWrapper.prototype.remove = function (key) {
|
105 | this.domStorage_.removeItem(this.prefixedName_(key));
|
106 | };
|
107 | DOMStorageWrapper.prototype.prefixedName_ = function (name) {
|
108 | return this.prefix_ + name;
|
109 | };
|
110 | DOMStorageWrapper.prototype.toString = function () {
|
111 | return this.domStorage_.toString();
|
112 | };
|
113 | return DOMStorageWrapper;
|
114 | }());
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 |
|
125 |
|
126 |
|
127 |
|
128 |
|
129 |
|
130 |
|
131 |
|
132 |
|
133 |
|
134 |
|
135 |
|
136 | var MemoryStorage = (function () {
|
137 | function MemoryStorage() {
|
138 | this.cache_ = {};
|
139 | this.isInMemoryStorage = true;
|
140 | }
|
141 | MemoryStorage.prototype.set = function (key, value) {
|
142 | if (value == null) {
|
143 | delete this.cache_[key];
|
144 | }
|
145 | else {
|
146 | this.cache_[key] = value;
|
147 | }
|
148 | };
|
149 | MemoryStorage.prototype.get = function (key) {
|
150 | if (util.contains(this.cache_, key)) {
|
151 | return this.cache_[key];
|
152 | }
|
153 | return null;
|
154 | };
|
155 | MemoryStorage.prototype.remove = function (key) {
|
156 | delete this.cache_[key];
|
157 | };
|
158 | return MemoryStorage;
|
159 | }());
|
160 |
|
161 |
|
162 |
|
163 |
|
164 |
|
165 |
|
166 |
|
167 |
|
168 |
|
169 |
|
170 |
|
171 |
|
172 |
|
173 |
|
174 |
|
175 |
|
176 |
|
177 |
|
178 |
|
179 |
|
180 |
|
181 |
|
182 |
|
183 |
|
184 |
|
185 |
|
186 | var createStoragefor = function (domStorageName) {
|
187 | try {
|
188 |
|
189 |
|
190 | if (typeof window !== 'undefined' &&
|
191 | typeof window[domStorageName] !== 'undefined') {
|
192 |
|
193 | var domStorage = window[domStorageName];
|
194 | domStorage.setItem('firebase:sentinel', 'cache');
|
195 | domStorage.removeItem('firebase:sentinel');
|
196 | return new DOMStorageWrapper(domStorage);
|
197 | }
|
198 | }
|
199 | catch (e) { }
|
200 |
|
201 |
|
202 | return new MemoryStorage();
|
203 | };
|
204 |
|
205 | var PersistentStorage = createStoragefor('localStorage');
|
206 |
|
207 | var SessionStorage = createStoragefor('sessionStorage');
|
208 |
|
209 |
|
210 |
|
211 |
|
212 |
|
213 |
|
214 |
|
215 |
|
216 |
|
217 |
|
218 |
|
219 |
|
220 |
|
221 |
|
222 |
|
223 |
|
224 |
|
225 | var logClient = new logger$1.Logger('@firebase/database');
|
226 |
|
227 |
|
228 |
|
229 | var LUIDGenerator = (function () {
|
230 | var id = 1;
|
231 | return function () {
|
232 | return id++;
|
233 | };
|
234 | })();
|
235 |
|
236 |
|
237 |
|
238 |
|
239 |
|
240 | var sha1 = function (str) {
|
241 | var utf8Bytes = util.stringToByteArray(str);
|
242 | var sha1 = new util.Sha1();
|
243 | sha1.update(utf8Bytes);
|
244 | var sha1Bytes = sha1.digest();
|
245 | return util.base64.encodeByteArray(sha1Bytes);
|
246 | };
|
247 | var buildLogMessage_ = function () {
|
248 | var varArgs = [];
|
249 | for (var _i = 0; _i < arguments.length; _i++) {
|
250 | varArgs[_i] = arguments[_i];
|
251 | }
|
252 | var message = '';
|
253 | for (var i = 0; i < varArgs.length; i++) {
|
254 | var arg = varArgs[i];
|
255 | if (Array.isArray(arg) ||
|
256 | (arg &&
|
257 | typeof arg === 'object' &&
|
258 |
|
259 | typeof arg.length === 'number')) {
|
260 | message += buildLogMessage_.apply(null, arg);
|
261 | }
|
262 | else if (typeof arg === 'object') {
|
263 | message += util.stringify(arg);
|
264 | }
|
265 | else {
|
266 | message += arg;
|
267 | }
|
268 | message += ' ';
|
269 | }
|
270 | return message;
|
271 | };
|
272 |
|
273 |
|
274 |
|
275 | var logger = null;
|
276 |
|
277 |
|
278 |
|
279 | var firstLog_ = true;
|
280 |
|
281 |
|
282 |
|
283 |
|
284 |
|
285 | var enableLogging$1 = function (logger_, persistent) {
|
286 | util.assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
|
287 | if (logger_ === true) {
|
288 | logClient.logLevel = logger$1.LogLevel.VERBOSE;
|
289 | logger = logClient.log.bind(logClient);
|
290 | if (persistent) {
|
291 | SessionStorage.set('logging_enabled', true);
|
292 | }
|
293 | }
|
294 | else if (typeof logger_ === 'function') {
|
295 | logger = logger_;
|
296 | }
|
297 | else {
|
298 | logger = null;
|
299 | SessionStorage.remove('logging_enabled');
|
300 | }
|
301 | };
|
302 | var log = function () {
|
303 | var varArgs = [];
|
304 | for (var _i = 0; _i < arguments.length; _i++) {
|
305 | varArgs[_i] = arguments[_i];
|
306 | }
|
307 | if (firstLog_ === true) {
|
308 | firstLog_ = false;
|
309 | if (logger === null && SessionStorage.get('logging_enabled') === true) {
|
310 | enableLogging$1(true);
|
311 | }
|
312 | }
|
313 | if (logger) {
|
314 | var message = buildLogMessage_.apply(null, varArgs);
|
315 | logger(message);
|
316 | }
|
317 | };
|
318 | var logWrapper = function (prefix) {
|
319 | return function () {
|
320 | var varArgs = [];
|
321 | for (var _i = 0; _i < arguments.length; _i++) {
|
322 | varArgs[_i] = arguments[_i];
|
323 | }
|
324 | log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
|
325 | };
|
326 | };
|
327 | var error = function () {
|
328 | var varArgs = [];
|
329 | for (var _i = 0; _i < arguments.length; _i++) {
|
330 | varArgs[_i] = arguments[_i];
|
331 | }
|
332 | var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
|
333 | logClient.error(message);
|
334 | };
|
335 | var fatal = function () {
|
336 | var varArgs = [];
|
337 | for (var _i = 0; _i < arguments.length; _i++) {
|
338 | varArgs[_i] = arguments[_i];
|
339 | }
|
340 | var message = "FIREBASE FATAL ERROR: ".concat(buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false)));
|
341 | logClient.error(message);
|
342 | throw new Error(message);
|
343 | };
|
344 | var warn = function () {
|
345 | var varArgs = [];
|
346 | for (var _i = 0; _i < arguments.length; _i++) {
|
347 | varArgs[_i] = arguments[_i];
|
348 | }
|
349 | var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, tslib.__spreadArray([], tslib.__read(varArgs), false));
|
350 | logClient.warn(message);
|
351 | };
|
352 |
|
353 |
|
354 |
|
355 |
|
356 | var warnIfPageIsSecure = function () {
|
357 |
|
358 | if (typeof window !== 'undefined' &&
|
359 | window.location &&
|
360 | window.location.protocol &&
|
361 | window.location.protocol.indexOf('https:') !== -1) {
|
362 | warn('Insecure Firebase access from a secure page. ' +
|
363 | 'Please use https in calls to new Firebase().');
|
364 | }
|
365 | };
|
366 |
|
367 |
|
368 |
|
369 | var isInvalidJSONNumber = function (data) {
|
370 | return (typeof data === 'number' &&
|
371 | (data !== data ||
|
372 | data === Number.POSITIVE_INFINITY ||
|
373 | data === Number.NEGATIVE_INFINITY));
|
374 | };
|
375 | var executeWhenDOMReady = function (fn) {
|
376 | if (util.isNodeSdk() || document.readyState === 'complete') {
|
377 | fn();
|
378 | }
|
379 | else {
|
380 |
|
381 |
|
382 | var called_1 = false;
|
383 | var wrappedFn_1 = function () {
|
384 | if (!document.body) {
|
385 | setTimeout(wrappedFn_1, Math.floor(10));
|
386 | return;
|
387 | }
|
388 | if (!called_1) {
|
389 | called_1 = true;
|
390 | fn();
|
391 | }
|
392 | };
|
393 | if (document.addEventListener) {
|
394 | document.addEventListener('DOMContentLoaded', wrappedFn_1, false);
|
395 |
|
396 | window.addEventListener('load', wrappedFn_1, false);
|
397 |
|
398 | }
|
399 | else if (document.attachEvent) {
|
400 |
|
401 |
|
402 | document.attachEvent('onreadystatechange', function () {
|
403 | if (document.readyState === 'complete') {
|
404 | wrappedFn_1();
|
405 | }
|
406 | });
|
407 |
|
408 |
|
409 | window.attachEvent('onload', wrappedFn_1);
|
410 |
|
411 |
|
412 |
|
413 | }
|
414 | }
|
415 | };
|
416 |
|
417 |
|
418 |
|
419 | var MIN_NAME = '[MIN_NAME]';
|
420 |
|
421 |
|
422 |
|
423 | var MAX_NAME = '[MAX_NAME]';
|
424 |
|
425 |
|
426 |
|
427 | var nameCompare = function (a, b) {
|
428 | if (a === b) {
|
429 | return 0;
|
430 | }
|
431 | else if (a === MIN_NAME || b === MAX_NAME) {
|
432 | return -1;
|
433 | }
|
434 | else if (b === MIN_NAME || a === MAX_NAME) {
|
435 | return 1;
|
436 | }
|
437 | else {
|
438 | var aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);
|
439 | if (aAsInt !== null) {
|
440 | if (bAsInt !== null) {
|
441 | return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;
|
442 | }
|
443 | else {
|
444 | return -1;
|
445 | }
|
446 | }
|
447 | else if (bAsInt !== null) {
|
448 | return 1;
|
449 | }
|
450 | else {
|
451 | return a < b ? -1 : 1;
|
452 | }
|
453 | }
|
454 | };
|
455 |
|
456 |
|
457 |
|
458 | var stringCompare = function (a, b) {
|
459 | if (a === b) {
|
460 | return 0;
|
461 | }
|
462 | else if (a < b) {
|
463 | return -1;
|
464 | }
|
465 | else {
|
466 | return 1;
|
467 | }
|
468 | };
|
469 | var requireKey = function (key, obj) {
|
470 | if (obj && key in obj) {
|
471 | return obj[key];
|
472 | }
|
473 | else {
|
474 | throw new Error('Missing required key (' + key + ') in object: ' + util.stringify(obj));
|
475 | }
|
476 | };
|
477 | var ObjectToUniqueKey = function (obj) {
|
478 | if (typeof obj !== 'object' || obj === null) {
|
479 | return util.stringify(obj);
|
480 | }
|
481 | var keys = [];
|
482 |
|
483 | for (var k in obj) {
|
484 | keys.push(k);
|
485 | }
|
486 |
|
487 | keys.sort();
|
488 | var key = '{';
|
489 | for (var i = 0; i < keys.length; i++) {
|
490 | if (i !== 0) {
|
491 | key += ',';
|
492 | }
|
493 | key += util.stringify(keys[i]);
|
494 | key += ':';
|
495 | key += ObjectToUniqueKey(obj[keys[i]]);
|
496 | }
|
497 | key += '}';
|
498 | return key;
|
499 | };
|
500 |
|
501 |
|
502 |
|
503 |
|
504 |
|
505 |
|
506 | var splitStringBySize = function (str, segsize) {
|
507 | var len = str.length;
|
508 | if (len <= segsize) {
|
509 | return [str];
|
510 | }
|
511 | var dataSegs = [];
|
512 | for (var c = 0; c < len; c += segsize) {
|
513 | if (c + segsize > len) {
|
514 | dataSegs.push(str.substring(c, len));
|
515 | }
|
516 | else {
|
517 | dataSegs.push(str.substring(c, c + segsize));
|
518 | }
|
519 | }
|
520 | return dataSegs;
|
521 | };
|
522 |
|
523 |
|
524 |
|
525 |
|
526 |
|
527 |
|
528 | function each(obj, fn) {
|
529 | for (var key in obj) {
|
530 | if (obj.hasOwnProperty(key)) {
|
531 | fn(key, obj[key]);
|
532 | }
|
533 | }
|
534 | }
|
535 |
|
536 |
|
537 |
|
538 |
|
539 |
|
540 |
|
541 |
|
542 | var doubleToIEEE754String = function (v) {
|
543 | util.assert(!isInvalidJSONNumber(v), 'Invalid JSON number');
|
544 | var ebits = 11, fbits = 52;
|
545 | var bias = (1 << (ebits - 1)) - 1;
|
546 | var s, e, f, ln, i;
|
547 |
|
548 |
|
549 | if (v === 0) {
|
550 | e = 0;
|
551 | f = 0;
|
552 | s = 1 / v === -Infinity ? 1 : 0;
|
553 | }
|
554 | else {
|
555 | s = v < 0;
|
556 | v = Math.abs(v);
|
557 | if (v >= Math.pow(2, 1 - bias)) {
|
558 |
|
559 | ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
|
560 | e = ln + bias;
|
561 | f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
|
562 | }
|
563 | else {
|
564 |
|
565 | e = 0;
|
566 | f = Math.round(v / Math.pow(2, 1 - bias - fbits));
|
567 | }
|
568 | }
|
569 |
|
570 | var bits = [];
|
571 | for (i = fbits; i; i -= 1) {
|
572 | bits.push(f % 2 ? 1 : 0);
|
573 | f = Math.floor(f / 2);
|
574 | }
|
575 | for (i = ebits; i; i -= 1) {
|
576 | bits.push(e % 2 ? 1 : 0);
|
577 | e = Math.floor(e / 2);
|
578 | }
|
579 | bits.push(s ? 1 : 0);
|
580 | bits.reverse();
|
581 | var str = bits.join('');
|
582 |
|
583 | var hexByteString = '';
|
584 | for (i = 0; i < 64; i += 8) {
|
585 | var hexByte = parseInt(str.substr(i, 8), 2).toString(16);
|
586 | if (hexByte.length === 1) {
|
587 | hexByte = '0' + hexByte;
|
588 | }
|
589 | hexByteString = hexByteString + hexByte;
|
590 | }
|
591 | return hexByteString.toLowerCase();
|
592 | };
|
593 |
|
594 |
|
595 |
|
596 |
|
597 | var isChromeExtensionContentScript = function () {
|
598 | return !!(typeof window === 'object' &&
|
599 | window['chrome'] &&
|
600 | window['chrome']['extension'] &&
|
601 | !/^chrome/.test(window.location.href));
|
602 | };
|
603 |
|
604 |
|
605 |
|
606 | var isWindowsStoreApp = function () {
|
607 |
|
608 | return typeof Windows === 'object' && typeof Windows.UI === 'object';
|
609 | };
|
610 |
|
611 |
|
612 |
|
613 | function errorForServerCode(code, query) {
|
614 | var reason = 'Unknown Error';
|
615 | if (code === 'too_big') {
|
616 | reason =
|
617 | 'The data requested exceeds the maximum size ' +
|
618 | 'that can be accessed with a single request.';
|
619 | }
|
620 | else if (code === 'permission_denied') {
|
621 | reason = "Client doesn't have permission to access the desired data.";
|
622 | }
|
623 | else if (code === 'unavailable') {
|
624 | reason = 'The service is unavailable';
|
625 | }
|
626 | var error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);
|
627 |
|
628 | error.code = code.toUpperCase();
|
629 | return error;
|
630 | }
|
631 |
|
632 |
|
633 |
|
634 | var INTEGER_REGEXP_ = new RegExp('^-?(0*)\\d{1,10}$');
|
635 |
|
636 |
|
637 |
|
638 | var INTEGER_32_MIN = -2147483648;
|
639 |
|
640 |
|
641 |
|
642 | var INTEGER_32_MAX = 2147483647;
|
643 |
|
644 |
|
645 |
|
646 | var tryParseInt = function (str) {
|
647 | if (INTEGER_REGEXP_.test(str)) {
|
648 | var intVal = Number(str);
|
649 | if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
|
650 | return intVal;
|
651 | }
|
652 | }
|
653 | return null;
|
654 | };
|
655 |
|
656 |
|
657 |
|
658 |
|
659 |
|
660 |
|
661 |
|
662 |
|
663 |
|
664 |
|
665 |
|
666 |
|
667 |
|
668 |
|
669 |
|
670 |
|
671 |
|
672 | var exceptionGuard = function (fn) {
|
673 | try {
|
674 | fn();
|
675 | }
|
676 | catch (e) {
|
677 |
|
678 | setTimeout(function () {
|
679 |
|
680 |
|
681 |
|
682 |
|
683 | var stack = e.stack || '';
|
684 | warn('Exception was thrown by user callback.', stack);
|
685 | throw e;
|
686 | }, Math.floor(0));
|
687 | }
|
688 | };
|
689 |
|
690 |
|
691 |
|
692 | var beingCrawled = function () {
|
693 | var userAgent = (typeof window === 'object' &&
|
694 | window['navigator'] &&
|
695 | window['navigator']['userAgent']) ||
|
696 | '';
|
697 |
|
698 |
|
699 |
|
700 |
|
701 | return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);
|
702 | };
|
703 |
|
704 |
|
705 |
|
706 |
|
707 |
|
708 |
|
709 |
|
710 |
|
711 |
|
712 | var setTimeoutNonBlocking = function (fn, time) {
|
713 | var timeout = setTimeout(fn, time);
|
714 |
|
715 | if (typeof timeout === 'number' &&
|
716 |
|
717 | typeof Deno !== 'undefined' &&
|
718 |
|
719 | Deno['unrefTimer']) {
|
720 |
|
721 | Deno.unrefTimer(timeout);
|
722 |
|
723 | }
|
724 | else if (typeof timeout === 'object' && timeout['unref']) {
|
725 |
|
726 | timeout['unref']();
|
727 | }
|
728 | return timeout;
|
729 | };
|
730 |
|
731 |
|
732 |
|
733 |
|
734 |
|
735 |
|
736 |
|
737 |
|
738 |
|
739 |
|
740 |
|
741 |
|
742 |
|
743 |
|
744 |
|
745 |
|
746 |
|
747 |
|
748 |
|
749 |
|
750 | var RepoInfo = (function () {
|
751 | |
752 |
|
753 |
|
754 |
|
755 |
|
756 |
|
757 |
|
758 |
|
759 | function RepoInfo(host, secure, namespace, webSocketOnly, nodeAdmin, persistenceKey, includeNamespaceInQueryParams, isUsingEmulator) {
|
760 | if (nodeAdmin === void 0) { nodeAdmin = false; }
|
761 | if (persistenceKey === void 0) { persistenceKey = ''; }
|
762 | if (includeNamespaceInQueryParams === void 0) { includeNamespaceInQueryParams = false; }
|
763 | if (isUsingEmulator === void 0) { isUsingEmulator = false; }
|
764 | this.secure = secure;
|
765 | this.namespace = namespace;
|
766 | this.webSocketOnly = webSocketOnly;
|
767 | this.nodeAdmin = nodeAdmin;
|
768 | this.persistenceKey = persistenceKey;
|
769 | this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
|
770 | this.isUsingEmulator = isUsingEmulator;
|
771 | this._host = host.toLowerCase();
|
772 | this._domain = this._host.substr(this._host.indexOf('.') + 1);
|
773 | this.internalHost =
|
774 | PersistentStorage.get('host:' + host) || this._host;
|
775 | }
|
776 | RepoInfo.prototype.isCacheableHost = function () {
|
777 | return this.internalHost.substr(0, 2) === 's-';
|
778 | };
|
779 | RepoInfo.prototype.isCustomHost = function () {
|
780 | return (this._domain !== 'firebaseio.com' &&
|
781 | this._domain !== 'firebaseio-demo.com');
|
782 | };
|
783 | Object.defineProperty(RepoInfo.prototype, "host", {
|
784 | get: function () {
|
785 | return this._host;
|
786 | },
|
787 | set: function (newHost) {
|
788 | if (newHost !== this.internalHost) {
|
789 | this.internalHost = newHost;
|
790 | if (this.isCacheableHost()) {
|
791 | PersistentStorage.set('host:' + this._host, this.internalHost);
|
792 | }
|
793 | }
|
794 | },
|
795 | enumerable: false,
|
796 | configurable: true
|
797 | });
|
798 | RepoInfo.prototype.toString = function () {
|
799 | var str = this.toURLString();
|
800 | if (this.persistenceKey) {
|
801 | str += '<' + this.persistenceKey + '>';
|
802 | }
|
803 | return str;
|
804 | };
|
805 | RepoInfo.prototype.toURLString = function () {
|
806 | var protocol = this.secure ? 'https://' : 'http://';
|
807 | var query = this.includeNamespaceInQueryParams
|
808 | ? "?ns=".concat(this.namespace)
|
809 | : '';
|
810 | return "".concat(protocol).concat(this.host, "/").concat(query);
|
811 | };
|
812 | return RepoInfo;
|
813 | }());
|
814 | function repoInfoNeedsQueryParam(repoInfo) {
|
815 | return (repoInfo.host !== repoInfo.internalHost ||
|
816 | repoInfo.isCustomHost() ||
|
817 | repoInfo.includeNamespaceInQueryParams);
|
818 | }
|
819 |
|
820 |
|
821 |
|
822 |
|
823 |
|
824 |
|
825 |
|
826 | function repoInfoConnectionURL(repoInfo, type, params) {
|
827 | util.assert(typeof type === 'string', 'typeof type must == string');
|
828 | util.assert(typeof params === 'object', 'typeof params must == object');
|
829 | var connURL;
|
830 | if (type === WEBSOCKET) {
|
831 | connURL =
|
832 | (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';
|
833 | }
|
834 | else if (type === LONG_POLLING) {
|
835 | connURL =
|
836 | (repoInfo.secure ? 'https://' : 'http://') +
|
837 | repoInfo.internalHost +
|
838 | '/.lp?';
|
839 | }
|
840 | else {
|
841 | throw new Error('Unknown connection type: ' + type);
|
842 | }
|
843 | if (repoInfoNeedsQueryParam(repoInfo)) {
|
844 | params['ns'] = repoInfo.namespace;
|
845 | }
|
846 | var pairs = [];
|
847 | each(params, function (key, value) {
|
848 | pairs.push(key + '=' + value);
|
849 | });
|
850 | return connURL + pairs.join('&');
|
851 | }
|
852 |
|
853 |
|
854 |
|
855 |
|
856 |
|
857 |
|
858 |
|
859 |
|
860 |
|
861 |
|
862 |
|
863 |
|
864 |
|
865 |
|
866 |
|
867 |
|
868 |
|
869 |
|
870 |
|
871 |
|
872 | var StatsCollection = (function () {
|
873 | function StatsCollection() {
|
874 | this.counters_ = {};
|
875 | }
|
876 | StatsCollection.prototype.incrementCounter = function (name, amount) {
|
877 | if (amount === void 0) { amount = 1; }
|
878 | if (!util.contains(this.counters_, name)) {
|
879 | this.counters_[name] = 0;
|
880 | }
|
881 | this.counters_[name] += amount;
|
882 | };
|
883 | StatsCollection.prototype.get = function () {
|
884 | return util.deepCopy(this.counters_);
|
885 | };
|
886 | return StatsCollection;
|
887 | }());
|
888 |
|
889 |
|
890 |
|
891 |
|
892 |
|
893 |
|
894 |
|
895 |
|
896 |
|
897 |
|
898 |
|
899 |
|
900 |
|
901 |
|
902 |
|
903 |
|
904 |
|
905 | var collections = {};
|
906 | var reporters = {};
|
907 | function statsManagerGetCollection(repoInfo) {
|
908 | var hashString = repoInfo.toString();
|
909 | if (!collections[hashString]) {
|
910 | collections[hashString] = new StatsCollection();
|
911 | }
|
912 | return collections[hashString];
|
913 | }
|
914 | function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
|
915 | var hashString = repoInfo.toString();
|
916 | if (!reporters[hashString]) {
|
917 | reporters[hashString] = creatorFunction();
|
918 | }
|
919 | return reporters[hashString];
|
920 | }
|
921 |
|
922 |
|
923 |
|
924 |
|
925 |
|
926 |
|
927 |
|
928 |
|
929 |
|
930 |
|
931 |
|
932 |
|
933 |
|
934 |
|
935 |
|
936 |
|
937 |
|
938 |
|
939 | var SDK_VERSION = '';
|
940 |
|
941 |
|
942 |
|
943 |
|
944 | function setSDKVersion(version) {
|
945 | SDK_VERSION = version;
|
946 | }
|
947 |
|
948 |
|
949 |
|
950 |
|
951 |
|
952 |
|
953 |
|
954 |
|
955 |
|
956 |
|
957 |
|
958 |
|
959 |
|
960 |
|
961 |
|
962 |
|
963 |
|
964 | var WEBSOCKET_MAX_FRAME_SIZE = 16384;
|
965 | var WEBSOCKET_KEEPALIVE_INTERVAL = 45000;
|
966 | var WebSocketImpl = null;
|
967 | if (typeof MozWebSocket !== 'undefined') {
|
968 | WebSocketImpl = MozWebSocket;
|
969 | }
|
970 | else if (typeof WebSocket !== 'undefined') {
|
971 | WebSocketImpl = WebSocket;
|
972 | }
|
973 | function setWebSocketImpl(impl) {
|
974 | WebSocketImpl = impl;
|
975 | }
|
976 |
|
977 |
|
978 |
|
979 | var WebSocketConnection = (function () {
|
980 | |
981 |
|
982 |
|
983 |
|
984 |
|
985 |
|
986 |
|
987 |
|
988 |
|
989 |
|
990 |
|
991 | function WebSocketConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
|
992 | this.connId = connId;
|
993 | this.applicationId = applicationId;
|
994 | this.appCheckToken = appCheckToken;
|
995 | this.authToken = authToken;
|
996 | this.keepaliveTimer = null;
|
997 | this.frames = null;
|
998 | this.totalFrames = 0;
|
999 | this.bytesSent = 0;
|
1000 | this.bytesReceived = 0;
|
1001 | this.log_ = logWrapper(this.connId);
|
1002 | this.stats_ = statsManagerGetCollection(repoInfo);
|
1003 | this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
|
1004 | this.nodeAdmin = repoInfo.nodeAdmin;
|
1005 | }
|
1006 | |
1007 |
|
1008 |
|
1009 |
|
1010 |
|
1011 |
|
1012 |
|
1013 | WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
|
1014 | var urlParams = {};
|
1015 | urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
|
1016 | if (!util.isNodeSdk() &&
|
1017 | typeof location !== 'undefined' &&
|
1018 | location.hostname &&
|
1019 | FORGE_DOMAIN_RE.test(location.hostname)) {
|
1020 | urlParams[REFERER_PARAM] = FORGE_REF;
|
1021 | }
|
1022 | if (transportSessionId) {
|
1023 | urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
|
1024 | }
|
1025 | if (lastSessionId) {
|
1026 | urlParams[LAST_SESSION_PARAM] = lastSessionId;
|
1027 | }
|
1028 | if (appCheckToken) {
|
1029 | urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
|
1030 | }
|
1031 | if (applicationId) {
|
1032 | urlParams[APPLICATION_ID_PARAM] = applicationId;
|
1033 | }
|
1034 | return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
|
1035 | };
|
1036 | |
1037 |
|
1038 |
|
1039 |
|
1040 | WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {
|
1041 | var _this = this;
|
1042 | this.onDisconnect = onDisconnect;
|
1043 | this.onMessage = onMessage;
|
1044 | this.log_('Websocket connecting to ' + this.connURL);
|
1045 | this.everConnected_ = false;
|
1046 |
|
1047 | PersistentStorage.set('previous_websocket_failure', true);
|
1048 | try {
|
1049 | var options = void 0;
|
1050 | if (util.isNodeSdk()) {
|
1051 | var device = this.nodeAdmin ? 'AdminNode' : 'Node';
|
1052 |
|
1053 | options = {
|
1054 | headers: {
|
1055 | 'User-Agent': "Firebase/".concat(PROTOCOL_VERSION, "/").concat(SDK_VERSION, "/").concat(process.platform, "/").concat(device),
|
1056 | 'X-Firebase-GMPID': this.applicationId || ''
|
1057 | }
|
1058 | };
|
1059 |
|
1060 |
|
1061 |
|
1062 |
|
1063 |
|
1064 | if (this.authToken) {
|
1065 | options.headers['Authorization'] = "Bearer ".concat(this.authToken);
|
1066 | }
|
1067 | if (this.appCheckToken) {
|
1068 | options.headers['X-Firebase-AppCheck'] = this.appCheckToken;
|
1069 | }
|
1070 |
|
1071 | var env = process['env'];
|
1072 | var proxy = this.connURL.indexOf('wss://') === 0
|
1073 | ? env['HTTPS_PROXY'] || env['https_proxy']
|
1074 | : env['HTTP_PROXY'] || env['http_proxy'];
|
1075 | if (proxy) {
|
1076 | options['proxy'] = { origin: proxy };
|
1077 | }
|
1078 | }
|
1079 | this.mySock = new WebSocketImpl(this.connURL, [], options);
|
1080 | }
|
1081 | catch (e) {
|
1082 | this.log_('Error instantiating WebSocket.');
|
1083 | var error = e.message || e.data;
|
1084 | if (error) {
|
1085 | this.log_(error);
|
1086 | }
|
1087 | this.onClosed_();
|
1088 | return;
|
1089 | }
|
1090 | this.mySock.onopen = function () {
|
1091 | _this.log_('Websocket connected.');
|
1092 | _this.everConnected_ = true;
|
1093 | };
|
1094 | this.mySock.onclose = function () {
|
1095 | _this.log_('Websocket connection was disconnected.');
|
1096 | _this.mySock = null;
|
1097 | _this.onClosed_();
|
1098 | };
|
1099 | this.mySock.onmessage = function (m) {
|
1100 | _this.handleIncomingFrame(m);
|
1101 | };
|
1102 | this.mySock.onerror = function (e) {
|
1103 | _this.log_('WebSocket error. Closing connection.');
|
1104 |
|
1105 | var error = e.message || e.data;
|
1106 | if (error) {
|
1107 | _this.log_(error);
|
1108 | }
|
1109 | _this.onClosed_();
|
1110 | };
|
1111 | };
|
1112 | |
1113 |
|
1114 |
|
1115 | WebSocketConnection.prototype.start = function () { };
|
1116 | WebSocketConnection.forceDisallow = function () {
|
1117 | WebSocketConnection.forceDisallow_ = true;
|
1118 | };
|
1119 | WebSocketConnection.isAvailable = function () {
|
1120 | var isOldAndroid = false;
|
1121 | if (typeof navigator !== 'undefined' && navigator.userAgent) {
|
1122 | var oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
|
1123 | var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
|
1124 | if (oldAndroidMatch && oldAndroidMatch.length > 1) {
|
1125 | if (parseFloat(oldAndroidMatch[1]) < 4.4) {
|
1126 | isOldAndroid = true;
|
1127 | }
|
1128 | }
|
1129 | }
|
1130 | return (!isOldAndroid &&
|
1131 | WebSocketImpl !== null &&
|
1132 | !WebSocketConnection.forceDisallow_);
|
1133 | };
|
1134 | |
1135 |
|
1136 |
|
1137 | WebSocketConnection.previouslyFailed = function () {
|
1138 |
|
1139 |
|
1140 | return (PersistentStorage.isInMemoryStorage ||
|
1141 | PersistentStorage.get('previous_websocket_failure') === true);
|
1142 | };
|
1143 | WebSocketConnection.prototype.markConnectionHealthy = function () {
|
1144 | PersistentStorage.remove('previous_websocket_failure');
|
1145 | };
|
1146 | WebSocketConnection.prototype.appendFrame_ = function (data) {
|
1147 | this.frames.push(data);
|
1148 | if (this.frames.length === this.totalFrames) {
|
1149 | var fullMess = this.frames.join('');
|
1150 | this.frames = null;
|
1151 | var jsonMess = util.jsonEval(fullMess);
|
1152 |
|
1153 | this.onMessage(jsonMess);
|
1154 | }
|
1155 | };
|
1156 | |
1157 |
|
1158 |
|
1159 | WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {
|
1160 | this.totalFrames = frameCount;
|
1161 | this.frames = [];
|
1162 | };
|
1163 | |
1164 |
|
1165 |
|
1166 |
|
1167 | WebSocketConnection.prototype.extractFrameCount_ = function (data) {
|
1168 | util.assert(this.frames === null, 'We already have a frame buffer');
|
1169 |
|
1170 |
|
1171 | if (data.length <= 6) {
|
1172 | var frameCount = Number(data);
|
1173 | if (!isNaN(frameCount)) {
|
1174 | this.handleNewFrameCount_(frameCount);
|
1175 | return null;
|
1176 | }
|
1177 | }
|
1178 | this.handleNewFrameCount_(1);
|
1179 | return data;
|
1180 | };
|
1181 | |
1182 |
|
1183 |
|
1184 |
|
1185 | WebSocketConnection.prototype.handleIncomingFrame = function (mess) {
|
1186 | if (this.mySock === null) {
|
1187 | return;
|
1188 | }
|
1189 | var data = mess['data'];
|
1190 | this.bytesReceived += data.length;
|
1191 | this.stats_.incrementCounter('bytes_received', data.length);
|
1192 | this.resetKeepAlive();
|
1193 | if (this.frames !== null) {
|
1194 |
|
1195 | this.appendFrame_(data);
|
1196 | }
|
1197 | else {
|
1198 |
|
1199 | var remainingData = this.extractFrameCount_(data);
|
1200 | if (remainingData !== null) {
|
1201 | this.appendFrame_(remainingData);
|
1202 | }
|
1203 | }
|
1204 | };
|
1205 | |
1206 |
|
1207 |
|
1208 |
|
1209 | WebSocketConnection.prototype.send = function (data) {
|
1210 | this.resetKeepAlive();
|
1211 | var dataStr = util.stringify(data);
|
1212 | this.bytesSent += dataStr.length;
|
1213 | this.stats_.incrementCounter('bytes_sent', dataStr.length);
|
1214 |
|
1215 |
|
1216 | var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
|
1217 |
|
1218 | if (dataSegs.length > 1) {
|
1219 | this.sendString_(String(dataSegs.length));
|
1220 | }
|
1221 |
|
1222 | for (var i = 0; i < dataSegs.length; i++) {
|
1223 | this.sendString_(dataSegs[i]);
|
1224 | }
|
1225 | };
|
1226 | WebSocketConnection.prototype.shutdown_ = function () {
|
1227 | this.isClosed_ = true;
|
1228 | if (this.keepaliveTimer) {
|
1229 | clearInterval(this.keepaliveTimer);
|
1230 | this.keepaliveTimer = null;
|
1231 | }
|
1232 | if (this.mySock) {
|
1233 | this.mySock.close();
|
1234 | this.mySock = null;
|
1235 | }
|
1236 | };
|
1237 | WebSocketConnection.prototype.onClosed_ = function () {
|
1238 | if (!this.isClosed_) {
|
1239 | this.log_('WebSocket is closing itself');
|
1240 | this.shutdown_();
|
1241 |
|
1242 | if (this.onDisconnect) {
|
1243 | this.onDisconnect(this.everConnected_);
|
1244 | this.onDisconnect = null;
|
1245 | }
|
1246 | }
|
1247 | };
|
1248 | |
1249 |
|
1250 |
|
1251 |
|
1252 | WebSocketConnection.prototype.close = function () {
|
1253 | if (!this.isClosed_) {
|
1254 | this.log_('WebSocket is being closed');
|
1255 | this.shutdown_();
|
1256 | }
|
1257 | };
|
1258 | |
1259 |
|
1260 |
|
1261 |
|
1262 | WebSocketConnection.prototype.resetKeepAlive = function () {
|
1263 | var _this = this;
|
1264 | clearInterval(this.keepaliveTimer);
|
1265 | this.keepaliveTimer = setInterval(function () {
|
1266 |
|
1267 | if (_this.mySock) {
|
1268 | _this.sendString_('0');
|
1269 | }
|
1270 | _this.resetKeepAlive();
|
1271 |
|
1272 | }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
|
1273 | };
|
1274 | |
1275 |
|
1276 |
|
1277 |
|
1278 |
|
1279 | WebSocketConnection.prototype.sendString_ = function (str) {
|
1280 |
|
1281 |
|
1282 |
|
1283 | try {
|
1284 | this.mySock.send(str);
|
1285 | }
|
1286 | catch (e) {
|
1287 | this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');
|
1288 | setTimeout(this.onClosed_.bind(this), 0);
|
1289 | }
|
1290 | };
|
1291 | |
1292 |
|
1293 |
|
1294 | WebSocketConnection.responsesRequiredToBeHealthy = 2;
|
1295 | |
1296 |
|
1297 |
|
1298 | WebSocketConnection.healthyTimeout = 30000;
|
1299 | return WebSocketConnection;
|
1300 | }());
|
1301 |
|
1302 | var name = "@firebase/database";
|
1303 | var version = "0.14.4";
|
1304 |
|
1305 |
|
1306 |
|
1307 |
|
1308 |
|
1309 |
|
1310 |
|
1311 |
|
1312 |
|
1313 |
|
1314 |
|
1315 |
|
1316 |
|
1317 |
|
1318 |
|
1319 |
|
1320 |
|
1321 |
|
1322 |
|
1323 |
|
1324 | var AppCheckTokenProvider = (function () {
|
1325 | function AppCheckTokenProvider(appName_, appCheckProvider) {
|
1326 | var _this = this;
|
1327 | this.appName_ = appName_;
|
1328 | this.appCheckProvider = appCheckProvider;
|
1329 | this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
|
1330 | if (!this.appCheck) {
|
1331 | appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); });
|
1332 | }
|
1333 | }
|
1334 | AppCheckTokenProvider.prototype.getToken = function (forceRefresh) {
|
1335 | var _this = this;
|
1336 | if (!this.appCheck) {
|
1337 | return new Promise(function (resolve, reject) {
|
1338 |
|
1339 |
|
1340 |
|
1341 |
|
1342 | setTimeout(function () {
|
1343 | if (_this.appCheck) {
|
1344 | _this.getToken(forceRefresh).then(resolve, reject);
|
1345 | }
|
1346 | else {
|
1347 | resolve(null);
|
1348 | }
|
1349 | }, 0);
|
1350 | });
|
1351 | }
|
1352 | return this.appCheck.getToken(forceRefresh);
|
1353 | };
|
1354 | AppCheckTokenProvider.prototype.addTokenChangeListener = function (listener) {
|
1355 | var _a;
|
1356 | (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(function (appCheck) { return appCheck.addTokenListener(listener); });
|
1357 | };
|
1358 | AppCheckTokenProvider.prototype.notifyForInvalidToken = function () {
|
1359 | warn("Provided AppCheck credentials for the app named \"".concat(this.appName_, "\" ") +
|
1360 | 'are invalid. This usually indicates your app was not initialized correctly.');
|
1361 | };
|
1362 | return AppCheckTokenProvider;
|
1363 | }());
|
1364 |
|
1365 |
|
1366 |
|
1367 |
|
1368 |
|
1369 |
|
1370 |
|
1371 |
|
1372 |
|
1373 |
|
1374 |
|
1375 |
|
1376 |
|
1377 |
|
1378 |
|
1379 |
|
1380 |
|
1381 |
|
1382 |
|
1383 |
|
1384 | var FirebaseAuthTokenProvider = (function () {
|
1385 | function FirebaseAuthTokenProvider(appName_, firebaseOptions_, authProvider_) {
|
1386 | var _this = this;
|
1387 | this.appName_ = appName_;
|
1388 | this.firebaseOptions_ = firebaseOptions_;
|
1389 | this.authProvider_ = authProvider_;
|
1390 | this.auth_ = null;
|
1391 | this.auth_ = authProvider_.getImmediate({ optional: true });
|
1392 | if (!this.auth_) {
|
1393 | authProvider_.onInit(function (auth) { return (_this.auth_ = auth); });
|
1394 | }
|
1395 | }
|
1396 | FirebaseAuthTokenProvider.prototype.getToken = function (forceRefresh) {
|
1397 | var _this = this;
|
1398 | if (!this.auth_) {
|
1399 | return new Promise(function (resolve, reject) {
|
1400 |
|
1401 |
|
1402 |
|
1403 |
|
1404 | setTimeout(function () {
|
1405 | if (_this.auth_) {
|
1406 | _this.getToken(forceRefresh).then(resolve, reject);
|
1407 | }
|
1408 | else {
|
1409 | resolve(null);
|
1410 | }
|
1411 | }, 0);
|
1412 | });
|
1413 | }
|
1414 | return this.auth_.getToken(forceRefresh).catch(function (error) {
|
1415 |
|
1416 |
|
1417 | if (error && error.code === 'auth/token-not-initialized') {
|
1418 | log('Got auth/token-not-initialized error. Treating as null token.');
|
1419 | return null;
|
1420 | }
|
1421 | else {
|
1422 | return Promise.reject(error);
|
1423 | }
|
1424 | });
|
1425 | };
|
1426 | FirebaseAuthTokenProvider.prototype.addTokenChangeListener = function (listener) {
|
1427 |
|
1428 |
|
1429 | if (this.auth_) {
|
1430 | this.auth_.addAuthTokenListener(listener);
|
1431 | }
|
1432 | else {
|
1433 | this.authProvider_
|
1434 | .get()
|
1435 | .then(function (auth) { return auth.addAuthTokenListener(listener); });
|
1436 | }
|
1437 | };
|
1438 | FirebaseAuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {
|
1439 | this.authProvider_
|
1440 | .get()
|
1441 | .then(function (auth) { return auth.removeAuthTokenListener(listener); });
|
1442 | };
|
1443 | FirebaseAuthTokenProvider.prototype.notifyForInvalidToken = function () {
|
1444 | var errorMessage = 'Provided authentication credentials for the app named "' +
|
1445 | this.appName_ +
|
1446 | '" are invalid. This usually indicates your app was not ' +
|
1447 | 'initialized correctly. ';
|
1448 | if ('credential' in this.firebaseOptions_) {
|
1449 | errorMessage +=
|
1450 | 'Make sure the "credential" property provided to initializeApp() ' +
|
1451 | 'is authorized to access the specified "databaseURL" and is from the correct ' +
|
1452 | 'project.';
|
1453 | }
|
1454 | else if ('serviceAccount' in this.firebaseOptions_) {
|
1455 | errorMessage +=
|
1456 | 'Make sure the "serviceAccount" property provided to initializeApp() ' +
|
1457 | 'is authorized to access the specified "databaseURL" and is from the correct ' +
|
1458 | 'project.';
|
1459 | }
|
1460 | else {
|
1461 | errorMessage +=
|
1462 | 'Make sure the "apiKey" and "databaseURL" properties provided to ' +
|
1463 | 'initializeApp() match the values provided for your app at ' +
|
1464 | 'https://console.firebase.google.com/.';
|
1465 | }
|
1466 | warn(errorMessage);
|
1467 | };
|
1468 | return FirebaseAuthTokenProvider;
|
1469 | }());
|
1470 |
|
1471 | var EmulatorTokenProvider = (function () {
|
1472 | function EmulatorTokenProvider(accessToken) {
|
1473 | this.accessToken = accessToken;
|
1474 | }
|
1475 | EmulatorTokenProvider.prototype.getToken = function (forceRefresh) {
|
1476 | return Promise.resolve({
|
1477 | accessToken: this.accessToken
|
1478 | });
|
1479 | };
|
1480 | EmulatorTokenProvider.prototype.addTokenChangeListener = function (listener) {
|
1481 |
|
1482 |
|
1483 | listener(this.accessToken);
|
1484 | };
|
1485 | EmulatorTokenProvider.prototype.removeTokenChangeListener = function (listener) { };
|
1486 | EmulatorTokenProvider.prototype.notifyForInvalidToken = function () { };
|
1487 |
|
1488 | EmulatorTokenProvider.OWNER = 'owner';
|
1489 | return EmulatorTokenProvider;
|
1490 | }());
|
1491 |
|
1492 |
|
1493 |
|
1494 |
|
1495 |
|
1496 |
|
1497 |
|
1498 |
|
1499 |
|
1500 |
|
1501 |
|
1502 |
|
1503 |
|
1504 |
|
1505 |
|
1506 |
|
1507 |
|
1508 |
|
1509 |
|
1510 |
|
1511 |
|
1512 | var PacketReceiver = (function () {
|
1513 | |
1514 |
|
1515 |
|
1516 | function PacketReceiver(onMessage_) {
|
1517 | this.onMessage_ = onMessage_;
|
1518 | this.pendingResponses = [];
|
1519 | this.currentResponseNum = 0;
|
1520 | this.closeAfterResponse = -1;
|
1521 | this.onClose = null;
|
1522 | }
|
1523 | PacketReceiver.prototype.closeAfter = function (responseNum, callback) {
|
1524 | this.closeAfterResponse = responseNum;
|
1525 | this.onClose = callback;
|
1526 | if (this.closeAfterResponse < this.currentResponseNum) {
|
1527 | this.onClose();
|
1528 | this.onClose = null;
|
1529 | }
|
1530 | };
|
1531 | |
1532 |
|
1533 |
|
1534 |
|
1535 |
|
1536 | PacketReceiver.prototype.handleResponse = function (requestNum, data) {
|
1537 | var _this = this;
|
1538 | this.pendingResponses[requestNum] = data;
|
1539 | var _loop_1 = function () {
|
1540 | var toProcess = this_1.pendingResponses[this_1.currentResponseNum];
|
1541 | delete this_1.pendingResponses[this_1.currentResponseNum];
|
1542 | var _loop_2 = function (i) {
|
1543 | if (toProcess[i]) {
|
1544 | exceptionGuard(function () {
|
1545 | _this.onMessage_(toProcess[i]);
|
1546 | });
|
1547 | }
|
1548 | };
|
1549 | for (var i = 0; i < toProcess.length; ++i) {
|
1550 | _loop_2(i);
|
1551 | }
|
1552 | if (this_1.currentResponseNum === this_1.closeAfterResponse) {
|
1553 | if (this_1.onClose) {
|
1554 | this_1.onClose();
|
1555 | this_1.onClose = null;
|
1556 | }
|
1557 | return "break";
|
1558 | }
|
1559 | this_1.currentResponseNum++;
|
1560 | };
|
1561 | var this_1 = this;
|
1562 | while (this.pendingResponses[this.currentResponseNum]) {
|
1563 | var state_1 = _loop_1();
|
1564 | if (state_1 === "break")
|
1565 | break;
|
1566 | }
|
1567 | };
|
1568 | return PacketReceiver;
|
1569 | }());
|
1570 |
|
1571 |
|
1572 |
|
1573 |
|
1574 |
|
1575 |
|
1576 |
|
1577 |
|
1578 |
|
1579 |
|
1580 |
|
1581 |
|
1582 |
|
1583 |
|
1584 |
|
1585 |
|
1586 |
|
1587 |
|
1588 | var FIREBASE_LONGPOLL_START_PARAM = 'start';
|
1589 | var FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';
|
1590 | var FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';
|
1591 | var FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';
|
1592 | var FIREBASE_LONGPOLL_ID_PARAM = 'id';
|
1593 | var FIREBASE_LONGPOLL_PW_PARAM = 'pw';
|
1594 | var FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';
|
1595 | var FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';
|
1596 | var FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';
|
1597 | var FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';
|
1598 | var FIREBASE_LONGPOLL_DATA_PARAM = 'd';
|
1599 | var FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';
|
1600 |
|
1601 |
|
1602 |
|
1603 | var MAX_URL_DATA_SIZE = 1870;
|
1604 | var SEG_HEADER_SIZE = 30;
|
1605 | var MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
|
1606 |
|
1607 |
|
1608 |
|
1609 |
|
1610 |
|
1611 | var KEEPALIVE_REQUEST_INTERVAL = 25000;
|
1612 |
|
1613 |
|
1614 |
|
1615 | var LP_CONNECT_TIMEOUT = 30000;
|
1616 |
|
1617 |
|
1618 |
|
1619 | var BrowserPollConnection = (function () {
|
1620 | |
1621 |
|
1622 |
|
1623 |
|
1624 |
|
1625 |
|
1626 |
|
1627 |
|
1628 |
|
1629 |
|
1630 |
|
1631 | function BrowserPollConnection(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
|
1632 | var _this = this;
|
1633 | this.connId = connId;
|
1634 | this.repoInfo = repoInfo;
|
1635 | this.applicationId = applicationId;
|
1636 | this.appCheckToken = appCheckToken;
|
1637 | this.authToken = authToken;
|
1638 | this.transportSessionId = transportSessionId;
|
1639 | this.lastSessionId = lastSessionId;
|
1640 | this.bytesSent = 0;
|
1641 | this.bytesReceived = 0;
|
1642 | this.everConnected_ = false;
|
1643 | this.log_ = logWrapper(connId);
|
1644 | this.stats_ = statsManagerGetCollection(repoInfo);
|
1645 | this.urlFn = function (params) {
|
1646 |
|
1647 | if (_this.appCheckToken) {
|
1648 | params[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
|
1649 | }
|
1650 | return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
|
1651 | };
|
1652 | }
|
1653 | |
1654 |
|
1655 |
|
1656 |
|
1657 | BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {
|
1658 | var _this = this;
|
1659 | this.curSegmentNum = 0;
|
1660 | this.onDisconnect_ = onDisconnect;
|
1661 | this.myPacketOrderer = new PacketReceiver(onMessage);
|
1662 | this.isClosed_ = false;
|
1663 | this.connectTimeoutTimer_ = setTimeout(function () {
|
1664 | _this.log_('Timed out trying to connect.');
|
1665 |
|
1666 | _this.onClosed_();
|
1667 | _this.connectTimeoutTimer_ = null;
|
1668 |
|
1669 | }, Math.floor(LP_CONNECT_TIMEOUT));
|
1670 |
|
1671 | executeWhenDOMReady(function () {
|
1672 | if (_this.isClosed_) {
|
1673 | return;
|
1674 | }
|
1675 |
|
1676 | _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {
|
1677 | var args = [];
|
1678 | for (var _i = 0; _i < arguments.length; _i++) {
|
1679 | args[_i] = arguments[_i];
|
1680 | }
|
1681 | var _a = tslib.__read(args, 5), command = _a[0], arg1 = _a[1], arg2 = _a[2]; _a[3]; _a[4];
|
1682 | _this.incrementIncomingBytes_(args);
|
1683 | if (!_this.scriptTagHolder) {
|
1684 | return;
|
1685 | }
|
1686 | if (_this.connectTimeoutTimer_) {
|
1687 | clearTimeout(_this.connectTimeoutTimer_);
|
1688 | _this.connectTimeoutTimer_ = null;
|
1689 | }
|
1690 | _this.everConnected_ = true;
|
1691 | if (command === FIREBASE_LONGPOLL_START_PARAM) {
|
1692 | _this.id = arg1;
|
1693 | _this.password = arg2;
|
1694 | }
|
1695 | else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
|
1696 |
|
1697 | if (arg1) {
|
1698 |
|
1699 |
|
1700 | _this.scriptTagHolder.sendNewPolls = false;
|
1701 |
|
1702 |
|
1703 | _this.myPacketOrderer.closeAfter(arg1, function () {
|
1704 | _this.onClosed_();
|
1705 | });
|
1706 | }
|
1707 | else {
|
1708 | _this.onClosed_();
|
1709 | }
|
1710 | }
|
1711 | else {
|
1712 | throw new Error('Unrecognized command received: ' + command);
|
1713 | }
|
1714 | }, function () {
|
1715 | var args = [];
|
1716 | for (var _i = 0; _i < arguments.length; _i++) {
|
1717 | args[_i] = arguments[_i];
|
1718 | }
|
1719 | var _a = tslib.__read(args, 2), pN = _a[0], data = _a[1];
|
1720 | _this.incrementIncomingBytes_(args);
|
1721 | _this.myPacketOrderer.handleResponse(pN, data);
|
1722 | }, function () {
|
1723 | _this.onClosed_();
|
1724 | }, _this.urlFn);
|
1725 |
|
1726 |
|
1727 | var urlParams = {};
|
1728 | urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';
|
1729 | urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);
|
1730 | if (_this.scriptTagHolder.uniqueCallbackIdentifier) {
|
1731 | urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =
|
1732 | _this.scriptTagHolder.uniqueCallbackIdentifier;
|
1733 | }
|
1734 | urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
|
1735 | if (_this.transportSessionId) {
|
1736 | urlParams[TRANSPORT_SESSION_PARAM] = _this.transportSessionId;
|
1737 | }
|
1738 | if (_this.lastSessionId) {
|
1739 | urlParams[LAST_SESSION_PARAM] = _this.lastSessionId;
|
1740 | }
|
1741 | if (_this.applicationId) {
|
1742 | urlParams[APPLICATION_ID_PARAM] = _this.applicationId;
|
1743 | }
|
1744 | if (_this.appCheckToken) {
|
1745 | urlParams[APP_CHECK_TOKEN_PARAM] = _this.appCheckToken;
|
1746 | }
|
1747 | if (typeof location !== 'undefined' &&
|
1748 | location.hostname &&
|
1749 | FORGE_DOMAIN_RE.test(location.hostname)) {
|
1750 | urlParams[REFERER_PARAM] = FORGE_REF;
|
1751 | }
|
1752 | var connectURL = _this.urlFn(urlParams);
|
1753 | _this.log_('Connecting via long-poll to ' + connectURL);
|
1754 | _this.scriptTagHolder.addTag(connectURL, function () {
|
1755 |
|
1756 | });
|
1757 | });
|
1758 | };
|
1759 | |
1760 |
|
1761 |
|
1762 | BrowserPollConnection.prototype.start = function () {
|
1763 | this.scriptTagHolder.startLongPoll(this.id, this.password);
|
1764 | this.addDisconnectPingFrame(this.id, this.password);
|
1765 | };
|
1766 | |
1767 |
|
1768 |
|
1769 | BrowserPollConnection.forceAllow = function () {
|
1770 | BrowserPollConnection.forceAllow_ = true;
|
1771 | };
|
1772 | |
1773 |
|
1774 |
|
1775 | BrowserPollConnection.forceDisallow = function () {
|
1776 | BrowserPollConnection.forceDisallow_ = true;
|
1777 | };
|
1778 |
|
1779 | BrowserPollConnection.isAvailable = function () {
|
1780 | if (util.isNodeSdk()) {
|
1781 | return false;
|
1782 | }
|
1783 | else if (BrowserPollConnection.forceAllow_) {
|
1784 | return true;
|
1785 | }
|
1786 | else {
|
1787 |
|
1788 |
|
1789 | return (!BrowserPollConnection.forceDisallow_ &&
|
1790 | typeof document !== 'undefined' &&
|
1791 | document.createElement != null &&
|
1792 | !isChromeExtensionContentScript() &&
|
1793 | !isWindowsStoreApp());
|
1794 | }
|
1795 | };
|
1796 | |
1797 |
|
1798 |
|
1799 | BrowserPollConnection.prototype.markConnectionHealthy = function () { };
|
1800 | |
1801 |
|
1802 |
|
1803 | BrowserPollConnection.prototype.shutdown_ = function () {
|
1804 | this.isClosed_ = true;
|
1805 | if (this.scriptTagHolder) {
|
1806 | this.scriptTagHolder.close();
|
1807 | this.scriptTagHolder = null;
|
1808 | }
|
1809 |
|
1810 | if (this.myDisconnFrame) {
|
1811 | document.body.removeChild(this.myDisconnFrame);
|
1812 | this.myDisconnFrame = null;
|
1813 | }
|
1814 | if (this.connectTimeoutTimer_) {
|
1815 | clearTimeout(this.connectTimeoutTimer_);
|
1816 | this.connectTimeoutTimer_ = null;
|
1817 | }
|
1818 | };
|
1819 | |
1820 |
|
1821 |
|
1822 | BrowserPollConnection.prototype.onClosed_ = function () {
|
1823 | if (!this.isClosed_) {
|
1824 | this.log_('Longpoll is closing itself');
|
1825 | this.shutdown_();
|
1826 | if (this.onDisconnect_) {
|
1827 | this.onDisconnect_(this.everConnected_);
|
1828 | this.onDisconnect_ = null;
|
1829 | }
|
1830 | }
|
1831 | };
|
1832 | |
1833 |
|
1834 |
|
1835 |
|
1836 | BrowserPollConnection.prototype.close = function () {
|
1837 | if (!this.isClosed_) {
|
1838 | this.log_('Longpoll is being closed.');
|
1839 | this.shutdown_();
|
1840 | }
|
1841 | };
|
1842 | |
1843 |
|
1844 |
|
1845 |
|
1846 |
|
1847 | BrowserPollConnection.prototype.send = function (data) {
|
1848 | var dataStr = util.stringify(data);
|
1849 | this.bytesSent += dataStr.length;
|
1850 | this.stats_.incrementCounter('bytes_sent', dataStr.length);
|
1851 |
|
1852 | var base64data = util.base64Encode(dataStr);
|
1853 |
|
1854 |
|
1855 | var dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
|
1856 |
|
1857 |
|
1858 | for (var i = 0; i < dataSegs.length; i++) {
|
1859 | this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);
|
1860 | this.curSegmentNum++;
|
1861 | }
|
1862 | };
|
1863 | |
1864 |
|
1865 |
|
1866 |
|
1867 |
|
1868 | BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {
|
1869 | if (util.isNodeSdk()) {
|
1870 | return;
|
1871 | }
|
1872 | this.myDisconnFrame = document.createElement('iframe');
|
1873 | var urlParams = {};
|
1874 | urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';
|
1875 | urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
|
1876 | urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
|
1877 | this.myDisconnFrame.src = this.urlFn(urlParams);
|
1878 | this.myDisconnFrame.style.display = 'none';
|
1879 | document.body.appendChild(this.myDisconnFrame);
|
1880 | };
|
1881 | |
1882 |
|
1883 |
|
1884 | BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {
|
1885 |
|
1886 | var bytesReceived = util.stringify(args).length;
|
1887 | this.bytesReceived += bytesReceived;
|
1888 | this.stats_.incrementCounter('bytes_received', bytesReceived);
|
1889 | };
|
1890 | return BrowserPollConnection;
|
1891 | }());
|
1892 |
|
1893 |
|
1894 |
|
1895 | var FirebaseIFrameScriptHolder = (function () {
|
1896 | |
1897 |
|
1898 |
|
1899 |
|
1900 |
|
1901 |
|
1902 | function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {
|
1903 | this.onDisconnect = onDisconnect;
|
1904 | this.urlFn = urlFn;
|
1905 |
|
1906 |
|
1907 | this.outstandingRequests = new Set();
|
1908 |
|
1909 | this.pendingSegs = [];
|
1910 |
|
1911 |
|
1912 |
|
1913 |
|
1914 |
|
1915 | this.currentSerial = Math.floor(Math.random() * 100000000);
|
1916 |
|
1917 |
|
1918 | this.sendNewPolls = true;
|
1919 | if (!util.isNodeSdk()) {
|
1920 |
|
1921 |
|
1922 |
|
1923 |
|
1924 | this.uniqueCallbackIdentifier = LUIDGenerator();
|
1925 | window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
|
1926 | window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =
|
1927 | onMessageCB;
|
1928 |
|
1929 | this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
|
1930 |
|
1931 | var script = '';
|
1932 |
|
1933 |
|
1934 | if (this.myIFrame.src &&
|
1935 | this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {
|
1936 | var currentDomain = document.domain;
|
1937 | script = '<script>document.domain="' + currentDomain + '";</script>';
|
1938 | }
|
1939 | var iframeContents = '<html><body>' + script + '</body></html>';
|
1940 | try {
|
1941 | this.myIFrame.doc.open();
|
1942 | this.myIFrame.doc.write(iframeContents);
|
1943 | this.myIFrame.doc.close();
|
1944 | }
|
1945 | catch (e) {
|
1946 | log('frame writing exception');
|
1947 | if (e.stack) {
|
1948 | log(e.stack);
|
1949 | }
|
1950 | log(e);
|
1951 | }
|
1952 | }
|
1953 | else {
|
1954 | this.commandCB = commandCB;
|
1955 | this.onMessageCB = onMessageCB;
|
1956 | }
|
1957 | }
|
1958 | |
1959 |
|
1960 |
|
1961 |
|
1962 | FirebaseIFrameScriptHolder.createIFrame_ = function () {
|
1963 | var iframe = document.createElement('iframe');
|
1964 | iframe.style.display = 'none';
|
1965 |
|
1966 | if (document.body) {
|
1967 | document.body.appendChild(iframe);
|
1968 | try {
|
1969 |
|
1970 |
|
1971 |
|
1972 | var a = iframe.contentWindow.document;
|
1973 | if (!a) {
|
1974 |
|
1975 | log('No IE domain setting required');
|
1976 | }
|
1977 | }
|
1978 | catch (e) {
|
1979 | var domain = document.domain;
|
1980 | iframe.src =
|
1981 | "javascript:void((function(){document.open();document.domain='" +
|
1982 | domain +
|
1983 | "';document.close();})())";
|
1984 | }
|
1985 | }
|
1986 | else {
|
1987 |
|
1988 |
|
1989 | throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';
|
1990 | }
|
1991 |
|
1992 | if (iframe.contentDocument) {
|
1993 | iframe.doc = iframe.contentDocument;
|
1994 | }
|
1995 | else if (iframe.contentWindow) {
|
1996 | iframe.doc = iframe.contentWindow.document;
|
1997 |
|
1998 | }
|
1999 | else if (iframe.document) {
|
2000 |
|
2001 | iframe.doc = iframe.document;
|
2002 | }
|
2003 | return iframe;
|
2004 | };
|
2005 | |
2006 |
|
2007 |
|
2008 | FirebaseIFrameScriptHolder.prototype.close = function () {
|
2009 | var _this = this;
|
2010 |
|
2011 | this.alive = false;
|
2012 | if (this.myIFrame) {
|
2013 |
|
2014 |
|
2015 |
|
2016 | this.myIFrame.doc.body.textContent = '';
|
2017 | setTimeout(function () {
|
2018 | if (_this.myIFrame !== null) {
|
2019 | document.body.removeChild(_this.myIFrame);
|
2020 | _this.myIFrame = null;
|
2021 | }
|
2022 | }, Math.floor(0));
|
2023 | }
|
2024 |
|
2025 | var onDisconnect = this.onDisconnect;
|
2026 | if (onDisconnect) {
|
2027 | this.onDisconnect = null;
|
2028 | onDisconnect();
|
2029 | }
|
2030 | };
|
2031 | |
2032 |
|
2033 |
|
2034 |
|
2035 |
|
2036 | FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {
|
2037 | this.myID = id;
|
2038 | this.myPW = pw;
|
2039 | this.alive = true;
|
2040 |
|
2041 | while (this.newRequest_()) { }
|
2042 | };
|
2043 | |
2044 |
|
2045 |
|
2046 |
|
2047 |
|
2048 |
|
2049 |
|
2050 | FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {
|
2051 |
|
2052 |
|
2053 |
|
2054 | if (this.alive &&
|
2055 | this.sendNewPolls &&
|
2056 | this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
|
2057 |
|
2058 | this.currentSerial++;
|
2059 | var urlParams = {};
|
2060 | urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
|
2061 | urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
|
2062 | urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
|
2063 | var theURL = this.urlFn(urlParams);
|
2064 |
|
2065 | var curDataString = '';
|
2066 | var i = 0;
|
2067 | while (this.pendingSegs.length > 0) {
|
2068 |
|
2069 | var nextSeg = this.pendingSegs[0];
|
2070 | if (nextSeg.d.length +
|
2071 | SEG_HEADER_SIZE +
|
2072 | curDataString.length <=
|
2073 | MAX_URL_DATA_SIZE) {
|
2074 |
|
2075 | var theSeg = this.pendingSegs.shift();
|
2076 | curDataString =
|
2077 | curDataString +
|
2078 | '&' +
|
2079 | FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +
|
2080 | i +
|
2081 | '=' +
|
2082 | theSeg.seg +
|
2083 | '&' +
|
2084 | FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +
|
2085 | i +
|
2086 | '=' +
|
2087 | theSeg.ts +
|
2088 | '&' +
|
2089 | FIREBASE_LONGPOLL_DATA_PARAM +
|
2090 | i +
|
2091 | '=' +
|
2092 | theSeg.d;
|
2093 | i++;
|
2094 | }
|
2095 | else {
|
2096 | break;
|
2097 | }
|
2098 | }
|
2099 | theURL = theURL + curDataString;
|
2100 | this.addLongPollTag_(theURL, this.currentSerial);
|
2101 | return true;
|
2102 | }
|
2103 | else {
|
2104 | return false;
|
2105 | }
|
2106 | };
|
2107 | |
2108 |
|
2109 |
|
2110 |
|
2111 |
|
2112 |
|
2113 | FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {
|
2114 |
|
2115 | this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
|
2116 |
|
2117 |
|
2118 | if (this.alive) {
|
2119 | this.newRequest_();
|
2120 | }
|
2121 | };
|
2122 | |
2123 |
|
2124 |
|
2125 |
|
2126 |
|
2127 | FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {
|
2128 | var _this = this;
|
2129 |
|
2130 | this.outstandingRequests.add(serial);
|
2131 | var doNewRequest = function () {
|
2132 | _this.outstandingRequests.delete(serial);
|
2133 | _this.newRequest_();
|
2134 | };
|
2135 |
|
2136 |
|
2137 | var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
|
2138 | var readyStateCB = function () {
|
2139 |
|
2140 | clearTimeout(keepaliveTimeout);
|
2141 |
|
2142 | doNewRequest();
|
2143 | };
|
2144 | this.addTag(url, readyStateCB);
|
2145 | };
|
2146 | |
2147 |
|
2148 |
|
2149 |
|
2150 |
|
2151 | FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {
|
2152 | var _this = this;
|
2153 | if (util.isNodeSdk()) {
|
2154 |
|
2155 | this.doNodeLongPoll(url, loadCB);
|
2156 | }
|
2157 | else {
|
2158 | setTimeout(function () {
|
2159 | try {
|
2160 |
|
2161 | if (!_this.sendNewPolls) {
|
2162 | return;
|
2163 | }
|
2164 | var newScript_1 = _this.myIFrame.doc.createElement('script');
|
2165 | newScript_1.type = 'text/javascript';
|
2166 | newScript_1.async = true;
|
2167 | newScript_1.src = url;
|
2168 |
|
2169 | newScript_1.onload = newScript_1.onreadystatechange =
|
2170 | function () {
|
2171 |
|
2172 | var rstate = newScript_1.readyState;
|
2173 | if (!rstate || rstate === 'loaded' || rstate === 'complete') {
|
2174 |
|
2175 | newScript_1.onload = newScript_1.onreadystatechange = null;
|
2176 | if (newScript_1.parentNode) {
|
2177 | newScript_1.parentNode.removeChild(newScript_1);
|
2178 | }
|
2179 | loadCB();
|
2180 | }
|
2181 | };
|
2182 | newScript_1.onerror = function () {
|
2183 | log('Long-poll script failed to load: ' + url);
|
2184 | _this.sendNewPolls = false;
|
2185 | _this.close();
|
2186 | };
|
2187 | _this.myIFrame.doc.body.appendChild(newScript_1);
|
2188 | }
|
2189 | catch (e) {
|
2190 |
|
2191 | }
|
2192 | }, Math.floor(1));
|
2193 | }
|
2194 | };
|
2195 | return FirebaseIFrameScriptHolder;
|
2196 | }());
|
2197 |
|
2198 |
|
2199 |
|
2200 |
|
2201 |
|
2202 |
|
2203 |
|
2204 |
|
2205 |
|
2206 |
|
2207 |
|
2208 |
|
2209 |
|
2210 |
|
2211 |
|
2212 |
|
2213 |
|
2214 |
|
2215 |
|
2216 |
|
2217 |
|
2218 |
|
2219 |
|
2220 |
|
2221 | var TransportManager = (function () {
|
2222 | |
2223 |
|
2224 |
|
2225 | function TransportManager(repoInfo) {
|
2226 | this.initTransports_(repoInfo);
|
2227 | }
|
2228 | Object.defineProperty(TransportManager, "ALL_TRANSPORTS", {
|
2229 | get: function () {
|
2230 | return [BrowserPollConnection, WebSocketConnection];
|
2231 | },
|
2232 | enumerable: false,
|
2233 | configurable: true
|
2234 | });
|
2235 | Object.defineProperty(TransportManager, "IS_TRANSPORT_INITIALIZED", {
|
2236 | |
2237 |
|
2238 |
|
2239 |
|
2240 | get: function () {
|
2241 | return this.globalTransportInitialized_;
|
2242 | },
|
2243 | enumerable: false,
|
2244 | configurable: true
|
2245 | });
|
2246 | TransportManager.prototype.initTransports_ = function (repoInfo) {
|
2247 | var e_1, _a;
|
2248 | var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();
|
2249 | var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
|
2250 | if (repoInfo.webSocketOnly) {
|
2251 | if (!isWebSocketsAvailable) {
|
2252 | warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway.");
|
2253 | }
|
2254 | isSkipPollConnection = true;
|
2255 | }
|
2256 | if (isSkipPollConnection) {
|
2257 | this.transports_ = [WebSocketConnection];
|
2258 | }
|
2259 | else {
|
2260 | var transports = (this.transports_ = []);
|
2261 | try {
|
2262 | for (var _b = tslib.__values(TransportManager.ALL_TRANSPORTS), _c = _b.next(); !_c.done; _c = _b.next()) {
|
2263 | var transport = _c.value;
|
2264 | if (transport && transport['isAvailable']()) {
|
2265 | transports.push(transport);
|
2266 | }
|
2267 | }
|
2268 | }
|
2269 | catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
2270 | finally {
|
2271 | try {
|
2272 | if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
2273 | }
|
2274 | finally { if (e_1) throw e_1.error; }
|
2275 | }
|
2276 | TransportManager.globalTransportInitialized_ = true;
|
2277 | }
|
2278 | };
|
2279 | |
2280 |
|
2281 |
|
2282 | TransportManager.prototype.initialTransport = function () {
|
2283 | if (this.transports_.length > 0) {
|
2284 | return this.transports_[0];
|
2285 | }
|
2286 | else {
|
2287 | throw new Error('No transports available');
|
2288 | }
|
2289 | };
|
2290 | |
2291 |
|
2292 |
|
2293 | TransportManager.prototype.upgradeTransport = function () {
|
2294 | if (this.transports_.length > 1) {
|
2295 | return this.transports_[1];
|
2296 | }
|
2297 | else {
|
2298 | return null;
|
2299 | }
|
2300 | };
|
2301 |
|
2302 | TransportManager.globalTransportInitialized_ = false;
|
2303 | return TransportManager;
|
2304 | }());
|
2305 |
|
2306 |
|
2307 |
|
2308 |
|
2309 |
|
2310 |
|
2311 |
|
2312 |
|
2313 |
|
2314 |
|
2315 |
|
2316 |
|
2317 |
|
2318 |
|
2319 |
|
2320 |
|
2321 |
|
2322 |
|
2323 | var UPGRADE_TIMEOUT = 60000;
|
2324 |
|
2325 |
|
2326 | var DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;
|
2327 |
|
2328 |
|
2329 |
|
2330 | var BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
|
2331 | var BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
|
2332 | var MESSAGE_TYPE = 't';
|
2333 | var MESSAGE_DATA = 'd';
|
2334 | var CONTROL_SHUTDOWN = 's';
|
2335 | var CONTROL_RESET = 'r';
|
2336 | var CONTROL_ERROR = 'e';
|
2337 | var CONTROL_PONG = 'o';
|
2338 | var SWITCH_ACK = 'a';
|
2339 | var END_TRANSMISSION = 'n';
|
2340 | var PING = 'p';
|
2341 | var SERVER_HELLO = 'h';
|
2342 |
|
2343 |
|
2344 |
|
2345 |
|
2346 | var Connection = (function () {
|
2347 | |
2348 |
|
2349 |
|
2350 |
|
2351 |
|
2352 |
|
2353 |
|
2354 |
|
2355 |
|
2356 |
|
2357 |
|
2358 |
|
2359 | function Connection(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
|
2360 | this.id = id;
|
2361 | this.repoInfo_ = repoInfo_;
|
2362 | this.applicationId_ = applicationId_;
|
2363 | this.appCheckToken_ = appCheckToken_;
|
2364 | this.authToken_ = authToken_;
|
2365 | this.onMessage_ = onMessage_;
|
2366 | this.onReady_ = onReady_;
|
2367 | this.onDisconnect_ = onDisconnect_;
|
2368 | this.onKill_ = onKill_;
|
2369 | this.lastSessionId = lastSessionId;
|
2370 | this.connectionCount = 0;
|
2371 | this.pendingDataMessages = [];
|
2372 | this.state_ = 0 ;
|
2373 | this.log_ = logWrapper('c:' + this.id + ':');
|
2374 | this.transportManager_ = new TransportManager(repoInfo_);
|
2375 | this.log_('Connection created');
|
2376 | this.start_();
|
2377 | }
|
2378 | |
2379 |
|
2380 |
|
2381 | Connection.prototype.start_ = function () {
|
2382 | var _this = this;
|
2383 | var conn = this.transportManager_.initialTransport();
|
2384 | this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
|
2385 |
|
2386 |
|
2387 | this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;
|
2388 | var onMessageReceived = this.connReceiver_(this.conn_);
|
2389 | var onConnectionLost = this.disconnReceiver_(this.conn_);
|
2390 | this.tx_ = this.conn_;
|
2391 | this.rx_ = this.conn_;
|
2392 | this.secondaryConn_ = null;
|
2393 | this.isHealthy_ = false;
|
2394 | |
2395 |
|
2396 |
|
2397 |
|
2398 |
|
2399 |
|
2400 | setTimeout(function () {
|
2401 |
|
2402 | _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);
|
2403 | }, Math.floor(0));
|
2404 | var healthyTimeoutMS = conn['healthyTimeout'] || 0;
|
2405 | if (healthyTimeoutMS > 0) {
|
2406 | this.healthyTimeout_ = setTimeoutNonBlocking(function () {
|
2407 | _this.healthyTimeout_ = null;
|
2408 | if (!_this.isHealthy_) {
|
2409 | if (_this.conn_ &&
|
2410 | _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
|
2411 | _this.log_('Connection exceeded healthy timeout but has received ' +
|
2412 | _this.conn_.bytesReceived +
|
2413 | ' bytes. Marking connection healthy.');
|
2414 | _this.isHealthy_ = true;
|
2415 | _this.conn_.markConnectionHealthy();
|
2416 | }
|
2417 | else if (_this.conn_ &&
|
2418 | _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
|
2419 | _this.log_('Connection exceeded healthy timeout but has sent ' +
|
2420 | _this.conn_.bytesSent +
|
2421 | ' bytes. Leaving connection alive.');
|
2422 |
|
2423 |
|
2424 | }
|
2425 | else {
|
2426 | _this.log_('Closing unhealthy connection after timeout.');
|
2427 | _this.close();
|
2428 | }
|
2429 | }
|
2430 |
|
2431 | }, Math.floor(healthyTimeoutMS));
|
2432 | }
|
2433 | };
|
2434 | Connection.prototype.nextTransportId_ = function () {
|
2435 | return 'c:' + this.id + ':' + this.connectionCount++;
|
2436 | };
|
2437 | Connection.prototype.disconnReceiver_ = function (conn) {
|
2438 | var _this = this;
|
2439 | return function (everConnected) {
|
2440 | if (conn === _this.conn_) {
|
2441 | _this.onConnectionLost_(everConnected);
|
2442 | }
|
2443 | else if (conn === _this.secondaryConn_) {
|
2444 | _this.log_('Secondary connection lost.');
|
2445 | _this.onSecondaryConnectionLost_();
|
2446 | }
|
2447 | else {
|
2448 | _this.log_('closing an old connection');
|
2449 | }
|
2450 | };
|
2451 | };
|
2452 | Connection.prototype.connReceiver_ = function (conn) {
|
2453 | var _this = this;
|
2454 | return function (message) {
|
2455 | if (_this.state_ !== 2 ) {
|
2456 | if (conn === _this.rx_) {
|
2457 | _this.onPrimaryMessageReceived_(message);
|
2458 | }
|
2459 | else if (conn === _this.secondaryConn_) {
|
2460 | _this.onSecondaryMessageReceived_(message);
|
2461 | }
|
2462 | else {
|
2463 | _this.log_('message on old connection');
|
2464 | }
|
2465 | }
|
2466 | };
|
2467 | };
|
2468 | |
2469 |
|
2470 |
|
2471 | Connection.prototype.sendRequest = function (dataMsg) {
|
2472 |
|
2473 | var msg = { t: 'd', d: dataMsg };
|
2474 | this.sendData_(msg);
|
2475 | };
|
2476 | Connection.prototype.tryCleanupConnection = function () {
|
2477 | if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
|
2478 | this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);
|
2479 | this.conn_ = this.secondaryConn_;
|
2480 | this.secondaryConn_ = null;
|
2481 |
|
2482 | }
|
2483 | };
|
2484 | Connection.prototype.onSecondaryControl_ = function (controlData) {
|
2485 | if (MESSAGE_TYPE in controlData) {
|
2486 | var cmd = controlData[MESSAGE_TYPE];
|
2487 | if (cmd === SWITCH_ACK) {
|
2488 | this.upgradeIfSecondaryHealthy_();
|
2489 | }
|
2490 | else if (cmd === CONTROL_RESET) {
|
2491 |
|
2492 | this.log_('Got a reset on secondary, closing it');
|
2493 | this.secondaryConn_.close();
|
2494 |
|
2495 | if (this.tx_ === this.secondaryConn_ ||
|
2496 | this.rx_ === this.secondaryConn_) {
|
2497 | this.close();
|
2498 | }
|
2499 | }
|
2500 | else if (cmd === CONTROL_PONG) {
|
2501 | this.log_('got pong on secondary.');
|
2502 | this.secondaryResponsesRequired_--;
|
2503 | this.upgradeIfSecondaryHealthy_();
|
2504 | }
|
2505 | }
|
2506 | };
|
2507 | Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {
|
2508 | var layer = requireKey('t', parsedData);
|
2509 | var data = requireKey('d', parsedData);
|
2510 | if (layer === 'c') {
|
2511 | this.onSecondaryControl_(data);
|
2512 | }
|
2513 | else if (layer === 'd') {
|
2514 |
|
2515 | this.pendingDataMessages.push(data);
|
2516 | }
|
2517 | else {
|
2518 | throw new Error('Unknown protocol layer: ' + layer);
|
2519 | }
|
2520 | };
|
2521 | Connection.prototype.upgradeIfSecondaryHealthy_ = function () {
|
2522 | if (this.secondaryResponsesRequired_ <= 0) {
|
2523 | this.log_('Secondary connection is healthy.');
|
2524 | this.isHealthy_ = true;
|
2525 | this.secondaryConn_.markConnectionHealthy();
|
2526 | this.proceedWithUpgrade_();
|
2527 | }
|
2528 | else {
|
2529 |
|
2530 | this.log_('sending ping on secondary.');
|
2531 | this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });
|
2532 | }
|
2533 | };
|
2534 | Connection.prototype.proceedWithUpgrade_ = function () {
|
2535 |
|
2536 | this.secondaryConn_.start();
|
2537 |
|
2538 | this.log_('sending client ack on secondary');
|
2539 | this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });
|
2540 |
|
2541 |
|
2542 | this.log_('Ending transmission on primary');
|
2543 | this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });
|
2544 | this.tx_ = this.secondaryConn_;
|
2545 | this.tryCleanupConnection();
|
2546 | };
|
2547 | Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {
|
2548 |
|
2549 | var layer = requireKey('t', parsedData);
|
2550 | var data = requireKey('d', parsedData);
|
2551 | if (layer === 'c') {
|
2552 | this.onControl_(data);
|
2553 | }
|
2554 | else if (layer === 'd') {
|
2555 | this.onDataMessage_(data);
|
2556 | }
|
2557 | };
|
2558 | Connection.prototype.onDataMessage_ = function (message) {
|
2559 | this.onPrimaryResponse_();
|
2560 |
|
2561 | this.onMessage_(message);
|
2562 | };
|
2563 | Connection.prototype.onPrimaryResponse_ = function () {
|
2564 | if (!this.isHealthy_) {
|
2565 | this.primaryResponsesRequired_--;
|
2566 | if (this.primaryResponsesRequired_ <= 0) {
|
2567 | this.log_('Primary connection is healthy.');
|
2568 | this.isHealthy_ = true;
|
2569 | this.conn_.markConnectionHealthy();
|
2570 | }
|
2571 | }
|
2572 | };
|
2573 | Connection.prototype.onControl_ = function (controlData) {
|
2574 | var cmd = requireKey(MESSAGE_TYPE, controlData);
|
2575 | if (MESSAGE_DATA in controlData) {
|
2576 | var payload = controlData[MESSAGE_DATA];
|
2577 | if (cmd === SERVER_HELLO) {
|
2578 | var handshakePayload = tslib.__assign({}, payload);
|
2579 | if (this.repoInfo_.isUsingEmulator) {
|
2580 |
|
2581 | handshakePayload.h = this.repoInfo_.host;
|
2582 | }
|
2583 | this.onHandshake_(handshakePayload);
|
2584 | }
|
2585 | else if (cmd === END_TRANSMISSION) {
|
2586 | this.log_('recvd end transmission on primary');
|
2587 | this.rx_ = this.secondaryConn_;
|
2588 | for (var i = 0; i < this.pendingDataMessages.length; ++i) {
|
2589 | this.onDataMessage_(this.pendingDataMessages[i]);
|
2590 | }
|
2591 | this.pendingDataMessages = [];
|
2592 | this.tryCleanupConnection();
|
2593 | }
|
2594 | else if (cmd === CONTROL_SHUTDOWN) {
|
2595 |
|
2596 |
|
2597 | this.onConnectionShutdown_(payload);
|
2598 | }
|
2599 | else if (cmd === CONTROL_RESET) {
|
2600 |
|
2601 | this.onReset_(payload);
|
2602 | }
|
2603 | else if (cmd === CONTROL_ERROR) {
|
2604 | error('Server Error: ' + payload);
|
2605 | }
|
2606 | else if (cmd === CONTROL_PONG) {
|
2607 | this.log_('got pong on primary.');
|
2608 | this.onPrimaryResponse_();
|
2609 | this.sendPingOnPrimaryIfNecessary_();
|
2610 | }
|
2611 | else {
|
2612 | error('Unknown control packet command: ' + cmd);
|
2613 | }
|
2614 | }
|
2615 | };
|
2616 | |
2617 |
|
2618 |
|
2619 | Connection.prototype.onHandshake_ = function (handshake) {
|
2620 | var timestamp = handshake.ts;
|
2621 | var version = handshake.v;
|
2622 | var host = handshake.h;
|
2623 | this.sessionId = handshake.s;
|
2624 | this.repoInfo_.host = host;
|
2625 |
|
2626 | if (this.state_ === 0 ) {
|
2627 | this.conn_.start();
|
2628 | this.onConnectionEstablished_(this.conn_, timestamp);
|
2629 | if (PROTOCOL_VERSION !== version) {
|
2630 | warn('Protocol version mismatch detected');
|
2631 | }
|
2632 |
|
2633 | this.tryStartUpgrade_();
|
2634 | }
|
2635 | };
|
2636 | Connection.prototype.tryStartUpgrade_ = function () {
|
2637 | var conn = this.transportManager_.upgradeTransport();
|
2638 | if (conn) {
|
2639 | this.startUpgrade_(conn);
|
2640 | }
|
2641 | };
|
2642 | Connection.prototype.startUpgrade_ = function (conn) {
|
2643 | var _this = this;
|
2644 | this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
|
2645 |
|
2646 |
|
2647 | this.secondaryResponsesRequired_ =
|
2648 | conn['responsesRequiredToBeHealthy'] || 0;
|
2649 | var onMessage = this.connReceiver_(this.secondaryConn_);
|
2650 | var onDisconnect = this.disconnReceiver_(this.secondaryConn_);
|
2651 | this.secondaryConn_.open(onMessage, onDisconnect);
|
2652 |
|
2653 | setTimeoutNonBlocking(function () {
|
2654 | if (_this.secondaryConn_) {
|
2655 | _this.log_('Timed out trying to upgrade.');
|
2656 | _this.secondaryConn_.close();
|
2657 | }
|
2658 | }, Math.floor(UPGRADE_TIMEOUT));
|
2659 | };
|
2660 | Connection.prototype.onReset_ = function (host) {
|
2661 | this.log_('Reset packet received. New host: ' + host);
|
2662 | this.repoInfo_.host = host;
|
2663 |
|
2664 |
|
2665 | if (this.state_ === 1 ) {
|
2666 | this.close();
|
2667 | }
|
2668 | else {
|
2669 |
|
2670 | this.closeConnections_();
|
2671 | this.start_();
|
2672 | }
|
2673 | };
|
2674 | Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {
|
2675 | var _this = this;
|
2676 | this.log_('Realtime connection established.');
|
2677 | this.conn_ = conn;
|
2678 | this.state_ = 1 ;
|
2679 | if (this.onReady_) {
|
2680 | this.onReady_(timestamp, this.sessionId);
|
2681 | this.onReady_ = null;
|
2682 | }
|
2683 |
|
2684 |
|
2685 | if (this.primaryResponsesRequired_ === 0) {
|
2686 | this.log_('Primary connection is healthy.');
|
2687 | this.isHealthy_ = true;
|
2688 | }
|
2689 | else {
|
2690 | setTimeoutNonBlocking(function () {
|
2691 | _this.sendPingOnPrimaryIfNecessary_();
|
2692 | }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
|
2693 | }
|
2694 | };
|
2695 | Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {
|
2696 |
|
2697 | if (!this.isHealthy_ && this.state_ === 1 ) {
|
2698 | this.log_('sending ping on primary.');
|
2699 | this.sendData_({ t: 'c', d: { t: PING, d: {} } });
|
2700 | }
|
2701 | };
|
2702 | Connection.prototype.onSecondaryConnectionLost_ = function () {
|
2703 | var conn = this.secondaryConn_;
|
2704 | this.secondaryConn_ = null;
|
2705 | if (this.tx_ === conn || this.rx_ === conn) {
|
2706 |
|
2707 | this.close();
|
2708 | }
|
2709 | };
|
2710 | |
2711 |
|
2712 |
|
2713 |
|
2714 | Connection.prototype.onConnectionLost_ = function (everConnected) {
|
2715 | this.conn_ = null;
|
2716 |
|
2717 |
|
2718 | if (!everConnected && this.state_ === 0 ) {
|
2719 | this.log_('Realtime connection failed.');
|
2720 |
|
2721 | if (this.repoInfo_.isCacheableHost()) {
|
2722 | PersistentStorage.remove('host:' + this.repoInfo_.host);
|
2723 |
|
2724 | this.repoInfo_.internalHost = this.repoInfo_.host;
|
2725 | }
|
2726 | }
|
2727 | else if (this.state_ === 1 ) {
|
2728 | this.log_('Realtime connection lost.');
|
2729 | }
|
2730 | this.close();
|
2731 | };
|
2732 | Connection.prototype.onConnectionShutdown_ = function (reason) {
|
2733 | this.log_('Connection shutdown command received. Shutting down...');
|
2734 | if (this.onKill_) {
|
2735 | this.onKill_(reason);
|
2736 | this.onKill_ = null;
|
2737 | }
|
2738 |
|
2739 |
|
2740 | this.onDisconnect_ = null;
|
2741 | this.close();
|
2742 | };
|
2743 | Connection.prototype.sendData_ = function (data) {
|
2744 | if (this.state_ !== 1 ) {
|
2745 | throw 'Connection is not connected';
|
2746 | }
|
2747 | else {
|
2748 | this.tx_.send(data);
|
2749 | }
|
2750 | };
|
2751 | |
2752 |
|
2753 |
|
2754 | Connection.prototype.close = function () {
|
2755 | if (this.state_ !== 2 ) {
|
2756 | this.log_('Closing realtime connection.');
|
2757 | this.state_ = 2 ;
|
2758 | this.closeConnections_();
|
2759 | if (this.onDisconnect_) {
|
2760 | this.onDisconnect_();
|
2761 | this.onDisconnect_ = null;
|
2762 | }
|
2763 | }
|
2764 | };
|
2765 | Connection.prototype.closeConnections_ = function () {
|
2766 | this.log_('Shutting down all connections');
|
2767 | if (this.conn_) {
|
2768 | this.conn_.close();
|
2769 | this.conn_ = null;
|
2770 | }
|
2771 | if (this.secondaryConn_) {
|
2772 | this.secondaryConn_.close();
|
2773 | this.secondaryConn_ = null;
|
2774 | }
|
2775 | if (this.healthyTimeout_) {
|
2776 | clearTimeout(this.healthyTimeout_);
|
2777 | this.healthyTimeout_ = null;
|
2778 | }
|
2779 | };
|
2780 | return Connection;
|
2781 | }());
|
2782 |
|
2783 |
|
2784 |
|
2785 |
|
2786 |
|
2787 |
|
2788 |
|
2789 |
|
2790 |
|
2791 |
|
2792 |
|
2793 |
|
2794 |
|
2795 |
|
2796 |
|
2797 |
|
2798 |
|
2799 |
|
2800 |
|
2801 |
|
2802 |
|
2803 |
|
2804 |
|
2805 | var ServerActions = (function () {
|
2806 | function ServerActions() {
|
2807 | }
|
2808 | ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };
|
2809 | ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };
|
2810 | |
2811 |
|
2812 |
|
2813 |
|
2814 | ServerActions.prototype.refreshAuthToken = function (token) { };
|
2815 | |
2816 |
|
2817 |
|
2818 |
|
2819 | ServerActions.prototype.refreshAppCheckToken = function (token) { };
|
2820 | ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };
|
2821 | ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };
|
2822 | ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };
|
2823 | ServerActions.prototype.reportStats = function (stats) { };
|
2824 | return ServerActions;
|
2825 | }());
|
2826 |
|
2827 |
|
2828 |
|
2829 |
|
2830 |
|
2831 |
|
2832 |
|
2833 |
|
2834 |
|
2835 |
|
2836 |
|
2837 |
|
2838 |
|
2839 |
|
2840 |
|
2841 |
|
2842 |
|
2843 |
|
2844 |
|
2845 |
|
2846 |
|
2847 | var EventEmitter = (function () {
|
2848 | function EventEmitter(allowedEvents_) {
|
2849 | this.allowedEvents_ = allowedEvents_;
|
2850 | this.listeners_ = {};
|
2851 | util.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');
|
2852 | }
|
2853 | |
2854 |
|
2855 |
|
2856 | EventEmitter.prototype.trigger = function (eventType) {
|
2857 | var varArgs = [];
|
2858 | for (var _i = 1; _i < arguments.length; _i++) {
|
2859 | varArgs[_i - 1] = arguments[_i];
|
2860 | }
|
2861 | if (Array.isArray(this.listeners_[eventType])) {
|
2862 |
|
2863 | var listeners = tslib.__spreadArray([], tslib.__read(this.listeners_[eventType]), false);
|
2864 | for (var i = 0; i < listeners.length; i++) {
|
2865 | listeners[i].callback.apply(listeners[i].context, varArgs);
|
2866 | }
|
2867 | }
|
2868 | };
|
2869 | EventEmitter.prototype.on = function (eventType, callback, context) {
|
2870 | this.validateEventType_(eventType);
|
2871 | this.listeners_[eventType] = this.listeners_[eventType] || [];
|
2872 | this.listeners_[eventType].push({ callback: callback, context: context });
|
2873 | var eventData = this.getInitialEvent(eventType);
|
2874 | if (eventData) {
|
2875 | callback.apply(context, eventData);
|
2876 | }
|
2877 | };
|
2878 | EventEmitter.prototype.off = function (eventType, callback, context) {
|
2879 | this.validateEventType_(eventType);
|
2880 | var listeners = this.listeners_[eventType] || [];
|
2881 | for (var i = 0; i < listeners.length; i++) {
|
2882 | if (listeners[i].callback === callback &&
|
2883 | (!context || context === listeners[i].context)) {
|
2884 | listeners.splice(i, 1);
|
2885 | return;
|
2886 | }
|
2887 | }
|
2888 | };
|
2889 | EventEmitter.prototype.validateEventType_ = function (eventType) {
|
2890 | util.assert(this.allowedEvents_.find(function (et) {
|
2891 | return et === eventType;
|
2892 | }), 'Unknown event: ' + eventType);
|
2893 | };
|
2894 | return EventEmitter;
|
2895 | }());
|
2896 |
|
2897 |
|
2898 |
|
2899 |
|
2900 |
|
2901 |
|
2902 |
|
2903 |
|
2904 |
|
2905 |
|
2906 |
|
2907 |
|
2908 |
|
2909 |
|
2910 |
|
2911 |
|
2912 |
|
2913 |
|
2914 |
|
2915 |
|
2916 |
|
2917 |
|
2918 |
|
2919 |
|
2920 | var OnlineMonitor = (function (_super) {
|
2921 | tslib.__extends(OnlineMonitor, _super);
|
2922 | function OnlineMonitor() {
|
2923 | var _this = _super.call(this, ['online']) || this;
|
2924 | _this.online_ = true;
|
2925 |
|
2926 |
|
2927 |
|
2928 |
|
2929 | if (typeof window !== 'undefined' &&
|
2930 | typeof window.addEventListener !== 'undefined' &&
|
2931 | !util.isMobileCordova()) {
|
2932 | window.addEventListener('online', function () {
|
2933 | if (!_this.online_) {
|
2934 | _this.online_ = true;
|
2935 | _this.trigger('online', true);
|
2936 | }
|
2937 | }, false);
|
2938 | window.addEventListener('offline', function () {
|
2939 | if (_this.online_) {
|
2940 | _this.online_ = false;
|
2941 | _this.trigger('online', false);
|
2942 | }
|
2943 | }, false);
|
2944 | }
|
2945 | return _this;
|
2946 | }
|
2947 | OnlineMonitor.getInstance = function () {
|
2948 | return new OnlineMonitor();
|
2949 | };
|
2950 | OnlineMonitor.prototype.getInitialEvent = function (eventType) {
|
2951 | util.assert(eventType === 'online', 'Unknown event type: ' + eventType);
|
2952 | return [this.online_];
|
2953 | };
|
2954 | OnlineMonitor.prototype.currentlyOnline = function () {
|
2955 | return this.online_;
|
2956 | };
|
2957 | return OnlineMonitor;
|
2958 | }(EventEmitter));
|
2959 |
|
2960 |
|
2961 |
|
2962 |
|
2963 |
|
2964 |
|
2965 |
|
2966 |
|
2967 |
|
2968 |
|
2969 |
|
2970 |
|
2971 |
|
2972 |
|
2973 |
|
2974 |
|
2975 |
|
2976 |
|
2977 | var MAX_PATH_DEPTH = 32;
|
2978 |
|
2979 | var MAX_PATH_LENGTH_BYTES = 768;
|
2980 |
|
2981 |
|
2982 |
|
2983 |
|
2984 |
|
2985 | var Path = (function () {
|
2986 | |
2987 |
|
2988 |
|
2989 |
|
2990 | function Path(pathOrString, pieceNum) {
|
2991 | if (pieceNum === void 0) {
|
2992 | this.pieces_ = pathOrString.split('/');
|
2993 |
|
2994 | var copyTo = 0;
|
2995 | for (var i = 0; i < this.pieces_.length; i++) {
|
2996 | if (this.pieces_[i].length > 0) {
|
2997 | this.pieces_[copyTo] = this.pieces_[i];
|
2998 | copyTo++;
|
2999 | }
|
3000 | }
|
3001 | this.pieces_.length = copyTo;
|
3002 | this.pieceNum_ = 0;
|
3003 | }
|
3004 | else {
|
3005 | this.pieces_ = pathOrString;
|
3006 | this.pieceNum_ = pieceNum;
|
3007 | }
|
3008 | }
|
3009 | Path.prototype.toString = function () {
|
3010 | var pathString = '';
|
3011 | for (var i = this.pieceNum_; i < this.pieces_.length; i++) {
|
3012 | if (this.pieces_[i] !== '') {
|
3013 | pathString += '/' + this.pieces_[i];
|
3014 | }
|
3015 | }
|
3016 | return pathString || '/';
|
3017 | };
|
3018 | return Path;
|
3019 | }());
|
3020 | function newEmptyPath() {
|
3021 | return new Path('');
|
3022 | }
|
3023 | function pathGetFront(path) {
|
3024 | if (path.pieceNum_ >= path.pieces_.length) {
|
3025 | return null;
|
3026 | }
|
3027 | return path.pieces_[path.pieceNum_];
|
3028 | }
|
3029 |
|
3030 |
|
3031 |
|
3032 | function pathGetLength(path) {
|
3033 | return path.pieces_.length - path.pieceNum_;
|
3034 | }
|
3035 | function pathPopFront(path) {
|
3036 | var pieceNum = path.pieceNum_;
|
3037 | if (pieceNum < path.pieces_.length) {
|
3038 | pieceNum++;
|
3039 | }
|
3040 | return new Path(path.pieces_, pieceNum);
|
3041 | }
|
3042 | function pathGetBack(path) {
|
3043 | if (path.pieceNum_ < path.pieces_.length) {
|
3044 | return path.pieces_[path.pieces_.length - 1];
|
3045 | }
|
3046 | return null;
|
3047 | }
|
3048 | function pathToUrlEncodedString(path) {
|
3049 | var pathString = '';
|
3050 | for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
|
3051 | if (path.pieces_[i] !== '') {
|
3052 | pathString += '/' + encodeURIComponent(String(path.pieces_[i]));
|
3053 | }
|
3054 | }
|
3055 | return pathString || '/';
|
3056 | }
|
3057 |
|
3058 |
|
3059 |
|
3060 |
|
3061 | function pathSlice(path, begin) {
|
3062 | if (begin === void 0) { begin = 0; }
|
3063 | return path.pieces_.slice(path.pieceNum_ + begin);
|
3064 | }
|
3065 | function pathParent(path) {
|
3066 | if (path.pieceNum_ >= path.pieces_.length) {
|
3067 | return null;
|
3068 | }
|
3069 | var pieces = [];
|
3070 | for (var i = path.pieceNum_; i < path.pieces_.length - 1; i++) {
|
3071 | pieces.push(path.pieces_[i]);
|
3072 | }
|
3073 | return new Path(pieces, 0);
|
3074 | }
|
3075 | function pathChild(path, childPathObj) {
|
3076 | var pieces = [];
|
3077 | for (var i = path.pieceNum_; i < path.pieces_.length; i++) {
|
3078 | pieces.push(path.pieces_[i]);
|
3079 | }
|
3080 | if (childPathObj instanceof Path) {
|
3081 | for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {
|
3082 | pieces.push(childPathObj.pieces_[i]);
|
3083 | }
|
3084 | }
|
3085 | else {
|
3086 | var childPieces = childPathObj.split('/');
|
3087 | for (var i = 0; i < childPieces.length; i++) {
|
3088 | if (childPieces[i].length > 0) {
|
3089 | pieces.push(childPieces[i]);
|
3090 | }
|
3091 | }
|
3092 | }
|
3093 | return new Path(pieces, 0);
|
3094 | }
|
3095 |
|
3096 |
|
3097 |
|
3098 | function pathIsEmpty(path) {
|
3099 | return path.pieceNum_ >= path.pieces_.length;
|
3100 | }
|
3101 |
|
3102 |
|
3103 |
|
3104 | function newRelativePath(outerPath, innerPath) {
|
3105 | var outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
|
3106 | if (outer === null) {
|
3107 | return innerPath;
|
3108 | }
|
3109 | else if (outer === inner) {
|
3110 | return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
|
3111 | }
|
3112 | else {
|
3113 | throw new Error('INTERNAL ERROR: innerPath (' +
|
3114 | innerPath +
|
3115 | ') is not within ' +
|
3116 | 'outerPath (' +
|
3117 | outerPath +
|
3118 | ')');
|
3119 | }
|
3120 | }
|
3121 |
|
3122 |
|
3123 |
|
3124 | function pathCompare(left, right) {
|
3125 | var leftKeys = pathSlice(left, 0);
|
3126 | var rightKeys = pathSlice(right, 0);
|
3127 | for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
|
3128 | var cmp = nameCompare(leftKeys[i], rightKeys[i]);
|
3129 | if (cmp !== 0) {
|
3130 | return cmp;
|
3131 | }
|
3132 | }
|
3133 | if (leftKeys.length === rightKeys.length) {
|
3134 | return 0;
|
3135 | }
|
3136 | return leftKeys.length < rightKeys.length ? -1 : 1;
|
3137 | }
|
3138 |
|
3139 |
|
3140 |
|
3141 | function pathEquals(path, other) {
|
3142 | if (pathGetLength(path) !== pathGetLength(other)) {
|
3143 | return false;
|
3144 | }
|
3145 | for (var i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {
|
3146 | if (path.pieces_[i] !== other.pieces_[j]) {
|
3147 | return false;
|
3148 | }
|
3149 | }
|
3150 | return true;
|
3151 | }
|
3152 |
|
3153 |
|
3154 |
|
3155 | function pathContains(path, other) {
|
3156 | var i = path.pieceNum_;
|
3157 | var j = other.pieceNum_;
|
3158 | if (pathGetLength(path) > pathGetLength(other)) {
|
3159 | return false;
|
3160 | }
|
3161 | while (i < path.pieces_.length) {
|
3162 | if (path.pieces_[i] !== other.pieces_[j]) {
|
3163 | return false;
|
3164 | }
|
3165 | ++i;
|
3166 | ++j;
|
3167 | }
|
3168 | return true;
|
3169 | }
|
3170 |
|
3171 |
|
3172 |
|
3173 |
|
3174 |
|
3175 |
|
3176 |
|
3177 |
|
3178 |
|
3179 |
|
3180 | var ValidationPath = (function () {
|
3181 | |
3182 |
|
3183 |
|
3184 |
|
3185 | function ValidationPath(path, errorPrefix_) {
|
3186 | this.errorPrefix_ = errorPrefix_;
|
3187 | this.parts_ = pathSlice(path, 0);
|
3188 |
|
3189 | this.byteLength_ = Math.max(1, this.parts_.length);
|
3190 | for (var i = 0; i < this.parts_.length; i++) {
|
3191 | this.byteLength_ += util.stringLength(this.parts_[i]);
|
3192 | }
|
3193 | validationPathCheckValid(this);
|
3194 | }
|
3195 | return ValidationPath;
|
3196 | }());
|
3197 | function validationPathPush(validationPath, child) {
|
3198 |
|
3199 | if (validationPath.parts_.length > 0) {
|
3200 | validationPath.byteLength_ += 1;
|
3201 | }
|
3202 | validationPath.parts_.push(child);
|
3203 | validationPath.byteLength_ += util.stringLength(child);
|
3204 | validationPathCheckValid(validationPath);
|
3205 | }
|
3206 | function validationPathPop(validationPath) {
|
3207 | var last = validationPath.parts_.pop();
|
3208 | validationPath.byteLength_ -= util.stringLength(last);
|
3209 |
|
3210 | if (validationPath.parts_.length > 0) {
|
3211 | validationPath.byteLength_ -= 1;
|
3212 | }
|
3213 | }
|
3214 | function validationPathCheckValid(validationPath) {
|
3215 | if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
|
3216 | throw new Error(validationPath.errorPrefix_ +
|
3217 | 'has a key path longer than ' +
|
3218 | MAX_PATH_LENGTH_BYTES +
|
3219 | ' bytes (' +
|
3220 | validationPath.byteLength_ +
|
3221 | ').');
|
3222 | }
|
3223 | if (validationPath.parts_.length > MAX_PATH_DEPTH) {
|
3224 | throw new Error(validationPath.errorPrefix_ +
|
3225 | 'path specified exceeds the maximum depth that can be written (' +
|
3226 | MAX_PATH_DEPTH +
|
3227 | ') or object contains a cycle ' +
|
3228 | validationPathToErrorString(validationPath));
|
3229 | }
|
3230 | }
|
3231 |
|
3232 |
|
3233 |
|
3234 | function validationPathToErrorString(validationPath) {
|
3235 | if (validationPath.parts_.length === 0) {
|
3236 | return '';
|
3237 | }
|
3238 | return "in property '" + validationPath.parts_.join('.') + "'";
|
3239 | }
|
3240 |
|
3241 |
|
3242 |
|
3243 |
|
3244 |
|
3245 |
|
3246 |
|
3247 |
|
3248 |
|
3249 |
|
3250 |
|
3251 |
|
3252 |
|
3253 |
|
3254 |
|
3255 |
|
3256 |
|
3257 | var VisibilityMonitor = (function (_super) {
|
3258 | tslib.__extends(VisibilityMonitor, _super);
|
3259 | function VisibilityMonitor() {
|
3260 | var _this = _super.call(this, ['visible']) || this;
|
3261 | var hidden;
|
3262 | var visibilityChange;
|
3263 | if (typeof document !== 'undefined' &&
|
3264 | typeof document.addEventListener !== 'undefined') {
|
3265 | if (typeof document['hidden'] !== 'undefined') {
|
3266 |
|
3267 | visibilityChange = 'visibilitychange';
|
3268 | hidden = 'hidden';
|
3269 | }
|
3270 | else if (typeof document['mozHidden'] !== 'undefined') {
|
3271 | visibilityChange = 'mozvisibilitychange';
|
3272 | hidden = 'mozHidden';
|
3273 | }
|
3274 | else if (typeof document['msHidden'] !== 'undefined') {
|
3275 | visibilityChange = 'msvisibilitychange';
|
3276 | hidden = 'msHidden';
|
3277 | }
|
3278 | else if (typeof document['webkitHidden'] !== 'undefined') {
|
3279 | visibilityChange = 'webkitvisibilitychange';
|
3280 | hidden = 'webkitHidden';
|
3281 | }
|
3282 | }
|
3283 |
|
3284 |
|
3285 |
|
3286 |
|
3287 | _this.visible_ = true;
|
3288 | if (visibilityChange) {
|
3289 | document.addEventListener(visibilityChange, function () {
|
3290 | var visible = !document[hidden];
|
3291 | if (visible !== _this.visible_) {
|
3292 | _this.visible_ = visible;
|
3293 | _this.trigger('visible', visible);
|
3294 | }
|
3295 | }, false);
|
3296 | }
|
3297 | return _this;
|
3298 | }
|
3299 | VisibilityMonitor.getInstance = function () {
|
3300 | return new VisibilityMonitor();
|
3301 | };
|
3302 | VisibilityMonitor.prototype.getInitialEvent = function (eventType) {
|
3303 | util.assert(eventType === 'visible', 'Unknown event type: ' + eventType);
|
3304 | return [this.visible_];
|
3305 | };
|
3306 | return VisibilityMonitor;
|
3307 | }(EventEmitter));
|
3308 |
|
3309 |
|
3310 |
|
3311 |
|
3312 |
|
3313 |
|
3314 |
|
3315 |
|
3316 |
|
3317 |
|
3318 |
|
3319 |
|
3320 |
|
3321 |
|
3322 |
|
3323 |
|
3324 |
|
3325 | var RECONNECT_MIN_DELAY = 1000;
|
3326 | var RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000;
|
3327 | var RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000;
|
3328 | var RECONNECT_DELAY_MULTIPLIER = 1.3;
|
3329 | var RECONNECT_DELAY_RESET_TIMEOUT = 30000;
|
3330 | var SERVER_KILL_INTERRUPT_REASON = 'server_kill';
|
3331 |
|
3332 | var INVALID_TOKEN_THRESHOLD = 3;
|
3333 |
|
3334 |
|
3335 |
|
3336 |
|
3337 |
|
3338 |
|
3339 | var PersistentConnection = (function (_super) {
|
3340 | tslib.__extends(PersistentConnection, _super);
|
3341 | |
3342 |
|
3343 |
|
3344 |
|
3345 |
|
3346 | function PersistentConnection(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
|
3347 | var _this = _super.call(this) || this;
|
3348 | _this.repoInfo_ = repoInfo_;
|
3349 | _this.applicationId_ = applicationId_;
|
3350 | _this.onDataUpdate_ = onDataUpdate_;
|
3351 | _this.onConnectStatus_ = onConnectStatus_;
|
3352 | _this.onServerInfoUpdate_ = onServerInfoUpdate_;
|
3353 | _this.authTokenProvider_ = authTokenProvider_;
|
3354 | _this.appCheckTokenProvider_ = appCheckTokenProvider_;
|
3355 | _this.authOverride_ = authOverride_;
|
3356 |
|
3357 | _this.id = PersistentConnection.nextPersistentConnectionId_++;
|
3358 | _this.log_ = logWrapper('p:' + _this.id + ':');
|
3359 | _this.interruptReasons_ = {};
|
3360 | _this.listens = new Map();
|
3361 | _this.outstandingPuts_ = [];
|
3362 | _this.outstandingGets_ = [];
|
3363 | _this.outstandingPutCount_ = 0;
|
3364 | _this.outstandingGetCount_ = 0;
|
3365 | _this.onDisconnectRequestQueue_ = [];
|
3366 | _this.connected_ = false;
|
3367 | _this.reconnectDelay_ = RECONNECT_MIN_DELAY;
|
3368 | _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
|
3369 | _this.securityDebugCallback_ = null;
|
3370 | _this.lastSessionId = null;
|
3371 | _this.establishConnectionTimer_ = null;
|
3372 | _this.visible_ = false;
|
3373 |
|
3374 | _this.requestCBHash_ = {};
|
3375 | _this.requestNumber_ = 0;
|
3376 | _this.realtime_ = null;
|
3377 | _this.authToken_ = null;
|
3378 | _this.appCheckToken_ = null;
|
3379 | _this.forceTokenRefresh_ = false;
|
3380 | _this.invalidAuthTokenCount_ = 0;
|
3381 | _this.invalidAppCheckTokenCount_ = 0;
|
3382 | _this.firstConnection_ = true;
|
3383 | _this.lastConnectionAttemptTime_ = null;
|
3384 | _this.lastConnectionEstablishedTime_ = null;
|
3385 | if (authOverride_ && !util.isNodeSdk()) {
|
3386 | throw new Error('Auth override specified in options, but not supported on non Node.js platforms');
|
3387 | }
|
3388 | VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);
|
3389 | if (repoInfo_.host.indexOf('fblocal') === -1) {
|
3390 | OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);
|
3391 | }
|
3392 | return _this;
|
3393 | }
|
3394 | PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {
|
3395 | var curReqNum = ++this.requestNumber_;
|
3396 | var msg = { r: curReqNum, a: action, b: body };
|
3397 | this.log_(util.stringify(msg));
|
3398 | util.assert(this.connected_, "sendRequest call when we're not connected not allowed.");
|
3399 | this.realtime_.sendRequest(msg);
|
3400 | if (onResponse) {
|
3401 | this.requestCBHash_[curReqNum] = onResponse;
|
3402 | }
|
3403 | };
|
3404 | PersistentConnection.prototype.get = function (query) {
|
3405 | this.initConnection_();
|
3406 | var deferred = new util.Deferred();
|
3407 | var request = {
|
3408 | p: query._path.toString(),
|
3409 | q: query._queryObject
|
3410 | };
|
3411 | var outstandingGet = {
|
3412 | action: 'g',
|
3413 | request: request,
|
3414 | onComplete: function (message) {
|
3415 | var payload = message['d'];
|
3416 | if (message['s'] === 'ok') {
|
3417 | deferred.resolve(payload);
|
3418 | }
|
3419 | else {
|
3420 | deferred.reject(payload);
|
3421 | }
|
3422 | }
|
3423 | };
|
3424 | this.outstandingGets_.push(outstandingGet);
|
3425 | this.outstandingGetCount_++;
|
3426 | var index = this.outstandingGets_.length - 1;
|
3427 | if (this.connected_) {
|
3428 | this.sendGet_(index);
|
3429 | }
|
3430 | return deferred.promise;
|
3431 | };
|
3432 | PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {
|
3433 | this.initConnection_();
|
3434 | var queryId = query._queryIdentifier;
|
3435 | var pathString = query._path.toString();
|
3436 | this.log_('Listen called for ' + pathString + ' ' + queryId);
|
3437 | if (!this.listens.has(pathString)) {
|
3438 | this.listens.set(pathString, new Map());
|
3439 | }
|
3440 | util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');
|
3441 | util.assert(!this.listens.get(pathString).has(queryId), "listen() called twice for same path/queryId.");
|
3442 | var listenSpec = {
|
3443 | onComplete: onComplete,
|
3444 | hashFn: currentHashFn,
|
3445 | query: query,
|
3446 | tag: tag
|
3447 | };
|
3448 | this.listens.get(pathString).set(queryId, listenSpec);
|
3449 | if (this.connected_) {
|
3450 | this.sendListen_(listenSpec);
|
3451 | }
|
3452 | };
|
3453 | PersistentConnection.prototype.sendGet_ = function (index) {
|
3454 | var _this = this;
|
3455 | var get = this.outstandingGets_[index];
|
3456 | this.sendRequest('g', get.request, function (message) {
|
3457 | delete _this.outstandingGets_[index];
|
3458 | _this.outstandingGetCount_--;
|
3459 | if (_this.outstandingGetCount_ === 0) {
|
3460 | _this.outstandingGets_ = [];
|
3461 | }
|
3462 | if (get.onComplete) {
|
3463 | get.onComplete(message);
|
3464 | }
|
3465 | });
|
3466 | };
|
3467 | PersistentConnection.prototype.sendListen_ = function (listenSpec) {
|
3468 | var _this = this;
|
3469 | var query = listenSpec.query;
|
3470 | var pathString = query._path.toString();
|
3471 | var queryId = query._queryIdentifier;
|
3472 | this.log_('Listen on ' + pathString + ' for ' + queryId);
|
3473 | var req = { p: pathString };
|
3474 | var action = 'q';
|
3475 |
|
3476 | if (listenSpec.tag) {
|
3477 | req['q'] = query._queryObject;
|
3478 | req['t'] = listenSpec.tag;
|
3479 | }
|
3480 | req[ 'h'] = listenSpec.hashFn();
|
3481 | this.sendRequest(action, req, function (message) {
|
3482 | var payload = message[ 'd'];
|
3483 | var status = message[ 's'];
|
3484 |
|
3485 | PersistentConnection.warnOnListenWarnings_(payload, query);
|
3486 | var currentListenSpec = _this.listens.get(pathString) &&
|
3487 | _this.listens.get(pathString).get(queryId);
|
3488 |
|
3489 | if (currentListenSpec === listenSpec) {
|
3490 | _this.log_('listen response', message);
|
3491 | if (status !== 'ok') {
|
3492 | _this.removeListen_(pathString, queryId);
|
3493 | }
|
3494 | if (listenSpec.onComplete) {
|
3495 | listenSpec.onComplete(status, payload);
|
3496 | }
|
3497 | }
|
3498 | });
|
3499 | };
|
3500 | PersistentConnection.warnOnListenWarnings_ = function (payload, query) {
|
3501 | if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {
|
3502 |
|
3503 | var warnings = util.safeGet(payload, 'w');
|
3504 | if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {
|
3505 | var indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
|
3506 | var indexPath = query._path.toString();
|
3507 | warn("Using an unspecified index. Your data will be downloaded and " +
|
3508 | "filtered on the client. Consider adding ".concat(indexSpec, " at ") +
|
3509 | "".concat(indexPath, " to your security rules for better performance."));
|
3510 | }
|
3511 | }
|
3512 | };
|
3513 | PersistentConnection.prototype.refreshAuthToken = function (token) {
|
3514 | this.authToken_ = token;
|
3515 | this.log_('Auth token refreshed');
|
3516 | if (this.authToken_) {
|
3517 | this.tryAuth();
|
3518 | }
|
3519 | else {
|
3520 |
|
3521 |
|
3522 | if (this.connected_) {
|
3523 | this.sendRequest('unauth', {}, function () { });
|
3524 | }
|
3525 | }
|
3526 | this.reduceReconnectDelayIfAdminCredential_(token);
|
3527 | };
|
3528 | PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {
|
3529 |
|
3530 |
|
3531 | var isFirebaseSecret = credential && credential.length === 40;
|
3532 | if (isFirebaseSecret || util.isAdmin(credential)) {
|
3533 | this.log_('Admin auth credential detected. Reducing max reconnect time.');
|
3534 | this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
|
3535 | }
|
3536 | };
|
3537 | PersistentConnection.prototype.refreshAppCheckToken = function (token) {
|
3538 | this.appCheckToken_ = token;
|
3539 | this.log_('App check token refreshed');
|
3540 | if (this.appCheckToken_) {
|
3541 | this.tryAppCheck();
|
3542 | }
|
3543 | else {
|
3544 |
|
3545 |
|
3546 |
|
3547 | if (this.connected_) {
|
3548 | this.sendRequest('unappeck', {}, function () { });
|
3549 | }
|
3550 | }
|
3551 | };
|
3552 | |
3553 |
|
3554 |
|
3555 |
|
3556 | PersistentConnection.prototype.tryAuth = function () {
|
3557 | var _this = this;
|
3558 | if (this.connected_ && this.authToken_) {
|
3559 | var token_1 = this.authToken_;
|
3560 | var authMethod = util.isValidFormat(token_1) ? 'auth' : 'gauth';
|
3561 | var requestData = { cred: token_1 };
|
3562 | if (this.authOverride_ === null) {
|
3563 | requestData['noauth'] = true;
|
3564 | }
|
3565 | else if (typeof this.authOverride_ === 'object') {
|
3566 | requestData['authvar'] = this.authOverride_;
|
3567 | }
|
3568 | this.sendRequest(authMethod, requestData, function (res) {
|
3569 | var status = res[ 's'];
|
3570 | var data = res[ 'd'] || 'error';
|
3571 | if (_this.authToken_ === token_1) {
|
3572 | if (status === 'ok') {
|
3573 | _this.invalidAuthTokenCount_ = 0;
|
3574 | }
|
3575 | else {
|
3576 |
|
3577 | _this.onAuthRevoked_(status, data);
|
3578 | }
|
3579 | }
|
3580 | });
|
3581 | }
|
3582 | };
|
3583 | |
3584 |
|
3585 |
|
3586 |
|
3587 |
|
3588 | PersistentConnection.prototype.tryAppCheck = function () {
|
3589 | var _this = this;
|
3590 | if (this.connected_ && this.appCheckToken_) {
|
3591 | this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, function (res) {
|
3592 | var status = res[ 's'];
|
3593 | var data = res[ 'd'] || 'error';
|
3594 | if (status === 'ok') {
|
3595 | _this.invalidAppCheckTokenCount_ = 0;
|
3596 | }
|
3597 | else {
|
3598 | _this.onAppCheckRevoked_(status, data);
|
3599 | }
|
3600 | });
|
3601 | }
|
3602 | };
|
3603 | |
3604 |
|
3605 |
|
3606 | PersistentConnection.prototype.unlisten = function (query, tag) {
|
3607 | var pathString = query._path.toString();
|
3608 | var queryId = query._queryIdentifier;
|
3609 | this.log_('Unlisten called for ' + pathString + ' ' + queryId);
|
3610 | util.assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');
|
3611 | var listen = this.removeListen_(pathString, queryId);
|
3612 | if (listen && this.connected_) {
|
3613 | this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
|
3614 | }
|
3615 | };
|
3616 | PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {
|
3617 | this.log_('Unlisten on ' + pathString + ' for ' + queryId);
|
3618 | var req = { p: pathString };
|
3619 | var action = 'n';
|
3620 |
|
3621 | if (tag) {
|
3622 | req['q'] = queryObj;
|
3623 | req['t'] = tag;
|
3624 | }
|
3625 | this.sendRequest(action, req);
|
3626 | };
|
3627 | PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {
|
3628 | this.initConnection_();
|
3629 | if (this.connected_) {
|
3630 | this.sendOnDisconnect_('o', pathString, data, onComplete);
|
3631 | }
|
3632 | else {
|
3633 | this.onDisconnectRequestQueue_.push({
|
3634 | pathString: pathString,
|
3635 | action: 'o',
|
3636 | data: data,
|
3637 | onComplete: onComplete
|
3638 | });
|
3639 | }
|
3640 | };
|
3641 | PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {
|
3642 | this.initConnection_();
|
3643 | if (this.connected_) {
|
3644 | this.sendOnDisconnect_('om', pathString, data, onComplete);
|
3645 | }
|
3646 | else {
|
3647 | this.onDisconnectRequestQueue_.push({
|
3648 | pathString: pathString,
|
3649 | action: 'om',
|
3650 | data: data,
|
3651 | onComplete: onComplete
|
3652 | });
|
3653 | }
|
3654 | };
|
3655 | PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {
|
3656 | this.initConnection_();
|
3657 | if (this.connected_) {
|
3658 | this.sendOnDisconnect_('oc', pathString, null, onComplete);
|
3659 | }
|
3660 | else {
|
3661 | this.onDisconnectRequestQueue_.push({
|
3662 | pathString: pathString,
|
3663 | action: 'oc',
|
3664 | data: null,
|
3665 | onComplete: onComplete
|
3666 | });
|
3667 | }
|
3668 | };
|
3669 | PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {
|
3670 | var request = { p: pathString, d: data };
|
3671 | this.log_('onDisconnect ' + action, request);
|
3672 | this.sendRequest(action, request, function (response) {
|
3673 | if (onComplete) {
|
3674 | setTimeout(function () {
|
3675 | onComplete(response[ 's'], response[ 'd']);
|
3676 | }, Math.floor(0));
|
3677 | }
|
3678 | });
|
3679 | };
|
3680 | PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
|
3681 | this.putInternal('p', pathString, data, onComplete, hash);
|
3682 | };
|
3683 | PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {
|
3684 | this.putInternal('m', pathString, data, onComplete, hash);
|
3685 | };
|
3686 | PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {
|
3687 | this.initConnection_();
|
3688 | var request = {
|
3689 | p: pathString,
|
3690 | d: data
|
3691 | };
|
3692 | if (hash !== undefined) {
|
3693 | request[ 'h'] = hash;
|
3694 | }
|
3695 |
|
3696 | this.outstandingPuts_.push({
|
3697 | action: action,
|
3698 | request: request,
|
3699 | onComplete: onComplete
|
3700 | });
|
3701 | this.outstandingPutCount_++;
|
3702 | var index = this.outstandingPuts_.length - 1;
|
3703 | if (this.connected_) {
|
3704 | this.sendPut_(index);
|
3705 | }
|
3706 | else {
|
3707 | this.log_('Buffering put: ' + pathString);
|
3708 | }
|
3709 | };
|
3710 | PersistentConnection.prototype.sendPut_ = function (index) {
|
3711 | var _this = this;
|
3712 | var action = this.outstandingPuts_[index].action;
|
3713 | var request = this.outstandingPuts_[index].request;
|
3714 | var onComplete = this.outstandingPuts_[index].onComplete;
|
3715 | this.outstandingPuts_[index].queued = this.connected_;
|
3716 | this.sendRequest(action, request, function (message) {
|
3717 | _this.log_(action + ' response', message);
|
3718 | delete _this.outstandingPuts_[index];
|
3719 | _this.outstandingPutCount_--;
|
3720 |
|
3721 | if (_this.outstandingPutCount_ === 0) {
|
3722 | _this.outstandingPuts_ = [];
|
3723 | }
|
3724 | if (onComplete) {
|
3725 | onComplete(message[ 's'], message[ 'd']);
|
3726 | }
|
3727 | });
|
3728 | };
|
3729 | PersistentConnection.prototype.reportStats = function (stats) {
|
3730 | var _this = this;
|
3731 |
|
3732 | if (this.connected_) {
|
3733 | var request = { c: stats };
|
3734 | this.log_('reportStats', request);
|
3735 | this.sendRequest( 's', request, function (result) {
|
3736 | var status = result[ 's'];
|
3737 | if (status !== 'ok') {
|
3738 | var errorReason = result[ 'd'];
|
3739 | _this.log_('reportStats', 'Error sending stats: ' + errorReason);
|
3740 | }
|
3741 | });
|
3742 | }
|
3743 | };
|
3744 | PersistentConnection.prototype.onDataMessage_ = function (message) {
|
3745 | if ('r' in message) {
|
3746 |
|
3747 | this.log_('from server: ' + util.stringify(message));
|
3748 | var reqNum = message['r'];
|
3749 | var onResponse = this.requestCBHash_[reqNum];
|
3750 | if (onResponse) {
|
3751 | delete this.requestCBHash_[reqNum];
|
3752 | onResponse(message[ 'b']);
|
3753 | }
|
3754 | }
|
3755 | else if ('error' in message) {
|
3756 | throw 'A server-side error has occurred: ' + message['error'];
|
3757 | }
|
3758 | else if ('a' in message) {
|
3759 |
|
3760 | this.onDataPush_(message['a'], message['b']);
|
3761 | }
|
3762 | };
|
3763 | PersistentConnection.prototype.onDataPush_ = function (action, body) {
|
3764 | this.log_('handleServerMessage', action, body);
|
3765 | if (action === 'd') {
|
3766 | this.onDataUpdate_(body[ 'p'], body[ 'd'],
|
3767 | false, body['t']);
|
3768 | }
|
3769 | else if (action === 'm') {
|
3770 | this.onDataUpdate_(body[ 'p'], body[ 'd'],
|
3771 | true, body['t']);
|
3772 | }
|
3773 | else if (action === 'c') {
|
3774 | this.onListenRevoked_(body[ 'p'], body[ 'q']);
|
3775 | }
|
3776 | else if (action === 'ac') {
|
3777 | this.onAuthRevoked_(body[ 's'], body[ 'd']);
|
3778 | }
|
3779 | else if (action === 'apc') {
|
3780 | this.onAppCheckRevoked_(body[ 's'], body[ 'd']);
|
3781 | }
|
3782 | else if (action === 'sd') {
|
3783 | this.onSecurityDebugPacket_(body);
|
3784 | }
|
3785 | else {
|
3786 | error('Unrecognized action received from server: ' +
|
3787 | util.stringify(action) +
|
3788 | '\nAre you using the latest client?');
|
3789 | }
|
3790 | };
|
3791 | PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {
|
3792 | this.log_('connection ready');
|
3793 | this.connected_ = true;
|
3794 | this.lastConnectionEstablishedTime_ = new Date().getTime();
|
3795 | this.handleTimestamp_(timestamp);
|
3796 | this.lastSessionId = sessionId;
|
3797 | if (this.firstConnection_) {
|
3798 | this.sendConnectStats_();
|
3799 | }
|
3800 | this.restoreState_();
|
3801 | this.firstConnection_ = false;
|
3802 | this.onConnectStatus_(true);
|
3803 | };
|
3804 | PersistentConnection.prototype.scheduleConnect_ = function (timeout) {
|
3805 | var _this = this;
|
3806 | util.assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
|
3807 | if (this.establishConnectionTimer_) {
|
3808 | clearTimeout(this.establishConnectionTimer_);
|
3809 | }
|
3810 |
|
3811 |
|
3812 | this.establishConnectionTimer_ = setTimeout(function () {
|
3813 | _this.establishConnectionTimer_ = null;
|
3814 | _this.establishConnection_();
|
3815 |
|
3816 | }, Math.floor(timeout));
|
3817 | };
|
3818 | PersistentConnection.prototype.initConnection_ = function () {
|
3819 | if (!this.realtime_ && this.firstConnection_) {
|
3820 | this.scheduleConnect_(0);
|
3821 | }
|
3822 | };
|
3823 | PersistentConnection.prototype.onVisible_ = function (visible) {
|
3824 |
|
3825 | if (visible &&
|
3826 | !this.visible_ &&
|
3827 | this.reconnectDelay_ === this.maxReconnectDelay_) {
|
3828 | this.log_('Window became visible. Reducing delay.');
|
3829 | this.reconnectDelay_ = RECONNECT_MIN_DELAY;
|
3830 | if (!this.realtime_) {
|
3831 | this.scheduleConnect_(0);
|
3832 | }
|
3833 | }
|
3834 | this.visible_ = visible;
|
3835 | };
|
3836 | PersistentConnection.prototype.onOnline_ = function (online) {
|
3837 | if (online) {
|
3838 | this.log_('Browser went online.');
|
3839 | this.reconnectDelay_ = RECONNECT_MIN_DELAY;
|
3840 | if (!this.realtime_) {
|
3841 | this.scheduleConnect_(0);
|
3842 | }
|
3843 | }
|
3844 | else {
|
3845 | this.log_('Browser went offline. Killing connection.');
|
3846 | if (this.realtime_) {
|
3847 | this.realtime_.close();
|
3848 | }
|
3849 | }
|
3850 | };
|
3851 | PersistentConnection.prototype.onRealtimeDisconnect_ = function () {
|
3852 | this.log_('data client disconnected');
|
3853 | this.connected_ = false;
|
3854 | this.realtime_ = null;
|
3855 |
|
3856 | this.cancelSentTransactions_();
|
3857 |
|
3858 | this.requestCBHash_ = {};
|
3859 | if (this.shouldReconnect_()) {
|
3860 | if (!this.visible_) {
|
3861 | this.log_("Window isn't visible. Delaying reconnect.");
|
3862 | this.reconnectDelay_ = this.maxReconnectDelay_;
|
3863 | this.lastConnectionAttemptTime_ = new Date().getTime();
|
3864 | }
|
3865 | else if (this.lastConnectionEstablishedTime_) {
|
3866 |
|
3867 | var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;
|
3868 | if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
|
3869 | this.reconnectDelay_ = RECONNECT_MIN_DELAY;
|
3870 | }
|
3871 | this.lastConnectionEstablishedTime_ = null;
|
3872 | }
|
3873 | var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;
|
3874 | var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
|
3875 | reconnectDelay = Math.random() * reconnectDelay;
|
3876 | this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');
|
3877 | this.scheduleConnect_(reconnectDelay);
|
3878 |
|
3879 | this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
|
3880 | }
|
3881 | this.onConnectStatus_(false);
|
3882 | };
|
3883 | PersistentConnection.prototype.establishConnection_ = function () {
|
3884 | return tslib.__awaiter(this, void 0, void 0, function () {
|
3885 | var onDataMessage, onReady, onDisconnect_1, connId, lastSessionId, canceled_1, connection_1, closeFn, sendRequestFn, forceRefresh, _a, authToken, appCheckToken, error_1;
|
3886 | var _this = this;
|
3887 | return tslib.__generator(this, function (_b) {
|
3888 | switch (_b.label) {
|
3889 | case 0:
|
3890 | if (!this.shouldReconnect_()) return [3 , 4];
|
3891 | this.log_('Making a connection attempt');
|
3892 | this.lastConnectionAttemptTime_ = new Date().getTime();
|
3893 | this.lastConnectionEstablishedTime_ = null;
|
3894 | onDataMessage = this.onDataMessage_.bind(this);
|
3895 | onReady = this.onReady_.bind(this);
|
3896 | onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);
|
3897 | connId = this.id + ':' + PersistentConnection.nextConnectionId_++;
|
3898 | lastSessionId = this.lastSessionId;
|
3899 | canceled_1 = false;
|
3900 | connection_1 = null;
|
3901 | closeFn = function () {
|
3902 | if (connection_1) {
|
3903 | connection_1.close();
|
3904 | }
|
3905 | else {
|
3906 | canceled_1 = true;
|
3907 | onDisconnect_1();
|
3908 | }
|
3909 | };
|
3910 | sendRequestFn = function (msg) {
|
3911 | util.assert(connection_1, "sendRequest call when we're not connected not allowed.");
|
3912 | connection_1.sendRequest(msg);
|
3913 | };
|
3914 | this.realtime_ = {
|
3915 | close: closeFn,
|
3916 | sendRequest: sendRequestFn
|
3917 | };
|
3918 | forceRefresh = this.forceTokenRefresh_;
|
3919 | this.forceTokenRefresh_ = false;
|
3920 | _b.label = 1;
|
3921 | case 1:
|
3922 | _b.trys.push([1, 3, , 4]);
|
3923 | return [4 , Promise.all([
|
3924 | this.authTokenProvider_.getToken(forceRefresh),
|
3925 | this.appCheckTokenProvider_.getToken(forceRefresh)
|
3926 | ])];
|
3927 | case 2:
|
3928 | _a = tslib.__read.apply(void 0, [_b.sent(), 2]), authToken = _a[0], appCheckToken = _a[1];
|
3929 | if (!canceled_1) {
|
3930 | log('getToken() completed. Creating connection.');
|
3931 | this.authToken_ = authToken && authToken.accessToken;
|
3932 | this.appCheckToken_ = appCheckToken && appCheckToken.token;
|
3933 | connection_1 = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect_1,
|
3934 | function (reason) {
|
3935 | warn(reason + ' (' + _this.repoInfo_.toString() + ')');
|
3936 | _this.interrupt(SERVER_KILL_INTERRUPT_REASON);
|
3937 | }, lastSessionId);
|
3938 | }
|
3939 | else {
|
3940 | log('getToken() completed but was canceled');
|
3941 | }
|
3942 | return [3 , 4];
|
3943 | case 3:
|
3944 | error_1 = _b.sent();
|
3945 | this.log_('Failed to get token: ' + error_1);
|
3946 | if (!canceled_1) {
|
3947 | if (this.repoInfo_.nodeAdmin) {
|
3948 |
|
3949 |
|
3950 |
|
3951 | warn(error_1);
|
3952 | }
|
3953 | closeFn();
|
3954 | }
|
3955 | return [3 , 4];
|
3956 | case 4: return [2 ];
|
3957 | }
|
3958 | });
|
3959 | });
|
3960 | };
|
3961 | PersistentConnection.prototype.interrupt = function (reason) {
|
3962 | log('Interrupting connection for reason: ' + reason);
|
3963 | this.interruptReasons_[reason] = true;
|
3964 | if (this.realtime_) {
|
3965 | this.realtime_.close();
|
3966 | }
|
3967 | else {
|
3968 | if (this.establishConnectionTimer_) {
|
3969 | clearTimeout(this.establishConnectionTimer_);
|
3970 | this.establishConnectionTimer_ = null;
|
3971 | }
|
3972 | if (this.connected_) {
|
3973 | this.onRealtimeDisconnect_();
|
3974 | }
|
3975 | }
|
3976 | };
|
3977 | PersistentConnection.prototype.resume = function (reason) {
|
3978 | log('Resuming connection for reason: ' + reason);
|
3979 | delete this.interruptReasons_[reason];
|
3980 | if (util.isEmpty(this.interruptReasons_)) {
|
3981 | this.reconnectDelay_ = RECONNECT_MIN_DELAY;
|
3982 | if (!this.realtime_) {
|
3983 | this.scheduleConnect_(0);
|
3984 | }
|
3985 | }
|
3986 | };
|
3987 | PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {
|
3988 | var delta = timestamp - new Date().getTime();
|
3989 | this.onServerInfoUpdate_({ serverTimeOffset: delta });
|
3990 | };
|
3991 | PersistentConnection.prototype.cancelSentTransactions_ = function () {
|
3992 | for (var i = 0; i < this.outstandingPuts_.length; i++) {
|
3993 | var put = this.outstandingPuts_[i];
|
3994 | if (put && 'h' in put.request && put.queued) {
|
3995 | if (put.onComplete) {
|
3996 | put.onComplete('disconnect');
|
3997 | }
|
3998 | delete this.outstandingPuts_[i];
|
3999 | this.outstandingPutCount_--;
|
4000 | }
|
4001 | }
|
4002 |
|
4003 | if (this.outstandingPutCount_ === 0) {
|
4004 | this.outstandingPuts_ = [];
|
4005 | }
|
4006 | };
|
4007 | PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {
|
4008 |
|
4009 | var queryId;
|
4010 | if (!query) {
|
4011 | queryId = 'default';
|
4012 | }
|
4013 | else {
|
4014 | queryId = query.map(function (q) { return ObjectToUniqueKey(q); }).join('$');
|
4015 | }
|
4016 | var listen = this.removeListen_(pathString, queryId);
|
4017 | if (listen && listen.onComplete) {
|
4018 | listen.onComplete('permission_denied');
|
4019 | }
|
4020 | };
|
4021 | PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {
|
4022 | var normalizedPathString = new Path(pathString).toString();
|
4023 | var listen;
|
4024 | if (this.listens.has(normalizedPathString)) {
|
4025 | var map = this.listens.get(normalizedPathString);
|
4026 | listen = map.get(queryId);
|
4027 | map.delete(queryId);
|
4028 | if (map.size === 0) {
|
4029 | this.listens.delete(normalizedPathString);
|
4030 | }
|
4031 | }
|
4032 | else {
|
4033 |
|
4034 | listen = undefined;
|
4035 | }
|
4036 | return listen;
|
4037 | };
|
4038 | PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {
|
4039 | log('Auth token revoked: ' + statusCode + '/' + explanation);
|
4040 | this.authToken_ = null;
|
4041 | this.forceTokenRefresh_ = true;
|
4042 | this.realtime_.close();
|
4043 | if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
|
4044 |
|
4045 |
|
4046 |
|
4047 | this.invalidAuthTokenCount_++;
|
4048 | if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
|
4049 |
|
4050 | this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
|
4051 |
|
4052 |
|
4053 | this.authTokenProvider_.notifyForInvalidToken();
|
4054 | }
|
4055 | }
|
4056 | };
|
4057 | PersistentConnection.prototype.onAppCheckRevoked_ = function (statusCode, explanation) {
|
4058 | log('App check token revoked: ' + statusCode + '/' + explanation);
|
4059 | this.appCheckToken_ = null;
|
4060 | this.forceTokenRefresh_ = true;
|
4061 |
|
4062 |
|
4063 | if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {
|
4064 |
|
4065 |
|
4066 |
|
4067 | this.invalidAppCheckTokenCount_++;
|
4068 | if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
|
4069 | this.appCheckTokenProvider_.notifyForInvalidToken();
|
4070 | }
|
4071 | }
|
4072 | };
|
4073 | PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {
|
4074 | if (this.securityDebugCallback_) {
|
4075 | this.securityDebugCallback_(body);
|
4076 | }
|
4077 | else {
|
4078 | if ('msg' in body) {
|
4079 | console.log('FIREBASE: ' + body['msg'].replace('\n', '\nFIREBASE: '));
|
4080 | }
|
4081 | }
|
4082 | };
|
4083 | PersistentConnection.prototype.restoreState_ = function () {
|
4084 | var e_1, _a, e_2, _b;
|
4085 |
|
4086 | this.tryAuth();
|
4087 | this.tryAppCheck();
|
4088 | try {
|
4089 |
|
4090 |
|
4091 | for (var _c = tslib.__values(this.listens.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
|
4092 | var queries = _d.value;
|
4093 | try {
|
4094 | for (var _e = (e_2 = void 0, tslib.__values(queries.values())), _f = _e.next(); !_f.done; _f = _e.next()) {
|
4095 | var listenSpec = _f.value;
|
4096 | this.sendListen_(listenSpec);
|
4097 | }
|
4098 | }
|
4099 | catch (e_2_1) { e_2 = { error: e_2_1 }; }
|
4100 | finally {
|
4101 | try {
|
4102 | if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
|
4103 | }
|
4104 | finally { if (e_2) throw e_2.error; }
|
4105 | }
|
4106 | }
|
4107 | }
|
4108 | catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
4109 | finally {
|
4110 | try {
|
4111 | if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
|
4112 | }
|
4113 | finally { if (e_1) throw e_1.error; }
|
4114 | }
|
4115 | for (var i = 0; i < this.outstandingPuts_.length; i++) {
|
4116 | if (this.outstandingPuts_[i]) {
|
4117 | this.sendPut_(i);
|
4118 | }
|
4119 | }
|
4120 | while (this.onDisconnectRequestQueue_.length) {
|
4121 | var request = this.onDisconnectRequestQueue_.shift();
|
4122 | this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
|
4123 | }
|
4124 | for (var i = 0; i < this.outstandingGets_.length; i++) {
|
4125 | if (this.outstandingGets_[i]) {
|
4126 | this.sendGet_(i);
|
4127 | }
|
4128 | }
|
4129 | };
|
4130 | |
4131 |
|
4132 |
|
4133 | PersistentConnection.prototype.sendConnectStats_ = function () {
|
4134 | var stats = {};
|
4135 | var clientName = 'js';
|
4136 | if (util.isNodeSdk()) {
|
4137 | if (this.repoInfo_.nodeAdmin) {
|
4138 | clientName = 'admin_node';
|
4139 | }
|
4140 | else {
|
4141 | clientName = 'node';
|
4142 | }
|
4143 | }
|
4144 | stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\./g, '-')] = 1;
|
4145 | if (util.isMobileCordova()) {
|
4146 | stats['framework.cordova'] = 1;
|
4147 | }
|
4148 | else if (util.isReactNative()) {
|
4149 | stats['framework.reactnative'] = 1;
|
4150 | }
|
4151 | this.reportStats(stats);
|
4152 | };
|
4153 | PersistentConnection.prototype.shouldReconnect_ = function () {
|
4154 | var online = OnlineMonitor.getInstance().currentlyOnline();
|
4155 | return util.isEmpty(this.interruptReasons_) && online;
|
4156 | };
|
4157 | PersistentConnection.nextPersistentConnectionId_ = 0;
|
4158 | |
4159 |
|
4160 |
|
4161 | PersistentConnection.nextConnectionId_ = 0;
|
4162 | return PersistentConnection;
|
4163 | }(ServerActions));
|
4164 |
|
4165 |
|
4166 |
|
4167 |
|
4168 |
|
4169 |
|
4170 |
|
4171 |
|
4172 |
|
4173 |
|
4174 |
|
4175 |
|
4176 |
|
4177 |
|
4178 |
|
4179 |
|
4180 |
|
4181 | var NamedNode = (function () {
|
4182 | function NamedNode(name, node) {
|
4183 | this.name = name;
|
4184 | this.node = node;
|
4185 | }
|
4186 | NamedNode.Wrap = function (name, node) {
|
4187 | return new NamedNode(name, node);
|
4188 | };
|
4189 | return NamedNode;
|
4190 | }());
|
4191 |
|
4192 |
|
4193 |
|
4194 |
|
4195 |
|
4196 |
|
4197 |
|
4198 |
|
4199 |
|
4200 |
|
4201 |
|
4202 |
|
4203 |
|
4204 |
|
4205 |
|
4206 |
|
4207 |
|
4208 | var Index = (function () {
|
4209 | function Index() {
|
4210 | }
|
4211 | |
4212 |
|
4213 |
|
4214 |
|
4215 | Index.prototype.getCompare = function () {
|
4216 | return this.compare.bind(this);
|
4217 | };
|
4218 | |
4219 |
|
4220 |
|
4221 |
|
4222 |
|
4223 |
|
4224 |
|
4225 | Index.prototype.indexedValueChanged = function (oldNode, newNode) {
|
4226 | var oldWrapped = new NamedNode(MIN_NAME, oldNode);
|
4227 | var newWrapped = new NamedNode(MIN_NAME, newNode);
|
4228 | return this.compare(oldWrapped, newWrapped) !== 0;
|
4229 | };
|
4230 | |
4231 |
|
4232 |
|
4233 |
|
4234 | Index.prototype.minPost = function () {
|
4235 |
|
4236 | return NamedNode.MIN;
|
4237 | };
|
4238 | return Index;
|
4239 | }());
|
4240 |
|
4241 |
|
4242 |
|
4243 |
|
4244 |
|
4245 |
|
4246 |
|
4247 |
|
4248 |
|
4249 |
|
4250 |
|
4251 |
|
4252 |
|
4253 |
|
4254 |
|
4255 |
|
4256 |
|
4257 | var __EMPTY_NODE;
|
4258 | var KeyIndex = (function (_super) {
|
4259 | tslib.__extends(KeyIndex, _super);
|
4260 | function KeyIndex() {
|
4261 | return _super !== null && _super.apply(this, arguments) || this;
|
4262 | }
|
4263 | Object.defineProperty(KeyIndex, "__EMPTY_NODE", {
|
4264 | get: function () {
|
4265 | return __EMPTY_NODE;
|
4266 | },
|
4267 | set: function (val) {
|
4268 | __EMPTY_NODE = val;
|
4269 | },
|
4270 | enumerable: false,
|
4271 | configurable: true
|
4272 | });
|
4273 | KeyIndex.prototype.compare = function (a, b) {
|
4274 | return nameCompare(a.name, b.name);
|
4275 | };
|
4276 | KeyIndex.prototype.isDefinedOn = function (node) {
|
4277 |
|
4278 |
|
4279 | throw util.assertionError('KeyIndex.isDefinedOn not expected to be called.');
|
4280 | };
|
4281 | KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
|
4282 | return false;
|
4283 | };
|
4284 | KeyIndex.prototype.minPost = function () {
|
4285 |
|
4286 | return NamedNode.MIN;
|
4287 | };
|
4288 | KeyIndex.prototype.maxPost = function () {
|
4289 |
|
4290 |
|
4291 | return new NamedNode(MAX_NAME, __EMPTY_NODE);
|
4292 | };
|
4293 | KeyIndex.prototype.makePost = function (indexValue, name) {
|
4294 | util.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');
|
4295 |
|
4296 | return new NamedNode(indexValue, __EMPTY_NODE);
|
4297 | };
|
4298 | |
4299 |
|
4300 |
|
4301 | KeyIndex.prototype.toString = function () {
|
4302 | return '.key';
|
4303 | };
|
4304 | return KeyIndex;
|
4305 | }(Index));
|
4306 | var KEY_INDEX = new KeyIndex();
|
4307 |
|
4308 |
|
4309 |
|
4310 |
|
4311 |
|
4312 |
|
4313 |
|
4314 |
|
4315 |
|
4316 |
|
4317 |
|
4318 |
|
4319 |
|
4320 |
|
4321 |
|
4322 |
|
4323 |
|
4324 |
|
4325 |
|
4326 |
|
4327 | var SortedMapIterator = (function () {
|
4328 | |
4329 |
|
4330 |
|
4331 |
|
4332 | function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {
|
4333 | if (resultGenerator_ === void 0) { resultGenerator_ = null; }
|
4334 | this.isReverse_ = isReverse_;
|
4335 | this.resultGenerator_ = resultGenerator_;
|
4336 | this.nodeStack_ = [];
|
4337 | var cmp = 1;
|
4338 | while (!node.isEmpty()) {
|
4339 | node = node;
|
4340 | cmp = startKey ? comparator(node.key, startKey) : 1;
|
4341 |
|
4342 | if (isReverse_) {
|
4343 | cmp *= -1;
|
4344 | }
|
4345 | if (cmp < 0) {
|
4346 |
|
4347 | if (this.isReverse_) {
|
4348 | node = node.left;
|
4349 | }
|
4350 | else {
|
4351 | node = node.right;
|
4352 | }
|
4353 | }
|
4354 | else if (cmp === 0) {
|
4355 |
|
4356 | this.nodeStack_.push(node);
|
4357 | break;
|
4358 | }
|
4359 | else {
|
4360 |
|
4361 | this.nodeStack_.push(node);
|
4362 | if (this.isReverse_) {
|
4363 | node = node.right;
|
4364 | }
|
4365 | else {
|
4366 | node = node.left;
|
4367 | }
|
4368 | }
|
4369 | }
|
4370 | }
|
4371 | SortedMapIterator.prototype.getNext = function () {
|
4372 | if (this.nodeStack_.length === 0) {
|
4373 | return null;
|
4374 | }
|
4375 | var node = this.nodeStack_.pop();
|
4376 | var result;
|
4377 | if (this.resultGenerator_) {
|
4378 | result = this.resultGenerator_(node.key, node.value);
|
4379 | }
|
4380 | else {
|
4381 | result = { key: node.key, value: node.value };
|
4382 | }
|
4383 | if (this.isReverse_) {
|
4384 | node = node.left;
|
4385 | while (!node.isEmpty()) {
|
4386 | this.nodeStack_.push(node);
|
4387 | node = node.right;
|
4388 | }
|
4389 | }
|
4390 | else {
|
4391 | node = node.right;
|
4392 | while (!node.isEmpty()) {
|
4393 | this.nodeStack_.push(node);
|
4394 | node = node.left;
|
4395 | }
|
4396 | }
|
4397 | return result;
|
4398 | };
|
4399 | SortedMapIterator.prototype.hasNext = function () {
|
4400 | return this.nodeStack_.length > 0;
|
4401 | };
|
4402 | SortedMapIterator.prototype.peek = function () {
|
4403 | if (this.nodeStack_.length === 0) {
|
4404 | return null;
|
4405 | }
|
4406 | var node = this.nodeStack_[this.nodeStack_.length - 1];
|
4407 | if (this.resultGenerator_) {
|
4408 | return this.resultGenerator_(node.key, node.value);
|
4409 | }
|
4410 | else {
|
4411 | return { key: node.key, value: node.value };
|
4412 | }
|
4413 | };
|
4414 | return SortedMapIterator;
|
4415 | }());
|
4416 |
|
4417 |
|
4418 |
|
4419 | var LLRBNode = (function () {
|
4420 | |
4421 |
|
4422 |
|
4423 |
|
4424 |
|
4425 |
|
4426 |
|
4427 | function LLRBNode(key, value, color, left, right) {
|
4428 | this.key = key;
|
4429 | this.value = value;
|
4430 | this.color = color != null ? color : LLRBNode.RED;
|
4431 | this.left =
|
4432 | left != null ? left : SortedMap.EMPTY_NODE;
|
4433 | this.right =
|
4434 | right != null ? right : SortedMap.EMPTY_NODE;
|
4435 | }
|
4436 | |
4437 |
|
4438 |
|
4439 |
|
4440 |
|
4441 |
|
4442 |
|
4443 |
|
4444 |
|
4445 |
|
4446 | LLRBNode.prototype.copy = function (key, value, color, left, right) {
|
4447 | 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);
|
4448 | };
|
4449 | |
4450 |
|
4451 |
|
4452 | LLRBNode.prototype.count = function () {
|
4453 | return this.left.count() + 1 + this.right.count();
|
4454 | };
|
4455 | |
4456 |
|
4457 |
|
4458 | LLRBNode.prototype.isEmpty = function () {
|
4459 | return false;
|
4460 | };
|
4461 | |
4462 |
|
4463 |
|
4464 |
|
4465 |
|
4466 |
|
4467 |
|
4468 |
|
4469 |
|
4470 | LLRBNode.prototype.inorderTraversal = function (action) {
|
4471 | return (this.left.inorderTraversal(action) ||
|
4472 | !!action(this.key, this.value) ||
|
4473 | this.right.inorderTraversal(action));
|
4474 | };
|
4475 | |
4476 |
|
4477 |
|
4478 |
|
4479 |
|
4480 |
|
4481 |
|
4482 |
|
4483 | LLRBNode.prototype.reverseTraversal = function (action) {
|
4484 | return (this.right.reverseTraversal(action) ||
|
4485 | action(this.key, this.value) ||
|
4486 | this.left.reverseTraversal(action));
|
4487 | };
|
4488 | |
4489 |
|
4490 |
|
4491 | LLRBNode.prototype.min_ = function () {
|
4492 | if (this.left.isEmpty()) {
|
4493 | return this;
|
4494 | }
|
4495 | else {
|
4496 | return this.left.min_();
|
4497 | }
|
4498 | };
|
4499 | |
4500 |
|
4501 |
|
4502 | LLRBNode.prototype.minKey = function () {
|
4503 | return this.min_().key;
|
4504 | };
|
4505 | |
4506 |
|
4507 |
|
4508 | LLRBNode.prototype.maxKey = function () {
|
4509 | if (this.right.isEmpty()) {
|
4510 | return this.key;
|
4511 | }
|
4512 | else {
|
4513 | return this.right.maxKey();
|
4514 | }
|
4515 | };
|
4516 | |
4517 |
|
4518 |
|
4519 |
|
4520 |
|
4521 |
|
4522 | LLRBNode.prototype.insert = function (key, value, comparator) {
|
4523 | var n = this;
|
4524 | var cmp = comparator(key, n.key);
|
4525 | if (cmp < 0) {
|
4526 | n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
|
4527 | }
|
4528 | else if (cmp === 0) {
|
4529 | n = n.copy(null, value, null, null, null);
|
4530 | }
|
4531 | else {
|
4532 | n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));
|
4533 | }
|
4534 | return n.fixUp_();
|
4535 | };
|
4536 | |
4537 |
|
4538 |
|
4539 | LLRBNode.prototype.removeMin_ = function () {
|
4540 | if (this.left.isEmpty()) {
|
4541 | return SortedMap.EMPTY_NODE;
|
4542 | }
|
4543 | var n = this;
|
4544 | if (!n.left.isRed_() && !n.left.left.isRed_()) {
|
4545 | n = n.moveRedLeft_();
|
4546 | }
|
4547 | n = n.copy(null, null, null, n.left.removeMin_(), null);
|
4548 | return n.fixUp_();
|
4549 | };
|
4550 | |
4551 |
|
4552 |
|
4553 |
|
4554 |
|
4555 | LLRBNode.prototype.remove = function (key, comparator) {
|
4556 | var n, smallest;
|
4557 | n = this;
|
4558 | if (comparator(key, n.key) < 0) {
|
4559 | if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {
|
4560 | n = n.moveRedLeft_();
|
4561 | }
|
4562 | n = n.copy(null, null, null, n.left.remove(key, comparator), null);
|
4563 | }
|
4564 | else {
|
4565 | if (n.left.isRed_()) {
|
4566 | n = n.rotateRight_();
|
4567 | }
|
4568 | if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {
|
4569 | n = n.moveRedRight_();
|
4570 | }
|
4571 | if (comparator(key, n.key) === 0) {
|
4572 | if (n.right.isEmpty()) {
|
4573 | return SortedMap.EMPTY_NODE;
|
4574 | }
|
4575 | else {
|
4576 | smallest = n.right.min_();
|
4577 | n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());
|
4578 | }
|
4579 | }
|
4580 | n = n.copy(null, null, null, null, n.right.remove(key, comparator));
|
4581 | }
|
4582 | return n.fixUp_();
|
4583 | };
|
4584 | |
4585 |
|
4586 |
|
4587 | LLRBNode.prototype.isRed_ = function () {
|
4588 | return this.color;
|
4589 | };
|
4590 | |
4591 |
|
4592 |
|
4593 | LLRBNode.prototype.fixUp_ = function () {
|
4594 | var n = this;
|
4595 | if (n.right.isRed_() && !n.left.isRed_()) {
|
4596 | n = n.rotateLeft_();
|
4597 | }
|
4598 | if (n.left.isRed_() && n.left.left.isRed_()) {
|
4599 | n = n.rotateRight_();
|
4600 | }
|
4601 | if (n.left.isRed_() && n.right.isRed_()) {
|
4602 | n = n.colorFlip_();
|
4603 | }
|
4604 | return n;
|
4605 | };
|
4606 | |
4607 |
|
4608 |
|
4609 | LLRBNode.prototype.moveRedLeft_ = function () {
|
4610 | var n = this.colorFlip_();
|
4611 | if (n.right.left.isRed_()) {
|
4612 | n = n.copy(null, null, null, null, n.right.rotateRight_());
|
4613 | n = n.rotateLeft_();
|
4614 | n = n.colorFlip_();
|
4615 | }
|
4616 | return n;
|
4617 | };
|
4618 | |
4619 |
|
4620 |
|
4621 | LLRBNode.prototype.moveRedRight_ = function () {
|
4622 | var n = this.colorFlip_();
|
4623 | if (n.left.left.isRed_()) {
|
4624 | n = n.rotateRight_();
|
4625 | n = n.colorFlip_();
|
4626 | }
|
4627 | return n;
|
4628 | };
|
4629 | |
4630 |
|
4631 |
|
4632 | LLRBNode.prototype.rotateLeft_ = function () {
|
4633 | var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
|
4634 | return this.right.copy(null, null, this.color, nl, null);
|
4635 | };
|
4636 | |
4637 |
|
4638 |
|
4639 | LLRBNode.prototype.rotateRight_ = function () {
|
4640 | var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
|
4641 | return this.left.copy(null, null, this.color, null, nr);
|
4642 | };
|
4643 | |
4644 |
|
4645 |
|
4646 | LLRBNode.prototype.colorFlip_ = function () {
|
4647 | var left = this.left.copy(null, null, !this.left.color, null, null);
|
4648 | var right = this.right.copy(null, null, !this.right.color, null, null);
|
4649 | return this.copy(null, null, !this.color, left, right);
|
4650 | };
|
4651 | |
4652 |
|
4653 |
|
4654 |
|
4655 |
|
4656 | LLRBNode.prototype.checkMaxDepth_ = function () {
|
4657 | var blackDepth = this.check_();
|
4658 | return Math.pow(2.0, blackDepth) <= this.count() + 1;
|
4659 | };
|
4660 | LLRBNode.prototype.check_ = function () {
|
4661 | if (this.isRed_() && this.left.isRed_()) {
|
4662 | throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');
|
4663 | }
|
4664 | if (this.right.isRed_()) {
|
4665 | throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');
|
4666 | }
|
4667 | var blackDepth = this.left.check_();
|
4668 | if (blackDepth !== this.right.check_()) {
|
4669 | throw new Error('Black depths differ');
|
4670 | }
|
4671 | else {
|
4672 | return blackDepth + (this.isRed_() ? 0 : 1);
|
4673 | }
|
4674 | };
|
4675 | LLRBNode.RED = true;
|
4676 | LLRBNode.BLACK = false;
|
4677 | return LLRBNode;
|
4678 | }());
|
4679 |
|
4680 |
|
4681 |
|
4682 | var LLRBEmptyNode = (function () {
|
4683 | function LLRBEmptyNode() {
|
4684 | }
|
4685 | |
4686 |
|
4687 |
|
4688 |
|
4689 |
|
4690 | LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {
|
4691 | return this;
|
4692 | };
|
4693 | |
4694 |
|
4695 |
|
4696 |
|
4697 |
|
4698 |
|
4699 |
|
4700 |
|
4701 | LLRBEmptyNode.prototype.insert = function (key, value, comparator) {
|
4702 | return new LLRBNode(key, value, null);
|
4703 | };
|
4704 | |
4705 |
|
4706 |
|
4707 |
|
4708 |
|
4709 |
|
4710 |
|
4711 | LLRBEmptyNode.prototype.remove = function (key, comparator) {
|
4712 | return this;
|
4713 | };
|
4714 | |
4715 |
|
4716 |
|
4717 | LLRBEmptyNode.prototype.count = function () {
|
4718 | return 0;
|
4719 | };
|
4720 | |
4721 |
|
4722 |
|
4723 | LLRBEmptyNode.prototype.isEmpty = function () {
|
4724 | return true;
|
4725 | };
|
4726 | |
4727 |
|
4728 |
|
4729 |
|
4730 |
|
4731 |
|
4732 |
|
4733 |
|
4734 | LLRBEmptyNode.prototype.inorderTraversal = function (action) {
|
4735 | return false;
|
4736 | };
|
4737 | |
4738 |
|
4739 |
|
4740 |
|
4741 |
|
4742 |
|
4743 |
|
4744 |
|
4745 | LLRBEmptyNode.prototype.reverseTraversal = function (action) {
|
4746 | return false;
|
4747 | };
|
4748 | LLRBEmptyNode.prototype.minKey = function () {
|
4749 | return null;
|
4750 | };
|
4751 | LLRBEmptyNode.prototype.maxKey = function () {
|
4752 | return null;
|
4753 | };
|
4754 | LLRBEmptyNode.prototype.check_ = function () {
|
4755 | return 0;
|
4756 | };
|
4757 | |
4758 |
|
4759 |
|
4760 | LLRBEmptyNode.prototype.isRed_ = function () {
|
4761 | return false;
|
4762 | };
|
4763 | return LLRBEmptyNode;
|
4764 | }());
|
4765 |
|
4766 |
|
4767 |
|
4768 |
|
4769 | var SortedMap = (function () {
|
4770 | |
4771 |
|
4772 |
|
4773 |
|
4774 | function SortedMap(comparator_, root_) {
|
4775 | if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }
|
4776 | this.comparator_ = comparator_;
|
4777 | this.root_ = root_;
|
4778 | }
|
4779 | |
4780 |
|
4781 |
|
4782 |
|
4783 |
|
4784 |
|
4785 |
|
4786 |
|
4787 | SortedMap.prototype.insert = function (key, value) {
|
4788 | return new SortedMap(this.comparator_, this.root_
|
4789 | .insert(key, value, this.comparator_)
|
4790 | .copy(null, null, LLRBNode.BLACK, null, null));
|
4791 | };
|
4792 | |
4793 |
|
4794 |
|
4795 |
|
4796 |
|
4797 |
|
4798 | SortedMap.prototype.remove = function (key) {
|
4799 | return new SortedMap(this.comparator_, this.root_
|
4800 | .remove(key, this.comparator_)
|
4801 | .copy(null, null, LLRBNode.BLACK, null, null));
|
4802 | };
|
4803 | |
4804 |
|
4805 |
|
4806 |
|
4807 |
|
4808 |
|
4809 |
|
4810 | SortedMap.prototype.get = function (key) {
|
4811 | var cmp;
|
4812 | var node = this.root_;
|
4813 | while (!node.isEmpty()) {
|
4814 | cmp = this.comparator_(key, node.key);
|
4815 | if (cmp === 0) {
|
4816 | return node.value;
|
4817 | }
|
4818 | else if (cmp < 0) {
|
4819 | node = node.left;
|
4820 | }
|
4821 | else if (cmp > 0) {
|
4822 | node = node.right;
|
4823 | }
|
4824 | }
|
4825 | return null;
|
4826 | };
|
4827 | |
4828 |
|
4829 |
|
4830 |
|
4831 |
|
4832 | SortedMap.prototype.getPredecessorKey = function (key) {
|
4833 | var cmp, node = this.root_, rightParent = null;
|
4834 | while (!node.isEmpty()) {
|
4835 | cmp = this.comparator_(key, node.key);
|
4836 | if (cmp === 0) {
|
4837 | if (!node.left.isEmpty()) {
|
4838 | node = node.left;
|
4839 | while (!node.right.isEmpty()) {
|
4840 | node = node.right;
|
4841 | }
|
4842 | return node.key;
|
4843 | }
|
4844 | else if (rightParent) {
|
4845 | return rightParent.key;
|
4846 | }
|
4847 | else {
|
4848 | return null;
|
4849 | }
|
4850 | }
|
4851 | else if (cmp < 0) {
|
4852 | node = node.left;
|
4853 | }
|
4854 | else if (cmp > 0) {
|
4855 | rightParent = node;
|
4856 | node = node.right;
|
4857 | }
|
4858 | }
|
4859 | throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');
|
4860 | };
|
4861 | |
4862 |
|
4863 |
|
4864 | SortedMap.prototype.isEmpty = function () {
|
4865 | return this.root_.isEmpty();
|
4866 | };
|
4867 | |
4868 |
|
4869 |
|
4870 | SortedMap.prototype.count = function () {
|
4871 | return this.root_.count();
|
4872 | };
|
4873 | |
4874 |
|
4875 |
|
4876 | SortedMap.prototype.minKey = function () {
|
4877 | return this.root_.minKey();
|
4878 | };
|
4879 | |
4880 |
|
4881 |
|
4882 | SortedMap.prototype.maxKey = function () {
|
4883 | return this.root_.maxKey();
|
4884 | };
|
4885 | |
4886 |
|
4887 |
|
4888 |
|
4889 |
|
4890 |
|
4891 |
|
4892 |
|
4893 |
|
4894 | SortedMap.prototype.inorderTraversal = function (action) {
|
4895 | return this.root_.inorderTraversal(action);
|
4896 | };
|
4897 | |
4898 |
|
4899 |
|
4900 |
|
4901 |
|
4902 |
|
4903 |
|
4904 |
|
4905 | SortedMap.prototype.reverseTraversal = function (action) {
|
4906 | return this.root_.reverseTraversal(action);
|
4907 | };
|
4908 | |
4909 |
|
4910 |
|
4911 |
|
4912 | SortedMap.prototype.getIterator = function (resultGenerator) {
|
4913 | return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
|
4914 | };
|
4915 | SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {
|
4916 | return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
|
4917 | };
|
4918 | SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {
|
4919 | return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
|
4920 | };
|
4921 | SortedMap.prototype.getReverseIterator = function (resultGenerator) {
|
4922 | return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
|
4923 | };
|
4924 | |
4925 |
|
4926 |
|
4927 | SortedMap.EMPTY_NODE = new LLRBEmptyNode();
|
4928 | return SortedMap;
|
4929 | }());
|
4930 |
|
4931 |
|
4932 |
|
4933 |
|
4934 |
|
4935 |
|
4936 |
|
4937 |
|
4938 |
|
4939 |
|
4940 |
|
4941 |
|
4942 |
|
4943 |
|
4944 |
|
4945 |
|
4946 |
|
4947 | function NAME_ONLY_COMPARATOR(left, right) {
|
4948 | return nameCompare(left.name, right.name);
|
4949 | }
|
4950 | function NAME_COMPARATOR(left, right) {
|
4951 | return nameCompare(left, right);
|
4952 | }
|
4953 |
|
4954 |
|
4955 |
|
4956 |
|
4957 |
|
4958 |
|
4959 |
|
4960 |
|
4961 |
|
4962 |
|
4963 |
|
4964 |
|
4965 |
|
4966 |
|
4967 |
|
4968 |
|
4969 |
|
4970 | var MAX_NODE$2;
|
4971 | function setMaxNode$1(val) {
|
4972 | MAX_NODE$2 = val;
|
4973 | }
|
4974 | var priorityHashText = function (priority) {
|
4975 | if (typeof priority === 'number') {
|
4976 | return 'number:' + doubleToIEEE754String(priority);
|
4977 | }
|
4978 | else {
|
4979 | return 'string:' + priority;
|
4980 | }
|
4981 | };
|
4982 |
|
4983 |
|
4984 |
|
4985 | var validatePriorityNode = function (priorityNode) {
|
4986 | if (priorityNode.isLeafNode()) {
|
4987 | var val = priorityNode.val();
|
4988 | util.assert(typeof val === 'string' ||
|
4989 | typeof val === 'number' ||
|
4990 | (typeof val === 'object' && util.contains(val, '.sv')), 'Priority must be a string or number.');
|
4991 | }
|
4992 | else {
|
4993 | util.assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');
|
4994 | }
|
4995 |
|
4996 | util.assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
|
4997 | };
|
4998 |
|
4999 |
|
5000 |
|
5001 |
|
5002 |
|
5003 |
|
5004 |
|
5005 |
|
5006 |
|
5007 |
|
5008 |
|
5009 |
|
5010 |
|
5011 |
|
5012 |
|
5013 |
|
5014 |
|
5015 | var __childrenNodeConstructor;
|
5016 |
|
5017 |
|
5018 |
|
5019 |
|
5020 |
|
5021 | var LeafNode = (function () {
|
5022 | |
5023 |
|
5024 |
|
5025 |
|
5026 |
|
5027 | function LeafNode(value_, priorityNode_) {
|
5028 | if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }
|
5029 | this.value_ = value_;
|
5030 | this.priorityNode_ = priorityNode_;
|
5031 | this.lazyHash_ = null;
|
5032 | util.assert(this.value_ !== undefined && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
|
5033 | validatePriorityNode(this.priorityNode_);
|
5034 | }
|
5035 | Object.defineProperty(LeafNode, "__childrenNodeConstructor", {
|
5036 | get: function () {
|
5037 | return __childrenNodeConstructor;
|
5038 | },
|
5039 | set: function (val) {
|
5040 | __childrenNodeConstructor = val;
|
5041 | },
|
5042 | enumerable: false,
|
5043 | configurable: true
|
5044 | });
|
5045 |
|
5046 | LeafNode.prototype.isLeafNode = function () {
|
5047 | return true;
|
5048 | };
|
5049 |
|
5050 | LeafNode.prototype.getPriority = function () {
|
5051 | return this.priorityNode_;
|
5052 | };
|
5053 |
|
5054 | LeafNode.prototype.updatePriority = function (newPriorityNode) {
|
5055 | return new LeafNode(this.value_, newPriorityNode);
|
5056 | };
|
5057 |
|
5058 | LeafNode.prototype.getImmediateChild = function (childName) {
|
5059 |
|
5060 | if (childName === '.priority') {
|
5061 | return this.priorityNode_;
|
5062 | }
|
5063 | else {
|
5064 | return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
|
5065 | }
|
5066 | };
|
5067 |
|
5068 | LeafNode.prototype.getChild = function (path) {
|
5069 | if (pathIsEmpty(path)) {
|
5070 | return this;
|
5071 | }
|
5072 | else if (pathGetFront(path) === '.priority') {
|
5073 | return this.priorityNode_;
|
5074 | }
|
5075 | else {
|
5076 | return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
|
5077 | }
|
5078 | };
|
5079 | LeafNode.prototype.hasChild = function () {
|
5080 | return false;
|
5081 | };
|
5082 |
|
5083 | LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {
|
5084 | return null;
|
5085 | };
|
5086 |
|
5087 | LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {
|
5088 | if (childName === '.priority') {
|
5089 | return this.updatePriority(newChildNode);
|
5090 | }
|
5091 | else if (newChildNode.isEmpty() && childName !== '.priority') {
|
5092 | return this;
|
5093 | }
|
5094 | else {
|
5095 | return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
|
5096 | }
|
5097 | };
|
5098 |
|
5099 | LeafNode.prototype.updateChild = function (path, newChildNode) {
|
5100 | var front = pathGetFront(path);
|
5101 | if (front === null) {
|
5102 | return newChildNode;
|
5103 | }
|
5104 | else if (newChildNode.isEmpty() && front !== '.priority') {
|
5105 | return this;
|
5106 | }
|
5107 | else {
|
5108 | util.assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
|
5109 | return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
|
5110 | }
|
5111 | };
|
5112 |
|
5113 | LeafNode.prototype.isEmpty = function () {
|
5114 | return false;
|
5115 | };
|
5116 |
|
5117 | LeafNode.prototype.numChildren = function () {
|
5118 | return 0;
|
5119 | };
|
5120 |
|
5121 | LeafNode.prototype.forEachChild = function (index, action) {
|
5122 | return false;
|
5123 | };
|
5124 | LeafNode.prototype.val = function (exportFormat) {
|
5125 | if (exportFormat && !this.getPriority().isEmpty()) {
|
5126 | return {
|
5127 | '.value': this.getValue(),
|
5128 | '.priority': this.getPriority().val()
|
5129 | };
|
5130 | }
|
5131 | else {
|
5132 | return this.getValue();
|
5133 | }
|
5134 | };
|
5135 |
|
5136 | LeafNode.prototype.hash = function () {
|
5137 | if (this.lazyHash_ === null) {
|
5138 | var toHash = '';
|
5139 | if (!this.priorityNode_.isEmpty()) {
|
5140 | toHash +=
|
5141 | 'priority:' +
|
5142 | priorityHashText(this.priorityNode_.val()) +
|
5143 | ':';
|
5144 | }
|
5145 | var type = typeof this.value_;
|
5146 | toHash += type + ':';
|
5147 | if (type === 'number') {
|
5148 | toHash += doubleToIEEE754String(this.value_);
|
5149 | }
|
5150 | else {
|
5151 | toHash += this.value_;
|
5152 | }
|
5153 | this.lazyHash_ = sha1(toHash);
|
5154 | }
|
5155 | return this.lazyHash_;
|
5156 | };
|
5157 | |
5158 |
|
5159 |
|
5160 |
|
5161 | LeafNode.prototype.getValue = function () {
|
5162 | return this.value_;
|
5163 | };
|
5164 | LeafNode.prototype.compareTo = function (other) {
|
5165 | if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
|
5166 | return 1;
|
5167 | }
|
5168 | else if (other instanceof LeafNode.__childrenNodeConstructor) {
|
5169 | return -1;
|
5170 | }
|
5171 | else {
|
5172 | util.assert(other.isLeafNode(), 'Unknown node type');
|
5173 | return this.compareToLeafNode_(other);
|
5174 | }
|
5175 | };
|
5176 | |
5177 |
|
5178 |
|
5179 | LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {
|
5180 | var otherLeafType = typeof otherLeaf.value_;
|
5181 | var thisLeafType = typeof this.value_;
|
5182 | var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
|
5183 | var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
|
5184 | util.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);
|
5185 | util.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);
|
5186 | if (otherIndex === thisIndex) {
|
5187 |
|
5188 | if (thisLeafType === 'object') {
|
5189 |
|
5190 | return 0;
|
5191 | }
|
5192 | else {
|
5193 |
|
5194 | if (this.value_ < otherLeaf.value_) {
|
5195 | return -1;
|
5196 | }
|
5197 | else if (this.value_ === otherLeaf.value_) {
|
5198 | return 0;
|
5199 | }
|
5200 | else {
|
5201 | return 1;
|
5202 | }
|
5203 | }
|
5204 | }
|
5205 | else {
|
5206 | return thisIndex - otherIndex;
|
5207 | }
|
5208 | };
|
5209 | LeafNode.prototype.withIndex = function () {
|
5210 | return this;
|
5211 | };
|
5212 | LeafNode.prototype.isIndexed = function () {
|
5213 | return true;
|
5214 | };
|
5215 | LeafNode.prototype.equals = function (other) {
|
5216 | if (other === this) {
|
5217 | return true;
|
5218 | }
|
5219 | else if (other.isLeafNode()) {
|
5220 | var otherLeaf = other;
|
5221 | return (this.value_ === otherLeaf.value_ &&
|
5222 | this.priorityNode_.equals(otherLeaf.priorityNode_));
|
5223 | }
|
5224 | else {
|
5225 | return false;
|
5226 | }
|
5227 | };
|
5228 | |
5229 |
|
5230 |
|
5231 |
|
5232 | LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];
|
5233 | return LeafNode;
|
5234 | }());
|
5235 |
|
5236 |
|
5237 |
|
5238 |
|
5239 |
|
5240 |
|
5241 |
|
5242 |
|
5243 |
|
5244 |
|
5245 |
|
5246 |
|
5247 |
|
5248 |
|
5249 |
|
5250 |
|
5251 |
|
5252 | var nodeFromJSON$1;
|
5253 | var MAX_NODE$1;
|
5254 | function setNodeFromJSON(val) {
|
5255 | nodeFromJSON$1 = val;
|
5256 | }
|
5257 | function setMaxNode(val) {
|
5258 | MAX_NODE$1 = val;
|
5259 | }
|
5260 | var PriorityIndex = (function (_super) {
|
5261 | tslib.__extends(PriorityIndex, _super);
|
5262 | function PriorityIndex() {
|
5263 | return _super !== null && _super.apply(this, arguments) || this;
|
5264 | }
|
5265 | PriorityIndex.prototype.compare = function (a, b) {
|
5266 | var aPriority = a.node.getPriority();
|
5267 | var bPriority = b.node.getPriority();
|
5268 | var indexCmp = aPriority.compareTo(bPriority);
|
5269 | if (indexCmp === 0) {
|
5270 | return nameCompare(a.name, b.name);
|
5271 | }
|
5272 | else {
|
5273 | return indexCmp;
|
5274 | }
|
5275 | };
|
5276 | PriorityIndex.prototype.isDefinedOn = function (node) {
|
5277 | return !node.getPriority().isEmpty();
|
5278 | };
|
5279 | PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
|
5280 | return !oldNode.getPriority().equals(newNode.getPriority());
|
5281 | };
|
5282 | PriorityIndex.prototype.minPost = function () {
|
5283 |
|
5284 | return NamedNode.MIN;
|
5285 | };
|
5286 | PriorityIndex.prototype.maxPost = function () {
|
5287 | return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));
|
5288 | };
|
5289 | PriorityIndex.prototype.makePost = function (indexValue, name) {
|
5290 | var priorityNode = nodeFromJSON$1(indexValue);
|
5291 | return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));
|
5292 | };
|
5293 | |
5294 |
|
5295 |
|
5296 | PriorityIndex.prototype.toString = function () {
|
5297 | return '.priority';
|
5298 | };
|
5299 | return PriorityIndex;
|
5300 | }(Index));
|
5301 | var PRIORITY_INDEX = new PriorityIndex();
|
5302 |
|
5303 |
|
5304 |
|
5305 |
|
5306 |
|
5307 |
|
5308 |
|
5309 |
|
5310 |
|
5311 |
|
5312 |
|
5313 |
|
5314 |
|
5315 |
|
5316 |
|
5317 |
|
5318 |
|
5319 | var LOG_2 = Math.log(2);
|
5320 | var Base12Num = (function () {
|
5321 | function Base12Num(length) {
|
5322 | var logBase2 = function (num) {
|
5323 |
|
5324 | return parseInt((Math.log(num) / LOG_2), 10);
|
5325 | };
|
5326 | var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };
|
5327 | this.count = logBase2(length + 1);
|
5328 | this.current_ = this.count - 1;
|
5329 | var mask = bitMask(this.count);
|
5330 | this.bits_ = (length + 1) & mask;
|
5331 | }
|
5332 | Base12Num.prototype.nextBitIsOne = function () {
|
5333 |
|
5334 | var result = !(this.bits_ & (0x1 << this.current_));
|
5335 | this.current_--;
|
5336 | return result;
|
5337 | };
|
5338 | return Base12Num;
|
5339 | }());
|
5340 |
|
5341 |
|
5342 |
|
5343 |
|
5344 |
|
5345 |
|
5346 |
|
5347 |
|
5348 |
|
5349 |
|
5350 |
|
5351 |
|
5352 |
|
5353 | var buildChildSet = function (childList, cmp, keyFn, mapSortFn) {
|
5354 | childList.sort(cmp);
|
5355 | var buildBalancedTree = function (low, high) {
|
5356 | var length = high - low;
|
5357 | var namedNode;
|
5358 | var key;
|
5359 | if (length === 0) {
|
5360 | return null;
|
5361 | }
|
5362 | else if (length === 1) {
|
5363 | namedNode = childList[low];
|
5364 | key = keyFn ? keyFn(namedNode) : namedNode;
|
5365 | return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
|
5366 | }
|
5367 | else {
|
5368 |
|
5369 | var middle = parseInt((length / 2), 10) + low;
|
5370 | var left = buildBalancedTree(low, middle);
|
5371 | var right = buildBalancedTree(middle + 1, high);
|
5372 | namedNode = childList[middle];
|
5373 | key = keyFn ? keyFn(namedNode) : namedNode;
|
5374 | return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
|
5375 | }
|
5376 | };
|
5377 | var buildFrom12Array = function (base12) {
|
5378 | var node = null;
|
5379 | var root = null;
|
5380 | var index = childList.length;
|
5381 | var buildPennant = function (chunkSize, color) {
|
5382 | var low = index - chunkSize;
|
5383 | var high = index;
|
5384 | index -= chunkSize;
|
5385 | var childTree = buildBalancedTree(low + 1, high);
|
5386 | var namedNode = childList[low];
|
5387 | var key = keyFn ? keyFn(namedNode) : namedNode;
|
5388 | attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
|
5389 | };
|
5390 | var attachPennant = function (pennant) {
|
5391 | if (node) {
|
5392 | node.left = pennant;
|
5393 | node = pennant;
|
5394 | }
|
5395 | else {
|
5396 | root = pennant;
|
5397 | node = pennant;
|
5398 | }
|
5399 | };
|
5400 | for (var i = 0; i < base12.count; ++i) {
|
5401 | var isOne = base12.nextBitIsOne();
|
5402 |
|
5403 | var chunkSize = Math.pow(2, base12.count - (i + 1));
|
5404 | if (isOne) {
|
5405 | buildPennant(chunkSize, LLRBNode.BLACK);
|
5406 | }
|
5407 | else {
|
5408 |
|
5409 | buildPennant(chunkSize, LLRBNode.BLACK);
|
5410 | buildPennant(chunkSize, LLRBNode.RED);
|
5411 | }
|
5412 | }
|
5413 | return root;
|
5414 | };
|
5415 | var base12 = new Base12Num(childList.length);
|
5416 | var root = buildFrom12Array(base12);
|
5417 |
|
5418 | return new SortedMap(mapSortFn || cmp, root);
|
5419 | };
|
5420 |
|
5421 |
|
5422 |
|
5423 |
|
5424 |
|
5425 |
|
5426 |
|
5427 |
|
5428 |
|
5429 |
|
5430 |
|
5431 |
|
5432 |
|
5433 |
|
5434 |
|
5435 |
|
5436 |
|
5437 | var _defaultIndexMap;
|
5438 | var fallbackObject = {};
|
5439 | var IndexMap = (function () {
|
5440 | function IndexMap(indexes_, indexSet_) {
|
5441 | this.indexes_ = indexes_;
|
5442 | this.indexSet_ = indexSet_;
|
5443 | }
|
5444 | Object.defineProperty(IndexMap, "Default", {
|
5445 | |
5446 |
|
5447 |
|
5448 | get: function () {
|
5449 | util.assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');
|
5450 | _defaultIndexMap =
|
5451 | _defaultIndexMap ||
|
5452 | new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });
|
5453 | return _defaultIndexMap;
|
5454 | },
|
5455 | enumerable: false,
|
5456 | configurable: true
|
5457 | });
|
5458 | IndexMap.prototype.get = function (indexKey) {
|
5459 | var sortedMap = util.safeGet(this.indexes_, indexKey);
|
5460 | if (!sortedMap) {
|
5461 | throw new Error('No index defined for ' + indexKey);
|
5462 | }
|
5463 | if (sortedMap instanceof SortedMap) {
|
5464 | return sortedMap;
|
5465 | }
|
5466 | else {
|
5467 |
|
5468 |
|
5469 | return null;
|
5470 | }
|
5471 | };
|
5472 | IndexMap.prototype.hasIndex = function (indexDefinition) {
|
5473 | return util.contains(this.indexSet_, indexDefinition.toString());
|
5474 | };
|
5475 | IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {
|
5476 | util.assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
|
5477 | var childList = [];
|
5478 | var sawIndexedValue = false;
|
5479 | var iter = existingChildren.getIterator(NamedNode.Wrap);
|
5480 | var next = iter.getNext();
|
5481 | while (next) {
|
5482 | sawIndexedValue =
|
5483 | sawIndexedValue || indexDefinition.isDefinedOn(next.node);
|
5484 | childList.push(next);
|
5485 | next = iter.getNext();
|
5486 | }
|
5487 | var newIndex;
|
5488 | if (sawIndexedValue) {
|
5489 | newIndex = buildChildSet(childList, indexDefinition.getCompare());
|
5490 | }
|
5491 | else {
|
5492 | newIndex = fallbackObject;
|
5493 | }
|
5494 | var indexName = indexDefinition.toString();
|
5495 | var newIndexSet = tslib.__assign({}, this.indexSet_);
|
5496 | newIndexSet[indexName] = indexDefinition;
|
5497 | var newIndexes = tslib.__assign({}, this.indexes_);
|
5498 | newIndexes[indexName] = newIndex;
|
5499 | return new IndexMap(newIndexes, newIndexSet);
|
5500 | };
|
5501 | |
5502 |
|
5503 |
|
5504 | IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {
|
5505 | var _this = this;
|
5506 | var newIndexes = util.map(this.indexes_, function (indexedChildren, indexName) {
|
5507 | var index = util.safeGet(_this.indexSet_, indexName);
|
5508 | util.assert(index, 'Missing index implementation for ' + indexName);
|
5509 | if (indexedChildren === fallbackObject) {
|
5510 |
|
5511 | if (index.isDefinedOn(namedNode.node)) {
|
5512 |
|
5513 | var childList = [];
|
5514 | var iter = existingChildren.getIterator(NamedNode.Wrap);
|
5515 | var next = iter.getNext();
|
5516 | while (next) {
|
5517 | if (next.name !== namedNode.name) {
|
5518 | childList.push(next);
|
5519 | }
|
5520 | next = iter.getNext();
|
5521 | }
|
5522 | childList.push(namedNode);
|
5523 | return buildChildSet(childList, index.getCompare());
|
5524 | }
|
5525 | else {
|
5526 |
|
5527 | return fallbackObject;
|
5528 | }
|
5529 | }
|
5530 | else {
|
5531 | var existingSnap = existingChildren.get(namedNode.name);
|
5532 | var newChildren = indexedChildren;
|
5533 | if (existingSnap) {
|
5534 | newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
|
5535 | }
|
5536 | return newChildren.insert(namedNode, namedNode.node);
|
5537 | }
|
5538 | });
|
5539 | return new IndexMap(newIndexes, this.indexSet_);
|
5540 | };
|
5541 | |
5542 |
|
5543 |
|
5544 | IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {
|
5545 | var newIndexes = util.map(this.indexes_, function (indexedChildren) {
|
5546 | if (indexedChildren === fallbackObject) {
|
5547 |
|
5548 | return indexedChildren;
|
5549 | }
|
5550 | else {
|
5551 | var existingSnap = existingChildren.get(namedNode.name);
|
5552 | if (existingSnap) {
|
5553 | return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
|
5554 | }
|
5555 | else {
|
5556 |
|
5557 | return indexedChildren;
|
5558 | }
|
5559 | }
|
5560 | });
|
5561 | return new IndexMap(newIndexes, this.indexSet_);
|
5562 | };
|
5563 | return IndexMap;
|
5564 | }());
|
5565 |
|
5566 |
|
5567 |
|
5568 |
|
5569 |
|
5570 |
|
5571 |
|
5572 |
|
5573 |
|
5574 |
|
5575 |
|
5576 |
|
5577 |
|
5578 |
|
5579 |
|
5580 |
|
5581 |
|
5582 |
|
5583 | var EMPTY_NODE;
|
5584 |
|
5585 |
|
5586 |
|
5587 |
|
5588 |
|
5589 | var ChildrenNode = (function () {
|
5590 | |
5591 |
|
5592 |
|
5593 |
|
5594 | function ChildrenNode(children_, priorityNode_, indexMap_) {
|
5595 | this.children_ = children_;
|
5596 | this.priorityNode_ = priorityNode_;
|
5597 | this.indexMap_ = indexMap_;
|
5598 | this.lazyHash_ = null;
|
5599 | |
5600 |
|
5601 |
|
5602 |
|
5603 |
|
5604 | if (this.priorityNode_) {
|
5605 | validatePriorityNode(this.priorityNode_);
|
5606 | }
|
5607 | if (this.children_.isEmpty()) {
|
5608 | util.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');
|
5609 | }
|
5610 | }
|
5611 | Object.defineProperty(ChildrenNode, "EMPTY_NODE", {
|
5612 | get: function () {
|
5613 | return (EMPTY_NODE ||
|
5614 | (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));
|
5615 | },
|
5616 | enumerable: false,
|
5617 | configurable: true
|
5618 | });
|
5619 |
|
5620 | ChildrenNode.prototype.isLeafNode = function () {
|
5621 | return false;
|
5622 | };
|
5623 |
|
5624 | ChildrenNode.prototype.getPriority = function () {
|
5625 | return this.priorityNode_ || EMPTY_NODE;
|
5626 | };
|
5627 |
|
5628 | ChildrenNode.prototype.updatePriority = function (newPriorityNode) {
|
5629 | if (this.children_.isEmpty()) {
|
5630 |
|
5631 | return this;
|
5632 | }
|
5633 | else {
|
5634 | return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
|
5635 | }
|
5636 | };
|
5637 |
|
5638 | ChildrenNode.prototype.getImmediateChild = function (childName) {
|
5639 |
|
5640 | if (childName === '.priority') {
|
5641 | return this.getPriority();
|
5642 | }
|
5643 | else {
|
5644 | var child = this.children_.get(childName);
|
5645 | return child === null ? EMPTY_NODE : child;
|
5646 | }
|
5647 | };
|
5648 |
|
5649 | ChildrenNode.prototype.getChild = function (path) {
|
5650 | var front = pathGetFront(path);
|
5651 | if (front === null) {
|
5652 | return this;
|
5653 | }
|
5654 | return this.getImmediateChild(front).getChild(pathPopFront(path));
|
5655 | };
|
5656 |
|
5657 | ChildrenNode.prototype.hasChild = function (childName) {
|
5658 | return this.children_.get(childName) !== null;
|
5659 | };
|
5660 |
|
5661 | ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {
|
5662 | util.assert(newChildNode, 'We should always be passing snapshot nodes');
|
5663 | if (childName === '.priority') {
|
5664 | return this.updatePriority(newChildNode);
|
5665 | }
|
5666 | else {
|
5667 | var namedNode = new NamedNode(childName, newChildNode);
|
5668 | var newChildren = void 0, newIndexMap = void 0;
|
5669 | if (newChildNode.isEmpty()) {
|
5670 | newChildren = this.children_.remove(childName);
|
5671 | newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
|
5672 | }
|
5673 | else {
|
5674 | newChildren = this.children_.insert(childName, newChildNode);
|
5675 | newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
|
5676 | }
|
5677 | var newPriority = newChildren.isEmpty()
|
5678 | ? EMPTY_NODE
|
5679 | : this.priorityNode_;
|
5680 | return new ChildrenNode(newChildren, newPriority, newIndexMap);
|
5681 | }
|
5682 | };
|
5683 |
|
5684 | ChildrenNode.prototype.updateChild = function (path, newChildNode) {
|
5685 | var front = pathGetFront(path);
|
5686 | if (front === null) {
|
5687 | return newChildNode;
|
5688 | }
|
5689 | else {
|
5690 | util.assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');
|
5691 | var newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
|
5692 | return this.updateImmediateChild(front, newImmediateChild);
|
5693 | }
|
5694 | };
|
5695 |
|
5696 | ChildrenNode.prototype.isEmpty = function () {
|
5697 | return this.children_.isEmpty();
|
5698 | };
|
5699 |
|
5700 | ChildrenNode.prototype.numChildren = function () {
|
5701 | return this.children_.count();
|
5702 | };
|
5703 |
|
5704 | ChildrenNode.prototype.val = function (exportFormat) {
|
5705 | if (this.isEmpty()) {
|
5706 | return null;
|
5707 | }
|
5708 | var obj = {};
|
5709 | var numKeys = 0, maxKey = 0, allIntegerKeys = true;
|
5710 | this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
|
5711 | obj[key] = childNode.val(exportFormat);
|
5712 | numKeys++;
|
5713 | if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
|
5714 | maxKey = Math.max(maxKey, Number(key));
|
5715 | }
|
5716 | else {
|
5717 | allIntegerKeys = false;
|
5718 | }
|
5719 | });
|
5720 | if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
|
5721 |
|
5722 | var array = [];
|
5723 |
|
5724 | for (var key in obj) {
|
5725 | array[key] = obj[key];
|
5726 | }
|
5727 | return array;
|
5728 | }
|
5729 | else {
|
5730 | if (exportFormat && !this.getPriority().isEmpty()) {
|
5731 | obj['.priority'] = this.getPriority().val();
|
5732 | }
|
5733 | return obj;
|
5734 | }
|
5735 | };
|
5736 |
|
5737 | ChildrenNode.prototype.hash = function () {
|
5738 | if (this.lazyHash_ === null) {
|
5739 | var toHash_1 = '';
|
5740 | if (!this.getPriority().isEmpty()) {
|
5741 | toHash_1 +=
|
5742 | 'priority:' +
|
5743 | priorityHashText(this.getPriority().val()) +
|
5744 | ':';
|
5745 | }
|
5746 | this.forEachChild(PRIORITY_INDEX, function (key, childNode) {
|
5747 | var childHash = childNode.hash();
|
5748 | if (childHash !== '') {
|
5749 | toHash_1 += ':' + key + ':' + childHash;
|
5750 | }
|
5751 | });
|
5752 | this.lazyHash_ = toHash_1 === '' ? '' : sha1(toHash_1);
|
5753 | }
|
5754 | return this.lazyHash_;
|
5755 | };
|
5756 |
|
5757 | ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {
|
5758 | var idx = this.resolveIndex_(index);
|
5759 | if (idx) {
|
5760 | var predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
|
5761 | return predecessor ? predecessor.name : null;
|
5762 | }
|
5763 | else {
|
5764 | return this.children_.getPredecessorKey(childName);
|
5765 | }
|
5766 | };
|
5767 | ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {
|
5768 | var idx = this.resolveIndex_(indexDefinition);
|
5769 | if (idx) {
|
5770 | var minKey = idx.minKey();
|
5771 | return minKey && minKey.name;
|
5772 | }
|
5773 | else {
|
5774 | return this.children_.minKey();
|
5775 | }
|
5776 | };
|
5777 | ChildrenNode.prototype.getFirstChild = function (indexDefinition) {
|
5778 | var minKey = this.getFirstChildName(indexDefinition);
|
5779 | if (minKey) {
|
5780 | return new NamedNode(minKey, this.children_.get(minKey));
|
5781 | }
|
5782 | else {
|
5783 | return null;
|
5784 | }
|
5785 | };
|
5786 | |
5787 |
|
5788 |
|
5789 | ChildrenNode.prototype.getLastChildName = function (indexDefinition) {
|
5790 | var idx = this.resolveIndex_(indexDefinition);
|
5791 | if (idx) {
|
5792 | var maxKey = idx.maxKey();
|
5793 | return maxKey && maxKey.name;
|
5794 | }
|
5795 | else {
|
5796 | return this.children_.maxKey();
|
5797 | }
|
5798 | };
|
5799 | ChildrenNode.prototype.getLastChild = function (indexDefinition) {
|
5800 | var maxKey = this.getLastChildName(indexDefinition);
|
5801 | if (maxKey) {
|
5802 | return new NamedNode(maxKey, this.children_.get(maxKey));
|
5803 | }
|
5804 | else {
|
5805 | return null;
|
5806 | }
|
5807 | };
|
5808 | ChildrenNode.prototype.forEachChild = function (index, action) {
|
5809 | var idx = this.resolveIndex_(index);
|
5810 | if (idx) {
|
5811 | return idx.inorderTraversal(function (wrappedNode) {
|
5812 | return action(wrappedNode.name, wrappedNode.node);
|
5813 | });
|
5814 | }
|
5815 | else {
|
5816 | return this.children_.inorderTraversal(action);
|
5817 | }
|
5818 | };
|
5819 | ChildrenNode.prototype.getIterator = function (indexDefinition) {
|
5820 | return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
|
5821 | };
|
5822 | ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {
|
5823 | var idx = this.resolveIndex_(indexDefinition);
|
5824 | if (idx) {
|
5825 | return idx.getIteratorFrom(startPost, function (key) { return key; });
|
5826 | }
|
5827 | else {
|
5828 | var iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
|
5829 | var next = iterator.peek();
|
5830 | while (next != null && indexDefinition.compare(next, startPost) < 0) {
|
5831 | iterator.getNext();
|
5832 | next = iterator.peek();
|
5833 | }
|
5834 | return iterator;
|
5835 | }
|
5836 | };
|
5837 | ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {
|
5838 | return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
|
5839 | };
|
5840 | ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {
|
5841 | var idx = this.resolveIndex_(indexDefinition);
|
5842 | if (idx) {
|
5843 | return idx.getReverseIteratorFrom(endPost, function (key) {
|
5844 | return key;
|
5845 | });
|
5846 | }
|
5847 | else {
|
5848 | var iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
|
5849 | var next = iterator.peek();
|
5850 | while (next != null && indexDefinition.compare(next, endPost) > 0) {
|
5851 | iterator.getNext();
|
5852 | next = iterator.peek();
|
5853 | }
|
5854 | return iterator;
|
5855 | }
|
5856 | };
|
5857 | ChildrenNode.prototype.compareTo = function (other) {
|
5858 | if (this.isEmpty()) {
|
5859 | if (other.isEmpty()) {
|
5860 | return 0;
|
5861 | }
|
5862 | else {
|
5863 | return -1;
|
5864 | }
|
5865 | }
|
5866 | else if (other.isLeafNode() || other.isEmpty()) {
|
5867 | return 1;
|
5868 | }
|
5869 | else if (other === MAX_NODE) {
|
5870 | return -1;
|
5871 | }
|
5872 | else {
|
5873 |
|
5874 | return 0;
|
5875 | }
|
5876 | };
|
5877 | ChildrenNode.prototype.withIndex = function (indexDefinition) {
|
5878 | if (indexDefinition === KEY_INDEX ||
|
5879 | this.indexMap_.hasIndex(indexDefinition)) {
|
5880 | return this;
|
5881 | }
|
5882 | else {
|
5883 | var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
|
5884 | return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
|
5885 | }
|
5886 | };
|
5887 | ChildrenNode.prototype.isIndexed = function (index) {
|
5888 | return index === KEY_INDEX || this.indexMap_.hasIndex(index);
|
5889 | };
|
5890 | ChildrenNode.prototype.equals = function (other) {
|
5891 | if (other === this) {
|
5892 | return true;
|
5893 | }
|
5894 | else if (other.isLeafNode()) {
|
5895 | return false;
|
5896 | }
|
5897 | else {
|
5898 | var otherChildrenNode = other;
|
5899 | if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
|
5900 | return false;
|
5901 | }
|
5902 | else if (this.children_.count() === otherChildrenNode.children_.count()) {
|
5903 | var thisIter = this.getIterator(PRIORITY_INDEX);
|
5904 | var otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
|
5905 | var thisCurrent = thisIter.getNext();
|
5906 | var otherCurrent = otherIter.getNext();
|
5907 | while (thisCurrent && otherCurrent) {
|
5908 | if (thisCurrent.name !== otherCurrent.name ||
|
5909 | !thisCurrent.node.equals(otherCurrent.node)) {
|
5910 | return false;
|
5911 | }
|
5912 | thisCurrent = thisIter.getNext();
|
5913 | otherCurrent = otherIter.getNext();
|
5914 | }
|
5915 | return thisCurrent === null && otherCurrent === null;
|
5916 | }
|
5917 | else {
|
5918 | return false;
|
5919 | }
|
5920 | }
|
5921 | };
|
5922 | |
5923 |
|
5924 |
|
5925 |
|
5926 |
|
5927 | ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {
|
5928 | if (indexDefinition === KEY_INDEX) {
|
5929 | return null;
|
5930 | }
|
5931 | else {
|
5932 | return this.indexMap_.get(indexDefinition.toString());
|
5933 | }
|
5934 | };
|
5935 | ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
|
5936 | return ChildrenNode;
|
5937 | }());
|
5938 | var MaxNode = (function (_super) {
|
5939 | tslib.__extends(MaxNode, _super);
|
5940 | function MaxNode() {
|
5941 | return _super.call(this, new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default) || this;
|
5942 | }
|
5943 | MaxNode.prototype.compareTo = function (other) {
|
5944 | if (other === this) {
|
5945 | return 0;
|
5946 | }
|
5947 | else {
|
5948 | return 1;
|
5949 | }
|
5950 | };
|
5951 | MaxNode.prototype.equals = function (other) {
|
5952 |
|
5953 | return other === this;
|
5954 | };
|
5955 | MaxNode.prototype.getPriority = function () {
|
5956 | return this;
|
5957 | };
|
5958 | MaxNode.prototype.getImmediateChild = function (childName) {
|
5959 | return ChildrenNode.EMPTY_NODE;
|
5960 | };
|
5961 | MaxNode.prototype.isEmpty = function () {
|
5962 | return false;
|
5963 | };
|
5964 | return MaxNode;
|
5965 | }(ChildrenNode));
|
5966 |
|
5967 |
|
5968 |
|
5969 | var MAX_NODE = new MaxNode();
|
5970 | Object.defineProperties(NamedNode, {
|
5971 | MIN: {
|
5972 | value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
|
5973 | },
|
5974 | MAX: {
|
5975 | value: new NamedNode(MAX_NAME, MAX_NODE)
|
5976 | }
|
5977 | });
|
5978 |
|
5979 |
|
5980 |
|
5981 | KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
|
5982 | LeafNode.__childrenNodeConstructor = ChildrenNode;
|
5983 | setMaxNode$1(MAX_NODE);
|
5984 | setMaxNode(MAX_NODE);
|
5985 |
|
5986 |
|
5987 |
|
5988 |
|
5989 |
|
5990 |
|
5991 |
|
5992 |
|
5993 |
|
5994 |
|
5995 |
|
5996 |
|
5997 |
|
5998 |
|
5999 |
|
6000 |
|
6001 |
|
6002 | var USE_HINZE = true;
|
6003 |
|
6004 |
|
6005 |
|
6006 |
|
6007 |
|
6008 |
|
6009 | function nodeFromJSON(json, priority) {
|
6010 | if (priority === void 0) { priority = null; }
|
6011 | if (json === null) {
|
6012 | return ChildrenNode.EMPTY_NODE;
|
6013 | }
|
6014 | if (typeof json === 'object' && '.priority' in json) {
|
6015 | priority = json['.priority'];
|
6016 | }
|
6017 | util.assert(priority === null ||
|
6018 | typeof priority === 'string' ||
|
6019 | typeof priority === 'number' ||
|
6020 | (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);
|
6021 | if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {
|
6022 | json = json['.value'];
|
6023 | }
|
6024 |
|
6025 | if (typeof json !== 'object' || '.sv' in json) {
|
6026 | var jsonLeaf = json;
|
6027 | return new LeafNode(jsonLeaf, nodeFromJSON(priority));
|
6028 | }
|
6029 | if (!(json instanceof Array) && USE_HINZE) {
|
6030 | var children_1 = [];
|
6031 | var childrenHavePriority_1 = false;
|
6032 | var hinzeJsonObj = json;
|
6033 | each(hinzeJsonObj, function (key, child) {
|
6034 | if (key.substring(0, 1) !== '.') {
|
6035 |
|
6036 | var childNode = nodeFromJSON(child);
|
6037 | if (!childNode.isEmpty()) {
|
6038 | childrenHavePriority_1 =
|
6039 | childrenHavePriority_1 || !childNode.getPriority().isEmpty();
|
6040 | children_1.push(new NamedNode(key, childNode));
|
6041 | }
|
6042 | }
|
6043 | });
|
6044 | if (children_1.length === 0) {
|
6045 | return ChildrenNode.EMPTY_NODE;
|
6046 | }
|
6047 | var childSet = buildChildSet(children_1, NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, NAME_COMPARATOR);
|
6048 | if (childrenHavePriority_1) {
|
6049 | var sortedChildSet = buildChildSet(children_1, PRIORITY_INDEX.getCompare());
|
6050 | return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));
|
6051 | }
|
6052 | else {
|
6053 | return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
|
6054 | }
|
6055 | }
|
6056 | else {
|
6057 | var node_1 = ChildrenNode.EMPTY_NODE;
|
6058 | each(json, function (key, childData) {
|
6059 | if (util.contains(json, key)) {
|
6060 | if (key.substring(0, 1) !== '.') {
|
6061 |
|
6062 | var childNode = nodeFromJSON(childData);
|
6063 | if (childNode.isLeafNode() || !childNode.isEmpty()) {
|
6064 | node_1 = node_1.updateImmediateChild(key, childNode);
|
6065 | }
|
6066 | }
|
6067 | }
|
6068 | });
|
6069 | return node_1.updatePriority(nodeFromJSON(priority));
|
6070 | }
|
6071 | }
|
6072 | setNodeFromJSON(nodeFromJSON);
|
6073 |
|
6074 |
|
6075 |
|
6076 |
|
6077 |
|
6078 |
|
6079 |
|
6080 |
|
6081 |
|
6082 |
|
6083 |
|
6084 |
|
6085 |
|
6086 |
|
6087 |
|
6088 |
|
6089 |
|
6090 | var PathIndex = (function (_super) {
|
6091 | tslib.__extends(PathIndex, _super);
|
6092 | function PathIndex(indexPath_) {
|
6093 | var _this = _super.call(this) || this;
|
6094 | _this.indexPath_ = indexPath_;
|
6095 | util.assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', "Can't create PathIndex with empty path or .priority key");
|
6096 | return _this;
|
6097 | }
|
6098 | PathIndex.prototype.extractChild = function (snap) {
|
6099 | return snap.getChild(this.indexPath_);
|
6100 | };
|
6101 | PathIndex.prototype.isDefinedOn = function (node) {
|
6102 | return !node.getChild(this.indexPath_).isEmpty();
|
6103 | };
|
6104 | PathIndex.prototype.compare = function (a, b) {
|
6105 | var aChild = this.extractChild(a.node);
|
6106 | var bChild = this.extractChild(b.node);
|
6107 | var indexCmp = aChild.compareTo(bChild);
|
6108 | if (indexCmp === 0) {
|
6109 | return nameCompare(a.name, b.name);
|
6110 | }
|
6111 | else {
|
6112 | return indexCmp;
|
6113 | }
|
6114 | };
|
6115 | PathIndex.prototype.makePost = function (indexValue, name) {
|
6116 | var valueNode = nodeFromJSON(indexValue);
|
6117 | var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
|
6118 | return new NamedNode(name, node);
|
6119 | };
|
6120 | PathIndex.prototype.maxPost = function () {
|
6121 | var node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
|
6122 | return new NamedNode(MAX_NAME, node);
|
6123 | };
|
6124 | PathIndex.prototype.toString = function () {
|
6125 | return pathSlice(this.indexPath_, 0).join('/');
|
6126 | };
|
6127 | return PathIndex;
|
6128 | }(Index));
|
6129 |
|
6130 |
|
6131 |
|
6132 |
|
6133 |
|
6134 |
|
6135 |
|
6136 |
|
6137 |
|
6138 |
|
6139 |
|
6140 |
|
6141 |
|
6142 |
|
6143 |
|
6144 |
|
6145 |
|
6146 | var ValueIndex = (function (_super) {
|
6147 | tslib.__extends(ValueIndex, _super);
|
6148 | function ValueIndex() {
|
6149 | return _super !== null && _super.apply(this, arguments) || this;
|
6150 | }
|
6151 | ValueIndex.prototype.compare = function (a, b) {
|
6152 | var indexCmp = a.node.compareTo(b.node);
|
6153 | if (indexCmp === 0) {
|
6154 | return nameCompare(a.name, b.name);
|
6155 | }
|
6156 | else {
|
6157 | return indexCmp;
|
6158 | }
|
6159 | };
|
6160 | ValueIndex.prototype.isDefinedOn = function (node) {
|
6161 | return true;
|
6162 | };
|
6163 | ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {
|
6164 | return !oldNode.equals(newNode);
|
6165 | };
|
6166 | ValueIndex.prototype.minPost = function () {
|
6167 |
|
6168 | return NamedNode.MIN;
|
6169 | };
|
6170 | ValueIndex.prototype.maxPost = function () {
|
6171 |
|
6172 | return NamedNode.MAX;
|
6173 | };
|
6174 | ValueIndex.prototype.makePost = function (indexValue, name) {
|
6175 | var valueNode = nodeFromJSON(indexValue);
|
6176 | return new NamedNode(name, valueNode);
|
6177 | };
|
6178 | |
6179 |
|
6180 |
|
6181 | ValueIndex.prototype.toString = function () {
|
6182 | return '.value';
|
6183 | };
|
6184 | return ValueIndex;
|
6185 | }(Index));
|
6186 | var VALUE_INDEX = new ValueIndex();
|
6187 |
|
6188 |
|
6189 |
|
6190 |
|
6191 |
|
6192 |
|
6193 |
|
6194 |
|
6195 |
|
6196 |
|
6197 |
|
6198 |
|
6199 |
|
6200 |
|
6201 |
|
6202 |
|
6203 |
|
6204 | function changeValue(snapshotNode) {
|
6205 | return { type: "value" , snapshotNode: snapshotNode };
|
6206 | }
|
6207 | function changeChildAdded(childName, snapshotNode) {
|
6208 | return { type: "child_added" , snapshotNode: snapshotNode, childName: childName };
|
6209 | }
|
6210 | function changeChildRemoved(childName, snapshotNode) {
|
6211 | return { type: "child_removed" , snapshotNode: snapshotNode, childName: childName };
|
6212 | }
|
6213 | function changeChildChanged(childName, snapshotNode, oldSnap) {
|
6214 | return {
|
6215 | type: "child_changed" ,
|
6216 | snapshotNode: snapshotNode,
|
6217 | childName: childName,
|
6218 | oldSnap: oldSnap
|
6219 | };
|
6220 | }
|
6221 | function changeChildMoved(childName, snapshotNode) {
|
6222 | return { type: "child_moved" , snapshotNode: snapshotNode, childName: childName };
|
6223 | }
|
6224 |
|
6225 |
|
6226 |
|
6227 |
|
6228 |
|
6229 |
|
6230 |
|
6231 |
|
6232 |
|
6233 |
|
6234 |
|
6235 |
|
6236 |
|
6237 |
|
6238 |
|
6239 |
|
6240 |
|
6241 |
|
6242 |
|
6243 |
|
6244 | var IndexedFilter = (function () {
|
6245 | function IndexedFilter(index_) {
|
6246 | this.index_ = index_;
|
6247 | }
|
6248 | IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
|
6249 | util.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');
|
6250 | var oldChild = snap.getImmediateChild(key);
|
6251 |
|
6252 | if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
|
6253 |
|
6254 |
|
6255 |
|
6256 | if (oldChild.isEmpty() === newChild.isEmpty()) {
|
6257 |
|
6258 |
|
6259 |
|
6260 | return snap;
|
6261 | }
|
6262 | }
|
6263 | if (optChangeAccumulator != null) {
|
6264 | if (newChild.isEmpty()) {
|
6265 | if (snap.hasChild(key)) {
|
6266 | optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
|
6267 | }
|
6268 | else {
|
6269 | util.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');
|
6270 | }
|
6271 | }
|
6272 | else if (oldChild.isEmpty()) {
|
6273 | optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
|
6274 | }
|
6275 | else {
|
6276 | optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
|
6277 | }
|
6278 | }
|
6279 | if (snap.isLeafNode() && newChild.isEmpty()) {
|
6280 | return snap;
|
6281 | }
|
6282 | else {
|
6283 |
|
6284 | return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
|
6285 | }
|
6286 | };
|
6287 | IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
|
6288 | if (optChangeAccumulator != null) {
|
6289 | if (!oldSnap.isLeafNode()) {
|
6290 | oldSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
|
6291 | if (!newSnap.hasChild(key)) {
|
6292 | optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
|
6293 | }
|
6294 | });
|
6295 | }
|
6296 | if (!newSnap.isLeafNode()) {
|
6297 | newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
|
6298 | if (oldSnap.hasChild(key)) {
|
6299 | var oldChild = oldSnap.getImmediateChild(key);
|
6300 | if (!oldChild.equals(childNode)) {
|
6301 | optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
|
6302 | }
|
6303 | }
|
6304 | else {
|
6305 | optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
|
6306 | }
|
6307 | });
|
6308 | }
|
6309 | }
|
6310 | return newSnap.withIndex(this.index_);
|
6311 | };
|
6312 | IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
|
6313 | if (oldSnap.isEmpty()) {
|
6314 | return ChildrenNode.EMPTY_NODE;
|
6315 | }
|
6316 | else {
|
6317 | return oldSnap.updatePriority(newPriority);
|
6318 | }
|
6319 | };
|
6320 | IndexedFilter.prototype.filtersNodes = function () {
|
6321 | return false;
|
6322 | };
|
6323 | IndexedFilter.prototype.getIndexedFilter = function () {
|
6324 | return this;
|
6325 | };
|
6326 | IndexedFilter.prototype.getIndex = function () {
|
6327 | return this.index_;
|
6328 | };
|
6329 | return IndexedFilter;
|
6330 | }());
|
6331 |
|
6332 |
|
6333 |
|
6334 |
|
6335 |
|
6336 |
|
6337 |
|
6338 |
|
6339 |
|
6340 |
|
6341 |
|
6342 |
|
6343 |
|
6344 |
|
6345 |
|
6346 |
|
6347 |
|
6348 |
|
6349 |
|
6350 |
|
6351 | var RangedFilter = (function () {
|
6352 | function RangedFilter(params) {
|
6353 | this.indexedFilter_ = new IndexedFilter(params.getIndex());
|
6354 | this.index_ = params.getIndex();
|
6355 | this.startPost_ = RangedFilter.getStartPost_(params);
|
6356 | this.endPost_ = RangedFilter.getEndPost_(params);
|
6357 | this.startIsInclusive_ = !params.startAfterSet_;
|
6358 | this.endIsInclusive_ = !params.endBeforeSet_;
|
6359 | }
|
6360 | RangedFilter.prototype.getStartPost = function () {
|
6361 | return this.startPost_;
|
6362 | };
|
6363 | RangedFilter.prototype.getEndPost = function () {
|
6364 | return this.endPost_;
|
6365 | };
|
6366 | RangedFilter.prototype.matches = function (node) {
|
6367 | var isWithinStart = this.startIsInclusive_
|
6368 | ? this.index_.compare(this.getStartPost(), node) <= 0
|
6369 | : this.index_.compare(this.getStartPost(), node) < 0;
|
6370 | var isWithinEnd = this.endIsInclusive_
|
6371 | ? this.index_.compare(node, this.getEndPost()) <= 0
|
6372 | : this.index_.compare(node, this.getEndPost()) < 0;
|
6373 | return isWithinStart && isWithinEnd;
|
6374 | };
|
6375 | RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
|
6376 | if (!this.matches(new NamedNode(key, newChild))) {
|
6377 | newChild = ChildrenNode.EMPTY_NODE;
|
6378 | }
|
6379 | return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
|
6380 | };
|
6381 | RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
|
6382 | if (newSnap.isLeafNode()) {
|
6383 |
|
6384 | newSnap = ChildrenNode.EMPTY_NODE;
|
6385 | }
|
6386 | var filtered = newSnap.withIndex(this.index_);
|
6387 |
|
6388 | filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
|
6389 | var self = this;
|
6390 | newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {
|
6391 | if (!self.matches(new NamedNode(key, childNode))) {
|
6392 | filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
|
6393 | }
|
6394 | });
|
6395 | return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
|
6396 | };
|
6397 | RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
|
6398 |
|
6399 | return oldSnap;
|
6400 | };
|
6401 | RangedFilter.prototype.filtersNodes = function () {
|
6402 | return true;
|
6403 | };
|
6404 | RangedFilter.prototype.getIndexedFilter = function () {
|
6405 | return this.indexedFilter_;
|
6406 | };
|
6407 | RangedFilter.prototype.getIndex = function () {
|
6408 | return this.index_;
|
6409 | };
|
6410 | RangedFilter.getStartPost_ = function (params) {
|
6411 | if (params.hasStart()) {
|
6412 | var startName = params.getIndexStartName();
|
6413 | return params.getIndex().makePost(params.getIndexStartValue(), startName);
|
6414 | }
|
6415 | else {
|
6416 | return params.getIndex().minPost();
|
6417 | }
|
6418 | };
|
6419 | RangedFilter.getEndPost_ = function (params) {
|
6420 | if (params.hasEnd()) {
|
6421 | var endName = params.getIndexEndName();
|
6422 | return params.getIndex().makePost(params.getIndexEndValue(), endName);
|
6423 | }
|
6424 | else {
|
6425 | return params.getIndex().maxPost();
|
6426 | }
|
6427 | };
|
6428 | return RangedFilter;
|
6429 | }());
|
6430 |
|
6431 |
|
6432 |
|
6433 |
|
6434 |
|
6435 |
|
6436 |
|
6437 |
|
6438 |
|
6439 |
|
6440 |
|
6441 |
|
6442 |
|
6443 |
|
6444 |
|
6445 |
|
6446 |
|
6447 |
|
6448 |
|
6449 |
|
6450 | var LimitedFilter = (function () {
|
6451 | function LimitedFilter(params) {
|
6452 | var _this = this;
|
6453 | this.withinDirectionalStart = function (node) {
|
6454 | return _this.reverse_ ? _this.withinEndPost(node) : _this.withinStartPost(node);
|
6455 | };
|
6456 | this.withinDirectionalEnd = function (node) {
|
6457 | return _this.reverse_ ? _this.withinStartPost(node) : _this.withinEndPost(node);
|
6458 | };
|
6459 | this.withinStartPost = function (node) {
|
6460 | var compareRes = _this.index_.compare(_this.rangedFilter_.getStartPost(), node);
|
6461 | return _this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
|
6462 | };
|
6463 | this.withinEndPost = function (node) {
|
6464 | var compareRes = _this.index_.compare(node, _this.rangedFilter_.getEndPost());
|
6465 | return _this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
|
6466 | };
|
6467 | this.rangedFilter_ = new RangedFilter(params);
|
6468 | this.index_ = params.getIndex();
|
6469 | this.limit_ = params.getLimit();
|
6470 | this.reverse_ = !params.isViewFromLeft();
|
6471 | this.startIsInclusive_ = !params.startAfterSet_;
|
6472 | this.endIsInclusive_ = !params.endBeforeSet_;
|
6473 | }
|
6474 | LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {
|
6475 | if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
|
6476 | newChild = ChildrenNode.EMPTY_NODE;
|
6477 | }
|
6478 | if (snap.getImmediateChild(key).equals(newChild)) {
|
6479 |
|
6480 | return snap;
|
6481 | }
|
6482 | else if (snap.numChildren() < this.limit_) {
|
6483 | return this.rangedFilter_
|
6484 | .getIndexedFilter()
|
6485 | .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
|
6486 | }
|
6487 | else {
|
6488 | return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
|
6489 | }
|
6490 | };
|
6491 | LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {
|
6492 | var filtered;
|
6493 | if (newSnap.isLeafNode() || newSnap.isEmpty()) {
|
6494 |
|
6495 | filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
|
6496 | }
|
6497 | else {
|
6498 | if (this.limit_ * 2 < newSnap.numChildren() &&
|
6499 | newSnap.isIndexed(this.index_)) {
|
6500 |
|
6501 | filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
|
6502 |
|
6503 | var iterator = void 0;
|
6504 | if (this.reverse_) {
|
6505 | iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
|
6506 | }
|
6507 | else {
|
6508 | iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
|
6509 | }
|
6510 | var count = 0;
|
6511 | while (iterator.hasNext() && count < this.limit_) {
|
6512 | var next = iterator.getNext();
|
6513 | if (!this.withinDirectionalStart(next)) {
|
6514 |
|
6515 | continue;
|
6516 | }
|
6517 | else if (!this.withinDirectionalEnd(next)) {
|
6518 |
|
6519 | break;
|
6520 | }
|
6521 | else {
|
6522 | filtered = filtered.updateImmediateChild(next.name, next.node);
|
6523 | count++;
|
6524 | }
|
6525 | }
|
6526 | }
|
6527 | else {
|
6528 |
|
6529 | filtered = newSnap.withIndex(this.index_);
|
6530 |
|
6531 | filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
|
6532 | var iterator = void 0;
|
6533 | if (this.reverse_) {
|
6534 | iterator = filtered.getReverseIterator(this.index_);
|
6535 | }
|
6536 | else {
|
6537 | iterator = filtered.getIterator(this.index_);
|
6538 | }
|
6539 | var count = 0;
|
6540 | while (iterator.hasNext()) {
|
6541 | var next = iterator.getNext();
|
6542 | var inRange = count < this.limit_ &&
|
6543 | this.withinDirectionalStart(next) &&
|
6544 | this.withinDirectionalEnd(next);
|
6545 | if (inRange) {
|
6546 | count++;
|
6547 | }
|
6548 | else {
|
6549 | filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
|
6550 | }
|
6551 | }
|
6552 | }
|
6553 | }
|
6554 | return this.rangedFilter_
|
6555 | .getIndexedFilter()
|
6556 | .updateFullNode(oldSnap, filtered, optChangeAccumulator);
|
6557 | };
|
6558 | LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {
|
6559 |
|
6560 | return oldSnap;
|
6561 | };
|
6562 | LimitedFilter.prototype.filtersNodes = function () {
|
6563 | return true;
|
6564 | };
|
6565 | LimitedFilter.prototype.getIndexedFilter = function () {
|
6566 | return this.rangedFilter_.getIndexedFilter();
|
6567 | };
|
6568 | LimitedFilter.prototype.getIndex = function () {
|
6569 | return this.index_;
|
6570 | };
|
6571 | LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {
|
6572 |
|
6573 | var cmp;
|
6574 | if (this.reverse_) {
|
6575 | var indexCmp_1 = this.index_.getCompare();
|
6576 | cmp = function (a, b) { return indexCmp_1(b, a); };
|
6577 | }
|
6578 | else {
|
6579 | cmp = this.index_.getCompare();
|
6580 | }
|
6581 | var oldEventCache = snap;
|
6582 | util.assert(oldEventCache.numChildren() === this.limit_, '');
|
6583 | var newChildNamedNode = new NamedNode(childKey, childSnap);
|
6584 | var windowBoundary = this.reverse_
|
6585 | ? oldEventCache.getFirstChild(this.index_)
|
6586 | : oldEventCache.getLastChild(this.index_);
|
6587 | var inRange = this.rangedFilter_.matches(newChildNamedNode);
|
6588 | if (oldEventCache.hasChild(childKey)) {
|
6589 | var oldChildSnap = oldEventCache.getImmediateChild(childKey);
|
6590 | var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
|
6591 | while (nextChild != null &&
|
6592 | (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
|
6593 |
|
6594 |
|
6595 |
|
6596 | nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
|
6597 | }
|
6598 | var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
|
6599 | var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
|
6600 | if (remainsInWindow) {
|
6601 | if (changeAccumulator != null) {
|
6602 | changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
|
6603 | }
|
6604 | return oldEventCache.updateImmediateChild(childKey, childSnap);
|
6605 | }
|
6606 | else {
|
6607 | if (changeAccumulator != null) {
|
6608 | changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
|
6609 | }
|
6610 | var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
|
6611 | var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
|
6612 | if (nextChildInRange) {
|
6613 | if (changeAccumulator != null) {
|
6614 | changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
|
6615 | }
|
6616 | return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
|
6617 | }
|
6618 | else {
|
6619 | return newEventCache;
|
6620 | }
|
6621 | }
|
6622 | }
|
6623 | else if (childSnap.isEmpty()) {
|
6624 |
|
6625 | return snap;
|
6626 | }
|
6627 | else if (inRange) {
|
6628 | if (cmp(windowBoundary, newChildNamedNode) >= 0) {
|
6629 | if (changeAccumulator != null) {
|
6630 | changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
|
6631 | changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
|
6632 | }
|
6633 | return oldEventCache
|
6634 | .updateImmediateChild(childKey, childSnap)
|
6635 | .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
|
6636 | }
|
6637 | else {
|
6638 | return snap;
|
6639 | }
|
6640 | }
|
6641 | else {
|
6642 | return snap;
|
6643 | }
|
6644 | };
|
6645 | return LimitedFilter;
|
6646 | }());
|
6647 |
|
6648 |
|
6649 |
|
6650 |
|
6651 |
|
6652 |
|
6653 |
|
6654 |
|
6655 |
|
6656 |
|
6657 |
|
6658 |
|
6659 |
|
6660 |
|
6661 |
|
6662 |
|
6663 |
|
6664 |
|
6665 |
|
6666 |
|
6667 |
|
6668 |
|
6669 |
|
6670 |
|
6671 | var QueryParams = (function () {
|
6672 | function QueryParams() {
|
6673 | this.limitSet_ = false;
|
6674 | this.startSet_ = false;
|
6675 | this.startNameSet_ = false;
|
6676 | this.startAfterSet_ = false;
|
6677 | this.endSet_ = false;
|
6678 | this.endNameSet_ = false;
|
6679 | this.endBeforeSet_ = false;
|
6680 | this.limit_ = 0;
|
6681 | this.viewFrom_ = '';
|
6682 | this.indexStartValue_ = null;
|
6683 | this.indexStartName_ = '';
|
6684 | this.indexEndValue_ = null;
|
6685 | this.indexEndName_ = '';
|
6686 | this.index_ = PRIORITY_INDEX;
|
6687 | }
|
6688 | QueryParams.prototype.hasStart = function () {
|
6689 | return this.startSet_;
|
6690 | };
|
6691 | |
6692 |
|
6693 |
|
6694 | QueryParams.prototype.isViewFromLeft = function () {
|
6695 | if (this.viewFrom_ === '') {
|
6696 |
|
6697 |
|
6698 |
|
6699 |
|
6700 | return this.startSet_;
|
6701 | }
|
6702 | else {
|
6703 | return this.viewFrom_ === "l" ;
|
6704 | }
|
6705 | };
|
6706 | |
6707 |
|
6708 |
|
6709 | QueryParams.prototype.getIndexStartValue = function () {
|
6710 | util.assert(this.startSet_, 'Only valid if start has been set');
|
6711 | return this.indexStartValue_;
|
6712 | };
|
6713 | |
6714 |
|
6715 |
|
6716 |
|
6717 | QueryParams.prototype.getIndexStartName = function () {
|
6718 | util.assert(this.startSet_, 'Only valid if start has been set');
|
6719 | if (this.startNameSet_) {
|
6720 | return this.indexStartName_;
|
6721 | }
|
6722 | else {
|
6723 | return MIN_NAME;
|
6724 | }
|
6725 | };
|
6726 | QueryParams.prototype.hasEnd = function () {
|
6727 | return this.endSet_;
|
6728 | };
|
6729 | |
6730 |
|
6731 |
|
6732 | QueryParams.prototype.getIndexEndValue = function () {
|
6733 | util.assert(this.endSet_, 'Only valid if end has been set');
|
6734 | return this.indexEndValue_;
|
6735 | };
|
6736 | |
6737 |
|
6738 |
|
6739 |
|
6740 | QueryParams.prototype.getIndexEndName = function () {
|
6741 | util.assert(this.endSet_, 'Only valid if end has been set');
|
6742 | if (this.endNameSet_) {
|
6743 | return this.indexEndName_;
|
6744 | }
|
6745 | else {
|
6746 | return MAX_NAME;
|
6747 | }
|
6748 | };
|
6749 | QueryParams.prototype.hasLimit = function () {
|
6750 | return this.limitSet_;
|
6751 | };
|
6752 | |
6753 |
|
6754 |
|
6755 | QueryParams.prototype.hasAnchoredLimit = function () {
|
6756 | return this.limitSet_ && this.viewFrom_ !== '';
|
6757 | };
|
6758 | |
6759 |
|
6760 |
|
6761 | QueryParams.prototype.getLimit = function () {
|
6762 | util.assert(this.limitSet_, 'Only valid if limit has been set');
|
6763 | return this.limit_;
|
6764 | };
|
6765 | QueryParams.prototype.getIndex = function () {
|
6766 | return this.index_;
|
6767 | };
|
6768 | QueryParams.prototype.loadsAllData = function () {
|
6769 | return !(this.startSet_ || this.endSet_ || this.limitSet_);
|
6770 | };
|
6771 | QueryParams.prototype.isDefault = function () {
|
6772 | return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
|
6773 | };
|
6774 | QueryParams.prototype.copy = function () {
|
6775 | var copy = new QueryParams();
|
6776 | copy.limitSet_ = this.limitSet_;
|
6777 | copy.limit_ = this.limit_;
|
6778 | copy.startSet_ = this.startSet_;
|
6779 | copy.startAfterSet_ = this.startAfterSet_;
|
6780 | copy.indexStartValue_ = this.indexStartValue_;
|
6781 | copy.startNameSet_ = this.startNameSet_;
|
6782 | copy.indexStartName_ = this.indexStartName_;
|
6783 | copy.endSet_ = this.endSet_;
|
6784 | copy.endBeforeSet_ = this.endBeforeSet_;
|
6785 | copy.indexEndValue_ = this.indexEndValue_;
|
6786 | copy.endNameSet_ = this.endNameSet_;
|
6787 | copy.indexEndName_ = this.indexEndName_;
|
6788 | copy.index_ = this.index_;
|
6789 | copy.viewFrom_ = this.viewFrom_;
|
6790 | return copy;
|
6791 | };
|
6792 | return QueryParams;
|
6793 | }());
|
6794 | function queryParamsGetNodeFilter(queryParams) {
|
6795 | if (queryParams.loadsAllData()) {
|
6796 | return new IndexedFilter(queryParams.getIndex());
|
6797 | }
|
6798 | else if (queryParams.hasLimit()) {
|
6799 | return new LimitedFilter(queryParams);
|
6800 | }
|
6801 | else {
|
6802 | return new RangedFilter(queryParams);
|
6803 | }
|
6804 | }
|
6805 | function queryParamsLimitToFirst(queryParams, newLimit) {
|
6806 | var newParams = queryParams.copy();
|
6807 | newParams.limitSet_ = true;
|
6808 | newParams.limit_ = newLimit;
|
6809 | newParams.viewFrom_ = "l" ;
|
6810 | return newParams;
|
6811 | }
|
6812 | function queryParamsLimitToLast(queryParams, newLimit) {
|
6813 | var newParams = queryParams.copy();
|
6814 | newParams.limitSet_ = true;
|
6815 | newParams.limit_ = newLimit;
|
6816 | newParams.viewFrom_ = "r" ;
|
6817 | return newParams;
|
6818 | }
|
6819 | function queryParamsStartAt(queryParams, indexValue, key) {
|
6820 | var newParams = queryParams.copy();
|
6821 | newParams.startSet_ = true;
|
6822 | if (indexValue === undefined) {
|
6823 | indexValue = null;
|
6824 | }
|
6825 | newParams.indexStartValue_ = indexValue;
|
6826 | if (key != null) {
|
6827 | newParams.startNameSet_ = true;
|
6828 | newParams.indexStartName_ = key;
|
6829 | }
|
6830 | else {
|
6831 | newParams.startNameSet_ = false;
|
6832 | newParams.indexStartName_ = '';
|
6833 | }
|
6834 | return newParams;
|
6835 | }
|
6836 | function queryParamsStartAfter(queryParams, indexValue, key) {
|
6837 | var params;
|
6838 | if (queryParams.index_ === KEY_INDEX || !!key) {
|
6839 | params = queryParamsStartAt(queryParams, indexValue, key);
|
6840 | }
|
6841 | else {
|
6842 | params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);
|
6843 | }
|
6844 | params.startAfterSet_ = true;
|
6845 | return params;
|
6846 | }
|
6847 | function queryParamsEndAt(queryParams, indexValue, key) {
|
6848 | var newParams = queryParams.copy();
|
6849 | newParams.endSet_ = true;
|
6850 | if (indexValue === undefined) {
|
6851 | indexValue = null;
|
6852 | }
|
6853 | newParams.indexEndValue_ = indexValue;
|
6854 | if (key !== undefined) {
|
6855 | newParams.endNameSet_ = true;
|
6856 | newParams.indexEndName_ = key;
|
6857 | }
|
6858 | else {
|
6859 | newParams.endNameSet_ = false;
|
6860 | newParams.indexEndName_ = '';
|
6861 | }
|
6862 | return newParams;
|
6863 | }
|
6864 | function queryParamsEndBefore(queryParams, indexValue, key) {
|
6865 | var params;
|
6866 | if (queryParams.index_ === KEY_INDEX || !!key) {
|
6867 | params = queryParamsEndAt(queryParams, indexValue, key);
|
6868 | }
|
6869 | else {
|
6870 | params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);
|
6871 | }
|
6872 | params.endBeforeSet_ = true;
|
6873 | return params;
|
6874 | }
|
6875 | function queryParamsOrderBy(queryParams, index) {
|
6876 | var newParams = queryParams.copy();
|
6877 | newParams.index_ = index;
|
6878 | return newParams;
|
6879 | }
|
6880 |
|
6881 |
|
6882 |
|
6883 |
|
6884 |
|
6885 | function queryParamsToRestQueryStringParameters(queryParams) {
|
6886 | var qs = {};
|
6887 | if (queryParams.isDefault()) {
|
6888 | return qs;
|
6889 | }
|
6890 | var orderBy;
|
6891 | if (queryParams.index_ === PRIORITY_INDEX) {
|
6892 | orderBy = "$priority" ;
|
6893 | }
|
6894 | else if (queryParams.index_ === VALUE_INDEX) {
|
6895 | orderBy = "$value" ;
|
6896 | }
|
6897 | else if (queryParams.index_ === KEY_INDEX) {
|
6898 | orderBy = "$key" ;
|
6899 | }
|
6900 | else {
|
6901 | util.assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');
|
6902 | orderBy = queryParams.index_.toString();
|
6903 | }
|
6904 | qs["orderBy" ] = util.stringify(orderBy);
|
6905 | if (queryParams.startSet_) {
|
6906 | var startParam = queryParams.startAfterSet_
|
6907 | ? "startAfter"
|
6908 | : "startAt" ;
|
6909 | qs[startParam] = util.stringify(queryParams.indexStartValue_);
|
6910 | if (queryParams.startNameSet_) {
|
6911 | qs[startParam] += ',' + util.stringify(queryParams.indexStartName_);
|
6912 | }
|
6913 | }
|
6914 | if (queryParams.endSet_) {
|
6915 | var endParam = queryParams.endBeforeSet_
|
6916 | ? "endBefore"
|
6917 | : "endAt" ;
|
6918 | qs[endParam] = util.stringify(queryParams.indexEndValue_);
|
6919 | if (queryParams.endNameSet_) {
|
6920 | qs[endParam] += ',' + util.stringify(queryParams.indexEndName_);
|
6921 | }
|
6922 | }
|
6923 | if (queryParams.limitSet_) {
|
6924 | if (queryParams.isViewFromLeft()) {
|
6925 | qs["limitToFirst" ] = queryParams.limit_;
|
6926 | }
|
6927 | else {
|
6928 | qs["limitToLast" ] = queryParams.limit_;
|
6929 | }
|
6930 | }
|
6931 | return qs;
|
6932 | }
|
6933 | function queryParamsGetQueryObject(queryParams) {
|
6934 | var obj = {};
|
6935 | if (queryParams.startSet_) {
|
6936 | obj["sp" ] =
|
6937 | queryParams.indexStartValue_;
|
6938 | if (queryParams.startNameSet_) {
|
6939 | obj["sn" ] =
|
6940 | queryParams.indexStartName_;
|
6941 | }
|
6942 | obj["sin" ] =
|
6943 | !queryParams.startAfterSet_;
|
6944 | }
|
6945 | if (queryParams.endSet_) {
|
6946 | obj["ep" ] = queryParams.indexEndValue_;
|
6947 | if (queryParams.endNameSet_) {
|
6948 | obj["en" ] = queryParams.indexEndName_;
|
6949 | }
|
6950 | obj["ein" ] =
|
6951 | !queryParams.endBeforeSet_;
|
6952 | }
|
6953 | if (queryParams.limitSet_) {
|
6954 | obj["l" ] = queryParams.limit_;
|
6955 | var viewFrom = queryParams.viewFrom_;
|
6956 | if (viewFrom === '') {
|
6957 | if (queryParams.isViewFromLeft()) {
|
6958 | viewFrom = "l" ;
|
6959 | }
|
6960 | else {
|
6961 | viewFrom = "r" ;
|
6962 | }
|
6963 | }
|
6964 | obj["vf" ] = viewFrom;
|
6965 | }
|
6966 |
|
6967 | if (queryParams.index_ !== PRIORITY_INDEX) {
|
6968 | obj["i" ] = queryParams.index_.toString();
|
6969 | }
|
6970 | return obj;
|
6971 | }
|
6972 |
|
6973 |
|
6974 |
|
6975 |
|
6976 |
|
6977 |
|
6978 |
|
6979 |
|
6980 |
|
6981 |
|
6982 |
|
6983 |
|
6984 |
|
6985 |
|
6986 |
|
6987 |
|
6988 |
|
6989 |
|
6990 |
|
6991 |
|
6992 |
|
6993 |
|
6994 | var ReadonlyRestClient = (function (_super) {
|
6995 | tslib.__extends(ReadonlyRestClient, _super);
|
6996 | |
6997 |
|
6998 |
|
6999 |
|
7000 | function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
|
7001 | var _this = _super.call(this) || this;
|
7002 | _this.repoInfo_ = repoInfo_;
|
7003 | _this.onDataUpdate_ = onDataUpdate_;
|
7004 | _this.authTokenProvider_ = authTokenProvider_;
|
7005 | _this.appCheckTokenProvider_ = appCheckTokenProvider_;
|
7006 |
|
7007 | _this.log_ = logWrapper('p:rest:');
|
7008 | |
7009 |
|
7010 |
|
7011 |
|
7012 | _this.listens_ = {};
|
7013 | return _this;
|
7014 | }
|
7015 | ReadonlyRestClient.prototype.reportStats = function (stats) {
|
7016 | throw new Error('Method not implemented.');
|
7017 | };
|
7018 | ReadonlyRestClient.getListenId_ = function (query, tag) {
|
7019 | if (tag !== undefined) {
|
7020 | return 'tag$' + tag;
|
7021 | }
|
7022 | else {
|
7023 | util.assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
|
7024 | return query._path.toString();
|
7025 | }
|
7026 | };
|
7027 |
|
7028 | ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {
|
7029 | var _this = this;
|
7030 | var pathString = query._path.toString();
|
7031 | this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);
|
7032 |
|
7033 | var listenId = ReadonlyRestClient.getListenId_(query, tag);
|
7034 | var thisListen = {};
|
7035 | this.listens_[listenId] = thisListen;
|
7036 | var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
|
7037 | this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
|
7038 | var data = result;
|
7039 | if (error === 404) {
|
7040 | data = null;
|
7041 | error = null;
|
7042 | }
|
7043 | if (error === null) {
|
7044 | _this.onDataUpdate_(pathString, data, false, tag);
|
7045 | }
|
7046 | if (util.safeGet(_this.listens_, listenId) === thisListen) {
|
7047 | var status_1;
|
7048 | if (!error) {
|
7049 | status_1 = 'ok';
|
7050 | }
|
7051 | else if (error === 401) {
|
7052 | status_1 = 'permission_denied';
|
7053 | }
|
7054 | else {
|
7055 | status_1 = 'rest_error:' + error;
|
7056 | }
|
7057 | onComplete(status_1, null);
|
7058 | }
|
7059 | });
|
7060 | };
|
7061 |
|
7062 | ReadonlyRestClient.prototype.unlisten = function (query, tag) {
|
7063 | var listenId = ReadonlyRestClient.getListenId_(query, tag);
|
7064 | delete this.listens_[listenId];
|
7065 | };
|
7066 | ReadonlyRestClient.prototype.get = function (query) {
|
7067 | var _this = this;
|
7068 | var queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
|
7069 | var pathString = query._path.toString();
|
7070 | var deferred = new util.Deferred();
|
7071 | this.restRequest_(pathString + '.json', queryStringParameters, function (error, result) {
|
7072 | var data = result;
|
7073 | if (error === 404) {
|
7074 | data = null;
|
7075 | error = null;
|
7076 | }
|
7077 | if (error === null) {
|
7078 | _this.onDataUpdate_(pathString, data,
|
7079 | false,
|
7080 | null);
|
7081 | deferred.resolve(data);
|
7082 | }
|
7083 | else {
|
7084 | deferred.reject(new Error(data));
|
7085 | }
|
7086 | });
|
7087 | return deferred.promise;
|
7088 | };
|
7089 |
|
7090 | ReadonlyRestClient.prototype.refreshAuthToken = function (token) {
|
7091 |
|
7092 | };
|
7093 | |
7094 |
|
7095 |
|
7096 |
|
7097 | ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {
|
7098 | var _this = this;
|
7099 | if (queryStringParameters === void 0) { queryStringParameters = {}; }
|
7100 | queryStringParameters['format'] = 'export';
|
7101 | return Promise.all([
|
7102 | this.authTokenProvider_.getToken( false),
|
7103 | this.appCheckTokenProvider_.getToken( false)
|
7104 | ]).then(function (_a) {
|
7105 | var _b = tslib.__read(_a, 2), authToken = _b[0], appCheckToken = _b[1];
|
7106 | if (authToken && authToken.accessToken) {
|
7107 | queryStringParameters['auth'] = authToken.accessToken;
|
7108 | }
|
7109 | if (appCheckToken && appCheckToken.token) {
|
7110 | queryStringParameters['ac'] = appCheckToken.token;
|
7111 | }
|
7112 | var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +
|
7113 | _this.repoInfo_.host +
|
7114 | pathString +
|
7115 | '?' +
|
7116 | 'ns=' +
|
7117 | _this.repoInfo_.namespace +
|
7118 | util.querystring(queryStringParameters);
|
7119 | _this.log_('Sending REST request for ' + url);
|
7120 | var xhr = new XMLHttpRequest();
|
7121 | xhr.onreadystatechange = function () {
|
7122 | if (callback && xhr.readyState === 4) {
|
7123 | _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);
|
7124 | var res = null;
|
7125 | if (xhr.status >= 200 && xhr.status < 300) {
|
7126 | try {
|
7127 | res = util.jsonEval(xhr.responseText);
|
7128 | }
|
7129 | catch (e) {
|
7130 | warn('Failed to parse JSON response for ' +
|
7131 | url +
|
7132 | ': ' +
|
7133 | xhr.responseText);
|
7134 | }
|
7135 | callback(null, res);
|
7136 | }
|
7137 | else {
|
7138 |
|
7139 | if (xhr.status !== 401 && xhr.status !== 404) {
|
7140 | warn('Got unsuccessful REST response for ' +
|
7141 | url +
|
7142 | ' Status: ' +
|
7143 | xhr.status);
|
7144 | }
|
7145 | callback(xhr.status);
|
7146 | }
|
7147 | callback = null;
|
7148 | }
|
7149 | };
|
7150 | xhr.open('GET', url, true);
|
7151 | xhr.send();
|
7152 | });
|
7153 | };
|
7154 | return ReadonlyRestClient;
|
7155 | }(ServerActions));
|
7156 |
|
7157 |
|
7158 |
|
7159 |
|
7160 |
|
7161 |
|
7162 |
|
7163 |
|
7164 |
|
7165 |
|
7166 |
|
7167 |
|
7168 |
|
7169 |
|
7170 |
|
7171 |
|
7172 |
|
7173 |
|
7174 |
|
7175 |
|
7176 | var SnapshotHolder = (function () {
|
7177 | function SnapshotHolder() {
|
7178 | this.rootNode_ = ChildrenNode.EMPTY_NODE;
|
7179 | }
|
7180 | SnapshotHolder.prototype.getNode = function (path) {
|
7181 | return this.rootNode_.getChild(path);
|
7182 | };
|
7183 | SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {
|
7184 | this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
|
7185 | };
|
7186 | return SnapshotHolder;
|
7187 | }());
|
7188 |
|
7189 |
|
7190 |
|
7191 |
|
7192 |
|
7193 |
|
7194 |
|
7195 |
|
7196 |
|
7197 |
|
7198 |
|
7199 |
|
7200 |
|
7201 |
|
7202 |
|
7203 |
|
7204 |
|
7205 | function newSparseSnapshotTree() {
|
7206 | return {
|
7207 | value: null,
|
7208 | children: new Map()
|
7209 | };
|
7210 | }
|
7211 |
|
7212 |
|
7213 |
|
7214 |
|
7215 |
|
7216 |
|
7217 |
|
7218 | function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
|
7219 | if (pathIsEmpty(path)) {
|
7220 | sparseSnapshotTree.value = data;
|
7221 | sparseSnapshotTree.children.clear();
|
7222 | }
|
7223 | else if (sparseSnapshotTree.value !== null) {
|
7224 | sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
|
7225 | }
|
7226 | else {
|
7227 | var childKey = pathGetFront(path);
|
7228 | if (!sparseSnapshotTree.children.has(childKey)) {
|
7229 | sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
|
7230 | }
|
7231 | var child = sparseSnapshotTree.children.get(childKey);
|
7232 | path = pathPopFront(path);
|
7233 | sparseSnapshotTreeRemember(child, path, data);
|
7234 | }
|
7235 | }
|
7236 |
|
7237 |
|
7238 |
|
7239 |
|
7240 |
|
7241 |
|
7242 | function sparseSnapshotTreeForget(sparseSnapshotTree, path) {
|
7243 | if (pathIsEmpty(path)) {
|
7244 | sparseSnapshotTree.value = null;
|
7245 | sparseSnapshotTree.children.clear();
|
7246 | return true;
|
7247 | }
|
7248 | else {
|
7249 | if (sparseSnapshotTree.value !== null) {
|
7250 | if (sparseSnapshotTree.value.isLeafNode()) {
|
7251 |
|
7252 | return false;
|
7253 | }
|
7254 | else {
|
7255 | var value = sparseSnapshotTree.value;
|
7256 | sparseSnapshotTree.value = null;
|
7257 | value.forEachChild(PRIORITY_INDEX, function (key, tree) {
|
7258 | sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);
|
7259 | });
|
7260 | return sparseSnapshotTreeForget(sparseSnapshotTree, path);
|
7261 | }
|
7262 | }
|
7263 | else if (sparseSnapshotTree.children.size > 0) {
|
7264 | var childKey = pathGetFront(path);
|
7265 | path = pathPopFront(path);
|
7266 | if (sparseSnapshotTree.children.has(childKey)) {
|
7267 | var safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);
|
7268 | if (safeToRemove) {
|
7269 | sparseSnapshotTree.children.delete(childKey);
|
7270 | }
|
7271 | }
|
7272 | return sparseSnapshotTree.children.size === 0;
|
7273 | }
|
7274 | else {
|
7275 | return true;
|
7276 | }
|
7277 | }
|
7278 | }
|
7279 |
|
7280 |
|
7281 |
|
7282 |
|
7283 |
|
7284 |
|
7285 |
|
7286 | function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
|
7287 | if (sparseSnapshotTree.value !== null) {
|
7288 | func(prefixPath, sparseSnapshotTree.value);
|
7289 | }
|
7290 | else {
|
7291 | sparseSnapshotTreeForEachChild(sparseSnapshotTree, function (key, tree) {
|
7292 | var path = new Path(prefixPath.toString() + '/' + key);
|
7293 | sparseSnapshotTreeForEachTree(tree, path, func);
|
7294 | });
|
7295 | }
|
7296 | }
|
7297 |
|
7298 |
|
7299 |
|
7300 |
|
7301 |
|
7302 |
|
7303 | function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
|
7304 | sparseSnapshotTree.children.forEach(function (tree, key) {
|
7305 | func(key, tree);
|
7306 | });
|
7307 | }
|
7308 |
|
7309 |
|
7310 |
|
7311 |
|
7312 |
|
7313 |
|
7314 |
|
7315 |
|
7316 |
|
7317 |
|
7318 |
|
7319 |
|
7320 |
|
7321 |
|
7322 |
|
7323 |
|
7324 |
|
7325 |
|
7326 |
|
7327 |
|
7328 |
|
7329 |
|
7330 | var StatsListener = (function () {
|
7331 | function StatsListener(collection_) {
|
7332 | this.collection_ = collection_;
|
7333 | this.last_ = null;
|
7334 | }
|
7335 | StatsListener.prototype.get = function () {
|
7336 | var newStats = this.collection_.get();
|
7337 | var delta = tslib.__assign({}, newStats);
|
7338 | if (this.last_) {
|
7339 | each(this.last_, function (stat, value) {
|
7340 | delta[stat] = delta[stat] - value;
|
7341 | });
|
7342 | }
|
7343 | this.last_ = newStats;
|
7344 | return delta;
|
7345 | };
|
7346 | return StatsListener;
|
7347 | }());
|
7348 |
|
7349 |
|
7350 |
|
7351 |
|
7352 |
|
7353 |
|
7354 |
|
7355 |
|
7356 |
|
7357 |
|
7358 |
|
7359 |
|
7360 |
|
7361 |
|
7362 |
|
7363 |
|
7364 |
|
7365 |
|
7366 |
|
7367 |
|
7368 | var FIRST_STATS_MIN_TIME = 10 * 1000;
|
7369 | var FIRST_STATS_MAX_TIME = 30 * 1000;
|
7370 |
|
7371 | var REPORT_STATS_INTERVAL = 5 * 60 * 1000;
|
7372 | var StatsReporter = (function () {
|
7373 | function StatsReporter(collection, server_) {
|
7374 | this.server_ = server_;
|
7375 | this.statsToReport_ = {};
|
7376 | this.statsListener_ = new StatsListener(collection);
|
7377 | var timeout = FIRST_STATS_MIN_TIME +
|
7378 | (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
|
7379 | setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
|
7380 | }
|
7381 | StatsReporter.prototype.reportStats_ = function () {
|
7382 | var _this = this;
|
7383 | var stats = this.statsListener_.get();
|
7384 | var reportedStats = {};
|
7385 | var haveStatsToReport = false;
|
7386 | each(stats, function (stat, value) {
|
7387 | if (value > 0 && util.contains(_this.statsToReport_, stat)) {
|
7388 | reportedStats[stat] = value;
|
7389 | haveStatsToReport = true;
|
7390 | }
|
7391 | });
|
7392 | if (haveStatsToReport) {
|
7393 | this.server_.reportStats(reportedStats);
|
7394 | }
|
7395 |
|
7396 | setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
|
7397 | };
|
7398 | return StatsReporter;
|
7399 | }());
|
7400 |
|
7401 |
|
7402 |
|
7403 |
|
7404 |
|
7405 |
|
7406 |
|
7407 |
|
7408 |
|
7409 |
|
7410 |
|
7411 |
|
7412 |
|
7413 |
|
7414 |
|
7415 |
|
7416 |
|
7417 |
|
7418 |
|
7419 |
|
7420 |
|
7421 | var OperationType;
|
7422 | (function (OperationType) {
|
7423 | OperationType[OperationType["OVERWRITE"] = 0] = "OVERWRITE";
|
7424 | OperationType[OperationType["MERGE"] = 1] = "MERGE";
|
7425 | OperationType[OperationType["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
|
7426 | OperationType[OperationType["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
|
7427 | })(OperationType || (OperationType = {}));
|
7428 | function newOperationSourceUser() {
|
7429 | return {
|
7430 | fromUser: true,
|
7431 | fromServer: false,
|
7432 | queryId: null,
|
7433 | tagged: false
|
7434 | };
|
7435 | }
|
7436 | function newOperationSourceServer() {
|
7437 | return {
|
7438 | fromUser: false,
|
7439 | fromServer: true,
|
7440 | queryId: null,
|
7441 | tagged: false
|
7442 | };
|
7443 | }
|
7444 | function newOperationSourceServerTaggedQuery(queryId) {
|
7445 | return {
|
7446 | fromUser: false,
|
7447 | fromServer: true,
|
7448 | queryId: queryId,
|
7449 | tagged: true
|
7450 | };
|
7451 | }
|
7452 |
|
7453 |
|
7454 |
|
7455 |
|
7456 |
|
7457 |
|
7458 |
|
7459 |
|
7460 |
|
7461 |
|
7462 |
|
7463 |
|
7464 |
|
7465 |
|
7466 |
|
7467 |
|
7468 |
|
7469 | var AckUserWrite = (function () {
|
7470 | |
7471 |
|
7472 |
|
7473 | function AckUserWrite(
|
7474 | /** @inheritDoc */ path,
|
7475 | /** @inheritDoc */ affectedTree,
|
7476 | /** @inheritDoc */ revert) {
|
7477 | this.path = path;
|
7478 | this.affectedTree = affectedTree;
|
7479 | this.revert = revert;
|
7480 |
|
7481 | this.type = OperationType.ACK_USER_WRITE;
|
7482 |
|
7483 | this.source = newOperationSourceUser();
|
7484 | }
|
7485 | AckUserWrite.prototype.operationForChild = function (childName) {
|
7486 | if (!pathIsEmpty(this.path)) {
|
7487 | util.assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');
|
7488 | return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
|
7489 | }
|
7490 | else if (this.affectedTree.value != null) {
|
7491 | util.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');
|
7492 |
|
7493 | return this;
|
7494 | }
|
7495 | else {
|
7496 | var childTree = this.affectedTree.subtree(new Path(childName));
|
7497 | return new AckUserWrite(newEmptyPath(), childTree, this.revert);
|
7498 | }
|
7499 | };
|
7500 | return AckUserWrite;
|
7501 | }());
|
7502 |
|
7503 |
|
7504 |
|
7505 |
|
7506 |
|
7507 |
|
7508 |
|
7509 |
|
7510 |
|
7511 |
|
7512 |
|
7513 |
|
7514 |
|
7515 |
|
7516 |
|
7517 |
|
7518 |
|
7519 | var ListenComplete = (function () {
|
7520 | function ListenComplete(source, path) {
|
7521 | this.source = source;
|
7522 | this.path = path;
|
7523 |
|
7524 | this.type = OperationType.LISTEN_COMPLETE;
|
7525 | }
|
7526 | ListenComplete.prototype.operationForChild = function (childName) {
|
7527 | if (pathIsEmpty(this.path)) {
|
7528 | return new ListenComplete(this.source, newEmptyPath());
|
7529 | }
|
7530 | else {
|
7531 | return new ListenComplete(this.source, pathPopFront(this.path));
|
7532 | }
|
7533 | };
|
7534 | return ListenComplete;
|
7535 | }());
|
7536 |
|
7537 |
|
7538 |
|
7539 |
|
7540 |
|
7541 |
|
7542 |
|
7543 |
|
7544 |
|
7545 |
|
7546 |
|
7547 |
|
7548 |
|
7549 |
|
7550 |
|
7551 |
|
7552 |
|
7553 | var Overwrite = (function () {
|
7554 | function Overwrite(source, path, snap) {
|
7555 | this.source = source;
|
7556 | this.path = path;
|
7557 | this.snap = snap;
|
7558 |
|
7559 | this.type = OperationType.OVERWRITE;
|
7560 | }
|
7561 | Overwrite.prototype.operationForChild = function (childName) {
|
7562 | if (pathIsEmpty(this.path)) {
|
7563 | return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
|
7564 | }
|
7565 | else {
|
7566 | return new Overwrite(this.source, pathPopFront(this.path), this.snap);
|
7567 | }
|
7568 | };
|
7569 | return Overwrite;
|
7570 | }());
|
7571 |
|
7572 |
|
7573 |
|
7574 |
|
7575 |
|
7576 |
|
7577 |
|
7578 |
|
7579 |
|
7580 |
|
7581 |
|
7582 |
|
7583 |
|
7584 |
|
7585 |
|
7586 |
|
7587 |
|
7588 | var Merge = (function () {
|
7589 | function Merge(
|
7590 | /** @inheritDoc */ source,
|
7591 | /** @inheritDoc */ path,
|
7592 | /** @inheritDoc */ children) {
|
7593 | this.source = source;
|
7594 | this.path = path;
|
7595 | this.children = children;
|
7596 |
|
7597 | this.type = OperationType.MERGE;
|
7598 | }
|
7599 | Merge.prototype.operationForChild = function (childName) {
|
7600 | if (pathIsEmpty(this.path)) {
|
7601 | var childTree = this.children.subtree(new Path(childName));
|
7602 | if (childTree.isEmpty()) {
|
7603 |
|
7604 | return null;
|
7605 | }
|
7606 | else if (childTree.value) {
|
7607 |
|
7608 | return new Overwrite(this.source, newEmptyPath(), childTree.value);
|
7609 | }
|
7610 | else {
|
7611 |
|
7612 | return new Merge(this.source, newEmptyPath(), childTree);
|
7613 | }
|
7614 | }
|
7615 | else {
|
7616 | util.assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
|
7617 | return new Merge(this.source, pathPopFront(this.path), this.children);
|
7618 | }
|
7619 | };
|
7620 | Merge.prototype.toString = function () {
|
7621 | return ('Operation(' +
|
7622 | this.path +
|
7623 | ': ' +
|
7624 | this.source.toString() +
|
7625 | ' merge: ' +
|
7626 | this.children.toString() +
|
7627 | ')');
|
7628 | };
|
7629 | return Merge;
|
7630 | }());
|
7631 |
|
7632 |
|
7633 |
|
7634 |
|
7635 |
|
7636 |
|
7637 |
|
7638 |
|
7639 |
|
7640 |
|
7641 |
|
7642 |
|
7643 |
|
7644 |
|
7645 |
|
7646 |
|
7647 |
|
7648 |
|
7649 |
|
7650 |
|
7651 |
|
7652 |
|
7653 |
|
7654 | var CacheNode = (function () {
|
7655 | function CacheNode(node_, fullyInitialized_, filtered_) {
|
7656 | this.node_ = node_;
|
7657 | this.fullyInitialized_ = fullyInitialized_;
|
7658 | this.filtered_ = filtered_;
|
7659 | }
|
7660 | |
7661 |
|
7662 |
|
7663 | CacheNode.prototype.isFullyInitialized = function () {
|
7664 | return this.fullyInitialized_;
|
7665 | };
|
7666 | |
7667 |
|
7668 |
|
7669 | CacheNode.prototype.isFiltered = function () {
|
7670 | return this.filtered_;
|
7671 | };
|
7672 | CacheNode.prototype.isCompleteForPath = function (path) {
|
7673 | if (pathIsEmpty(path)) {
|
7674 | return this.isFullyInitialized() && !this.filtered_;
|
7675 | }
|
7676 | var childKey = pathGetFront(path);
|
7677 | return this.isCompleteForChild(childKey);
|
7678 | };
|
7679 | CacheNode.prototype.isCompleteForChild = function (key) {
|
7680 | return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));
|
7681 | };
|
7682 | CacheNode.prototype.getNode = function () {
|
7683 | return this.node_;
|
7684 | };
|
7685 | return CacheNode;
|
7686 | }());
|
7687 |
|
7688 |
|
7689 |
|
7690 |
|
7691 |
|
7692 |
|
7693 |
|
7694 |
|
7695 |
|
7696 |
|
7697 |
|
7698 |
|
7699 |
|
7700 |
|
7701 |
|
7702 |
|
7703 |
|
7704 |
|
7705 |
|
7706 |
|
7707 |
|
7708 |
|
7709 |
|
7710 | var EventGenerator = (function () {
|
7711 | function EventGenerator(query_) {
|
7712 | this.query_ = query_;
|
7713 | this.index_ = this.query_._queryParams.getIndex();
|
7714 | }
|
7715 | return EventGenerator;
|
7716 | }());
|
7717 |
|
7718 |
|
7719 |
|
7720 |
|
7721 |
|
7722 |
|
7723 |
|
7724 |
|
7725 |
|
7726 | function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
|
7727 | var events = [];
|
7728 | var moves = [];
|
7729 | changes.forEach(function (change) {
|
7730 | if (change.type === "child_changed" &&
|
7731 | eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
|
7732 | moves.push(changeChildMoved(change.childName, change.snapshotNode));
|
7733 | }
|
7734 | });
|
7735 | eventGeneratorGenerateEventsForType(eventGenerator, events, "child_removed" , changes, eventRegistrations, eventCache);
|
7736 | eventGeneratorGenerateEventsForType(eventGenerator, events, "child_added" , changes, eventRegistrations, eventCache);
|
7737 | eventGeneratorGenerateEventsForType(eventGenerator, events, "child_moved" , moves, eventRegistrations, eventCache);
|
7738 | eventGeneratorGenerateEventsForType(eventGenerator, events, "child_changed" , changes, eventRegistrations, eventCache);
|
7739 | eventGeneratorGenerateEventsForType(eventGenerator, events, "value" , changes, eventRegistrations, eventCache);
|
7740 | return events;
|
7741 | }
|
7742 |
|
7743 |
|
7744 |
|
7745 | function eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {
|
7746 | var filteredChanges = changes.filter(function (change) { return change.type === eventType; });
|
7747 | filteredChanges.sort(function (a, b) {
|
7748 | return eventGeneratorCompareChanges(eventGenerator, a, b);
|
7749 | });
|
7750 | filteredChanges.forEach(function (change) {
|
7751 | var materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
|
7752 | registrations.forEach(function (registration) {
|
7753 | if (registration.respondsTo(change.type)) {
|
7754 | events.push(registration.createEvent(materializedChange, eventGenerator.query_));
|
7755 | }
|
7756 | });
|
7757 | });
|
7758 | }
|
7759 | function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
|
7760 | if (change.type === 'value' || change.type === 'child_removed') {
|
7761 | return change;
|
7762 | }
|
7763 | else {
|
7764 | change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
|
7765 | return change;
|
7766 | }
|
7767 | }
|
7768 | function eventGeneratorCompareChanges(eventGenerator, a, b) {
|
7769 | if (a.childName == null || b.childName == null) {
|
7770 | throw util.assertionError('Should only compare child_ events.');
|
7771 | }
|
7772 | var aWrapped = new NamedNode(a.childName, a.snapshotNode);
|
7773 | var bWrapped = new NamedNode(b.childName, b.snapshotNode);
|
7774 | return eventGenerator.index_.compare(aWrapped, bWrapped);
|
7775 | }
|
7776 |
|
7777 |
|
7778 |
|
7779 |
|
7780 |
|
7781 |
|
7782 |
|
7783 |
|
7784 |
|
7785 |
|
7786 |
|
7787 |
|
7788 |
|
7789 |
|
7790 |
|
7791 |
|
7792 |
|
7793 | function newViewCache(eventCache, serverCache) {
|
7794 | return { eventCache: eventCache, serverCache: serverCache };
|
7795 | }
|
7796 | function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
|
7797 | return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
|
7798 | }
|
7799 | function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
|
7800 | return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
|
7801 | }
|
7802 | function viewCacheGetCompleteEventSnap(viewCache) {
|
7803 | return viewCache.eventCache.isFullyInitialized()
|
7804 | ? viewCache.eventCache.getNode()
|
7805 | : null;
|
7806 | }
|
7807 | function viewCacheGetCompleteServerSnap(viewCache) {
|
7808 | return viewCache.serverCache.isFullyInitialized()
|
7809 | ? viewCache.serverCache.getNode()
|
7810 | : null;
|
7811 | }
|
7812 |
|
7813 |
|
7814 |
|
7815 |
|
7816 |
|
7817 |
|
7818 |
|
7819 |
|
7820 |
|
7821 |
|
7822 |
|
7823 |
|
7824 |
|
7825 |
|
7826 |
|
7827 |
|
7828 |
|
7829 | var emptyChildrenSingleton;
|
7830 |
|
7831 |
|
7832 |
|
7833 |
|
7834 | var EmptyChildren = function () {
|
7835 | if (!emptyChildrenSingleton) {
|
7836 | emptyChildrenSingleton = new SortedMap(stringCompare);
|
7837 | }
|
7838 | return emptyChildrenSingleton;
|
7839 | };
|
7840 |
|
7841 |
|
7842 |
|
7843 | var ImmutableTree = (function () {
|
7844 | function ImmutableTree(value, children) {
|
7845 | if (children === void 0) { children = EmptyChildren(); }
|
7846 | this.value = value;
|
7847 | this.children = children;
|
7848 | }
|
7849 | ImmutableTree.fromObject = function (obj) {
|
7850 | var tree = new ImmutableTree(null);
|
7851 | each(obj, function (childPath, childSnap) {
|
7852 | tree = tree.set(new Path(childPath), childSnap);
|
7853 | });
|
7854 | return tree;
|
7855 | };
|
7856 | |
7857 |
|
7858 |
|
7859 | ImmutableTree.prototype.isEmpty = function () {
|
7860 | return this.value === null && this.children.isEmpty();
|
7861 | };
|
7862 | |
7863 |
|
7864 |
|
7865 |
|
7866 |
|
7867 |
|
7868 |
|
7869 |
|
7870 |
|
7871 |
|
7872 | ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {
|
7873 | if (this.value != null && predicate(this.value)) {
|
7874 | return { path: newEmptyPath(), value: this.value };
|
7875 | }
|
7876 | else {
|
7877 | if (pathIsEmpty(relativePath)) {
|
7878 | return null;
|
7879 | }
|
7880 | else {
|
7881 | var front = pathGetFront(relativePath);
|
7882 | var child = this.children.get(front);
|
7883 | if (child !== null) {
|
7884 | var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
|
7885 | if (childExistingPathAndValue != null) {
|
7886 | var fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
|
7887 | return { path: fullPath, value: childExistingPathAndValue.value };
|
7888 | }
|
7889 | else {
|
7890 | return null;
|
7891 | }
|
7892 | }
|
7893 | else {
|
7894 | return null;
|
7895 | }
|
7896 | }
|
7897 | }
|
7898 | };
|
7899 | |
7900 |
|
7901 |
|
7902 |
|
7903 | ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {
|
7904 | return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });
|
7905 | };
|
7906 | |
7907 |
|
7908 |
|
7909 | ImmutableTree.prototype.subtree = function (relativePath) {
|
7910 | if (pathIsEmpty(relativePath)) {
|
7911 | return this;
|
7912 | }
|
7913 | else {
|
7914 | var front = pathGetFront(relativePath);
|
7915 | var childTree = this.children.get(front);
|
7916 | if (childTree !== null) {
|
7917 | return childTree.subtree(pathPopFront(relativePath));
|
7918 | }
|
7919 | else {
|
7920 | return new ImmutableTree(null);
|
7921 | }
|
7922 | }
|
7923 | };
|
7924 | |
7925 |
|
7926 |
|
7927 |
|
7928 |
|
7929 |
|
7930 |
|
7931 | ImmutableTree.prototype.set = function (relativePath, toSet) {
|
7932 | if (pathIsEmpty(relativePath)) {
|
7933 | return new ImmutableTree(toSet, this.children);
|
7934 | }
|
7935 | else {
|
7936 | var front = pathGetFront(relativePath);
|
7937 | var child = this.children.get(front) || new ImmutableTree(null);
|
7938 | var newChild = child.set(pathPopFront(relativePath), toSet);
|
7939 | var newChildren = this.children.insert(front, newChild);
|
7940 | return new ImmutableTree(this.value, newChildren);
|
7941 | }
|
7942 | };
|
7943 | |
7944 |
|
7945 |
|
7946 |
|
7947 |
|
7948 |
|
7949 | ImmutableTree.prototype.remove = function (relativePath) {
|
7950 | if (pathIsEmpty(relativePath)) {
|
7951 | if (this.children.isEmpty()) {
|
7952 | return new ImmutableTree(null);
|
7953 | }
|
7954 | else {
|
7955 | return new ImmutableTree(null, this.children);
|
7956 | }
|
7957 | }
|
7958 | else {
|
7959 | var front = pathGetFront(relativePath);
|
7960 | var child = this.children.get(front);
|
7961 | if (child) {
|
7962 | var newChild = child.remove(pathPopFront(relativePath));
|
7963 | var newChildren = void 0;
|
7964 | if (newChild.isEmpty()) {
|
7965 | newChildren = this.children.remove(front);
|
7966 | }
|
7967 | else {
|
7968 | newChildren = this.children.insert(front, newChild);
|
7969 | }
|
7970 | if (this.value === null && newChildren.isEmpty()) {
|
7971 | return new ImmutableTree(null);
|
7972 | }
|
7973 | else {
|
7974 | return new ImmutableTree(this.value, newChildren);
|
7975 | }
|
7976 | }
|
7977 | else {
|
7978 | return this;
|
7979 | }
|
7980 | }
|
7981 | };
|
7982 | |
7983 |
|
7984 |
|
7985 |
|
7986 |
|
7987 |
|
7988 | ImmutableTree.prototype.get = function (relativePath) {
|
7989 | if (pathIsEmpty(relativePath)) {
|
7990 | return this.value;
|
7991 | }
|
7992 | else {
|
7993 | var front = pathGetFront(relativePath);
|
7994 | var child = this.children.get(front);
|
7995 | if (child) {
|
7996 | return child.get(pathPopFront(relativePath));
|
7997 | }
|
7998 | else {
|
7999 | return null;
|
8000 | }
|
8001 | }
|
8002 | };
|
8003 | |
8004 |
|
8005 |
|
8006 |
|
8007 |
|
8008 |
|
8009 |
|
8010 | ImmutableTree.prototype.setTree = function (relativePath, newTree) {
|
8011 | if (pathIsEmpty(relativePath)) {
|
8012 | return newTree;
|
8013 | }
|
8014 | else {
|
8015 | var front = pathGetFront(relativePath);
|
8016 | var child = this.children.get(front) || new ImmutableTree(null);
|
8017 | var newChild = child.setTree(pathPopFront(relativePath), newTree);
|
8018 | var newChildren = void 0;
|
8019 | if (newChild.isEmpty()) {
|
8020 | newChildren = this.children.remove(front);
|
8021 | }
|
8022 | else {
|
8023 | newChildren = this.children.insert(front, newChild);
|
8024 | }
|
8025 | return new ImmutableTree(this.value, newChildren);
|
8026 | }
|
8027 | };
|
8028 | |
8029 |
|
8030 |
|
8031 |
|
8032 |
|
8033 | ImmutableTree.prototype.fold = function (fn) {
|
8034 | return this.fold_(newEmptyPath(), fn);
|
8035 | };
|
8036 | |
8037 |
|
8038 |
|
8039 | ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {
|
8040 | var accum = {};
|
8041 | this.children.inorderTraversal(function (childKey, childTree) {
|
8042 | accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);
|
8043 | });
|
8044 | return fn(pathSoFar, this.value, accum);
|
8045 | };
|
8046 | |
8047 |
|
8048 |
|
8049 | ImmutableTree.prototype.findOnPath = function (path, f) {
|
8050 | return this.findOnPath_(path, newEmptyPath(), f);
|
8051 | };
|
8052 | ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {
|
8053 | var result = this.value ? f(pathSoFar, this.value) : false;
|
8054 | if (result) {
|
8055 | return result;
|
8056 | }
|
8057 | else {
|
8058 | if (pathIsEmpty(pathToFollow)) {
|
8059 | return null;
|
8060 | }
|
8061 | else {
|
8062 | var front = pathGetFront(pathToFollow);
|
8063 | var nextChild = this.children.get(front);
|
8064 | if (nextChild) {
|
8065 | return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);
|
8066 | }
|
8067 | else {
|
8068 | return null;
|
8069 | }
|
8070 | }
|
8071 | }
|
8072 | };
|
8073 | ImmutableTree.prototype.foreachOnPath = function (path, f) {
|
8074 | return this.foreachOnPath_(path, newEmptyPath(), f);
|
8075 | };
|
8076 | ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {
|
8077 | if (pathIsEmpty(pathToFollow)) {
|
8078 | return this;
|
8079 | }
|
8080 | else {
|
8081 | if (this.value) {
|
8082 | f(currentRelativePath, this.value);
|
8083 | }
|
8084 | var front = pathGetFront(pathToFollow);
|
8085 | var nextChild = this.children.get(front);
|
8086 | if (nextChild) {
|
8087 | return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);
|
8088 | }
|
8089 | else {
|
8090 | return new ImmutableTree(null);
|
8091 | }
|
8092 | }
|
8093 | };
|
8094 | |
8095 |
|
8096 |
|
8097 |
|
8098 |
|
8099 |
|
8100 | ImmutableTree.prototype.foreach = function (f) {
|
8101 | this.foreach_(newEmptyPath(), f);
|
8102 | };
|
8103 | ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {
|
8104 | this.children.inorderTraversal(function (childName, childTree) {
|
8105 | childTree.foreach_(pathChild(currentRelativePath, childName), f);
|
8106 | });
|
8107 | if (this.value) {
|
8108 | f(currentRelativePath, this.value);
|
8109 | }
|
8110 | };
|
8111 | ImmutableTree.prototype.foreachChild = function (f) {
|
8112 | this.children.inorderTraversal(function (childName, childTree) {
|
8113 | if (childTree.value) {
|
8114 | f(childName, childTree.value);
|
8115 | }
|
8116 | });
|
8117 | };
|
8118 | return ImmutableTree;
|
8119 | }());
|
8120 |
|
8121 |
|
8122 |
|
8123 |
|
8124 |
|
8125 |
|
8126 |
|
8127 |
|
8128 |
|
8129 |
|
8130 |
|
8131 |
|
8132 |
|
8133 |
|
8134 |
|
8135 |
|
8136 |
|
8137 |
|
8138 |
|
8139 |
|
8140 |
|
8141 |
|
8142 |
|
8143 | var CompoundWrite = (function () {
|
8144 | function CompoundWrite(writeTree_) {
|
8145 | this.writeTree_ = writeTree_;
|
8146 | }
|
8147 | CompoundWrite.empty = function () {
|
8148 | return new CompoundWrite(new ImmutableTree(null));
|
8149 | };
|
8150 | return CompoundWrite;
|
8151 | }());
|
8152 | function compoundWriteAddWrite(compoundWrite, path, node) {
|
8153 | if (pathIsEmpty(path)) {
|
8154 | return new CompoundWrite(new ImmutableTree(node));
|
8155 | }
|
8156 | else {
|
8157 | var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
|
8158 | if (rootmost != null) {
|
8159 | var rootMostPath = rootmost.path;
|
8160 | var value = rootmost.value;
|
8161 | var relativePath = newRelativePath(rootMostPath, path);
|
8162 | value = value.updateChild(relativePath, node);
|
8163 | return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
|
8164 | }
|
8165 | else {
|
8166 | var subtree = new ImmutableTree(node);
|
8167 | var newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);
|
8168 | return new CompoundWrite(newWriteTree);
|
8169 | }
|
8170 | }
|
8171 | }
|
8172 | function compoundWriteAddWrites(compoundWrite, path, updates) {
|
8173 | var newWrite = compoundWrite;
|
8174 | each(updates, function (childKey, node) {
|
8175 | newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
|
8176 | });
|
8177 | return newWrite;
|
8178 | }
|
8179 |
|
8180 |
|
8181 |
|
8182 |
|
8183 |
|
8184 |
|
8185 |
|
8186 |
|
8187 | function compoundWriteRemoveWrite(compoundWrite, path) {
|
8188 | if (pathIsEmpty(path)) {
|
8189 | return CompoundWrite.empty();
|
8190 | }
|
8191 | else {
|
8192 | var newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
|
8193 | return new CompoundWrite(newWriteTree);
|
8194 | }
|
8195 | }
|
8196 |
|
8197 |
|
8198 |
|
8199 |
|
8200 |
|
8201 |
|
8202 |
|
8203 |
|
8204 | function compoundWriteHasCompleteWrite(compoundWrite, path) {
|
8205 | return compoundWriteGetCompleteNode(compoundWrite, path) != null;
|
8206 | }
|
8207 |
|
8208 |
|
8209 |
|
8210 |
|
8211 |
|
8212 |
|
8213 |
|
8214 |
|
8215 | function compoundWriteGetCompleteNode(compoundWrite, path) {
|
8216 | var rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
|
8217 | if (rootmost != null) {
|
8218 | return compoundWrite.writeTree_
|
8219 | .get(rootmost.path)
|
8220 | .getChild(newRelativePath(rootmost.path, path));
|
8221 | }
|
8222 | else {
|
8223 | return null;
|
8224 | }
|
8225 | }
|
8226 |
|
8227 |
|
8228 |
|
8229 |
|
8230 |
|
8231 |
|
8232 | function compoundWriteGetCompleteChildren(compoundWrite) {
|
8233 | var children = [];
|
8234 | var node = compoundWrite.writeTree_.value;
|
8235 | if (node != null) {
|
8236 |
|
8237 | if (!node.isLeafNode()) {
|
8238 | node.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
|
8239 | children.push(new NamedNode(childName, childNode));
|
8240 | });
|
8241 | }
|
8242 | }
|
8243 | else {
|
8244 | compoundWrite.writeTree_.children.inorderTraversal(function (childName, childTree) {
|
8245 | if (childTree.value != null) {
|
8246 | children.push(new NamedNode(childName, childTree.value));
|
8247 | }
|
8248 | });
|
8249 | }
|
8250 | return children;
|
8251 | }
|
8252 | function compoundWriteChildCompoundWrite(compoundWrite, path) {
|
8253 | if (pathIsEmpty(path)) {
|
8254 | return compoundWrite;
|
8255 | }
|
8256 | else {
|
8257 | var shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
|
8258 | if (shadowingNode != null) {
|
8259 | return new CompoundWrite(new ImmutableTree(shadowingNode));
|
8260 | }
|
8261 | else {
|
8262 | return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
|
8263 | }
|
8264 | }
|
8265 | }
|
8266 |
|
8267 |
|
8268 |
|
8269 |
|
8270 | function compoundWriteIsEmpty(compoundWrite) {
|
8271 | return compoundWrite.writeTree_.isEmpty();
|
8272 | }
|
8273 |
|
8274 |
|
8275 |
|
8276 |
|
8277 |
|
8278 |
|
8279 | function compoundWriteApply(compoundWrite, node) {
|
8280 | return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
|
8281 | }
|
8282 | function applySubtreeWrite(relativePath, writeTree, node) {
|
8283 | if (writeTree.value != null) {
|
8284 |
|
8285 | return node.updateChild(relativePath, writeTree.value);
|
8286 | }
|
8287 | else {
|
8288 | var priorityWrite_1 = null;
|
8289 | writeTree.children.inorderTraversal(function (childKey, childTree) {
|
8290 | if (childKey === '.priority') {
|
8291 |
|
8292 |
|
8293 | util.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');
|
8294 | priorityWrite_1 = childTree.value;
|
8295 | }
|
8296 | else {
|
8297 | node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
|
8298 | }
|
8299 | });
|
8300 |
|
8301 | if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {
|
8302 | node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite_1);
|
8303 | }
|
8304 | return node;
|
8305 | }
|
8306 | }
|
8307 |
|
8308 |
|
8309 |
|
8310 |
|
8311 |
|
8312 |
|
8313 |
|
8314 |
|
8315 |
|
8316 |
|
8317 |
|
8318 |
|
8319 |
|
8320 |
|
8321 |
|
8322 |
|
8323 |
|
8324 |
|
8325 |
|
8326 |
|
8327 |
|
8328 | function writeTreeChildWrites(writeTree, path) {
|
8329 | return newWriteTreeRef(path, writeTree);
|
8330 | }
|
8331 |
|
8332 |
|
8333 |
|
8334 |
|
8335 |
|
8336 | function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
|
8337 | util.assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');
|
8338 | if (visible === undefined) {
|
8339 | visible = true;
|
8340 | }
|
8341 | writeTree.allWrites.push({
|
8342 | path: path,
|
8343 | snap: snap,
|
8344 | writeId: writeId,
|
8345 | visible: visible
|
8346 | });
|
8347 | if (visible) {
|
8348 | writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
|
8349 | }
|
8350 | writeTree.lastWriteId = writeId;
|
8351 | }
|
8352 |
|
8353 |
|
8354 |
|
8355 | function writeTreeAddMerge(writeTree, path, changedChildren, writeId) {
|
8356 | util.assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');
|
8357 | writeTree.allWrites.push({
|
8358 | path: path,
|
8359 | children: changedChildren,
|
8360 | writeId: writeId,
|
8361 | visible: true
|
8362 | });
|
8363 | writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);
|
8364 | writeTree.lastWriteId = writeId;
|
8365 | }
|
8366 | function writeTreeGetWrite(writeTree, writeId) {
|
8367 | for (var i = 0; i < writeTree.allWrites.length; i++) {
|
8368 | var record = writeTree.allWrites[i];
|
8369 | if (record.writeId === writeId) {
|
8370 | return record;
|
8371 | }
|
8372 | }
|
8373 | return null;
|
8374 | }
|
8375 |
|
8376 |
|
8377 |
|
8378 |
|
8379 |
|
8380 |
|
8381 |
|
8382 | function writeTreeRemoveWrite(writeTree, writeId) {
|
8383 |
|
8384 |
|
8385 |
|
8386 |
|
8387 | var idx = writeTree.allWrites.findIndex(function (s) {
|
8388 | return s.writeId === writeId;
|
8389 | });
|
8390 | util.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');
|
8391 | var writeToRemove = writeTree.allWrites[idx];
|
8392 | writeTree.allWrites.splice(idx, 1);
|
8393 | var removedWriteWasVisible = writeToRemove.visible;
|
8394 | var removedWriteOverlapsWithOtherWrites = false;
|
8395 | var i = writeTree.allWrites.length - 1;
|
8396 | while (removedWriteWasVisible && i >= 0) {
|
8397 | var currentWrite = writeTree.allWrites[i];
|
8398 | if (currentWrite.visible) {
|
8399 | if (i >= idx &&
|
8400 | writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
|
8401 |
|
8402 | removedWriteWasVisible = false;
|
8403 | }
|
8404 | else if (pathContains(writeToRemove.path, currentWrite.path)) {
|
8405 |
|
8406 | removedWriteOverlapsWithOtherWrites = true;
|
8407 | }
|
8408 | }
|
8409 | i--;
|
8410 | }
|
8411 | if (!removedWriteWasVisible) {
|
8412 | return false;
|
8413 | }
|
8414 | else if (removedWriteOverlapsWithOtherWrites) {
|
8415 |
|
8416 | writeTreeResetTree_(writeTree);
|
8417 | return true;
|
8418 | }
|
8419 | else {
|
8420 |
|
8421 | if (writeToRemove.snap) {
|
8422 | writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
|
8423 | }
|
8424 | else {
|
8425 | var children = writeToRemove.children;
|
8426 | each(children, function (childName) {
|
8427 | writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
|
8428 | });
|
8429 | }
|
8430 | return true;
|
8431 | }
|
8432 | }
|
8433 | function writeTreeRecordContainsPath_(writeRecord, path) {
|
8434 | if (writeRecord.snap) {
|
8435 | return pathContains(writeRecord.path, path);
|
8436 | }
|
8437 | else {
|
8438 | for (var childName in writeRecord.children) {
|
8439 | if (writeRecord.children.hasOwnProperty(childName) &&
|
8440 | pathContains(pathChild(writeRecord.path, childName), path)) {
|
8441 | return true;
|
8442 | }
|
8443 | }
|
8444 | return false;
|
8445 | }
|
8446 | }
|
8447 |
|
8448 |
|
8449 |
|
8450 | function writeTreeResetTree_(writeTree) {
|
8451 | writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
|
8452 | if (writeTree.allWrites.length > 0) {
|
8453 | writeTree.lastWriteId =
|
8454 | writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
|
8455 | }
|
8456 | else {
|
8457 | writeTree.lastWriteId = -1;
|
8458 | }
|
8459 | }
|
8460 |
|
8461 |
|
8462 |
|
8463 | function writeTreeDefaultFilter_(write) {
|
8464 | return write.visible;
|
8465 | }
|
8466 |
|
8467 |
|
8468 |
|
8469 |
|
8470 | function writeTreeLayerTree_(writes, filter, treeRoot) {
|
8471 | var compoundWrite = CompoundWrite.empty();
|
8472 | for (var i = 0; i < writes.length; ++i) {
|
8473 | var write = writes[i];
|
8474 |
|
8475 |
|
8476 |
|
8477 | if (filter(write)) {
|
8478 | var writePath = write.path;
|
8479 | var relativePath = void 0;
|
8480 | if (write.snap) {
|
8481 | if (pathContains(treeRoot, writePath)) {
|
8482 | relativePath = newRelativePath(treeRoot, writePath);
|
8483 | compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
|
8484 | }
|
8485 | else if (pathContains(writePath, treeRoot)) {
|
8486 | relativePath = newRelativePath(writePath, treeRoot);
|
8487 | compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
|
8488 | }
|
8489 | else ;
|
8490 | }
|
8491 | else if (write.children) {
|
8492 | if (pathContains(treeRoot, writePath)) {
|
8493 | relativePath = newRelativePath(treeRoot, writePath);
|
8494 | compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
|
8495 | }
|
8496 | else if (pathContains(writePath, treeRoot)) {
|
8497 | relativePath = newRelativePath(writePath, treeRoot);
|
8498 | if (pathIsEmpty(relativePath)) {
|
8499 | compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
|
8500 | }
|
8501 | else {
|
8502 | var child = util.safeGet(write.children, pathGetFront(relativePath));
|
8503 | if (child) {
|
8504 |
|
8505 | var deepNode = child.getChild(pathPopFront(relativePath));
|
8506 | compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
|
8507 | }
|
8508 | }
|
8509 | }
|
8510 | else ;
|
8511 | }
|
8512 | else {
|
8513 | throw util.assertionError('WriteRecord should have .snap or .children');
|
8514 | }
|
8515 | }
|
8516 | }
|
8517 | return compoundWrite;
|
8518 | }
|
8519 |
|
8520 |
|
8521 |
|
8522 |
|
8523 |
|
8524 |
|
8525 |
|
8526 | function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
|
8527 | if (!writeIdsToExclude && !includeHiddenWrites) {
|
8528 | var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
|
8529 | if (shadowingNode != null) {
|
8530 | return shadowingNode;
|
8531 | }
|
8532 | else {
|
8533 | var subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
|
8534 | if (compoundWriteIsEmpty(subMerge)) {
|
8535 | return completeServerCache;
|
8536 | }
|
8537 | else if (completeServerCache == null &&
|
8538 | !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
|
8539 |
|
8540 | return null;
|
8541 | }
|
8542 | else {
|
8543 | var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
|
8544 | return compoundWriteApply(subMerge, layeredCache);
|
8545 | }
|
8546 | }
|
8547 | }
|
8548 | else {
|
8549 | var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
|
8550 | if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
|
8551 | return completeServerCache;
|
8552 | }
|
8553 | else {
|
8554 |
|
8555 | if (!includeHiddenWrites &&
|
8556 | completeServerCache == null &&
|
8557 | !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
|
8558 | return null;
|
8559 | }
|
8560 | else {
|
8561 | var filter = function (write) {
|
8562 | return ((write.visible || includeHiddenWrites) &&
|
8563 | (!writeIdsToExclude ||
|
8564 | !~writeIdsToExclude.indexOf(write.writeId)) &&
|
8565 | (pathContains(write.path, treePath) ||
|
8566 | pathContains(treePath, write.path)));
|
8567 | };
|
8568 | var mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
|
8569 | var layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
|
8570 | return compoundWriteApply(mergeAtPath, layeredCache);
|
8571 | }
|
8572 | }
|
8573 | }
|
8574 | }
|
8575 |
|
8576 |
|
8577 |
|
8578 |
|
8579 | function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
|
8580 | var completeChildren = ChildrenNode.EMPTY_NODE;
|
8581 | var topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
|
8582 | if (topLevelSet) {
|
8583 | if (!topLevelSet.isLeafNode()) {
|
8584 |
|
8585 | topLevelSet.forEachChild(PRIORITY_INDEX, function (childName, childSnap) {
|
8586 | completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
|
8587 | });
|
8588 | }
|
8589 | return completeChildren;
|
8590 | }
|
8591 | else if (completeServerChildren) {
|
8592 |
|
8593 |
|
8594 | var merge_1 = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
|
8595 | completeServerChildren.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
|
8596 | var node = compoundWriteApply(compoundWriteChildCompoundWrite(merge_1, new Path(childName)), childNode);
|
8597 | completeChildren = completeChildren.updateImmediateChild(childName, node);
|
8598 | });
|
8599 |
|
8600 | compoundWriteGetCompleteChildren(merge_1).forEach(function (namedNode) {
|
8601 | completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
|
8602 | });
|
8603 | return completeChildren;
|
8604 | }
|
8605 | else {
|
8606 |
|
8607 |
|
8608 | var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
|
8609 | compoundWriteGetCompleteChildren(merge).forEach(function (namedNode) {
|
8610 | completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
|
8611 | });
|
8612 | return completeChildren;
|
8613 | }
|
8614 | }
|
8615 |
|
8616 |
|
8617 |
|
8618 |
|
8619 |
|
8620 |
|
8621 |
|
8622 |
|
8623 |
|
8624 |
|
8625 |
|
8626 |
|
8627 |
|
8628 |
|
8629 | function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
|
8630 | util.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');
|
8631 | var path = pathChild(treePath, childPath);
|
8632 | if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
|
8633 |
|
8634 |
|
8635 | return null;
|
8636 | }
|
8637 | else {
|
8638 |
|
8639 | var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
|
8640 | if (compoundWriteIsEmpty(childMerge)) {
|
8641 |
|
8642 | return existingServerSnap.getChild(childPath);
|
8643 | }
|
8644 | else {
|
8645 |
|
8646 |
|
8647 |
|
8648 |
|
8649 |
|
8650 |
|
8651 | return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
|
8652 | }
|
8653 | }
|
8654 | }
|
8655 |
|
8656 |
|
8657 |
|
8658 |
|
8659 | function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
|
8660 | var path = pathChild(treePath, childKey);
|
8661 | var shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
|
8662 | if (shadowingNode != null) {
|
8663 | return shadowingNode;
|
8664 | }
|
8665 | else {
|
8666 | if (existingServerSnap.isCompleteForChild(childKey)) {
|
8667 | var childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
|
8668 | return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
|
8669 | }
|
8670 | else {
|
8671 | return null;
|
8672 | }
|
8673 | }
|
8674 | }
|
8675 |
|
8676 |
|
8677 |
|
8678 |
|
8679 |
|
8680 | function writeTreeShadowingWrite(writeTree, path) {
|
8681 | return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
|
8682 | }
|
8683 |
|
8684 |
|
8685 |
|
8686 |
|
8687 | function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {
|
8688 | var toIterate;
|
8689 | var merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
|
8690 | var shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
|
8691 | if (shadowingNode != null) {
|
8692 | toIterate = shadowingNode;
|
8693 | }
|
8694 | else if (completeServerData != null) {
|
8695 | toIterate = compoundWriteApply(merge, completeServerData);
|
8696 | }
|
8697 | else {
|
8698 |
|
8699 | return [];
|
8700 | }
|
8701 | toIterate = toIterate.withIndex(index);
|
8702 | if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
|
8703 | var nodes = [];
|
8704 | var cmp = index.getCompare();
|
8705 | var iter = reverse
|
8706 | ? toIterate.getReverseIteratorFrom(startPost, index)
|
8707 | : toIterate.getIteratorFrom(startPost, index);
|
8708 | var next = iter.getNext();
|
8709 | while (next && nodes.length < count) {
|
8710 | if (cmp(next, startPost) !== 0) {
|
8711 | nodes.push(next);
|
8712 | }
|
8713 | next = iter.getNext();
|
8714 | }
|
8715 | return nodes;
|
8716 | }
|
8717 | else {
|
8718 | return [];
|
8719 | }
|
8720 | }
|
8721 | function newWriteTree() {
|
8722 | return {
|
8723 | visibleWrites: CompoundWrite.empty(),
|
8724 | allWrites: [],
|
8725 | lastWriteId: -1
|
8726 | };
|
8727 | }
|
8728 |
|
8729 |
|
8730 |
|
8731 |
|
8732 |
|
8733 |
|
8734 |
|
8735 |
|
8736 | function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
|
8737 | return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
|
8738 | }
|
8739 |
|
8740 |
|
8741 |
|
8742 |
|
8743 |
|
8744 | function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
|
8745 | return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
|
8746 | }
|
8747 |
|
8748 |
|
8749 |
|
8750 |
|
8751 |
|
8752 |
|
8753 |
|
8754 |
|
8755 |
|
8756 |
|
8757 |
|
8758 |
|
8759 |
|
8760 |
|
8761 |
|
8762 |
|
8763 | function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
|
8764 | return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
|
8765 | }
|
8766 |
|
8767 |
|
8768 |
|
8769 |
|
8770 |
|
8771 |
|
8772 | function writeTreeRefShadowingWrite(writeTreeRef, path) {
|
8773 | return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
|
8774 | }
|
8775 |
|
8776 |
|
8777 |
|
8778 |
|
8779 | function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {
|
8780 | return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);
|
8781 | }
|
8782 |
|
8783 |
|
8784 |
|
8785 |
|
8786 | function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
|
8787 | return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
|
8788 | }
|
8789 |
|
8790 |
|
8791 |
|
8792 | function writeTreeRefChild(writeTreeRef, childName) {
|
8793 | return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
|
8794 | }
|
8795 | function newWriteTreeRef(path, writeTree) {
|
8796 | return {
|
8797 | treePath: path,
|
8798 | writeTree: writeTree
|
8799 | };
|
8800 | }
|
8801 |
|
8802 |
|
8803 |
|
8804 |
|
8805 |
|
8806 |
|
8807 |
|
8808 |
|
8809 |
|
8810 |
|
8811 |
|
8812 |
|
8813 |
|
8814 |
|
8815 |
|
8816 |
|
8817 |
|
8818 | var ChildChangeAccumulator = (function () {
|
8819 | function ChildChangeAccumulator() {
|
8820 | this.changeMap = new Map();
|
8821 | }
|
8822 | ChildChangeAccumulator.prototype.trackChildChange = function (change) {
|
8823 | var type = change.type;
|
8824 | var childKey = change.childName;
|
8825 | util.assert(type === "child_added" ||
|
8826 | type === "child_changed" ||
|
8827 | type === "child_removed" , 'Only child changes supported for tracking');
|
8828 | util.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');
|
8829 | var oldChange = this.changeMap.get(childKey);
|
8830 | if (oldChange) {
|
8831 | var oldType = oldChange.type;
|
8832 | if (type === "child_added" &&
|
8833 | oldType === "child_removed" ) {
|
8834 | this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
|
8835 | }
|
8836 | else if (type === "child_removed" &&
|
8837 | oldType === "child_added" ) {
|
8838 | this.changeMap.delete(childKey);
|
8839 | }
|
8840 | else if (type === "child_removed" &&
|
8841 | oldType === "child_changed" ) {
|
8842 | this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
|
8843 | }
|
8844 | else if (type === "child_changed" &&
|
8845 | oldType === "child_added" ) {
|
8846 | this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
|
8847 | }
|
8848 | else if (type === "child_changed" &&
|
8849 | oldType === "child_changed" ) {
|
8850 | this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
|
8851 | }
|
8852 | else {
|
8853 | throw util.assertionError('Illegal combination of changes: ' +
|
8854 | change +
|
8855 | ' occurred after ' +
|
8856 | oldChange);
|
8857 | }
|
8858 | }
|
8859 | else {
|
8860 | this.changeMap.set(childKey, change);
|
8861 | }
|
8862 | };
|
8863 | ChildChangeAccumulator.prototype.getChanges = function () {
|
8864 | return Array.from(this.changeMap.values());
|
8865 | };
|
8866 | return ChildChangeAccumulator;
|
8867 | }());
|
8868 |
|
8869 |
|
8870 |
|
8871 |
|
8872 |
|
8873 |
|
8874 |
|
8875 |
|
8876 |
|
8877 |
|
8878 |
|
8879 |
|
8880 |
|
8881 |
|
8882 |
|
8883 |
|
8884 |
|
8885 |
|
8886 |
|
8887 |
|
8888 |
|
8889 | var NoCompleteChildSource_ = (function () {
|
8890 | function NoCompleteChildSource_() {
|
8891 | }
|
8892 | NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {
|
8893 | return null;
|
8894 | };
|
8895 | NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {
|
8896 | return null;
|
8897 | };
|
8898 | return NoCompleteChildSource_;
|
8899 | }());
|
8900 |
|
8901 |
|
8902 |
|
8903 | var NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
|
8904 |
|
8905 |
|
8906 |
|
8907 |
|
8908 | var WriteTreeCompleteChildSource = (function () {
|
8909 | function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {
|
8910 | if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }
|
8911 | this.writes_ = writes_;
|
8912 | this.viewCache_ = viewCache_;
|
8913 | this.optCompleteServerCache_ = optCompleteServerCache_;
|
8914 | }
|
8915 | WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {
|
8916 | var node = this.viewCache_.eventCache;
|
8917 | if (node.isCompleteForChild(childKey)) {
|
8918 | return node.getNode().getImmediateChild(childKey);
|
8919 | }
|
8920 | else {
|
8921 | var serverNode = this.optCompleteServerCache_ != null
|
8922 | ? new CacheNode(this.optCompleteServerCache_, true, false)
|
8923 | : this.viewCache_.serverCache;
|
8924 | return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
|
8925 | }
|
8926 | };
|
8927 | WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {
|
8928 | var completeServerData = this.optCompleteServerCache_ != null
|
8929 | ? this.optCompleteServerCache_
|
8930 | : viewCacheGetCompleteServerSnap(this.viewCache_);
|
8931 | var nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);
|
8932 | if (nodes.length === 0) {
|
8933 | return null;
|
8934 | }
|
8935 | else {
|
8936 | return nodes[0];
|
8937 | }
|
8938 | };
|
8939 | return WriteTreeCompleteChildSource;
|
8940 | }());
|
8941 |
|
8942 |
|
8943 |
|
8944 |
|
8945 |
|
8946 |
|
8947 |
|
8948 |
|
8949 |
|
8950 |
|
8951 |
|
8952 |
|
8953 |
|
8954 |
|
8955 |
|
8956 |
|
8957 |
|
8958 | function newViewProcessor(filter) {
|
8959 | return { filter: filter };
|
8960 | }
|
8961 | function viewProcessorAssertIndexed(viewProcessor, viewCache) {
|
8962 | util.assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');
|
8963 | util.assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');
|
8964 | }
|
8965 | function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
|
8966 | var accumulator = new ChildChangeAccumulator();
|
8967 | var newViewCache, filterServerNode;
|
8968 | if (operation.type === OperationType.OVERWRITE) {
|
8969 | var overwrite = operation;
|
8970 | if (overwrite.source.fromUser) {
|
8971 | newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
|
8972 | }
|
8973 | else {
|
8974 | util.assert(overwrite.source.fromServer, 'Unknown source.');
|
8975 |
|
8976 |
|
8977 |
|
8978 | filterServerNode =
|
8979 | overwrite.source.tagged ||
|
8980 | (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));
|
8981 | newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
|
8982 | }
|
8983 | }
|
8984 | else if (operation.type === OperationType.MERGE) {
|
8985 | var merge = operation;
|
8986 | if (merge.source.fromUser) {
|
8987 | newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
|
8988 | }
|
8989 | else {
|
8990 | util.assert(merge.source.fromServer, 'Unknown source.');
|
8991 |
|
8992 | filterServerNode =
|
8993 | merge.source.tagged || oldViewCache.serverCache.isFiltered();
|
8994 | newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
|
8995 | }
|
8996 | }
|
8997 | else if (operation.type === OperationType.ACK_USER_WRITE) {
|
8998 | var ackUserWrite = operation;
|
8999 | if (!ackUserWrite.revert) {
|
9000 | newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
|
9001 | }
|
9002 | else {
|
9003 | newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
|
9004 | }
|
9005 | }
|
9006 | else if (operation.type === OperationType.LISTEN_COMPLETE) {
|
9007 | newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
|
9008 | }
|
9009 | else {
|
9010 | throw util.assertionError('Unknown operation type: ' + operation.type);
|
9011 | }
|
9012 | var changes = accumulator.getChanges();
|
9013 | viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);
|
9014 | return { viewCache: newViewCache, changes: changes };
|
9015 | }
|
9016 | function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {
|
9017 | var eventSnap = newViewCache.eventCache;
|
9018 | if (eventSnap.isFullyInitialized()) {
|
9019 | var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
|
9020 | var oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
|
9021 | if (accumulator.length > 0 ||
|
9022 | !oldViewCache.eventCache.isFullyInitialized() ||
|
9023 | (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||
|
9024 | !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
|
9025 | accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));
|
9026 | }
|
9027 | }
|
9028 | }
|
9029 | function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
|
9030 | var oldEventSnap = viewCache.eventCache;
|
9031 | if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
|
9032 |
|
9033 | return viewCache;
|
9034 | }
|
9035 | else {
|
9036 | var newEventCache = void 0, serverNode = void 0;
|
9037 | if (pathIsEmpty(changePath)) {
|
9038 |
|
9039 | util.assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');
|
9040 | if (viewCache.serverCache.isFiltered()) {
|
9041 |
|
9042 |
|
9043 |
|
9044 | var serverCache = viewCacheGetCompleteServerSnap(viewCache);
|
9045 | var completeChildren = serverCache instanceof ChildrenNode
|
9046 | ? serverCache
|
9047 | : ChildrenNode.EMPTY_NODE;
|
9048 | var completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
|
9049 | newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
|
9050 | }
|
9051 | else {
|
9052 | var completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
|
9053 | newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
|
9054 | }
|
9055 | }
|
9056 | else {
|
9057 | var childKey = pathGetFront(changePath);
|
9058 | if (childKey === '.priority') {
|
9059 | util.assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
|
9060 | var oldEventNode = oldEventSnap.getNode();
|
9061 | serverNode = viewCache.serverCache.getNode();
|
9062 |
|
9063 | var updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
|
9064 | if (updatedPriority != null) {
|
9065 | newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
|
9066 | }
|
9067 | else {
|
9068 |
|
9069 | newEventCache = oldEventSnap.getNode();
|
9070 | }
|
9071 | }
|
9072 | else {
|
9073 | var childChangePath = pathPopFront(changePath);
|
9074 |
|
9075 | var newEventChild = void 0;
|
9076 | if (oldEventSnap.isCompleteForChild(childKey)) {
|
9077 | serverNode = viewCache.serverCache.getNode();
|
9078 | var eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
|
9079 | if (eventChildUpdate != null) {
|
9080 | newEventChild = oldEventSnap
|
9081 | .getNode()
|
9082 | .getImmediateChild(childKey)
|
9083 | .updateChild(childChangePath, eventChildUpdate);
|
9084 | }
|
9085 | else {
|
9086 |
|
9087 | newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
|
9088 | }
|
9089 | }
|
9090 | else {
|
9091 | newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
|
9092 | }
|
9093 | if (newEventChild != null) {
|
9094 | newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
|
9095 | }
|
9096 | else {
|
9097 |
|
9098 | newEventCache = oldEventSnap.getNode();
|
9099 | }
|
9100 | }
|
9101 | }
|
9102 | return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
|
9103 | }
|
9104 | }
|
9105 | function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
|
9106 | var oldServerSnap = oldViewCache.serverCache;
|
9107 | var newServerCache;
|
9108 | var serverFilter = filterServerNode
|
9109 | ? viewProcessor.filter
|
9110 | : viewProcessor.filter.getIndexedFilter();
|
9111 | if (pathIsEmpty(changePath)) {
|
9112 | newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
|
9113 | }
|
9114 | else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
|
9115 |
|
9116 | var newServerNode = oldServerSnap
|
9117 | .getNode()
|
9118 | .updateChild(changePath, changedSnap);
|
9119 | newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
|
9120 | }
|
9121 | else {
|
9122 | var childKey = pathGetFront(changePath);
|
9123 | if (!oldServerSnap.isCompleteForPath(changePath) &&
|
9124 | pathGetLength(changePath) > 1) {
|
9125 |
|
9126 | return oldViewCache;
|
9127 | }
|
9128 | var childChangePath = pathPopFront(changePath);
|
9129 | var childNode = oldServerSnap.getNode().getImmediateChild(childKey);
|
9130 | var newChildNode = childNode.updateChild(childChangePath, changedSnap);
|
9131 | if (childKey === '.priority') {
|
9132 | newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
|
9133 | }
|
9134 | else {
|
9135 | newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
|
9136 | }
|
9137 | }
|
9138 | var newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
|
9139 | var source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);
|
9140 | return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);
|
9141 | }
|
9142 | function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
|
9143 | var oldEventSnap = oldViewCache.eventCache;
|
9144 | var newViewCache, newEventCache;
|
9145 | var source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
|
9146 | if (pathIsEmpty(changePath)) {
|
9147 | newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
|
9148 | newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
|
9149 | }
|
9150 | else {
|
9151 | var childKey = pathGetFront(changePath);
|
9152 | if (childKey === '.priority') {
|
9153 | newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
|
9154 | newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
|
9155 | }
|
9156 | else {
|
9157 | var childChangePath = pathPopFront(changePath);
|
9158 | var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
|
9159 | var newChild = void 0;
|
9160 | if (pathIsEmpty(childChangePath)) {
|
9161 |
|
9162 | newChild = changedSnap;
|
9163 | }
|
9164 | else {
|
9165 | var childNode = source.getCompleteChild(childKey);
|
9166 | if (childNode != null) {
|
9167 | if (pathGetBack(childChangePath) === '.priority' &&
|
9168 | childNode.getChild(pathParent(childChangePath)).isEmpty()) {
|
9169 |
|
9170 |
|
9171 | newChild = childNode;
|
9172 | }
|
9173 | else {
|
9174 | newChild = childNode.updateChild(childChangePath, changedSnap);
|
9175 | }
|
9176 | }
|
9177 | else {
|
9178 |
|
9179 | newChild = ChildrenNode.EMPTY_NODE;
|
9180 | }
|
9181 | }
|
9182 | if (!oldChild.equals(newChild)) {
|
9183 | var newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
|
9184 | newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
|
9185 | }
|
9186 | else {
|
9187 | newViewCache = oldViewCache;
|
9188 | }
|
9189 | }
|
9190 | }
|
9191 | return newViewCache;
|
9192 | }
|
9193 | function viewProcessorCacheHasChild(viewCache, childKey) {
|
9194 | return viewCache.eventCache.isCompleteForChild(childKey);
|
9195 | }
|
9196 | function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
|
9197 |
|
9198 |
|
9199 |
|
9200 |
|
9201 |
|
9202 |
|
9203 | var curViewCache = viewCache;
|
9204 | changedChildren.foreach(function (relativePath, childNode) {
|
9205 | var writePath = pathChild(path, relativePath);
|
9206 | if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
|
9207 | curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
|
9208 | }
|
9209 | });
|
9210 | changedChildren.foreach(function (relativePath, childNode) {
|
9211 | var writePath = pathChild(path, relativePath);
|
9212 | if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
|
9213 | curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
|
9214 | }
|
9215 | });
|
9216 | return curViewCache;
|
9217 | }
|
9218 | function viewProcessorApplyMerge(viewProcessor, node, merge) {
|
9219 | merge.foreach(function (relativePath, childNode) {
|
9220 | node = node.updateChild(relativePath, childNode);
|
9221 | });
|
9222 | return node;
|
9223 | }
|
9224 | function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
|
9225 |
|
9226 |
|
9227 | if (viewCache.serverCache.getNode().isEmpty() &&
|
9228 | !viewCache.serverCache.isFullyInitialized()) {
|
9229 | return viewCache;
|
9230 | }
|
9231 |
|
9232 |
|
9233 |
|
9234 |
|
9235 |
|
9236 |
|
9237 | var curViewCache = viewCache;
|
9238 | var viewMergeTree;
|
9239 | if (pathIsEmpty(path)) {
|
9240 | viewMergeTree = changedChildren;
|
9241 | }
|
9242 | else {
|
9243 | viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
|
9244 | }
|
9245 | var serverNode = viewCache.serverCache.getNode();
|
9246 | viewMergeTree.children.inorderTraversal(function (childKey, childTree) {
|
9247 | if (serverNode.hasChild(childKey)) {
|
9248 | var serverChild = viewCache.serverCache
|
9249 | .getNode()
|
9250 | .getImmediateChild(childKey);
|
9251 | var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
|
9252 | curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
|
9253 | }
|
9254 | });
|
9255 | viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {
|
9256 | var isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&
|
9257 | childMergeTree.value === null;
|
9258 | if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
|
9259 | var serverChild = viewCache.serverCache
|
9260 | .getNode()
|
9261 | .getImmediateChild(childKey);
|
9262 | var newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
|
9263 | curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
|
9264 | }
|
9265 | });
|
9266 | return curViewCache;
|
9267 | }
|
9268 | function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
|
9269 | if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
|
9270 | return viewCache;
|
9271 | }
|
9272 |
|
9273 | var filterServerNode = viewCache.serverCache.isFiltered();
|
9274 |
|
9275 |
|
9276 | var serverCache = viewCache.serverCache;
|
9277 | if (affectedTree.value != null) {
|
9278 |
|
9279 | if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||
|
9280 | serverCache.isCompleteForPath(ackPath)) {
|
9281 | return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
|
9282 | }
|
9283 | else if (pathIsEmpty(ackPath)) {
|
9284 |
|
9285 |
|
9286 | var changedChildren_1 = new ImmutableTree(null);
|
9287 | serverCache.getNode().forEachChild(KEY_INDEX, function (name, node) {
|
9288 | changedChildren_1 = changedChildren_1.set(new Path(name), node);
|
9289 | });
|
9290 | return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);
|
9291 | }
|
9292 | else {
|
9293 | return viewCache;
|
9294 | }
|
9295 | }
|
9296 | else {
|
9297 |
|
9298 | var changedChildren_2 = new ImmutableTree(null);
|
9299 | affectedTree.foreach(function (mergePath, value) {
|
9300 | var serverCachePath = pathChild(ackPath, mergePath);
|
9301 | if (serverCache.isCompleteForPath(serverCachePath)) {
|
9302 | changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));
|
9303 | }
|
9304 | });
|
9305 | return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);
|
9306 | }
|
9307 | }
|
9308 | function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
|
9309 | var oldServerNode = viewCache.serverCache;
|
9310 | var newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
|
9311 | return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
|
9312 | }
|
9313 | function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
|
9314 | var complete;
|
9315 | if (writeTreeRefShadowingWrite(writesCache, path) != null) {
|
9316 | return viewCache;
|
9317 | }
|
9318 | else {
|
9319 | var source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
|
9320 | var oldEventCache = viewCache.eventCache.getNode();
|
9321 | var newEventCache = void 0;
|
9322 | if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {
|
9323 | var newNode = void 0;
|
9324 | if (viewCache.serverCache.isFullyInitialized()) {
|
9325 | newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
|
9326 | }
|
9327 | else {
|
9328 | var serverChildren = viewCache.serverCache.getNode();
|
9329 | util.assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');
|
9330 | newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
|
9331 | }
|
9332 | newNode = newNode;
|
9333 | newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
|
9334 | }
|
9335 | else {
|
9336 | var childKey = pathGetFront(path);
|
9337 | var newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
|
9338 | if (newChild == null &&
|
9339 | viewCache.serverCache.isCompleteForChild(childKey)) {
|
9340 | newChild = oldEventCache.getImmediateChild(childKey);
|
9341 | }
|
9342 | if (newChild != null) {
|
9343 | newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
|
9344 | }
|
9345 | else if (viewCache.eventCache.getNode().hasChild(childKey)) {
|
9346 |
|
9347 | newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
|
9348 | }
|
9349 | else {
|
9350 | newEventCache = oldEventCache;
|
9351 | }
|
9352 | if (newEventCache.isEmpty() &&
|
9353 | viewCache.serverCache.isFullyInitialized()) {
|
9354 |
|
9355 | complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
|
9356 | if (complete.isLeafNode()) {
|
9357 | newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
|
9358 | }
|
9359 | }
|
9360 | }
|
9361 | complete =
|
9362 | viewCache.serverCache.isFullyInitialized() ||
|
9363 | writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
|
9364 | return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
|
9365 | }
|
9366 | }
|
9367 |
|
9368 |
|
9369 |
|
9370 |
|
9371 |
|
9372 |
|
9373 |
|
9374 |
|
9375 |
|
9376 |
|
9377 |
|
9378 |
|
9379 |
|
9380 |
|
9381 |
|
9382 |
|
9383 |
|
9384 |
|
9385 |
|
9386 |
|
9387 |
|
9388 |
|
9389 |
|
9390 |
|
9391 |
|
9392 |
|
9393 | var View = (function () {
|
9394 | function View(query_, initialViewCache) {
|
9395 | this.query_ = query_;
|
9396 | this.eventRegistrations_ = [];
|
9397 | var params = this.query_._queryParams;
|
9398 | var indexFilter = new IndexedFilter(params.getIndex());
|
9399 | var filter = queryParamsGetNodeFilter(params);
|
9400 | this.processor_ = newViewProcessor(filter);
|
9401 | var initialServerCache = initialViewCache.serverCache;
|
9402 | var initialEventCache = initialViewCache.eventCache;
|
9403 |
|
9404 | var serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
|
9405 | var eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
|
9406 | var newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
|
9407 | var newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
|
9408 | this.viewCache_ = newViewCache(newEventCache, newServerCache);
|
9409 | this.eventGenerator_ = new EventGenerator(this.query_);
|
9410 | }
|
9411 | Object.defineProperty(View.prototype, "query", {
|
9412 | get: function () {
|
9413 | return this.query_;
|
9414 | },
|
9415 | enumerable: false,
|
9416 | configurable: true
|
9417 | });
|
9418 | return View;
|
9419 | }());
|
9420 | function viewGetServerCache(view) {
|
9421 | return view.viewCache_.serverCache.getNode();
|
9422 | }
|
9423 | function viewGetCompleteNode(view) {
|
9424 | return viewCacheGetCompleteEventSnap(view.viewCache_);
|
9425 | }
|
9426 | function viewGetCompleteServerCache(view, path) {
|
9427 | var cache = viewCacheGetCompleteServerSnap(view.viewCache_);
|
9428 | if (cache) {
|
9429 |
|
9430 |
|
9431 | if (view.query._queryParams.loadsAllData() ||
|
9432 | (!pathIsEmpty(path) &&
|
9433 | !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {
|
9434 | return cache.getChild(path);
|
9435 | }
|
9436 | }
|
9437 | return null;
|
9438 | }
|
9439 | function viewIsEmpty(view) {
|
9440 | return view.eventRegistrations_.length === 0;
|
9441 | }
|
9442 | function viewAddEventRegistration(view, eventRegistration) {
|
9443 | view.eventRegistrations_.push(eventRegistration);
|
9444 | }
|
9445 |
|
9446 |
|
9447 |
|
9448 |
|
9449 |
|
9450 | function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
|
9451 | var cancelEvents = [];
|
9452 | if (cancelError) {
|
9453 | util.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');
|
9454 | var path_1 = view.query._path;
|
9455 | view.eventRegistrations_.forEach(function (registration) {
|
9456 | var maybeEvent = registration.createCancelEvent(cancelError, path_1);
|
9457 | if (maybeEvent) {
|
9458 | cancelEvents.push(maybeEvent);
|
9459 | }
|
9460 | });
|
9461 | }
|
9462 | if (eventRegistration) {
|
9463 | var remaining = [];
|
9464 | for (var i = 0; i < view.eventRegistrations_.length; ++i) {
|
9465 | var existing = view.eventRegistrations_[i];
|
9466 | if (!existing.matches(eventRegistration)) {
|
9467 | remaining.push(existing);
|
9468 | }
|
9469 | else if (eventRegistration.hasAnyCallback()) {
|
9470 |
|
9471 | remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));
|
9472 | break;
|
9473 | }
|
9474 | }
|
9475 | view.eventRegistrations_ = remaining;
|
9476 | }
|
9477 | else {
|
9478 | view.eventRegistrations_ = [];
|
9479 | }
|
9480 | return cancelEvents;
|
9481 | }
|
9482 |
|
9483 |
|
9484 |
|
9485 | function viewApplyOperation(view, operation, writesCache, completeServerCache) {
|
9486 | if (operation.type === OperationType.MERGE &&
|
9487 | operation.source.queryId !== null) {
|
9488 | util.assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');
|
9489 | util.assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');
|
9490 | }
|
9491 | var oldViewCache = view.viewCache_;
|
9492 | var result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
|
9493 | viewProcessorAssertIndexed(view.processor_, result.viewCache);
|
9494 | util.assert(result.viewCache.serverCache.isFullyInitialized() ||
|
9495 | !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');
|
9496 | view.viewCache_ = result.viewCache;
|
9497 | return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
|
9498 | }
|
9499 | function viewGetInitialEvents(view, registration) {
|
9500 | var eventSnap = view.viewCache_.eventCache;
|
9501 | var initialChanges = [];
|
9502 | if (!eventSnap.getNode().isLeafNode()) {
|
9503 | var eventNode = eventSnap.getNode();
|
9504 | eventNode.forEachChild(PRIORITY_INDEX, function (key, childNode) {
|
9505 | initialChanges.push(changeChildAdded(key, childNode));
|
9506 | });
|
9507 | }
|
9508 | if (eventSnap.isFullyInitialized()) {
|
9509 | initialChanges.push(changeValue(eventSnap.getNode()));
|
9510 | }
|
9511 | return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
|
9512 | }
|
9513 | function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
|
9514 | var registrations = eventRegistration
|
9515 | ? [eventRegistration]
|
9516 | : view.eventRegistrations_;
|
9517 | return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
|
9518 | }
|
9519 |
|
9520 |
|
9521 |
|
9522 |
|
9523 |
|
9524 |
|
9525 |
|
9526 |
|
9527 |
|
9528 |
|
9529 |
|
9530 |
|
9531 |
|
9532 |
|
9533 |
|
9534 |
|
9535 |
|
9536 | var referenceConstructor$1;
|
9537 |
|
9538 |
|
9539 |
|
9540 |
|
9541 |
|
9542 |
|
9543 |
|
9544 |
|
9545 |
|
9546 |
|
9547 | var SyncPoint = (function () {
|
9548 | function SyncPoint() {
|
9549 | |
9550 |
|
9551 |
|
9552 |
|
9553 |
|
9554 |
|
9555 | this.views = new Map();
|
9556 | }
|
9557 | return SyncPoint;
|
9558 | }());
|
9559 | function syncPointSetReferenceConstructor(val) {
|
9560 | util.assert(!referenceConstructor$1, '__referenceConstructor has already been defined');
|
9561 | referenceConstructor$1 = val;
|
9562 | }
|
9563 | function syncPointGetReferenceConstructor() {
|
9564 | util.assert(referenceConstructor$1, 'Reference.ts has not been loaded');
|
9565 | return referenceConstructor$1;
|
9566 | }
|
9567 | function syncPointIsEmpty(syncPoint) {
|
9568 | return syncPoint.views.size === 0;
|
9569 | }
|
9570 | function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
|
9571 | var e_1, _a;
|
9572 | var queryId = operation.source.queryId;
|
9573 | if (queryId !== null) {
|
9574 | var view = syncPoint.views.get(queryId);
|
9575 | util.assert(view != null, 'SyncTree gave us an op for an invalid query.');
|
9576 | return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
|
9577 | }
|
9578 | else {
|
9579 | var events = [];
|
9580 | try {
|
9581 | for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
|
9582 | var view = _c.value;
|
9583 | events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
|
9584 | }
|
9585 | }
|
9586 | catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
9587 | finally {
|
9588 | try {
|
9589 | if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
9590 | }
|
9591 | finally { if (e_1) throw e_1.error; }
|
9592 | }
|
9593 | return events;
|
9594 | }
|
9595 | }
|
9596 |
|
9597 |
|
9598 |
|
9599 |
|
9600 |
|
9601 |
|
9602 |
|
9603 |
|
9604 |
|
9605 | function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
|
9606 | var queryId = query._queryIdentifier;
|
9607 | var view = syncPoint.views.get(queryId);
|
9608 | if (!view) {
|
9609 |
|
9610 | var eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
|
9611 | var eventCacheComplete = false;
|
9612 | if (eventCache) {
|
9613 | eventCacheComplete = true;
|
9614 | }
|
9615 | else if (serverCache instanceof ChildrenNode) {
|
9616 | eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
|
9617 | eventCacheComplete = false;
|
9618 | }
|
9619 | else {
|
9620 | eventCache = ChildrenNode.EMPTY_NODE;
|
9621 | eventCacheComplete = false;
|
9622 | }
|
9623 | var viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
|
9624 | return new View(query, viewCache);
|
9625 | }
|
9626 | return view;
|
9627 | }
|
9628 |
|
9629 |
|
9630 |
|
9631 |
|
9632 |
|
9633 |
|
9634 |
|
9635 |
|
9636 |
|
9637 |
|
9638 | function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
|
9639 | var view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
|
9640 | if (!syncPoint.views.has(query._queryIdentifier)) {
|
9641 | syncPoint.views.set(query._queryIdentifier, view);
|
9642 | }
|
9643 |
|
9644 | viewAddEventRegistration(view, eventRegistration);
|
9645 | return viewGetInitialEvents(view, eventRegistration);
|
9646 | }
|
9647 |
|
9648 |
|
9649 |
|
9650 |
|
9651 |
|
9652 |
|
9653 |
|
9654 |
|
9655 |
|
9656 |
|
9657 | function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
|
9658 | var e_2, _a;
|
9659 | var queryId = query._queryIdentifier;
|
9660 | var removed = [];
|
9661 | var cancelEvents = [];
|
9662 | var hadCompleteView = syncPointHasCompleteView(syncPoint);
|
9663 | if (queryId === 'default') {
|
9664 | try {
|
9665 |
|
9666 | for (var _b = tslib.__values(syncPoint.views.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
|
9667 | var _d = tslib.__read(_c.value, 2), viewQueryId = _d[0], view = _d[1];
|
9668 | cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
|
9669 | if (viewIsEmpty(view)) {
|
9670 | syncPoint.views.delete(viewQueryId);
|
9671 |
|
9672 | if (!view.query._queryParams.loadsAllData()) {
|
9673 | removed.push(view.query);
|
9674 | }
|
9675 | }
|
9676 | }
|
9677 | }
|
9678 | catch (e_2_1) { e_2 = { error: e_2_1 }; }
|
9679 | finally {
|
9680 | try {
|
9681 | if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
9682 | }
|
9683 | finally { if (e_2) throw e_2.error; }
|
9684 | }
|
9685 | }
|
9686 | else {
|
9687 |
|
9688 | var view = syncPoint.views.get(queryId);
|
9689 | if (view) {
|
9690 | cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
|
9691 | if (viewIsEmpty(view)) {
|
9692 | syncPoint.views.delete(queryId);
|
9693 |
|
9694 | if (!view.query._queryParams.loadsAllData()) {
|
9695 | removed.push(view.query);
|
9696 | }
|
9697 | }
|
9698 | }
|
9699 | }
|
9700 | if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
|
9701 |
|
9702 | removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
|
9703 | }
|
9704 | return { removed: removed, events: cancelEvents };
|
9705 | }
|
9706 | function syncPointGetQueryViews(syncPoint) {
|
9707 | var e_3, _a;
|
9708 | var result = [];
|
9709 | try {
|
9710 | for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
|
9711 | var view = _c.value;
|
9712 | if (!view.query._queryParams.loadsAllData()) {
|
9713 | result.push(view);
|
9714 | }
|
9715 | }
|
9716 | }
|
9717 | catch (e_3_1) { e_3 = { error: e_3_1 }; }
|
9718 | finally {
|
9719 | try {
|
9720 | if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
9721 | }
|
9722 | finally { if (e_3) throw e_3.error; }
|
9723 | }
|
9724 | return result;
|
9725 | }
|
9726 |
|
9727 |
|
9728 |
|
9729 |
|
9730 | function syncPointGetCompleteServerCache(syncPoint, path) {
|
9731 | var e_4, _a;
|
9732 | var serverCache = null;
|
9733 | try {
|
9734 | for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
|
9735 | var view = _c.value;
|
9736 | serverCache = serverCache || viewGetCompleteServerCache(view, path);
|
9737 | }
|
9738 | }
|
9739 | catch (e_4_1) { e_4 = { error: e_4_1 }; }
|
9740 | finally {
|
9741 | try {
|
9742 | if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
9743 | }
|
9744 | finally { if (e_4) throw e_4.error; }
|
9745 | }
|
9746 | return serverCache;
|
9747 | }
|
9748 | function syncPointViewForQuery(syncPoint, query) {
|
9749 | var params = query._queryParams;
|
9750 | if (params.loadsAllData()) {
|
9751 | return syncPointGetCompleteView(syncPoint);
|
9752 | }
|
9753 | else {
|
9754 | var queryId = query._queryIdentifier;
|
9755 | return syncPoint.views.get(queryId);
|
9756 | }
|
9757 | }
|
9758 | function syncPointViewExistsForQuery(syncPoint, query) {
|
9759 | return syncPointViewForQuery(syncPoint, query) != null;
|
9760 | }
|
9761 | function syncPointHasCompleteView(syncPoint) {
|
9762 | return syncPointGetCompleteView(syncPoint) != null;
|
9763 | }
|
9764 | function syncPointGetCompleteView(syncPoint) {
|
9765 | var e_5, _a;
|
9766 | try {
|
9767 | for (var _b = tslib.__values(syncPoint.views.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
|
9768 | var view = _c.value;
|
9769 | if (view.query._queryParams.loadsAllData()) {
|
9770 | return view;
|
9771 | }
|
9772 | }
|
9773 | }
|
9774 | catch (e_5_1) { e_5 = { error: e_5_1 }; }
|
9775 | finally {
|
9776 | try {
|
9777 | if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
9778 | }
|
9779 | finally { if (e_5) throw e_5.error; }
|
9780 | }
|
9781 | return null;
|
9782 | }
|
9783 |
|
9784 |
|
9785 |
|
9786 |
|
9787 |
|
9788 |
|
9789 |
|
9790 |
|
9791 |
|
9792 |
|
9793 |
|
9794 |
|
9795 |
|
9796 |
|
9797 |
|
9798 |
|
9799 |
|
9800 | var referenceConstructor;
|
9801 | function syncTreeSetReferenceConstructor(val) {
|
9802 | util.assert(!referenceConstructor, '__referenceConstructor has already been defined');
|
9803 | referenceConstructor = val;
|
9804 | }
|
9805 | function syncTreeGetReferenceConstructor() {
|
9806 | util.assert(referenceConstructor, 'Reference.ts has not been loaded');
|
9807 | return referenceConstructor;
|
9808 | }
|
9809 |
|
9810 |
|
9811 |
|
9812 | var syncTreeNextQueryTag_ = 1;
|
9813 |
|
9814 |
|
9815 |
|
9816 |
|
9817 |
|
9818 |
|
9819 |
|
9820 |
|
9821 |
|
9822 |
|
9823 |
|
9824 |
|
9825 |
|
9826 |
|
9827 |
|
9828 |
|
9829 |
|
9830 |
|
9831 |
|
9832 |
|
9833 |
|
9834 | var SyncTree = (function () {
|
9835 | |
9836 |
|
9837 |
|
9838 |
|
9839 | function SyncTree(listenProvider_) {
|
9840 | this.listenProvider_ = listenProvider_;
|
9841 | |
9842 |
|
9843 |
|
9844 | this.syncPointTree_ = new ImmutableTree(null);
|
9845 | |
9846 |
|
9847 |
|
9848 | this.pendingWriteTree_ = newWriteTree();
|
9849 | this.tagToQueryMap = new Map();
|
9850 | this.queryToTagMap = new Map();
|
9851 | }
|
9852 | return SyncTree;
|
9853 | }());
|
9854 |
|
9855 |
|
9856 |
|
9857 |
|
9858 |
|
9859 | function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
|
9860 |
|
9861 | writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
|
9862 | if (!visible) {
|
9863 | return [];
|
9864 | }
|
9865 | else {
|
9866 | return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
|
9867 | }
|
9868 | }
|
9869 |
|
9870 |
|
9871 |
|
9872 |
|
9873 |
|
9874 | function syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {
|
9875 |
|
9876 | writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);
|
9877 | var changeTree = ImmutableTree.fromObject(changedChildren);
|
9878 | return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));
|
9879 | }
|
9880 |
|
9881 |
|
9882 |
|
9883 |
|
9884 |
|
9885 |
|
9886 | function syncTreeAckUserWrite(syncTree, writeId, revert) {
|
9887 | if (revert === void 0) { revert = false; }
|
9888 | var write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
|
9889 | var needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
|
9890 | if (!needToReevaluate) {
|
9891 | return [];
|
9892 | }
|
9893 | else {
|
9894 | var affectedTree_1 = new ImmutableTree(null);
|
9895 | if (write.snap != null) {
|
9896 |
|
9897 | affectedTree_1 = affectedTree_1.set(newEmptyPath(), true);
|
9898 | }
|
9899 | else {
|
9900 | each(write.children, function (pathString) {
|
9901 | affectedTree_1 = affectedTree_1.set(new Path(pathString), true);
|
9902 | });
|
9903 | }
|
9904 | return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree_1, revert));
|
9905 | }
|
9906 | }
|
9907 |
|
9908 |
|
9909 |
|
9910 |
|
9911 |
|
9912 | function syncTreeApplyServerOverwrite(syncTree, path, newData) {
|
9913 | return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
|
9914 | }
|
9915 |
|
9916 |
|
9917 |
|
9918 |
|
9919 |
|
9920 | function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
|
9921 | var changeTree = ImmutableTree.fromObject(changedChildren);
|
9922 | return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
|
9923 | }
|
9924 |
|
9925 |
|
9926 |
|
9927 |
|
9928 |
|
9929 | function syncTreeApplyListenComplete(syncTree, path) {
|
9930 | return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
|
9931 | }
|
9932 |
|
9933 |
|
9934 |
|
9935 |
|
9936 |
|
9937 | function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
|
9938 | var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
|
9939 | if (queryKey) {
|
9940 | var r = syncTreeParseQueryKey_(queryKey);
|
9941 | var queryPath = r.path, queryId = r.queryId;
|
9942 | var relativePath = newRelativePath(queryPath, path);
|
9943 | var op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
|
9944 | return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
|
9945 | }
|
9946 | else {
|
9947 |
|
9948 | return [];
|
9949 | }
|
9950 | }
|
9951 |
|
9952 |
|
9953 |
|
9954 |
|
9955 |
|
9956 |
|
9957 |
|
9958 |
|
9959 |
|
9960 |
|
9961 |
|
9962 |
|
9963 | function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup) {
|
9964 | if (skipListenerDedup === void 0) { skipListenerDedup = false; }
|
9965 |
|
9966 | var path = query._path;
|
9967 | var maybeSyncPoint = syncTree.syncPointTree_.get(path);
|
9968 | var cancelEvents = [];
|
9969 |
|
9970 |
|
9971 |
|
9972 | if (maybeSyncPoint &&
|
9973 | (query._queryIdentifier === 'default' ||
|
9974 | syncPointViewExistsForQuery(maybeSyncPoint, query))) {
|
9975 | var removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
|
9976 | if (syncPointIsEmpty(maybeSyncPoint)) {
|
9977 | syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
|
9978 | }
|
9979 | var removed = removedAndEvents.removed;
|
9980 | cancelEvents = removedAndEvents.events;
|
9981 | if (!skipListenerDedup) {
|
9982 | |
9983 |
|
9984 |
|
9985 |
|
9986 |
|
9987 |
|
9988 |
|
9989 | var removingDefault = -1 !==
|
9990 | removed.findIndex(function (query) {
|
9991 | return query._queryParams.loadsAllData();
|
9992 | });
|
9993 | var covered = syncTree.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {
|
9994 | return syncPointHasCompleteView(parentSyncPoint);
|
9995 | });
|
9996 | if (removingDefault && !covered) {
|
9997 | var subtree = syncTree.syncPointTree_.subtree(path);
|
9998 |
|
9999 |
|
10000 | if (!subtree.isEmpty()) {
|
10001 |
|
10002 | var newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
|
10003 |
|
10004 | for (var i = 0; i < newViews.length; ++i) {
|
10005 | var view = newViews[i], newQuery = view.query;
|
10006 | var listener = syncTreeCreateListenerForView_(syncTree, view);
|
10007 | syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
|
10008 | }
|
10009 | }
|
10010 |
|
10011 | }
|
10012 |
|
10013 |
|
10014 |
|
10015 | if (!covered && removed.length > 0 && !cancelError) {
|
10016 |
|
10017 |
|
10018 | if (removingDefault) {
|
10019 |
|
10020 | var defaultTag = null;
|
10021 | syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
|
10022 | }
|
10023 | else {
|
10024 | removed.forEach(function (queryToRemove) {
|
10025 | var tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
|
10026 | syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
|
10027 | });
|
10028 | }
|
10029 | }
|
10030 | }
|
10031 |
|
10032 | syncTreeRemoveTags_(syncTree, removed);
|
10033 | }
|
10034 | return cancelEvents;
|
10035 | }
|
10036 |
|
10037 |
|
10038 |
|
10039 |
|
10040 |
|
10041 | function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
|
10042 | var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
|
10043 | if (queryKey != null) {
|
10044 | var r = syncTreeParseQueryKey_(queryKey);
|
10045 | var queryPath = r.path, queryId = r.queryId;
|
10046 | var relativePath = newRelativePath(queryPath, path);
|
10047 | var op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
|
10048 | return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
|
10049 | }
|
10050 | else {
|
10051 |
|
10052 | return [];
|
10053 | }
|
10054 | }
|
10055 |
|
10056 |
|
10057 |
|
10058 |
|
10059 |
|
10060 | function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
|
10061 | var queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
|
10062 | if (queryKey) {
|
10063 | var r = syncTreeParseQueryKey_(queryKey);
|
10064 | var queryPath = r.path, queryId = r.queryId;
|
10065 | var relativePath = newRelativePath(queryPath, path);
|
10066 | var changeTree = ImmutableTree.fromObject(changedChildren);
|
10067 | var op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
|
10068 | return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
|
10069 | }
|
10070 | else {
|
10071 |
|
10072 | return [];
|
10073 | }
|
10074 | }
|
10075 |
|
10076 |
|
10077 |
|
10078 |
|
10079 |
|
10080 | function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener) {
|
10081 | if (skipSetupListener === void 0) { skipSetupListener = false; }
|
10082 | var path = query._path;
|
10083 | var serverCache = null;
|
10084 | var foundAncestorDefaultView = false;
|
10085 |
|
10086 |
|
10087 | syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
|
10088 | var relativePath = newRelativePath(pathToSyncPoint, path);
|
10089 | serverCache =
|
10090 | serverCache || syncPointGetCompleteServerCache(sp, relativePath);
|
10091 | foundAncestorDefaultView =
|
10092 | foundAncestorDefaultView || syncPointHasCompleteView(sp);
|
10093 | });
|
10094 | var syncPoint = syncTree.syncPointTree_.get(path);
|
10095 | if (!syncPoint) {
|
10096 | syncPoint = new SyncPoint();
|
10097 | syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
|
10098 | }
|
10099 | else {
|
10100 | foundAncestorDefaultView =
|
10101 | foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
|
10102 | serverCache =
|
10103 | serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
|
10104 | }
|
10105 | var serverCacheComplete;
|
10106 | if (serverCache != null) {
|
10107 | serverCacheComplete = true;
|
10108 | }
|
10109 | else {
|
10110 | serverCacheComplete = false;
|
10111 | serverCache = ChildrenNode.EMPTY_NODE;
|
10112 | var subtree = syncTree.syncPointTree_.subtree(path);
|
10113 | subtree.foreachChild(function (childName, childSyncPoint) {
|
10114 | var completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
|
10115 | if (completeCache) {
|
10116 | serverCache = serverCache.updateImmediateChild(childName, completeCache);
|
10117 | }
|
10118 | });
|
10119 | }
|
10120 | var viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
|
10121 | if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
|
10122 |
|
10123 | var queryKey = syncTreeMakeQueryKey_(query);
|
10124 | util.assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');
|
10125 | var tag = syncTreeGetNextQueryTag_();
|
10126 | syncTree.queryToTagMap.set(queryKey, tag);
|
10127 | syncTree.tagToQueryMap.set(tag, queryKey);
|
10128 | }
|
10129 | var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
|
10130 | var events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
|
10131 | if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
|
10132 | var view = syncPointViewForQuery(syncPoint, query);
|
10133 | events = events.concat(syncTreeSetupListener_(syncTree, query, view));
|
10134 | }
|
10135 | return events;
|
10136 | }
|
10137 |
|
10138 |
|
10139 |
|
10140 |
|
10141 |
|
10142 |
|
10143 |
|
10144 |
|
10145 |
|
10146 |
|
10147 |
|
10148 | function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
|
10149 | var includeHiddenSets = true;
|
10150 | var writeTree = syncTree.pendingWriteTree_;
|
10151 | var serverCache = syncTree.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {
|
10152 | var relativePath = newRelativePath(pathSoFar, path);
|
10153 | var serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);
|
10154 | if (serverCache) {
|
10155 | return serverCache;
|
10156 | }
|
10157 | });
|
10158 | return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
|
10159 | }
|
10160 | function syncTreeGetServerValue(syncTree, query) {
|
10161 | var path = query._path;
|
10162 | var serverCache = null;
|
10163 |
|
10164 |
|
10165 | syncTree.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {
|
10166 | var relativePath = newRelativePath(pathToSyncPoint, path);
|
10167 | serverCache =
|
10168 | serverCache || syncPointGetCompleteServerCache(sp, relativePath);
|
10169 | });
|
10170 | var syncPoint = syncTree.syncPointTree_.get(path);
|
10171 | if (!syncPoint) {
|
10172 | syncPoint = new SyncPoint();
|
10173 | syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
|
10174 | }
|
10175 | else {
|
10176 | serverCache =
|
10177 | serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
|
10178 | }
|
10179 | var serverCacheComplete = serverCache != null;
|
10180 | var serverCacheNode = serverCacheComplete
|
10181 | ? new CacheNode(serverCache, true, false)
|
10182 | : null;
|
10183 | var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
|
10184 | var view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
|
10185 | return viewGetCompleteNode(view);
|
10186 | }
|
10187 |
|
10188 |
|
10189 |
|
10190 |
|
10191 |
|
10192 |
|
10193 |
|
10194 |
|
10195 |
|
10196 |
|
10197 |
|
10198 |
|
10199 |
|
10200 | function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
|
10201 | return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_,
|
10202 | null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));
|
10203 | }
|
10204 |
|
10205 |
|
10206 |
|
10207 | function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
|
10208 | if (pathIsEmpty(operation.path)) {
|
10209 | return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
|
10210 | }
|
10211 | else {
|
10212 | var syncPoint = syncPointTree.get(newEmptyPath());
|
10213 |
|
10214 | if (serverCache == null && syncPoint != null) {
|
10215 | serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
|
10216 | }
|
10217 | var events = [];
|
10218 | var childName = pathGetFront(operation.path);
|
10219 | var childOperation = operation.operationForChild(childName);
|
10220 | var childTree = syncPointTree.children.get(childName);
|
10221 | if (childTree && childOperation) {
|
10222 | var childServerCache = serverCache
|
10223 | ? serverCache.getImmediateChild(childName)
|
10224 | : null;
|
10225 | var childWritesCache = writeTreeRefChild(writesCache, childName);
|
10226 | events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
|
10227 | }
|
10228 | if (syncPoint) {
|
10229 | events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
|
10230 | }
|
10231 | return events;
|
10232 | }
|
10233 | }
|
10234 |
|
10235 |
|
10236 |
|
10237 | function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
|
10238 | var syncPoint = syncPointTree.get(newEmptyPath());
|
10239 |
|
10240 | if (serverCache == null && syncPoint != null) {
|
10241 | serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
|
10242 | }
|
10243 | var events = [];
|
10244 | syncPointTree.children.inorderTraversal(function (childName, childTree) {
|
10245 | var childServerCache = serverCache
|
10246 | ? serverCache.getImmediateChild(childName)
|
10247 | : null;
|
10248 | var childWritesCache = writeTreeRefChild(writesCache, childName);
|
10249 | var childOperation = operation.operationForChild(childName);
|
10250 | if (childOperation) {
|
10251 | events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
|
10252 | }
|
10253 | });
|
10254 | if (syncPoint) {
|
10255 | events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
|
10256 | }
|
10257 | return events;
|
10258 | }
|
10259 | function syncTreeCreateListenerForView_(syncTree, view) {
|
10260 | var query = view.query;
|
10261 | var tag = syncTreeTagForQuery(syncTree, query);
|
10262 | return {
|
10263 | hashFn: function () {
|
10264 | var cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
|
10265 | return cache.hash();
|
10266 | },
|
10267 | onComplete: function (status) {
|
10268 | if (status === 'ok') {
|
10269 | if (tag) {
|
10270 | return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
|
10271 | }
|
10272 | else {
|
10273 | return syncTreeApplyListenComplete(syncTree, query._path);
|
10274 | }
|
10275 | }
|
10276 | else {
|
10277 |
|
10278 |
|
10279 | var error = errorForServerCode(status, query);
|
10280 | return syncTreeRemoveEventRegistration(syncTree, query,
|
10281 | null, error);
|
10282 | }
|
10283 | }
|
10284 | };
|
10285 | }
|
10286 |
|
10287 |
|
10288 |
|
10289 | function syncTreeTagForQuery(syncTree, query) {
|
10290 | var queryKey = syncTreeMakeQueryKey_(query);
|
10291 | return syncTree.queryToTagMap.get(queryKey);
|
10292 | }
|
10293 |
|
10294 |
|
10295 |
|
10296 | function syncTreeMakeQueryKey_(query) {
|
10297 | return query._path.toString() + '$' + query._queryIdentifier;
|
10298 | }
|
10299 |
|
10300 |
|
10301 |
|
10302 | function syncTreeQueryKeyForTag_(syncTree, tag) {
|
10303 | return syncTree.tagToQueryMap.get(tag);
|
10304 | }
|
10305 |
|
10306 |
|
10307 |
|
10308 | function syncTreeParseQueryKey_(queryKey) {
|
10309 | var splitIndex = queryKey.indexOf('$');
|
10310 | util.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');
|
10311 | return {
|
10312 | queryId: queryKey.substr(splitIndex + 1),
|
10313 | path: new Path(queryKey.substr(0, splitIndex))
|
10314 | };
|
10315 | }
|
10316 |
|
10317 |
|
10318 |
|
10319 | function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
|
10320 | var syncPoint = syncTree.syncPointTree_.get(queryPath);
|
10321 | util.assert(syncPoint, "Missing sync point for query tag that we're tracking");
|
10322 | var writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
|
10323 | return syncPointApplyOperation(syncPoint, operation, writesCache, null);
|
10324 | }
|
10325 |
|
10326 |
|
10327 |
|
10328 |
|
10329 | function syncTreeCollectDistinctViewsForSubTree_(subtree) {
|
10330 | return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
|
10331 | if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
|
10332 | var completeView = syncPointGetCompleteView(maybeChildSyncPoint);
|
10333 | return [completeView];
|
10334 | }
|
10335 | else {
|
10336 |
|
10337 | var views_1 = [];
|
10338 | if (maybeChildSyncPoint) {
|
10339 | views_1 = syncPointGetQueryViews(maybeChildSyncPoint);
|
10340 | }
|
10341 | each(childMap, function (_key, childViews) {
|
10342 | views_1 = views_1.concat(childViews);
|
10343 | });
|
10344 | return views_1;
|
10345 | }
|
10346 | });
|
10347 | }
|
10348 |
|
10349 |
|
10350 |
|
10351 |
|
10352 |
|
10353 | function syncTreeQueryForListening_(query) {
|
10354 | if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
|
10355 |
|
10356 |
|
10357 |
|
10358 | return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
|
10359 | }
|
10360 | else {
|
10361 | return query;
|
10362 | }
|
10363 | }
|
10364 | function syncTreeRemoveTags_(syncTree, queries) {
|
10365 | for (var j = 0; j < queries.length; ++j) {
|
10366 | var removedQuery = queries[j];
|
10367 | if (!removedQuery._queryParams.loadsAllData()) {
|
10368 |
|
10369 | var removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
|
10370 | var removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
|
10371 | syncTree.queryToTagMap.delete(removedQueryKey);
|
10372 | syncTree.tagToQueryMap.delete(removedQueryTag);
|
10373 | }
|
10374 | }
|
10375 | }
|
10376 |
|
10377 |
|
10378 |
|
10379 | function syncTreeGetNextQueryTag_() {
|
10380 | return syncTreeNextQueryTag_++;
|
10381 | }
|
10382 |
|
10383 |
|
10384 |
|
10385 |
|
10386 |
|
10387 | function syncTreeSetupListener_(syncTree, query, view) {
|
10388 | var path = query._path;
|
10389 | var tag = syncTreeTagForQuery(syncTree, query);
|
10390 | var listener = syncTreeCreateListenerForView_(syncTree, view);
|
10391 | var events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
|
10392 | var subtree = syncTree.syncPointTree_.subtree(path);
|
10393 |
|
10394 |
|
10395 | if (tag) {
|
10396 | util.assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
|
10397 | }
|
10398 | else {
|
10399 |
|
10400 | var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {
|
10401 | if (!pathIsEmpty(relativePath) &&
|
10402 | maybeChildSyncPoint &&
|
10403 | syncPointHasCompleteView(maybeChildSyncPoint)) {
|
10404 | return [syncPointGetCompleteView(maybeChildSyncPoint).query];
|
10405 | }
|
10406 | else {
|
10407 |
|
10408 | var queries_1 = [];
|
10409 | if (maybeChildSyncPoint) {
|
10410 | queries_1 = queries_1.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(function (view) { return view.query; }));
|
10411 | }
|
10412 | each(childMap, function (_key, childQueries) {
|
10413 | queries_1 = queries_1.concat(childQueries);
|
10414 | });
|
10415 | return queries_1;
|
10416 | }
|
10417 | });
|
10418 | for (var i = 0; i < queriesToStop.length; ++i) {
|
10419 | var queryToStop = queriesToStop[i];
|
10420 | syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
|
10421 | }
|
10422 | }
|
10423 | return events;
|
10424 | }
|
10425 |
|
10426 |
|
10427 |
|
10428 |
|
10429 |
|
10430 |
|
10431 |
|
10432 |
|
10433 |
|
10434 |
|
10435 |
|
10436 |
|
10437 |
|
10438 |
|
10439 |
|
10440 |
|
10441 |
|
10442 | var ExistingValueProvider = (function () {
|
10443 | function ExistingValueProvider(node_) {
|
10444 | this.node_ = node_;
|
10445 | }
|
10446 | ExistingValueProvider.prototype.getImmediateChild = function (childName) {
|
10447 | var child = this.node_.getImmediateChild(childName);
|
10448 | return new ExistingValueProvider(child);
|
10449 | };
|
10450 | ExistingValueProvider.prototype.node = function () {
|
10451 | return this.node_;
|
10452 | };
|
10453 | return ExistingValueProvider;
|
10454 | }());
|
10455 | var DeferredValueProvider = (function () {
|
10456 | function DeferredValueProvider(syncTree, path) {
|
10457 | this.syncTree_ = syncTree;
|
10458 | this.path_ = path;
|
10459 | }
|
10460 | DeferredValueProvider.prototype.getImmediateChild = function (childName) {
|
10461 | var childPath = pathChild(this.path_, childName);
|
10462 | return new DeferredValueProvider(this.syncTree_, childPath);
|
10463 | };
|
10464 | DeferredValueProvider.prototype.node = function () {
|
10465 | return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
|
10466 | };
|
10467 | return DeferredValueProvider;
|
10468 | }());
|
10469 |
|
10470 |
|
10471 |
|
10472 | var generateWithValues = function (values) {
|
10473 | values = values || {};
|
10474 | values['timestamp'] = values['timestamp'] || new Date().getTime();
|
10475 | return values;
|
10476 | };
|
10477 |
|
10478 |
|
10479 |
|
10480 |
|
10481 | var resolveDeferredLeafValue = function (value, existingVal, serverValues) {
|
10482 | if (!value || typeof value !== 'object') {
|
10483 | return value;
|
10484 | }
|
10485 | util.assert('.sv' in value, 'Unexpected leaf node or priority contents');
|
10486 | if (typeof value['.sv'] === 'string') {
|
10487 | return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);
|
10488 | }
|
10489 | else if (typeof value['.sv'] === 'object') {
|
10490 | return resolveComplexDeferredValue(value['.sv'], existingVal);
|
10491 | }
|
10492 | else {
|
10493 | util.assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));
|
10494 | }
|
10495 | };
|
10496 | var resolveScalarDeferredValue = function (op, existing, serverValues) {
|
10497 | switch (op) {
|
10498 | case 'timestamp':
|
10499 | return serverValues['timestamp'];
|
10500 | default:
|
10501 | util.assert(false, 'Unexpected server value: ' + op);
|
10502 | }
|
10503 | };
|
10504 | var resolveComplexDeferredValue = function (op, existing, unused) {
|
10505 | if (!op.hasOwnProperty('increment')) {
|
10506 | util.assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));
|
10507 | }
|
10508 | var delta = op['increment'];
|
10509 | if (typeof delta !== 'number') {
|
10510 | util.assert(false, 'Unexpected increment value: ' + delta);
|
10511 | }
|
10512 | var existingNode = existing.node();
|
10513 | util.assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');
|
10514 |
|
10515 | if (!existingNode.isLeafNode()) {
|
10516 | return delta;
|
10517 | }
|
10518 | var leaf = existingNode;
|
10519 | var existingVal = leaf.getValue();
|
10520 | if (typeof existingVal !== 'number') {
|
10521 | return delta;
|
10522 | }
|
10523 |
|
10524 | return existingVal + delta;
|
10525 | };
|
10526 |
|
10527 |
|
10528 |
|
10529 |
|
10530 |
|
10531 |
|
10532 |
|
10533 | var resolveDeferredValueTree = function (path, node, syncTree, serverValues) {
|
10534 | return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
|
10535 | };
|
10536 |
|
10537 |
|
10538 |
|
10539 |
|
10540 |
|
10541 | var resolveDeferredValueSnapshot = function (node, existing, serverValues) {
|
10542 | return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
|
10543 | };
|
10544 | function resolveDeferredValue(node, existingVal, serverValues) {
|
10545 | var rawPri = node.getPriority().val();
|
10546 | var priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);
|
10547 | var newNode;
|
10548 | if (node.isLeafNode()) {
|
10549 | var leafNode = node;
|
10550 | var value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
|
10551 | if (value !== leafNode.getValue() ||
|
10552 | priority !== leafNode.getPriority().val()) {
|
10553 | return new LeafNode(value, nodeFromJSON(priority));
|
10554 | }
|
10555 | else {
|
10556 | return node;
|
10557 | }
|
10558 | }
|
10559 | else {
|
10560 | var childrenNode = node;
|
10561 | newNode = childrenNode;
|
10562 | if (priority !== childrenNode.getPriority().val()) {
|
10563 | newNode = newNode.updatePriority(new LeafNode(priority));
|
10564 | }
|
10565 | childrenNode.forEachChild(PRIORITY_INDEX, function (childName, childNode) {
|
10566 | var newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
|
10567 | if (newChildNode !== childNode) {
|
10568 | newNode = newNode.updateImmediateChild(childName, newChildNode);
|
10569 | }
|
10570 | });
|
10571 | return newNode;
|
10572 | }
|
10573 | }
|
10574 |
|
10575 |
|
10576 |
|
10577 |
|
10578 |
|
10579 |
|
10580 |
|
10581 |
|
10582 |
|
10583 |
|
10584 |
|
10585 |
|
10586 |
|
10587 |
|
10588 |
|
10589 |
|
10590 |
|
10591 |
|
10592 |
|
10593 |
|
10594 |
|
10595 |
|
10596 | var Tree = (function () {
|
10597 | |
10598 |
|
10599 |
|
10600 |
|
10601 |
|
10602 | function Tree(name, parent, node) {
|
10603 | if (name === void 0) { name = ''; }
|
10604 | if (parent === void 0) { parent = null; }
|
10605 | if (node === void 0) { node = { children: {}, childCount: 0 }; }
|
10606 | this.name = name;
|
10607 | this.parent = parent;
|
10608 | this.node = node;
|
10609 | }
|
10610 | return Tree;
|
10611 | }());
|
10612 |
|
10613 |
|
10614 |
|
10615 |
|
10616 |
|
10617 |
|
10618 | function treeSubTree(tree, pathObj) {
|
10619 |
|
10620 | var path = pathObj instanceof Path ? pathObj : new Path(pathObj);
|
10621 | var child = tree, next = pathGetFront(path);
|
10622 | while (next !== null) {
|
10623 | var childNode = util.safeGet(child.node.children, next) || {
|
10624 | children: {},
|
10625 | childCount: 0
|
10626 | };
|
10627 | child = new Tree(next, child, childNode);
|
10628 | path = pathPopFront(path);
|
10629 | next = pathGetFront(path);
|
10630 | }
|
10631 | return child;
|
10632 | }
|
10633 |
|
10634 |
|
10635 |
|
10636 |
|
10637 |
|
10638 | function treeGetValue(tree) {
|
10639 | return tree.node.value;
|
10640 | }
|
10641 |
|
10642 |
|
10643 |
|
10644 |
|
10645 |
|
10646 | function treeSetValue(tree, value) {
|
10647 | tree.node.value = value;
|
10648 | treeUpdateParents(tree);
|
10649 | }
|
10650 |
|
10651 |
|
10652 |
|
10653 | function treeHasChildren(tree) {
|
10654 | return tree.node.childCount > 0;
|
10655 | }
|
10656 |
|
10657 |
|
10658 |
|
10659 | function treeIsEmpty(tree) {
|
10660 | return treeGetValue(tree) === undefined && !treeHasChildren(tree);
|
10661 | }
|
10662 |
|
10663 |
|
10664 |
|
10665 |
|
10666 |
|
10667 | function treeForEachChild(tree, action) {
|
10668 | each(tree.node.children, function (child, childTree) {
|
10669 | action(new Tree(child, tree, childTree));
|
10670 | });
|
10671 | }
|
10672 |
|
10673 |
|
10674 |
|
10675 |
|
10676 |
|
10677 |
|
10678 |
|
10679 |
|
10680 |
|
10681 | function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
|
10682 | if (includeSelf && !childrenFirst) {
|
10683 | action(tree);
|
10684 | }
|
10685 | treeForEachChild(tree, function (child) {
|
10686 | treeForEachDescendant(child, action, true, childrenFirst);
|
10687 | });
|
10688 | if (includeSelf && childrenFirst) {
|
10689 | action(tree);
|
10690 | }
|
10691 | }
|
10692 |
|
10693 |
|
10694 |
|
10695 |
|
10696 |
|
10697 |
|
10698 |
|
10699 |
|
10700 | function treeForEachAncestor(tree, action, includeSelf) {
|
10701 | var node = includeSelf ? tree : tree.parent;
|
10702 | while (node !== null) {
|
10703 | if (action(node)) {
|
10704 | return true;
|
10705 | }
|
10706 | node = node.parent;
|
10707 | }
|
10708 | return false;
|
10709 | }
|
10710 |
|
10711 |
|
10712 |
|
10713 | function treeGetPath(tree) {
|
10714 | return new Path(tree.parent === null
|
10715 | ? tree.name
|
10716 | : treeGetPath(tree.parent) + '/' + tree.name);
|
10717 | }
|
10718 |
|
10719 |
|
10720 |
|
10721 | function treeUpdateParents(tree) {
|
10722 | if (tree.parent !== null) {
|
10723 | treeUpdateChild(tree.parent, tree.name, tree);
|
10724 | }
|
10725 | }
|
10726 |
|
10727 |
|
10728 |
|
10729 |
|
10730 |
|
10731 |
|
10732 | function treeUpdateChild(tree, childName, child) {
|
10733 | var childEmpty = treeIsEmpty(child);
|
10734 | var childExists = util.contains(tree.node.children, childName);
|
10735 | if (childEmpty && childExists) {
|
10736 | delete tree.node.children[childName];
|
10737 | tree.node.childCount--;
|
10738 | treeUpdateParents(tree);
|
10739 | }
|
10740 | else if (!childEmpty && !childExists) {
|
10741 | tree.node.children[childName] = child.node;
|
10742 | tree.node.childCount++;
|
10743 | treeUpdateParents(tree);
|
10744 | }
|
10745 | }
|
10746 |
|
10747 |
|
10748 |
|
10749 |
|
10750 |
|
10751 |
|
10752 |
|
10753 |
|
10754 |
|
10755 |
|
10756 |
|
10757 |
|
10758 |
|
10759 |
|
10760 |
|
10761 |
|
10762 |
|
10763 |
|
10764 |
|
10765 |
|
10766 | var INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
|
10767 |
|
10768 |
|
10769 |
|
10770 |
|
10771 | var INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
|
10772 |
|
10773 |
|
10774 |
|
10775 | var MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
|
10776 | var isValidKey = function (key) {
|
10777 | return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));
|
10778 | };
|
10779 | var isValidPathString = function (pathString) {
|
10780 | return (typeof pathString === 'string' &&
|
10781 | pathString.length !== 0 &&
|
10782 | !INVALID_PATH_REGEX_.test(pathString));
|
10783 | };
|
10784 | var isValidRootPathString = function (pathString) {
|
10785 | if (pathString) {
|
10786 |
|
10787 | pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
|
10788 | }
|
10789 | return isValidPathString(pathString);
|
10790 | };
|
10791 | var isValidPriority = function (priority) {
|
10792 | return (priority === null ||
|
10793 | typeof priority === 'string' ||
|
10794 | (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||
|
10795 | (priority &&
|
10796 | typeof priority === 'object' &&
|
10797 |
|
10798 | util.contains(priority, '.sv')));
|
10799 | };
|
10800 |
|
10801 |
|
10802 |
|
10803 | var validateFirebaseDataArg = function (fnName, value, path, optional) {
|
10804 | if (optional && value === undefined) {
|
10805 | return;
|
10806 | }
|
10807 | validateFirebaseData(util.errorPrefix(fnName, 'value'), value, path);
|
10808 | };
|
10809 |
|
10810 |
|
10811 |
|
10812 | var validateFirebaseData = function (errorPrefix, data, path_) {
|
10813 | var path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;
|
10814 | if (data === undefined) {
|
10815 | throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));
|
10816 | }
|
10817 | if (typeof data === 'function') {
|
10818 | throw new Error(errorPrefix +
|
10819 | 'contains a function ' +
|
10820 | validationPathToErrorString(path) +
|
10821 | ' with contents = ' +
|
10822 | data.toString());
|
10823 | }
|
10824 | if (isInvalidJSONNumber(data)) {
|
10825 | throw new Error(errorPrefix +
|
10826 | 'contains ' +
|
10827 | data.toString() +
|
10828 | ' ' +
|
10829 | validationPathToErrorString(path));
|
10830 | }
|
10831 |
|
10832 | if (typeof data === 'string' &&
|
10833 | data.length > MAX_LEAF_SIZE_ / 3 &&
|
10834 | util.stringLength(data) > MAX_LEAF_SIZE_) {
|
10835 | throw new Error(errorPrefix +
|
10836 | 'contains a string greater than ' +
|
10837 | MAX_LEAF_SIZE_ +
|
10838 | ' utf8 bytes ' +
|
10839 | validationPathToErrorString(path) +
|
10840 | " ('" +
|
10841 | data.substring(0, 50) +
|
10842 | "...')");
|
10843 | }
|
10844 |
|
10845 |
|
10846 | if (data && typeof data === 'object') {
|
10847 | var hasDotValue_1 = false;
|
10848 | var hasActualChild_1 = false;
|
10849 | each(data, function (key, value) {
|
10850 | if (key === '.value') {
|
10851 | hasDotValue_1 = true;
|
10852 | }
|
10853 | else if (key !== '.priority' && key !== '.sv') {
|
10854 | hasActualChild_1 = true;
|
10855 | if (!isValidKey(key)) {
|
10856 | throw new Error(errorPrefix +
|
10857 | ' contains an invalid key (' +
|
10858 | key +
|
10859 | ') ' +
|
10860 | validationPathToErrorString(path) +
|
10861 | '. Keys must be non-empty strings ' +
|
10862 | 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
|
10863 | }
|
10864 | }
|
10865 | validationPathPush(path, key);
|
10866 | validateFirebaseData(errorPrefix, value, path);
|
10867 | validationPathPop(path);
|
10868 | });
|
10869 | if (hasDotValue_1 && hasActualChild_1) {
|
10870 | throw new Error(errorPrefix +
|
10871 | ' contains ".value" child ' +
|
10872 | validationPathToErrorString(path) +
|
10873 | ' in addition to actual children.');
|
10874 | }
|
10875 | }
|
10876 | };
|
10877 |
|
10878 |
|
10879 |
|
10880 | var validateFirebaseMergePaths = function (errorPrefix, mergePaths) {
|
10881 | var i, curPath;
|
10882 | for (i = 0; i < mergePaths.length; i++) {
|
10883 | curPath = mergePaths[i];
|
10884 | var keys = pathSlice(curPath);
|
10885 | for (var j = 0; j < keys.length; j++) {
|
10886 | if (keys[j] === '.priority' && j === keys.length - 1) ;
|
10887 | else if (!isValidKey(keys[j])) {
|
10888 | throw new Error(errorPrefix +
|
10889 | 'contains an invalid key (' +
|
10890 | keys[j] +
|
10891 | ') in path ' +
|
10892 | curPath.toString() +
|
10893 | '. Keys must be non-empty strings ' +
|
10894 | 'and can\'t contain ".", "#", "$", "/", "[", or "]"');
|
10895 | }
|
10896 | }
|
10897 | }
|
10898 |
|
10899 |
|
10900 |
|
10901 | mergePaths.sort(pathCompare);
|
10902 | var prevPath = null;
|
10903 | for (i = 0; i < mergePaths.length; i++) {
|
10904 | curPath = mergePaths[i];
|
10905 | if (prevPath !== null && pathContains(prevPath, curPath)) {
|
10906 | throw new Error(errorPrefix +
|
10907 | 'contains a path ' +
|
10908 | prevPath.toString() +
|
10909 | ' that is ancestor of another path ' +
|
10910 | curPath.toString());
|
10911 | }
|
10912 | prevPath = curPath;
|
10913 | }
|
10914 | };
|
10915 |
|
10916 |
|
10917 |
|
10918 |
|
10919 | var validateFirebaseMergeDataArg = function (fnName, data, path, optional) {
|
10920 | if (optional && data === undefined) {
|
10921 | return;
|
10922 | }
|
10923 | var errorPrefix = util.errorPrefix(fnName, 'values');
|
10924 | if (!(data && typeof data === 'object') || Array.isArray(data)) {
|
10925 | throw new Error(errorPrefix + ' must be an object containing the children to replace.');
|
10926 | }
|
10927 | var mergePaths = [];
|
10928 | each(data, function (key, value) {
|
10929 | var curPath = new Path(key);
|
10930 | validateFirebaseData(errorPrefix, value, pathChild(path, curPath));
|
10931 | if (pathGetBack(curPath) === '.priority') {
|
10932 | if (!isValidPriority(value)) {
|
10933 | throw new Error(errorPrefix +
|
10934 | "contains an invalid value for '" +
|
10935 | curPath.toString() +
|
10936 | "', which must be a valid " +
|
10937 | 'Firebase priority (a string, finite number, server value, or null).');
|
10938 | }
|
10939 | }
|
10940 | mergePaths.push(curPath);
|
10941 | });
|
10942 | validateFirebaseMergePaths(errorPrefix, mergePaths);
|
10943 | };
|
10944 | var validatePriority = function (fnName, priority, optional) {
|
10945 | if (optional && priority === undefined) {
|
10946 | return;
|
10947 | }
|
10948 | if (isInvalidJSONNumber(priority)) {
|
10949 | throw new Error(util.errorPrefix(fnName, 'priority') +
|
10950 | 'is ' +
|
10951 | priority.toString() +
|
10952 | ', but must be a valid Firebase priority (a string, finite number, ' +
|
10953 | 'server value, or null).');
|
10954 | }
|
10955 |
|
10956 | if (!isValidPriority(priority)) {
|
10957 | throw new Error(util.errorPrefix(fnName, 'priority') +
|
10958 | 'must be a valid Firebase priority ' +
|
10959 | '(a string, finite number, server value, or null).');
|
10960 | }
|
10961 | };
|
10962 | var validateKey = function (fnName, argumentName, key, optional) {
|
10963 | if (optional && key === undefined) {
|
10964 | return;
|
10965 | }
|
10966 | if (!isValidKey(key)) {
|
10967 | throw new Error(util.errorPrefix(fnName, argumentName) +
|
10968 | 'was an invalid key = "' +
|
10969 | key +
|
10970 | '". Firebase keys must be non-empty strings and ' +
|
10971 | 'can\'t contain ".", "#", "$", "/", "[", or "]").');
|
10972 | }
|
10973 | };
|
10974 |
|
10975 |
|
10976 |
|
10977 | var validatePathString = function (fnName, argumentName, pathString, optional) {
|
10978 | if (optional && pathString === undefined) {
|
10979 | return;
|
10980 | }
|
10981 | if (!isValidPathString(pathString)) {
|
10982 | throw new Error(util.errorPrefix(fnName, argumentName) +
|
10983 | 'was an invalid path = "' +
|
10984 | pathString +
|
10985 | '". Paths must be non-empty strings and ' +
|
10986 | 'can\'t contain ".", "#", "$", "[", or "]"');
|
10987 | }
|
10988 | };
|
10989 | var validateRootPathString = function (fnName, argumentName, pathString, optional) {
|
10990 | if (pathString) {
|
10991 |
|
10992 | pathString = pathString.replace(/^\/*\.info(\/|$)/, '/');
|
10993 | }
|
10994 | validatePathString(fnName, argumentName, pathString, optional);
|
10995 | };
|
10996 |
|
10997 |
|
10998 |
|
10999 | var validateWritablePath = function (fnName, path) {
|
11000 | if (pathGetFront(path) === '.info') {
|
11001 | throw new Error(fnName + " failed = Can't modify data under /.info/");
|
11002 | }
|
11003 | };
|
11004 | var validateUrl = function (fnName, parsedUrl) {
|
11005 |
|
11006 | var pathString = parsedUrl.path.toString();
|
11007 | if (!(typeof parsedUrl.repoInfo.host === 'string') ||
|
11008 | parsedUrl.repoInfo.host.length === 0 ||
|
11009 | (!isValidKey(parsedUrl.repoInfo.namespace) &&
|
11010 | parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||
|
11011 | (pathString.length !== 0 && !isValidRootPathString(pathString))) {
|
11012 | throw new Error(util.errorPrefix(fnName, 'url') +
|
11013 | 'must be a valid firebase URL and ' +
|
11014 | 'the path can\'t contain ".", "#", "$", "[", or "]".');
|
11015 | }
|
11016 | };
|
11017 |
|
11018 |
|
11019 |
|
11020 |
|
11021 |
|
11022 |
|
11023 |
|
11024 |
|
11025 |
|
11026 |
|
11027 |
|
11028 |
|
11029 |
|
11030 |
|
11031 |
|
11032 |
|
11033 |
|
11034 |
|
11035 |
|
11036 |
|
11037 |
|
11038 |
|
11039 |
|
11040 |
|
11041 |
|
11042 |
|
11043 |
|
11044 |
|
11045 |
|
11046 |
|
11047 | var EventQueue = (function () {
|
11048 | function EventQueue() {
|
11049 | this.eventLists_ = [];
|
11050 | |
11051 |
|
11052 |
|
11053 | this.recursionDepth_ = 0;
|
11054 | }
|
11055 | return EventQueue;
|
11056 | }());
|
11057 |
|
11058 |
|
11059 |
|
11060 | function eventQueueQueueEvents(eventQueue, eventDataList) {
|
11061 |
|
11062 | var currList = null;
|
11063 | for (var i = 0; i < eventDataList.length; i++) {
|
11064 | var data = eventDataList[i];
|
11065 | var path = data.getPath();
|
11066 | if (currList !== null && !pathEquals(path, currList.path)) {
|
11067 | eventQueue.eventLists_.push(currList);
|
11068 | currList = null;
|
11069 | }
|
11070 | if (currList === null) {
|
11071 | currList = { events: [], path: path };
|
11072 | }
|
11073 | currList.events.push(data);
|
11074 | }
|
11075 | if (currList) {
|
11076 | eventQueue.eventLists_.push(currList);
|
11077 | }
|
11078 | }
|
11079 |
|
11080 |
|
11081 |
|
11082 |
|
11083 |
|
11084 |
|
11085 |
|
11086 |
|
11087 |
|
11088 | function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
|
11089 | eventQueueQueueEvents(eventQueue, eventDataList);
|
11090 | eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
|
11091 | return pathEquals(eventPath, path);
|
11092 | });
|
11093 | }
|
11094 |
|
11095 |
|
11096 |
|
11097 |
|
11098 |
|
11099 |
|
11100 |
|
11101 |
|
11102 |
|
11103 | function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
|
11104 | eventQueueQueueEvents(eventQueue, eventDataList);
|
11105 | eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, function (eventPath) {
|
11106 | return pathContains(eventPath, changedPath) ||
|
11107 | pathContains(changedPath, eventPath);
|
11108 | });
|
11109 | }
|
11110 | function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
|
11111 | eventQueue.recursionDepth_++;
|
11112 | var sentAll = true;
|
11113 | for (var i = 0; i < eventQueue.eventLists_.length; i++) {
|
11114 | var eventList = eventQueue.eventLists_[i];
|
11115 | if (eventList) {
|
11116 | var eventPath = eventList.path;
|
11117 | if (predicate(eventPath)) {
|
11118 | eventListRaise(eventQueue.eventLists_[i]);
|
11119 | eventQueue.eventLists_[i] = null;
|
11120 | }
|
11121 | else {
|
11122 | sentAll = false;
|
11123 | }
|
11124 | }
|
11125 | }
|
11126 | if (sentAll) {
|
11127 | eventQueue.eventLists_ = [];
|
11128 | }
|
11129 | eventQueue.recursionDepth_--;
|
11130 | }
|
11131 |
|
11132 |
|
11133 |
|
11134 | function eventListRaise(eventList) {
|
11135 | for (var i = 0; i < eventList.events.length; i++) {
|
11136 | var eventData = eventList.events[i];
|
11137 | if (eventData !== null) {
|
11138 | eventList.events[i] = null;
|
11139 | var eventFn = eventData.getEventRunner();
|
11140 | if (logger) {
|
11141 | log('event: ' + eventData.toString());
|
11142 | }
|
11143 | exceptionGuard(eventFn);
|
11144 | }
|
11145 | }
|
11146 | }
|
11147 |
|
11148 |
|
11149 |
|
11150 |
|
11151 |
|
11152 |
|
11153 |
|
11154 |
|
11155 |
|
11156 |
|
11157 |
|
11158 |
|
11159 |
|
11160 |
|
11161 |
|
11162 |
|
11163 |
|
11164 | var INTERRUPT_REASON = 'repo_interrupt';
|
11165 |
|
11166 |
|
11167 |
|
11168 |
|
11169 |
|
11170 | var MAX_TRANSACTION_RETRIES = 25;
|
11171 |
|
11172 |
|
11173 |
|
11174 | var Repo = (function () {
|
11175 | function Repo(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
|
11176 | this.repoInfo_ = repoInfo_;
|
11177 | this.forceRestClient_ = forceRestClient_;
|
11178 | this.authTokenProvider_ = authTokenProvider_;
|
11179 | this.appCheckProvider_ = appCheckProvider_;
|
11180 | this.dataUpdateCount = 0;
|
11181 | this.statsListener_ = null;
|
11182 | this.eventQueue_ = new EventQueue();
|
11183 | this.nextWriteId_ = 1;
|
11184 | this.interceptServerDataCallback_ = null;
|
11185 |
|
11186 | this.onDisconnect_ = newSparseSnapshotTree();
|
11187 |
|
11188 | this.transactionQueueTree_ = new Tree();
|
11189 |
|
11190 | this.persistentConnection_ = null;
|
11191 |
|
11192 | this.key = this.repoInfo_.toURLString();
|
11193 | }
|
11194 | |
11195 |
|
11196 |
|
11197 | Repo.prototype.toString = function () {
|
11198 | return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);
|
11199 | };
|
11200 | return Repo;
|
11201 | }());
|
11202 | function repoStart(repo, appId, authOverride) {
|
11203 | repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
|
11204 | if (repo.forceRestClient_ || beingCrawled()) {
|
11205 | repo.server_ = new ReadonlyRestClient(repo.repoInfo_, function (pathString, data, isMerge, tag) {
|
11206 | repoOnDataUpdate(repo, pathString, data, isMerge, tag);
|
11207 | }, repo.authTokenProvider_, repo.appCheckProvider_);
|
11208 |
|
11209 | setTimeout(function () { return repoOnConnectStatus(repo, true); }, 0);
|
11210 | }
|
11211 | else {
|
11212 |
|
11213 | if (typeof authOverride !== 'undefined' && authOverride !== null) {
|
11214 | if (typeof authOverride !== 'object') {
|
11215 | throw new Error('Only objects are supported for option databaseAuthVariableOverride');
|
11216 | }
|
11217 | try {
|
11218 | util.stringify(authOverride);
|
11219 | }
|
11220 | catch (e) {
|
11221 | throw new Error('Invalid authOverride provided: ' + e);
|
11222 | }
|
11223 | }
|
11224 | repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, function (pathString, data, isMerge, tag) {
|
11225 | repoOnDataUpdate(repo, pathString, data, isMerge, tag);
|
11226 | }, function (connectStatus) {
|
11227 | repoOnConnectStatus(repo, connectStatus);
|
11228 | }, function (updates) {
|
11229 | repoOnServerInfoUpdate(repo, updates);
|
11230 | }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
|
11231 | repo.server_ = repo.persistentConnection_;
|
11232 | }
|
11233 | repo.authTokenProvider_.addTokenChangeListener(function (token) {
|
11234 | repo.server_.refreshAuthToken(token);
|
11235 | });
|
11236 | repo.appCheckProvider_.addTokenChangeListener(function (result) {
|
11237 | repo.server_.refreshAppCheckToken(result.token);
|
11238 | });
|
11239 |
|
11240 |
|
11241 | repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, function () { return new StatsReporter(repo.stats_, repo.server_); });
|
11242 |
|
11243 | repo.infoData_ = new SnapshotHolder();
|
11244 | repo.infoSyncTree_ = new SyncTree({
|
11245 | startListening: function (query, tag, currentHashFn, onComplete) {
|
11246 | var infoEvents = [];
|
11247 | var node = repo.infoData_.getNode(query._path);
|
11248 |
|
11249 |
|
11250 | if (!node.isEmpty()) {
|
11251 | infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
|
11252 | setTimeout(function () {
|
11253 | onComplete('ok');
|
11254 | }, 0);
|
11255 | }
|
11256 | return infoEvents;
|
11257 | },
|
11258 | stopListening: function () { }
|
11259 | });
|
11260 | repoUpdateInfo(repo, 'connected', false);
|
11261 | repo.serverSyncTree_ = new SyncTree({
|
11262 | startListening: function (query, tag, currentHashFn, onComplete) {
|
11263 | repo.server_.listen(query, currentHashFn, tag, function (status, data) {
|
11264 | var events = onComplete(status, data);
|
11265 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
|
11266 | });
|
11267 |
|
11268 | return [];
|
11269 | },
|
11270 | stopListening: function (query, tag) {
|
11271 | repo.server_.unlisten(query, tag);
|
11272 | }
|
11273 | });
|
11274 | }
|
11275 |
|
11276 |
|
11277 |
|
11278 | function repoServerTime(repo) {
|
11279 | var offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));
|
11280 | var offset = offsetNode.val() || 0;
|
11281 | return new Date().getTime() + offset;
|
11282 | }
|
11283 |
|
11284 |
|
11285 |
|
11286 | function repoGenerateServerValues(repo) {
|
11287 | return generateWithValues({
|
11288 | timestamp: repoServerTime(repo)
|
11289 | });
|
11290 | }
|
11291 |
|
11292 |
|
11293 |
|
11294 | function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
|
11295 |
|
11296 | repo.dataUpdateCount++;
|
11297 | var path = new Path(pathString);
|
11298 | data = repo.interceptServerDataCallback_
|
11299 | ? repo.interceptServerDataCallback_(pathString, data)
|
11300 | : data;
|
11301 | var events = [];
|
11302 | if (tag) {
|
11303 | if (isMerge) {
|
11304 | var taggedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
|
11305 | events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
|
11306 | }
|
11307 | else {
|
11308 | var taggedSnap = nodeFromJSON(data);
|
11309 | events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
|
11310 | }
|
11311 | }
|
11312 | else if (isMerge) {
|
11313 | var changedChildren = util.map(data, function (raw) { return nodeFromJSON(raw); });
|
11314 | events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
|
11315 | }
|
11316 | else {
|
11317 | var snap = nodeFromJSON(data);
|
11318 | events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
|
11319 | }
|
11320 | var affectedPath = path;
|
11321 | if (events.length > 0) {
|
11322 |
|
11323 |
|
11324 | affectedPath = repoRerunTransactions(repo, path);
|
11325 | }
|
11326 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);
|
11327 | }
|
11328 | function repoOnConnectStatus(repo, connectStatus) {
|
11329 | repoUpdateInfo(repo, 'connected', connectStatus);
|
11330 | if (connectStatus === false) {
|
11331 | repoRunOnDisconnectEvents(repo);
|
11332 | }
|
11333 | }
|
11334 | function repoOnServerInfoUpdate(repo, updates) {
|
11335 | each(updates, function (key, value) {
|
11336 | repoUpdateInfo(repo, key, value);
|
11337 | });
|
11338 | }
|
11339 | function repoUpdateInfo(repo, pathString, value) {
|
11340 | var path = new Path('/.info/' + pathString);
|
11341 | var newNode = nodeFromJSON(value);
|
11342 | repo.infoData_.updateSnapshot(path, newNode);
|
11343 | var events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
|
11344 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
|
11345 | }
|
11346 | function repoGetNextWriteId(repo) {
|
11347 | return repo.nextWriteId_++;
|
11348 | }
|
11349 |
|
11350 |
|
11351 |
|
11352 |
|
11353 |
|
11354 |
|
11355 |
|
11356 |
|
11357 |
|
11358 |
|
11359 |
|
11360 |
|
11361 |
|
11362 |
|
11363 |
|
11364 | function repoGetValue(repo, query, eventRegistration) {
|
11365 |
|
11366 | var cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
|
11367 | if (cached != null) {
|
11368 | return Promise.resolve(cached);
|
11369 | }
|
11370 | return repo.server_.get(query).then(function (payload) {
|
11371 | var node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
|
11372 | |
11373 |
|
11374 |
|
11375 |
|
11376 |
|
11377 |
|
11378 |
|
11379 | syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
|
11380 | var events;
|
11381 | if (query._queryParams.loadsAllData()) {
|
11382 | events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
|
11383 | }
|
11384 | else {
|
11385 | var tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
|
11386 | events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
|
11387 | }
|
11388 | |
11389 |
|
11390 |
|
11391 |
|
11392 |
|
11393 |
|
11394 |
|
11395 |
|
11396 |
|
11397 |
|
11398 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);
|
11399 | syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
|
11400 | return node;
|
11401 | }, function (err) {
|
11402 | repoLog(repo, 'get for query ' + util.stringify(query) + ' failed: ' + err);
|
11403 | return Promise.reject(new Error(err));
|
11404 | });
|
11405 | }
|
11406 | function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
|
11407 | repoLog(repo, 'set', {
|
11408 | path: path.toString(),
|
11409 | value: newVal,
|
11410 | priority: newPriority
|
11411 | });
|
11412 |
|
11413 |
|
11414 | var serverValues = repoGenerateServerValues(repo);
|
11415 | var newNodeUnresolved = nodeFromJSON(newVal, newPriority);
|
11416 | var existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
|
11417 | var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
|
11418 | var writeId = repoGetNextWriteId(repo);
|
11419 | var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
|
11420 | eventQueueQueueEvents(repo.eventQueue_, events);
|
11421 | repo.server_.put(path.toString(), newNodeUnresolved.val( true), function (status, errorReason) {
|
11422 | var success = status === 'ok';
|
11423 | if (!success) {
|
11424 | warn('set at ' + path + ' failed: ' + status);
|
11425 | }
|
11426 | var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
|
11427 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
|
11428 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11429 | });
|
11430 | var affectedPath = repoAbortTransactions(repo, path);
|
11431 | repoRerunTransactions(repo, affectedPath);
|
11432 |
|
11433 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
|
11434 | }
|
11435 | function repoUpdate(repo, path, childrenToMerge, onComplete) {
|
11436 | repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });
|
11437 |
|
11438 | var empty = true;
|
11439 | var serverValues = repoGenerateServerValues(repo);
|
11440 | var changedChildren = {};
|
11441 | each(childrenToMerge, function (changedKey, changedValue) {
|
11442 | empty = false;
|
11443 | changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);
|
11444 | });
|
11445 | if (!empty) {
|
11446 | var writeId_1 = repoGetNextWriteId(repo);
|
11447 | var events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId_1);
|
11448 | eventQueueQueueEvents(repo.eventQueue_, events);
|
11449 | repo.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {
|
11450 | var success = status === 'ok';
|
11451 | if (!success) {
|
11452 | warn('update at ' + path + ' failed: ' + status);
|
11453 | }
|
11454 | var clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId_1, !success);
|
11455 | var affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;
|
11456 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);
|
11457 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11458 | });
|
11459 | each(childrenToMerge, function (changedPath) {
|
11460 | var affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));
|
11461 | repoRerunTransactions(repo, affectedPath);
|
11462 | });
|
11463 |
|
11464 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);
|
11465 | }
|
11466 | else {
|
11467 | log("update() called with empty data. Don't do anything.");
|
11468 | repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
|
11469 | }
|
11470 | }
|
11471 |
|
11472 |
|
11473 |
|
11474 | function repoRunOnDisconnectEvents(repo) {
|
11475 | repoLog(repo, 'onDisconnectEvents');
|
11476 | var serverValues = repoGenerateServerValues(repo);
|
11477 | var resolvedOnDisconnectTree = newSparseSnapshotTree();
|
11478 | sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), function (path, node) {
|
11479 | var resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
|
11480 | sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
|
11481 | });
|
11482 | var events = [];
|
11483 | sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), function (path, snap) {
|
11484 | events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
|
11485 | var affectedPath = repoAbortTransactions(repo, path);
|
11486 | repoRerunTransactions(repo, affectedPath);
|
11487 | });
|
11488 | repo.onDisconnect_ = newSparseSnapshotTree();
|
11489 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);
|
11490 | }
|
11491 | function repoOnDisconnectCancel(repo, path, onComplete) {
|
11492 | repo.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {
|
11493 | if (status === 'ok') {
|
11494 | sparseSnapshotTreeForget(repo.onDisconnect_, path);
|
11495 | }
|
11496 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11497 | });
|
11498 | }
|
11499 | function repoOnDisconnectSet(repo, path, value, onComplete) {
|
11500 | var newNode = nodeFromJSON(value);
|
11501 | repo.server_.onDisconnectPut(path.toString(), newNode.val( true), function (status, errorReason) {
|
11502 | if (status === 'ok') {
|
11503 | sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
|
11504 | }
|
11505 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11506 | });
|
11507 | }
|
11508 | function repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {
|
11509 | var newNode = nodeFromJSON(value, priority);
|
11510 | repo.server_.onDisconnectPut(path.toString(), newNode.val( true), function (status, errorReason) {
|
11511 | if (status === 'ok') {
|
11512 | sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);
|
11513 | }
|
11514 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11515 | });
|
11516 | }
|
11517 | function repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {
|
11518 | if (util.isEmpty(childrenToMerge)) {
|
11519 | log("onDisconnect().update() called with empty data. Don't do anything.");
|
11520 | repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);
|
11521 | return;
|
11522 | }
|
11523 | repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {
|
11524 | if (status === 'ok') {
|
11525 | each(childrenToMerge, function (childName, childNode) {
|
11526 | var newChildNode = nodeFromJSON(childNode);
|
11527 | sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);
|
11528 | });
|
11529 | }
|
11530 | repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
|
11531 | });
|
11532 | }
|
11533 | function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
|
11534 | var events;
|
11535 | if (pathGetFront(query._path) === '.info') {
|
11536 | events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
|
11537 | }
|
11538 | else {
|
11539 | events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
|
11540 | }
|
11541 | eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
|
11542 | }
|
11543 | function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
|
11544 |
|
11545 |
|
11546 | var events;
|
11547 | if (pathGetFront(query._path) === '.info') {
|
11548 | events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
|
11549 | }
|
11550 | else {
|
11551 | events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
|
11552 | }
|
11553 | eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);
|
11554 | }
|
11555 | function repoInterrupt(repo) {
|
11556 | if (repo.persistentConnection_) {
|
11557 | repo.persistentConnection_.interrupt(INTERRUPT_REASON);
|
11558 | }
|
11559 | }
|
11560 | function repoResume(repo) {
|
11561 | if (repo.persistentConnection_) {
|
11562 | repo.persistentConnection_.resume(INTERRUPT_REASON);
|
11563 | }
|
11564 | }
|
11565 | function repoLog(repo) {
|
11566 | var varArgs = [];
|
11567 | for (var _i = 1; _i < arguments.length; _i++) {
|
11568 | varArgs[_i - 1] = arguments[_i];
|
11569 | }
|
11570 | var prefix = '';
|
11571 | if (repo.persistentConnection_) {
|
11572 | prefix = repo.persistentConnection_.id + ':';
|
11573 | }
|
11574 | log.apply(void 0, tslib.__spreadArray([prefix], tslib.__read(varArgs), false));
|
11575 | }
|
11576 | function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
|
11577 | if (callback) {
|
11578 | exceptionGuard(function () {
|
11579 | if (status === 'ok') {
|
11580 | callback(null);
|
11581 | }
|
11582 | else {
|
11583 | var code = (status || 'error').toUpperCase();
|
11584 | var message = code;
|
11585 | if (errorReason) {
|
11586 | message += ': ' + errorReason;
|
11587 | }
|
11588 | var error = new Error(message);
|
11589 |
|
11590 | error.code = code;
|
11591 | callback(error);
|
11592 | }
|
11593 | });
|
11594 | }
|
11595 | }
|
11596 |
|
11597 |
|
11598 |
|
11599 |
|
11600 |
|
11601 |
|
11602 |
|
11603 |
|
11604 |
|
11605 |
|
11606 |
|
11607 | function repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {
|
11608 | repoLog(repo, 'transaction on ' + path);
|
11609 |
|
11610 | var transaction = {
|
11611 | path: path,
|
11612 | update: transactionUpdate,
|
11613 | onComplete: onComplete,
|
11614 |
|
11615 | status: null,
|
11616 |
|
11617 |
|
11618 | order: LUIDGenerator(),
|
11619 |
|
11620 | applyLocally: applyLocally,
|
11621 |
|
11622 | retryCount: 0,
|
11623 |
|
11624 | unwatcher: unwatcher,
|
11625 |
|
11626 | abortReason: null,
|
11627 | currentWriteId: null,
|
11628 | currentInputSnapshot: null,
|
11629 | currentOutputSnapshotRaw: null,
|
11630 | currentOutputSnapshotResolved: null
|
11631 | };
|
11632 |
|
11633 | var currentState = repoGetLatestState(repo, path, undefined);
|
11634 | transaction.currentInputSnapshot = currentState;
|
11635 | var newVal = transaction.update(currentState.val());
|
11636 | if (newVal === undefined) {
|
11637 |
|
11638 | transaction.unwatcher();
|
11639 | transaction.currentOutputSnapshotRaw = null;
|
11640 | transaction.currentOutputSnapshotResolved = null;
|
11641 | if (transaction.onComplete) {
|
11642 | transaction.onComplete(null, false, transaction.currentInputSnapshot);
|
11643 | }
|
11644 | }
|
11645 | else {
|
11646 | validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);
|
11647 |
|
11648 | transaction.status = 0 ;
|
11649 | var queueNode = treeSubTree(repo.transactionQueueTree_, path);
|
11650 | var nodeQueue = treeGetValue(queueNode) || [];
|
11651 | nodeQueue.push(transaction);
|
11652 | treeSetValue(queueNode, nodeQueue);
|
11653 |
|
11654 |
|
11655 |
|
11656 |
|
11657 | var priorityForNode = void 0;
|
11658 | if (typeof newVal === 'object' &&
|
11659 | newVal !== null &&
|
11660 | util.contains(newVal, '.priority')) {
|
11661 |
|
11662 | priorityForNode = util.safeGet(newVal, '.priority');
|
11663 | util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +
|
11664 | 'Priority must be a valid string, finite number, server value, or null.');
|
11665 | }
|
11666 | else {
|
11667 | var currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||
|
11668 | ChildrenNode.EMPTY_NODE;
|
11669 | priorityForNode = currentNode.getPriority().val();
|
11670 | }
|
11671 | var serverValues = repoGenerateServerValues(repo);
|
11672 | var newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);
|
11673 | var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);
|
11674 | transaction.currentOutputSnapshotRaw = newNodeUnresolved;
|
11675 | transaction.currentOutputSnapshotResolved = newNode;
|
11676 | transaction.currentWriteId = repoGetNextWriteId(repo);
|
11677 | var events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);
|
11678 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
|
11679 | repoSendReadyTransactions(repo, repo.transactionQueueTree_);
|
11680 | }
|
11681 | }
|
11682 |
|
11683 |
|
11684 |
|
11685 | function repoGetLatestState(repo, path, excludeSets) {
|
11686 | return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||
|
11687 | ChildrenNode.EMPTY_NODE);
|
11688 | }
|
11689 |
|
11690 |
|
11691 |
|
11692 |
|
11693 |
|
11694 |
|
11695 |
|
11696 |
|
11697 |
|
11698 | function repoSendReadyTransactions(repo, node) {
|
11699 | if (node === void 0) { node = repo.transactionQueueTree_; }
|
11700 |
|
11701 | if (!node) {
|
11702 | repoPruneCompletedTransactionsBelowNode(repo, node);
|
11703 | }
|
11704 | if (treeGetValue(node)) {
|
11705 | var queue = repoBuildTransactionQueue(repo, node);
|
11706 | util.assert(queue.length > 0, 'Sending zero length transaction queue');
|
11707 | var allRun = queue.every(function (transaction) { return transaction.status === 0 ; });
|
11708 |
|
11709 | if (allRun) {
|
11710 | repoSendTransactionQueue(repo, treeGetPath(node), queue);
|
11711 | }
|
11712 | }
|
11713 | else if (treeHasChildren(node)) {
|
11714 | treeForEachChild(node, function (childNode) {
|
11715 | repoSendReadyTransactions(repo, childNode);
|
11716 | });
|
11717 | }
|
11718 | }
|
11719 |
|
11720 |
|
11721 |
|
11722 |
|
11723 |
|
11724 |
|
11725 |
|
11726 | function repoSendTransactionQueue(repo, path, queue) {
|
11727 |
|
11728 | var setsToIgnore = queue.map(function (txn) {
|
11729 | return txn.currentWriteId;
|
11730 | });
|
11731 | var latestState = repoGetLatestState(repo, path, setsToIgnore);
|
11732 | var snapToSend = latestState;
|
11733 | var latestHash = latestState.hash();
|
11734 | for (var i = 0; i < queue.length; i++) {
|
11735 | var txn = queue[i];
|
11736 | util.assert(txn.status === 0 , 'tryToSendTransactionQueue_: items in queue should all be run.');
|
11737 | txn.status = 1 ;
|
11738 | txn.retryCount++;
|
11739 | var relativePath = newRelativePath(path, txn.path);
|
11740 |
|
11741 | snapToSend = snapToSend.updateChild(relativePath , txn.currentOutputSnapshotRaw);
|
11742 | }
|
11743 | var dataToSend = snapToSend.val(true);
|
11744 | var pathToSend = path;
|
11745 |
|
11746 | repo.server_.put(pathToSend.toString(), dataToSend, function (status) {
|
11747 | repoLog(repo, 'transaction put response', {
|
11748 | path: pathToSend.toString(),
|
11749 | status: status
|
11750 | });
|
11751 | var events = [];
|
11752 | if (status === 'ok') {
|
11753 |
|
11754 |
|
11755 |
|
11756 | var callbacks = [];
|
11757 | var _loop_1 = function (i) {
|
11758 | queue[i].status = 2 ;
|
11759 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));
|
11760 | if (queue[i].onComplete) {
|
11761 |
|
11762 |
|
11763 | callbacks.push(function () {
|
11764 | return queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved);
|
11765 | });
|
11766 | }
|
11767 | queue[i].unwatcher();
|
11768 | };
|
11769 | for (var i = 0; i < queue.length; i++) {
|
11770 | _loop_1(i);
|
11771 | }
|
11772 |
|
11773 | repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
|
11774 |
|
11775 | repoSendReadyTransactions(repo, repo.transactionQueueTree_);
|
11776 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
|
11777 |
|
11778 | for (var i = 0; i < callbacks.length; i++) {
|
11779 | exceptionGuard(callbacks[i]);
|
11780 | }
|
11781 | }
|
11782 | else {
|
11783 |
|
11784 | if (status === 'datastale') {
|
11785 | for (var i = 0; i < queue.length; i++) {
|
11786 | if (queue[i].status === 3 ) {
|
11787 | queue[i].status = 4 ;
|
11788 | }
|
11789 | else {
|
11790 | queue[i].status = 0 ;
|
11791 | }
|
11792 | }
|
11793 | }
|
11794 | else {
|
11795 | warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);
|
11796 | for (var i = 0; i < queue.length; i++) {
|
11797 | queue[i].status = 4 ;
|
11798 | queue[i].abortReason = status;
|
11799 | }
|
11800 | }
|
11801 | repoRerunTransactions(repo, path);
|
11802 | }
|
11803 | }, latestHash);
|
11804 | }
|
11805 |
|
11806 |
|
11807 |
|
11808 |
|
11809 |
|
11810 |
|
11811 |
|
11812 |
|
11813 |
|
11814 |
|
11815 |
|
11816 | function repoRerunTransactions(repo, changedPath) {
|
11817 | var rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
|
11818 | var path = treeGetPath(rootMostTransactionNode);
|
11819 | var queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
|
11820 | repoRerunTransactionQueue(repo, queue, path);
|
11821 | return path;
|
11822 | }
|
11823 |
|
11824 |
|
11825 |
|
11826 |
|
11827 |
|
11828 |
|
11829 |
|
11830 | function repoRerunTransactionQueue(repo, queue, path) {
|
11831 | if (queue.length === 0) {
|
11832 | return;
|
11833 | }
|
11834 |
|
11835 |
|
11836 |
|
11837 | var callbacks = [];
|
11838 | var events = [];
|
11839 |
|
11840 | var txnsToRerun = queue.filter(function (q) {
|
11841 | return q.status === 0 ;
|
11842 | });
|
11843 | var setsToIgnore = txnsToRerun.map(function (q) {
|
11844 | return q.currentWriteId;
|
11845 | });
|
11846 | var _loop_2 = function (i) {
|
11847 | var transaction = queue[i];
|
11848 | var relativePath = newRelativePath(path, transaction.path);
|
11849 | var abortTransaction = false, abortReason;
|
11850 | util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');
|
11851 | if (transaction.status === 4 ) {
|
11852 | abortTransaction = true;
|
11853 | abortReason = transaction.abortReason;
|
11854 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
|
11855 | }
|
11856 | else if (transaction.status === 0 ) {
|
11857 | if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
|
11858 | abortTransaction = true;
|
11859 | abortReason = 'maxretry';
|
11860 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
|
11861 | }
|
11862 | else {
|
11863 |
|
11864 | var currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
|
11865 | transaction.currentInputSnapshot = currentNode;
|
11866 | var newData = queue[i].update(currentNode.val());
|
11867 | if (newData !== undefined) {
|
11868 | validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);
|
11869 | var newDataNode = nodeFromJSON(newData);
|
11870 | var hasExplicitPriority = typeof newData === 'object' &&
|
11871 | newData != null &&
|
11872 | util.contains(newData, '.priority');
|
11873 | if (!hasExplicitPriority) {
|
11874 |
|
11875 | newDataNode = newDataNode.updatePriority(currentNode.getPriority());
|
11876 | }
|
11877 | var oldWriteId = transaction.currentWriteId;
|
11878 | var serverValues = repoGenerateServerValues(repo);
|
11879 | var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
|
11880 | transaction.currentOutputSnapshotRaw = newDataNode;
|
11881 | transaction.currentOutputSnapshotResolved = newNodeResolved;
|
11882 | transaction.currentWriteId = repoGetNextWriteId(repo);
|
11883 |
|
11884 | setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
|
11885 | events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
|
11886 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
|
11887 | }
|
11888 | else {
|
11889 | abortTransaction = true;
|
11890 | abortReason = 'nodata';
|
11891 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
|
11892 | }
|
11893 | }
|
11894 | }
|
11895 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);
|
11896 | events = [];
|
11897 | if (abortTransaction) {
|
11898 |
|
11899 | queue[i].status = 2 ;
|
11900 |
|
11901 |
|
11902 |
|
11903 | (function (unwatcher) {
|
11904 | setTimeout(unwatcher, Math.floor(0));
|
11905 | })(queue[i].unwatcher);
|
11906 | if (queue[i].onComplete) {
|
11907 | if (abortReason === 'nodata') {
|
11908 | callbacks.push(function () {
|
11909 | return queue[i].onComplete(null, false, queue[i].currentInputSnapshot);
|
11910 | });
|
11911 | }
|
11912 | else {
|
11913 | callbacks.push(function () {
|
11914 | return queue[i].onComplete(new Error(abortReason), false, null);
|
11915 | });
|
11916 | }
|
11917 | }
|
11918 | }
|
11919 | };
|
11920 | for (var i = 0; i < queue.length; i++) {
|
11921 | _loop_2(i);
|
11922 | }
|
11923 |
|
11924 | repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
|
11925 |
|
11926 | for (var i = 0; i < callbacks.length; i++) {
|
11927 | exceptionGuard(callbacks[i]);
|
11928 | }
|
11929 |
|
11930 | repoSendReadyTransactions(repo, repo.transactionQueueTree_);
|
11931 | }
|
11932 |
|
11933 |
|
11934 |
|
11935 |
|
11936 |
|
11937 |
|
11938 |
|
11939 |
|
11940 | function repoGetAncestorTransactionNode(repo, path) {
|
11941 | var front;
|
11942 |
|
11943 |
|
11944 | var transactionNode = repo.transactionQueueTree_;
|
11945 | front = pathGetFront(path);
|
11946 | while (front !== null && treeGetValue(transactionNode) === undefined) {
|
11947 | transactionNode = treeSubTree(transactionNode, front);
|
11948 | path = pathPopFront(path);
|
11949 | front = pathGetFront(path);
|
11950 | }
|
11951 | return transactionNode;
|
11952 | }
|
11953 |
|
11954 |
|
11955 |
|
11956 |
|
11957 |
|
11958 |
|
11959 |
|
11960 | function repoBuildTransactionQueue(repo, transactionNode) {
|
11961 |
|
11962 | var transactionQueue = [];
|
11963 | repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
|
11964 |
|
11965 | transactionQueue.sort(function (a, b) { return a.order - b.order; });
|
11966 | return transactionQueue;
|
11967 | }
|
11968 | function repoAggregateTransactionQueuesForNode(repo, node, queue) {
|
11969 | var nodeQueue = treeGetValue(node);
|
11970 | if (nodeQueue) {
|
11971 | for (var i = 0; i < nodeQueue.length; i++) {
|
11972 | queue.push(nodeQueue[i]);
|
11973 | }
|
11974 | }
|
11975 | treeForEachChild(node, function (child) {
|
11976 | repoAggregateTransactionQueuesForNode(repo, child, queue);
|
11977 | });
|
11978 | }
|
11979 |
|
11980 |
|
11981 |
|
11982 | function repoPruneCompletedTransactionsBelowNode(repo, node) {
|
11983 | var queue = treeGetValue(node);
|
11984 | if (queue) {
|
11985 | var to = 0;
|
11986 | for (var from = 0; from < queue.length; from++) {
|
11987 | if (queue[from].status !== 2 ) {
|
11988 | queue[to] = queue[from];
|
11989 | to++;
|
11990 | }
|
11991 | }
|
11992 | queue.length = to;
|
11993 | treeSetValue(node, queue.length > 0 ? queue : undefined);
|
11994 | }
|
11995 | treeForEachChild(node, function (childNode) {
|
11996 | repoPruneCompletedTransactionsBelowNode(repo, childNode);
|
11997 | });
|
11998 | }
|
11999 |
|
12000 |
|
12001 |
|
12002 |
|
12003 |
|
12004 |
|
12005 |
|
12006 | function repoAbortTransactions(repo, path) {
|
12007 | var affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
|
12008 | var transactionNode = treeSubTree(repo.transactionQueueTree_, path);
|
12009 | treeForEachAncestor(transactionNode, function (node) {
|
12010 | repoAbortTransactionsOnNode(repo, node);
|
12011 | });
|
12012 | repoAbortTransactionsOnNode(repo, transactionNode);
|
12013 | treeForEachDescendant(transactionNode, function (node) {
|
12014 | repoAbortTransactionsOnNode(repo, node);
|
12015 | });
|
12016 | return affectedPath;
|
12017 | }
|
12018 |
|
12019 |
|
12020 |
|
12021 |
|
12022 |
|
12023 | function repoAbortTransactionsOnNode(repo, node) {
|
12024 | var queue = treeGetValue(node);
|
12025 | if (queue) {
|
12026 |
|
12027 |
|
12028 |
|
12029 | var callbacks = [];
|
12030 |
|
12031 |
|
12032 | var events = [];
|
12033 | var lastSent = -1;
|
12034 | for (var i = 0; i < queue.length; i++) {
|
12035 | if (queue[i].status === 3 ) ;
|
12036 | else if (queue[i].status === 1 ) {
|
12037 | util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');
|
12038 | lastSent = i;
|
12039 |
|
12040 | queue[i].status = 3 ;
|
12041 | queue[i].abortReason = 'set';
|
12042 | }
|
12043 | else {
|
12044 | util.assert(queue[i].status === 0 , 'Unexpected transaction status in abort');
|
12045 |
|
12046 | queue[i].unwatcher();
|
12047 | events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));
|
12048 | if (queue[i].onComplete) {
|
12049 | callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));
|
12050 | }
|
12051 | }
|
12052 | }
|
12053 | if (lastSent === -1) {
|
12054 |
|
12055 | treeSetValue(node, undefined);
|
12056 | }
|
12057 | else {
|
12058 |
|
12059 | queue.length = lastSent + 1;
|
12060 | }
|
12061 |
|
12062 | eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);
|
12063 | for (var i = 0; i < callbacks.length; i++) {
|
12064 | exceptionGuard(callbacks[i]);
|
12065 | }
|
12066 | }
|
12067 | }
|
12068 |
|
12069 |
|
12070 |
|
12071 |
|
12072 |
|
12073 |
|
12074 |
|
12075 |
|
12076 |
|
12077 |
|
12078 |
|
12079 |
|
12080 |
|
12081 |
|
12082 |
|
12083 |
|
12084 |
|
12085 | function decodePath(pathString) {
|
12086 | var pathStringDecoded = '';
|
12087 | var pieces = pathString.split('/');
|
12088 | for (var i = 0; i < pieces.length; i++) {
|
12089 | if (pieces[i].length > 0) {
|
12090 | var piece = pieces[i];
|
12091 | try {
|
12092 | piece = decodeURIComponent(piece.replace(/\+/g, ' '));
|
12093 | }
|
12094 | catch (e) { }
|
12095 | pathStringDecoded += '/' + piece;
|
12096 | }
|
12097 | }
|
12098 | return pathStringDecoded;
|
12099 | }
|
12100 |
|
12101 |
|
12102 |
|
12103 | function decodeQuery(queryString) {
|
12104 | var e_1, _a;
|
12105 | var results = {};
|
12106 | if (queryString.charAt(0) === '?') {
|
12107 | queryString = queryString.substring(1);
|
12108 | }
|
12109 | try {
|
12110 | for (var _b = tslib.__values(queryString.split('&')), _c = _b.next(); !_c.done; _c = _b.next()) {
|
12111 | var segment = _c.value;
|
12112 | if (segment.length === 0) {
|
12113 | continue;
|
12114 | }
|
12115 | var kv = segment.split('=');
|
12116 | if (kv.length === 2) {
|
12117 | results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
|
12118 | }
|
12119 | else {
|
12120 | warn("Invalid query segment '".concat(segment, "' in query '").concat(queryString, "'"));
|
12121 | }
|
12122 | }
|
12123 | }
|
12124 | catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
12125 | finally {
|
12126 | try {
|
12127 | if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
|
12128 | }
|
12129 | finally { if (e_1) throw e_1.error; }
|
12130 | }
|
12131 | return results;
|
12132 | }
|
12133 | var parseRepoInfo = function (dataURL, nodeAdmin) {
|
12134 | var parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
|
12135 | if (parsedUrl.domain === 'firebase.com') {
|
12136 | fatal(parsedUrl.host +
|
12137 | ' is no longer supported. ' +
|
12138 | 'Please use <YOUR FIREBASE>.firebaseio.com instead');
|
12139 | }
|
12140 |
|
12141 | if ((!namespace || namespace === 'undefined') &&
|
12142 | parsedUrl.domain !== 'localhost') {
|
12143 | fatal('Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com');
|
12144 | }
|
12145 | if (!parsedUrl.secure) {
|
12146 | warnIfPageIsSecure();
|
12147 | }
|
12148 | var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';
|
12149 | return {
|
12150 | repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin,
|
12151 | '',
|
12152 | namespace !== parsedUrl.subdomain),
|
12153 | path: new Path(parsedUrl.pathString)
|
12154 | };
|
12155 | };
|
12156 | var parseDatabaseURL = function (dataURL) {
|
12157 |
|
12158 | var host = '', domain = '', subdomain = '', pathString = '', namespace = '';
|
12159 |
|
12160 | var secure = true, scheme = 'https', port = 443;
|
12161 |
|
12162 | if (typeof dataURL === 'string') {
|
12163 |
|
12164 | var colonInd = dataURL.indexOf('//');
|
12165 | if (colonInd >= 0) {
|
12166 | scheme = dataURL.substring(0, colonInd - 1);
|
12167 | dataURL = dataURL.substring(colonInd + 2);
|
12168 | }
|
12169 |
|
12170 | var slashInd = dataURL.indexOf('/');
|
12171 | if (slashInd === -1) {
|
12172 | slashInd = dataURL.length;
|
12173 | }
|
12174 | var questionMarkInd = dataURL.indexOf('?');
|
12175 | if (questionMarkInd === -1) {
|
12176 | questionMarkInd = dataURL.length;
|
12177 | }
|
12178 | host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
|
12179 | if (slashInd < questionMarkInd) {
|
12180 |
|
12181 | pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
|
12182 | }
|
12183 | var queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
|
12184 |
|
12185 | colonInd = host.indexOf(':');
|
12186 | if (colonInd >= 0) {
|
12187 | secure = scheme === 'https' || scheme === 'wss';
|
12188 | port = parseInt(host.substring(colonInd + 1), 10);
|
12189 | }
|
12190 | else {
|
12191 | colonInd = host.length;
|
12192 | }
|
12193 | var hostWithoutPort = host.slice(0, colonInd);
|
12194 | if (hostWithoutPort.toLowerCase() === 'localhost') {
|
12195 | domain = 'localhost';
|
12196 | }
|
12197 | else if (hostWithoutPort.split('.').length <= 2) {
|
12198 | domain = hostWithoutPort;
|
12199 | }
|
12200 | else {
|
12201 |
|
12202 | var dotInd = host.indexOf('.');
|
12203 | subdomain = host.substring(0, dotInd).toLowerCase();
|
12204 | domain = host.substring(dotInd + 1);
|
12205 |
|
12206 | namespace = subdomain;
|
12207 | }
|
12208 |
|
12209 | if ('ns' in queryParams) {
|
12210 | namespace = queryParams['ns'];
|
12211 | }
|
12212 | }
|
12213 | return {
|
12214 | host: host,
|
12215 | port: port,
|
12216 | domain: domain,
|
12217 | subdomain: subdomain,
|
12218 | secure: secure,
|
12219 | scheme: scheme,
|
12220 | pathString: pathString,
|
12221 | namespace: namespace
|
12222 | };
|
12223 | };
|
12224 |
|
12225 |
|
12226 |
|
12227 |
|
12228 |
|
12229 |
|
12230 |
|
12231 |
|
12232 |
|
12233 |
|
12234 |
|
12235 |
|
12236 |
|
12237 |
|
12238 |
|
12239 |
|
12240 |
|
12241 |
|
12242 | var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
|
12243 |
|
12244 |
|
12245 |
|
12246 |
|
12247 |
|
12248 |
|
12249 |
|
12250 |
|
12251 |
|
12252 |
|
12253 |
|
12254 |
|
12255 |
|
12256 |
|
12257 | var nextPushId = (function () {
|
12258 |
|
12259 |
|
12260 | var lastPushTime = 0;
|
12261 |
|
12262 |
|
12263 |
|
12264 |
|
12265 | var lastRandChars = [];
|
12266 | return function (now) {
|
12267 | var duplicateTime = now === lastPushTime;
|
12268 | lastPushTime = now;
|
12269 | var i;
|
12270 | var timeStampChars = new Array(8);
|
12271 | for (i = 7; i >= 0; i--) {
|
12272 | timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
|
12273 |
|
12274 |
|
12275 | now = Math.floor(now / 64);
|
12276 | }
|
12277 | util.assert(now === 0, 'Cannot push at time == 0');
|
12278 | var id = timeStampChars.join('');
|
12279 | if (!duplicateTime) {
|
12280 | for (i = 0; i < 12; i++) {
|
12281 | lastRandChars[i] = Math.floor(Math.random() * 64);
|
12282 | }
|
12283 | }
|
12284 | else {
|
12285 |
|
12286 |
|
12287 | for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
|
12288 | lastRandChars[i] = 0;
|
12289 | }
|
12290 | lastRandChars[i]++;
|
12291 | }
|
12292 | for (i = 0; i < 12; i++) {
|
12293 | id += PUSH_CHARS.charAt(lastRandChars[i]);
|
12294 | }
|
12295 | util.assert(id.length === 20, 'nextPushId: Length should be 20.');
|
12296 | return id;
|
12297 | };
|
12298 | })();
|
12299 |
|
12300 |
|
12301 |
|
12302 |
|
12303 |
|
12304 |
|
12305 |
|
12306 |
|
12307 |
|
12308 |
|
12309 |
|
12310 |
|
12311 |
|
12312 |
|
12313 |
|
12314 |
|
12315 |
|
12316 |
|
12317 |
|
12318 |
|
12319 | var DataEvent = (function () {
|
12320 | |
12321 |
|
12322 |
|
12323 |
|
12324 |
|
12325 |
|
12326 | function DataEvent(eventType, eventRegistration, snapshot, prevName) {
|
12327 | this.eventType = eventType;
|
12328 | this.eventRegistration = eventRegistration;
|
12329 | this.snapshot = snapshot;
|
12330 | this.prevName = prevName;
|
12331 | }
|
12332 | DataEvent.prototype.getPath = function () {
|
12333 | var ref = this.snapshot.ref;
|
12334 | if (this.eventType === 'value') {
|
12335 | return ref._path;
|
12336 | }
|
12337 | else {
|
12338 | return ref.parent._path;
|
12339 | }
|
12340 | };
|
12341 | DataEvent.prototype.getEventType = function () {
|
12342 | return this.eventType;
|
12343 | };
|
12344 | DataEvent.prototype.getEventRunner = function () {
|
12345 | return this.eventRegistration.getEventRunner(this);
|
12346 | };
|
12347 | DataEvent.prototype.toString = function () {
|
12348 | return (this.getPath().toString() +
|
12349 | ':' +
|
12350 | this.eventType +
|
12351 | ':' +
|
12352 | util.stringify(this.snapshot.exportVal()));
|
12353 | };
|
12354 | return DataEvent;
|
12355 | }());
|
12356 | var CancelEvent = (function () {
|
12357 | function CancelEvent(eventRegistration, error, path) {
|
12358 | this.eventRegistration = eventRegistration;
|
12359 | this.error = error;
|
12360 | this.path = path;
|
12361 | }
|
12362 | CancelEvent.prototype.getPath = function () {
|
12363 | return this.path;
|
12364 | };
|
12365 | CancelEvent.prototype.getEventType = function () {
|
12366 | return 'cancel';
|
12367 | };
|
12368 | CancelEvent.prototype.getEventRunner = function () {
|
12369 | return this.eventRegistration.getEventRunner(this);
|
12370 | };
|
12371 | CancelEvent.prototype.toString = function () {
|
12372 | return this.path.toString() + ':cancel';
|
12373 | };
|
12374 | return CancelEvent;
|
12375 | }());
|
12376 |
|
12377 |
|
12378 |
|
12379 |
|
12380 |
|
12381 |
|
12382 |
|
12383 |
|
12384 |
|
12385 |
|
12386 |
|
12387 |
|
12388 |
|
12389 |
|
12390 |
|
12391 |
|
12392 |
|
12393 |
|
12394 |
|
12395 |
|
12396 |
|
12397 |
|
12398 |
|
12399 | var CallbackContext = (function () {
|
12400 | function CallbackContext(snapshotCallback, cancelCallback) {
|
12401 | this.snapshotCallback = snapshotCallback;
|
12402 | this.cancelCallback = cancelCallback;
|
12403 | }
|
12404 | CallbackContext.prototype.onValue = function (expDataSnapshot, previousChildName) {
|
12405 | this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
|
12406 | };
|
12407 | CallbackContext.prototype.onCancel = function (error) {
|
12408 | util.assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');
|
12409 | return this.cancelCallback.call(null, error);
|
12410 | };
|
12411 | Object.defineProperty(CallbackContext.prototype, "hasCancelCallback", {
|
12412 | get: function () {
|
12413 | return !!this.cancelCallback;
|
12414 | },
|
12415 | enumerable: false,
|
12416 | configurable: true
|
12417 | });
|
12418 | CallbackContext.prototype.matches = function (other) {
|
12419 | return (this.snapshotCallback === other.snapshotCallback ||
|
12420 | (this.snapshotCallback.userCallback !== undefined &&
|
12421 | this.snapshotCallback.userCallback ===
|
12422 | other.snapshotCallback.userCallback &&
|
12423 | this.snapshotCallback.context === other.snapshotCallback.context));
|
12424 | };
|
12425 | return CallbackContext;
|
12426 | }());
|
12427 |
|
12428 |
|
12429 |
|
12430 |
|
12431 |
|
12432 |
|
12433 |
|
12434 |
|
12435 |
|
12436 |
|
12437 |
|
12438 |
|
12439 |
|
12440 |
|
12441 |
|
12442 |
|
12443 |
|
12444 |
|
12445 |
|
12446 |
|
12447 |
|
12448 |
|
12449 |
|
12450 |
|
12451 |
|
12452 |
|
12453 |
|
12454 |
|
12455 |
|
12456 |
|
12457 |
|
12458 |
|
12459 |
|
12460 |
|
12461 |
|
12462 |
|
12463 |
|
12464 | var OnDisconnect = (function () {
|
12465 |
|
12466 | function OnDisconnect(_repo, _path) {
|
12467 | this._repo = _repo;
|
12468 | this._path = _path;
|
12469 | }
|
12470 | |
12471 |
|
12472 |
|
12473 |
|
12474 |
|
12475 |
|
12476 |
|
12477 |
|
12478 |
|
12479 |
|
12480 | OnDisconnect.prototype.cancel = function () {
|
12481 | var deferred = new util.Deferred();
|
12482 | repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(function () { }));
|
12483 | return deferred.promise;
|
12484 | };
|
12485 | |
12486 |
|
12487 |
|
12488 |
|
12489 |
|
12490 |
|
12491 | OnDisconnect.prototype.remove = function () {
|
12492 | validateWritablePath('OnDisconnect.remove', this._path);
|
12493 | var deferred = new util.Deferred();
|
12494 | repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(function () { }));
|
12495 | return deferred.promise;
|
12496 | };
|
12497 | |
12498 |
|
12499 |
|
12500 |
|
12501 |
|
12502 |
|
12503 |
|
12504 |
|
12505 |
|
12506 |
|
12507 |
|
12508 |
|
12509 |
|
12510 |
|
12511 |
|
12512 |
|
12513 |
|
12514 |
|
12515 |
|
12516 | OnDisconnect.prototype.set = function (value) {
|
12517 | validateWritablePath('OnDisconnect.set', this._path);
|
12518 | validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);
|
12519 | var deferred = new util.Deferred();
|
12520 | repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(function () { }));
|
12521 | return deferred.promise;
|
12522 | };
|
12523 | |
12524 |
|
12525 |
|
12526 |
|
12527 |
|
12528 |
|
12529 |
|
12530 |
|
12531 |
|
12532 |
|
12533 | OnDisconnect.prototype.setWithPriority = function (value, priority) {
|
12534 | validateWritablePath('OnDisconnect.setWithPriority', this._path);
|
12535 | validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);
|
12536 | validatePriority('OnDisconnect.setWithPriority', priority, false);
|
12537 | var deferred = new util.Deferred();
|
12538 | repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(function () { }));
|
12539 | return deferred.promise;
|
12540 | };
|
12541 | |
12542 |
|
12543 |
|
12544 |
|
12545 |
|
12546 |
|
12547 |
|
12548 |
|
12549 |
|
12550 |
|
12551 |
|
12552 |
|
12553 |
|
12554 |
|
12555 |
|
12556 |
|
12557 | OnDisconnect.prototype.update = function (values) {
|
12558 | validateWritablePath('OnDisconnect.update', this._path);
|
12559 | validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);
|
12560 | var deferred = new util.Deferred();
|
12561 | repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(function () { }));
|
12562 | return deferred.promise;
|
12563 | };
|
12564 | return OnDisconnect;
|
12565 | }());
|
12566 |
|
12567 |
|
12568 |
|
12569 |
|
12570 |
|
12571 |
|
12572 |
|
12573 |
|
12574 |
|
12575 |
|
12576 |
|
12577 |
|
12578 |
|
12579 |
|
12580 |
|
12581 |
|
12582 |
|
12583 |
|
12584 |
|
12585 |
|
12586 | var QueryImpl = (function () {
|
12587 | |
12588 |
|
12589 |
|
12590 | function QueryImpl(_repo, _path, _queryParams, _orderByCalled) {
|
12591 | this._repo = _repo;
|
12592 | this._path = _path;
|
12593 | this._queryParams = _queryParams;
|
12594 | this._orderByCalled = _orderByCalled;
|
12595 | }
|
12596 | Object.defineProperty(QueryImpl.prototype, "key", {
|
12597 | get: function () {
|
12598 | if (pathIsEmpty(this._path)) {
|
12599 | return null;
|
12600 | }
|
12601 | else {
|
12602 | return pathGetBack(this._path);
|
12603 | }
|
12604 | },
|
12605 | enumerable: false,
|
12606 | configurable: true
|
12607 | });
|
12608 | Object.defineProperty(QueryImpl.prototype, "ref", {
|
12609 | get: function () {
|
12610 | return new ReferenceImpl(this._repo, this._path);
|
12611 | },
|
12612 | enumerable: false,
|
12613 | configurable: true
|
12614 | });
|
12615 | Object.defineProperty(QueryImpl.prototype, "_queryIdentifier", {
|
12616 | get: function () {
|
12617 | var obj = queryParamsGetQueryObject(this._queryParams);
|
12618 | var id = ObjectToUniqueKey(obj);
|
12619 | return id === '{}' ? 'default' : id;
|
12620 | },
|
12621 | enumerable: false,
|
12622 | configurable: true
|
12623 | });
|
12624 | Object.defineProperty(QueryImpl.prototype, "_queryObject", {
|
12625 | |
12626 |
|
12627 |
|
12628 | get: function () {
|
12629 | return queryParamsGetQueryObject(this._queryParams);
|
12630 | },
|
12631 | enumerable: false,
|
12632 | configurable: true
|
12633 | });
|
12634 | QueryImpl.prototype.isEqual = function (other) {
|
12635 | other = util.getModularInstance(other);
|
12636 | if (!(other instanceof QueryImpl)) {
|
12637 | return false;
|
12638 | }
|
12639 | var sameRepo = this._repo === other._repo;
|
12640 | var samePath = pathEquals(this._path, other._path);
|
12641 | var sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
|
12642 | return sameRepo && samePath && sameQueryIdentifier;
|
12643 | };
|
12644 | QueryImpl.prototype.toJSON = function () {
|
12645 | return this.toString();
|
12646 | };
|
12647 | QueryImpl.prototype.toString = function () {
|
12648 | return this._repo.toString() + pathToUrlEncodedString(this._path);
|
12649 | };
|
12650 | return QueryImpl;
|
12651 | }());
|
12652 |
|
12653 |
|
12654 |
|
12655 | function validateNoPreviousOrderByCall(query, fnName) {
|
12656 | if (query._orderByCalled === true) {
|
12657 | throw new Error(fnName + ": You can't combine multiple orderBy calls.");
|
12658 | }
|
12659 | }
|
12660 |
|
12661 |
|
12662 |
|
12663 | function validateQueryEndpoints(params) {
|
12664 | var startNode = null;
|
12665 | var endNode = null;
|
12666 | if (params.hasStart()) {
|
12667 | startNode = params.getIndexStartValue();
|
12668 | }
|
12669 | if (params.hasEnd()) {
|
12670 | endNode = params.getIndexEndValue();
|
12671 | }
|
12672 | if (params.getIndex() === KEY_INDEX) {
|
12673 | var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +
|
12674 | 'startAt(), endAt(), or equalTo().';
|
12675 | var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +
|
12676 | 'endAt(), endBefore(), or equalTo() must be a string.';
|
12677 | if (params.hasStart()) {
|
12678 | var startName = params.getIndexStartName();
|
12679 | if (startName !== MIN_NAME) {
|
12680 | throw new Error(tooManyArgsError);
|
12681 | }
|
12682 | else if (typeof startNode !== 'string') {
|
12683 | throw new Error(wrongArgTypeError);
|
12684 | }
|
12685 | }
|
12686 | if (params.hasEnd()) {
|
12687 | var endName = params.getIndexEndName();
|
12688 | if (endName !== MAX_NAME) {
|
12689 | throw new Error(tooManyArgsError);
|
12690 | }
|
12691 | else if (typeof endNode !== 'string') {
|
12692 | throw new Error(wrongArgTypeError);
|
12693 | }
|
12694 | }
|
12695 | }
|
12696 | else if (params.getIndex() === PRIORITY_INDEX) {
|
12697 | if ((startNode != null && !isValidPriority(startNode)) ||
|
12698 | (endNode != null && !isValidPriority(endNode))) {
|
12699 | throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +
|
12700 | 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +
|
12701 | '(null, a number, or a string).');
|
12702 | }
|
12703 | }
|
12704 | else {
|
12705 | util.assert(params.getIndex() instanceof PathIndex ||
|
12706 | params.getIndex() === VALUE_INDEX, 'unknown index type.');
|
12707 | if ((startNode != null && typeof startNode === 'object') ||
|
12708 | (endNode != null && typeof endNode === 'object')) {
|
12709 | throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +
|
12710 | 'equalTo() cannot be an object.');
|
12711 | }
|
12712 | }
|
12713 | }
|
12714 |
|
12715 |
|
12716 |
|
12717 | function validateLimit(params) {
|
12718 | if (params.hasStart() &&
|
12719 | params.hasEnd() &&
|
12720 | params.hasLimit() &&
|
12721 | !params.hasAnchoredLimit()) {
|
12722 | throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use " +
|
12723 | 'limitToFirst() or limitToLast() instead.');
|
12724 | }
|
12725 | }
|
12726 |
|
12727 |
|
12728 |
|
12729 | var ReferenceImpl = (function (_super) {
|
12730 | tslib.__extends(ReferenceImpl, _super);
|
12731 |
|
12732 | function ReferenceImpl(repo, path) {
|
12733 | return _super.call(this, repo, path, new QueryParams(), false) || this;
|
12734 | }
|
12735 | Object.defineProperty(ReferenceImpl.prototype, "parent", {
|
12736 | get: function () {
|
12737 | var parentPath = pathParent(this._path);
|
12738 | return parentPath === null
|
12739 | ? null
|
12740 | : new ReferenceImpl(this._repo, parentPath);
|
12741 | },
|
12742 | enumerable: false,
|
12743 | configurable: true
|
12744 | });
|
12745 | Object.defineProperty(ReferenceImpl.prototype, "root", {
|
12746 | get: function () {
|
12747 | var ref = this;
|
12748 | while (ref.parent !== null) {
|
12749 | ref = ref.parent;
|
12750 | }
|
12751 | return ref;
|
12752 | },
|
12753 | enumerable: false,
|
12754 | configurable: true
|
12755 | });
|
12756 | return ReferenceImpl;
|
12757 | }(QueryImpl));
|
12758 |
|
12759 |
|
12760 |
|
12761 |
|
12762 |
|
12763 |
|
12764 |
|
12765 |
|
12766 |
|
12767 |
|
12768 |
|
12769 |
|
12770 |
|
12771 |
|
12772 | var DataSnapshot = (function () {
|
12773 | |
12774 |
|
12775 |
|
12776 |
|
12777 |
|
12778 |
|
12779 | function DataSnapshot(_node,
|
12780 | /**
|
12781 | * The location of this DataSnapshot.
|
12782 | */
|
12783 | ref, _index) {
|
12784 | this._node = _node;
|
12785 | this.ref = ref;
|
12786 | this._index = _index;
|
12787 | }
|
12788 | Object.defineProperty(DataSnapshot.prototype, "priority", {
|
12789 | |
12790 |
|
12791 |
|
12792 |
|
12793 |
|
12794 |
|
12795 |
|
12796 |
|
12797 | get: function () {
|
12798 |
|
12799 | return this._node.getPriority().val();
|
12800 | },
|
12801 | enumerable: false,
|
12802 | configurable: true
|
12803 | });
|
12804 | Object.defineProperty(DataSnapshot.prototype, "key", {
|
12805 | |
12806 |
|
12807 |
|
12808 |
|
12809 |
|
12810 |
|
12811 |
|
12812 |
|
12813 |
|
12814 | get: function () {
|
12815 | return this.ref.key;
|
12816 | },
|
12817 | enumerable: false,
|
12818 | configurable: true
|
12819 | });
|
12820 | Object.defineProperty(DataSnapshot.prototype, "size", {
|
12821 |
|
12822 | get: function () {
|
12823 | return this._node.numChildren();
|
12824 | },
|
12825 | enumerable: false,
|
12826 | configurable: true
|
12827 | });
|
12828 | |
12829 |
|
12830 |
|
12831 |
|
12832 |
|
12833 |
|
12834 |
|
12835 |
|
12836 |
|
12837 |
|
12838 |
|
12839 |
|
12840 | DataSnapshot.prototype.child = function (path) {
|
12841 | var childPath = new Path(path);
|
12842 | var childRef = child(this.ref, path);
|
12843 | return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
|
12844 | };
|
12845 | |
12846 |
|
12847 |
|
12848 |
|
12849 | DataSnapshot.prototype.exists = function () {
|
12850 | return !this._node.isEmpty();
|
12851 | };
|
12852 | |
12853 |
|
12854 |
|
12855 |
|
12856 |
|
12857 |
|
12858 |
|
12859 |
|
12860 |
|
12861 |
|
12862 | DataSnapshot.prototype.exportVal = function () {
|
12863 | return this._node.val(true);
|
12864 | };
|
12865 | |
12866 |
|
12867 |
|
12868 |
|
12869 |
|
12870 |
|
12871 |
|
12872 |
|
12873 |
|
12874 |
|
12875 |
|
12876 |
|
12877 |
|
12878 |
|
12879 |
|
12880 |
|
12881 |
|
12882 |
|
12883 | DataSnapshot.prototype.forEach = function (action) {
|
12884 | var _this = this;
|
12885 | if (this._node.isLeafNode()) {
|
12886 | return false;
|
12887 | }
|
12888 | var childrenNode = this._node;
|
12889 |
|
12890 | return !!childrenNode.forEachChild(this._index, function (key, node) {
|
12891 | return action(new DataSnapshot(node, child(_this.ref, key), PRIORITY_INDEX));
|
12892 | });
|
12893 | };
|
12894 | |
12895 |
|
12896 |
|
12897 |
|
12898 |
|
12899 |
|
12900 |
|
12901 | DataSnapshot.prototype.hasChild = function (path) {
|
12902 | var childPath = new Path(path);
|
12903 | return !this._node.getChild(childPath).isEmpty();
|
12904 | };
|
12905 | |
12906 |
|
12907 |
|
12908 |
|
12909 |
|
12910 |
|
12911 |
|
12912 |
|
12913 |
|
12914 |
|
12915 |
|
12916 |
|
12917 | DataSnapshot.prototype.hasChildren = function () {
|
12918 | if (this._node.isLeafNode()) {
|
12919 | return false;
|
12920 | }
|
12921 | else {
|
12922 | return !this._node.isEmpty();
|
12923 | }
|
12924 | };
|
12925 | |
12926 |
|
12927 |
|
12928 | DataSnapshot.prototype.toJSON = function () {
|
12929 | return this.exportVal();
|
12930 | };
|
12931 | |
12932 |
|
12933 |
|
12934 |
|
12935 |
|
12936 |
|
12937 |
|
12938 |
|
12939 |
|
12940 |
|
12941 |
|
12942 |
|
12943 | DataSnapshot.prototype.val = function () {
|
12944 | return this._node.val();
|
12945 | };
|
12946 | return DataSnapshot;
|
12947 | }());
|
12948 |
|
12949 |
|
12950 |
|
12951 |
|
12952 |
|
12953 |
|
12954 |
|
12955 |
|
12956 |
|
12957 |
|
12958 |
|
12959 |
|
12960 |
|
12961 |
|
12962 | function ref(db, path) {
|
12963 | db = util.getModularInstance(db);
|
12964 | db._checkNotDeleted('ref');
|
12965 | return path !== undefined ? child(db._root, path) : db._root;
|
12966 | }
|
12967 |
|
12968 |
|
12969 |
|
12970 |
|
12971 |
|
12972 |
|
12973 |
|
12974 |
|
12975 |
|
12976 |
|
12977 |
|
12978 |
|
12979 |
|
12980 |
|
12981 |
|
12982 |
|
12983 | function refFromURL(db, url) {
|
12984 | db = util.getModularInstance(db);
|
12985 | db._checkNotDeleted('refFromURL');
|
12986 | var parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);
|
12987 | validateUrl('refFromURL', parsedURL);
|
12988 | var repoInfo = parsedURL.repoInfo;
|
12989 | if (!db._repo.repoInfo_.isCustomHost() &&
|
12990 | repoInfo.host !== db._repo.repoInfo_.host) {
|
12991 | fatal('refFromURL' +
|
12992 | ': Host name does not match the current database: ' +
|
12993 | '(found ' +
|
12994 | repoInfo.host +
|
12995 | ' but expected ' +
|
12996 | db._repo.repoInfo_.host +
|
12997 | ')');
|
12998 | }
|
12999 | return ref(db, parsedURL.path.toString());
|
13000 | }
|
13001 |
|
13002 |
|
13003 |
|
13004 |
|
13005 |
|
13006 |
|
13007 |
|
13008 |
|
13009 |
|
13010 |
|
13011 |
|
13012 | function child(parent, path) {
|
13013 | parent = util.getModularInstance(parent);
|
13014 | if (pathGetFront(parent._path) === null) {
|
13015 | validateRootPathString('child', 'path', path, false);
|
13016 | }
|
13017 | else {
|
13018 | validatePathString('child', 'path', path, false);
|
13019 | }
|
13020 | return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
|
13021 | }
|
13022 |
|
13023 |
|
13024 |
|
13025 |
|
13026 |
|
13027 |
|
13028 |
|
13029 | function onDisconnect(ref) {
|
13030 | ref = util.getModularInstance(ref);
|
13031 | return new OnDisconnect(ref._repo, ref._path);
|
13032 | }
|
13033 |
|
13034 |
|
13035 |
|
13036 |
|
13037 |
|
13038 |
|
13039 |
|
13040 |
|
13041 |
|
13042 |
|
13043 |
|
13044 |
|
13045 |
|
13046 |
|
13047 |
|
13048 |
|
13049 |
|
13050 |
|
13051 |
|
13052 |
|
13053 |
|
13054 |
|
13055 |
|
13056 | function push(parent, value) {
|
13057 | parent = util.getModularInstance(parent);
|
13058 | validateWritablePath('push', parent._path);
|
13059 | validateFirebaseDataArg('push', value, parent._path, true);
|
13060 | var now = repoServerTime(parent._repo);
|
13061 | var name = nextPushId(now);
|
13062 |
|
13063 |
|
13064 |
|
13065 |
|
13066 |
|
13067 |
|
13068 | var thennablePushRef = child(parent, name);
|
13069 | var pushRef = child(parent, name);
|
13070 | var promise;
|
13071 | if (value != null) {
|
13072 | promise = set(pushRef, value).then(function () { return pushRef; });
|
13073 | }
|
13074 | else {
|
13075 | promise = Promise.resolve(pushRef);
|
13076 | }
|
13077 | thennablePushRef.then = promise.then.bind(promise);
|
13078 | thennablePushRef.catch = promise.then.bind(promise, undefined);
|
13079 | return thennablePushRef;
|
13080 | }
|
13081 |
|
13082 |
|
13083 |
|
13084 |
|
13085 |
|
13086 |
|
13087 |
|
13088 |
|
13089 |
|
13090 |
|
13091 |
|
13092 |
|
13093 |
|
13094 |
|
13095 | function remove(ref) {
|
13096 | validateWritablePath('remove', ref._path);
|
13097 | return set(ref, null);
|
13098 | }
|
13099 | /**
|
13100 | * Writes data to this Database location.
|
13101 | *
|
13102 | * This will overwrite any data at this location and all child locations.
|
13103 | *
|
13104 | * The effect of the write will be visible immediately, and the corresponding
|
13105 | * events ("value", "child_added", etc.) will be triggered. Synchronization of
|
13106 | * the data to the Firebase servers will also be started, and the returned
|
13107 | * Promise will resolve when complete. If provided, the `onComplete` callback
|
13108 | * will be called asynchronously after synchronization has finished.
|
13109 | *
|
13110 | * Passing `null` for the new value is equivalent to calling `remove()`; namely,
|
13111 | * all data at this location and all child locations will be deleted.
|
13112 | *
|
13113 | * `set()` will remove any priority stored at this location, so if priority is
|
13114 | * meant to be preserved, you need to use `setWithPriority()` instead.
|
13115 | *
|
13116 | * Note that modifying data with `set()` will cancel any pending transactions
|
13117 | * at that location, so extreme care should be taken if mixing `set()` and
|
13118 | * `transaction()` to modify the same data.
|
13119 | *
|
13120 | * A single `set()` will generate a single "value" event at the location where
|
13121 | * the `set()` was performed.
|
13122 | *
|
13123 | * @param ref - The location to write to.
|
13124 | * @param value - The value to be written (string, number, boolean, object,
|
13125 | * array, or null).
|
13126 | * @returns Resolves when write to server is complete.
|
13127 | */
|
13128 | function set(ref, value) {
|
13129 | ref = util.getModularInstance(ref);
|
13130 | validateWritablePath('set', ref._path);
|
13131 | validateFirebaseDataArg('set', value, ref._path, false);
|
13132 | var deferred = new util.Deferred();
|
13133 | repoSetWithPriority(ref._repo, ref._path, value,
|
13134 | null, deferred.wrapCallback(function () { }));
|
13135 | return deferred.promise;
|
13136 | }
|
13137 |
|
13138 |
|
13139 |
|
13140 |
|
13141 |
|
13142 |
|
13143 |
|
13144 |
|
13145 |
|
13146 |
|
13147 |
|
13148 |
|
13149 | function setPriority(ref, priority) {
|
13150 | ref = util.getModularInstance(ref);
|
13151 | validateWritablePath('setPriority', ref._path);
|
13152 | validatePriority('setPriority', priority, false);
|
13153 | var deferred = new util.Deferred();
|
13154 | repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(function () { }));
|
13155 | return deferred.promise;
|
13156 | }
|
13157 |
|
13158 |
|
13159 |
|
13160 |
|
13161 |
|
13162 |
|
13163 |
|
13164 |
|
13165 |
|
13166 |
|
13167 |
|
13168 |
|
13169 |
|
13170 |
|
13171 |
|
13172 | function setWithPriority(ref, value, priority) {
|
13173 | validateWritablePath('setWithPriority', ref._path);
|
13174 | validateFirebaseDataArg('setWithPriority', value, ref._path, false);
|
13175 | validatePriority('setWithPriority', priority, false);
|
13176 | if (ref.key === '.length' || ref.key === '.keys') {
|
13177 | throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';
|
13178 | }
|
13179 | var deferred = new util.Deferred();
|
13180 | repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(function () { }));
|
13181 | return deferred.promise;
|
13182 | }
|
13183 |
|
13184 |
|
13185 |
|
13186 |
|
13187 |
|
13188 |
|
13189 |
|
13190 |
|
13191 |
|
13192 |
|
13193 |
|
13194 |
|
13195 |
|
13196 |
|
13197 |
|
13198 |
|
13199 |
|
13200 |
|
13201 |
|
13202 |
|
13203 |
|
13204 |
|
13205 |
|
13206 |
|
13207 |
|
13208 |
|
13209 |
|
13210 |
|
13211 |
|
13212 |
|
13213 |
|
13214 |
|
13215 |
|
13216 |
|
13217 |
|
13218 | function update(ref, values) {
|
13219 | validateFirebaseMergeDataArg('update', values, ref._path, false);
|
13220 | var deferred = new util.Deferred();
|
13221 | repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(function () { }));
|
13222 | return deferred.promise;
|
13223 | }
|
13224 |
|
13225 |
|
13226 |
|
13227 |
|
13228 |
|
13229 |
|
13230 |
|
13231 |
|
13232 | function get(query) {
|
13233 | query = util.getModularInstance(query);
|
13234 | var callbackContext = new CallbackContext(function () { });
|
13235 | var container = new ValueEventRegistration(callbackContext);
|
13236 | return repoGetValue(query._repo, query, container).then(function (node) {
|
13237 | return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
|
13238 | });
|
13239 | }
|
13240 |
|
13241 |
|
13242 |
|
13243 | var ValueEventRegistration = (function () {
|
13244 | function ValueEventRegistration(callbackContext) {
|
13245 | this.callbackContext = callbackContext;
|
13246 | }
|
13247 | ValueEventRegistration.prototype.respondsTo = function (eventType) {
|
13248 | return eventType === 'value';
|
13249 | };
|
13250 | ValueEventRegistration.prototype.createEvent = function (change, query) {
|
13251 | var index = query._queryParams.getIndex();
|
13252 | return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));
|
13253 | };
|
13254 | ValueEventRegistration.prototype.getEventRunner = function (eventData) {
|
13255 | var _this = this;
|
13256 | if (eventData.getEventType() === 'cancel') {
|
13257 | return function () {
|
13258 | return _this.callbackContext.onCancel(eventData.error);
|
13259 | };
|
13260 | }
|
13261 | else {
|
13262 | return function () {
|
13263 | return _this.callbackContext.onValue(eventData.snapshot, null);
|
13264 | };
|
13265 | }
|
13266 | };
|
13267 | ValueEventRegistration.prototype.createCancelEvent = function (error, path) {
|
13268 | if (this.callbackContext.hasCancelCallback) {
|
13269 | return new CancelEvent(this, error, path);
|
13270 | }
|
13271 | else {
|
13272 | return null;
|
13273 | }
|
13274 | };
|
13275 | ValueEventRegistration.prototype.matches = function (other) {
|
13276 | if (!(other instanceof ValueEventRegistration)) {
|
13277 | return false;
|
13278 | }
|
13279 | else if (!other.callbackContext || !this.callbackContext) {
|
13280 |
|
13281 | return true;
|
13282 | }
|
13283 | else {
|
13284 | return other.callbackContext.matches(this.callbackContext);
|
13285 | }
|
13286 | };
|
13287 | ValueEventRegistration.prototype.hasAnyCallback = function () {
|
13288 | return this.callbackContext !== null;
|
13289 | };
|
13290 | return ValueEventRegistration;
|
13291 | }());
|
13292 |
|
13293 |
|
13294 |
|
13295 | var ChildEventRegistration = (function () {
|
13296 | function ChildEventRegistration(eventType, callbackContext) {
|
13297 | this.eventType = eventType;
|
13298 | this.callbackContext = callbackContext;
|
13299 | }
|
13300 | ChildEventRegistration.prototype.respondsTo = function (eventType) {
|
13301 | var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;
|
13302 | eventToCheck =
|
13303 | eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;
|
13304 | return this.eventType === eventToCheck;
|
13305 | };
|
13306 | ChildEventRegistration.prototype.createCancelEvent = function (error, path) {
|
13307 | if (this.callbackContext.hasCancelCallback) {
|
13308 | return new CancelEvent(this, error, path);
|
13309 | }
|
13310 | else {
|
13311 | return null;
|
13312 | }
|
13313 | };
|
13314 | ChildEventRegistration.prototype.createEvent = function (change, query) {
|
13315 | util.assert(change.childName != null, 'Child events should have a childName.');
|
13316 | var childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
|
13317 | var index = query._queryParams.getIndex();
|
13318 | return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);
|
13319 | };
|
13320 | ChildEventRegistration.prototype.getEventRunner = function (eventData) {
|
13321 | var _this = this;
|
13322 | if (eventData.getEventType() === 'cancel') {
|
13323 | return function () {
|
13324 | return _this.callbackContext.onCancel(eventData.error);
|
13325 | };
|
13326 | }
|
13327 | else {
|
13328 | return function () {
|
13329 | return _this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
|
13330 | };
|
13331 | }
|
13332 | };
|
13333 | ChildEventRegistration.prototype.matches = function (other) {
|
13334 | if (other instanceof ChildEventRegistration) {
|
13335 | return (this.eventType === other.eventType &&
|
13336 | (!this.callbackContext ||
|
13337 | !other.callbackContext ||
|
13338 | this.callbackContext.matches(other.callbackContext)));
|
13339 | }
|
13340 | return false;
|
13341 | };
|
13342 | ChildEventRegistration.prototype.hasAnyCallback = function () {
|
13343 | return !!this.callbackContext;
|
13344 | };
|
13345 | return ChildEventRegistration;
|
13346 | }());
|
13347 | function addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {
|
13348 | var cancelCallback;
|
13349 | if (typeof cancelCallbackOrListenOptions === 'object') {
|
13350 | cancelCallback = undefined;
|
13351 | options = cancelCallbackOrListenOptions;
|
13352 | }
|
13353 | if (typeof cancelCallbackOrListenOptions === 'function') {
|
13354 | cancelCallback = cancelCallbackOrListenOptions;
|
13355 | }
|
13356 | if (options && options.onlyOnce) {
|
13357 | var userCallback_1 = callback;
|
13358 | var onceCallback = function (dataSnapshot, previousChildName) {
|
13359 | repoRemoveEventCallbackForQuery(query._repo, query, container);
|
13360 | userCallback_1(dataSnapshot, previousChildName);
|
13361 | };
|
13362 | onceCallback.userCallback = callback.userCallback;
|
13363 | onceCallback.context = callback.context;
|
13364 | callback = onceCallback;
|
13365 | }
|
13366 | var callbackContext = new CallbackContext(callback, cancelCallback || undefined);
|
13367 | var container = eventType === 'value'
|
13368 | ? new ValueEventRegistration(callbackContext)
|
13369 | : new ChildEventRegistration(eventType, callbackContext);
|
13370 | repoAddEventCallbackForQuery(query._repo, query, container);
|
13371 | return function () { return repoRemoveEventCallbackForQuery(query._repo, query, container); };
|
13372 | }
|
13373 | function onValue(query, callback, cancelCallbackOrListenOptions, options) {
|
13374 | return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);
|
13375 | }
|
13376 | function onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {
|
13377 | return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);
|
13378 | }
|
13379 | function onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {
|
13380 | return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);
|
13381 | }
|
13382 | function onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {
|
13383 | return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);
|
13384 | }
|
13385 | function onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {
|
13386 | return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);
|
13387 | }
|
13388 |
|
13389 |
|
13390 |
|
13391 |
|
13392 |
|
13393 |
|
13394 |
|
13395 |
|
13396 |
|
13397 |
|
13398 |
|
13399 |
|
13400 |
|
13401 |
|
13402 |
|
13403 |
|
13404 |
|
13405 |
|
13406 |
|
13407 |
|
13408 |
|
13409 |
|
13410 |
|
13411 | function off(query, eventType, callback) {
|
13412 | var container = null;
|
13413 | var expCallback = callback ? new CallbackContext(callback) : null;
|
13414 | if (eventType === 'value') {
|
13415 | container = new ValueEventRegistration(expCallback);
|
13416 | }
|
13417 | else if (eventType) {
|
13418 | container = new ChildEventRegistration(eventType, expCallback);
|
13419 | }
|
13420 | repoRemoveEventCallbackForQuery(query._repo, query, container);
|
13421 | }
|
13422 |
|
13423 |
|
13424 |
|
13425 |
|
13426 |
|
13427 |
|
13428 |
|
13429 |
|
13430 |
|
13431 |
|
13432 | var QueryConstraint = (function () {
|
13433 | function QueryConstraint() {
|
13434 | }
|
13435 | return QueryConstraint;
|
13436 | }());
|
13437 | var QueryEndAtConstraint = (function (_super) {
|
13438 | tslib.__extends(QueryEndAtConstraint, _super);
|
13439 | function QueryEndAtConstraint(_value, _key) {
|
13440 | var _this = _super.call(this) || this;
|
13441 | _this._value = _value;
|
13442 | _this._key = _key;
|
13443 | return _this;
|
13444 | }
|
13445 | QueryEndAtConstraint.prototype._apply = function (query) {
|
13446 | validateFirebaseDataArg('endAt', this._value, query._path, true);
|
13447 | var newParams = queryParamsEndAt(query._queryParams, this._value, this._key);
|
13448 | validateLimit(newParams);
|
13449 | validateQueryEndpoints(newParams);
|
13450 | if (query._queryParams.hasEnd()) {
|
13451 | throw new Error('endAt: Starting point was already set (by another call to endAt, ' +
|
13452 | 'endBefore or equalTo).');
|
13453 | }
|
13454 | return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
|
13455 | };
|
13456 | return QueryEndAtConstraint;
|
13457 | }(QueryConstraint));
|
13458 |
|
13459 |
|
13460 |
|
13461 |
|
13462 |
|
13463 |
|
13464 |
|
13465 |
|
13466 |
|
13467 |
|
13468 |
|
13469 |
|
13470 |
|
13471 |
|
13472 |
|
13473 |
|
13474 |
|
13475 |
|
13476 |
|
13477 |
|
13478 |
|
13479 |
|
13480 |
|
13481 | function endAt(value, key) {
|
13482 | validateKey('endAt', 'key', key, true);
|
13483 | return new QueryEndAtConstraint(value, key);
|
13484 | }
|
13485 | var QueryEndBeforeConstraint = (function (_super) {
|
13486 | tslib.__extends(QueryEndBeforeConstraint, _super);
|
13487 | function QueryEndBeforeConstraint(_value, _key) {
|
13488 | var _this = _super.call(this) || this;
|
13489 | _this._value = _value;
|
13490 | _this._key = _key;
|
13491 | return _this;
|
13492 | }
|
13493 | QueryEndBeforeConstraint.prototype._apply = function (query) {
|
13494 | validateFirebaseDataArg('endBefore', this._value, query._path, false);
|
13495 | var newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);
|
13496 | validateLimit(newParams);
|
13497 | validateQueryEndpoints(newParams);
|
13498 | if (query._queryParams.hasEnd()) {
|
13499 | throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +
|
13500 | 'endBefore or equalTo).');
|
13501 | }
|
13502 | return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
|
13503 | };
|
13504 | return QueryEndBeforeConstraint;
|
13505 | }(QueryConstraint));
|
13506 |
|
13507 |
|
13508 |
|
13509 |
|
13510 |
|
13511 |
|
13512 |
|
13513 |
|
13514 |
|
13515 |
|
13516 |
|
13517 |
|
13518 |
|
13519 |
|
13520 |
|
13521 |
|
13522 |
|
13523 |
|
13524 |
|
13525 | function endBefore(value, key) {
|
13526 | validateKey('endBefore', 'key', key, true);
|
13527 | return new QueryEndBeforeConstraint(value, key);
|
13528 | }
|
13529 | var QueryStartAtConstraint = (function (_super) {
|
13530 | tslib.__extends(QueryStartAtConstraint, _super);
|
13531 | function QueryStartAtConstraint(_value, _key) {
|
13532 | var _this = _super.call(this) || this;
|
13533 | _this._value = _value;
|
13534 | _this._key = _key;
|
13535 | return _this;
|
13536 | }
|
13537 | QueryStartAtConstraint.prototype._apply = function (query) {
|
13538 | validateFirebaseDataArg('startAt', this._value, query._path, true);
|
13539 | var newParams = queryParamsStartAt(query._queryParams, this._value, this._key);
|
13540 | validateLimit(newParams);
|
13541 | validateQueryEndpoints(newParams);
|
13542 | if (query._queryParams.hasStart()) {
|
13543 | throw new Error('startAt: Starting point was already set (by another call to startAt, ' +
|
13544 | 'startBefore or equalTo).');
|
13545 | }
|
13546 | return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
|
13547 | };
|
13548 | return QueryStartAtConstraint;
|
13549 | }(QueryConstraint));
|
13550 |
|
13551 |
|
13552 |
|
13553 |
|
13554 |
|
13555 |
|
13556 |
|
13557 |
|
13558 |
|
13559 |
|
13560 |
|
13561 |
|
13562 |
|
13563 |
|
13564 |
|
13565 |
|
13566 |
|
13567 |
|
13568 |
|
13569 |
|
13570 |
|
13571 |
|
13572 | function startAt(value, key) {
|
13573 | if (value === void 0) { value = null; }
|
13574 | validateKey('startAt', 'key', key, true);
|
13575 | return new QueryStartAtConstraint(value, key);
|
13576 | }
|
13577 | var QueryStartAfterConstraint = (function (_super) {
|
13578 | tslib.__extends(QueryStartAfterConstraint, _super);
|
13579 | function QueryStartAfterConstraint(_value, _key) {
|
13580 | var _this = _super.call(this) || this;
|
13581 | _this._value = _value;
|
13582 | _this._key = _key;
|
13583 | return _this;
|
13584 | }
|
13585 | QueryStartAfterConstraint.prototype._apply = function (query) {
|
13586 | validateFirebaseDataArg('startAfter', this._value, query._path, false);
|
13587 | var newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);
|
13588 | validateLimit(newParams);
|
13589 | validateQueryEndpoints(newParams);
|
13590 | if (query._queryParams.hasStart()) {
|
13591 | throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +
|
13592 | 'startAfter, or equalTo).');
|
13593 | }
|
13594 | return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);
|
13595 | };
|
13596 | return QueryStartAfterConstraint;
|
13597 | }(QueryConstraint));
|
13598 |
|
13599 |
|
13600 |
|
13601 |
|
13602 |
|
13603 |
|
13604 |
|
13605 |
|
13606 |
|
13607 |
|
13608 |
|
13609 |
|
13610 |
|
13611 |
|
13612 |
|
13613 |
|
13614 |
|
13615 |
|
13616 | function startAfter(value, key) {
|
13617 | validateKey('startAfter', 'key', key, true);
|
13618 | return new QueryStartAfterConstraint(value, key);
|
13619 | }
|
13620 | var QueryLimitToFirstConstraint = (function (_super) {
|
13621 | tslib.__extends(QueryLimitToFirstConstraint, _super);
|
13622 | function QueryLimitToFirstConstraint(_limit) {
|
13623 | var _this = _super.call(this) || this;
|
13624 | _this._limit = _limit;
|
13625 | return _this;
|
13626 | }
|
13627 | QueryLimitToFirstConstraint.prototype._apply = function (query) {
|
13628 | if (query._queryParams.hasLimit()) {
|
13629 | throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +
|
13630 | 'or limitToLast).');
|
13631 | }
|
13632 | return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);
|
13633 | };
|
13634 | return QueryLimitToFirstConstraint;
|
13635 | }(QueryConstraint));
|
13636 |
|
13637 |
|
13638 |
|
13639 |
|
13640 |
|
13641 |
|
13642 |
|
13643 |
|
13644 |
|
13645 |
|
13646 |
|
13647 |
|
13648 |
|
13649 |
|
13650 |
|
13651 |
|
13652 |
|
13653 |
|
13654 | function limitToFirst(limit) {
|
13655 | if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
|
13656 | throw new Error('limitToFirst: First argument must be a positive integer.');
|
13657 | }
|
13658 | return new QueryLimitToFirstConstraint(limit);
|
13659 | }
|
13660 | var QueryLimitToLastConstraint = (function (_super) {
|
13661 | tslib.__extends(QueryLimitToLastConstraint, _super);
|
13662 | function QueryLimitToLastConstraint(_limit) {
|
13663 | var _this = _super.call(this) || this;
|
13664 | _this._limit = _limit;
|
13665 | return _this;
|
13666 | }
|
13667 | QueryLimitToLastConstraint.prototype._apply = function (query) {
|
13668 | if (query._queryParams.hasLimit()) {
|
13669 | throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +
|
13670 | 'or limitToLast).');
|
13671 | }
|
13672 | return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);
|
13673 | };
|
13674 | return QueryLimitToLastConstraint;
|
13675 | }(QueryConstraint));
|
13676 |
|
13677 |
|
13678 |
|
13679 |
|
13680 |
|
13681 |
|
13682 |
|
13683 |
|
13684 |
|
13685 |
|
13686 |
|
13687 |
|
13688 |
|
13689 |
|
13690 |
|
13691 |
|
13692 |
|
13693 |
|
13694 | function limitToLast(limit) {
|
13695 | if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {
|
13696 | throw new Error('limitToLast: First argument must be a positive integer.');
|
13697 | }
|
13698 | return new QueryLimitToLastConstraint(limit);
|
13699 | }
|
13700 | var QueryOrderByChildConstraint = (function (_super) {
|
13701 | tslib.__extends(QueryOrderByChildConstraint, _super);
|
13702 | function QueryOrderByChildConstraint(_path) {
|
13703 | var _this = _super.call(this) || this;
|
13704 | _this._path = _path;
|
13705 | return _this;
|
13706 | }
|
13707 | QueryOrderByChildConstraint.prototype._apply = function (query) {
|
13708 | validateNoPreviousOrderByCall(query, 'orderByChild');
|
13709 | var parsedPath = new Path(this._path);
|
13710 | if (pathIsEmpty(parsedPath)) {
|
13711 | throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');
|
13712 | }
|
13713 | var index = new PathIndex(parsedPath);
|
13714 | var newParams = queryParamsOrderBy(query._queryParams, index);
|
13715 | validateQueryEndpoints(newParams);
|
13716 | return new QueryImpl(query._repo, query._path, newParams,
|
13717 | true);
|
13718 | };
|
13719 | return QueryOrderByChildConstraint;
|
13720 | }(QueryConstraint));
|
13721 |
|
13722 |
|
13723 |
|
13724 |
|
13725 |
|
13726 |
|
13727 |
|
13728 |
|
13729 |
|
13730 |
|
13731 |
|
13732 |
|
13733 |
|
13734 |
|
13735 |
|
13736 |
|
13737 |
|
13738 | function orderByChild(path) {
|
13739 | if (path === '$key') {
|
13740 | throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');
|
13741 | }
|
13742 | else if (path === '$priority') {
|
13743 | throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');
|
13744 | }
|
13745 | else if (path === '$value') {
|
13746 | throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');
|
13747 | }
|
13748 | validatePathString('orderByChild', 'path', path, false);
|
13749 | return new QueryOrderByChildConstraint(path);
|
13750 | }
|
13751 | var QueryOrderByKeyConstraint = (function (_super) {
|
13752 | tslib.__extends(QueryOrderByKeyConstraint, _super);
|
13753 | function QueryOrderByKeyConstraint() {
|
13754 | return _super !== null && _super.apply(this, arguments) || this;
|
13755 | }
|
13756 | QueryOrderByKeyConstraint.prototype._apply = function (query) {
|
13757 | validateNoPreviousOrderByCall(query, 'orderByKey');
|
13758 | var newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);
|
13759 | validateQueryEndpoints(newParams);
|
13760 | return new QueryImpl(query._repo, query._path, newParams,
|
13761 | true);
|
13762 | };
|
13763 | return QueryOrderByKeyConstraint;
|
13764 | }(QueryConstraint));
|
13765 |
|
13766 |
|
13767 |
|
13768 |
|
13769 |
|
13770 |
|
13771 |
|
13772 |
|
13773 | function orderByKey() {
|
13774 | return new QueryOrderByKeyConstraint();
|
13775 | }
|
13776 | var QueryOrderByPriorityConstraint = (function (_super) {
|
13777 | tslib.__extends(QueryOrderByPriorityConstraint, _super);
|
13778 | function QueryOrderByPriorityConstraint() {
|
13779 | return _super !== null && _super.apply(this, arguments) || this;
|
13780 | }
|
13781 | QueryOrderByPriorityConstraint.prototype._apply = function (query) {
|
13782 | validateNoPreviousOrderByCall(query, 'orderByPriority');
|
13783 | var newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);
|
13784 | validateQueryEndpoints(newParams);
|
13785 | return new QueryImpl(query._repo, query._path, newParams,
|
13786 | true);
|
13787 | };
|
13788 | return QueryOrderByPriorityConstraint;
|
13789 | }(QueryConstraint));
|
13790 |
|
13791 |
|
13792 |
|
13793 |
|
13794 |
|
13795 |
|
13796 |
|
13797 |
|
13798 | function orderByPriority() {
|
13799 | return new QueryOrderByPriorityConstraint();
|
13800 | }
|
13801 | var QueryOrderByValueConstraint = (function (_super) {
|
13802 | tslib.__extends(QueryOrderByValueConstraint, _super);
|
13803 | function QueryOrderByValueConstraint() {
|
13804 | return _super !== null && _super.apply(this, arguments) || this;
|
13805 | }
|
13806 | QueryOrderByValueConstraint.prototype._apply = function (query) {
|
13807 | validateNoPreviousOrderByCall(query, 'orderByValue');
|
13808 | var newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);
|
13809 | validateQueryEndpoints(newParams);
|
13810 | return new QueryImpl(query._repo, query._path, newParams,
|
13811 | true);
|
13812 | };
|
13813 | return QueryOrderByValueConstraint;
|
13814 | }(QueryConstraint));
|
13815 |
|
13816 |
|
13817 |
|
13818 |
|
13819 |
|
13820 |
|
13821 |
|
13822 |
|
13823 |
|
13824 | function orderByValue() {
|
13825 | return new QueryOrderByValueConstraint();
|
13826 | }
|
13827 | var QueryEqualToValueConstraint = (function (_super) {
|
13828 | tslib.__extends(QueryEqualToValueConstraint, _super);
|
13829 | function QueryEqualToValueConstraint(_value, _key) {
|
13830 | var _this = _super.call(this) || this;
|
13831 | _this._value = _value;
|
13832 | _this._key = _key;
|
13833 | return _this;
|
13834 | }
|
13835 | QueryEqualToValueConstraint.prototype._apply = function (query) {
|
13836 | validateFirebaseDataArg('equalTo', this._value, query._path, false);
|
13837 | if (query._queryParams.hasStart()) {
|
13838 | throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +
|
13839 | 'equalTo).');
|
13840 | }
|
13841 | if (query._queryParams.hasEnd()) {
|
13842 | throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +
|
13843 | 'equalTo).');
|
13844 | }
|
13845 | return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));
|
13846 | };
|
13847 | return QueryEqualToValueConstraint;
|
13848 | }(QueryConstraint));
|
13849 |
|
13850 |
|
13851 |
|
13852 |
|
13853 |
|
13854 |
|
13855 |
|
13856 |
|
13857 |
|
13858 |
|
13859 |
|
13860 |
|
13861 |
|
13862 |
|
13863 |
|
13864 |
|
13865 |
|
13866 |
|
13867 |
|
13868 |
|
13869 |
|
13870 |
|
13871 |
|
13872 | function equalTo(value, key) {
|
13873 | validateKey('equalTo', 'key', key, true);
|
13874 | return new QueryEqualToValueConstraint(value, key);
|
13875 | }
|
13876 |
|
13877 |
|
13878 |
|
13879 |
|
13880 |
|
13881 |
|
13882 |
|
13883 |
|
13884 |
|
13885 | function query(query) {
|
13886 | var e_1, _a;
|
13887 | var queryConstraints = [];
|
13888 | for (var _i = 1; _i < arguments.length; _i++) {
|
13889 | queryConstraints[_i - 1] = arguments[_i];
|
13890 | }
|
13891 | var queryImpl = util.getModularInstance(query);
|
13892 | try {
|
13893 | for (var queryConstraints_1 = tslib.__values(queryConstraints), queryConstraints_1_1 = queryConstraints_1.next(); !queryConstraints_1_1.done; queryConstraints_1_1 = queryConstraints_1.next()) {
|
13894 | var constraint = queryConstraints_1_1.value;
|
13895 | queryImpl = constraint._apply(queryImpl);
|
13896 | }
|
13897 | }
|
13898 | catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
13899 | finally {
|
13900 | try {
|
13901 | if (queryConstraints_1_1 && !queryConstraints_1_1.done && (_a = queryConstraints_1.return)) _a.call(queryConstraints_1);
|
13902 | }
|
13903 | finally { if (e_1) throw e_1.error; }
|
13904 | }
|
13905 | return queryImpl;
|
13906 | }
|
13907 |
|
13908 |
|
13909 |
|
13910 |
|
13911 |
|
13912 |
|
13913 | syncPointSetReferenceConstructor(ReferenceImpl);
|
13914 | syncTreeSetReferenceConstructor(ReferenceImpl);
|
13915 |
|
13916 |
|
13917 |
|
13918 |
|
13919 |
|
13920 |
|
13921 |
|
13922 |
|
13923 |
|
13924 | var FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';
|
13925 |
|
13926 |
|
13927 |
|
13928 | var repos = {};
|
13929 |
|
13930 |
|
13931 |
|
13932 | var useRestClient = false;
|
13933 |
|
13934 |
|
13935 |
|
13936 | function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
|
13937 | repo.repoInfo_ = new RepoInfo("".concat(host, ":").concat(port),
|
13938 | false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams,
|
13939 | true);
|
13940 | if (tokenProvider) {
|
13941 | repo.authTokenProvider_ = tokenProvider;
|
13942 | }
|
13943 | }
|
13944 |
|
13945 |
|
13946 |
|
13947 |
|
13948 | function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
|
13949 | var dbUrl = url || app.options.databaseURL;
|
13950 | if (dbUrl === undefined) {
|
13951 | if (!app.options.projectId) {
|
13952 | fatal("Can't determine Firebase Database URL. Be sure to include " +
|
13953 | ' a Project ID when calling firebase.initializeApp().');
|
13954 | }
|
13955 | log('Using default host for project ', app.options.projectId);
|
13956 | dbUrl = "".concat(app.options.projectId, "-default-rtdb.firebaseio.com");
|
13957 | }
|
13958 | var parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
|
13959 | var repoInfo = parsedUrl.repoInfo;
|
13960 | var isEmulator;
|
13961 | var dbEmulatorHost = undefined;
|
13962 | if (typeof process !== 'undefined' && process.env) {
|
13963 | dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
|
13964 | }
|
13965 | if (dbEmulatorHost) {
|
13966 | isEmulator = true;
|
13967 | dbUrl = "http://".concat(dbEmulatorHost, "?ns=").concat(repoInfo.namespace);
|
13968 | parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
|
13969 | repoInfo = parsedUrl.repoInfo;
|
13970 | }
|
13971 | else {
|
13972 | isEmulator = !parsedUrl.repoInfo.secure;
|
13973 | }
|
13974 | var authTokenProvider = nodeAdmin && isEmulator
|
13975 | ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)
|
13976 | : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
|
13977 | validateUrl('Invalid Firebase Database URL', parsedUrl);
|
13978 | if (!pathIsEmpty(parsedUrl.path)) {
|
13979 | fatal('Database URL must point to the root of a Firebase Database ' +
|
13980 | '(not including a child path).');
|
13981 | }
|
13982 | var repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
|
13983 | return new Database(repo, app);
|
13984 | }
|
13985 |
|
13986 |
|
13987 |
|
13988 |
|
13989 | function repoManagerDeleteRepo(repo, appName) {
|
13990 | var appRepos = repos[appName];
|
13991 |
|
13992 | if (!appRepos || appRepos[repo.key] !== repo) {
|
13993 | fatal("Database ".concat(appName, "(").concat(repo.repoInfo_, ") has already been deleted."));
|
13994 | }
|
13995 | repoInterrupt(repo);
|
13996 | delete appRepos[repo.key];
|
13997 | }
|
13998 |
|
13999 |
|
14000 |
|
14001 |
|
14002 |
|
14003 |
|
14004 |
|
14005 | function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
|
14006 | var appRepos = repos[app.name];
|
14007 | if (!appRepos) {
|
14008 | appRepos = {};
|
14009 | repos[app.name] = appRepos;
|
14010 | }
|
14011 | var repo = appRepos[repoInfo.toURLString()];
|
14012 | if (repo) {
|
14013 | fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');
|
14014 | }
|
14015 | repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
|
14016 | appRepos[repoInfo.toURLString()] = repo;
|
14017 | return repo;
|
14018 | }
|
14019 |
|
14020 |
|
14021 |
|
14022 | function repoManagerForceRestClient(forceRestClient) {
|
14023 | useRestClient = forceRestClient;
|
14024 | }
|
14025 |
|
14026 |
|
14027 |
|
14028 | var Database = (function () {
|
14029 |
|
14030 | function Database(_repoInternal,
|
14031 | /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
|
14032 | app) {
|
14033 | this._repoInternal = _repoInternal;
|
14034 | this.app = app;
|
14035 |
|
14036 | this['type'] = 'database';
|
14037 |
|
14038 | this._instanceStarted = false;
|
14039 | }
|
14040 | Object.defineProperty(Database.prototype, "_repo", {
|
14041 | get: function () {
|
14042 | if (!this._instanceStarted) {
|
14043 | repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);
|
14044 | this._instanceStarted = true;
|
14045 | }
|
14046 | return this._repoInternal;
|
14047 | },
|
14048 | enumerable: false,
|
14049 | configurable: true
|
14050 | });
|
14051 | Object.defineProperty(Database.prototype, "_root", {
|
14052 | get: function () {
|
14053 | if (!this._rootInternal) {
|
14054 | this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
|
14055 | }
|
14056 | return this._rootInternal;
|
14057 | },
|
14058 | enumerable: false,
|
14059 | configurable: true
|
14060 | });
|
14061 | Database.prototype._delete = function () {
|
14062 | if (this._rootInternal !== null) {
|
14063 | repoManagerDeleteRepo(this._repo, this.app.name);
|
14064 | this._repoInternal = null;
|
14065 | this._rootInternal = null;
|
14066 | }
|
14067 | return Promise.resolve();
|
14068 | };
|
14069 | Database.prototype._checkNotDeleted = function (apiName) {
|
14070 | if (this._rootInternal === null) {
|
14071 | fatal('Cannot call ' + apiName + ' on a deleted database.');
|
14072 | }
|
14073 | };
|
14074 | return Database;
|
14075 | }());
|
14076 | function checkTransportInit() {
|
14077 | if (TransportManager.IS_TRANSPORT_INITIALIZED) {
|
14078 | warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');
|
14079 | }
|
14080 | }
|
14081 |
|
14082 |
|
14083 |
|
14084 | function forceWebSockets() {
|
14085 | checkTransportInit();
|
14086 | BrowserPollConnection.forceDisallow();
|
14087 | }
|
14088 |
|
14089 |
|
14090 |
|
14091 | function forceLongPolling() {
|
14092 | checkTransportInit();
|
14093 | WebSocketConnection.forceDisallow();
|
14094 | BrowserPollConnection.forceAllow();
|
14095 | }
|
14096 |
|
14097 |
|
14098 |
|
14099 |
|
14100 |
|
14101 |
|
14102 |
|
14103 |
|
14104 |
|
14105 |
|
14106 |
|
14107 |
|
14108 | function getDatabase(app$1, url) {
|
14109 | if (app$1 === void 0) { app$1 = app.getApp(); }
|
14110 | var db = app._getProvider(app$1, 'database').getImmediate({
|
14111 | identifier: url
|
14112 | });
|
14113 | if (!db._instanceStarted) {
|
14114 | var emulator = util.getDefaultEmulatorHostnameAndPort('database');
|
14115 | if (emulator) {
|
14116 | connectDatabaseEmulator.apply(void 0, tslib.__spreadArray([db], tslib.__read(emulator), false));
|
14117 | }
|
14118 | }
|
14119 | return db;
|
14120 | }
|
14121 |
|
14122 |
|
14123 |
|
14124 |
|
14125 |
|
14126 |
|
14127 |
|
14128 |
|
14129 |
|
14130 |
|
14131 |
|
14132 | function connectDatabaseEmulator(db, host, port, options) {
|
14133 | if (options === void 0) { options = {}; }
|
14134 | db = util.getModularInstance(db);
|
14135 | db._checkNotDeleted('useEmulator');
|
14136 | if (db._instanceStarted) {
|
14137 | fatal('Cannot call useEmulator() after instance has already been initialized.');
|
14138 | }
|
14139 | var repo = db._repoInternal;
|
14140 | var tokenProvider = undefined;
|
14141 | if (repo.repoInfo_.nodeAdmin) {
|
14142 | if (options.mockUserToken) {
|
14143 | fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
|
14144 | }
|
14145 | tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
|
14146 | }
|
14147 | else if (options.mockUserToken) {
|
14148 | var token = typeof options.mockUserToken === 'string'
|
14149 | ? options.mockUserToken
|
14150 | : util.createMockUserToken(options.mockUserToken, db.app.options.projectId);
|
14151 | tokenProvider = new EmulatorTokenProvider(token);
|
14152 | }
|
14153 |
|
14154 | repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
|
14155 | }
|
14156 |
|
14157 |
|
14158 |
|
14159 |
|
14160 |
|
14161 |
|
14162 |
|
14163 |
|
14164 |
|
14165 |
|
14166 |
|
14167 |
|
14168 |
|
14169 |
|
14170 |
|
14171 |
|
14172 |
|
14173 |
|
14174 |
|
14175 |
|
14176 |
|
14177 | function goOffline(db) {
|
14178 | db = util.getModularInstance(db);
|
14179 | db._checkNotDeleted('goOffline');
|
14180 | repoInterrupt(db._repo);
|
14181 | }
|
14182 |
|
14183 |
|
14184 |
|
14185 |
|
14186 |
|
14187 |
|
14188 |
|
14189 |
|
14190 |
|
14191 |
|
14192 |
|
14193 | function goOnline(db) {
|
14194 | db = util.getModularInstance(db);
|
14195 | db._checkNotDeleted('goOnline');
|
14196 | repoResume(db._repo);
|
14197 | }
|
14198 | function enableLogging(logger, persistent) {
|
14199 | enableLogging$1(logger, persistent);
|
14200 | }
|
14201 |
|
14202 |
|
14203 |
|
14204 |
|
14205 |
|
14206 |
|
14207 |
|
14208 |
|
14209 |
|
14210 |
|
14211 |
|
14212 |
|
14213 |
|
14214 |
|
14215 |
|
14216 |
|
14217 |
|
14218 | function registerDatabase(variant) {
|
14219 | setSDKVersion(app.SDK_VERSION);
|
14220 | app._registerComponent(new component.Component('database', function (container, _a) {
|
14221 | var url = _a.instanceIdentifier;
|
14222 | var app = container.getProvider('app').getImmediate();
|
14223 | var authProvider = container.getProvider('auth-internal');
|
14224 | var appCheckProvider = container.getProvider('app-check-internal');
|
14225 | return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
|
14226 | }, "PUBLIC" ).setMultipleInstances(true));
|
14227 | app.registerVersion(name, version, variant);
|
14228 |
|
14229 | app.registerVersion(name, version, 'cjs5');
|
14230 | }
|
14231 |
|
14232 |
|
14233 |
|
14234 |
|
14235 |
|
14236 |
|
14237 |
|
14238 |
|
14239 |
|
14240 |
|
14241 |
|
14242 |
|
14243 |
|
14244 |
|
14245 |
|
14246 |
|
14247 |
|
14248 | var SERVER_TIMESTAMP = {
|
14249 | '.sv': 'timestamp'
|
14250 | };
|
14251 |
|
14252 |
|
14253 |
|
14254 |
|
14255 |
|
14256 | function serverTimestamp() {
|
14257 | return SERVER_TIMESTAMP;
|
14258 | }
|
14259 |
|
14260 |
|
14261 |
|
14262 |
|
14263 |
|
14264 |
|
14265 |
|
14266 | function increment(delta) {
|
14267 | return {
|
14268 | '.sv': {
|
14269 | 'increment': delta
|
14270 | }
|
14271 | };
|
14272 | }
|
14273 |
|
14274 |
|
14275 |
|
14276 |
|
14277 |
|
14278 |
|
14279 |
|
14280 |
|
14281 |
|
14282 |
|
14283 |
|
14284 |
|
14285 |
|
14286 |
|
14287 |
|
14288 |
|
14289 |
|
14290 |
|
14291 |
|
14292 |
|
14293 | var TransactionResult = (function () {
|
14294 |
|
14295 | function TransactionResult(
|
14296 | /** Whether the transaction was successfully committed. */
|
14297 | committed,
|
14298 | /** The resulting data snapshot. */
|
14299 | snapshot) {
|
14300 | this.committed = committed;
|
14301 | this.snapshot = snapshot;
|
14302 | }
|
14303 |
|
14304 | TransactionResult.prototype.toJSON = function () {
|
14305 | return { committed: this.committed, snapshot: this.snapshot.toJSON() };
|
14306 | };
|
14307 | return TransactionResult;
|
14308 | }());
|
14309 |
|
14310 |
|
14311 |
|
14312 |
|
14313 |
|
14314 |
|
14315 |
|
14316 |
|
14317 |
|
14318 |
|
14319 |
|
14320 |
|
14321 |
|
14322 |
|
14323 |
|
14324 |
|
14325 |
|
14326 |
|
14327 |
|
14328 |
|
14329 |
|
14330 |
|
14331 |
|
14332 |
|
14333 |
|
14334 |
|
14335 |
|
14336 |
|
14337 |
|
14338 |
|
14339 |
|
14340 |
|
14341 |
|
14342 |
|
14343 |
|
14344 |
|
14345 |
|
14346 | function runTransaction(ref,
|
14347 | // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
14348 | transactionUpdate, options) {
|
14349 | var _a;
|
14350 | ref = util.getModularInstance(ref);
|
14351 | validateWritablePath('Reference.transaction', ref._path);
|
14352 | if (ref.key === '.length' || ref.key === '.keys') {
|
14353 | throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');
|
14354 | }
|
14355 | var applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;
|
14356 | var deferred = new util.Deferred();
|
14357 | var promiseComplete = function (error, committed, node) {
|
14358 | var dataSnapshot = null;
|
14359 | if (error) {
|
14360 | deferred.reject(error);
|
14361 | }
|
14362 | else {
|
14363 | dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);
|
14364 | deferred.resolve(new TransactionResult(committed, dataSnapshot));
|
14365 | }
|
14366 | };
|
14367 |
|
14368 | var unwatcher = onValue(ref, function () { });
|
14369 | repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);
|
14370 | return deferred.promise;
|
14371 | }
|
14372 |
|
14373 |
|
14374 |
|
14375 |
|
14376 |
|
14377 |
|
14378 |
|
14379 |
|
14380 |
|
14381 |
|
14382 |
|
14383 |
|
14384 |
|
14385 |
|
14386 |
|
14387 |
|
14388 |
|
14389 |
|
14390 | PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {
|
14391 | this.sendRequest('q', { p: pathString }, onComplete);
|
14392 | };
|
14393 |
|
14394 | PersistentConnection.prototype.echo = function (data, onEcho) {
|
14395 | this.sendRequest('echo', { d: data }, onEcho);
|
14396 | };
|
14397 |
|
14398 |
|
14399 |
|
14400 | var hijackHash = function (newHash) {
|
14401 | var oldPut = PersistentConnection.prototype.put;
|
14402 | PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {
|
14403 | if (hash !== undefined) {
|
14404 | hash = newHash();
|
14405 | }
|
14406 | oldPut.call(this, pathString, data, onComplete, hash);
|
14407 | };
|
14408 | return function () {
|
14409 | PersistentConnection.prototype.put = oldPut;
|
14410 | };
|
14411 | };
|
14412 |
|
14413 |
|
14414 |
|
14415 |
|
14416 | var forceRestClient = function (forceRestClient) {
|
14417 | repoManagerForceRestClient(forceRestClient);
|
14418 | };
|
14419 |
|
14420 |
|
14421 |
|
14422 |
|
14423 |
|
14424 |
|
14425 |
|
14426 |
|
14427 |
|
14428 |
|
14429 |
|
14430 |
|
14431 |
|
14432 |
|
14433 |
|
14434 |
|
14435 |
|
14436 | setWebSocketImpl(Websocket__default["default"].Client);
|
14437 | registerDatabase('node');
|
14438 |
|
14439 | exports.DataSnapshot = DataSnapshot;
|
14440 | exports.Database = Database;
|
14441 | exports.OnDisconnect = OnDisconnect;
|
14442 | exports.QueryConstraint = QueryConstraint;
|
14443 | exports.TransactionResult = TransactionResult;
|
14444 | exports._QueryImpl = QueryImpl;
|
14445 | exports._QueryParams = QueryParams;
|
14446 | exports._ReferenceImpl = ReferenceImpl;
|
14447 | exports._TEST_ACCESS_forceRestClient = forceRestClient;
|
14448 | exports._TEST_ACCESS_hijackHash = hijackHash;
|
14449 | exports._repoManagerDatabaseFromApp = repoManagerDatabaseFromApp;
|
14450 | exports._setSDKVersion = setSDKVersion;
|
14451 | exports._validatePathString = validatePathString;
|
14452 | exports._validateWritablePath = validateWritablePath;
|
14453 | exports.child = child;
|
14454 | exports.connectDatabaseEmulator = connectDatabaseEmulator;
|
14455 | exports.enableLogging = enableLogging;
|
14456 | exports.endAt = endAt;
|
14457 | exports.endBefore = endBefore;
|
14458 | exports.equalTo = equalTo;
|
14459 | exports.forceLongPolling = forceLongPolling;
|
14460 | exports.forceWebSockets = forceWebSockets;
|
14461 | exports.get = get;
|
14462 | exports.getDatabase = getDatabase;
|
14463 | exports.goOffline = goOffline;
|
14464 | exports.goOnline = goOnline;
|
14465 | exports.increment = increment;
|
14466 | exports.limitToFirst = limitToFirst;
|
14467 | exports.limitToLast = limitToLast;
|
14468 | exports.off = off;
|
14469 | exports.onChildAdded = onChildAdded;
|
14470 | exports.onChildChanged = onChildChanged;
|
14471 | exports.onChildMoved = onChildMoved;
|
14472 | exports.onChildRemoved = onChildRemoved;
|
14473 | exports.onDisconnect = onDisconnect;
|
14474 | exports.onValue = onValue;
|
14475 | exports.orderByChild = orderByChild;
|
14476 | exports.orderByKey = orderByKey;
|
14477 | exports.orderByPriority = orderByPriority;
|
14478 | exports.orderByValue = orderByValue;
|
14479 | exports.push = push;
|
14480 | exports.query = query;
|
14481 | exports.ref = ref;
|
14482 | exports.refFromURL = refFromURL;
|
14483 | exports.remove = remove;
|
14484 | exports.runTransaction = runTransaction;
|
14485 | exports.serverTimestamp = serverTimestamp;
|
14486 | exports.set = set;
|
14487 | exports.setPriority = setPriority;
|
14488 | exports.setWithPriority = setWithPriority;
|
14489 | exports.startAfter = startAfter;
|
14490 | exports.startAt = startAt;
|
14491 | exports.update = update;
|
14492 | //# sourceMappingURL=index.node.cjs.js.map
|