UNPKG

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