| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690 |
16x
16x
16x
16x
16x
16x
16x
16x
16x
16x
16x
83x
16x
413x
413x
413x
413x
413x
16x
12x
12x
12x
12x
12x
12x
12x
16x
16x
16x
12449x
5155x
9x
9x
5155x
16x
6169x
4505x
16x
16x
6x
6x
16x
6x
6x
6x
6x
16x
4x
16x
16x
2629x
16x
5x
5x
16x
16x
16x
18027x
7897x
10130x
1167x
8963x
509x
8454x
8454x
8454x
358x
346x
12x
8096x
13x
8083x
16x
26511x
10136x
16375x
3879x
12496x
16x
2892x
2892x
16x
6704x
2714x
2714x
3990x
2714x
2714x
2714x
3990x
3990x
3990x
3990x
2714x
2714x
16x
1046x
1046x
1046x
16x
21x
5x
10x
16x
16x
16x
291x
291x
291x
291x
291x
10x
10x
10x
281x
281x
281x
281x
281x
281x
291x
291x
15132x
15132x
291x
3201x
3201x
291x
291x
291x
291x
291x
2328x
2328x
2328x
291x
16x
5x
16x
5x
16x
16x
16x
16908x
717x
717x
717x
16191x
16x
1135x
1135x
16x
16x
31x
31x
16x
16x
55x
55x
55x
| /**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Query } from '../../api/Query';
declare const window: any;
declare const Windows: any;
import { assert } from '@firebase/util';
import { forEach } from '@firebase/util';
import { base64 } from '@firebase/util';
import { Sha1 } from '@firebase/util';
import { stringToByteArray } from '@firebase/util';
import { stringify } from '@firebase/util';
import { SessionStorage } from '../storage/storage';
import { isNodeSdk } from '@firebase/util';
/**
* Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).
* @type {function(): number} Generated ID.
*/
export const LUIDGenerator: (() => number) = (function() {
let id = 1;
return function() {
return id++;
};
})();
/**
* Sha1 hash of the input string
* @param {!string} str The string to hash
* @return {!string} The resulting hash
*/
export const sha1 = function(str: string): string {
const utf8Bytes = stringToByteArray(str);
const sha1 = new Sha1();
sha1.update(utf8Bytes);
const sha1Bytes = sha1.digest();
return base64.encodeByteArray(sha1Bytes);
};
/**
* @param {...*} var_args
* @return {string}
* @private
*/
const buildLogMessage_ = function(...var_args: any[]): string {
let message = '';
for (let i = 0; i < var_args.length; i++) {
Iif (
Array.isArray(var_args[i]) ||
(var_args[i] &&
typeof var_args[i] === 'object' &&
typeof var_args[i].length === 'number')
) {
message += buildLogMessage_.apply(null, var_args[i]);
} else Iif (typeof var_args[i] === 'object') {
message += stringify(var_args[i]);
} else {
message += var_args[i];
}
message += ' ';
}
return message;
};
/**
* Use this for all debug messages in Firebase.
* @type {?function(string)}
*/
export let logger: ((a: string) => void) | null = null;
/**
* Flag to check for log availability on first log message
* @type {boolean}
* @private
*/
let firstLog_ = true;
/**
* The implementation of Firebase.enableLogging (defined here to break dependencies)
* @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger
* @param {boolean=} persistent Whether or not to persist logging settings across refreshes
*/
export const enableLogging = function(
logger_?: boolean | ((a: string) => void) | null,
persistent?: boolean
) {
assert(
!persistent || (logger_ === true || logger_ === false),
"Can't turn on custom loggers persistently."
);
if (logger_ === true) {
if (typeof console !== 'undefined') {
if (typeof console.log === 'function') {
logger = console.log.bind(console);
} else if (typeof console.log === 'object') {
// IE does this.
logger = function(message) {
console.log(message);
};
}
}
if (persistent) SessionStorage.set('logging_enabled', true);
} else if (typeof logger_ === 'function') {
logger = logger_;
} else {
logger = null;
SessionStorage.remove('logging_enabled');
}
};
/**
*
* @param {...(string|Arguments)} var_args
*/
export const log = function(...var_args: string[]) {
if (firstLog_ === true) {
firstLog_ = false;
Iif (logger === null && SessionStorage.get('logging_enabled') === true)
enableLogging(true);
}
Iif (logger) {
const message = buildLogMessage_.apply(null, var_args);
logger(message);
}
};
/**
* @param {!string} prefix
* @return {function(...[*])}
*/
export const logWrapper = function(
prefix: string
): (...var_args: any[]) => void {
return function(...var_args: any[]) {
log(prefix, ...var_args);
};
};
/**
* @param {...string} var_args
*/
export const error = function(...var_args: string[]) {
if (typeof console !== 'undefined') {
const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...var_args);
if (typeof console.error !== 'undefined') {
console.error(message);
} else {
console.log(message);
}
}
};
/**
* @param {...string} var_args
*/
export const fatal = function(...var_args: string[]) {
const message = buildLogMessage_(...var_args);
throw new Error('FIREBASE FATAL ERROR: ' + message);
};
/**
* @param {...*} var_args
*/
export const warn = function(...var_args: any[]) {
Eif (typeof console !== 'undefined') {
const message = 'FIREBASE WARNING: ' + buildLogMessage_(...var_args);
Eif (typeof console.warn !== 'undefined') {
console.warn(message);
} else {
console.log(message);
}
}
};
/**
* Logs a warning if the containing page uses https. Called when a call to new Firebase
* does not use https.
*/
export const warnIfPageIsSecure = function() {
// Be very careful accessing browser globals. Who knows what may or may not exist.
Iif (
typeof window !== 'undefined' &&
window.location &&
window.location.protocol &&
window.location.protocol.indexOf('https:') !== -1
) {
warn(
'Insecure Firebase access from a secure page. ' +
'Please use https in calls to new Firebase().'
);
}
};
/**
* @param {!String} methodName
*/
export const warnAboutUnsupportedMethod = function(methodName: string) {
warn(
methodName +
' is unsupported and will likely change soon. ' +
'Please do not use.'
);
};
/**
* Returns true if data is NaN, or +/- Infinity.
* @param {*} data
* @return {boolean}
*/
export const isInvalidJSONNumber = function(data: any): boolean {
return (
typeof data === 'number' &&
(data != data || // NaN
data == Number.POSITIVE_INFINITY ||
data == Number.NEGATIVE_INFINITY)
);
};
/**
* @param {function()} fn
*/
export const executeWhenDOMReady = function(fn: () => void) {
Eif (isNodeSdk() || document.readyState === 'complete') {
fn();
} else {
// Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which
// fire before onload), but fall back to onload.
let called = false;
let wrappedFn = function() {
if (!document.body) {
setTimeout(wrappedFn, Math.floor(10));
return;
}
if (!called) {
called = true;
fn();
}
};
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', wrappedFn, false);
// fallback to onload.
window.addEventListener('load', wrappedFn, false);
} else if ((document as any).attachEvent) {
// IE.
(document as any).attachEvent('onreadystatechange', function() {
if (document.readyState === 'complete') wrappedFn();
});
// fallback to onload.
(window as any).attachEvent('onload', wrappedFn);
// jQuery has an extra hack for IE that we could employ (based on
// http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.
// I'm hoping we don't need it.
}
}
};
/**
* Minimum key name. Invalid for actual data, used as a marker to sort before any valid names
* @type {!string}
*/
export const MIN_NAME = '[MIN_NAME]';
/**
* Maximum key name. Invalid for actual data, used as a marker to sort above any valid names
* @type {!string}
*/
export const MAX_NAME = '[MAX_NAME]';
/**
* Compares valid Firebase key names, plus min and max name
* @param {!string} a
* @param {!string} b
* @return {!number}
*/
export const nameCompare = function(a: string, b: string): number {
if (a === b) {
return 0;
} else if (a === MIN_NAME || b === MAX_NAME) {
return -1;
} else if (b === MIN_NAME || a === MAX_NAME) {
return 1;
} else {
const aAsInt = tryParseInt(a),
bAsInt = tryParseInt(b);
if (aAsInt !== null) {
if (bAsInt !== null) {
return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;
} else {
return -1;
}
} else if (bAsInt !== null) {
return 1;
} else {
return a < b ? -1 : 1;
}
}
};
/**
* @param {!string} a
* @param {!string} b
* @return {!number} comparison result.
*/
export const stringCompare = function(a: string, b: string): number {
if (a === b) {
return 0;
} else if (a < b) {
return -1;
} else {
return 1;
}
};
/**
* @param {string} key
* @param {Object} obj
* @return {*}
*/
export const requireKey = function(
key: string,
obj: { [k: string]: any }
): any {
Eif (obj && key in obj) {
return obj[key];
} else {
throw new Error(
'Missing required key (' + key + ') in object: ' + stringify(obj)
);
}
};
/**
* @param {*} obj
* @return {string}
*/
export const ObjectToUniqueKey = function(obj: any): string {
if (typeof obj !== 'object' || obj === null) return stringify(obj);
const keys = [];
for (let k in obj) {
keys.push(k);
}
// Export as json, but with the keys sorted.
keys.sort();
let key = '{';
for (let i = 0; i < keys.length; i++) {
if (i !== 0) key += ',';
key += stringify(keys[i]);
key += ':';
key += ObjectToUniqueKey(obj[keys[i]]);
}
key += '}';
return key;
};
/**
* Splits a string into a number of smaller segments of maximum size
* @param {!string} str The string
* @param {!number} segsize The maximum number of chars in the string.
* @return {Array.<string>} The string, split into appropriately-sized chunks
*/
export const splitStringBySize = function(
str: string,
segsize: number
): string[] {
const len = str.length;
Eif (len <= segsize) {
return [str];
}
const dataSegs = [];
for (let c = 0; c < len; c += segsize) {
if (c + segsize > len) {
dataSegs.push(str.substring(c, len));
} else {
dataSegs.push(str.substring(c, c + segsize));
}
}
return dataSegs;
};
/**
* Apply a function to each (key, value) pair in an object or
* apply a function to each (index, value) pair in an array
* @param {!(Object|Array)} obj The object or array to iterate over
* @param {function(?, ?)} fn The function to apply
*/
export const each = function(
obj: Object | Array<any>,
fn: (v?: any, k?: any) => void
) {
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; ++i) {
fn(i, obj[i]);
}
} else {
/**
* in the conversion of code we removed the goog.object.forEach
* function which did a value,key callback. We standardized on
* a single impl that does a key, value callback. So we invert
* to not have to touch the `each` code points
*/
forEach(obj, (key: any, val: any) => fn(val, key));
}
};
/**
* Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.
* @param {function(*)} callback Callback function.
* @param {?Object=} context Optional context to bind to.
* @return {function(*)}
*/
export const bindCallback = function(
callback: (a: any) => void,
context?: object | null
): Function {
return context ? callback.bind(context) : callback;
};
/**
* Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)
* I made one modification at the end and removed the NaN / Infinity
* handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.
* @param {!number} v A double
* @return {string}
*/
export const doubleToIEEE754String = function(v: number): string {
assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL
const ebits = 11,
fbits = 52;
let bias = (1 << (ebits - 1)) - 1,
s,
e,
f,
ln,
i,
bits,
str;
// Compute sign, exponent, fraction
// Skip NaN / Infinity handling --MJL.
if (v === 0) {
e = 0;
f = 0;
s = 1 / v === -Infinity ? 1 : 0;
} else {
s = v < 0;
v = Math.abs(v);
Eif (v >= Math.pow(2, 1 - bias)) {
// Normalized
ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
e = ln + bias;
f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
} else {
// Denormalized
e = 0;
f = Math.round(v / Math.pow(2, 1 - bias - fbits));
}
}
// Pack sign, exponent, fraction
bits = [];
for (i = fbits; i; i -= 1) {
bits.push(f % 2 ? 1 : 0);
f = Math.floor(f / 2);
}
for (i = ebits; i; i -= 1) {
bits.push(e % 2 ? 1 : 0);
e = Math.floor(e / 2);
}
bits.push(s ? 1 : 0);
bits.reverse();
str = bits.join('');
// Return the data as a hex string. --MJL
let hexByteString = '';
for (i = 0; i < 64; i += 8) {
let hexByte = parseInt(str.substr(i, 8), 2).toString(16);
if (hexByte.length === 1) hexByte = '0' + hexByte;
hexByteString = hexByteString + hexByte;
}
return hexByteString.toLowerCase();
};
/**
* Used to detect if we're in a Chrome content script (which executes in an
* isolated environment where long-polling doesn't work).
* @return {boolean}
*/
export const isChromeExtensionContentScript = function(): boolean {
return !!(
typeof window === 'object' &&
window['chrome'] &&
window['chrome']['extension'] &&
!/^chrome/.test(window.location.href)
);
};
/**
* Used to detect if we're in a Windows 8 Store app.
* @return {boolean}
*/
export const isWindowsStoreApp = function(): boolean {
// Check for the presence of a couple WinRT globals
return typeof Windows === 'object' && typeof Windows.UI === 'object';
};
/**
* Converts a server error code to a Javascript Error
* @param {!string} code
* @param {!Query} query
* @return {Error}
*/
export const errorForServerCode = function(code: string, query: Query): Error {
let reason = 'Unknown Error';
if (code === 'too_big') {
reason =
'The data requested exceeds the maximum size ' +
'that can be accessed with a single request.';
} else if (code == 'permission_denied') {
reason = "Client doesn't have permission to access the desired data.";
} else if (code == 'unavailable') {
reason = 'The service is unavailable';
}
const error = new Error(
code + ' at ' + query.path.toString() + ': ' + reason
);
(error as any).code = code.toUpperCase();
return error;
};
/**
* Used to test for integer-looking strings
* @type {RegExp}
* @private
*/
export const INTEGER_REGEXP_ = new RegExp('^-?\\d{1,10}$');
/**
* If the string contains a 32-bit integer, return it. Else return null.
* @param {!string} str
* @return {?number}
*/
export const tryParseInt = function(str: string): number | null {
if (INTEGER_REGEXP_.test(str)) {
const intVal = Number(str);
Eif (intVal >= -2147483648 && intVal <= 2147483647) {
return intVal;
}
}
return null;
};
/**
* Helper to run some code but catch any exceptions and re-throw them later.
* Useful for preventing user callbacks from breaking internal code.
*
* Re-throwing the exception from a setTimeout is a little evil, but it's very
* convenient (we don't have to try to figure out when is a safe point to
* re-throw it), and the behavior seems reasonable:
*
* * If you aren't pausing on exceptions, you get an error in the console with
* the correct stack trace.
* * If you're pausing on all exceptions, the debugger will pause on your
* exception and then again when we rethrow it.
* * If you're only pausing on uncaught exceptions, the debugger will only pause
* on us re-throwing it.
*
* @param {!function()} fn The code to guard.
*/
export const exceptionGuard = function(fn: () => void) {
try {
fn();
} catch (e) {
// Re-throw exception when it's safe.
setTimeout(function() {
// It used to be that "throw e" would result in a good console error with
// relevant context, but as of Chrome 39, you just get the firebase.js
// file/line number where we re-throw it, which is useless. So we log
// e.stack explicitly.
const stack = e.stack || '';
warn('Exception was thrown by user callback.', stack);
throw e;
}, Math.floor(0));
}
};
/**
* Helper function to safely call opt_callback with the specified arguments. It:
* 1. Turns into a no-op if opt_callback is null or undefined.
* 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.
*
* @param {?Function=} callback Optional onComplete callback.
* @param {...*} var_args Arbitrary args to be passed to opt_onComplete
*/
export const callUserCallback = function(
callback?: Function | null,
...var_args: any[]
) {
if (typeof callback === 'function') {
exceptionGuard(function() {
callback(...var_args);
});
}
};
/**
* @return {boolean} true if we think we're currently being crawled.
*/
export const beingCrawled = function(): boolean {
const userAgent =
(typeof window === 'object' &&
window['navigator'] &&
window['navigator']['userAgent']) ||
'';
// For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we
// believe to support JavaScript/AJAX rendering.
// NOTE: Google Webmaster Tools doesn't really belong, but their "This is how a visitor to your website
// would have seen the page" is flaky if we don't treat it as a crawler.
return (
userAgent.search(
/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i
) >= 0
);
};
/**
* Export a property of an object using a getter function.
*
* @param {!Object} object
* @param {string} name
* @param {!function(): *} fnGet
*/
export const exportPropGetter = function(
object: Object,
name: string,
fnGet: () => any
) {
Object.defineProperty(object, name, { get: fnGet });
};
/**
* Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.
*
* It is removed with clearTimeout() as normal.
*
* @param {Function} fn Function to run.
* @param {number} time Milliseconds to wait before running.
* @return {number|Object} The setTimeout() return value.
*/
export const setTimeoutNonBlocking = function(
fn: Function,
time: number
): number | Object {
const timeout: number | Object = setTimeout(fn, time);
Iif (typeof timeout === 'object' && (timeout as any)['unref']) {
(timeout as any)['unref']();
}
return timeout;
};
|