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