@firebase/util 1.9.0 → 1.9.1-20230201003102

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