UNPKG

438 kBJavaScriptView Raw
1import { __awaiter, __generator, __spreadArray, __assign, __rest, __extends } from 'tslib';
2import { ErrorFactory, deepEqual, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, isIE, getUA, createSubscribe, querystringDecode, extractQuerystring, isEmpty } from '@firebase/util';
3import { SDK_VERSION, _getProvider, _registerComponent, registerVersion } from '@firebase/app';
4import { Component } from '@firebase/component';
5import { Logger, LogLevel } from '@firebase/logger';
6
7var STORAGE_AVAILABLE_KEY = '__sak';
8
9/**
10 * @license
11 * Copyright 2019 Google LLC
12 *
13 * Licensed under the Apache License, Version 2.0 (the "License");
14 * you may not use this file except in compliance with the License.
15 * You may obtain a copy of the License at
16 *
17 * http://www.apache.org/licenses/LICENSE-2.0
18 *
19 * Unless required by applicable law or agreed to in writing, software
20 * distributed under the License is distributed on an "AS IS" BASIS,
21 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 * See the License for the specific language governing permissions and
23 * limitations under the License.
24 */
25/**
26 * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.
27 *
28 * @param promises - Array of promises to wait on.
29 */
30function _allSettled(promises) {
31 var _this = this;
32 return Promise.all(promises.map(function (promise) { return __awaiter(_this, void 0, void 0, function () {
33 var value, reason_1;
34 return __generator(this, function (_a) {
35 switch (_a.label) {
36 case 0:
37 _a.trys.push([0, 2, , 3]);
38 return [4 /*yield*/, promise];
39 case 1:
40 value = _a.sent();
41 return [2 /*return*/, {
42 fulfilled: true,
43 value: value
44 }];
45 case 2:
46 reason_1 = _a.sent();
47 return [2 /*return*/, {
48 fulfilled: false,
49 reason: reason_1
50 }];
51 case 3: return [2 /*return*/];
52 }
53 });
54 }); }));
55}
56
57/**
58 * @license
59 * Copyright 2019 Google LLC
60 *
61 * Licensed under the Apache License, Version 2.0 (the "License");
62 * you may not use this file except in compliance with the License.
63 * You may obtain a copy of the License at
64 *
65 * http://www.apache.org/licenses/LICENSE-2.0
66 *
67 * Unless required by applicable law or agreed to in writing, software
68 * distributed under the License is distributed on an "AS IS" BASIS,
69 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
70 * See the License for the specific language governing permissions and
71 * limitations under the License.
72 */
73/**
74 * Interface class for receiving messages.
75 *
76 */
77var Receiver = /** @class */ (function () {
78 function Receiver(eventTarget) {
79 this.eventTarget = eventTarget;
80 this.handlersMap = {};
81 this.boundEventHandler = this.handleEvent.bind(this);
82 }
83 /**
84 * Obtain an instance of a Receiver for a given event target, if none exists it will be created.
85 *
86 * @param eventTarget - An event target (such as window or self) through which the underlying
87 * messages will be received.
88 */
89 Receiver._getInstance = function (eventTarget) {
90 // The results are stored in an array since objects can't be keys for other
91 // objects. In addition, setting a unique property on an event target as a
92 // hash map key may not be allowed due to CORS restrictions.
93 var existingInstance = this.receivers.find(function (receiver) {
94 return receiver.isListeningto(eventTarget);
95 });
96 if (existingInstance) {
97 return existingInstance;
98 }
99 var newInstance = new Receiver(eventTarget);
100 this.receivers.push(newInstance);
101 return newInstance;
102 };
103 Receiver.prototype.isListeningto = function (eventTarget) {
104 return this.eventTarget === eventTarget;
105 };
106 /**
107 * Fans out a MessageEvent to the appropriate listeners.
108 *
109 * @remarks
110 * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have
111 * finished processing.
112 *
113 * @param event - The MessageEvent.
114 *
115 */
116 Receiver.prototype.handleEvent = function (event) {
117 return __awaiter(this, void 0, void 0, function () {
118 var messageEvent, _a, eventId, eventType, data, handlers, promises, response;
119 var _this = this;
120 return __generator(this, function (_b) {
121 switch (_b.label) {
122 case 0:
123 messageEvent = event;
124 _a = messageEvent.data, eventId = _a.eventId, eventType = _a.eventType, data = _a.data;
125 handlers = this.handlersMap[eventType];
126 if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {
127 return [2 /*return*/];
128 }
129 messageEvent.ports[0].postMessage({
130 status: "ack" /* ACK */,
131 eventId: eventId,
132 eventType: eventType
133 });
134 promises = Array.from(handlers).map(function (handler) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
135 return [2 /*return*/, handler(messageEvent.origin, data)];
136 }); }); });
137 return [4 /*yield*/, _allSettled(promises)];
138 case 1:
139 response = _b.sent();
140 messageEvent.ports[0].postMessage({
141 status: "done" /* DONE */,
142 eventId: eventId,
143 eventType: eventType,
144 response: response
145 });
146 return [2 /*return*/];
147 }
148 });
149 });
150 };
151 /**
152 * Subscribe an event handler for a particular event.
153 *
154 * @param eventType - Event name to subscribe to.
155 * @param eventHandler - The event handler which should receive the events.
156 *
157 */
158 Receiver.prototype._subscribe = function (eventType, eventHandler) {
159 if (Object.keys(this.handlersMap).length === 0) {
160 this.eventTarget.addEventListener('message', this.boundEventHandler);
161 }
162 if (!this.handlersMap[eventType]) {
163 this.handlersMap[eventType] = new Set();
164 }
165 this.handlersMap[eventType].add(eventHandler);
166 };
167 /**
168 * Unsubscribe an event handler from a particular event.
169 *
170 * @param eventType - Event name to unsubscribe from.
171 * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.
172 *
173 */
174 Receiver.prototype._unsubscribe = function (eventType, eventHandler) {
175 if (this.handlersMap[eventType] && eventHandler) {
176 this.handlersMap[eventType].delete(eventHandler);
177 }
178 if (!eventHandler || this.handlersMap[eventType].size === 0) {
179 delete this.handlersMap[eventType];
180 }
181 if (Object.keys(this.handlersMap).length === 0) {
182 this.eventTarget.removeEventListener('message', this.boundEventHandler);
183 }
184 };
185 Receiver.receivers = [];
186 return Receiver;
187}());
188
189/**
190 * @license
191 * Copyright 2020 Google LLC
192 *
193 * Licensed under the Apache License, Version 2.0 (the "License");
194 * you may not use this file except in compliance with the License.
195 * You may obtain a copy of the License at
196 *
197 * http://www.apache.org/licenses/LICENSE-2.0
198 *
199 * Unless required by applicable law or agreed to in writing, software
200 * distributed under the License is distributed on an "AS IS" BASIS,
201 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202 * See the License for the specific language governing permissions and
203 * limitations under the License.
204 */
205function _generateEventId(prefix, digits) {
206 if (prefix === void 0) { prefix = ''; }
207 if (digits === void 0) { digits = 10; }
208 var random = '';
209 for (var i = 0; i < digits; i++) {
210 random += Math.floor(Math.random() * 10);
211 }
212 return prefix + random;
213}
214
215/**
216 * @license
217 * Copyright 2019 Google LLC
218 *
219 * Licensed under the Apache License, Version 2.0 (the "License");
220 * you may not use this file except in compliance with the License.
221 * You may obtain a copy of the License at
222 *
223 * http://www.apache.org/licenses/LICENSE-2.0
224 *
225 * Unless required by applicable law or agreed to in writing, software
226 * distributed under the License is distributed on an "AS IS" BASIS,
227 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
228 * See the License for the specific language governing permissions and
229 * limitations under the License.
230 */
231/**
232 * Interface for sending messages and waiting for a completion response.
233 *
234 */
235var Sender = /** @class */ (function () {
236 function Sender(target) {
237 this.target = target;
238 this.handlers = new Set();
239 }
240 /**
241 * Unsubscribe the handler and remove it from our tracking Set.
242 *
243 * @param handler - The handler to unsubscribe.
244 */
245 Sender.prototype.removeMessageHandler = function (handler) {
246 if (handler.messageChannel) {
247 handler.messageChannel.port1.removeEventListener('message', handler.onMessage);
248 handler.messageChannel.port1.close();
249 }
250 this.handlers.delete(handler);
251 };
252 /**
253 * Send a message to the Receiver located at {@link target}.
254 *
255 * @remarks
256 * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the
257 * receiver has had a chance to fully process the event.
258 *
259 * @param eventType - Type of event to send.
260 * @param data - The payload of the event.
261 * @param timeout - Timeout for waiting on an ACK from the receiver.
262 *
263 * @returns An array of settled promises from all the handlers that were listening on the receiver.
264 */
265 Sender.prototype._send = function (eventType, data, timeout) {
266 if (timeout === void 0) { timeout = 50 /* ACK */; }
267 return __awaiter(this, void 0, void 0, function () {
268 var messageChannel, completionTimer, handler;
269 var _this = this;
270 return __generator(this, function (_a) {
271 messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;
272 if (!messageChannel) {
273 throw new Error("connection_unavailable" /* CONNECTION_UNAVAILABLE */);
274 }
275 return [2 /*return*/, new Promise(function (resolve, reject) {
276 var eventId = _generateEventId('', 20);
277 messageChannel.port1.start();
278 var ackTimer = setTimeout(function () {
279 reject(new Error("unsupported_event" /* UNSUPPORTED_EVENT */));
280 }, timeout);
281 handler = {
282 messageChannel: messageChannel,
283 onMessage: function (event) {
284 var messageEvent = event;
285 if (messageEvent.data.eventId !== eventId) {
286 return;
287 }
288 switch (messageEvent.data.status) {
289 case "ack" /* ACK */:
290 // The receiver should ACK first.
291 clearTimeout(ackTimer);
292 completionTimer = setTimeout(function () {
293 reject(new Error("timeout" /* TIMEOUT */));
294 }, 3000 /* COMPLETION */);
295 break;
296 case "done" /* DONE */:
297 // Once the receiver's handlers are finished we will get the results.
298 clearTimeout(completionTimer);
299 resolve(messageEvent.data.response);
300 break;
301 default:
302 clearTimeout(ackTimer);
303 clearTimeout(completionTimer);
304 reject(new Error("invalid_response" /* INVALID_RESPONSE */));
305 break;
306 }
307 }
308 };
309 _this.handlers.add(handler);
310 messageChannel.port1.addEventListener('message', handler.onMessage);
311 _this.target.postMessage({
312 eventType: eventType,
313 eventId: eventId,
314 data: data
315 }, [messageChannel.port2]);
316 }).finally(function () {
317 if (handler) {
318 _this.removeMessageHandler(handler);
319 }
320 })];
321 });
322 });
323 };
324 return Sender;
325}());
326
327/**
328 * @license
329 * Copyright 2020 Google LLC
330 *
331 * Licensed under the Apache License, Version 2.0 (the "License");
332 * you may not use this file except in compliance with the License.
333 * You may obtain a copy of the License at
334 *
335 * http://www.apache.org/licenses/LICENSE-2.0
336 *
337 * Unless required by applicable law or agreed to in writing, software
338 * distributed under the License is distributed on an "AS IS" BASIS,
339 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
340 * See the License for the specific language governing permissions and
341 * limitations under the License.
342 */
343/**
344 * Lazy accessor for window, since the compat layer won't tree shake this out,
345 * we need to make sure not to mess with window unless we have to
346 */
347function _window() {
348 return window;
349}
350function _setWindowLocation(url) {
351 _window().location.href = url;
352}
353
354/**
355 * @license
356 * Copyright 2020 Google LLC.
357 *
358 * Licensed under the Apache License, Version 2.0 (the "License");
359 * you may not use this file except in compliance with the License.
360 * You may obtain a copy of the License at
361 *
362 * http://www.apache.org/licenses/LICENSE-2.0
363 *
364 * Unless required by applicable law or agreed to in writing, software
365 * distributed under the License is distributed on an "AS IS" BASIS,
366 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
367 * See the License for the specific language governing permissions and
368 * limitations under the License.
369 */
370function _isWorker() {
371 return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&
372 typeof _window()['importScripts'] === 'function');
373}
374function _getActiveServiceWorker() {
375 return __awaiter(this, void 0, void 0, function () {
376 var registration;
377 return __generator(this, function (_b) {
378 switch (_b.label) {
379 case 0:
380 if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {
381 return [2 /*return*/, null];
382 }
383 _b.label = 1;
384 case 1:
385 _b.trys.push([1, 3, , 4]);
386 return [4 /*yield*/, navigator.serviceWorker.ready];
387 case 2:
388 registration = _b.sent();
389 return [2 /*return*/, registration.active];
390 case 3:
391 _b.sent();
392 return [2 /*return*/, null];
393 case 4: return [2 /*return*/];
394 }
395 });
396 });
397}
398function _getServiceWorkerController() {
399 var _a;
400 return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;
401}
402function _getWorkerGlobalScope() {
403 return _isWorker() ? self : null;
404}
405
406/**
407 * @license
408 * Copyright 2019 Google LLC
409 *
410 * Licensed under the Apache License, Version 2.0 (the "License");
411 * you may not use this file except in compliance with the License.
412 * You may obtain a copy of the License at
413 *
414 * http://www.apache.org/licenses/LICENSE-2.0
415 *
416 * Unless required by applicable law or agreed to in writing, software
417 * distributed under the License is distributed on an "AS IS" BASIS,
418 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
419 * See the License for the specific language governing permissions and
420 * limitations under the License.
421 */
422var DB_NAME = 'firebaseLocalStorageDb';
423var DB_VERSION = 1;
424var DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';
425var DB_DATA_KEYPATH = 'fbase_key';
426/**
427 * Promise wrapper for IDBRequest
428 *
429 * Unfortunately we can't cleanly extend Promise<T> since promises are not callable in ES6
430 *
431 */
432var DBPromise = /** @class */ (function () {
433 function DBPromise(request) {
434 this.request = request;
435 }
436 DBPromise.prototype.toPromise = function () {
437 var _this = this;
438 return new Promise(function (resolve, reject) {
439 _this.request.addEventListener('success', function () {
440 resolve(_this.request.result);
441 });
442 _this.request.addEventListener('error', function () {
443 reject(_this.request.error);
444 });
445 });
446 };
447 return DBPromise;
448}());
449function getObjectStore(db, isReadWrite) {
450 return db
451 .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')
452 .objectStore(DB_OBJECTSTORE_NAME);
453}
454function _deleteDatabase() {
455 var request = indexedDB.deleteDatabase(DB_NAME);
456 return new DBPromise(request).toPromise();
457}
458function _openDatabase() {
459 var _this = this;
460 var request = indexedDB.open(DB_NAME, DB_VERSION);
461 return new Promise(function (resolve, reject) {
462 request.addEventListener('error', function () {
463 reject(request.error);
464 });
465 request.addEventListener('upgradeneeded', function () {
466 var db = request.result;
467 try {
468 db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });
469 }
470 catch (e) {
471 reject(e);
472 }
473 });
474 request.addEventListener('success', function () { return __awaiter(_this, void 0, void 0, function () {
475 var db, _a;
476 return __generator(this, function (_b) {
477 switch (_b.label) {
478 case 0:
479 db = request.result;
480 if (!!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) return [3 /*break*/, 3];
481 // Need to close the database or else you get a `blocked` event
482 db.close();
483 return [4 /*yield*/, _deleteDatabase()];
484 case 1:
485 _b.sent();
486 _a = resolve;
487 return [4 /*yield*/, _openDatabase()];
488 case 2:
489 _a.apply(void 0, [_b.sent()]);
490 return [3 /*break*/, 4];
491 case 3:
492 resolve(db);
493 _b.label = 4;
494 case 4: return [2 /*return*/];
495 }
496 });
497 }); });
498 });
499}
500function _putObject(db, key, value) {
501 return __awaiter(this, void 0, void 0, function () {
502 var request;
503 var _a;
504 return __generator(this, function (_b) {
505 request = getObjectStore(db, true).put((_a = {},
506 _a[DB_DATA_KEYPATH] = key,
507 _a.value = value,
508 _a));
509 return [2 /*return*/, new DBPromise(request).toPromise()];
510 });
511 });
512}
513function getObject(db, key) {
514 return __awaiter(this, void 0, void 0, function () {
515 var request, data;
516 return __generator(this, function (_a) {
517 switch (_a.label) {
518 case 0:
519 request = getObjectStore(db, false).get(key);
520 return [4 /*yield*/, new DBPromise(request).toPromise()];
521 case 1:
522 data = _a.sent();
523 return [2 /*return*/, data === undefined ? null : data.value];
524 }
525 });
526 });
527}
528function _deleteObject(db, key) {
529 var request = getObjectStore(db, true).delete(key);
530 return new DBPromise(request).toPromise();
531}
532var _POLLING_INTERVAL_MS$1 = 800;
533var _TRANSACTION_RETRY_COUNT = 3;
534var IndexedDBLocalPersistence = /** @class */ (function () {
535 function IndexedDBLocalPersistence() {
536 this.type = "LOCAL" /* LOCAL */;
537 this._shouldAllowMigration = true;
538 this.listeners = {};
539 this.localCache = {};
540 // setTimeout return value is platform specific
541 // eslint-disable-next-line @typescript-eslint/no-explicit-any
542 this.pollTimer = null;
543 this.pendingWrites = 0;
544 this.receiver = null;
545 this.sender = null;
546 this.serviceWorkerReceiverAvailable = false;
547 this.activeServiceWorker = null;
548 // Fire & forget the service worker registration as it may never resolve
549 this._workerInitializationPromise =
550 this.initializeServiceWorkerMessaging().then(function () { }, function () { });
551 }
552 IndexedDBLocalPersistence.prototype._openDb = function () {
553 return __awaiter(this, void 0, void 0, function () {
554 var _a;
555 return __generator(this, function (_b) {
556 switch (_b.label) {
557 case 0:
558 if (this.db) {
559 return [2 /*return*/, this.db];
560 }
561 _a = this;
562 return [4 /*yield*/, _openDatabase()];
563 case 1:
564 _a.db = _b.sent();
565 return [2 /*return*/, this.db];
566 }
567 });
568 });
569 };
570 IndexedDBLocalPersistence.prototype._withRetries = function (op) {
571 return __awaiter(this, void 0, void 0, function () {
572 var numAttempts, db, e_1;
573 return __generator(this, function (_a) {
574 switch (_a.label) {
575 case 0:
576 numAttempts = 0;
577 _a.label = 1;
578 case 1:
579 _a.label = 2;
580 case 2:
581 _a.trys.push([2, 5, , 6]);
582 return [4 /*yield*/, this._openDb()];
583 case 3:
584 db = _a.sent();
585 return [4 /*yield*/, op(db)];
586 case 4: return [2 /*return*/, _a.sent()];
587 case 5:
588 e_1 = _a.sent();
589 if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {
590 throw e_1;
591 }
592 if (this.db) {
593 this.db.close();
594 this.db = undefined;
595 }
596 return [3 /*break*/, 6];
597 case 6: return [3 /*break*/, 1];
598 case 7: return [2 /*return*/];
599 }
600 });
601 });
602 };
603 /**
604 * IndexedDB events do not propagate from the main window to the worker context. We rely on a
605 * postMessage interface to send these events to the worker ourselves.
606 */
607 IndexedDBLocalPersistence.prototype.initializeServiceWorkerMessaging = function () {
608 return __awaiter(this, void 0, void 0, function () {
609 return __generator(this, function (_a) {
610 return [2 /*return*/, _isWorker() ? this.initializeReceiver() : this.initializeSender()];
611 });
612 });
613 };
614 /**
615 * As the worker we should listen to events from the main window.
616 */
617 IndexedDBLocalPersistence.prototype.initializeReceiver = function () {
618 return __awaiter(this, void 0, void 0, function () {
619 var _this = this;
620 return __generator(this, function (_a) {
621 this.receiver = Receiver._getInstance(_getWorkerGlobalScope());
622 // Refresh from persistence if we receive a KeyChanged message.
623 this.receiver._subscribe("keyChanged" /* KEY_CHANGED */, function (_origin, data) { return __awaiter(_this, void 0, void 0, function () {
624 var keys;
625 return __generator(this, function (_a) {
626 switch (_a.label) {
627 case 0: return [4 /*yield*/, this._poll()];
628 case 1:
629 keys = _a.sent();
630 return [2 /*return*/, {
631 keyProcessed: keys.includes(data.key)
632 }];
633 }
634 });
635 }); });
636 // Let the sender know that we are listening so they give us more timeout.
637 this.receiver._subscribe("ping" /* PING */, function (_origin, _data) { return __awaiter(_this, void 0, void 0, function () {
638 return __generator(this, function (_a) {
639 return [2 /*return*/, ["keyChanged" /* KEY_CHANGED */]];
640 });
641 }); });
642 return [2 /*return*/];
643 });
644 });
645 };
646 /**
647 * As the main window, we should let the worker know when keys change (set and remove).
648 *
649 * @remarks
650 * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}
651 * may not resolve.
652 */
653 IndexedDBLocalPersistence.prototype.initializeSender = function () {
654 var _a, _b;
655 return __awaiter(this, void 0, void 0, function () {
656 var _c, results;
657 return __generator(this, function (_d) {
658 switch (_d.label) {
659 case 0:
660 // Check to see if there's an active service worker.
661 _c = this;
662 return [4 /*yield*/, _getActiveServiceWorker()];
663 case 1:
664 // Check to see if there's an active service worker.
665 _c.activeServiceWorker = _d.sent();
666 if (!this.activeServiceWorker) {
667 return [2 /*return*/];
668 }
669 this.sender = new Sender(this.activeServiceWorker);
670 return [4 /*yield*/, this.sender._send("ping" /* PING */, {}, 800 /* LONG_ACK */)];
671 case 2:
672 results = _d.sent();
673 if (!results) {
674 return [2 /*return*/];
675 }
676 if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&
677 ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes("keyChanged" /* KEY_CHANGED */))) {
678 this.serviceWorkerReceiverAvailable = true;
679 }
680 return [2 /*return*/];
681 }
682 });
683 });
684 };
685 /**
686 * Let the worker know about a changed key, the exact key doesn't technically matter since the
687 * worker will just trigger a full sync anyway.
688 *
689 * @remarks
690 * For now, we only support one service worker per page.
691 *
692 * @param key - Storage key which changed.
693 */
694 IndexedDBLocalPersistence.prototype.notifyServiceWorker = function (key) {
695 return __awaiter(this, void 0, void 0, function () {
696 return __generator(this, function (_b) {
697 switch (_b.label) {
698 case 0:
699 if (!this.sender ||
700 !this.activeServiceWorker ||
701 _getServiceWorkerController() !== this.activeServiceWorker) {
702 return [2 /*return*/];
703 }
704 _b.label = 1;
705 case 1:
706 _b.trys.push([1, 3, , 4]);
707 return [4 /*yield*/, this.sender._send("keyChanged" /* KEY_CHANGED */, { key: key },
708 // Use long timeout if receiver has previously responded to a ping from us.
709 this.serviceWorkerReceiverAvailable
710 ? 800 /* LONG_ACK */
711 : 50 /* ACK */)];
712 case 2:
713 _b.sent();
714 return [3 /*break*/, 4];
715 case 3:
716 _b.sent();
717 return [3 /*break*/, 4];
718 case 4: return [2 /*return*/];
719 }
720 });
721 });
722 };
723 IndexedDBLocalPersistence.prototype._isAvailable = function () {
724 return __awaiter(this, void 0, void 0, function () {
725 var db;
726 return __generator(this, function (_b) {
727 switch (_b.label) {
728 case 0:
729 _b.trys.push([0, 4, , 5]);
730 if (!indexedDB) {
731 return [2 /*return*/, false];
732 }
733 return [4 /*yield*/, _openDatabase()];
734 case 1:
735 db = _b.sent();
736 return [4 /*yield*/, _putObject(db, STORAGE_AVAILABLE_KEY, '1')];
737 case 2:
738 _b.sent();
739 return [4 /*yield*/, _deleteObject(db, STORAGE_AVAILABLE_KEY)];
740 case 3:
741 _b.sent();
742 return [2 /*return*/, true];
743 case 4:
744 _b.sent();
745 return [3 /*break*/, 5];
746 case 5: return [2 /*return*/, false];
747 }
748 });
749 });
750 };
751 IndexedDBLocalPersistence.prototype._withPendingWrite = function (write) {
752 return __awaiter(this, void 0, void 0, function () {
753 return __generator(this, function (_a) {
754 switch (_a.label) {
755 case 0:
756 this.pendingWrites++;
757 _a.label = 1;
758 case 1:
759 _a.trys.push([1, , 3, 4]);
760 return [4 /*yield*/, write()];
761 case 2:
762 _a.sent();
763 return [3 /*break*/, 4];
764 case 3:
765 this.pendingWrites--;
766 return [7 /*endfinally*/];
767 case 4: return [2 /*return*/];
768 }
769 });
770 });
771 };
772 IndexedDBLocalPersistence.prototype._set = function (key, value) {
773 return __awaiter(this, void 0, void 0, function () {
774 var _this = this;
775 return __generator(this, function (_a) {
776 return [2 /*return*/, this._withPendingWrite(function () { return __awaiter(_this, void 0, void 0, function () {
777 return __generator(this, function (_a) {
778 switch (_a.label) {
779 case 0: return [4 /*yield*/, this._withRetries(function (db) { return _putObject(db, key, value); })];
780 case 1:
781 _a.sent();
782 this.localCache[key] = value;
783 return [2 /*return*/, this.notifyServiceWorker(key)];
784 }
785 });
786 }); })];
787 });
788 });
789 };
790 IndexedDBLocalPersistence.prototype._get = function (key) {
791 return __awaiter(this, void 0, void 0, function () {
792 var obj;
793 return __generator(this, function (_a) {
794 switch (_a.label) {
795 case 0: return [4 /*yield*/, this._withRetries(function (db) {
796 return getObject(db, key);
797 })];
798 case 1:
799 obj = (_a.sent());
800 this.localCache[key] = obj;
801 return [2 /*return*/, obj];
802 }
803 });
804 });
805 };
806 IndexedDBLocalPersistence.prototype._remove = function (key) {
807 return __awaiter(this, void 0, void 0, function () {
808 var _this = this;
809 return __generator(this, function (_a) {
810 return [2 /*return*/, this._withPendingWrite(function () { return __awaiter(_this, void 0, void 0, function () {
811 return __generator(this, function (_a) {
812 switch (_a.label) {
813 case 0: return [4 /*yield*/, this._withRetries(function (db) { return _deleteObject(db, key); })];
814 case 1:
815 _a.sent();
816 delete this.localCache[key];
817 return [2 /*return*/, this.notifyServiceWorker(key)];
818 }
819 });
820 }); })];
821 });
822 });
823 };
824 IndexedDBLocalPersistence.prototype._poll = function () {
825 return __awaiter(this, void 0, void 0, function () {
826 var result, keys, keysInResult, _i, result_1, _a, key, value, _b, _c, localKey;
827 return __generator(this, function (_d) {
828 switch (_d.label) {
829 case 0: return [4 /*yield*/, this._withRetries(function (db) {
830 var getAllRequest = getObjectStore(db, false).getAll();
831 return new DBPromise(getAllRequest).toPromise();
832 })];
833 case 1:
834 result = _d.sent();
835 if (!result) {
836 return [2 /*return*/, []];
837 }
838 // If we have pending writes in progress abort, we'll get picked up on the next poll
839 if (this.pendingWrites !== 0) {
840 return [2 /*return*/, []];
841 }
842 keys = [];
843 keysInResult = new Set();
844 for (_i = 0, result_1 = result; _i < result_1.length; _i++) {
845 _a = result_1[_i], key = _a.fbase_key, value = _a.value;
846 keysInResult.add(key);
847 if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {
848 this.notifyListeners(key, value);
849 keys.push(key);
850 }
851 }
852 for (_b = 0, _c = Object.keys(this.localCache); _b < _c.length; _b++) {
853 localKey = _c[_b];
854 if (this.localCache[localKey] && !keysInResult.has(localKey)) {
855 // Deleted
856 this.notifyListeners(localKey, null);
857 keys.push(localKey);
858 }
859 }
860 return [2 /*return*/, keys];
861 }
862 });
863 });
864 };
865 IndexedDBLocalPersistence.prototype.notifyListeners = function (key, newValue) {
866 this.localCache[key] = newValue;
867 var listeners = this.listeners[key];
868 if (listeners) {
869 for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
870 var listener = _a[_i];
871 listener(newValue);
872 }
873 }
874 };
875 IndexedDBLocalPersistence.prototype.startPolling = function () {
876 var _this = this;
877 this.stopPolling();
878 this.pollTimer = setInterval(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
879 return [2 /*return*/, this._poll()];
880 }); }); }, _POLLING_INTERVAL_MS$1);
881 };
882 IndexedDBLocalPersistence.prototype.stopPolling = function () {
883 if (this.pollTimer) {
884 clearInterval(this.pollTimer);
885 this.pollTimer = null;
886 }
887 };
888 IndexedDBLocalPersistence.prototype._addListener = function (key, listener) {
889 if (Object.keys(this.listeners).length === 0) {
890 this.startPolling();
891 }
892 if (!this.listeners[key]) {
893 this.listeners[key] = new Set();
894 // Populate the cache to avoid spuriously triggering on first poll.
895 void this._get(key); // This can happen in the background async and we can return immediately.
896 }
897 this.listeners[key].add(listener);
898 };
899 IndexedDBLocalPersistence.prototype._removeListener = function (key, listener) {
900 if (this.listeners[key]) {
901 this.listeners[key].delete(listener);
902 if (this.listeners[key].size === 0) {
903 delete this.listeners[key];
904 }
905 }
906 if (Object.keys(this.listeners).length === 0) {
907 this.stopPolling();
908 }
909 };
910 IndexedDBLocalPersistence.type = 'LOCAL';
911 return IndexedDBLocalPersistence;
912}());
913/**
914 * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`
915 * for the underlying storage.
916 *
917 * @public
918 */
919var indexedDBLocalPersistence = IndexedDBLocalPersistence;
920
921/**
922 * @license
923 * Copyright 2020 Google LLC
924 *
925 * Licensed under the Apache License, Version 2.0 (the "License");
926 * you may not use this file except in compliance with the License.
927 * You may obtain a copy of the License at
928 *
929 * http://www.apache.org/licenses/LICENSE-2.0
930 *
931 * Unless required by applicable law or agreed to in writing, software
932 * distributed under the License is distributed on an "AS IS" BASIS,
933 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
934 * See the License for the specific language governing permissions and
935 * limitations under the License.
936 */
937function _debugErrorMap() {
938 var _a;
939 return _a = {},
940 _a["admin-restricted-operation" /* ADMIN_ONLY_OPERATION */] = 'This operation is restricted to administrators only.',
941 _a["argument-error" /* ARGUMENT_ERROR */] = '',
942 _a["app-not-authorized" /* APP_NOT_AUTHORIZED */] = "This app, identified by the domain where it's hosted, is not " +
943 'authorized to use Firebase Authentication with the provided API key. ' +
944 'Review your key configuration in the Google API console.',
945 _a["app-not-installed" /* APP_NOT_INSTALLED */] = 'The requested mobile application corresponding to the identifier (' +
946 'Android package name or iOS bundle ID) provided is not installed on ' +
947 'this device.',
948 _a["captcha-check-failed" /* CAPTCHA_CHECK_FAILED */] = 'The reCAPTCHA response token provided is either invalid, expired, ' +
949 'already used or the domain associated with it does not match the list ' +
950 'of whitelisted domains.',
951 _a["code-expired" /* CODE_EXPIRED */] = 'The SMS code has expired. Please re-send the verification code to try ' +
952 'again.',
953 _a["cordova-not-ready" /* CORDOVA_NOT_READY */] = 'Cordova framework is not ready.',
954 _a["cors-unsupported" /* CORS_UNSUPPORTED */] = 'This browser is not supported.',
955 _a["credential-already-in-use" /* CREDENTIAL_ALREADY_IN_USE */] = 'This credential is already associated with a different user account.',
956 _a["custom-token-mismatch" /* CREDENTIAL_MISMATCH */] = 'The custom token corresponds to a different audience.',
957 _a["requires-recent-login" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = 'This operation is sensitive and requires recent authentication. Log in ' +
958 'again before retrying this request.',
959 _a["dependent-sdk-initialized-before-auth" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
960 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
961 'starting any other Firebase SDK.',
962 _a["dynamic-link-not-activated" /* DYNAMIC_LINK_NOT_ACTIVATED */] = 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +
963 'conditions.',
964 _a["email-change-needs-verification" /* EMAIL_CHANGE_NEEDS_VERIFICATION */] = 'Multi-factor users must always have a verified email.',
965 _a["email-already-in-use" /* EMAIL_EXISTS */] = 'The email address is already in use by another account.',
966 _a["emulator-config-failed" /* EMULATOR_CONFIG_FAILED */] = 'Auth instance has already been used to make a network call. Auth can ' +
967 'no longer be configured to use the emulator. Try calling ' +
968 '"connectAuthEmulator()" sooner.',
969 _a["expired-action-code" /* EXPIRED_OOB_CODE */] = 'The action code has expired.',
970 _a["cancelled-popup-request" /* EXPIRED_POPUP_REQUEST */] = 'This operation has been cancelled due to another conflicting popup being opened.',
971 _a["internal-error" /* INTERNAL_ERROR */] = 'An internal AuthError has occurred.',
972 _a["invalid-app-credential" /* INVALID_APP_CREDENTIAL */] = 'The phone verification request contains an invalid application verifier.' +
973 ' The reCAPTCHA token response is either invalid or expired.',
974 _a["invalid-app-id" /* INVALID_APP_ID */] = 'The mobile app identifier is not registed for the current project.',
975 _a["invalid-user-token" /* INVALID_AUTH */] = "This user's credential isn't valid for this project. This can happen " +
976 "if the user's token has been tampered with, or if the user isn't for " +
977 'the project associated with this API key.',
978 _a["invalid-auth-event" /* INVALID_AUTH_EVENT */] = 'An internal AuthError has occurred.',
979 _a["invalid-verification-code" /* INVALID_CODE */] = 'The SMS verification code used to create the phone auth credential is ' +
980 'invalid. Please resend the verification code sms and be sure to use the ' +
981 'verification code provided by the user.',
982 _a["invalid-continue-uri" /* INVALID_CONTINUE_URI */] = 'The continue URL provided in the request is invalid.',
983 _a["invalid-cordova-configuration" /* INVALID_CORDOVA_CONFIGURATION */] = 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +
984 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +
985 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +
986 'cordova-plugin-customurlscheme.',
987 _a["invalid-custom-token" /* INVALID_CUSTOM_TOKEN */] = 'The custom token format is incorrect. Please check the documentation.',
988 _a["invalid-dynamic-link-domain" /* INVALID_DYNAMIC_LINK_DOMAIN */] = 'The provided dynamic link domain is not configured or authorized for the current project.',
989 _a["invalid-email" /* INVALID_EMAIL */] = 'The email address is badly formatted.',
990 _a["invalid-emulator-scheme" /* INVALID_EMULATOR_SCHEME */] = 'Emulator URL must start with a valid scheme (http:// or https://).',
991 _a["invalid-api-key" /* INVALID_API_KEY */] = 'Your API key is invalid, please check you have copied it correctly.',
992 _a["invalid-cert-hash" /* INVALID_CERT_HASH */] = 'The SHA-1 certificate hash provided is invalid.',
993 _a["invalid-credential" /* INVALID_IDP_RESPONSE */] = 'The supplied auth credential is malformed or has expired.',
994 _a["invalid-message-payload" /* INVALID_MESSAGE_PAYLOAD */] = 'The email template corresponding to this action contains invalid characters in its message. ' +
995 'Please fix by going to the Auth email templates section in the Firebase Console.',
996 _a["invalid-multi-factor-session" /* INVALID_MFA_SESSION */] = 'The request does not contain a valid proof of first factor successful sign-in.',
997 _a["invalid-oauth-provider" /* INVALID_OAUTH_PROVIDER */] = 'EmailAuthProvider is not supported for this operation. This operation ' +
998 'only supports OAuth providers.',
999 _a["invalid-oauth-client-id" /* INVALID_OAUTH_CLIENT_ID */] = 'The OAuth client ID provided is either invalid or does not match the ' +
1000 'specified API key.',
1001 _a["unauthorized-domain" /* INVALID_ORIGIN */] = 'This domain is not authorized for OAuth operations for your Firebase ' +
1002 'project. Edit the list of authorized domains from the Firebase console.',
1003 _a["invalid-action-code" /* INVALID_OOB_CODE */] = 'The action code is invalid. This can happen if the code is malformed, ' +
1004 'expired, or has already been used.',
1005 _a["wrong-password" /* INVALID_PASSWORD */] = 'The password is invalid or the user does not have a password.',
1006 _a["invalid-persistence-type" /* INVALID_PERSISTENCE */] = 'The specified persistence type is invalid. It can only be local, session or none.',
1007 _a["invalid-phone-number" /* INVALID_PHONE_NUMBER */] = 'The format of the phone number provided is incorrect. Please enter the ' +
1008 'phone number in a format that can be parsed into E.164 format. E.164 ' +
1009 'phone numbers are written in the format [+][country code][subscriber ' +
1010 'number including area code].',
1011 _a["invalid-provider-id" /* INVALID_PROVIDER_ID */] = 'The specified provider ID is invalid.',
1012 _a["invalid-recipient-email" /* INVALID_RECIPIENT_EMAIL */] = 'The email corresponding to this action failed to send as the provided ' +
1013 'recipient email address is invalid.',
1014 _a["invalid-sender" /* INVALID_SENDER */] = 'The email template corresponding to this action contains an invalid sender email or name. ' +
1015 'Please fix by going to the Auth email templates section in the Firebase Console.',
1016 _a["invalid-verification-id" /* INVALID_SESSION_INFO */] = 'The verification ID used to create the phone auth credential is invalid.',
1017 _a["invalid-tenant-id" /* INVALID_TENANT_ID */] = "The Auth instance's tenant ID is invalid.",
1018 _a["login-blocked" /* LOGIN_BLOCKED */] = "Login blocked by user-provided method: {$originalMessage}",
1019 _a["missing-android-pkg-name" /* MISSING_ANDROID_PACKAGE_NAME */] = 'An Android Package Name must be provided if the Android App is required to be installed.',
1020 _a["auth-domain-config-required" /* MISSING_AUTH_DOMAIN */] = 'Be sure to include authDomain when calling firebase.initializeApp(), ' +
1021 'by following the instructions in the Firebase console.',
1022 _a["missing-app-credential" /* MISSING_APP_CREDENTIAL */] = 'The phone verification request is missing an application verifier ' +
1023 'assertion. A reCAPTCHA response token needs to be provided.',
1024 _a["missing-verification-code" /* MISSING_CODE */] = 'The phone auth credential was created with an empty SMS verification code.',
1025 _a["missing-continue-uri" /* MISSING_CONTINUE_URI */] = 'A continue URL must be provided in the request.',
1026 _a["missing-iframe-start" /* MISSING_IFRAME_START */] = 'An internal AuthError has occurred.',
1027 _a["missing-ios-bundle-id" /* MISSING_IOS_BUNDLE_ID */] = 'An iOS Bundle ID must be provided if an App Store ID is provided.',
1028 _a["missing-or-invalid-nonce" /* MISSING_OR_INVALID_NONCE */] = 'The request does not contain a valid nonce. This can occur if the ' +
1029 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +
1030 'in the ID token payload.',
1031 _a["missing-multi-factor-info" /* MISSING_MFA_INFO */] = 'No second factor identifier is provided.',
1032 _a["missing-multi-factor-session" /* MISSING_MFA_SESSION */] = 'The request is missing proof of first factor successful sign-in.',
1033 _a["missing-phone-number" /* MISSING_PHONE_NUMBER */] = 'To send verification codes, provide a phone number for the recipient.',
1034 _a["missing-verification-id" /* MISSING_SESSION_INFO */] = 'The phone auth credential was created with an empty verification ID.',
1035 _a["app-deleted" /* MODULE_DESTROYED */] = 'This instance of FirebaseApp has been deleted.',
1036 _a["multi-factor-info-not-found" /* MFA_INFO_NOT_FOUND */] = 'The user does not have a second factor matching the identifier provided.',
1037 _a["multi-factor-auth-required" /* MFA_REQUIRED */] = 'Proof of ownership of a second factor is required to complete sign-in.',
1038 _a["account-exists-with-different-credential" /* NEED_CONFIRMATION */] = 'An account already exists with the same email address but different ' +
1039 'sign-in credentials. Sign in using a provider associated with this ' +
1040 'email address.',
1041 _a["network-request-failed" /* NETWORK_REQUEST_FAILED */] = 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',
1042 _a["no-auth-event" /* NO_AUTH_EVENT */] = 'An internal AuthError has occurred.',
1043 _a["no-such-provider" /* NO_SUCH_PROVIDER */] = 'User was not linked to an account with the given provider.',
1044 _a["null-user" /* NULL_USER */] = 'A null user object was provided as the argument for an operation which ' +
1045 'requires a non-null user object.',
1046 _a["operation-not-allowed" /* OPERATION_NOT_ALLOWED */] = 'The given sign-in provider is disabled for this Firebase project. ' +
1047 'Enable it in the Firebase console, under the sign-in method tab of the ' +
1048 'Auth section.',
1049 _a["operation-not-supported-in-this-environment" /* OPERATION_NOT_SUPPORTED */] = 'This operation is not supported in the environment this application is ' +
1050 'running on. "location.protocol" must be http, https or chrome-extension' +
1051 ' and web storage must be enabled.',
1052 _a["popup-blocked" /* POPUP_BLOCKED */] = 'Unable to establish a connection with the popup. It may have been blocked by the browser.',
1053 _a["popup-closed-by-user" /* POPUP_CLOSED_BY_USER */] = 'The popup has been closed by the user before finalizing the operation.',
1054 _a["provider-already-linked" /* PROVIDER_ALREADY_LINKED */] = 'User can only be linked to one identity for the given provider.',
1055 _a["quota-exceeded" /* QUOTA_EXCEEDED */] = "The project's quota for this operation has been exceeded.",
1056 _a["redirect-cancelled-by-user" /* REDIRECT_CANCELLED_BY_USER */] = 'The redirect operation has been cancelled by the user before finalizing.',
1057 _a["redirect-operation-pending" /* REDIRECT_OPERATION_PENDING */] = 'A redirect sign-in operation is already pending.',
1058 _a["rejected-credential" /* REJECTED_CREDENTIAL */] = 'The request contains malformed or mismatching credentials.',
1059 _a["second-factor-already-in-use" /* SECOND_FACTOR_ALREADY_ENROLLED */] = 'The second factor is already enrolled on this account.',
1060 _a["maximum-second-factor-count-exceeded" /* SECOND_FACTOR_LIMIT_EXCEEDED */] = 'The maximum allowed number of second factors on a user has been exceeded.',
1061 _a["tenant-id-mismatch" /* TENANT_ID_MISMATCH */] = "The provided tenant ID does not match the Auth instance's tenant ID",
1062 _a["timeout" /* TIMEOUT */] = 'The operation has timed out.',
1063 _a["user-token-expired" /* TOKEN_EXPIRED */] = "The user's credential is no longer valid. The user must sign in again.",
1064 _a["too-many-requests" /* TOO_MANY_ATTEMPTS_TRY_LATER */] = 'We have blocked all requests from this device due to unusual activity. ' +
1065 'Try again later.',
1066 _a["unauthorized-continue-uri" /* UNAUTHORIZED_DOMAIN */] = 'The domain of the continue URL is not whitelisted. Please whitelist ' +
1067 'the domain in the Firebase console.',
1068 _a["unsupported-first-factor" /* UNSUPPORTED_FIRST_FACTOR */] = 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',
1069 _a["unsupported-persistence-type" /* UNSUPPORTED_PERSISTENCE */] = 'The current environment does not support the specified persistence type.',
1070 _a["unsupported-tenant-operation" /* UNSUPPORTED_TENANT_OPERATION */] = 'This operation is not supported in a multi-tenant context.',
1071 _a["unverified-email" /* UNVERIFIED_EMAIL */] = 'The operation requires a verified email.',
1072 _a["user-cancelled" /* USER_CANCELLED */] = 'The user did not grant your application the permissions it requested.',
1073 _a["user-not-found" /* USER_DELETED */] = 'There is no user record corresponding to this identifier. The user may ' +
1074 'have been deleted.',
1075 _a["user-disabled" /* USER_DISABLED */] = 'The user account has been disabled by an administrator.',
1076 _a["user-mismatch" /* USER_MISMATCH */] = 'The supplied credentials do not correspond to the previously signed in user.',
1077 _a["user-signed-out" /* USER_SIGNED_OUT */] = '',
1078 _a["weak-password" /* WEAK_PASSWORD */] = 'The password must be 6 characters long or more.',
1079 _a["web-storage-unsupported" /* WEB_STORAGE_UNSUPPORTED */] = 'This browser is not supported or 3rd party cookies and data may be disabled.',
1080 _a["already-initialized" /* ALREADY_INITIALIZED */] = 'initializeAuth() has already been called with ' +
1081 'different options. To avoid this error, call initializeAuth() with the ' +
1082 'same options as when it was originally called, or call getAuth() to return the' +
1083 ' already initialized instance.',
1084 _a;
1085}
1086function _prodErrorMap() {
1087 var _a;
1088 // We will include this one message in the prod error map since by the very
1089 // nature of this error, developers will never be able to see the message
1090 // using the debugErrorMap (which is installed during auth initialization).
1091 return _a = {},
1092 _a["dependent-sdk-initialized-before-auth" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */] = 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +
1093 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +
1094 'starting any other Firebase SDK.',
1095 _a;
1096}
1097/**
1098 * A verbose error map with detailed descriptions for most error codes.
1099 *
1100 * See discussion at {@link AuthErrorMap}
1101 *
1102 * @public
1103 */
1104var debugErrorMap = _debugErrorMap;
1105/**
1106 * A minimal error map with all verbose error messages stripped.
1107 *
1108 * See discussion at {@link AuthErrorMap}
1109 *
1110 * @public
1111 */
1112var prodErrorMap = _prodErrorMap;
1113var _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());
1114/**
1115 * A map of potential `Auth` error codes, for easier comparison with errors
1116 * thrown by the SDK.
1117 *
1118 * @remarks
1119 * Note that you can't tree-shake individual keys
1120 * in the map, so by using the map you might substantially increase your
1121 * bundle size.
1122 *
1123 * @public
1124 */
1125var AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {
1126 ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',
1127 ARGUMENT_ERROR: 'auth/argument-error',
1128 APP_NOT_AUTHORIZED: 'auth/app-not-authorized',
1129 APP_NOT_INSTALLED: 'auth/app-not-installed',
1130 CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',
1131 CODE_EXPIRED: 'auth/code-expired',
1132 CORDOVA_NOT_READY: 'auth/cordova-not-ready',
1133 CORS_UNSUPPORTED: 'auth/cors-unsupported',
1134 CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',
1135 CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',
1136 CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',
1137 DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',
1138 DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',
1139 EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',
1140 EMAIL_EXISTS: 'auth/email-already-in-use',
1141 EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',
1142 EXPIRED_OOB_CODE: 'auth/expired-action-code',
1143 EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',
1144 INTERNAL_ERROR: 'auth/internal-error',
1145 INVALID_API_KEY: 'auth/invalid-api-key',
1146 INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',
1147 INVALID_APP_ID: 'auth/invalid-app-id',
1148 INVALID_AUTH: 'auth/invalid-user-token',
1149 INVALID_AUTH_EVENT: 'auth/invalid-auth-event',
1150 INVALID_CERT_HASH: 'auth/invalid-cert-hash',
1151 INVALID_CODE: 'auth/invalid-verification-code',
1152 INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',
1153 INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',
1154 INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',
1155 INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',
1156 INVALID_EMAIL: 'auth/invalid-email',
1157 INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',
1158 INVALID_IDP_RESPONSE: 'auth/invalid-credential',
1159 INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',
1160 INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',
1161 INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',
1162 INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',
1163 INVALID_OOB_CODE: 'auth/invalid-action-code',
1164 INVALID_ORIGIN: 'auth/unauthorized-domain',
1165 INVALID_PASSWORD: 'auth/wrong-password',
1166 INVALID_PERSISTENCE: 'auth/invalid-persistence-type',
1167 INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',
1168 INVALID_PROVIDER_ID: 'auth/invalid-provider-id',
1169 INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',
1170 INVALID_SENDER: 'auth/invalid-sender',
1171 INVALID_SESSION_INFO: 'auth/invalid-verification-id',
1172 INVALID_TENANT_ID: 'auth/invalid-tenant-id',
1173 MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',
1174 MFA_REQUIRED: 'auth/multi-factor-auth-required',
1175 MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',
1176 MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',
1177 MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',
1178 MISSING_CODE: 'auth/missing-verification-code',
1179 MISSING_CONTINUE_URI: 'auth/missing-continue-uri',
1180 MISSING_IFRAME_START: 'auth/missing-iframe-start',
1181 MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',
1182 MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',
1183 MISSING_MFA_INFO: 'auth/missing-multi-factor-info',
1184 MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',
1185 MISSING_PHONE_NUMBER: 'auth/missing-phone-number',
1186 MISSING_SESSION_INFO: 'auth/missing-verification-id',
1187 MODULE_DESTROYED: 'auth/app-deleted',
1188 NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',
1189 NETWORK_REQUEST_FAILED: 'auth/network-request-failed',
1190 NULL_USER: 'auth/null-user',
1191 NO_AUTH_EVENT: 'auth/no-auth-event',
1192 NO_SUCH_PROVIDER: 'auth/no-such-provider',
1193 OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',
1194 OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',
1195 POPUP_BLOCKED: 'auth/popup-blocked',
1196 POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',
1197 PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',
1198 QUOTA_EXCEEDED: 'auth/quota-exceeded',
1199 REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',
1200 REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',
1201 REJECTED_CREDENTIAL: 'auth/rejected-credential',
1202 SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',
1203 SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',
1204 TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',
1205 TIMEOUT: 'auth/timeout',
1206 TOKEN_EXPIRED: 'auth/user-token-expired',
1207 TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',
1208 UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',
1209 UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',
1210 UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',
1211 UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',
1212 UNVERIFIED_EMAIL: 'auth/unverified-email',
1213 USER_CANCELLED: 'auth/user-cancelled',
1214 USER_DELETED: 'auth/user-not-found',
1215 USER_DISABLED: 'auth/user-disabled',
1216 USER_MISMATCH: 'auth/user-mismatch',
1217 USER_SIGNED_OUT: 'auth/user-signed-out',
1218 WEAK_PASSWORD: 'auth/weak-password',
1219 WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',
1220 ALREADY_INITIALIZED: 'auth/already-initialized'
1221};
1222
1223/**
1224 * @license
1225 * Copyright 2020 Google LLC
1226 *
1227 * Licensed under the Apache License, Version 2.0 (the "License");
1228 * you may not use this file except in compliance with the License.
1229 * You may obtain a copy of the License at
1230 *
1231 * http://www.apache.org/licenses/LICENSE-2.0
1232 *
1233 * Unless required by applicable law or agreed to in writing, software
1234 * distributed under the License is distributed on an "AS IS" BASIS,
1235 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1236 * See the License for the specific language governing permissions and
1237 * limitations under the License.
1238 */
1239var logClient = new Logger('@firebase/auth');
1240function _logError(msg) {
1241 var args = [];
1242 for (var _i = 1; _i < arguments.length; _i++) {
1243 args[_i - 1] = arguments[_i];
1244 }
1245 if (logClient.logLevel <= LogLevel.ERROR) {
1246 logClient.error.apply(logClient, __spreadArray(["Auth (" + SDK_VERSION + "): " + msg], args));
1247 }
1248}
1249
1250/**
1251 * @license
1252 * Copyright 2020 Google LLC
1253 *
1254 * Licensed under the Apache License, Version 2.0 (the "License");
1255 * you may not use this file except in compliance with the License.
1256 * You may obtain a copy of the License at
1257 *
1258 * http://www.apache.org/licenses/LICENSE-2.0
1259 *
1260 * Unless required by applicable law or agreed to in writing, software
1261 * distributed under the License is distributed on an "AS IS" BASIS,
1262 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1263 * See the License for the specific language governing permissions and
1264 * limitations under the License.
1265 */
1266function _fail(authOrCode) {
1267 var rest = [];
1268 for (var _i = 1; _i < arguments.length; _i++) {
1269 rest[_i - 1] = arguments[_i];
1270 }
1271 throw createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest));
1272}
1273function _createError(authOrCode) {
1274 var rest = [];
1275 for (var _i = 1; _i < arguments.length; _i++) {
1276 rest[_i - 1] = arguments[_i];
1277 }
1278 return createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest));
1279}
1280function _errorWithCustomMessage(auth, code, message) {
1281 var _a;
1282 var errorMap = __assign(__assign({}, prodErrorMap()), (_a = {}, _a[code] = message, _a));
1283 var factory = new ErrorFactory('auth', 'Firebase', errorMap);
1284 return factory.create(code, {
1285 appName: auth.name,
1286 });
1287}
1288function _assertInstanceOf(auth, object, instance) {
1289 var constructorInstance = instance;
1290 if (!(object instanceof constructorInstance)) {
1291 if (constructorInstance.name !== object.constructor.name) {
1292 _fail(auth, "argument-error" /* ARGUMENT_ERROR */);
1293 }
1294 throw _errorWithCustomMessage(auth, "argument-error" /* ARGUMENT_ERROR */, "Type of " + object.constructor.name + " does not match expected instance." +
1295 "Did you pass a reference from a different Auth SDK?");
1296 }
1297}
1298function createErrorInternal(authOrCode) {
1299 var _a;
1300 var rest = [];
1301 for (var _i = 1; _i < arguments.length; _i++) {
1302 rest[_i - 1] = arguments[_i];
1303 }
1304 if (typeof authOrCode !== 'string') {
1305 var code = rest[0];
1306 var fullParams = __spreadArray([], rest.slice(1));
1307 if (fullParams[0]) {
1308 fullParams[0].appName = authOrCode.name;
1309 }
1310 return (_a = authOrCode._errorFactory).create.apply(_a, __spreadArray([code], fullParams));
1311 }
1312 return _DEFAULT_AUTH_ERROR_FACTORY.create.apply(_DEFAULT_AUTH_ERROR_FACTORY, __spreadArray([authOrCode], rest));
1313}
1314function _assert(assertion, authOrCode) {
1315 var rest = [];
1316 for (var _i = 2; _i < arguments.length; _i++) {
1317 rest[_i - 2] = arguments[_i];
1318 }
1319 if (!assertion) {
1320 throw createErrorInternal.apply(void 0, __spreadArray([authOrCode], rest));
1321 }
1322}
1323/**
1324 * Unconditionally fails, throwing an internal error with the given message.
1325 *
1326 * @param failure type of failure encountered
1327 * @throws Error
1328 */
1329function debugFail(failure) {
1330 // Log the failure in addition to throw an exception, just in case the
1331 // exception is swallowed.
1332 var message = "INTERNAL ASSERTION FAILED: " + failure;
1333 _logError(message);
1334 // NOTE: We don't use FirebaseError here because these are internal failures
1335 // that cannot be handled by the user. (Also it would create a circular
1336 // dependency between the error and assert modules which doesn't work.)
1337 throw new Error(message);
1338}
1339/**
1340 * Fails if the given assertion condition is false, throwing an Error with the
1341 * given message if it did.
1342 *
1343 * @param assertion
1344 * @param message
1345 */
1346function debugAssert(assertion, message) {
1347 if (!assertion) {
1348 debugFail(message);
1349 }
1350}
1351
1352/**
1353 * @license
1354 * Copyright 2020 Google LLC
1355 *
1356 * Licensed under the Apache License, Version 2.0 (the "License");
1357 * you may not use this file except in compliance with the License.
1358 * You may obtain a copy of the License at
1359 *
1360 * http://www.apache.org/licenses/LICENSE-2.0
1361 *
1362 * Unless required by applicable law or agreed to in writing, software
1363 * distributed under the License is distributed on an "AS IS" BASIS,
1364 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1365 * See the License for the specific language governing permissions and
1366 * limitations under the License.
1367 */
1368var instanceCache = new Map();
1369function _getInstance(cls) {
1370 debugAssert(cls instanceof Function, 'Expected a class definition');
1371 var instance = instanceCache.get(cls);
1372 if (instance) {
1373 debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');
1374 return instance;
1375 }
1376 instance = new cls();
1377 instanceCache.set(cls, instance);
1378 return instance;
1379}
1380
1381/**
1382 * @license
1383 * Copyright 2020 Google LLC
1384 *
1385 * Licensed under the Apache License, Version 2.0 (the "License");
1386 * you may not use this file except in compliance with the License.
1387 * You may obtain a copy of the License at
1388 *
1389 * http://www.apache.org/licenses/LICENSE-2.0
1390 *
1391 * Unless required by applicable law or agreed to in writing, software
1392 * distributed under the License is distributed on an "AS IS" BASIS,
1393 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1394 * See the License for the specific language governing permissions and
1395 * limitations under the License.
1396 */
1397/**
1398 * Initializes an {@link Auth} instance with fine-grained control over
1399 * {@link Dependencies}.
1400 *
1401 * @remarks
1402 *
1403 * This function allows more control over the {@link Auth} instance than
1404 * {@link getAuth}. `getAuth` uses platform-specific defaults to supply
1405 * the {@link Dependencies}. In general, `getAuth` is the easiest way to
1406 * initialize Auth and works for most use cases. Use `initializeAuth` if you
1407 * need control over which persistence layer is used, or to minimize bundle
1408 * size if you're not using either `signInWithPopup` or `signInWithRedirect`.
1409 *
1410 * For example, if your app only uses anonymous accounts and you only want
1411 * accounts saved for the current session, initialize `Auth` with:
1412 *
1413 * ```js
1414 * const auth = initializeAuth(app, {
1415 * persistence: browserSessionPersistence,
1416 * popupRedirectResolver: undefined,
1417 * });
1418 * ```
1419 *
1420 * @public
1421 */
1422function initializeAuth(app, deps) {
1423 var provider = _getProvider(app, 'auth');
1424 if (provider.isInitialized()) {
1425 var auth_1 = provider.getImmediate();
1426 var initialOptions = provider.getOptions();
1427 if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {
1428 return auth_1;
1429 }
1430 else {
1431 _fail(auth_1, "already-initialized" /* ALREADY_INITIALIZED */);
1432 }
1433 }
1434 var auth = provider.initialize({ options: deps });
1435 return auth;
1436}
1437function _initializeAuthInstance(auth, deps) {
1438 var persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];
1439 var hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);
1440 if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {
1441 auth._updateErrorMap(deps.errorMap);
1442 }
1443 // This promise is intended to float; auth initialization happens in the
1444 // background, meanwhile the auth object may be used by the app.
1445 // eslint-disable-next-line @typescript-eslint/no-floating-promises
1446 auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);
1447}
1448
1449/**
1450 * @license
1451 * Copyright 2020 Google LLC
1452 *
1453 * Licensed under the Apache License, Version 2.0 (the "License");
1454 * you may not use this file except in compliance with the License.
1455 * You may obtain a copy of the License at
1456 *
1457 * http://www.apache.org/licenses/LICENSE-2.0
1458 *
1459 * Unless required by applicable law or agreed to in writing, software
1460 * distributed under the License is distributed on an "AS IS" BASIS,
1461 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1462 * See the License for the specific language governing permissions and
1463 * limitations under the License.
1464 */
1465function _getCurrentUrl() {
1466 var _a;
1467 return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';
1468}
1469function _isHttpOrHttps() {
1470 return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';
1471}
1472function _getCurrentScheme() {
1473 var _a;
1474 return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;
1475}
1476
1477/**
1478 * @license
1479 * Copyright 2020 Google LLC
1480 *
1481 * Licensed under the Apache License, Version 2.0 (the "License");
1482 * you may not use this file except in compliance with the License.
1483 * You may obtain a copy of the License at
1484 *
1485 * http://www.apache.org/licenses/LICENSE-2.0
1486 *
1487 * Unless required by applicable law or agreed to in writing, software
1488 * distributed under the License is distributed on an "AS IS" BASIS,
1489 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1490 * See the License for the specific language governing permissions and
1491 * limitations under the License.
1492 */
1493/**
1494 * Determine whether the browser is working online
1495 */
1496function _isOnline() {
1497 if (typeof navigator !== 'undefined' &&
1498 navigator &&
1499 'onLine' in navigator &&
1500 typeof navigator.onLine === 'boolean' &&
1501 // Apply only for traditional web apps and Chrome extensions.
1502 // This is especially true for Cordova apps which have unreliable
1503 // navigator.onLine behavior unless cordova-plugin-network-information is
1504 // installed which overwrites the native navigator.onLine value and
1505 // defines navigator.connection.
1506 (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {
1507 return navigator.onLine;
1508 }
1509 // If we can't determine the state, assume it is online.
1510 return true;
1511}
1512function _getUserLanguage() {
1513 if (typeof navigator === 'undefined') {
1514 return null;
1515 }
1516 var navigatorLanguage = navigator;
1517 return (
1518 // Most reliable, but only supported in Chrome/Firefox.
1519 (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||
1520 // Supported in most browsers, but returns the language of the browser
1521 // UI, not the language set in browser settings.
1522 navigatorLanguage.language ||
1523 // Couldn't determine language.
1524 null);
1525}
1526
1527/**
1528 * @license
1529 * Copyright 2020 Google LLC
1530 *
1531 * Licensed under the Apache License, Version 2.0 (the "License");
1532 * you may not use this file except in compliance with the License.
1533 * You may obtain a copy of the License at
1534 *
1535 * http://www.apache.org/licenses/LICENSE-2.0
1536 *
1537 * Unless required by applicable law or agreed to in writing, software
1538 * distributed under the License is distributed on an "AS IS" BASIS,
1539 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1540 * See the License for the specific language governing permissions and
1541 * limitations under the License.
1542 */
1543/**
1544 * A structure to help pick between a range of long and short delay durations
1545 * depending on the current environment. In general, the long delay is used for
1546 * mobile environments whereas short delays are used for desktop environments.
1547 */
1548var Delay = /** @class */ (function () {
1549 function Delay(shortDelay, longDelay) {
1550 this.shortDelay = shortDelay;
1551 this.longDelay = longDelay;
1552 // Internal error when improperly initialized.
1553 debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');
1554 this.isMobile = isMobileCordova() || isReactNative();
1555 }
1556 Delay.prototype.get = function () {
1557 if (!_isOnline()) {
1558 // Pick the shorter timeout.
1559 return Math.min(5000 /* OFFLINE */, this.shortDelay);
1560 }
1561 // If running in a mobile environment, return the long delay, otherwise
1562 // return the short delay.
1563 // This could be improved in the future to dynamically change based on other
1564 // variables instead of just reading the current environment.
1565 return this.isMobile ? this.longDelay : this.shortDelay;
1566 };
1567 return Delay;
1568}());
1569
1570/**
1571 * @license
1572 * Copyright 2020 Google LLC
1573 *
1574 * Licensed under the Apache License, Version 2.0 (the "License");
1575 * you may not use this file except in compliance with the License.
1576 * You may obtain a copy of the License at
1577 *
1578 * http://www.apache.org/licenses/LICENSE-2.0
1579 *
1580 * Unless required by applicable law or agreed to in writing, software
1581 * distributed under the License is distributed on an "AS IS" BASIS,
1582 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1583 * See the License for the specific language governing permissions and
1584 * limitations under the License.
1585 */
1586function _emulatorUrl(config, path) {
1587 debugAssert(config.emulator, 'Emulator should always be set here');
1588 var url = config.emulator.url;
1589 if (!path) {
1590 return url;
1591 }
1592 return "" + url + (path.startsWith('/') ? path.slice(1) : path);
1593}
1594
1595/**
1596 * @license
1597 * Copyright 2020 Google LLC
1598 *
1599 * Licensed under the Apache License, Version 2.0 (the "License");
1600 * you may not use this file except in compliance with the License.
1601 * You may obtain a copy of the License at
1602 *
1603 * http://www.apache.org/licenses/LICENSE-2.0
1604 *
1605 * Unless required by applicable law or agreed to in writing, software
1606 * distributed under the License is distributed on an "AS IS" BASIS,
1607 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1608 * See the License for the specific language governing permissions and
1609 * limitations under the License.
1610 */
1611var FetchProvider = /** @class */ (function () {
1612 function FetchProvider() {
1613 }
1614 FetchProvider.initialize = function (fetchImpl, headersImpl, responseImpl) {
1615 this.fetchImpl = fetchImpl;
1616 if (headersImpl) {
1617 this.headersImpl = headersImpl;
1618 }
1619 if (responseImpl) {
1620 this.responseImpl = responseImpl;
1621 }
1622 };
1623 FetchProvider.fetch = function () {
1624 if (this.fetchImpl) {
1625 return this.fetchImpl;
1626 }
1627 if (typeof self !== 'undefined' && 'fetch' in self) {
1628 return self.fetch;
1629 }
1630 debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
1631 };
1632 FetchProvider.headers = function () {
1633 if (this.headersImpl) {
1634 return this.headersImpl;
1635 }
1636 if (typeof self !== 'undefined' && 'Headers' in self) {
1637 return self.Headers;
1638 }
1639 debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
1640 };
1641 FetchProvider.response = function () {
1642 if (this.responseImpl) {
1643 return this.responseImpl;
1644 }
1645 if (typeof self !== 'undefined' && 'Response' in self) {
1646 return self.Response;
1647 }
1648 debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');
1649 };
1650 return FetchProvider;
1651}());
1652
1653/**
1654 * @license
1655 * Copyright 2020 Google LLC
1656 *
1657 * Licensed under the Apache License, Version 2.0 (the "License");
1658 * you may not use this file except in compliance with the License.
1659 * You may obtain a copy of the License at
1660 *
1661 * http://www.apache.org/licenses/LICENSE-2.0
1662 *
1663 * Unless required by applicable law or agreed to in writing, software
1664 * distributed under the License is distributed on an "AS IS" BASIS,
1665 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1666 * See the License for the specific language governing permissions and
1667 * limitations under the License.
1668 */
1669var _a$1;
1670/**
1671 * Map from errors returned by the server to errors to developer visible errors
1672 */
1673var SERVER_ERROR_MAP = (_a$1 = {},
1674 // Custom token errors.
1675 _a$1["CREDENTIAL_MISMATCH" /* CREDENTIAL_MISMATCH */] = "custom-token-mismatch" /* CREDENTIAL_MISMATCH */,
1676 // This can only happen if the SDK sends a bad request.
1677 _a$1["MISSING_CUSTOM_TOKEN" /* MISSING_CUSTOM_TOKEN */] = "internal-error" /* INTERNAL_ERROR */,
1678 // Create Auth URI errors.
1679 _a$1["INVALID_IDENTIFIER" /* INVALID_IDENTIFIER */] = "invalid-email" /* INVALID_EMAIL */,
1680 // This can only happen if the SDK sends a bad request.
1681 _a$1["MISSING_CONTINUE_URI" /* MISSING_CONTINUE_URI */] = "internal-error" /* INTERNAL_ERROR */,
1682 // Sign in with email and password errors (some apply to sign up too).
1683 _a$1["INVALID_PASSWORD" /* INVALID_PASSWORD */] = "wrong-password" /* INVALID_PASSWORD */,
1684 // This can only happen if the SDK sends a bad request.
1685 _a$1["MISSING_PASSWORD" /* MISSING_PASSWORD */] = "internal-error" /* INTERNAL_ERROR */,
1686 // Sign up with email and password errors.
1687 _a$1["EMAIL_EXISTS" /* EMAIL_EXISTS */] = "email-already-in-use" /* EMAIL_EXISTS */,
1688 _a$1["PASSWORD_LOGIN_DISABLED" /* PASSWORD_LOGIN_DISABLED */] = "operation-not-allowed" /* OPERATION_NOT_ALLOWED */,
1689 // Verify assertion for sign in with credential errors:
1690 _a$1["INVALID_IDP_RESPONSE" /* INVALID_IDP_RESPONSE */] = "invalid-credential" /* INVALID_IDP_RESPONSE */,
1691 _a$1["INVALID_PENDING_TOKEN" /* INVALID_PENDING_TOKEN */] = "invalid-credential" /* INVALID_IDP_RESPONSE */,
1692 _a$1["FEDERATED_USER_ID_ALREADY_LINKED" /* FEDERATED_USER_ID_ALREADY_LINKED */] = "credential-already-in-use" /* CREDENTIAL_ALREADY_IN_USE */,
1693 // This can only happen if the SDK sends a bad request.
1694 _a$1["MISSING_REQ_TYPE" /* MISSING_REQ_TYPE */] = "internal-error" /* INTERNAL_ERROR */,
1695 // Send Password reset email errors:
1696 _a$1["EMAIL_NOT_FOUND" /* EMAIL_NOT_FOUND */] = "user-not-found" /* USER_DELETED */,
1697 _a$1["RESET_PASSWORD_EXCEED_LIMIT" /* RESET_PASSWORD_EXCEED_LIMIT */] = "too-many-requests" /* TOO_MANY_ATTEMPTS_TRY_LATER */,
1698 _a$1["EXPIRED_OOB_CODE" /* EXPIRED_OOB_CODE */] = "expired-action-code" /* EXPIRED_OOB_CODE */,
1699 _a$1["INVALID_OOB_CODE" /* INVALID_OOB_CODE */] = "invalid-action-code" /* INVALID_OOB_CODE */,
1700 // This can only happen if the SDK sends a bad request.
1701 _a$1["MISSING_OOB_CODE" /* MISSING_OOB_CODE */] = "internal-error" /* INTERNAL_ERROR */,
1702 // Operations that require ID token in request:
1703 _a$1["CREDENTIAL_TOO_OLD_LOGIN_AGAIN" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */] = "requires-recent-login" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,
1704 _a$1["INVALID_ID_TOKEN" /* INVALID_ID_TOKEN */] = "invalid-user-token" /* INVALID_AUTH */,
1705 _a$1["TOKEN_EXPIRED" /* TOKEN_EXPIRED */] = "user-token-expired" /* TOKEN_EXPIRED */,
1706 _a$1["USER_NOT_FOUND" /* USER_NOT_FOUND */] = "user-token-expired" /* TOKEN_EXPIRED */,
1707 // Other errors.
1708 _a$1["TOO_MANY_ATTEMPTS_TRY_LATER" /* TOO_MANY_ATTEMPTS_TRY_LATER */] = "too-many-requests" /* TOO_MANY_ATTEMPTS_TRY_LATER */,
1709 // Phone Auth related errors.
1710 _a$1["INVALID_CODE" /* INVALID_CODE */] = "invalid-verification-code" /* INVALID_CODE */,
1711 _a$1["INVALID_SESSION_INFO" /* INVALID_SESSION_INFO */] = "invalid-verification-id" /* INVALID_SESSION_INFO */,
1712 _a$1["INVALID_TEMPORARY_PROOF" /* INVALID_TEMPORARY_PROOF */] = "invalid-credential" /* INVALID_IDP_RESPONSE */,
1713 _a$1["MISSING_SESSION_INFO" /* MISSING_SESSION_INFO */] = "missing-verification-id" /* MISSING_SESSION_INFO */,
1714 _a$1["SESSION_EXPIRED" /* SESSION_EXPIRED */] = "code-expired" /* CODE_EXPIRED */,
1715 // Other action code errors when additional settings passed.
1716 // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.
1717 // This is OK as this error will be caught by client side validation.
1718 _a$1["MISSING_ANDROID_PACKAGE_NAME" /* MISSING_ANDROID_PACKAGE_NAME */] = "missing-android-pkg-name" /* MISSING_ANDROID_PACKAGE_NAME */,
1719 _a$1["UNAUTHORIZED_DOMAIN" /* UNAUTHORIZED_DOMAIN */] = "unauthorized-continue-uri" /* UNAUTHORIZED_DOMAIN */,
1720 // getProjectConfig errors when clientId is passed.
1721 _a$1["INVALID_OAUTH_CLIENT_ID" /* INVALID_OAUTH_CLIENT_ID */] = "invalid-oauth-client-id" /* INVALID_OAUTH_CLIENT_ID */,
1722 // User actions (sign-up or deletion) disabled errors.
1723 _a$1["ADMIN_ONLY_OPERATION" /* ADMIN_ONLY_OPERATION */] = "admin-restricted-operation" /* ADMIN_ONLY_OPERATION */,
1724 // Multi factor related errors.
1725 _a$1["INVALID_MFA_PENDING_CREDENTIAL" /* INVALID_MFA_PENDING_CREDENTIAL */] = "invalid-multi-factor-session" /* INVALID_MFA_SESSION */,
1726 _a$1["MFA_ENROLLMENT_NOT_FOUND" /* MFA_ENROLLMENT_NOT_FOUND */] = "multi-factor-info-not-found" /* MFA_INFO_NOT_FOUND */,
1727 _a$1["MISSING_MFA_ENROLLMENT_ID" /* MISSING_MFA_ENROLLMENT_ID */] = "missing-multi-factor-info" /* MISSING_MFA_INFO */,
1728 _a$1["MISSING_MFA_PENDING_CREDENTIAL" /* MISSING_MFA_PENDING_CREDENTIAL */] = "missing-multi-factor-session" /* MISSING_MFA_SESSION */,
1729 _a$1["SECOND_FACTOR_EXISTS" /* SECOND_FACTOR_EXISTS */] = "second-factor-already-in-use" /* SECOND_FACTOR_ALREADY_ENROLLED */,
1730 _a$1["SECOND_FACTOR_LIMIT_EXCEEDED" /* SECOND_FACTOR_LIMIT_EXCEEDED */] = "maximum-second-factor-count-exceeded" /* SECOND_FACTOR_LIMIT_EXCEEDED */,
1731 // Blocking functions related errors.
1732 _a$1["BLOCKING_FUNCTION_ERROR_RESPONSE" /* BLOCKING_FUNCTION_ERROR_RESPONSE */] = "internal-error" /* INTERNAL_ERROR */,
1733 _a$1);
1734
1735/**
1736 * @license
1737 * Copyright 2020 Google LLC
1738 *
1739 * Licensed under the Apache License, Version 2.0 (the "License");
1740 * you may not use this file except in compliance with the License.
1741 * You may obtain a copy of the License at
1742 *
1743 * http://www.apache.org/licenses/LICENSE-2.0
1744 *
1745 * Unless required by applicable law or agreed to in writing, software
1746 * distributed under the License is distributed on an "AS IS" BASIS,
1747 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1748 * See the License for the specific language governing permissions and
1749 * limitations under the License.
1750 */
1751var DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);
1752function _addTidIfNecessary(auth, request) {
1753 if (auth.tenantId && !request.tenantId) {
1754 return __assign(__assign({}, request), { tenantId: auth.tenantId });
1755 }
1756 return request;
1757}
1758function _performApiRequest(auth, method, path, request, customErrorMap) {
1759 if (customErrorMap === void 0) { customErrorMap = {}; }
1760 return __awaiter(this, void 0, void 0, function () {
1761 var _this = this;
1762 return __generator(this, function (_a) {
1763 return [2 /*return*/, _performFetchWithErrorHandling(auth, customErrorMap, function () { return __awaiter(_this, void 0, void 0, function () {
1764 var body, params, query, headers;
1765 return __generator(this, function (_a) {
1766 switch (_a.label) {
1767 case 0:
1768 body = {};
1769 params = {};
1770 if (request) {
1771 if (method === "GET" /* GET */) {
1772 params = request;
1773 }
1774 else {
1775 body = {
1776 body: JSON.stringify(request)
1777 };
1778 }
1779 }
1780 query = querystring(__assign({ key: auth.config.apiKey }, params)).slice(1);
1781 return [4 /*yield*/, auth._getAdditionalHeaders()];
1782 case 1:
1783 headers = _a.sent();
1784 headers["Content-Type" /* CONTENT_TYPE */] = 'application/json';
1785 if (auth.languageCode) {
1786 headers["X-Firebase-Locale" /* X_FIREBASE_LOCALE */] = auth.languageCode;
1787 }
1788 return [2 /*return*/, FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), __assign({ method: method,
1789 headers: headers, referrerPolicy: 'no-referrer' }, body))];
1790 }
1791 });
1792 }); })];
1793 });
1794 });
1795}
1796function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {
1797 return __awaiter(this, void 0, void 0, function () {
1798 var errorMap, networkTimeout, response, json, errorMessage, _a, serverErrorCode, serverErrorMessage, authError, e_1;
1799 return __generator(this, function (_b) {
1800 switch (_b.label) {
1801 case 0:
1802 auth._canInitEmulator = false;
1803 errorMap = __assign(__assign({}, SERVER_ERROR_MAP), customErrorMap);
1804 _b.label = 1;
1805 case 1:
1806 _b.trys.push([1, 4, , 5]);
1807 networkTimeout = new NetworkTimeout(auth);
1808 return [4 /*yield*/, Promise.race([
1809 fetchFn(),
1810 networkTimeout.promise
1811 ])];
1812 case 2:
1813 response = _b.sent();
1814 // If we've reached this point, the fetch succeeded and the networkTimeout
1815 // didn't throw; clear the network timeout delay so that Node won't hang
1816 networkTimeout.clearNetworkTimeout();
1817 return [4 /*yield*/, response.json()];
1818 case 3:
1819 json = _b.sent();
1820 if ('needConfirmation' in json) {
1821 throw _makeTaggedError(auth, "account-exists-with-different-credential" /* NEED_CONFIRMATION */, json);
1822 }
1823 if (response.ok && !('errorMessage' in json)) {
1824 return [2 /*return*/, json];
1825 }
1826 else {
1827 errorMessage = response.ok ? json.errorMessage : json.error.message;
1828 _a = errorMessage.split(' : '), serverErrorCode = _a[0], serverErrorMessage = _a[1];
1829 if (serverErrorCode === "FEDERATED_USER_ID_ALREADY_LINKED" /* FEDERATED_USER_ID_ALREADY_LINKED */) {
1830 throw _makeTaggedError(auth, "credential-already-in-use" /* CREDENTIAL_ALREADY_IN_USE */, json);
1831 }
1832 else if (serverErrorCode === "EMAIL_EXISTS" /* EMAIL_EXISTS */) {
1833 throw _makeTaggedError(auth, "email-already-in-use" /* EMAIL_EXISTS */, json);
1834 }
1835 authError = errorMap[serverErrorCode] ||
1836 serverErrorCode
1837 .toLowerCase()
1838 .replace(/[_\s]+/g, '-');
1839 if (serverErrorMessage) {
1840 throw _errorWithCustomMessage(auth, authError, serverErrorMessage);
1841 }
1842 else {
1843 _fail(auth, authError);
1844 }
1845 }
1846 return [3 /*break*/, 5];
1847 case 4:
1848 e_1 = _b.sent();
1849 if (e_1 instanceof FirebaseError) {
1850 throw e_1;
1851 }
1852 _fail(auth, "network-request-failed" /* NETWORK_REQUEST_FAILED */);
1853 return [3 /*break*/, 5];
1854 case 5: return [2 /*return*/];
1855 }
1856 });
1857 });
1858}
1859function _performSignInRequest(auth, method, path, request, customErrorMap) {
1860 if (customErrorMap === void 0) { customErrorMap = {}; }
1861 return __awaiter(this, void 0, void 0, function () {
1862 var serverResponse;
1863 return __generator(this, function (_a) {
1864 switch (_a.label) {
1865 case 0: return [4 /*yield*/, _performApiRequest(auth, method, path, request, customErrorMap)];
1866 case 1:
1867 serverResponse = (_a.sent());
1868 if ('mfaPendingCredential' in serverResponse) {
1869 _fail(auth, "multi-factor-auth-required" /* MFA_REQUIRED */, {
1870 _serverResponse: serverResponse
1871 });
1872 }
1873 return [2 /*return*/, serverResponse];
1874 }
1875 });
1876 });
1877}
1878function _getFinalTarget(auth, host, path, query) {
1879 var base = "" + host + path + "?" + query;
1880 if (!auth.config.emulator) {
1881 return auth.config.apiScheme + "://" + base;
1882 }
1883 return _emulatorUrl(auth.config, base);
1884}
1885var NetworkTimeout = /** @class */ (function () {
1886 function NetworkTimeout(auth) {
1887 var _this = this;
1888 this.auth = auth;
1889 // Node timers and browser timers are fundamentally incompatible, but we
1890 // don't care about the value here
1891 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1892 this.timer = null;
1893 this.promise = new Promise(function (_, reject) {
1894 _this.timer = setTimeout(function () {
1895 return reject(_createError(_this.auth, "network-request-failed" /* NETWORK_REQUEST_FAILED */));
1896 }, DEFAULT_API_TIMEOUT_MS.get());
1897 });
1898 }
1899 NetworkTimeout.prototype.clearNetworkTimeout = function () {
1900 clearTimeout(this.timer);
1901 };
1902 return NetworkTimeout;
1903}());
1904function _makeTaggedError(auth, code, response) {
1905 var errorParams = {
1906 appName: auth.name
1907 };
1908 if (response.email) {
1909 errorParams.email = response.email;
1910 }
1911 if (response.phoneNumber) {
1912 errorParams.phoneNumber = response.phoneNumber;
1913 }
1914 var error = _createError(auth, code, errorParams);
1915 // We know customData is defined on error because errorParams is defined
1916 error.customData._tokenResponse = response;
1917 return error;
1918}
1919
1920/**
1921 * @license
1922 * Copyright 2020 Google LLC
1923 *
1924 * Licensed under the Apache License, Version 2.0 (the "License");
1925 * you may not use this file except in compliance with the License.
1926 * You may obtain a copy of the License at
1927 *
1928 * http://www.apache.org/licenses/LICENSE-2.0
1929 *
1930 * Unless required by applicable law or agreed to in writing, software
1931 * distributed under the License is distributed on an "AS IS" BASIS,
1932 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1933 * See the License for the specific language governing permissions and
1934 * limitations under the License.
1935 */
1936function deleteAccount(auth, request) {
1937 return __awaiter(this, void 0, void 0, function () {
1938 return __generator(this, function (_a) {
1939 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:delete" /* DELETE_ACCOUNT */, request)];
1940 });
1941 });
1942}
1943function deleteLinkedAccounts(auth, request) {
1944 return __awaiter(this, void 0, void 0, function () {
1945 return __generator(this, function (_a) {
1946 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, request)];
1947 });
1948 });
1949}
1950function getAccountInfo(auth, request) {
1951 return __awaiter(this, void 0, void 0, function () {
1952 return __generator(this, function (_a) {
1953 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:lookup" /* GET_ACCOUNT_INFO */, request)];
1954 });
1955 });
1956}
1957
1958/**
1959 * @license
1960 * Copyright 2020 Google LLC
1961 *
1962 * Licensed under the Apache License, Version 2.0 (the "License");
1963 * you may not use this file except in compliance with the License.
1964 * You may obtain a copy of the License at
1965 *
1966 * http://www.apache.org/licenses/LICENSE-2.0
1967 *
1968 * Unless required by applicable law or agreed to in writing, software
1969 * distributed under the License is distributed on an "AS IS" BASIS,
1970 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1971 * See the License for the specific language governing permissions and
1972 * limitations under the License.
1973 */
1974function utcTimestampToDateString(utcTimestamp) {
1975 if (!utcTimestamp) {
1976 return undefined;
1977 }
1978 try {
1979 // Convert to date object.
1980 var date = new Date(Number(utcTimestamp));
1981 // Test date is valid.
1982 if (!isNaN(date.getTime())) {
1983 // Convert to UTC date string.
1984 return date.toUTCString();
1985 }
1986 }
1987 catch (e) {
1988 // Do nothing. undefined will be returned.
1989 }
1990 return undefined;
1991}
1992
1993/**
1994 * @license
1995 * Copyright 2020 Google LLC
1996 *
1997 * Licensed under the Apache License, Version 2.0 (the "License");
1998 * you may not use this file except in compliance with the License.
1999 * You may obtain a copy of the License at
2000 *
2001 * http://www.apache.org/licenses/LICENSE-2.0
2002 *
2003 * Unless required by applicable law or agreed to in writing, software
2004 * distributed under the License is distributed on an "AS IS" BASIS,
2005 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2006 * See the License for the specific language governing permissions and
2007 * limitations under the License.
2008 */
2009/**
2010 * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.
2011 *
2012 * @remarks
2013 * Returns the current token if it has not expired or if it will not expire in the next five
2014 * minutes. Otherwise, this will refresh the token and return a new one.
2015 *
2016 * @param user - The user.
2017 * @param forceRefresh - Force refresh regardless of token expiration.
2018 *
2019 * @public
2020 */
2021function getIdToken(user, forceRefresh) {
2022 if (forceRefresh === void 0) { forceRefresh = false; }
2023 return getModularInstance(user).getIdToken(forceRefresh);
2024}
2025/**
2026 * Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.
2027 *
2028 * @remarks
2029 * Returns the current token if it has not expired or if it will not expire in the next five
2030 * minutes. Otherwise, this will refresh the token and return a new one.
2031 *
2032 * @param user - The user.
2033 * @param forceRefresh - Force refresh regardless of token expiration.
2034 *
2035 * @public
2036 */
2037function getIdTokenResult(user, forceRefresh) {
2038 if (forceRefresh === void 0) { forceRefresh = false; }
2039 return __awaiter(this, void 0, void 0, function () {
2040 var userInternal, token, claims, firebase, signInProvider;
2041 return __generator(this, function (_a) {
2042 switch (_a.label) {
2043 case 0:
2044 userInternal = getModularInstance(user);
2045 return [4 /*yield*/, userInternal.getIdToken(forceRefresh)];
2046 case 1:
2047 token = _a.sent();
2048 claims = _parseToken(token);
2049 _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, "internal-error" /* INTERNAL_ERROR */);
2050 firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;
2051 signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];
2052 return [2 /*return*/, {
2053 claims: claims,
2054 token: token,
2055 authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),
2056 issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),
2057 expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),
2058 signInProvider: signInProvider || null,
2059 signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null
2060 }];
2061 }
2062 });
2063 });
2064}
2065function secondsStringToMilliseconds(seconds) {
2066 return Number(seconds) * 1000;
2067}
2068function _parseToken(token) {
2069 var _a = token.split('.'), algorithm = _a[0], payload = _a[1], signature = _a[2];
2070 if (algorithm === undefined ||
2071 payload === undefined ||
2072 signature === undefined) {
2073 _logError('JWT malformed, contained fewer than 3 sections');
2074 return null;
2075 }
2076 try {
2077 var decoded = base64Decode(payload);
2078 if (!decoded) {
2079 _logError('Failed to decode base64 JWT payload');
2080 return null;
2081 }
2082 return JSON.parse(decoded);
2083 }
2084 catch (e) {
2085 _logError('Caught error parsing JWT payload as JSON', e);
2086 return null;
2087 }
2088}
2089/**
2090 * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.
2091 */
2092function _tokenExpiresIn(token) {
2093 var parsedToken = _parseToken(token);
2094 _assert(parsedToken, "internal-error" /* INTERNAL_ERROR */);
2095 _assert(typeof parsedToken.exp !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
2096 _assert(typeof parsedToken.iat !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
2097 return Number(parsedToken.exp) - Number(parsedToken.iat);
2098}
2099
2100/**
2101 * @license
2102 * Copyright 2020 Google LLC
2103 *
2104 * Licensed under the Apache License, Version 2.0 (the "License");
2105 * you may not use this file except in compliance with the License.
2106 * You may obtain a copy of the License at
2107 *
2108 * http://www.apache.org/licenses/LICENSE-2.0
2109 *
2110 * Unless required by applicable law or agreed to in writing, software
2111 * distributed under the License is distributed on an "AS IS" BASIS,
2112 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2113 * See the License for the specific language governing permissions and
2114 * limitations under the License.
2115 */
2116function _logoutIfInvalidated(user, promise, bypassAuthState) {
2117 if (bypassAuthState === void 0) { bypassAuthState = false; }
2118 return __awaiter(this, void 0, void 0, function () {
2119 var e_1;
2120 return __generator(this, function (_a) {
2121 switch (_a.label) {
2122 case 0:
2123 if (bypassAuthState) {
2124 return [2 /*return*/, promise];
2125 }
2126 _a.label = 1;
2127 case 1:
2128 _a.trys.push([1, 3, , 6]);
2129 return [4 /*yield*/, promise];
2130 case 2: return [2 /*return*/, _a.sent()];
2131 case 3:
2132 e_1 = _a.sent();
2133 if (!(e_1 instanceof FirebaseError && isUserInvalidated(e_1))) return [3 /*break*/, 5];
2134 if (!(user.auth.currentUser === user)) return [3 /*break*/, 5];
2135 return [4 /*yield*/, user.auth.signOut()];
2136 case 4:
2137 _a.sent();
2138 _a.label = 5;
2139 case 5: throw e_1;
2140 case 6: return [2 /*return*/];
2141 }
2142 });
2143 });
2144}
2145function isUserInvalidated(_a) {
2146 var code = _a.code;
2147 return (code === "auth/" + "user-disabled" /* USER_DISABLED */ ||
2148 code === "auth/" + "user-token-expired" /* TOKEN_EXPIRED */);
2149}
2150
2151/**
2152 * @license
2153 * Copyright 2020 Google LLC
2154 *
2155 * Licensed under the Apache License, Version 2.0 (the "License");
2156 * you may not use this file except in compliance with the License.
2157 * You may obtain a copy of the License at
2158 *
2159 * http://www.apache.org/licenses/LICENSE-2.0
2160 *
2161 * Unless required by applicable law or agreed to in writing, software
2162 * distributed under the License is distributed on an "AS IS" BASIS,
2163 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2164 * See the License for the specific language governing permissions and
2165 * limitations under the License.
2166 */
2167var ProactiveRefresh = /** @class */ (function () {
2168 function ProactiveRefresh(user) {
2169 this.user = user;
2170 this.isRunning = false;
2171 // Node timers and browser timers return fundamentally different types.
2172 // We don't actually care what the value is but TS won't accept unknown and
2173 // we can't cast properly in both environments.
2174 // eslint-disable-next-line @typescript-eslint/no-explicit-any
2175 this.timerId = null;
2176 this.errorBackoff = 30000 /* RETRY_BACKOFF_MIN */;
2177 }
2178 ProactiveRefresh.prototype._start = function () {
2179 if (this.isRunning) {
2180 return;
2181 }
2182 this.isRunning = true;
2183 this.schedule();
2184 };
2185 ProactiveRefresh.prototype._stop = function () {
2186 if (!this.isRunning) {
2187 return;
2188 }
2189 this.isRunning = false;
2190 if (this.timerId !== null) {
2191 clearTimeout(this.timerId);
2192 }
2193 };
2194 ProactiveRefresh.prototype.getInterval = function (wasError) {
2195 var _a;
2196 if (wasError) {
2197 var interval = this.errorBackoff;
2198 this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* RETRY_BACKOFF_MAX */);
2199 return interval;
2200 }
2201 else {
2202 // Reset the error backoff
2203 this.errorBackoff = 30000 /* RETRY_BACKOFF_MIN */;
2204 var expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;
2205 var interval = expTime - Date.now() - 300000 /* OFFSET */;
2206 return Math.max(0, interval);
2207 }
2208 };
2209 ProactiveRefresh.prototype.schedule = function (wasError) {
2210 var _this = this;
2211 if (wasError === void 0) { wasError = false; }
2212 if (!this.isRunning) {
2213 // Just in case...
2214 return;
2215 }
2216 var interval = this.getInterval(wasError);
2217 this.timerId = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
2218 return __generator(this, function (_a) {
2219 switch (_a.label) {
2220 case 0: return [4 /*yield*/, this.iteration()];
2221 case 1:
2222 _a.sent();
2223 return [2 /*return*/];
2224 }
2225 });
2226 }); }, interval);
2227 };
2228 ProactiveRefresh.prototype.iteration = function () {
2229 return __awaiter(this, void 0, void 0, function () {
2230 var e_1;
2231 return __generator(this, function (_a) {
2232 switch (_a.label) {
2233 case 0:
2234 _a.trys.push([0, 2, , 3]);
2235 return [4 /*yield*/, this.user.getIdToken(true)];
2236 case 1:
2237 _a.sent();
2238 return [3 /*break*/, 3];
2239 case 2:
2240 e_1 = _a.sent();
2241 // Only retry on network errors
2242 if (e_1.code === "auth/" + "network-request-failed" /* NETWORK_REQUEST_FAILED */) {
2243 this.schedule(/* wasError */ true);
2244 }
2245 return [2 /*return*/];
2246 case 3:
2247 this.schedule();
2248 return [2 /*return*/];
2249 }
2250 });
2251 });
2252 };
2253 return ProactiveRefresh;
2254}());
2255
2256/**
2257 * @license
2258 * Copyright 2020 Google LLC
2259 *
2260 * Licensed under the Apache License, Version 2.0 (the "License");
2261 * you may not use this file except in compliance with the License.
2262 * You may obtain a copy of the License at
2263 *
2264 * http://www.apache.org/licenses/LICENSE-2.0
2265 *
2266 * Unless required by applicable law or agreed to in writing, software
2267 * distributed under the License is distributed on an "AS IS" BASIS,
2268 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2269 * See the License for the specific language governing permissions and
2270 * limitations under the License.
2271 */
2272var UserMetadata = /** @class */ (function () {
2273 function UserMetadata(createdAt, lastLoginAt) {
2274 this.createdAt = createdAt;
2275 this.lastLoginAt = lastLoginAt;
2276 this._initializeTime();
2277 }
2278 UserMetadata.prototype._initializeTime = function () {
2279 this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);
2280 this.creationTime = utcTimestampToDateString(this.createdAt);
2281 };
2282 UserMetadata.prototype._copy = function (metadata) {
2283 this.createdAt = metadata.createdAt;
2284 this.lastLoginAt = metadata.lastLoginAt;
2285 this._initializeTime();
2286 };
2287 UserMetadata.prototype.toJSON = function () {
2288 return {
2289 createdAt: this.createdAt,
2290 lastLoginAt: this.lastLoginAt
2291 };
2292 };
2293 return UserMetadata;
2294}());
2295
2296/**
2297 * @license
2298 * Copyright 2019 Google LLC
2299 *
2300 * Licensed under the Apache License, Version 2.0 (the "License");
2301 * you may not use this file except in compliance with the License.
2302 * You may obtain a copy of the License at
2303 *
2304 * http://www.apache.org/licenses/LICENSE-2.0
2305 *
2306 * Unless required by applicable law or agreed to in writing, software
2307 * distributed under the License is distributed on an "AS IS" BASIS,
2308 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2309 * See the License for the specific language governing permissions and
2310 * limitations under the License.
2311 */
2312function _reloadWithoutSaving(user) {
2313 var _a;
2314 return __awaiter(this, void 0, void 0, function () {
2315 var auth, idToken, response, coreAccount, newProviderData, providerData, oldIsAnonymous, newIsAnonymous, isAnonymous, updates;
2316 return __generator(this, function (_b) {
2317 switch (_b.label) {
2318 case 0:
2319 auth = user.auth;
2320 return [4 /*yield*/, user.getIdToken()];
2321 case 1:
2322 idToken = _b.sent();
2323 return [4 /*yield*/, _logoutIfInvalidated(user, getAccountInfo(auth, { idToken: idToken }))];
2324 case 2:
2325 response = _b.sent();
2326 _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, "internal-error" /* INTERNAL_ERROR */);
2327 coreAccount = response.users[0];
2328 user._notifyReloadListener(coreAccount);
2329 newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)
2330 ? extractProviderData(coreAccount.providerUserInfo)
2331 : [];
2332 providerData = mergeProviderData(user.providerData, newProviderData);
2333 oldIsAnonymous = user.isAnonymous;
2334 newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);
2335 isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;
2336 updates = {
2337 uid: coreAccount.localId,
2338 displayName: coreAccount.displayName || null,
2339 photoURL: coreAccount.photoUrl || null,
2340 email: coreAccount.email || null,
2341 emailVerified: coreAccount.emailVerified || false,
2342 phoneNumber: coreAccount.phoneNumber || null,
2343 tenantId: coreAccount.tenantId || null,
2344 providerData: providerData,
2345 metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),
2346 isAnonymous: isAnonymous
2347 };
2348 Object.assign(user, updates);
2349 return [2 /*return*/];
2350 }
2351 });
2352 });
2353}
2354/**
2355 * Reloads user account data, if signed in.
2356 *
2357 * @param user - The user.
2358 *
2359 * @public
2360 */
2361function reload(user) {
2362 return __awaiter(this, void 0, void 0, function () {
2363 var userInternal;
2364 return __generator(this, function (_a) {
2365 switch (_a.label) {
2366 case 0:
2367 userInternal = getModularInstance(user);
2368 return [4 /*yield*/, _reloadWithoutSaving(userInternal)];
2369 case 1:
2370 _a.sent();
2371 // Even though the current user hasn't changed, update
2372 // current user will trigger a persistence update w/ the
2373 // new info.
2374 return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
2375 case 2:
2376 // Even though the current user hasn't changed, update
2377 // current user will trigger a persistence update w/ the
2378 // new info.
2379 _a.sent();
2380 userInternal.auth._notifyListenersIfCurrent(userInternal);
2381 return [2 /*return*/];
2382 }
2383 });
2384 });
2385}
2386function mergeProviderData(original, newData) {
2387 var deduped = original.filter(function (o) { return !newData.some(function (n) { return n.providerId === o.providerId; }); });
2388 return __spreadArray(__spreadArray([], deduped), newData);
2389}
2390function extractProviderData(providers) {
2391 return providers.map(function (_a) {
2392 var providerId = _a.providerId, provider = __rest(_a, ["providerId"]);
2393 return {
2394 providerId: providerId,
2395 uid: provider.rawId || '',
2396 displayName: provider.displayName || null,
2397 email: provider.email || null,
2398 phoneNumber: provider.phoneNumber || null,
2399 photoURL: provider.photoUrl || null
2400 };
2401 });
2402}
2403
2404/**
2405 * @license
2406 * Copyright 2020 Google LLC
2407 *
2408 * Licensed under the Apache License, Version 2.0 (the "License");
2409 * you may not use this file except in compliance with the License.
2410 * You may obtain a copy of the License at
2411 *
2412 * http://www.apache.org/licenses/LICENSE-2.0
2413 *
2414 * Unless required by applicable law or agreed to in writing, software
2415 * distributed under the License is distributed on an "AS IS" BASIS,
2416 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2417 * See the License for the specific language governing permissions and
2418 * limitations under the License.
2419 */
2420function requestStsToken(auth, refreshToken) {
2421 return __awaiter(this, void 0, void 0, function () {
2422 var response;
2423 var _this = this;
2424 return __generator(this, function (_a) {
2425 switch (_a.label) {
2426 case 0: return [4 /*yield*/, _performFetchWithErrorHandling(auth, {}, function () { return __awaiter(_this, void 0, void 0, function () {
2427 var body, _a, tokenApiHost, apiKey, url, headers;
2428 return __generator(this, function (_b) {
2429 switch (_b.label) {
2430 case 0:
2431 body = querystring({
2432 'grant_type': 'refresh_token',
2433 'refresh_token': refreshToken
2434 }).slice(1);
2435 _a = auth.config, tokenApiHost = _a.tokenApiHost, apiKey = _a.apiKey;
2436 url = _getFinalTarget(auth, tokenApiHost, "/v1/token" /* TOKEN */, "key=" + apiKey);
2437 return [4 /*yield*/, auth._getAdditionalHeaders()];
2438 case 1:
2439 headers = _b.sent();
2440 headers["Content-Type" /* CONTENT_TYPE */] = 'application/x-www-form-urlencoded';
2441 return [2 /*return*/, FetchProvider.fetch()(url, {
2442 method: "POST" /* POST */,
2443 headers: headers,
2444 body: body
2445 })];
2446 }
2447 });
2448 }); })];
2449 case 1:
2450 response = _a.sent();
2451 // The response comes back in snake_case. Convert to camel:
2452 return [2 /*return*/, {
2453 accessToken: response.access_token,
2454 expiresIn: response.expires_in,
2455 refreshToken: response.refresh_token
2456 }];
2457 }
2458 });
2459 });
2460}
2461
2462/**
2463 * @license
2464 * Copyright 2020 Google LLC
2465 *
2466 * Licensed under the Apache License, Version 2.0 (the "License");
2467 * you may not use this file except in compliance with the License.
2468 * You may obtain a copy of the License at
2469 *
2470 * http://www.apache.org/licenses/LICENSE-2.0
2471 *
2472 * Unless required by applicable law or agreed to in writing, software
2473 * distributed under the License is distributed on an "AS IS" BASIS,
2474 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2475 * See the License for the specific language governing permissions and
2476 * limitations under the License.
2477 */
2478/**
2479 * We need to mark this class as internal explicitly to exclude it in the public typings, because
2480 * it references AuthInternal which has a circular dependency with UserInternal.
2481 *
2482 * @internal
2483 */
2484var StsTokenManager = /** @class */ (function () {
2485 function StsTokenManager() {
2486 this.refreshToken = null;
2487 this.accessToken = null;
2488 this.expirationTime = null;
2489 }
2490 Object.defineProperty(StsTokenManager.prototype, "isExpired", {
2491 get: function () {
2492 return (!this.expirationTime ||
2493 Date.now() > this.expirationTime - 30000 /* TOKEN_REFRESH */);
2494 },
2495 enumerable: false,
2496 configurable: true
2497 });
2498 StsTokenManager.prototype.updateFromServerResponse = function (response) {
2499 _assert(response.idToken, "internal-error" /* INTERNAL_ERROR */);
2500 _assert(typeof response.idToken !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
2501 _assert(typeof response.refreshToken !== 'undefined', "internal-error" /* INTERNAL_ERROR */);
2502 var expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'
2503 ? Number(response.expiresIn)
2504 : _tokenExpiresIn(response.idToken);
2505 this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);
2506 };
2507 StsTokenManager.prototype.getToken = function (auth, forceRefresh) {
2508 if (forceRefresh === void 0) { forceRefresh = false; }
2509 return __awaiter(this, void 0, void 0, function () {
2510 return __generator(this, function (_a) {
2511 switch (_a.label) {
2512 case 0:
2513 _assert(!this.accessToken || this.refreshToken, auth, "user-token-expired" /* TOKEN_EXPIRED */);
2514 if (!forceRefresh && this.accessToken && !this.isExpired) {
2515 return [2 /*return*/, this.accessToken];
2516 }
2517 if (!this.refreshToken) return [3 /*break*/, 2];
2518 return [4 /*yield*/, this.refresh(auth, this.refreshToken)];
2519 case 1:
2520 _a.sent();
2521 return [2 /*return*/, this.accessToken];
2522 case 2: return [2 /*return*/, null];
2523 }
2524 });
2525 });
2526 };
2527 StsTokenManager.prototype.clearRefreshToken = function () {
2528 this.refreshToken = null;
2529 };
2530 StsTokenManager.prototype.refresh = function (auth, oldToken) {
2531 return __awaiter(this, void 0, void 0, function () {
2532 var _a, accessToken, refreshToken, expiresIn;
2533 return __generator(this, function (_b) {
2534 switch (_b.label) {
2535 case 0: return [4 /*yield*/, requestStsToken(auth, oldToken)];
2536 case 1:
2537 _a = _b.sent(), accessToken = _a.accessToken, refreshToken = _a.refreshToken, expiresIn = _a.expiresIn;
2538 this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));
2539 return [2 /*return*/];
2540 }
2541 });
2542 });
2543 };
2544 StsTokenManager.prototype.updateTokensAndExpiration = function (accessToken, refreshToken, expiresInSec) {
2545 this.refreshToken = refreshToken || null;
2546 this.accessToken = accessToken || null;
2547 this.expirationTime = Date.now() + expiresInSec * 1000;
2548 };
2549 StsTokenManager.fromJSON = function (appName, object) {
2550 var refreshToken = object.refreshToken, accessToken = object.accessToken, expirationTime = object.expirationTime;
2551 var manager = new StsTokenManager();
2552 if (refreshToken) {
2553 _assert(typeof refreshToken === 'string', "internal-error" /* INTERNAL_ERROR */, {
2554 appName: appName
2555 });
2556 manager.refreshToken = refreshToken;
2557 }
2558 if (accessToken) {
2559 _assert(typeof accessToken === 'string', "internal-error" /* INTERNAL_ERROR */, {
2560 appName: appName
2561 });
2562 manager.accessToken = accessToken;
2563 }
2564 if (expirationTime) {
2565 _assert(typeof expirationTime === 'number', "internal-error" /* INTERNAL_ERROR */, {
2566 appName: appName
2567 });
2568 manager.expirationTime = expirationTime;
2569 }
2570 return manager;
2571 };
2572 StsTokenManager.prototype.toJSON = function () {
2573 return {
2574 refreshToken: this.refreshToken,
2575 accessToken: this.accessToken,
2576 expirationTime: this.expirationTime
2577 };
2578 };
2579 StsTokenManager.prototype._assign = function (stsTokenManager) {
2580 this.accessToken = stsTokenManager.accessToken;
2581 this.refreshToken = stsTokenManager.refreshToken;
2582 this.expirationTime = stsTokenManager.expirationTime;
2583 };
2584 StsTokenManager.prototype._clone = function () {
2585 return Object.assign(new StsTokenManager(), this.toJSON());
2586 };
2587 StsTokenManager.prototype._performRefresh = function () {
2588 return debugFail('not implemented');
2589 };
2590 return StsTokenManager;
2591}());
2592
2593/**
2594 * @license
2595 * Copyright 2020 Google LLC
2596 *
2597 * Licensed under the Apache License, Version 2.0 (the "License");
2598 * you may not use this file except in compliance with the License.
2599 * You may obtain a copy of the License at
2600 *
2601 * http://www.apache.org/licenses/LICENSE-2.0
2602 *
2603 * Unless required by applicable law or agreed to in writing, software
2604 * distributed under the License is distributed on an "AS IS" BASIS,
2605 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2606 * See the License for the specific language governing permissions and
2607 * limitations under the License.
2608 */
2609function assertStringOrUndefined(assertion, appName) {
2610 _assert(typeof assertion === 'string' || typeof assertion === 'undefined', "internal-error" /* INTERNAL_ERROR */, { appName: appName });
2611}
2612var UserImpl = /** @class */ (function () {
2613 function UserImpl(_a) {
2614 var uid = _a.uid, auth = _a.auth, stsTokenManager = _a.stsTokenManager, opt = __rest(_a, ["uid", "auth", "stsTokenManager"]);
2615 // For the user object, provider is always Firebase.
2616 this.providerId = "firebase" /* FIREBASE */;
2617 this.proactiveRefresh = new ProactiveRefresh(this);
2618 this.reloadUserInfo = null;
2619 this.reloadListener = null;
2620 this.uid = uid;
2621 this.auth = auth;
2622 this.stsTokenManager = stsTokenManager;
2623 this.accessToken = stsTokenManager.accessToken;
2624 this.displayName = opt.displayName || null;
2625 this.email = opt.email || null;
2626 this.emailVerified = opt.emailVerified || false;
2627 this.phoneNumber = opt.phoneNumber || null;
2628 this.photoURL = opt.photoURL || null;
2629 this.isAnonymous = opt.isAnonymous || false;
2630 this.tenantId = opt.tenantId || null;
2631 this.providerData = opt.providerData ? __spreadArray([], opt.providerData) : [];
2632 this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);
2633 }
2634 UserImpl.prototype.getIdToken = function (forceRefresh) {
2635 return __awaiter(this, void 0, void 0, function () {
2636 var accessToken;
2637 return __generator(this, function (_a) {
2638 switch (_a.label) {
2639 case 0: return [4 /*yield*/, _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh))];
2640 case 1:
2641 accessToken = _a.sent();
2642 _assert(accessToken, this.auth, "internal-error" /* INTERNAL_ERROR */);
2643 if (!(this.accessToken !== accessToken)) return [3 /*break*/, 3];
2644 this.accessToken = accessToken;
2645 return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
2646 case 2:
2647 _a.sent();
2648 this.auth._notifyListenersIfCurrent(this);
2649 _a.label = 3;
2650 case 3: return [2 /*return*/, accessToken];
2651 }
2652 });
2653 });
2654 };
2655 UserImpl.prototype.getIdTokenResult = function (forceRefresh) {
2656 return getIdTokenResult(this, forceRefresh);
2657 };
2658 UserImpl.prototype.reload = function () {
2659 return reload(this);
2660 };
2661 UserImpl.prototype._assign = function (user) {
2662 if (this === user) {
2663 return;
2664 }
2665 _assert(this.uid === user.uid, this.auth, "internal-error" /* INTERNAL_ERROR */);
2666 this.displayName = user.displayName;
2667 this.photoURL = user.photoURL;
2668 this.email = user.email;
2669 this.emailVerified = user.emailVerified;
2670 this.phoneNumber = user.phoneNumber;
2671 this.isAnonymous = user.isAnonymous;
2672 this.tenantId = user.tenantId;
2673 this.providerData = user.providerData.map(function (userInfo) { return (__assign({}, userInfo)); });
2674 this.metadata._copy(user.metadata);
2675 this.stsTokenManager._assign(user.stsTokenManager);
2676 };
2677 UserImpl.prototype._clone = function (auth) {
2678 return new UserImpl(__assign(__assign({}, this), { auth: auth, stsTokenManager: this.stsTokenManager._clone() }));
2679 };
2680 UserImpl.prototype._onReload = function (callback) {
2681 // There should only ever be one listener, and that is a single instance of MultiFactorUser
2682 _assert(!this.reloadListener, this.auth, "internal-error" /* INTERNAL_ERROR */);
2683 this.reloadListener = callback;
2684 if (this.reloadUserInfo) {
2685 this._notifyReloadListener(this.reloadUserInfo);
2686 this.reloadUserInfo = null;
2687 }
2688 };
2689 UserImpl.prototype._notifyReloadListener = function (userInfo) {
2690 if (this.reloadListener) {
2691 this.reloadListener(userInfo);
2692 }
2693 else {
2694 // If no listener is subscribed yet, save the result so it's available when they do subscribe
2695 this.reloadUserInfo = userInfo;
2696 }
2697 };
2698 UserImpl.prototype._startProactiveRefresh = function () {
2699 this.proactiveRefresh._start();
2700 };
2701 UserImpl.prototype._stopProactiveRefresh = function () {
2702 this.proactiveRefresh._stop();
2703 };
2704 UserImpl.prototype._updateTokensIfNecessary = function (response, reload) {
2705 if (reload === void 0) { reload = false; }
2706 return __awaiter(this, void 0, void 0, function () {
2707 var tokensRefreshed;
2708 return __generator(this, function (_a) {
2709 switch (_a.label) {
2710 case 0:
2711 tokensRefreshed = false;
2712 if (response.idToken &&
2713 response.idToken !== this.stsTokenManager.accessToken) {
2714 this.stsTokenManager.updateFromServerResponse(response);
2715 tokensRefreshed = true;
2716 }
2717 if (!reload) return [3 /*break*/, 2];
2718 return [4 /*yield*/, _reloadWithoutSaving(this)];
2719 case 1:
2720 _a.sent();
2721 _a.label = 2;
2722 case 2: return [4 /*yield*/, this.auth._persistUserIfCurrent(this)];
2723 case 3:
2724 _a.sent();
2725 if (tokensRefreshed) {
2726 this.auth._notifyListenersIfCurrent(this);
2727 }
2728 return [2 /*return*/];
2729 }
2730 });
2731 });
2732 };
2733 UserImpl.prototype.delete = function () {
2734 return __awaiter(this, void 0, void 0, function () {
2735 var idToken;
2736 return __generator(this, function (_a) {
2737 switch (_a.label) {
2738 case 0: return [4 /*yield*/, this.getIdToken()];
2739 case 1:
2740 idToken = _a.sent();
2741 return [4 /*yield*/, _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken: idToken }))];
2742 case 2:
2743 _a.sent();
2744 this.stsTokenManager.clearRefreshToken();
2745 // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()
2746 // cancels pending actions...
2747 return [2 /*return*/, this.auth.signOut()];
2748 }
2749 });
2750 });
2751 };
2752 UserImpl.prototype.toJSON = function () {
2753 return __assign(__assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(function (userInfo) { return (__assign({}, userInfo)); }), stsTokenManager: this.stsTokenManager.toJSON(),
2754 // Redirect event ID must be maintained in case there is a pending
2755 // redirect event.
2756 _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), {
2757 // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):
2758 apiKey: this.auth.config.apiKey, appName: this.auth.name });
2759 };
2760 Object.defineProperty(UserImpl.prototype, "refreshToken", {
2761 get: function () {
2762 return this.stsTokenManager.refreshToken || '';
2763 },
2764 enumerable: false,
2765 configurable: true
2766 });
2767 UserImpl._fromJSON = function (auth, object) {
2768 var _a, _b, _c, _d, _e, _f, _g, _h;
2769 var displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;
2770 var email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;
2771 var phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;
2772 var photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;
2773 var tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;
2774 var _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;
2775 var createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;
2776 var lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;
2777 var uid = object.uid, emailVerified = object.emailVerified, isAnonymous = object.isAnonymous, providerData = object.providerData, plainObjectTokenManager = object.stsTokenManager;
2778 _assert(uid && plainObjectTokenManager, auth, "internal-error" /* INTERNAL_ERROR */);
2779 var stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);
2780 _assert(typeof uid === 'string', auth, "internal-error" /* INTERNAL_ERROR */);
2781 assertStringOrUndefined(displayName, auth.name);
2782 assertStringOrUndefined(email, auth.name);
2783 _assert(typeof emailVerified === 'boolean', auth, "internal-error" /* INTERNAL_ERROR */);
2784 _assert(typeof isAnonymous === 'boolean', auth, "internal-error" /* INTERNAL_ERROR */);
2785 assertStringOrUndefined(phoneNumber, auth.name);
2786 assertStringOrUndefined(photoURL, auth.name);
2787 assertStringOrUndefined(tenantId, auth.name);
2788 assertStringOrUndefined(_redirectEventId, auth.name);
2789 assertStringOrUndefined(createdAt, auth.name);
2790 assertStringOrUndefined(lastLoginAt, auth.name);
2791 var user = new UserImpl({
2792 uid: uid,
2793 auth: auth,
2794 email: email,
2795 emailVerified: emailVerified,
2796 displayName: displayName,
2797 isAnonymous: isAnonymous,
2798 photoURL: photoURL,
2799 phoneNumber: phoneNumber,
2800 tenantId: tenantId,
2801 stsTokenManager: stsTokenManager,
2802 createdAt: createdAt,
2803 lastLoginAt: lastLoginAt
2804 });
2805 if (providerData && Array.isArray(providerData)) {
2806 user.providerData = providerData.map(function (userInfo) { return (__assign({}, userInfo)); });
2807 }
2808 if (_redirectEventId) {
2809 user._redirectEventId = _redirectEventId;
2810 }
2811 return user;
2812 };
2813 /**
2814 * Initialize a User from an idToken server response
2815 * @param auth
2816 * @param idTokenResponse
2817 */
2818 UserImpl._fromIdTokenResponse = function (auth, idTokenResponse, isAnonymous) {
2819 if (isAnonymous === void 0) { isAnonymous = false; }
2820 return __awaiter(this, void 0, void 0, function () {
2821 var stsTokenManager, user;
2822 return __generator(this, function (_a) {
2823 switch (_a.label) {
2824 case 0:
2825 stsTokenManager = new StsTokenManager();
2826 stsTokenManager.updateFromServerResponse(idTokenResponse);
2827 user = new UserImpl({
2828 uid: idTokenResponse.localId,
2829 auth: auth,
2830 stsTokenManager: stsTokenManager,
2831 isAnonymous: isAnonymous
2832 });
2833 // Updates the user info and data and resolves with a user instance.
2834 return [4 /*yield*/, _reloadWithoutSaving(user)];
2835 case 1:
2836 // Updates the user info and data and resolves with a user instance.
2837 _a.sent();
2838 return [2 /*return*/, user];
2839 }
2840 });
2841 });
2842 };
2843 return UserImpl;
2844}());
2845
2846/**
2847 * @license
2848 * Copyright 2019 Google LLC
2849 *
2850 * Licensed under the Apache License, Version 2.0 (the "License");
2851 * you may not use this file except in compliance with the License.
2852 * You may obtain a copy of the License at
2853 *
2854 * http://www.apache.org/licenses/LICENSE-2.0
2855 *
2856 * Unless required by applicable law or agreed to in writing, software
2857 * distributed under the License is distributed on an "AS IS" BASIS,
2858 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2859 * See the License for the specific language governing permissions and
2860 * limitations under the License.
2861 */
2862var InMemoryPersistence = /** @class */ (function () {
2863 function InMemoryPersistence() {
2864 this.type = "NONE" /* NONE */;
2865 this.storage = {};
2866 }
2867 InMemoryPersistence.prototype._isAvailable = function () {
2868 return __awaiter(this, void 0, void 0, function () {
2869 return __generator(this, function (_a) {
2870 return [2 /*return*/, true];
2871 });
2872 });
2873 };
2874 InMemoryPersistence.prototype._set = function (key, value) {
2875 return __awaiter(this, void 0, void 0, function () {
2876 return __generator(this, function (_a) {
2877 this.storage[key] = value;
2878 return [2 /*return*/];
2879 });
2880 });
2881 };
2882 InMemoryPersistence.prototype._get = function (key) {
2883 return __awaiter(this, void 0, void 0, function () {
2884 var value;
2885 return __generator(this, function (_a) {
2886 value = this.storage[key];
2887 return [2 /*return*/, value === undefined ? null : value];
2888 });
2889 });
2890 };
2891 InMemoryPersistence.prototype._remove = function (key) {
2892 return __awaiter(this, void 0, void 0, function () {
2893 return __generator(this, function (_a) {
2894 delete this.storage[key];
2895 return [2 /*return*/];
2896 });
2897 });
2898 };
2899 InMemoryPersistence.prototype._addListener = function (_key, _listener) {
2900 // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
2901 return;
2902 };
2903 InMemoryPersistence.prototype._removeListener = function (_key, _listener) {
2904 // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers
2905 return;
2906 };
2907 InMemoryPersistence.type = 'NONE';
2908 return InMemoryPersistence;
2909}());
2910/**
2911 * An implementation of {@link Persistence} of type 'NONE'.
2912 *
2913 * @public
2914 */
2915var inMemoryPersistence = InMemoryPersistence;
2916
2917/**
2918 * @license
2919 * Copyright 2019 Google LLC
2920 *
2921 * Licensed under the Apache License, Version 2.0 (the "License");
2922 * you may not use this file except in compliance with the License.
2923 * You may obtain a copy of the License at
2924 *
2925 * http://www.apache.org/licenses/LICENSE-2.0
2926 *
2927 * Unless required by applicable law or agreed to in writing, software
2928 * distributed under the License is distributed on an "AS IS" BASIS,
2929 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2930 * See the License for the specific language governing permissions and
2931 * limitations under the License.
2932 */
2933function _persistenceKeyName(key, apiKey, appName) {
2934 return "firebase" /* PERSISTENCE */ + ":" + key + ":" + apiKey + ":" + appName;
2935}
2936var PersistenceUserManager = /** @class */ (function () {
2937 function PersistenceUserManager(persistence, auth, userKey) {
2938 this.persistence = persistence;
2939 this.auth = auth;
2940 this.userKey = userKey;
2941 var _a = this.auth, config = _a.config, name = _a.name;
2942 this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);
2943 this.fullPersistenceKey = _persistenceKeyName("persistence" /* PERSISTENCE_USER */, config.apiKey, name);
2944 this.boundEventHandler = auth._onStorageEvent.bind(auth);
2945 this.persistence._addListener(this.fullUserKey, this.boundEventHandler);
2946 }
2947 PersistenceUserManager.prototype.setCurrentUser = function (user) {
2948 return this.persistence._set(this.fullUserKey, user.toJSON());
2949 };
2950 PersistenceUserManager.prototype.getCurrentUser = function () {
2951 return __awaiter(this, void 0, void 0, function () {
2952 var blob;
2953 return __generator(this, function (_a) {
2954 switch (_a.label) {
2955 case 0: return [4 /*yield*/, this.persistence._get(this.fullUserKey)];
2956 case 1:
2957 blob = _a.sent();
2958 return [2 /*return*/, blob ? UserImpl._fromJSON(this.auth, blob) : null];
2959 }
2960 });
2961 });
2962 };
2963 PersistenceUserManager.prototype.removeCurrentUser = function () {
2964 return this.persistence._remove(this.fullUserKey);
2965 };
2966 PersistenceUserManager.prototype.savePersistenceForRedirect = function () {
2967 return this.persistence._set(this.fullPersistenceKey, this.persistence.type);
2968 };
2969 PersistenceUserManager.prototype.setPersistence = function (newPersistence) {
2970 return __awaiter(this, void 0, void 0, function () {
2971 var currentUser;
2972 return __generator(this, function (_a) {
2973 switch (_a.label) {
2974 case 0:
2975 if (this.persistence === newPersistence) {
2976 return [2 /*return*/];
2977 }
2978 return [4 /*yield*/, this.getCurrentUser()];
2979 case 1:
2980 currentUser = _a.sent();
2981 return [4 /*yield*/, this.removeCurrentUser()];
2982 case 2:
2983 _a.sent();
2984 this.persistence = newPersistence;
2985 if (currentUser) {
2986 return [2 /*return*/, this.setCurrentUser(currentUser)];
2987 }
2988 return [2 /*return*/];
2989 }
2990 });
2991 });
2992 };
2993 PersistenceUserManager.prototype.delete = function () {
2994 this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);
2995 };
2996 PersistenceUserManager.create = function (auth, persistenceHierarchy, userKey) {
2997 if (userKey === void 0) { userKey = "authUser" /* AUTH_USER */; }
2998 return __awaiter(this, void 0, void 0, function () {
2999 var availablePersistences, selectedPersistence, key, userToMigrate, _i, persistenceHierarchy_1, persistence, blob, user, migrationHierarchy;
3000 var _this = this;
3001 return __generator(this, function (_b) {
3002 switch (_b.label) {
3003 case 0:
3004 if (!persistenceHierarchy.length) {
3005 return [2 /*return*/, new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey)];
3006 }
3007 return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return __awaiter(_this, void 0, void 0, function () {
3008 return __generator(this, function (_a) {
3009 switch (_a.label) {
3010 case 0: return [4 /*yield*/, persistence._isAvailable()];
3011 case 1:
3012 if (_a.sent()) {
3013 return [2 /*return*/, persistence];
3014 }
3015 return [2 /*return*/, undefined];
3016 }
3017 });
3018 }); }))];
3019 case 1:
3020 availablePersistences = (_b.sent()).filter(function (persistence) { return persistence; });
3021 selectedPersistence = availablePersistences[0] ||
3022 _getInstance(inMemoryPersistence);
3023 key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);
3024 userToMigrate = null;
3025 _i = 0, persistenceHierarchy_1 = persistenceHierarchy;
3026 _b.label = 2;
3027 case 2:
3028 if (!(_i < persistenceHierarchy_1.length)) return [3 /*break*/, 7];
3029 persistence = persistenceHierarchy_1[_i];
3030 _b.label = 3;
3031 case 3:
3032 _b.trys.push([3, 5, , 6]);
3033 return [4 /*yield*/, persistence._get(key)];
3034 case 4:
3035 blob = _b.sent();
3036 if (blob) {
3037 user = UserImpl._fromJSON(auth, blob);
3038 if (persistence !== selectedPersistence) {
3039 userToMigrate = user;
3040 }
3041 selectedPersistence = persistence;
3042 return [3 /*break*/, 7];
3043 }
3044 return [3 /*break*/, 6];
3045 case 5:
3046 _b.sent();
3047 return [3 /*break*/, 6];
3048 case 6:
3049 _i++;
3050 return [3 /*break*/, 2];
3051 case 7:
3052 migrationHierarchy = availablePersistences.filter(function (p) { return p._shouldAllowMigration; });
3053 // If the persistence does _not_ allow migration, just finish off here
3054 if (!selectedPersistence._shouldAllowMigration ||
3055 !migrationHierarchy.length) {
3056 return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
3057 }
3058 selectedPersistence = migrationHierarchy[0];
3059 if (!userToMigrate) return [3 /*break*/, 9];
3060 // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
3061 // we'll just let it bubble to surface the error.
3062 return [4 /*yield*/, selectedPersistence._set(key, userToMigrate.toJSON())];
3063 case 8:
3064 // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does
3065 // we'll just let it bubble to surface the error.
3066 _b.sent();
3067 _b.label = 9;
3068 case 9:
3069 // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
3070 // such as users getting stuck with a previous account after signing out and refreshing the tab.
3071 return [4 /*yield*/, Promise.all(persistenceHierarchy.map(function (persistence) { return __awaiter(_this, void 0, void 0, function () {
3072 return __generator(this, function (_b) {
3073 switch (_b.label) {
3074 case 0:
3075 if (!(persistence !== selectedPersistence)) return [3 /*break*/, 4];
3076 _b.label = 1;
3077 case 1:
3078 _b.trys.push([1, 3, , 4]);
3079 return [4 /*yield*/, persistence._remove(key)];
3080 case 2:
3081 _b.sent();
3082 return [3 /*break*/, 4];
3083 case 3:
3084 _b.sent();
3085 return [3 /*break*/, 4];
3086 case 4: return [2 /*return*/];
3087 }
3088 });
3089 }); }))];
3090 case 10:
3091 // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues
3092 // such as users getting stuck with a previous account after signing out and refreshing the tab.
3093 _b.sent();
3094 return [2 /*return*/, new PersistenceUserManager(selectedPersistence, auth, userKey)];
3095 }
3096 });
3097 });
3098 };
3099 return PersistenceUserManager;
3100}());
3101
3102/**
3103 * @license
3104 * Copyright 2020 Google LLC
3105 *
3106 * Licensed under the Apache License, Version 2.0 (the "License");
3107 * you may not use this file except in compliance with the License.
3108 * You may obtain a copy of the License at
3109 *
3110 * http://www.apache.org/licenses/LICENSE-2.0
3111 *
3112 * Unless required by applicable law or agreed to in writing, software
3113 * distributed under the License is distributed on an "AS IS" BASIS,
3114 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3115 * See the License for the specific language governing permissions and
3116 * limitations under the License.
3117 */
3118/**
3119 * Determine the browser for the purposes of reporting usage to the API
3120 */
3121function _getBrowserName(userAgent) {
3122 var ua = userAgent.toLowerCase();
3123 if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {
3124 return "Opera" /* OPERA */;
3125 }
3126 else if (_isIEMobile(ua)) {
3127 // Windows phone IEMobile browser.
3128 return "IEMobile" /* IEMOBILE */;
3129 }
3130 else if (ua.includes('msie') || ua.includes('trident/')) {
3131 return "IE" /* IE */;
3132 }
3133 else if (ua.includes('edge/')) {
3134 return "Edge" /* EDGE */;
3135 }
3136 else if (_isFirefox(ua)) {
3137 return "Firefox" /* FIREFOX */;
3138 }
3139 else if (ua.includes('silk/')) {
3140 return "Silk" /* SILK */;
3141 }
3142 else if (_isBlackBerry(ua)) {
3143 // Blackberry browser.
3144 return "Blackberry" /* BLACKBERRY */;
3145 }
3146 else if (_isWebOS(ua)) {
3147 // WebOS default browser.
3148 return "Webos" /* WEBOS */;
3149 }
3150 else if (_isSafari(ua)) {
3151 return "Safari" /* SAFARI */;
3152 }
3153 else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&
3154 !ua.includes('edge/')) {
3155 return "Chrome" /* CHROME */;
3156 }
3157 else if (_isAndroid(ua)) {
3158 // Android stock browser.
3159 return "Android" /* ANDROID */;
3160 }
3161 else {
3162 // Most modern browsers have name/version at end of user agent string.
3163 var re = /([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;
3164 var matches = userAgent.match(re);
3165 if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {
3166 return matches[1];
3167 }
3168 }
3169 return "Other" /* OTHER */;
3170}
3171function _isFirefox(ua) {
3172 if (ua === void 0) { ua = getUA(); }
3173 return /firefox\//i.test(ua);
3174}
3175function _isSafari(userAgent) {
3176 if (userAgent === void 0) { userAgent = getUA(); }
3177 var ua = userAgent.toLowerCase();
3178 return (ua.includes('safari/') &&
3179 !ua.includes('chrome/') &&
3180 !ua.includes('crios/') &&
3181 !ua.includes('android'));
3182}
3183function _isChromeIOS(ua) {
3184 if (ua === void 0) { ua = getUA(); }
3185 return /crios\//i.test(ua);
3186}
3187function _isIEMobile(ua) {
3188 if (ua === void 0) { ua = getUA(); }
3189 return /iemobile/i.test(ua);
3190}
3191function _isAndroid(ua) {
3192 if (ua === void 0) { ua = getUA(); }
3193 return /android/i.test(ua);
3194}
3195function _isBlackBerry(ua) {
3196 if (ua === void 0) { ua = getUA(); }
3197 return /blackberry/i.test(ua);
3198}
3199function _isWebOS(ua) {
3200 if (ua === void 0) { ua = getUA(); }
3201 return /webos/i.test(ua);
3202}
3203function _isIOS(ua) {
3204 if (ua === void 0) { ua = getUA(); }
3205 return /iphone|ipad|ipod/i.test(ua);
3206}
3207function _isIOS7Or8(ua) {
3208 if (ua === void 0) { ua = getUA(); }
3209 return (/(iPad|iPhone|iPod).*OS 7_\d/i.test(ua) ||
3210 /(iPad|iPhone|iPod).*OS 8_\d/i.test(ua));
3211}
3212function _isIOSStandalone(ua) {
3213 var _a;
3214 if (ua === void 0) { ua = getUA(); }
3215 return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);
3216}
3217function _isIE10() {
3218 return isIE() && document.documentMode === 10;
3219}
3220function _isMobileBrowser(ua) {
3221 if (ua === void 0) { ua = getUA(); }
3222 // TODO: implement getBrowserName equivalent for OS.
3223 return (_isIOS(ua) ||
3224 _isAndroid(ua) ||
3225 _isWebOS(ua) ||
3226 _isBlackBerry(ua) ||
3227 /windows phone/i.test(ua) ||
3228 _isIEMobile(ua));
3229}
3230function _isIframe() {
3231 try {
3232 // Check that the current window is not the top window.
3233 // If so, return true.
3234 return !!(window && window !== window.top);
3235 }
3236 catch (e) {
3237 return false;
3238 }
3239}
3240
3241/**
3242 * @license
3243 * Copyright 2020 Google LLC
3244 *
3245 * Licensed under the Apache License, Version 2.0 (the "License");
3246 * you may not use this file except in compliance with the License.
3247 * You may obtain a copy of the License at
3248 *
3249 * http://www.apache.org/licenses/LICENSE-2.0
3250 *
3251 * Unless required by applicable law or agreed to in writing, software
3252 * distributed under the License is distributed on an "AS IS" BASIS,
3253 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3254 * See the License for the specific language governing permissions and
3255 * limitations under the License.
3256 */
3257/*
3258 * Determine the SDK version string
3259 */
3260function _getClientVersion(clientPlatform, frameworks) {
3261 if (frameworks === void 0) { frameworks = []; }
3262 var reportedPlatform;
3263 switch (clientPlatform) {
3264 case "Browser" /* BROWSER */:
3265 // In a browser environment, report the browser name.
3266 reportedPlatform = _getBrowserName(getUA());
3267 break;
3268 case "Worker" /* WORKER */:
3269 // Technically a worker runs from a browser but we need to differentiate a
3270 // worker from a browser.
3271 // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.
3272 reportedPlatform = _getBrowserName(getUA()) + "-" + clientPlatform;
3273 break;
3274 default:
3275 reportedPlatform = clientPlatform;
3276 }
3277 var reportedFrameworks = frameworks.length
3278 ? frameworks.join(',')
3279 : 'FirebaseCore-web'; /* default value if no other framework is used */
3280 return reportedPlatform + "/" + "JsCore" /* CORE */ + "/" + SDK_VERSION + "/" + reportedFrameworks;
3281}
3282
3283/**
3284 * @license
3285 * Copyright 2022 Google LLC
3286 *
3287 * Licensed under the Apache License, Version 2.0 (the "License");
3288 * you may not use this file except in compliance with the License.
3289 * You may obtain a copy of the License at
3290 *
3291 * http://www.apache.org/licenses/LICENSE-2.0
3292 *
3293 * Unless required by applicable law or agreed to in writing, software
3294 * distributed under the License is distributed on an "AS IS" BASIS,
3295 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3296 * See the License for the specific language governing permissions and
3297 * limitations under the License.
3298 */
3299var AuthMiddlewareQueue = /** @class */ (function () {
3300 function AuthMiddlewareQueue(auth) {
3301 this.auth = auth;
3302 this.queue = [];
3303 }
3304 AuthMiddlewareQueue.prototype.pushCallback = function (callback, onAbort) {
3305 var _this = this;
3306 // The callback could be sync or async. Wrap it into a
3307 // function that is always async.
3308 var wrappedCallback = function (user) { return new Promise(function (resolve, reject) {
3309 try {
3310 var result = callback(user);
3311 // Either resolve with existing promise or wrap a non-promise
3312 // return value into a promise.
3313 resolve(result);
3314 }
3315 catch (e) {
3316 // Sync callback throws.
3317 reject(e);
3318 }
3319 }); };
3320 // Attach the onAbort if present
3321 wrappedCallback.onAbort = onAbort;
3322 this.queue.push(wrappedCallback);
3323 var index = this.queue.length - 1;
3324 return function () {
3325 // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb
3326 // indexing of other elements.
3327 _this.queue[index] = function () { return Promise.resolve(); };
3328 };
3329 };
3330 AuthMiddlewareQueue.prototype.runMiddleware = function (nextUser) {
3331 return __awaiter(this, void 0, void 0, function () {
3332 var onAbortStack, _i, _a, beforeStateCallback, e_1, _b, onAbortStack_1, onAbort;
3333 return __generator(this, function (_c) {
3334 switch (_c.label) {
3335 case 0:
3336 if (this.auth.currentUser === nextUser) {
3337 return [2 /*return*/];
3338 }
3339 onAbortStack = [];
3340 _c.label = 1;
3341 case 1:
3342 _c.trys.push([1, 6, , 7]);
3343 _i = 0, _a = this.queue;
3344 _c.label = 2;
3345 case 2:
3346 if (!(_i < _a.length)) return [3 /*break*/, 5];
3347 beforeStateCallback = _a[_i];
3348 return [4 /*yield*/, beforeStateCallback(nextUser)];
3349 case 3:
3350 _c.sent();
3351 // Only push the onAbort if the callback succeeds
3352 if (beforeStateCallback.onAbort) {
3353 onAbortStack.push(beforeStateCallback.onAbort);
3354 }
3355 _c.label = 4;
3356 case 4:
3357 _i++;
3358 return [3 /*break*/, 2];
3359 case 5: return [3 /*break*/, 7];
3360 case 6:
3361 e_1 = _c.sent();
3362 // Run all onAbort, with separate try/catch to ignore any errors and
3363 // continue
3364 onAbortStack.reverse();
3365 for (_b = 0, onAbortStack_1 = onAbortStack; _b < onAbortStack_1.length; _b++) {
3366 onAbort = onAbortStack_1[_b];
3367 try {
3368 onAbort();
3369 }
3370 catch (_) { /* swallow error */ }
3371 }
3372 throw this.auth._errorFactory.create("login-blocked" /* LOGIN_BLOCKED */, { originalMessage: e_1.message });
3373 case 7: return [2 /*return*/];
3374 }
3375 });
3376 });
3377 };
3378 return AuthMiddlewareQueue;
3379}());
3380
3381/**
3382 * @license
3383 * Copyright 2020 Google LLC
3384 *
3385 * Licensed under the Apache License, Version 2.0 (the "License");
3386 * you may not use this file except in compliance with the License.
3387 * You may obtain a copy of the License at
3388 *
3389 * http://www.apache.org/licenses/LICENSE-2.0
3390 *
3391 * Unless required by applicable law or agreed to in writing, software
3392 * distributed under the License is distributed on an "AS IS" BASIS,
3393 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3394 * See the License for the specific language governing permissions and
3395 * limitations under the License.
3396 */
3397var AuthImpl = /** @class */ (function () {
3398 function AuthImpl(app, heartbeatServiceProvider, config) {
3399 this.app = app;
3400 this.heartbeatServiceProvider = heartbeatServiceProvider;
3401 this.config = config;
3402 this.currentUser = null;
3403 this.emulatorConfig = null;
3404 this.operations = Promise.resolve();
3405 this.authStateSubscription = new Subscription(this);
3406 this.idTokenSubscription = new Subscription(this);
3407 this.beforeStateQueue = new AuthMiddlewareQueue(this);
3408 this.redirectUser = null;
3409 this.isProactiveRefreshEnabled = false;
3410 // Any network calls will set this to true and prevent subsequent emulator
3411 // initialization
3412 this._canInitEmulator = true;
3413 this._isInitialized = false;
3414 this._deleted = false;
3415 this._initializationPromise = null;
3416 this._popupRedirectResolver = null;
3417 this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;
3418 // Tracks the last notified UID for state change listeners to prevent
3419 // repeated calls to the callbacks. Undefined means it's never been
3420 // called, whereas null means it's been called with a signed out user
3421 this.lastNotifiedUid = undefined;
3422 this.languageCode = null;
3423 this.tenantId = null;
3424 this.settings = { appVerificationDisabledForTesting: false };
3425 this.frameworks = [];
3426 this.name = app.name;
3427 this.clientVersion = config.sdkClientVersion;
3428 }
3429 AuthImpl.prototype._initializeWithPersistence = function (persistenceHierarchy, popupRedirectResolver) {
3430 var _this = this;
3431 if (popupRedirectResolver) {
3432 this._popupRedirectResolver = _getInstance(popupRedirectResolver);
3433 }
3434 // Have to check for app deletion throughout initialization (after each
3435 // promise resolution)
3436 this._initializationPromise = this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
3437 var _a;
3438 var _b, _c;
3439 return __generator(this, function (_d) {
3440 switch (_d.label) {
3441 case 0:
3442 if (this._deleted) {
3443 return [2 /*return*/];
3444 }
3445 _a = this;
3446 return [4 /*yield*/, PersistenceUserManager.create(this, persistenceHierarchy)];
3447 case 1:
3448 _a.persistenceManager = _d.sent();
3449 if (this._deleted) {
3450 return [2 /*return*/];
3451 }
3452 if (!((_b = this._popupRedirectResolver) === null || _b === void 0 ? void 0 : _b._shouldInitProactively)) return [3 /*break*/, 5];
3453 _d.label = 2;
3454 case 2:
3455 _d.trys.push([2, 4, , 5]);
3456 return [4 /*yield*/, this._popupRedirectResolver._initialize(this)];
3457 case 3:
3458 _d.sent();
3459 return [3 /*break*/, 5];
3460 case 4:
3461 _d.sent();
3462 return [3 /*break*/, 5];
3463 case 5: return [4 /*yield*/, this.initializeCurrentUser(popupRedirectResolver)];
3464 case 6:
3465 _d.sent();
3466 this.lastNotifiedUid = ((_c = this.currentUser) === null || _c === void 0 ? void 0 : _c.uid) || null;
3467 if (this._deleted) {
3468 return [2 /*return*/];
3469 }
3470 this._isInitialized = true;
3471 return [2 /*return*/];
3472 }
3473 });
3474 }); });
3475 return this._initializationPromise;
3476 };
3477 /**
3478 * If the persistence is changed in another window, the user manager will let us know
3479 */
3480 AuthImpl.prototype._onStorageEvent = function () {
3481 return __awaiter(this, void 0, void 0, function () {
3482 var user;
3483 return __generator(this, function (_a) {
3484 switch (_a.label) {
3485 case 0:
3486 if (this._deleted) {
3487 return [2 /*return*/];
3488 }
3489 return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
3490 case 1:
3491 user = _a.sent();
3492 if (!this.currentUser && !user) {
3493 // No change, do nothing (was signed out and remained signed out).
3494 return [2 /*return*/];
3495 }
3496 if (!(this.currentUser && user && this.currentUser.uid === user.uid)) return [3 /*break*/, 3];
3497 // Data update, simply copy data changes.
3498 this._currentUser._assign(user);
3499 // If tokens changed from previous user tokens, this will trigger
3500 // notifyAuthListeners_.
3501 return [4 /*yield*/, this.currentUser.getIdToken()];
3502 case 2:
3503 // If tokens changed from previous user tokens, this will trigger
3504 // notifyAuthListeners_.
3505 _a.sent();
3506 return [2 /*return*/];
3507 case 3:
3508 // Update current Auth state. Either a new login or logout.
3509 // Skip blocking callbacks, they should not apply to a change in another tab.
3510 return [4 /*yield*/, this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true)];
3511 case 4:
3512 // Update current Auth state. Either a new login or logout.
3513 // Skip blocking callbacks, they should not apply to a change in another tab.
3514 _a.sent();
3515 return [2 /*return*/];
3516 }
3517 });
3518 });
3519 };
3520 AuthImpl.prototype.initializeCurrentUser = function (popupRedirectResolver) {
3521 var _a;
3522 return __awaiter(this, void 0, void 0, function () {
3523 var previouslyStoredUser, futureCurrentUser, needsTocheckMiddleware, redirectUserEventId, storedUserEventId, result, e_2;
3524 return __generator(this, function (_b) {
3525 switch (_b.label) {
3526 case 0: return [4 /*yield*/, this.assertedPersistence.getCurrentUser()];
3527 case 1:
3528 previouslyStoredUser = (_b.sent());
3529 futureCurrentUser = previouslyStoredUser;
3530 needsTocheckMiddleware = false;
3531 if (!(popupRedirectResolver && this.config.authDomain)) return [3 /*break*/, 4];
3532 return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
3533 case 2:
3534 _b.sent();
3535 redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;
3536 storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;
3537 return [4 /*yield*/, this.tryRedirectSignIn(popupRedirectResolver)];
3538 case 3:
3539 result = _b.sent();
3540 // If the stored user (i.e. the old "currentUser") has a redirectId that
3541 // matches the redirect user, then we want to initially sign in with the
3542 // new user object from result.
3543 // TODO(samgho): More thoroughly test all of this
3544 if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&
3545 (result === null || result === void 0 ? void 0 : result.user)) {
3546 futureCurrentUser = result.user;
3547 needsTocheckMiddleware = true;
3548 }
3549 _b.label = 4;
3550 case 4:
3551 // If no user in persistence, there is no current user. Set to null.
3552 if (!futureCurrentUser) {
3553 return [2 /*return*/, this.directlySetCurrentUser(null)];
3554 }
3555 if (!!futureCurrentUser._redirectEventId) return [3 /*break*/, 9];
3556 if (!needsTocheckMiddleware) return [3 /*break*/, 8];
3557 _b.label = 5;
3558 case 5:
3559 _b.trys.push([5, 7, , 8]);
3560 return [4 /*yield*/, this.beforeStateQueue.runMiddleware(futureCurrentUser)];
3561 case 6:
3562 _b.sent();
3563 return [3 /*break*/, 8];
3564 case 7:
3565 e_2 = _b.sent();
3566 futureCurrentUser = previouslyStoredUser;
3567 // We know this is available since the bit is only set when the
3568 // resolver is available
3569 this._popupRedirectResolver._overrideRedirectResult(this, function () { return Promise.reject(e_2); });
3570 return [3 /*break*/, 8];
3571 case 8:
3572 if (futureCurrentUser) {
3573 return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
3574 }
3575 else {
3576 return [2 /*return*/, this.directlySetCurrentUser(null)];
3577 }
3578 case 9:
3579 _assert(this._popupRedirectResolver, this, "argument-error" /* ARGUMENT_ERROR */);
3580 return [4 /*yield*/, this.getOrInitRedirectPersistenceManager()];
3581 case 10:
3582 _b.sent();
3583 // If the redirect user's event ID matches the current user's event ID,
3584 // DO NOT reload the current user, otherwise they'll be cleared from storage.
3585 // This is important for the reauthenticateWithRedirect() flow.
3586 if (this.redirectUser &&
3587 this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {
3588 return [2 /*return*/, this.directlySetCurrentUser(futureCurrentUser)];
3589 }
3590 return [2 /*return*/, this.reloadAndSetCurrentUserOrClear(futureCurrentUser)];
3591 }
3592 });
3593 });
3594 };
3595 AuthImpl.prototype.tryRedirectSignIn = function (redirectResolver) {
3596 return __awaiter(this, void 0, void 0, function () {
3597 var result;
3598 return __generator(this, function (_a) {
3599 switch (_a.label) {
3600 case 0:
3601 result = null;
3602 _a.label = 1;
3603 case 1:
3604 _a.trys.push([1, 3, , 5]);
3605 return [4 /*yield*/, this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true)];
3606 case 2:
3607 // We know this._popupRedirectResolver is set since redirectResolver
3608 // is passed in. The _completeRedirectFn expects the unwrapped extern.
3609 result = _a.sent();
3610 return [3 /*break*/, 5];
3611 case 3:
3612 _a.sent();
3613 // Swallow any errors here; the code can retrieve them in
3614 // getRedirectResult().
3615 return [4 /*yield*/, this._setRedirectUser(null)];
3616 case 4:
3617 // Swallow any errors here; the code can retrieve them in
3618 // getRedirectResult().
3619 _a.sent();
3620 return [3 /*break*/, 5];
3621 case 5: return [2 /*return*/, result];
3622 }
3623 });
3624 });
3625 };
3626 AuthImpl.prototype.reloadAndSetCurrentUserOrClear = function (user) {
3627 return __awaiter(this, void 0, void 0, function () {
3628 var e_4;
3629 return __generator(this, function (_a) {
3630 switch (_a.label) {
3631 case 0:
3632 _a.trys.push([0, 2, , 3]);
3633 return [4 /*yield*/, _reloadWithoutSaving(user)];
3634 case 1:
3635 _a.sent();
3636 return [3 /*break*/, 3];
3637 case 2:
3638 e_4 = _a.sent();
3639 if (e_4.code !== "auth/" + "network-request-failed" /* NETWORK_REQUEST_FAILED */) {
3640 // Something's wrong with the user's token. Log them out and remove
3641 // them from storage
3642 return [2 /*return*/, this.directlySetCurrentUser(null)];
3643 }
3644 return [3 /*break*/, 3];
3645 case 3: return [2 /*return*/, this.directlySetCurrentUser(user)];
3646 }
3647 });
3648 });
3649 };
3650 AuthImpl.prototype.useDeviceLanguage = function () {
3651 this.languageCode = _getUserLanguage();
3652 };
3653 AuthImpl.prototype._delete = function () {
3654 return __awaiter(this, void 0, void 0, function () {
3655 return __generator(this, function (_a) {
3656 this._deleted = true;
3657 return [2 /*return*/];
3658 });
3659 });
3660 };
3661 AuthImpl.prototype.updateCurrentUser = function (userExtern) {
3662 return __awaiter(this, void 0, void 0, function () {
3663 var user;
3664 return __generator(this, function (_a) {
3665 user = userExtern
3666 ? getModularInstance(userExtern)
3667 : null;
3668 if (user) {
3669 _assert(user.auth.config.apiKey === this.config.apiKey, this, "invalid-user-token" /* INVALID_AUTH */);
3670 }
3671 return [2 /*return*/, this._updateCurrentUser(user && user._clone(this))];
3672 });
3673 });
3674 };
3675 AuthImpl.prototype._updateCurrentUser = function (user, skipBeforeStateCallbacks) {
3676 if (skipBeforeStateCallbacks === void 0) { skipBeforeStateCallbacks = false; }
3677 return __awaiter(this, void 0, void 0, function () {
3678 var _this = this;
3679 return __generator(this, function (_a) {
3680 switch (_a.label) {
3681 case 0:
3682 if (this._deleted) {
3683 return [2 /*return*/];
3684 }
3685 if (user) {
3686 _assert(this.tenantId === user.tenantId, this, "tenant-id-mismatch" /* TENANT_ID_MISMATCH */);
3687 }
3688 if (!!skipBeforeStateCallbacks) return [3 /*break*/, 2];
3689 return [4 /*yield*/, this.beforeStateQueue.runMiddleware(user)];
3690 case 1:
3691 _a.sent();
3692 _a.label = 2;
3693 case 2: return [2 /*return*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
3694 return __generator(this, function (_a) {
3695 switch (_a.label) {
3696 case 0: return [4 /*yield*/, this.directlySetCurrentUser(user)];
3697 case 1:
3698 _a.sent();
3699 this.notifyAuthListeners();
3700 return [2 /*return*/];
3701 }
3702 });
3703 }); })];
3704 }
3705 });
3706 });
3707 };
3708 AuthImpl.prototype.signOut = function () {
3709 return __awaiter(this, void 0, void 0, function () {
3710 return __generator(this, function (_a) {
3711 switch (_a.label) {
3712 case 0:
3713 // Run first, to block _setRedirectUser() if any callbacks fail.
3714 return [4 /*yield*/, this.beforeStateQueue.runMiddleware(null)];
3715 case 1:
3716 // Run first, to block _setRedirectUser() if any callbacks fail.
3717 _a.sent();
3718 if (!(this.redirectPersistenceManager || this._popupRedirectResolver)) return [3 /*break*/, 3];
3719 return [4 /*yield*/, this._setRedirectUser(null)];
3720 case 2:
3721 _a.sent();
3722 _a.label = 3;
3723 case 3:
3724 // Prevent callbacks from being called again in _updateCurrentUser, as
3725 // they were already called in the first line.
3726 return [2 /*return*/, this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true)];
3727 }
3728 });
3729 });
3730 };
3731 AuthImpl.prototype.setPersistence = function (persistence) {
3732 var _this = this;
3733 return this.queue(function () { return __awaiter(_this, void 0, void 0, function () {
3734 return __generator(this, function (_a) {
3735 switch (_a.label) {
3736 case 0: return [4 /*yield*/, this.assertedPersistence.setPersistence(_getInstance(persistence))];
3737 case 1:
3738 _a.sent();
3739 return [2 /*return*/];
3740 }
3741 });
3742 }); });
3743 };
3744 AuthImpl.prototype._getPersistence = function () {
3745 return this.assertedPersistence.persistence.type;
3746 };
3747 AuthImpl.prototype._updateErrorMap = function (errorMap) {
3748 this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());
3749 };
3750 AuthImpl.prototype.onAuthStateChanged = function (nextOrObserver, error, completed) {
3751 return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);
3752 };
3753 AuthImpl.prototype.beforeAuthStateChanged = function (callback, onAbort) {
3754 return this.beforeStateQueue.pushCallback(callback, onAbort);
3755 };
3756 AuthImpl.prototype.onIdTokenChanged = function (nextOrObserver, error, completed) {
3757 return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);
3758 };
3759 AuthImpl.prototype.toJSON = function () {
3760 var _a;
3761 return {
3762 apiKey: this.config.apiKey,
3763 authDomain: this.config.authDomain,
3764 appName: this.name,
3765 currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()
3766 };
3767 };
3768 AuthImpl.prototype._setRedirectUser = function (user, popupRedirectResolver) {
3769 return __awaiter(this, void 0, void 0, function () {
3770 var redirectManager;
3771 return __generator(this, function (_a) {
3772 switch (_a.label) {
3773 case 0: return [4 /*yield*/, this.getOrInitRedirectPersistenceManager(popupRedirectResolver)];
3774 case 1:
3775 redirectManager = _a.sent();
3776 return [2 /*return*/, user === null
3777 ? redirectManager.removeCurrentUser()
3778 : redirectManager.setCurrentUser(user)];
3779 }
3780 });
3781 });
3782 };
3783 AuthImpl.prototype.getOrInitRedirectPersistenceManager = function (popupRedirectResolver) {
3784 return __awaiter(this, void 0, void 0, function () {
3785 var resolver, _a, _b;
3786 return __generator(this, function (_c) {
3787 switch (_c.label) {
3788 case 0:
3789 if (!!this.redirectPersistenceManager) return [3 /*break*/, 3];
3790 resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||
3791 this._popupRedirectResolver;
3792 _assert(resolver, this, "argument-error" /* ARGUMENT_ERROR */);
3793 _a = this;
3794 return [4 /*yield*/, PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], "redirectUser" /* REDIRECT_USER */)];
3795 case 1:
3796 _a.redirectPersistenceManager = _c.sent();
3797 _b = this;
3798 return [4 /*yield*/, this.redirectPersistenceManager.getCurrentUser()];
3799 case 2:
3800 _b.redirectUser =
3801 _c.sent();
3802 _c.label = 3;
3803 case 3: return [2 /*return*/, this.redirectPersistenceManager];
3804 }
3805 });
3806 });
3807 };
3808 AuthImpl.prototype._redirectUserForId = function (id) {
3809 var _a, _b;
3810 return __awaiter(this, void 0, void 0, function () {
3811 var _this = this;
3812 return __generator(this, function (_c) {
3813 switch (_c.label) {
3814 case 0:
3815 if (!this._isInitialized) return [3 /*break*/, 2];
3816 return [4 /*yield*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
3817 return [2 /*return*/];
3818 }); }); })];
3819 case 1:
3820 _c.sent();
3821 _c.label = 2;
3822 case 2:
3823 if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {
3824 return [2 /*return*/, this._currentUser];
3825 }
3826 if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {
3827 return [2 /*return*/, this.redirectUser];
3828 }
3829 return [2 /*return*/, null];
3830 }
3831 });
3832 });
3833 };
3834 AuthImpl.prototype._persistUserIfCurrent = function (user) {
3835 return __awaiter(this, void 0, void 0, function () {
3836 var _this = this;
3837 return __generator(this, function (_a) {
3838 if (user === this.currentUser) {
3839 return [2 /*return*/, this.queue(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
3840 return [2 /*return*/, this.directlySetCurrentUser(user)];
3841 }); }); })];
3842 }
3843 return [2 /*return*/];
3844 });
3845 });
3846 };
3847 /** Notifies listeners only if the user is current */
3848 AuthImpl.prototype._notifyListenersIfCurrent = function (user) {
3849 if (user === this.currentUser) {
3850 this.notifyAuthListeners();
3851 }
3852 };
3853 AuthImpl.prototype._key = function () {
3854 return this.config.authDomain + ":" + this.config.apiKey + ":" + this.name;
3855 };
3856 AuthImpl.prototype._startProactiveRefresh = function () {
3857 this.isProactiveRefreshEnabled = true;
3858 if (this.currentUser) {
3859 this._currentUser._startProactiveRefresh();
3860 }
3861 };
3862 AuthImpl.prototype._stopProactiveRefresh = function () {
3863 this.isProactiveRefreshEnabled = false;
3864 if (this.currentUser) {
3865 this._currentUser._stopProactiveRefresh();
3866 }
3867 };
3868 Object.defineProperty(AuthImpl.prototype, "_currentUser", {
3869 /** Returns the current user cast as the internal type */
3870 get: function () {
3871 return this.currentUser;
3872 },
3873 enumerable: false,
3874 configurable: true
3875 });
3876 AuthImpl.prototype.notifyAuthListeners = function () {
3877 var _a, _b;
3878 if (!this._isInitialized) {
3879 return;
3880 }
3881 this.idTokenSubscription.next(this.currentUser);
3882 var currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;
3883 if (this.lastNotifiedUid !== currentUid) {
3884 this.lastNotifiedUid = currentUid;
3885 this.authStateSubscription.next(this.currentUser);
3886 }
3887 };
3888 AuthImpl.prototype.registerStateListener = function (subscription, nextOrObserver, error, completed) {
3889 var _this = this;
3890 if (this._deleted) {
3891 return function () { };
3892 }
3893 var cb = typeof nextOrObserver === 'function'
3894 ? nextOrObserver
3895 : nextOrObserver.next.bind(nextOrObserver);
3896 var promise = this._isInitialized
3897 ? Promise.resolve()
3898 : this._initializationPromise;
3899 _assert(promise, this, "internal-error" /* INTERNAL_ERROR */);
3900 // The callback needs to be called asynchronously per the spec.
3901 // eslint-disable-next-line @typescript-eslint/no-floating-promises
3902 promise.then(function () { return cb(_this.currentUser); });
3903 if (typeof nextOrObserver === 'function') {
3904 return subscription.addObserver(nextOrObserver, error, completed);
3905 }
3906 else {
3907 return subscription.addObserver(nextOrObserver);
3908 }
3909 };
3910 /**
3911 * Unprotected (from race conditions) method to set the current user. This
3912 * should only be called from within a queued callback. This is necessary
3913 * because the queue shouldn't rely on another queued callback.
3914 */
3915 AuthImpl.prototype.directlySetCurrentUser = function (user) {
3916 return __awaiter(this, void 0, void 0, function () {
3917 return __generator(this, function (_a) {
3918 switch (_a.label) {
3919 case 0:
3920 if (this.currentUser && this.currentUser !== user) {
3921 this._currentUser._stopProactiveRefresh();
3922 if (user && this.isProactiveRefreshEnabled) {
3923 user._startProactiveRefresh();
3924 }
3925 }
3926 this.currentUser = user;
3927 if (!user) return [3 /*break*/, 2];
3928 return [4 /*yield*/, this.assertedPersistence.setCurrentUser(user)];
3929 case 1:
3930 _a.sent();
3931 return [3 /*break*/, 4];
3932 case 2: return [4 /*yield*/, this.assertedPersistence.removeCurrentUser()];
3933 case 3:
3934 _a.sent();
3935 _a.label = 4;
3936 case 4: return [2 /*return*/];
3937 }
3938 });
3939 });
3940 };
3941 AuthImpl.prototype.queue = function (action) {
3942 // In case something errors, the callback still should be called in order
3943 // to keep the promise chain alive
3944 this.operations = this.operations.then(action, action);
3945 return this.operations;
3946 };
3947 Object.defineProperty(AuthImpl.prototype, "assertedPersistence", {
3948 get: function () {
3949 _assert(this.persistenceManager, this, "internal-error" /* INTERNAL_ERROR */);
3950 return this.persistenceManager;
3951 },
3952 enumerable: false,
3953 configurable: true
3954 });
3955 AuthImpl.prototype._logFramework = function (framework) {
3956 if (!framework || this.frameworks.includes(framework)) {
3957 return;
3958 }
3959 this.frameworks.push(framework);
3960 // Sort alphabetically so that "FirebaseCore-web,FirebaseUI-web" and
3961 // "FirebaseUI-web,FirebaseCore-web" aren't viewed as different.
3962 this.frameworks.sort();
3963 this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());
3964 };
3965 AuthImpl.prototype._getFrameworks = function () {
3966 return this.frameworks;
3967 };
3968 AuthImpl.prototype._getAdditionalHeaders = function () {
3969 var _a;
3970 return __awaiter(this, void 0, void 0, function () {
3971 var headers, heartbeatsHeader;
3972 var _b;
3973 return __generator(this, function (_c) {
3974 switch (_c.label) {
3975 case 0:
3976 headers = (_b = {},
3977 _b["X-Client-Version" /* X_CLIENT_VERSION */] = this.clientVersion,
3978 _b);
3979 if (this.app.options.appId) {
3980 headers["X-Firebase-gmpid" /* X_FIREBASE_GMPID */] = this.app.options.appId;
3981 }
3982 return [4 /*yield*/, ((_a = this.heartbeatServiceProvider.getImmediate({
3983 optional: true,
3984 })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader())];
3985 case 1:
3986 heartbeatsHeader = _c.sent();
3987 if (heartbeatsHeader) {
3988 headers["X-Firebase-Client" /* X_FIREBASE_CLIENT */] = heartbeatsHeader;
3989 }
3990 return [2 /*return*/, headers];
3991 }
3992 });
3993 });
3994 };
3995 return AuthImpl;
3996}());
3997/**
3998 * Method to be used to cast down to our private implmentation of Auth.
3999 * It will also handle unwrapping from the compat type if necessary
4000 *
4001 * @param auth Auth object passed in from developer
4002 */
4003function _castAuth(auth) {
4004 return getModularInstance(auth);
4005}
4006/** Helper class to wrap subscriber logic */
4007var Subscription = /** @class */ (function () {
4008 function Subscription(auth) {
4009 var _this = this;
4010 this.auth = auth;
4011 this.observer = null;
4012 this.addObserver = createSubscribe(function (observer) { return (_this.observer = observer); });
4013 }
4014 Object.defineProperty(Subscription.prototype, "next", {
4015 get: function () {
4016 _assert(this.observer, this.auth, "internal-error" /* INTERNAL_ERROR */);
4017 return this.observer.next.bind(this.observer);
4018 },
4019 enumerable: false,
4020 configurable: true
4021 });
4022 return Subscription;
4023}());
4024
4025/**
4026 * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production
4027 * Firebase Auth services.
4028 *
4029 * @remarks
4030 * This must be called synchronously immediately following the first call to
4031 * {@link initializeAuth}. Do not use with production credentials as emulator
4032 * traffic is not encrypted.
4033 *
4034 *
4035 * @example
4036 * ```javascript
4037 * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });
4038 * ```
4039 *
4040 * @param auth - The {@link Auth} instance.
4041 * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').
4042 * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to
4043 * `true` to disable the warning banner attached to the DOM.
4044 *
4045 * @public
4046 */
4047function connectAuthEmulator(auth, url, options) {
4048 var authInternal = _castAuth(auth);
4049 _assert(authInternal._canInitEmulator, authInternal, "emulator-config-failed" /* EMULATOR_CONFIG_FAILED */);
4050 _assert(/^https?:\/\//.test(url), authInternal, "invalid-emulator-scheme" /* INVALID_EMULATOR_SCHEME */);
4051 var disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);
4052 var protocol = extractProtocol(url);
4053 var _a = extractHostAndPort(url), host = _a.host, port = _a.port;
4054 var portStr = port === null ? '' : ":" + port;
4055 // Always replace path with "/" (even if input url had no path at all, or had a different one).
4056 authInternal.config.emulator = { url: protocol + "//" + host + portStr + "/" };
4057 authInternal.settings.appVerificationDisabledForTesting = true;
4058 authInternal.emulatorConfig = Object.freeze({
4059 host: host,
4060 port: port,
4061 protocol: protocol.replace(':', ''),
4062 options: Object.freeze({ disableWarnings: disableWarnings })
4063 });
4064 if (!disableWarnings) {
4065 emitEmulatorWarning();
4066 }
4067}
4068function extractProtocol(url) {
4069 var protocolEnd = url.indexOf(':');
4070 return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);
4071}
4072function extractHostAndPort(url) {
4073 var protocol = extractProtocol(url);
4074 var authority = /(\/\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.
4075 if (!authority) {
4076 return { host: '', port: null };
4077 }
4078 var hostAndPort = authority[2].split('@').pop() || ''; // Strip out "username:password@".
4079 var bracketedIPv6 = /^(\[[^\]]+\])(:|$)/.exec(hostAndPort);
4080 if (bracketedIPv6) {
4081 var host = bracketedIPv6[1];
4082 return { host: host, port: parsePort(hostAndPort.substr(host.length + 1)) };
4083 }
4084 else {
4085 var _a = hostAndPort.split(':'), host = _a[0], port = _a[1];
4086 return { host: host, port: parsePort(port) };
4087 }
4088}
4089function parsePort(portStr) {
4090 if (!portStr) {
4091 return null;
4092 }
4093 var port = Number(portStr);
4094 if (isNaN(port)) {
4095 return null;
4096 }
4097 return port;
4098}
4099function emitEmulatorWarning() {
4100 function attachBanner() {
4101 var el = document.createElement('p');
4102 var sty = el.style;
4103 el.innerText =
4104 'Running in emulator mode. Do not use with production credentials.';
4105 sty.position = 'fixed';
4106 sty.width = '100%';
4107 sty.backgroundColor = '#ffffff';
4108 sty.border = '.1em solid #000000';
4109 sty.color = '#b50000';
4110 sty.bottom = '0px';
4111 sty.left = '0px';
4112 sty.margin = '0px';
4113 sty.zIndex = '10000';
4114 sty.textAlign = 'center';
4115 el.classList.add('firebase-emulator-warning');
4116 document.body.appendChild(el);
4117 }
4118 if (typeof console !== 'undefined' && typeof console.info === 'function') {
4119 console.info('WARNING: You are using the Auth Emulator,' +
4120 ' which is intended for local testing only. Do not use with' +
4121 ' production credentials.');
4122 }
4123 if (typeof window !== 'undefined' &&
4124 typeof document !== 'undefined') {
4125 if (document.readyState === 'loading') {
4126 window.addEventListener('DOMContentLoaded', attachBanner);
4127 }
4128 else {
4129 attachBanner();
4130 }
4131 }
4132}
4133
4134/**
4135 * @license
4136 * Copyright 2020 Google LLC
4137 *
4138 * Licensed under the Apache License, Version 2.0 (the "License");
4139 * you may not use this file except in compliance with the License.
4140 * You may obtain a copy of the License at
4141 *
4142 * http://www.apache.org/licenses/LICENSE-2.0
4143 *
4144 * Unless required by applicable law or agreed to in writing, software
4145 * distributed under the License is distributed on an "AS IS" BASIS,
4146 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4147 * See the License for the specific language governing permissions and
4148 * limitations under the License.
4149 */
4150/**
4151 * Interface that represents the credentials returned by an {@link AuthProvider}.
4152 *
4153 * @remarks
4154 * Implementations specify the details about each auth provider's credential requirements.
4155 *
4156 * @public
4157 */
4158var AuthCredential = /** @class */ (function () {
4159 /** @internal */
4160 function AuthCredential(
4161 /**
4162 * The authentication provider ID for the credential.
4163 *
4164 * @remarks
4165 * For example, 'facebook.com', or 'google.com'.
4166 */
4167 providerId,
4168 /**
4169 * The authentication sign in method for the credential.
4170 *
4171 * @remarks
4172 * For example, {@link SignInMethod}.EMAIL_PASSWORD, or
4173 * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method
4174 * identifier as returned in {@link fetchSignInMethodsForEmail}.
4175 */
4176 signInMethod) {
4177 this.providerId = providerId;
4178 this.signInMethod = signInMethod;
4179 }
4180 /**
4181 * Returns a JSON-serializable representation of this object.
4182 *
4183 * @returns a JSON-serializable representation of this object.
4184 */
4185 AuthCredential.prototype.toJSON = function () {
4186 return debugFail('not implemented');
4187 };
4188 /** @internal */
4189 AuthCredential.prototype._getIdTokenResponse = function (_auth) {
4190 return debugFail('not implemented');
4191 };
4192 /** @internal */
4193 AuthCredential.prototype._linkToIdToken = function (_auth, _idToken) {
4194 return debugFail('not implemented');
4195 };
4196 /** @internal */
4197 AuthCredential.prototype._getReauthenticationResolver = function (_auth) {
4198 return debugFail('not implemented');
4199 };
4200 return AuthCredential;
4201}());
4202
4203/**
4204 * @license
4205 * Copyright 2020 Google LLC
4206 *
4207 * Licensed under the Apache License, Version 2.0 (the "License");
4208 * you may not use this file except in compliance with the License.
4209 * You may obtain a copy of the License at
4210 *
4211 * http://www.apache.org/licenses/LICENSE-2.0
4212 *
4213 * Unless required by applicable law or agreed to in writing, software
4214 * distributed under the License is distributed on an "AS IS" BASIS,
4215 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4216 * See the License for the specific language governing permissions and
4217 * limitations under the License.
4218 */
4219function resetPassword(auth, request) {
4220 return __awaiter(this, void 0, void 0, function () {
4221 return __generator(this, function (_a) {
4222 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:resetPassword" /* RESET_PASSWORD */, _addTidIfNecessary(auth, request))];
4223 });
4224 });
4225}
4226function updateEmailPassword(auth, request) {
4227 return __awaiter(this, void 0, void 0, function () {
4228 return __generator(this, function (_a) {
4229 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, request)];
4230 });
4231 });
4232}
4233function applyActionCode$1(auth, request) {
4234 return __awaiter(this, void 0, void 0, function () {
4235 return __generator(this, function (_a) {
4236 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request))];
4237 });
4238 });
4239}
4240
4241/**
4242 * @license
4243 * Copyright 2020 Google LLC
4244 *
4245 * Licensed under the Apache License, Version 2.0 (the "License");
4246 * you may not use this file except in compliance with the License.
4247 * You may obtain a copy of the License at
4248 *
4249 * http://www.apache.org/licenses/LICENSE-2.0
4250 *
4251 * Unless required by applicable law or agreed to in writing, software
4252 * distributed under the License is distributed on an "AS IS" BASIS,
4253 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4254 * See the License for the specific language governing permissions and
4255 * limitations under the License.
4256 */
4257function signInWithPassword(auth, request) {
4258 return __awaiter(this, void 0, void 0, function () {
4259 return __generator(this, function (_a) {
4260 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPassword" /* SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request))];
4261 });
4262 });
4263}
4264function sendOobCode(auth, request) {
4265 return __awaiter(this, void 0, void 0, function () {
4266 return __generator(this, function (_a) {
4267 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:sendOobCode" /* SEND_OOB_CODE */, _addTidIfNecessary(auth, request))];
4268 });
4269 });
4270}
4271function sendEmailVerification$1(auth, request) {
4272 return __awaiter(this, void 0, void 0, function () {
4273 return __generator(this, function (_a) {
4274 return [2 /*return*/, sendOobCode(auth, request)];
4275 });
4276 });
4277}
4278function sendPasswordResetEmail$1(auth, request) {
4279 return __awaiter(this, void 0, void 0, function () {
4280 return __generator(this, function (_a) {
4281 return [2 /*return*/, sendOobCode(auth, request)];
4282 });
4283 });
4284}
4285function sendSignInLinkToEmail$1(auth, request) {
4286 return __awaiter(this, void 0, void 0, function () {
4287 return __generator(this, function (_a) {
4288 return [2 /*return*/, sendOobCode(auth, request)];
4289 });
4290 });
4291}
4292function verifyAndChangeEmail(auth, request) {
4293 return __awaiter(this, void 0, void 0, function () {
4294 return __generator(this, function (_a) {
4295 return [2 /*return*/, sendOobCode(auth, request)];
4296 });
4297 });
4298}
4299
4300/**
4301 * @license
4302 * Copyright 2020 Google LLC
4303 *
4304 * Licensed under the Apache License, Version 2.0 (the "License");
4305 * you may not use this file except in compliance with the License.
4306 * You may obtain a copy of the License at
4307 *
4308 * http://www.apache.org/licenses/LICENSE-2.0
4309 *
4310 * Unless required by applicable law or agreed to in writing, software
4311 * distributed under the License is distributed on an "AS IS" BASIS,
4312 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4313 * See the License for the specific language governing permissions and
4314 * limitations under the License.
4315 */
4316function signInWithEmailLink$1(auth, request) {
4317 return __awaiter(this, void 0, void 0, function () {
4318 return __generator(this, function (_a) {
4319 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithEmailLink" /* SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
4320 });
4321 });
4322}
4323function signInWithEmailLinkForLinking(auth, request) {
4324 return __awaiter(this, void 0, void 0, function () {
4325 return __generator(this, function (_a) {
4326 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithEmailLink" /* SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request))];
4327 });
4328 });
4329}
4330
4331/**
4332 * @license
4333 * Copyright 2020 Google LLC
4334 *
4335 * Licensed under the Apache License, Version 2.0 (the "License");
4336 * you may not use this file except in compliance with the License.
4337 * You may obtain a copy of the License at
4338 *
4339 * http://www.apache.org/licenses/LICENSE-2.0
4340 *
4341 * Unless required by applicable law or agreed to in writing, software
4342 * distributed under the License is distributed on an "AS IS" BASIS,
4343 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4344 * See the License for the specific language governing permissions and
4345 * limitations under the License.
4346 */
4347/**
4348 * Interface that represents the credentials returned by {@link EmailAuthProvider} for
4349 * {@link ProviderId}.PASSWORD
4350 *
4351 * @remarks
4352 * Covers both {@link SignInMethod}.EMAIL_PASSWORD and
4353 * {@link SignInMethod}.EMAIL_LINK.
4354 *
4355 * @public
4356 */
4357var EmailAuthCredential = /** @class */ (function (_super) {
4358 __extends(EmailAuthCredential, _super);
4359 /** @internal */
4360 function EmailAuthCredential(
4361 /** @internal */
4362 _email,
4363 /** @internal */
4364 _password, signInMethod,
4365 /** @internal */
4366 _tenantId) {
4367 if (_tenantId === void 0) { _tenantId = null; }
4368 var _this = _super.call(this, "password" /* PASSWORD */, signInMethod) || this;
4369 _this._email = _email;
4370 _this._password = _password;
4371 _this._tenantId = _tenantId;
4372 return _this;
4373 }
4374 /** @internal */
4375 EmailAuthCredential._fromEmailAndPassword = function (email, password) {
4376 return new EmailAuthCredential(email, password, "password" /* EMAIL_PASSWORD */);
4377 };
4378 /** @internal */
4379 EmailAuthCredential._fromEmailAndCode = function (email, oobCode, tenantId) {
4380 if (tenantId === void 0) { tenantId = null; }
4381 return new EmailAuthCredential(email, oobCode, "emailLink" /* EMAIL_LINK */, tenantId);
4382 };
4383 /** {@inheritdoc AuthCredential.toJSON} */
4384 EmailAuthCredential.prototype.toJSON = function () {
4385 return {
4386 email: this._email,
4387 password: this._password,
4388 signInMethod: this.signInMethod,
4389 tenantId: this._tenantId
4390 };
4391 };
4392 /**
4393 * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.
4394 *
4395 * @param json - Either `object` or the stringified representation of the object. When string is
4396 * provided, `JSON.parse` would be called first.
4397 *
4398 * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
4399 */
4400 EmailAuthCredential.fromJSON = function (json) {
4401 var obj = typeof json === 'string' ? JSON.parse(json) : json;
4402 if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {
4403 if (obj.signInMethod === "password" /* EMAIL_PASSWORD */) {
4404 return this._fromEmailAndPassword(obj.email, obj.password);
4405 }
4406 else if (obj.signInMethod === "emailLink" /* EMAIL_LINK */) {
4407 return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);
4408 }
4409 }
4410 return null;
4411 };
4412 /** @internal */
4413 EmailAuthCredential.prototype._getIdTokenResponse = function (auth) {
4414 return __awaiter(this, void 0, void 0, function () {
4415 return __generator(this, function (_a) {
4416 switch (this.signInMethod) {
4417 case "password" /* EMAIL_PASSWORD */:
4418 return [2 /*return*/, signInWithPassword(auth, {
4419 returnSecureToken: true,
4420 email: this._email,
4421 password: this._password
4422 })];
4423 case "emailLink" /* EMAIL_LINK */:
4424 return [2 /*return*/, signInWithEmailLink$1(auth, {
4425 email: this._email,
4426 oobCode: this._password
4427 })];
4428 default:
4429 _fail(auth, "internal-error" /* INTERNAL_ERROR */);
4430 }
4431 return [2 /*return*/];
4432 });
4433 });
4434 };
4435 /** @internal */
4436 EmailAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
4437 return __awaiter(this, void 0, void 0, function () {
4438 return __generator(this, function (_a) {
4439 switch (this.signInMethod) {
4440 case "password" /* EMAIL_PASSWORD */:
4441 return [2 /*return*/, updateEmailPassword(auth, {
4442 idToken: idToken,
4443 returnSecureToken: true,
4444 email: this._email,
4445 password: this._password
4446 })];
4447 case "emailLink" /* EMAIL_LINK */:
4448 return [2 /*return*/, signInWithEmailLinkForLinking(auth, {
4449 idToken: idToken,
4450 email: this._email,
4451 oobCode: this._password
4452 })];
4453 default:
4454 _fail(auth, "internal-error" /* INTERNAL_ERROR */);
4455 }
4456 return [2 /*return*/];
4457 });
4458 });
4459 };
4460 /** @internal */
4461 EmailAuthCredential.prototype._getReauthenticationResolver = function (auth) {
4462 return this._getIdTokenResponse(auth);
4463 };
4464 return EmailAuthCredential;
4465}(AuthCredential));
4466
4467/**
4468 * @license
4469 * Copyright 2020 Google LLC
4470 *
4471 * Licensed under the Apache License, Version 2.0 (the "License");
4472 * you may not use this file except in compliance with the License.
4473 * You may obtain a copy of the License at
4474 *
4475 * http://www.apache.org/licenses/LICENSE-2.0
4476 *
4477 * Unless required by applicable law or agreed to in writing, software
4478 * distributed under the License is distributed on an "AS IS" BASIS,
4479 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4480 * See the License for the specific language governing permissions and
4481 * limitations under the License.
4482 */
4483function signInWithIdp(auth, request) {
4484 return __awaiter(this, void 0, void 0, function () {
4485 return __generator(this, function (_a) {
4486 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithIdp" /* SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request))];
4487 });
4488 });
4489}
4490
4491/**
4492 * @license
4493 * Copyright 2020 Google LLC
4494 *
4495 * Licensed under the Apache License, Version 2.0 (the "License");
4496 * you may not use this file except in compliance with the License.
4497 * You may obtain a copy of the License at
4498 *
4499 * http://www.apache.org/licenses/LICENSE-2.0
4500 *
4501 * Unless required by applicable law or agreed to in writing, software
4502 * distributed under the License is distributed on an "AS IS" BASIS,
4503 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4504 * See the License for the specific language governing permissions and
4505 * limitations under the License.
4506 */
4507var IDP_REQUEST_URI$1 = 'http://localhost';
4508/**
4509 * Represents the OAuth credentials returned by an {@link OAuthProvider}.
4510 *
4511 * @remarks
4512 * Implementations specify the details about each auth provider's credential requirements.
4513 *
4514 * @public
4515 */
4516var OAuthCredential = /** @class */ (function (_super) {
4517 __extends(OAuthCredential, _super);
4518 function OAuthCredential() {
4519 var _this = _super !== null && _super.apply(this, arguments) || this;
4520 _this.pendingToken = null;
4521 return _this;
4522 }
4523 /** @internal */
4524 OAuthCredential._fromParams = function (params) {
4525 var cred = new OAuthCredential(params.providerId, params.signInMethod);
4526 if (params.idToken || params.accessToken) {
4527 // OAuth 2 and either ID token or access token.
4528 if (params.idToken) {
4529 cred.idToken = params.idToken;
4530 }
4531 if (params.accessToken) {
4532 cred.accessToken = params.accessToken;
4533 }
4534 // Add nonce if available and no pendingToken is present.
4535 if (params.nonce && !params.pendingToken) {
4536 cred.nonce = params.nonce;
4537 }
4538 if (params.pendingToken) {
4539 cred.pendingToken = params.pendingToken;
4540 }
4541 }
4542 else if (params.oauthToken && params.oauthTokenSecret) {
4543 // OAuth 1 and OAuth token with token secret
4544 cred.accessToken = params.oauthToken;
4545 cred.secret = params.oauthTokenSecret;
4546 }
4547 else {
4548 _fail("argument-error" /* ARGUMENT_ERROR */);
4549 }
4550 return cred;
4551 };
4552 /** {@inheritdoc AuthCredential.toJSON} */
4553 OAuthCredential.prototype.toJSON = function () {
4554 return {
4555 idToken: this.idToken,
4556 accessToken: this.accessToken,
4557 secret: this.secret,
4558 nonce: this.nonce,
4559 pendingToken: this.pendingToken,
4560 providerId: this.providerId,
4561 signInMethod: this.signInMethod
4562 };
4563 };
4564 /**
4565 * Static method to deserialize a JSON representation of an object into an
4566 * {@link AuthCredential}.
4567 *
4568 * @param json - Input can be either Object or the stringified representation of the object.
4569 * When string is provided, JSON.parse would be called first.
4570 *
4571 * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
4572 */
4573 OAuthCredential.fromJSON = function (json) {
4574 var obj = typeof json === 'string' ? JSON.parse(json) : json;
4575 var providerId = obj.providerId, signInMethod = obj.signInMethod, rest = __rest(obj, ["providerId", "signInMethod"]);
4576 if (!providerId || !signInMethod) {
4577 return null;
4578 }
4579 var cred = new OAuthCredential(providerId, signInMethod);
4580 cred.idToken = rest.idToken || undefined;
4581 cred.accessToken = rest.accessToken || undefined;
4582 cred.secret = rest.secret;
4583 cred.nonce = rest.nonce;
4584 cred.pendingToken = rest.pendingToken || null;
4585 return cred;
4586 };
4587 /** @internal */
4588 OAuthCredential.prototype._getIdTokenResponse = function (auth) {
4589 var request = this.buildRequest();
4590 return signInWithIdp(auth, request);
4591 };
4592 /** @internal */
4593 OAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
4594 var request = this.buildRequest();
4595 request.idToken = idToken;
4596 return signInWithIdp(auth, request);
4597 };
4598 /** @internal */
4599 OAuthCredential.prototype._getReauthenticationResolver = function (auth) {
4600 var request = this.buildRequest();
4601 request.autoCreate = false;
4602 return signInWithIdp(auth, request);
4603 };
4604 OAuthCredential.prototype.buildRequest = function () {
4605 var request = {
4606 requestUri: IDP_REQUEST_URI$1,
4607 returnSecureToken: true
4608 };
4609 if (this.pendingToken) {
4610 request.pendingToken = this.pendingToken;
4611 }
4612 else {
4613 var postBody = {};
4614 if (this.idToken) {
4615 postBody['id_token'] = this.idToken;
4616 }
4617 if (this.accessToken) {
4618 postBody['access_token'] = this.accessToken;
4619 }
4620 if (this.secret) {
4621 postBody['oauth_token_secret'] = this.secret;
4622 }
4623 postBody['providerId'] = this.providerId;
4624 if (this.nonce && !this.pendingToken) {
4625 postBody['nonce'] = this.nonce;
4626 }
4627 request.postBody = querystring(postBody);
4628 }
4629 return request;
4630 };
4631 return OAuthCredential;
4632}(AuthCredential));
4633
4634/**
4635 * @license
4636 * Copyright 2020 Google LLC
4637 *
4638 * Licensed under the Apache License, Version 2.0 (the "License");
4639 * you may not use this file except in compliance with the License.
4640 * You may obtain a copy of the License at
4641 *
4642 * http://www.apache.org/licenses/LICENSE-2.0
4643 *
4644 * Unless required by applicable law or agreed to in writing, software
4645 * distributed under the License is distributed on an "AS IS" BASIS,
4646 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4647 * See the License for the specific language governing permissions and
4648 * limitations under the License.
4649 */
4650var _a;
4651function sendPhoneVerificationCode(auth, request) {
4652 return __awaiter(this, void 0, void 0, function () {
4653 return __generator(this, function (_a) {
4654 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:sendVerificationCode" /* SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request))];
4655 });
4656 });
4657}
4658function signInWithPhoneNumber(auth, request) {
4659 return __awaiter(this, void 0, void 0, function () {
4660 return __generator(this, function (_a) {
4661 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPhoneNumber" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
4662 });
4663 });
4664}
4665function linkWithPhoneNumber(auth, request) {
4666 return __awaiter(this, void 0, void 0, function () {
4667 var response;
4668 return __generator(this, function (_a) {
4669 switch (_a.label) {
4670 case 0: return [4 /*yield*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPhoneNumber" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request))];
4671 case 1:
4672 response = _a.sent();
4673 if (response.temporaryProof) {
4674 throw _makeTaggedError(auth, "account-exists-with-different-credential" /* NEED_CONFIRMATION */, response);
4675 }
4676 return [2 /*return*/, response];
4677 }
4678 });
4679 });
4680}
4681var VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = (_a = {},
4682 _a["USER_NOT_FOUND" /* USER_NOT_FOUND */] = "user-not-found" /* USER_DELETED */,
4683 _a);
4684function verifyPhoneNumberForExisting(auth, request) {
4685 return __awaiter(this, void 0, void 0, function () {
4686 var apiRequest;
4687 return __generator(this, function (_a) {
4688 apiRequest = __assign(__assign({}, request), { operation: 'REAUTH' });
4689 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithPhoneNumber" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_)];
4690 });
4691 });
4692}
4693
4694/**
4695 * @license
4696 * Copyright 2020 Google LLC
4697 *
4698 * Licensed under the Apache License, Version 2.0 (the "License");
4699 * you may not use this file except in compliance with the License.
4700 * You may obtain a copy of the License at
4701 *
4702 * http://www.apache.org/licenses/LICENSE-2.0
4703 *
4704 * Unless required by applicable law or agreed to in writing, software
4705 * distributed under the License is distributed on an "AS IS" BASIS,
4706 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4707 * See the License for the specific language governing permissions and
4708 * limitations under the License.
4709 */
4710/**
4711 * Represents the credentials returned by {@link PhoneAuthProvider}.
4712 *
4713 * @public
4714 */
4715var PhoneAuthCredential = /** @class */ (function (_super) {
4716 __extends(PhoneAuthCredential, _super);
4717 function PhoneAuthCredential(params) {
4718 var _this = _super.call(this, "phone" /* PHONE */, "phone" /* PHONE */) || this;
4719 _this.params = params;
4720 return _this;
4721 }
4722 /** @internal */
4723 PhoneAuthCredential._fromVerification = function (verificationId, verificationCode) {
4724 return new PhoneAuthCredential({ verificationId: verificationId, verificationCode: verificationCode });
4725 };
4726 /** @internal */
4727 PhoneAuthCredential._fromTokenResponse = function (phoneNumber, temporaryProof) {
4728 return new PhoneAuthCredential({ phoneNumber: phoneNumber, temporaryProof: temporaryProof });
4729 };
4730 /** @internal */
4731 PhoneAuthCredential.prototype._getIdTokenResponse = function (auth) {
4732 return signInWithPhoneNumber(auth, this._makeVerificationRequest());
4733 };
4734 /** @internal */
4735 PhoneAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
4736 return linkWithPhoneNumber(auth, __assign({ idToken: idToken }, this._makeVerificationRequest()));
4737 };
4738 /** @internal */
4739 PhoneAuthCredential.prototype._getReauthenticationResolver = function (auth) {
4740 return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());
4741 };
4742 /** @internal */
4743 PhoneAuthCredential.prototype._makeVerificationRequest = function () {
4744 var _a = this.params, temporaryProof = _a.temporaryProof, phoneNumber = _a.phoneNumber, verificationId = _a.verificationId, verificationCode = _a.verificationCode;
4745 if (temporaryProof && phoneNumber) {
4746 return { temporaryProof: temporaryProof, phoneNumber: phoneNumber };
4747 }
4748 return {
4749 sessionInfo: verificationId,
4750 code: verificationCode
4751 };
4752 };
4753 /** {@inheritdoc AuthCredential.toJSON} */
4754 PhoneAuthCredential.prototype.toJSON = function () {
4755 var obj = {
4756 providerId: this.providerId
4757 };
4758 if (this.params.phoneNumber) {
4759 obj.phoneNumber = this.params.phoneNumber;
4760 }
4761 if (this.params.temporaryProof) {
4762 obj.temporaryProof = this.params.temporaryProof;
4763 }
4764 if (this.params.verificationCode) {
4765 obj.verificationCode = this.params.verificationCode;
4766 }
4767 if (this.params.verificationId) {
4768 obj.verificationId = this.params.verificationId;
4769 }
4770 return obj;
4771 };
4772 /** Generates a phone credential based on a plain object or a JSON string. */
4773 PhoneAuthCredential.fromJSON = function (json) {
4774 if (typeof json === 'string') {
4775 json = JSON.parse(json);
4776 }
4777 var _a = json, verificationId = _a.verificationId, verificationCode = _a.verificationCode, phoneNumber = _a.phoneNumber, temporaryProof = _a.temporaryProof;
4778 if (!verificationCode &&
4779 !verificationId &&
4780 !phoneNumber &&
4781 !temporaryProof) {
4782 return null;
4783 }
4784 return new PhoneAuthCredential({
4785 verificationId: verificationId,
4786 verificationCode: verificationCode,
4787 phoneNumber: phoneNumber,
4788 temporaryProof: temporaryProof
4789 });
4790 };
4791 return PhoneAuthCredential;
4792}(AuthCredential));
4793
4794/**
4795 * @license
4796 * Copyright 2020 Google LLC
4797 *
4798 * Licensed under the Apache License, Version 2.0 (the "License");
4799 * you may not use this file except in compliance with the License.
4800 * You may obtain a copy of the License at
4801 *
4802 * http://www.apache.org/licenses/LICENSE-2.0
4803 *
4804 * Unless required by applicable law or agreed to in writing, software
4805 * distributed under the License is distributed on an "AS IS" BASIS,
4806 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4807 * See the License for the specific language governing permissions and
4808 * limitations under the License.
4809 */
4810/**
4811 * Maps the mode string in action code URL to Action Code Info operation.
4812 *
4813 * @param mode
4814 */
4815function parseMode(mode) {
4816 switch (mode) {
4817 case 'recoverEmail':
4818 return "RECOVER_EMAIL" /* RECOVER_EMAIL */;
4819 case 'resetPassword':
4820 return "PASSWORD_RESET" /* PASSWORD_RESET */;
4821 case 'signIn':
4822 return "EMAIL_SIGNIN" /* EMAIL_SIGNIN */;
4823 case 'verifyEmail':
4824 return "VERIFY_EMAIL" /* VERIFY_EMAIL */;
4825 case 'verifyAndChangeEmail':
4826 return "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */;
4827 case 'revertSecondFactorAddition':
4828 return "REVERT_SECOND_FACTOR_ADDITION" /* REVERT_SECOND_FACTOR_ADDITION */;
4829 default:
4830 return null;
4831 }
4832}
4833/**
4834 * Helper to parse FDL links
4835 *
4836 * @param url
4837 */
4838function parseDeepLink(url) {
4839 var link = querystringDecode(extractQuerystring(url))['link'];
4840 // Double link case (automatic redirect).
4841 var doubleDeepLink = link
4842 ? querystringDecode(extractQuerystring(link))['deep_link_id']
4843 : null;
4844 // iOS custom scheme links.
4845 var iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];
4846 var iOSDoubleDeepLink = iOSDeepLink
4847 ? querystringDecode(extractQuerystring(iOSDeepLink))['link']
4848 : null;
4849 return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
4850}
4851/**
4852 * A utility class to parse email action URLs such as password reset, email verification,
4853 * email link sign in, etc.
4854 *
4855 * @public
4856 */
4857var ActionCodeURL = /** @class */ (function () {
4858 /**
4859 * @param actionLink - The link from which to extract the URL.
4860 * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
4861 *
4862 * @internal
4863 */
4864 function ActionCodeURL(actionLink) {
4865 var _a, _b, _c, _d, _e, _f;
4866 var searchParams = querystringDecode(extractQuerystring(actionLink));
4867 var apiKey = (_a = searchParams["apiKey" /* API_KEY */]) !== null && _a !== void 0 ? _a : null;
4868 var code = (_b = searchParams["oobCode" /* CODE */]) !== null && _b !== void 0 ? _b : null;
4869 var operation = parseMode((_c = searchParams["mode" /* MODE */]) !== null && _c !== void 0 ? _c : null);
4870 // Validate API key, code and mode.
4871 _assert(apiKey && code && operation, "argument-error" /* ARGUMENT_ERROR */);
4872 this.apiKey = apiKey;
4873 this.operation = operation;
4874 this.code = code;
4875 this.continueUrl = (_d = searchParams["continueUrl" /* CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;
4876 this.languageCode = (_e = searchParams["languageCode" /* LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;
4877 this.tenantId = (_f = searchParams["tenantId" /* TENANT_ID */]) !== null && _f !== void 0 ? _f : null;
4878 }
4879 /**
4880 * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,
4881 * otherwise returns null.
4882 *
4883 * @param link - The email action link string.
4884 * @returns The {@link ActionCodeURL} object, or null if the link is invalid.
4885 *
4886 * @public
4887 */
4888 ActionCodeURL.parseLink = function (link) {
4889 var actionLink = parseDeepLink(link);
4890 try {
4891 return new ActionCodeURL(actionLink);
4892 }
4893 catch (_a) {
4894 return null;
4895 }
4896 };
4897 return ActionCodeURL;
4898}());
4899/**
4900 * Parses the email action link string and returns an {@link ActionCodeURL} if
4901 * the link is valid, otherwise returns null.
4902 *
4903 * @public
4904 */
4905function parseActionCodeURL(link) {
4906 return ActionCodeURL.parseLink(link);
4907}
4908
4909/**
4910 * @license
4911 * Copyright 2020 Google LLC
4912 *
4913 * Licensed under the Apache License, Version 2.0 (the "License");
4914 * you may not use this file except in compliance with the License.
4915 * You may obtain a copy of the License at
4916 *
4917 * http://www.apache.org/licenses/LICENSE-2.0
4918 *
4919 * Unless required by applicable law or agreed to in writing, software
4920 * distributed under the License is distributed on an "AS IS" BASIS,
4921 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4922 * See the License for the specific language governing permissions and
4923 * limitations under the License.
4924 */
4925/**
4926 * Provider for generating {@link EmailAuthCredential}.
4927 *
4928 * @public
4929 */
4930var EmailAuthProvider = /** @class */ (function () {
4931 function EmailAuthProvider() {
4932 /**
4933 * Always set to {@link ProviderId}.PASSWORD, even for email link.
4934 */
4935 this.providerId = EmailAuthProvider.PROVIDER_ID;
4936 }
4937 /**
4938 * Initialize an {@link AuthCredential} using an email and password.
4939 *
4940 * @example
4941 * ```javascript
4942 * const authCredential = EmailAuthProvider.credential(email, password);
4943 * const userCredential = await signInWithCredential(auth, authCredential);
4944 * ```
4945 *
4946 * @example
4947 * ```javascript
4948 * const userCredential = await signInWithEmailAndPassword(auth, email, password);
4949 * ```
4950 *
4951 * @param email - Email address.
4952 * @param password - User account password.
4953 * @returns The auth provider credential.
4954 */
4955 EmailAuthProvider.credential = function (email, password) {
4956 return EmailAuthCredential._fromEmailAndPassword(email, password);
4957 };
4958 /**
4959 * Initialize an {@link AuthCredential} using an email and an email link after a sign in with
4960 * email link operation.
4961 *
4962 * @example
4963 * ```javascript
4964 * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);
4965 * const userCredential = await signInWithCredential(auth, authCredential);
4966 * ```
4967 *
4968 * @example
4969 * ```javascript
4970 * await sendSignInLinkToEmail(auth, email);
4971 * // Obtain emailLink from user.
4972 * const userCredential = await signInWithEmailLink(auth, email, emailLink);
4973 * ```
4974 *
4975 * @param auth - The {@link Auth} instance used to verify the link.
4976 * @param email - Email address.
4977 * @param emailLink - Sign-in email link.
4978 * @returns - The auth provider credential.
4979 */
4980 EmailAuthProvider.credentialWithLink = function (email, emailLink) {
4981 var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
4982 _assert(actionCodeUrl, "argument-error" /* ARGUMENT_ERROR */);
4983 return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);
4984 };
4985 /**
4986 * Always set to {@link ProviderId}.PASSWORD, even for email link.
4987 */
4988 EmailAuthProvider.PROVIDER_ID = "password" /* PASSWORD */;
4989 /**
4990 * Always set to {@link SignInMethod}.EMAIL_PASSWORD.
4991 */
4992 EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = "password" /* EMAIL_PASSWORD */;
4993 /**
4994 * Always set to {@link SignInMethod}.EMAIL_LINK.
4995 */
4996 EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = "emailLink" /* EMAIL_LINK */;
4997 return EmailAuthProvider;
4998}());
4999
5000/**
5001 * @license
5002 * Copyright 2020 Google LLC
5003 *
5004 * Licensed under the Apache License, Version 2.0 (the "License");
5005 * you may not use this file except in compliance with the License.
5006 * You may obtain a copy of the License at
5007 *
5008 * http://www.apache.org/licenses/LICENSE-2.0
5009 *
5010 * Unless required by applicable law or agreed to in writing, software
5011 * distributed under the License is distributed on an "AS IS" BASIS,
5012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5013 * See the License for the specific language governing permissions and
5014 * limitations under the License.
5015 */
5016/**
5017 * The base class for all Federated providers (OAuth (including OIDC), SAML).
5018 *
5019 * This class is not meant to be instantiated directly.
5020 *
5021 * @public
5022 */
5023var FederatedAuthProvider = /** @class */ (function () {
5024 /**
5025 * Constructor for generic OAuth providers.
5026 *
5027 * @param providerId - Provider for which credentials should be generated.
5028 */
5029 function FederatedAuthProvider(providerId) {
5030 this.providerId = providerId;
5031 /** @internal */
5032 this.defaultLanguageCode = null;
5033 /** @internal */
5034 this.customParameters = {};
5035 }
5036 /**
5037 * Set the language gode.
5038 *
5039 * @param languageCode - language code
5040 */
5041 FederatedAuthProvider.prototype.setDefaultLanguage = function (languageCode) {
5042 this.defaultLanguageCode = languageCode;
5043 };
5044 /**
5045 * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in
5046 * operations.
5047 *
5048 * @remarks
5049 * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,
5050 * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.
5051 *
5052 * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.
5053 */
5054 FederatedAuthProvider.prototype.setCustomParameters = function (customOAuthParameters) {
5055 this.customParameters = customOAuthParameters;
5056 return this;
5057 };
5058 /**
5059 * Retrieve the current list of {@link CustomParameters}.
5060 */
5061 FederatedAuthProvider.prototype.getCustomParameters = function () {
5062 return this.customParameters;
5063 };
5064 return FederatedAuthProvider;
5065}());
5066
5067/**
5068 * @license
5069 * Copyright 2019 Google LLC
5070 *
5071 * Licensed under the Apache License, Version 2.0 (the "License");
5072 * you may not use this file except in compliance with the License.
5073 * You may obtain a copy of the License at
5074 *
5075 * http://www.apache.org/licenses/LICENSE-2.0
5076 *
5077 * Unless required by applicable law or agreed to in writing, software
5078 * distributed under the License is distributed on an "AS IS" BASIS,
5079 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5080 * See the License for the specific language governing permissions and
5081 * limitations under the License.
5082 */
5083/**
5084 * Common code to all OAuth providers. This is separate from the
5085 * {@link OAuthProvider} so that child providers (like
5086 * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.
5087 * Instead, they rely on a static `credential` method.
5088 */
5089var BaseOAuthProvider = /** @class */ (function (_super) {
5090 __extends(BaseOAuthProvider, _super);
5091 function BaseOAuthProvider() {
5092 var _this = _super !== null && _super.apply(this, arguments) || this;
5093 /** @internal */
5094 _this.scopes = [];
5095 return _this;
5096 }
5097 /**
5098 * Add an OAuth scope to the credential.
5099 *
5100 * @param scope - Provider OAuth scope to add.
5101 */
5102 BaseOAuthProvider.prototype.addScope = function (scope) {
5103 // If not already added, add scope to list.
5104 if (!this.scopes.includes(scope)) {
5105 this.scopes.push(scope);
5106 }
5107 return this;
5108 };
5109 /**
5110 * Retrieve the current list of OAuth scopes.
5111 */
5112 BaseOAuthProvider.prototype.getScopes = function () {
5113 return __spreadArray([], this.scopes);
5114 };
5115 return BaseOAuthProvider;
5116}(FederatedAuthProvider));
5117/**
5118 * Provider for generating generic {@link OAuthCredential}.
5119 *
5120 * @example
5121 * ```javascript
5122 * // Sign in using a redirect.
5123 * const provider = new OAuthProvider('google.com');
5124 * // Start a sign in process for an unauthenticated user.
5125 * provider.addScope('profile');
5126 * provider.addScope('email');
5127 * await signInWithRedirect(auth, provider);
5128 * // This will trigger a full page redirect away from your app
5129 *
5130 * // After returning from the redirect when your app initializes you can obtain the result
5131 * const result = await getRedirectResult(auth);
5132 * if (result) {
5133 * // This is the signed-in user
5134 * const user = result.user;
5135 * // This gives you a OAuth Access Token for the provider.
5136 * const credential = provider.credentialFromResult(auth, result);
5137 * const token = credential.accessToken;
5138 * }
5139 * ```
5140 *
5141 * @example
5142 * ```javascript
5143 * // Sign in using a popup.
5144 * const provider = new OAuthProvider('google.com');
5145 * provider.addScope('profile');
5146 * provider.addScope('email');
5147 * const result = await signInWithPopup(auth, provider);
5148 *
5149 * // The signed-in user info.
5150 * const user = result.user;
5151 * // This gives you a OAuth Access Token for the provider.
5152 * const credential = provider.credentialFromResult(auth, result);
5153 * const token = credential.accessToken;
5154 * ```
5155 * @public
5156 */
5157var OAuthProvider = /** @class */ (function (_super) {
5158 __extends(OAuthProvider, _super);
5159 function OAuthProvider() {
5160 return _super !== null && _super.apply(this, arguments) || this;
5161 }
5162 /**
5163 * Creates an {@link OAuthCredential} from a JSON string or a plain object.
5164 * @param json - A plain object or a JSON string
5165 */
5166 OAuthProvider.credentialFromJSON = function (json) {
5167 var obj = typeof json === 'string' ? JSON.parse(json) : json;
5168 _assert('providerId' in obj && 'signInMethod' in obj, "argument-error" /* ARGUMENT_ERROR */);
5169 return OAuthCredential._fromParams(obj);
5170 };
5171 /**
5172 * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.
5173 *
5174 * @remarks
5175 * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of
5176 * the raw nonce must match the nonce field in the ID token.
5177 *
5178 * @example
5179 * ```javascript
5180 * // `googleUser` from the onsuccess Google Sign In callback.
5181 * // Initialize a generate OAuth provider with a `google.com` providerId.
5182 * const provider = new OAuthProvider('google.com');
5183 * const credential = provider.credential({
5184 * idToken: googleUser.getAuthResponse().id_token,
5185 * });
5186 * const result = await signInWithCredential(credential);
5187 * ```
5188 *
5189 * @param params - Either the options object containing the ID token, access token and raw nonce
5190 * or the ID token string.
5191 */
5192 OAuthProvider.prototype.credential = function (params) {
5193 return this._credential(__assign(__assign({}, params), { nonce: params.rawNonce }));
5194 };
5195 /** An internal credential method that accepts more permissive options */
5196 OAuthProvider.prototype._credential = function (params) {
5197 _assert(params.idToken || params.accessToken, "argument-error" /* ARGUMENT_ERROR */);
5198 // For OAuthCredential, sign in method is same as providerId.
5199 return OAuthCredential._fromParams(__assign(__assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));
5200 };
5201 /**
5202 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
5203 *
5204 * @param userCredential - The user credential.
5205 */
5206 OAuthProvider.credentialFromResult = function (userCredential) {
5207 return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);
5208 };
5209 /**
5210 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
5211 * thrown during a sign-in, link, or reauthenticate operation.
5212 *
5213 * @param userCredential - The user credential.
5214 */
5215 OAuthProvider.credentialFromError = function (error) {
5216 return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));
5217 };
5218 OAuthProvider.oauthCredentialFromTaggedObject = function (_a) {
5219 var tokenResponse = _a._tokenResponse;
5220 if (!tokenResponse) {
5221 return null;
5222 }
5223 var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret, pendingToken = _b.pendingToken, nonce = _b.nonce, providerId = _b.providerId;
5224 if (!oauthAccessToken &&
5225 !oauthTokenSecret &&
5226 !oauthIdToken &&
5227 !pendingToken) {
5228 return null;
5229 }
5230 if (!providerId) {
5231 return null;
5232 }
5233 try {
5234 return new OAuthProvider(providerId)._credential({
5235 idToken: oauthIdToken,
5236 accessToken: oauthAccessToken,
5237 nonce: nonce,
5238 pendingToken: pendingToken
5239 });
5240 }
5241 catch (e) {
5242 return null;
5243 }
5244 };
5245 return OAuthProvider;
5246}(BaseOAuthProvider));
5247
5248/**
5249 * @license
5250 * Copyright 2020 Google LLC
5251 *
5252 * Licensed under the Apache License, Version 2.0 (the "License");
5253 * you may not use this file except in compliance with the License.
5254 * You may obtain a copy of the License at
5255 *
5256 * http://www.apache.org/licenses/LICENSE-2.0
5257 *
5258 * Unless required by applicable law or agreed to in writing, software
5259 * distributed under the License is distributed on an "AS IS" BASIS,
5260 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5261 * See the License for the specific language governing permissions and
5262 * limitations under the License.
5263 */
5264/**
5265 * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.
5266 *
5267 * @example
5268 * ```javascript
5269 * // Sign in using a redirect.
5270 * const provider = new FacebookAuthProvider();
5271 * // Start a sign in process for an unauthenticated user.
5272 * provider.addScope('user_birthday');
5273 * await signInWithRedirect(auth, provider);
5274 * // This will trigger a full page redirect away from your app
5275 *
5276 * // After returning from the redirect when your app initializes you can obtain the result
5277 * const result = await getRedirectResult(auth);
5278 * if (result) {
5279 * // This is the signed-in user
5280 * const user = result.user;
5281 * // This gives you a Facebook Access Token.
5282 * const credential = FacebookAuthProvider.credentialFromResult(result);
5283 * const token = credential.accessToken;
5284 * }
5285 * ```
5286 *
5287 * @example
5288 * ```javascript
5289 * // Sign in using a popup.
5290 * const provider = new FacebookAuthProvider();
5291 * provider.addScope('user_birthday');
5292 * const result = await signInWithPopup(auth, provider);
5293 *
5294 * // The signed-in user info.
5295 * const user = result.user;
5296 * // This gives you a Facebook Access Token.
5297 * const credential = FacebookAuthProvider.credentialFromResult(result);
5298 * const token = credential.accessToken;
5299 * ```
5300 *
5301 * @public
5302 */
5303var FacebookAuthProvider = /** @class */ (function (_super) {
5304 __extends(FacebookAuthProvider, _super);
5305 function FacebookAuthProvider() {
5306 return _super.call(this, "facebook.com" /* FACEBOOK */) || this;
5307 }
5308 /**
5309 * Creates a credential for Facebook.
5310 *
5311 * @example
5312 * ```javascript
5313 * // `event` from the Facebook auth.authResponseChange callback.
5314 * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);
5315 * const result = await signInWithCredential(credential);
5316 * ```
5317 *
5318 * @param accessToken - Facebook access token.
5319 */
5320 FacebookAuthProvider.credential = function (accessToken) {
5321 return OAuthCredential._fromParams({
5322 providerId: FacebookAuthProvider.PROVIDER_ID,
5323 signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,
5324 accessToken: accessToken
5325 });
5326 };
5327 /**
5328 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
5329 *
5330 * @param userCredential - The user credential.
5331 */
5332 FacebookAuthProvider.credentialFromResult = function (userCredential) {
5333 return FacebookAuthProvider.credentialFromTaggedObject(userCredential);
5334 };
5335 /**
5336 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
5337 * thrown during a sign-in, link, or reauthenticate operation.
5338 *
5339 * @param userCredential - The user credential.
5340 */
5341 FacebookAuthProvider.credentialFromError = function (error) {
5342 return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));
5343 };
5344 FacebookAuthProvider.credentialFromTaggedObject = function (_a) {
5345 var tokenResponse = _a._tokenResponse;
5346 if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
5347 return null;
5348 }
5349 if (!tokenResponse.oauthAccessToken) {
5350 return null;
5351 }
5352 try {
5353 return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);
5354 }
5355 catch (_b) {
5356 return null;
5357 }
5358 };
5359 /** Always set to {@link SignInMethod}.FACEBOOK. */
5360 FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = "facebook.com" /* FACEBOOK */;
5361 /** Always set to {@link ProviderId}.FACEBOOK. */
5362 FacebookAuthProvider.PROVIDER_ID = "facebook.com" /* FACEBOOK */;
5363 return FacebookAuthProvider;
5364}(BaseOAuthProvider));
5365
5366/**
5367 * @license
5368 * Copyright 2020 Google LLC
5369 *
5370 * Licensed under the Apache License, Version 2.0 (the "License");
5371 * you may not use this file except in compliance with the License.
5372 * You may obtain a copy of the License at
5373 *
5374 * http://www.apache.org/licenses/LICENSE-2.0
5375 *
5376 * Unless required by applicable law or agreed to in writing, software
5377 * distributed under the License is distributed on an "AS IS" BASIS,
5378 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5379 * See the License for the specific language governing permissions and
5380 * limitations under the License.
5381 */
5382/**
5383 * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.
5384 *
5385 * @example
5386 * ```javascript
5387 * // Sign in using a redirect.
5388 * const provider = new GoogleAuthProvider();
5389 * // Start a sign in process for an unauthenticated user.
5390 * provider.addScope('profile');
5391 * provider.addScope('email');
5392 * await signInWithRedirect(auth, provider);
5393 * // This will trigger a full page redirect away from your app
5394 *
5395 * // After returning from the redirect when your app initializes you can obtain the result
5396 * const result = await getRedirectResult(auth);
5397 * if (result) {
5398 * // This is the signed-in user
5399 * const user = result.user;
5400 * // This gives you a Google Access Token.
5401 * const credential = GoogleAuthProvider.credentialFromResult(result);
5402 * const token = credential.accessToken;
5403 * }
5404 * ```
5405 *
5406 * @example
5407 * ```javascript
5408 * // Sign in using a popup.
5409 * const provider = new GoogleAuthProvider();
5410 * provider.addScope('profile');
5411 * provider.addScope('email');
5412 * const result = await signInWithPopup(auth, provider);
5413 *
5414 * // The signed-in user info.
5415 * const user = result.user;
5416 * // This gives you a Google Access Token.
5417 * const credential = GoogleAuthProvider.credentialFromResult(result);
5418 * const token = credential.accessToken;
5419 * ```
5420 *
5421 * @public
5422 */
5423var GoogleAuthProvider = /** @class */ (function (_super) {
5424 __extends(GoogleAuthProvider, _super);
5425 function GoogleAuthProvider() {
5426 var _this = _super.call(this, "google.com" /* GOOGLE */) || this;
5427 _this.addScope('profile');
5428 return _this;
5429 }
5430 /**
5431 * Creates a credential for Google. At least one of ID token and access token is required.
5432 *
5433 * @example
5434 * ```javascript
5435 * // \`googleUser\` from the onsuccess Google Sign In callback.
5436 * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
5437 * const result = await signInWithCredential(credential);
5438 * ```
5439 *
5440 * @param idToken - Google ID token.
5441 * @param accessToken - Google access token.
5442 */
5443 GoogleAuthProvider.credential = function (idToken, accessToken) {
5444 return OAuthCredential._fromParams({
5445 providerId: GoogleAuthProvider.PROVIDER_ID,
5446 signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,
5447 idToken: idToken,
5448 accessToken: accessToken
5449 });
5450 };
5451 /**
5452 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
5453 *
5454 * @param userCredential - The user credential.
5455 */
5456 GoogleAuthProvider.credentialFromResult = function (userCredential) {
5457 return GoogleAuthProvider.credentialFromTaggedObject(userCredential);
5458 };
5459 /**
5460 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
5461 * thrown during a sign-in, link, or reauthenticate operation.
5462 *
5463 * @param userCredential - The user credential.
5464 */
5465 GoogleAuthProvider.credentialFromError = function (error) {
5466 return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));
5467 };
5468 GoogleAuthProvider.credentialFromTaggedObject = function (_a) {
5469 var tokenResponse = _a._tokenResponse;
5470 if (!tokenResponse) {
5471 return null;
5472 }
5473 var _b = tokenResponse, oauthIdToken = _b.oauthIdToken, oauthAccessToken = _b.oauthAccessToken;
5474 if (!oauthIdToken && !oauthAccessToken) {
5475 // This could be an oauth 1 credential or a phone credential
5476 return null;
5477 }
5478 try {
5479 return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);
5480 }
5481 catch (_c) {
5482 return null;
5483 }
5484 };
5485 /** Always set to {@link SignInMethod}.GOOGLE. */
5486 GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = "google.com" /* GOOGLE */;
5487 /** Always set to {@link ProviderId}.GOOGLE. */
5488 GoogleAuthProvider.PROVIDER_ID = "google.com" /* GOOGLE */;
5489 return GoogleAuthProvider;
5490}(BaseOAuthProvider));
5491
5492/**
5493 * @license
5494 * Copyright 2020 Google LLC
5495 *
5496 * Licensed under the Apache License, Version 2.0 (the "License");
5497 * you may not use this file except in compliance with the License.
5498 * You may obtain a copy of the License at
5499 *
5500 * http://www.apache.org/licenses/LICENSE-2.0
5501 *
5502 * Unless required by applicable law or agreed to in writing, software
5503 * distributed under the License is distributed on an "AS IS" BASIS,
5504 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5505 * See the License for the specific language governing permissions and
5506 * limitations under the License.
5507 */
5508/**
5509 * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.
5510 *
5511 * @remarks
5512 * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use
5513 * the {@link signInWithPopup} handler:
5514 *
5515 * @example
5516 * ```javascript
5517 * // Sign in using a redirect.
5518 * const provider = new GithubAuthProvider();
5519 * // Start a sign in process for an unauthenticated user.
5520 * provider.addScope('repo');
5521 * await signInWithRedirect(auth, provider);
5522 * // This will trigger a full page redirect away from your app
5523 *
5524 * // After returning from the redirect when your app initializes you can obtain the result
5525 * const result = await getRedirectResult(auth);
5526 * if (result) {
5527 * // This is the signed-in user
5528 * const user = result.user;
5529 * // This gives you a Github Access Token.
5530 * const credential = GithubAuthProvider.credentialFromResult(result);
5531 * const token = credential.accessToken;
5532 * }
5533 * ```
5534 *
5535 * @example
5536 * ```javascript
5537 * // Sign in using a popup.
5538 * const provider = new GithubAuthProvider();
5539 * provider.addScope('repo');
5540 * const result = await signInWithPopup(auth, provider);
5541 *
5542 * // The signed-in user info.
5543 * const user = result.user;
5544 * // This gives you a Github Access Token.
5545 * const credential = GithubAuthProvider.credentialFromResult(result);
5546 * const token = credential.accessToken;
5547 * ```
5548 * @public
5549 */
5550var GithubAuthProvider = /** @class */ (function (_super) {
5551 __extends(GithubAuthProvider, _super);
5552 function GithubAuthProvider() {
5553 return _super.call(this, "github.com" /* GITHUB */) || this;
5554 }
5555 /**
5556 * Creates a credential for Github.
5557 *
5558 * @param accessToken - Github access token.
5559 */
5560 GithubAuthProvider.credential = function (accessToken) {
5561 return OAuthCredential._fromParams({
5562 providerId: GithubAuthProvider.PROVIDER_ID,
5563 signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,
5564 accessToken: accessToken
5565 });
5566 };
5567 /**
5568 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
5569 *
5570 * @param userCredential - The user credential.
5571 */
5572 GithubAuthProvider.credentialFromResult = function (userCredential) {
5573 return GithubAuthProvider.credentialFromTaggedObject(userCredential);
5574 };
5575 /**
5576 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
5577 * thrown during a sign-in, link, or reauthenticate operation.
5578 *
5579 * @param userCredential - The user credential.
5580 */
5581 GithubAuthProvider.credentialFromError = function (error) {
5582 return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));
5583 };
5584 GithubAuthProvider.credentialFromTaggedObject = function (_a) {
5585 var tokenResponse = _a._tokenResponse;
5586 if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {
5587 return null;
5588 }
5589 if (!tokenResponse.oauthAccessToken) {
5590 return null;
5591 }
5592 try {
5593 return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);
5594 }
5595 catch (_b) {
5596 return null;
5597 }
5598 };
5599 /** Always set to {@link SignInMethod}.GITHUB. */
5600 GithubAuthProvider.GITHUB_SIGN_IN_METHOD = "github.com" /* GITHUB */;
5601 /** Always set to {@link ProviderId}.GITHUB. */
5602 GithubAuthProvider.PROVIDER_ID = "github.com" /* GITHUB */;
5603 return GithubAuthProvider;
5604}(BaseOAuthProvider));
5605
5606/**
5607 * @license
5608 * Copyright 2020 Google LLC
5609 *
5610 * Licensed under the Apache License, Version 2.0 (the "License");
5611 * you may not use this file except in compliance with the License.
5612 * You may obtain a copy of the License at
5613 *
5614 * http://www.apache.org/licenses/LICENSE-2.0
5615 *
5616 * Unless required by applicable law or agreed to in writing, software
5617 * distributed under the License is distributed on an "AS IS" BASIS,
5618 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5619 * See the License for the specific language governing permissions and
5620 * limitations under the License.
5621 */
5622var IDP_REQUEST_URI = 'http://localhost';
5623/**
5624 * @public
5625 */
5626var SAMLAuthCredential = /** @class */ (function (_super) {
5627 __extends(SAMLAuthCredential, _super);
5628 /** @internal */
5629 function SAMLAuthCredential(providerId, pendingToken) {
5630 var _this = _super.call(this, providerId, providerId) || this;
5631 _this.pendingToken = pendingToken;
5632 return _this;
5633 }
5634 /** @internal */
5635 SAMLAuthCredential.prototype._getIdTokenResponse = function (auth) {
5636 var request = this.buildRequest();
5637 return signInWithIdp(auth, request);
5638 };
5639 /** @internal */
5640 SAMLAuthCredential.prototype._linkToIdToken = function (auth, idToken) {
5641 var request = this.buildRequest();
5642 request.idToken = idToken;
5643 return signInWithIdp(auth, request);
5644 };
5645 /** @internal */
5646 SAMLAuthCredential.prototype._getReauthenticationResolver = function (auth) {
5647 var request = this.buildRequest();
5648 request.autoCreate = false;
5649 return signInWithIdp(auth, request);
5650 };
5651 /** {@inheritdoc AuthCredential.toJSON} */
5652 SAMLAuthCredential.prototype.toJSON = function () {
5653 return {
5654 signInMethod: this.signInMethod,
5655 providerId: this.providerId,
5656 pendingToken: this.pendingToken
5657 };
5658 };
5659 /**
5660 * Static method to deserialize a JSON representation of an object into an
5661 * {@link AuthCredential}.
5662 *
5663 * @param json - Input can be either Object or the stringified representation of the object.
5664 * When string is provided, JSON.parse would be called first.
5665 *
5666 * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.
5667 */
5668 SAMLAuthCredential.fromJSON = function (json) {
5669 var obj = typeof json === 'string' ? JSON.parse(json) : json;
5670 var providerId = obj.providerId, signInMethod = obj.signInMethod, pendingToken = obj.pendingToken;
5671 if (!providerId ||
5672 !signInMethod ||
5673 !pendingToken ||
5674 providerId !== signInMethod) {
5675 return null;
5676 }
5677 return new SAMLAuthCredential(providerId, pendingToken);
5678 };
5679 /**
5680 * Helper static method to avoid exposing the constructor to end users.
5681 *
5682 * @internal
5683 */
5684 SAMLAuthCredential._create = function (providerId, pendingToken) {
5685 return new SAMLAuthCredential(providerId, pendingToken);
5686 };
5687 SAMLAuthCredential.prototype.buildRequest = function () {
5688 return {
5689 requestUri: IDP_REQUEST_URI,
5690 returnSecureToken: true,
5691 pendingToken: this.pendingToken
5692 };
5693 };
5694 return SAMLAuthCredential;
5695}(AuthCredential));
5696
5697/**
5698 * @license
5699 * Copyright 2020 Google LLC
5700 *
5701 * Licensed under the Apache License, Version 2.0 (the "License");
5702 * you may not use this file except in compliance with the License.
5703 * You may obtain a copy of the License at
5704 *
5705 * http://www.apache.org/licenses/LICENSE-2.0
5706 *
5707 * Unless required by applicable law or agreed to in writing, software
5708 * distributed under the License is distributed on an "AS IS" BASIS,
5709 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5710 * See the License for the specific language governing permissions and
5711 * limitations under the License.
5712 */
5713var SAML_PROVIDER_PREFIX = 'saml.';
5714/**
5715 * An {@link AuthProvider} for SAML.
5716 *
5717 * @public
5718 */
5719var SAMLAuthProvider = /** @class */ (function (_super) {
5720 __extends(SAMLAuthProvider, _super);
5721 /**
5722 * Constructor. The providerId must start with "saml."
5723 * @param providerId - SAML provider ID.
5724 */
5725 function SAMLAuthProvider(providerId) {
5726 var _this = this;
5727 _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), "argument-error" /* ARGUMENT_ERROR */);
5728 _this = _super.call(this, providerId) || this;
5729 return _this;
5730 }
5731 /**
5732 * Generates an {@link AuthCredential} from a {@link UserCredential} after a
5733 * successful SAML flow completes.
5734 *
5735 * @remarks
5736 *
5737 * For example, to get an {@link AuthCredential}, you could write the
5738 * following code:
5739 *
5740 * ```js
5741 * const userCredential = await signInWithPopup(auth, samlProvider);
5742 * const credential = SAMLAuthProvider.credentialFromResult(userCredential);
5743 * ```
5744 *
5745 * @param userCredential - The user credential.
5746 */
5747 SAMLAuthProvider.credentialFromResult = function (userCredential) {
5748 return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);
5749 };
5750 /**
5751 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
5752 * thrown during a sign-in, link, or reauthenticate operation.
5753 *
5754 * @param userCredential - The user credential.
5755 */
5756 SAMLAuthProvider.credentialFromError = function (error) {
5757 return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));
5758 };
5759 /**
5760 * Creates an {@link AuthCredential} from a JSON string or a plain object.
5761 * @param json - A plain object or a JSON string
5762 */
5763 SAMLAuthProvider.credentialFromJSON = function (json) {
5764 var credential = SAMLAuthCredential.fromJSON(json);
5765 _assert(credential, "argument-error" /* ARGUMENT_ERROR */);
5766 return credential;
5767 };
5768 SAMLAuthProvider.samlCredentialFromTaggedObject = function (_a) {
5769 var tokenResponse = _a._tokenResponse;
5770 if (!tokenResponse) {
5771 return null;
5772 }
5773 var _b = tokenResponse, pendingToken = _b.pendingToken, providerId = _b.providerId;
5774 if (!pendingToken || !providerId) {
5775 return null;
5776 }
5777 try {
5778 return SAMLAuthCredential._create(providerId, pendingToken);
5779 }
5780 catch (e) {
5781 return null;
5782 }
5783 };
5784 return SAMLAuthProvider;
5785}(FederatedAuthProvider));
5786
5787/**
5788 * @license
5789 * Copyright 2020 Google LLC
5790 *
5791 * Licensed under the Apache License, Version 2.0 (the "License");
5792 * you may not use this file except in compliance with the License.
5793 * You may obtain a copy of the License at
5794 *
5795 * http://www.apache.org/licenses/LICENSE-2.0
5796 *
5797 * Unless required by applicable law or agreed to in writing, software
5798 * distributed under the License is distributed on an "AS IS" BASIS,
5799 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5800 * See the License for the specific language governing permissions and
5801 * limitations under the License.
5802 */
5803/**
5804 * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.
5805 *
5806 * @example
5807 * ```javascript
5808 * // Sign in using a redirect.
5809 * const provider = new TwitterAuthProvider();
5810 * // Start a sign in process for an unauthenticated user.
5811 * await signInWithRedirect(auth, provider);
5812 * // This will trigger a full page redirect away from your app
5813 *
5814 * // After returning from the redirect when your app initializes you can obtain the result
5815 * const result = await getRedirectResult(auth);
5816 * if (result) {
5817 * // This is the signed-in user
5818 * const user = result.user;
5819 * // This gives you a Twitter Access Token and Secret.
5820 * const credential = TwitterAuthProvider.credentialFromResult(result);
5821 * const token = credential.accessToken;
5822 * const secret = credential.secret;
5823 * }
5824 * ```
5825 *
5826 * @example
5827 * ```javascript
5828 * // Sign in using a popup.
5829 * const provider = new TwitterAuthProvider();
5830 * const result = await signInWithPopup(auth, provider);
5831 *
5832 * // The signed-in user info.
5833 * const user = result.user;
5834 * // This gives you a Twitter Access Token and Secret.
5835 * const credential = TwitterAuthProvider.credentialFromResult(result);
5836 * const token = credential.accessToken;
5837 * const secret = credential.secret;
5838 * ```
5839 *
5840 * @public
5841 */
5842var TwitterAuthProvider = /** @class */ (function (_super) {
5843 __extends(TwitterAuthProvider, _super);
5844 function TwitterAuthProvider() {
5845 return _super.call(this, "twitter.com" /* TWITTER */) || this;
5846 }
5847 /**
5848 * Creates a credential for Twitter.
5849 *
5850 * @param token - Twitter access token.
5851 * @param secret - Twitter secret.
5852 */
5853 TwitterAuthProvider.credential = function (token, secret) {
5854 return OAuthCredential._fromParams({
5855 providerId: TwitterAuthProvider.PROVIDER_ID,
5856 signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,
5857 oauthToken: token,
5858 oauthTokenSecret: secret
5859 });
5860 };
5861 /**
5862 * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.
5863 *
5864 * @param userCredential - The user credential.
5865 */
5866 TwitterAuthProvider.credentialFromResult = function (userCredential) {
5867 return TwitterAuthProvider.credentialFromTaggedObject(userCredential);
5868 };
5869 /**
5870 * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was
5871 * thrown during a sign-in, link, or reauthenticate operation.
5872 *
5873 * @param userCredential - The user credential.
5874 */
5875 TwitterAuthProvider.credentialFromError = function (error) {
5876 return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));
5877 };
5878 TwitterAuthProvider.credentialFromTaggedObject = function (_a) {
5879 var tokenResponse = _a._tokenResponse;
5880 if (!tokenResponse) {
5881 return null;
5882 }
5883 var _b = tokenResponse, oauthAccessToken = _b.oauthAccessToken, oauthTokenSecret = _b.oauthTokenSecret;
5884 if (!oauthAccessToken || !oauthTokenSecret) {
5885 return null;
5886 }
5887 try {
5888 return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);
5889 }
5890 catch (_c) {
5891 return null;
5892 }
5893 };
5894 /** Always set to {@link SignInMethod}.TWITTER. */
5895 TwitterAuthProvider.TWITTER_SIGN_IN_METHOD = "twitter.com" /* TWITTER */;
5896 /** Always set to {@link ProviderId}.TWITTER. */
5897 TwitterAuthProvider.PROVIDER_ID = "twitter.com" /* TWITTER */;
5898 return TwitterAuthProvider;
5899}(BaseOAuthProvider));
5900
5901/**
5902 * @license
5903 * Copyright 2020 Google LLC
5904 *
5905 * Licensed under the Apache License, Version 2.0 (the "License");
5906 * you may not use this file except in compliance with the License.
5907 * You may obtain a copy of the License at
5908 *
5909 * http://www.apache.org/licenses/LICENSE-2.0
5910 *
5911 * Unless required by applicable law or agreed to in writing, software
5912 * distributed under the License is distributed on an "AS IS" BASIS,
5913 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5914 * See the License for the specific language governing permissions and
5915 * limitations under the License.
5916 */
5917function signUp(auth, request) {
5918 return __awaiter(this, void 0, void 0, function () {
5919 return __generator(this, function (_a) {
5920 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signUp" /* SIGN_UP */, _addTidIfNecessary(auth, request))];
5921 });
5922 });
5923}
5924
5925/**
5926 * @license
5927 * Copyright 2020 Google LLC
5928 *
5929 * Licensed under the Apache License, Version 2.0 (the "License");
5930 * you may not use this file except in compliance with the License.
5931 * You may obtain a copy of the License at
5932 *
5933 * http://www.apache.org/licenses/LICENSE-2.0
5934 *
5935 * Unless required by applicable law or agreed to in writing, software
5936 * distributed under the License is distributed on an "AS IS" BASIS,
5937 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5938 * See the License for the specific language governing permissions and
5939 * limitations under the License.
5940 */
5941var UserCredentialImpl = /** @class */ (function () {
5942 function UserCredentialImpl(params) {
5943 this.user = params.user;
5944 this.providerId = params.providerId;
5945 this._tokenResponse = params._tokenResponse;
5946 this.operationType = params.operationType;
5947 }
5948 UserCredentialImpl._fromIdTokenResponse = function (auth, operationType, idTokenResponse, isAnonymous) {
5949 if (isAnonymous === void 0) { isAnonymous = false; }
5950 return __awaiter(this, void 0, void 0, function () {
5951 var user, providerId, userCred;
5952 return __generator(this, function (_a) {
5953 switch (_a.label) {
5954 case 0: return [4 /*yield*/, UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous)];
5955 case 1:
5956 user = _a.sent();
5957 providerId = providerIdForResponse(idTokenResponse);
5958 userCred = new UserCredentialImpl({
5959 user: user,
5960 providerId: providerId,
5961 _tokenResponse: idTokenResponse,
5962 operationType: operationType
5963 });
5964 return [2 /*return*/, userCred];
5965 }
5966 });
5967 });
5968 };
5969 UserCredentialImpl._forOperation = function (user, operationType, response) {
5970 return __awaiter(this, void 0, void 0, function () {
5971 var providerId;
5972 return __generator(this, function (_a) {
5973 switch (_a.label) {
5974 case 0: return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
5975 case 1:
5976 _a.sent();
5977 providerId = providerIdForResponse(response);
5978 return [2 /*return*/, new UserCredentialImpl({
5979 user: user,
5980 providerId: providerId,
5981 _tokenResponse: response,
5982 operationType: operationType
5983 })];
5984 }
5985 });
5986 });
5987 };
5988 return UserCredentialImpl;
5989}());
5990function providerIdForResponse(response) {
5991 if (response.providerId) {
5992 return response.providerId;
5993 }
5994 if ('phoneNumber' in response) {
5995 return "phone" /* PHONE */;
5996 }
5997 return null;
5998}
5999
6000/**
6001 * @license
6002 * Copyright 2020 Google LLC
6003 *
6004 * Licensed under the Apache License, Version 2.0 (the "License");
6005 * you may not use this file except in compliance with the License.
6006 * You may obtain a copy of the License at
6007 *
6008 * http://www.apache.org/licenses/LICENSE-2.0
6009 *
6010 * Unless required by applicable law or agreed to in writing, software
6011 * distributed under the License is distributed on an "AS IS" BASIS,
6012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6013 * See the License for the specific language governing permissions and
6014 * limitations under the License.
6015 */
6016/**
6017 * Asynchronously signs in as an anonymous user.
6018 *
6019 * @remarks
6020 * If there is already an anonymous user signed in, that user will be returned; otherwise, a
6021 * new anonymous user identity will be created and returned.
6022 *
6023 * @param auth - The {@link Auth} instance.
6024 *
6025 * @public
6026 */
6027function signInAnonymously(auth) {
6028 var _a;
6029 return __awaiter(this, void 0, void 0, function () {
6030 var authInternal, response, userCredential;
6031 return __generator(this, function (_b) {
6032 switch (_b.label) {
6033 case 0:
6034 authInternal = _castAuth(auth);
6035 return [4 /*yield*/, authInternal._initializationPromise];
6036 case 1:
6037 _b.sent();
6038 if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {
6039 // If an anonymous user is already signed in, no need to sign them in again.
6040 return [2 /*return*/, new UserCredentialImpl({
6041 user: authInternal.currentUser,
6042 providerId: null,
6043 operationType: "signIn" /* SIGN_IN */
6044 })];
6045 }
6046 return [4 /*yield*/, signUp(authInternal, {
6047 returnSecureToken: true
6048 })];
6049 case 2:
6050 response = _b.sent();
6051 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* SIGN_IN */, response, true)];
6052 case 3:
6053 userCredential = _b.sent();
6054 return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
6055 case 4:
6056 _b.sent();
6057 return [2 /*return*/, userCredential];
6058 }
6059 });
6060 });
6061}
6062
6063/**
6064 * @license
6065 * Copyright 2020 Google LLC
6066 *
6067 * Licensed under the Apache License, Version 2.0 (the "License");
6068 * you may not use this file except in compliance with the License.
6069 * You may obtain a copy of the License at
6070 *
6071 * http://www.apache.org/licenses/LICENSE-2.0
6072 *
6073 * Unless required by applicable law or agreed to in writing, software
6074 * distributed under the License is distributed on an "AS IS" BASIS,
6075 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6076 * See the License for the specific language governing permissions and
6077 * limitations under the License.
6078 */
6079var MultiFactorError = /** @class */ (function (_super) {
6080 __extends(MultiFactorError, _super);
6081 function MultiFactorError(auth, error, operationType, user) {
6082 var _a;
6083 var _this = _super.call(this, error.code, error.message) || this;
6084 _this.operationType = operationType;
6085 _this.user = user;
6086 // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
6087 Object.setPrototypeOf(_this, MultiFactorError.prototype);
6088 _this.customData = {
6089 appName: auth.name,
6090 tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,
6091 _serverResponse: error.customData._serverResponse,
6092 operationType: operationType,
6093 };
6094 return _this;
6095 }
6096 MultiFactorError._fromErrorAndOperation = function (auth, error, operationType, user) {
6097 return new MultiFactorError(auth, error, operationType, user);
6098 };
6099 return MultiFactorError;
6100}(FirebaseError));
6101function _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {
6102 var idTokenProvider = operationType === "reauthenticate" /* REAUTHENTICATE */
6103 ? credential._getReauthenticationResolver(auth)
6104 : credential._getIdTokenResponse(auth);
6105 return idTokenProvider.catch(function (error) {
6106 if (error.code === "auth/" + "multi-factor-auth-required" /* MFA_REQUIRED */) {
6107 throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);
6108 }
6109 throw error;
6110 });
6111}
6112
6113/**
6114 * @license
6115 * Copyright 2020 Google LLC
6116 *
6117 * Licensed under the Apache License, Version 2.0 (the "License");
6118 * you may not use this file except in compliance with the License.
6119 * You may obtain a copy of the License at
6120 *
6121 * http://www.apache.org/licenses/LICENSE-2.0
6122 *
6123 * Unless required by applicable law or agreed to in writing, software
6124 * distributed under the License is distributed on an "AS IS" BASIS,
6125 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6126 * See the License for the specific language governing permissions and
6127 * limitations under the License.
6128 */
6129/**
6130 * Takes a set of UserInfo provider data and converts it to a set of names
6131 */
6132function providerDataAsNames(providerData) {
6133 return new Set(providerData
6134 .map(function (_a) {
6135 var providerId = _a.providerId;
6136 return providerId;
6137 })
6138 .filter(function (pid) { return !!pid; }));
6139}
6140
6141/**
6142 * @license
6143 * Copyright 2019 Google LLC
6144 *
6145 * Licensed under the Apache License, Version 2.0 (the "License");
6146 * you may not use this file except in compliance with the License.
6147 * You may obtain a copy of the License at
6148 *
6149 * http://www.apache.org/licenses/LICENSE-2.0
6150 *
6151 * Unless required by applicable law or agreed to in writing, software
6152 * distributed under the License is distributed on an "AS IS" BASIS,
6153 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6154 * See the License for the specific language governing permissions and
6155 * limitations under the License.
6156 */
6157/**
6158 * Unlinks a provider from a user account.
6159 *
6160 * @param user - The user.
6161 * @param providerId - The provider to unlink.
6162 *
6163 * @public
6164 */
6165function unlink(user, providerId) {
6166 return __awaiter(this, void 0, void 0, function () {
6167 var userInternal, providerUserInfo, _a, _b, providersLeft;
6168 var _c;
6169 return __generator(this, function (_d) {
6170 switch (_d.label) {
6171 case 0:
6172 userInternal = getModularInstance(user);
6173 return [4 /*yield*/, _assertLinkedStatus(true, userInternal, providerId)];
6174 case 1:
6175 _d.sent();
6176 _a = deleteLinkedAccounts;
6177 _b = [userInternal.auth];
6178 _c = {};
6179 return [4 /*yield*/, userInternal.getIdToken()];
6180 case 2: return [4 /*yield*/, _a.apply(void 0, _b.concat([(_c.idToken = _d.sent(),
6181 _c.deleteProvider = [providerId],
6182 _c)]))];
6183 case 3:
6184 providerUserInfo = (_d.sent()).providerUserInfo;
6185 providersLeft = providerDataAsNames(providerUserInfo || []);
6186 userInternal.providerData = userInternal.providerData.filter(function (pd) {
6187 return providersLeft.has(pd.providerId);
6188 });
6189 if (!providersLeft.has("phone" /* PHONE */)) {
6190 userInternal.phoneNumber = null;
6191 }
6192 return [4 /*yield*/, userInternal.auth._persistUserIfCurrent(userInternal)];
6193 case 4:
6194 _d.sent();
6195 return [2 /*return*/, userInternal];
6196 }
6197 });
6198 });
6199}
6200function _link$1(user, credential, bypassAuthState) {
6201 if (bypassAuthState === void 0) { bypassAuthState = false; }
6202 return __awaiter(this, void 0, void 0, function () {
6203 var response, _a, _b, _c, _d, _e;
6204 return __generator(this, function (_f) {
6205 switch (_f.label) {
6206 case 0:
6207 _a = _logoutIfInvalidated;
6208 _b = [user];
6209 _d = (_c = credential)._linkToIdToken;
6210 _e = [user.auth];
6211 return [4 /*yield*/, user.getIdToken()];
6212 case 1: return [4 /*yield*/, _a.apply(void 0, _b.concat([_d.apply(_c, _e.concat([_f.sent()])), bypassAuthState]))];
6213 case 2:
6214 response = _f.sent();
6215 return [2 /*return*/, UserCredentialImpl._forOperation(user, "link" /* LINK */, response)];
6216 }
6217 });
6218 });
6219}
6220function _assertLinkedStatus(expected, user, provider) {
6221 return __awaiter(this, void 0, void 0, function () {
6222 var providerIds, code;
6223 return __generator(this, function (_a) {
6224 switch (_a.label) {
6225 case 0: return [4 /*yield*/, _reloadWithoutSaving(user)];
6226 case 1:
6227 _a.sent();
6228 providerIds = providerDataAsNames(user.providerData);
6229 code = expected === false
6230 ? "provider-already-linked" /* PROVIDER_ALREADY_LINKED */
6231 : "no-such-provider" /* NO_SUCH_PROVIDER */;
6232 _assert(providerIds.has(provider) === expected, user.auth, code);
6233 return [2 /*return*/];
6234 }
6235 });
6236 });
6237}
6238
6239/**
6240 * @license
6241 * Copyright 2019 Google LLC
6242 *
6243 * Licensed under the Apache License, Version 2.0 (the "License");
6244 * you may not use this file except in compliance with the License.
6245 * You may obtain a copy of the License at
6246 *
6247 * http://www.apache.org/licenses/LICENSE-2.0
6248 *
6249 * Unless required by applicable law or agreed to in writing, software
6250 * distributed under the License is distributed on an "AS IS" BASIS,
6251 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6252 * See the License for the specific language governing permissions and
6253 * limitations under the License.
6254 */
6255function _reauthenticate(user, credential, bypassAuthState) {
6256 if (bypassAuthState === void 0) { bypassAuthState = false; }
6257 return __awaiter(this, void 0, void 0, function () {
6258 var auth, operationType, response, parsed, localId, e_1;
6259 return __generator(this, function (_a) {
6260 switch (_a.label) {
6261 case 0:
6262 auth = user.auth;
6263 operationType = "reauthenticate" /* REAUTHENTICATE */;
6264 _a.label = 1;
6265 case 1:
6266 _a.trys.push([1, 3, , 4]);
6267 return [4 /*yield*/, _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState)];
6268 case 2:
6269 response = _a.sent();
6270 _assert(response.idToken, auth, "internal-error" /* INTERNAL_ERROR */);
6271 parsed = _parseToken(response.idToken);
6272 _assert(parsed, auth, "internal-error" /* INTERNAL_ERROR */);
6273 localId = parsed.sub;
6274 _assert(user.uid === localId, auth, "user-mismatch" /* USER_MISMATCH */);
6275 return [2 /*return*/, UserCredentialImpl._forOperation(user, operationType, response)];
6276 case 3:
6277 e_1 = _a.sent();
6278 // Convert user deleted error into user mismatch
6279 if ((e_1 === null || e_1 === void 0 ? void 0 : e_1.code) === "auth/" + "user-not-found" /* USER_DELETED */) {
6280 _fail(auth, "user-mismatch" /* USER_MISMATCH */);
6281 }
6282 throw e_1;
6283 case 4: return [2 /*return*/];
6284 }
6285 });
6286 });
6287}
6288
6289/**
6290 * @license
6291 * Copyright 2020 Google LLC
6292 *
6293 * Licensed under the Apache License, Version 2.0 (the "License");
6294 * you may not use this file except in compliance with the License.
6295 * You may obtain a copy of the License at
6296 *
6297 * http://www.apache.org/licenses/LICENSE-2.0
6298 *
6299 * Unless required by applicable law or agreed to in writing, software
6300 * distributed under the License is distributed on an "AS IS" BASIS,
6301 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6302 * See the License for the specific language governing permissions and
6303 * limitations under the License.
6304 */
6305function _signInWithCredential(auth, credential, bypassAuthState) {
6306 if (bypassAuthState === void 0) { bypassAuthState = false; }
6307 return __awaiter(this, void 0, void 0, function () {
6308 var operationType, response, userCredential;
6309 return __generator(this, function (_a) {
6310 switch (_a.label) {
6311 case 0:
6312 operationType = "signIn" /* SIGN_IN */;
6313 return [4 /*yield*/, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential)];
6314 case 1:
6315 response = _a.sent();
6316 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, operationType, response)];
6317 case 2:
6318 userCredential = _a.sent();
6319 if (!!bypassAuthState) return [3 /*break*/, 4];
6320 return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
6321 case 3:
6322 _a.sent();
6323 _a.label = 4;
6324 case 4: return [2 /*return*/, userCredential];
6325 }
6326 });
6327 });
6328}
6329/**
6330 * Asynchronously signs in with the given credentials.
6331 *
6332 * @remarks
6333 * An {@link AuthProvider} can be used to generate the credential.
6334 *
6335 * @param auth - The {@link Auth} instance.
6336 * @param credential - The auth credential.
6337 *
6338 * @public
6339 */
6340function signInWithCredential(auth, credential) {
6341 return __awaiter(this, void 0, void 0, function () {
6342 return __generator(this, function (_a) {
6343 return [2 /*return*/, _signInWithCredential(_castAuth(auth), credential)];
6344 });
6345 });
6346}
6347/**
6348 * Links the user account with the given credentials.
6349 *
6350 * @remarks
6351 * An {@link AuthProvider} can be used to generate the credential.
6352 *
6353 * @param user - The user.
6354 * @param credential - The auth credential.
6355 *
6356 * @public
6357 */
6358function linkWithCredential(user, credential) {
6359 return __awaiter(this, void 0, void 0, function () {
6360 var userInternal;
6361 return __generator(this, function (_a) {
6362 switch (_a.label) {
6363 case 0:
6364 userInternal = getModularInstance(user);
6365 return [4 /*yield*/, _assertLinkedStatus(false, userInternal, credential.providerId)];
6366 case 1:
6367 _a.sent();
6368 return [2 /*return*/, _link$1(userInternal, credential)];
6369 }
6370 });
6371 });
6372}
6373/**
6374 * Re-authenticates a user using a fresh credential.
6375 *
6376 * @remarks
6377 * Use before operations such as {@link updatePassword} that require tokens from recent sign-in
6378 * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error.
6379 *
6380 * @param user - The user.
6381 * @param credential - The auth credential.
6382 *
6383 * @public
6384 */
6385function reauthenticateWithCredential(user, credential) {
6386 return __awaiter(this, void 0, void 0, function () {
6387 return __generator(this, function (_a) {
6388 return [2 /*return*/, _reauthenticate(getModularInstance(user), credential)];
6389 });
6390 });
6391}
6392
6393/**
6394 * @license
6395 * Copyright 2020 Google LLC
6396 *
6397 * Licensed under the Apache License, Version 2.0 (the "License");
6398 * you may not use this file except in compliance with the License.
6399 * You may obtain a copy of the License at
6400 *
6401 * http://www.apache.org/licenses/LICENSE-2.0
6402 *
6403 * Unless required by applicable law or agreed to in writing, software
6404 * distributed under the License is distributed on an "AS IS" BASIS,
6405 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6406 * See the License for the specific language governing permissions and
6407 * limitations under the License.
6408 */
6409function signInWithCustomToken$1(auth, request) {
6410 return __awaiter(this, void 0, void 0, function () {
6411 return __generator(this, function (_a) {
6412 return [2 /*return*/, _performSignInRequest(auth, "POST" /* POST */, "/v1/accounts:signInWithCustomToken" /* SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request))];
6413 });
6414 });
6415}
6416
6417/**
6418 * @license
6419 * Copyright 2020 Google LLC
6420 *
6421 * Licensed under the Apache License, Version 2.0 (the "License");
6422 * you may not use this file except in compliance with the License.
6423 * You may obtain a copy of the License at
6424 *
6425 * http://www.apache.org/licenses/LICENSE-2.0
6426 *
6427 * Unless required by applicable law or agreed to in writing, software
6428 * distributed under the License is distributed on an "AS IS" BASIS,
6429 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6430 * See the License for the specific language governing permissions and
6431 * limitations under the License.
6432 */
6433/**
6434 * Asynchronously signs in using a custom token.
6435 *
6436 * @remarks
6437 * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must
6438 * be generated by an auth backend using the
6439 * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}
6440 * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .
6441 *
6442 * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
6443 *
6444 * @param auth - The {@link Auth} instance.
6445 * @param customToken - The custom token to sign in with.
6446 *
6447 * @public
6448 */
6449function signInWithCustomToken(auth, customToken) {
6450 return __awaiter(this, void 0, void 0, function () {
6451 var authInternal, response, cred;
6452 return __generator(this, function (_a) {
6453 switch (_a.label) {
6454 case 0:
6455 authInternal = _castAuth(auth);
6456 return [4 /*yield*/, signInWithCustomToken$1(authInternal, {
6457 token: customToken,
6458 returnSecureToken: true
6459 })];
6460 case 1:
6461 response = _a.sent();
6462 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* SIGN_IN */, response)];
6463 case 2:
6464 cred = _a.sent();
6465 return [4 /*yield*/, authInternal._updateCurrentUser(cred.user)];
6466 case 3:
6467 _a.sent();
6468 return [2 /*return*/, cred];
6469 }
6470 });
6471 });
6472}
6473
6474/**
6475 * @license
6476 * Copyright 2020 Google LLC
6477 *
6478 * Licensed under the Apache License, Version 2.0 (the "License");
6479 * you may not use this file except in compliance with the License.
6480 * You may obtain a copy of the License at
6481 *
6482 * http://www.apache.org/licenses/LICENSE-2.0
6483 *
6484 * Unless required by applicable law or agreed to in writing, software
6485 * distributed under the License is distributed on an "AS IS" BASIS,
6486 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6487 * See the License for the specific language governing permissions and
6488 * limitations under the License.
6489 */
6490var MultiFactorInfoImpl = /** @class */ (function () {
6491 function MultiFactorInfoImpl(factorId, response) {
6492 this.factorId = factorId;
6493 this.uid = response.mfaEnrollmentId;
6494 this.enrollmentTime = new Date(response.enrolledAt).toUTCString();
6495 this.displayName = response.displayName;
6496 }
6497 MultiFactorInfoImpl._fromServerResponse = function (auth, enrollment) {
6498 if ('phoneInfo' in enrollment) {
6499 return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);
6500 }
6501 return _fail(auth, "internal-error" /* INTERNAL_ERROR */);
6502 };
6503 return MultiFactorInfoImpl;
6504}());
6505var PhoneMultiFactorInfoImpl = /** @class */ (function (_super) {
6506 __extends(PhoneMultiFactorInfoImpl, _super);
6507 function PhoneMultiFactorInfoImpl(response) {
6508 var _this = _super.call(this, "phone" /* PHONE */, response) || this;
6509 _this.phoneNumber = response.phoneInfo;
6510 return _this;
6511 }
6512 PhoneMultiFactorInfoImpl._fromServerResponse = function (_auth, enrollment) {
6513 return new PhoneMultiFactorInfoImpl(enrollment);
6514 };
6515 return PhoneMultiFactorInfoImpl;
6516}(MultiFactorInfoImpl));
6517
6518/**
6519 * @license
6520 * Copyright 2020 Google LLC
6521 *
6522 * Licensed under the Apache License, Version 2.0 (the "License");
6523 * you may not use this file except in compliance with the License.
6524 * You may obtain a copy of the License at
6525 *
6526 * http://www.apache.org/licenses/LICENSE-2.0
6527 *
6528 * Unless required by applicable law or agreed to in writing, software
6529 * distributed under the License is distributed on an "AS IS" BASIS,
6530 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6531 * See the License for the specific language governing permissions and
6532 * limitations under the License.
6533 */
6534function _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {
6535 var _a;
6536 _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, "invalid-continue-uri" /* INVALID_CONTINUE_URI */);
6537 _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||
6538 actionCodeSettings.dynamicLinkDomain.length > 0, auth, "invalid-dynamic-link-domain" /* INVALID_DYNAMIC_LINK_DOMAIN */);
6539 request.continueUrl = actionCodeSettings.url;
6540 request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;
6541 request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;
6542 if (actionCodeSettings.iOS) {
6543 _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, "missing-ios-bundle-id" /* MISSING_IOS_BUNDLE_ID */);
6544 request.iOSBundleId = actionCodeSettings.iOS.bundleId;
6545 }
6546 if (actionCodeSettings.android) {
6547 _assert(actionCodeSettings.android.packageName.length > 0, auth, "missing-android-pkg-name" /* MISSING_ANDROID_PACKAGE_NAME */);
6548 request.androidInstallApp = actionCodeSettings.android.installApp;
6549 request.androidMinimumVersionCode =
6550 actionCodeSettings.android.minimumVersion;
6551 request.androidPackageName = actionCodeSettings.android.packageName;
6552 }
6553}
6554
6555/**
6556 * @license
6557 * Copyright 2020 Google LLC
6558 *
6559 * Licensed under the Apache License, Version 2.0 (the "License");
6560 * you may not use this file except in compliance with the License.
6561 * You may obtain a copy of the License at
6562 *
6563 * http://www.apache.org/licenses/LICENSE-2.0
6564 *
6565 * Unless required by applicable law or agreed to in writing, software
6566 * distributed under the License is distributed on an "AS IS" BASIS,
6567 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6568 * See the License for the specific language governing permissions and
6569 * limitations under the License.
6570 */
6571/**
6572 * Sends a password reset email to the given email address.
6573 *
6574 * @remarks
6575 * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in
6576 * the email sent to the user, along with the new password specified by the user.
6577 *
6578 * @example
6579 * ```javascript
6580 * const actionCodeSettings = {
6581 * url: 'https://www.example.com/?email=user@example.com',
6582 * iOS: {
6583 * bundleId: 'com.example.ios'
6584 * },
6585 * android: {
6586 * packageName: 'com.example.android',
6587 * installApp: true,
6588 * minimumVersion: '12'
6589 * },
6590 * handleCodeInApp: true
6591 * };
6592 * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);
6593 * // Obtain code from user.
6594 * await confirmPasswordReset('user@example.com', code);
6595 * ```
6596 *
6597 * @param auth - The {@link Auth} instance.
6598 * @param email - The user's email address.
6599 * @param actionCodeSettings - The {@link ActionCodeSettings}.
6600 *
6601 * @public
6602 */
6603function sendPasswordResetEmail(auth, email, actionCodeSettings) {
6604 return __awaiter(this, void 0, void 0, function () {
6605 var authModular, request;
6606 return __generator(this, function (_a) {
6607 switch (_a.label) {
6608 case 0:
6609 authModular = getModularInstance(auth);
6610 request = {
6611 requestType: "PASSWORD_RESET" /* PASSWORD_RESET */,
6612 email: email
6613 };
6614 if (actionCodeSettings) {
6615 _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
6616 }
6617 return [4 /*yield*/, sendPasswordResetEmail$1(authModular, request)];
6618 case 1:
6619 _a.sent();
6620 return [2 /*return*/];
6621 }
6622 });
6623 });
6624}
6625/**
6626 * Completes the password reset process, given a confirmation code and new password.
6627 *
6628 * @param auth - The {@link Auth} instance.
6629 * @param oobCode - A confirmation code sent to the user.
6630 * @param newPassword - The new password.
6631 *
6632 * @public
6633 */
6634function confirmPasswordReset(auth, oobCode, newPassword) {
6635 return __awaiter(this, void 0, void 0, function () {
6636 return __generator(this, function (_a) {
6637 switch (_a.label) {
6638 case 0: return [4 /*yield*/, resetPassword(getModularInstance(auth), {
6639 oobCode: oobCode,
6640 newPassword: newPassword
6641 })];
6642 case 1:
6643 _a.sent();
6644 return [2 /*return*/];
6645 }
6646 });
6647 });
6648}
6649/**
6650 * Applies a verification code sent to the user by email or other out-of-band mechanism.
6651 *
6652 * @param auth - The {@link Auth} instance.
6653 * @param oobCode - A verification code sent to the user.
6654 *
6655 * @public
6656 */
6657function applyActionCode(auth, oobCode) {
6658 return __awaiter(this, void 0, void 0, function () {
6659 return __generator(this, function (_a) {
6660 switch (_a.label) {
6661 case 0: return [4 /*yield*/, applyActionCode$1(getModularInstance(auth), { oobCode: oobCode })];
6662 case 1:
6663 _a.sent();
6664 return [2 /*return*/];
6665 }
6666 });
6667 });
6668}
6669/**
6670 * Checks a verification code sent to the user by email or other out-of-band mechanism.
6671 *
6672 * @returns metadata about the code.
6673 *
6674 * @param auth - The {@link Auth} instance.
6675 * @param oobCode - A verification code sent to the user.
6676 *
6677 * @public
6678 */
6679function checkActionCode(auth, oobCode) {
6680 return __awaiter(this, void 0, void 0, function () {
6681 var authModular, response, operation, multiFactorInfo;
6682 return __generator(this, function (_a) {
6683 switch (_a.label) {
6684 case 0:
6685 authModular = getModularInstance(auth);
6686 return [4 /*yield*/, resetPassword(authModular, { oobCode: oobCode })];
6687 case 1:
6688 response = _a.sent();
6689 operation = response.requestType;
6690 _assert(operation, authModular, "internal-error" /* INTERNAL_ERROR */);
6691 switch (operation) {
6692 case "EMAIL_SIGNIN" /* EMAIL_SIGNIN */:
6693 break;
6694 case "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */:
6695 _assert(response.newEmail, authModular, "internal-error" /* INTERNAL_ERROR */);
6696 break;
6697 case "REVERT_SECOND_FACTOR_ADDITION" /* REVERT_SECOND_FACTOR_ADDITION */:
6698 _assert(response.mfaInfo, authModular, "internal-error" /* INTERNAL_ERROR */);
6699 // fall through
6700 default:
6701 _assert(response.email, authModular, "internal-error" /* INTERNAL_ERROR */);
6702 }
6703 multiFactorInfo = null;
6704 if (response.mfaInfo) {
6705 multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);
6706 }
6707 return [2 /*return*/, {
6708 data: {
6709 email: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */
6710 ? response.newEmail
6711 : response.email) || null,
6712 previousEmail: (response.requestType === "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */
6713 ? response.email
6714 : response.newEmail) || null,
6715 multiFactorInfo: multiFactorInfo
6716 },
6717 operation: operation
6718 }];
6719 }
6720 });
6721 });
6722}
6723/**
6724 * Checks a password reset code sent to the user by email or other out-of-band mechanism.
6725 *
6726 * @returns the user's email address if valid.
6727 *
6728 * @param auth - The {@link Auth} instance.
6729 * @param code - A verification code sent to the user.
6730 *
6731 * @public
6732 */
6733function verifyPasswordResetCode(auth, code) {
6734 return __awaiter(this, void 0, void 0, function () {
6735 var data;
6736 return __generator(this, function (_a) {
6737 switch (_a.label) {
6738 case 0: return [4 /*yield*/, checkActionCode(getModularInstance(auth), code)];
6739 case 1:
6740 data = (_a.sent()).data;
6741 // Email should always be present since a code was sent to it
6742 return [2 /*return*/, data.email];
6743 }
6744 });
6745 });
6746}
6747/**
6748 * Creates a new user account associated with the specified email address and password.
6749 *
6750 * @remarks
6751 * On successful creation of the user account, this user will also be signed in to your application.
6752 *
6753 * User account creation can fail if the account already exists or the password is invalid.
6754 *
6755 * Note: The email address acts as a unique identifier for the user and enables an email-based
6756 * password reset. This function will create a new user account and set the initial user password.
6757 *
6758 * @param auth - The {@link Auth} instance.
6759 * @param email - The user's email address.
6760 * @param password - The user's chosen password.
6761 *
6762 * @public
6763 */
6764function createUserWithEmailAndPassword(auth, email, password) {
6765 return __awaiter(this, void 0, void 0, function () {
6766 var authInternal, response, userCredential;
6767 return __generator(this, function (_a) {
6768 switch (_a.label) {
6769 case 0:
6770 authInternal = _castAuth(auth);
6771 return [4 /*yield*/, signUp(authInternal, {
6772 returnSecureToken: true,
6773 email: email,
6774 password: password
6775 })];
6776 case 1:
6777 response = _a.sent();
6778 return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(authInternal, "signIn" /* SIGN_IN */, response)];
6779 case 2:
6780 userCredential = _a.sent();
6781 return [4 /*yield*/, authInternal._updateCurrentUser(userCredential.user)];
6782 case 3:
6783 _a.sent();
6784 return [2 /*return*/, userCredential];
6785 }
6786 });
6787 });
6788}
6789/**
6790 * Asynchronously signs in using an email and password.
6791 *
6792 * @remarks
6793 * Fails with an error if the email address and password do not match.
6794 *
6795 * Note: The user's password is NOT the password used to access the user's email account. The
6796 * email address serves as a unique identifier for the user, and the password is used to access
6797 * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.
6798 *
6799 * @param auth - The {@link Auth} instance.
6800 * @param email - The users email address.
6801 * @param password - The users password.
6802 *
6803 * @public
6804 */
6805function signInWithEmailAndPassword(auth, email, password) {
6806 return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));
6807}
6808
6809/**
6810 * @license
6811 * Copyright 2020 Google LLC
6812 *
6813 * Licensed under the Apache License, Version 2.0 (the "License");
6814 * you may not use this file except in compliance with the License.
6815 * You may obtain a copy of the License at
6816 *
6817 * http://www.apache.org/licenses/LICENSE-2.0
6818 *
6819 * Unless required by applicable law or agreed to in writing, software
6820 * distributed under the License is distributed on an "AS IS" BASIS,
6821 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6822 * See the License for the specific language governing permissions and
6823 * limitations under the License.
6824 */
6825/**
6826 * Sends a sign-in email link to the user with the specified email.
6827 *
6828 * @remarks
6829 * The sign-in operation has to always be completed in the app unlike other out of band email
6830 * actions (password reset and email verifications). This is because, at the end of the flow,
6831 * the user is expected to be signed in and their Auth state persisted within the app.
6832 *
6833 * To complete sign in with the email link, call {@link signInWithEmailLink} with the email
6834 * address and the email link supplied in the email sent to the user.
6835 *
6836 * @example
6837 * ```javascript
6838 * const actionCodeSettings = {
6839 * url: 'https://www.example.com/?email=user@example.com',
6840 * iOS: {
6841 * bundleId: 'com.example.ios'
6842 * },
6843 * android: {
6844 * packageName: 'com.example.android',
6845 * installApp: true,
6846 * minimumVersion: '12'
6847 * },
6848 * handleCodeInApp: true
6849 * };
6850 * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
6851 * // Obtain emailLink from the user.
6852 * if(isSignInWithEmailLink(auth, emailLink)) {
6853 * await signInWithEmailLink(auth, 'user@example.com', emailLink);
6854 * }
6855 * ```
6856 *
6857 * @param authInternal - The {@link Auth} instance.
6858 * @param email - The user's email address.
6859 * @param actionCodeSettings - The {@link ActionCodeSettings}.
6860 *
6861 * @public
6862 */
6863function sendSignInLinkToEmail(auth, email, actionCodeSettings) {
6864 return __awaiter(this, void 0, void 0, function () {
6865 var authModular, request;
6866 return __generator(this, function (_a) {
6867 switch (_a.label) {
6868 case 0:
6869 authModular = getModularInstance(auth);
6870 request = {
6871 requestType: "EMAIL_SIGNIN" /* EMAIL_SIGNIN */,
6872 email: email
6873 };
6874 _assert(actionCodeSettings.handleCodeInApp, authModular, "argument-error" /* ARGUMENT_ERROR */);
6875 if (actionCodeSettings) {
6876 _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);
6877 }
6878 return [4 /*yield*/, sendSignInLinkToEmail$1(authModular, request)];
6879 case 1:
6880 _a.sent();
6881 return [2 /*return*/];
6882 }
6883 });
6884 });
6885}
6886/**
6887 * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.
6888 *
6889 * @param auth - The {@link Auth} instance.
6890 * @param emailLink - The link sent to the user's email address.
6891 *
6892 * @public
6893 */
6894function isSignInWithEmailLink(auth, emailLink) {
6895 var actionCodeUrl = ActionCodeURL.parseLink(emailLink);
6896 return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === "EMAIL_SIGNIN" /* EMAIL_SIGNIN */;
6897}
6898/**
6899 * Asynchronously signs in using an email and sign-in email link.
6900 *
6901 * @remarks
6902 * If no link is passed, the link is inferred from the current URL.
6903 *
6904 * Fails with an error if the email address is invalid or OTP in email link expires.
6905 *
6906 * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.
6907 *
6908 * @example
6909 * ```javascript
6910 * const actionCodeSettings = {
6911 * url: 'https://www.example.com/?email=user@example.com',
6912 * iOS: {
6913 * bundleId: 'com.example.ios'
6914 * },
6915 * android: {
6916 * packageName: 'com.example.android',
6917 * installApp: true,
6918 * minimumVersion: '12'
6919 * },
6920 * handleCodeInApp: true
6921 * };
6922 * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);
6923 * // Obtain emailLink from the user.
6924 * if(isSignInWithEmailLink(auth, emailLink)) {
6925 * await signInWithEmailLink(auth, 'user@example.com', emailLink);
6926 * }
6927 * ```
6928 *
6929 * @param auth - The {@link Auth} instance.
6930 * @param email - The user's email address.
6931 * @param emailLink - The link sent to the user's email address.
6932 *
6933 * @public
6934 */
6935function signInWithEmailLink(auth, email, emailLink) {
6936 return __awaiter(this, void 0, void 0, function () {
6937 var authModular, credential;
6938 return __generator(this, function (_a) {
6939 authModular = getModularInstance(auth);
6940 credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());
6941 // Check if the tenant ID in the email link matches the tenant ID on Auth
6942 // instance.
6943 _assert(credential._tenantId === (authModular.tenantId || null), authModular, "tenant-id-mismatch" /* TENANT_ID_MISMATCH */);
6944 return [2 /*return*/, signInWithCredential(authModular, credential)];
6945 });
6946 });
6947}
6948
6949/**
6950 * @license
6951 * Copyright 2020 Google LLC
6952 *
6953 * Licensed under the Apache License, Version 2.0 (the "License");
6954 * you may not use this file except in compliance with the License.
6955 * You may obtain a copy of the License at
6956 *
6957 * http://www.apache.org/licenses/LICENSE-2.0
6958 *
6959 * Unless required by applicable law or agreed to in writing, software
6960 * distributed under the License is distributed on an "AS IS" BASIS,
6961 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6962 * See the License for the specific language governing permissions and
6963 * limitations under the License.
6964 */
6965function createAuthUri(auth, request) {
6966 return __awaiter(this, void 0, void 0, function () {
6967 return __generator(this, function (_a) {
6968 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:createAuthUri" /* CREATE_AUTH_URI */, _addTidIfNecessary(auth, request))];
6969 });
6970 });
6971}
6972
6973/**
6974 * @license
6975 * Copyright 2020 Google LLC
6976 *
6977 * Licensed under the Apache License, Version 2.0 (the "License");
6978 * you may not use this file except in compliance with the License.
6979 * You may obtain a copy of the License at
6980 *
6981 * http://www.apache.org/licenses/LICENSE-2.0
6982 *
6983 * Unless required by applicable law or agreed to in writing, software
6984 * distributed under the License is distributed on an "AS IS" BASIS,
6985 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6986 * See the License for the specific language governing permissions and
6987 * limitations under the License.
6988 */
6989/**
6990 * Gets the list of possible sign in methods for the given email address.
6991 *
6992 * @remarks
6993 * This is useful to differentiate methods of sign-in for the same provider, eg.
6994 * {@link EmailAuthProvider} which has 2 methods of sign-in,
6995 * {@link SignInMethod}.EMAIL_PASSWORD and
6996 * {@link SignInMethod}.EMAIL_LINK.
6997 *
6998 * @param auth - The {@link Auth} instance.
6999 * @param email - The user's email address.
7000 *
7001 * @public
7002 */
7003function fetchSignInMethodsForEmail(auth, email) {
7004 return __awaiter(this, void 0, void 0, function () {
7005 var continueUri, request, signinMethods;
7006 return __generator(this, function (_a) {
7007 switch (_a.label) {
7008 case 0:
7009 continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';
7010 request = {
7011 identifier: email,
7012 continueUri: continueUri
7013 };
7014 return [4 /*yield*/, createAuthUri(getModularInstance(auth), request)];
7015 case 1:
7016 signinMethods = (_a.sent()).signinMethods;
7017 return [2 /*return*/, signinMethods || []];
7018 }
7019 });
7020 });
7021}
7022/**
7023 * Sends a verification email to a user.
7024 *
7025 * @remarks
7026 * The verification process is completed by calling {@link applyActionCode}.
7027 *
7028 * @example
7029 * ```javascript
7030 * const actionCodeSettings = {
7031 * url: 'https://www.example.com/?email=user@example.com',
7032 * iOS: {
7033 * bundleId: 'com.example.ios'
7034 * },
7035 * android: {
7036 * packageName: 'com.example.android',
7037 * installApp: true,
7038 * minimumVersion: '12'
7039 * },
7040 * handleCodeInApp: true
7041 * };
7042 * await sendEmailVerification(user, actionCodeSettings);
7043 * // Obtain code from the user.
7044 * await applyActionCode(auth, code);
7045 * ```
7046 *
7047 * @param user - The user.
7048 * @param actionCodeSettings - The {@link ActionCodeSettings}.
7049 *
7050 * @public
7051 */
7052function sendEmailVerification(user, actionCodeSettings) {
7053 return __awaiter(this, void 0, void 0, function () {
7054 var userInternal, idToken, request, email;
7055 return __generator(this, function (_a) {
7056 switch (_a.label) {
7057 case 0:
7058 userInternal = getModularInstance(user);
7059 return [4 /*yield*/, user.getIdToken()];
7060 case 1:
7061 idToken = _a.sent();
7062 request = {
7063 requestType: "VERIFY_EMAIL" /* VERIFY_EMAIL */,
7064 idToken: idToken
7065 };
7066 if (actionCodeSettings) {
7067 _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
7068 }
7069 return [4 /*yield*/, sendEmailVerification$1(userInternal.auth, request)];
7070 case 2:
7071 email = (_a.sent()).email;
7072 if (!(email !== user.email)) return [3 /*break*/, 4];
7073 return [4 /*yield*/, user.reload()];
7074 case 3:
7075 _a.sent();
7076 _a.label = 4;
7077 case 4: return [2 /*return*/];
7078 }
7079 });
7080 });
7081}
7082/**
7083 * Sends a verification email to a new email address.
7084 *
7085 * @remarks
7086 * The user's email will be updated to the new one after being verified.
7087 *
7088 * If you have a custom email action handler, you can complete the verification process by calling
7089 * {@link applyActionCode}.
7090 *
7091 * @example
7092 * ```javascript
7093 * const actionCodeSettings = {
7094 * url: 'https://www.example.com/?email=user@example.com',
7095 * iOS: {
7096 * bundleId: 'com.example.ios'
7097 * },
7098 * android: {
7099 * packageName: 'com.example.android',
7100 * installApp: true,
7101 * minimumVersion: '12'
7102 * },
7103 * handleCodeInApp: true
7104 * };
7105 * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);
7106 * // Obtain code from the user.
7107 * await applyActionCode(auth, code);
7108 * ```
7109 *
7110 * @param user - The user.
7111 * @param newEmail - The new email address to be verified before update.
7112 * @param actionCodeSettings - The {@link ActionCodeSettings}.
7113 *
7114 * @public
7115 */
7116function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {
7117 return __awaiter(this, void 0, void 0, function () {
7118 var userInternal, idToken, request, email;
7119 return __generator(this, function (_a) {
7120 switch (_a.label) {
7121 case 0:
7122 userInternal = getModularInstance(user);
7123 return [4 /*yield*/, user.getIdToken()];
7124 case 1:
7125 idToken = _a.sent();
7126 request = {
7127 requestType: "VERIFY_AND_CHANGE_EMAIL" /* VERIFY_AND_CHANGE_EMAIL */,
7128 idToken: idToken,
7129 newEmail: newEmail
7130 };
7131 if (actionCodeSettings) {
7132 _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);
7133 }
7134 return [4 /*yield*/, verifyAndChangeEmail(userInternal.auth, request)];
7135 case 2:
7136 email = (_a.sent()).email;
7137 if (!(email !== user.email)) return [3 /*break*/, 4];
7138 // If the local copy of the email on user is outdated, reload the
7139 // user.
7140 return [4 /*yield*/, user.reload()];
7141 case 3:
7142 // If the local copy of the email on user is outdated, reload the
7143 // user.
7144 _a.sent();
7145 _a.label = 4;
7146 case 4: return [2 /*return*/];
7147 }
7148 });
7149 });
7150}
7151
7152/**
7153 * @license
7154 * Copyright 2020 Google LLC
7155 *
7156 * Licensed under the Apache License, Version 2.0 (the "License");
7157 * you may not use this file except in compliance with the License.
7158 * You may obtain a copy of the License at
7159 *
7160 * http://www.apache.org/licenses/LICENSE-2.0
7161 *
7162 * Unless required by applicable law or agreed to in writing, software
7163 * distributed under the License is distributed on an "AS IS" BASIS,
7164 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7165 * See the License for the specific language governing permissions and
7166 * limitations under the License.
7167 */
7168function updateProfile$1(auth, request) {
7169 return __awaiter(this, void 0, void 0, function () {
7170 return __generator(this, function (_a) {
7171 return [2 /*return*/, _performApiRequest(auth, "POST" /* POST */, "/v1/accounts:update" /* SET_ACCOUNT_INFO */, request)];
7172 });
7173 });
7174}
7175
7176/**
7177 * @license
7178 * Copyright 2020 Google LLC
7179 *
7180 * Licensed under the Apache License, Version 2.0 (the "License");
7181 * you may not use this file except in compliance with the License.
7182 * You may obtain a copy of the License at
7183 *
7184 * http://www.apache.org/licenses/LICENSE-2.0
7185 *
7186 * Unless required by applicable law or agreed to in writing, software
7187 * distributed under the License is distributed on an "AS IS" BASIS,
7188 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7189 * See the License for the specific language governing permissions and
7190 * limitations under the License.
7191 */
7192/**
7193 * Updates a user's profile data.
7194 *
7195 * @param user - The user.
7196 * @param profile - The profile's `displayName` and `photoURL` to update.
7197 *
7198 * @public
7199 */
7200function updateProfile(user, _a) {
7201 var displayName = _a.displayName, photoUrl = _a.photoURL;
7202 return __awaiter(this, void 0, void 0, function () {
7203 var userInternal, idToken, profileRequest, response, passwordProvider;
7204 return __generator(this, function (_b) {
7205 switch (_b.label) {
7206 case 0:
7207 if (displayName === undefined && photoUrl === undefined) {
7208 return [2 /*return*/];
7209 }
7210 userInternal = getModularInstance(user);
7211 return [4 /*yield*/, userInternal.getIdToken()];
7212 case 1:
7213 idToken = _b.sent();
7214 profileRequest = {
7215 idToken: idToken,
7216 displayName: displayName,
7217 photoUrl: photoUrl,
7218 returnSecureToken: true
7219 };
7220 return [4 /*yield*/, _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest))];
7221 case 2:
7222 response = _b.sent();
7223 userInternal.displayName = response.displayName || null;
7224 userInternal.photoURL = response.photoUrl || null;
7225 passwordProvider = userInternal.providerData.find(function (_a) {
7226 var providerId = _a.providerId;
7227 return providerId === "password" /* PASSWORD */;
7228 });
7229 if (passwordProvider) {
7230 passwordProvider.displayName = userInternal.displayName;
7231 passwordProvider.photoURL = userInternal.photoURL;
7232 }
7233 return [4 /*yield*/, userInternal._updateTokensIfNecessary(response)];
7234 case 3:
7235 _b.sent();
7236 return [2 /*return*/];
7237 }
7238 });
7239 });
7240}
7241/**
7242 * Updates the user's email address.
7243 *
7244 * @remarks
7245 * An email will be sent to the original email address (if it was set) that allows to revoke the
7246 * email address change, in order to protect them from account hijacking.
7247 *
7248 * Important: this is a security sensitive operation that requires the user to have recently signed
7249 * in. If this requirement isn't met, ask the user to authenticate again and then call
7250 * {@link reauthenticateWithCredential}.
7251 *
7252 * @param user - The user.
7253 * @param newEmail - The new email address.
7254 *
7255 * @public
7256 */
7257function updateEmail(user, newEmail) {
7258 return updateEmailOrPassword(getModularInstance(user), newEmail, null);
7259}
7260/**
7261 * Updates the user's password.
7262 *
7263 * @remarks
7264 * Important: this is a security sensitive operation that requires the user to have recently signed
7265 * in. If this requirement isn't met, ask the user to authenticate again and then call
7266 * {@link reauthenticateWithCredential}.
7267 *
7268 * @param user - The user.
7269 * @param newPassword - The new password.
7270 *
7271 * @public
7272 */
7273function updatePassword(user, newPassword) {
7274 return updateEmailOrPassword(getModularInstance(user), null, newPassword);
7275}
7276function updateEmailOrPassword(user, email, password) {
7277 return __awaiter(this, void 0, void 0, function () {
7278 var auth, idToken, request, response;
7279 return __generator(this, function (_a) {
7280 switch (_a.label) {
7281 case 0:
7282 auth = user.auth;
7283 return [4 /*yield*/, user.getIdToken()];
7284 case 1:
7285 idToken = _a.sent();
7286 request = {
7287 idToken: idToken,
7288 returnSecureToken: true
7289 };
7290 if (email) {
7291 request.email = email;
7292 }
7293 if (password) {
7294 request.password = password;
7295 }
7296 return [4 /*yield*/, _logoutIfInvalidated(user, updateEmailPassword(auth, request))];
7297 case 2:
7298 response = _a.sent();
7299 return [4 /*yield*/, user._updateTokensIfNecessary(response, /* reload */ true)];
7300 case 3:
7301 _a.sent();
7302 return [2 /*return*/];
7303 }
7304 });
7305 });
7306}
7307
7308/**
7309 * @license
7310 * Copyright 2019 Google LLC
7311 *
7312 * Licensed under the Apache License, Version 2.0 (the "License");
7313 * you may not use this file except in compliance with the License.
7314 * You may obtain a copy of the License at
7315 *
7316 * http://www.apache.org/licenses/LICENSE-2.0
7317 *
7318 * Unless required by applicable law or agreed to in writing, software
7319 * distributed under the License is distributed on an "AS IS" BASIS,
7320 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7321 * See the License for the specific language governing permissions and
7322 * limitations under the License.
7323 */
7324/**
7325 * Parse the `AdditionalUserInfo` from the ID token response.
7326 *
7327 */
7328function _fromIdTokenResponse(idTokenResponse) {
7329 var _a, _b;
7330 if (!idTokenResponse) {
7331 return null;
7332 }
7333 var providerId = idTokenResponse.providerId;
7334 var profile = idTokenResponse.rawUserInfo
7335 ? JSON.parse(idTokenResponse.rawUserInfo)
7336 : {};
7337 var isNewUser = idTokenResponse.isNewUser ||
7338 idTokenResponse.kind === "identitytoolkit#SignupNewUserResponse" /* SignupNewUser */;
7339 if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {
7340 var signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];
7341 if (signInProvider) {
7342 var filteredProviderId = signInProvider !== "anonymous" /* ANONYMOUS */ &&
7343 signInProvider !== "custom" /* CUSTOM */
7344 ? signInProvider
7345 : null;
7346 // Uses generic class in accordance with the legacy SDK.
7347 return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);
7348 }
7349 }
7350 if (!providerId) {
7351 return null;
7352 }
7353 switch (providerId) {
7354 case "facebook.com" /* FACEBOOK */:
7355 return new FacebookAdditionalUserInfo(isNewUser, profile);
7356 case "github.com" /* GITHUB */:
7357 return new GithubAdditionalUserInfo(isNewUser, profile);
7358 case "google.com" /* GOOGLE */:
7359 return new GoogleAdditionalUserInfo(isNewUser, profile);
7360 case "twitter.com" /* TWITTER */:
7361 return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);
7362 case "custom" /* CUSTOM */:
7363 case "anonymous" /* ANONYMOUS */:
7364 return new GenericAdditionalUserInfo(isNewUser, null);
7365 default:
7366 return new GenericAdditionalUserInfo(isNewUser, providerId, profile);
7367 }
7368}
7369var GenericAdditionalUserInfo = /** @class */ (function () {
7370 function GenericAdditionalUserInfo(isNewUser, providerId, profile) {
7371 if (profile === void 0) { profile = {}; }
7372 this.isNewUser = isNewUser;
7373 this.providerId = providerId;
7374 this.profile = profile;
7375 }
7376 return GenericAdditionalUserInfo;
7377}());
7378var FederatedAdditionalUserInfoWithUsername = /** @class */ (function (_super) {
7379 __extends(FederatedAdditionalUserInfoWithUsername, _super);
7380 function FederatedAdditionalUserInfoWithUsername(isNewUser, providerId, profile, username) {
7381 var _this = _super.call(this, isNewUser, providerId, profile) || this;
7382 _this.username = username;
7383 return _this;
7384 }
7385 return FederatedAdditionalUserInfoWithUsername;
7386}(GenericAdditionalUserInfo));
7387var FacebookAdditionalUserInfo = /** @class */ (function (_super) {
7388 __extends(FacebookAdditionalUserInfo, _super);
7389 function FacebookAdditionalUserInfo(isNewUser, profile) {
7390 return _super.call(this, isNewUser, "facebook.com" /* FACEBOOK */, profile) || this;
7391 }
7392 return FacebookAdditionalUserInfo;
7393}(GenericAdditionalUserInfo));
7394var GithubAdditionalUserInfo = /** @class */ (function (_super) {
7395 __extends(GithubAdditionalUserInfo, _super);
7396 function GithubAdditionalUserInfo(isNewUser, profile) {
7397 return _super.call(this, isNewUser, "github.com" /* GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null) || this;
7398 }
7399 return GithubAdditionalUserInfo;
7400}(FederatedAdditionalUserInfoWithUsername));
7401var GoogleAdditionalUserInfo = /** @class */ (function (_super) {
7402 __extends(GoogleAdditionalUserInfo, _super);
7403 function GoogleAdditionalUserInfo(isNewUser, profile) {
7404 return _super.call(this, isNewUser, "google.com" /* GOOGLE */, profile) || this;
7405 }
7406 return GoogleAdditionalUserInfo;
7407}(GenericAdditionalUserInfo));
7408var TwitterAdditionalUserInfo = /** @class */ (function (_super) {
7409 __extends(TwitterAdditionalUserInfo, _super);
7410 function TwitterAdditionalUserInfo(isNewUser, profile, screenName) {
7411 return _super.call(this, isNewUser, "twitter.com" /* TWITTER */, profile, screenName) || this;
7412 }
7413 return TwitterAdditionalUserInfo;
7414}(FederatedAdditionalUserInfoWithUsername));
7415/**
7416 * Extracts provider specific {@link AdditionalUserInfo} for the given credential.
7417 *
7418 * @param userCredential - The user credential.
7419 *
7420 * @public
7421 */
7422function getAdditionalUserInfo(userCredential) {
7423 var _a = userCredential, user = _a.user, _tokenResponse = _a._tokenResponse;
7424 if (user.isAnonymous && !_tokenResponse) {
7425 // Handle the special case where signInAnonymously() gets called twice.
7426 // No network call is made so there's nothing to actually fill this in
7427 return {
7428 providerId: null,
7429 isNewUser: false,
7430 profile: null
7431 };
7432 }
7433 return _fromIdTokenResponse(_tokenResponse);
7434}
7435
7436/**
7437 * @license
7438 * Copyright 2020 Google LLC
7439 *
7440 * Licensed under the Apache License, Version 2.0 (the "License");
7441 * you may not use this file except in compliance with the License.
7442 * You may obtain a copy of the License at
7443 *
7444 * http://www.apache.org/licenses/LICENSE-2.0
7445 *
7446 * Unless required by applicable law or agreed to in writing, software
7447 * distributed under the License is distributed on an "AS IS" BASIS,
7448 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7449 * See the License for the specific language governing permissions and
7450 * limitations under the License.
7451 */
7452// Non-optional auth methods.
7453/**
7454 * Changes the type of persistence on the {@link Auth} instance for the currently saved
7455 * `Auth` session and applies this type of persistence for future sign-in requests, including
7456 * sign-in with redirect requests.
7457 *
7458 * @remarks
7459 * This makes it easy for a user signing in to specify whether their session should be
7460 * remembered or not. It also makes it easier to never persist the `Auth` state for applications
7461 * that are shared by other users or have sensitive data.
7462 *
7463 * @example
7464 * ```javascript
7465 * setPersistence(auth, browserSessionPersistence);
7466 * ```
7467 *
7468 * @param auth - The {@link Auth} instance.
7469 * @param persistence - The {@link Persistence} to use.
7470 * @returns A `Promise` that resolves once the persistence change has completed
7471 *
7472 * @public
7473 */
7474function setPersistence(auth, persistence) {
7475 return getModularInstance(auth).setPersistence(persistence);
7476}
7477/**
7478 * Adds an observer for changes to the signed-in user's ID token, which includes sign-in,
7479 * sign-out, and token refresh events.
7480 *
7481 * @param auth - The {@link Auth} instance.
7482 * @param nextOrObserver - callback triggered on change.
7483 * @param error - callback triggered on error.
7484 * @param completed - callback triggered when observer is removed.
7485 *
7486 * @public
7487 */
7488function onIdTokenChanged(auth, nextOrObserver, error, completed) {
7489 return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);
7490}
7491/**
7492 * Adds a blocking callback that runs before an auth state change
7493 * sets a new user.
7494 *
7495 * @param auth - The {@link Auth} instance.
7496 * @param callback - callback triggered before new user value is set.
7497 * If this throws, it blocks the user from being set.
7498 * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`
7499 * callback throws, allowing you to undo any side effects.
7500 */
7501function beforeAuthStateChanged(auth, callback, onAbort) {
7502 return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);
7503}
7504/**
7505 * Adds an observer for changes to the user's sign-in state.
7506 *
7507 * @remarks
7508 * To keep the old behavior, see {@link onIdTokenChanged}.
7509 *
7510 * @param auth - The {@link Auth} instance.
7511 * @param nextOrObserver - callback triggered on change.
7512 * @param error - callback triggered on error.
7513 * @param completed - callback triggered when observer is removed.
7514 *
7515 * @public
7516 */
7517function onAuthStateChanged(auth, nextOrObserver, error, completed) {
7518 return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);
7519}
7520/**
7521 * Sets the current language to the default device/browser preference.
7522 *
7523 * @param auth - The {@link Auth} instance.
7524 *
7525 * @public
7526 */
7527function useDeviceLanguage(auth) {
7528 getModularInstance(auth).useDeviceLanguage();
7529}
7530/**
7531 * Asynchronously sets the provided user as {@link Auth.currentUser} on the
7532 * {@link Auth} instance.
7533 *
7534 * @remarks
7535 * A new instance copy of the user provided will be made and set as currentUser.
7536 *
7537 * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners
7538 * like other sign in methods.
7539 *
7540 * The operation fails with an error if the user to be updated belongs to a different Firebase
7541 * project.
7542 *
7543 * @param auth - The {@link Auth} instance.
7544 * @param user - The new {@link User}.
7545 *
7546 * @public
7547 */
7548function updateCurrentUser(auth, user) {
7549 return getModularInstance(auth).updateCurrentUser(user);
7550}
7551/**
7552 * Signs out the current user.
7553 *
7554 * @param auth - The {@link Auth} instance.
7555 *
7556 * @public
7557 */
7558function signOut(auth) {
7559 return getModularInstance(auth).signOut();
7560}
7561/**
7562 * Deletes and signs out the user.
7563 *
7564 * @remarks
7565 * Important: this is a security-sensitive operation that requires the user to have recently
7566 * signed in. If this requirement isn't met, ask the user to authenticate again and then call
7567 * {@link reauthenticateWithCredential}.
7568 *
7569 * @param user - The user.
7570 *
7571 * @public
7572 */
7573function deleteUser(user) {
7574 return __awaiter(this, void 0, void 0, function () {
7575 return __generator(this, function (_a) {
7576 return [2 /*return*/, getModularInstance(user).delete()];
7577 });
7578 });
7579}
7580
7581var MultiFactorSessionImpl = /** @class */ (function () {
7582 function MultiFactorSessionImpl(type, credential) {
7583 this.type = type;
7584 this.credential = credential;
7585 }
7586 MultiFactorSessionImpl._fromIdtoken = function (idToken) {
7587 return new MultiFactorSessionImpl("enroll" /* ENROLL */, idToken);
7588 };
7589 MultiFactorSessionImpl._fromMfaPendingCredential = function (mfaPendingCredential) {
7590 return new MultiFactorSessionImpl("signin" /* SIGN_IN */, mfaPendingCredential);
7591 };
7592 MultiFactorSessionImpl.prototype.toJSON = function () {
7593 var _a;
7594 var key = this.type === "enroll" /* ENROLL */
7595 ? 'idToken'
7596 : 'pendingCredential';
7597 return {
7598 multiFactorSession: (_a = {},
7599 _a[key] = this.credential,
7600 _a)
7601 };
7602 };
7603 MultiFactorSessionImpl.fromJSON = function (obj) {
7604 var _a, _b;
7605 if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {
7606 if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {
7607 return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);
7608 }
7609 else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {
7610 return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);
7611 }
7612 }
7613 return null;
7614 };
7615 return MultiFactorSessionImpl;
7616}());
7617
7618/**
7619 * @license
7620 * Copyright 2020 Google LLC
7621 *
7622 * Licensed under the Apache License, Version 2.0 (the "License");
7623 * you may not use this file except in compliance with the License.
7624 * You may obtain a copy of the License at
7625 *
7626 * http://www.apache.org/licenses/LICENSE-2.0
7627 *
7628 * Unless required by applicable law or agreed to in writing, software
7629 * distributed under the License is distributed on an "AS IS" BASIS,
7630 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7631 * See the License for the specific language governing permissions and
7632 * limitations under the License.
7633 */
7634var MultiFactorResolverImpl = /** @class */ (function () {
7635 function MultiFactorResolverImpl(session, hints, signInResolver) {
7636 this.session = session;
7637 this.hints = hints;
7638 this.signInResolver = signInResolver;
7639 }
7640 /** @internal */
7641 MultiFactorResolverImpl._fromError = function (authExtern, error) {
7642 var _this = this;
7643 var auth = _castAuth(authExtern);
7644 var serverResponse = error.customData._serverResponse;
7645 var hints = (serverResponse.mfaInfo || []).map(function (enrollment) {
7646 return MultiFactorInfoImpl._fromServerResponse(auth, enrollment);
7647 });
7648 _assert(serverResponse.mfaPendingCredential, auth, "internal-error" /* INTERNAL_ERROR */);
7649 var session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);
7650 return new MultiFactorResolverImpl(session, hints, function (assertion) { return __awaiter(_this, void 0, void 0, function () {
7651 var mfaResponse, idTokenResponse, _a, userCredential;
7652 return __generator(this, function (_b) {
7653 switch (_b.label) {
7654 case 0: return [4 /*yield*/, assertion._process(auth, session)];
7655 case 1:
7656 mfaResponse = _b.sent();
7657 // Clear out the unneeded fields from the old login response
7658 delete serverResponse.mfaInfo;
7659 delete serverResponse.mfaPendingCredential;
7660 idTokenResponse = __assign(__assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });
7661 _a = error.operationType;
7662 switch (_a) {
7663 case "signIn" /* SIGN_IN */: return [3 /*break*/, 2];
7664 case "reauthenticate" /* REAUTHENTICATE */: return [3 /*break*/, 5];
7665 }
7666 return [3 /*break*/, 6];
7667 case 2: return [4 /*yield*/, UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse)];
7668 case 3:
7669 userCredential = _b.sent();
7670 return [4 /*yield*/, auth._updateCurrentUser(userCredential.user)];
7671 case 4:
7672 _b.sent();
7673 return [2 /*return*/, userCredential];
7674 case 5:
7675 _assert(error.user, auth, "internal-error" /* INTERNAL_ERROR */);
7676 return [2 /*return*/, UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse)];
7677 case 6:
7678 _fail(auth, "internal-error" /* INTERNAL_ERROR */);
7679 _b.label = 7;
7680 case 7: return [2 /*return*/];
7681 }
7682 });
7683 }); });
7684 };
7685 MultiFactorResolverImpl.prototype.resolveSignIn = function (assertionExtern) {
7686 return __awaiter(this, void 0, void 0, function () {
7687 var assertion;
7688 return __generator(this, function (_a) {
7689 assertion = assertionExtern;
7690 return [2 /*return*/, this.signInResolver(assertion)];
7691 });
7692 });
7693 };
7694 return MultiFactorResolverImpl;
7695}());
7696/**
7697 * Provides a {@link MultiFactorResolver} suitable for completion of a
7698 * multi-factor flow.
7699 *
7700 * @param auth - The {@link Auth} instance.
7701 * @param error - The {@link MultiFactorError} raised during a sign-in, or
7702 * reauthentication operation.
7703 *
7704 * @public
7705 */
7706function getMultiFactorResolver(auth, error) {
7707 var _a;
7708 var authModular = getModularInstance(auth);
7709 var errorInternal = error;
7710 _assert(error.customData.operationType, authModular, "argument-error" /* ARGUMENT_ERROR */);
7711 _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, "argument-error" /* ARGUMENT_ERROR */);
7712 return MultiFactorResolverImpl._fromError(authModular, errorInternal);
7713}
7714
7715/**
7716 * @license
7717 * Copyright 2020 Google LLC
7718 *
7719 * Licensed under the Apache License, Version 2.0 (the "License");
7720 * you may not use this file except in compliance with the License.
7721 * You may obtain a copy of the License at
7722 *
7723 * http://www.apache.org/licenses/LICENSE-2.0
7724 *
7725 * Unless required by applicable law or agreed to in writing, software
7726 * distributed under the License is distributed on an "AS IS" BASIS,
7727 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7728 * See the License for the specific language governing permissions and
7729 * limitations under the License.
7730 */
7731function startEnrollPhoneMfa(auth, request) {
7732 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaEnrollment:start" /* START_PHONE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
7733}
7734function finalizeEnrollPhoneMfa(auth, request) {
7735 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaEnrollment:finalize" /* FINALIZE_PHONE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));
7736}
7737function withdrawMfa(auth, request) {
7738 return _performApiRequest(auth, "POST" /* POST */, "/v2/accounts/mfaEnrollment:withdraw" /* WITHDRAW_MFA */, _addTidIfNecessary(auth, request));
7739}
7740
7741var MultiFactorUserImpl = /** @class */ (function () {
7742 function MultiFactorUserImpl(user) {
7743 var _this = this;
7744 this.user = user;
7745 this.enrolledFactors = [];
7746 user._onReload(function (userInfo) {
7747 if (userInfo.mfaInfo) {
7748 _this.enrolledFactors = userInfo.mfaInfo.map(function (enrollment) {
7749 return MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment);
7750 });
7751 }
7752 });
7753 }
7754 MultiFactorUserImpl._fromUser = function (user) {
7755 return new MultiFactorUserImpl(user);
7756 };
7757 MultiFactorUserImpl.prototype.getSession = function () {
7758 return __awaiter(this, void 0, void 0, function () {
7759 var _a, _b;
7760 return __generator(this, function (_c) {
7761 switch (_c.label) {
7762 case 0:
7763 _b = (_a = MultiFactorSessionImpl)._fromIdtoken;
7764 return [4 /*yield*/, this.user.getIdToken()];
7765 case 1: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
7766 }
7767 });
7768 });
7769 };
7770 MultiFactorUserImpl.prototype.enroll = function (assertionExtern, displayName) {
7771 return __awaiter(this, void 0, void 0, function () {
7772 var assertion, session, finalizeMfaResponse;
7773 return __generator(this, function (_a) {
7774 switch (_a.label) {
7775 case 0:
7776 assertion = assertionExtern;
7777 return [4 /*yield*/, this.getSession()];
7778 case 1:
7779 session = (_a.sent());
7780 return [4 /*yield*/, _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName))];
7781 case 2:
7782 finalizeMfaResponse = _a.sent();
7783 // New tokens will be issued after enrollment of the new second factors.
7784 // They need to be updated on the user.
7785 return [4 /*yield*/, this.user._updateTokensIfNecessary(finalizeMfaResponse)];
7786 case 3:
7787 // New tokens will be issued after enrollment of the new second factors.
7788 // They need to be updated on the user.
7789 _a.sent();
7790 // The user needs to be reloaded to get the new multi-factor information
7791 // from server. USER_RELOADED event will be triggered and `enrolledFactors`
7792 // will be updated.
7793 return [2 /*return*/, this.user.reload()];
7794 }
7795 });
7796 });
7797 };
7798 MultiFactorUserImpl.prototype.unenroll = function (infoOrUid) {
7799 return __awaiter(this, void 0, void 0, function () {
7800 var mfaEnrollmentId, idToken, idTokenResponse, e_1;
7801 return __generator(this, function (_a) {
7802 switch (_a.label) {
7803 case 0:
7804 mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;
7805 return [4 /*yield*/, this.user.getIdToken()];
7806 case 1:
7807 idToken = _a.sent();
7808 return [4 /*yield*/, _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {
7809 idToken: idToken,
7810 mfaEnrollmentId: mfaEnrollmentId
7811 }))];
7812 case 2:
7813 idTokenResponse = _a.sent();
7814 // Remove the second factor from the user's list.
7815 this.enrolledFactors = this.enrolledFactors.filter(function (_a) {
7816 var uid = _a.uid;
7817 return uid !== mfaEnrollmentId;
7818 });
7819 // Depending on whether the backend decided to revoke the user's session,
7820 // the tokenResponse may be empty. If the tokens were not updated (and they
7821 // are now invalid), reloading the user will discover this and invalidate
7822 // the user's state accordingly.
7823 return [4 /*yield*/, this.user._updateTokensIfNecessary(idTokenResponse)];
7824 case 3:
7825 // Depending on whether the backend decided to revoke the user's session,
7826 // the tokenResponse may be empty. If the tokens were not updated (and they
7827 // are now invalid), reloading the user will discover this and invalidate
7828 // the user's state accordingly.
7829 _a.sent();
7830 _a.label = 4;
7831 case 4:
7832 _a.trys.push([4, 6, , 7]);
7833 return [4 /*yield*/, this.user.reload()];
7834 case 5:
7835 _a.sent();
7836 return [3 /*break*/, 7];
7837 case 6:
7838 e_1 = _a.sent();
7839 if (e_1.code !== "auth/" + "user-token-expired" /* TOKEN_EXPIRED */) {
7840 throw e_1;
7841 }
7842 return [3 /*break*/, 7];
7843 case 7: return [2 /*return*/];
7844 }
7845 });
7846 });
7847 };
7848 return MultiFactorUserImpl;
7849}());
7850var multiFactorUserCache = new WeakMap();
7851/**
7852 * The {@link MultiFactorUser} corresponding to the user.
7853 *
7854 * @remarks
7855 * This is used to access all multi-factor properties and operations related to the user.
7856 *
7857 * @param user - The user.
7858 *
7859 * @public
7860 */
7861function multiFactor(user) {
7862 var userModular = getModularInstance(user);
7863 if (!multiFactorUserCache.has(userModular)) {
7864 multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));
7865 }
7866 return multiFactorUserCache.get(userModular);
7867}
7868
7869var name = "@firebase/auth";
7870var version = "0.20.1";
7871
7872/**
7873 * @license
7874 * Copyright 2020 Google LLC
7875 *
7876 * Licensed under the Apache License, Version 2.0 (the "License");
7877 * you may not use this file except in compliance with the License.
7878 * You may obtain a copy of the License at
7879 *
7880 * http://www.apache.org/licenses/LICENSE-2.0
7881 *
7882 * Unless required by applicable law or agreed to in writing, software
7883 * distributed under the License is distributed on an "AS IS" BASIS,
7884 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7885 * See the License for the specific language governing permissions and
7886 * limitations under the License.
7887 */
7888var AuthInterop = /** @class */ (function () {
7889 function AuthInterop(auth) {
7890 this.auth = auth;
7891 this.internalListeners = new Map();
7892 }
7893 AuthInterop.prototype.getUid = function () {
7894 var _a;
7895 this.assertAuthConfigured();
7896 return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;
7897 };
7898 AuthInterop.prototype.getToken = function (forceRefresh) {
7899 return __awaiter(this, void 0, void 0, function () {
7900 var accessToken;
7901 return __generator(this, function (_a) {
7902 switch (_a.label) {
7903 case 0:
7904 this.assertAuthConfigured();
7905 return [4 /*yield*/, this.auth._initializationPromise];
7906 case 1:
7907 _a.sent();
7908 if (!this.auth.currentUser) {
7909 return [2 /*return*/, null];
7910 }
7911 return [4 /*yield*/, this.auth.currentUser.getIdToken(forceRefresh)];
7912 case 2:
7913 accessToken = _a.sent();
7914 return [2 /*return*/, { accessToken: accessToken }];
7915 }
7916 });
7917 });
7918 };
7919 AuthInterop.prototype.addAuthTokenListener = function (listener) {
7920 this.assertAuthConfigured();
7921 if (this.internalListeners.has(listener)) {
7922 return;
7923 }
7924 var unsubscribe = this.auth.onIdTokenChanged(function (user) {
7925 var _a;
7926 listener(((_a = user) === null || _a === void 0 ? void 0 : _a.stsTokenManager.accessToken) || null);
7927 });
7928 this.internalListeners.set(listener, unsubscribe);
7929 this.updateProactiveRefresh();
7930 };
7931 AuthInterop.prototype.removeAuthTokenListener = function (listener) {
7932 this.assertAuthConfigured();
7933 var unsubscribe = this.internalListeners.get(listener);
7934 if (!unsubscribe) {
7935 return;
7936 }
7937 this.internalListeners.delete(listener);
7938 unsubscribe();
7939 this.updateProactiveRefresh();
7940 };
7941 AuthInterop.prototype.assertAuthConfigured = function () {
7942 _assert(this.auth._initializationPromise, "dependent-sdk-initialized-before-auth" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */);
7943 };
7944 AuthInterop.prototype.updateProactiveRefresh = function () {
7945 if (this.internalListeners.size > 0) {
7946 this.auth._startProactiveRefresh();
7947 }
7948 else {
7949 this.auth._stopProactiveRefresh();
7950 }
7951 };
7952 return AuthInterop;
7953}());
7954
7955/**
7956 * @license
7957 * Copyright 2020 Google LLC
7958 *
7959 * Licensed under the Apache License, Version 2.0 (the "License");
7960 * you may not use this file except in compliance with the License.
7961 * You may obtain a copy of the License at
7962 *
7963 * http://www.apache.org/licenses/LICENSE-2.0
7964 *
7965 * Unless required by applicable law or agreed to in writing, software
7966 * distributed under the License is distributed on an "AS IS" BASIS,
7967 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7968 * See the License for the specific language governing permissions and
7969 * limitations under the License.
7970 */
7971function getVersionForPlatform(clientPlatform) {
7972 switch (clientPlatform) {
7973 case "Node" /* NODE */:
7974 return 'node';
7975 case "ReactNative" /* REACT_NATIVE */:
7976 return 'rn';
7977 case "Worker" /* WORKER */:
7978 return 'webworker';
7979 case "Cordova" /* CORDOVA */:
7980 return 'cordova';
7981 default:
7982 return undefined;
7983 }
7984}
7985/** @internal */
7986function registerAuth(clientPlatform) {
7987 _registerComponent(new Component("auth" /* AUTH */, function (container, _a) {
7988 var deps = _a.options;
7989 var app = container.getProvider('app').getImmediate();
7990 var heartbeatServiceProvider = container.getProvider('heartbeat');
7991 var _b = app.options, apiKey = _b.apiKey, authDomain = _b.authDomain;
7992 return (function (app, heartbeatServiceProvider) {
7993 _assert(apiKey && !apiKey.includes(':'), "invalid-api-key" /* INVALID_API_KEY */, { appName: app.name });
7994 // Auth domain is optional if IdP sign in isn't being used
7995 _assert(!(authDomain === null || authDomain === void 0 ? void 0 : authDomain.includes(':')), "argument-error" /* ARGUMENT_ERROR */, {
7996 appName: app.name
7997 });
7998 var config = {
7999 apiKey: apiKey,
8000 authDomain: authDomain,
8001 clientPlatform: clientPlatform,
8002 apiHost: "identitytoolkit.googleapis.com" /* API_HOST */,
8003 tokenApiHost: "securetoken.googleapis.com" /* TOKEN_API_HOST */,
8004 apiScheme: "https" /* API_SCHEME */,
8005 sdkClientVersion: _getClientVersion(clientPlatform)
8006 };
8007 var authInstance = new AuthImpl(app, heartbeatServiceProvider, config);
8008 _initializeAuthInstance(authInstance, deps);
8009 return authInstance;
8010 })(app, heartbeatServiceProvider);
8011 }, "PUBLIC" /* PUBLIC */)
8012 /**
8013 * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()
8014 * For why we do this, See go/firebase-next-auth-init
8015 */
8016 .setInstantiationMode("EXPLICIT" /* EXPLICIT */)
8017 /**
8018 * Because all firebase products that depend on auth depend on auth-internal directly,
8019 * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.
8020 */
8021 .setInstanceCreatedCallback(function (container, _instanceIdentifier, _instance) {
8022 var authInternalProvider = container.getProvider("auth-internal" /* AUTH_INTERNAL */);
8023 authInternalProvider.initialize();
8024 }));
8025 _registerComponent(new Component("auth-internal" /* AUTH_INTERNAL */, function (container) {
8026 var auth = _castAuth(container.getProvider("auth" /* AUTH */).getImmediate());
8027 return (function (auth) { return new AuthInterop(auth); })(auth);
8028 }, "PRIVATE" /* PRIVATE */).setInstantiationMode("EXPLICIT" /* EXPLICIT */));
8029 registerVersion(name, version, getVersionForPlatform(clientPlatform));
8030 // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
8031 registerVersion(name, version, 'esm5');
8032}
8033
8034/**
8035 * @license
8036 * Copyright 2021 Google LLC
8037 *
8038 * Licensed under the Apache License, Version 2.0 (the "License");
8039 * you may not use this file except in compliance with the License.
8040 * You may obtain a copy of the License at
8041 *
8042 * http://www.apache.org/licenses/LICENSE-2.0
8043 *
8044 * Unless required by applicable law or agreed to in writing, software
8045 * distributed under the License is distributed on an "AS IS" BASIS,
8046 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8047 * See the License for the specific language governing permissions and
8048 * limitations under the License.
8049 */
8050/**
8051 * An enum of factors that may be used for multifactor authentication.
8052 *
8053 * @public
8054 */
8055var FactorId = {
8056 /** Phone as second factor */
8057 PHONE: 'phone'
8058};
8059/**
8060 * Enumeration of supported providers.
8061 *
8062 * @public
8063 */
8064var ProviderId = {
8065 /** Facebook provider ID */
8066 FACEBOOK: 'facebook.com',
8067 /** GitHub provider ID */
8068 GITHUB: 'github.com',
8069 /** Google provider ID */
8070 GOOGLE: 'google.com',
8071 /** Password provider */
8072 PASSWORD: 'password',
8073 /** Phone provider */
8074 PHONE: 'phone',
8075 /** Twitter provider ID */
8076 TWITTER: 'twitter.com'
8077};
8078/**
8079 * Enumeration of supported sign-in methods.
8080 *
8081 * @public
8082 */
8083var SignInMethod = {
8084 /** Email link sign in method */
8085 EMAIL_LINK: 'emailLink',
8086 /** Email/password sign in method */
8087 EMAIL_PASSWORD: 'password',
8088 /** Facebook sign in method */
8089 FACEBOOK: 'facebook.com',
8090 /** GitHub sign in method */
8091 GITHUB: 'github.com',
8092 /** Google sign in method */
8093 GOOGLE: 'google.com',
8094 /** Phone sign in method */
8095 PHONE: 'phone',
8096 /** Twitter sign in method */
8097 TWITTER: 'twitter.com'
8098};
8099/**
8100 * Enumeration of supported operation types.
8101 *
8102 * @public
8103 */
8104var OperationType = {
8105 /** Operation involving linking an additional provider to an already signed-in user. */
8106 LINK: 'link',
8107 /** Operation involving using a provider to reauthenticate an already signed-in user. */
8108 REAUTHENTICATE: 'reauthenticate',
8109 /** Operation involving signing in a user. */
8110 SIGN_IN: 'signIn'
8111};
8112/**
8113 * An enumeration of the possible email action types.
8114 *
8115 * @public
8116 */
8117var ActionCodeOperation = {
8118 /** The email link sign-in action. */
8119 EMAIL_SIGNIN: 'EMAIL_SIGNIN',
8120 /** The password reset action. */
8121 PASSWORD_RESET: 'PASSWORD_RESET',
8122 /** The email revocation action. */
8123 RECOVER_EMAIL: 'RECOVER_EMAIL',
8124 /** The revert second factor addition email action. */
8125 REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',
8126 /** The revert second factor addition email action. */
8127 VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',
8128 /** The email verification action. */
8129 VERIFY_EMAIL: 'VERIFY_EMAIL'
8130};
8131
8132/**
8133 * @license
8134 * Copyright 2019 Google LLC
8135 *
8136 * Licensed under the Apache License, Version 2.0 (the "License");
8137 * you may not use this file except in compliance with the License.
8138 * You may obtain a copy of the License at
8139 *
8140 * http://www.apache.org/licenses/LICENSE-2.0
8141 *
8142 * Unless required by applicable law or agreed to in writing, software
8143 * distributed under the License is distributed on an "AS IS" BASIS,
8144 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8145 * See the License for the specific language governing permissions and
8146 * limitations under the License.
8147 */
8148// There are two different browser persistence types: local and session.
8149// Both have the same implementation but use a different underlying storage
8150// object.
8151var BrowserPersistenceClass = /** @class */ (function () {
8152 function BrowserPersistenceClass(storageRetriever, type) {
8153 this.storageRetriever = storageRetriever;
8154 this.type = type;
8155 }
8156 BrowserPersistenceClass.prototype._isAvailable = function () {
8157 try {
8158 if (!this.storage) {
8159 return Promise.resolve(false);
8160 }
8161 this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');
8162 this.storage.removeItem(STORAGE_AVAILABLE_KEY);
8163 return Promise.resolve(true);
8164 }
8165 catch (_a) {
8166 return Promise.resolve(false);
8167 }
8168 };
8169 BrowserPersistenceClass.prototype._set = function (key, value) {
8170 this.storage.setItem(key, JSON.stringify(value));
8171 return Promise.resolve();
8172 };
8173 BrowserPersistenceClass.prototype._get = function (key) {
8174 var json = this.storage.getItem(key);
8175 return Promise.resolve(json ? JSON.parse(json) : null);
8176 };
8177 BrowserPersistenceClass.prototype._remove = function (key) {
8178 this.storage.removeItem(key);
8179 return Promise.resolve();
8180 };
8181 Object.defineProperty(BrowserPersistenceClass.prototype, "storage", {
8182 get: function () {
8183 return this.storageRetriever();
8184 },
8185 enumerable: false,
8186 configurable: true
8187 });
8188 return BrowserPersistenceClass;
8189}());
8190
8191/**
8192 * @license
8193 * Copyright 2020 Google LLC
8194 *
8195 * Licensed under the Apache License, Version 2.0 (the "License");
8196 * you may not use this file except in compliance with the License.
8197 * You may obtain a copy of the License at
8198 *
8199 * http://www.apache.org/licenses/LICENSE-2.0
8200 *
8201 * Unless required by applicable law or agreed to in writing, software
8202 * distributed under the License is distributed on an "AS IS" BASIS,
8203 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8204 * See the License for the specific language governing permissions and
8205 * limitations under the License.
8206 */
8207function _iframeCannotSyncWebStorage() {
8208 var ua = getUA();
8209 return _isSafari(ua) || _isIOS(ua);
8210}
8211// The polling period in case events are not supported
8212var _POLLING_INTERVAL_MS = 1000;
8213// The IE 10 localStorage cross tab synchronization delay in milliseconds
8214var IE10_LOCAL_STORAGE_SYNC_DELAY = 10;
8215var BrowserLocalPersistence = /** @class */ (function (_super) {
8216 __extends(BrowserLocalPersistence, _super);
8217 function BrowserLocalPersistence() {
8218 var _this = _super.call(this, function () { return window.localStorage; }, "LOCAL" /* LOCAL */) || this;
8219 _this.boundEventHandler = function (event, poll) { return _this.onStorageEvent(event, poll); };
8220 _this.listeners = {};
8221 _this.localCache = {};
8222 // setTimeout return value is platform specific
8223 // eslint-disable-next-line @typescript-eslint/no-explicit-any
8224 _this.pollTimer = null;
8225 // Safari or iOS browser and embedded in an iframe.
8226 _this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();
8227 // Whether to use polling instead of depending on window events
8228 _this.fallbackToPolling = _isMobileBrowser();
8229 _this._shouldAllowMigration = true;
8230 return _this;
8231 }
8232 BrowserLocalPersistence.prototype.forAllChangedKeys = function (cb) {
8233 // Check all keys with listeners on them.
8234 for (var _i = 0, _a = Object.keys(this.listeners); _i < _a.length; _i++) {
8235 var key = _a[_i];
8236 // Get value from localStorage.
8237 var newValue = this.storage.getItem(key);
8238 var oldValue = this.localCache[key];
8239 // If local map value does not match, trigger listener with storage event.
8240 // Differentiate this simulated event from the real storage event.
8241 if (newValue !== oldValue) {
8242 cb(key, oldValue, newValue);
8243 }
8244 }
8245 };
8246 BrowserLocalPersistence.prototype.onStorageEvent = function (event, poll) {
8247 var _this = this;
8248 if (poll === void 0) { poll = false; }
8249 // Key would be null in some situations, like when localStorage is cleared
8250 if (!event.key) {
8251 this.forAllChangedKeys(function (key, _oldValue, newValue) {
8252 _this.notifyListeners(key, newValue);
8253 });
8254 return;
8255 }
8256 var key = event.key;
8257 // Check the mechanism how this event was detected.
8258 // The first event will dictate the mechanism to be used.
8259 if (poll) {
8260 // Environment detects storage changes via polling.
8261 // Remove storage event listener to prevent possible event duplication.
8262 this.detachListener();
8263 }
8264 else {
8265 // Environment detects storage changes via storage event listener.
8266 // Remove polling listener to prevent possible event duplication.
8267 this.stopPolling();
8268 }
8269 // Safari embedded iframe. Storage event will trigger with the delta
8270 // changes but no changes will be applied to the iframe localStorage.
8271 if (this.safariLocalStorageNotSynced) {
8272 // Get current iframe page value.
8273 var storedValue_1 = this.storage.getItem(key);
8274 // Value not synchronized, synchronize manually.
8275 if (event.newValue !== storedValue_1) {
8276 if (event.newValue !== null) {
8277 // Value changed from current value.
8278 this.storage.setItem(key, event.newValue);
8279 }
8280 else {
8281 // Current value deleted.
8282 this.storage.removeItem(key);
8283 }
8284 }
8285 else if (this.localCache[key] === event.newValue && !poll) {
8286 // Already detected and processed, do not trigger listeners again.
8287 return;
8288 }
8289 }
8290 var triggerListeners = function () {
8291 // Keep local map up to date in case storage event is triggered before
8292 // poll.
8293 var storedValue = _this.storage.getItem(key);
8294 if (!poll && _this.localCache[key] === storedValue) {
8295 // Real storage event which has already been detected, do nothing.
8296 // This seems to trigger in some IE browsers for some reason.
8297 return;
8298 }
8299 _this.notifyListeners(key, storedValue);
8300 };
8301 var storedValue = this.storage.getItem(key);
8302 if (_isIE10() &&
8303 storedValue !== event.newValue &&
8304 event.newValue !== event.oldValue) {
8305 // IE 10 has this weird bug where a storage event would trigger with the
8306 // correct key, oldValue and newValue but localStorage.getItem(key) does
8307 // not yield the updated value until a few milliseconds. This ensures
8308 // this recovers from that situation.
8309 setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);
8310 }
8311 else {
8312 triggerListeners();
8313 }
8314 };
8315 BrowserLocalPersistence.prototype.notifyListeners = function (key, value) {
8316 this.localCache[key] = value;
8317 var listeners = this.listeners[key];
8318 if (listeners) {
8319 for (var _i = 0, _a = Array.from(listeners); _i < _a.length; _i++) {
8320 var listener = _a[_i];
8321 listener(value ? JSON.parse(value) : value);
8322 }
8323 }
8324 };
8325 BrowserLocalPersistence.prototype.startPolling = function () {
8326 var _this = this;
8327 this.stopPolling();
8328 this.pollTimer = setInterval(function () {
8329 _this.forAllChangedKeys(function (key, oldValue, newValue) {
8330 _this.onStorageEvent(new StorageEvent('storage', {
8331 key: key,
8332 oldValue: oldValue,
8333 newValue: newValue
8334 }),
8335 /* poll */ true);
8336 });
8337 }, _POLLING_INTERVAL_MS);
8338 };
8339 BrowserLocalPersistence.prototype.stopPolling = function () {
8340 if (this.pollTimer) {
8341 clearInterval(this.pollTimer);
8342 this.pollTimer = null;
8343 }
8344 };
8345 BrowserLocalPersistence.prototype.attachListener = function () {
8346 window.addEventListener('storage', this.boundEventHandler);
8347 };
8348 BrowserLocalPersistence.prototype.detachListener = function () {
8349 window.removeEventListener('storage', this.boundEventHandler);
8350 };
8351 BrowserLocalPersistence.prototype._addListener = function (key, listener) {
8352 if (Object.keys(this.listeners).length === 0) {
8353 // Whether browser can detect storage event when it had already been pushed to the background.
8354 // This may happen in some mobile browsers. A localStorage change in the foreground window
8355 // will not be detected in the background window via the storage event.
8356 // This was detected in iOS 7.x mobile browsers
8357 if (this.fallbackToPolling) {
8358 this.startPolling();
8359 }
8360 else {
8361 this.attachListener();
8362 }
8363 }
8364 if (!this.listeners[key]) {
8365 this.listeners[key] = new Set();
8366 // Populate the cache to avoid spuriously triggering on first poll.
8367 this.localCache[key] = this.storage.getItem(key);
8368 }
8369 this.listeners[key].add(listener);
8370 };
8371 BrowserLocalPersistence.prototype._removeListener = function (key, listener) {
8372 if (this.listeners[key]) {
8373 this.listeners[key].delete(listener);
8374 if (this.listeners[key].size === 0) {
8375 delete this.listeners[key];
8376 }
8377 }
8378 if (Object.keys(this.listeners).length === 0) {
8379 this.detachListener();
8380 this.stopPolling();
8381 }
8382 };
8383 // Update local cache on base operations:
8384 BrowserLocalPersistence.prototype._set = function (key, value) {
8385 return __awaiter(this, void 0, void 0, function () {
8386 return __generator(this, function (_a) {
8387 switch (_a.label) {
8388 case 0: return [4 /*yield*/, _super.prototype._set.call(this, key, value)];
8389 case 1:
8390 _a.sent();
8391 this.localCache[key] = JSON.stringify(value);
8392 return [2 /*return*/];
8393 }
8394 });
8395 });
8396 };
8397 BrowserLocalPersistence.prototype._get = function (key) {
8398 return __awaiter(this, void 0, void 0, function () {
8399 var value;
8400 return __generator(this, function (_a) {
8401 switch (_a.label) {
8402 case 0: return [4 /*yield*/, _super.prototype._get.call(this, key)];
8403 case 1:
8404 value = _a.sent();
8405 this.localCache[key] = JSON.stringify(value);
8406 return [2 /*return*/, value];
8407 }
8408 });
8409 });
8410 };
8411 BrowserLocalPersistence.prototype._remove = function (key) {
8412 return __awaiter(this, void 0, void 0, function () {
8413 return __generator(this, function (_a) {
8414 switch (_a.label) {
8415 case 0: return [4 /*yield*/, _super.prototype._remove.call(this, key)];
8416 case 1:
8417 _a.sent();
8418 delete this.localCache[key];
8419 return [2 /*return*/];
8420 }
8421 });
8422 });
8423 };
8424 BrowserLocalPersistence.type = 'LOCAL';
8425 return BrowserLocalPersistence;
8426}(BrowserPersistenceClass));
8427/**
8428 * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`
8429 * for the underlying storage.
8430 *
8431 * @public
8432 */
8433var browserLocalPersistence = BrowserLocalPersistence;
8434
8435/**
8436 * @license
8437 * Copyright 2020 Google LLC
8438 *
8439 * Licensed under the Apache License, Version 2.0 (the "License");
8440 * you may not use this file except in compliance with the License.
8441 * You may obtain a copy of the License at
8442 *
8443 * http://www.apache.org/licenses/LICENSE-2.0
8444 *
8445 * Unless required by applicable law or agreed to in writing, software
8446 * distributed under the License is distributed on an "AS IS" BASIS,
8447 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8448 * See the License for the specific language governing permissions and
8449 * limitations under the License.
8450 */
8451var BrowserSessionPersistence = /** @class */ (function (_super) {
8452 __extends(BrowserSessionPersistence, _super);
8453 function BrowserSessionPersistence() {
8454 return _super.call(this, function () { return window.sessionStorage; }, "SESSION" /* SESSION */) || this;
8455 }
8456 BrowserSessionPersistence.prototype._addListener = function (_key, _listener) {
8457 // Listeners are not supported for session storage since it cannot be shared across windows
8458 return;
8459 };
8460 BrowserSessionPersistence.prototype._removeListener = function (_key, _listener) {
8461 // Listeners are not supported for session storage since it cannot be shared across windows
8462 return;
8463 };
8464 BrowserSessionPersistence.type = 'SESSION';
8465 return BrowserSessionPersistence;
8466}(BrowserPersistenceClass));
8467/**
8468 * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`
8469 * for the underlying storage.
8470 *
8471 * @public
8472 */
8473var browserSessionPersistence = BrowserSessionPersistence;
8474
8475/**
8476 * @license
8477 * Copyright 2021 Google LLC
8478 *
8479 * Licensed under the Apache License, Version 2.0 (the "License");
8480 * you may not use this file except in compliance with the License.
8481 * You may obtain a copy of the License at
8482 *
8483 * http://www.apache.org/licenses/LICENSE-2.0
8484 *
8485 * Unless required by applicable law or agreed to in writing, software
8486 * distributed under the License is distributed on an "AS IS" BASIS,
8487 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8488 * See the License for the specific language governing permissions and
8489 * limitations under the License.
8490 */
8491/**
8492 * Chooses a popup/redirect resolver to use. This prefers the override (which
8493 * is directly passed in), and falls back to the property set on the auth
8494 * object. If neither are available, this function errors w/ an argument error.
8495 */
8496function _withDefaultResolver(auth, resolverOverride) {
8497 if (resolverOverride) {
8498 return _getInstance(resolverOverride);
8499 }
8500 _assert(auth._popupRedirectResolver, auth, "argument-error" /* ARGUMENT_ERROR */);
8501 return auth._popupRedirectResolver;
8502}
8503
8504/**
8505 * @license
8506 * Copyright 2019 Google LLC
8507 *
8508 * Licensed under the Apache License, Version 2.0 (the "License");
8509 * you may not use this file except in compliance with the License.
8510 * You may obtain a copy of the License at
8511 *
8512 * http://www.apache.org/licenses/LICENSE-2.0
8513 *
8514 * Unless required by applicable law or agreed to in writing, software
8515 * distributed under the License is distributed on an "AS IS" BASIS,
8516 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8517 * See the License for the specific language governing permissions and
8518 * limitations under the License.
8519 */
8520var IdpCredential = /** @class */ (function (_super) {
8521 __extends(IdpCredential, _super);
8522 function IdpCredential(params) {
8523 var _this = _super.call(this, "custom" /* CUSTOM */, "custom" /* CUSTOM */) || this;
8524 _this.params = params;
8525 return _this;
8526 }
8527 IdpCredential.prototype._getIdTokenResponse = function (auth) {
8528 return signInWithIdp(auth, this._buildIdpRequest());
8529 };
8530 IdpCredential.prototype._linkToIdToken = function (auth, idToken) {
8531 return signInWithIdp(auth, this._buildIdpRequest(idToken));
8532 };
8533 IdpCredential.prototype._getReauthenticationResolver = function (auth) {
8534 return signInWithIdp(auth, this._buildIdpRequest());
8535 };
8536 IdpCredential.prototype._buildIdpRequest = function (idToken) {
8537 var request = {
8538 requestUri: this.params.requestUri,
8539 sessionId: this.params.sessionId,
8540 postBody: this.params.postBody,
8541 tenantId: this.params.tenantId,
8542 pendingToken: this.params.pendingToken,
8543 returnSecureToken: true,
8544 returnIdpCredential: true
8545 };
8546 if (idToken) {
8547 request.idToken = idToken;
8548 }
8549 return request;
8550 };
8551 return IdpCredential;
8552}(AuthCredential));
8553function _signIn(params) {
8554 return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);
8555}
8556function _reauth(params) {
8557 var auth = params.auth, user = params.user;
8558 _assert(user, auth, "internal-error" /* INTERNAL_ERROR */);
8559 return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);
8560}
8561function _link(params) {
8562 return __awaiter(this, void 0, void 0, function () {
8563 var auth, user;
8564 return __generator(this, function (_a) {
8565 auth = params.auth, user = params.user;
8566 _assert(user, auth, "internal-error" /* INTERNAL_ERROR */);
8567 return [2 /*return*/, _link$1(user, new IdpCredential(params), params.bypassAuthState)];
8568 });
8569 });
8570}
8571
8572/**
8573 * @license
8574 * Copyright 2020 Google LLC
8575 *
8576 * Licensed under the Apache License, Version 2.0 (the "License");
8577 * you may not use this file except in compliance with the License.
8578 * You may obtain a copy of the License at
8579 *
8580 * http://www.apache.org/licenses/LICENSE-2.0
8581 *
8582 * Unless required by applicable law or agreed to in writing, software
8583 * distributed under the License is distributed on an "AS IS" BASIS,
8584 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8585 * See the License for the specific language governing permissions and
8586 * limitations under the License.
8587 */
8588/**
8589 * Popup event manager. Handles the popup's entire lifecycle; listens to auth
8590 * events
8591 */
8592var AbstractPopupRedirectOperation = /** @class */ (function () {
8593 function AbstractPopupRedirectOperation(auth, filter, resolver, user, bypassAuthState) {
8594 if (bypassAuthState === void 0) { bypassAuthState = false; }
8595 this.auth = auth;
8596 this.resolver = resolver;
8597 this.user = user;
8598 this.bypassAuthState = bypassAuthState;
8599 this.pendingPromise = null;
8600 this.eventManager = null;
8601 this.filter = Array.isArray(filter) ? filter : [filter];
8602 }
8603 AbstractPopupRedirectOperation.prototype.execute = function () {
8604 var _this = this;
8605 return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
8606 var _a, e_1;
8607 return __generator(this, function (_b) {
8608 switch (_b.label) {
8609 case 0:
8610 this.pendingPromise = { resolve: resolve, reject: reject };
8611 _b.label = 1;
8612 case 1:
8613 _b.trys.push([1, 4, , 5]);
8614 _a = this;
8615 return [4 /*yield*/, this.resolver._initialize(this.auth)];
8616 case 2:
8617 _a.eventManager = _b.sent();
8618 return [4 /*yield*/, this.onExecution()];
8619 case 3:
8620 _b.sent();
8621 this.eventManager.registerConsumer(this);
8622 return [3 /*break*/, 5];
8623 case 4:
8624 e_1 = _b.sent();
8625 this.reject(e_1);
8626 return [3 /*break*/, 5];
8627 case 5: return [2 /*return*/];
8628 }
8629 });
8630 }); });
8631 };
8632 AbstractPopupRedirectOperation.prototype.onAuthEvent = function (event) {
8633 return __awaiter(this, void 0, void 0, function () {
8634 var urlResponse, sessionId, postBody, tenantId, error, type, params, _a, e_2;
8635 return __generator(this, function (_b) {
8636 switch (_b.label) {
8637 case 0:
8638 urlResponse = event.urlResponse, sessionId = event.sessionId, postBody = event.postBody, tenantId = event.tenantId, error = event.error, type = event.type;
8639 if (error) {
8640 this.reject(error);
8641 return [2 /*return*/];
8642 }
8643 params = {
8644 auth: this.auth,
8645 requestUri: urlResponse,
8646 sessionId: sessionId,
8647 tenantId: tenantId || undefined,
8648 postBody: postBody || undefined,
8649 user: this.user,
8650 bypassAuthState: this.bypassAuthState
8651 };
8652 _b.label = 1;
8653 case 1:
8654 _b.trys.push([1, 3, , 4]);
8655 _a = this.resolve;
8656 return [4 /*yield*/, this.getIdpTask(type)(params)];
8657 case 2:
8658 _a.apply(this, [_b.sent()]);
8659 return [3 /*break*/, 4];
8660 case 3:
8661 e_2 = _b.sent();
8662 this.reject(e_2);
8663 return [3 /*break*/, 4];
8664 case 4: return [2 /*return*/];
8665 }
8666 });
8667 });
8668 };
8669 AbstractPopupRedirectOperation.prototype.onError = function (error) {
8670 this.reject(error);
8671 };
8672 AbstractPopupRedirectOperation.prototype.getIdpTask = function (type) {
8673 switch (type) {
8674 case "signInViaPopup" /* SIGN_IN_VIA_POPUP */:
8675 case "signInViaRedirect" /* SIGN_IN_VIA_REDIRECT */:
8676 return _signIn;
8677 case "linkViaPopup" /* LINK_VIA_POPUP */:
8678 case "linkViaRedirect" /* LINK_VIA_REDIRECT */:
8679 return _link;
8680 case "reauthViaPopup" /* REAUTH_VIA_POPUP */:
8681 case "reauthViaRedirect" /* REAUTH_VIA_REDIRECT */:
8682 return _reauth;
8683 default:
8684 _fail(this.auth, "internal-error" /* INTERNAL_ERROR */);
8685 }
8686 };
8687 AbstractPopupRedirectOperation.prototype.resolve = function (cred) {
8688 debugAssert(this.pendingPromise, 'Pending promise was never set');
8689 this.pendingPromise.resolve(cred);
8690 this.unregisterAndCleanUp();
8691 };
8692 AbstractPopupRedirectOperation.prototype.reject = function (error) {
8693 debugAssert(this.pendingPromise, 'Pending promise was never set');
8694 this.pendingPromise.reject(error);
8695 this.unregisterAndCleanUp();
8696 };
8697 AbstractPopupRedirectOperation.prototype.unregisterAndCleanUp = function () {
8698 if (this.eventManager) {
8699 this.eventManager.unregisterConsumer(this);
8700 }
8701 this.pendingPromise = null;
8702 this.cleanUp();
8703 };
8704 return AbstractPopupRedirectOperation;
8705}());
8706
8707/**
8708 * @license
8709 * Copyright 2020 Google LLC
8710 *
8711 * Licensed under the Apache License, Version 2.0 (the "License");
8712 * you may not use this file except in compliance with the License.
8713 * You may obtain a copy of the License at
8714 *
8715 * http://www.apache.org/licenses/LICENSE-2.0
8716 *
8717 * Unless required by applicable law or agreed to in writing, software
8718 * distributed under the License is distributed on an "AS IS" BASIS,
8719 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8720 * See the License for the specific language governing permissions and
8721 * limitations under the License.
8722 */
8723var PENDING_REDIRECT_KEY = 'pendingRedirect';
8724// We only get one redirect outcome for any one auth, so just store it
8725// in here.
8726var redirectOutcomeMap = new Map();
8727var RedirectAction = /** @class */ (function (_super) {
8728 __extends(RedirectAction, _super);
8729 function RedirectAction(auth, resolver, bypassAuthState) {
8730 if (bypassAuthState === void 0) { bypassAuthState = false; }
8731 var _this = _super.call(this, auth, [
8732 "signInViaRedirect" /* SIGN_IN_VIA_REDIRECT */,
8733 "linkViaRedirect" /* LINK_VIA_REDIRECT */,
8734 "reauthViaRedirect" /* REAUTH_VIA_REDIRECT */,
8735 "unknown" /* UNKNOWN */
8736 ], resolver, undefined, bypassAuthState) || this;
8737 _this.eventId = null;
8738 return _this;
8739 }
8740 /**
8741 * Override the execute function; if we already have a redirect result, then
8742 * just return it.
8743 */
8744 RedirectAction.prototype.execute = function () {
8745 return __awaiter(this, void 0, void 0, function () {
8746 var readyOutcome, hasPendingRedirect, result_1, _a, e_1;
8747 return __generator(this, function (_b) {
8748 switch (_b.label) {
8749 case 0:
8750 readyOutcome = redirectOutcomeMap.get(this.auth._key());
8751 if (!!readyOutcome) return [3 /*break*/, 8];
8752 _b.label = 1;
8753 case 1:
8754 _b.trys.push([1, 6, , 7]);
8755 return [4 /*yield*/, _getAndClearPendingRedirectStatus(this.resolver, this.auth)];
8756 case 2:
8757 hasPendingRedirect = _b.sent();
8758 if (!hasPendingRedirect) return [3 /*break*/, 4];
8759 return [4 /*yield*/, _super.prototype.execute.call(this)];
8760 case 3:
8761 _a = _b.sent();
8762 return [3 /*break*/, 5];
8763 case 4:
8764 _a = null;
8765 _b.label = 5;
8766 case 5:
8767 result_1 = _a;
8768 readyOutcome = function () { return Promise.resolve(result_1); };
8769 return [3 /*break*/, 7];
8770 case 6:
8771 e_1 = _b.sent();
8772 readyOutcome = function () { return Promise.reject(e_1); };
8773 return [3 /*break*/, 7];
8774 case 7:
8775 redirectOutcomeMap.set(this.auth._key(), readyOutcome);
8776 _b.label = 8;
8777 case 8:
8778 // If we're not bypassing auth state, the ready outcome should be set to
8779 // null.
8780 if (!this.bypassAuthState) {
8781 redirectOutcomeMap.set(this.auth._key(), function () { return Promise.resolve(null); });
8782 }
8783 return [2 /*return*/, readyOutcome()];
8784 }
8785 });
8786 });
8787 };
8788 RedirectAction.prototype.onAuthEvent = function (event) {
8789 return __awaiter(this, void 0, void 0, function () {
8790 var user;
8791 return __generator(this, function (_a) {
8792 switch (_a.label) {
8793 case 0:
8794 if (event.type === "signInViaRedirect" /* SIGN_IN_VIA_REDIRECT */) {
8795 return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
8796 }
8797 else if (event.type === "unknown" /* UNKNOWN */) {
8798 // This is a sentinel value indicating there's no pending redirect
8799 this.resolve(null);
8800 return [2 /*return*/];
8801 }
8802 if (!event.eventId) return [3 /*break*/, 2];
8803 return [4 /*yield*/, this.auth._redirectUserForId(event.eventId)];
8804 case 1:
8805 user = _a.sent();
8806 if (user) {
8807 this.user = user;
8808 return [2 /*return*/, _super.prototype.onAuthEvent.call(this, event)];
8809 }
8810 else {
8811 this.resolve(null);
8812 }
8813 _a.label = 2;
8814 case 2: return [2 /*return*/];
8815 }
8816 });
8817 });
8818 };
8819 RedirectAction.prototype.onExecution = function () {
8820 return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
8821 return [2 /*return*/];
8822 }); });
8823 };
8824 RedirectAction.prototype.cleanUp = function () { };
8825 return RedirectAction;
8826}(AbstractPopupRedirectOperation));
8827function _getAndClearPendingRedirectStatus(resolver, auth) {
8828 return __awaiter(this, void 0, void 0, function () {
8829 var key, persistence, hasPendingRedirect;
8830 return __generator(this, function (_a) {
8831 switch (_a.label) {
8832 case 0:
8833 key = pendingRedirectKey(auth);
8834 persistence = resolverPersistence(resolver);
8835 return [4 /*yield*/, persistence._isAvailable()];
8836 case 1:
8837 if (!(_a.sent())) {
8838 return [2 /*return*/, false];
8839 }
8840 return [4 /*yield*/, persistence._get(key)];
8841 case 2:
8842 hasPendingRedirect = (_a.sent()) === 'true';
8843 return [4 /*yield*/, persistence._remove(key)];
8844 case 3:
8845 _a.sent();
8846 return [2 /*return*/, hasPendingRedirect];
8847 }
8848 });
8849 });
8850}
8851function _setPendingRedirectStatus(resolver, auth) {
8852 return __awaiter(this, void 0, void 0, function () {
8853 return __generator(this, function (_a) {
8854 return [2 /*return*/, resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true')];
8855 });
8856 });
8857}
8858function _clearRedirectOutcomes() {
8859 redirectOutcomeMap.clear();
8860}
8861function _overrideRedirectResult(auth, result) {
8862 redirectOutcomeMap.set(auth._key(), result);
8863}
8864function resolverPersistence(resolver) {
8865 return _getInstance(resolver._redirectPersistence);
8866}
8867function pendingRedirectKey(auth) {
8868 return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);
8869}
8870
8871/**
8872 * @license
8873 * Copyright 2020 Google LLC
8874 *
8875 * Licensed under the Apache License, Version 2.0 (the "License");
8876 * you may not use this file except in compliance with the License.
8877 * You may obtain a copy of the License at
8878 *
8879 * http://www.apache.org/licenses/LICENSE-2.0
8880 *
8881 * Unless required by applicable law or agreed to in writing, software
8882 * distributed under the License is distributed on an "AS IS" BASIS,
8883 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
8884 * See the License for the specific language governing permissions and
8885 * limitations under the License.
8886 */
8887/**
8888 * Authenticates a Firebase client using a full-page redirect flow.
8889 *
8890 * @remarks
8891 * To handle the results and errors for this operation, refer to {@link getRedirectResult}.
8892 *
8893 * @example
8894 * ```javascript
8895 * // Sign in using a redirect.
8896 * const provider = new FacebookAuthProvider();
8897 * // You can add additional scopes to the provider:
8898 * provider.addScope('user_birthday');
8899 * // Start a sign in process for an unauthenticated user.
8900 * await signInWithRedirect(auth, provider);
8901 * // This will trigger a full page redirect away from your app
8902 *
8903 * // After returning from the redirect when your app initializes you can obtain the result
8904 * const result = await getRedirectResult(auth);
8905 * if (result) {
8906 * // This is the signed-in user
8907 * const user = result.user;
8908 * // This gives you a Facebook Access Token.
8909 * const credential = provider.credentialFromResult(auth, result);
8910 * const token = credential.accessToken;
8911 * }
8912 * // As this API can be used for sign-in, linking and reauthentication,
8913 * // check the operationType to determine what triggered this redirect
8914 * // operation.
8915 * const operationType = result.operationType;
8916 * ```
8917 *
8918 * @param auth - The {@link Auth} instance.
8919 * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
8920 * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
8921 * @param resolver - An instance of {@link PopupRedirectResolver}, optional
8922 * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
8923 *
8924 * @public
8925 */
8926function signInWithRedirect(auth, provider, resolver) {
8927 return _signInWithRedirect(auth, provider, resolver);
8928}
8929function _signInWithRedirect(auth, provider, resolver) {
8930 return __awaiter(this, void 0, void 0, function () {
8931 var authInternal, resolverInternal;
8932 return __generator(this, function (_a) {
8933 switch (_a.label) {
8934 case 0:
8935 authInternal = _castAuth(auth);
8936 _assertInstanceOf(auth, provider, FederatedAuthProvider);
8937 resolverInternal = _withDefaultResolver(authInternal, resolver);
8938 return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, authInternal)];
8939 case 1:
8940 _a.sent();
8941 return [2 /*return*/, resolverInternal._openRedirect(authInternal, provider, "signInViaRedirect" /* SIGN_IN_VIA_REDIRECT */)];
8942 }
8943 });
8944 });
8945}
8946/**
8947 * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.
8948 *
8949 * @example
8950 * ```javascript
8951 * // Sign in using a redirect.
8952 * const provider = new FacebookAuthProvider();
8953 * const result = await signInWithRedirect(auth, provider);
8954 * // This will trigger a full page redirect away from your app
8955 *
8956 * // After returning from the redirect when your app initializes you can obtain the result
8957 * const result = await getRedirectResult(auth);
8958 * // Link using a redirect.
8959 * await linkWithRedirect(result.user, provider);
8960 * // This will again trigger a full page redirect away from your app
8961 *
8962 * // After returning from the redirect when your app initializes you can obtain the result
8963 * const result = await getRedirectResult(auth);
8964 * ```
8965 *
8966 * @param user - The user.
8967 * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
8968 * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
8969 * @param resolver - An instance of {@link PopupRedirectResolver}, optional
8970 * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
8971 *
8972 * @public
8973 */
8974function reauthenticateWithRedirect(user, provider, resolver) {
8975 return _reauthenticateWithRedirect(user, provider, resolver);
8976}
8977function _reauthenticateWithRedirect(user, provider, resolver) {
8978 return __awaiter(this, void 0, void 0, function () {
8979 var userInternal, resolverInternal, eventId;
8980 return __generator(this, function (_a) {
8981 switch (_a.label) {
8982 case 0:
8983 userInternal = getModularInstance(user);
8984 _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
8985 resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
8986 return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, userInternal.auth)];
8987 case 1:
8988 _a.sent();
8989 return [4 /*yield*/, prepareUserForRedirect(userInternal)];
8990 case 2:
8991 eventId = _a.sent();
8992 return [2 /*return*/, resolverInternal._openRedirect(userInternal.auth, provider, "reauthViaRedirect" /* REAUTH_VIA_REDIRECT */, eventId)];
8993 }
8994 });
8995 });
8996}
8997/**
8998 * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.
8999 *
9000 * @example
9001 * ```javascript
9002 * // Sign in using some other provider.
9003 * const result = await signInWithEmailAndPassword(auth, email, password);
9004 * // Link using a redirect.
9005 * const provider = new FacebookAuthProvider();
9006 * await linkWithRedirect(result.user, provider);
9007 * // This will trigger a full page redirect away from your app
9008 *
9009 * // After returning from the redirect when your app initializes you can obtain the result
9010 * const result = await getRedirectResult(auth);
9011 * ```
9012 *
9013 * @param user - The user.
9014 * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.
9015 * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.
9016 * @param resolver - An instance of {@link PopupRedirectResolver}, optional
9017 * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
9018 *
9019 *
9020 * @public
9021 */
9022function linkWithRedirect(user, provider, resolver) {
9023 return _linkWithRedirect(user, provider, resolver);
9024}
9025function _linkWithRedirect(user, provider, resolver) {
9026 return __awaiter(this, void 0, void 0, function () {
9027 var userInternal, resolverInternal, eventId;
9028 return __generator(this, function (_a) {
9029 switch (_a.label) {
9030 case 0:
9031 userInternal = getModularInstance(user);
9032 _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);
9033 resolverInternal = _withDefaultResolver(userInternal.auth, resolver);
9034 return [4 /*yield*/, _assertLinkedStatus(false, userInternal, provider.providerId)];
9035 case 1:
9036 _a.sent();
9037 return [4 /*yield*/, _setPendingRedirectStatus(resolverInternal, userInternal.auth)];
9038 case 2:
9039 _a.sent();
9040 return [4 /*yield*/, prepareUserForRedirect(userInternal)];
9041 case 3:
9042 eventId = _a.sent();
9043 return [2 /*return*/, resolverInternal._openRedirect(userInternal.auth, provider, "linkViaRedirect" /* LINK_VIA_REDIRECT */, eventId)];
9044 }
9045 });
9046 });
9047}
9048/**
9049 * Returns a {@link UserCredential} from the redirect-based sign-in flow.
9050 *
9051 * @remarks
9052 * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an
9053 * error. If no redirect operation was called, returns a {@link UserCredential}
9054 * with a null `user`.
9055 *
9056 * @example
9057 * ```javascript
9058 * // Sign in using a redirect.
9059 * const provider = new FacebookAuthProvider();
9060 * // You can add additional scopes to the provider:
9061 * provider.addScope('user_birthday');
9062 * // Start a sign in process for an unauthenticated user.
9063 * await signInWithRedirect(auth, provider);
9064 * // This will trigger a full page redirect away from your app
9065 *
9066 * // After returning from the redirect when your app initializes you can obtain the result
9067 * const result = await getRedirectResult(auth);
9068 * if (result) {
9069 * // This is the signed-in user
9070 * const user = result.user;
9071 * // This gives you a Facebook Access Token.
9072 * const credential = provider.credentialFromResult(auth, result);
9073 * const token = credential.accessToken;
9074 * }
9075 * // As this API can be used for sign-in, linking and reauthentication,
9076 * // check the operationType to determine what triggered this redirect
9077 * // operation.
9078 * const operationType = result.operationType;
9079 * ```
9080 *
9081 * @param auth - The {@link Auth} instance.
9082 * @param resolver - An instance of {@link PopupRedirectResolver}, optional
9083 * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.
9084 *
9085 * @public
9086 */
9087function getRedirectResult(auth, resolver) {
9088 return __awaiter(this, void 0, void 0, function () {
9089 return __generator(this, function (_a) {
9090 switch (_a.label) {
9091 case 0: return [4 /*yield*/, _castAuth(auth)._initializationPromise];
9092 case 1:
9093 _a.sent();
9094 return [2 /*return*/, _getRedirectResult(auth, resolver, false)];
9095 }
9096 });
9097 });
9098}
9099function _getRedirectResult(auth, resolverExtern, bypassAuthState) {
9100 if (bypassAuthState === void 0) { bypassAuthState = false; }
9101 return __awaiter(this, void 0, void 0, function () {
9102 var authInternal, resolver, action, result;
9103 return __generator(this, function (_a) {
9104 switch (_a.label) {
9105 case 0:
9106 authInternal = _castAuth(auth);
9107 resolver = _withDefaultResolver(authInternal, resolverExtern);
9108 action = new RedirectAction(authInternal, resolver, bypassAuthState);
9109 return [4 /*yield*/, action.execute()];
9110 case 1:
9111 result = _a.sent();
9112 if (!(result && !bypassAuthState)) return [3 /*break*/, 4];
9113 delete result.user._redirectEventId;
9114 return [4 /*yield*/, authInternal._persistUserIfCurrent(result.user)];
9115 case 2:
9116 _a.sent();
9117 return [4 /*yield*/, authInternal._setRedirectUser(null, resolverExtern)];
9118 case 3:
9119 _a.sent();
9120 _a.label = 4;
9121 case 4: return [2 /*return*/, result];
9122 }
9123 });
9124 });
9125}
9126function prepareUserForRedirect(user) {
9127 return __awaiter(this, void 0, void 0, function () {
9128 var eventId;
9129 return __generator(this, function (_a) {
9130 switch (_a.label) {
9131 case 0:
9132 eventId = _generateEventId(user.uid + ":::");
9133 user._redirectEventId = eventId;
9134 return [4 /*yield*/, user.auth._setRedirectUser(user)];
9135 case 1:
9136 _a.sent();
9137 return [4 /*yield*/, user.auth._persistUserIfCurrent(user)];
9138 case 2:
9139 _a.sent();
9140 return [2 /*return*/, eventId];
9141 }
9142 });
9143 });
9144}
9145
9146/**
9147 * @license
9148 * Copyright 2021 Google LLC
9149 *
9150 * Licensed under the Apache License, Version 2.0 (the "License");
9151 * you may not use this file except in compliance with the License.
9152 * You may obtain a copy of the License at
9153 *
9154 * http://www.apache.org/licenses/LICENSE-2.0
9155 *
9156 * Unless required by applicable law or agreed to in writing, software
9157 * distributed under the License is distributed on an "AS IS" BASIS,
9158 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9159 * See the License for the specific language governing permissions and
9160 * limitations under the License.
9161 */
9162/**
9163 * URL for Authentication widget which will initiate the OAuth handshake
9164 *
9165 * @internal
9166 */
9167var WIDGET_PATH = '__/auth/handler';
9168/**
9169 * URL for emulated environment
9170 *
9171 * @internal
9172 */
9173var EMULATOR_WIDGET_PATH = 'emulator/auth/handler';
9174function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {
9175 _assert(auth.config.authDomain, auth, "auth-domain-config-required" /* MISSING_AUTH_DOMAIN */);
9176 _assert(auth.config.apiKey, auth, "invalid-api-key" /* INVALID_API_KEY */);
9177 var params = {
9178 apiKey: auth.config.apiKey,
9179 appName: auth.name,
9180 authType: authType,
9181 redirectUrl: redirectUrl,
9182 v: SDK_VERSION,
9183 eventId: eventId
9184 };
9185 if (provider instanceof FederatedAuthProvider) {
9186 provider.setDefaultLanguage(auth.languageCode);
9187 params.providerId = provider.providerId || '';
9188 if (!isEmpty(provider.getCustomParameters())) {
9189 params.customParameters = JSON.stringify(provider.getCustomParameters());
9190 }
9191 // TODO set additionalParams from the provider as well?
9192 for (var _i = 0, _a = Object.entries(additionalParams || {}); _i < _a.length; _i++) {
9193 var _b = _a[_i], key = _b[0], value = _b[1];
9194 params[key] = value;
9195 }
9196 }
9197 if (provider instanceof BaseOAuthProvider) {
9198 var scopes = provider.getScopes().filter(function (scope) { return scope !== ''; });
9199 if (scopes.length > 0) {
9200 params.scopes = scopes.join(',');
9201 }
9202 }
9203 if (auth.tenantId) {
9204 params.tid = auth.tenantId;
9205 }
9206 // TODO: maybe set eid as endipointId
9207 // TODO: maybe set fw as Frameworks.join(",")
9208 var paramsDict = params;
9209 for (var _c = 0, _d = Object.keys(paramsDict); _c < _d.length; _c++) {
9210 var key = _d[_c];
9211 if (paramsDict[key] === undefined) {
9212 delete paramsDict[key];
9213 }
9214 }
9215 return getHandlerBase(auth) + "?" + querystring(paramsDict).slice(1);
9216}
9217function getHandlerBase(_a) {
9218 var config = _a.config;
9219 if (!config.emulator) {
9220 return "https://" + config.authDomain + "/" + WIDGET_PATH;
9221 }
9222 return _emulatorUrl(config, EMULATOR_WIDGET_PATH);
9223}
9224
9225/**
9226 * @license
9227 * Copyright 2021 Google LLC
9228 *
9229 * Licensed under the Apache License, Version 2.0 (the "License");
9230 * you may not use this file except in compliance with the License.
9231 * You may obtain a copy of the License at
9232 *
9233 * http://www.apache.org/licenses/LICENSE-2.0
9234 *
9235 * Unless required by applicable law or agreed to in writing, software
9236 * distributed under the License is distributed on an "AS IS" BASIS,
9237 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9238 * See the License for the specific language governing permissions and
9239 * limitations under the License.
9240 */
9241function _cordovaWindow() {
9242 return window;
9243}
9244
9245/**
9246 * @license
9247 * Copyright 2020 Google LLC
9248 *
9249 * Licensed under the Apache License, Version 2.0 (the "License");
9250 * you may not use this file except in compliance with the License.
9251 * You may obtain a copy of the License at
9252 *
9253 * http://www.apache.org/licenses/LICENSE-2.0
9254 *
9255 * Unless required by applicable law or agreed to in writing, software
9256 * distributed under the License is distributed on an "AS IS" BASIS,
9257 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9258 * See the License for the specific language governing permissions and
9259 * limitations under the License.
9260 */
9261function _getProjectConfig(auth, request) {
9262 if (request === void 0) { request = {}; }
9263 return __awaiter(this, void 0, void 0, function () {
9264 return __generator(this, function (_a) {
9265 return [2 /*return*/, _performApiRequest(auth, "GET" /* GET */, "/v1/projects" /* GET_PROJECT_CONFIG */, request)];
9266 });
9267 });
9268}
9269
9270/**
9271 * @license
9272 * Copyright 2020 Google LLC
9273 *
9274 * Licensed under the Apache License, Version 2.0 (the "License");
9275 * you may not use this file except in compliance with the License.
9276 * You may obtain a copy of the License at
9277 *
9278 * http://www.apache.org/licenses/LICENSE-2.0
9279 *
9280 * Unless required by applicable law or agreed to in writing, software
9281 * distributed under the License is distributed on an "AS IS" BASIS,
9282 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9283 * See the License for the specific language governing permissions and
9284 * limitations under the License.
9285 */
9286/**
9287 * How long to wait after the app comes back into focus before concluding that
9288 * the user closed the sign in tab.
9289 */
9290var REDIRECT_TIMEOUT_MS = 2000;
9291/**
9292 * Generates the URL for the OAuth handler.
9293 */
9294function _generateHandlerUrl(auth, event, provider) {
9295 var _a;
9296 return __awaiter(this, void 0, void 0, function () {
9297 var BuildInfo, sessionDigest, additionalParams;
9298 return __generator(this, function (_b) {
9299 switch (_b.label) {
9300 case 0:
9301 BuildInfo = _cordovaWindow().BuildInfo;
9302 debugAssert(event.sessionId, 'AuthEvent did not contain a session ID');
9303 return [4 /*yield*/, computeSha256(event.sessionId)];
9304 case 1:
9305 sessionDigest = _b.sent();
9306 additionalParams = {};
9307 if (_isIOS()) {
9308 // iOS app identifier
9309 additionalParams['ibi'] = BuildInfo.packageName;
9310 }
9311 else if (_isAndroid()) {
9312 // Android app identifier
9313 additionalParams['apn'] = BuildInfo.packageName;
9314 }
9315 else {
9316 _fail(auth, "operation-not-supported-in-this-environment" /* OPERATION_NOT_SUPPORTED */);
9317 }
9318 // Add the display name if available
9319 if (BuildInfo.displayName) {
9320 additionalParams['appDisplayName'] = BuildInfo.displayName;
9321 }
9322 // Attached the hashed session ID
9323 additionalParams['sessionId'] = sessionDigest;
9324 return [2 /*return*/, _getRedirectUrl(auth, provider, event.type, undefined, (_a = event.eventId) !== null && _a !== void 0 ? _a : undefined, additionalParams)];
9325 }
9326 });
9327 });
9328}
9329/**
9330 * Validates that this app is valid for this project configuration
9331 */
9332function _validateOrigin(auth) {
9333 return __awaiter(this, void 0, void 0, function () {
9334 var BuildInfo, request;
9335 return __generator(this, function (_a) {
9336 switch (_a.label) {
9337 case 0:
9338 BuildInfo = _cordovaWindow().BuildInfo;
9339 request = {};
9340 if (_isIOS()) {
9341 request.iosBundleId = BuildInfo.packageName;
9342 }
9343 else if (_isAndroid()) {
9344 request.androidPackageName = BuildInfo.packageName;
9345 }
9346 else {
9347 _fail(auth, "operation-not-supported-in-this-environment" /* OPERATION_NOT_SUPPORTED */);
9348 }
9349 // Will fail automatically if package name is not authorized
9350 return [4 /*yield*/, _getProjectConfig(auth, request)];
9351 case 1:
9352 // Will fail automatically if package name is not authorized
9353 _a.sent();
9354 return [2 /*return*/];
9355 }
9356 });
9357 });
9358}
9359function _performRedirect(handlerUrl) {
9360 // Get the cordova plugins
9361 var cordova = _cordovaWindow().cordova;
9362 return new Promise(function (resolve) {
9363 cordova.plugins.browsertab.isAvailable(function (browserTabIsAvailable) {
9364 var iabRef = null;
9365 if (browserTabIsAvailable) {
9366 cordova.plugins.browsertab.openUrl(handlerUrl);
9367 }
9368 else {
9369 // TODO: Return the inappbrowser ref that's returned from the open call
9370 iabRef = cordova.InAppBrowser.open(handlerUrl, _isIOS7Or8() ? '_blank' : '_system', 'location=yes');
9371 }
9372 resolve(iabRef);
9373 });
9374 });
9375}
9376/**
9377 * This function waits for app activity to be seen before resolving. It does
9378 * this by attaching listeners to various dom events. Once the app is determined
9379 * to be visible, this promise resolves. AFTER that resolution, the listeners
9380 * are detached and any browser tabs left open will be closed.
9381 */
9382function _waitForAppResume(auth, eventListener, iabRef) {
9383 return __awaiter(this, void 0, void 0, function () {
9384 var cordova, cleanup;
9385 return __generator(this, function (_a) {
9386 switch (_a.label) {
9387 case 0:
9388 cordova = _cordovaWindow().cordova;
9389 cleanup = function () { };
9390 _a.label = 1;
9391 case 1:
9392 _a.trys.push([1, , 3, 4]);
9393 return [4 /*yield*/, new Promise(function (resolve, reject) {
9394 var onCloseTimer = null;
9395 // DEFINE ALL THE CALLBACKS =====
9396 function authEventSeen() {
9397 var _a;
9398 // Auth event was detected. Resolve this promise and close the extra
9399 // window if it's still open.
9400 resolve();
9401 var closeBrowserTab = (_a = cordova.plugins.browsertab) === null || _a === void 0 ? void 0 : _a.close;
9402 if (typeof closeBrowserTab === 'function') {
9403 closeBrowserTab();
9404 }
9405 // Close inappbrowser emebedded webview in iOS7 and 8 case if still
9406 // open.
9407 if (typeof (iabRef === null || iabRef === void 0 ? void 0 : iabRef.close) === 'function') {
9408 iabRef.close();
9409 }
9410 }
9411 function resumed() {
9412 if (onCloseTimer) {
9413 // This code already ran; do not rerun.
9414 return;
9415 }
9416 onCloseTimer = window.setTimeout(function () {
9417 // Wait two seeconds after resume then reject.
9418 reject(_createError(auth, "redirect-cancelled-by-user" /* REDIRECT_CANCELLED_BY_USER */));
9419 }, REDIRECT_TIMEOUT_MS);
9420 }
9421 function visibilityChanged() {
9422 if ((document === null || document === void 0 ? void 0 : document.visibilityState) === 'visible') {
9423 resumed();
9424 }
9425 }
9426 // ATTACH ALL THE LISTENERS =====
9427 // Listen for the auth event
9428 eventListener.addPassiveListener(authEventSeen);
9429 // Listen for resume and visibility events
9430 document.addEventListener('resume', resumed, false);
9431 if (_isAndroid()) {
9432 document.addEventListener('visibilitychange', visibilityChanged, false);
9433 }
9434 // SETUP THE CLEANUP FUNCTION =====
9435 cleanup = function () {
9436 eventListener.removePassiveListener(authEventSeen);
9437 document.removeEventListener('resume', resumed, false);
9438 document.removeEventListener('visibilitychange', visibilityChanged, false);
9439 if (onCloseTimer) {
9440 window.clearTimeout(onCloseTimer);
9441 }
9442 };
9443 })];
9444 case 2:
9445 _a.sent();
9446 return [3 /*break*/, 4];
9447 case 3:
9448 cleanup();
9449 return [7 /*endfinally*/];
9450 case 4: return [2 /*return*/];
9451 }
9452 });
9453 });
9454}
9455/**
9456 * Checks the configuration of the Cordova environment. This has no side effect
9457 * if the configuration is correct; otherwise it throws an error with the
9458 * missing plugin.
9459 */
9460function _checkCordovaConfiguration(auth) {
9461 var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
9462 var win = _cordovaWindow();
9463 // Check all dependencies installed.
9464 // https://github.com/nordnet/cordova-universal-links-plugin
9465 // Note that cordova-universal-links-plugin has been abandoned.
9466 // A fork with latest fixes is available at:
9467 // https://www.npmjs.com/package/cordova-universal-links-plugin-fix
9468 _assert(typeof ((_a = win === null || win === void 0 ? void 0 : win.universalLinks) === null || _a === void 0 ? void 0 : _a.subscribe) === 'function', auth, "invalid-cordova-configuration" /* INVALID_CORDOVA_CONFIGURATION */, {
9469 missingPlugin: 'cordova-universal-links-plugin-fix'
9470 });
9471 // https://www.npmjs.com/package/cordova-plugin-buildinfo
9472 _assert(typeof ((_b = win === null || win === void 0 ? void 0 : win.BuildInfo) === null || _b === void 0 ? void 0 : _b.packageName) !== 'undefined', auth, "invalid-cordova-configuration" /* INVALID_CORDOVA_CONFIGURATION */, {
9473 missingPlugin: 'cordova-plugin-buildInfo'
9474 });
9475 // https://github.com/google/cordova-plugin-browsertab
9476 _assert(typeof ((_e = (_d = (_c = win === null || win === void 0 ? void 0 : win.cordova) === null || _c === void 0 ? void 0 : _c.plugins) === null || _d === void 0 ? void 0 : _d.browsertab) === null || _e === void 0 ? void 0 : _e.openUrl) === 'function', auth, "invalid-cordova-configuration" /* INVALID_CORDOVA_CONFIGURATION */, {
9477 missingPlugin: 'cordova-plugin-browsertab'
9478 });
9479 _assert(typeof ((_h = (_g = (_f = win === null || win === void 0 ? void 0 : win.cordova) === null || _f === void 0 ? void 0 : _f.plugins) === null || _g === void 0 ? void 0 : _g.browsertab) === null || _h === void 0 ? void 0 : _h.isAvailable) === 'function', auth, "invalid-cordova-configuration" /* INVALID_CORDOVA_CONFIGURATION */, {
9480 missingPlugin: 'cordova-plugin-browsertab'
9481 });
9482 // https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/
9483 _assert(typeof ((_k = (_j = win === null || win === void 0 ? void 0 : win.cordova) === null || _j === void 0 ? void 0 : _j.InAppBrowser) === null || _k === void 0 ? void 0 : _k.open) === 'function', auth, "invalid-cordova-configuration" /* INVALID_CORDOVA_CONFIGURATION */, {
9484 missingPlugin: 'cordova-plugin-inappbrowser'
9485 });
9486}
9487/**
9488 * Computes the SHA-256 of a session ID. The SubtleCrypto interface is only
9489 * available in "secure" contexts, which covers Cordova (which is served on a file
9490 * protocol).
9491 */
9492function computeSha256(sessionId) {
9493 return __awaiter(this, void 0, void 0, function () {
9494 var bytes, buf, arr;
9495 return __generator(this, function (_a) {
9496 switch (_a.label) {
9497 case 0:
9498 bytes = stringToArrayBuffer(sessionId);
9499 return [4 /*yield*/, crypto.subtle.digest('SHA-256', bytes)];
9500 case 1:
9501 buf = _a.sent();
9502 arr = Array.from(new Uint8Array(buf));
9503 return [2 /*return*/, arr.map(function (num) { return num.toString(16).padStart(2, '0'); }).join('')];
9504 }
9505 });
9506 });
9507}
9508function stringToArrayBuffer(str) {
9509 // This function is only meant to deal with an ASCII charset and makes
9510 // certain simplifying assumptions.
9511 debugAssert(/[0-9a-zA-Z]+/.test(str), 'Can only convert alpha-numeric strings');
9512 if (typeof TextEncoder !== 'undefined') {
9513 return new TextEncoder().encode(str);
9514 }
9515 var buff = new ArrayBuffer(str.length);
9516 var view = new Uint8Array(buff);
9517 for (var i = 0; i < str.length; i++) {
9518 view[i] = str.charCodeAt(i);
9519 }
9520 return view;
9521}
9522
9523/**
9524 * @license
9525 * Copyright 2020 Google LLC
9526 *
9527 * Licensed under the Apache License, Version 2.0 (the "License");
9528 * you may not use this file except in compliance with the License.
9529 * You may obtain a copy of the License at
9530 *
9531 * http://www.apache.org/licenses/LICENSE-2.0
9532 *
9533 * Unless required by applicable law or agreed to in writing, software
9534 * distributed under the License is distributed on an "AS IS" BASIS,
9535 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9536 * See the License for the specific language governing permissions and
9537 * limitations under the License.
9538 */
9539// The amount of time to store the UIDs of seen events; this is
9540// set to 10 min by default
9541var EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;
9542var AuthEventManager = /** @class */ (function () {
9543 function AuthEventManager(auth) {
9544 this.auth = auth;
9545 this.cachedEventUids = new Set();
9546 this.consumers = new Set();
9547 this.queuedRedirectEvent = null;
9548 this.hasHandledPotentialRedirect = false;
9549 this.lastProcessedEventTime = Date.now();
9550 }
9551 AuthEventManager.prototype.registerConsumer = function (authEventConsumer) {
9552 this.consumers.add(authEventConsumer);
9553 if (this.queuedRedirectEvent &&
9554 this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {
9555 this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);
9556 this.saveEventToCache(this.queuedRedirectEvent);
9557 this.queuedRedirectEvent = null;
9558 }
9559 };
9560 AuthEventManager.prototype.unregisterConsumer = function (authEventConsumer) {
9561 this.consumers.delete(authEventConsumer);
9562 };
9563 AuthEventManager.prototype.onEvent = function (event) {
9564 var _this = this;
9565 // Check if the event has already been handled
9566 if (this.hasEventBeenHandled(event)) {
9567 return false;
9568 }
9569 var handled = false;
9570 this.consumers.forEach(function (consumer) {
9571 if (_this.isEventForConsumer(event, consumer)) {
9572 handled = true;
9573 _this.sendToConsumer(event, consumer);
9574 _this.saveEventToCache(event);
9575 }
9576 });
9577 if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {
9578 // If we've already seen a redirect before, or this is a popup event,
9579 // bail now
9580 return handled;
9581 }
9582 this.hasHandledPotentialRedirect = true;
9583 // If the redirect wasn't handled, hang on to it
9584 if (!handled) {
9585 this.queuedRedirectEvent = event;
9586 handled = true;
9587 }
9588 return handled;
9589 };
9590 AuthEventManager.prototype.sendToConsumer = function (event, consumer) {
9591 var _a;
9592 if (event.error && !isNullRedirectEvent(event)) {
9593 var code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||
9594 "internal-error" /* INTERNAL_ERROR */;
9595 consumer.onError(_createError(this.auth, code));
9596 }
9597 else {
9598 consumer.onAuthEvent(event);
9599 }
9600 };
9601 AuthEventManager.prototype.isEventForConsumer = function (event, consumer) {
9602 var eventIdMatches = consumer.eventId === null ||
9603 (!!event.eventId && event.eventId === consumer.eventId);
9604 return consumer.filter.includes(event.type) && eventIdMatches;
9605 };
9606 AuthEventManager.prototype.hasEventBeenHandled = function (event) {
9607 if (Date.now() - this.lastProcessedEventTime >=
9608 EVENT_DUPLICATION_CACHE_DURATION_MS) {
9609 this.cachedEventUids.clear();
9610 }
9611 return this.cachedEventUids.has(eventUid(event));
9612 };
9613 AuthEventManager.prototype.saveEventToCache = function (event) {
9614 this.cachedEventUids.add(eventUid(event));
9615 this.lastProcessedEventTime = Date.now();
9616 };
9617 return AuthEventManager;
9618}());
9619function eventUid(e) {
9620 return [e.type, e.eventId, e.sessionId, e.tenantId].filter(function (v) { return v; }).join('-');
9621}
9622function isNullRedirectEvent(_a) {
9623 var type = _a.type, error = _a.error;
9624 return (type === "unknown" /* UNKNOWN */ &&
9625 (error === null || error === void 0 ? void 0 : error.code) === "auth/" + "no-auth-event" /* NO_AUTH_EVENT */);
9626}
9627function isRedirectEvent(event) {
9628 switch (event.type) {
9629 case "signInViaRedirect" /* SIGN_IN_VIA_REDIRECT */:
9630 case "linkViaRedirect" /* LINK_VIA_REDIRECT */:
9631 case "reauthViaRedirect" /* REAUTH_VIA_REDIRECT */:
9632 return true;
9633 case "unknown" /* UNKNOWN */:
9634 return isNullRedirectEvent(event);
9635 default:
9636 return false;
9637 }
9638}
9639
9640/**
9641 * @license
9642 * Copyright 2020 Google LLC
9643 *
9644 * Licensed under the Apache License, Version 2.0 (the "License");
9645 * you may not use this file except in compliance with the License.
9646 * You may obtain a copy of the License at
9647 *
9648 * http://www.apache.org/licenses/LICENSE-2.0
9649 *
9650 * Unless required by applicable law or agreed to in writing, software
9651 * distributed under the License is distributed on an "AS IS" BASIS,
9652 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9653 * See the License for the specific language governing permissions and
9654 * limitations under the License.
9655 */
9656var SESSION_ID_LENGTH = 20;
9657/** Custom AuthEventManager that adds passive listeners to events */
9658var CordovaAuthEventManager = /** @class */ (function (_super) {
9659 __extends(CordovaAuthEventManager, _super);
9660 function CordovaAuthEventManager() {
9661 var _this = _super !== null && _super.apply(this, arguments) || this;
9662 _this.passiveListeners = new Set();
9663 _this.initPromise = new Promise(function (resolve) {
9664 _this.resolveInialized = resolve;
9665 });
9666 return _this;
9667 }
9668 CordovaAuthEventManager.prototype.addPassiveListener = function (cb) {
9669 this.passiveListeners.add(cb);
9670 };
9671 CordovaAuthEventManager.prototype.removePassiveListener = function (cb) {
9672 this.passiveListeners.delete(cb);
9673 };
9674 // In a Cordova environment, this manager can live through multiple redirect
9675 // operations
9676 CordovaAuthEventManager.prototype.resetRedirect = function () {
9677 this.queuedRedirectEvent = null;
9678 this.hasHandledPotentialRedirect = false;
9679 };
9680 /** Override the onEvent method */
9681 CordovaAuthEventManager.prototype.onEvent = function (event) {
9682 this.resolveInialized();
9683 this.passiveListeners.forEach(function (cb) { return cb(event); });
9684 return _super.prototype.onEvent.call(this, event);
9685 };
9686 CordovaAuthEventManager.prototype.initialized = function () {
9687 return __awaiter(this, void 0, void 0, function () {
9688 return __generator(this, function (_a) {
9689 switch (_a.label) {
9690 case 0: return [4 /*yield*/, this.initPromise];
9691 case 1:
9692 _a.sent();
9693 return [2 /*return*/];
9694 }
9695 });
9696 });
9697 };
9698 return CordovaAuthEventManager;
9699}(AuthEventManager));
9700/**
9701 * Generates a (partial) {@link AuthEvent}.
9702 */
9703function _generateNewEvent(auth, type, eventId) {
9704 if (eventId === void 0) { eventId = null; }
9705 return {
9706 type: type,
9707 eventId: eventId,
9708 urlResponse: null,
9709 sessionId: generateSessionId(),
9710 postBody: null,
9711 tenantId: auth.tenantId,
9712 error: _createError(auth, "no-auth-event" /* NO_AUTH_EVENT */)
9713 };
9714}
9715function _savePartialEvent(auth, event) {
9716 return storage()._set(persistenceKey(auth), event);
9717}
9718function _getAndRemoveEvent(auth) {
9719 return __awaiter(this, void 0, void 0, function () {
9720 var event;
9721 return __generator(this, function (_a) {
9722 switch (_a.label) {
9723 case 0: return [4 /*yield*/, storage()._get(persistenceKey(auth))];
9724 case 1:
9725 event = (_a.sent());
9726 if (!event) return [3 /*break*/, 3];
9727 return [4 /*yield*/, storage()._remove(persistenceKey(auth))];
9728 case 2:
9729 _a.sent();
9730 _a.label = 3;
9731 case 3: return [2 /*return*/, event];
9732 }
9733 });
9734 });
9735}
9736function _eventFromPartialAndUrl(partialEvent, url) {
9737 var _a, _b;
9738 // Parse the deep link within the dynamic link URL.
9739 var callbackUrl = _getDeepLinkFromCallback(url);
9740 // Confirm it is actually a callback URL.
9741 // Currently the universal link will be of this format:
9742 // https://<AUTH_DOMAIN>/__/auth/callback<OAUTH_RESPONSE>
9743 // This is a fake URL but is not intended to take the user anywhere
9744 // and just redirect to the app.
9745 if (callbackUrl.includes('/__/auth/callback')) {
9746 // Check if there is an error in the URL.
9747 // This mechanism is also used to pass errors back to the app:
9748 // https://<AUTH_DOMAIN>/__/auth/callback?firebaseError=<STRINGIFIED_ERROR>
9749 var params = searchParamsOrEmpty(callbackUrl);
9750 // Get the error object corresponding to the stringified error if found.
9751 var errorObject = params['firebaseError']
9752 ? parseJsonOrNull(decodeURIComponent(params['firebaseError']))
9753 : null;
9754 var code = (_b = (_a = errorObject === null || errorObject === void 0 ? void 0 : errorObject['code']) === null || _a === void 0 ? void 0 : _a.split('auth/')) === null || _b === void 0 ? void 0 : _b[1];
9755 var error = code ? _createError(code) : null;
9756 if (error) {
9757 return {
9758 type: partialEvent.type,
9759 eventId: partialEvent.eventId,
9760 tenantId: partialEvent.tenantId,
9761 error: error,
9762 urlResponse: null,
9763 sessionId: null,
9764 postBody: null
9765 };
9766 }
9767 else {
9768 return {
9769 type: partialEvent.type,
9770 eventId: partialEvent.eventId,
9771 tenantId: partialEvent.tenantId,
9772 sessionId: partialEvent.sessionId,
9773 urlResponse: callbackUrl,
9774 postBody: null
9775 };
9776 }
9777 }
9778 return null;
9779}
9780function generateSessionId() {
9781 var chars = [];
9782 var allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
9783 for (var i = 0; i < SESSION_ID_LENGTH; i++) {
9784 var idx = Math.floor(Math.random() * allowedChars.length);
9785 chars.push(allowedChars.charAt(idx));
9786 }
9787 return chars.join('');
9788}
9789function storage() {
9790 return _getInstance(browserLocalPersistence);
9791}
9792function persistenceKey(auth) {
9793 return _persistenceKeyName("authEvent" /* AUTH_EVENT */, auth.config.apiKey, auth.name);
9794}
9795function parseJsonOrNull(json) {
9796 try {
9797 return JSON.parse(json);
9798 }
9799 catch (e) {
9800 return null;
9801 }
9802}
9803// Exported for testing
9804function _getDeepLinkFromCallback(url) {
9805 var params = searchParamsOrEmpty(url);
9806 var link = params['link'] ? decodeURIComponent(params['link']) : undefined;
9807 // Double link case (automatic redirect)
9808 var doubleDeepLink = searchParamsOrEmpty(link)['link'];
9809 // iOS custom scheme links.
9810 var iOSDeepLink = params['deep_link_id']
9811 ? decodeURIComponent(params['deep_link_id'])
9812 : undefined;
9813 var iOSDoubleDeepLink = searchParamsOrEmpty(iOSDeepLink)['link'];
9814 return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;
9815}
9816/**
9817 * Optimistically tries to get search params from a string, or else returns an
9818 * empty search params object.
9819 */
9820function searchParamsOrEmpty(url) {
9821 if (!(url === null || url === void 0 ? void 0 : url.includes('?'))) {
9822 return {};
9823 }
9824 var _a = url.split('?'); _a[0]; var rest = _a.slice(1);
9825 return querystringDecode(rest.join('?'));
9826}
9827
9828/**
9829 * @license
9830 * Copyright 2021 Google LLC
9831 *
9832 * Licensed under the Apache License, Version 2.0 (the "License");
9833 * you may not use this file except in compliance with the License.
9834 * You may obtain a copy of the License at
9835 *
9836 * http://www.apache.org/licenses/LICENSE-2.0
9837 *
9838 * Unless required by applicable law or agreed to in writing, software
9839 * distributed under the License is distributed on an "AS IS" BASIS,
9840 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9841 * See the License for the specific language governing permissions and
9842 * limitations under the License.
9843 */
9844/**
9845 * How long to wait for the initial auth event before concluding no
9846 * redirect pending
9847 */
9848var INITIAL_EVENT_TIMEOUT_MS = 500;
9849var CordovaPopupRedirectResolver = /** @class */ (function () {
9850 function CordovaPopupRedirectResolver() {
9851 this._redirectPersistence = browserSessionPersistence;
9852 this._shouldInitProactively = true; // This is lightweight for Cordova
9853 this.eventManagers = new Map();
9854 this.originValidationPromises = {};
9855 this._completeRedirectFn = _getRedirectResult;
9856 this._overrideRedirectResult = _overrideRedirectResult;
9857 }
9858 CordovaPopupRedirectResolver.prototype._initialize = function (auth) {
9859 return __awaiter(this, void 0, void 0, function () {
9860 var key, manager;
9861 return __generator(this, function (_a) {
9862 key = auth._key();
9863 manager = this.eventManagers.get(key);
9864 if (!manager) {
9865 manager = new CordovaAuthEventManager(auth);
9866 this.eventManagers.set(key, manager);
9867 this.attachCallbackListeners(auth, manager);
9868 }
9869 return [2 /*return*/, manager];
9870 });
9871 });
9872 };
9873 CordovaPopupRedirectResolver.prototype._openPopup = function (auth) {
9874 _fail(auth, "operation-not-supported-in-this-environment" /* OPERATION_NOT_SUPPORTED */);
9875 };
9876 CordovaPopupRedirectResolver.prototype._openRedirect = function (auth, provider, authType, eventId) {
9877 return __awaiter(this, void 0, void 0, function () {
9878 var manager, event, url, iabRef;
9879 return __generator(this, function (_a) {
9880 switch (_a.label) {
9881 case 0:
9882 _checkCordovaConfiguration(auth);
9883 return [4 /*yield*/, this._initialize(auth)];
9884 case 1:
9885 manager = _a.sent();
9886 return [4 /*yield*/, manager.initialized()];
9887 case 2:
9888 _a.sent();
9889 // Reset the persisted redirect states. This does not matter on Web where
9890 // the redirect always blows away application state entirely. On Cordova,
9891 // the app maintains control flow through the redirect.
9892 manager.resetRedirect();
9893 _clearRedirectOutcomes();
9894 return [4 /*yield*/, this._originValidation(auth)];
9895 case 3:
9896 _a.sent();
9897 event = _generateNewEvent(auth, authType, eventId);
9898 return [4 /*yield*/, _savePartialEvent(auth, event)];
9899 case 4:
9900 _a.sent();
9901 return [4 /*yield*/, _generateHandlerUrl(auth, event, provider)];
9902 case 5:
9903 url = _a.sent();
9904 return [4 /*yield*/, _performRedirect(url)];
9905 case 6:
9906 iabRef = _a.sent();
9907 return [2 /*return*/, _waitForAppResume(auth, manager, iabRef)];
9908 }
9909 });
9910 });
9911 };
9912 CordovaPopupRedirectResolver.prototype._isIframeWebStorageSupported = function (_auth, _cb) {
9913 throw new Error('Method not implemented.');
9914 };
9915 CordovaPopupRedirectResolver.prototype._originValidation = function (auth) {
9916 var key = auth._key();
9917 if (!this.originValidationPromises[key]) {
9918 this.originValidationPromises[key] = _validateOrigin(auth);
9919 }
9920 return this.originValidationPromises[key];
9921 };
9922 CordovaPopupRedirectResolver.prototype.attachCallbackListeners = function (auth, manager) {
9923 var _this = this;
9924 // Get the global plugins
9925 var _a = _cordovaWindow(), universalLinks = _a.universalLinks, handleOpenURL = _a.handleOpenURL, BuildInfo = _a.BuildInfo;
9926 var noEventTimeout = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
9927 return __generator(this, function (_a) {
9928 switch (_a.label) {
9929 case 0:
9930 // We didn't see that initial event. Clear any pending object and
9931 // dispatch no event
9932 return [4 /*yield*/, _getAndRemoveEvent(auth)];
9933 case 1:
9934 // We didn't see that initial event. Clear any pending object and
9935 // dispatch no event
9936 _a.sent();
9937 manager.onEvent(generateNoEvent());
9938 return [2 /*return*/];
9939 }
9940 });
9941 }); }, INITIAL_EVENT_TIMEOUT_MS);
9942 var universalLinksCb = function (eventData) { return __awaiter(_this, void 0, void 0, function () {
9943 var partialEvent, finalEvent;
9944 return __generator(this, function (_a) {
9945 switch (_a.label) {
9946 case 0:
9947 // We have an event so we can clear the no event timeout
9948 clearTimeout(noEventTimeout);
9949 return [4 /*yield*/, _getAndRemoveEvent(auth)];
9950 case 1:
9951 partialEvent = _a.sent();
9952 finalEvent = null;
9953 if (partialEvent && (eventData === null || eventData === void 0 ? void 0 : eventData['url'])) {
9954 finalEvent = _eventFromPartialAndUrl(partialEvent, eventData['url']);
9955 }
9956 // If finalEvent is never filled, trigger with no event
9957 manager.onEvent(finalEvent || generateNoEvent());
9958 return [2 /*return*/];
9959 }
9960 });
9961 }); };
9962 // Universal links subscriber doesn't exist for iOS, so we need to check
9963 if (typeof universalLinks !== 'undefined' &&
9964 typeof universalLinks.subscribe === 'function') {
9965 universalLinks.subscribe(null, universalLinksCb);
9966 }
9967 // iOS 7 or 8 custom URL schemes.
9968 // This is also the current default behavior for iOS 9+.
9969 // For this to work, cordova-plugin-customurlscheme needs to be installed.
9970 // https://github.com/EddyVerbruggen/Custom-URL-scheme
9971 // Do not overwrite the existing developer's URL handler.
9972 var existingHandleOpenURL = handleOpenURL;
9973 var packagePrefix = BuildInfo.packageName.toLowerCase() + "://";
9974 _cordovaWindow().handleOpenURL = function (url) { return __awaiter(_this, void 0, void 0, function () {
9975 return __generator(this, function (_a) {
9976 if (url.toLowerCase().startsWith(packagePrefix)) {
9977 // We want this intentionally to float
9978 // eslint-disable-next-line @typescript-eslint/no-floating-promises
9979 universalLinksCb({ url: url });
9980 }
9981 // Call the developer's handler if it is present.
9982 if (typeof existingHandleOpenURL === 'function') {
9983 try {
9984 existingHandleOpenURL(url);
9985 }
9986 catch (e) {
9987 // This is a developer error. Don't stop the flow of the SDK.
9988 console.error(e);
9989 }
9990 }
9991 return [2 /*return*/];
9992 });
9993 }); };
9994 };
9995 return CordovaPopupRedirectResolver;
9996}());
9997/**
9998 * An implementation of {@link PopupRedirectResolver} suitable for Cordova
9999 * based applications.
10000 *
10001 * @public
10002 */
10003var cordovaPopupRedirectResolver = CordovaPopupRedirectResolver;
10004function generateNoEvent() {
10005 return {
10006 type: "unknown" /* UNKNOWN */,
10007 eventId: null,
10008 sessionId: null,
10009 urlResponse: null,
10010 postBody: null,
10011 tenantId: null,
10012 error: _createError("no-auth-event" /* NO_AUTH_EVENT */)
10013 };
10014}
10015
10016export { signInWithEmailLink as $, ActionCodeOperation as A, FacebookAuthProvider as B, GithubAuthProvider as C, OAuthProvider as D, EmailAuthCredential as E, FactorId as F, GoogleAuthProvider as G, SAMLAuthProvider as H, signInAnonymously as I, signInWithCredential as J, linkWithCredential as K, reauthenticateWithCredential as L, signInWithCustomToken as M, sendPasswordResetEmail as N, OperationType as O, ProviderId as P, confirmPasswordReset as Q, applyActionCode as R, SignInMethod as S, TwitterAuthProvider as T, checkActionCode as U, verifyPasswordResetCode as V, createUserWithEmailAndPassword as W, signInWithEmailAndPassword as X, sendSignInLinkToEmail as Y, isSignInWithEmailLink as Z, _signInWithRedirect as _, _reauthenticateWithRedirect as a, fetchSignInMethodsForEmail as a0, sendEmailVerification as a1, verifyBeforeUpdateEmail as a2, ActionCodeURL as a3, parseActionCodeURL as a4, updateProfile as a5, updateEmail as a6, updatePassword as a7, getIdToken as a8, getIdTokenResult as a9, _getCurrentUrl as aA, _emulatorUrl as aB, _isChromeIOS as aC, _isFirefox as aD, _isIOSStandalone as aE, _isMobileBrowser as aF, _isSafari as aG, _isIOS as aH, _getRedirectResult as aI, _overrideRedirectResult as aJ, _getRedirectUrl as aK, _setWindowLocation as aL, AuthEventManager as aM, debugFail as aN, finalizeEnrollPhoneMfa as aO, _persistenceKeyName as aP, UserImpl as aQ, _getInstance as aR, AuthImpl as aS, _getClientVersion as aT, FetchProvider as aU, SAMLAuthCredential as aV, signInWithRedirect as aW, linkWithRedirect as aX, reauthenticateWithRedirect as aY, unlink as aa, getAdditionalUserInfo as ab, reload as ac, getMultiFactorResolver as ad, multiFactor as ae, _performApiRequest as af, _addTidIfNecessary as ag, _createError as ah, _assert as ai, Delay as aj, _window as ak, _isHttpOrHttps as al, _isWorker as am, _castAuth as an, sendPhoneVerificationCode as ao, startEnrollPhoneMfa as ap, _assertLinkedStatus as aq, _link$1 as ar, debugAssert as as, _generateEventId as at, AbstractPopupRedirectOperation as au, _assertInstanceOf as av, _withDefaultResolver as aw, FederatedAuthProvider as ax, _fail as ay, _getProjectConfig as az, _linkWithRedirect as b, indexedDBLocalPersistence as c, cordovaPopupRedirectResolver as d, browserLocalPersistence as e, browserSessionPersistence as f, getRedirectResult as g, beforeAuthStateChanged as h, initializeAuth as i, onAuthStateChanged as j, updateCurrentUser as k, signOut as l, deleteUser as m, debugErrorMap as n, onIdTokenChanged as o, prodErrorMap as p, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as q, registerAuth as r, setPersistence as s, connectAuthEmulator as t, useDeviceLanguage as u, AuthCredential as v, OAuthCredential as w, PhoneAuthCredential as x, inMemoryPersistence as y, EmailAuthProvider as z };
10017//# sourceMappingURL=popup_redirect-212c98e6.js.map