UNPKG

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