{ "version": 3, "sources": ["../../../../node_modules/use-dehydrated-state/dist/index.js", "../../app/root.tsx", "../../../../packages/remix-core/src/contexts/RootContext.ts", "../../../../node_modules/@firebase/auth/src/model/enum_maps.ts", "../../../../node_modules/@firebase/auth/src/core/errors.ts", "../../../../node_modules/@firebase/auth/src/core/util/log.ts", "../../../../node_modules/@firebase/auth/src/core/util/assert.ts", "../../../../node_modules/@firebase/auth/src/core/util/location.ts", "../../../../node_modules/@firebase/auth/src/core/util/navigator.ts", "../../../../node_modules/@firebase/auth/src/core/util/delay.ts", "../../../../node_modules/@firebase/auth/src/core/util/emulator.ts", "../../../../node_modules/@firebase/auth/src/core/util/fetch_provider.ts", "../../../../node_modules/@firebase/auth/src/api/errors.ts", "../../../../node_modules/@firebase/auth/src/api/index.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha.ts", "../../../../node_modules/@firebase/auth/src/api/authentication/recaptcha.ts", "../../../../node_modules/@firebase/auth/src/api/account_management/account.ts", "../../../../node_modules/@firebase/auth/src/core/util/time.ts", "../../../../node_modules/@firebase/auth/src/core/user/id_token_result.ts", "../../../../node_modules/@firebase/auth/src/core/user/invalidation.ts", "../../../../node_modules/@firebase/auth/src/core/user/proactive_refresh.ts", "../../../../node_modules/@firebase/auth/src/core/user/user_metadata.ts", "../../../../node_modules/@firebase/auth/src/core/user/reload.ts", "../../../../node_modules/@firebase/auth/src/api/authentication/token.ts", "../../../../node_modules/@firebase/auth/src/core/user/token_manager.ts", "../../../../node_modules/@firebase/auth/src/core/user/user_impl.ts", "../../../../node_modules/@firebase/auth/src/core/util/instantiator.ts", "../../../../node_modules/@firebase/auth/src/core/persistence/in_memory.ts", "../../../../node_modules/@firebase/auth/src/core/persistence/persistence_user_manager.ts", "../../../../node_modules/@firebase/auth/src/core/util/browser.ts", "../../../../node_modules/@firebase/auth/src/core/util/version.ts", "../../../../node_modules/@firebase/auth/src/core/auth/middleware.ts", "../../../../node_modules/@firebase/auth/src/api/password_policy/get_password_policy.ts", "../../../../node_modules/@firebase/auth/src/core/auth/password_policy_impl.ts", "../../../../node_modules/@firebase/auth/src/core/auth/auth_impl.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/load_js.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_enterprise_verifier.ts", "../../../../node_modules/@firebase/auth/src/core/auth/initialize.ts", "../../../../node_modules/@firebase/auth/src/core/auth/emulator.ts", "../../../../node_modules/@firebase/auth/src/core/credentials/auth_credential.ts", "../../../../node_modules/@firebase/auth/src/api/account_management/email_and_password.ts", "../../../../node_modules/@firebase/auth/src/api/authentication/email_and_password.ts", "../../../../node_modules/@firebase/auth/src/api/authentication/email_link.ts", "../../../../node_modules/@firebase/auth/src/core/credentials/email.ts", "../../../../node_modules/@firebase/auth/src/api/authentication/idp.ts", "../../../../node_modules/@firebase/auth/src/core/credentials/oauth.ts", "../../../../node_modules/@firebase/auth/src/api/authentication/sms.ts", "../../../../node_modules/@firebase/auth/src/core/credentials/phone.ts", "../../../../node_modules/@firebase/auth/src/core/action_code_url.ts", "../../../../node_modules/@firebase/auth/src/core/providers/email.ts", "../../../../node_modules/@firebase/auth/src/core/providers/federated.ts", "../../../../node_modules/@firebase/auth/src/core/providers/oauth.ts", "../../../../node_modules/@firebase/auth/src/core/providers/facebook.ts", "../../../../node_modules/@firebase/auth/src/core/providers/google.ts", "../../../../node_modules/@firebase/auth/src/core/providers/github.ts", "../../../../node_modules/@firebase/auth/src/core/credentials/saml.ts", "../../../../node_modules/@firebase/auth/src/core/providers/saml.ts", "../../../../node_modules/@firebase/auth/src/core/providers/twitter.ts", "../../../../node_modules/@firebase/auth/src/api/authentication/sign_up.ts", "../../../../node_modules/@firebase/auth/src/core/user/user_credential_impl.ts", "../../../../node_modules/@firebase/auth/src/core/strategies/anonymous.ts", "../../../../node_modules/@firebase/auth/src/mfa/mfa_error.ts", "../../../../node_modules/@firebase/auth/src/core/util/providers.ts", "../../../../node_modules/@firebase/auth/src/core/user/link_unlink.ts", "../../../../node_modules/@firebase/auth/src/core/user/reauthenticate.ts", "../../../../node_modules/@firebase/auth/src/core/strategies/credential.ts", "../../../../node_modules/@firebase/auth/src/api/authentication/custom_token.ts", "../../../../node_modules/@firebase/auth/src/core/strategies/custom_token.ts", "../../../../node_modules/@firebase/auth/src/mfa/mfa_info.ts", "../../../../node_modules/@firebase/auth/src/core/strategies/action_code_settings.ts", "../../../../node_modules/@firebase/auth/src/core/strategies/email_and_password.ts", "../../../../node_modules/@firebase/auth/src/core/strategies/email_link.ts", "../../../../node_modules/@firebase/auth/src/api/authentication/create_auth_uri.ts", "../../../../node_modules/@firebase/auth/src/core/strategies/email.ts", "../../../../node_modules/@firebase/auth/src/api/account_management/profile.ts", "../../../../node_modules/@firebase/auth/src/core/user/account_info.ts", "../../../../node_modules/@firebase/auth/src/core/user/additional_user_info.ts", "../../../../node_modules/@firebase/auth/src/core/index.ts", "../../../../node_modules/@firebase/auth/src/mfa/mfa_session.ts", "../../../../node_modules/@firebase/auth/src/mfa/mfa_resolver.ts", "../../../../node_modules/@firebase/auth/src/api/account_management/mfa.ts", "../../../../node_modules/@firebase/auth/src/mfa/mfa_user.ts", "../../../../node_modules/@firebase/auth/src/core/persistence/index.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/persistence/browser.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/persistence/local_storage.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/persistence/session_storage.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/messagechannel/promise.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/messagechannel/receiver.ts", "../../../../node_modules/@firebase/auth/src/core/util/event_id.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/messagechannel/sender.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/auth_window.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/util/worker.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/persistence/indexed_db.ts", "../../../../node_modules/@firebase/auth/src/api/authentication/mfa.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_mock.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_loader.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/recaptcha/recaptcha_verifier.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/strategies/phone.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/providers/phone.ts", "../../../../node_modules/@firebase/auth/src/core/util/resolver.ts", "../../../../node_modules/@firebase/auth/src/core/strategies/idp.ts", "../../../../node_modules/@firebase/auth/src/core/strategies/abstract_popup_redirect_operation.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/strategies/popup.ts", "../../../../node_modules/@firebase/auth/src/core/strategies/redirect.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/strategies/redirect.ts", "../../../../node_modules/@firebase/auth/src/core/auth/auth_event_manager.ts", "../../../../node_modules/@firebase/auth/src/api/project_config/get_project_config.ts", "../../../../node_modules/@firebase/auth/src/core/util/validate_origin.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/iframe/gapi.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/iframe/iframe.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/util/popup.ts", "../../../../node_modules/@firebase/auth/src/core/util/handler.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/popup_redirect.ts", "../../../../node_modules/@firebase/auth/src/mfa/mfa_assertion.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/mfa/assertions/phone.ts", "../../../../node_modules/@firebase/auth/src/mfa/assertions/totp.ts", "../../../../node_modules/@firebase/auth/src/core/auth/firebase_internal.ts", "../../../../node_modules/@firebase/auth/src/core/auth/register.ts", "../../../../node_modules/@firebase/auth/src/platform_browser/index.ts", "../../../../packages/remix-core/src/root.tsx", "../../../../packages/elemason-remix/src/ElemasonRemixProvider.tsx", "../../../../packages/elemason-remix/src/hooks/useParams.tsx", "../../../../packages/remix-core/node_modules/axios/lib/helpers/bind.js", "../../../../packages/remix-core/node_modules/axios/lib/utils.js", "../../../../packages/remix-core/node_modules/axios/lib/core/AxiosError.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/null.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/toFormData.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/AxiosURLSearchParams.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/buildURL.js", "../../../../packages/remix-core/node_modules/axios/lib/core/InterceptorManager.js", "../../../../packages/remix-core/node_modules/axios/lib/defaults/transitional.js", "../../../../packages/remix-core/node_modules/axios/lib/platform/browser/classes/URLSearchParams.js", "../../../../packages/remix-core/node_modules/axios/lib/platform/browser/classes/FormData.js", "../../../../packages/remix-core/node_modules/axios/lib/platform/browser/classes/Blob.js", "../../../../packages/remix-core/node_modules/axios/lib/platform/browser/index.js", "../../../../packages/remix-core/node_modules/axios/lib/platform/common/utils.js", "../../../../packages/remix-core/node_modules/axios/lib/platform/index.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/toURLEncodedForm.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/formDataToJSON.js", "../../../../packages/remix-core/node_modules/axios/lib/defaults/index.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/parseHeaders.js", "../../../../packages/remix-core/node_modules/axios/lib/core/AxiosHeaders.js", "../../../../packages/remix-core/node_modules/axios/lib/core/transformData.js", "../../../../packages/remix-core/node_modules/axios/lib/cancel/isCancel.js", "../../../../packages/remix-core/node_modules/axios/lib/cancel/CanceledError.js", "../../../../packages/remix-core/node_modules/axios/lib/core/settle.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/parseProtocol.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/speedometer.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/throttle.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/progressEventReducer.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/isURLSameOrigin.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/cookies.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/isAbsoluteURL.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/combineURLs.js", "../../../../packages/remix-core/node_modules/axios/lib/core/buildFullPath.js", "../../../../packages/remix-core/node_modules/axios/lib/core/mergeConfig.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/resolveConfig.js", "../../../../packages/remix-core/node_modules/axios/lib/adapters/xhr.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/composeSignals.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/trackStream.js", "../../../../packages/remix-core/node_modules/axios/lib/adapters/fetch.js", "../../../../packages/remix-core/node_modules/axios/lib/adapters/adapters.js", "../../../../packages/remix-core/node_modules/axios/lib/core/dispatchRequest.js", "../../../../packages/remix-core/node_modules/axios/lib/env/data.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/validator.js", "../../../../packages/remix-core/node_modules/axios/lib/core/Axios.js", "../../../../packages/remix-core/node_modules/axios/lib/cancel/CancelToken.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/spread.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/isAxiosError.js", "../../../../packages/remix-core/node_modules/axios/lib/helpers/HttpStatusCode.js", "../../../../packages/remix-core/node_modules/axios/lib/axios.js", "../../../../packages/remix-core/node_modules/axios/index.js", "../../../../packages/remix-core/src/components/Fingerprints/Fingerprints.tsx", "../../../../packages/remix-core/src/components/Fingerprints/index.ts", "../../../../packages/remix-core/src/components/OIB/OIB.tsx", "../../../../packages/remix-core/src/components/OIB/index.ts", "../../../../packages/remix-core/src/components/Transition/Transition.tsx", "../../../../packages/remix-core/src/components/Transition/index.ts", "../../../../packages/remix-core/src/hooks/useAppLaunchEffect.ts", "../../../../packages/remix-core/src/hooks/useAnalyticsEffect.ts", "../../../../packages/remix-core/node_modules/@sentry/src/is.ts", "../../../../packages/remix-core/node_modules/@sentry/src/version.ts", "../../../../packages/remix-core/node_modules/@sentry/src/worldwide.ts", "../../../../packages/remix-core/node_modules/@sentry/src/debug-build.ts", "../../../../packages/remix-core/node_modules/@sentry/src/logger.ts", "../../../../packages/remix-core/node_modules/@sentry/src/object.ts", "../../../../packages/remix-core/node_modules/@sentry/src/time.ts", "../../../../packages/remix-core/node_modules/@sentry/src/misc.ts", "../../../../packages/remix-core/node_modules/@sentry/src/propagationContext.ts", "../../../../packages/remix-core/node_modules/@sentry/src/carrier.ts", "../../../../packages/remix-core/node_modules/@sentry/src/session.ts", "../../../../packages/remix-core/node_modules/@sentry/src/utils/spanOnScope.ts", "../../../../packages/remix-core/node_modules/@sentry/src/scope.ts", "../../../../packages/remix-core/node_modules/@sentry/src/defaultScopes.ts", "../../../../packages/remix-core/node_modules/@sentry/src/asyncContext/stackStrategy.ts", "../../../../packages/remix-core/node_modules/@sentry/src/asyncContext/index.ts", "../../../../packages/remix-core/node_modules/@sentry/src/currentScopes.ts", "../../../../packages/remix-core/node_modules/@sentry/src/exports.ts", "../../../../node_modules/web-vitals/dist/web-vitals.js", "../../../../packages/remix-core/src/hooks/usePageDurationTracker.ts", "../../../../packages/remix-core/src/hooks/usePageViewTracker.ts", "../../../../packages/remix-core/src/hooks/useSessionDurationTracker.ts", "../../../../packages/remix-core/src/hooks/useFirebaseEffect.ts", "../../colors.ts", "../../routes.json"], "sourcesContent": ["\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nexports.__esModule = true;\nexports.useDehydratedState = void 0;\nvar react_1 = require(\"@remix-run/react\");\nvar deepmerge_1 = __importDefault(require(\"deepmerge\"));\nvar useDehydratedState = function () {\n var matches = (0, react_1.useMatches)();\n var dehydratedState = matches\n .map(function (match) { var _a; return (_a = match.data) === null || _a === void 0 ? void 0 : _a.dehydratedState; })\n .filter(Boolean);\n return dehydratedState.length\n ? dehydratedState.reduce(function (accumulator, currentValue) { return (0, deepmerge_1[\"default\"])(accumulator, currentValue); }, {})\n : undefined;\n};\nexports.useDehydratedState = useDehydratedState;\n", "import { cssBundleHref } from '@remix-run/css-bundle';\nimport { useRouteError } from '@remix-run/react';\nimport { captureRemixErrorBoundaryError } from '@sentry/remix';\nimport { Logger } from '@tectonic/logger';\nimport { RootApp, loaderGen } from '@tectonic/remix-core';\nimport { generateTWColors } from '@tectonic/utils';\nimport { memo } from 'react';\nimport { colors } from '../colors';\nimport mainSvg from '../public/main.svg';\nimport routes from '../routes.json';\nimport mainCss from './styles/main.css';\n\nimport type { LinksFunction } from '@remix-run/node';\nimport type { MetaFunction } from '@remix-run/react';\n\nconst description =\n'Buy cosmetics, skincare & personal care products online in Bangladesh. Explore all the big brands under one roof at OHSOGO and get amazing offers & deals';\n\nconst meta: MetaFunction = ({ data }) => {\n return [\n {\n title: 'OHSOGO | Buy Cosmetics & Beauty Products Online in Bangladesh'\n },\n { name: 'description', content: description },\n { property: 'og:description', content: description },\n { name: 'author', content: 'OHSOGO' },\n {\n name: 'google-site-verification',\n content: '5tly_WCQybC-yJM7r9V6YTWoSeqY4lkddsYNAl7gDNc'\n },\n {\n tagName: 'link',\n rel: 'canonical',\n href: 'https://ohsogo.com'\n },\n {\n 'script:ld+json': {\n '@context': 'http://schema.org',\n '@type': 'WebSite',\n name: 'OHSOGO',\n potentialAction: {\n '@type': 'SearchAction',\n target: 'https://ohsogo.com/search?q={search_term_string}',\n 'query-input': 'required name=search_term_string'\n },\n url: 'https://ohsogo.com'\n }\n },\n {\n 'script:ld+json': {\n '@context': 'https://schema.org',\n '@type': 'Organization',\n name: 'Ohsogo',\n url: 'https://ohsogo.com/',\n logo: 'https://dhz27qxctdo0r.cloudfront.net/images/scale/4x/181671b276696988966de2b17fa587e0.webp',\n contactPoint: {\n '@type': 'ContactPoint',\n telephone: '9612554411',\n contactType: 'customer service',\n areaServed: 'BD',\n availableLanguage: 'en'\n },\n address: {\n '@type': 'PostalAddress',\n streetAddress: 'Bond Center (Level 5), House # 71, Road # 11',\n addressLocality: 'Block # D, Banani',\n addressRegion: 'Dhaka-1213',\n postalCode: '',\n addressCountry: 'BD'\n },\n sameAs: [\n 'https://www.facebook.com/ohsogo',\n 'https://www.instagram.com/ohsogo_bd/',\n 'https://www.youtube.com/@ohsogo1122']\n\n }\n },\n {\n 'script:ld+json': {\n '@context': 'https://schema.org',\n '@type': 'BreadcrumbList',\n itemListElement: [\n {\n '@type': 'ListItem',\n position: 1,\n name: 'Home',\n item: 'https://ohsogo.com'\n }]\n\n }\n }];\n\n};\n\nconst Body = memo(() => {\n return (\n <>\n \n \n );\n\n});\n\nconst links: LinksFunction = () => [\n...(cssBundleHref ? [{ rel: 'stylesheet', href: cssBundleHref }] : [])];\n\n\nconst App = () =>\n} />;\n\n\n\nconst loader = loaderGen(mainCss);\n\nexport { links, loader };\n\nexport const ErrorBoundary = () => {\n const error = useRouteError();\n captureRemixErrorBoundaryError(error);\n Logger.error(error);\n return
Something went wrong
;\n};\n\nexport { meta };\n\nexport default App;", "import { createContext } from '@tectonic/utils';\n\nimport type { Maybe } from '@tectonic/types';\n\ninterface RootContextType {\n isMobile: boolean;\n currentUser: unknown; // TODO: fix type\n currentCookies: Maybe>\n env: Record;\n}\n\nconst errorMessage =\n 'useRootContext must be inside a RootProvider with a value';\n\nconst name = 'RootContext';\n\nconst [RootProvider, useRootContext, RootContext] =\n createContext({ errorMessage, name });\n\nexport { RootContext, RootProvider, useRootContext };\n", "/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * An enum of factors that may be used for multifactor authentication.\n *\n * @public\n */\nexport const FactorId = {\n /** Phone as second factor */\n PHONE: 'phone',\n TOTP: 'totp'\n} as const;\n\n/**\n * Enumeration of supported providers.\n *\n * @public\n */\nexport const ProviderId = {\n /** Facebook provider ID */\n FACEBOOK: 'facebook.com',\n /** GitHub provider ID */\n GITHUB: 'github.com',\n /** Google provider ID */\n GOOGLE: 'google.com',\n /** Password provider */\n PASSWORD: 'password',\n /** Phone provider */\n PHONE: 'phone',\n /** Twitter provider ID */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported sign-in methods.\n *\n * @public\n */\nexport const SignInMethod = {\n /** Email link sign in method */\n EMAIL_LINK: 'emailLink',\n /** Email/password sign in method */\n EMAIL_PASSWORD: 'password',\n /** Facebook sign in method */\n FACEBOOK: 'facebook.com',\n /** GitHub sign in method */\n GITHUB: 'github.com',\n /** Google sign in method */\n GOOGLE: 'google.com',\n /** Phone sign in method */\n PHONE: 'phone',\n /** Twitter sign in method */\n TWITTER: 'twitter.com'\n} as const;\n\n/**\n * Enumeration of supported operation types.\n *\n * @public\n */\nexport const OperationType = {\n /** Operation involving linking an additional provider to an already signed-in user. */\n LINK: 'link',\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\n REAUTHENTICATE: 'reauthenticate',\n /** Operation involving signing in a user. */\n SIGN_IN: 'signIn'\n} as const;\n\n/**\n * An enumeration of the possible email action types.\n *\n * @public\n */\nexport const ActionCodeOperation = {\n /** The email link sign-in action. */\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\n /** The password reset action. */\n PASSWORD_RESET: 'PASSWORD_RESET',\n /** The email revocation action. */\n RECOVER_EMAIL: 'RECOVER_EMAIL',\n /** The revert second factor addition email action. */\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\n /** The revert second factor addition email action. */\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\n /** The email verification action. */\n VERIFY_EMAIL: 'VERIFY_EMAIL'\n} as const;\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorMap, User } from '../model/public_types';\nimport { ErrorFactory, ErrorMap } from '@firebase/util';\n\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { AppName } from '../model/auth';\nimport { AuthCredential } from './credentials';\n\n/**\n * Enumeration of Firebase Auth error codes.\n *\n * @internal\n */\nexport const enum AuthErrorCode {\n ADMIN_ONLY_OPERATION = 'admin-restricted-operation',\n ARGUMENT_ERROR = 'argument-error',\n APP_NOT_AUTHORIZED = 'app-not-authorized',\n APP_NOT_INSTALLED = 'app-not-installed',\n CAPTCHA_CHECK_FAILED = 'captcha-check-failed',\n CODE_EXPIRED = 'code-expired',\n CORDOVA_NOT_READY = 'cordova-not-ready',\n CORS_UNSUPPORTED = 'cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE = 'credential-already-in-use',\n CREDENTIAL_MISMATCH = 'custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH = 'dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED = 'dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'email-change-needs-verification',\n EMAIL_EXISTS = 'email-already-in-use',\n EMULATOR_CONFIG_FAILED = 'emulator-config-failed',\n EXPIRED_OOB_CODE = 'expired-action-code',\n EXPIRED_POPUP_REQUEST = 'cancelled-popup-request',\n INTERNAL_ERROR = 'internal-error',\n INVALID_API_KEY = 'invalid-api-key',\n INVALID_APP_CREDENTIAL = 'invalid-app-credential',\n INVALID_APP_ID = 'invalid-app-id',\n INVALID_AUTH = 'invalid-user-token',\n INVALID_AUTH_EVENT = 'invalid-auth-event',\n INVALID_CERT_HASH = 'invalid-cert-hash',\n INVALID_CODE = 'invalid-verification-code',\n INVALID_CONTINUE_URI = 'invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION = 'invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN = 'invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN = 'invalid-dynamic-link-domain',\n INVALID_EMAIL = 'invalid-email',\n INVALID_EMULATOR_SCHEME = 'invalid-emulator-scheme',\n INVALID_CREDENTIAL = 'invalid-credential',\n INVALID_MESSAGE_PAYLOAD = 'invalid-message-payload',\n INVALID_MFA_SESSION = 'invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID = 'invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER = 'invalid-oauth-provider',\n INVALID_OOB_CODE = 'invalid-action-code',\n INVALID_ORIGIN = 'unauthorized-domain',\n INVALID_PASSWORD = 'wrong-password',\n INVALID_PERSISTENCE = 'invalid-persistence-type',\n INVALID_PHONE_NUMBER = 'invalid-phone-number',\n INVALID_PROVIDER_ID = 'invalid-provider-id',\n INVALID_RECIPIENT_EMAIL = 'invalid-recipient-email',\n INVALID_SENDER = 'invalid-sender',\n INVALID_SESSION_INFO = 'invalid-verification-id',\n INVALID_TENANT_ID = 'invalid-tenant-id',\n LOGIN_BLOCKED = 'login-blocked',\n MFA_INFO_NOT_FOUND = 'multi-factor-info-not-found',\n MFA_REQUIRED = 'multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME = 'missing-android-pkg-name',\n MISSING_APP_CREDENTIAL = 'missing-app-credential',\n MISSING_AUTH_DOMAIN = 'auth-domain-config-required',\n MISSING_CODE = 'missing-verification-code',\n MISSING_CONTINUE_URI = 'missing-continue-uri',\n MISSING_IFRAME_START = 'missing-iframe-start',\n MISSING_IOS_BUNDLE_ID = 'missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE = 'missing-or-invalid-nonce',\n MISSING_MFA_INFO = 'missing-multi-factor-info',\n MISSING_MFA_SESSION = 'missing-multi-factor-session',\n MISSING_PHONE_NUMBER = 'missing-phone-number',\n MISSING_PASSWORD = 'missing-password',\n MISSING_SESSION_INFO = 'missing-verification-id',\n MODULE_DESTROYED = 'app-deleted',\n NEED_CONFIRMATION = 'account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED = 'network-request-failed',\n NULL_USER = 'null-user',\n NO_AUTH_EVENT = 'no-auth-event',\n NO_SUCH_PROVIDER = 'no-such-provider',\n OPERATION_NOT_ALLOWED = 'operation-not-allowed',\n OPERATION_NOT_SUPPORTED = 'operation-not-supported-in-this-environment',\n POPUP_BLOCKED = 'popup-blocked',\n POPUP_CLOSED_BY_USER = 'popup-closed-by-user',\n PROVIDER_ALREADY_LINKED = 'provider-already-linked',\n QUOTA_EXCEEDED = 'quota-exceeded',\n REDIRECT_CANCELLED_BY_USER = 'redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING = 'redirect-operation-pending',\n REJECTED_CREDENTIAL = 'rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED = 'second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH = 'tenant-id-mismatch',\n TIMEOUT = 'timeout',\n TOKEN_EXPIRED = 'user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'too-many-requests',\n UNAUTHORIZED_DOMAIN = 'unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR = 'unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE = 'unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION = 'unsupported-tenant-operation',\n UNVERIFIED_EMAIL = 'unverified-email',\n USER_CANCELLED = 'user-cancelled',\n USER_DELETED = 'user-not-found',\n USER_DISABLED = 'user-disabled',\n USER_MISMATCH = 'user-mismatch',\n USER_SIGNED_OUT = 'user-signed-out',\n WEAK_PASSWORD = 'weak-password',\n WEB_STORAGE_UNSUPPORTED = 'web-storage-unsupported',\n ALREADY_INITIALIZED = 'already-initialized',\n RECAPTCHA_NOT_ENABLED = 'recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN = 'missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN = 'invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION = 'invalid-recaptcha-action',\n MISSING_CLIENT_TYPE = 'missing-client-type',\n MISSING_RECAPTCHA_VERSION = 'missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION = 'invalid-recaptcha-version',\n INVALID_REQ_TYPE = 'invalid-req-type',\n UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION = 'unsupported-password-policy-schema-version',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'password-does-not-meet-requirements'\n}\n\nfunction _debugErrorMap(): ErrorMap {\n return {\n [AuthErrorCode.ADMIN_ONLY_OPERATION]:\n 'This operation is restricted to administrators only.',\n [AuthErrorCode.ARGUMENT_ERROR]: '',\n [AuthErrorCode.APP_NOT_AUTHORIZED]:\n \"This app, identified by the domain where it's hosted, is not \" +\n 'authorized to use Firebase Authentication with the provided API key. ' +\n 'Review your key configuration in the Google API console.',\n [AuthErrorCode.APP_NOT_INSTALLED]:\n 'The requested mobile application corresponding to the identifier (' +\n 'Android package name or iOS bundle ID) provided is not installed on ' +\n 'this device.',\n [AuthErrorCode.CAPTCHA_CHECK_FAILED]:\n 'The reCAPTCHA response token provided is either invalid, expired, ' +\n 'already used or the domain associated with it does not match the list ' +\n 'of whitelisted domains.',\n [AuthErrorCode.CODE_EXPIRED]:\n 'The SMS code has expired. Please re-send the verification code to try ' +\n 'again.',\n [AuthErrorCode.CORDOVA_NOT_READY]: 'Cordova framework is not ready.',\n [AuthErrorCode.CORS_UNSUPPORTED]: 'This browser is not supported.',\n [AuthErrorCode.CREDENTIAL_ALREADY_IN_USE]:\n 'This credential is already associated with a different user account.',\n [AuthErrorCode.CREDENTIAL_MISMATCH]:\n 'The custom token corresponds to a different audience.',\n [AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n 'This operation is sensitive and requires recent authentication. Log in ' +\n 'again before retrying this request.',\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.',\n [AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED]:\n 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\n 'conditions.',\n [AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION]:\n 'Multi-factor users must always have a verified email.',\n [AuthErrorCode.EMAIL_EXISTS]:\n 'The email address is already in use by another account.',\n [AuthErrorCode.EMULATOR_CONFIG_FAILED]:\n 'Auth instance has already been used to make a network call. Auth can ' +\n 'no longer be configured to use the emulator. Try calling ' +\n '\"connectAuthEmulator()\" sooner.',\n [AuthErrorCode.EXPIRED_OOB_CODE]: 'The action code has expired.',\n [AuthErrorCode.EXPIRED_POPUP_REQUEST]:\n 'This operation has been cancelled due to another conflicting popup being opened.',\n [AuthErrorCode.INTERNAL_ERROR]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_APP_CREDENTIAL]:\n 'The phone verification request contains an invalid application verifier.' +\n ' The reCAPTCHA token response is either invalid or expired.',\n [AuthErrorCode.INVALID_APP_ID]:\n 'The mobile app identifier is not registed for the current project.',\n [AuthErrorCode.INVALID_AUTH]:\n \"This user's credential isn't valid for this project. This can happen \" +\n \"if the user's token has been tampered with, or if the user isn't for \" +\n 'the project associated with this API key.',\n [AuthErrorCode.INVALID_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.INVALID_CODE]:\n 'The SMS verification code used to create the phone auth credential is ' +\n 'invalid. Please resend the verification code sms and be sure to use the ' +\n 'verification code provided by the user.',\n [AuthErrorCode.INVALID_CONTINUE_URI]:\n 'The continue URL provided in the request is invalid.',\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]:\n 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\n 'cordova-plugin-customurlscheme.',\n [AuthErrorCode.INVALID_CUSTOM_TOKEN]:\n 'The custom token format is incorrect. Please check the documentation.',\n [AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN]:\n 'The provided dynamic link domain is not configured or authorized for the current project.',\n [AuthErrorCode.INVALID_EMAIL]: 'The email address is badly formatted.',\n [AuthErrorCode.INVALID_EMULATOR_SCHEME]:\n 'Emulator URL must start with a valid scheme (http:// or https://).',\n [AuthErrorCode.INVALID_API_KEY]:\n 'Your API key is invalid, please check you have copied it correctly.',\n [AuthErrorCode.INVALID_CERT_HASH]:\n 'The SHA-1 certificate hash provided is invalid.',\n [AuthErrorCode.INVALID_CREDENTIAL]:\n 'The supplied auth credential is incorrect, malformed or has expired.',\n [AuthErrorCode.INVALID_MESSAGE_PAYLOAD]:\n 'The email template corresponding to this action contains invalid characters in its message. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_MFA_SESSION]:\n 'The request does not contain a valid proof of first factor successful sign-in.',\n [AuthErrorCode.INVALID_OAUTH_PROVIDER]:\n 'EmailAuthProvider is not supported for this operation. This operation ' +\n 'only supports OAuth providers.',\n [AuthErrorCode.INVALID_OAUTH_CLIENT_ID]:\n 'The OAuth client ID provided is either invalid or does not match the ' +\n 'specified API key.',\n [AuthErrorCode.INVALID_ORIGIN]:\n 'This domain is not authorized for OAuth operations for your Firebase ' +\n 'project. Edit the list of authorized domains from the Firebase console.',\n [AuthErrorCode.INVALID_OOB_CODE]:\n 'The action code is invalid. This can happen if the code is malformed, ' +\n 'expired, or has already been used.',\n [AuthErrorCode.INVALID_PASSWORD]:\n 'The password is invalid or the user does not have a password.',\n [AuthErrorCode.INVALID_PERSISTENCE]:\n 'The specified persistence type is invalid. It can only be local, session or none.',\n [AuthErrorCode.INVALID_PHONE_NUMBER]:\n 'The format of the phone number provided is incorrect. Please enter the ' +\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\n 'phone numbers are written in the format [+][country code][subscriber ' +\n 'number including area code].',\n [AuthErrorCode.INVALID_PROVIDER_ID]:\n 'The specified provider ID is invalid.',\n [AuthErrorCode.INVALID_RECIPIENT_EMAIL]:\n 'The email corresponding to this action failed to send as the provided ' +\n 'recipient email address is invalid.',\n [AuthErrorCode.INVALID_SENDER]:\n 'The email template corresponding to this action contains an invalid sender email or name. ' +\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\n [AuthErrorCode.INVALID_SESSION_INFO]:\n 'The verification ID used to create the phone auth credential is invalid.',\n [AuthErrorCode.INVALID_TENANT_ID]:\n \"The Auth instance's tenant ID is invalid.\",\n [AuthErrorCode.LOGIN_BLOCKED]:\n 'Login blocked by user-provided method: {$originalMessage}',\n [AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME]:\n 'An Android Package Name must be provided if the Android App is required to be installed.',\n [AuthErrorCode.MISSING_AUTH_DOMAIN]:\n 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\n 'by following the instructions in the Firebase console.',\n [AuthErrorCode.MISSING_APP_CREDENTIAL]:\n 'The phone verification request is missing an application verifier ' +\n 'assertion. A reCAPTCHA response token needs to be provided.',\n [AuthErrorCode.MISSING_CODE]:\n 'The phone auth credential was created with an empty SMS verification code.',\n [AuthErrorCode.MISSING_CONTINUE_URI]:\n 'A continue URL must be provided in the request.',\n [AuthErrorCode.MISSING_IFRAME_START]: 'An internal AuthError has occurred.',\n [AuthErrorCode.MISSING_IOS_BUNDLE_ID]:\n 'An iOS Bundle ID must be provided if an App Store ID is provided.',\n [AuthErrorCode.MISSING_OR_INVALID_NONCE]:\n 'The request does not contain a valid nonce. This can occur if the ' +\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\n 'in the ID token payload.',\n [AuthErrorCode.MISSING_PASSWORD]: 'A non-empty password must be provided',\n [AuthErrorCode.MISSING_MFA_INFO]:\n 'No second factor identifier is provided.',\n [AuthErrorCode.MISSING_MFA_SESSION]:\n 'The request is missing proof of first factor successful sign-in.',\n [AuthErrorCode.MISSING_PHONE_NUMBER]:\n 'To send verification codes, provide a phone number for the recipient.',\n [AuthErrorCode.MISSING_SESSION_INFO]:\n 'The phone auth credential was created with an empty verification ID.',\n [AuthErrorCode.MODULE_DESTROYED]:\n 'This instance of FirebaseApp has been deleted.',\n [AuthErrorCode.MFA_INFO_NOT_FOUND]:\n 'The user does not have a second factor matching the identifier provided.',\n [AuthErrorCode.MFA_REQUIRED]:\n 'Proof of ownership of a second factor is required to complete sign-in.',\n [AuthErrorCode.NEED_CONFIRMATION]:\n 'An account already exists with the same email address but different ' +\n 'sign-in credentials. Sign in using a provider associated with this ' +\n 'email address.',\n [AuthErrorCode.NETWORK_REQUEST_FAILED]:\n 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\n [AuthErrorCode.NO_AUTH_EVENT]: 'An internal AuthError has occurred.',\n [AuthErrorCode.NO_SUCH_PROVIDER]:\n 'User was not linked to an account with the given provider.',\n [AuthErrorCode.NULL_USER]:\n 'A null user object was provided as the argument for an operation which ' +\n 'requires a non-null user object.',\n [AuthErrorCode.OPERATION_NOT_ALLOWED]:\n 'The given sign-in provider is disabled for this Firebase project. ' +\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\n 'Auth section.',\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]:\n 'This operation is not supported in the environment this application is ' +\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\n ' and web storage must be enabled.',\n [AuthErrorCode.POPUP_BLOCKED]:\n 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\n [AuthErrorCode.POPUP_CLOSED_BY_USER]:\n 'The popup has been closed by the user before finalizing the operation.',\n [AuthErrorCode.PROVIDER_ALREADY_LINKED]:\n 'User can only be linked to one identity for the given provider.',\n [AuthErrorCode.QUOTA_EXCEEDED]:\n \"The project's quota for this operation has been exceeded.\",\n [AuthErrorCode.REDIRECT_CANCELLED_BY_USER]:\n 'The redirect operation has been cancelled by the user before finalizing.',\n [AuthErrorCode.REDIRECT_OPERATION_PENDING]:\n 'A redirect sign-in operation is already pending.',\n [AuthErrorCode.REJECTED_CREDENTIAL]:\n 'The request contains malformed or mismatching credentials.',\n [AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED]:\n 'The second factor is already enrolled on this account.',\n [AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED]:\n 'The maximum allowed number of second factors on a user has been exceeded.',\n [AuthErrorCode.TENANT_ID_MISMATCH]:\n \"The provided tenant ID does not match the Auth instance's tenant ID\",\n [AuthErrorCode.TIMEOUT]: 'The operation has timed out.',\n [AuthErrorCode.TOKEN_EXPIRED]:\n \"The user's credential is no longer valid. The user must sign in again.\",\n [AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER]:\n 'We have blocked all requests from this device due to unusual activity. ' +\n 'Try again later.',\n [AuthErrorCode.UNAUTHORIZED_DOMAIN]:\n 'The domain of the continue URL is not whitelisted. Please whitelist ' +\n 'the domain in the Firebase console.',\n [AuthErrorCode.UNSUPPORTED_FIRST_FACTOR]:\n 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\n [AuthErrorCode.UNSUPPORTED_PERSISTENCE]:\n 'The current environment does not support the specified persistence type.',\n [AuthErrorCode.UNSUPPORTED_TENANT_OPERATION]:\n 'This operation is not supported in a multi-tenant context.',\n [AuthErrorCode.UNVERIFIED_EMAIL]:\n 'The operation requires a verified email.',\n [AuthErrorCode.USER_CANCELLED]:\n 'The user did not grant your application the permissions it requested.',\n [AuthErrorCode.USER_DELETED]:\n 'There is no user record corresponding to this identifier. The user may ' +\n 'have been deleted.',\n [AuthErrorCode.USER_DISABLED]:\n 'The user account has been disabled by an administrator.',\n [AuthErrorCode.USER_MISMATCH]:\n 'The supplied credentials do not correspond to the previously signed in user.',\n [AuthErrorCode.USER_SIGNED_OUT]: '',\n [AuthErrorCode.WEAK_PASSWORD]:\n 'The password must be 6 characters long or more.',\n [AuthErrorCode.WEB_STORAGE_UNSUPPORTED]:\n 'This browser is not supported or 3rd party cookies and data may be disabled.',\n [AuthErrorCode.ALREADY_INITIALIZED]:\n 'initializeAuth() has already been called with ' +\n 'different options. To avoid this error, call initializeAuth() with the ' +\n 'same options as when it was originally called, or call getAuth() to return the' +\n ' already initialized instance.',\n [AuthErrorCode.MISSING_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_TOKEN]:\n 'The reCAPTCHA token is invalid when sending request to the backend.',\n [AuthErrorCode.INVALID_RECAPTCHA_ACTION]:\n 'The reCAPTCHA action is invalid when sending request to the backend.',\n [AuthErrorCode.RECAPTCHA_NOT_ENABLED]:\n 'reCAPTCHA Enterprise integration is not enabled for this project.',\n [AuthErrorCode.MISSING_CLIENT_TYPE]:\n 'The reCAPTCHA client type is missing when sending request to the backend.',\n [AuthErrorCode.MISSING_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is missing when sending request to the backend.',\n [AuthErrorCode.INVALID_REQ_TYPE]: 'Invalid request parameters.',\n [AuthErrorCode.INVALID_RECAPTCHA_VERSION]:\n 'The reCAPTCHA version is invalid when sending request to the backend.',\n [AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION]:\n 'The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.',\n [AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n 'The password does not meet the requirements.'\n };\n}\n\nexport interface ErrorMapRetriever extends AuthErrorMap {\n (): ErrorMap;\n}\n\nfunction _prodErrorMap(): ErrorMap {\n // We will include this one message in the prod error map since by the very\n // nature of this error, developers will never be able to see the message\n // using the debugErrorMap (which is installed during auth initialization).\n return {\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]:\n 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\n 'starting any other Firebase SDK.'\n } as ErrorMap;\n}\n\n/**\n * A verbose error map with detailed descriptions for most error codes.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const debugErrorMap: AuthErrorMap = _debugErrorMap;\n\n/**\n * A minimal error map with all verbose error messages stripped.\n *\n * See discussion at {@link AuthErrorMap}\n *\n * @public\n */\nexport const prodErrorMap: AuthErrorMap = _prodErrorMap;\n\nexport interface NamedErrorParams {\n appName: AppName;\n credential?: AuthCredential;\n email?: string;\n phoneNumber?: string;\n tenantId?: string;\n user?: User;\n _serverResponse?: object;\n}\n\n/**\n * @internal\n */\ntype GenericAuthErrorParams = {\n [key in Exclude<\n AuthErrorCode,\n | AuthErrorCode.ARGUMENT_ERROR\n | AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n | AuthErrorCode.INTERNAL_ERROR\n | AuthErrorCode.MFA_REQUIRED\n | AuthErrorCode.NO_AUTH_EVENT\n | AuthErrorCode.OPERATION_NOT_SUPPORTED\n >]: {\n appName?: AppName;\n email?: string;\n phoneNumber?: string;\n message?: string;\n };\n};\n\n/**\n * @internal\n */\nexport interface AuthErrorParams extends GenericAuthErrorParams {\n [AuthErrorCode.ARGUMENT_ERROR]: { appName?: AppName };\n [AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH]: { appName?: AppName };\n [AuthErrorCode.INTERNAL_ERROR]: { appName?: AppName };\n [AuthErrorCode.LOGIN_BLOCKED]: {\n appName?: AppName;\n originalMessage?: string;\n };\n [AuthErrorCode.OPERATION_NOT_SUPPORTED]: { appName?: AppName };\n [AuthErrorCode.NO_AUTH_EVENT]: { appName?: AppName };\n [AuthErrorCode.MFA_REQUIRED]: {\n appName: AppName;\n _serverResponse: IdTokenMfaResponse;\n };\n [AuthErrorCode.INVALID_CORDOVA_CONFIGURATION]: {\n appName: AppName;\n missingPlugin?: string;\n };\n}\n\nexport const _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory<\n AuthErrorCode,\n AuthErrorParams\n>('auth', 'Firebase', _prodErrorMap());\n\n/**\n * A map of potential `Auth` error codes, for easier comparison with errors\n * thrown by the SDK.\n *\n * @remarks\n * Note that you can't tree-shake individual keys\n * in the map, so by using the map you might substantially increase your\n * bundle size.\n *\n * @public\n */\nexport const AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\n ARGUMENT_ERROR: 'auth/argument-error',\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\n APP_NOT_INSTALLED: 'auth/app-not-installed',\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\n CODE_EXPIRED: 'auth/code-expired',\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\n EMAIL_EXISTS: 'auth/email-already-in-use',\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\n INTERNAL_ERROR: 'auth/internal-error',\n INVALID_API_KEY: 'auth/invalid-api-key',\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\n INVALID_APP_ID: 'auth/invalid-app-id',\n INVALID_AUTH: 'auth/invalid-user-token',\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\n INVALID_CODE: 'auth/invalid-verification-code',\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\n INVALID_EMAIL: 'auth/invalid-email',\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\n INVALID_LOGIN_CREDENTIALS: 'auth/invalid-credential',\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\n INVALID_OOB_CODE: 'auth/invalid-action-code',\n INVALID_ORIGIN: 'auth/unauthorized-domain',\n INVALID_PASSWORD: 'auth/wrong-password',\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\n INVALID_SENDER: 'auth/invalid-sender',\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\n MISSING_CODE: 'auth/missing-verification-code',\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\n MODULE_DESTROYED: 'auth/app-deleted',\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\n NULL_USER: 'auth/null-user',\n NO_AUTH_EVENT: 'auth/no-auth-event',\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\n POPUP_BLOCKED: 'auth/popup-blocked',\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\n TIMEOUT: 'auth/timeout',\n TOKEN_EXPIRED: 'auth/user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\n UNVERIFIED_EMAIL: 'auth/unverified-email',\n USER_CANCELLED: 'auth/user-cancelled',\n USER_DELETED: 'auth/user-not-found',\n USER_DISABLED: 'auth/user-disabled',\n USER_MISMATCH: 'auth/user-mismatch',\n USER_SIGNED_OUT: 'auth/user-signed-out',\n WEAK_PASSWORD: 'auth/weak-password',\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\n ALREADY_INITIALIZED: 'auth/already-initialized',\n RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\n INVALID_REQ_TYPE: 'auth/invalid-req-type'\n} as const;\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { SDK_VERSION } from '@firebase/app';\n\nexport { LogLevel };\n\nconst logClient = new Logger('@firebase/auth');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function _getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\nexport function _setLogLevel(newLevel: LogLevel): void {\n logClient.logLevel = newLevel;\n}\n\nexport function _logDebug(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.DEBUG) {\n logClient.debug(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logWarn(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.WARN) {\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\nexport function _logError(msg: string, ...args: string[]): void {\n if (logClient.logLevel <= LogLevel.ERROR) {\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth } from '../../model/public_types';\nimport { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../../model/auth';\nimport {\n _DEFAULT_AUTH_ERROR_FACTORY,\n AuthErrorCode,\n AuthErrorParams,\n prodErrorMap,\n ErrorMapRetriever\n} from '../errors';\nimport { _logError } from './log';\n\ntype AuthErrorListParams = K extends keyof AuthErrorParams\n ? [AuthErrorParams[K]]\n : [];\ntype LessAppName = Omit;\n\n/**\n * Unconditionally fails, throwing a developer facing INTERNAL_ERROR\n *\n * @example\n * ```javascript\n * fail(auth, AuthErrorCode.MFA_REQUIRED); // Error: the MFA_REQUIRED error needs more params than appName\n * fail(auth, AuthErrorCode.MFA_REQUIRED, {serverResponse}); // Compiles\n * fail(AuthErrorCode.INTERNAL_ERROR); // Compiles; internal error does not need appName\n * fail(AuthErrorCode.USER_DELETED); // Error: USER_DELETED requires app name\n * fail(auth, AuthErrorCode.USER_DELETED); // Compiles; USER_DELETED _only_ needs app name\n * ```\n *\n * @param appName App name for tagging the error\n * @throws FirebaseError\n */\nexport function _fail(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): never;\nexport function _fail(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): never;\nexport function _fail(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): never {\n throw createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _createError(\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): FirebaseError;\nexport function _createError(\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): FirebaseError;\nexport function _createError(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n return createErrorInternal(authOrCode, ...rest);\n}\n\nexport function _errorWithCustomMessage(\n auth: Auth,\n code: AuthErrorCode,\n message: string\n): FirebaseError {\n const errorMap = {\n ...(prodErrorMap as ErrorMapRetriever)(),\n [code]: message\n };\n const factory = new ErrorFactory(\n 'auth',\n 'Firebase',\n errorMap\n );\n return factory.create(code, {\n appName: auth.name\n });\n}\n\nexport function _assertInstanceOf(\n auth: Auth,\n object: object,\n instance: unknown\n): void {\n const constructorInstance = instance as { new (...args: unknown[]): unknown };\n if (!(object instanceof constructorInstance)) {\n if (constructorInstance.name !== object.constructor.name) {\n _fail(auth, AuthErrorCode.ARGUMENT_ERROR);\n }\n\n throw _errorWithCustomMessage(\n auth,\n AuthErrorCode.ARGUMENT_ERROR,\n `Type of ${object.constructor.name} does not match expected instance.` +\n `Did you pass a reference from a different Auth SDK?`\n );\n }\n}\n\nfunction createErrorInternal(\n authOrCode: Auth | K,\n ...rest: unknown[]\n): FirebaseError {\n if (typeof authOrCode !== 'string') {\n const code = rest[0] as K;\n const fullParams = [...rest.slice(1)] as AuthErrorListParams;\n if (fullParams[0]) {\n fullParams[0].appName = authOrCode.name;\n }\n\n return (authOrCode as AuthInternal)._errorFactory.create(\n code,\n ...fullParams\n );\n }\n\n return _DEFAULT_AUTH_ERROR_FACTORY.create(\n authOrCode,\n ...(rest as AuthErrorListParams)\n );\n}\n\nexport function _assert(\n assertion: unknown,\n code: K,\n ...data: {} extends AuthErrorParams[K]\n ? [AuthErrorParams[K]?]\n : [AuthErrorParams[K]]\n): asserts assertion;\nexport function _assert(\n assertion: unknown,\n auth: Auth,\n code: K,\n ...data: {} extends LessAppName ? [LessAppName?] : [LessAppName]\n): asserts assertion;\nexport function _assert(\n assertion: unknown,\n authOrCode: Auth | K,\n ...rest: unknown[]\n): asserts assertion {\n if (!assertion) {\n throw createErrorInternal(authOrCode, ...rest);\n }\n}\n\n// We really do want to accept literally any function type here\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype TypeExpectation = Function | string | MapType;\n\ninterface MapType extends Record {}\n\nclass Optional {\n constructor(readonly type: TypeExpectation) {}\n}\n\nexport function opt(type: TypeExpectation): Optional {\n return new Optional(type);\n}\n\n/**\n * Asserts the runtime types of arguments. The 'expected' field can be one of\n * a class, a string (representing a \"typeof\" call), or a record map of name\n * to type. Furthermore, the opt() function can be used to mark a field as\n * optional. For example:\n *\n * function foo(auth: Auth, profile: {displayName?: string}, update = false) {\n * assertTypes(arguments, [AuthImpl, {displayName: opt('string')}, opt('boolean')]);\n * }\n *\n * opt() can be used for any type:\n * function foo(auth?: Auth) {\n * assertTypes(arguments, [opt(AuthImpl)]);\n * }\n *\n * The string types can be or'd together, and you can use \"null\" as well (note\n * that typeof null === 'object'; this is an edge case). For example:\n *\n * function foo(profile: {displayName?: string | null}) {\n * assertTypes(arguments, [{displayName: opt('string|null')}]);\n * }\n *\n * @param args\n * @param expected\n */\nexport function assertTypes(\n args: Omit,\n ...expected: Array\n): void {\n if (args.length > expected.length) {\n _fail(AuthErrorCode.ARGUMENT_ERROR, {});\n }\n\n for (let i = 0; i < expected.length; i++) {\n let expect = expected[i];\n const arg = args[i];\n\n if (expect instanceof Optional) {\n // If the arg is undefined, then it matches \"optional\" and we can move to\n // the next arg\n if (typeof arg === 'undefined') {\n continue;\n }\n expect = expect.type;\n }\n\n if (typeof expect === 'string') {\n // Handle the edge case for null because typeof null === 'object'\n if (expect.includes('null') && arg === null) {\n continue;\n }\n\n const required = expect.split('|');\n _assert(required.includes(typeof arg), AuthErrorCode.ARGUMENT_ERROR, {});\n } else if (typeof expect === 'object') {\n // Recursively check record arguments\n const record = arg as Record;\n const map = expect as MapType;\n const keys = Object.keys(expect);\n\n assertTypes(\n keys.map(k => record[k]),\n ...keys.map(k => map[k])\n );\n } else {\n _assert(arg instanceof expect, AuthErrorCode.ARGUMENT_ERROR, {});\n }\n }\n}\n\n/**\n * Unconditionally fails, throwing an internal error with the given message.\n *\n * @param failure type of failure encountered\n * @throws Error\n */\nexport function debugFail(failure: string): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\n _logError(message);\n\n // NOTE: We don't use FirebaseError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * @param assertion\n * @param message\n */\nexport function debugAssert(\n assertion: unknown,\n message: string\n): asserts assertion {\n if (!assertion) {\n debugFail(message);\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _getCurrentUrl(): string {\n return (typeof self !== 'undefined' && self.location?.href) || '';\n}\n\nexport function _isHttpOrHttps(): boolean {\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\n}\n\nexport function _getCurrentScheme(): string | null {\n return (typeof self !== 'undefined' && self.location?.protocol) || null;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isBrowserExtension } from '@firebase/util';\nimport { _isHttpOrHttps } from './location';\n\n/**\n * Determine whether the browser is working online\n */\nexport function _isOnline(): boolean {\n if (\n typeof navigator !== 'undefined' &&\n navigator &&\n 'onLine' in navigator &&\n typeof navigator.onLine === 'boolean' &&\n // Apply only for traditional web apps and Chrome extensions.\n // This is especially true for Cordova apps which have unreliable\n // navigator.onLine behavior unless cordova-plugin-network-information is\n // installed which overwrites the native navigator.onLine value and\n // defines navigator.connection.\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)\n ) {\n return navigator.onLine;\n }\n // If we can't determine the state, assume it is online.\n return true;\n}\n\nexport function _getUserLanguage(): string | null {\n if (typeof navigator === 'undefined') {\n return null;\n }\n const navigatorLanguage: NavigatorLanguage = navigator;\n return (\n // Most reliable, but only supported in Chrome/Firefox.\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\n // Supported in most browsers, but returns the language of the browser\n // UI, not the language set in browser settings.\n navigatorLanguage.language ||\n // Couldn't determine language.\n null\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isMobileCordova, isReactNative } from '@firebase/util';\nimport { _isOnline } from './navigator';\nimport { debugAssert } from './assert';\n\nexport const enum DelayMin {\n OFFLINE = 5000\n}\n\n/**\n * A structure to help pick between a range of long and short delay durations\n * depending on the current environment. In general, the long delay is used for\n * mobile environments whereas short delays are used for desktop environments.\n */\nexport class Delay {\n // The default value for the offline delay timeout in ms.\n\n private readonly isMobile: boolean;\n constructor(\n private readonly shortDelay: number,\n private readonly longDelay: number\n ) {\n // Internal error when improperly initialized.\n debugAssert(\n longDelay > shortDelay,\n 'Short delay should be less than long delay!'\n );\n this.isMobile = isMobileCordova() || isReactNative();\n }\n\n get(): number {\n if (!_isOnline()) {\n // Pick the shorter timeout.\n return Math.min(DelayMin.OFFLINE, this.shortDelay);\n }\n // If running in a mobile environment, return the long delay, otherwise\n // return the short delay.\n // This could be improved in the future to dynamically change based on other\n // variables instead of just reading the current environment.\n return this.isMobile ? this.longDelay : this.shortDelay;\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConfigInternal } from '../../model/auth';\nimport { debugAssert } from './assert';\n\nexport function _emulatorUrl(config: ConfigInternal, path?: string): string {\n debugAssert(config.emulator, 'Emulator should always be set here');\n const { url } = config.emulator;\n\n if (!path) {\n return url;\n }\n\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugFail } from './assert';\n\nexport class FetchProvider {\n private static fetchImpl: typeof fetch | null;\n private static headersImpl: typeof Headers | null;\n private static responseImpl: typeof Response | null;\n\n static initialize(\n fetchImpl: typeof fetch,\n headersImpl?: typeof Headers,\n responseImpl?: typeof Response\n ): void {\n this.fetchImpl = fetchImpl;\n if (headersImpl) {\n this.headersImpl = headersImpl;\n }\n if (responseImpl) {\n this.responseImpl = responseImpl;\n }\n }\n\n static fetch(): typeof fetch {\n if (this.fetchImpl) {\n return this.fetchImpl;\n }\n if (typeof self !== 'undefined' && 'fetch' in self) {\n return self.fetch;\n }\n if (typeof globalThis !== 'undefined' && globalThis.fetch) {\n return globalThis.fetch;\n }\n if (typeof fetch !== 'undefined') {\n return fetch;\n }\n debugFail(\n 'Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static headers(): typeof Headers {\n if (this.headersImpl) {\n return this.headersImpl;\n }\n if (typeof self !== 'undefined' && 'Headers' in self) {\n return self.Headers;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Headers) {\n return globalThis.Headers;\n }\n if (typeof Headers !== 'undefined') {\n return Headers;\n }\n debugFail(\n 'Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n\n static response(): typeof Response {\n if (this.responseImpl) {\n return this.responseImpl;\n }\n if (typeof self !== 'undefined' && 'Response' in self) {\n return self.Response;\n }\n if (typeof globalThis !== 'undefined' && globalThis.Response) {\n return globalThis.Response;\n }\n if (typeof Response !== 'undefined') {\n return Response;\n }\n debugFail(\n 'Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill'\n );\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../core/errors';\n\n/**\n * Errors that can be returned by the backend\n */\nexport const enum ServerError {\n ADMIN_ONLY_OPERATION = 'ADMIN_ONLY_OPERATION',\n BLOCKING_FUNCTION_ERROR_RESPONSE = 'BLOCKING_FUNCTION_ERROR_RESPONSE',\n CAPTCHA_CHECK_FAILED = 'CAPTCHA_CHECK_FAILED',\n CORS_UNSUPPORTED = 'CORS_UNSUPPORTED',\n CREDENTIAL_MISMATCH = 'CREDENTIAL_MISMATCH',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN = 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN',\n DYNAMIC_LINK_NOT_ACTIVATED = 'DYNAMIC_LINK_NOT_ACTIVATED',\n EMAIL_CHANGE_NEEDS_VERIFICATION = 'EMAIL_CHANGE_NEEDS_VERIFICATION',\n EMAIL_EXISTS = 'EMAIL_EXISTS',\n EMAIL_NOT_FOUND = 'EMAIL_NOT_FOUND',\n EXPIRED_OOB_CODE = 'EXPIRED_OOB_CODE',\n FEDERATED_USER_ID_ALREADY_LINKED = 'FEDERATED_USER_ID_ALREADY_LINKED',\n INVALID_APP_CREDENTIAL = 'INVALID_APP_CREDENTIAL',\n INVALID_APP_ID = 'INVALID_APP_ID',\n INVALID_CERT_HASH = 'INVALID_CERT_HASH',\n INVALID_CODE = 'INVALID_CODE',\n INVALID_CONTINUE_URI = 'INVALID_CONTINUE_URI',\n INVALID_CUSTOM_TOKEN = 'INVALID_CUSTOM_TOKEN',\n INVALID_DYNAMIC_LINK_DOMAIN = 'INVALID_DYNAMIC_LINK_DOMAIN',\n INVALID_EMAIL = 'INVALID_EMAIL',\n INVALID_ID_TOKEN = 'INVALID_ID_TOKEN',\n INVALID_IDP_RESPONSE = 'INVALID_IDP_RESPONSE',\n INVALID_IDENTIFIER = 'INVALID_IDENTIFIER',\n INVALID_LOGIN_CREDENTIALS = 'INVALID_LOGIN_CREDENTIALS',\n INVALID_MESSAGE_PAYLOAD = 'INVALID_MESSAGE_PAYLOAD',\n INVALID_MFA_PENDING_CREDENTIAL = 'INVALID_MFA_PENDING_CREDENTIAL',\n INVALID_OAUTH_CLIENT_ID = 'INVALID_OAUTH_CLIENT_ID',\n INVALID_OOB_CODE = 'INVALID_OOB_CODE',\n INVALID_PASSWORD = 'INVALID_PASSWORD',\n INVALID_PENDING_TOKEN = 'INVALID_PENDING_TOKEN',\n INVALID_PHONE_NUMBER = 'INVALID_PHONE_NUMBER',\n INVALID_PROVIDER_ID = 'INVALID_PROVIDER_ID',\n INVALID_RECIPIENT_EMAIL = 'INVALID_RECIPIENT_EMAIL',\n INVALID_SENDER = 'INVALID_SENDER',\n INVALID_SESSION_INFO = 'INVALID_SESSION_INFO',\n INVALID_TEMPORARY_PROOF = 'INVALID_TEMPORARY_PROOF',\n INVALID_TENANT_ID = 'INVALID_TENANT_ID',\n MFA_ENROLLMENT_NOT_FOUND = 'MFA_ENROLLMENT_NOT_FOUND',\n MISSING_ANDROID_PACKAGE_NAME = 'MISSING_ANDROID_PACKAGE_NAME',\n MISSING_APP_CREDENTIAL = 'MISSING_APP_CREDENTIAL',\n MISSING_CODE = 'MISSING_CODE',\n MISSING_CONTINUE_URI = 'MISSING_CONTINUE_URI',\n MISSING_CUSTOM_TOKEN = 'MISSING_CUSTOM_TOKEN',\n MISSING_IOS_BUNDLE_ID = 'MISSING_IOS_BUNDLE_ID',\n MISSING_MFA_ENROLLMENT_ID = 'MISSING_MFA_ENROLLMENT_ID',\n MISSING_MFA_PENDING_CREDENTIAL = 'MISSING_MFA_PENDING_CREDENTIAL',\n MISSING_OOB_CODE = 'MISSING_OOB_CODE',\n MISSING_OR_INVALID_NONCE = 'MISSING_OR_INVALID_NONCE',\n MISSING_PASSWORD = 'MISSING_PASSWORD',\n MISSING_REQ_TYPE = 'MISSING_REQ_TYPE',\n MISSING_PHONE_NUMBER = 'MISSING_PHONE_NUMBER',\n MISSING_SESSION_INFO = 'MISSING_SESSION_INFO',\n OPERATION_NOT_ALLOWED = 'OPERATION_NOT_ALLOWED',\n PASSWORD_LOGIN_DISABLED = 'PASSWORD_LOGIN_DISABLED',\n QUOTA_EXCEEDED = 'QUOTA_EXCEEDED',\n RESET_PASSWORD_EXCEED_LIMIT = 'RESET_PASSWORD_EXCEED_LIMIT',\n REJECTED_CREDENTIAL = 'REJECTED_CREDENTIAL',\n SECOND_FACTOR_EXISTS = 'SECOND_FACTOR_EXISTS',\n SECOND_FACTOR_LIMIT_EXCEEDED = 'SECOND_FACTOR_LIMIT_EXCEEDED',\n SESSION_EXPIRED = 'SESSION_EXPIRED',\n TENANT_ID_MISMATCH = 'TENANT_ID_MISMATCH',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n TOO_MANY_ATTEMPTS_TRY_LATER = 'TOO_MANY_ATTEMPTS_TRY_LATER',\n UNSUPPORTED_FIRST_FACTOR = 'UNSUPPORTED_FIRST_FACTOR',\n UNSUPPORTED_TENANT_OPERATION = 'UNSUPPORTED_TENANT_OPERATION',\n UNAUTHORIZED_DOMAIN = 'UNAUTHORIZED_DOMAIN',\n UNVERIFIED_EMAIL = 'UNVERIFIED_EMAIL',\n USER_CANCELLED = 'USER_CANCELLED',\n USER_DISABLED = 'USER_DISABLED',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n WEAK_PASSWORD = 'WEAK_PASSWORD',\n RECAPTCHA_NOT_ENABLED = 'RECAPTCHA_NOT_ENABLED',\n MISSING_RECAPTCHA_TOKEN = 'MISSING_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_TOKEN = 'INVALID_RECAPTCHA_TOKEN',\n INVALID_RECAPTCHA_ACTION = 'INVALID_RECAPTCHA_ACTION',\n MISSING_CLIENT_TYPE = 'MISSING_CLIENT_TYPE',\n MISSING_RECAPTCHA_VERSION = 'MISSING_RECAPTCHA_VERSION',\n INVALID_RECAPTCHA_VERSION = 'INVALID_RECAPTCHA_VERSION',\n INVALID_REQ_TYPE = 'INVALID_REQ_TYPE',\n PASSWORD_DOES_NOT_MEET_REQUIREMENTS = 'PASSWORD_DOES_NOT_MEET_REQUIREMENTS'\n}\n\n/**\n * API Response in the event of an error\n */\nexport interface JsonError {\n error: {\n code: number;\n message: string;\n errors?: [\n {\n message: ServerError;\n domain: string;\n reason: string;\n }\n ];\n };\n}\n\n/**\n * Type definition for a map from server errors to developer visible errors\n */\nexport declare type ServerErrorMap = {\n readonly [K in ApiError]: AuthErrorCode;\n};\n\n/**\n * Map from errors returned by the server to errors to developer visible errors\n */\nexport const SERVER_ERROR_MAP: Partial> = {\n // Custom token errors.\n [ServerError.CREDENTIAL_MISMATCH]: AuthErrorCode.CREDENTIAL_MISMATCH,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CUSTOM_TOKEN]: AuthErrorCode.INTERNAL_ERROR,\n\n // Create Auth URI errors.\n [ServerError.INVALID_IDENTIFIER]: AuthErrorCode.INVALID_EMAIL,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_CONTINUE_URI]: AuthErrorCode.INTERNAL_ERROR,\n\n // Sign in with email and password errors (some apply to sign up too).\n [ServerError.INVALID_PASSWORD]: AuthErrorCode.INVALID_PASSWORD,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_PASSWORD]: AuthErrorCode.MISSING_PASSWORD,\n // Thrown if Email Enumeration Protection is enabled in the project and the email or password is\n // invalid.\n [ServerError.INVALID_LOGIN_CREDENTIALS]: AuthErrorCode.INVALID_CREDENTIAL,\n\n // Sign up with email and password errors.\n [ServerError.EMAIL_EXISTS]: AuthErrorCode.EMAIL_EXISTS,\n [ServerError.PASSWORD_LOGIN_DISABLED]: AuthErrorCode.OPERATION_NOT_ALLOWED,\n\n // Verify assertion for sign in with credential errors:\n [ServerError.INVALID_IDP_RESPONSE]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.INVALID_PENDING_TOKEN]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.FEDERATED_USER_ID_ALREADY_LINKED]:\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_REQ_TYPE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Send Password reset email errors:\n [ServerError.EMAIL_NOT_FOUND]: AuthErrorCode.USER_DELETED,\n [ServerError.RESET_PASSWORD_EXCEED_LIMIT]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n\n [ServerError.EXPIRED_OOB_CODE]: AuthErrorCode.EXPIRED_OOB_CODE,\n [ServerError.INVALID_OOB_CODE]: AuthErrorCode.INVALID_OOB_CODE,\n // This can only happen if the SDK sends a bad request.\n [ServerError.MISSING_OOB_CODE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Operations that require ID token in request:\n [ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN]:\n AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN,\n [ServerError.INVALID_ID_TOKEN]: AuthErrorCode.INVALID_AUTH,\n [ServerError.TOKEN_EXPIRED]: AuthErrorCode.TOKEN_EXPIRED,\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.TOKEN_EXPIRED,\n\n // Other errors.\n [ServerError.TOO_MANY_ATTEMPTS_TRY_LATER]:\n AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER,\n [ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS]:\n AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS,\n\n // Phone Auth related errors.\n [ServerError.INVALID_CODE]: AuthErrorCode.INVALID_CODE,\n [ServerError.INVALID_SESSION_INFO]: AuthErrorCode.INVALID_SESSION_INFO,\n [ServerError.INVALID_TEMPORARY_PROOF]: AuthErrorCode.INVALID_CREDENTIAL,\n [ServerError.MISSING_SESSION_INFO]: AuthErrorCode.MISSING_SESSION_INFO,\n [ServerError.SESSION_EXPIRED]: AuthErrorCode.CODE_EXPIRED,\n\n // Other action code errors when additional settings passed.\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\n // This is OK as this error will be caught by client side validation.\n [ServerError.MISSING_ANDROID_PACKAGE_NAME]:\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME,\n [ServerError.UNAUTHORIZED_DOMAIN]: AuthErrorCode.UNAUTHORIZED_DOMAIN,\n\n // getProjectConfig errors when clientId is passed.\n [ServerError.INVALID_OAUTH_CLIENT_ID]: AuthErrorCode.INVALID_OAUTH_CLIENT_ID,\n\n // User actions (sign-up or deletion) disabled errors.\n [ServerError.ADMIN_ONLY_OPERATION]: AuthErrorCode.ADMIN_ONLY_OPERATION,\n\n // Multi factor related errors.\n [ServerError.INVALID_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.INVALID_MFA_SESSION,\n [ServerError.MFA_ENROLLMENT_NOT_FOUND]: AuthErrorCode.MFA_INFO_NOT_FOUND,\n [ServerError.MISSING_MFA_ENROLLMENT_ID]: AuthErrorCode.MISSING_MFA_INFO,\n [ServerError.MISSING_MFA_PENDING_CREDENTIAL]:\n AuthErrorCode.MISSING_MFA_SESSION,\n [ServerError.SECOND_FACTOR_EXISTS]:\n AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED,\n [ServerError.SECOND_FACTOR_LIMIT_EXCEEDED]:\n AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED,\n\n // Blocking functions related errors.\n [ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE]: AuthErrorCode.INTERNAL_ERROR,\n\n // Recaptcha related errors.\n [ServerError.RECAPTCHA_NOT_ENABLED]: AuthErrorCode.RECAPTCHA_NOT_ENABLED,\n [ServerError.MISSING_RECAPTCHA_TOKEN]: AuthErrorCode.MISSING_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_TOKEN]: AuthErrorCode.INVALID_RECAPTCHA_TOKEN,\n [ServerError.INVALID_RECAPTCHA_ACTION]:\n AuthErrorCode.INVALID_RECAPTCHA_ACTION,\n [ServerError.MISSING_CLIENT_TYPE]: AuthErrorCode.MISSING_CLIENT_TYPE,\n [ServerError.MISSING_RECAPTCHA_VERSION]:\n AuthErrorCode.MISSING_RECAPTCHA_VERSION,\n [ServerError.INVALID_RECAPTCHA_VERSION]:\n AuthErrorCode.INVALID_RECAPTCHA_VERSION,\n [ServerError.INVALID_REQ_TYPE]: AuthErrorCode.INVALID_REQ_TYPE\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError, querystring } from '@firebase/util';\n\nimport { AuthErrorCode, NamedErrorParams } from '../core/errors';\nimport {\n _createError,\n _errorWithCustomMessage,\n _fail\n} from '../core/util/assert';\nimport { Delay } from '../core/util/delay';\nimport { _emulatorUrl } from '../core/util/emulator';\nimport { FetchProvider } from '../core/util/fetch_provider';\nimport { Auth } from '../model/public_types';\nimport { AuthInternal, ConfigInternal } from '../model/auth';\nimport { IdTokenResponse, TaggedWithTokenResponse } from '../model/id_token';\nimport { IdTokenMfaResponse } from './authentication/mfa';\nimport { SERVER_ERROR_MAP, ServerError, ServerErrorMap } from './errors';\n\nexport const enum HttpMethod {\n POST = 'POST',\n GET = 'GET'\n}\n\nexport const enum HttpHeader {\n CONTENT_TYPE = 'Content-Type',\n X_FIREBASE_LOCALE = 'X-Firebase-Locale',\n X_CLIENT_VERSION = 'X-Client-Version',\n X_FIREBASE_GMPID = 'X-Firebase-gmpid',\n X_FIREBASE_CLIENT = 'X-Firebase-Client',\n X_FIREBASE_APP_CHECK = 'X-Firebase-AppCheck'\n}\n\nexport const enum Endpoint {\n CREATE_AUTH_URI = '/v1/accounts:createAuthUri',\n DELETE_ACCOUNT = '/v1/accounts:delete',\n RESET_PASSWORD = '/v1/accounts:resetPassword',\n SIGN_UP = '/v1/accounts:signUp',\n SIGN_IN_WITH_CUSTOM_TOKEN = '/v1/accounts:signInWithCustomToken',\n SIGN_IN_WITH_EMAIL_LINK = '/v1/accounts:signInWithEmailLink',\n SIGN_IN_WITH_IDP = '/v1/accounts:signInWithIdp',\n SIGN_IN_WITH_PASSWORD = '/v1/accounts:signInWithPassword',\n SIGN_IN_WITH_PHONE_NUMBER = '/v1/accounts:signInWithPhoneNumber',\n SEND_VERIFICATION_CODE = '/v1/accounts:sendVerificationCode',\n SEND_OOB_CODE = '/v1/accounts:sendOobCode',\n SET_ACCOUNT_INFO = '/v1/accounts:update',\n GET_ACCOUNT_INFO = '/v1/accounts:lookup',\n GET_RECAPTCHA_PARAM = '/v1/recaptchaParams',\n START_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:start',\n FINALIZE_MFA_ENROLLMENT = '/v2/accounts/mfaEnrollment:finalize',\n START_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:start',\n FINALIZE_MFA_SIGN_IN = '/v2/accounts/mfaSignIn:finalize',\n WITHDRAW_MFA = '/v2/accounts/mfaEnrollment:withdraw',\n GET_PROJECT_CONFIG = '/v1/projects',\n GET_RECAPTCHA_CONFIG = '/v2/recaptchaConfig',\n GET_PASSWORD_POLICY = '/v2/passwordPolicy',\n TOKEN = '/v1/token',\n REVOKE_TOKEN = '/v2/accounts:revokeToken'\n}\n\nexport const enum RecaptchaClientType {\n WEB = 'CLIENT_TYPE_WEB',\n ANDROID = 'CLIENT_TYPE_ANDROID',\n IOS = 'CLIENT_TYPE_IOS'\n}\n\nexport const enum RecaptchaVersion {\n ENTERPRISE = 'RECAPTCHA_ENTERPRISE'\n}\n\nexport const enum RecaptchaActionName {\n SIGN_IN_WITH_PASSWORD = 'signInWithPassword',\n GET_OOB_CODE = 'getOobCode',\n SIGN_UP_PASSWORD = 'signUpPassword'\n}\n\nexport const enum EnforcementState {\n ENFORCE = 'ENFORCE',\n AUDIT = 'AUDIT',\n OFF = 'OFF',\n ENFORCEMENT_STATE_UNSPECIFIED = 'ENFORCEMENT_STATE_UNSPECIFIED'\n}\n\n// Providers that have reCAPTCHA Enterprise support.\nexport const enum RecaptchaProvider {\n EMAIL_PASSWORD_PROVIDER = 'EMAIL_PASSWORD_PROVIDER'\n}\n\nexport const DEFAULT_API_TIMEOUT_MS = new Delay(30_000, 60_000);\n\nexport function _addTidIfNecessary(\n auth: Auth,\n request: T\n): T {\n if (auth.tenantId && !request.tenantId) {\n return {\n ...request,\n tenantId: auth.tenantId\n };\n }\n return request;\n}\n\nexport async function _performApiRequest(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial> = {}\n): Promise {\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\n let body = {};\n let params = {};\n if (request) {\n if (method === HttpMethod.GET) {\n params = request;\n } else {\n body = {\n body: JSON.stringify(request)\n };\n }\n }\n\n const query = querystring({\n key: auth.config.apiKey,\n ...params\n }).slice(1);\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/json';\n\n if (auth.languageCode) {\n headers[HttpHeader.X_FIREBASE_LOCALE] = auth.languageCode;\n }\n\n return FetchProvider.fetch()(\n _getFinalTarget(auth, auth.config.apiHost, path, query),\n {\n method,\n headers,\n referrerPolicy: 'no-referrer',\n ...body\n }\n );\n });\n}\n\nexport async function _performFetchWithErrorHandling(\n auth: Auth,\n customErrorMap: Partial>,\n fetchFn: () => Promise\n): Promise {\n (auth as AuthInternal)._canInitEmulator = false;\n const errorMap = { ...SERVER_ERROR_MAP, ...customErrorMap };\n try {\n const networkTimeout = new NetworkTimeout(auth);\n const response: Response = await Promise.race>([\n fetchFn(),\n networkTimeout.promise\n ]);\n\n // If we've reached this point, the fetch succeeded and the networkTimeout\n // didn't throw; clear the network timeout delay so that Node won't hang\n networkTimeout.clearNetworkTimeout();\n\n const json = await response.json();\n if ('needConfirmation' in json) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, json);\n }\n\n if (response.ok && !('errorMessage' in json)) {\n return json;\n } else {\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\n if (serverErrorCode === ServerError.FEDERATED_USER_ID_ALREADY_LINKED) {\n throw _makeTaggedError(\n auth,\n AuthErrorCode.CREDENTIAL_ALREADY_IN_USE,\n json\n );\n } else if (serverErrorCode === ServerError.EMAIL_EXISTS) {\n throw _makeTaggedError(auth, AuthErrorCode.EMAIL_EXISTS, json);\n } else if (serverErrorCode === ServerError.USER_DISABLED) {\n throw _makeTaggedError(auth, AuthErrorCode.USER_DISABLED, json);\n }\n const authError =\n errorMap[serverErrorCode as ServerError] ||\n (serverErrorCode\n .toLowerCase()\n .replace(/[_\\s]+/g, '-') as unknown as AuthErrorCode);\n if (serverErrorMessage) {\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\n } else {\n _fail(auth, authError);\n }\n }\n } catch (e) {\n if (e instanceof FirebaseError) {\n throw e;\n }\n // Changing this to a different error code will log user out when there is a network error\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\n _fail(auth, AuthErrorCode.NETWORK_REQUEST_FAILED, { 'message': String(e) });\n }\n}\n\nexport async function _performSignInRequest(\n auth: Auth,\n method: HttpMethod,\n path: Endpoint,\n request?: T,\n customErrorMap: Partial> = {}\n): Promise {\n const serverResponse = (await _performApiRequest(\n auth,\n method,\n path,\n request,\n customErrorMap\n )) as V;\n if ('mfaPendingCredential' in serverResponse) {\n _fail(auth, AuthErrorCode.MFA_REQUIRED, {\n _serverResponse: serverResponse\n });\n }\n\n return serverResponse;\n}\n\nexport function _getFinalTarget(\n auth: Auth,\n host: string,\n path: string,\n query: string\n): string {\n const base = `${host}${path}?${query}`;\n\n if (!(auth as AuthInternal).config.emulator) {\n return `${auth.config.apiScheme}://${base}`;\n }\n\n return _emulatorUrl(auth.config as ConfigInternal, base);\n}\n\nexport function _parseEnforcementState(\n enforcementStateStr: string\n): EnforcementState {\n switch (enforcementStateStr) {\n case 'ENFORCE':\n return EnforcementState.ENFORCE;\n case 'AUDIT':\n return EnforcementState.AUDIT;\n case 'OFF':\n return EnforcementState.OFF;\n default:\n return EnforcementState.ENFORCEMENT_STATE_UNSPECIFIED;\n }\n}\n\nclass NetworkTimeout {\n // Node timers and browser timers are fundamentally incompatible, but we\n // don't care about the value here\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timer: any | null = null;\n readonly promise = new Promise((_, reject) => {\n this.timer = setTimeout(() => {\n return reject(\n _createError(this.auth, AuthErrorCode.NETWORK_REQUEST_FAILED)\n );\n }, DEFAULT_API_TIMEOUT_MS.get());\n });\n\n clearNetworkTimeout(): void {\n clearTimeout(this.timer);\n }\n\n constructor(private readonly auth: Auth) {}\n}\n\ninterface PotentialResponse extends IdTokenResponse {\n email?: string;\n phoneNumber?: string;\n}\n\nexport function _makeTaggedError(\n auth: Auth,\n code: AuthErrorCode,\n response: PotentialResponse\n): FirebaseError {\n const errorParams: NamedErrorParams = {\n appName: auth.name\n };\n\n if (response.email) {\n errorParams.email = response.email;\n }\n if (response.phoneNumber) {\n errorParams.phoneNumber = response.phoneNumber;\n }\n\n const error = _createError(auth, code, errorParams);\n\n // We know customData is defined on error because errorParams is defined\n (error.customData! as TaggedWithTokenResponse)._tokenResponse = response;\n return error;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { RecaptchaParameters } from '../../model/public_types';\nimport {\n GetRecaptchaConfigResponse,\n RecaptchaEnforcementProviderState\n} from '../../api/authentication/recaptcha';\nimport { EnforcementState, _parseEnforcementState } from '../../api/index';\n\n// reCAPTCHA v2 interface\nexport interface Recaptcha {\n render: (container: HTMLElement, parameters: RecaptchaParameters) => number;\n getResponse: (id: number) => string;\n execute: (id: number) => unknown;\n reset: (id: number) => unknown;\n}\n\nexport function isV2(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is Recaptcha {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as Recaptcha).getResponse !== undefined\n );\n}\n\n// reCAPTCHA Enterprise & v3 shared interface\nexport interface GreCAPTCHATopLevel extends GreCAPTCHA {\n enterprise: GreCAPTCHA;\n}\n\n// reCAPTCHA Enterprise interface\nexport interface GreCAPTCHA {\n ready: (callback: () => void) => void;\n execute: (siteKey: string, options: { action: string }) => Promise;\n render: (\n container: string | HTMLElement,\n parameters: GreCAPTCHARenderOption\n ) => string;\n}\n\nexport interface GreCAPTCHARenderOption {\n sitekey: string;\n size: 'invisible';\n}\n\nexport function isEnterprise(\n grecaptcha: Recaptcha | GreCAPTCHA | undefined\n): grecaptcha is GreCAPTCHATopLevel {\n return (\n grecaptcha !== undefined &&\n (grecaptcha as GreCAPTCHATopLevel).enterprise !== undefined\n );\n}\n\n// TODO(chuanr): Replace this with the AuthWindow after resolving the dependency issue in Node.js env.\ndeclare global {\n interface Window {\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n }\n}\n\nexport class RecaptchaConfig {\n /**\n * The reCAPTCHA site key.\n */\n siteKey: string = '';\n\n /**\n * The list of providers and their enablement status for reCAPTCHA Enterprise.\n */\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[] = [];\n\n constructor(response: GetRecaptchaConfigResponse) {\n if (response.recaptchaKey === undefined) {\n throw new Error('recaptchaKey undefined');\n }\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\n this.siteKey = response.recaptchaKey.split('/')[3];\n this.recaptchaEnforcementState = response.recaptchaEnforcementState;\n }\n\n /**\n * Returns the reCAPTCHA Enterprise enforcement state for the given provider.\n *\n * @param providerStr - The provider whose enforcement state is to be returned.\n * @returns The reCAPTCHA Enterprise enforcement state for the given provider.\n */\n getProviderEnforcementState(providerStr: string): EnforcementState | null {\n if (\n !this.recaptchaEnforcementState ||\n this.recaptchaEnforcementState.length === 0\n ) {\n return null;\n }\n\n for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {\n if (\n recaptchaEnforcementState.provider &&\n recaptchaEnforcementState.provider === providerStr\n ) {\n return _parseEnforcementState(\n recaptchaEnforcementState.enforcementState\n );\n }\n }\n return null;\n }\n\n /**\n * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.\n *\n * @param providerStr - The provider whose enablement state is to be returned.\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.\n */\n isProviderEnabled(providerStr: string): boolean {\n return (\n this.getProviderEnforcementState(providerStr) ===\n EnforcementState.ENFORCE ||\n this.getProviderEnforcementState(providerStr) === EnforcementState.AUDIT\n );\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _performApiRequest,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\ninterface GetRecaptchaParamResponse {\n recaptchaSiteKey?: string;\n}\n\nexport async function getRecaptchaParams(auth: Auth): Promise {\n return (\n (\n await _performApiRequest(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_PARAM\n )\n ).recaptchaSiteKey || ''\n );\n}\n\n// The following functions are for reCAPTCHA enterprise integration.\ninterface GetRecaptchaConfigRequest {\n tenantId?: string;\n clientType?: RecaptchaClientType;\n version?: RecaptchaVersion;\n}\n\nexport interface RecaptchaEnforcementProviderState {\n provider: string;\n enforcementState: string;\n}\n\nexport interface GetRecaptchaConfigResponse {\n recaptchaKey: string;\n recaptchaEnforcementState: RecaptchaEnforcementProviderState[];\n}\n\nexport async function getRecaptchaConfig(\n auth: Auth,\n request: GetRecaptchaConfigRequest\n): Promise {\n return _performApiRequest<\n GetRecaptchaConfigRequest,\n GetRecaptchaConfigResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_RECAPTCHA_CONFIG,\n _addTidIfNecessary(auth, request)\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { MfaEnrollment } from './mfa';\nimport { Auth } from '../../model/public_types';\n\nexport interface DeleteAccountRequest {\n idToken: string;\n}\n\nexport async function deleteAccount(\n auth: Auth,\n request: DeleteAccountRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.DELETE_ACCOUNT,\n request\n );\n}\n\nexport interface ProviderUserInfo {\n providerId: string;\n rawId?: string;\n email?: string;\n displayName?: string;\n photoUrl?: string;\n phoneNumber?: string;\n}\n\nexport interface DeleteLinkedAccountsRequest {\n idToken: string;\n deleteProvider: string[];\n}\n\nexport interface DeleteLinkedAccountsResponse {\n providerUserInfo: ProviderUserInfo[];\n}\n\nexport async function deleteLinkedAccounts(\n auth: Auth,\n request: DeleteLinkedAccountsRequest\n): Promise {\n return _performApiRequest<\n DeleteLinkedAccountsRequest,\n DeleteLinkedAccountsResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\nexport interface APIUserInfo {\n localId?: string;\n displayName?: string;\n photoUrl?: string;\n email?: string;\n emailVerified?: boolean;\n phoneNumber?: string;\n lastLoginAt?: number;\n createdAt?: number;\n tenantId?: string;\n passwordHash?: string;\n providerUserInfo?: ProviderUserInfo[];\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface GetAccountInfoRequest {\n idToken: string;\n}\n\nexport interface GetAccountInfoResponse {\n users: APIUserInfo[];\n}\n\nexport async function getAccountInfo(\n auth: Auth,\n request: GetAccountInfoRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.GET_ACCOUNT_INFO,\n request\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function utcTimestampToDateString(\n utcTimestamp?: string | number\n): string | undefined {\n if (!utcTimestamp) {\n return undefined;\n }\n try {\n // Convert to date object.\n const date = new Date(Number(utcTimestamp));\n // Test date is valid.\n if (!isNaN(date.getTime())) {\n // Convert to UTC date string.\n return date.toUTCString();\n }\n } catch (e) {\n // Do nothing. undefined will be returned.\n }\n return undefined;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult, ParsedToken, User } from '../../model/public_types';\nimport { base64Decode, getModularInstance } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { _logError } from '../util/log';\nimport { utcTimestampToDateString } from '../util/time';\nimport { AuthErrorCode } from '../errors';\n\n/**\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport function getIdToken(user: User, forceRefresh = false): Promise {\n return getModularInstance(user).getIdToken(forceRefresh);\n}\n\n/**\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\n *\n * @remarks\n * Returns the current token if it has not expired or if it will not expire in the next five\n * minutes. Otherwise, this will refresh the token and return a new one.\n *\n * @param user - The user.\n * @param forceRefresh - Force refresh regardless of token expiration.\n *\n * @public\n */\nexport async function getIdTokenResult(\n user: User,\n forceRefresh = false\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const token = await userInternal.getIdToken(forceRefresh);\n const claims = _parseToken(token);\n\n _assert(\n claims && claims.exp && claims.auth_time && claims.iat,\n userInternal.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const firebase =\n typeof claims.firebase === 'object' ? claims.firebase : undefined;\n\n const signInProvider: string | undefined = firebase?.['sign_in_provider'];\n\n return {\n claims,\n token,\n authTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.auth_time)\n )!,\n issuedAtTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.iat)\n )!,\n expirationTime: utcTimestampToDateString(\n secondsStringToMilliseconds(claims.exp)\n )!,\n signInProvider: signInProvider || null,\n signInSecondFactor: firebase?.['sign_in_second_factor'] || null\n };\n}\n\nfunction secondsStringToMilliseconds(seconds: string): number {\n return Number(seconds) * 1000;\n}\n\nexport function _parseToken(token: string): ParsedToken | null {\n const [algorithm, payload, signature] = token.split('.');\n if (\n algorithm === undefined ||\n payload === undefined ||\n signature === undefined\n ) {\n _logError('JWT malformed, contained fewer than 3 sections');\n return null;\n }\n\n try {\n const decoded = base64Decode(payload);\n if (!decoded) {\n _logError('Failed to decode base64 JWT payload');\n return null;\n }\n return JSON.parse(decoded);\n } catch (e) {\n _logError(\n 'Caught error parsing JWT payload as JSON',\n (e as Error)?.toString()\n );\n return null;\n }\n}\n\n/**\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\n */\nexport function _tokenExpiresIn(token: string): number {\n const parsedToken = _parseToken(token);\n _assert(parsedToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.exp !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n _assert(typeof parsedToken.iat !== 'undefined', AuthErrorCode.INTERNAL_ERROR);\n return Number(parsedToken.exp) - Number(parsedToken.iat);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\nexport async function _logoutIfInvalidated(\n user: UserInternal,\n promise: Promise,\n bypassAuthState = false\n): Promise {\n if (bypassAuthState) {\n return promise;\n }\n try {\n return await promise;\n } catch (e) {\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\n if (user.auth.currentUser === user) {\n await user.auth.signOut();\n }\n }\n\n throw e;\n }\n}\n\nfunction isUserInvalidated({ code }: FirebaseError): boolean {\n return (\n code === `auth/${AuthErrorCode.USER_DISABLED}` ||\n code === `auth/${AuthErrorCode.TOKEN_EXPIRED}`\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\n\n// Refresh the token five minutes before expiration\nexport const enum Duration {\n OFFSET = 5 * 1000 * 60,\n RETRY_BACKOFF_MIN = 30 * 1000,\n RETRY_BACKOFF_MAX = 16 * 60 * 1000\n}\n\nexport class ProactiveRefresh {\n private isRunning = false;\n\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private timerId: any | null = null;\n private errorBackoff = Duration.RETRY_BACKOFF_MIN;\n\n constructor(private readonly user: UserInternal) {}\n\n _start(): void {\n if (this.isRunning) {\n return;\n }\n\n this.isRunning = true;\n this.schedule();\n }\n\n _stop(): void {\n if (!this.isRunning) {\n return;\n }\n\n this.isRunning = false;\n if (this.timerId !== null) {\n clearTimeout(this.timerId);\n }\n }\n\n private getInterval(wasError: boolean): number {\n if (wasError) {\n const interval = this.errorBackoff;\n this.errorBackoff = Math.min(\n this.errorBackoff * 2,\n Duration.RETRY_BACKOFF_MAX\n );\n return interval;\n } else {\n // Reset the error backoff\n this.errorBackoff = Duration.RETRY_BACKOFF_MIN;\n const expTime = this.user.stsTokenManager.expirationTime ?? 0;\n const interval = expTime - Date.now() - Duration.OFFSET;\n\n return Math.max(0, interval);\n }\n }\n\n private schedule(wasError = false): void {\n if (!this.isRunning) {\n // Just in case...\n return;\n }\n\n const interval = this.getInterval(wasError);\n this.timerId = setTimeout(async () => {\n await this.iteration();\n }, interval);\n }\n\n private async iteration(): Promise {\n try {\n await this.user.getIdToken(true);\n } catch (e) {\n // Only retry on network errors\n if (\n (e as FirebaseError)?.code ===\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n this.schedule(/* wasError */ true);\n }\n\n return;\n }\n this.schedule();\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserMetadata as UserMetadataType } from '../../model/public_types';\n\nimport { utcTimestampToDateString } from '../util/time';\n\nexport class UserMetadata implements UserMetadataType {\n creationTime?: string;\n lastSignInTime?: string;\n\n constructor(\n private createdAt?: string | number,\n private lastLoginAt?: string | number\n ) {\n this._initializeTime();\n }\n\n private _initializeTime(): void {\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\n this.creationTime = utcTimestampToDateString(this.createdAt);\n }\n\n _copy(metadata: UserMetadata): void {\n this.createdAt = metadata.createdAt;\n this.lastLoginAt = metadata.lastLoginAt;\n this._initializeTime();\n }\n\n toJSON(): object {\n return {\n createdAt: this.createdAt,\n lastLoginAt: this.lastLoginAt\n };\n }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User, UserInfo } from '../../model/public_types';\n\nimport {\n getAccountInfo,\n ProviderUserInfo\n} from '../../api/account_management/account';\nimport { UserInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserMetadata } from './user_metadata';\nimport { getModularInstance } from '@firebase/util';\n\nexport async function _reloadWithoutSaving(user: UserInternal): Promise {\n const auth = user.auth;\n const idToken = await user.getIdToken();\n const response = await _logoutIfInvalidated(\n user,\n getAccountInfo(auth, { idToken })\n );\n\n _assert(response?.users.length, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const coreAccount = response.users[0];\n\n user._notifyReloadListener(coreAccount);\n\n const newProviderData = coreAccount.providerUserInfo?.length\n ? extractProviderData(coreAccount.providerUserInfo)\n : [];\n\n const providerData = mergeProviderData(user.providerData, newProviderData);\n\n // Preserves the non-nonymous status of the stored user, even if no more\n // credentials (federated or email/password) are linked to the user. If\n // the user was previously anonymous, then use provider data to update.\n // On the other hand, if it was not anonymous before, it should never be\n // considered anonymous now.\n const oldIsAnonymous = user.isAnonymous;\n const newIsAnonymous =\n !(user.email && coreAccount.passwordHash) && !providerData?.length;\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\n\n const updates: Partial = {\n uid: coreAccount.localId,\n displayName: coreAccount.displayName || null,\n photoURL: coreAccount.photoUrl || null,\n email: coreAccount.email || null,\n emailVerified: coreAccount.emailVerified || false,\n phoneNumber: coreAccount.phoneNumber || null,\n tenantId: coreAccount.tenantId || null,\n providerData,\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\n isAnonymous\n };\n\n Object.assign(user, updates);\n}\n\n/**\n * Reloads user account data, if signed in.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function reload(user: User): Promise {\n const userInternal: UserInternal = getModularInstance(user) as UserInternal;\n await _reloadWithoutSaving(userInternal);\n\n // Even though the current user hasn't changed, update\n // current user will trigger a persistence update w/ the\n // new info.\n await userInternal.auth._persistUserIfCurrent(userInternal);\n userInternal.auth._notifyListenersIfCurrent(userInternal);\n}\n\nfunction mergeProviderData(\n original: UserInfo[],\n newData: UserInfo[]\n): UserInfo[] {\n const deduped = original.filter(\n o => !newData.some(n => n.providerId === o.providerId)\n );\n return [...deduped, ...newData];\n}\n\nfunction extractProviderData(providers: ProviderUserInfo[]): UserInfo[] {\n return providers.map(({ providerId, ...provider }) => {\n return {\n providerId,\n uid: provider.rawId || '',\n displayName: provider.displayName || null,\n email: provider.email || null,\n phoneNumber: provider.phoneNumber || null,\n photoURL: provider.photoUrl || null\n };\n });\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable camelcase */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n _getFinalTarget,\n _performFetchWithErrorHandling,\n _performApiRequest,\n _addTidIfNecessary,\n HttpMethod,\n HttpHeader,\n Endpoint\n} from '../index';\nimport { FetchProvider } from '../../core/util/fetch_provider';\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\n\nexport const enum TokenType {\n REFRESH_TOKEN = 'REFRESH_TOKEN',\n ACCESS_TOKEN = 'ACCESS_TOKEN'\n}\n\n/** The server responses with snake_case; we convert to camelCase */\ninterface RequestStsTokenServerResponse {\n access_token: string;\n expires_in: string;\n refresh_token: string;\n}\n\nexport interface RequestStsTokenResponse {\n accessToken: string;\n expiresIn: string;\n refreshToken: string;\n}\n\nexport interface RevokeTokenRequest {\n providerId: string;\n tokenType: TokenType;\n token: string;\n idToken: string;\n tenantId?: string;\n}\n\nexport interface RevokeTokenResponse {}\n\nexport async function requestStsToken(\n auth: Auth,\n refreshToken: string\n): Promise {\n const response =\n await _performFetchWithErrorHandling(\n auth,\n {},\n async () => {\n const body = querystring({\n 'grant_type': 'refresh_token',\n 'refresh_token': refreshToken\n }).slice(1);\n const { tokenApiHost, apiKey } = auth.config;\n const url = _getFinalTarget(\n auth,\n tokenApiHost,\n Endpoint.TOKEN,\n `key=${apiKey}`\n );\n\n const headers = await (auth as AuthInternal)._getAdditionalHeaders();\n headers[HttpHeader.CONTENT_TYPE] = 'application/x-www-form-urlencoded';\n\n return FetchProvider.fetch()(url, {\n method: HttpMethod.POST,\n headers,\n body\n });\n }\n );\n\n // The response comes back in snake_case. Convert to camel:\n return {\n accessToken: response.access_token,\n expiresIn: response.expires_in,\n refreshToken: response.refresh_token\n };\n}\n\nexport async function revokeToken(\n auth: Auth,\n request: RevokeTokenRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.REVOKE_TOKEN,\n _addTidIfNecessary(auth, request)\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { requestStsToken } from '../../api/authentication/token';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert, debugFail } from '../util/assert';\nimport { _tokenExpiresIn } from './id_token_result';\n\n/**\n * The number of milliseconds before the official expiration time of a token\n * to refresh that token, to provide a buffer for RPCs to complete.\n */\nexport const enum Buffer {\n TOKEN_REFRESH = 30_000\n}\n\n/**\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport class StsTokenManager {\n refreshToken: string | null = null;\n accessToken: string | null = null;\n expirationTime: number | null = null;\n\n get isExpired(): boolean {\n return (\n !this.expirationTime ||\n Date.now() > this.expirationTime - Buffer.TOKEN_REFRESH\n );\n }\n\n updateFromServerResponse(\n response: IdTokenResponse | FinalizeMfaResponse\n ): void {\n _assert(response.idToken, AuthErrorCode.INTERNAL_ERROR);\n _assert(\n typeof response.idToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof response.refreshToken !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n const expiresIn =\n 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\n ? Number(response.expiresIn)\n : _tokenExpiresIn(response.idToken);\n this.updateTokensAndExpiration(\n response.idToken,\n response.refreshToken,\n expiresIn\n );\n }\n\n async getToken(\n auth: AuthInternal,\n forceRefresh = false\n ): Promise {\n _assert(\n !this.accessToken || this.refreshToken,\n auth,\n AuthErrorCode.TOKEN_EXPIRED\n );\n\n if (!forceRefresh && this.accessToken && !this.isExpired) {\n return this.accessToken;\n }\n\n if (this.refreshToken) {\n await this.refresh(auth, this.refreshToken!);\n return this.accessToken;\n }\n\n return null;\n }\n\n clearRefreshToken(): void {\n this.refreshToken = null;\n }\n\n private async refresh(auth: AuthInternal, oldToken: string): Promise {\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(\n auth,\n oldToken\n );\n this.updateTokensAndExpiration(\n accessToken,\n refreshToken,\n Number(expiresIn)\n );\n }\n\n private updateTokensAndExpiration(\n accessToken: string,\n refreshToken: string,\n expiresInSec: number\n ): void {\n this.refreshToken = refreshToken || null;\n this.accessToken = accessToken || null;\n this.expirationTime = Date.now() + expiresInSec * 1000;\n }\n\n static fromJSON(appName: string, object: PersistedBlob): StsTokenManager {\n const { refreshToken, accessToken, expirationTime } = object;\n\n const manager = new StsTokenManager();\n if (refreshToken) {\n _assert(typeof refreshToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.refreshToken = refreshToken;\n }\n if (accessToken) {\n _assert(typeof accessToken === 'string', AuthErrorCode.INTERNAL_ERROR, {\n appName\n });\n manager.accessToken = accessToken;\n }\n if (expirationTime) {\n _assert(\n typeof expirationTime === 'number',\n AuthErrorCode.INTERNAL_ERROR,\n {\n appName\n }\n );\n manager.expirationTime = expirationTime;\n }\n return manager;\n }\n\n toJSON(): object {\n return {\n refreshToken: this.refreshToken,\n accessToken: this.accessToken,\n expirationTime: this.expirationTime\n };\n }\n\n _assign(stsTokenManager: StsTokenManager): void {\n this.accessToken = stsTokenManager.accessToken;\n this.refreshToken = stsTokenManager.refreshToken;\n this.expirationTime = stsTokenManager.expirationTime;\n }\n\n _clone(): StsTokenManager {\n return Object.assign(new StsTokenManager(), this.toJSON());\n }\n\n _performRefresh(): never {\n return debugFail('not implemented');\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdTokenResult } from '../../model/public_types';\nimport { NextFn } from '@firebase/util';\n\nimport {\n APIUserInfo,\n deleteAccount\n} from '../../api/account_management/account';\nimport { FinalizeMfaResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport {\n MutableUserInfo,\n UserInternal,\n UserParameters\n} from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { PersistedBlob } from '../persistence';\nimport { _assert } from '../util/assert';\nimport { getIdTokenResult } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { ProactiveRefresh } from './proactive_refresh';\nimport { _reloadWithoutSaving, reload } from './reload';\nimport { StsTokenManager } from './token_manager';\nimport { UserMetadata } from './user_metadata';\nimport { ProviderId } from '../../model/enums';\n\nfunction assertStringOrUndefined(\n assertion: unknown,\n appName: string\n): asserts assertion is string | undefined {\n _assert(\n typeof assertion === 'string' || typeof assertion === 'undefined',\n AuthErrorCode.INTERNAL_ERROR,\n { appName }\n );\n}\n\nexport class UserImpl implements UserInternal {\n // For the user object, provider is always Firebase.\n readonly providerId = ProviderId.FIREBASE;\n stsTokenManager: StsTokenManager;\n // Last known accessToken so we know when it changes\n private accessToken: string | null;\n\n uid: string;\n auth: AuthInternal;\n emailVerified: boolean;\n isAnonymous: boolean;\n tenantId: string | null;\n readonly metadata: UserMetadata;\n providerData: MutableUserInfo[];\n\n // Optional fields from UserInfo\n displayName: string | null;\n email: string | null;\n phoneNumber: string | null;\n photoURL: string | null;\n\n _redirectEventId?: string;\n private readonly proactiveRefresh = new ProactiveRefresh(this);\n\n constructor({ uid, auth, stsTokenManager, ...opt }: UserParameters) {\n this.uid = uid;\n this.auth = auth;\n this.stsTokenManager = stsTokenManager;\n this.accessToken = stsTokenManager.accessToken;\n this.displayName = opt.displayName || null;\n this.email = opt.email || null;\n this.emailVerified = opt.emailVerified || false;\n this.phoneNumber = opt.phoneNumber || null;\n this.photoURL = opt.photoURL || null;\n this.isAnonymous = opt.isAnonymous || false;\n this.tenantId = opt.tenantId || null;\n this.providerData = opt.providerData ? [...opt.providerData] : [];\n this.metadata = new UserMetadata(\n opt.createdAt || undefined,\n opt.lastLoginAt || undefined\n );\n }\n\n async getIdToken(forceRefresh?: boolean): Promise {\n const accessToken = await _logoutIfInvalidated(\n this,\n this.stsTokenManager.getToken(this.auth, forceRefresh)\n );\n _assert(accessToken, this.auth, AuthErrorCode.INTERNAL_ERROR);\n\n if (this.accessToken !== accessToken) {\n this.accessToken = accessToken;\n await this.auth._persistUserIfCurrent(this);\n this.auth._notifyListenersIfCurrent(this);\n }\n\n return accessToken;\n }\n\n getIdTokenResult(forceRefresh?: boolean): Promise {\n return getIdTokenResult(this, forceRefresh);\n }\n\n reload(): Promise {\n return reload(this);\n }\n\n private reloadUserInfo: APIUserInfo | null = null;\n private reloadListener: NextFn | null = null;\n\n _assign(user: UserInternal): void {\n if (this === user) {\n return;\n }\n _assert(this.uid === user.uid, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.displayName = user.displayName;\n this.photoURL = user.photoURL;\n this.email = user.email;\n this.emailVerified = user.emailVerified;\n this.phoneNumber = user.phoneNumber;\n this.isAnonymous = user.isAnonymous;\n this.tenantId = user.tenantId;\n this.providerData = user.providerData.map(userInfo => ({ ...userInfo }));\n this.metadata._copy(user.metadata);\n this.stsTokenManager._assign(user.stsTokenManager);\n }\n\n _clone(auth: AuthInternal): UserInternal {\n const newUser = new UserImpl({\n ...this,\n auth,\n stsTokenManager: this.stsTokenManager._clone()\n });\n newUser.metadata._copy(this.metadata);\n return newUser;\n }\n\n _onReload(callback: NextFn): void {\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\n _assert(!this.reloadListener, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.reloadListener = callback;\n if (this.reloadUserInfo) {\n this._notifyReloadListener(this.reloadUserInfo);\n this.reloadUserInfo = null;\n }\n }\n\n _notifyReloadListener(userInfo: APIUserInfo): void {\n if (this.reloadListener) {\n this.reloadListener(userInfo);\n } else {\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\n this.reloadUserInfo = userInfo;\n }\n }\n\n _startProactiveRefresh(): void {\n this.proactiveRefresh._start();\n }\n\n _stopProactiveRefresh(): void {\n this.proactiveRefresh._stop();\n }\n\n async _updateTokensIfNecessary(\n response: IdTokenResponse | FinalizeMfaResponse,\n reload = false\n ): Promise {\n let tokensRefreshed = false;\n if (\n response.idToken &&\n response.idToken !== this.stsTokenManager.accessToken\n ) {\n this.stsTokenManager.updateFromServerResponse(response);\n tokensRefreshed = true;\n }\n\n if (reload) {\n await _reloadWithoutSaving(this);\n }\n\n await this.auth._persistUserIfCurrent(this);\n if (tokensRefreshed) {\n this.auth._notifyListenersIfCurrent(this);\n }\n }\n\n async delete(): Promise {\n const idToken = await this.getIdToken();\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\n this.stsTokenManager.clearRefreshToken();\n\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\n // cancels pending actions...\n\n return this.auth.signOut();\n }\n\n toJSON(): PersistedBlob {\n return {\n uid: this.uid,\n email: this.email || undefined,\n emailVerified: this.emailVerified,\n displayName: this.displayName || undefined,\n isAnonymous: this.isAnonymous,\n photoURL: this.photoURL || undefined,\n phoneNumber: this.phoneNumber || undefined,\n tenantId: this.tenantId || undefined,\n providerData: this.providerData.map(userInfo => ({ ...userInfo })),\n stsTokenManager: this.stsTokenManager.toJSON(),\n // Redirect event ID must be maintained in case there is a pending\n // redirect event.\n _redirectEventId: this._redirectEventId,\n ...this.metadata.toJSON(),\n\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\n apiKey: this.auth.config.apiKey,\n appName: this.auth.name\n // Missing authDomain will be tolerated by the legacy SDK.\n // stsTokenManager.apiKey isn't actually required (despite the legacy SDK persisting it).\n };\n }\n\n get refreshToken(): string {\n return this.stsTokenManager.refreshToken || '';\n }\n\n static _fromJSON(auth: AuthInternal, object: PersistedBlob): UserInternal {\n const displayName = object.displayName ?? undefined;\n const email = object.email ?? undefined;\n const phoneNumber = object.phoneNumber ?? undefined;\n const photoURL = object.photoURL ?? undefined;\n const tenantId = object.tenantId ?? undefined;\n const _redirectEventId = object._redirectEventId ?? undefined;\n const createdAt = object.createdAt ?? undefined;\n const lastLoginAt = object.lastLoginAt ?? undefined;\n const {\n uid,\n emailVerified,\n isAnonymous,\n providerData,\n stsTokenManager: plainObjectTokenManager\n } = object;\n\n _assert(uid && plainObjectTokenManager, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const stsTokenManager = StsTokenManager.fromJSON(\n this.name,\n plainObjectTokenManager as PersistedBlob\n );\n\n _assert(typeof uid === 'string', auth, AuthErrorCode.INTERNAL_ERROR);\n assertStringOrUndefined(displayName, auth.name);\n assertStringOrUndefined(email, auth.name);\n _assert(\n typeof emailVerified === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n _assert(\n typeof isAnonymous === 'boolean',\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n assertStringOrUndefined(phoneNumber, auth.name);\n assertStringOrUndefined(photoURL, auth.name);\n assertStringOrUndefined(tenantId, auth.name);\n assertStringOrUndefined(_redirectEventId, auth.name);\n assertStringOrUndefined(createdAt, auth.name);\n assertStringOrUndefined(lastLoginAt, auth.name);\n const user = new UserImpl({\n uid,\n auth,\n email,\n emailVerified,\n displayName,\n isAnonymous,\n photoURL,\n phoneNumber,\n tenantId,\n stsTokenManager,\n createdAt,\n lastLoginAt\n });\n\n if (providerData && Array.isArray(providerData)) {\n user.providerData = providerData.map(userInfo => ({ ...userInfo }));\n }\n\n if (_redirectEventId) {\n user._redirectEventId = _redirectEventId;\n }\n\n return user;\n }\n\n /**\n * Initialize a User from an idToken server response\n * @param auth\n * @param idTokenResponse\n */\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise {\n const stsTokenManager = new StsTokenManager();\n stsTokenManager.updateFromServerResponse(idTokenResponse);\n\n // Initialize the Firebase Auth user.\n const user = new UserImpl({\n uid: idTokenResponse.localId,\n auth,\n stsTokenManager,\n isAnonymous\n });\n\n // Updates the user info and data and resolves with a user instance.\n await _reloadWithoutSaving(user);\n return user;\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\n/**\n * Our API has a lot of one-off constants that are used to do things.\n * Unfortunately we can't export these as classes instantiated directly since\n * the constructor may side effect and therefore can't be proven to be safely\n * culled. Instead, we export these classes themselves as a lowerCamelCase\n * constant, and instantiate them under the hood.\n */\nexport interface SingletonInstantiator {\n new (): T;\n}\n\nconst instanceCache: Map = new Map();\n\nexport function _getInstance(cls: unknown): T {\n debugAssert(cls instanceof Function, 'Expected a class definition');\n let instance = instanceCache.get(cls) as T | undefined;\n\n if (instance) {\n debugAssert(\n instance instanceof cls,\n 'Instance stored in cache mismatched with class'\n );\n return instance;\n }\n\n instance = new (cls as SingletonInstantiator)();\n instanceCache.set(cls, instance);\n return instance;\n}\n\nexport function _clearInstanceMap(): void {\n instanceCache.clear();\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../persistence';\n\nexport class InMemoryPersistence implements PersistenceInternal {\n static type: 'NONE' = 'NONE';\n readonly type = PersistenceType.NONE;\n storage: Record = {};\n\n async _isAvailable(): Promise {\n return true;\n }\n\n async _set(key: string, value: PersistenceValue): Promise {\n this.storage[key] = value;\n }\n\n async _get(key: string): Promise {\n const value = this.storage[key];\n return value === undefined ? null : (value as T);\n }\n\n async _remove(key: string): Promise {\n delete this.storage[key];\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type 'NONE'.\n *\n * @public\n */\nexport const inMemoryPersistence: Persistence = InMemoryPersistence;\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { PersistedBlob, PersistenceInternal } from '../persistence';\nimport { UserImpl } from '../user/user_impl';\nimport { _getInstance } from '../util/instantiator';\nimport { inMemoryPersistence } from './in_memory';\n\nexport const enum KeyName {\n AUTH_USER = 'authUser',\n AUTH_EVENT = 'authEvent',\n REDIRECT_USER = 'redirectUser',\n PERSISTENCE_USER = 'persistence'\n}\nexport const enum Namespace {\n PERSISTENCE = 'firebase'\n}\n\nexport function _persistenceKeyName(\n key: string,\n apiKey: ApiKey,\n appName: AppName\n): string {\n return `${Namespace.PERSISTENCE}:${key}:${apiKey}:${appName}`;\n}\n\nexport class PersistenceUserManager {\n private readonly fullUserKey: string;\n private readonly fullPersistenceKey: string;\n private readonly boundEventHandler: () => void;\n\n private constructor(\n public persistence: PersistenceInternal,\n private readonly auth: AuthInternal,\n private readonly userKey: string\n ) {\n const { config, name } = this.auth;\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\n this.fullPersistenceKey = _persistenceKeyName(\n KeyName.PERSISTENCE_USER,\n config.apiKey,\n name\n );\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\n }\n\n setCurrentUser(user: UserInternal): Promise {\n return this.persistence._set(this.fullUserKey, user.toJSON());\n }\n\n async getCurrentUser(): Promise {\n const blob = await this.persistence._get(this.fullUserKey);\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\n }\n\n removeCurrentUser(): Promise {\n return this.persistence._remove(this.fullUserKey);\n }\n\n savePersistenceForRedirect(): Promise {\n return this.persistence._set(\n this.fullPersistenceKey,\n this.persistence.type\n );\n }\n\n async setPersistence(newPersistence: PersistenceInternal): Promise {\n if (this.persistence === newPersistence) {\n return;\n }\n\n const currentUser = await this.getCurrentUser();\n await this.removeCurrentUser();\n\n this.persistence = newPersistence;\n\n if (currentUser) {\n return this.setCurrentUser(currentUser);\n }\n }\n\n delete(): void {\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\n }\n\n static async create(\n auth: AuthInternal,\n persistenceHierarchy: PersistenceInternal[],\n userKey = KeyName.AUTH_USER\n ): Promise {\n if (!persistenceHierarchy.length) {\n return new PersistenceUserManager(\n _getInstance(inMemoryPersistence),\n auth,\n userKey\n );\n }\n\n // Eliminate any persistences that are not available\n const availablePersistences = (\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (await persistence._isAvailable()) {\n return persistence;\n }\n return undefined;\n })\n )\n ).filter(persistence => persistence) as PersistenceInternal[];\n\n // Fall back to the first persistence listed, or in memory if none available\n let selectedPersistence =\n availablePersistences[0] ||\n _getInstance(inMemoryPersistence);\n\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\n\n // Pull out the existing user, setting the chosen persistence to that\n // persistence if the user exists.\n let userToMigrate: UserInternal | null = null;\n // Note, here we check for a user in _all_ persistences, not just the\n // ones deemed available. If we can migrate a user out of a broken\n // persistence, we will (but only if that persistence supports migration).\n for (const persistence of persistenceHierarchy) {\n try {\n const blob = await persistence._get(key);\n if (blob) {\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\n if (persistence !== selectedPersistence) {\n userToMigrate = user;\n }\n selectedPersistence = persistence;\n break;\n }\n } catch {}\n }\n\n // If we find the user in a persistence that does support migration, use\n // that migration path (of only persistences that support migration)\n const migrationHierarchy = availablePersistences.filter(\n p => p._shouldAllowMigration\n );\n\n // If the persistence does _not_ allow migration, just finish off here\n if (\n !selectedPersistence._shouldAllowMigration ||\n !migrationHierarchy.length\n ) {\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n\n selectedPersistence = migrationHierarchy[0];\n if (userToMigrate) {\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\n // we'll just let it bubble to surface the error.\n await selectedPersistence._set(key, userToMigrate.toJSON());\n }\n\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\n await Promise.all(\n persistenceHierarchy.map(async persistence => {\n if (persistence !== selectedPersistence) {\n try {\n await persistence._remove(key);\n } catch {}\n }\n })\n );\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isIE, getUA } from '@firebase/util';\n\ninterface NavigatorStandalone extends Navigator {\n standalone?: unknown;\n}\n\ninterface Document {\n documentMode?: number;\n}\n\n/**\n * Enums for Browser name.\n */\nexport const enum BrowserName {\n ANDROID = 'Android',\n BLACKBERRY = 'Blackberry',\n EDGE = 'Edge',\n FIREFOX = 'Firefox',\n IE = 'IE',\n IEMOBILE = 'IEMobile',\n OPERA = 'Opera',\n OTHER = 'Other',\n CHROME = 'Chrome',\n SAFARI = 'Safari',\n SILK = 'Silk',\n WEBOS = 'Webos'\n}\n\n/**\n * Determine the browser for the purposes of reporting usage to the API\n */\nexport function _getBrowserName(userAgent: string): BrowserName | string {\n const ua = userAgent.toLowerCase();\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\n return BrowserName.OPERA;\n } else if (_isIEMobile(ua)) {\n // Windows phone IEMobile browser.\n return BrowserName.IEMOBILE;\n } else if (ua.includes('msie') || ua.includes('trident/')) {\n return BrowserName.IE;\n } else if (ua.includes('edge/')) {\n return BrowserName.EDGE;\n } else if (_isFirefox(ua)) {\n return BrowserName.FIREFOX;\n } else if (ua.includes('silk/')) {\n return BrowserName.SILK;\n } else if (_isBlackBerry(ua)) {\n // Blackberry browser.\n return BrowserName.BLACKBERRY;\n } else if (_isWebOS(ua)) {\n // WebOS default browser.\n return BrowserName.WEBOS;\n } else if (_isSafari(ua)) {\n return BrowserName.SAFARI;\n } else if (\n (ua.includes('chrome/') || _isChromeIOS(ua)) &&\n !ua.includes('edge/')\n ) {\n return BrowserName.CHROME;\n } else if (_isAndroid(ua)) {\n // Android stock browser.\n return BrowserName.ANDROID;\n } else {\n // Most modern browsers have name/version at end of user agent string.\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\n const matches = userAgent.match(re);\n if (matches?.length === 2) {\n return matches[1];\n }\n }\n return BrowserName.OTHER;\n}\n\nexport function _isFirefox(ua = getUA()): boolean {\n return /firefox\\//i.test(ua);\n}\n\nexport function _isSafari(userAgent = getUA()): boolean {\n const ua = userAgent.toLowerCase();\n return (\n ua.includes('safari/') &&\n !ua.includes('chrome/') &&\n !ua.includes('crios/') &&\n !ua.includes('android')\n );\n}\n\nexport function _isChromeIOS(ua = getUA()): boolean {\n return /crios\\//i.test(ua);\n}\n\nexport function _isIEMobile(ua = getUA()): boolean {\n return /iemobile/i.test(ua);\n}\n\nexport function _isAndroid(ua = getUA()): boolean {\n return /android/i.test(ua);\n}\n\nexport function _isBlackBerry(ua = getUA()): boolean {\n return /blackberry/i.test(ua);\n}\n\nexport function _isWebOS(ua = getUA()): boolean {\n return /webos/i.test(ua);\n}\n\nexport function _isIOS(ua = getUA()): boolean {\n return (\n /iphone|ipad|ipod/i.test(ua) ||\n (/macintosh/i.test(ua) && /mobile/i.test(ua))\n );\n}\n\nexport function _isIOS7Or8(ua = getUA()): boolean {\n return (\n /(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua)\n );\n}\n\nexport function _isIOSStandalone(ua = getUA()): boolean {\n return _isIOS(ua) && !!(window.navigator as NavigatorStandalone)?.standalone;\n}\n\nexport function _isIE10(): boolean {\n return isIE() && (document as Document).documentMode === 10;\n}\n\nexport function _isMobileBrowser(ua: string = getUA()): boolean {\n // TODO: implement getBrowserName equivalent for OS.\n return (\n _isIOS(ua) ||\n _isAndroid(ua) ||\n _isWebOS(ua) ||\n _isBlackBerry(ua) ||\n /windows phone/i.test(ua) ||\n _isIEMobile(ua)\n );\n}\n\nexport function _isIframe(): boolean {\n try {\n // Check that the current window is not the top window.\n // If so, return true.\n return !!(window && window !== window.top);\n } catch (e) {\n return false;\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { _getBrowserName } from './browser';\nimport { getUA } from '@firebase/util';\n\nexport const enum ClientImplementation {\n CORE = 'JsCore'\n}\n\n/**\n * @internal\n */\nexport const enum ClientPlatform {\n BROWSER = 'Browser',\n NODE = 'Node',\n REACT_NATIVE = 'ReactNative',\n CORDOVA = 'Cordova',\n WORKER = 'Worker'\n}\n\n/*\n * Determine the SDK version string\n */\nexport function _getClientVersion(\n clientPlatform: ClientPlatform,\n frameworks: readonly string[] = []\n): string {\n let reportedPlatform: string;\n switch (clientPlatform) {\n case ClientPlatform.BROWSER:\n // In a browser environment, report the browser name.\n reportedPlatform = _getBrowserName(getUA());\n break;\n case ClientPlatform.WORKER:\n // Technically a worker runs from a browser but we need to differentiate a\n // worker from a browser.\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\n break;\n default:\n reportedPlatform = clientPlatform;\n }\n const reportedFrameworks = frameworks.length\n ? frameworks.join(',')\n : 'FirebaseCore-web'; /* default value if no other framework is used */\n return `${reportedPlatform}/${ClientImplementation.CORE}/${SDK_VERSION}/${reportedFrameworks}`;\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport { Unsubscribe, User } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\n\ninterface MiddlewareEntry {\n (user: User | null): Promise;\n onAbort?: () => void;\n}\n\nexport class AuthMiddlewareQueue {\n private readonly queue: MiddlewareEntry[] = [];\n\n constructor(private readonly auth: AuthInternal) {}\n\n pushCallback(\n callback: (user: User | null) => void | Promise,\n onAbort?: () => void\n ): Unsubscribe {\n // The callback could be sync or async. Wrap it into a\n // function that is always async.\n const wrappedCallback: MiddlewareEntry = (\n user: User | null\n ): Promise =>\n new Promise((resolve, reject) => {\n try {\n const result = callback(user);\n // Either resolve with existing promise or wrap a non-promise\n // return value into a promise.\n resolve(result);\n } catch (e) {\n // Sync callback throws.\n reject(e);\n }\n });\n // Attach the onAbort if present\n wrappedCallback.onAbort = onAbort;\n this.queue.push(wrappedCallback);\n\n const index = this.queue.length - 1;\n return () => {\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\n // indexing of other elements.\n this.queue[index] = () => Promise.resolve();\n };\n }\n\n async runMiddleware(nextUser: User | null): Promise {\n if (this.auth.currentUser === nextUser) {\n return;\n }\n\n // While running the middleware, build a temporary stack of onAbort\n // callbacks to call if one middleware callback rejects.\n\n const onAbortStack: Array<() => void> = [];\n try {\n for (const beforeStateCallback of this.queue) {\n await beforeStateCallback(nextUser);\n\n // Only push the onAbort if the callback succeeds\n if (beforeStateCallback.onAbort) {\n onAbortStack.push(beforeStateCallback.onAbort);\n }\n }\n } catch (e) {\n // Run all onAbort, with separate try/catch to ignore any errors and\n // continue\n onAbortStack.reverse();\n for (const onAbort of onAbortStack) {\n try {\n onAbort();\n } catch (_) {\n /* swallow error */\n }\n }\n\n throw this.auth._errorFactory.create(AuthErrorCode.LOGIN_BLOCKED, {\n originalMessage: (e as Error)?.message\n });\n }\n }\n}\n", "/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\n/**\n * Request object for fetching the password policy.\n */\nexport interface GetPasswordPolicyRequest {\n tenantId?: string;\n}\n\n/**\n * Response object for fetching the password policy.\n */\nexport interface GetPasswordPolicyResponse {\n customStrengthOptions: {\n minPasswordLength?: number;\n maxPasswordLength?: number;\n containsLowercaseCharacter?: boolean;\n containsUppercaseCharacter?: boolean;\n containsNumericCharacter?: boolean;\n containsNonAlphanumericCharacter?: boolean;\n };\n allowedNonAlphanumericCharacters?: string[];\n enforcementState: string;\n forceUpgradeOnSignin?: boolean;\n schemaVersion: number;\n}\n\n/**\n * Fetches the password policy for the currently set tenant or the project if no tenant is set.\n *\n * @param auth Auth object.\n * @param request Password policy request.\n * @returns Password policy response.\n */\nexport async function _getPasswordPolicy(\n auth: Auth,\n request: GetPasswordPolicyRequest = {}\n): Promise {\n return _performApiRequest<\n GetPasswordPolicyRequest,\n GetPasswordPolicyResponse\n >(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PASSWORD_POLICY,\n _addTidIfNecessary(auth, request)\n );\n}\n", "/**\n * @license\n * Copyright 2023 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetPasswordPolicyResponse } from '../../api/password_policy/get_password_policy';\nimport {\n PasswordPolicyCustomStrengthOptions,\n PasswordPolicyInternal,\n PasswordValidationStatusInternal\n} from '../../model/password_policy';\nimport { PasswordValidationStatus } from '../../model/public_types';\n\n// Minimum min password length enforced by the backend, even if no minimum length is set.\nconst MINIMUM_MIN_PASSWORD_LENGTH = 6;\n\n/**\n * Stores password policy requirements and provides password validation against the policy.\n *\n * @internal\n */\nexport class PasswordPolicyImpl implements PasswordPolicyInternal {\n readonly customStrengthOptions: PasswordPolicyCustomStrengthOptions;\n readonly allowedNonAlphanumericCharacters: string;\n readonly enforcementState: string;\n readonly forceUpgradeOnSignin: boolean;\n readonly schemaVersion: number;\n\n constructor(response: GetPasswordPolicyResponse) {\n // Only include custom strength options defined in the response.\n const responseOptions = response.customStrengthOptions;\n this.customStrengthOptions = {};\n // TODO: Remove once the backend is updated to include the minimum min password length instead of undefined when there is no minimum length set.\n this.customStrengthOptions.minPasswordLength =\n responseOptions.minPasswordLength ?? MINIMUM_MIN_PASSWORD_LENGTH;\n if (responseOptions.maxPasswordLength) {\n this.customStrengthOptions.maxPasswordLength =\n responseOptions.maxPasswordLength;\n }\n if (responseOptions.containsLowercaseCharacter !== undefined) {\n this.customStrengthOptions.containsLowercaseLetter =\n responseOptions.containsLowercaseCharacter;\n }\n if (responseOptions.containsUppercaseCharacter !== undefined) {\n this.customStrengthOptions.containsUppercaseLetter =\n responseOptions.containsUppercaseCharacter;\n }\n if (responseOptions.containsNumericCharacter !== undefined) {\n this.customStrengthOptions.containsNumericCharacter =\n responseOptions.containsNumericCharacter;\n }\n if (responseOptions.containsNonAlphanumericCharacter !== undefined) {\n this.customStrengthOptions.containsNonAlphanumericCharacter =\n responseOptions.containsNonAlphanumericCharacter;\n }\n\n this.enforcementState = response.enforcementState;\n if (this.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED') {\n this.enforcementState = 'OFF';\n }\n\n // Use an empty string if no non-alphanumeric characters are specified in the response.\n this.allowedNonAlphanumericCharacters =\n response.allowedNonAlphanumericCharacters?.join('') ?? '';\n\n this.forceUpgradeOnSignin = response.forceUpgradeOnSignin ?? false;\n this.schemaVersion = response.schemaVersion;\n }\n\n validatePassword(password: string): PasswordValidationStatus {\n const status: PasswordValidationStatusInternal = {\n isValid: true,\n passwordPolicy: this\n };\n\n // Check the password length and character options.\n this.validatePasswordLengthOptions(password, status);\n this.validatePasswordCharacterOptions(password, status);\n\n // Combine the status into single isValid property.\n status.isValid &&= status.meetsMinPasswordLength ?? true;\n status.isValid &&= status.meetsMaxPasswordLength ?? true;\n status.isValid &&= status.containsLowercaseLetter ?? true;\n status.isValid &&= status.containsUppercaseLetter ?? true;\n status.isValid &&= status.containsNumericCharacter ?? true;\n status.isValid &&= status.containsNonAlphanumericCharacter ?? true;\n\n return status;\n }\n\n /**\n * Validates that the password meets the length options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordLengthOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n const minPasswordLength = this.customStrengthOptions.minPasswordLength;\n const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;\n if (minPasswordLength) {\n status.meetsMinPasswordLength = password.length >= minPasswordLength;\n }\n if (maxPasswordLength) {\n status.meetsMaxPasswordLength = password.length <= maxPasswordLength;\n }\n }\n\n /**\n * Validates that the password meets the character options for the policy.\n *\n * @param password Password to validate.\n * @param status Validation status.\n */\n private validatePasswordCharacterOptions(\n password: string,\n status: PasswordValidationStatusInternal\n ): void {\n // Assign statuses for requirements even if the password is an empty string.\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ false,\n /* containsUppercaseCharacter= */ false,\n /* containsNumericCharacter= */ false,\n /* containsNonAlphanumericCharacter= */ false\n );\n\n let passwordChar;\n for (let i = 0; i < password.length; i++) {\n passwordChar = password.charAt(i);\n this.updatePasswordCharacterOptionsStatuses(\n status,\n /* containsLowercaseCharacter= */ passwordChar >= 'a' &&\n passwordChar <= 'z',\n /* containsUppercaseCharacter= */ passwordChar >= 'A' &&\n passwordChar <= 'Z',\n /* containsNumericCharacter= */ passwordChar >= '0' &&\n passwordChar <= '9',\n /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(\n passwordChar\n )\n );\n }\n }\n\n /**\n * Updates the running validation status with the statuses for the character options.\n * Expected to be called each time a character is processed to update each option status\n * based on the current character.\n *\n * @param status Validation status.\n * @param containsLowercaseCharacter Whether the character is a lowercase letter.\n * @param containsUppercaseCharacter Whether the character is an uppercase letter.\n * @param containsNumericCharacter Whether the character is a numeric character.\n * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.\n */\n private updatePasswordCharacterOptionsStatuses(\n status: PasswordValidationStatusInternal,\n containsLowercaseCharacter: boolean,\n containsUppercaseCharacter: boolean,\n containsNumericCharacter: boolean,\n containsNonAlphanumericCharacter: boolean\n ): void {\n if (this.customStrengthOptions.containsLowercaseLetter) {\n status.containsLowercaseLetter ||= containsLowercaseCharacter;\n }\n if (this.customStrengthOptions.containsUppercaseLetter) {\n status.containsUppercaseLetter ||= containsUppercaseCharacter;\n }\n if (this.customStrengthOptions.containsNumericCharacter) {\n status.containsNumericCharacter ||= containsNumericCharacter;\n }\n if (this.customStrengthOptions.containsNonAlphanumericCharacter) {\n status.containsNonAlphanumericCharacter ||=\n containsNonAlphanumericCharacter;\n }\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _FirebaseService, FirebaseApp } from '@firebase/app';\nimport { Provider } from '@firebase/component';\nimport { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';\nimport {\n Auth,\n AuthErrorMap,\n AuthSettings,\n EmulatorConfig,\n NextOrObserver,\n Persistence,\n PopupRedirectResolver,\n User,\n UserCredential,\n CompleteFn,\n ErrorFn,\n NextFn,\n Unsubscribe,\n PasswordValidationStatus\n} from '../../model/public_types';\nimport {\n createSubscribe,\n ErrorFactory,\n FirebaseError,\n getModularInstance,\n Observer,\n Subscribe\n} from '@firebase/util';\n\nimport { AuthInternal, ConfigInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport {\n AuthErrorCode,\n AuthErrorParams,\n ErrorMapRetriever,\n _DEFAULT_AUTH_ERROR_FACTORY\n} from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport {\n KeyName,\n PersistenceUserManager\n} from '../persistence/persistence_user_manager';\nimport { _reloadWithoutSaving } from '../user/reload';\nimport { _assert } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { _getUserLanguage } from '../util/navigator';\nimport { _getClientVersion } from '../util/version';\nimport { HttpHeader } from '../../api';\nimport {\n RevokeTokenRequest,\n TokenType,\n revokeToken\n} from '../../api/authentication/token';\nimport { AuthMiddlewareQueue } from './middleware';\nimport { RecaptchaConfig } from '../../platform_browser/recaptcha/recaptcha';\nimport { _logWarn } from '../util/log';\nimport { _getPasswordPolicy } from '../../api/password_policy/get_password_policy';\nimport { PasswordPolicyInternal } from '../../model/password_policy';\nimport { PasswordPolicyImpl } from './password_policy_impl';\n\ninterface AsyncAction {\n (): Promise;\n}\n\nexport const enum DefaultConfig {\n TOKEN_API_HOST = 'securetoken.googleapis.com',\n API_HOST = 'identitytoolkit.googleapis.com',\n API_SCHEME = 'https'\n}\n\nexport class AuthImpl implements AuthInternal, _FirebaseService {\n currentUser: User | null = null;\n emulatorConfig: EmulatorConfig | null = null;\n private operations = Promise.resolve();\n private persistenceManager?: PersistenceUserManager;\n private redirectPersistenceManager?: PersistenceUserManager;\n private authStateSubscription = new Subscription(this);\n private idTokenSubscription = new Subscription(this);\n private readonly beforeStateQueue = new AuthMiddlewareQueue(this);\n private redirectUser: UserInternal | null = null;\n private isProactiveRefreshEnabled = false;\n private readonly EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION: number = 1;\n\n // Any network calls will set this to true and prevent subsequent emulator\n // initialization\n _canInitEmulator = true;\n _isInitialized = false;\n _deleted = false;\n _initializationPromise: Promise | null = null;\n _popupRedirectResolver: PopupRedirectResolverInternal | null = null;\n _errorFactory: ErrorFactory =\n _DEFAULT_AUTH_ERROR_FACTORY;\n _agentRecaptchaConfig: RecaptchaConfig | null = null;\n _tenantRecaptchaConfigs: Record = {};\n _projectPasswordPolicy: PasswordPolicyInternal | null = null;\n _tenantPasswordPolicies: Record = {};\n readonly name: string;\n\n // Tracks the last notified UID for state change listeners to prevent\n // repeated calls to the callbacks. Undefined means it's never been\n // called, whereas null means it's been called with a signed out user\n private lastNotifiedUid: string | null | undefined = undefined;\n\n languageCode: string | null = null;\n tenantId: string | null = null;\n settings: AuthSettings = { appVerificationDisabledForTesting: false };\n\n constructor(\n public readonly app: FirebaseApp,\n private readonly heartbeatServiceProvider: Provider<'heartbeat'>,\n private readonly appCheckServiceProvider: Provider,\n public readonly config: ConfigInternal\n ) {\n this.name = app.name;\n this.clientVersion = config.sdkClientVersion;\n }\n\n _initializeWithPersistence(\n persistenceHierarchy: PersistenceInternal[],\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n if (popupRedirectResolver) {\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\n }\n\n // Have to check for app deletion throughout initialization (after each\n // promise resolution)\n this._initializationPromise = this.queue(async () => {\n if (this._deleted) {\n return;\n }\n\n this.persistenceManager = await PersistenceUserManager.create(\n this,\n persistenceHierarchy\n );\n\n if (this._deleted) {\n return;\n }\n\n // Initialize the resolver early if necessary (only applicable to web:\n // this will cause the iframe to load immediately in certain cases)\n if (this._popupRedirectResolver?._shouldInitProactively) {\n // If this fails, don't halt auth loading\n try {\n await this._popupRedirectResolver._initialize(this);\n } catch (e) {\n /* Ignore the error */\n }\n }\n\n await this.initializeCurrentUser(popupRedirectResolver);\n this.lastNotifiedUid = this.currentUser?.uid || null;\n\n if (this._deleted) {\n return;\n }\n\n this._isInitialized = true;\n });\n\n return this._initializationPromise;\n }\n\n /**\n * If the persistence is changed in another window, the user manager will let us know\n */\n async _onStorageEvent(): Promise {\n if (this._deleted) {\n return;\n }\n\n const user = await this.assertedPersistence.getCurrentUser();\n\n if (!this.currentUser && !user) {\n // No change, do nothing (was signed out and remained signed out).\n return;\n }\n\n // If the same user is to be synchronized.\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\n // Data update, simply copy data changes.\n this._currentUser._assign(user);\n // If tokens changed from previous user tokens, this will trigger\n // notifyAuthListeners_.\n await this.currentUser.getIdToken();\n return;\n }\n\n // Update current Auth state. Either a new login or logout.\n // Skip blocking callbacks, they should not apply to a change in another tab.\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\n }\n\n private async initializeCurrentUser(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n // First check to see if we have a pending redirect event.\n const previouslyStoredUser =\n (await this.assertedPersistence.getCurrentUser()) as UserInternal | null;\n let futureCurrentUser = previouslyStoredUser;\n let needsTocheckMiddleware = false;\n if (popupRedirectResolver && this.config.authDomain) {\n await this.getOrInitRedirectPersistenceManager();\n const redirectUserEventId = this.redirectUser?._redirectEventId;\n const storedUserEventId = futureCurrentUser?._redirectEventId;\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\n\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\n // matches the redirect user, then we want to initially sign in with the\n // new user object from result.\n // TODO(samgho): More thoroughly test all of this\n if (\n (!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\n result?.user\n ) {\n futureCurrentUser = result.user as UserInternal;\n needsTocheckMiddleware = true;\n }\n }\n\n // If no user in persistence, there is no current user. Set to null.\n if (!futureCurrentUser) {\n return this.directlySetCurrentUser(null);\n }\n\n if (!futureCurrentUser._redirectEventId) {\n // This isn't a redirect link operation, we can reload and bail.\n // First though, ensure that we check the middleware is happy.\n if (needsTocheckMiddleware) {\n try {\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\n } catch (e) {\n futureCurrentUser = previouslyStoredUser;\n // We know this is available since the bit is only set when the\n // resolver is available\n this._popupRedirectResolver!._overrideRedirectResult(this, () =>\n Promise.reject(e)\n );\n }\n }\n\n if (futureCurrentUser) {\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n } else {\n return this.directlySetCurrentUser(null);\n }\n }\n\n _assert(this._popupRedirectResolver, this, AuthErrorCode.ARGUMENT_ERROR);\n await this.getOrInitRedirectPersistenceManager();\n\n // If the redirect user's event ID matches the current user's event ID,\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\n // This is important for the reauthenticateWithRedirect() flow.\n if (\n this.redirectUser &&\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId\n ) {\n return this.directlySetCurrentUser(futureCurrentUser);\n }\n\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\n }\n\n private async tryRedirectSignIn(\n redirectResolver: PopupRedirectResolver\n ): Promise {\n // The redirect user needs to be checked (and signed in if available)\n // during auth initialization. All of the normal sign in and link/reauth\n // flows call back into auth and push things onto the promise queue. We\n // need to await the result of the redirect sign in *inside the promise\n // queue*. This presents a problem: we run into deadlock. See:\n // ┌> [Initialization] ─────┐\n // ┌> [] │\n // └─ [getRedirectResult] <─┘\n // where [] are tasks on the queue and arrows denote awaits\n // Initialization will never complete because it's waiting on something\n // that's waiting for initialization to complete!\n //\n // Instead, this method calls getRedirectResult() (stored in\n // _completeRedirectFn) with an optional parameter that instructs all of\n // the underlying auth operations to skip anything that mutates auth state.\n\n let result: UserCredential | null = null;\n try {\n // We know this._popupRedirectResolver is set since redirectResolver\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\n result = await this._popupRedirectResolver!._completeRedirectFn(\n this,\n redirectResolver,\n true\n );\n } catch (e) {\n // Swallow any errors here; the code can retrieve them in\n // getRedirectResult().\n await this._setRedirectUser(null);\n }\n\n return result;\n }\n\n private async reloadAndSetCurrentUserOrClear(\n user: UserInternal\n ): Promise {\n try {\n await _reloadWithoutSaving(user);\n } catch (e) {\n if (\n (e as FirebaseError)?.code !==\n `auth/${AuthErrorCode.NETWORK_REQUEST_FAILED}`\n ) {\n // Something's wrong with the user's token. Log them out and remove\n // them from storage\n return this.directlySetCurrentUser(null);\n }\n }\n\n return this.directlySetCurrentUser(user);\n }\n\n useDeviceLanguage(): void {\n this.languageCode = _getUserLanguage();\n }\n\n async _delete(): Promise {\n this._deleted = true;\n }\n\n async updateCurrentUser(userExtern: User | null): Promise {\n // The public updateCurrentUser method needs to make a copy of the user,\n // and also check that the project matches\n const user = userExtern\n ? (getModularInstance(userExtern) as UserInternal)\n : null;\n if (user) {\n _assert(\n user.auth.config.apiKey === this.config.apiKey,\n this,\n AuthErrorCode.INVALID_AUTH\n );\n }\n return this._updateCurrentUser(user && user._clone(this));\n }\n\n async _updateCurrentUser(\n user: User | null,\n skipBeforeStateCallbacks: boolean = false\n ): Promise {\n if (this._deleted) {\n return;\n }\n if (user) {\n _assert(\n this.tenantId === user.tenantId,\n this,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n }\n\n if (!skipBeforeStateCallbacks) {\n await this.beforeStateQueue.runMiddleware(user);\n }\n\n return this.queue(async () => {\n await this.directlySetCurrentUser(user as UserInternal | null);\n this.notifyAuthListeners();\n });\n }\n\n async signOut(): Promise {\n // Run first, to block _setRedirectUser() if any callbacks fail.\n await this.beforeStateQueue.runMiddleware(null);\n // Clear the redirect user when signOut is called\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\n await this._setRedirectUser(null);\n }\n\n // Prevent callbacks from being called again in _updateCurrentUser, as\n // they were already called in the first line.\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\n }\n\n setPersistence(persistence: Persistence): Promise {\n return this.queue(async () => {\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\n });\n }\n\n _getRecaptchaConfig(): RecaptchaConfig | null {\n if (this.tenantId == null) {\n return this._agentRecaptchaConfig;\n } else {\n return this._tenantRecaptchaConfigs[this.tenantId];\n }\n }\n\n async validatePassword(password: string): Promise {\n if (!this._getPasswordPolicyInternal()) {\n await this._updatePasswordPolicy();\n }\n\n // Password policy will be defined after fetching.\n const passwordPolicy: PasswordPolicyInternal =\n this._getPasswordPolicyInternal()!;\n\n // Check that the policy schema version is supported by the SDK.\n // TODO: Update this logic to use a max supported policy schema version once we have multiple schema versions.\n if (\n passwordPolicy.schemaVersion !==\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION\n ) {\n return Promise.reject(\n this._errorFactory.create(\n AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION,\n {}\n )\n );\n }\n\n return passwordPolicy.validatePassword(password);\n }\n\n _getPasswordPolicyInternal(): PasswordPolicyInternal | null {\n if (this.tenantId === null) {\n return this._projectPasswordPolicy;\n } else {\n return this._tenantPasswordPolicies[this.tenantId];\n }\n }\n\n async _updatePasswordPolicy(): Promise {\n const response = await _getPasswordPolicy(this);\n\n const passwordPolicy: PasswordPolicyInternal = new PasswordPolicyImpl(\n response\n );\n\n if (this.tenantId === null) {\n this._projectPasswordPolicy = passwordPolicy;\n } else {\n this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;\n }\n }\n\n _getPersistence(): string {\n return this.assertedPersistence.persistence.type;\n }\n\n _updateErrorMap(errorMap: AuthErrorMap): void {\n this._errorFactory = new ErrorFactory(\n 'auth',\n 'Firebase',\n (errorMap as ErrorMapRetriever)()\n );\n }\n\n onAuthStateChanged(\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.authStateSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n beforeAuthStateChanged(\n callback: (user: User | null) => void | Promise,\n onAbort?: () => void\n ): Unsubscribe {\n return this.beforeStateQueue.pushCallback(callback, onAbort);\n }\n\n onIdTokenChanged(\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n return this.registerStateListener(\n this.idTokenSubscription,\n nextOrObserver,\n error,\n completed\n );\n }\n\n authStateReady(): Promise {\n return new Promise((resolve, reject) => {\n if (this.currentUser) {\n resolve();\n } else {\n const unsubscribe = this.onAuthStateChanged(() => {\n unsubscribe();\n resolve();\n }, reject);\n }\n });\n }\n\n /**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n */\n async revokeAccessToken(token: string): Promise {\n if (this.currentUser) {\n const idToken = await this.currentUser.getIdToken();\n // Generalize this to accept other providers once supported.\n const request: RevokeTokenRequest = {\n providerId: 'apple.com',\n tokenType: TokenType.ACCESS_TOKEN,\n token,\n idToken\n };\n if (this.tenantId != null) {\n request.tenantId = this.tenantId;\n }\n await revokeToken(this, request);\n }\n }\n\n toJSON(): object {\n return {\n apiKey: this.config.apiKey,\n authDomain: this.config.authDomain,\n appName: this.name,\n currentUser: this._currentUser?.toJSON()\n };\n }\n\n async _setRedirectUser(\n user: UserInternal | null,\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n const redirectManager = await this.getOrInitRedirectPersistenceManager(\n popupRedirectResolver\n );\n return user === null\n ? redirectManager.removeCurrentUser()\n : redirectManager.setCurrentUser(user);\n }\n\n private async getOrInitRedirectPersistenceManager(\n popupRedirectResolver?: PopupRedirectResolver\n ): Promise {\n if (!this.redirectPersistenceManager) {\n const resolver: PopupRedirectResolverInternal | null =\n (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\n this._popupRedirectResolver;\n _assert(resolver, this, AuthErrorCode.ARGUMENT_ERROR);\n this.redirectPersistenceManager = await PersistenceUserManager.create(\n this,\n [_getInstance(resolver._redirectPersistence)],\n KeyName.REDIRECT_USER\n );\n this.redirectUser =\n await this.redirectPersistenceManager.getCurrentUser();\n }\n\n return this.redirectPersistenceManager;\n }\n\n async _redirectUserForId(id: string): Promise {\n // Make sure we've cleared any pending persistence actions if we're not in\n // the initializer\n if (this._isInitialized) {\n await this.queue(async () => {});\n }\n\n if (this._currentUser?._redirectEventId === id) {\n return this._currentUser;\n }\n\n if (this.redirectUser?._redirectEventId === id) {\n return this.redirectUser;\n }\n\n return null;\n }\n\n async _persistUserIfCurrent(user: UserInternal): Promise {\n if (user === this.currentUser) {\n return this.queue(async () => this.directlySetCurrentUser(user));\n }\n }\n\n /** Notifies listeners only if the user is current */\n _notifyListenersIfCurrent(user: UserInternal): void {\n if (user === this.currentUser) {\n this.notifyAuthListeners();\n }\n }\n\n _key(): string {\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\n }\n\n _startProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = true;\n if (this.currentUser) {\n this._currentUser._startProactiveRefresh();\n }\n }\n\n _stopProactiveRefresh(): void {\n this.isProactiveRefreshEnabled = false;\n if (this.currentUser) {\n this._currentUser._stopProactiveRefresh();\n }\n }\n\n /** Returns the current user cast as the internal type */\n get _currentUser(): UserInternal {\n return this.currentUser as UserInternal;\n }\n\n private notifyAuthListeners(): void {\n if (!this._isInitialized) {\n return;\n }\n\n this.idTokenSubscription.next(this.currentUser);\n\n const currentUid = this.currentUser?.uid ?? null;\n if (this.lastNotifiedUid !== currentUid) {\n this.lastNotifiedUid = currentUid;\n this.authStateSubscription.next(this.currentUser);\n }\n }\n\n private registerStateListener(\n subscription: Subscription,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n ): Unsubscribe {\n if (this._deleted) {\n return () => {};\n }\n\n const cb =\n typeof nextOrObserver === 'function'\n ? nextOrObserver\n : nextOrObserver.next.bind(nextOrObserver);\n\n let isUnsubscribed = false;\n\n const promise = this._isInitialized\n ? Promise.resolve()\n : this._initializationPromise;\n _assert(promise, this, AuthErrorCode.INTERNAL_ERROR);\n // The callback needs to be called asynchronously per the spec.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n promise.then(() => {\n if (isUnsubscribed) {\n return;\n }\n cb(this.currentUser);\n });\n\n if (typeof nextOrObserver === 'function') {\n const unsubscribe = subscription.addObserver(\n nextOrObserver,\n error,\n completed\n );\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n } else {\n const unsubscribe = subscription.addObserver(nextOrObserver);\n return () => {\n isUnsubscribed = true;\n unsubscribe();\n };\n }\n }\n\n /**\n * Unprotected (from race conditions) method to set the current user. This\n * should only be called from within a queued callback. This is necessary\n * because the queue shouldn't rely on another queued callback.\n */\n private async directlySetCurrentUser(\n user: UserInternal | null\n ): Promise {\n if (this.currentUser && this.currentUser !== user) {\n this._currentUser._stopProactiveRefresh();\n }\n if (user && this.isProactiveRefreshEnabled) {\n user._startProactiveRefresh();\n }\n\n this.currentUser = user;\n\n if (user) {\n await this.assertedPersistence.setCurrentUser(user);\n } else {\n await this.assertedPersistence.removeCurrentUser();\n }\n }\n\n private queue(action: AsyncAction): Promise {\n // In case something errors, the callback still should be called in order\n // to keep the promise chain alive\n this.operations = this.operations.then(action, action);\n return this.operations;\n }\n\n private get assertedPersistence(): PersistenceUserManager {\n _assert(this.persistenceManager, this, AuthErrorCode.INTERNAL_ERROR);\n return this.persistenceManager;\n }\n\n private frameworks: string[] = [];\n private clientVersion: string;\n _logFramework(framework: string): void {\n if (!framework || this.frameworks.includes(framework)) {\n return;\n }\n this.frameworks.push(framework);\n\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\n this.frameworks.sort();\n this.clientVersion = _getClientVersion(\n this.config.clientPlatform,\n this._getFrameworks()\n );\n }\n _getFrameworks(): readonly string[] {\n return this.frameworks;\n }\n async _getAdditionalHeaders(): Promise> {\n // Additional headers on every request\n const headers: Record = {\n [HttpHeader.X_CLIENT_VERSION]: this.clientVersion\n };\n\n if (this.app.options.appId) {\n headers[HttpHeader.X_FIREBASE_GMPID] = this.app.options.appId;\n }\n\n // If the heartbeat service exists, add the heartbeat string\n const heartbeatsHeader = await this.heartbeatServiceProvider\n .getImmediate({\n optional: true\n })\n ?.getHeartbeatsHeader();\n if (heartbeatsHeader) {\n headers[HttpHeader.X_FIREBASE_CLIENT] = heartbeatsHeader;\n }\n\n // If the App Check service exists, add the App Check token in the headers\n const appCheckToken = await this._getAppCheckToken();\n if (appCheckToken) {\n headers[HttpHeader.X_FIREBASE_APP_CHECK] = appCheckToken;\n }\n\n return headers;\n }\n\n async _getAppCheckToken(): Promise {\n const appCheckTokenResult = await this.appCheckServiceProvider\n .getImmediate({ optional: true })\n ?.getToken();\n if (appCheckTokenResult?.error) {\n // Context: appCheck.getToken() will never throw even if an error happened.\n // In the error case, a dummy token will be returned along with an error field describing\n // the error. In general, we shouldn't care about the error condition and just use\n // the token (actual or dummy) to send requests.\n _logWarn(\n `Error while retrieving App Check token: ${appCheckTokenResult.error}`\n );\n }\n return appCheckTokenResult?.token;\n }\n}\n\n/**\n * Method to be used to cast down to our private implmentation of Auth.\n * It will also handle unwrapping from the compat type if necessary\n *\n * @param auth Auth object passed in from developer\n */\nexport function _castAuth(auth: Auth): AuthInternal {\n return getModularInstance(auth) as AuthInternal;\n}\n\n/** Helper class to wrap subscriber logic */\nclass Subscription {\n private observer: Observer | null = null;\n readonly addObserver: Subscribe = createSubscribe(\n observer => (this.observer = observer)\n );\n\n constructor(readonly auth: AuthInternal) {}\n\n get next(): NextFn {\n _assert(this.observer, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.observer.next.bind(this.observer);\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../core/errors';\nimport { _createError } from '../core/util/assert';\n\nfunction getScriptParentElement(): HTMLDocument | HTMLHeadElement {\n return document.getElementsByTagName('head')?.[0] ?? document;\n}\n\nexport function _loadJS(url: string): Promise {\n // TODO: consider adding timeout support & cancellation\n return new Promise((resolve, reject) => {\n const el = document.createElement('script');\n el.setAttribute('src', url);\n el.onload = resolve;\n el.onerror = e => {\n const error = _createError(AuthErrorCode.INTERNAL_ERROR);\n error.customData = e as unknown as Record;\n reject(error);\n };\n el.type = 'text/javascript';\n el.charset = 'UTF-8';\n getScriptParentElement().appendChild(el);\n });\n}\n\nexport function _generateCallbackName(prefix: string): string {\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\n}\n", "/* eslint-disable @typescript-eslint/no-require-imports */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isEnterprise, RecaptchaConfig } from './recaptcha';\nimport { getRecaptchaConfig } from '../../api/authentication/recaptcha';\nimport {\n RecaptchaClientType,\n RecaptchaVersion,\n RecaptchaActionName,\n RecaptchaProvider\n} from '../../api';\n\nimport { Auth } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport * as jsHelpers from '../load_js';\nimport { AuthErrorCode } from '../../core/errors';\n\nconst RECAPTCHA_ENTERPRISE_URL =\n 'https://www.google.com/recaptcha/enterprise.js?render=';\n\nexport const RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\nexport const FAKE_TOKEN = 'NO_RECAPTCHA';\n\nexport class RecaptchaEnterpriseVerifier {\n /**\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\n */\n readonly type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\n\n private readonly auth: AuthInternal;\n\n /**\n *\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n */\n constructor(authExtern: Auth) {\n this.auth = _castAuth(authExtern);\n }\n\n /**\n * Executes the verification process.\n *\n * @returns A Promise for a token that can be used to assert the validity of a request.\n */\n async verify(\n action: string = 'verify',\n forceRefresh = false\n ): Promise {\n async function retrieveSiteKey(auth: AuthInternal): Promise {\n if (!forceRefresh) {\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\n return auth._agentRecaptchaConfig.siteKey;\n }\n if (\n auth.tenantId != null &&\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined\n ) {\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\n }\n }\n\n return new Promise(async (resolve, reject) => {\n getRecaptchaConfig(auth, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n })\n .then(response => {\n if (response.recaptchaKey === undefined) {\n reject(new Error('recaptcha Enterprise site key undefined'));\n } else {\n const config = new RecaptchaConfig(response);\n if (auth.tenantId == null) {\n auth._agentRecaptchaConfig = config;\n } else {\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\n }\n return resolve(config.siteKey);\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n\n function retrieveRecaptchaToken(\n siteKey: string,\n resolve: (value: string | PromiseLike) => void,\n reject: (reason?: unknown) => void\n ): void {\n const grecaptcha = window.grecaptcha;\n if (isEnterprise(grecaptcha)) {\n grecaptcha.enterprise.ready(() => {\n grecaptcha.enterprise\n .execute(siteKey, { action })\n .then(token => {\n resolve(token);\n })\n .catch(() => {\n resolve(FAKE_TOKEN);\n });\n });\n } else {\n reject(Error('No reCAPTCHA enterprise script loaded.'));\n }\n }\n\n return new Promise((resolve, reject) => {\n retrieveSiteKey(this.auth)\n .then(siteKey => {\n if (!forceRefresh && isEnterprise(window.grecaptcha)) {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n } else {\n if (typeof window === 'undefined') {\n reject(\n new Error('RecaptchaVerifier is only supported in browser')\n );\n return;\n }\n jsHelpers\n ._loadJS(RECAPTCHA_ENTERPRISE_URL + siteKey)\n .then(() => {\n retrieveRecaptchaToken(siteKey, resolve, reject);\n })\n .catch(error => {\n reject(error);\n });\n }\n })\n .catch(error => {\n reject(error);\n });\n });\n }\n}\n\nexport async function injectRecaptchaFields(\n auth: AuthInternal,\n request: T,\n action: RecaptchaActionName,\n captchaResp = false\n): Promise {\n const verifier = new RecaptchaEnterpriseVerifier(auth);\n let captchaResponse;\n try {\n captchaResponse = await verifier.verify(action);\n } catch (error) {\n captchaResponse = await verifier.verify(action, true);\n }\n const newRequest = { ...request };\n if (!captchaResp) {\n Object.assign(newRequest, { captchaResponse });\n } else {\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\n }\n Object.assign(newRequest, { 'clientType': RecaptchaClientType.WEB });\n Object.assign(newRequest, {\n 'recaptchaVersion': RecaptchaVersion.ENTERPRISE\n });\n return newRequest;\n}\n\ntype ActionMethod = (\n auth: Auth,\n request: TRequest\n) => Promise;\n\nexport async function handleRecaptchaFlow(\n authInstance: AuthInternal,\n request: TRequest,\n actionName: RecaptchaActionName,\n actionMethod: ActionMethod\n): Promise {\n if (\n authInstance\n ._getRecaptchaConfig()\n ?.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)\n ) {\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return actionMethod(authInstance, request).catch(async error => {\n if (error.code === `auth/${AuthErrorCode.MISSING_RECAPTCHA_TOKEN}`) {\n console.log(\n `${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`\n );\n const requestWithRecaptcha = await injectRecaptchaFields(\n authInstance,\n request,\n actionName,\n actionName === RecaptchaActionName.GET_OOB_CODE\n );\n return actionMethod(authInstance, requestWithRecaptcha);\n } else {\n return Promise.reject(error);\n }\n });\n }\n}\n\nexport async function _initializeRecaptchaConfig(auth: Auth): Promise {\n const authInternal = _castAuth(auth);\n\n const response = await getRecaptchaConfig(authInternal, {\n clientType: RecaptchaClientType.WEB,\n version: RecaptchaVersion.ENTERPRISE\n });\n\n const config = new RecaptchaConfig(response);\n if (authInternal.tenantId == null) {\n authInternal._agentRecaptchaConfig = config;\n } else {\n authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config;\n }\n\n if (config.isProviderEnabled(RecaptchaProvider.EMAIL_PASSWORD_PROVIDER)) {\n const verifier = new RecaptchaEnterpriseVerifier(authInternal);\n void verifier.verify();\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProvider, FirebaseApp } from '@firebase/app';\nimport { deepEqual } from '@firebase/util';\nimport { Auth, Dependencies } from '../../model/public_types';\n\nimport { AuthErrorCode } from '../errors';\nimport { PersistenceInternal } from '../persistence';\nimport { _fail } from '../util/assert';\nimport { _getInstance } from '../util/instantiator';\nimport { AuthImpl } from './auth_impl';\n\n/**\n * Initializes an {@link Auth} instance with fine-grained control over\n * {@link Dependencies}.\n *\n * @remarks\n *\n * This function allows more control over the {@link Auth} instance than\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\n * need control over which persistence layer is used, or to minimize bundle\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\n *\n * For example, if your app only uses anonymous accounts and you only want\n * accounts saved for the current session, initialize `Auth` with:\n *\n * ```js\n * const auth = initializeAuth(app, {\n * persistence: browserSessionPersistence,\n * popupRedirectResolver: undefined,\n * });\n * ```\n *\n * @public\n */\nexport function initializeAuth(app: FirebaseApp, deps?: Dependencies): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n const auth = provider.getImmediate() as AuthImpl;\n const initialOptions = provider.getOptions() as Dependencies;\n if (deepEqual(initialOptions, deps ?? {})) {\n return auth;\n } else {\n _fail(auth, AuthErrorCode.ALREADY_INITIALIZED);\n }\n }\n\n const auth = provider.initialize({ options: deps }) as AuthImpl;\n\n return auth;\n}\n\nexport function _initializeAuthInstance(\n auth: AuthImpl,\n deps?: Dependencies\n): void {\n const persistence = deps?.persistence || [];\n const hierarchy = (\n Array.isArray(persistence) ? persistence : [persistence]\n ).map(_getInstance);\n if (deps?.errorMap) {\n auth._updateErrorMap(deps.errorMap);\n }\n\n // This promise is intended to float; auth initialization happens in the\n // background, meanwhile the auth object may be used by the app.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n auth._initializeWithPersistence(hierarchy, deps?.popupRedirectResolver);\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Auth } from '../../model/public_types';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _castAuth } from './auth_impl';\n\n/**\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\n * Firebase Auth services.\n *\n * @remarks\n * This must be called synchronously immediately following the first call to\n * {@link initializeAuth}. Do not use with production credentials as emulator\n * traffic is not encrypted.\n *\n *\n * @example\n * ```javascript\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\n * `true` to disable the warning banner attached to the DOM.\n *\n * @public\n */\nexport function connectAuthEmulator(\n auth: Auth,\n url: string,\n options?: { disableWarnings: boolean }\n): void {\n const authInternal = _castAuth(auth);\n _assert(\n authInternal._canInitEmulator,\n authInternal,\n AuthErrorCode.EMULATOR_CONFIG_FAILED\n );\n\n _assert(\n /^https?:\\/\\//.test(url),\n authInternal,\n AuthErrorCode.INVALID_EMULATOR_SCHEME\n );\n\n const disableWarnings = !!options?.disableWarnings;\n\n const protocol = extractProtocol(url);\n const { host, port } = extractHostAndPort(url);\n const portStr = port === null ? '' : `:${port}`;\n\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\n authInternal.settings.appVerificationDisabledForTesting = true;\n authInternal.emulatorConfig = Object.freeze({\n host,\n port,\n protocol: protocol.replace(':', ''),\n options: Object.freeze({ disableWarnings })\n });\n\n if (!disableWarnings) {\n emitEmulatorWarning();\n }\n}\n\nfunction extractProtocol(url: string): string {\n const protocolEnd = url.indexOf(':');\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\n}\n\nfunction extractHostAndPort(url: string): {\n host: string;\n port: number | null;\n} {\n const protocol = extractProtocol(url);\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\n if (!authority) {\n return { host: '', port: null };\n }\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\n if (bracketedIPv6) {\n const host = bracketedIPv6[1];\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\n } else {\n const [host, port] = hostAndPort.split(':');\n return { host, port: parsePort(port) };\n }\n}\n\nfunction parsePort(portStr: string): number | null {\n if (!portStr) {\n return null;\n }\n const port = Number(portStr);\n if (isNaN(port)) {\n return null;\n }\n return port;\n}\n\nfunction emitEmulatorWarning(): void {\n function attachBanner(): void {\n const el = document.createElement('p');\n const sty = el.style;\n el.innerText =\n 'Running in emulator mode. Do not use with production credentials.';\n sty.position = 'fixed';\n sty.width = '100%';\n sty.backgroundColor = '#ffffff';\n sty.border = '.1em solid #000000';\n sty.color = '#b50000';\n sty.bottom = '0px';\n sty.left = '0px';\n sty.margin = '0px';\n sty.zIndex = '10000';\n sty.textAlign = 'center';\n el.classList.add('firebase-emulator-warning');\n document.body.appendChild(el);\n }\n\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\n console.info(\n 'WARNING: You are using the Auth Emulator,' +\n ' which is intended for local testing only. Do not use with' +\n ' production credentials.'\n );\n }\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n window.addEventListener('DOMContentLoaded', attachBanner);\n } else {\n attachBanner();\n }\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { debugFail } from '../util/assert';\n\n/**\n * Interface that represents the credentials returned by an {@link AuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class AuthCredential {\n /** @internal */\n protected constructor(\n /**\n * The authentication provider ID for the credential.\n *\n * @remarks\n * For example, 'facebook.com', or 'google.com'.\n */\n readonly providerId: string,\n /**\n * The authentication sign in method for the credential.\n *\n * @remarks\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\n */\n readonly signInMethod: string\n ) {}\n\n /**\n * Returns a JSON-serializable representation of this object.\n *\n * @returns a JSON-serializable representation of this object.\n */\n toJSON(): object {\n return debugFail('not implemented');\n }\n\n /** @internal */\n _getIdTokenResponse(_auth: AuthInternal): Promise {\n return debugFail('not implemented');\n }\n /** @internal */\n _linkToIdToken(\n _auth: AuthInternal,\n _idToken: string\n ): Promise {\n return debugFail('not implemented');\n }\n /** @internal */\n _getReauthenticationResolver(_auth: AuthInternal): Promise {\n return debugFail('not implemented');\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from './mfa';\nimport { SignUpRequest, SignUpResponse } from '../authentication/sign_up';\n\nexport interface ResetPasswordRequest {\n oobCode: string;\n newPassword?: string;\n tenantId?: string;\n}\n\nexport interface ResetPasswordResponse {\n email: string;\n newEmail?: string;\n requestType?: ActionCodeOperation;\n mfaInfo?: MfaEnrollment;\n}\n\nexport async function resetPassword(\n auth: Auth,\n request: ResetPasswordRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.RESET_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface UpdateEmailPasswordRequest {\n idToken: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n}\n\nexport interface UpdateEmailPasswordResponse extends IdTokenResponse {}\n\nexport async function updateEmailPassword(\n auth: Auth,\n request: UpdateEmailPasswordRequest\n): Promise {\n return _performApiRequest<\n UpdateEmailPasswordRequest,\n UpdateEmailPasswordResponse\n >(auth, HttpMethod.POST, Endpoint.SET_ACCOUNT_INFO, request);\n}\n\n// Used for linking an email/password account to an existing idToken. Uses the same request/response\n// format as updateEmailPassword.\nexport async function linkEmailPassword(\n auth: Auth,\n request: SignUpRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n request\n );\n}\n\nexport interface ApplyActionCodeRequest {\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface ApplyActionCodeResponse {}\n\nexport async function applyActionCode(\n auth: Auth,\n request: ApplyActionCodeRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n _addTidIfNecessary(auth, request)\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeOperation, Auth } from '../../model/public_types';\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\n\nexport interface SignInWithPasswordRequest {\n returnSecureToken?: boolean;\n email: string;\n password: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignInWithPasswordResponse extends IdTokenResponse {\n email: string;\n displayName: string;\n}\n\nexport async function signInWithPassword(\n auth: Auth,\n request: SignInWithPasswordRequest\n): Promise {\n return _performSignInRequest<\n SignInWithPasswordRequest,\n SignInWithPasswordResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PASSWORD,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface GetOobCodeRequest {\n email?: string; // Everything except VERIFY_AND_CHANGE_EMAIL\n continueUrl?: string;\n iOSBundleId?: string;\n iosAppStoreId?: string;\n androidPackageName?: string;\n androidInstallApp?: boolean;\n androidMinimumVersionCode?: string;\n canHandleCodeInApp?: boolean;\n dynamicLinkDomain?: string;\n tenantId?: string;\n targetProjectid?: string;\n}\n\nexport interface VerifyEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_EMAIL;\n idToken: IdToken;\n}\n\nexport interface PasswordResetRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.PASSWORD_RESET;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface EmailSignInRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.EMAIL_SIGNIN;\n email: string;\n captchaResp?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface VerifyAndChangeEmailRequest extends GetOobCodeRequest {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n idToken: IdToken;\n newEmail: string;\n}\n\ninterface GetOobCodeResponse {\n email: string;\n}\n\nexport interface VerifyEmailResponse extends GetOobCodeResponse {}\nexport interface PasswordResetResponse extends GetOobCodeResponse {}\nexport interface EmailSignInResponse extends GetOobCodeResponse {}\nexport interface VerifyAndChangeEmailResponse extends GetOobCodeRequest {}\n\nasync function sendOobCode(\n auth: Auth,\n request: GetOobCodeRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_OOB_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function sendEmailVerification(\n auth: Auth,\n request: VerifyEmailRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function sendPasswordResetEmail(\n auth: Auth,\n request: PasswordResetRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n request: EmailSignInRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n\nexport async function verifyAndChangeEmail(\n auth: Auth,\n request: VerifyAndChangeEmailRequest\n): Promise {\n return sendOobCode(auth, request);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performSignInRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithEmailLinkRequest {\n email: string;\n oobCode: string;\n tenantId?: string;\n}\n\nexport interface SignInWithEmailLinkResponse extends IdTokenResponse {\n email: string;\n isNewUser: boolean;\n}\n\nexport async function signInWithEmailLink(\n auth: Auth,\n request: SignInWithEmailLinkRequest\n): Promise {\n return _performSignInRequest<\n SignInWithEmailLinkRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface SignInWithEmailLinkForLinkingRequest\n extends SignInWithEmailLinkRequest {\n idToken: string;\n}\n\nexport async function signInWithEmailLinkForLinking(\n auth: Auth,\n request: SignInWithEmailLinkForLinkingRequest\n): Promise {\n return _performSignInRequest<\n SignInWithEmailLinkForLinkingRequest,\n SignInWithEmailLinkResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_EMAIL_LINK,\n _addTidIfNecessary(auth, request)\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { linkEmailPassword } from '../../api/account_management/email_and_password';\nimport {\n signInWithPassword,\n SignInWithPasswordRequest\n} from '../../api/authentication/email_and_password';\nimport {\n signInWithEmailLink,\n signInWithEmailLinkForLinking\n} from '../../api/authentication/email_link';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\nimport { SignUpRequest } from '../../api/authentication/sign_up';\n/**\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\n * {@link ProviderId}.PASSWORD\n *\n * @remarks\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @public\n */\nexport class EmailAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n /** @internal */\n readonly _email: string,\n /** @internal */\n readonly _password: string,\n signInMethod: SignInMethod,\n /** @internal */\n readonly _tenantId: string | null = null\n ) {\n super(ProviderId.PASSWORD, signInMethod);\n }\n\n /** @internal */\n static _fromEmailAndPassword(\n email: string,\n password: string\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n password,\n SignInMethod.EMAIL_PASSWORD\n );\n }\n\n /** @internal */\n static _fromEmailAndCode(\n email: string,\n oobCode: string,\n tenantId: string | null = null\n ): EmailAuthCredential {\n return new EmailAuthCredential(\n email,\n oobCode,\n SignInMethod.EMAIL_LINK,\n tenantId\n );\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n email: this._email,\n password: this._password,\n signInMethod: this.signInMethod,\n tenantId: this._tenantId\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\n *\n * @param json - Either `object` or the stringified representation of the object. When string is\n * provided, `JSON.parse` would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: object | string): EmailAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n if (obj?.email && obj?.password) {\n if (obj.signInMethod === SignInMethod.EMAIL_PASSWORD) {\n return this._fromEmailAndPassword(obj.email, obj.password);\n } else if (obj.signInMethod === SignInMethod.EMAIL_LINK) {\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\n }\n }\n return null;\n }\n\n /** @internal */\n async _getIdTokenResponse(auth: AuthInternal): Promise {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignInWithPasswordRequest = {\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_IN_WITH_PASSWORD,\n signInWithPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLink(auth, {\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n async _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n switch (this.signInMethod) {\n case SignInMethod.EMAIL_PASSWORD:\n const request: SignUpRequest = {\n idToken,\n returnSecureToken: true,\n email: this._email,\n password: this._password,\n clientType: RecaptchaClientType.WEB\n };\n return handleRecaptchaFlow(\n auth,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n linkEmailPassword\n );\n case SignInMethod.EMAIL_LINK:\n return signInWithEmailLinkForLinking(auth, {\n idToken,\n email: this._email,\n oobCode: this._password\n });\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return this._getIdTokenResponse(auth);\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdToken, IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithIdpRequest {\n requestUri: string;\n postBody?: string;\n sessionId?: string;\n tenantId?: string;\n returnSecureToken: boolean;\n returnIdpCredential?: boolean;\n idToken?: IdToken;\n autoCreate?: boolean;\n pendingToken?: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithIdpResponse extends IdTokenResponse {\n oauthAccessToken?: string;\n oauthTokenSecret?: string;\n nonce?: string;\n oauthIdToken?: string;\n pendingToken?: string;\n}\n\nexport async function signInWithIdp(\n auth: Auth,\n request: SignInWithIdpRequest\n): Promise {\n return _performSignInRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_IDP,\n _addTidIfNecessary(auth, request)\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from '../util/assert';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\nexport interface OAuthCredentialParams {\n // OAuth 2 uses either id token or access token\n idToken?: string | null;\n accessToken?: string | null;\n\n // These fields are used with OAuth 1\n oauthToken?: string;\n secret?: string;\n oauthTokenSecret?: string;\n\n // Nonce is only set if pendingToken is not present\n nonce?: string;\n pendingToken?: string;\n\n // Utilities\n providerId: string;\n signInMethod: string;\n}\n\n/**\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\n *\n * @remarks\n * Implementations specify the details about each auth provider's credential requirements.\n *\n * @public\n */\nexport class OAuthCredential extends AuthCredential {\n /**\n * The OAuth ID token associated with the credential if it belongs to an OIDC provider,\n * such as `google.com`.\n * @readonly\n */\n idToken?: string;\n /**\n * The OAuth access token associated with the credential if it belongs to an\n * {@link OAuthProvider}, such as `facebook.com`, `twitter.com`, etc.\n * @readonly\n */\n accessToken?: string;\n /**\n * The OAuth access token secret associated with the credential if it belongs to an OAuth 1.0\n * provider, such as `twitter.com`.\n * @readonly\n */\n secret?: string;\n\n private nonce?: string;\n private pendingToken: string | null = null;\n\n /** @internal */\n static _fromParams(params: OAuthCredentialParams): OAuthCredential {\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\n\n if (params.idToken || params.accessToken) {\n // OAuth 2 and either ID token or access token.\n if (params.idToken) {\n cred.idToken = params.idToken;\n }\n\n if (params.accessToken) {\n cred.accessToken = params.accessToken;\n }\n\n // Add nonce if available and no pendingToken is present.\n if (params.nonce && !params.pendingToken) {\n cred.nonce = params.nonce;\n }\n\n if (params.pendingToken) {\n cred.pendingToken = params.pendingToken;\n }\n } else if (params.oauthToken && params.oauthTokenSecret) {\n // OAuth 1 and OAuth token with token secret\n cred.accessToken = params.oauthToken;\n cred.secret = params.oauthTokenSecret;\n } else {\n _fail(AuthErrorCode.ARGUMENT_ERROR);\n }\n\n return cred;\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n idToken: this.idToken,\n accessToken: this.accessToken,\n secret: this.secret,\n nonce: this.nonce,\n pendingToken: this.pendingToken,\n providerId: this.providerId,\n signInMethod: this.signInMethod\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): OAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, ...rest }: OAuthCredentialParams = obj;\n if (!providerId || !signInMethod) {\n return null;\n }\n\n const cred = new OAuthCredential(providerId, signInMethod);\n cred.idToken = rest.idToken || undefined;\n cred.accessToken = rest.accessToken || undefined;\n cred.secret = rest.secret;\n cred.nonce = rest.nonce;\n cred.pendingToken = rest.pendingToken || null;\n return cred;\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true\n };\n\n if (this.pendingToken) {\n request.pendingToken = this.pendingToken;\n } else {\n const postBody: Record = {};\n if (this.idToken) {\n postBody['id_token'] = this.idToken;\n }\n if (this.accessToken) {\n postBody['access_token'] = this.accessToken;\n }\n if (this.secret) {\n postBody['oauth_token_secret'] = this.secret;\n }\n\n postBody['providerId'] = this.providerId;\n if (this.nonce && !this.pendingToken) {\n postBody['nonce'] = this.nonce;\n }\n\n request.postBody = querystring(postBody);\n }\n\n return request;\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _makeTaggedError,\n _performApiRequest,\n _performSignInRequest\n} from '../index';\nimport { AuthErrorCode } from '../../core/errors';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { ServerError, ServerErrorMap } from '../errors';\nimport { Auth } from '../../model/public_types';\n\nexport interface SendPhoneVerificationCodeRequest {\n phoneNumber: string;\n recaptchaToken: string;\n tenantId?: string;\n}\n\nexport interface SendPhoneVerificationCodeResponse {\n sessionInfo: string;\n}\n\nexport async function sendPhoneVerificationCode(\n auth: Auth,\n request: SendPhoneVerificationCodeRequest\n): Promise {\n return _performApiRequest<\n SendPhoneVerificationCodeRequest,\n SendPhoneVerificationCodeResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SEND_VERIFICATION_CODE,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberRequest {\n temporaryProof?: string;\n phoneNumber?: string;\n sessionInfo?: string;\n code?: string;\n tenantId?: string;\n}\n\nexport interface LinkWithPhoneNumberRequest\n extends SignInWithPhoneNumberRequest {\n idToken: string;\n}\n\n/**\n * @internal\n */\nexport interface SignInWithPhoneNumberResponse extends IdTokenResponse {\n temporaryProof?: string;\n phoneNumber?: string;\n}\n\nexport async function signInWithPhoneNumber(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise {\n return _performSignInRequest<\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport async function linkWithPhoneNumber(\n auth: Auth,\n request: LinkWithPhoneNumberRequest\n): Promise {\n const response = await _performSignInRequest<\n LinkWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, request)\n );\n if (response.temporaryProof) {\n throw _makeTaggedError(auth, AuthErrorCode.NEED_CONFIRMATION, response);\n }\n return response;\n}\n\ninterface VerifyPhoneNumberForExistingRequest\n extends SignInWithPhoneNumberRequest {\n operation: 'REAUTH';\n}\n\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_: Partial<\n ServerErrorMap\n> = {\n [ServerError.USER_NOT_FOUND]: AuthErrorCode.USER_DELETED\n};\n\nexport async function verifyPhoneNumberForExisting(\n auth: Auth,\n request: SignInWithPhoneNumberRequest\n): Promise {\n const apiRequest: VerifyPhoneNumberForExistingRequest = {\n ...request,\n operation: 'REAUTH'\n };\n return _performSignInRequest<\n VerifyPhoneNumberForExistingRequest,\n SignInWithPhoneNumberResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_PHONE_NUMBER,\n _addTidIfNecessary(auth, apiRequest),\n VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport {\n linkWithPhoneNumber,\n signInWithPhoneNumber,\n SignInWithPhoneNumberRequest,\n verifyPhoneNumberForExisting\n} from '../../api/authentication/sms';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nexport interface PhoneAuthCredentialParameters {\n verificationId?: string;\n verificationCode?: string;\n phoneNumber?: string;\n temporaryProof?: string;\n}\n\n/**\n * Represents the credentials returned by {@link PhoneAuthProvider}.\n *\n * @public\n */\nexport class PhoneAuthCredential extends AuthCredential {\n private constructor(private readonly params: PhoneAuthCredentialParameters) {\n super(ProviderId.PHONE, SignInMethod.PHONE);\n }\n\n /** @internal */\n static _fromVerification(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ verificationId, verificationCode });\n }\n\n /** @internal */\n static _fromTokenResponse(\n phoneNumber: string,\n temporaryProof: string\n ): PhoneAuthCredential {\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n return signInWithPhoneNumber(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n return linkWithPhoneNumber(auth, {\n idToken,\n ...this._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\n }\n\n /** @internal */\n _makeVerificationRequest(): SignInWithPhoneNumberRequest {\n const { temporaryProof, phoneNumber, verificationId, verificationCode } =\n this.params;\n if (temporaryProof && phoneNumber) {\n return { temporaryProof, phoneNumber };\n }\n\n return {\n sessionInfo: verificationId,\n code: verificationCode\n };\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n const obj: Record = {\n providerId: this.providerId\n };\n if (this.params.phoneNumber) {\n obj.phoneNumber = this.params.phoneNumber;\n }\n if (this.params.temporaryProof) {\n obj.temporaryProof = this.params.temporaryProof;\n }\n if (this.params.verificationCode) {\n obj.verificationCode = this.params.verificationCode;\n }\n if (this.params.verificationId) {\n obj.verificationId = this.params.verificationId;\n }\n\n return obj;\n }\n\n /** Generates a phone credential based on a plain object or a JSON string. */\n static fromJSON(json: object | string): PhoneAuthCredential | null {\n if (typeof json === 'string') {\n json = JSON.parse(json);\n }\n\n const { verificationId, verificationCode, phoneNumber, temporaryProof } =\n json as { [key: string]: string };\n if (\n !verificationCode &&\n !verificationId &&\n !phoneNumber &&\n !temporaryProof\n ) {\n return null;\n }\n\n return new PhoneAuthCredential({\n verificationId,\n verificationCode,\n phoneNumber,\n temporaryProof\n });\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extractQuerystring, querystringDecode } from '@firebase/util';\nimport { ActionCodeOperation } from '../model/public_types';\nimport { AuthErrorCode } from './errors';\nimport { _assert } from './util/assert';\n\n/**\n * Enums for fields in URL query string.\n *\n * @enum {string}\n */\nconst enum QueryField {\n API_KEY = 'apiKey',\n CODE = 'oobCode',\n CONTINUE_URL = 'continueUrl',\n LANGUAGE_CODE = 'languageCode',\n MODE = 'mode',\n TENANT_ID = 'tenantId'\n}\n\n/**\n * Maps the mode string in action code URL to Action Code Info operation.\n *\n * @param mode\n */\nfunction parseMode(mode: string | null): ActionCodeOperation | null {\n switch (mode) {\n case 'recoverEmail':\n return ActionCodeOperation.RECOVER_EMAIL;\n case 'resetPassword':\n return ActionCodeOperation.PASSWORD_RESET;\n case 'signIn':\n return ActionCodeOperation.EMAIL_SIGNIN;\n case 'verifyEmail':\n return ActionCodeOperation.VERIFY_EMAIL;\n case 'verifyAndChangeEmail':\n return ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL;\n case 'revertSecondFactorAddition':\n return ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION;\n default:\n return null;\n }\n}\n\n/**\n * Helper to parse FDL links\n *\n * @param url\n */\nfunction parseDeepLink(url: string): string {\n const link = querystringDecode(extractQuerystring(url))['link'];\n\n // Double link case (automatic redirect).\n const doubleDeepLink = link\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\n : null;\n // iOS custom scheme links.\n const iOSDeepLink = querystringDecode(extractQuerystring(url))[\n 'deep_link_id'\n ];\n const iOSDoubleDeepLink = iOSDeepLink\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\n : null;\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\n}\n\n/**\n * A utility class to parse email action URLs such as password reset, email verification,\n * email link sign in, etc.\n *\n * @public\n */\nexport class ActionCodeURL {\n /**\n * The API key of the email action link.\n */\n readonly apiKey: string;\n /**\n * The action code of the email action link.\n */\n readonly code: string;\n /**\n * The continue URL of the email action link. Null if not provided.\n */\n readonly continueUrl: string | null;\n /**\n * The language code of the email action link. Null if not provided.\n */\n readonly languageCode: string | null;\n /**\n * The action performed by the email action link. It returns from one of the types from\n * {@link ActionCodeInfo}\n */\n readonly operation: string;\n /**\n * The tenant ID of the email action link. Null if the email action is from the parent project.\n */\n readonly tenantId: string | null;\n\n /**\n * @param actionLink - The link from which to extract the URL.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @internal\n */\n constructor(actionLink: string) {\n const searchParams = querystringDecode(extractQuerystring(actionLink));\n const apiKey = searchParams[QueryField.API_KEY] ?? null;\n const code = searchParams[QueryField.CODE] ?? null;\n const operation = parseMode(searchParams[QueryField.MODE] ?? null);\n // Validate API key, code and mode.\n _assert(apiKey && code && operation, AuthErrorCode.ARGUMENT_ERROR);\n this.apiKey = apiKey;\n this.operation = operation;\n this.code = code;\n this.continueUrl = searchParams[QueryField.CONTINUE_URL] ?? null;\n this.languageCode = searchParams[QueryField.LANGUAGE_CODE] ?? null;\n this.tenantId = searchParams[QueryField.TENANT_ID] ?? null;\n }\n\n /**\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\n * otherwise returns null.\n *\n * @param link - The email action link string.\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\n *\n * @public\n */\n static parseLink(link: string): ActionCodeURL | null {\n const actionLink = parseDeepLink(link);\n try {\n return new ActionCodeURL(actionLink);\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Parses the email action link string and returns an {@link ActionCodeURL} if\n * the link is valid, otherwise returns null.\n *\n * @public\n */\nexport function parseActionCodeURL(link: string): ActionCodeURL | null {\n return ActionCodeURL.parseLink(link);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ProviderId, SignInMethod } from '../../model/enums';\nimport { AuthProvider } from '../../model/public_types';\n\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthCredential } from '../credentials/email';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\n/**\n * Provider for generating {@link EmailAuthCredential}.\n *\n * @public\n */\nexport class EmailAuthProvider implements AuthProvider {\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n static readonly PROVIDER_ID: 'password' = ProviderId.PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\n */\n static readonly EMAIL_PASSWORD_SIGN_IN_METHOD: 'password' =\n SignInMethod.EMAIL_PASSWORD;\n /**\n * Always set to {@link SignInMethod}.EMAIL_LINK.\n */\n static readonly EMAIL_LINK_SIGN_IN_METHOD: 'emailLink' =\n SignInMethod.EMAIL_LINK;\n /**\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\n */\n readonly providerId = EmailAuthProvider.PROVIDER_ID;\n\n /**\n * Initialize an {@link AuthCredential} using an email and password.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credential(email, password);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\n * ```\n *\n * @param email - Email address.\n * @param password - User account password.\n * @returns The auth provider credential.\n */\n static credential(email: string, password: string): EmailAuthCredential {\n return EmailAuthCredential._fromEmailAndPassword(email, password);\n }\n\n /**\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\n * email link operation.\n *\n * @example\n * ```javascript\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * ```javascript\n * await sendSignInLinkToEmail(auth, email);\n * // Obtain emailLink from user.\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\n * ```\n *\n * @param auth - The {@link Auth} instance used to verify the link.\n * @param email - Email address.\n * @param emailLink - Sign-in email link.\n * @returns - The auth provider credential.\n */\n static credentialWithLink(\n email: string,\n emailLink: string\n ): EmailAuthCredential {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n _assert(actionCodeUrl, AuthErrorCode.ARGUMENT_ERROR);\n\n return EmailAuthCredential._fromEmailAndCode(\n email,\n actionCodeUrl.code,\n actionCodeUrl.tenantId\n );\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider } from '../../model/public_types';\n\n/**\n * Map of OAuth Custom Parameters.\n *\n * @public\n */\nexport type CustomParameters = Record;\n\n/**\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\n *\n * This class is not meant to be instantiated directly.\n *\n * @public\n */\nexport abstract class FederatedAuthProvider implements AuthProvider {\n /** @internal */\n defaultLanguageCode: string | null = null;\n /** @internal */\n private customParameters: CustomParameters = {};\n\n /**\n * Constructor for generic OAuth providers.\n *\n * @param providerId - Provider for which credentials should be generated.\n */\n constructor(readonly providerId: string) {}\n\n /**\n * Set the language gode.\n *\n * @param languageCode - language code\n */\n setDefaultLanguage(languageCode: string | null): void {\n this.defaultLanguageCode = languageCode;\n }\n\n /**\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\n * operations.\n *\n * @remarks\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\n *\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\n */\n setCustomParameters(customOAuthParameters: CustomParameters): AuthProvider {\n this.customParameters = customOAuthParameters;\n return this;\n }\n\n /**\n * Retrieve the current list of {@link CustomParameters}.\n */\n getCustomParameters(): CustomParameters {\n return this.customParameters;\n }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, UserCredential } from '../../model/public_types';\n\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\nimport { OAuthCredential, OAuthCredentialParams } from '../credentials/oauth';\nimport { UserCredentialInternal } from '../../model/user';\nimport { FirebaseError } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { SignInWithIdpResponse } from '../../../internal';\nimport { FederatedAuthProvider } from './federated';\n\n/**\n * Defines the options for initializing an {@link OAuthCredential}.\n *\n * @remarks\n * For ID tokens with nonce claim, the raw nonce has to also be provided.\n *\n * @public\n */\nexport interface OAuthCredentialOptions {\n /**\n * The OAuth ID token used to initialize the {@link OAuthCredential}.\n */\n idToken?: string;\n /**\n * The OAuth access token used to initialize the {@link OAuthCredential}.\n */\n accessToken?: string;\n /**\n * The raw nonce associated with the ID token.\n *\n * @remarks\n * It is required when an ID token with a nonce field is provided. The SHA-256 hash of the\n * raw nonce must match the nonce field in the ID token.\n */\n rawNonce?: string;\n}\n\n/**\n * Common code to all OAuth providers. This is separate from the\n * {@link OAuthProvider} so that child providers (like\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\n * Instead, they rely on a static `credential` method.\n */\nexport abstract class BaseOAuthProvider\n extends FederatedAuthProvider\n implements AuthProvider\n{\n /** @internal */\n private scopes: string[] = [];\n\n /**\n * Add an OAuth scope to the credential.\n *\n * @param scope - Provider OAuth scope to add.\n */\n addScope(scope: string): AuthProvider {\n // If not already added, add scope to list.\n if (!this.scopes.includes(scope)) {\n this.scopes.push(scope);\n }\n return this;\n }\n\n /**\n * Retrieve the current list of OAuth scopes.\n */\n getScopes(): string[] {\n return [...this.scopes];\n }\n}\n\n/**\n * Provider for generating generic {@link OAuthCredential}.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new OAuthProvider('google.com');\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new OAuthProvider('google.com');\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a OAuth Access Token for the provider.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class OAuthProvider extends BaseOAuthProvider {\n /**\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: object | string): OAuthCredential {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n _assert(\n 'providerId' in obj && 'signInMethod' in obj,\n AuthErrorCode.ARGUMENT_ERROR\n );\n return OAuthCredential._fromParams(obj);\n }\n\n /**\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\n *\n * @remarks\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\n * the raw nonce must match the nonce field in the ID token.\n *\n * @example\n * ```javascript\n * // `googleUser` from the onsuccess Google Sign In callback.\n * // Initialize a generate OAuth provider with a `google.com` providerId.\n * const provider = new OAuthProvider('google.com');\n * const credential = provider.credential({\n * idToken: googleUser.getAuthResponse().id_token,\n * });\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param params - Either the options object containing the ID token, access token and raw nonce\n * or the ID token string.\n */\n credential(params: OAuthCredentialOptions): OAuthCredential {\n return this._credential({ ...params, nonce: params.rawNonce });\n }\n\n /** An internal credential method that accepts more permissive options */\n private _credential(\n params: Omit\n ): OAuthCredential {\n _assert(params.idToken || params.accessToken, AuthErrorCode.ARGUMENT_ERROR);\n // For OAuthCredential, sign in method is same as providerId.\n return OAuthCredential._fromParams({\n ...params,\n providerId: this.providerId,\n signInMethod: this.providerId\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return OAuthProvider.oauthCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static oauthCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const {\n oauthIdToken,\n oauthAccessToken,\n oauthTokenSecret,\n pendingToken,\n nonce,\n providerId\n } = tokenResponse as SignInWithIdpResponse;\n if (\n !oauthAccessToken &&\n !oauthTokenSecret &&\n !oauthIdToken &&\n !pendingToken\n ) {\n return null;\n }\n\n if (!providerId) {\n return null;\n }\n\n try {\n return new OAuthProvider(providerId)._credential({\n idToken: oauthIdToken,\n accessToken: oauthAccessToken,\n nonce,\n pendingToken\n });\n } catch (e) {\n return null;\n }\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('user_birthday');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * provider.addScope('user_birthday');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = FacebookAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class FacebookAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.FACEBOOK. */\n static readonly FACEBOOK_SIGN_IN_METHOD: 'facebook.com' =\n SignInMethod.FACEBOOK;\n /** Always set to {@link ProviderId}.FACEBOOK. */\n static readonly PROVIDER_ID: 'facebook.com' = ProviderId.FACEBOOK;\n\n constructor() {\n super(ProviderId.FACEBOOK);\n }\n\n /**\n * Creates a credential for Facebook.\n *\n * @example\n * ```javascript\n * // `event` from the Facebook auth.authResponseChange callback.\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param accessToken - Facebook access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: FacebookAuthProvider.PROVIDER_ID,\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return FacebookAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GoogleAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('profile');\n * provider.addScope('email');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GoogleAuthProvider();\n * provider.addScope('profile');\n * provider.addScope('email');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Google Access Token.\n * const credential = GoogleAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n *\n * @public\n */\nexport class GoogleAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GOOGLE. */\n static readonly GOOGLE_SIGN_IN_METHOD: 'google.com' = SignInMethod.GOOGLE;\n /** Always set to {@link ProviderId}.GOOGLE. */\n static readonly PROVIDER_ID: 'google.com' = ProviderId.GOOGLE;\n\n constructor() {\n super(ProviderId.GOOGLE);\n this.addScope('profile');\n }\n\n /**\n * Creates a credential for Google. At least one of ID token and access token is required.\n *\n * @example\n * ```javascript\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\n * const result = await signInWithCredential(credential);\n * ```\n *\n * @param idToken - Google ID token.\n * @param accessToken - Google access token.\n */\n static credential(\n idToken?: string | null,\n accessToken?: string | null\n ): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GoogleAuthProvider.PROVIDER_ID,\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\n idToken,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GoogleAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { oauthIdToken, oauthAccessToken } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthIdToken && !oauthAccessToken) {\n // This could be an oauth 1 credential or a phone credential\n return null;\n }\n\n try {\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\n *\n * @remarks\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\n * the {@link signInWithPopup} handler:\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new GithubAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * provider.addScope('repo');\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new GithubAuthProvider();\n * provider.addScope('repo');\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Github Access Token.\n * const credential = GithubAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * ```\n * @public\n */\nexport class GithubAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.GITHUB. */\n static readonly GITHUB_SIGN_IN_METHOD: 'github.com' = SignInMethod.GITHUB;\n /** Always set to {@link ProviderId}.GITHUB. */\n static readonly PROVIDER_ID: 'github.com' = ProviderId.GITHUB;\n\n constructor() {\n super(ProviderId.GITHUB);\n }\n\n /**\n * Creates a credential for Github.\n *\n * @param accessToken - Github access token.\n */\n static credential(accessToken: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: GithubAuthProvider.PROVIDER_ID,\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\n accessToken\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return GithubAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\n return null;\n }\n\n if (!tokenResponse.oauthAccessToken) {\n return null;\n }\n\n try {\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\n } catch {\n return null;\n }\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents the SAML credentials returned by an {@link SAMLAuthProvider}.\n *\n * @public\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { AuthCredential } from './auth_credential';\n\nconst IDP_REQUEST_URI = 'http://localhost';\n\n/**\n * @public\n */\nexport class SAMLAuthCredential extends AuthCredential {\n /** @internal */\n private constructor(\n providerId: string,\n private readonly pendingToken: string\n ) {\n super(providerId, providerId);\n }\n\n /** @internal */\n _getIdTokenResponse(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n const request = this.buildRequest();\n request.idToken = idToken;\n return signInWithIdp(auth, request);\n }\n\n /** @internal */\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n const request = this.buildRequest();\n request.autoCreate = false;\n return signInWithIdp(auth, request);\n }\n\n /** {@inheritdoc AuthCredential.toJSON} */\n toJSON(): object {\n return {\n signInMethod: this.signInMethod,\n providerId: this.providerId,\n pendingToken: this.pendingToken\n };\n }\n\n /**\n * Static method to deserialize a JSON representation of an object into an\n * {@link AuthCredential}.\n *\n * @param json - Input can be either Object or the stringified representation of the object.\n * When string is provided, JSON.parse would be called first.\n *\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\n */\n static fromJSON(json: string | object): SAMLAuthCredential | null {\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\n const { providerId, signInMethod, pendingToken }: Record =\n obj;\n if (\n !providerId ||\n !signInMethod ||\n !pendingToken ||\n providerId !== signInMethod\n ) {\n return null;\n }\n\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n /**\n * Helper static method to avoid exposing the constructor to end users.\n *\n * @internal\n */\n static _create(providerId: string, pendingToken: string): SAMLAuthCredential {\n return new SAMLAuthCredential(providerId, pendingToken);\n }\n\n private buildRequest(): SignInWithIdpRequest {\n return {\n requestUri: IDP_REQUEST_URI,\n returnSecureToken: true,\n pendingToken: this.pendingToken\n };\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredential } from '../../model/public_types';\nimport { UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { SAMLAuthCredential } from '../credentials/saml';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { FederatedAuthProvider } from './federated';\n\nconst SAML_PROVIDER_PREFIX = 'saml.';\n\n/**\n * An {@link AuthProvider} for SAML.\n *\n * @public\n */\nexport class SAMLAuthProvider extends FederatedAuthProvider {\n /**\n * Constructor. The providerId must start with \"saml.\"\n * @param providerId - SAML provider ID.\n */\n constructor(providerId: string) {\n _assert(\n providerId.startsWith(SAML_PROVIDER_PREFIX),\n AuthErrorCode.ARGUMENT_ERROR\n );\n super(providerId);\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\n * successful SAML flow completes.\n *\n * @remarks\n *\n * For example, to get an {@link AuthCredential}, you could write the\n * following code:\n *\n * ```js\n * const userCredential = await signInWithPopup(auth, samlProvider);\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\n * ```\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return SAMLAuthProvider.samlCredentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n /**\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\n * @param json - A plain object or a JSON string\n */\n static credentialFromJSON(json: string | object): AuthCredential {\n const credential = SAMLAuthCredential.fromJSON(json);\n _assert(credential, AuthErrorCode.ARGUMENT_ERROR);\n return credential;\n }\n\n private static samlCredentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): SAMLAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n\n const { pendingToken, providerId } = tokenResponse as SignInWithIdpResponse;\n\n if (!pendingToken || !providerId) {\n return null;\n }\n\n try {\n return SAMLAuthCredential._create(providerId, pendingToken);\n } catch (e) {\n return null;\n }\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @license\n * Copyright 2020 Twitter LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential } from '../../model/public_types';\nimport { FirebaseError } from '@firebase/util';\n\nimport { SignInWithIdpResponse } from '../../api/authentication/idp';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { UserCredentialInternal } from '../../model/user';\nimport { OAuthCredential } from '../credentials/oauth';\nimport { BaseOAuthProvider } from './oauth';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new TwitterAuthProvider();\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * }\n * ```\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new TwitterAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Twitter Access Token and Secret.\n * const credential = TwitterAuthProvider.credentialFromResult(result);\n * const token = credential.accessToken;\n * const secret = credential.secret;\n * ```\n *\n * @public\n */\nexport class TwitterAuthProvider extends BaseOAuthProvider {\n /** Always set to {@link SignInMethod}.TWITTER. */\n static readonly TWITTER_SIGN_IN_METHOD: 'twitter.com' = SignInMethod.TWITTER;\n /** Always set to {@link ProviderId}.TWITTER. */\n static readonly PROVIDER_ID: 'twitter.com' = ProviderId.TWITTER;\n\n constructor() {\n super(ProviderId.TWITTER);\n }\n\n /**\n * Creates a credential for Twitter.\n *\n * @param token - Twitter access token.\n * @param secret - Twitter secret.\n */\n static credential(token: string, secret: string): OAuthCredential {\n return OAuthCredential._fromParams({\n providerId: TwitterAuthProvider.PROVIDER_ID,\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\n oauthToken: token,\n oauthTokenSecret: secret\n });\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n userCredential as UserCredentialInternal\n );\n }\n\n /**\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\n * thrown during a sign-in, link, or reauthenticate operation.\n *\n * @param userCredential - The user credential.\n */\n static credentialFromError(error: FirebaseError): OAuthCredential | null {\n return TwitterAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): OAuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { oauthAccessToken, oauthTokenSecret } =\n tokenResponse as SignInWithIdpResponse;\n if (!oauthAccessToken || !oauthTokenSecret) {\n return null;\n }\n\n try {\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\n } catch {\n return null;\n }\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n RecaptchaClientType,\n RecaptchaVersion,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignUpRequest {\n idToken?: string;\n returnSecureToken?: boolean;\n email?: string;\n password?: string;\n tenantId?: string;\n captchaResponse?: string;\n clientType?: RecaptchaClientType;\n recaptchaVersion?: RecaptchaVersion;\n}\n\nexport interface SignUpResponse extends IdTokenResponse {\n displayName?: string;\n email?: string;\n}\n\nexport async function signUp(\n auth: Auth,\n request: SignUpRequest\n): Promise {\n return _performSignInRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_UP,\n _addTidIfNecessary(auth, request)\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { UserImpl } from './user_impl';\nimport { AuthInternal } from '../../model/auth';\nimport { OperationType, ProviderId } from '../../model/enums';\n\ninterface UserCredentialParams {\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse?: PhoneOrOauthTokenResponse;\n readonly operationType: OperationType;\n}\n\nexport class UserCredentialImpl\n implements UserCredentialInternal, UserCredentialParams\n{\n readonly user: UserInternal;\n readonly providerId: ProviderId | string | null;\n readonly _tokenResponse: PhoneOrOauthTokenResponse | undefined;\n readonly operationType: OperationType;\n\n constructor(params: UserCredentialParams) {\n this.user = params.user;\n this.providerId = params.providerId;\n this._tokenResponse = params._tokenResponse;\n this.operationType = params.operationType;\n }\n\n static async _fromIdTokenResponse(\n auth: AuthInternal,\n operationType: OperationType,\n idTokenResponse: IdTokenResponse,\n isAnonymous: boolean = false\n ): Promise {\n const user = await UserImpl._fromIdTokenResponse(\n auth,\n idTokenResponse,\n isAnonymous\n );\n const providerId = providerIdForResponse(idTokenResponse);\n const userCred = new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: idTokenResponse,\n operationType\n });\n return userCred;\n }\n\n static async _forOperation(\n user: UserInternal,\n operationType: OperationType,\n response: PhoneOrOauthTokenResponse\n ): Promise {\n await user._updateTokensIfNecessary(response, /* reload */ true);\n const providerId = providerIdForResponse(response);\n return new UserCredentialImpl({\n user,\n providerId,\n _tokenResponse: response,\n operationType\n });\n }\n}\n\nfunction providerIdForResponse(\n response: IdTokenResponse\n): ProviderId | string | null {\n if (response.providerId) {\n return response.providerId;\n }\n\n if ('phoneNumber' in response) {\n return ProviderId.PHONE;\n }\n\n return null;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, UserCredential } from '../../model/public_types';\nimport { signUp } from '../../api/authentication/sign_up';\nimport { UserInternal } from '../../model/user';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\n\n/**\n * Asynchronously signs in as an anonymous user.\n *\n * @remarks\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\n * new anonymous user identity will be created and returned.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport async function signInAnonymously(auth: Auth): Promise {\n const authInternal = _castAuth(auth);\n await authInternal._initializationPromise;\n if (authInternal.currentUser?.isAnonymous) {\n // If an anonymous user is already signed in, no need to sign them in again.\n return new UserCredentialImpl({\n user: authInternal.currentUser as UserInternal,\n providerId: null,\n operationType: OperationType.SIGN_IN\n });\n }\n const response = await signUp(authInternal, {\n returnSecureToken: true\n });\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response,\n true\n );\n await authInternal._updateCurrentUser(userCredential.user);\n return userCredential;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MultiFactorError as MultiFactorErrorPublic } from '../model/public_types';\nimport { FirebaseError } from '@firebase/util';\nimport { AuthInternal } from '../model/auth';\nimport { IdTokenResponse } from '../model/id_token';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserInternal } from '../model/user';\nimport { AuthCredential } from '../core/credentials';\nimport { IdTokenMfaResponse } from '../api/authentication/mfa';\nimport { OperationType } from '../model/enums';\n\nexport type MultiFactorErrorData = MultiFactorErrorPublic['customData'] & {\n _serverResponse: IdTokenMfaResponse;\n};\n\nexport class MultiFactorError\n extends FirebaseError\n implements MultiFactorErrorPublic\n{\n readonly customData: MultiFactorErrorData;\n\n private constructor(\n auth: AuthInternal,\n error: FirebaseError,\n readonly operationType: OperationType,\n readonly user?: UserInternal\n ) {\n super(error.code, error.message);\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MultiFactorError.prototype);\n this.customData = {\n appName: auth.name,\n tenantId: auth.tenantId ?? undefined,\n _serverResponse: error.customData!._serverResponse as IdTokenMfaResponse,\n operationType\n };\n }\n\n static _fromErrorAndOperation(\n auth: AuthInternal,\n error: FirebaseError,\n operationType: OperationType,\n user?: UserInternal\n ): MultiFactorError {\n return new MultiFactorError(auth, error, operationType, user);\n }\n}\n\nexport function _processCredentialSavingMfaContextIfNecessary(\n auth: AuthInternal,\n operationType: OperationType,\n credential: AuthCredential,\n user?: UserInternal\n): Promise {\n const idTokenProvider =\n operationType === OperationType.REAUTHENTICATE\n ? credential._getReauthenticationResolver(auth)\n : credential._getIdTokenResponse(auth);\n\n return idTokenProvider.catch(error => {\n if (error.code === `auth/${AuthErrorCode.MFA_REQUIRED}`) {\n throw MultiFactorError._fromErrorAndOperation(\n auth,\n error,\n operationType,\n user\n );\n }\n\n throw error;\n });\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ProviderAssociatedObject {\n providerId?: string;\n}\n\n/**\n * Takes a set of UserInfo provider data and converts it to a set of names\n */\nexport function providerDataAsNames(\n providerData: T[]\n): Set {\n return new Set(\n providerData\n .map(({ providerId }) => providerId)\n .filter(pid => !!pid) as string[]\n );\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../../model/public_types';\n\nimport { deleteLinkedAccounts } from '../../api/account_management/account';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { providerDataAsNames } from '../util/providers';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { _reloadWithoutSaving } from './reload';\nimport { UserCredentialImpl } from './user_credential_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType, ProviderId } from '../../model/enums';\n\n/**\n * Unlinks a provider from a user account.\n *\n * @param user - The user.\n * @param providerId - The provider to unlink.\n *\n * @public\n */\nexport async function unlink(user: User, providerId: string): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(true, userInternal, providerId);\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\n idToken: await userInternal.getIdToken(),\n deleteProvider: [providerId]\n });\n\n const providersLeft = providerDataAsNames(providerUserInfo || []);\n\n userInternal.providerData = userInternal.providerData.filter(pd =>\n providersLeft.has(pd.providerId)\n );\n if (!providersLeft.has(ProviderId.PHONE)) {\n userInternal.phoneNumber = null;\n }\n\n await userInternal.auth._persistUserIfCurrent(userInternal);\n return userInternal;\n}\n\nexport async function _link(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n const response = await _logoutIfInvalidated(\n user,\n credential._linkToIdToken(user.auth, await user.getIdToken()),\n bypassAuthState\n );\n return UserCredentialImpl._forOperation(user, OperationType.LINK, response);\n}\n\nexport async function _assertLinkedStatus(\n expected: boolean,\n user: UserInternal,\n provider: string\n): Promise {\n await _reloadWithoutSaving(user);\n const providerIds = providerDataAsNames(user.providerData);\n\n const code =\n expected === false\n ? AuthErrorCode.PROVIDER_ALREADY_LINKED\n : AuthErrorCode.NO_SUCH_PROVIDER;\n _assert(providerIds.has(provider) === expected, user.auth, code);\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { OperationType } from '../../model/enums';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { AuthErrorCode } from '../errors';\nimport { _assert, _fail } from '../util/assert';\nimport { _parseToken } from './id_token_result';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { UserCredentialImpl } from './user_credential_impl';\n\nexport async function _reauthenticate(\n user: UserInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n const { auth } = user;\n const operationType = OperationType.REAUTHENTICATE;\n\n try {\n const response = await _logoutIfInvalidated(\n user,\n _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential,\n user\n ),\n bypassAuthState\n );\n _assert(response.idToken, auth, AuthErrorCode.INTERNAL_ERROR);\n const parsed = _parseToken(response.idToken);\n _assert(parsed, auth, AuthErrorCode.INTERNAL_ERROR);\n\n const { sub: localId } = parsed;\n _assert(user.uid === localId, auth, AuthErrorCode.USER_MISMATCH);\n\n return UserCredentialImpl._forOperation(user, operationType, response);\n } catch (e) {\n // Convert user deleted error into user mismatch\n if ((e as FirebaseError)?.code === `auth/${AuthErrorCode.USER_DELETED}`) {\n _fail(auth, AuthErrorCode.USER_MISMATCH);\n }\n throw e;\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserCredential, Auth, User } from '../../model/public_types';\n\nimport { _processCredentialSavingMfaContextIfNecessary } from '../../mfa/mfa_error';\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _assertLinkedStatus, _link } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\n\nexport async function _signInWithCredential(\n auth: AuthInternal,\n credential: AuthCredential,\n bypassAuthState = false\n): Promise {\n const operationType = OperationType.SIGN_IN;\n const response = await _processCredentialSavingMfaContextIfNecessary(\n auth,\n operationType,\n credential\n );\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n auth,\n operationType,\n response\n );\n\n if (!bypassAuthState) {\n await auth._updateCurrentUser(userCredential.user);\n }\n return userCredential;\n}\n\n/**\n * Asynchronously signs in with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param auth - The {@link Auth} instance.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function signInWithCredential(\n auth: Auth,\n credential: AuthCredential\n): Promise {\n return _signInWithCredential(_castAuth(auth), credential);\n}\n\n/**\n * Links the user account with the given credentials.\n *\n * @remarks\n * An {@link AuthProvider} can be used to generate the credential.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function linkWithCredential(\n user: User,\n credential: AuthCredential\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n\n await _assertLinkedStatus(false, userInternal, credential.providerId);\n\n return _link(userInternal, credential);\n}\n\n/**\n * Re-authenticates a user using a fresh credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\n * or a `TOKEN_EXPIRED` error.\n *\n * @param user - The user.\n * @param credential - The auth credential.\n *\n * @public\n */\nexport async function reauthenticateWithCredential(\n user: User,\n credential: AuthCredential\n): Promise {\n return _reauthenticate(getModularInstance(user) as UserInternal, credential);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performSignInRequest\n} from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface SignInWithCustomTokenRequest {\n token: string;\n returnSecureToken: boolean;\n tenantId?: string;\n}\n\nexport interface SignInWithCustomTokenResponse extends IdTokenResponse {}\n\nexport async function signInWithCustomToken(\n auth: Auth,\n request: SignInWithCustomTokenRequest\n): Promise {\n return _performSignInRequest<\n SignInWithCustomTokenRequest,\n SignInWithCustomTokenResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN,\n _addTidIfNecessary(auth, request)\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, UserCredential } from '../../model/public_types';\n\nimport { signInWithCustomToken as getIdTokenResponse } from '../../api/authentication/custom_token';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _castAuth } from '../auth/auth_impl';\nimport { OperationType } from '../../model/enums';\n\n/**\n * Asynchronously signs in using a custom token.\n *\n * @remarks\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\n * be generated by an auth backend using the\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\n *\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\n *\n * @param auth - The {@link Auth} instance.\n * @param customToken - The custom token to sign in with.\n *\n * @public\n */\nexport async function signInWithCustomToken(\n auth: Auth,\n customToken: string\n): Promise {\n const authInternal = _castAuth(auth);\n const response: IdTokenResponse = await getIdTokenResponse(authInternal, {\n token: customToken,\n returnSecureToken: true\n });\n const cred = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(cred.user);\n return cred;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FactorId,\n MultiFactorInfo,\n PhoneMultiFactorInfo,\n TotpMultiFactorInfo\n} from '../model/public_types';\nimport {\n PhoneMfaEnrollment,\n MfaEnrollment,\n TotpMfaEnrollment\n} from '../api/account_management/mfa';\nimport { AuthErrorCode } from '../core/errors';\nimport { _fail } from '../core/util/assert';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorInfoImpl implements MultiFactorInfo {\n readonly uid: string;\n readonly displayName?: string | null;\n readonly enrollmentTime: string;\n\n protected constructor(readonly factorId: FactorId, response: MfaEnrollment) {\n this.uid = response.mfaEnrollmentId;\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\n this.displayName = response.displayName;\n }\n\n static _fromServerResponse(\n auth: AuthInternal,\n enrollment: MfaEnrollment\n ): MultiFactorInfoImpl {\n if ('phoneInfo' in enrollment) {\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n } else if ('totpInfo' in enrollment) {\n return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\n }\n return _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n}\n\nexport class PhoneMultiFactorInfoImpl\n extends MultiFactorInfoImpl\n implements PhoneMultiFactorInfo\n{\n readonly phoneNumber: string;\n\n private constructor(response: PhoneMfaEnrollment) {\n super(FactorId.PHONE, response);\n this.phoneNumber = response.phoneInfo;\n }\n\n static _fromServerResponse(\n _auth: AuthInternal,\n enrollment: MfaEnrollment\n ): PhoneMultiFactorInfoImpl {\n return new PhoneMultiFactorInfoImpl(enrollment as PhoneMfaEnrollment);\n }\n}\nexport class TotpMultiFactorInfoImpl\n extends MultiFactorInfoImpl\n implements TotpMultiFactorInfo\n{\n private constructor(response: TotpMfaEnrollment) {\n super(FactorId.TOTP, response);\n }\n\n static _fromServerResponse(\n _auth: AuthInternal,\n enrollment: MfaEnrollment\n ): TotpMultiFactorInfoImpl {\n return new TotpMultiFactorInfoImpl(enrollment as TotpMfaEnrollment);\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ActionCodeSettings, Auth } from '../../model/public_types';\n\nimport { GetOobCodeRequest } from '../../api/authentication/email_and_password';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\n\nexport function _setActionCodeSettingsOnRequest(\n auth: Auth,\n request: GetOobCodeRequest,\n actionCodeSettings: ActionCodeSettings\n): void {\n _assert(\n actionCodeSettings.url?.length > 0,\n auth,\n AuthErrorCode.INVALID_CONTINUE_URI\n );\n _assert(\n typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\n actionCodeSettings.dynamicLinkDomain.length > 0,\n auth,\n AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN\n );\n\n request.continueUrl = actionCodeSettings.url;\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\n\n if (actionCodeSettings.iOS) {\n _assert(\n actionCodeSettings.iOS.bundleId.length > 0,\n auth,\n AuthErrorCode.MISSING_IOS_BUNDLE_ID\n );\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\n }\n\n if (actionCodeSettings.android) {\n _assert(\n actionCodeSettings.android.packageName.length > 0,\n auth,\n AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME\n );\n request.androidInstallApp = actionCodeSettings.android.installApp;\n request.androidMinimumVersionCode =\n actionCodeSettings.android.minimumVersion;\n request.androidPackageName = actionCodeSettings.android.packageName;\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeInfo,\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as account from '../../api/account_management/email_and_password';\nimport * as authentication from '../../api/authentication/email_and_password';\nimport { signUp, SignUpRequest } from '../../api/authentication/sign_up';\nimport { MultiFactorInfoImpl } from '../../mfa/mfa_info';\nimport { EmailAuthProvider } from '../providers/email';\nimport { UserCredentialImpl } from '../user/user_credential_impl';\nimport { _assert } from '../util/assert';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { _castAuth } from '../auth/auth_impl';\nimport { AuthErrorCode } from '../errors';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../../model/enums';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\n\n/**\n * Updates the password policy cached in the {@link Auth} instance if a policy is already\n * cached for the project or tenant.\n *\n * @remarks\n * We only fetch the password policy if the password did not meet policy requirements and\n * there is an existing policy cached. A developer must call validatePassword at least\n * once for the cache to be automatically updated.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @private\n */\nasync function recachePasswordPolicy(auth: Auth): Promise {\n const authInternal = _castAuth(auth);\n if (authInternal._getPasswordPolicyInternal()) {\n await authInternal._updatePasswordPolicy();\n }\n}\n\n/**\n * Sends a password reset email to the given email address. This method does not throw an error when\n * there's no user account with the given email address and\n * [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection) is enabled.\n *\n * @remarks\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\n * the email sent to the user, along with the new password specified by the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain code from user.\n * await confirmPasswordReset('user@example.com', code);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendPasswordResetEmail(\n auth: Auth,\n email: string,\n actionCodeSettings?: ActionCodeSettings\n): Promise {\n const authInternal = _castAuth(auth);\n const request: authentication.PasswordResetRequest = {\n requestType: ActionCodeOperation.PASSWORD_RESET,\n email,\n clientType: RecaptchaClientType.WEB\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\n }\n await handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.GET_OOB_CODE,\n authentication.sendPasswordResetEmail\n );\n}\n\n/**\n * Completes the password reset process, given a confirmation code and new password.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A confirmation code sent to the user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport async function confirmPasswordReset(\n auth: Auth,\n oobCode: string,\n newPassword: string\n): Promise {\n await account\n .resetPassword(getModularInstance(auth), {\n oobCode,\n newPassword\n })\n .catch(async error => {\n if (\n error.code ===\n `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n // Do not return the email.\n}\n\n/**\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function applyActionCode(\n auth: Auth,\n oobCode: string\n): Promise {\n await account.applyActionCode(getModularInstance(auth), { oobCode });\n}\n\n/**\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\n *\n * @returns metadata about the code.\n *\n * @param auth - The {@link Auth} instance.\n * @param oobCode - A verification code sent to the user.\n *\n * @public\n */\nexport async function checkActionCode(\n auth: Auth,\n oobCode: string\n): Promise {\n const authModular = getModularInstance(auth);\n const response = await account.resetPassword(authModular, { oobCode });\n\n // Email could be empty only if the request type is EMAIL_SIGNIN or\n // VERIFY_AND_CHANGE_EMAIL.\n // New email should not be empty if the request type is\n // VERIFY_AND_CHANGE_EMAIL.\n // Multi-factor info could not be empty if the request type is\n // REVERT_SECOND_FACTOR_ADDITION.\n const operation = response.requestType;\n _assert(operation, authModular, AuthErrorCode.INTERNAL_ERROR);\n switch (operation) {\n case ActionCodeOperation.EMAIL_SIGNIN:\n break;\n case ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL:\n _assert(response.newEmail, authModular, AuthErrorCode.INTERNAL_ERROR);\n break;\n case ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION:\n _assert(response.mfaInfo, authModular, AuthErrorCode.INTERNAL_ERROR);\n // fall through\n default:\n _assert(response.email, authModular, AuthErrorCode.INTERNAL_ERROR);\n }\n\n // The multi-factor info for revert second factor addition\n let multiFactorInfo: MultiFactorInfoImpl | null = null;\n if (response.mfaInfo) {\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(\n _castAuth(authModular),\n response.mfaInfo\n );\n }\n\n return {\n data: {\n email:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.newEmail\n : response.email) || null,\n previousEmail:\n (response.requestType === ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL\n ? response.email\n : response.newEmail) || null,\n multiFactorInfo\n },\n operation\n };\n}\n\n/**\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\n *\n * @returns the user's email address if valid.\n *\n * @param auth - The {@link Auth} instance.\n * @param code - A verification code sent to the user.\n *\n * @public\n */\nexport async function verifyPasswordResetCode(\n auth: Auth,\n code: string\n): Promise {\n const { data } = await checkActionCode(getModularInstance(auth), code);\n // Email should always be present since a code was sent to it\n return data.email!;\n}\n\n/**\n * Creates a new user account associated with the specified email address and password.\n *\n * @remarks\n * On successful creation of the user account, this user will also be signed in to your application.\n *\n * User account creation can fail if the account already exists or the password is invalid.\n *\n * Note: The email address acts as a unique identifier for the user and enables an email-based\n * password reset. This function will create a new user account and set the initial user password.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param password - The user's chosen password.\n *\n * @public\n */\nexport async function createUserWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise {\n const authInternal = _castAuth(auth);\n const request: SignUpRequest = {\n returnSecureToken: true,\n email,\n password,\n clientType: RecaptchaClientType.WEB\n };\n const signUpResponse: Promise = handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.SIGN_UP_PASSWORD,\n signUp\n );\n const response = await signUpResponse.catch(error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(\n authInternal,\n OperationType.SIGN_IN,\n response\n );\n await authInternal._updateCurrentUser(userCredential.user);\n\n return userCredential;\n}\n\n/**\n * Asynchronously signs in using an email and password.\n *\n * @remarks\n * Fails with an error if the email address and password do not match.\n * When [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection) is enabled,\n * this method fails with \"auth/invalid-credential\" in case of an invalid email/password.\n *\n * Note: The user's password is NOT the password used to access the user's email account. The\n * email address serves as a unique identifier for the user, and the password is used to access\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The users email address.\n * @param password - The users password.\n *\n * @public\n */\nexport function signInWithEmailAndPassword(\n auth: Auth,\n email: string,\n password: string\n): Promise {\n return signInWithCredential(\n getModularInstance(auth),\n EmailAuthProvider.credential(email, password)\n ).catch(async error => {\n if (\n error.code === `auth/${AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS}`\n ) {\n void recachePasswordPolicy(auth);\n }\n\n throw error;\n });\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n UserCredential\n} from '../../model/public_types';\n\nimport * as api from '../../api/authentication/email_and_password';\nimport { ActionCodeURL } from '../action_code_url';\nimport { EmailAuthProvider } from '../providers/email';\nimport { _getCurrentUrl } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { getModularInstance } from '@firebase/util';\nimport { _castAuth } from '../auth/auth_impl';\nimport { handleRecaptchaFlow } from '../../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { RecaptchaActionName, RecaptchaClientType } from '../../api';\n\n/**\n * Sends a sign-in email link to the user with the specified email.\n *\n * @remarks\n * The sign-in operation has to always be completed in the app unlike other out of band email\n * actions (password reset and email verifications). This is because, at the end of the flow,\n * the user is expected to be signed in and their Auth state persisted within the app.\n *\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\n * address and the email link supplied in the email sent to the user.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n * @param authInternal - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendSignInLinkToEmail(\n auth: Auth,\n email: string,\n actionCodeSettings: ActionCodeSettings\n): Promise {\n const authInternal = _castAuth(auth);\n const request: api.EmailSignInRequest = {\n requestType: ActionCodeOperation.EMAIL_SIGNIN,\n email,\n clientType: RecaptchaClientType.WEB\n };\n function setActionCodeSettings(\n request: api.EmailSignInRequest,\n actionCodeSettings: ActionCodeSettings\n ): void {\n _assert(\n actionCodeSettings.handleCodeInApp,\n authInternal,\n AuthErrorCode.ARGUMENT_ERROR\n );\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n authInternal,\n request,\n actionCodeSettings\n );\n }\n }\n setActionCodeSettings(request, actionCodeSettings);\n await handleRecaptchaFlow(\n authInternal,\n request,\n RecaptchaActionName.GET_OOB_CODE,\n api.sendSignInLinkToEmail\n );\n}\n\n/**\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\n *\n * @param auth - The {@link Auth} instance.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport function isSignInWithEmailLink(auth: Auth, emailLink: string): boolean {\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\n return actionCodeUrl?.operation === ActionCodeOperation.EMAIL_SIGNIN;\n}\n\n/**\n * Asynchronously signs in using an email and sign-in email link.\n *\n * @remarks\n * If no link is passed, the link is inferred from the current URL.\n *\n * Fails with an error if the email address is invalid or OTP in email link expires.\n *\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\n * // Obtain emailLink from the user.\n * if(isSignInWithEmailLink(auth, emailLink)) {\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\n * }\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n * @param emailLink - The link sent to the user's email address.\n *\n * @public\n */\nexport async function signInWithEmailLink(\n auth: Auth,\n email: string,\n emailLink?: string\n): Promise {\n const authModular = getModularInstance(auth);\n const credential = EmailAuthProvider.credentialWithLink(\n email,\n emailLink || _getCurrentUrl()\n );\n // Check if the tenant ID in the email link matches the tenant ID on Auth\n // instance.\n _assert(\n credential._tenantId === (authModular.tenantId || null),\n authModular,\n AuthErrorCode.TENANT_ID_MISMATCH\n );\n return signInWithCredential(authModular, credential);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface CreateAuthUriRequest {\n identifier: string;\n continueUri: string;\n tenantId?: string;\n}\n\nexport interface CreateAuthUriResponse {\n signinMethods: string[];\n}\n\nexport async function createAuthUri(\n auth: Auth,\n request: CreateAuthUriRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.CREATE_AUTH_URI,\n _addTidIfNecessary(auth, request)\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ActionCodeOperation,\n ActionCodeSettings,\n Auth,\n User\n} from '../../model/public_types';\n\nimport {\n createAuthUri,\n CreateAuthUriRequest\n} from '../../api/authentication/create_auth_uri';\nimport * as api from '../../api/authentication/email_and_password';\nimport { UserInternal } from '../../model/user';\nimport { _getCurrentUrl, _isHttpOrHttps } from '../util/location';\nimport { _setActionCodeSettingsOnRequest } from './action_code_settings';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Gets the list of possible sign in methods for the given email address. This method returns an\n * empty list when [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection) is enabled, irrespective of the number of\n * authentication methods available for the given email.\n *\n * @remarks\n * This is useful to differentiate methods of sign-in for the same provider, eg.\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\n * {@link SignInMethod}.EMAIL_PASSWORD and\n * {@link SignInMethod}.EMAIL_LINK.\n *\n * @param auth - The {@link Auth} instance.\n * @param email - The user's email address.\n *\n * Deprecated. Migrating off of this method is recommended as a security best-practice.\n * Learn more in the Identity Platform documentation for [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection).\n * @public\n */\nexport async function fetchSignInMethodsForEmail(\n auth: Auth,\n email: string\n): Promise {\n // createAuthUri returns an error if continue URI is not http or https.\n // For environments like Cordova, Chrome extensions, native frameworks, file\n // systems, etc, use http://localhost as continue URL.\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\n const request: CreateAuthUriRequest = {\n identifier: email,\n continueUri\n };\n\n const { signinMethods } = await createAuthUri(\n getModularInstance(auth),\n request\n );\n\n return signinMethods || [];\n}\n\n/**\n * Sends a verification email to a user.\n *\n * @remarks\n * The verification process is completed by calling {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await sendEmailVerification(user, actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function sendEmailVerification(\n user: User,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_EMAIL,\n idToken\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.sendEmailVerification(userInternal.auth, request);\n\n if (email !== user.email) {\n await user.reload();\n }\n}\n\n/**\n * Sends a verification email to a new email address.\n *\n * @remarks\n * The user's email will be updated to the new one after being verified.\n *\n * If you have a custom email action handler, you can complete the verification process by calling\n * {@link applyActionCode}.\n *\n * @example\n * ```javascript\n * const actionCodeSettings = {\n * url: 'https://www.example.com/?email=user@example.com',\n * iOS: {\n * bundleId: 'com.example.ios'\n * },\n * android: {\n * packageName: 'com.example.android',\n * installApp: true,\n * minimumVersion: '12'\n * },\n * handleCodeInApp: true\n * };\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\n * // Obtain code from the user.\n * await applyActionCode(auth, code);\n * ```\n *\n * @param user - The user.\n * @param newEmail - The new email address to be verified before update.\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\n *\n * @public\n */\nexport async function verifyBeforeUpdateEmail(\n user: User,\n newEmail: string,\n actionCodeSettings?: ActionCodeSettings | null\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await user.getIdToken();\n const request: api.VerifyAndChangeEmailRequest = {\n requestType: ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,\n idToken,\n newEmail\n };\n if (actionCodeSettings) {\n _setActionCodeSettingsOnRequest(\n userInternal.auth,\n request,\n actionCodeSettings\n );\n }\n\n const { email } = await api.verifyAndChangeEmail(userInternal.auth, request);\n\n if (email !== user.email) {\n // If the local copy of the email on user is outdated, reload the\n // user.\n await user.reload();\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Endpoint, HttpMethod, _performApiRequest } from '../index';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { Auth } from '../../model/public_types';\n\nexport interface UpdateProfileRequest {\n idToken: string;\n displayName?: string | null;\n photoUrl?: string | null;\n returnSecureToken: boolean;\n}\n\nexport interface UpdateProfileResponse extends IdTokenResponse {\n displayName?: string | null;\n photoUrl?: string | null;\n}\n\nexport async function updateProfile(\n auth: Auth,\n request: UpdateProfileRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.SET_ACCOUNT_INFO,\n request\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../../model/public_types';\n\nimport {\n updateEmailPassword as apiUpdateEmailPassword,\n UpdateEmailPasswordRequest\n} from '../../api/account_management/email_and_password';\nimport { updateProfile as apiUpdateProfile } from '../../api/account_management/profile';\nimport { UserInternal } from '../../model/user';\nimport { _logoutIfInvalidated } from './invalidation';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\n\n/**\n * Updates a user's profile data.\n *\n * @param user - The user.\n * @param profile - The profile's `displayName` and `photoURL` to update.\n *\n * @public\n */\nexport async function updateProfile(\n user: User,\n {\n displayName,\n photoURL: photoUrl\n }: { displayName?: string | null; photoURL?: string | null }\n): Promise {\n if (displayName === undefined && photoUrl === undefined) {\n return;\n }\n\n const userInternal = getModularInstance(user) as UserInternal;\n const idToken = await userInternal.getIdToken();\n const profileRequest = {\n idToken,\n displayName,\n photoUrl,\n returnSecureToken: true\n };\n const response = await _logoutIfInvalidated(\n userInternal,\n apiUpdateProfile(userInternal.auth, profileRequest)\n );\n\n userInternal.displayName = response.displayName || null;\n userInternal.photoURL = response.photoUrl || null;\n\n // Update the password provider as well\n const passwordProvider = userInternal.providerData.find(\n ({ providerId }) => providerId === ProviderId.PASSWORD\n );\n if (passwordProvider) {\n passwordProvider.displayName = userInternal.displayName;\n passwordProvider.photoURL = userInternal.photoURL;\n }\n\n await userInternal._updateTokensIfNecessary(response);\n}\n\n/**\n * Updates the user's email address.\n *\n * @remarks\n * An email will be sent to the original email address (if it was set) that allows to revoke the\n * email address change, in order to protect them from account hijacking.\n *\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newEmail - The new email address.\n *\n * Throws \"auth/operation-not-allowed\" error when [Email Enumeration Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection) is enabled.\n * Deprecated - Use {@link verifyBeforeUpdateEmail} instead.\n *\n * @public\n */\nexport function updateEmail(user: User, newEmail: string): Promise {\n return updateEmailOrPassword(\n getModularInstance(user) as UserInternal,\n newEmail,\n null\n );\n}\n\n/**\n * Updates the user's password.\n *\n * @remarks\n * Important: this is a security sensitive operation that requires the user to have recently signed\n * in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n * @param newPassword - The new password.\n *\n * @public\n */\nexport function updatePassword(user: User, newPassword: string): Promise {\n return updateEmailOrPassword(\n getModularInstance(user) as UserInternal,\n null,\n newPassword\n );\n}\n\nasync function updateEmailOrPassword(\n user: UserInternal,\n email: string | null,\n password: string | null\n): Promise {\n const { auth } = user;\n const idToken = await user.getIdToken();\n const request: UpdateEmailPasswordRequest = {\n idToken,\n returnSecureToken: true\n };\n\n if (email) {\n request.email = email;\n }\n\n if (password) {\n request.password = password;\n }\n\n const response = await _logoutIfInvalidated(\n user,\n apiUpdateEmailPassword(auth, request)\n );\n await user._updateTokensIfNecessary(response, /* reload */ true);\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AdditionalUserInfo, UserCredential } from '../../model/public_types';\nimport { IdTokenResponse, IdTokenResponseKind } from '../../model/id_token';\nimport { _parseToken } from './id_token_result';\nimport { UserCredentialInternal } from '../../model/user';\nimport { ProviderId } from '../../model/enums';\n\n/**\n * Parse the `AdditionalUserInfo` from the ID token response.\n *\n */\nexport function _fromIdTokenResponse(\n idTokenResponse?: IdTokenResponse\n): AdditionalUserInfo | null {\n if (!idTokenResponse) {\n return null;\n }\n const { providerId } = idTokenResponse;\n const profile = idTokenResponse.rawUserInfo\n ? JSON.parse(idTokenResponse.rawUserInfo)\n : {};\n const isNewUser =\n idTokenResponse.isNewUser ||\n idTokenResponse.kind === IdTokenResponseKind.SignupNewUser;\n if (!providerId && idTokenResponse?.idToken) {\n const signInProvider = _parseToken(idTokenResponse.idToken)?.firebase?.[\n 'sign_in_provider'\n ];\n if (signInProvider) {\n const filteredProviderId =\n signInProvider !== ProviderId.ANONYMOUS &&\n signInProvider !== ProviderId.CUSTOM\n ? (signInProvider as ProviderId)\n : null;\n // Uses generic class in accordance with the legacy SDK.\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\n }\n }\n if (!providerId) {\n return null;\n }\n switch (providerId) {\n case ProviderId.FACEBOOK:\n return new FacebookAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GITHUB:\n return new GithubAdditionalUserInfo(isNewUser, profile);\n case ProviderId.GOOGLE:\n return new GoogleAdditionalUserInfo(isNewUser, profile);\n case ProviderId.TWITTER:\n return new TwitterAdditionalUserInfo(\n isNewUser,\n profile,\n idTokenResponse.screenName || null\n );\n case ProviderId.CUSTOM:\n case ProviderId.ANONYMOUS:\n return new GenericAdditionalUserInfo(isNewUser, null);\n default:\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\n }\n}\n\nclass GenericAdditionalUserInfo implements AdditionalUserInfo {\n constructor(\n readonly isNewUser: boolean,\n readonly providerId: ProviderId | string | null,\n readonly profile: Record = {}\n ) {}\n}\n\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\n constructor(\n isNewUser: boolean,\n providerId: ProviderId,\n profile: Record,\n readonly username: string | null\n ) {\n super(isNewUser, providerId, profile);\n }\n}\n\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record) {\n super(isNewUser, ProviderId.FACEBOOK, profile);\n }\n}\n\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(isNewUser: boolean, profile: Record) {\n super(\n isNewUser,\n ProviderId.GITHUB,\n profile,\n typeof profile?.login === 'string' ? profile?.login : null\n );\n }\n}\n\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\n constructor(isNewUser: boolean, profile: Record) {\n super(isNewUser, ProviderId.GOOGLE, profile);\n }\n}\n\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\n constructor(\n isNewUser: boolean,\n profile: Record,\n screenName: string | null\n ) {\n super(isNewUser, ProviderId.TWITTER, profile, screenName);\n }\n}\n\n/**\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\n *\n * @param userCredential - The user credential.\n *\n * @public\n */\nexport function getAdditionalUserInfo(\n userCredential: UserCredential\n): AdditionalUserInfo | null {\n const { user, _tokenResponse } = userCredential as UserCredentialInternal;\n if (user.isAnonymous && !_tokenResponse) {\n // Handle the special case where signInAnonymously() gets called twice.\n // No network call is made so there's nothing to actually fill this in\n return {\n providerId: null,\n isNewUser: false,\n profile: null\n };\n }\n\n return _fromIdTokenResponse(_tokenResponse);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\nimport {\n Auth,\n NextOrObserver,\n Persistence,\n User,\n CompleteFn,\n ErrorFn,\n Unsubscribe,\n PasswordValidationStatus\n} from '../model/public_types';\nimport { _initializeRecaptchaConfig } from '../platform_browser/recaptcha/recaptcha_enterprise_verifier';\nimport { _castAuth } from '../core/auth/auth_impl';\n\nexport {\n debugErrorMap,\n prodErrorMap,\n AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as AuthErrorCodes\n} from './errors';\n\n// Non-optional auth methods.\n/**\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\n * `Auth` session and applies this type of persistence for future sign-in requests, including\n * sign-in with redirect requests.\n *\n * @remarks\n * This makes it easy for a user signing in to specify whether their session should be\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\n * that are shared by other users or have sensitive data.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * setPersistence(auth, browserSessionPersistence);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param persistence - The {@link Persistence} to use.\n * @returns A `Promise` that resolves once the persistence change has completed\n *\n * @public\n */\nexport function setPersistence(\n auth: Auth,\n persistence: Persistence\n): Promise {\n return getModularInstance(auth).setPersistence(persistence);\n}\n\n/**\n * Loads the reCAPTCHA configuration into the `Auth` instance.\n *\n * @remarks\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\n * verification flow should be triggered for each auth provider, into the\n * current Auth session.\n *\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\n * auth flows.\n *\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * initializeRecaptchaConfig(auth);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function initializeRecaptchaConfig(auth: Auth): Promise {\n return _initializeRecaptchaConfig(auth);\n}\n\n/**\n * Validates the password against the password policy configured for the project or tenant.\n *\n * @remarks\n * If no tenant ID is set on the `Auth` instance, then this method will use the password\n * policy configured for the project. Otherwise, this method will use the policy configured\n * for the tenant. If a password policy has not been configured, then the default policy\n * configured for all projects will be used.\n *\n * If an auth flow fails because a submitted password does not meet the password policy\n * requirements and this method has previously been called, then this method will use the\n * most recent policy available when called again.\n *\n * @example\n * ```javascript\n * validatePassword(auth, 'some-password');\n * ```\n *\n * @param auth The {@link Auth} instance.\n * @param password The password to validate.\n *\n * @public\n */\nexport async function validatePassword(\n auth: Auth,\n password: string\n): Promise {\n const authInternal = _castAuth(auth);\n return authInternal.validatePassword(password);\n}\n\n/**\n * Adds an observer for changes to the signed-in user's ID token.\n *\n * @remarks\n * This includes sign-in, sign-out, and token refresh events.\n * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onIdTokenChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onIdTokenChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Adds a blocking callback that runs before an auth state change\n * sets a new user.\n *\n * @param auth - The {@link Auth} instance.\n * @param callback - callback triggered before new user value is set.\n * If this throws, it blocks the user from being set.\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\n * callback throws, allowing you to undo any side effects.\n */\nexport function beforeAuthStateChanged(\n auth: Auth,\n callback: (user: User | null) => void | Promise,\n onAbort?: () => void\n): Unsubscribe {\n return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\n}\n/**\n * Adds an observer for changes to the user's sign-in state.\n *\n * @remarks\n * To keep the old behavior, see {@link onIdTokenChanged}.\n *\n * @param auth - The {@link Auth} instance.\n * @param nextOrObserver - callback triggered on change.\n * @param error - Deprecated. This callback is never triggered. Errors\n * on signing in/out can be caught in promises returned from\n * sign-in/sign-out functions.\n * @param completed - Deprecated. This callback is never triggered.\n *\n * @public\n */\nexport function onAuthStateChanged(\n auth: Auth,\n nextOrObserver: NextOrObserver,\n error?: ErrorFn,\n completed?: CompleteFn\n): Unsubscribe {\n return getModularInstance(auth).onAuthStateChanged(\n nextOrObserver,\n error,\n completed\n );\n}\n/**\n * Sets the current language to the default device/browser preference.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function useDeviceLanguage(auth: Auth): void {\n getModularInstance(auth).useDeviceLanguage();\n}\n/**\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\n * {@link Auth} instance.\n *\n * @remarks\n * A new instance copy of the user provided will be made and set as currentUser.\n *\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\n * like other sign in methods.\n *\n * The operation fails with an error if the user to be updated belongs to a different Firebase\n * project.\n *\n * @param auth - The {@link Auth} instance.\n * @param user - The new {@link User}.\n *\n * @public\n */\nexport function updateCurrentUser(\n auth: Auth,\n user: User | null\n): Promise {\n return getModularInstance(auth).updateCurrentUser(user);\n}\n/**\n * Signs out the current user.\n *\n * @param auth - The {@link Auth} instance.\n *\n * @public\n */\nexport function signOut(auth: Auth): Promise {\n return getModularInstance(auth).signOut();\n}\n\n/**\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\n *\n * @param auth - The {@link Auth} instance.\n * @param token - The Apple OAuth access token.\n *\n * @public\n */\nexport function revokeAccessToken(auth: Auth, token: string): Promise {\n const authInternal = _castAuth(auth);\n return authInternal.revokeAccessToken(token);\n}\n\nexport { initializeAuth } from './auth/initialize';\nexport { connectAuthEmulator } from './auth/emulator';\n\n// credentials\nexport { AuthCredential } from './credentials';\nexport { EmailAuthCredential } from './credentials/email';\nexport { OAuthCredential } from './credentials/oauth';\nexport { PhoneAuthCredential } from './credentials/phone';\n\n// persistence\nexport { inMemoryPersistence } from './persistence/in_memory';\n\n// providers\nexport { EmailAuthProvider } from './providers/email';\nexport { FacebookAuthProvider } from './providers/facebook';\nexport { CustomParameters } from './providers/federated';\nexport { GoogleAuthProvider } from './providers/google';\nexport { GithubAuthProvider } from './providers/github';\nexport { OAuthProvider, OAuthCredentialOptions } from './providers/oauth';\nexport { SAMLAuthProvider } from './providers/saml';\nexport { TwitterAuthProvider } from './providers/twitter';\n\n// strategies\nexport { signInAnonymously } from './strategies/anonymous';\nexport {\n signInWithCredential,\n linkWithCredential,\n reauthenticateWithCredential\n} from './strategies/credential';\nexport { signInWithCustomToken } from './strategies/custom_token';\nexport {\n sendPasswordResetEmail,\n confirmPasswordReset,\n applyActionCode,\n checkActionCode,\n verifyPasswordResetCode,\n createUserWithEmailAndPassword,\n signInWithEmailAndPassword\n} from './strategies/email_and_password';\nexport {\n sendSignInLinkToEmail,\n isSignInWithEmailLink,\n signInWithEmailLink\n} from './strategies/email_link';\nexport {\n fetchSignInMethodsForEmail,\n sendEmailVerification,\n verifyBeforeUpdateEmail\n} from './strategies/email';\n\n// core\nexport { ActionCodeURL, parseActionCodeURL } from './action_code_url';\n\n// user\nexport {\n updateProfile,\n updateEmail,\n updatePassword\n} from './user/account_info';\nexport { getIdToken, getIdTokenResult } from './user/id_token_result';\nexport { unlink } from './user/link_unlink';\nexport { getAdditionalUserInfo } from './user/additional_user_info';\n\n// Non-optional user methods.\nexport { reload } from './user/reload';\n/**\n * Deletes and signs out the user.\n *\n * @remarks\n * Important: this is a security-sensitive operation that requires the user to have recently\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\n * {@link reauthenticateWithCredential}.\n *\n * @param user - The user.\n *\n * @public\n */\nexport async function deleteUser(user: User): Promise {\n return getModularInstance(user).delete();\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { UserInternal } from '../model/user';\nimport { MultiFactorSession } from '../model/public_types';\n\nexport const enum MultiFactorSessionType {\n ENROLL = 'enroll',\n SIGN_IN = 'signin'\n}\n\ninterface SerializedMultiFactorSession {\n multiFactorSession: {\n idToken?: string;\n pendingCredential?: string;\n };\n}\n\nexport class MultiFactorSessionImpl implements MultiFactorSession {\n private constructor(\n readonly type: MultiFactorSessionType,\n readonly credential: string,\n readonly user?: UserInternal\n ) {}\n\n static _fromIdtoken(\n idToken: string,\n user?: UserInternal\n ): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(\n MultiFactorSessionType.ENROLL,\n idToken,\n user\n );\n }\n\n static _fromMfaPendingCredential(\n mfaPendingCredential: string\n ): MultiFactorSessionImpl {\n return new MultiFactorSessionImpl(\n MultiFactorSessionType.SIGN_IN,\n mfaPendingCredential\n );\n }\n\n toJSON(): SerializedMultiFactorSession {\n const key =\n this.type === MultiFactorSessionType.ENROLL\n ? 'idToken'\n : 'pendingCredential';\n return {\n multiFactorSession: {\n [key]: this.credential\n }\n };\n }\n\n static fromJSON(\n obj: Partial\n ): MultiFactorSessionImpl | null {\n if (obj?.multiFactorSession) {\n if (obj.multiFactorSession?.pendingCredential) {\n return MultiFactorSessionImpl._fromMfaPendingCredential(\n obj.multiFactorSession.pendingCredential\n );\n } else if (obj.multiFactorSession?.idToken) {\n return MultiFactorSessionImpl._fromIdtoken(\n obj.multiFactorSession.idToken\n );\n }\n }\n return null;\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n MultiFactorResolver,\n UserCredential,\n MultiFactorError\n} from '../model/public_types';\n\nimport { _castAuth } from '../core/auth/auth_impl';\nimport { AuthErrorCode } from '../core/errors';\nimport { UserCredentialImpl } from '../core/user/user_credential_impl';\nimport { _assert, _fail } from '../core/util/assert';\nimport { UserCredentialInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorError as MultiFactorErrorInternal } from './mfa_error';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\nimport { OperationType } from '../model/enums';\n\nexport class MultiFactorResolverImpl implements MultiFactorResolver {\n private constructor(\n readonly session: MultiFactorSessionImpl,\n readonly hints: MultiFactorInfoImpl[],\n private readonly signInResolver: (\n assertion: MultiFactorAssertionImpl\n ) => Promise\n ) {}\n\n /** @internal */\n static _fromError(\n authExtern: Auth,\n error: MultiFactorErrorInternal\n ): MultiFactorResolverImpl {\n const auth = _castAuth(authExtern);\n const serverResponse = error.customData._serverResponse;\n const hints = (serverResponse.mfaInfo || []).map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(auth, enrollment)\n );\n\n _assert(\n serverResponse.mfaPendingCredential,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(\n serverResponse.mfaPendingCredential\n );\n\n return new MultiFactorResolverImpl(\n session,\n hints,\n async (\n assertion: MultiFactorAssertionImpl\n ): Promise => {\n const mfaResponse = await assertion._process(auth, session);\n // Clear out the unneeded fields from the old login response\n delete serverResponse.mfaInfo;\n delete serverResponse.mfaPendingCredential;\n\n // Use in the new token & refresh token in the old response\n const idTokenResponse = {\n ...serverResponse,\n idToken: mfaResponse.idToken,\n refreshToken: mfaResponse.refreshToken\n };\n\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\n switch (error.operationType) {\n case OperationType.SIGN_IN:\n const userCredential =\n await UserCredentialImpl._fromIdTokenResponse(\n auth,\n error.operationType,\n idTokenResponse\n );\n await auth._updateCurrentUser(userCredential.user);\n return userCredential;\n case OperationType.REAUTHENTICATE:\n _assert(error.user, auth, AuthErrorCode.INTERNAL_ERROR);\n return UserCredentialImpl._forOperation(\n error.user,\n error.operationType,\n idTokenResponse\n );\n default:\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n );\n }\n\n async resolveSignIn(\n assertionExtern: MultiFactorAssertionImpl\n ): Promise {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n return this.signInResolver(assertion);\n }\n}\n\n/**\n * Provides a {@link MultiFactorResolver} suitable for completion of a\n * multi-factor flow.\n *\n * @param auth - The {@link Auth} instance.\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\n * reauthentication operation.\n *\n * @public\n */\nexport function getMultiFactorResolver(\n auth: Auth,\n error: MultiFactorError\n): MultiFactorResolver {\n const authModular = getModularInstance(auth);\n const errorInternal = error as MultiFactorErrorInternal;\n _assert(\n error.customData.operationType,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n errorInternal.customData._serverResponse?.mfaPendingCredential,\n authModular,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Endpoint,\n HttpMethod,\n _addTidIfNecessary,\n _performApiRequest\n} from '../index';\nimport { SignInWithPhoneNumberRequest } from '../authentication/sms';\nimport { FinalizeMfaResponse } from '../authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\n\n/**\n * MFA Info as returned by the API.\n */\ninterface BaseMfaEnrollment {\n mfaEnrollmentId: string;\n enrolledAt: number;\n displayName?: string;\n}\n\n/**\n * An MFA provided by SMS verification.\n */\nexport interface PhoneMfaEnrollment extends BaseMfaEnrollment {\n phoneInfo: string;\n}\n\n/**\n * An MFA provided by TOTP (Time-based One Time Password).\n */\nexport interface TotpMfaEnrollment extends BaseMfaEnrollment {}\n\n/**\n * MfaEnrollment can be any subtype of BaseMfaEnrollment, currently only PhoneMfaEnrollment and TotpMfaEnrollment are supported.\n */\nexport type MfaEnrollment = PhoneMfaEnrollment | TotpMfaEnrollment;\n\nexport interface StartPhoneMfaEnrollmentRequest {\n idToken: string;\n phoneEnrollmentInfo: {\n phoneNumber: string;\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaEnrollmentResponse {\n phoneSessionInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startEnrollPhoneMfa(\n auth: AuthInternal,\n request: StartPhoneMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n StartPhoneMfaEnrollmentRequest,\n StartPhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaEnrollmentRequest {\n idToken: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizePhoneMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollPhoneMfa(\n auth: AuthInternal,\n request: FinalizePhoneMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n FinalizePhoneMfaEnrollmentRequest,\n FinalizePhoneMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\nexport interface StartTotpMfaEnrollmentRequest {\n idToken: string;\n totpEnrollmentInfo: {};\n tenantId?: string;\n}\n\nexport interface StartTotpMfaEnrollmentResponse {\n totpSessionInfo: {\n sharedSecretKey: string;\n verificationCodeLength: number;\n hashingAlgorithm: string;\n periodSec: number;\n sessionInfo: string;\n finalizeEnrollmentTime: number;\n };\n}\n\nexport function startEnrollTotpMfa(\n auth: AuthInternal,\n request: StartTotpMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n StartTotpMfaEnrollmentRequest,\n StartTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface TotpVerificationInfo {\n sessionInfo: string;\n verificationCode: string;\n}\nexport interface FinalizeTotpMfaEnrollmentRequest {\n idToken: string;\n totpVerificationInfo: TotpVerificationInfo;\n displayName?: string | null;\n tenantId?: string;\n}\n\nexport interface FinalizeTotpMfaEnrollmentResponse\n extends FinalizeMfaResponse {}\n\nexport function finalizeEnrollTotpMfa(\n auth: AuthInternal,\n request: FinalizeTotpMfaEnrollmentRequest\n): Promise {\n return _performApiRequest<\n FinalizeTotpMfaEnrollmentRequest,\n FinalizeTotpMfaEnrollmentResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_ENROLLMENT,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface WithdrawMfaRequest {\n idToken: string;\n mfaEnrollmentId: string;\n tenantId?: string;\n}\n\nexport interface WithdrawMfaResponse extends FinalizeMfaResponse {}\n\nexport function withdrawMfa(\n auth: AuthInternal,\n request: WithdrawMfaRequest\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.POST,\n Endpoint.WITHDRAW_MFA,\n _addTidIfNecessary(auth, request)\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n MultiFactorAssertion,\n MultiFactorInfo,\n MultiFactorSession,\n MultiFactorUser,\n User\n} from '../model/public_types';\n\nimport { withdrawMfa } from '../api/account_management/mfa';\nimport { _logoutIfInvalidated } from '../core/user/invalidation';\nimport { UserInternal } from '../model/user';\nimport { MultiFactorAssertionImpl } from './mfa_assertion';\nimport { MultiFactorInfoImpl } from './mfa_info';\nimport { MultiFactorSessionImpl } from './mfa_session';\nimport { getModularInstance } from '@firebase/util';\n\nexport class MultiFactorUserImpl implements MultiFactorUser {\n enrolledFactors: MultiFactorInfo[] = [];\n\n private constructor(readonly user: UserInternal) {\n user._onReload(userInfo => {\n if (userInfo.mfaInfo) {\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment =>\n MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment)\n );\n }\n });\n }\n\n static _fromUser(user: UserInternal): MultiFactorUserImpl {\n return new MultiFactorUserImpl(user);\n }\n\n async getSession(): Promise {\n return MultiFactorSessionImpl._fromIdtoken(\n await this.user.getIdToken(),\n this.user\n );\n }\n\n async enroll(\n assertionExtern: MultiFactorAssertion,\n displayName?: string | null\n ): Promise {\n const assertion = assertionExtern as MultiFactorAssertionImpl;\n const session = (await this.getSession()) as MultiFactorSessionImpl;\n const finalizeMfaResponse = await _logoutIfInvalidated(\n this.user,\n assertion._process(this.user.auth, session, displayName)\n );\n // New tokens will be issued after enrollment of the new second factors.\n // They need to be updated on the user.\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\n // The user needs to be reloaded to get the new multi-factor information\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\n // will be updated.\n return this.user.reload();\n }\n\n async unenroll(infoOrUid: MultiFactorInfo | string): Promise {\n const mfaEnrollmentId =\n typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\n const idToken = await this.user.getIdToken();\n try {\n const idTokenResponse = await _logoutIfInvalidated(\n this.user,\n withdrawMfa(this.user.auth, {\n idToken,\n mfaEnrollmentId\n })\n );\n // Remove the second factor from the user's list.\n this.enrolledFactors = this.enrolledFactors.filter(\n ({ uid }) => uid !== mfaEnrollmentId\n );\n // Depending on whether the backend decided to revoke the user's session,\n // the tokenResponse may be empty. If the tokens were not updated (and they\n // are now invalid), reloading the user will discover this and invalidate\n // the user's state accordingly.\n await this.user._updateTokensIfNecessary(idTokenResponse);\n await this.user.reload();\n } catch (e) {\n throw e;\n }\n }\n}\n\nconst multiFactorUserCache = new WeakMap();\n\n/**\n * The {@link MultiFactorUser} corresponding to the user.\n *\n * @remarks\n * This is used to access all multi-factor properties and operations related to the user.\n *\n * @param user - The user.\n *\n * @public\n */\nexport function multiFactor(user: User): MultiFactorUser {\n const userModular = getModularInstance(user);\n if (!multiFactorUserCache.has(userModular)) {\n multiFactorUserCache.set(\n userModular,\n MultiFactorUserImpl._fromUser(userModular as UserInternal)\n );\n }\n return multiFactorUserCache.get(userModular)!;\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Persistence } from '../../model/public_types';\n\nexport const enum PersistenceType {\n SESSION = 'SESSION',\n LOCAL = 'LOCAL',\n NONE = 'NONE'\n}\n\nexport type PersistedBlob = Record;\n\nexport interface Instantiator {\n (blob: PersistedBlob): T;\n}\n\nexport type PersistenceValue = PersistedBlob | string;\n\nexport const STORAGE_AVAILABLE_KEY = '__sak';\n\nexport interface StorageEventListener {\n (value: PersistenceValue | null): void;\n}\n\nexport interface PersistenceInternal extends Persistence {\n type: PersistenceType;\n _isAvailable(): Promise;\n _set(key: string, value: PersistenceValue): Promise;\n _get(key: string): Promise;\n _remove(key: string): Promise;\n _addListener(key: string, listener: StorageEventListener): void;\n _removeListener(key: string, listener: StorageEventListener): void;\n // Should this persistence allow migration up the chosen hierarchy?\n _shouldAllowMigration?: boolean;\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n PersistenceValue,\n STORAGE_AVAILABLE_KEY,\n PersistenceType\n} from '../../core/persistence';\n\n// There are two different browser persistence types: local and session.\n// Both have the same implementation but use a different underlying storage\n// object.\n\nexport abstract class BrowserPersistenceClass {\n protected constructor(\n protected readonly storageRetriever: () => Storage,\n readonly type: PersistenceType\n ) {}\n\n _isAvailable(): Promise {\n try {\n if (!this.storage) {\n return Promise.resolve(false);\n }\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\n return Promise.resolve(true);\n } catch {\n return Promise.resolve(false);\n }\n }\n\n _set(key: string, value: PersistenceValue): Promise {\n this.storage.setItem(key, JSON.stringify(value));\n return Promise.resolve();\n }\n\n _get(key: string): Promise {\n const json = this.storage.getItem(key);\n return Promise.resolve(json ? JSON.parse(json) : null);\n }\n\n _remove(key: string): Promise {\n this.storage.removeItem(key);\n return Promise.resolve();\n }\n\n protected get storage(): Storage {\n return this.storageRetriever();\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport { getUA } from '@firebase/util';\nimport {\n _isSafari,\n _isIOS,\n _isIframe,\n _isMobileBrowser,\n _isIE10\n} from '../../core/util/browser';\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nfunction _iframeCannotSyncWebStorage(): boolean {\n const ua = getUA();\n return _isSafari(ua) || _isIOS(ua);\n}\n\n// The polling period in case events are not supported\nexport const _POLLING_INTERVAL_MS = 1000;\n\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\n\nclass BrowserLocalPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'LOCAL' = 'LOCAL';\n\n constructor() {\n super(() => window.localStorage, PersistenceType.LOCAL);\n }\n\n private readonly boundEventHandler = (\n event: StorageEvent,\n poll?: boolean\n ): void => this.onStorageEvent(event, poll);\n private readonly listeners: Record> = {};\n private readonly localCache: Record = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n\n // Safari or iOS browser and embedded in an iframe.\n private readonly safariLocalStorageNotSynced =\n _iframeCannotSyncWebStorage() && _isIframe();\n // Whether to use polling instead of depending on window events\n private readonly fallbackToPolling = _isMobileBrowser();\n readonly _shouldAllowMigration = true;\n\n private forAllChangedKeys(\n cb: (key: string, oldValue: string | null, newValue: string | null) => void\n ): void {\n // Check all keys with listeners on them.\n for (const key of Object.keys(this.listeners)) {\n // Get value from localStorage.\n const newValue = this.storage.getItem(key);\n const oldValue = this.localCache[key];\n // If local map value does not match, trigger listener with storage event.\n // Differentiate this simulated event from the real storage event.\n if (newValue !== oldValue) {\n cb(key, oldValue, newValue);\n }\n }\n }\n\n private onStorageEvent(event: StorageEvent, poll = false): void {\n // Key would be null in some situations, like when localStorage is cleared\n if (!event.key) {\n this.forAllChangedKeys(\n (key: string, _oldValue: string | null, newValue: string | null) => {\n this.notifyListeners(key, newValue);\n }\n );\n return;\n }\n\n const key = event.key;\n\n // Check the mechanism how this event was detected.\n // The first event will dictate the mechanism to be used.\n if (poll) {\n // Environment detects storage changes via polling.\n // Remove storage event listener to prevent possible event duplication.\n this.detachListener();\n } else {\n // Environment detects storage changes via storage event listener.\n // Remove polling listener to prevent possible event duplication.\n this.stopPolling();\n }\n\n // Safari embedded iframe. Storage event will trigger with the delta\n // changes but no changes will be applied to the iframe localStorage.\n if (this.safariLocalStorageNotSynced) {\n // Get current iframe page value.\n const storedValue = this.storage.getItem(key);\n // Value not synchronized, synchronize manually.\n if (event.newValue !== storedValue) {\n if (event.newValue !== null) {\n // Value changed from current value.\n this.storage.setItem(key, event.newValue);\n } else {\n // Current value deleted.\n this.storage.removeItem(key);\n }\n } else if (this.localCache[key] === event.newValue && !poll) {\n // Already detected and processed, do not trigger listeners again.\n return;\n }\n }\n\n const triggerListeners = (): void => {\n // Keep local map up to date in case storage event is triggered before\n // poll.\n const storedValue = this.storage.getItem(key);\n if (!poll && this.localCache[key] === storedValue) {\n // Real storage event which has already been detected, do nothing.\n // This seems to trigger in some IE browsers for some reason.\n return;\n }\n this.notifyListeners(key, storedValue);\n };\n\n const storedValue = this.storage.getItem(key);\n if (\n _isIE10() &&\n storedValue !== event.newValue &&\n event.newValue !== event.oldValue\n ) {\n // IE 10 has this weird bug where a storage event would trigger with the\n // correct key, oldValue and newValue but localStorage.getItem(key) does\n // not yield the updated value until a few milliseconds. This ensures\n // this recovers from that situation.\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\n } else {\n triggerListeners();\n }\n }\n\n private notifyListeners(key: string, value: string | null): void {\n this.localCache[key] = value;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(value ? JSON.parse(value) : value);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(() => {\n this.forAllChangedKeys(\n (key: string, oldValue: string | null, newValue: string | null) => {\n this.onStorageEvent(\n new StorageEvent('storage', {\n key,\n oldValue,\n newValue\n }),\n /* poll */ true\n );\n }\n );\n }, _POLLING_INTERVAL_MS);\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n private attachListener(): void {\n window.addEventListener('storage', this.boundEventHandler);\n }\n\n private detachListener(): void {\n window.removeEventListener('storage', this.boundEventHandler);\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n // Whether browser can detect storage event when it had already been pushed to the background.\n // This may happen in some mobile browsers. A localStorage change in the foreground window\n // will not be detected in the background window via the storage event.\n // This was detected in iOS 7.x mobile browsers\n if (this.fallbackToPolling) {\n this.startPolling();\n } else {\n this.attachListener();\n }\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n this.localCache[key] = this.storage.getItem(key);\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.detachListener();\n this.stopPolling();\n }\n }\n\n // Update local cache on base operations:\n\n async _set(key: string, value: PersistenceValue): Promise {\n await super._set(key, value);\n this.localCache[key] = JSON.stringify(value);\n }\n\n async _get(key: string): Promise {\n const value = await super._get(key);\n this.localCache[key] = JSON.stringify(value);\n return value;\n }\n\n async _remove(key: string): Promise {\n await super._remove(key);\n delete this.localCache[key];\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserLocalPersistence: Persistence = BrowserLocalPersistence;\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\n\nimport {\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n StorageEventListener\n} from '../../core/persistence';\nimport { BrowserPersistenceClass } from './browser';\n\nclass BrowserSessionPersistence\n extends BrowserPersistenceClass\n implements InternalPersistence\n{\n static type: 'SESSION' = 'SESSION';\n\n constructor() {\n super(() => window.sessionStorage, PersistenceType.SESSION);\n }\n\n _addListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n\n _removeListener(_key: string, _listener: StorageEventListener): void {\n // Listeners are not supported for session storage since it cannot be shared across windows\n return;\n }\n}\n\n/**\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\n * for the underlying storage.\n *\n * @public\n */\nexport const browserSessionPersistence: Persistence = BrowserSessionPersistence;\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** TODO: remove this once tslib has a polyfill for Promise.allSettled */\ninterface PromiseFulfilledResult {\n fulfilled: true;\n value: T;\n}\n\ninterface PromiseRejectedResult {\n fulfilled: false;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n reason: any;\n}\n\nexport type PromiseSettledResult =\n | PromiseFulfilledResult\n | PromiseRejectedResult;\n\n/**\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\n *\n * @param promises - Array of promises to wait on.\n */\nexport function _allSettled(\n promises: Array>\n): Promise>> {\n return Promise.all(\n promises.map(async promise => {\n try {\n const value = await promise;\n return {\n fulfilled: true,\n value\n } as PromiseFulfilledResult;\n } catch (reason) {\n return {\n fulfilled: false,\n reason\n } as PromiseRejectedResult;\n }\n })\n );\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ReceiverHandler,\n _EventType,\n _ReceiverResponse,\n SenderMessageEvent,\n _Status,\n _SenderRequest\n} from './index';\nimport { _allSettled } from './promise';\n\n/**\n * Interface class for receiving messages.\n *\n */\nexport class Receiver {\n private static readonly receivers: Receiver[] = [];\n private readonly boundEventHandler: EventListener;\n\n private readonly handlersMap: {\n // Typescript doesn't have existential types :(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [eventType: string]: Set>;\n } = {};\n\n constructor(private readonly eventTarget: EventTarget) {\n this.boundEventHandler = this.handleEvent.bind(this);\n }\n\n /**\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\n *\n * @param eventTarget - An event target (such as window or self) through which the underlying\n * messages will be received.\n */\n static _getInstance(eventTarget: EventTarget): Receiver {\n // The results are stored in an array since objects can't be keys for other\n // objects. In addition, setting a unique property on an event target as a\n // hash map key may not be allowed due to CORS restrictions.\n const existingInstance = this.receivers.find(receiver =>\n receiver.isListeningto(eventTarget)\n );\n if (existingInstance) {\n return existingInstance;\n }\n const newInstance = new Receiver(eventTarget);\n this.receivers.push(newInstance);\n return newInstance;\n }\n\n private isListeningto(eventTarget: EventTarget): boolean {\n return this.eventTarget === eventTarget;\n }\n\n /**\n * Fans out a MessageEvent to the appropriate listeners.\n *\n * @remarks\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\n * finished processing.\n *\n * @param event - The MessageEvent.\n *\n */\n private async handleEvent<\n T extends _ReceiverResponse,\n S extends _SenderRequest\n >(event: Event): Promise {\n const messageEvent = event as MessageEvent>;\n const { eventId, eventType, data } = messageEvent.data;\n\n const handlers: Set> | undefined =\n this.handlersMap[eventType];\n if (!handlers?.size) {\n return;\n }\n\n messageEvent.ports[0].postMessage({\n status: _Status.ACK,\n eventId,\n eventType\n });\n\n const promises = Array.from(handlers).map(async handler =>\n handler(messageEvent.origin, data)\n );\n const response = await _allSettled(promises);\n messageEvent.ports[0].postMessage({\n status: _Status.DONE,\n eventId,\n eventType,\n response\n });\n }\n\n /**\n * Subscribe an event handler for a particular event.\n *\n * @param eventType - Event name to subscribe to.\n * @param eventHandler - The event handler which should receive the events.\n *\n */\n _subscribe(\n eventType: _EventType,\n eventHandler: ReceiverHandler\n ): void {\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.addEventListener('message', this.boundEventHandler);\n }\n\n if (!this.handlersMap[eventType]) {\n this.handlersMap[eventType] = new Set();\n }\n\n this.handlersMap[eventType].add(eventHandler);\n }\n\n /**\n * Unsubscribe an event handler from a particular event.\n *\n * @param eventType - Event name to unsubscribe from.\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\n *\n */\n _unsubscribe(\n eventType: _EventType,\n eventHandler?: ReceiverHandler\n ): void {\n if (this.handlersMap[eventType] && eventHandler) {\n this.handlersMap[eventType].delete(eventHandler);\n }\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\n delete this.handlersMap[eventType];\n }\n\n if (Object.keys(this.handlersMap).length === 0) {\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\n }\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function _generateEventId(prefix = '', digits = 10): string {\n let random = '';\n for (let i = 0; i < digits; i++) {\n random += Math.floor(Math.random() * 10);\n }\n return prefix + random;\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _generateEventId } from '../../core/util/event_id';\nimport {\n _SenderRequest,\n _EventType,\n ReceiverMessageEvent,\n _MessageError,\n SenderMessageEvent,\n _Status,\n _ReceiverMessageResponse,\n _ReceiverResponse,\n _TimeoutDuration\n} from './index';\n\ninterface MessageHandler {\n messageChannel: MessageChannel;\n onMessage: EventListenerOrEventListenerObject;\n}\n\n/**\n * Interface for sending messages and waiting for a completion response.\n *\n */\nexport class Sender {\n private readonly handlers = new Set();\n\n constructor(private readonly target: ServiceWorker) {}\n\n /**\n * Unsubscribe the handler and remove it from our tracking Set.\n *\n * @param handler - The handler to unsubscribe.\n */\n private removeMessageHandler(handler: MessageHandler): void {\n if (handler.messageChannel) {\n handler.messageChannel.port1.removeEventListener(\n 'message',\n handler.onMessage\n );\n handler.messageChannel.port1.close();\n }\n this.handlers.delete(handler);\n }\n\n /**\n * Send a message to the Receiver located at {@link target}.\n *\n * @remarks\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\n * receiver has had a chance to fully process the event.\n *\n * @param eventType - Type of event to send.\n * @param data - The payload of the event.\n * @param timeout - Timeout for waiting on an ACK from the receiver.\n *\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\n */\n async _send(\n eventType: _EventType,\n data: S,\n timeout = _TimeoutDuration.ACK\n ): Promise<_ReceiverMessageResponse> {\n const messageChannel =\n typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\n if (!messageChannel) {\n throw new Error(_MessageError.CONNECTION_UNAVAILABLE);\n }\n // Node timers and browser timers return fundamentally different types.\n // We don't actually care what the value is but TS won't accept unknown and\n // we can't cast properly in both environments.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let completionTimer: any;\n let handler: MessageHandler;\n return new Promise<_ReceiverMessageResponse>((resolve, reject) => {\n const eventId = _generateEventId('', 20);\n messageChannel.port1.start();\n const ackTimer = setTimeout(() => {\n reject(new Error(_MessageError.UNSUPPORTED_EVENT));\n }, timeout);\n handler = {\n messageChannel,\n onMessage(event: Event): void {\n const messageEvent = event as MessageEvent>;\n if (messageEvent.data.eventId !== eventId) {\n return;\n }\n switch (messageEvent.data.status) {\n case _Status.ACK:\n // The receiver should ACK first.\n clearTimeout(ackTimer);\n completionTimer = setTimeout(() => {\n reject(new Error(_MessageError.TIMEOUT));\n }, _TimeoutDuration.COMPLETION);\n break;\n case _Status.DONE:\n // Once the receiver's handlers are finished we will get the results.\n clearTimeout(completionTimer);\n resolve(messageEvent.data.response);\n break;\n default:\n clearTimeout(ackTimer);\n clearTimeout(completionTimer);\n reject(new Error(_MessageError.INVALID_RESPONSE));\n break;\n }\n }\n };\n this.handlers.add(handler);\n messageChannel.port1.addEventListener('message', handler.onMessage);\n this.target.postMessage(\n {\n eventType,\n eventId,\n data\n } as SenderMessageEvent,\n [messageChannel.port2]\n );\n }).finally(() => {\n if (handler) {\n this.removeMessageHandler(handler);\n }\n });\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Recaptcha, GreCAPTCHATopLevel } from './recaptcha/recaptcha';\n\n/**\n * A specialized window type that melds the normal window type plus the\n * various bits we need. The three different blocks that are &'d together\n * cant be defined in the same block together.\n */\nexport type AuthWindow = {\n // Standard window types\n [T in keyof Window]: Window[T];\n} & {\n // Any known / named properties we want to add\n grecaptcha?: Recaptcha | GreCAPTCHATopLevel;\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n ___jsl?: Record;\n gapi?: typeof gapi;\n} & {\n // A final catch-all for callbacks (which will have random names) that\n // we will stick on the window.\n [callback: string]: (...args: unknown[]) => void;\n};\n\n/**\n * Lazy accessor for window, since the compat layer won't tree shake this out,\n * we need to make sure not to mess with window unless we have to\n */\nexport function _window(): AuthWindow {\n return window as unknown as AuthWindow;\n}\n\nexport function _setWindowLocation(url: string): void {\n _window().location.href = url;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _window } from '../auth_window';\n\nexport function _isWorker(): boolean {\n return (\n typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\n typeof _window()['importScripts'] === 'function'\n );\n}\n\nexport async function _getActiveServiceWorker(): Promise {\n if (!navigator?.serviceWorker) {\n return null;\n }\n try {\n const registration = await navigator.serviceWorker.ready;\n return registration.active;\n } catch {\n return null;\n }\n}\n\nexport function _getServiceWorkerController(): ServiceWorker | null {\n return navigator?.serviceWorker?.controller || null;\n}\n\nexport function _getWorkerGlobalScope(): ServiceWorker | null {\n return _isWorker() ? (self as unknown as ServiceWorker) : null;\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Persistence } from '../../model/public_types';\nimport {\n PersistedBlob,\n PersistenceInternal as InternalPersistence,\n PersistenceType,\n PersistenceValue,\n StorageEventListener,\n STORAGE_AVAILABLE_KEY\n} from '../../core/persistence/';\nimport {\n _EventType,\n _PingResponse,\n KeyChangedResponse,\n KeyChangedRequest,\n PingRequest,\n _TimeoutDuration\n} from '../messagechannel/index';\nimport { Receiver } from '../messagechannel/receiver';\nimport { Sender } from '../messagechannel/sender';\nimport {\n _isWorker,\n _getActiveServiceWorker,\n _getServiceWorkerController,\n _getWorkerGlobalScope\n} from '../util/worker';\n\nexport const DB_NAME = 'firebaseLocalStorageDb';\nconst DB_VERSION = 1;\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\nconst DB_DATA_KEYPATH = 'fbase_key';\n\ninterface DBObject {\n [DB_DATA_KEYPATH]: string;\n value: PersistedBlob;\n}\n\n/**\n * Promise wrapper for IDBRequest\n *\n * Unfortunately we can't cleanly extend Promise since promises are not callable in ES6\n *\n */\nclass DBPromise {\n constructor(private readonly request: IDBRequest) {}\n\n toPromise(): Promise {\n return new Promise((resolve, reject) => {\n this.request.addEventListener('success', () => {\n resolve(this.request.result);\n });\n this.request.addEventListener('error', () => {\n reject(this.request.error);\n });\n });\n }\n}\n\nfunction getObjectStore(db: IDBDatabase, isReadWrite: boolean): IDBObjectStore {\n return db\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\n .objectStore(DB_OBJECTSTORE_NAME);\n}\n\nexport async function _clearDatabase(db: IDBDatabase): Promise {\n const objectStore = getObjectStore(db, true);\n return new DBPromise(objectStore.clear()).toPromise();\n}\n\nexport function _deleteDatabase(): Promise {\n const request = indexedDB.deleteDatabase(DB_NAME);\n return new DBPromise(request).toPromise();\n}\n\nexport function _openDatabase(): Promise {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n return new Promise((resolve, reject) => {\n request.addEventListener('error', () => {\n reject(request.error);\n });\n\n request.addEventListener('upgradeneeded', () => {\n const db = request.result;\n\n try {\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\n } catch (e) {\n reject(e);\n }\n });\n\n request.addEventListener('success', async () => {\n const db: IDBDatabase = request.result;\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\n // same time. The only way to recover seems to be deleting the database\n // and re-initializing it.\n // https://github.com/firebase/firebase-js-sdk/issues/634\n\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\n // Need to close the database or else you get a `blocked` event\n db.close();\n await _deleteDatabase();\n resolve(await _openDatabase());\n } else {\n resolve(db);\n }\n });\n });\n}\n\nexport async function _putObject(\n db: IDBDatabase,\n key: string,\n value: PersistenceValue | string\n): Promise {\n const request = getObjectStore(db, true).put({\n [DB_DATA_KEYPATH]: key,\n value\n });\n return new DBPromise(request).toPromise();\n}\n\nasync function getObject(\n db: IDBDatabase,\n key: string\n): Promise {\n const request = getObjectStore(db, false).get(key);\n const data = await new DBPromise(request).toPromise();\n return data === undefined ? null : data.value;\n}\n\nexport function _deleteObject(db: IDBDatabase, key: string): Promise {\n const request = getObjectStore(db, true).delete(key);\n return new DBPromise(request).toPromise();\n}\n\nexport const _POLLING_INTERVAL_MS = 800;\nexport const _TRANSACTION_RETRY_COUNT = 3;\n\nclass IndexedDBLocalPersistence implements InternalPersistence {\n static type: 'LOCAL' = 'LOCAL';\n\n type = PersistenceType.LOCAL;\n db?: IDBDatabase;\n readonly _shouldAllowMigration = true;\n\n private readonly listeners: Record> = {};\n private readonly localCache: Record = {};\n // setTimeout return value is platform specific\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private pollTimer: any | null = null;\n private pendingWrites = 0;\n\n private receiver: Receiver | null = null;\n private sender: Sender | null = null;\n private serviceWorkerReceiverAvailable = false;\n private activeServiceWorker: ServiceWorker | null = null;\n // Visible for testing only\n readonly _workerInitializationPromise: Promise;\n\n constructor() {\n // Fire & forget the service worker registration as it may never resolve\n this._workerInitializationPromise =\n this.initializeServiceWorkerMessaging().then(\n () => {},\n () => {}\n );\n }\n\n async _openDb(): Promise {\n if (this.db) {\n return this.db;\n }\n this.db = await _openDatabase();\n return this.db;\n }\n\n async _withRetries(op: (db: IDBDatabase) => Promise): Promise {\n let numAttempts = 0;\n\n while (true) {\n try {\n const db = await this._openDb();\n return await op(db);\n } catch (e) {\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\n throw e;\n }\n if (this.db) {\n this.db.close();\n this.db = undefined;\n }\n // TODO: consider adding exponential backoff\n }\n }\n }\n\n /**\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\n * postMessage interface to send these events to the worker ourselves.\n */\n private async initializeServiceWorkerMessaging(): Promise {\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\n }\n\n /**\n * As the worker we should listen to events from the main window.\n */\n private async initializeReceiver(): Promise {\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope()!);\n // Refresh from persistence if we receive a KeyChanged message.\n this.receiver._subscribe(\n _EventType.KEY_CHANGED,\n async (_origin: string, data: KeyChangedRequest) => {\n const keys = await this._poll();\n return {\n keyProcessed: keys.includes(data.key)\n };\n }\n );\n // Let the sender know that we are listening so they give us more timeout.\n this.receiver._subscribe(\n _EventType.PING,\n async (_origin: string, _data: PingRequest) => {\n return [_EventType.KEY_CHANGED];\n }\n );\n }\n\n /**\n * As the main window, we should let the worker know when keys change (set and remove).\n *\n * @remarks\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\n * may not resolve.\n */\n private async initializeSender(): Promise {\n // Check to see if there's an active service worker.\n this.activeServiceWorker = await _getActiveServiceWorker();\n if (!this.activeServiceWorker) {\n return;\n }\n this.sender = new Sender(this.activeServiceWorker);\n // Ping the service worker to check what events they can handle.\n const results = await this.sender._send<_PingResponse, PingRequest>(\n _EventType.PING,\n {},\n _TimeoutDuration.LONG_ACK\n );\n if (!results) {\n return;\n }\n if (\n results[0]?.fulfilled &&\n results[0]?.value.includes(_EventType.KEY_CHANGED)\n ) {\n this.serviceWorkerReceiverAvailable = true;\n }\n }\n\n /**\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\n * worker will just trigger a full sync anyway.\n *\n * @remarks\n * For now, we only support one service worker per page.\n *\n * @param key - Storage key which changed.\n */\n private async notifyServiceWorker(key: string): Promise {\n if (\n !this.sender ||\n !this.activeServiceWorker ||\n _getServiceWorkerController() !== this.activeServiceWorker\n ) {\n return;\n }\n try {\n await this.sender._send(\n _EventType.KEY_CHANGED,\n { key },\n // Use long timeout if receiver has previously responded to a ping from us.\n this.serviceWorkerReceiverAvailable\n ? _TimeoutDuration.LONG_ACK\n : _TimeoutDuration.ACK\n );\n } catch {\n // This is a best effort approach. Ignore errors.\n }\n }\n\n async _isAvailable(): Promise {\n try {\n if (!indexedDB) {\n return false;\n }\n const db = await _openDatabase();\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\n return true;\n } catch {}\n return false;\n }\n\n private async _withPendingWrite(write: () => Promise): Promise {\n this.pendingWrites++;\n try {\n await write();\n } finally {\n this.pendingWrites--;\n }\n }\n\n async _set(key: string, value: PersistenceValue): Promise {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _putObject(db, key, value));\n this.localCache[key] = value;\n return this.notifyServiceWorker(key);\n });\n }\n\n async _get(key: string): Promise {\n const obj = (await this._withRetries((db: IDBDatabase) =>\n getObject(db, key)\n )) as T;\n this.localCache[key] = obj;\n return obj;\n }\n\n async _remove(key: string): Promise {\n return this._withPendingWrite(async () => {\n await this._withRetries((db: IDBDatabase) => _deleteObject(db, key));\n delete this.localCache[key];\n return this.notifyServiceWorker(key);\n });\n }\n\n private async _poll(): Promise {\n // TODO: check if we need to fallback if getAll is not supported\n const result = await this._withRetries((db: IDBDatabase) => {\n const getAllRequest = getObjectStore(db, false).getAll();\n return new DBPromise(getAllRequest).toPromise();\n });\n\n if (!result) {\n return [];\n }\n\n // If we have pending writes in progress abort, we'll get picked up on the next poll\n if (this.pendingWrites !== 0) {\n return [];\n }\n\n const keys = [];\n const keysInResult = new Set();\n if (result.length !== 0) {\n for (const { fbase_key: key, value } of result) {\n keysInResult.add(key);\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\n this.notifyListeners(key, value as PersistenceValue);\n keys.push(key);\n }\n }\n }\n\n for (const localKey of Object.keys(this.localCache)) {\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\n // Deleted\n this.notifyListeners(localKey, null);\n keys.push(localKey);\n }\n }\n return keys;\n }\n\n private notifyListeners(\n key: string,\n newValue: PersistenceValue | null\n ): void {\n this.localCache[key] = newValue;\n const listeners = this.listeners[key];\n if (listeners) {\n for (const listener of Array.from(listeners)) {\n listener(newValue);\n }\n }\n }\n\n private startPolling(): void {\n this.stopPolling();\n\n this.pollTimer = setInterval(\n async () => this._poll(),\n _POLLING_INTERVAL_MS\n );\n }\n\n private stopPolling(): void {\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n _addListener(key: string, listener: StorageEventListener): void {\n if (Object.keys(this.listeners).length === 0) {\n this.startPolling();\n }\n if (!this.listeners[key]) {\n this.listeners[key] = new Set();\n // Populate the cache to avoid spuriously triggering on first poll.\n void this._get(key); // This can happen in the background async and we can return immediately.\n }\n this.listeners[key].add(listener);\n }\n\n _removeListener(key: string, listener: StorageEventListener): void {\n if (this.listeners[key]) {\n this.listeners[key].delete(listener);\n\n if (this.listeners[key].size === 0) {\n delete this.listeners[key];\n }\n }\n\n if (Object.keys(this.listeners).length === 0) {\n this.stopPolling();\n }\n }\n}\n\n/**\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\n * for the underlying storage.\n *\n * @public\n */\nexport const indexedDBLocalPersistence: Persistence = IndexedDBLocalPersistence;\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _performApiRequest,\n Endpoint,\n HttpMethod,\n _addTidIfNecessary\n} from '../index';\nimport { Auth } from '../../model/public_types';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { MfaEnrollment } from '../account_management/mfa';\nimport { SignInWithIdpResponse } from './idp';\nimport {\n SignInWithPhoneNumberRequest,\n SignInWithPhoneNumberResponse\n} from './sms';\n\nexport interface FinalizeMfaResponse {\n idToken: string;\n refreshToken: string;\n}\n\n/**\n * @internal\n */\nexport interface IdTokenMfaResponse extends IdTokenResponse {\n mfaPendingCredential?: string;\n mfaInfo?: MfaEnrollment[];\n}\n\nexport interface StartPhoneMfaSignInRequest {\n mfaPendingCredential: string;\n mfaEnrollmentId: string;\n phoneSignInInfo: {\n recaptchaToken: string;\n };\n tenantId?: string;\n}\n\nexport interface StartPhoneMfaSignInResponse {\n phoneResponseInfo: {\n sessionInfo: string;\n };\n}\n\nexport function startSignInPhoneMfa(\n auth: Auth,\n request: StartPhoneMfaSignInRequest\n): Promise {\n return _performApiRequest<\n StartPhoneMfaSignInRequest,\n StartPhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.START_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport interface FinalizePhoneMfaSignInRequest {\n mfaPendingCredential: string;\n phoneVerificationInfo: SignInWithPhoneNumberRequest;\n tenantId?: string;\n}\n\n// TOTP MFA Sign in only has a finalize phase. Phone MFA has a start phase to initiate sending an\n// SMS and a finalize phase to complete sign in. With TOTP, the user already has the OTP in the\n// TOTP/Authenticator app.\nexport interface FinalizeTotpMfaSignInRequest {\n mfaPendingCredential: string;\n totpVerificationInfo: { verificationCode: string };\n tenantId?: string;\n mfaEnrollmentId: string;\n}\n\nexport interface FinalizePhoneMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport interface FinalizeTotpMfaSignInResponse extends FinalizeMfaResponse {}\n\nexport function finalizeSignInPhoneMfa(\n auth: Auth,\n request: FinalizePhoneMfaSignInRequest\n): Promise {\n return _performApiRequest<\n FinalizePhoneMfaSignInRequest,\n FinalizePhoneMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\nexport function finalizeSignInTotpMfa(\n auth: Auth,\n request: FinalizeTotpMfaSignInRequest\n): Promise {\n return _performApiRequest<\n FinalizeTotpMfaSignInRequest,\n FinalizeTotpMfaSignInResponse\n >(\n auth,\n HttpMethod.POST,\n Endpoint.FINALIZE_MFA_SIGN_IN,\n _addTidIfNecessary(auth, request)\n );\n}\n\n/**\n * @internal\n */\nexport type PhoneOrOauthTokenResponse =\n | SignInWithPhoneNumberResponse\n | SignInWithIdpResponse\n | IdTokenResponse;\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport { RecaptchaParameters } from '../../model/public_types';\nimport {\n Recaptcha,\n GreCAPTCHATopLevel,\n GreCAPTCHARenderOption,\n GreCAPTCHA\n} from './recaptcha';\n\nexport const _SOLVE_TIME_MS = 500;\nexport const _EXPIRATION_TIME_MS = 60_000;\nexport const _WIDGET_ID_START = 1_000_000_000_000;\n\nexport interface Widget {\n getResponse: () => string | null;\n delete: () => void;\n execute: () => void;\n}\n\nexport class MockReCaptcha implements Recaptcha {\n private counter = _WIDGET_ID_START;\n _widgets = new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n render(\n container: string | HTMLElement,\n parameters?: RecaptchaParameters\n ): number {\n const id = this.counter;\n this._widgets.set(\n id,\n new MockWidget(container, this.auth.name, parameters || {})\n );\n this.counter++;\n return id;\n }\n\n reset(optWidgetId?: number): void {\n const id = optWidgetId || _WIDGET_ID_START;\n void this._widgets.get(id)?.delete();\n this._widgets.delete(id);\n }\n\n getResponse(optWidgetId?: number): string {\n const id = optWidgetId || _WIDGET_ID_START;\n return this._widgets.get(id)?.getResponse() || '';\n }\n\n async execute(optWidgetId?: number | string): Promise {\n const id: number = (optWidgetId as number) || _WIDGET_ID_START;\n void this._widgets.get(id)?.execute();\n return '';\n }\n}\n\nexport class MockGreCAPTCHATopLevel implements GreCAPTCHATopLevel {\n enterprise: GreCAPTCHA = new MockGreCAPTCHA();\n ready(callback: () => void): void {\n callback();\n }\n\n execute(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _siteKey: string,\n _options: { action: string }\n ): Promise {\n return Promise.resolve('token');\n }\n render(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _container: string | HTMLElement,\n _parameters: GreCAPTCHARenderOption\n ): string {\n return '';\n }\n}\n\nexport class MockGreCAPTCHA implements GreCAPTCHA {\n ready(callback: () => void): void {\n callback();\n }\n\n execute(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _siteKey: string,\n _options: { action: string }\n ): Promise {\n return Promise.resolve('token');\n }\n render(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _container: string | HTMLElement,\n _parameters: GreCAPTCHARenderOption\n ): string {\n return '';\n }\n}\n\nexport class MockWidget {\n private readonly container: HTMLElement;\n private readonly isVisible: boolean;\n private timerId: number | null = null;\n private deleted = false;\n private responseToken: string | null = null;\n private readonly clickHandler = (): void => {\n this.execute();\n };\n\n constructor(\n containerOrId: string | HTMLElement,\n appName: string,\n private readonly params: RecaptchaParameters\n ) {\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, AuthErrorCode.ARGUMENT_ERROR, { appName });\n\n this.container = container;\n this.isVisible = this.params.size !== 'invisible';\n if (this.isVisible) {\n this.execute();\n } else {\n this.container.addEventListener('click', this.clickHandler);\n }\n }\n\n getResponse(): string | null {\n this.checkIfDeleted();\n return this.responseToken;\n }\n\n delete(): void {\n this.checkIfDeleted();\n this.deleted = true;\n if (this.timerId) {\n clearTimeout(this.timerId);\n this.timerId = null;\n }\n this.container.removeEventListener('click', this.clickHandler);\n }\n\n execute(): void {\n this.checkIfDeleted();\n if (this.timerId) {\n return;\n }\n\n this.timerId = window.setTimeout(() => {\n this.responseToken = generateRandomAlphaNumericString(50);\n const { callback, 'expired-callback': expiredCallback } = this.params;\n if (callback) {\n try {\n callback(this.responseToken);\n } catch (e) {}\n }\n\n this.timerId = window.setTimeout(() => {\n this.timerId = null;\n this.responseToken = null;\n if (expiredCallback) {\n try {\n expiredCallback();\n } catch (e) {}\n }\n\n if (this.isVisible) {\n this.execute();\n }\n }, _EXPIRATION_TIME_MS);\n }, _SOLVE_TIME_MS);\n }\n\n private checkIfDeleted(): void {\n if (this.deleted) {\n throw new Error('reCAPTCHA mock was already deleted!');\n }\n }\n}\n\nfunction generateRandomAlphaNumericString(len: number): string {\n const chars = [];\n const allowedChars =\n '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n for (let i = 0; i < len; i++) {\n chars.push(\n allowedChars.charAt(Math.floor(Math.random() * allowedChars.length))\n );\n }\n return chars.join('');\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { querystring } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as jsHelpers from '../load_js';\nimport { Recaptcha, isV2 } from './recaptcha';\nimport { MockReCaptcha } from './recaptcha_mock';\n\n// ReCaptcha will load using the same callback, so the callback function needs\n// to be kept around\nexport const _JSLOAD_CALLBACK = jsHelpers._generateCallbackName('rcb');\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\nconst RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';\n\n/**\n * We need to mark this interface as internal explicitly to exclude it in the public typings, because\n * it references AuthInternal which has a circular dependency with UserInternal.\n *\n * @internal\n */\nexport interface ReCaptchaLoader {\n load(auth: AuthInternal, hl?: string): Promise;\n clearedOneInstance(): void;\n}\n\n/**\n * Loader for the GReCaptcha library. There should only ever be one of this.\n */\nexport class ReCaptchaLoaderImpl implements ReCaptchaLoader {\n private hostLanguage = '';\n private counter = 0;\n /**\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\n * `window.grecaptcha.render()` will not. Another load will add it.\n */\n private readonly librarySeparatelyLoaded = !!_window().grecaptcha?.render;\n\n load(auth: AuthInternal, hl = ''): Promise {\n _assert(isHostLanguageValid(hl), auth, AuthErrorCode.ARGUMENT_ERROR);\n\n if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\n return Promise.resolve(_window().grecaptcha! as Recaptcha);\n }\n return new Promise((resolve, reject) => {\n const networkTimeout = _window().setTimeout(() => {\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }, NETWORK_TIMEOUT_DELAY.get());\n\n _window()[_JSLOAD_CALLBACK] = () => {\n _window().clearTimeout(networkTimeout);\n delete _window()[_JSLOAD_CALLBACK];\n\n const recaptcha = _window().grecaptcha as Recaptcha;\n\n if (!recaptcha || !isV2(recaptcha)) {\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n return;\n }\n\n // Wrap the greptcha render function so that we know if the developer has\n // called it separately\n const render = recaptcha.render;\n recaptcha.render = (container, params) => {\n const widgetId = render(container, params);\n this.counter++;\n return widgetId;\n };\n\n this.hostLanguage = hl;\n resolve(recaptcha);\n };\n\n const url = `${RECAPTCHA_BASE}?${querystring({\n onload: _JSLOAD_CALLBACK,\n render: 'explicit',\n hl\n })}`;\n\n jsHelpers._loadJS(url).catch(() => {\n clearTimeout(networkTimeout);\n reject(_createError(auth, AuthErrorCode.INTERNAL_ERROR));\n });\n });\n }\n\n clearedOneInstance(): void {\n this.counter--;\n }\n\n private shouldResolveImmediately(hl: string): boolean {\n // We can resolve immediately if:\n // • grecaptcha is already defined AND (\n // 1. the requested language codes are the same OR\n // 2. there exists already a ReCaptcha on the page\n // 3. the library was already loaded by the app\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\n // that are already in the page\n return (\n !!_window().grecaptcha?.render &&\n (hl === this.hostLanguage ||\n this.counter > 0 ||\n this.librarySeparatelyLoaded)\n );\n }\n}\n\nfunction isHostLanguageValid(hl: string): boolean {\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\n}\n\nexport class MockReCaptchaLoaderImpl implements ReCaptchaLoader {\n async load(auth: AuthInternal): Promise {\n return new MockReCaptcha(auth);\n }\n\n clearedOneInstance(): void {}\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Auth, RecaptchaParameters } from '../../model/public_types';\nimport { getRecaptchaParams } from '../../api/authentication/recaptcha';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport { _isHttpOrHttps } from '../../core/util/location';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport { _isWorker } from '../util/worker';\nimport { Recaptcha } from './recaptcha';\nimport {\n MockReCaptchaLoaderImpl,\n ReCaptchaLoader,\n ReCaptchaLoaderImpl\n} from './recaptcha_loader';\n\nexport const RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\n\nconst DEFAULT_PARAMS: RecaptchaParameters = {\n theme: 'light',\n type: 'image'\n};\n\ntype TokenCallback = (token: string) => void;\n\n/**\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\n *\n * @remarks\n * `RecaptchaVerifier` does not work in a Node.js environment.\n *\n * @public\n */\nexport class RecaptchaVerifier implements ApplicationVerifierInternal {\n /**\n * The application verifier type.\n *\n * @remarks\n * For a reCAPTCHA verifier, this is 'recaptcha'.\n */\n readonly type = RECAPTCHA_VERIFIER_TYPE;\n private destroyed = false;\n private widgetId: number | null = null;\n private readonly container: HTMLElement;\n private readonly isInvisible: boolean;\n private readonly tokenChangeListeners = new Set();\n private renderPromise: Promise | null = null;\n private readonly auth: AuthInternal;\n\n /** @internal */\n readonly _recaptchaLoader: ReCaptchaLoader;\n private recaptcha: Recaptcha | null = null;\n\n /**\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\n *\n * @param containerOrId - The reCAPTCHA container parameter.\n *\n * @remarks\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\n * an element ID. The corresponding element must also must be in the DOM at the time of\n * initialization.\n *\n * @param parameters - The optional reCAPTCHA parameters.\n *\n * @remarks\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\n * 'invisible'.\n */\n constructor(\n authExtern: Auth,\n containerOrId: HTMLElement | string,\n private readonly parameters: RecaptchaParameters = {\n ...DEFAULT_PARAMS\n }\n ) {\n this.auth = _castAuth(authExtern);\n this.isInvisible = this.parameters.size === 'invisible';\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n const container =\n typeof containerOrId === 'string'\n ? document.getElementById(containerOrId)\n : containerOrId;\n _assert(container, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n\n this.container = container;\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\n\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\n ? new MockReCaptchaLoaderImpl()\n : new ReCaptchaLoaderImpl();\n\n this.validateStartingState();\n // TODO: Figure out if sdk version is needed\n }\n\n /**\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\n *\n * @returns A Promise for the reCAPTCHA token.\n */\n async verify(): Promise {\n this.assertNotDestroyed();\n const id = await this.render();\n const recaptcha = this.getAssertedRecaptcha();\n\n const response = recaptcha.getResponse(id);\n if (response) {\n return response;\n }\n\n return new Promise(resolve => {\n const tokenChange = (token: string): void => {\n if (!token) {\n return; // Ignore token expirations.\n }\n this.tokenChangeListeners.delete(tokenChange);\n resolve(token);\n };\n\n this.tokenChangeListeners.add(tokenChange);\n if (this.isInvisible) {\n recaptcha.execute(id);\n }\n });\n }\n\n /**\n * Renders the reCAPTCHA widget on the page.\n *\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\n */\n render(): Promise {\n try {\n this.assertNotDestroyed();\n } catch (e) {\n // This method returns a promise. Since it's not async (we want to return the\n // _same_ promise if rendering is still occurring), the API surface should\n // reject with the error rather than just throw\n return Promise.reject(e);\n }\n\n if (this.renderPromise) {\n return this.renderPromise;\n }\n\n this.renderPromise = this.makeRenderPromise().catch(e => {\n this.renderPromise = null;\n throw e;\n });\n\n return this.renderPromise;\n }\n\n /** @internal */\n _reset(): void {\n this.assertNotDestroyed();\n if (this.widgetId !== null) {\n this.getAssertedRecaptcha().reset(this.widgetId);\n }\n }\n\n /**\n * Clears the reCAPTCHA widget from the page and destroys the instance.\n */\n clear(): void {\n this.assertNotDestroyed();\n this.destroyed = true;\n this._recaptchaLoader.clearedOneInstance();\n if (!this.isInvisible) {\n this.container.childNodes.forEach(node => {\n this.container.removeChild(node);\n });\n }\n }\n\n private validateStartingState(): void {\n _assert(!this.parameters.sitekey, this.auth, AuthErrorCode.ARGUMENT_ERROR);\n _assert(\n this.isInvisible || !this.container.hasChildNodes(),\n this.auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n typeof document !== 'undefined',\n this.auth,\n AuthErrorCode.OPERATION_NOT_SUPPORTED\n );\n }\n\n private makeTokenCallback(\n existing: TokenCallback | string | undefined\n ): TokenCallback {\n return token => {\n this.tokenChangeListeners.forEach(listener => listener(token));\n if (typeof existing === 'function') {\n existing(token);\n } else if (typeof existing === 'string') {\n const globalFunc = _window()[existing];\n if (typeof globalFunc === 'function') {\n globalFunc(token);\n }\n }\n };\n }\n\n private assertNotDestroyed(): void {\n _assert(!this.destroyed, this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n\n private async makeRenderPromise(): Promise {\n await this.init();\n if (!this.widgetId) {\n let container = this.container;\n if (!this.isInvisible) {\n const guaranteedEmpty = document.createElement('div');\n container.appendChild(guaranteedEmpty);\n container = guaranteedEmpty;\n }\n\n this.widgetId = this.getAssertedRecaptcha().render(\n container,\n this.parameters\n );\n }\n\n return this.widgetId;\n }\n\n private async init(): Promise {\n _assert(\n _isHttpOrHttps() && !_isWorker(),\n this.auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n\n await domReady();\n this.recaptcha = await this._recaptchaLoader.load(\n this.auth,\n this.auth.languageCode || undefined\n );\n\n const siteKey = await getRecaptchaParams(this.auth);\n _assert(siteKey, this.auth, AuthErrorCode.INTERNAL_ERROR);\n this.parameters.sitekey = siteKey;\n }\n\n private getAssertedRecaptcha(): Recaptcha {\n _assert(this.recaptcha, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return this.recaptcha;\n }\n}\n\nfunction domReady(): Promise {\n let resolver: (() => void) | null = null;\n return new Promise(resolve => {\n if (document.readyState === 'complete') {\n resolve();\n return;\n }\n\n // Document not ready, wait for load before resolving.\n // Save resolver, so we can remove listener in case it was externally\n // cancelled.\n resolver = () => resolve();\n window.addEventListener('load', resolver);\n }).catch(e => {\n if (resolver) {\n window.removeEventListener('load', resolver);\n }\n\n throw e;\n });\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ApplicationVerifier,\n Auth,\n ConfirmationResult,\n PhoneInfoOptions,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { startEnrollPhoneMfa } from '../../api/account_management/mfa';\nimport { startSignInPhoneMfa } from '../../api/authentication/mfa';\nimport { sendPhoneVerificationCode } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assertLinkedStatus, _link } from '../../core/user/link_unlink';\nimport { _assert } from '../../core/util/assert';\nimport { AuthInternal } from '../../model/auth';\nimport {\n linkWithCredential,\n reauthenticateWithCredential,\n signInWithCredential\n} from '../../core/strategies/credential';\nimport {\n MultiFactorSessionImpl,\n MultiFactorSessionType\n} from '../../mfa/mfa_session';\nimport { UserInternal } from '../../model/user';\nimport { RECAPTCHA_VERIFIER_TYPE } from '../recaptcha/recaptcha_verifier';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { getModularInstance } from '@firebase/util';\nimport { ProviderId } from '../../model/enums';\n\ninterface OnConfirmationCallback {\n (credential: PhoneAuthCredential): Promise;\n}\n\nclass ConfirmationResultImpl implements ConfirmationResult {\n constructor(\n readonly verificationId: string,\n private readonly onConfirmation: OnConfirmationCallback\n ) {}\n\n confirm(verificationCode: string): Promise {\n const authCredential = PhoneAuthCredential._fromVerification(\n this.verificationId,\n verificationCode\n );\n return this.onConfirmation(authCredential);\n }\n}\n\n/**\n * Asynchronously signs in using a phone number.\n *\n * @remarks\n * This method sends a code via SMS to the given\n * phone number, and returns a {@link ConfirmationResult}. After the user\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\n * with the code to sign the user in.\n *\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\n * This function can work on other platforms that do not support the\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\n * third-party {@link ApplicationVerifier} implementation.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain a verificationCode from the user.\n * const credential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function signInWithPhoneNumber(\n auth: Auth,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n const authInternal = _castAuth(auth);\n const verificationId = await _verifyPhoneNumber(\n authInternal,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n signInWithCredential(authInternal, cred)\n );\n}\n\n/**\n * Links the user account with the given phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function linkWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n await _assertLinkedStatus(false, userInternal, ProviderId.PHONE);\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n linkWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Re-authenticates a user using a fresh phone credential.\n *\n * @remarks\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\n *\n * This method does not work in a Node.js environment.\n *\n * @param user - The user.\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\n * @param appVerifier - The {@link ApplicationVerifier}.\n *\n * @public\n */\nexport async function reauthenticateWithPhoneNumber(\n user: User,\n phoneNumber: string,\n appVerifier: ApplicationVerifier\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n const verificationId = await _verifyPhoneNumber(\n userInternal.auth,\n phoneNumber,\n getModularInstance(appVerifier as ApplicationVerifierInternal)\n );\n return new ConfirmationResultImpl(verificationId, cred =>\n reauthenticateWithCredential(userInternal, cred)\n );\n}\n\n/**\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\n *\n */\nexport async function _verifyPhoneNumber(\n auth: AuthInternal,\n options: PhoneInfoOptions | string,\n verifier: ApplicationVerifierInternal\n): Promise {\n const recaptchaToken = await verifier.verify();\n\n try {\n _assert(\n typeof recaptchaToken === 'string',\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n _assert(\n verifier.type === RECAPTCHA_VERIFIER_TYPE,\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n\n let phoneInfoOptions: PhoneInfoOptions;\n\n if (typeof options === 'string') {\n phoneInfoOptions = {\n phoneNumber: options\n };\n } else {\n phoneInfoOptions = options;\n }\n\n if ('session' in phoneInfoOptions) {\n const session = phoneInfoOptions.session as MultiFactorSessionImpl;\n\n if ('phoneNumber' in phoneInfoOptions) {\n _assert(\n session.type === MultiFactorSessionType.ENROLL,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const response = await startEnrollPhoneMfa(auth, {\n idToken: session.credential,\n phoneEnrollmentInfo: {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n }\n });\n return response.phoneSessionInfo.sessionInfo;\n } else {\n _assert(\n session.type === MultiFactorSessionType.SIGN_IN,\n auth,\n AuthErrorCode.INTERNAL_ERROR\n );\n const mfaEnrollmentId =\n phoneInfoOptions.multiFactorHint?.uid ||\n phoneInfoOptions.multiFactorUid;\n _assert(mfaEnrollmentId, auth, AuthErrorCode.MISSING_MFA_INFO);\n const response = await startSignInPhoneMfa(auth, {\n mfaPendingCredential: session.credential,\n mfaEnrollmentId,\n phoneSignInInfo: {\n recaptchaToken\n }\n });\n return response.phoneResponseInfo.sessionInfo;\n }\n } else {\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\n phoneNumber: phoneInfoOptions.phoneNumber,\n recaptchaToken\n });\n return sessionInfo;\n }\n } finally {\n verifier._reset();\n }\n}\n\n/**\n * Updates the user's phone number.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * await updatePhoneNumber(user, phoneCredential);\n * ```\n *\n * @param user - The user.\n * @param credential - A credential authenticating the new phone number.\n *\n * @public\n */\nexport async function updatePhoneNumber(\n user: User,\n credential: PhoneAuthCredential\n): Promise {\n await _link(getModularInstance(user) as UserInternal, credential);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n PhoneInfoOptions,\n ApplicationVerifier,\n UserCredential\n} from '../../model/public_types';\n\nimport { SignInWithPhoneNumberResponse } from '../../api/authentication/sms';\nimport { ApplicationVerifierInternal as ApplicationVerifierInternal } from '../../model/application_verifier';\nimport { AuthInternal as AuthInternal } from '../../model/auth';\nimport { UserCredentialInternal as UserCredentialInternal } from '../../model/user';\nimport { PhoneAuthCredential } from '../../core/credentials/phone';\nimport { _verifyPhoneNumber } from '../strategies/phone';\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthCredential } from '../../core';\nimport { FirebaseError, getModularInstance } from '@firebase/util';\nimport { TaggedWithTokenResponse } from '../../model/id_token';\nimport { ProviderId, SignInMethod } from '../../model/enums';\n\n/**\n * Provider for generating an {@link PhoneAuthCredential}.\n *\n * @remarks\n * `PhoneAuthProvider` does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // 'recaptcha-container' is the ID of an element in the DOM.\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\n * // Obtain the verificationCode from the user.\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, phoneCredential);\n * ```\n *\n * @public\n */\nexport class PhoneAuthProvider {\n /** Always set to {@link ProviderId}.PHONE. */\n static readonly PROVIDER_ID: 'phone' = ProviderId.PHONE;\n /** Always set to {@link SignInMethod}.PHONE. */\n static readonly PHONE_SIGN_IN_METHOD: 'phone' = SignInMethod.PHONE;\n\n /** Always set to {@link ProviderId}.PHONE. */\n readonly providerId = PhoneAuthProvider.PROVIDER_ID;\n private readonly auth: AuthInternal;\n\n /**\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\n *\n */\n constructor(auth: Auth) {\n this.auth = _castAuth(auth);\n }\n\n /**\n *\n * Starts a phone number authentication flow by sending a verification code to the given phone\n * number.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = await signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\n * E.164 format (e.g. +16505550101).\n * @param applicationVerifier - For abuse prevention, this method also requires a\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\n * {@link RecaptchaVerifier}.\n *\n * @returns A Promise for a verification ID that can be passed to\n * {@link PhoneAuthProvider.credential} to identify this flow..\n */\n verifyPhoneNumber(\n phoneOptions: PhoneInfoOptions | string,\n applicationVerifier: ApplicationVerifier\n ): Promise {\n return _verifyPhoneNumber(\n this.auth,\n phoneOptions,\n getModularInstance(applicationVerifier as ApplicationVerifierInternal)\n );\n }\n\n /**\n * Creates a phone auth credential, given the verification ID from\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\n * mobile device.\n *\n * @example\n * ```javascript\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\n * const userCredential = signInWithCredential(auth, authCredential);\n * ```\n *\n * @example\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\n * ```javascript\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\n * // Obtain verificationCode from the user.\n * const userCredential = await confirmationResult.confirm(verificationCode);\n * ```\n *\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\n * @param verificationCode - The verification code sent to the user's mobile device.\n *\n * @returns The auth provider credential.\n */\n static credential(\n verificationId: string,\n verificationCode: string\n ): PhoneAuthCredential {\n return PhoneAuthCredential._fromVerification(\n verificationId,\n verificationCode\n );\n }\n\n /**\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\n * @param userCredential - The user credential.\n */\n static credentialFromResult(\n userCredential: UserCredential\n ): AuthCredential | null {\n const credential = userCredential as UserCredentialInternal;\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\n }\n\n /**\n * Returns an {@link AuthCredential} when passed an error.\n *\n * @remarks\n *\n * This method works for errors like\n * `auth/account-exists-with-different-credentials`. This is useful for\n * recovering when attempting to set a user's phone number but the number\n * in question is already tied to another account. For example, the following\n * code tries to update the current user's phone number, and if that\n * fails, links the user with the account associated with that number:\n *\n * ```js\n * const provider = new PhoneAuthProvider(auth);\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\n * try {\n * const code = ''; // Prompt the user for the verification code\n * await updatePhoneNumber(\n * auth.currentUser,\n * PhoneAuthProvider.credential(verificationId, code));\n * } catch (e) {\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\n * const cred = PhoneAuthProvider.credentialFromError(e);\n * await linkWithCredential(auth.currentUser, cred);\n * }\n * }\n *\n * // At this point, auth.currentUser.phoneNumber === number.\n * ```\n *\n * @param error - The error to generate a credential from.\n */\n static credentialFromError(error: FirebaseError): AuthCredential | null {\n return PhoneAuthProvider.credentialFromTaggedObject(\n (error.customData || {}) as TaggedWithTokenResponse\n );\n }\n\n private static credentialFromTaggedObject({\n _tokenResponse: tokenResponse\n }: TaggedWithTokenResponse): AuthCredential | null {\n if (!tokenResponse) {\n return null;\n }\n const { phoneNumber, temporaryProof } =\n tokenResponse as SignInWithPhoneNumberResponse;\n if (phoneNumber && temporaryProof) {\n return PhoneAuthCredential._fromTokenResponse(\n phoneNumber,\n temporaryProof\n );\n }\n return null;\n }\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PopupRedirectResolver } from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport { PopupRedirectResolverInternal } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { _getInstance } from './instantiator';\n\n/**\n * Chooses a popup/redirect resolver to use. This prefers the override (which\n * is directly passed in), and falls back to the property set on the auth\n * object. If neither are available, this function errors w/ an argument error.\n */\nexport function _withDefaultResolver(\n auth: AuthInternal,\n resolverOverride: PopupRedirectResolver | undefined\n): PopupRedirectResolverInternal {\n if (resolverOverride) {\n return _getInstance(resolverOverride);\n }\n\n _assert(auth._popupRedirectResolver, auth, AuthErrorCode.ARGUMENT_ERROR);\n\n return auth._popupRedirectResolver;\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n signInWithIdp,\n SignInWithIdpRequest\n} from '../../api/authentication/idp';\nimport { PhoneOrOauthTokenResponse } from '../../api/authentication/mfa';\nimport { AuthInternal } from '../../model/auth';\nimport { IdTokenResponse } from '../../model/id_token';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthCredential } from '../credentials';\nimport { _link as _linkUser } from '../user/link_unlink';\nimport { _reauthenticate } from '../user/reauthenticate';\nimport { _assert } from '../util/assert';\nimport { _signInWithCredential } from './credential';\nimport { AuthErrorCode } from '../errors';\nimport { ProviderId } from '../../model/enums';\n\nexport interface IdpTaskParams {\n auth: AuthInternal;\n requestUri: string;\n sessionId?: string;\n tenantId?: string;\n postBody?: string;\n pendingToken?: string;\n user?: UserInternal;\n bypassAuthState?: boolean;\n}\n\nexport type IdpTask = (\n params: IdpTaskParams\n) => Promise;\n\nclass IdpCredential extends AuthCredential {\n constructor(readonly params: IdpTaskParams) {\n super(ProviderId.CUSTOM, ProviderId.CUSTOM);\n }\n\n _getIdTokenResponse(auth: AuthInternal): Promise {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n _linkToIdToken(\n auth: AuthInternal,\n idToken: string\n ): Promise {\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\n }\n\n _getReauthenticationResolver(auth: AuthInternal): Promise {\n return signInWithIdp(auth, this._buildIdpRequest());\n }\n\n private _buildIdpRequest(idToken?: string): SignInWithIdpRequest {\n const request: SignInWithIdpRequest = {\n requestUri: this.params.requestUri,\n sessionId: this.params.sessionId,\n postBody: this.params.postBody,\n tenantId: this.params.tenantId,\n pendingToken: this.params.pendingToken,\n returnSecureToken: true,\n returnIdpCredential: true\n };\n\n if (idToken) {\n request.idToken = idToken;\n }\n\n return request;\n }\n}\n\nexport function _signIn(\n params: IdpTaskParams\n): Promise {\n return _signInWithCredential(\n params.auth,\n new IdpCredential(params),\n params.bypassAuthState\n ) as Promise;\n}\n\nexport function _reauth(\n params: IdpTaskParams\n): Promise {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _reauthenticate(\n user,\n new IdpCredential(params),\n params.bypassAuthState\n );\n}\n\nexport async function _link(\n params: IdpTaskParams\n): Promise {\n const { auth, user } = params;\n _assert(user, auth, AuthErrorCode.INTERNAL_ERROR);\n return _linkUser(user, new IdpCredential(params), params.bypassAuthState);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseError } from '@firebase/util';\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal, UserCredentialInternal } from '../../model/user';\nimport { AuthErrorCode } from '../errors';\nimport { debugAssert, _fail } from '../util/assert';\nimport {\n _link,\n _reauth,\n _signIn,\n IdpTask,\n IdpTaskParams\n} from '../strategies/idp';\nimport { AuthInternal } from '../../model/auth';\n\ninterface PendingPromise {\n resolve: (cred: UserCredentialInternal | null) => void;\n reject: (error: Error) => void;\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n */\nexport abstract class AbstractPopupRedirectOperation\n implements AuthEventConsumer\n{\n private pendingPromise: PendingPromise | null = null;\n private eventManager: EventManager | null = null;\n readonly filter: AuthEventType[];\n\n abstract eventId: string | null;\n\n constructor(\n protected readonly auth: AuthInternal,\n filter: AuthEventType | AuthEventType[],\n protected readonly resolver: PopupRedirectResolverInternal,\n protected user?: UserInternal,\n protected readonly bypassAuthState = false\n ) {\n this.filter = Array.isArray(filter) ? filter : [filter];\n }\n\n abstract onExecution(): Promise;\n\n execute(): Promise {\n return new Promise(\n async (resolve, reject) => {\n this.pendingPromise = { resolve, reject };\n\n try {\n this.eventManager = await this.resolver._initialize(this.auth);\n await this.onExecution();\n this.eventManager.registerConsumer(this);\n } catch (e) {\n this.reject(e as Error);\n }\n }\n );\n }\n\n async onAuthEvent(event: AuthEvent): Promise {\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\n if (error) {\n this.reject(error);\n return;\n }\n\n const params: IdpTaskParams = {\n auth: this.auth,\n requestUri: urlResponse!,\n sessionId: sessionId!,\n tenantId: tenantId || undefined,\n postBody: postBody || undefined,\n user: this.user,\n bypassAuthState: this.bypassAuthState\n };\n\n try {\n this.resolve(await this.getIdpTask(type)(params));\n } catch (e) {\n this.reject(e as Error);\n }\n }\n\n onError(error: FirebaseError): void {\n this.reject(error);\n }\n\n private getIdpTask(type: AuthEventType): IdpTask {\n switch (type) {\n case AuthEventType.SIGN_IN_VIA_POPUP:\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n return _signIn;\n case AuthEventType.LINK_VIA_POPUP:\n case AuthEventType.LINK_VIA_REDIRECT:\n return _link;\n case AuthEventType.REAUTH_VIA_POPUP:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return _reauth;\n default:\n _fail(this.auth, AuthErrorCode.INTERNAL_ERROR);\n }\n }\n\n protected resolve(cred: UserCredentialInternal | null): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.resolve(cred);\n this.unregisterAndCleanUp();\n }\n\n protected reject(error: Error): void {\n debugAssert(this.pendingPromise, 'Pending promise was never set');\n this.pendingPromise.reject(error);\n this.unregisterAndCleanUp();\n }\n\n private unregisterAndCleanUp(): void {\n if (this.eventManager) {\n this.eventManager.unregisterConsumer(this);\n }\n\n this.pendingPromise = null;\n this.cleanUp();\n }\n\n abstract cleanUp(): void;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { AuthErrorCode } from '../../core/errors';\nimport {\n _assert,\n debugAssert,\n _createError,\n _assertInstanceOf\n} from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport { AuthPopup } from '../util/popup';\nimport { AbstractPopupRedirectOperation } from '../../core/strategies/abstract_popup_redirect_operation';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/*\n * The event timeout is the same on mobile and desktop, no need for Delay. Set this to 8s since\n * blocking functions can take upto 7s to complete sign in, as documented in:\n * https://cloud.google.com/identity-platform/docs/blocking-functions#understanding_blocking_functions\n * https://firebase.google.com/docs/auth/extend-with-blocking-functions#understanding_blocking_functions\n */\nexport const enum _Timeout {\n AUTH_EVENT = 8000\n}\nexport const _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\n\n/**\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\n *\n * @remarks\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\n * unsuccessful, returns an error object containing additional information about the error.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n *\n * // The signed-in user info.\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function signInWithPopup(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n const action = new PopupOperation(\n authInternal,\n AuthEventType.SIGN_IN_VIA_POPUP,\n provider,\n resolverInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\n * OAuth flow.\n *\n * @remarks\n * If the reauthentication is successful, the returned result will contain the user and the\n * provider's credential.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a popup.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithPopup(auth, provider);\n * // Reauthenticate using a popup.\n * await reauthenticateWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function reauthenticateWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.REAUTH_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\n *\n * @remarks\n * If the linking is successful, the returned result will contain the user and the provider's credential.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a popup.\n * const provider = new FacebookAuthProvider();\n * await linkWithPopup(result.user, provider);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function linkWithPopup(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n\n const action = new PopupOperation(\n userInternal.auth,\n AuthEventType.LINK_VIA_POPUP,\n provider,\n resolverInternal,\n userInternal\n );\n return action.executeNotNull();\n}\n\n/**\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\n * events\n *\n */\nclass PopupOperation extends AbstractPopupRedirectOperation {\n // Only one popup is ever shown at once. The lifecycle of the current popup\n // can be managed / cancelled by the constructor.\n private static currentPopupAction: PopupOperation | null = null;\n private authWindow: AuthPopup | null = null;\n private pollId: number | null = null;\n\n constructor(\n auth: AuthInternal,\n filter: AuthEventType,\n private readonly provider: AuthProvider,\n resolver: PopupRedirectResolverInternal,\n user?: UserInternal\n ) {\n super(auth, filter, resolver, user);\n if (PopupOperation.currentPopupAction) {\n PopupOperation.currentPopupAction.cancel();\n }\n\n PopupOperation.currentPopupAction = this;\n }\n\n async executeNotNull(): Promise {\n const result = await this.execute();\n _assert(result, this.auth, AuthErrorCode.INTERNAL_ERROR);\n return result;\n }\n\n async onExecution(): Promise {\n debugAssert(\n this.filter.length === 1,\n 'Popup operations only handle one event'\n );\n const eventId = _generateEventId();\n this.authWindow = await this.resolver._openPopup(\n this.auth,\n this.provider,\n this.filter[0], // There's always one, see constructor\n eventId\n );\n this.authWindow.associatedEvent = eventId;\n\n // Check for web storage support and origin validation _after_ the popup is\n // loaded. These operations are slow (~1 second or so) Rather than\n // waiting on them before opening the window, optimistically open the popup\n // and check for storage support at the same time. If storage support is\n // not available, this will cause the whole thing to reject properly. It\n // will also close the popup, but since the promise has already rejected,\n // the popup closed by user poll will reject into the void.\n this.resolver._originValidation(this.auth).catch(e => {\n this.reject(e);\n });\n\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\n if (!isSupported) {\n this.reject(\n _createError(this.auth, AuthErrorCode.WEB_STORAGE_UNSUPPORTED)\n );\n }\n });\n\n // Handle user closure. Notice this does *not* use await\n this.pollUserCancellation();\n }\n\n get eventId(): string | null {\n return this.authWindow?.associatedEvent || null;\n }\n\n cancel(): void {\n this.reject(_createError(this.auth, AuthErrorCode.EXPIRED_POPUP_REQUEST));\n }\n\n cleanUp(): void {\n if (this.authWindow) {\n this.authWindow.close();\n }\n\n if (this.pollId) {\n window.clearTimeout(this.pollId);\n }\n\n this.authWindow = null;\n this.pollId = null;\n PopupOperation.currentPopupAction = null;\n }\n\n private pollUserCancellation(): void {\n const poll = (): void => {\n if (this.authWindow?.window?.closed) {\n // Make sure that there is sufficient time for whatever action to\n // complete. The window could have closed but the sign in network\n // call could still be in flight. This is specifically true for\n // Firefox or if the opener is in an iframe, in which case the oauth\n // helper closes the popup.\n this.pollId = window.setTimeout(() => {\n this.pollId = null;\n this.reject(\n _createError(this.auth, AuthErrorCode.POPUP_CLOSED_BY_USER)\n );\n }, _Timeout.AUTH_EVENT);\n return;\n }\n\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\n };\n\n poll();\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthInternal } from '../../model/auth';\nimport {\n AuthEvent,\n AuthEventType,\n PopupRedirectResolverInternal\n} from '../../model/popup_redirect';\nimport { UserCredentialInternal } from '../../model/user';\nimport { PersistenceInternal } from '../persistence';\nimport { _persistenceKeyName } from '../persistence/persistence_user_manager';\nimport { _getInstance } from '../util/instantiator';\nimport { AbstractPopupRedirectOperation } from './abstract_popup_redirect_operation';\n\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\n\n// We only get one redirect outcome for any one auth, so just store it\n// in here.\nconst redirectOutcomeMap: Map<\n string,\n () => Promise\n> = new Map();\n\nexport class RedirectAction extends AbstractPopupRedirectOperation {\n eventId = null;\n\n constructor(\n auth: AuthInternal,\n resolver: PopupRedirectResolverInternal,\n bypassAuthState = false\n ) {\n super(\n auth,\n [\n AuthEventType.SIGN_IN_VIA_REDIRECT,\n AuthEventType.LINK_VIA_REDIRECT,\n AuthEventType.REAUTH_VIA_REDIRECT,\n AuthEventType.UNKNOWN\n ],\n resolver,\n undefined,\n bypassAuthState\n );\n }\n\n /**\n * Override the execute function; if we already have a redirect result, then\n * just return it.\n */\n async execute(): Promise {\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\n if (!readyOutcome) {\n try {\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(\n this.resolver,\n this.auth\n );\n const result = hasPendingRedirect ? await super.execute() : null;\n readyOutcome = () => Promise.resolve(result);\n } catch (e) {\n readyOutcome = () => Promise.reject(e);\n }\n\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\n }\n\n // If we're not bypassing auth state, the ready outcome should be set to\n // null.\n if (!this.bypassAuthState) {\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\n }\n\n return readyOutcome();\n }\n\n async onAuthEvent(event: AuthEvent): Promise {\n if (event.type === AuthEventType.SIGN_IN_VIA_REDIRECT) {\n return super.onAuthEvent(event);\n } else if (event.type === AuthEventType.UNKNOWN) {\n // This is a sentinel value indicating there's no pending redirect\n this.resolve(null);\n return;\n }\n\n if (event.eventId) {\n const user = await this.auth._redirectUserForId(event.eventId);\n if (user) {\n this.user = user;\n return super.onAuthEvent(event);\n } else {\n this.resolve(null);\n }\n }\n }\n\n async onExecution(): Promise {}\n\n cleanUp(): void {}\n}\n\nexport async function _getAndClearPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise {\n const key = pendingRedirectKey(auth);\n const persistence = resolverPersistence(resolver);\n if (!(await persistence._isAvailable())) {\n return false;\n }\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\n await persistence._remove(key);\n return hasPendingRedirect;\n}\n\nexport async function _setPendingRedirectStatus(\n resolver: PopupRedirectResolverInternal,\n auth: AuthInternal\n): Promise {\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\n}\n\nexport function _clearRedirectOutcomes(): void {\n redirectOutcomeMap.clear();\n}\n\nexport function _overrideRedirectResult(\n auth: AuthInternal,\n result: () => Promise\n): void {\n redirectOutcomeMap.set(auth._key(), result);\n}\n\nfunction resolverPersistence(\n resolver: PopupRedirectResolverInternal\n): PersistenceInternal {\n return _getInstance(resolver._redirectPersistence);\n}\n\nfunction pendingRedirectKey(auth: AuthInternal): string {\n return _persistenceKeyName(\n PENDING_REDIRECT_KEY,\n auth.config.apiKey,\n auth.name\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Auth,\n AuthProvider,\n PopupRedirectResolver,\n User,\n UserCredential\n} from '../../model/public_types';\n\nimport { _castAuth } from '../../core/auth/auth_impl';\nimport { _assertLinkedStatus } from '../../core/user/link_unlink';\nimport { _assertInstanceOf } from '../../core/util/assert';\nimport { _generateEventId } from '../../core/util/event_id';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { UserInternal } from '../../model/user';\nimport { _withDefaultResolver } from '../../core/util/resolver';\nimport {\n RedirectAction,\n _setPendingRedirectStatus\n} from '../../core/strategies/redirect';\nimport { FederatedAuthProvider } from '../../core/providers/federated';\nimport { getModularInstance } from '@firebase/util';\n\n/**\n * Authenticates a Firebase client using a full-page redirect flow.\n *\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link signInWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _signInWithRedirect(auth, provider, resolver) as Promise;\n}\n\nexport async function _signInWithRedirect(\n auth: Auth,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const authInternal = _castAuth(auth);\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await authInternal._initializationPromise;\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\n await _setPendingRedirectStatus(resolverInternal, authInternal);\n\n return resolverInternal._openRedirect(\n authInternal,\n provider,\n AuthEventType.SIGN_IN_VIA_REDIRECT\n );\n}\n\n/**\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link reauthenticateWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * const result = await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * // Reauthenticate using a redirect.\n * await reauthenticateWithRedirect(result.user, provider);\n * // This will again trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _reauthenticateWithRedirect(\n user,\n provider,\n resolver\n ) as Promise;\n}\nexport async function _reauthenticateWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.REAUTH_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\n * @remarks\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\n * | best practices} when using {@link linkWithRedirect}.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using some other provider.\n * const result = await signInWithEmailAndPassword(auth, email, password);\n * // Link using a redirect.\n * const provider = new FacebookAuthProvider();\n * await linkWithRedirect(result.user, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * ```\n *\n * @param user - The user.\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport function linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n return _linkWithRedirect(user, provider, resolver) as Promise;\n}\nexport async function _linkWithRedirect(\n user: User,\n provider: AuthProvider,\n resolver?: PopupRedirectResolver\n): Promise {\n const userInternal = getModularInstance(user) as UserInternal;\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\n // Wait for auth initialization to complete, this will process pending redirects and clear the\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\n // redirect and creating a PENDING_REDIRECT_KEY entry.\n await userInternal.auth._initializationPromise;\n // Allow the resolver to error before persisting the redirect user\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\n await _assertLinkedStatus(false, userInternal, provider.providerId);\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\n\n const eventId = await prepareUserForRedirect(userInternal);\n return resolverInternal._openRedirect(\n userInternal.auth,\n provider,\n AuthEventType.LINK_VIA_REDIRECT,\n eventId\n );\n}\n\n/**\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\n *\n * @remarks\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\n * error. If no redirect operation was called, returns `null`.\n *\n * This method does not work in a Node.js environment.\n *\n * @example\n * ```javascript\n * // Sign in using a redirect.\n * const provider = new FacebookAuthProvider();\n * // You can add additional scopes to the provider:\n * provider.addScope('user_birthday');\n * // Start a sign in process for an unauthenticated user.\n * await signInWithRedirect(auth, provider);\n * // This will trigger a full page redirect away from your app\n *\n * // After returning from the redirect when your app initializes you can obtain the result\n * const result = await getRedirectResult(auth);\n * if (result) {\n * // This is the signed-in user\n * const user = result.user;\n * // This gives you a Facebook Access Token.\n * const credential = provider.credentialFromResult(auth, result);\n * const token = credential.accessToken;\n * }\n * // As this API can be used for sign-in, linking and reauthentication,\n * // check the operationType to determine what triggered this redirect\n * // operation.\n * const operationType = result.operationType;\n * ```\n *\n * @param auth - The {@link Auth} instance.\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\n *\n * @public\n */\nexport async function getRedirectResult(\n auth: Auth,\n resolver?: PopupRedirectResolver\n): Promise {\n await _castAuth(auth)._initializationPromise;\n return _getRedirectResult(auth, resolver, false);\n}\n\nexport async function _getRedirectResult(\n auth: Auth,\n resolverExtern?: PopupRedirectResolver,\n bypassAuthState = false\n): Promise {\n const authInternal = _castAuth(auth);\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\n const result = await action.execute();\n\n if (result && !bypassAuthState) {\n delete result.user._redirectEventId;\n await authInternal._persistUserIfCurrent(result.user as UserInternal);\n await authInternal._setRedirectUser(null, resolverExtern);\n }\n\n return result;\n}\n\nasync function prepareUserForRedirect(user: UserInternal): Promise {\n const eventId = _generateEventId(`${user.uid}:::`);\n user._redirectEventId = eventId;\n await user.auth._setRedirectUser(user);\n await user.auth._persistUserIfCurrent(user);\n return eventId;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AuthEvent,\n AuthEventConsumer,\n AuthEventType,\n EventManager\n} from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { AuthInternal } from '../../model/auth';\nimport { _createError } from '../util/assert';\n\n// The amount of time to store the UIDs of seen events; this is\n// set to 10 min by default\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\n\nexport class AuthEventManager implements EventManager {\n private readonly cachedEventUids: Set = new Set();\n private readonly consumers: Set = new Set();\n protected queuedRedirectEvent: AuthEvent | null = null;\n protected hasHandledPotentialRedirect = false;\n private lastProcessedEventTime = Date.now();\n\n constructor(private readonly auth: AuthInternal) {}\n\n registerConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.add(authEventConsumer);\n\n if (\n this.queuedRedirectEvent &&\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)\n ) {\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\n this.saveEventToCache(this.queuedRedirectEvent);\n this.queuedRedirectEvent = null;\n }\n }\n\n unregisterConsumer(authEventConsumer: AuthEventConsumer): void {\n this.consumers.delete(authEventConsumer);\n }\n\n onEvent(event: AuthEvent): boolean {\n // Check if the event has already been handled\n if (this.hasEventBeenHandled(event)) {\n return false;\n }\n\n let handled = false;\n this.consumers.forEach(consumer => {\n if (this.isEventForConsumer(event, consumer)) {\n handled = true;\n this.sendToConsumer(event, consumer);\n this.saveEventToCache(event);\n }\n });\n\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\n // If we've already seen a redirect before, or this is a popup event,\n // bail now\n return handled;\n }\n\n this.hasHandledPotentialRedirect = true;\n\n // If the redirect wasn't handled, hang on to it\n if (!handled) {\n this.queuedRedirectEvent = event;\n handled = true;\n }\n\n return handled;\n }\n\n private sendToConsumer(event: AuthEvent, consumer: AuthEventConsumer): void {\n if (event.error && !isNullRedirectEvent(event)) {\n const code =\n (event.error.code?.split('auth/')[1] as AuthErrorCode) ||\n AuthErrorCode.INTERNAL_ERROR;\n consumer.onError(_createError(this.auth, code));\n } else {\n consumer.onAuthEvent(event);\n }\n }\n\n private isEventForConsumer(\n event: AuthEvent,\n consumer: AuthEventConsumer\n ): boolean {\n const eventIdMatches =\n consumer.eventId === null ||\n (!!event.eventId && event.eventId === consumer.eventId);\n return consumer.filter.includes(event.type) && eventIdMatches;\n }\n\n private hasEventBeenHandled(event: AuthEvent): boolean {\n if (\n Date.now() - this.lastProcessedEventTime >=\n EVENT_DUPLICATION_CACHE_DURATION_MS\n ) {\n this.cachedEventUids.clear();\n }\n\n return this.cachedEventUids.has(eventUid(event));\n }\n\n private saveEventToCache(event: AuthEvent): void {\n this.cachedEventUids.add(eventUid(event));\n this.lastProcessedEventTime = Date.now();\n }\n}\n\nfunction eventUid(e: AuthEvent): string {\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\n}\n\nfunction isNullRedirectEvent({ type, error }: AuthEvent): boolean {\n return (\n type === AuthEventType.UNKNOWN &&\n error?.code === `auth/${AuthErrorCode.NO_AUTH_EVENT}`\n );\n}\n\nfunction isRedirectEvent(event: AuthEvent): boolean {\n switch (event.type) {\n case AuthEventType.SIGN_IN_VIA_REDIRECT:\n case AuthEventType.LINK_VIA_REDIRECT:\n case AuthEventType.REAUTH_VIA_REDIRECT:\n return true;\n case AuthEventType.UNKNOWN:\n return isNullRedirectEvent(event);\n default:\n return false;\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _performApiRequest, Endpoint, HttpMethod } from '../index';\nimport { Auth } from '../../model/public_types';\n\nexport interface GetProjectConfigRequest {\n androidPackageName?: string;\n iosBundleId?: string;\n}\n\nexport interface GetProjectConfigResponse {\n authorizedDomains: string[];\n}\n\nexport async function _getProjectConfig(\n auth: Auth,\n request: GetProjectConfigRequest = {}\n): Promise {\n return _performApiRequest(\n auth,\n HttpMethod.GET,\n Endpoint.GET_PROJECT_CONFIG,\n request\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _getProjectConfig } from '../../api/project_config/get_project_config';\nimport { AuthInternal } from '../../model/auth';\nimport { AuthErrorCode } from '../errors';\nimport { _fail } from './assert';\nimport { _getCurrentUrl } from './location';\n\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\nconst HTTP_REGEX = /^https?/;\n\nexport async function _validateOrigin(auth: AuthInternal): Promise {\n // Skip origin validation if we are in an emulated environment\n if (auth.config.emulator) {\n return;\n }\n\n const { authorizedDomains } = await _getProjectConfig(auth);\n\n for (const domain of authorizedDomains) {\n try {\n if (matchDomain(domain)) {\n return;\n }\n } catch {\n // Do nothing if there's a URL error; just continue searching\n }\n }\n\n // In the old SDK, this error also provides helpful messages.\n _fail(auth, AuthErrorCode.INVALID_ORIGIN);\n}\n\nfunction matchDomain(expected: string): boolean {\n const currentUrl = _getCurrentUrl();\n const { protocol, hostname } = new URL(currentUrl);\n if (expected.startsWith('chrome-extension://')) {\n const ceUrl = new URL(expected);\n\n if (ceUrl.hostname === '' && hostname === '') {\n // For some reason we're not parsing chrome URLs properly\n return (\n protocol === 'chrome-extension:' &&\n expected.replace('chrome-extension://', '') ===\n currentUrl.replace('chrome-extension://', '')\n );\n }\n\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\n }\n\n if (!HTTP_REGEX.test(protocol)) {\n return false;\n }\n\n if (IP_ADDRESS_REGEX.test(expected)) {\n // The domain has to be exactly equal to the pattern, as an IP domain will\n // only contain the IP, no extra character.\n return hostname === expected;\n }\n\n // Dots in pattern should be escaped.\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\n // Non ip address domains.\n // domain.com = *.domain.com OR domain.com\n const re = new RegExp(\n '^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$',\n 'i'\n );\n return re.test(hostname);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as js from '../load_js';\n\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\n\n/**\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\n * it will stop working after a retrial. This is a hack to fix this issue.\n */\nfunction resetUnloadedGapiModules(): void {\n // Clear last failed gapi.load state to force next gapi.load to first\n // load the failed gapi.iframes module.\n // Get gapix.beacon context.\n const beacon = _window().___jsl;\n // Get current hint.\n if (beacon?.H) {\n // Get gapi hint.\n for (const hint of Object.keys(beacon.H)) {\n // Requested modules.\n beacon.H[hint].r = beacon.H[hint].r || [];\n // Loaded modules.\n beacon.H[hint].L = beacon.H[hint].L || [];\n // Set requested modules to a copy of the loaded modules.\n beacon.H[hint].r = [...beacon.H[hint].L];\n // Clear pending callbacks.\n if (beacon.CP) {\n for (let i = 0; i < beacon.CP.length; i++) {\n // Remove all failed pending callbacks.\n beacon.CP[i] = null;\n }\n }\n }\n }\n}\n\nfunction loadGapi(auth: AuthInternal): Promise {\n return new Promise((resolve, reject) => {\n // Function to run when gapi.load is ready.\n function loadGapiIframe(): void {\n // The developer may have tried to previously run gapi.load and failed.\n // Run this to fix that.\n resetUnloadedGapiModules();\n gapi.load('gapi.iframes', {\n callback: () => {\n resolve(gapi.iframes.getContext());\n },\n ontimeout: () => {\n // The above reset may be sufficient, but having this reset after\n // failure ensures that if the developer calls gapi.load after the\n // connection is re-established and before another attempt to embed\n // the iframe, it would work and would not be broken because of our\n // failed attempt.\n // Timeout when gapi.iframes.Iframe not loaded.\n resetUnloadedGapiModules();\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n },\n timeout: NETWORK_TIMEOUT.get()\n });\n }\n\n if (_window().gapi?.iframes?.Iframe) {\n // If gapi.iframes.Iframe available, resolve.\n resolve(gapi.iframes.getContext());\n } else if (!!_window().gapi?.load) {\n // Gapi loader ready, load gapi.iframes.\n loadGapiIframe();\n } else {\n // Create a new iframe callback when this is called so as not to overwrite\n // any previous defined callback. This happens if this method is called\n // multiple times in parallel and could result in the later callback\n // overwriting the previous one. This would end up with a iframe\n // timeout.\n const cbName = js._generateCallbackName('iframefcb');\n // GApi loader not available, dynamically load platform.js.\n _window()[cbName] = () => {\n // GApi loader should be ready.\n if (!!gapi.load) {\n loadGapiIframe();\n } else {\n // Gapi loader failed, throw error.\n reject(_createError(auth, AuthErrorCode.NETWORK_REQUEST_FAILED));\n }\n };\n // Load GApi loader.\n return js\n ._loadJS(`https://apis.google.com/js/api.js?onload=${cbName}`)\n .catch(e => reject(e));\n }\n }).catch(error => {\n // Reset cached promise to allow for retrial.\n cachedGApiLoader = null;\n throw error;\n });\n}\n\nlet cachedGApiLoader: Promise | null = null;\nexport function _loadGapi(auth: AuthInternal): Promise {\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\n return cachedGApiLoader;\n}\n\nexport function _resetLoader(): void {\n cachedGApiLoader = null;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { querystring } from '@firebase/util';\nimport { DefaultConfig } from '../../../internal';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert, _createError } from '../../core/util/assert';\nimport { Delay } from '../../core/util/delay';\nimport { _emulatorUrl } from '../../core/util/emulator';\nimport { AuthInternal } from '../../model/auth';\nimport { _window } from '../auth_window';\nimport * as gapiLoader from './gapi';\n\nconst PING_TIMEOUT = new Delay(5000, 15000);\nconst IFRAME_PATH = '__/auth/iframe';\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\n\nconst IFRAME_ATTRIBUTES = {\n style: {\n position: 'absolute',\n top: '-100px',\n width: '1px',\n height: '1px'\n },\n 'aria-hidden': 'true',\n tabindex: '-1'\n};\n\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\nconst EID_FROM_APIHOST = new Map([\n [DefaultConfig.API_HOST, 'p'], // production\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'], // staging\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\n]);\n\nfunction getIframeUrl(auth: AuthInternal): string {\n const config = auth.config;\n _assert(config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n const url = config.emulator\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\n\n const params: Record = {\n apiKey: config.apiKey,\n appName: auth.name,\n v: SDK_VERSION\n };\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\n if (eid) {\n params.eid = eid;\n }\n const frameworks = auth._getFrameworks();\n if (frameworks.length) {\n params.fw = frameworks.join(',');\n }\n return `${url}?${querystring(params).slice(1)}`;\n}\n\nexport async function _openIframe(\n auth: AuthInternal\n): Promise {\n const context = await gapiLoader._loadGapi(auth);\n const gapi = _window().gapi;\n _assert(gapi, auth, AuthErrorCode.INTERNAL_ERROR);\n return context.open(\n {\n where: document.body,\n url: getIframeUrl(auth),\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\n attributes: IFRAME_ATTRIBUTES,\n dontclear: true\n },\n (iframe: gapi.iframes.Iframe) =>\n new Promise(async (resolve, reject) => {\n await iframe.restyle({\n // Prevent iframe from closing on mouse out.\n setHideOnLeave: false\n });\n\n const networkError = _createError(\n auth,\n AuthErrorCode.NETWORK_REQUEST_FAILED\n );\n // Confirm iframe is correctly loaded.\n // To fallback on failure, set a timeout.\n const networkErrorTimer = _window().setTimeout(() => {\n reject(networkError);\n }, PING_TIMEOUT.get());\n // Clear timer and resolve pending iframe ready promise.\n function clearTimerAndResolve(): void {\n _window().clearTimeout(networkErrorTimer);\n resolve(iframe);\n }\n // This returns an IThenable. However the reject part does not call\n // when the iframe is not loaded.\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\n reject(networkError);\n });\n })\n );\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getUA } from '@firebase/util';\n\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\nimport {\n _isChromeIOS,\n _isFirefox,\n _isIOSStandalone\n} from '../../core/util/browser';\nimport { AuthInternal } from '../../model/auth';\n\nconst BASE_POPUP_OPTIONS = {\n location: 'yes',\n resizable: 'yes',\n statusbar: 'yes',\n toolbar: 'no'\n};\n\nconst DEFAULT_WIDTH = 500;\nconst DEFAULT_HEIGHT = 600;\nconst TARGET_BLANK = '_blank';\n\nconst FIREFOX_EMPTY_URL = 'http://localhost';\n\nexport class AuthPopup {\n associatedEvent: string | null = null;\n\n constructor(readonly window: Window | null) {}\n\n close(): void {\n if (this.window) {\n try {\n this.window.close();\n } catch (e) {}\n }\n }\n}\n\nexport function _open(\n auth: AuthInternal,\n url?: string,\n name?: string,\n width = DEFAULT_WIDTH,\n height = DEFAULT_HEIGHT\n): AuthPopup {\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\n let target = '';\n\n const options: { [key: string]: string } = {\n ...BASE_POPUP_OPTIONS,\n width: width.toString(),\n height: height.toString(),\n top,\n left\n };\n\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\n // specified, even though the popup is not necessarily blocked.\n const ua = getUA().toLowerCase();\n\n if (name) {\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\n }\n\n if (_isFirefox(ua)) {\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\n url = url || FIREFOX_EMPTY_URL;\n // Firefox disables by default scrolling on popup windows, which can create\n // issues when the user has many Google accounts, for instance.\n options.scrollbars = 'yes';\n }\n\n const optionsString = Object.entries(options).reduce(\n (accum, [key, value]) => `${accum}${key}=${value},`,\n ''\n );\n\n if (_isIOSStandalone(ua) && target !== '_self') {\n openAsNewWindowIOS(url || '', target);\n return new AuthPopup(null);\n }\n\n // about:blank getting sanitized causing browsers like IE/Edge to display\n // brief error message before redirecting to handler.\n const newWin = window.open(url || '', target, optionsString);\n _assert(newWin, auth, AuthErrorCode.POPUP_BLOCKED);\n\n // Flaky on IE edge, encapsulate with a try and catch.\n try {\n newWin.focus();\n } catch (e) {}\n\n return new AuthPopup(newWin);\n}\n\nfunction openAsNewWindowIOS(url: string, target: string): void {\n const el = document.createElement('a');\n el.href = url;\n el.target = target;\n const click = document.createEvent('MouseEvent');\n click.initMouseEvent(\n 'click',\n true,\n true,\n window,\n 1,\n 0,\n 0,\n 0,\n 0,\n false,\n false,\n false,\n false,\n 1,\n null\n );\n el.dispatchEvent(click);\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SDK_VERSION } from '@firebase/app';\nimport { AuthProvider } from '../../model/public_types';\nimport { ApiKey, AppName, AuthInternal } from '../../model/auth';\nimport { AuthEventType } from '../../model/popup_redirect';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from './assert';\nimport { isEmpty, querystring } from '@firebase/util';\nimport { _emulatorUrl } from './emulator';\nimport { FederatedAuthProvider } from '../providers/federated';\nimport { BaseOAuthProvider } from '../providers/oauth';\n\n/**\n * URL for Authentication widget which will initiate the OAuth handshake\n *\n * @internal\n */\nconst WIDGET_PATH = '__/auth/handler';\n\n/**\n * URL for emulated environment\n *\n * @internal\n */\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\n\n/**\n * Fragment name for the App Check token that gets passed to the widget\n *\n * @internal\n */\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ntype WidgetParams = {\n apiKey: ApiKey;\n appName: AppName;\n authType: AuthEventType;\n redirectUrl?: string;\n v: string;\n providerId?: string;\n scopes?: string;\n customParameters?: string;\n eventId?: string;\n tid?: string;\n} & { [key: string]: string | undefined };\n\nexport async function _getRedirectUrl(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n redirectUrl?: string,\n eventId?: string,\n additionalParams?: Record\n): Promise {\n _assert(auth.config.authDomain, auth, AuthErrorCode.MISSING_AUTH_DOMAIN);\n _assert(auth.config.apiKey, auth, AuthErrorCode.INVALID_API_KEY);\n\n const params: WidgetParams = {\n apiKey: auth.config.apiKey,\n appName: auth.name,\n authType,\n redirectUrl,\n v: SDK_VERSION,\n eventId\n };\n\n if (provider instanceof FederatedAuthProvider) {\n provider.setDefaultLanguage(auth.languageCode);\n params.providerId = provider.providerId || '';\n if (!isEmpty(provider.getCustomParameters())) {\n params.customParameters = JSON.stringify(provider.getCustomParameters());\n }\n\n // TODO set additionalParams from the provider as well?\n for (const [key, value] of Object.entries(additionalParams || {})) {\n params[key] = value;\n }\n }\n\n if (provider instanceof BaseOAuthProvider) {\n const scopes = provider.getScopes().filter(scope => scope !== '');\n if (scopes.length > 0) {\n params.scopes = scopes.join(',');\n }\n }\n\n if (auth.tenantId) {\n params.tid = auth.tenantId;\n }\n\n // TODO: maybe set eid as endipointId\n // TODO: maybe set fw as Frameworks.join(\",\")\n\n const paramsDict = params as Record;\n for (const key of Object.keys(paramsDict)) {\n if (paramsDict[key] === undefined) {\n delete paramsDict[key];\n }\n }\n\n // Sets the App Check token to pass to the widget\n const appCheckToken = await auth._getAppCheckToken();\n const appCheckTokenFragment = appCheckToken\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\n : '';\n\n // Start at index 1 to skip the leading '&' in the query string\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(\n 1\n )}${appCheckTokenFragment}`;\n}\n\nfunction getHandlerBase({ config }: AuthInternal): string {\n if (!config.emulator) {\n return `https://${config.authDomain}/${WIDGET_PATH}`;\n }\n\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AuthProvider, PopupRedirectResolver } from '../model/public_types';\n\nimport { AuthEventManager } from '../core/auth/auth_event_manager';\nimport { AuthErrorCode } from '../core/errors';\nimport { _assert, debugAssert, _fail } from '../core/util/assert';\nimport { _generateEventId } from '../core/util/event_id';\nimport { _getCurrentUrl } from '../core/util/location';\nimport { _validateOrigin } from '../core/util/validate_origin';\nimport { AuthInternal } from '../model/auth';\nimport {\n AuthEventType,\n EventManager,\n GapiAuthEvent,\n GapiOutcome,\n PopupRedirectResolverInternal\n} from '../model/popup_redirect';\nimport { _setWindowLocation } from './auth_window';\nimport { _openIframe } from './iframe/iframe';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { _open, AuthPopup } from './util/popup';\nimport { _getRedirectResult } from './strategies/redirect';\nimport { _getRedirectUrl } from '../core/util/handler';\nimport { _isIOS, _isMobileBrowser, _isSafari } from '../core/util/browser';\nimport { _overrideRedirectResult } from '../core/strategies/redirect';\n\n/**\n * The special web storage event\n *\n */\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\n\ninterface WebStorageSupportMessage extends gapi.iframes.Message {\n [index: number]: Record;\n}\n\ninterface ManagerOrPromise {\n manager?: EventManager;\n promise?: Promise;\n}\n\nclass BrowserPopupRedirectResolver implements PopupRedirectResolverInternal {\n private readonly eventManagers: Record = {};\n private readonly iframes: Record = {};\n private readonly originValidationPromises: Record> = {};\n\n readonly _redirectPersistence = browserSessionPersistence;\n\n // Wrapping in async even though we don't await anywhere in order\n // to make sure errors are raised as promise rejections\n async _openPopup(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise {\n debugAssert(\n this.eventManagers[auth._key()]?.manager,\n '_initialize() not called before _openPopup()'\n );\n\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n return _open(auth, url, _generateEventId());\n }\n\n async _openRedirect(\n auth: AuthInternal,\n provider: AuthProvider,\n authType: AuthEventType,\n eventId?: string\n ): Promise {\n await this._originValidation(auth);\n const url = await _getRedirectUrl(\n auth,\n provider,\n authType,\n _getCurrentUrl(),\n eventId\n );\n _setWindowLocation(url);\n return new Promise(() => {});\n }\n\n _initialize(auth: AuthInternal): Promise {\n const key = auth._key();\n if (this.eventManagers[key]) {\n const { manager, promise } = this.eventManagers[key];\n if (manager) {\n return Promise.resolve(manager);\n } else {\n debugAssert(promise, 'If manager is not set, promise should be');\n return promise;\n }\n }\n\n const promise = this.initAndGetManager(auth);\n this.eventManagers[key] = { promise };\n\n // If the promise is rejected, the key should be removed so that the\n // operation can be retried later.\n promise.catch(() => {\n delete this.eventManagers[key];\n });\n\n return promise;\n }\n\n private async initAndGetManager(auth: AuthInternal): Promise {\n const iframe = await _openIframe(auth);\n const manager = new AuthEventManager(auth);\n iframe.register(\n 'authEvent',\n (iframeEvent: GapiAuthEvent | null) => {\n _assert(iframeEvent?.authEvent, auth, AuthErrorCode.INVALID_AUTH_EVENT);\n // TODO: Consider splitting redirect and popup events earlier on\n\n const handled = manager.onEvent(iframeEvent.authEvent);\n return { status: handled ? GapiOutcome.ACK : GapiOutcome.ERROR };\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n\n this.eventManagers[auth._key()] = { manager };\n this.iframes[auth._key()] = iframe;\n return manager;\n }\n\n _isIframeWebStorageSupported(\n auth: AuthInternal,\n cb: (supported: boolean) => unknown\n ): void {\n const iframe = this.iframes[auth._key()];\n iframe.send(\n WEB_STORAGE_SUPPORT_KEY,\n { type: WEB_STORAGE_SUPPORT_KEY },\n result => {\n const isSupported = result?.[0]?.[WEB_STORAGE_SUPPORT_KEY];\n if (isSupported !== undefined) {\n cb(!!isSupported);\n }\n\n _fail(auth, AuthErrorCode.INTERNAL_ERROR);\n },\n gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER\n );\n }\n\n _originValidation(auth: AuthInternal): Promise {\n const key = auth._key();\n if (!this.originValidationPromises[key]) {\n this.originValidationPromises[key] = _validateOrigin(auth);\n }\n\n return this.originValidationPromises[key];\n }\n\n get _shouldInitProactively(): boolean {\n // Mobile browsers and Safari need to optimistically initialize\n return _isMobileBrowser() || _isSafari() || _isIOS();\n }\n\n _completeRedirectFn = _getRedirectResult;\n\n _overrideRedirectResult = _overrideRedirectResult;\n}\n\n/**\n * An implementation of {@link PopupRedirectResolver} suitable for browser\n * based applications.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @public\n */\nexport const browserPopupRedirectResolver: PopupRedirectResolver =\n BrowserPopupRedirectResolver;\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FactorId, MultiFactorAssertion } from '../model/public_types';\nimport { debugFail } from '../core/util/assert';\nimport { MultiFactorSessionImpl, MultiFactorSessionType } from './mfa_session';\nimport { FinalizeMfaResponse } from '../api/authentication/mfa';\nimport { AuthInternal } from '../model/auth';\n\nexport abstract class MultiFactorAssertionImpl implements MultiFactorAssertion {\n protected constructor(readonly factorId: FactorId) {}\n\n _process(\n auth: AuthInternal,\n session: MultiFactorSessionImpl,\n displayName?: string | null\n ): Promise {\n switch (session.type) {\n case MultiFactorSessionType.ENROLL:\n return this._finalizeEnroll(auth, session.credential, displayName);\n case MultiFactorSessionType.SIGN_IN:\n return this._finalizeSignIn(auth, session.credential);\n default:\n return debugFail('unexpected MultiFactorSessionType');\n }\n }\n\n abstract _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise;\n abstract _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n FactorId,\n PhoneMultiFactorAssertion\n} from '../../../model/public_types';\n\nimport { MultiFactorAssertionImpl } from '../../../mfa/mfa_assertion';\nimport { AuthInternal } from '../../../model/auth';\nimport { finalizeEnrollPhoneMfa } from '../../../api/account_management/mfa';\nimport { PhoneAuthCredential } from '../../../core/credentials/phone';\nimport {\n finalizeSignInPhoneMfa,\n FinalizeMfaResponse\n} from '../../../api/authentication/mfa';\n\n/**\n * {@inheritdoc PhoneMultiFactorAssertion}\n *\n * @public\n */\nexport class PhoneMultiFactorAssertionImpl\n extends MultiFactorAssertionImpl\n implements PhoneMultiFactorAssertion\n{\n private constructor(private readonly credential: PhoneAuthCredential) {\n super(FactorId.PHONE);\n }\n\n /** @internal */\n static _fromCredential(\n credential: PhoneAuthCredential\n ): PhoneMultiFactorAssertionImpl {\n return new PhoneMultiFactorAssertionImpl(credential);\n }\n\n /** @internal */\n _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise {\n return finalizeEnrollPhoneMfa(auth, {\n idToken,\n displayName,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n\n /** @internal */\n _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise {\n return finalizeSignInPhoneMfa(auth, {\n mfaPendingCredential,\n phoneVerificationInfo: this.credential._makeVerificationRequest()\n });\n }\n}\n\n/**\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\n *\n * @public\n */\nexport class PhoneMultiFactorGenerator {\n private constructor() {}\n\n /**\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\n *\n * @remarks\n * This method does not work in a Node.js environment.\n *\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\n * {@link MultiFactorResolver.resolveSignIn}\n */\n static assertion(credential: PhoneAuthCredential): PhoneMultiFactorAssertion {\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\n }\n\n /**\n * The identifier of the phone second factor: `phone`.\n */\n static FACTOR_ID = 'phone';\n}\n", "/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n TotpMultiFactorAssertion,\n MultiFactorSession,\n FactorId\n} from '../../model/public_types';\nimport { AuthInternal } from '../../model/auth';\nimport {\n finalizeEnrollTotpMfa,\n startEnrollTotpMfa,\n StartTotpMfaEnrollmentResponse,\n TotpVerificationInfo\n} from '../../api/account_management/mfa';\nimport {\n FinalizeMfaResponse,\n finalizeSignInTotpMfa\n} from '../../api/authentication/mfa';\nimport { MultiFactorAssertionImpl } from '../../mfa/mfa_assertion';\nimport { MultiFactorSessionImpl } from '../mfa_session';\nimport { AuthErrorCode } from '../../core/errors';\nimport { _assert } from '../../core/util/assert';\n\n/**\n * Provider for generating a {@link TotpMultiFactorAssertion}.\n *\n * @public\n */\nexport class TotpMultiFactorGenerator {\n /**\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of\n * the TOTP (time-based one-time password) second factor.\n * This assertion is used to complete enrollment in TOTP second factor.\n *\n * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.\n * @param oneTimePassword One-time password from TOTP App.\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\n * {@link MultiFactorUser.enroll}.\n */\n static assertionForEnrollment(\n secret: TotpSecret,\n oneTimePassword: string\n ): TotpMultiFactorAssertion {\n return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);\n }\n\n /**\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.\n * This assertion is used to complete signIn with TOTP as the second factor.\n *\n * @param enrollmentId identifies the enrolled TOTP second factor.\n * @param oneTimePassword One-time password from TOTP App.\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\n * {@link MultiFactorResolver.resolveSignIn}.\n */\n static assertionForSignIn(\n enrollmentId: string,\n oneTimePassword: string\n ): TotpMultiFactorAssertion {\n return TotpMultiFactorAssertionImpl._fromEnrollmentId(\n enrollmentId,\n oneTimePassword\n );\n }\n\n /**\n * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.\n * Creates a TOTP secret as part of enrolling a TOTP second factor.\n * Used for generating a QR code URL or inputting into a TOTP app.\n * This method uses the auth instance corresponding to the user in the multiFactorSession.\n *\n * @param session The {@link MultiFactorSession} that the user is part of.\n * @returns A promise to {@link TotpSecret}.\n */\n static async generateSecret(\n session: MultiFactorSession\n ): Promise {\n const mfaSession = session as MultiFactorSessionImpl;\n _assert(\n typeof mfaSession.user?.auth !== 'undefined',\n AuthErrorCode.INTERNAL_ERROR\n );\n const response = await startEnrollTotpMfa(mfaSession.user.auth, {\n idToken: mfaSession.credential,\n totpEnrollmentInfo: {}\n });\n return TotpSecret._fromStartTotpMfaEnrollmentResponse(\n response,\n mfaSession.user.auth\n );\n }\n\n /**\n * The identifier of the TOTP second factor: `totp`.\n */\n static FACTOR_ID: 'totp' = FactorId.TOTP;\n}\n\nexport class TotpMultiFactorAssertionImpl\n extends MultiFactorAssertionImpl\n implements TotpMultiFactorAssertion\n{\n constructor(\n readonly otp: string,\n readonly enrollmentId?: string,\n readonly secret?: TotpSecret\n ) {\n super(FactorId.TOTP);\n }\n\n /** @internal */\n static _fromSecret(\n secret: TotpSecret,\n otp: string\n ): TotpMultiFactorAssertionImpl {\n return new TotpMultiFactorAssertionImpl(otp, undefined, secret);\n }\n\n /** @internal */\n static _fromEnrollmentId(\n enrollmentId: string,\n otp: string\n ): TotpMultiFactorAssertionImpl {\n return new TotpMultiFactorAssertionImpl(otp, enrollmentId);\n }\n\n /** @internal */\n async _finalizeEnroll(\n auth: AuthInternal,\n idToken: string,\n displayName?: string | null\n ): Promise {\n _assert(\n typeof this.secret !== 'undefined',\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n return finalizeEnrollTotpMfa(auth, {\n idToken,\n displayName,\n totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)\n });\n }\n\n /** @internal */\n async _finalizeSignIn(\n auth: AuthInternal,\n mfaPendingCredential: string\n ): Promise {\n _assert(\n this.enrollmentId !== undefined && this.otp !== undefined,\n auth,\n AuthErrorCode.ARGUMENT_ERROR\n );\n const totpVerificationInfo = { verificationCode: this.otp };\n return finalizeSignInTotpMfa(auth, {\n mfaPendingCredential,\n mfaEnrollmentId: this.enrollmentId,\n totpVerificationInfo\n });\n }\n}\n\n/**\n * Provider for generating a {@link TotpMultiFactorAssertion}.\n *\n * Stores the shared secret key and other parameters to generate time-based OTPs.\n * Implements methods to retrieve the shared secret key and generate a QR code URL.\n * @public\n */\nexport class TotpSecret {\n /**\n * Shared secret key/seed used for enrolling in TOTP MFA and generating OTPs.\n */\n readonly secretKey: string;\n /**\n * Hashing algorithm used.\n */\n readonly hashingAlgorithm: string;\n /**\n * Length of the one-time passwords to be generated.\n */\n readonly codeLength: number;\n /**\n * The interval (in seconds) when the OTP codes should change.\n */\n readonly codeIntervalSeconds: number;\n /**\n * The timestamp (UTC string) by which TOTP enrollment should be completed.\n */\n // This can be used by callers to show a countdown of when to enter OTP code by.\n readonly enrollmentCompletionDeadline: string;\n\n // The public members are declared outside the constructor so the docs can be generated.\n private constructor(\n secretKey: string,\n hashingAlgorithm: string,\n codeLength: number,\n codeIntervalSeconds: number,\n enrollmentCompletionDeadline: string,\n private readonly sessionInfo: string,\n private readonly auth: AuthInternal\n ) {\n this.secretKey = secretKey;\n this.hashingAlgorithm = hashingAlgorithm;\n this.codeLength = codeLength;\n this.codeIntervalSeconds = codeIntervalSeconds;\n this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;\n }\n\n /** @internal */\n static _fromStartTotpMfaEnrollmentResponse(\n response: StartTotpMfaEnrollmentResponse,\n auth: AuthInternal\n ): TotpSecret {\n return new TotpSecret(\n response.totpSessionInfo.sharedSecretKey,\n response.totpSessionInfo.hashingAlgorithm,\n response.totpSessionInfo.verificationCodeLength,\n response.totpSessionInfo.periodSec,\n new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),\n response.totpSessionInfo.sessionInfo,\n auth\n );\n }\n\n /** @internal */\n _makeTotpVerificationInfo(otp: string): TotpVerificationInfo {\n return { sessionInfo: this.sessionInfo, verificationCode: otp };\n }\n\n /**\n * Returns a QR code URL as described in\n * https://github.com/google/google-authenticator/wiki/Key-Uri-Format\n * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.\n * If the optional parameters are unspecified, an accountName of and issuer of are used.\n *\n * @param accountName the name of the account/app along with a user identifier.\n * @param issuer issuer of the TOTP (likely the app name).\n * @returns A QR code URL string.\n */\n generateQrCodeUrl(accountName?: string, issuer?: string): string {\n let useDefaults = false;\n if (_isEmptyString(accountName) || _isEmptyString(issuer)) {\n useDefaults = true;\n }\n if (useDefaults) {\n if (_isEmptyString(accountName)) {\n accountName = this.auth.currentUser?.email || 'unknownuser';\n }\n if (_isEmptyString(issuer)) {\n issuer = this.auth.name;\n }\n }\n return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;\n }\n}\n\n/** @internal */\nfunction _isEmptyString(input?: string): boolean {\n return typeof input === 'undefined' || input?.length === 0;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Unsubscribe } from '@firebase/util';\nimport { FirebaseAuthInternal } from '@firebase/auth-interop-types';\n\nimport { AuthInternal } from '../../model/auth';\nimport { UserInternal } from '../../model/user';\nimport { _assert } from '../util/assert';\nimport { AuthErrorCode } from '../errors';\n\ninterface TokenListener {\n (tok: string | null): unknown;\n}\n\nexport class AuthInterop implements FirebaseAuthInternal {\n private readonly internalListeners: Map =\n new Map();\n\n constructor(private readonly auth: AuthInternal) {}\n\n getUid(): string | null {\n this.assertAuthConfigured();\n return this.auth.currentUser?.uid || null;\n }\n\n async getToken(\n forceRefresh?: boolean\n ): Promise<{ accessToken: string } | null> {\n this.assertAuthConfigured();\n await this.auth._initializationPromise;\n if (!this.auth.currentUser) {\n return null;\n }\n\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\n return { accessToken };\n }\n\n addAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n if (this.internalListeners.has(listener)) {\n return;\n }\n\n const unsubscribe = this.auth.onIdTokenChanged(user => {\n listener(\n (user as UserInternal | null)?.stsTokenManager.accessToken || null\n );\n });\n this.internalListeners.set(listener, unsubscribe);\n this.updateProactiveRefresh();\n }\n\n removeAuthTokenListener(listener: TokenListener): void {\n this.assertAuthConfigured();\n const unsubscribe = this.internalListeners.get(listener);\n if (!unsubscribe) {\n return;\n }\n\n this.internalListeners.delete(listener);\n unsubscribe();\n this.updateProactiveRefresh();\n }\n\n private assertAuthConfigured(): void {\n _assert(\n this.auth._initializationPromise,\n AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH\n );\n }\n\n private updateProactiveRefresh(): void {\n if (this.internalListeners.size > 0) {\n this.auth._startProactiveRefresh();\n } else {\n this.auth._stopProactiveRefresh();\n }\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { _registerComponent, registerVersion } from '@firebase/app';\nimport {\n Component,\n ComponentType,\n InstantiationMode\n} from '@firebase/component';\n\nimport { name, version } from '../../../package.json';\nimport { AuthErrorCode } from '../errors';\nimport { _assert } from '../util/assert';\nimport { _getClientVersion, ClientPlatform } from '../util/version';\nimport { _castAuth, AuthImpl, DefaultConfig } from './auth_impl';\nimport { AuthInterop } from './firebase_internal';\nimport { ConfigInternal } from '../../model/auth';\nimport { Dependencies } from '../../model/public_types';\nimport { _initializeAuthInstance } from './initialize';\n\nexport const enum _ComponentName {\n AUTH = 'auth',\n AUTH_INTERNAL = 'auth-internal'\n}\n\nfunction getVersionForPlatform(\n clientPlatform: ClientPlatform\n): string | undefined {\n switch (clientPlatform) {\n case ClientPlatform.NODE:\n return 'node';\n case ClientPlatform.REACT_NATIVE:\n return 'rn';\n case ClientPlatform.WORKER:\n return 'webworker';\n case ClientPlatform.CORDOVA:\n return 'cordova';\n default:\n return undefined;\n }\n}\n\n/** @internal */\nexport function registerAuth(clientPlatform: ClientPlatform): void {\n _registerComponent(\n new Component(\n _ComponentName.AUTH,\n (container, { options: deps }: { options?: Dependencies }) => {\n const app = container.getProvider('app').getImmediate()!;\n const heartbeatServiceProvider =\n container.getProvider<'heartbeat'>('heartbeat');\n const appCheckServiceProvider =\n container.getProvider<'app-check-internal'>('app-check-internal');\n const { apiKey, authDomain } = app.options;\n\n _assert(\n apiKey && !apiKey.includes(':'),\n AuthErrorCode.INVALID_API_KEY,\n { appName: app.name }\n );\n\n const config: ConfigInternal = {\n apiKey,\n authDomain,\n clientPlatform,\n apiHost: DefaultConfig.API_HOST,\n tokenApiHost: DefaultConfig.TOKEN_API_HOST,\n apiScheme: DefaultConfig.API_SCHEME,\n sdkClientVersion: _getClientVersion(clientPlatform)\n };\n\n const authInstance = new AuthImpl(\n app,\n heartbeatServiceProvider,\n appCheckServiceProvider,\n config\n );\n _initializeAuthInstance(authInstance, deps);\n\n return authInstance;\n },\n ComponentType.PUBLIC\n )\n /**\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\n * For why we do this, See go/firebase-next-auth-init\n */\n .setInstantiationMode(InstantiationMode.EXPLICIT)\n /**\n * Because all firebase products that depend on auth depend on auth-internal directly,\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\n */\n .setInstanceCreatedCallback(\n (container, _instanceIdentifier, _instance) => {\n const authInternalProvider = container.getProvider(\n _ComponentName.AUTH_INTERNAL\n );\n authInternalProvider.initialize();\n }\n )\n );\n\n _registerComponent(\n new Component(\n _ComponentName.AUTH_INTERNAL,\n container => {\n const auth = _castAuth(\n container.getProvider(_ComponentName.AUTH).getImmediate()!\n );\n return (auth => new AuthInterop(auth))(auth);\n },\n ComponentType.PRIVATE\n ).setInstantiationMode(InstantiationMode.EXPLICIT)\n );\n\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n", "/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp, getApp, _getProvider } from '@firebase/app';\n\nimport {\n initializeAuth,\n beforeAuthStateChanged,\n onIdTokenChanged,\n connectAuthEmulator\n} from '..';\nimport { registerAuth } from '../core/auth/register';\nimport { ClientPlatform } from '../core/util/version';\nimport { browserLocalPersistence } from './persistence/local_storage';\nimport { browserSessionPersistence } from './persistence/session_storage';\nimport { indexedDBLocalPersistence } from './persistence/indexed_db';\nimport { browserPopupRedirectResolver } from './popup_redirect';\nimport { Auth, User } from '../model/public_types';\nimport { getDefaultEmulatorHost, getExperimentalSetting } from '@firebase/util';\n\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\nconst authIdTokenMaxAge =\n getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\n\nlet lastPostedIdToken: string | undefined | null = null;\n\nconst mintCookieFactory = (url: string) => async (user: User | null) => {\n const idTokenResult = user && (await user.getIdTokenResult());\n const idTokenAge =\n idTokenResult &&\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1_000;\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\n return;\n }\n // Specifically trip null => undefined when logged out, to delete any existing cookie\n const idToken = idTokenResult?.token;\n if (lastPostedIdToken === idToken) {\n return;\n }\n lastPostedIdToken = idToken;\n await fetch(url, {\n method: idToken ? 'POST' : 'DELETE',\n headers: idToken\n ? {\n 'Authorization': `Bearer ${idToken}`\n }\n : {}\n });\n};\n\n/**\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\n *\n * @param app - The Firebase App.\n *\n * @public\n */\nexport function getAuth(app: FirebaseApp = getApp()): Auth {\n const provider = _getProvider(app, 'auth');\n\n if (provider.isInitialized()) {\n return provider.getImmediate();\n }\n\n const auth = initializeAuth(app, {\n popupRedirectResolver: browserPopupRedirectResolver,\n persistence: [\n indexedDBLocalPersistence,\n browserLocalPersistence,\n browserSessionPersistence\n ]\n });\n\n const authTokenSyncUrl = getExperimentalSetting('authTokenSyncURL');\n if (authTokenSyncUrl) {\n const mintCookie = mintCookieFactory(authTokenSyncUrl);\n beforeAuthStateChanged(auth, mintCookie, () =>\n mintCookie(auth.currentUser)\n );\n onIdTokenChanged(auth, user => mintCookie(user));\n }\n\n const authEmulatorHost = getDefaultEmulatorHost('auth');\n if (authEmulatorHost) {\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\n }\n\n return auth;\n}\n\nregisterAuth(ClientPlatform.BROWSER);\n", "/* eslint-disable no-param-reassign */\n/* eslint-disable react/no-unknown-property */\n/* eslint-disable react/no-danger */\nimport { json } from '@remix-run/node';\nimport {\n Links,\n LiveReload,\n Meta,\n Outlet,\n Scripts,\n ScrollRestoration,\n useLoaderData,\n} from '@remix-run/react';\nimport {\n HydrationBoundary,\n QueryClient,\n QueryClientProvider,\n} from '@tanstack/react-query';\nimport { ElemasonRemixProvider } from '@tectonic/elemason-remix';\nimport { ThemeProvider } from '@tectonic/uikit';\nimport {\n populate,\n populateEnvs,\n isMobile as queryIsMobile\n} from '@tectonic/utils';\nimport axios from 'axios';\nimport { useEffect, useMemo, useState } from 'react';\nimport { useDehydratedState } from 'use-dehydrated-state';\nimport FingerprintsDisplay from './components/Fingerprints';\nimport OIB from './components/OIB';\nimport Transition from './components/Transition';\nimport { RootProvider } from './contexts/RootContext';\nimport useAppLaunchEffect from './hooks/useAppLaunchEffect';\n\nimport type { AppLoadContext, LoaderFunctionArgs } from '@remix-run/node';\nimport type { Routes } from '@tectonic/elemason-remix';\nimport type { Color, ElemasonWidget, SessionInfo, User } from '@tectonic/types';\nimport type { ComponentType, FC, ReactNode } from 'react';\n\ninterface AppProps {\n routes: Routes;\n title?: string;\n cssHref?: string;\n svgHref?: string;\n description?: string;\n colors: Record;\n // extra children to be added to the head\n head?: ReactNode;\n body?: ReactNode;\n widgets?: Record<\n string,\n ComponentType<{ widget: ElemasonWidget }>\n >;\n}\n\nconst minifyCSS = (css: string) => {\n // Remove comments\n css = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n\n // Remove newline characters\n css = css.replace(/\\n/g, '');\n\n // Remove whitespace before and after colons\n css = css.replace(/\\s*:\\s*/g, ':');\n\n // Remove whitespace before and after semicolons\n css = css.replace(/\\s*;\\s*/g, ';');\n\n // Remove whitespace before and after commas\n css = css.replace(/\\s*,\\s*/g, ',');\n\n // Remove whitespace before and after curly braces\n css = css.replace(/\\s*{\\s*/g, '{');\n css = css.replace(/\\s*}\\s*/g, '}');\n\n // Remove whitespace before and after parentheses\n css = css.replace(/\\s*\\(\\s*/g, '(');\n css = css.replace(/\\s*\\)\\s*/g, ')');\n\n return css;\n};\n\nconst getBrowserEnv = (context: AppLoadContext): Record => {\n const env = context.browserEnvs as Record;\n const { GTAG_HOST, GTAG_ID, ORGANIZATION, API_HOST, GTM_ID } = env;\n const placeholders = {\n organization: ORGANIZATION,\n gtmHost: GTAG_HOST,\n gtagId: GTAG_ID,\n apiHost: API_HOST,\n };\n\n return {\n ORGANIZATION: env.ORGANIZATION,\n NODE_ENV: process.env.NODE_ENV,\n\n MIXPANEL_PROJECT_TOKEN: env.MIXPANEL_PROJECT_TOKEN,\n MIXPANEL_PROXY_DOMAIN: env.MIXPANEL_PROXY_DOMAIN,\n ENABLE_FP_PRO: env.ENABLE_FP_PRO,\n FP_PRO_KEY: env.FP_PRO_KEY,\n FP_PRO_REGION: env.FP_PRO_REGION,\n\n GTAG_HOST,\n GTAG_ID,\n GTM_ID,\n GTAG_JS_URL: populate(env.GTAG_JS_URL, placeholders),\n\n FIREBASE_APP_ID: env.FIREBASE_APP_ID,\n FIREBASE_API_KEY: env.FIREBASE_API_KEY,\n FIREBASE_PROJECT_ID: env.FIREBASE_PROJECT_ID,\n FIREBASE_AUTH_DOMAIN: env.FIREBASE_AUTH_DOMAIN,\n FIREBASE_STORAGE_BUCKET: env.FIREBASE_STORAGE_BUCKET,\n FIREBASE_MEASUREMENT_ID: env.FIREBASE_MEASUREMENT_ID,\n FIREBASE_MESSAGING_SENDER_ID: env.FIREBASE_MESSAGING_SENDER_ID,\n\n DAM_URL: populate(env.DAM_URL, placeholders),\n API_END_POINT_V2: populate(env.API_END_POINT_V2, placeholders),\n ROOT_DOMAIN: env.ROOT_DOMAIN,\n SENTRY_DSN: env.SENTRY_DSN,\n MIXPANEL_DEBUG_MODE: env.MIXPANEL_DEBUG_MODE,\n\n CLARITY_TOKEN: env.CLARITY_TOKEN\n };\n};\n\nlet cachedCss = '';\n\nconst loaderGen =\n (mainCss: string) =>\n async ({ context, request }: LoaderFunctionArgs) => {\n populateEnvs(process.env);\n\n const env = getBrowserEnv(context);\n const isMobile = queryIsMobile(request.headers.get('user-agent'));\n\n const css =\n cachedCss ||\n ((await axios.get(`${new URL(request.url).origin}${mainCss}`))\n .data as string);\n\n cachedCss = css;\n\n return json({\n env,\n isMobile,\n css: minifyCSS(css),\n serverTime: Date.now(),\n currentUser: (context.auth as Record)\n .currentUser as User,\n currentCookies: (context.currentCookies) as Record,\n sessionInfo: context.sessionInfo as SessionInfo,\n ttTester: context.ttTester,\n });\n };\n\nconst loader = async ({ context, request }: LoaderFunctionArgs) => {\n populateEnvs(process.env);\n\n const env = getBrowserEnv(context);\n const isMobile = queryIsMobile(request.headers.get('user-agent'));\n\n return json({\n env,\n isMobile,\n css: '',\n serverTime: Date.now(),\n currentUser: (context.auth as Record).currentUser as User,\n sessionInfo: context.sessionInfo as SessionInfo,\n currentCookies: (context.currentCookies) as Record,\n ttTester: context.ttTester as boolean,\n });\n};\n\ntype RootLoaderType = Awaited<\n ReturnType>['json']>\n>;\n\n// TODO: Delete this package and make it part of the application code itself.\n// - We need to setup analytics. Analytics requires it's own store. If we keep core\n// as a separate we'll have to add elemason as dependency to this project and import\n// functions like toAnalyticsPayload etc.\n// - we need route handle data so that we can pass arbitrary data to component\n// eg. analytics requires screen name. Presently, we dump screen name to analytic\n// store.\n// - Currently, remix is not part of the elemason. Because of that when we a user\n// navigates from one screen to another, entire page is reloaded since we are\n// using `window.location.href=something`. When we use useNavigation from\n// remix, it doesn't reload the entire page.\n\nconst App: FC = ({\n colors,\n routes,\n title,\n cssHref,\n svgHref,\n description,\n head,\n widgets,\n body,\n}) => {\n const dehydratedState = useDehydratedState();\n const [queryClient] = useState(() => new QueryClient());\n const {\n env,\n currentUser,\n sessionInfo,\n ttTester,\n isMobile,\n serverTime,\n css,\n currentCookies\n } =\n useLoaderData();\n\n useEffect(() => {\n globalThis.timeDrift = Date.now() - serverTime;\n }, []);\n\n useAppLaunchEffect({\n env,\n currentUser,\n isMobile,\n sessionInfo,\n serverTime,\n ttTester\n });\n\n const memoOIB = useMemo(() => , []);\n\n return (\n \n \n \n \n \n \n \n \n {title ? (\n <>\n {title}\n \n \n ) : null}\n\n {description ? (\n <>\n \n \n \n ) : null}\n {css ? (\n \n ) : (\n cssHref && (\n \n )\n )}\n \n \n {\n document?.body?.style.setProperty('--scroll-y', window.scrollY)\n });`,\n }}\n />\n {\n if (event.persisted && !document.cookie.match(/__tt_sanity/)) {\n window.location.reload();\n }\n })`,\n }}\n />\n {head ?? null}\n \n {/* @ts-ignore */}\n \n {ttTester ? (\n
\n

\uD83E\uDD16

\n
\n ) : null}\n {memoOIB}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n {/* */}\n {body}\n \n \n );\n};\n\nexport { loaderGen, App as RootApp, loader as rootLoader };\nexport type { RootLoaderType };\n\n", "import { useNavigate } from '@remix-run/react';\nimport { ElemasonProvider } from '@tectonic/elemason';\nimport { Logger } from '@tectonic/logger';\nimport { NavigationActionType } from '@tectonic/types';\nimport { populateWithEncode, toUrlSearchParams } from '@tectonic/utils';\nimport { useMemo } from 'react';\nimport { useParams } from './hooks';\n\nimport type {\n ElemasonWidget,\n Maybe,\n NavigationActionPayload,\n User,\n} from '@tectonic/types';\nimport type { ComponentProps, ComponentType, FC } from 'react';\n\ntype Route = {\n path: string;\n};\n\ntype Routes = Record;\n\ninterface ElemasonRemixProviderProps\n extends Omit, 'value'> {\n value: {\n user: User;\n currentCookies: Maybe>;\n routes: Routes;\n env: Record;\n widgets?: Record<\n string,\n ComponentType<{ widget: ElemasonWidget }>\n >;\n };\n}\n\nconst withSearchParams = (pathname: string, search?: Record) =>\n `${pathname}${search ? `?${toUrlSearchParams(search)}` : ''}`;\n\nconst getHref = (routes: Routes, payload: NavigationActionPayload) => {\n try {\n switch (payload.type) {\n case NavigationActionType.PDP: {\n const path = populateWithEncode(routes.pdp.path, payload.route);\n return withSearchParams(path, payload.search);\n }\n\n case NavigationActionType.PRODUCT_REVIEWS: {\n const path = populateWithEncode(\n routes['product-reviews'].path,\n payload.route\n );\n return withSearchParams(path, payload.search);\n }\n\n case NavigationActionType.COLLECTION: {\n const path = populateWithEncode(routes.collection.path, payload.route);\n return withSearchParams(path, payload.search);\n }\n\n case NavigationActionType.ORDER: {\n const path = populateWithEncode(routes.order.path, payload.route);\n return withSearchParams(path, payload.search);\n }\n\n case NavigationActionType.ORDER_ITEM: {\n const path = populateWithEncode(\n routes['order-details'].path,\n payload.route\n );\n return withSearchParams(path, payload.search);\n }\n\n case NavigationActionType.PATH: {\n const path = populateWithEncode(\n routes[payload.slug].path,\n payload.route ?? {}\n );\n return withSearchParams(path, payload.search);\n }\n\n default:\n throw new Error('Invalid navigation action');\n }\n } catch (e) {\n Logger.error(\n `Error while generating href ${JSON.stringify(\n payload\n )}. Check if page exists`\n );\n return '';\n }\n};\n\nconst getNavigationRegistry = (routes: Routes) => ({\n getHref(payload: NavigationActionPayload) {\n return getHref(routes, payload);\n },\n});\n\n// we need to so some sanitization on values so that accessor can have proper\n// conditions. eg. user returned from backend can not have phone key.\nconst useSanitizedUser = (user: User) =>\n useMemo(() => ({ ...user, phone: user?.phone ?? null }), []);\n\nconst ElemasonRemixProvider: FC = ({\n value,\n children,\n}) => {\n const { routeParams, searchParams, pathname } = useParams();\n const navigate = useNavigate();\n\n const sanitizedUser = useSanitizedUser(value.user);\n const navigationRegistry = useMemo(\n () => getNavigationRegistry(value.routes),\n [value.routes]\n );\n\n return (\n \n {children}\n \n );\n};\n\nElemasonRemixProvider.displayName = 'ElemasonRemixProvider';\n\nexport { ElemasonRemixProvider };\nexport type { Routes };\n\n", "import {\n useLocation,\n useParams as useRouteParams,\n useSearchParams,\n} from '@remix-run/react';\nimport { useMemo } from 'react';\n\nconst useParams = (): Record => {\n const routeParams = useRouteParams();\n const [searchParams] = useSearchParams();\n const location = useLocation();\n\n return useMemo(\n () => ({\n pathname: location.pathname,\n routeParams,\n searchParams: Object.fromEntries(searchParams.entries()),\n }),\n [routeParams, searchParams]\n );\n};\n\nuseParams.displayName = 'useParams';\n\nexport { useParams };\n", "'use strict';\n\nexport default function bind(fn, thisArg) {\n return function wrap() {\n return fn.apply(thisArg, arguments);\n };\n}\n", "'use strict';\n\nimport bind from './helpers/bind.js';\n\n// utils is a library of generic helper functions non-specific to axios\n\nconst {toString} = Object.prototype;\nconst {getPrototypeOf} = Object;\n\nconst kindOf = (cache => thing => {\n const str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n})(Object.create(null));\n\nconst kindOfTest = (type) => {\n type = type.toLowerCase();\n return (thing) => kindOf(thing) === type\n}\n\nconst typeOfTest = type => thing => typeof thing === type;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n *\n * @returns {boolean} True if value is an Array, otherwise false\n */\nconst {isArray} = Array;\n\n/**\n * Determine if a value is undefined\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nconst isUndefined = typeOfTest('undefined');\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nconst isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n let result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a String, otherwise false\n */\nconst isString = typeOfTest('string');\n\n/**\n * Determine if a value is a Function\n *\n * @param {*} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nconst isFunction = typeOfTest('function');\n\n/**\n * Determine if a value is a Number\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Number, otherwise false\n */\nconst isNumber = typeOfTest('number');\n\n/**\n * Determine if a value is an Object\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an Object, otherwise false\n */\nconst isObject = (thing) => thing !== null && typeof thing === 'object';\n\n/**\n * Determine if a value is a Boolean\n *\n * @param {*} thing The value to test\n * @returns {boolean} True if value is a Boolean, otherwise false\n */\nconst isBoolean = thing => thing === true || thing === false;\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a plain Object, otherwise false\n */\nconst isPlainObject = (val) => {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n const prototype = getPrototypeOf(val);\n return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Date, otherwise false\n */\nconst isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nconst isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a File, otherwise false\n */\nconst isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Stream\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nconst isStream = (val) => isObject(val) && isFunction(val.pipe);\n\n/**\n * Determine if a value is a FormData\n *\n * @param {*} thing The value to test\n *\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nconst isFormData = (thing) => {\n let kind;\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) || (\n isFunction(thing.append) && (\n (kind = kindOf(thing)) === 'formdata' ||\n // detect form-data instance\n (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')\n )\n )\n )\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nconst isURLSearchParams = kindOfTest('URLSearchParams');\n\nconst [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n *\n * @returns {String} The String freed of excess whitespace\n */\nconst trim = (str) => str.trim ?\n str.trim() : str.replace(/^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g, '');\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n *\n * @param {Boolean} [allOwnKeys = false]\n * @returns {any}\n */\nfunction forEach(obj, fn, {allOwnKeys = false} = {}) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n let i;\n let l;\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);\n const len = keys.length;\n let key;\n\n for (i = 0; i < len; i++) {\n key = keys[i];\n fn.call(null, obj[key], key, obj);\n }\n }\n}\n\nfunction findKey(obj, key) {\n key = key.toLowerCase();\n const keys = Object.keys(obj);\n let i = keys.length;\n let _key;\n while (i-- > 0) {\n _key = keys[i];\n if (key === _key.toLowerCase()) {\n return _key;\n }\n }\n return null;\n}\n\nconst _global = (() => {\n /*eslint no-undef:0*/\n if (typeof globalThis !== \"undefined\") return globalThis;\n return typeof self !== \"undefined\" ? self : (typeof window !== 'undefined' ? window : global)\n})();\n\nconst isContextDefined = (context) => !isUndefined(context) && context !== _global;\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n *\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n const {caseless} = isContextDefined(this) && this || {};\n const result = {};\n const assignValue = (val, key) => {\n const targetKey = caseless && findKey(result, key) || key;\n if (isPlainObject(result[targetKey]) && isPlainObject(val)) {\n result[targetKey] = merge(result[targetKey], val);\n } else if (isPlainObject(val)) {\n result[targetKey] = merge({}, val);\n } else if (isArray(val)) {\n result[targetKey] = val.slice();\n } else {\n result[targetKey] = val;\n }\n }\n\n for (let i = 0, l = arguments.length; i < l; i++) {\n arguments[i] && forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n *\n * @param {Boolean} [allOwnKeys]\n * @returns {Object} The resulting value of object a\n */\nconst extend = (a, b, thisArg, {allOwnKeys}= {}) => {\n forEach(b, (val, key) => {\n if (thisArg && isFunction(val)) {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n }, {allOwnKeys});\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n *\n * @returns {string} content value without BOM\n */\nconst stripBOM = (content) => {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n *\n * @returns {void}\n */\nconst inherits = (constructor, superConstructor, props, descriptors) => {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n Object.defineProperty(constructor, 'super', {\n value: superConstructor.prototype\n });\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function|Boolean} [filter]\n * @param {Function} [propFilter]\n *\n * @returns {Object}\n */\nconst toFlatObject = (sourceObj, destObj, filter, propFilter) => {\n let props;\n let i;\n let prop;\n const merged = {};\n\n destObj = destObj || {};\n // eslint-disable-next-line no-eq-null,eqeqeq\n if (sourceObj == null) return destObj;\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = filter !== false && getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/**\n * Determines whether a string ends with the characters of a specified string\n *\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n *\n * @returns {boolean}\n */\nconst endsWith = (str, searchString, position) => {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n const lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object or null if failed\n *\n * @param {*} [thing]\n *\n * @returns {?Array}\n */\nconst toArray = (thing) => {\n if (!thing) return null;\n if (isArray(thing)) return thing;\n let i = thing.length;\n if (!isNumber(i)) return null;\n const arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n/**\n * Checking if the Uint8Array exists and if it does, it returns a function that checks if the\n * thing passed in is an instance of Uint8Array\n *\n * @param {TypedArray}\n *\n * @returns {Array}\n */\n// eslint-disable-next-line func-names\nconst isTypedArray = (TypedArray => {\n // eslint-disable-next-line func-names\n return thing => {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));\n\n/**\n * For each entry in the object, call the function with the key and value.\n *\n * @param {Object} obj - The object to iterate over.\n * @param {Function} fn - The function to call for each entry.\n *\n * @returns {void}\n */\nconst forEachEntry = (obj, fn) => {\n const generator = obj && obj[Symbol.iterator];\n\n const iterator = generator.call(obj);\n\n let result;\n\n while ((result = iterator.next()) && !result.done) {\n const pair = result.value;\n fn.call(obj, pair[0], pair[1]);\n }\n}\n\n/**\n * It takes a regular expression and a string, and returns an array of all the matches\n *\n * @param {string} regExp - The regular expression to match against.\n * @param {string} str - The string to search.\n *\n * @returns {Array}\n */\nconst matchAll = (regExp, str) => {\n let matches;\n const arr = [];\n\n while ((matches = regExp.exec(str)) !== null) {\n arr.push(matches);\n }\n\n return arr;\n}\n\n/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */\nconst isHTMLForm = kindOfTest('HTMLFormElement');\n\nconst toCamelCase = str => {\n return str.toLowerCase().replace(/[-_\\s]([a-z\\d])(\\w*)/g,\n function replacer(m, p1, p2) {\n return p1.toUpperCase() + p2;\n }\n );\n};\n\n/* Creating a function that will check if an object has a property. */\nconst hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);\n\n/**\n * Determine if a value is a RegExp object\n *\n * @param {*} val The value to test\n *\n * @returns {boolean} True if value is a RegExp object, otherwise false\n */\nconst isRegExp = kindOfTest('RegExp');\n\nconst reduceDescriptors = (obj, reducer) => {\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n const reducedDescriptors = {};\n\n forEach(descriptors, (descriptor, name) => {\n let ret;\n if ((ret = reducer(descriptor, name, obj)) !== false) {\n reducedDescriptors[name] = ret || descriptor;\n }\n });\n\n Object.defineProperties(obj, reducedDescriptors);\n}\n\n/**\n * Makes all methods read-only\n * @param {Object} obj\n */\n\nconst freezeMethods = (obj) => {\n reduceDescriptors(obj, (descriptor, name) => {\n // skip restricted props in strict mode\n if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {\n return false;\n }\n\n const value = obj[name];\n\n if (!isFunction(value)) return;\n\n descriptor.enumerable = false;\n\n if ('writable' in descriptor) {\n descriptor.writable = false;\n return;\n }\n\n if (!descriptor.set) {\n descriptor.set = () => {\n throw Error('Can not rewrite read-only method \\'' + name + '\\'');\n };\n }\n });\n}\n\nconst toObjectSet = (arrayOrString, delimiter) => {\n const obj = {};\n\n const define = (arr) => {\n arr.forEach(value => {\n obj[value] = true;\n });\n }\n\n isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));\n\n return obj;\n}\n\nconst noop = () => {}\n\nconst toFiniteNumber = (value, defaultValue) => {\n return value != null && Number.isFinite(value = +value) ? value : defaultValue;\n}\n\nconst ALPHA = 'abcdefghijklmnopqrstuvwxyz'\n\nconst DIGIT = '0123456789';\n\nconst ALPHABET = {\n DIGIT,\n ALPHA,\n ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT\n}\n\nconst generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {\n let str = '';\n const {length} = alphabet;\n while (size--) {\n str += alphabet[Math.random() * length|0]\n }\n\n return str;\n}\n\n/**\n * If the thing is a FormData object, return true, otherwise return false.\n *\n * @param {unknown} thing - The thing to check.\n *\n * @returns {boolean}\n */\nfunction isSpecCompliantForm(thing) {\n return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);\n}\n\nconst toJSONObject = (obj) => {\n const stack = new Array(10);\n\n const visit = (source, i) => {\n\n if (isObject(source)) {\n if (stack.indexOf(source) >= 0) {\n return;\n }\n\n if(!('toJSON' in source)) {\n stack[i] = source;\n const target = isArray(source) ? [] : {};\n\n forEach(source, (value, key) => {\n const reducedValue = visit(value, i + 1);\n !isUndefined(reducedValue) && (target[key] = reducedValue);\n });\n\n stack[i] = undefined;\n\n return target;\n }\n }\n\n return source;\n }\n\n return visit(obj, 0);\n}\n\nconst isAsyncFn = kindOfTest('AsyncFunction');\n\nconst isThenable = (thing) =>\n thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);\n\nexport default {\n isArray,\n isArrayBuffer,\n isBuffer,\n isFormData,\n isArrayBufferView,\n isString,\n isNumber,\n isBoolean,\n isObject,\n isPlainObject,\n isReadableStream,\n isRequest,\n isResponse,\n isHeaders,\n isUndefined,\n isDate,\n isFile,\n isBlob,\n isRegExp,\n isFunction,\n isStream,\n isURLSearchParams,\n isTypedArray,\n isFileList,\n forEach,\n merge,\n extend,\n trim,\n stripBOM,\n inherits,\n toFlatObject,\n kindOf,\n kindOfTest,\n endsWith,\n toArray,\n forEachEntry,\n matchAll,\n isHTMLForm,\n hasOwnProperty,\n hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection\n reduceDescriptors,\n freezeMethods,\n toObjectSet,\n toCamelCase,\n noop,\n toFiniteNumber,\n findKey,\n global: _global,\n isContextDefined,\n ALPHABET,\n generateString,\n isSpecCompliantForm,\n toJSONObject,\n isAsyncFn,\n isThenable\n};\n", "'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n *\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n } else {\n this.stack = (new Error()).stack;\n }\n\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n response && (this.response = response);\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: utils.toJSONObject(this.config),\n code: this.code,\n status: this.response && this.response.status ? this.response.status : null\n };\n }\n});\n\nconst prototype = AxiosError.prototype;\nconst descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED',\n 'ERR_NOT_SUPPORT',\n 'ERR_INVALID_URL'\n// eslint-disable-next-line func-names\n].forEach(code => {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = (error, code, config, request, response, customProps) => {\n const axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n }, prop => {\n return prop !== 'isAxiosError';\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.cause = error;\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nexport default AxiosError;\n", "// eslint-disable-next-line strict\nexport default null;\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\n// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored\nimport PlatformFormData from '../platform/node/classes/FormData.js';\n\n/**\n * Determines if the given thing is a array or js object.\n *\n * @param {string} thing - The object or array to be visited.\n *\n * @returns {boolean}\n */\nfunction isVisitable(thing) {\n return utils.isPlainObject(thing) || utils.isArray(thing);\n}\n\n/**\n * It removes the brackets from the end of a string\n *\n * @param {string} key - The key of the parameter.\n *\n * @returns {string} the key without the brackets.\n */\nfunction removeBrackets(key) {\n return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;\n}\n\n/**\n * It takes a path, a key, and a boolean, and returns a string\n *\n * @param {string} path - The path to the current key.\n * @param {string} key - The key of the current object being iterated over.\n * @param {string} dots - If true, the key will be rendered with dots instead of brackets.\n *\n * @returns {string} The path to the current key.\n */\nfunction renderKey(path, key, dots) {\n if (!path) return key;\n return path.concat(key).map(function each(token, i) {\n // eslint-disable-next-line no-param-reassign\n token = removeBrackets(token);\n return !dots && i ? '[' + token + ']' : token;\n }).join(dots ? '.' : '');\n}\n\n/**\n * If the array is an array and none of its elements are visitable, then it's a flat array.\n *\n * @param {Array} arr - The array to check\n *\n * @returns {boolean}\n */\nfunction isFlatArray(arr) {\n return utils.isArray(arr) && !arr.some(isVisitable);\n}\n\nconst predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {\n return /^is[A-Z]/.test(prop);\n});\n\n/**\n * Convert a data object to FormData\n *\n * @param {Object} obj\n * @param {?Object} [formData]\n * @param {?Object} [options]\n * @param {Function} [options.visitor]\n * @param {Boolean} [options.metaTokens = true]\n * @param {Boolean} [options.dots = false]\n * @param {?Boolean} [options.indexes = false]\n *\n * @returns {Object}\n **/\n\n/**\n * It converts an object into a FormData object\n *\n * @param {Object} obj - The object to convert to form data.\n * @param {string} formData - The FormData object to append to.\n * @param {Object} options\n *\n * @returns\n */\nfunction toFormData(obj, formData, options) {\n if (!utils.isObject(obj)) {\n throw new TypeError('target must be an object');\n }\n\n // eslint-disable-next-line no-param-reassign\n formData = formData || new (PlatformFormData || FormData)();\n\n // eslint-disable-next-line no-param-reassign\n options = utils.toFlatObject(options, {\n metaTokens: true,\n dots: false,\n indexes: false\n }, false, function defined(option, source) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n return !utils.isUndefined(source[option]);\n });\n\n const metaTokens = options.metaTokens;\n // eslint-disable-next-line no-use-before-define\n const visitor = options.visitor || defaultVisitor;\n const dots = options.dots;\n const indexes = options.indexes;\n const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;\n const useBlob = _Blob && utils.isSpecCompliantForm(formData);\n\n if (!utils.isFunction(visitor)) {\n throw new TypeError('visitor must be a function');\n }\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (!useBlob && utils.isBlob(value)) {\n throw new AxiosError('Blob is not supported. Use a Buffer instead.');\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n /**\n * Default visitor.\n *\n * @param {*} value\n * @param {String|Number} key\n * @param {Array} path\n * @this {FormData}\n *\n * @returns {boolean} return true to visit the each prop of the value recursively\n */\n function defaultVisitor(value, key, path) {\n let arr = value;\n\n if (value && !path && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n key = metaTokens ? key : key.slice(0, -2);\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (\n (utils.isArray(value) && isFlatArray(value)) ||\n ((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value))\n )) {\n // eslint-disable-next-line no-param-reassign\n key = removeBrackets(key);\n\n arr.forEach(function each(el, index) {\n !(utils.isUndefined(el) || el === null) && formData.append(\n // eslint-disable-next-line no-nested-ternary\n indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),\n convertValue(el)\n );\n });\n return false;\n }\n }\n\n if (isVisitable(value)) {\n return true;\n }\n\n formData.append(renderKey(path, key, dots), convertValue(value));\n\n return false;\n }\n\n const stack = [];\n\n const exposedHelpers = Object.assign(predicates, {\n defaultVisitor,\n convertValue,\n isVisitable\n });\n\n function build(value, path) {\n if (utils.isUndefined(value)) return;\n\n if (stack.indexOf(value) !== -1) {\n throw Error('Circular reference detected in ' + path.join('.'));\n }\n\n stack.push(value);\n\n utils.forEach(value, function each(el, key) {\n const result = !(utils.isUndefined(el) || el === null) && visitor.call(\n formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers\n );\n\n if (result === true) {\n build(el, path ? path.concat(key) : [key]);\n }\n });\n\n stack.pop();\n }\n\n if (!utils.isObject(obj)) {\n throw new TypeError('data must be an object');\n }\n\n build(obj);\n\n return formData;\n}\n\nexport default toFormData;\n", "'use strict';\n\nimport toFormData from './toFormData.js';\n\n/**\n * It encodes a string by replacing all characters that are not in the unreserved set with\n * their percent-encoded equivalents\n *\n * @param {string} str - The string to encode.\n *\n * @returns {string} The encoded string.\n */\nfunction encode(str) {\n const charMap = {\n '!': '%21',\n \"'\": '%27',\n '(': '%28',\n ')': '%29',\n '~': '%7E',\n '%20': '+',\n '%00': '\\x00'\n };\n return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {\n return charMap[match];\n });\n}\n\n/**\n * It takes a params object and converts it to a FormData object\n *\n * @param {Object} params - The parameters to be converted to a FormData object.\n * @param {Object} options - The options object passed to the Axios constructor.\n *\n * @returns {void}\n */\nfunction AxiosURLSearchParams(params, options) {\n this._pairs = [];\n\n params && toFormData(params, this, options);\n}\n\nconst prototype = AxiosURLSearchParams.prototype;\n\nprototype.append = function append(name, value) {\n this._pairs.push([name, value]);\n};\n\nprototype.toString = function toString(encoder) {\n const _encode = encoder ? function(value) {\n return encoder.call(this, value, encode);\n } : encode;\n\n return this._pairs.map(function each(pair) {\n return _encode(pair[0]) + '=' + _encode(pair[1]);\n }, '').join('&');\n};\n\nexport default AxiosURLSearchParams;\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';\n\n/**\n * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their\n * URI encoded counterparts\n *\n * @param {string} val The value to be encoded.\n *\n * @returns {string} The encoded value.\n */\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @param {?object} options\n *\n * @returns {string} The formatted url\n */\nexport default function buildURL(url, params, options) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n \n const _encode = options && options.encode || encode;\n\n const serializeFn = options && options.serialize;\n\n let serializedParams;\n\n if (serializeFn) {\n serializedParams = serializeFn(params, options);\n } else {\n serializedParams = utils.isURLSearchParams(params) ?\n params.toString() :\n new AxiosURLSearchParams(params, options).toString(_encode);\n }\n\n if (serializedParams) {\n const hashmarkIndex = url.indexOf(\"#\");\n\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n}\n", "'use strict';\n\nimport utils from './../utils.js';\n\nclass InterceptorManager {\n constructor() {\n this.handlers = [];\n }\n\n /**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\n use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled,\n rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n }\n\n /**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n *\n * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise\n */\n eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n }\n\n /**\n * Clear all interceptors from the stack\n *\n * @returns {void}\n */\n clear() {\n if (this.handlers) {\n this.handlers = [];\n }\n }\n\n /**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n *\n * @returns {void}\n */\n forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n }\n}\n\nexport default InterceptorManager;\n", "'use strict';\n\nexport default {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n", "'use strict';\n\nimport AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';\nexport default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;\n", "'use strict';\n\nexport default typeof FormData !== 'undefined' ? FormData : null;\n", "'use strict'\n\nexport default typeof Blob !== 'undefined' ? Blob : null\n", "import URLSearchParams from './classes/URLSearchParams.js'\nimport FormData from './classes/FormData.js'\nimport Blob from './classes/Blob.js'\n\nexport default {\n isBrowser: true,\n classes: {\n URLSearchParams,\n FormData,\n Blob\n },\n protocols: ['http', 'https', 'file', 'blob', 'url', 'data']\n};\n", "const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n *\n * @returns {boolean}\n */\nconst hasStandardBrowserEnv = (\n (product) => {\n return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0\n })(typeof navigator !== 'undefined' && navigator.product);\n\n/**\n * Determine if we're running in a standard browser webWorker environment\n *\n * Although the `isStandardBrowserEnv` method indicates that\n * `allows axios to run in a web worker`, the WebWorker will still be\n * filtered out due to its judgment standard\n * `typeof window !== 'undefined' && typeof document !== 'undefined'`.\n * This leads to a problem when axios post `FormData` in webWorker\n */\nconst hasStandardBrowserWebWorkerEnv = (() => {\n return (\n typeof WorkerGlobalScope !== 'undefined' &&\n // eslint-disable-next-line no-undef\n self instanceof WorkerGlobalScope &&\n typeof self.importScripts === 'function'\n );\n})();\n\nconst origin = hasBrowserEnv && window.location.href || 'http://localhost';\n\nexport {\n hasBrowserEnv,\n hasStandardBrowserWebWorkerEnv,\n hasStandardBrowserEnv,\n origin\n}\n", "import platform from './node/index.js';\nimport * as utils from './common/utils.js';\n\nexport default {\n ...utils,\n ...platform\n}\n", "'use strict';\n\nimport utils from '../utils.js';\nimport toFormData from './toFormData.js';\nimport platform from '../platform/index.js';\n\nexport default function toURLEncodedForm(data, options) {\n return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({\n visitor: function(value, key, path, helpers) {\n if (platform.isNode && utils.isBuffer(value)) {\n this.append(key, value.toString('base64'));\n return false;\n }\n\n return helpers.defaultVisitor.apply(this, arguments);\n }\n }, options));\n}\n", "'use strict';\n\nimport utils from '../utils.js';\n\n/**\n * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']\n *\n * @param {string} name - The name of the property to get.\n *\n * @returns An array of strings.\n */\nfunction parsePropPath(name) {\n // foo[x][y][z]\n // foo.x.y.z\n // foo-x-y-z\n // foo x y z\n return utils.matchAll(/\\w+|\\[(\\w*)]/g, name).map(match => {\n return match[0] === '[]' ? '' : match[1] || match[0];\n });\n}\n\n/**\n * Convert an array to an object.\n *\n * @param {Array} arr - The array to convert to an object.\n *\n * @returns An object with the same keys and values as the array.\n */\nfunction arrayToObject(arr) {\n const obj = {};\n const keys = Object.keys(arr);\n let i;\n const len = keys.length;\n let key;\n for (i = 0; i < len; i++) {\n key = keys[i];\n obj[key] = arr[key];\n }\n return obj;\n}\n\n/**\n * It takes a FormData object and returns a JavaScript object\n *\n * @param {string} formData The FormData object to convert to JSON.\n *\n * @returns {Object | null} The converted object.\n */\nfunction formDataToJSON(formData) {\n function buildPath(path, value, target, index) {\n let name = path[index++];\n\n if (name === '__proto__') return true;\n\n const isNumericKey = Number.isFinite(+name);\n const isLast = index >= path.length;\n name = !name && utils.isArray(target) ? target.length : name;\n\n if (isLast) {\n if (utils.hasOwnProp(target, name)) {\n target[name] = [target[name], value];\n } else {\n target[name] = value;\n }\n\n return !isNumericKey;\n }\n\n if (!target[name] || !utils.isObject(target[name])) {\n target[name] = [];\n }\n\n const result = buildPath(path, value, target[name], index);\n\n if (result && utils.isArray(target[name])) {\n target[name] = arrayToObject(target[name]);\n }\n\n return !isNumericKey;\n }\n\n if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {\n const obj = {};\n\n utils.forEachEntry(formData, (name, value) => {\n buildPath(parsePropPath(name), value, obj, 0);\n });\n\n return obj;\n }\n\n return null;\n}\n\nexport default formDataToJSON;\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosError from '../core/AxiosError.js';\nimport transitionalDefaults from './transitional.js';\nimport toFormData from '../helpers/toFormData.js';\nimport toURLEncodedForm from '../helpers/toURLEncodedForm.js';\nimport platform from '../platform/index.js';\nimport formDataToJSON from '../helpers/formDataToJSON.js';\n\n/**\n * It takes a string, tries to parse it, and if it fails, it returns the stringified version\n * of the input\n *\n * @param {any} rawValue - The value to be stringified.\n * @param {Function} parser - A function that parses a string into a JavaScript object.\n * @param {Function} encoder - A function that takes a value and returns a string.\n *\n * @returns {string} A stringified version of the rawValue.\n */\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nconst defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: ['xhr', 'http', 'fetch'],\n\n transformRequest: [function transformRequest(data, headers) {\n const contentType = headers.getContentType() || '';\n const hasJSONContentType = contentType.indexOf('application/json') > -1;\n const isObjectPayload = utils.isObject(data);\n\n if (isObjectPayload && utils.isHTMLForm(data)) {\n data = new FormData(data);\n }\n\n const isFormData = utils.isFormData(data);\n\n if (isFormData) {\n return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;\n }\n\n if (utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data) ||\n utils.isReadableStream(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);\n return data.toString();\n }\n\n let isFileList;\n\n if (isObjectPayload) {\n if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {\n return toURLEncodedForm(data, this.formSerializer).toString();\n }\n\n if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {\n const _FormData = this.env && this.env.FormData;\n\n return toFormData(\n isFileList ? {'files[]': data} : data,\n _FormData && new _FormData(),\n this.formSerializer\n );\n }\n }\n\n if (isObjectPayload || hasJSONContentType ) {\n headers.setContentType('application/json', false);\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n const transitional = this.transitional || defaults.transitional;\n const forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n const JSONRequested = this.responseType === 'json';\n\n if (utils.isResponse(data) || utils.isReadableStream(data)) {\n return data;\n }\n\n if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {\n const silentJSONParsing = transitional && transitional.silentJSONParsing;\n const strictJSONParsing = !silentJSONParsing && JSONRequested;\n\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: platform.classes.FormData,\n Blob: platform.classes.Blob\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': undefined\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {\n defaults.headers[method] = {};\n});\n\nexport default defaults;\n", "'use strict';\n\nimport utils from './../utils.js';\n\n// RawAxiosHeaders whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nconst ignoreDuplicateOf = utils.toObjectSet([\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n]);\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} rawHeaders Headers needing to be parsed\n *\n * @returns {Object} Headers parsed into an object\n */\nexport default rawHeaders => {\n const parsed = {};\n let key;\n let val;\n let i;\n\n rawHeaders && rawHeaders.split('\\n').forEach(function parser(line) {\n i = line.indexOf(':');\n key = line.substring(0, i).trim().toLowerCase();\n val = line.substring(i + 1).trim();\n\n if (!key || (parsed[key] && ignoreDuplicateOf[key])) {\n return;\n }\n\n if (key === 'set-cookie') {\n if (parsed[key]) {\n parsed[key].push(val);\n } else {\n parsed[key] = [val];\n }\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n};\n", "'use strict';\n\nimport utils from '../utils.js';\nimport parseHeaders from '../helpers/parseHeaders.js';\n\nconst $internals = Symbol('internals');\n\nfunction normalizeHeader(header) {\n return header && String(header).trim().toLowerCase();\n}\n\nfunction normalizeValue(value) {\n if (value === false || value == null) {\n return value;\n }\n\n return utils.isArray(value) ? value.map(normalizeValue) : String(value);\n}\n\nfunction parseTokens(str) {\n const tokens = Object.create(null);\n const tokensRE = /([^\\s,;=]+)\\s*(?:=\\s*([^,;]+))?/g;\n let match;\n\n while ((match = tokensRE.exec(str))) {\n tokens[match[1]] = match[2];\n }\n\n return tokens;\n}\n\nconst isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());\n\nfunction matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {\n if (utils.isFunction(filter)) {\n return filter.call(this, value, header);\n }\n\n if (isHeaderNameFilter) {\n value = header;\n }\n\n if (!utils.isString(value)) return;\n\n if (utils.isString(filter)) {\n return value.indexOf(filter) !== -1;\n }\n\n if (utils.isRegExp(filter)) {\n return filter.test(value);\n }\n}\n\nfunction formatHeader(header) {\n return header.trim()\n .toLowerCase().replace(/([a-z\\d])(\\w*)/g, (w, char, str) => {\n return char.toUpperCase() + str;\n });\n}\n\nfunction buildAccessors(obj, header) {\n const accessorName = utils.toCamelCase(' ' + header);\n\n ['get', 'set', 'has'].forEach(methodName => {\n Object.defineProperty(obj, methodName + accessorName, {\n value: function(arg1, arg2, arg3) {\n return this[methodName].call(this, header, arg1, arg2, arg3);\n },\n configurable: true\n });\n });\n}\n\nclass AxiosHeaders {\n constructor(headers) {\n headers && this.set(headers);\n }\n\n set(header, valueOrRewrite, rewrite) {\n const self = this;\n\n function setHeader(_value, _header, _rewrite) {\n const lHeader = normalizeHeader(_header);\n\n if (!lHeader) {\n throw new Error('header name must be a non-empty string');\n }\n\n const key = utils.findKey(self, lHeader);\n\n if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {\n self[key || _header] = normalizeValue(_value);\n }\n }\n\n const setHeaders = (headers, _rewrite) =>\n utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));\n\n if (utils.isPlainObject(header) || header instanceof this.constructor) {\n setHeaders(header, valueOrRewrite)\n } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {\n setHeaders(parseHeaders(header), valueOrRewrite);\n } else if (utils.isHeaders(header)) {\n for (const [key, value] of header.entries()) {\n setHeader(value, key, rewrite);\n }\n } else {\n header != null && setHeader(valueOrRewrite, header, rewrite);\n }\n\n return this;\n }\n\n get(header, parser) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n if (key) {\n const value = this[key];\n\n if (!parser) {\n return value;\n }\n\n if (parser === true) {\n return parseTokens(value);\n }\n\n if (utils.isFunction(parser)) {\n return parser.call(this, value, key);\n }\n\n if (utils.isRegExp(parser)) {\n return parser.exec(value);\n }\n\n throw new TypeError('parser must be boolean|regexp|function');\n }\n }\n }\n\n has(header, matcher) {\n header = normalizeHeader(header);\n\n if (header) {\n const key = utils.findKey(this, header);\n\n return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));\n }\n\n return false;\n }\n\n delete(header, matcher) {\n const self = this;\n let deleted = false;\n\n function deleteHeader(_header) {\n _header = normalizeHeader(_header);\n\n if (_header) {\n const key = utils.findKey(self, _header);\n\n if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {\n delete self[key];\n\n deleted = true;\n }\n }\n }\n\n if (utils.isArray(header)) {\n header.forEach(deleteHeader);\n } else {\n deleteHeader(header);\n }\n\n return deleted;\n }\n\n clear(matcher) {\n const keys = Object.keys(this);\n let i = keys.length;\n let deleted = false;\n\n while (i--) {\n const key = keys[i];\n if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {\n delete this[key];\n deleted = true;\n }\n }\n\n return deleted;\n }\n\n normalize(format) {\n const self = this;\n const headers = {};\n\n utils.forEach(this, (value, header) => {\n const key = utils.findKey(headers, header);\n\n if (key) {\n self[key] = normalizeValue(value);\n delete self[header];\n return;\n }\n\n const normalized = format ? formatHeader(header) : String(header).trim();\n\n if (normalized !== header) {\n delete self[header];\n }\n\n self[normalized] = normalizeValue(value);\n\n headers[normalized] = true;\n });\n\n return this;\n }\n\n concat(...targets) {\n return this.constructor.concat(this, ...targets);\n }\n\n toJSON(asStrings) {\n const obj = Object.create(null);\n\n utils.forEach(this, (value, header) => {\n value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);\n });\n\n return obj;\n }\n\n [Symbol.iterator]() {\n return Object.entries(this.toJSON())[Symbol.iterator]();\n }\n\n toString() {\n return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\\n');\n }\n\n get [Symbol.toStringTag]() {\n return 'AxiosHeaders';\n }\n\n static from(thing) {\n return thing instanceof this ? thing : new this(thing);\n }\n\n static concat(first, ...targets) {\n const computed = new this(first);\n\n targets.forEach((target) => computed.set(target));\n\n return computed;\n }\n\n static accessor(header) {\n const internals = this[$internals] = (this[$internals] = {\n accessors: {}\n });\n\n const accessors = internals.accessors;\n const prototype = this.prototype;\n\n function defineAccessor(_header) {\n const lHeader = normalizeHeader(_header);\n\n if (!accessors[lHeader]) {\n buildAccessors(prototype, _header);\n accessors[lHeader] = true;\n }\n }\n\n utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);\n\n return this;\n }\n}\n\nAxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);\n\n// reserved names hotfix\nutils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {\n let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`\n return {\n get: () => value,\n set(headerValue) {\n this[mapped] = headerValue;\n }\n }\n});\n\nutils.freezeMethods(AxiosHeaders);\n\nexport default AxiosHeaders;\n", "'use strict';\n\nimport utils from './../utils.js';\nimport defaults from '../defaults/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Array|Function} fns A single function or Array of functions\n * @param {?Object} response The response object\n *\n * @returns {*} The resulting transformed data\n */\nexport default function transformData(fns, response) {\n const config = this || defaults;\n const context = response || config;\n const headers = AxiosHeaders.from(context.headers);\n let data = context.data;\n\n utils.forEach(fns, function transform(fn) {\n data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);\n });\n\n headers.normalize();\n\n return data;\n}\n", "'use strict';\n\nexport default function isCancel(value) {\n return !!(value && value.__CANCEL__);\n}\n", "'use strict';\n\nimport AxiosError from '../core/AxiosError.js';\nimport utils from '../utils.js';\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @param {string=} message The message.\n * @param {Object=} config The config.\n * @param {Object=} request The request.\n *\n * @returns {CanceledError} The created error.\n */\nfunction CanceledError(message, config, request) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nexport default CanceledError;\n", "'use strict';\n\nimport AxiosError from './AxiosError.js';\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n *\n * @returns {object} The response.\n */\nexport default function settle(resolve, reject, response) {\n const validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n}\n", "'use strict';\n\nexport default function parseProtocol(url) {\n const match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n}\n", "'use strict';\n\n/**\n * Calculate data maxRate\n * @param {Number} [samplesCount= 10]\n * @param {Number} [min= 1000]\n * @returns {Function}\n */\nfunction speedometer(samplesCount, min) {\n samplesCount = samplesCount || 10;\n const bytes = new Array(samplesCount);\n const timestamps = new Array(samplesCount);\n let head = 0;\n let tail = 0;\n let firstSampleTS;\n\n min = min !== undefined ? min : 1000;\n\n return function push(chunkLength) {\n const now = Date.now();\n\n const startedAt = timestamps[tail];\n\n if (!firstSampleTS) {\n firstSampleTS = now;\n }\n\n bytes[head] = chunkLength;\n timestamps[head] = now;\n\n let i = tail;\n let bytesCount = 0;\n\n while (i !== head) {\n bytesCount += bytes[i++];\n i = i % samplesCount;\n }\n\n head = (head + 1) % samplesCount;\n\n if (head === tail) {\n tail = (tail + 1) % samplesCount;\n }\n\n if (now - firstSampleTS < min) {\n return;\n }\n\n const passed = startedAt && now - startedAt;\n\n return passed ? Math.round(bytesCount * 1000 / passed) : undefined;\n };\n}\n\nexport default speedometer;\n", "'use strict';\n\n/**\n * Throttle decorator\n * @param {Function} fn\n * @param {Number} freq\n * @return {Function}\n */\nfunction throttle(fn, freq) {\n let timestamp = 0;\n const threshold = 1000 / freq;\n let timer = null;\n return function throttled() {\n const force = this === true;\n\n const now = Date.now();\n if (force || now - timestamp > threshold) {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n timestamp = now;\n return fn.apply(null, arguments);\n }\n if (!timer) {\n timer = setTimeout(() => {\n timer = null;\n timestamp = Date.now();\n return fn.apply(null, arguments);\n }, threshold - (now - timestamp));\n }\n };\n}\n\nexport default throttle;\n", "import speedometer from \"./speedometer.js\";\nimport throttle from \"./throttle.js\";\n\nexport default (listener, isDownloadStream, freq = 3) => {\n let bytesNotified = 0;\n const _speedometer = speedometer(50, 250);\n\n return throttle(e => {\n const loaded = e.loaded;\n const total = e.lengthComputable ? e.total : undefined;\n const progressBytes = loaded - bytesNotified;\n const rate = _speedometer(progressBytes);\n const inRange = loaded <= total;\n\n bytesNotified = loaded;\n\n const data = {\n loaded,\n total,\n progress: total ? (loaded / total) : undefined,\n bytes: progressBytes,\n rate: rate ? rate : undefined,\n estimated: rate && total && inRange ? (total - loaded) / rate : undefined,\n event: e,\n lengthComputable: total != null\n };\n\n data[isDownloadStream ? 'download' : 'upload'] = true;\n\n listener(data);\n }, freq);\n}\n", "'use strict';\n\nimport utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n// Standard browser envs have full support of the APIs needed to test\n// whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n const msie = /(msie|trident)/i.test(navigator.userAgent);\n const urlParsingNode = document.createElement('a');\n let originURL;\n\n /**\n * Parse a URL to discover its components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n let href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })();\n", "import utils from './../utils.js';\nimport platform from '../platform/index.js';\n\nexport default platform.hasStandardBrowserEnv ?\n\n // Standard browser envs support document.cookie\n {\n write(name, value, expires, path, domain, secure) {\n const cookie = [name + '=' + encodeURIComponent(value)];\n\n utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());\n\n utils.isString(path) && cookie.push('path=' + path);\n\n utils.isString(domain) && cookie.push('domain=' + domain);\n\n secure === true && cookie.push('secure');\n\n document.cookie = cookie.join('; ');\n },\n\n read(name) {\n const match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n }\n\n :\n\n // Non-standard browser env (web workers, react-native) lack needed support.\n {\n write() {},\n read() {\n return null;\n },\n remove() {}\n };\n\n", "'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n *\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nexport default function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n}\n", "'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n *\n * @returns {string} The combined URL\n */\nexport default function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/?\\/$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n}\n", "'use strict';\n\nimport isAbsoluteURL from '../helpers/isAbsoluteURL.js';\nimport combineURLs from '../helpers/combineURLs.js';\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n *\n * @returns {string} The combined full path\n */\nexport default function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n}\n", "'use strict';\n\nimport utils from '../utils.js';\nimport AxiosHeaders from \"./AxiosHeaders.js\";\n\nconst headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n *\n * @returns {Object} New object resulting from merging config2 to config1\n */\nexport default function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n const config = {};\n\n function getMergedValue(target, source, caseless) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge.call({caseless}, target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(a, b, caseless) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(a, b, caseless);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a, caseless);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(a, b) {\n if (!utils.isUndefined(b)) {\n return getMergedValue(undefined, b);\n } else if (!utils.isUndefined(a)) {\n return getMergedValue(undefined, a);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(a, b, prop) {\n if (prop in config2) {\n return getMergedValue(a, b);\n } else if (prop in config1) {\n return getMergedValue(undefined, a);\n }\n }\n\n const mergeMap = {\n url: valueFromConfig2,\n method: valueFromConfig2,\n data: valueFromConfig2,\n baseURL: defaultToConfig2,\n transformRequest: defaultToConfig2,\n transformResponse: defaultToConfig2,\n paramsSerializer: defaultToConfig2,\n timeout: defaultToConfig2,\n timeoutMessage: defaultToConfig2,\n withCredentials: defaultToConfig2,\n withXSRFToken: defaultToConfig2,\n adapter: defaultToConfig2,\n responseType: defaultToConfig2,\n xsrfCookieName: defaultToConfig2,\n xsrfHeaderName: defaultToConfig2,\n onUploadProgress: defaultToConfig2,\n onDownloadProgress: defaultToConfig2,\n decompress: defaultToConfig2,\n maxContentLength: defaultToConfig2,\n maxBodyLength: defaultToConfig2,\n beforeRedirect: defaultToConfig2,\n transport: defaultToConfig2,\n httpAgent: defaultToConfig2,\n httpsAgent: defaultToConfig2,\n cancelToken: defaultToConfig2,\n socketPath: defaultToConfig2,\n responseEncoding: defaultToConfig2,\n validateStatus: mergeDirectKeys,\n headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)\n };\n\n utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {\n const merge = mergeMap[prop] || mergeDeepProperties;\n const configValue = merge(config1[prop], config2[prop], prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n}\n", "import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport isURLSameOrigin from \"./isURLSameOrigin.js\";\nimport cookies from \"./cookies.js\";\nimport buildFullPath from \"../core/buildFullPath.js\";\nimport mergeConfig from \"../core/mergeConfig.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport buildURL from \"./buildURL.js\";\n\nexport default (config) => {\n const newConfig = mergeConfig({}, config);\n\n let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;\n\n newConfig.headers = headers = AxiosHeaders.from(headers);\n\n newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);\n\n // HTTP basic authentication\n if (auth) {\n headers.set('Authorization', 'Basic ' +\n btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))\n );\n }\n\n let contentType;\n\n if (utils.isFormData(data)) {\n if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {\n headers.setContentType(undefined); // Let the browser set it\n } else if ((contentType = headers.getContentType()) !== false) {\n // fix semicolon duplication issue for ReactNative FormData implementation\n const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];\n headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));\n }\n }\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n\n if (platform.hasStandardBrowserEnv) {\n withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));\n\n if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {\n // Add xsrf header\n const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);\n\n if (xsrfValue) {\n headers.set(xsrfHeaderName, xsrfValue);\n }\n }\n }\n\n return newConfig;\n}\n\n", "import utils from './../utils.js';\nimport settle from './../core/settle.js';\nimport transitionalDefaults from '../defaults/transitional.js';\nimport AxiosError from '../core/AxiosError.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport parseProtocol from '../helpers/parseProtocol.js';\nimport platform from '../platform/index.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport progressEventReducer from '../helpers/progressEventReducer.js';\nimport resolveConfig from \"../helpers/resolveConfig.js\";\n\nconst isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';\n\nexport default isXHRAdapterSupported && function (config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n const _config = resolveConfig(config);\n let requestData = _config.data;\n const requestHeaders = AxiosHeaders.from(_config.headers).normalize();\n let {responseType} = _config;\n let onCanceled;\n function done() {\n if (_config.cancelToken) {\n _config.cancelToken.unsubscribe(onCanceled);\n }\n\n if (_config.signal) {\n _config.signal.removeEventListener('abort', onCanceled);\n }\n }\n\n let request = new XMLHttpRequest();\n\n request.open(_config.method.toUpperCase(), _config.url, true);\n\n // Set the request timeout in MS\n request.timeout = _config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n const responseHeaders = AxiosHeaders.from(\n 'getAllResponseHeaders' in request && request.getAllResponseHeaders()\n );\n const responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n const response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config,\n request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, _config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, _config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';\n const transitional = _config.transitional || transitionalDefaults;\n if (_config.timeoutErrorMessage) {\n timeoutErrorMessage = _config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n _config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Remove Content-Type if data is undefined\n requestData === undefined && requestHeaders.setContentType(null);\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {\n request.setRequestHeader(key, val);\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(_config.withCredentials)) {\n request.withCredentials = !!_config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = _config.responseType;\n }\n\n // Handle progress if needed\n if (typeof _config.onDownloadProgress === 'function') {\n request.addEventListener('progress', progressEventReducer(_config.onDownloadProgress, true));\n }\n\n // Not all browsers support upload events\n if (typeof _config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', progressEventReducer(_config.onUploadProgress));\n }\n\n if (_config.cancelToken || _config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = cancel => {\n if (!request) {\n return;\n }\n reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);\n request.abort();\n request = null;\n };\n\n _config.cancelToken && _config.cancelToken.subscribe(onCanceled);\n if (_config.signal) {\n _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n const protocol = parseProtocol(_config.url);\n\n if (protocol && platform.protocols.indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData || null);\n });\n}\n", "import CanceledError from \"../cancel/CanceledError.js\";\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst composeSignals = (signals, timeout) => {\n let controller = new AbortController();\n\n let aborted;\n\n const onabort = function (cancel) {\n if (!aborted) {\n aborted = true;\n unsubscribe();\n const err = cancel instanceof Error ? cancel : this.reason;\n controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));\n }\n }\n\n let timer = timeout && setTimeout(() => {\n onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT))\n }, timeout)\n\n const unsubscribe = () => {\n if (signals) {\n timer && clearTimeout(timer);\n timer = null;\n signals.forEach(signal => {\n signal &&\n (signal.removeEventListener ? signal.removeEventListener('abort', onabort) : signal.unsubscribe(onabort));\n });\n signals = null;\n }\n }\n\n signals.forEach((signal) => signal && signal.addEventListener && signal.addEventListener('abort', onabort));\n\n const {signal} = controller;\n\n signal.unsubscribe = unsubscribe;\n\n return [signal, () => {\n timer && clearTimeout(timer);\n timer = null;\n }];\n}\n\nexport default composeSignals;\n", "\nexport const streamChunk = function* (chunk, chunkSize) {\n let len = chunk.byteLength;\n\n if (!chunkSize || len < chunkSize) {\n yield chunk;\n return;\n }\n\n let pos = 0;\n let end;\n\n while (pos < len) {\n end = pos + chunkSize;\n yield chunk.slice(pos, end);\n pos = end;\n }\n}\n\nconst encoder = new TextEncoder();\n\nexport const readBytes = async function* (iterable, chunkSize) {\n for await (const chunk of iterable) {\n yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encoder.encode(String(chunk))), chunkSize);\n }\n}\n\nexport const trackStream = (stream, chunkSize, onProgress, onFinish) => {\n const iterator = readBytes(stream, chunkSize);\n\n let bytes = 0;\n\n return new ReadableStream({\n type: 'bytes',\n\n async pull(controller) {\n const {done, value} = await iterator.next();\n\n if (done) {\n controller.close();\n onFinish();\n return;\n }\n\n let len = value.byteLength;\n onProgress && onProgress(bytes += len);\n controller.enqueue(new Uint8Array(value));\n },\n cancel(reason) {\n onFinish(reason);\n return iterator.return();\n }\n }, {\n highWaterMark: 2\n })\n}\n", "import platform from \"../platform/index.js\";\nimport utils from \"../utils.js\";\nimport AxiosError from \"../core/AxiosError.js\";\nimport composeSignals from \"../helpers/composeSignals.js\";\nimport {trackStream} from \"../helpers/trackStream.js\";\nimport AxiosHeaders from \"../core/AxiosHeaders.js\";\nimport progressEventReducer from \"../helpers/progressEventReducer.js\";\nimport resolveConfig from \"../helpers/resolveConfig.js\";\nimport settle from \"../core/settle.js\";\n\nconst fetchProgressDecorator = (total, fn) => {\n const lengthComputable = total != null;\n return (loaded) => setTimeout(() => fn({\n lengthComputable,\n total,\n loaded\n }));\n}\n\nconst isFetchSupported = typeof fetch !== 'undefined';\nconst isReadableStreamSupported = isFetchSupported && typeof ReadableStream !== 'undefined';\n\nconst supportsRequestStream = isReadableStreamSupported && (() => {\n let duplexAccessed = false;\n\n const hasContentType = new Request(platform.origin, {\n body: new ReadableStream(),\n method: 'POST',\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n\n return duplexAccessed && !hasContentType;\n})();\n\nconst DEFAULT_CHUNK_SIZE = 64 * 1024;\n\nconst supportsResponseStream = isReadableStreamSupported && !!(()=> {\n try {\n return utils.isReadableStream(new Response('').body);\n } catch(err) {\n // return undefined\n }\n})();\n\nconst resolvers = {\n stream: supportsResponseStream && ((res) => res.body)\n};\n\nisFetchSupported && (((res) => {\n ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {\n !resolvers[type] && (resolvers[type] = utils.isFunction(res[type]) ? (res) => res[type]() :\n (_, config) => {\n throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);\n })\n });\n})(new Response));\n\nconst getBodyLength = async (body) => {\n if (body == null) {\n return 0;\n }\n\n if(utils.isBlob(body)) {\n return body.size;\n }\n\n if(utils.isSpecCompliantForm(body)) {\n return (await new Request(body).arrayBuffer()).byteLength;\n }\n\n if(utils.isArrayBufferView(body)) {\n return body.byteLength;\n }\n\n if(utils.isURLSearchParams(body)) {\n body = body + '';\n }\n\n if(utils.isString(body)) {\n return (await new TextEncoder().encode(body)).byteLength;\n }\n}\n\nconst resolveBodyLength = async (headers, body) => {\n const length = utils.toFiniteNumber(headers.getContentLength());\n\n return length == null ? getBodyLength(body) : length;\n}\n\nexport default isFetchSupported && (async (config) => {\n let {\n url,\n method,\n data,\n signal,\n cancelToken,\n timeout,\n onDownloadProgress,\n onUploadProgress,\n responseType,\n headers,\n withCredentials = 'same-origin',\n fetchOptions\n } = resolveConfig(config);\n\n responseType = responseType ? (responseType + '').toLowerCase() : 'text';\n\n let [composedSignal, stopTimeout] = (signal || cancelToken || timeout) ?\n composeSignals([signal, cancelToken], timeout) : [];\n\n let finished, request;\n\n const onFinish = () => {\n !finished && setTimeout(() => {\n composedSignal && composedSignal.unsubscribe();\n });\n\n finished = true;\n }\n\n let requestContentLength;\n\n try {\n if (\n onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&\n (requestContentLength = await resolveBodyLength(headers, data)) !== 0\n ) {\n let _request = new Request(url, {\n method: 'POST',\n body: data,\n duplex: \"half\"\n });\n\n let contentTypeHeader;\n\n if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {\n headers.setContentType(contentTypeHeader)\n }\n\n if (_request.body) {\n data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, fetchProgressDecorator(\n requestContentLength,\n progressEventReducer(onUploadProgress)\n ));\n }\n }\n\n if (!utils.isString(withCredentials)) {\n withCredentials = withCredentials ? 'cors' : 'omit';\n }\n\n request = new Request(url, {\n ...fetchOptions,\n signal: composedSignal,\n method: method.toUpperCase(),\n headers: headers.normalize().toJSON(),\n body: data,\n duplex: \"half\",\n withCredentials\n });\n\n let response = await fetch(request);\n\n const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');\n\n if (supportsResponseStream && (onDownloadProgress || isStreamResponse)) {\n const options = {};\n\n ['status', 'statusText', 'headers'].forEach(prop => {\n options[prop] = response[prop];\n });\n\n const responseContentLength = utils.toFiniteNumber(response.headers.get('content-length'));\n\n response = new Response(\n trackStream(response.body, DEFAULT_CHUNK_SIZE, onDownloadProgress && fetchProgressDecorator(\n responseContentLength,\n progressEventReducer(onDownloadProgress, true)\n ), isStreamResponse && onFinish),\n options\n );\n }\n\n responseType = responseType || 'text';\n\n let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](response, config);\n\n !isStreamResponse && onFinish();\n\n stopTimeout && stopTimeout();\n\n return await new Promise((resolve, reject) => {\n settle(resolve, reject, {\n data: responseData,\n headers: AxiosHeaders.from(response.headers),\n status: response.status,\n statusText: response.statusText,\n config,\n request\n })\n })\n } catch (err) {\n onFinish();\n\n if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {\n throw Object.assign(\n new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),\n {\n cause: err.cause || err\n }\n )\n }\n\n throw AxiosError.from(err, err && err.code, config, request);\n }\n});\n\n\n", "import utils from '../utils.js';\nimport httpAdapter from './http.js';\nimport xhrAdapter from './xhr.js';\nimport fetchAdapter from './fetch.js';\nimport AxiosError from \"../core/AxiosError.js\";\n\nconst knownAdapters = {\n http: httpAdapter,\n xhr: xhrAdapter,\n fetch: fetchAdapter\n}\n\nutils.forEach(knownAdapters, (fn, value) => {\n if (fn) {\n try {\n Object.defineProperty(fn, 'name', {value});\n } catch (e) {\n // eslint-disable-next-line no-empty\n }\n Object.defineProperty(fn, 'adapterName', {value});\n }\n});\n\nconst renderReason = (reason) => `- ${reason}`;\n\nconst isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;\n\nexport default {\n getAdapter: (adapters) => {\n adapters = utils.isArray(adapters) ? adapters : [adapters];\n\n const {length} = adapters;\n let nameOrAdapter;\n let adapter;\n\n const rejectedReasons = {};\n\n for (let i = 0; i < length; i++) {\n nameOrAdapter = adapters[i];\n let id;\n\n adapter = nameOrAdapter;\n\n if (!isResolvedHandle(nameOrAdapter)) {\n adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];\n\n if (adapter === undefined) {\n throw new AxiosError(`Unknown adapter '${id}'`);\n }\n }\n\n if (adapter) {\n break;\n }\n\n rejectedReasons[id || '#' + i] = adapter;\n }\n\n if (!adapter) {\n\n const reasons = Object.entries(rejectedReasons)\n .map(([id, state]) => `adapter ${id} ` +\n (state === false ? 'is not supported by the environment' : 'is not available in the build')\n );\n\n let s = length ?\n (reasons.length > 1 ? 'since :\\n' + reasons.map(renderReason).join('\\n') : ' ' + renderReason(reasons[0])) :\n 'as no adapter specified';\n\n throw new AxiosError(\n `There is no suitable adapter to dispatch the request ` + s,\n 'ERR_NOT_SUPPORT'\n );\n }\n\n return adapter;\n },\n adapters: knownAdapters\n}\n", "'use strict';\n\nimport transformData from './transformData.js';\nimport isCancel from '../cancel/isCancel.js';\nimport defaults from '../defaults/index.js';\nimport CanceledError from '../cancel/CanceledError.js';\nimport AxiosHeaders from '../core/AxiosHeaders.js';\nimport adapters from \"../adapters/adapters.js\";\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n *\n * @param {Object} config The config that is to be used for the request\n *\n * @returns {void}\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError(null, config);\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n *\n * @returns {Promise} The Promise to be fulfilled\n */\nexport default function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n config.headers = AxiosHeaders.from(config.headers);\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.transformRequest\n );\n\n if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {\n config.headers.setContentType('application/x-www-form-urlencoded', false);\n }\n\n const adapter = adapters.getAdapter(config.adapter || defaults.adapter);\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n config.transformResponse,\n response\n );\n\n response.headers = AxiosHeaders.from(response.headers);\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n config.transformResponse,\n reason.response\n );\n reason.response.headers = AxiosHeaders.from(reason.response.headers);\n }\n }\n\n return Promise.reject(reason);\n });\n}\n", "export const VERSION = \"1.7.0\";", "'use strict';\n\nimport {VERSION} from '../env/data.js';\nimport AxiosError from '../core/AxiosError.js';\n\nconst validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nconst deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n *\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n *\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return (value, opt, opts) => {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n *\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n *\n * @returns {object}\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n const keys = Object.keys(options);\n let i = keys.length;\n while (i-- > 0) {\n const opt = keys[i];\n const validator = schema[opt];\n if (validator) {\n const value = options[opt];\n const result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nexport default {\n assertOptions,\n validators\n};\n", "'use strict';\n\nimport utils from './../utils.js';\nimport buildURL from '../helpers/buildURL.js';\nimport InterceptorManager from './InterceptorManager.js';\nimport dispatchRequest from './dispatchRequest.js';\nimport mergeConfig from './mergeConfig.js';\nimport buildFullPath from './buildFullPath.js';\nimport validator from '../helpers/validator.js';\nimport AxiosHeaders from './AxiosHeaders.js';\n\nconst validators = validator.validators;\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n *\n * @return {Axios} A new instance of Axios\n */\nclass Axios {\n constructor(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n }\n\n /**\n * Dispatch a request\n *\n * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)\n * @param {?Object} config\n *\n * @returns {Promise} The Promise to be fulfilled\n */\n async request(configOrUrl, config) {\n try {\n return await this._request(configOrUrl, config);\n } catch (err) {\n if (err instanceof Error) {\n let dummy;\n\n Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());\n\n // slice off the Error: ... line\n const stack = dummy.stack ? dummy.stack.replace(/^.+\\n/, '') : '';\n try {\n if (!err.stack) {\n err.stack = stack;\n // match without the 2 top stack lines\n } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\\n.+\\n/, ''))) {\n err.stack += '\\n' + stack\n }\n } catch (e) {\n // ignore the case where \"stack\" is an un-writable property\n }\n }\n\n throw err;\n }\n }\n\n _request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n const {transitional, paramsSerializer, headers} = config;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n if (paramsSerializer != null) {\n if (utils.isFunction(paramsSerializer)) {\n config.paramsSerializer = {\n serialize: paramsSerializer\n }\n } else {\n validator.assertOptions(paramsSerializer, {\n encode: validators.function,\n serialize: validators.function\n }, true);\n }\n }\n\n // Set config.method\n config.method = (config.method || this.defaults.method || 'get').toLowerCase();\n\n // Flatten headers\n let contextHeaders = headers && utils.merge(\n headers.common,\n headers[config.method]\n );\n\n headers && utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n (method) => {\n delete headers[method];\n }\n );\n\n config.headers = AxiosHeaders.concat(contextHeaders, headers);\n\n // filter out skipped interceptors\n const requestInterceptorChain = [];\n let synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n const responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n let promise;\n let i = 0;\n let len;\n\n if (!synchronousRequestInterceptors) {\n const chain = [dispatchRequest.bind(this), undefined];\n chain.unshift.apply(chain, requestInterceptorChain);\n chain.push.apply(chain, responseInterceptorChain);\n len = chain.length;\n\n promise = Promise.resolve(config);\n\n while (i < len) {\n promise = promise.then(chain[i++], chain[i++]);\n }\n\n return promise;\n }\n\n len = requestInterceptorChain.length;\n\n let newConfig = config;\n\n i = 0;\n\n while (i < len) {\n const onFulfilled = requestInterceptorChain[i++];\n const onRejected = requestInterceptorChain[i++];\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected.call(this, error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest.call(this, newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n i = 0;\n len = responseInterceptorChain.length;\n\n while (i < len) {\n promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);\n }\n\n return promise;\n }\n\n getUri(config) {\n config = mergeConfig(this.defaults, config);\n const fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n }\n}\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url,\n data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nexport default Axios;\n", "'use strict';\n\nimport CanceledError from './CanceledError.js';\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @param {Function} executor The executor function.\n *\n * @returns {CancelToken}\n */\nclass CancelToken {\n constructor(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n let resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n const token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(cancel => {\n if (!token._listeners) return;\n\n let i = token._listeners.length;\n\n while (i-- > 0) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = onfulfilled => {\n let _resolve;\n // eslint-disable-next-line func-names\n const promise = new Promise(resolve => {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message, config, request) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message, config, request);\n resolvePromise(token.reason);\n });\n }\n\n /**\n * Throws a `CanceledError` if cancellation has been requested.\n */\n throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n }\n\n /**\n * Subscribe to the cancel signal\n */\n\n subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n }\n\n /**\n * Unsubscribe from the cancel signal\n */\n\n unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n const index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n }\n\n /**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\n static source() {\n let cancel;\n const token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token,\n cancel\n };\n }\n}\n\nexport default CancelToken;\n", "'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n *\n * @returns {Function}\n */\nexport default function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n}\n", "'use strict';\n\nimport utils from './../utils.js';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n *\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nexport default function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n}\n", "const HttpStatusCode = {\n Continue: 100,\n SwitchingProtocols: 101,\n Processing: 102,\n EarlyHints: 103,\n Ok: 200,\n Created: 201,\n Accepted: 202,\n NonAuthoritativeInformation: 203,\n NoContent: 204,\n ResetContent: 205,\n PartialContent: 206,\n MultiStatus: 207,\n AlreadyReported: 208,\n ImUsed: 226,\n MultipleChoices: 300,\n MovedPermanently: 301,\n Found: 302,\n SeeOther: 303,\n NotModified: 304,\n UseProxy: 305,\n Unused: 306,\n TemporaryRedirect: 307,\n PermanentRedirect: 308,\n BadRequest: 400,\n Unauthorized: 401,\n PaymentRequired: 402,\n Forbidden: 403,\n NotFound: 404,\n MethodNotAllowed: 405,\n NotAcceptable: 406,\n ProxyAuthenticationRequired: 407,\n RequestTimeout: 408,\n Conflict: 409,\n Gone: 410,\n LengthRequired: 411,\n PreconditionFailed: 412,\n PayloadTooLarge: 413,\n UriTooLong: 414,\n UnsupportedMediaType: 415,\n RangeNotSatisfiable: 416,\n ExpectationFailed: 417,\n ImATeapot: 418,\n MisdirectedRequest: 421,\n UnprocessableEntity: 422,\n Locked: 423,\n FailedDependency: 424,\n TooEarly: 425,\n UpgradeRequired: 426,\n PreconditionRequired: 428,\n TooManyRequests: 429,\n RequestHeaderFieldsTooLarge: 431,\n UnavailableForLegalReasons: 451,\n InternalServerError: 500,\n NotImplemented: 501,\n BadGateway: 502,\n ServiceUnavailable: 503,\n GatewayTimeout: 504,\n HttpVersionNotSupported: 505,\n VariantAlsoNegotiates: 506,\n InsufficientStorage: 507,\n LoopDetected: 508,\n NotExtended: 510,\n NetworkAuthenticationRequired: 511,\n};\n\nObject.entries(HttpStatusCode).forEach(([key, value]) => {\n HttpStatusCode[value] = key;\n});\n\nexport default HttpStatusCode;\n", "'use strict';\n\nimport utils from './utils.js';\nimport bind from './helpers/bind.js';\nimport Axios from './core/Axios.js';\nimport mergeConfig from './core/mergeConfig.js';\nimport defaults from './defaults/index.js';\nimport formDataToJSON from './helpers/formDataToJSON.js';\nimport CanceledError from './cancel/CanceledError.js';\nimport CancelToken from './cancel/CancelToken.js';\nimport isCancel from './cancel/isCancel.js';\nimport {VERSION} from './env/data.js';\nimport toFormData from './helpers/toFormData.js';\nimport AxiosError from './core/AxiosError.js';\nimport spread from './helpers/spread.js';\nimport isAxiosError from './helpers/isAxiosError.js';\nimport AxiosHeaders from \"./core/AxiosHeaders.js\";\nimport adapters from './adapters/adapters.js';\nimport HttpStatusCode from './helpers/HttpStatusCode.js';\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n *\n * @returns {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n const context = new Axios(defaultConfig);\n const instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});\n\n // Copy context to instance\n utils.extend(instance, context, null, {allOwnKeys: true});\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nconst axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = CanceledError;\naxios.CancelToken = CancelToken;\naxios.isCancel = isCancel;\naxios.VERSION = VERSION;\naxios.toFormData = toFormData;\n\n// Expose AxiosError class\naxios.AxiosError = AxiosError;\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\n\naxios.spread = spread;\n\n// Expose isAxiosError\naxios.isAxiosError = isAxiosError;\n\n// Expose mergeConfig\naxios.mergeConfig = mergeConfig;\n\naxios.AxiosHeaders = AxiosHeaders;\n\naxios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);\n\naxios.getAdapter = adapters.getAdapter;\n\naxios.HttpStatusCode = HttpStatusCode;\n\naxios.default = axios;\n\n// this module should only have a default export\nexport default axios\n", "import axios from './lib/axios.js';\n\n// This module is intended to unwrap Axios default export as named.\n// Keep top-level export same with static properties\n// so that it can keep same with es module or cjs\nconst {\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n} = axios;\n\nexport {\n axios as default,\n Axios,\n AxiosError,\n CanceledError,\n isCancel,\n CancelToken,\n VERSION,\n all,\n Cancel,\n isAxiosError,\n spread,\n toFormData,\n AxiosHeaders,\n HttpStatusCode,\n formToJSON,\n getAdapter,\n mergeConfig\n}\n", "import { LocalStorage } from '@tectonic/storage';\nimport { isEmpty } from 'lodash-es';\nimport { useEffect, useMemo, useState } from 'react';\n\nimport type { FC } from 'react';\nimport type { FingerprintsDisplayProps } from './Fingerprints.types';\n\nconst getFps = () =>\n [\n LocalStorage.getItem('ttClientFpV0'),\n (LocalStorage.getItem('fingerPrintV3') ?? ({} as any)).visitorId,\n (LocalStorage.getItem('fingerPrintPro') ?? ({} as any)).visitorId,\n ].filter((fp) => !isEmpty(fp));\n\nconst FingerprintsDisplay: FC = () => {\n const [fingerprints, setFingerprints] = useState([]);\n\n useEffect(() => {\n const params = new URLSearchParams(window.location.search);\n if (!params.has('ttfp')) {\n return;\n }\n const fps = getFps();\n if (!isEmpty(fps)) {\n setFingerprints(fps);\n } else {\n setTimeout(() => {\n setFingerprints(getFps());\n }, 1500);\n }\n }, []);\n\n const fpComp = useMemo(() => {\n if (isEmpty(fingerprints)) {\n return null;\n }\n\n return (\n \n setFingerprints([])}\n >\n ✖\n \n Fingerprints
\n {\n // eslint-disable-next-line react/no-array-index-key\n fingerprints &&\n fingerprints.map((fp, _) =>
{fp}
)\n }\n \n );\n }, [setFingerprints, fingerprints]);\n\n return fpComp;\n};\n\nFingerprintsDisplay.displayName = 'FingerprintsDisplayComponent';\n\nexport default FingerprintsDisplay;\n", "import FingerprintsDisplay from './Fingerprints';\n\nexport default FingerprintsDisplay;", "import { Logger } from '@tectonic/logger';\nimport { getOIBInfo } from '@tectonic/remix-client-network';\nimport { SessionStorage } from '@tectonic/storage';\nimport { isEmpty } from 'lodash-es';\nimport { useEffect } from 'react';\n\nimport type { FC } from 'react';\nimport type { OIBProps } from './OIB.types';\n\nconst OIB: FC = () => {\n useEffect(() => {\n const isEvaluated = SessionStorage.getItem('tt_oib_evaluated');\n\n // console.log(\"isEvaluated\", isEvaluated, window.location.href)\n\n if (!isEmpty(isEvaluated)) {\n return;\n }\n\n const getOIBDetails = async () => {\n try {\n const oibResp = await getOIBInfo(\n window.location.href,\n document.referrer\n );\n const url = oibResp?.url;\n const status = oibResp?.status;\n // const message = oibResp?.message\n // Logger.info(`[OIB_DETAILS]`, url, status, message)\n if (status === 'SUCCESS') {\n SessionStorage.setItem('tt_oib_evaluated', 'true');\n if (!isEmpty(url)) {\n // @ts-ignore\n window.location.href = url;\n }\n }\n } catch (error) {\n Logger.error('Error getting OIB data:', error);\n }\n };\n\n getOIBDetails();\n\n // window.addEventListener('load', getOIBDetails);\n\n // eslint-disable-next-line consistent-return\n return () => {\n // window.removeEventListener('load', getOIBDetails);\n };\n }, []);\n\n return null;\n};\n\nOIB.displayName = 'OIBComponent';\n\nexport default OIB;\n", "import OIB from './OIB';\n\nexport default OIB;", "import { useNavigation } from '@remix-run/react';\nimport { Progress, ProgressIndicator } from '@tectonic/uikit';\nimport clsx from 'clsx';\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nimport type { Fetcher } from '@remix-run/react';\nimport type { FC } from 'react';\nimport type { TransitionProps } from './Transition.types';\n\nconst isLoading = (state: Fetcher['state']): boolean => state === 'loading';\n\nconst isIdle = (state: Fetcher['state']): boolean => state === 'idle';\n\nconst FAKE_MAX_PROGRESS = 95;\nconst FRAME_DELAY = 100;\n\nconst useProgress = () => {\n const [progress, setProgress] = useState(0);\n const animationRef = useRef();\n const { state: navState } = useNavigation();\n const timerRef = useRef>();\n\n const animate = useCallback(() => {\n animationRef.current = window.requestAnimationFrame(() => {\n setProgress((prevProgress) => {\n // Don't do anything if progress is already at max.\n if (prevProgress === 100) {\n return prevProgress;\n }\n let newProgress = prevProgress + 2 ** (prevProgress / 10);\n // Ensure progress doesn't exceed max progress\n newProgress = Math.min(newProgress, FAKE_MAX_PROGRESS);\n timerRef.current = setTimeout(animate, FRAME_DELAY);\n return newProgress;\n });\n });\n }, [animationRef, setProgress]);\n\n const start = useCallback(() => {\n setProgress(0);\n animate();\n }, [setProgress, animate]);\n\n const end = useCallback(() => {\n cancelAnimationFrame(animationRef.current!);\n clearTimeout(timerRef.current);\n setProgress(100);\n }, [setProgress]);\n\n useEffect(() => {\n if (isIdle(navState)) {\n end();\n } else if (isLoading(navState)) {\n start();\n }\n }, [start, end, navState]);\n\n return { progress } as const;\n};\n\nconst Transition: FC = () => {\n const { progress } = useProgress();\n const indicatorStyle = { width: `${progress}%` };\n\n const isVisible = progress !== 0 && progress !== 100;\n\n return (\n \n \n \n );\n};\n\nTransition.displayName = 'LoadersTransition';\n\nexport default Transition;\n", "import Transition from './Transition';\n\nexport default Transition;\n", "/* eslint-disable no-underscore-dangle */\nimport { useSearchParams } from '@remix-run/react';\nimport { LocalStorage } from '@tectonic/storage';\nimport { useEffect } from 'react';\nimport { useAnalyticsEffect } from './useAnalyticsEffect';\nimport useFirebaseEffect from './useFirebaseEffect';\n\nimport type { SessionInfo } from '@tectonic/types';\n\nconst useDebugHelpers = (\n { currentUser, sessionInfo }:\n { currentUser: unknown, sessionInfo: SessionInfo }\n) => {\n globalThis.___tt___ = globalThis.___tt___ ?? {};\n globalThis.___tt___.currentUser = currentUser;\n globalThis.___tt___.sessionInfo = sessionInfo;\n const [searchParams] = useSearchParams();\n const isTester = searchParams.has('ttTester');\n useEffect(() => {\n if (!isTester) {\n return;\n }\n const pValue = LocalStorage.getItem('isTester');\n if (pValue === null) {\n LocalStorage.setItem('isTester', true);\n }\n }, [isTester]);\n};\n\nconst injectEnvs = ({ env }: { env: Record }) => {\n globalThis.env = env as Record;\n};\n\nconst useAppLaunchEffect = (context: {\n env: Record;\n currentUser: unknown;\n isMobile: boolean;\n serverTime: number;\n sessionInfo: SessionInfo;\n ttTester: boolean;\n}) => {\n injectEnvs(context);\n useDebugHelpers(context);\n // TODO: Remove firebase. We don't need it.\n useFirebaseEffect(context);\n useAnalyticsEffect({\n env: context.env,\n currentUser: context.currentUser,\n sessionInfo: context.sessionInfo,\n ttTester: context.ttTester,\n });\n};\n\nexport default useAppLaunchEffect;\n", "import { createPath, useLocation } from '@remix-run/react';\nimport * as Sentry from '@sentry/browser';\nimport {\n generateV0Fp,\n initializeAnalytics,\n initializeFingerprintProProxy,\n initializeFingerprintV3,\n setGlobalProperties,\n setUserProperties,\n trackWebVitalMetric,\n useAnalyticsStore\n} from '@tectonic/analytics';\nimport { LocalStorage } from '@tectonic/storage';\nimport { loadScript, usePrevious } from '@tectonic/utils';\nimport { isEmpty, isNil } from 'lodash-es';\nimport { useEffect } from 'react';\nimport { onCLS, onFCP, onINP, onLCP, onTTFB } from 'web-vitals';\nimport { usePageDurationTracker } from './usePageDurationTracker';\nimport { usePageViewTracker } from './usePageViewTracker';\nimport useSessionDurationTracker from './useSessionDurationTracker';\n\nimport type { MixpanelConfig } from '@tectonic/analytics';\nimport type { SessionInfo, User } from '@tectonic/types';\n\n// Keeps the store for analytics in sync with ui state.\nconst useAnalyticsStoreEffect = () => {\n const setParams = useAnalyticsStore((state) => state.setParams);\n const location = useLocation();\n\n // There's no way to get previous url reliable. We use ref to remember previous\n // location and construct it manually when it is available.\n // https://stackoverflow.com/questions/3528324/how-to-get-the-previous-url-in-javascript\n const prevLocationRef = usePrevious(null);\n\n useEffect(() => {\n const previousUrl = prevLocationRef.current\n ? createPath(prevLocationRef.current ?? {})\n : null;\n // @ts-ignore\n prevLocationRef.current = location;\n // @ts-ignore\n setParams({ previousUrl });\n }, [prevLocationRef, location, setParams]);\n};\n\nconst useAnalyticsInitEffect = (\n env: Record,\n ttTester: boolean,\n sessionInfo: SessionInfo\n) => {\n const {\n MIXPANEL_PROJECT_TOKEN,\n MIXPANEL_PROXY_DOMAIN,\n MIXPANEL_DEBUG_MODE,\n NODE_ENV,\n } = env;\n\n const {\n session\n } = sessionInfo ?? {}\n\n useEffect(() => {\n const mixpanel: MixpanelConfig = {\n token: MIXPANEL_PROJECT_TOKEN,\n options: {\n ignore_dnt: true,\n persistence: 'localStorage',\n debug: NODE_ENV !== 'production' || MIXPANEL_DEBUG_MODE === 'true',\n api_host: MIXPANEL_PROXY_DOMAIN,\n },\n };\n const { id, ...rest } = session ?? {};\n initializeAnalytics({ mixpanel }, ttTester, id, rest);\n }, [\n MIXPANEL_PROJECT_TOKEN,\n MIXPANEL_PROXY_DOMAIN,\n MIXPANEL_DEBUG_MODE,\n NODE_ENV,\n ttTester,\n session\n ]);\n};\n\n// We have custom implementation of tracking. Therefore, we need to set, reset\n// and alias user as per our backend implementation.\n// 1. `ttUserId`\n// - We add `ttUserId` as current user id to identity a user for an event.\n// - It is always in sync with the user available in context.\n// 2. `identify`\n// - We identify user only when the user signs in or signs up.\n// 3. `aliases`\n// - Users are aliased when they login. We don't aliases a user when they sign\n// up cause the user id doesn't change.\nconst useAnalyticsUserEffect = (currentUser: User) => {\n const { externalUserId: userId, simpleId } = currentUser;\n const isAnonymous =\n isNil(currentUser?.isAnonymous) || currentUser.isAnonymous === true;\n\n // Keep `ttUserId` up to date.\n useEffect(() => {\n setGlobalProperties({\n ttUserId: userId,\n ttSourceUserId: simpleId,\n });\n }, [userId, simpleId]);\n\n // Keep `isAnonymous` up to date.\n useEffect(() => {\n Sentry.setUser({ id: userId });\n setUserProperties({ isAnonymous });\n setGlobalProperties({ isAnonymous });\n }, [isAnonymous, userId]);\n};\n\nconst useGtagEffect = (env: Record) => {\n const { GTAG_HOST, GTAG_ID, GTAG_JS_URL, ORGANIZATION } = env;\n\n useEffect(() => {\n globalThis.dataLayer = globalThis.dataLayer ?? [];\n globalThis.gtag = function gtagFn() {\n // eslint-disable-next-line prefer-rest-params\n globalThis.dataLayer.push(arguments);\n };\n globalThis.gtag('consent', 'default', {\n 'ad_storage': 'granted',\n 'ad_user_data': 'granted',\n 'ad_personalization': 'granted',\n 'analytics_storage': 'granted'\n });\n loadScript(GTAG_JS_URL);\n globalThis.gtag('js', new Date());\n globalThis.gtag('config', GTAG_ID, {\n sever_container_url: `https://${GTAG_HOST}`,\n tt_event_source: 'HERMES_CLI',\n tt_org: ORGANIZATION,\n tt_ga_tag: GTAG_ID,\n });\n }, [GTAG_HOST, GTAG_ID, GTAG_JS_URL, ORGANIZATION]);\n};\n\n\nconst useRUMEffect = () => {\n useEffect(() => {\n try {\n onCLS(trackWebVitalMetric)\n onTTFB(trackWebVitalMetric)\n onINP(trackWebVitalMetric)\n onFCP(trackWebVitalMetric)\n onLCP(trackWebVitalMetric)\n } catch (err) {\n // Log errors in future if we want to track\n }\n }, []);\n};\n\nconst useGtmEffect = (env: Record) => {\n const { GTM_ID, GTAG_HOST, ORGANIZATION } = env;\n useEffect(() => {\n if (isEmpty(GTM_ID)) {\n return\n }\n const GTM_JS_URL = `https://${GTAG_HOST}/gtm.js?id=${GTM_ID}&l=dataLayerClientSide`\n globalThis.dataLayerClientSide = globalThis.dataLayerClientSide ?? [];\n globalThis.clientSideGtag = function clientSideGtagFn() {\n // eslint-disable-next-line prefer-rest-params\n globalThis.dataLayerClientSide.push(arguments);\n };\n globalThis.clientSideGtag('consent', 'default', {\n 'ad_storage': 'granted',\n 'ad_user_data': 'granted',\n 'ad_personalization': 'granted',\n 'analytics_storage': 'granted'\n });\n loadScript(GTM_JS_URL);\n globalThis.dataLayerClientSide.push({\n 'gtm.start': new Date().getTime(),\n event: 'gtm.js'\n })\n }, [GTAG_HOST, GTM_ID, ORGANIZATION]);\n};\n\nconst useClartiyEffect = (\n env: Record,\n user: User,\n sessionInfo: SessionInfo\n) => {\n\n const { CLARITY_TOKEN } = env;\n const { simpleId, isAnonymous, externalUserId } = user;\n const { id: sessionId, landingUrl } = sessionInfo?.session ?? {};\n\n useEffect(() => {\n // Clean up once tested and enabled on all clients\n if (isEmpty(CLARITY_TOKEN)) {\n return\n }\n\n try {\n // eslint-disable-next-line func-names\n globalThis.clarity = globalThis.clarity ?? function () {\n // eslint-disable-next-line prefer-rest-params\n (globalThis.clarity.q = globalThis.clarity.q || []).push(arguments);\n };\n const CLARITY_URL = `https://www.clarity.ms/tag/${CLARITY_TOKEN}`\n loadScript(CLARITY_URL);\n // TODO set the below based on user consent\n globalThis.clarity(\"consent\")\n globalThis.clarity(\"identify\", externalUserId)\n globalThis.clarity(\"set\", \"ttUserId\", externalUserId);\n globalThis.clarity(\"set\", \"ttSessionType\", isAnonymous ? \"ANONYMOUS\" : \"LOGGED_IN\");\n if (!isEmpty(simpleId)) {\n globalThis.clarity(\"set\", \"ttSourceUserId\", simpleId);\n }\n if (!isEmpty(sessionId)) {\n globalThis.clarity(\"set\", \"ttClientSessionId\", sessionId);\n }\n if (!isEmpty(landingUrl)) {\n globalThis.clarity(\"set\", \"ttClientSessionLandingUrl\", landingUrl);\n }\n } catch {\n // log to sentry / collect metrics\n }\n\n }, [\n CLARITY_TOKEN,\n externalUserId,\n isAnonymous,\n simpleId,\n sessionId,\n landingUrl\n ])\n}\n\n// TODO for testing storing the data in localstorage, will move to using react components + state, env, etc once finalized\nconst useClientFPEffect = (env: Record) => {\n const { ENABLE_FP_PRO, NODE_ENV, FP_PRO_KEY, FP_PRO_REGION } = env;\n\n useEffect(() => {\n (async () => {\n if (NODE_ENV !== 'production' || ENABLE_FP_PRO !== 'true' || isEmpty(FP_PRO_KEY) || isEmpty(FP_PRO_REGION)) {\n return\n }\n try {\n const fp = await initializeFingerprintProProxy(\n FP_PRO_KEY,\n FP_PRO_REGION\n );\n const fpData = await fp.get({ extendedResult: true });\n LocalStorage.setItem(\"fingerPrintPro\", fpData)\n } catch (err) {\n // console.error(\"[FP_PRO_ERR]\", err)\n // log to sentry\n }\n })();\n }, [ENABLE_FP_PRO, NODE_ENV]);\n\n useEffect(() => {\n (async () => {\n try {\n const fp = await initializeFingerprintV3();\n const fpData = await fp.get();\n LocalStorage.setItem('fingerPrintV3', fpData);\n } catch (err) {\n // log to sentry\n }\n })();\n }, []);\n\n useEffect(() => {\n (async () => {\n try {\n const fp = await generateV0Fp();\n LocalStorage.setItem('ttClientFpV0', fp);\n } catch (err) {\n // log to sentry\n }\n })();\n }, []);\n};\n\nconst useAnalyticsEffect = ({\n env,\n currentUser,\n sessionInfo,\n ttTester,\n}: {\n env: Record;\n currentUser: unknown;\n sessionInfo: SessionInfo;\n ttTester: boolean;\n}) => {\n useAnalyticsStoreEffect();\n useGtagEffect(env);\n useGtmEffect(env);\n useAnalyticsInitEffect(env, ttTester, sessionInfo);\n useAnalyticsUserEffect(currentUser as User);\n useRUMEffect();\n useClientFPEffect(env);\n useClartiyEffect(env, currentUser as User, sessionInfo);\n usePageViewTracker();\n usePageDurationTracker();\n useSessionDurationTracker();\n};\n\nexport { useAnalyticsEffect };\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { ParameterizedString, PolymorphicEvent, Primitive } from '@sentry/types';\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isError(wat: unknown): wat is Error {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat: unknown, className: string): boolean {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isErrorEvent(wat: unknown): boolean {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMError(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isDOMException(wat: unknown): boolean {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isString(wat: unknown): wat is string {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isParameterizedString(wat: unknown): wat is ParameterizedString {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPrimitive(wat: unknown): wat is Primitive {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isPlainObject(wat: unknown): wat is Record {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isEvent(wat: unknown): wat is PolymorphicEvent {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isElement(wat: unknown): boolean {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isRegExp(wat: unknown): wat is RegExp {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nexport function isThenable(wat: any): wat is PromiseLike {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat && wat.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isSyntheticEvent(wat: unknown): boolean {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nexport function isInstanceOf(wat: any, base: any): boolean {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\ninterface VueViewModel {\n // Vue3\n __isVue?: boolean;\n // Vue2\n _isVue?: boolean;\n}\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nexport function isVueViewModel(wat: unknown): boolean {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat as VueViewModel).__isVue || (wat as VueViewModel)._isVue));\n}\n", "export const SDK_VERSION = '8.8.0';\n", "/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n *\n * Note: This file was originally called `global.ts`, but was changed to unblock users which might be doing\n * string replaces with bundlers like Vite for `global` (would break imports that rely on importing from utils/src/global).\n *\n * Why worldwide?\n *\n * Why not?\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { Client, MetricsAggregator, Scope } from '@sentry/types';\n\nimport type { SdkSource } from './env';\nimport { SDK_VERSION } from './version';\n\ninterface SentryCarrier {\n acs?: any;\n stack?: any;\n\n globalScope?: Scope;\n defaultIsolationScope?: Scope;\n defaultCurrentScope?: Scope;\n globalMetricsAggregators: WeakMap | undefined;\n\n /** Overwrites TextEncoder used in `@sentry/utils`, need for `react-native@0.73` and older */\n encodePolyfill?: (input: string) => Uint8Array;\n /** Overwrites TextDecoder used in `@sentry/utils`, need for `react-native@0.73` and older */\n decodePolyfill?: (input: Uint8Array) => string;\n}\n\n// TODO(v9): Clean up or remove this type\ntype BackwardsCompatibleSentryCarrier = SentryCarrier & {\n // pre-v7 hub (replaced by .stack)\n hub: any;\n integrations?: any[];\n logger: any;\n extensions?: {\n /** Extension methods for the hub, which are bound to the current Hub instance */\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n};\n\n/** Internal global with common properties and Sentry extensions */\nexport type InternalGlobal = {\n navigator?: { userAgent?: string };\n console: Console;\n Sentry?: any;\n onerror?: {\n (event: object | string, source?: string, lineno?: number, colno?: number, error?: Error): any;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n onunhandledrejection?: {\n (event: unknown): boolean;\n __SENTRY_INSTRUMENTED__?: true;\n __SENTRY_LOADER__?: true;\n };\n SENTRY_ENVIRONMENT?: string;\n SENTRY_DSN?: string;\n SENTRY_RELEASE?: {\n id?: string;\n };\n SENTRY_SDK_SOURCE?: SdkSource;\n /**\n * Debug IDs are indirectly injected by Sentry CLI or bundler plugins to directly reference a particular source map\n * for resolving of a source file. The injected code will place an entry into the record for each loaded bundle/JS\n * file.\n */\n _sentryDebugIds?: Record;\n __SENTRY__: Record, SentryCarrier> & {\n version?: string;\n } & BackwardsCompatibleSentryCarrier;\n /**\n * Raw module metadata that is injected by bundler plugins.\n *\n * Keys are `error.stack` strings, values are the metadata.\n */\n _sentryModuleMetadata?: Record;\n _sentryEsmLoaderHookRegistered?: boolean;\n};\n\n/** Get's the global object for the current JavaScript runtime */\nexport const GLOBAL_OBJ = globalThis as unknown as InternalGlobal;\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__[]` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nexport function getGlobalSingleton(name: keyof SentryCarrier, creator: () => T, obj?: unknown): T {\n const gbl = (obj || GLOBAL_OBJ) as InternalGlobal;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const versionedCarrier = (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});\n return versionedCarrier[name] || (versionedCarrier[name] = creator());\n}\n", "declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n", "import type { ConsoleLevel } from '@sentry/types';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { GLOBAL_OBJ } from './worldwide';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nexport const CONSOLE_LEVELS: readonly ConsoleLevel[] = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] as const;\n\ntype LoggerMethod = (...args: unknown[]) => void;\ntype LoggerConsoleMethods = Record;\n\n/** This may be mutated by the console instrumentation. */\nexport const originalConsoleMethods: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key in ConsoleLevel]?: (...args: any[]) => void;\n} = {};\n\n/** JSDoc */\ninterface Logger extends LoggerConsoleMethods {\n disable(): void;\n enable(): void;\n isEnabled(): boolean;\n}\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nexport function consoleSandbox(callback: () => T): T {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console as Console;\n const wrappedFuncs: Partial = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) as ConsoleLevel[];\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level] as LoggerMethod;\n wrappedFuncs[level] = console[level] as LoggerMethod | undefined;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] as LoggerMethod;\n });\n }\n}\n\nfunction makeLogger(): Logger {\n let enabled = false;\n const logger: Partial = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logger[name] = (...args: any[]) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger as Logger;\n}\n\nexport const logger = makeLogger();\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { WrappedFunction } from '@sentry/types';\n\nimport { htmlTreeAsString } from './browser';\nimport { DEBUG_BUILD } from './debug-build';\nimport { isElement, isError, isEvent, isInstanceOf, isPlainObject, isPrimitive } from './is';\nimport { logger } from './logger';\nimport { truncate } from './string';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] as () => any;\n const wrapped = replacementFactory(original) as WrappedFunction;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n source[name] = wrapped;\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\nexport function getOriginalFunction(func: WrappedFunction): WrappedFunction | undefined {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor\n * an Error.\n */\nexport function convertToPlainObject(\n value: V,\n):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj: {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n } = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target: unknown): string {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record)[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nexport function extractExceptionKeysForMessage(exception: Record, maxLength: number = 40): string {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nexport function dropUndefinedKeys(inputValue: T): T {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue: T, memoizationMap: Map): T {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: { [key: string]: any } = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.keys(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue as T;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal as T;\n }\n\n const returnValue: unknown[] = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item: unknown) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue as unknown as T;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) as { constructor: { name: string } }).constructor.name;\n return !name || name === 'Object';\n } catch {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nexport function objectify(wat: unknown): typeof Object {\n let objectified;\n switch (true) {\n case wat === undefined || wat === null:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat as any).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n", "import { GLOBAL_OBJ } from './worldwide';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\ninterface Performance {\n /**\n * The millisecond timestamp at which measurement began, measured in Unix time.\n */\n timeOrigin: number;\n /**\n * Returns the current millisecond timestamp, where 0 represents the start of measurement.\n */\n now(): number;\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n *\n * TODO(v8): Return type should be rounded.\n */\nexport function dateTimestampInSeconds(): number {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc(): () => number {\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & { performance?: Performance };\n if (!performance || !performance.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport const timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport let _browserPerformanceTimeOriginMode: string;\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport const browserPerformanceTimeOrigin = ((): number | undefined => {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing && performance.timing.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Event, Exception, Mechanism, StackFrame } from '@sentry/types';\n\nimport { addNonEnumerableProperty } from './object';\nimport { snipLine } from './string';\nimport { GLOBAL_OBJ } from './worldwide';\n\ninterface CryptoInternal {\n getRandomValues(array: Uint8Array): Uint8Array;\n randomUUID?(): string;\n}\n\n/** An interface for common properties on global */\ninterface CryptoGlobal {\n msCrypto?: CryptoInternal;\n crypto?: CryptoInternal;\n}\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4(): string {\n const gbl = GLOBAL_OBJ as typeof GLOBAL_OBJ & CryptoGlobal;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = (): number => Math.random() * 16;\n try {\n if (crypto && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] as unknown as string) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c as unknown as number) ^ ((getRandomByte() & 15) >> ((c as unknown as number) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event: Event): Exception | undefined {\n return event.exception && event.exception.values ? event.exception.values[0] : undefined;\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event: Event): string {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event: Event, value?: string, type?: string): void {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event: Event, newMechanism?: Partial): void {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...(currentMechanism && currentMechanism.data), ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\ninterface SemVer {\n major?: number;\n minor?: number;\n patch?: number;\n prerelease?: string;\n buildmetadata?: string;\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input: string): SemVer {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = parseInt(match[1], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line: string) => snipLine(line, 0));\n\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line: string) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception: unknown): boolean {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception as any).__sentry_captured__) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception as { [key: string]: unknown }, '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nexport function arrayify(maybeArray: T | T[]): T[] {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n", "import type { PropagationContext } from '@sentry/types';\nimport { uuid4 } from './misc';\n\n/**\n * Returns a new minimal propagation context\n */\nexport function generatePropagationContext(): PropagationContext {\n return {\n traceId: uuid4(),\n spanId: uuid4().substring(16),\n };\n}\n", "import type { Client, Integration, MetricsAggregator, Scope } from '@sentry/types';\nimport { GLOBAL_OBJ, SDK_VERSION } from '@sentry/utils';\nimport type { AsyncContextStack } from './asyncContext/stackStrategy';\nimport type { AsyncContextStrategy } from './asyncContext/types';\n\n/**\n * An object that contains globally accessible properties and maintains a scope stack.\n * @hidden\n */\nexport interface Carrier {\n __SENTRY__?: VersionedCarrier;\n}\n\ntype VersionedCarrier = {\n version?: string;\n} & Record, SentryCarrier>;\n\ninterface SentryCarrier {\n acs?: AsyncContextStrategy;\n stack?: AsyncContextStack;\n\n globalScope?: Scope;\n defaultIsolationScope?: Scope;\n defaultCurrentScope?: Scope;\n globalMetricsAggregators?: WeakMap | undefined;\n\n // TODO(v9): Remove these properties - they are no longer used and were left over in v8\n integrations?: Integration[];\n extensions?: {\n // eslint-disable-next-line @typescript-eslint/ban-types\n [key: string]: Function;\n };\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier(): Carrier {\n // This ensures a Sentry carrier exists\n getSentryCarrier(GLOBAL_OBJ);\n return GLOBAL_OBJ;\n}\n\n/** Will either get the existing sentry carrier, or create a new one. */\nexport function getSentryCarrier(carrier: Carrier): SentryCarrier {\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n\n // For now: First SDK that sets the .version property wins\n __SENTRY__.version = __SENTRY__.version || SDK_VERSION;\n\n // Intentionally populating and returning the version of \"this\" SDK instance\n // rather than what's set in .version so that \"this\" SDK always gets its carrier\n return (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});\n}\n", "import type { SerializedSession, Session, SessionContext, SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nexport function makeSession(context?: Omit): Session {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session: Session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see BaseClient.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nexport function updateSession(session: Session, context: SessionContext = {}): void {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nexport function closeSession(session: Session, status?: Exclude): void {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session: Session): SerializedSession {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n", "import type { Scope, Span } from '@sentry/types';\nimport { addNonEnumerableProperty } from '@sentry/utils';\n\nconst SCOPE_SPAN_FIELD = '_sentrySpan';\n\ntype ScopeWithMaybeSpan = Scope & {\n [SCOPE_SPAN_FIELD]?: Span;\n};\n\n/**\n * Set the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nexport function _setSpanForScope(scope: Scope, span: Span | undefined): void {\n if (span) {\n addNonEnumerableProperty(scope as ScopeWithMaybeSpan, SCOPE_SPAN_FIELD, span);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete (scope as ScopeWithMaybeSpan)[SCOPE_SPAN_FIELD];\n }\n}\n\n/**\n * Get the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nexport function _getSpanForScope(scope: ScopeWithMaybeSpan): Span | undefined {\n return scope[SCOPE_SPAN_FIELD];\n}\n", "/* eslint-disable max-lines */\nimport type {\n Attachment,\n Breadcrumb,\n CaptureContext,\n Client,\n Context,\n Contexts,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n Primitive,\n PropagationContext,\n RequestSession,\n Scope as ScopeInterface,\n ScopeContext,\n ScopeData,\n Session,\n SeverityLevel,\n User,\n} from '@sentry/types';\nimport { dateTimestampInSeconds, generatePropagationContext, isPlainObject, logger, uuid4 } from '@sentry/utils';\n\nimport { updateSession } from './session';\nimport { _getSpanForScope, _setSpanForScope } from './utils/spanOnScope';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information.\n */\nclass ScopeClass implements ScopeInterface {\n /** Flag if notifying is happening. */\n protected _notifyingListeners: boolean;\n\n /** Callback for client to receive scope changes. */\n protected _scopeListeners: Array<(scope: Scope) => void>;\n\n /** Callback list that will be called during event processing. */\n protected _eventProcessors: EventProcessor[];\n\n /** Array of breadcrumbs. */\n protected _breadcrumbs: Breadcrumb[];\n\n /** User */\n protected _user: User;\n\n /** Tags */\n protected _tags: { [key: string]: Primitive };\n\n /** Extra */\n protected _extra: Extras;\n\n /** Contexts */\n protected _contexts: Contexts;\n\n /** Attachments */\n protected _attachments: Attachment[];\n\n /** Propagation Context for distributed tracing */\n protected _propagationContext: PropagationContext;\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n protected _sdkProcessingMetadata: { [key: string]: unknown };\n\n /** Fingerprint */\n protected _fingerprint?: string[];\n\n /** Severity */\n protected _level?: SeverityLevel;\n\n /**\n * Transaction Name\n *\n * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.\n * It's purpose is to assign a transaction to the scope that's added to non-transaction events.\n */\n protected _transactionName?: string;\n\n /** Session */\n protected _session?: Session;\n\n /** Request Mode Session Status */\n protected _requestSession?: RequestSession;\n\n /** The client on this scope */\n protected _client?: Client;\n\n /** Contains the last event id of a captured event. */\n protected _lastEventId?: string;\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n public constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = generatePropagationContext();\n }\n\n /**\n * @inheritDoc\n */\n public clone(): ScopeClass {\n const newScope = new ScopeClass();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._requestSession = this._requestSession;\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n newScope._lastEventId = this._lastEventId;\n\n _setSpanForScope(newScope, _getSpanForScope(this));\n\n return newScope;\n }\n\n /**\n * @inheritDoc\n */\n public setClient(client: Client | undefined): void {\n this._client = client;\n }\n\n /**\n * @inheritDoc\n */\n public setLastEventId(lastEventId: string | undefined): void {\n this._lastEventId = lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n public getClient(): C | undefined {\n return this._client as C | undefined;\n }\n\n /**\n * @inheritDoc\n */\n public lastEventId(): string | undefined {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n public addScopeListener(callback: (scope: Scope) => void): void {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n public addEventProcessor(callback: EventProcessor): this {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setUser(user: User | null): this {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getUser(): User | undefined {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n public getRequestSession(): RequestSession | undefined {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n public setRequestSession(requestSession?: RequestSession): this {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTags(tags: { [key: string]: Primitive }): this {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTag(key: string, value: Primitive): this {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtras(extras: Extras): this {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setExtra(key: string, extra: Extra): this {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setFingerprint(fingerprint: string[]): this {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setLevel(level: SeverityLevel): this {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setTransactionName(name?: string): this {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setContext(key: string, context: Context | null): this {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setSession(session?: Session): this {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getSession(): Session | undefined {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n public update(captureContext?: CaptureContext): this {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n const [scopeInstance, requestSession] =\n scopeToMerge instanceof Scope\n ? [scopeToMerge.getScopeData(), scopeToMerge.getRequestSession()]\n : isPlainObject(scopeToMerge)\n ? [captureContext as ScopeContext, (captureContext as ScopeContext).requestSession]\n : [];\n\n const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {};\n\n this._tags = { ...this._tags, ...tags };\n this._extra = { ...this._extra, ...extra };\n this._contexts = { ...this._contexts, ...contexts };\n\n if (user && Object.keys(user).length) {\n this._user = user;\n }\n\n if (level) {\n this._level = level;\n }\n\n if (fingerprint.length) {\n this._fingerprint = fingerprint;\n }\n\n if (propagationContext) {\n this._propagationContext = propagationContext;\n }\n\n if (requestSession) {\n this._requestSession = requestSession;\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clear(): this {\n // client is not cleared here on purpose!\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._session = undefined;\n _setSpanForScope(this, undefined);\n this._attachments = [];\n this._propagationContext = generatePropagationContext();\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addBreadcrumb(breadcrumb: Breadcrumb, maxBreadcrumbs?: number): this {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getLastBreadcrumb(): Breadcrumb | undefined {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n public clearBreadcrumbs(): this {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public addAttachment(attachment: Attachment): this {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public clearAttachments(): this {\n this._attachments = [];\n return this;\n }\n\n /** @inheritDoc */\n public getScopeData(): ScopeData {\n return {\n breadcrumbs: this._breadcrumbs,\n attachments: this._attachments,\n contexts: this._contexts,\n tags: this._tags,\n extra: this._extra,\n user: this._user,\n level: this._level,\n fingerprint: this._fingerprint || [],\n eventProcessors: this._eventProcessors,\n propagationContext: this._propagationContext,\n sdkProcessingMetadata: this._sdkProcessingMetadata,\n transactionName: this._transactionName,\n span: _getSpanForScope(this),\n };\n }\n\n /**\n * @inheritDoc\n */\n public setSDKProcessingMetadata(newData: { [key: string]: unknown }): this {\n this._sdkProcessingMetadata = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public setPropagationContext(context: PropagationContext): this {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n public getPropagationContext(): PropagationContext {\n return this._propagationContext;\n }\n\n /**\n * @inheritDoc\n */\n public captureException(exception: unknown, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureMessage(message: string, level?: SeverityLevel, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n public captureEvent(event: Event, hint?: EventHint): string {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n protected _notifyScopeListeners(): void {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\n// NOTE: By exporting this here as const & type, instead of doing `export class`,\n// We can get the correct class when importing from `@sentry/core`, but the original type (from `@sentry/types`)\n// This is helpful for interop, e.g. when doing `import type { Scope } from '@sentry/node';` (which re-exports this)\n\n/**\n * Holds additional event information.\n */\nexport const Scope = ScopeClass;\n\n/**\n * Holds additional event information.\n */\nexport type Scope = ScopeInterface;\n", "import type { Scope } from '@sentry/types';\nimport { getGlobalSingleton } from '@sentry/utils';\nimport { Scope as ScopeClass } from './scope';\n\n/** Get the default current scope. */\nexport function getDefaultCurrentScope(): Scope {\n return getGlobalSingleton('defaultCurrentScope', () => new ScopeClass());\n}\n\n/** Get the default isolation scope. */\nexport function getDefaultIsolationScope(): Scope {\n return getGlobalSingleton('defaultIsolationScope', () => new ScopeClass());\n}\n", "import type { Client, Scope as ScopeInterface } from '@sentry/types';\nimport { isThenable } from '@sentry/utils';\nimport { getDefaultCurrentScope, getDefaultIsolationScope } from '../defaultScopes';\nimport { Scope } from '../scope';\n\nimport { getMainCarrier, getSentryCarrier } from './../carrier';\nimport type { AsyncContextStrategy } from './types';\n\ninterface Layer {\n client?: Client;\n scope: ScopeInterface;\n}\n\n/**\n * This is an object that holds a stack of scopes.\n */\nexport class AsyncContextStack {\n private readonly _stack: Layer[];\n private _isolationScope: ScopeInterface;\n\n public constructor(scope?: ScopeInterface, isolationScope?: ScopeInterface) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n this._stack = [{ scope: assignedScope }];\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Fork a scope for the stack.\n */\n public withScope(callback: (scope: ScopeInterface) => T): T {\n const scope = this._pushScope();\n\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n this._popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n this._popScope();\n return res;\n },\n e => {\n this._popScope();\n throw e;\n },\n );\n }\n\n this._popScope();\n return maybePromiseResult;\n }\n\n /**\n * Get the client of the stack.\n */\n public getClient(): C | undefined {\n return this.getStackTop().client as C;\n }\n\n /**\n * Returns the scope of the top stack.\n */\n public getScope(): ScopeInterface {\n return this.getStackTop().scope;\n }\n\n /**\n * Get the isolation scope for the stack.\n */\n public getIsolationScope(): ScopeInterface {\n return this._isolationScope;\n }\n\n /**\n * Returns the scope stack for domains or the process.\n */\n public getStack(): Layer[] {\n return this._stack;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n */\n public getStackTop(): Layer {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * Push a scope to the stack.\n */\n private _pushScope(): ScopeInterface {\n // We want to clone the content of prev scope\n const scope = this.getScope().clone();\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * Pop a scope from the stack.\n */\n private _popScope(): boolean {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n}\n\n/**\n * Get the global async context stack.\n * This will be removed during the v8 cycle and is only here to make migration easier.\n */\nfunction getAsyncContextStack(): AsyncContextStack {\n const registry = getMainCarrier();\n const sentry = getSentryCarrier(registry);\n\n return (sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()));\n}\n\nfunction withScope(callback: (scope: ScopeInterface) => T): T {\n return getAsyncContextStack().withScope(callback);\n}\n\nfunction withSetScope(scope: ScopeInterface, callback: (scope: ScopeInterface) => T): T {\n const stack = getAsyncContextStack() as AsyncContextStack;\n return stack.withScope(() => {\n stack.getStackTop().scope = scope;\n return callback(scope);\n });\n}\n\nfunction withIsolationScope(callback: (isolationScope: ScopeInterface) => T): T {\n return getAsyncContextStack().withScope(() => {\n return callback(getAsyncContextStack().getIsolationScope());\n });\n}\n\n/**\n * Get the stack-based async context strategy.\n */\nexport function getStackAsyncContextStrategy(): AsyncContextStrategy {\n return {\n withIsolationScope,\n withScope,\n withSetScope,\n withSetIsolationScope: (_isolationScope: ScopeInterface, callback: (isolationScope: ScopeInterface) => T) => {\n return withIsolationScope(callback);\n },\n getCurrentScope: () => getAsyncContextStack().getScope(),\n getIsolationScope: () => getAsyncContextStack().getIsolationScope(),\n };\n}\n", "import type { Carrier } from './../carrier';\nimport { getMainCarrier, getSentryCarrier } from './../carrier';\nimport { getStackAsyncContextStrategy } from './stackStrategy';\nimport type { AsyncContextStrategy } from './types';\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nexport function setAsyncContextStrategy(strategy: AsyncContextStrategy | undefined): void {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n const sentry = getSentryCarrier(registry);\n sentry.acs = strategy;\n}\n\n/**\n * Get the current async context strategy.\n * If none has been setup, the default will be used.\n */\nexport function getAsyncContextStrategy(carrier: Carrier): AsyncContextStrategy {\n const sentry = getSentryCarrier(carrier);\n\n if (sentry.acs) {\n return sentry.acs;\n }\n\n // Otherwise, use the default one (stack)\n return getStackAsyncContextStrategy();\n}\n", "import type { Scope } from '@sentry/types';\nimport type { Client } from '@sentry/types';\nimport { getGlobalSingleton } from '@sentry/utils';\nimport { getAsyncContextStrategy } from './asyncContext';\nimport { getMainCarrier } from './carrier';\nimport { Scope as ScopeClass } from './scope';\n\n/**\n * Get the currently active scope.\n */\nexport function getCurrentScope(): Scope {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n return acs.getCurrentScope();\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current exection context.\n */\nexport function getIsolationScope(): Scope {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n return acs.getIsolationScope();\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nexport function getGlobalScope(): Scope {\n return getGlobalSingleton('globalScope', () => new ScopeClass());\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n */\nexport function withScope(callback: (scope: Scope) => T): T;\n/**\n * Set the given scope as the active scope in the callback.\n */\nexport function withScope(scope: Scope | undefined, callback: (scope: Scope) => T): T;\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nexport function withScope(\n ...rest: [callback: (scope: Scope) => T] | [scope: Scope | undefined, callback: (scope: Scope) => T]\n): T {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n\n if (!scope) {\n return acs.withScope(callback);\n }\n\n return acs.withSetScope(scope, callback);\n }\n\n return acs.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n */\nexport function withIsolationScope(callback: (isolationScope: Scope) => T): T;\n/**\n * Set the provided isolation scope as active in the given callback. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n *\n * If you pass in `undefined` as a scope, it will fork a new isolation scope, the same as if no scope is passed.\n */\nexport function withIsolationScope(isolationScope: Scope | undefined, callback: (isolationScope: Scope) => T): T;\n/**\n * Either creates a new active isolation scope, or sets the given isolation scope as active scope in the given callback.\n */\nexport function withIsolationScope(\n ...rest:\n | [callback: (isolationScope: Scope) => T]\n | [isolationScope: Scope | undefined, callback: (isolationScope: Scope) => T]\n): T {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [isolationScope, callback] = rest;\n\n if (!isolationScope) {\n return acs.withIsolationScope(callback);\n }\n\n return acs.withSetIsolationScope(isolationScope, callback);\n }\n\n return acs.withIsolationScope(rest[0]);\n}\n\n/**\n * Get the currently active client.\n */\nexport function getClient(): C | undefined {\n return getCurrentScope().getClient();\n}\n", "import type {\n CaptureContext,\n CheckIn,\n Event,\n EventHint,\n EventProcessor,\n Extra,\n Extras,\n FinishedCheckIn,\n MonitorConfig,\n Primitive,\n Session,\n SessionContext,\n SeverityLevel,\n User,\n} from '@sentry/types';\nimport { GLOBAL_OBJ, isThenable, logger, timestampInSeconds, uuid4 } from '@sentry/utils';\n\nimport { DEFAULT_ENVIRONMENT } from './constants';\nimport { getClient, getCurrentScope, getIsolationScope, withIsolationScope } from './currentScopes';\nimport { DEBUG_BUILD } from './debug-build';\nimport { closeSession, makeSession, updateSession } from './session';\nimport type { ExclusiveEventHintOrCaptureContext } from './utils/prepareEvent';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nexport function captureException(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n exception: any,\n hint?: ExclusiveEventHintOrCaptureContext,\n): string {\n return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nexport function captureMessage(message: string, captureContext?: CaptureContext | SeverityLevel): string {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentScope().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param exception The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nexport function captureEvent(event: Event, hint?: EventHint): string {\n return getCurrentScope().captureEvent(event, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function setContext(name: string, context: { [key: string]: any } | null): void {\n getIsolationScope().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nexport function setExtras(extras: Extras): void {\n getIsolationScope().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nexport function setExtra(key: string, extra: Extra): void {\n getIsolationScope().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nexport function setTags(tags: { [key: string]: Primitive }): void {\n getIsolationScope().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nexport function setTag(key: string, value: Primitive): void {\n getIsolationScope().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nexport function setUser(user: User | null): void {\n getIsolationScope().setUser(user);\n}\n\n/**\n * The last error event id of the isolation scope.\n *\n * Warning: This function really returns the last recorded error event id on the current\n * isolation scope. If you call this function after handling a certain error and another error\n * is captured in between, the last one is returned instead of the one you might expect.\n * Also, ids of events that were never sent to Sentry (for example because\n * they were dropped in `beforeSend`) could be returned.\n *\n * @returns The last event id of the isolation scope.\n */\nexport function lastEventId(): string | undefined {\n return getIsolationScope().lastEventId();\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nexport function withMonitor(\n monitorSlug: CheckIn['monitorSlug'],\n callback: () => T,\n upsertMonitorConfig?: MonitorConfig,\n): T {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status: FinishedCheckIn['status']): void {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n return withIsolationScope(() => {\n let maybePromiseResult: T;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n () => {\n finishCheckIn('error');\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n });\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function flush(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nexport async function close(timeout?: number): Promise {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nexport function isInitialized(): boolean {\n return !!getClient();\n}\n\n/** If the SDK is initialized & enabled. */\nexport function isEnabled(): boolean {\n const client = getClient();\n return !!client && client.getOptions().enabled !== false && !!client.getTransport();\n}\n\n/**\n * Add an event processor.\n * This will be added to the current isolation scope, ensuring any event that is processed in the current execution\n * context will have the processor applied.\n */\nexport function addEventProcessor(callback: EventProcessor): void {\n getIsolationScope().addEventProcessor(callback);\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nexport function startSession(context?: SessionContext): Session {\n const client = getClient();\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nexport function endSession(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n\n // TODO (v8): Remove this and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n currentScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate(): void {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n const client = getClient();\n // TODO (v8): Remove currentScope and only use the isolation scope(?).\n // For v7 though, we can't \"soft-break\" people using getCurrentHub().getScope().setSession()\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session && client) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nexport function captureSession(end: boolean = false): void {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n", "var e,n,t,r,i,o=-1,a=function(e){addEventListener(\"pageshow\",(function(n){n.persisted&&(o=n.timeStamp,e(n))}),!0)},c=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType(\"navigation\")[0];if(e&&e.responseStart>0&&e.responseStart=0?r=\"back-forward-cache\":t&&(document.prerendering||u()>0?r=\"prerender\":document.wasDiscarded?r=\"restore\":t.type&&(r=t.type.replace(/_/g,\"-\")));return{name:e,value:void 0===n?-1:n,rating:\"good\",delta:0,entries:[],id:\"v4-\".concat(Date.now(),\"-\").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},s=function(e,n,t){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var r=new PerformanceObserver((function(e){Promise.resolve().then((function(){n(e.getEntries())}))}));return r.observe(Object.assign({type:e,buffered:!0},t||{})),r}}catch(e){}},d=function(e,n,t,r){var i,o;return function(a){n.value>=0&&(a||r)&&((o=n.value-(i||0))||void 0===i)&&(i=n.value,n.delta=o,n.rating=function(e,n){return e>n[1]?\"poor\":e>n[0]?\"needs-improvement\":\"good\"}(n.value,t),e(n))}},l=function(e){requestAnimationFrame((function(){return requestAnimationFrame((function(){return e()}))}))},p=function(e){document.addEventListener(\"visibilitychange\",(function(){\"hidden\"===document.visibilityState&&e()}))},v=function(e){var n=!1;return function(){n||(e(),n=!0)}},m=-1,h=function(){return\"hidden\"!==document.visibilityState||document.prerendering?1/0:0},g=function(e){\"hidden\"===document.visibilityState&&m>-1&&(m=\"visibilitychange\"===e.type?e.timeStamp:0,T())},y=function(){addEventListener(\"visibilitychange\",g,!0),addEventListener(\"prerenderingchange\",g,!0)},T=function(){removeEventListener(\"visibilitychange\",g,!0),removeEventListener(\"prerenderingchange\",g,!0)},E=function(){return m<0&&(m=h(),y(),a((function(){setTimeout((function(){m=h(),y()}),0)}))),{get firstHiddenTime(){return m}}},C=function(e){document.prerendering?addEventListener(\"prerenderingchange\",(function(){return e()}),!0):e()},b=[1800,3e3],S=function(e,n){n=n||{},C((function(){var t,r=E(),i=f(\"FCP\"),o=s(\"paint\",(function(e){e.forEach((function(e){\"first-contentful-paint\"===e.name&&(o.disconnect(),e.startTimer.value&&(r.value=i,r.entries=o,t())},u=s(\"layout-shift\",c);u&&(t=d(e,r,L,n.reportAllChanges),p((function(){c(u.takeRecords()),t(!0)})),a((function(){i=0,r=f(\"CLS\",0),t=d(e,r,L,n.reportAllChanges),l((function(){return t()}))})),setTimeout(t,0))})))},A=0,I=1/0,P=0,M=function(e){e.forEach((function(e){e.interactionId&&(I=Math.min(I,e.interactionId),P=Math.max(P,e.interactionId),A=P?(P-I)/7+1:0)}))},k=function(){return e?A:performance.interactionCount||0},F=function(){\"interactionCount\"in performance||e||(e=s(\"event\",M,{type:\"event\",buffered:!0,durationThreshold:0}))},D=[],x=new Map,R=0,B=function(){var e=Math.min(D.length-1,Math.floor((k()-R)/50));return D[e]},H=[],q=function(e){if(H.forEach((function(n){return n(e)})),e.interactionId||\"first-input\"===e.entryType){var n=D[D.length-1],t=x.get(e.interactionId);if(t||D.length<10||e.duration>n.latency){if(t)e.duration>t.latency?(t.entries=[e],t.latency=e.duration):e.duration===t.latency&&e.startTime===t.entries[0].startTime&&t.entries.push(e);else{var r={id:e.interactionId,latency:e.duration,entries:[e]};x.set(r.id,r),D.push(r)}D.sort((function(e,n){return n.latency-e.latency})),D.length>10&&D.splice(10).forEach((function(e){return x.delete(e.id)}))}}},O=function(e){var n=self.requestIdleCallback||self.setTimeout,t=-1;return e=v(e),\"hidden\"===document.visibilityState?e():(t=n(e),p(e)),t},N=[200,500],j=function(e,n){\"PerformanceEventTiming\"in self&&\"interactionId\"in PerformanceEventTiming.prototype&&(n=n||{},C((function(){var t;F();var r,i=f(\"INP\"),o=function(e){O((function(){e.forEach(q);var n=B();n&&n.latency!==i.value&&(i.value=n.latency,i.entries=n.entries,r())}))},c=s(\"event\",o,{durationThreshold:null!==(t=n.durationThreshold)&&void 0!==t?t:40});r=d(e,i,N,n.reportAllChanges),c&&(c.observe({type:\"first-input\",buffered:!0}),p((function(){o(c.takeRecords()),r(!0)})),a((function(){R=k(),D.length=0,x.clear(),i=f(\"INP\"),r=d(e,i,N,n.reportAllChanges)})))})))},_=[2500,4e3],z={},G=function(e,n){n=n||{},C((function(){var t,r=E(),i=f(\"LCP\"),o=function(e){n.reportAllChanges||(e=e.slice(-1)),e.forEach((function(e){e.startTime=0&&t1e12?new Date:performance.now())-e.timeStamp;\"pointerdown\"==e.type?function(e,n){var t=function(){W(e,n),i()},r=function(){i()},i=function(){removeEventListener(\"pointerup\",t,U),removeEventListener(\"pointercancel\",r,U)};addEventListener(\"pointerup\",t,U),addEventListener(\"pointercancel\",r,U)}(n,e):W(n,e)}},Z=function(e){[\"mousedown\",\"keydown\",\"touchstart\",\"pointerdown\"].forEach((function(n){return e(n,Y,U)}))},$=[100,300],ee=function(e,r){r=r||{},C((function(){var o,c=E(),u=f(\"FID\"),l=function(e){e.startTime {\n // https://css-tricks.com/how-i-put-the-scroll-percentage-in-the-browser-title-bar/\n const scrollTop = window.scrollY;\n const scrollHeight = getScrollHeight();\n const winHeight = window.innerHeight;\n return percent(scrollTop, scrollHeight - winHeight);\n};\n\n// Track the page duration along with scroll depth.\nconst usePageDurationTracker = () => {\n const scrollDepthRef = useRef(0);\n\n const location = useLocation();\n const params = useParams();\n const paramsRef = usePrevious(params);\n\n const onScroll = useCallback(() => {\n const sPercent = getScrollPercentage();\n scrollDepthRef.current = Math.max(sPercent, scrollDepthRef.current);\n }, [scrollDepthRef]);\n\n useOnWindowScroll(onScroll);\n\n useEffect(() => {\n timeEvent(AnalyticsEventNames.PAGE_DURATION);\n const pageParams = paramsRef.current;\n return () => {\n const payload = {\n pageParams,\n scrollDepth: scrollDepthRef.current,\n };\n trackEvent(AnalyticsEventNames.PAGE_DURATION, payload);\n scrollDepthRef.current = 0;\n };\n }, [paramsRef, location, scrollDepthRef]);\n};\n\nexport { usePageDurationTracker };\n", "import { useLocation, useParams } from '@remix-run/react';\nimport { toAnalyticsEventPayload, trackPageView } from '@tectonic/analytics';\nimport { usePrevious } from '@tectonic/utils';\nimport { useEffect } from 'react';\n\nimport type { Location } from '@remix-run/react';\nimport type { Nil } from '@tectonic/types';\n\nconst usePageViewTracker = () => {\n const location = useLocation();\n const params = useParams();\n const paramsRef = usePrevious(params);\n\n // There's no way to get previous url reliable. We use ref to remember previous\n // location and construct it manually when it is available.\n // https://stackoverflow.com/questions/3528324/how-to-get-the-previous-url-in-javascript\n const prevLocationRef = usePrevious>(null);\n\n useEffect(() => {\n paramsRef.current = params;\n }, [params, paramsRef]);\n\n useEffect(() => {\n const payload = toAnalyticsEventPayload({ pageParams: paramsRef.current });\n trackPageView(payload);\n prevLocationRef.current = location;\n }, [location, prevLocationRef, paramsRef]);\n};\n\nexport { usePageViewTracker };\n", "import { createPath, useLocation } from '@remix-run/react';\nimport {\n AnalyticsEventNames,\n timeEvent,\n trackEvent,\n} from '@tectonic/analytics';\nimport { usePrevious } from '@tectonic/utils';\nimport { useEffect } from 'react';\n\nimport type { Location } from '@remix-run/react';\n\n// Track the page duration along with scroll depth.\nconst useSessionDurationTracker = () => {\n const location = useLocation();\n const initialLocationRef = usePrevious(location);\n useEffect(() => {\n timeEvent(AnalyticsEventNames.SESSION_DURATION);\n const landingUrl = createPath(initialLocationRef.current ?? {});\n\n window.addEventListener('pagehide', () => {\n try {\n const payload = { landingUrl };\n trackEvent(AnalyticsEventNames.SESSION_DURATION, payload, {\n send_immediately: false,\n transport: 'sendBeacon',\n });\n } catch (error) {\n //\n }\n });\n }, [initialLocationRef]);\n};\n\nexport default useSessionDurationTracker;\n", "import { useEffect } from 'react';\nimport { Logger } from '@tectonic/logger';\n\nconst getFirebaseConfig = (env: Record) => {\n const config = {\n apiKey: env.FIREBASE_API_KEY,\n authDomain: env.FIREBASE_AUTH_DOMAIN,\n projectId: env.FIREBASE_PROJECT_ID,\n storageBucket: env.FIREBASE_STORAGE_BUCKET,\n messagingSenderId: env.FIREBASE_MESSAGING_SENDER_ID,\n appId: env.FIREBASE_APP_ID,\n measurementId: env.FIREBASE_MEASUREMENT_ID,\n };\n return config;\n};\n\nconst setupFirebase = async (env: Record) => {\n try {\n const config = getFirebaseConfig(env);\n const module = await import('../firebase/app');\n const { initializeApp } = module;\n initializeApp(config);\n } catch (error) {\n Logger.error('Firebase module could not be loaded');\n Logger.error(error);\n }\n};\n\nconst useFirebaseEffect = (context: unknown) => {\n const { env } = context as { env: Record };\n useEffect(() => {\n setupFirebase(env);\n }, [env]);\n};\n\nexport default useFirebaseEffect;\n", "const colors = {\n // TODO: Add values for black, white and secondary from theme.\n black: '#000',\n white: '#FFF',\n star: '#EAB308',\n primary: {\n 50: '#FEF1F5',\n 100: '#FCE3EC',\n 200: '#F9C7D9',\n 300: '#F7AAC5',\n 400: '#F1729F',\n 600: '#CC5C84',\n 800: '#A64669',\n 900: '#81314D',\n 950: undefined,\n },\n success: {\n 50: '#ECFDF5',\n 100: '#C2FFE3',\n 200: '#A7F3D0',\n 300: '#52BF9D',\n 400: '#41B893',\n 500: '#0FB380',\n 600: '#059669',\n 700: '#047857',\n 800: '#035A3F',\n 900: '#023C2A',\n 950: undefined,\n },\n danger: {\n 50: '#FEF2F2',\n 200: '#FECACA',\n 300: '#EA7D7D',\n 400: '#E16262',\n 500: '#E35151',\n 600: '#DC2626',\n 700: '#B91C1C',\n 800: '#841717',\n 900: '#580F0F',\n 950: undefined,\n },\n warning: {\n 50: '#FFF7ED',\n 100: '#FFE7CB',\n 200: '#FED7AA',\n 300: '#F29B6D',\n 400: '#F0844C',\n 500: '#F1702C',\n 600: '#EA580C',\n 700: '#C2410C',\n 800: '#8C3507',\n 900: '##8C3507',\n 950: undefined,\n },\n info: {\n 50: '#EFF6FF',\n 100: '#D6E8FF',\n 200: '#BFDBFE',\n 300: '#EFF6FF',\n 400: '#6A96F5',\n 500: '#3E75EF',\n 600: '#2563EB',\n 700: '#1D4ED8',\n 800: '#163B8D',\n 900: '#0F285E',\n 950: undefined,\n },\n neutral: {\n 50: '#FAFAFA',\n 100: '#EFEFEF',\n 200: '#E5E5E5',\n 300: '#D4D4D4',\n 400: '#A3A3A3',\n 500: '#737373',\n 600: '#6B6B6B',\n 700: '#535353',\n 800: '#343434',\n 900: '#0A0A0A',\n 950: '#0A0A0A',\n },\n}\n\nexport { colors }\n", "{\n \"home\": {\n \"path\": \"/\"\n },\n \"pdp\": {\n \"path\": \"/products/{slug}\"\n },\n \"product-reviews\": {\n \"path\": \"/products/{slug}/reviews\"\n },\n \"account\": {\n \"path\": \"/account\"\n },\n \"account-addresses\": {\n \"path\": \"/account/addresses\"\n },\n \"login\": {\n \"path\": \"/account/login\"\n },\n \"profile\": {\n \"path\": \"/account/profile\"\n },\n \"wishlist\": {\n \"path\": \"/account/wishlist\"\n },\n \"reset-password\": {\n \"path\": \"/account/reset-password\"\n },\n \"collection-pdp\": {\n \"path\": \"/collections/{collectionSlug}/products/{slug}\"\n },\n \"collection\": {\n \"path\": \"/collections/{slug}\"\n },\n \"orders\": {\n \"path\": \"/orders\"\n },\n \"order-details\": {\n \"path\": \"/orders/{orderId}/{variantId}\"\n },\n \"plp\": {\n \"path\": \"/pages/catalog-search-results\"\n },\n \"other\": {\n \"path\": \"/pages/contact-us\"\n },\n \"about-us\": {\n \"path\": \"/pages/about-us\"\n },\n \"contact-us\": {\n \"path\": \"/pages/contact-us\"\n },\n \"frequently-asked-questions\": {\n \"path\": \"/pages/frequently-asked-questions\"\n },\n \"terms-conditions\": {\n \"path\": \"/pages/terms-conditions\"\n },\n \"shipping-return-policy\": {\n \"path\": \"/pages/shipping-return-policy\"\n },\n \"privacy-policy-cookie-restriction-mode\": {\n \"path\": \"/pages/privacy-policy-cookie-restriction-mode\"\n },\n \"referrals\": {\n \"path\": \"/account/referrals\"\n },\n \"rewards\": {\n \"path\": \"/account/rewards\"\n },\n \"register\": {\n \"path\": \"/account/register\"\n },\n \"munafa-program\": {\n \"path\": \"/pages/munafa-program\"\n },\n \"settings\": {\n \"path\": \"/account/settings\"\n },\n \"cart-page\": {\n \"path\": \"/cart-page\"\n },\n \"search-page\": {\n \"path\": \"/search-page\"\n },\n \"help\": {\n \"path\": \"/pages/help\"\n },\n \"the-remedist-by-dr-rhazes\": {\n \"path\": \"/pages/the-remedist-by-dr-rhazes\"\n }\n}\n"], "mappings": "46BAAA,IAAAA,GAAAC,GAAAC,IAAA,cACA,IAAIC,GAAmBD,IAAQA,GAAK,iBAAoB,SAAUE,EAAK,CACnE,OAAQA,GAAOA,EAAI,WAAcA,EAAM,CAAE,QAAWA,CAAI,CAC5D,EACAF,GAAQ,WAAa,GACrBA,GAAQ,mBAAqB,OAC7B,IAAIG,GAAU,aACVC,GAAcH,GAAgB,IAAoB,EAClDI,GAAqB,UAAY,CACjC,IAAIC,KAAcH,GAAQ,YAAY,EAClCI,EAAkBD,EACjB,IAAI,SAAUE,EAAO,CAAE,IAAIC,EAAI,OAAQA,EAAKD,EAAM,QAAU,MAAQC,IAAO,OAAS,OAASA,EAAG,eAAiB,CAAC,EAClH,OAAO,OAAO,EACnB,OAAOF,EAAgB,OACjBA,EAAgB,OAAO,SAAUG,EAAaC,EAAc,CAAE,SAAWP,GAAY,SAAYM,EAAaC,CAAY,CAAG,EAAG,CAAC,CAAC,EAClI,MACV,EACAX,GAAQ,mBAAqBK,KChB7BO,ICUA,IAAMC,GACJ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C,OAAQC,GACR,QAASC,GACT,QAASA,GACT,OAAQC,GAAiBC,EAAM,EAC/B,QAAM,QAACN,GAAA,EAAK,EAAI,EAIZO,GAASC,GAAUJ,EAAO,EAIzB,IAAMK,GAAgB,IAAM,CACjC,IAAMC,EAAQC,GAAc,EAC5B,OAAAC,GAA+BF,CAAK,EACpCG,GAAO,MAAMH,CAAK,KACX,QAAC,OAAI,gCAAoB,CAClC,EAIA,IAAOI,GAAQC", "names": ["require_dist", "__commonJSMin", "exports", "__importDefault", "mod", "react_1", "deepmerge_1", "useDehydratedState", "matches", "dehydratedState", "match", "_a", "accumulator", "currentValue", "init_esm", "errorMessage", "name", "RootProvider", "useRootContext", "RootContext", "createContext", "_prodErrorMap", "prodErrorMap", "_prodErrorMap", "_DEFAULT_AUTH_ERROR_FACTORY", "ErrorFactory", "logClient", "Logger", "_logWarn", "msg", "args", "LogLevel", "SDK_VERSION", "_logError", "_fail", "authOrCode", "rest", "createErrorInternal", "_createError", "_errorWithCustomMessage", "auth", "code", "message", "errorMap", "prodErrorMap", "ErrorFactory", "createErrorInternal", "authOrCode", "rest", "code", "fullParams", "_DEFAULT_AUTH_ERROR_FACTORY", "_assert", "assertion", "debugFail", "failure", "message", "_logError", "debugAssert", "_isHttpOrHttps", "_getCurrentScheme", "_a", "_isOnline", "isBrowserExtension", "_getUserLanguage", "navigatorLanguage", "Delay", "shortDelay", "longDelay", "debugAssert", "isMobileCordova", "isReactNative", "_emulatorUrl", "config", "path", "url", "FetchProvider", "fetchImpl", "headersImpl", "responseImpl", "debugFail", "SERVER_ERROR_MAP", "DEFAULT_API_TIMEOUT_MS", "_addTidIfNecessary", "auth", "request", "_performApiRequest", "method", "customErrorMap", "_performFetchWithErrorHandling", "body", "params", "query", "querystring", "headers", "_getFinalTarget", "fetchFn", "errorMap", "networkTimeout", "NetworkTimeout", "response", "json", "_makeTaggedError", "errorMessage", "serverErrorCode", "serverErrorMessage", "authError", "_errorWithCustomMessage", "_fail", "e", "FirebaseError", "_performSignInRequest", "serverResponse", "host", "base", "_parseEnforcementState", "enforcementStateStr", "_", "reject", "_createError", "code", "errorParams", "error", "isEnterprise", "grecaptcha", "RecaptchaConfig", "response", "providerStr", "recaptchaEnforcementState", "_parseEnforcementState", "getRecaptchaConfig", "auth", "request", "_performApiRequest", "_addTidIfNecessary", "deleteAccount", "getAccountInfo", "auth", "request", "_performApiRequest", "utcTimestampToDateString", "utcTimestamp", "date", "getIdTokenResult", "user", "forceRefresh", "userInternal", "getModularInstance", "token", "claims", "_parseToken", "_assert", "firebase", "signInProvider", "utcTimestampToDateString", "secondsStringToMilliseconds", "seconds", "algorithm", "payload", "signature", "_logError", "decoded", "base64Decode", "e", "_tokenExpiresIn", "parsedToken", "_logoutIfInvalidated", "promise", "bypassAuthState", "FirebaseError", "isUserInvalidated", "code", "ProactiveRefresh", "wasError", "interval", "_a", "UserMetadata", "createdAt", "lastLoginAt", "metadata", "_reloadWithoutSaving", "auth", "idToken", "response", "getAccountInfo", "coreAccount", "newProviderData", "extractProviderData", "providerData", "mergeProviderData", "oldIsAnonymous", "newIsAnonymous", "isAnonymous", "updates", "reload", "original", "newData", "providers", "providerId", "provider", "__rest", "requestStsToken", "refreshToken", "_performFetchWithErrorHandling", "body", "querystring", "tokenApiHost", "apiKey", "url", "_getFinalTarget", "headers", "FetchProvider", "revokeToken", "request", "_performApiRequest", "_addTidIfNecessary", "StsTokenManager", "expiresIn", "oldToken", "accessToken", "expiresInSec", "appName", "object", "expirationTime", "manager", "stsTokenManager", "debugFail", "assertStringOrUndefined", "assertion", "UserImpl", "uid", "opt", "userInfo", "newUser", "callback", "tokensRefreshed", "deleteAccount", "displayName", "email", "_b", "phoneNumber", "_c", "photoURL", "_d", "tenantId", "_e", "_redirectEventId", "_f", "_g", "_h", "emailVerified", "plainObjectTokenManager", "idTokenResponse", "instanceCache", "_getInstance", "cls", "debugAssert", "instance", "InMemoryPersistence", "key", "value", "_key", "_listener", "inMemoryPersistence", "_persistenceKeyName", "PersistenceUserManager", "persistence", "userKey", "config", "name", "blob", "newPersistence", "currentUser", "persistenceHierarchy", "availablePersistences", "selectedPersistence", "userToMigrate", "migrationHierarchy", "p", "_getBrowserName", "userAgent", "ua", "_isIEMobile", "_isFirefox", "_isBlackBerry", "_isWebOS", "_isSafari", "_isChromeIOS", "_isAndroid", "re", "matches", "getUA", "_isIOS", "_isIE10", "isIE", "_isMobileBrowser", "ua", "getUA", "_isIOS", "_isAndroid", "_isWebOS", "_isBlackBerry", "_isIEMobile", "_isIframe", "_getClientVersion", "clientPlatform", "frameworks", "reportedPlatform", "_getBrowserName", "reportedFrameworks", "SDK_VERSION", "AuthMiddlewareQueue", "auth", "callback", "onAbort", "wrappedCallback", "user", "resolve", "reject", "result", "e", "index", "nextUser", "onAbortStack", "beforeStateCallback", "_getPasswordPolicy", "request", "_performApiRequest", "_addTidIfNecessary", "MINIMUM_MIN_PASSWORD_LENGTH", "PasswordPolicyImpl", "response", "responseOptions", "_a", "_c", "_b", "_d", "password", "status", "_e", "_f", "minPasswordLength", "maxPasswordLength", "passwordChar", "i", "containsLowercaseCharacter", "containsUppercaseCharacter", "containsNumericCharacter", "containsNonAlphanumericCharacter", "AuthImpl", "app", "heartbeatServiceProvider", "appCheckServiceProvider", "config", "Subscription", "_DEFAULT_AUTH_ERROR_FACTORY", "persistenceHierarchy", "popupRedirectResolver", "_getInstance", "PersistenceUserManager", "previouslyStoredUser", "futureCurrentUser", "needsTocheckMiddleware", "redirectUserEventId", "storedUserEventId", "_assert", "redirectResolver", "_reloadWithoutSaving", "_getUserLanguage", "userExtern", "getModularInstance", "skipBeforeStateCallbacks", "persistence", "passwordPolicy", "errorMap", "ErrorFactory", "nextOrObserver", "error", "completed", "unsubscribe", "token", "idToken", "revokeToken", "redirectManager", "resolver", "id", "currentUid", "subscription", "cb", "isUnsubscribed", "promise", "action", "framework", "headers", "heartbeatsHeader", "appCheckToken", "appCheckTokenResult", "_logWarn", "_castAuth", "createSubscribe", "observer", "getScriptParentElement", "_loadJS", "url", "el", "_createError", "_generateCallbackName", "prefix", "RECAPTCHA_ENTERPRISE_URL", "RECAPTCHA_ENTERPRISE_VERIFIER_TYPE", "FAKE_TOKEN", "RecaptchaEnterpriseVerifier", "authExtern", "forceRefresh", "retrieveSiteKey", "getRecaptchaConfig", "RecaptchaConfig", "retrieveRecaptchaToken", "siteKey", "grecaptcha", "isEnterprise", "jsHelpers\r\n ._loadJS", "injectRecaptchaFields", "captchaResp", "verifier", "captchaResponse", "newRequest", "handleRecaptchaFlow", "authInstance", "actionName", "actionMethod", "requestWithRecaptcha", "_initializeAuthInstance", "auth", "deps", "persistence", "hierarchy", "_getInstance", "AuthCredential", "providerId", "signInMethod", "debugFail", "_auth", "_idToken", "linkEmailPassword", "auth", "request", "_performApiRequest", "signInWithPassword", "auth", "request", "_performSignInRequest", "_addTidIfNecessary", "signInWithEmailLink", "auth", "request", "_performSignInRequest", "_addTidIfNecessary", "signInWithEmailLinkForLinking", "EmailAuthCredential", "AuthCredential", "_email", "_password", "signInMethod", "_tenantId", "email", "password", "oobCode", "tenantId", "json", "obj", "handleRecaptchaFlow", "signInWithPassword", "_fail", "idToken", "linkEmailPassword", "signInWithIdp", "IDP_REQUEST_URI", "OAuthCredential", "params", "cred", "providerId", "rest", "__rest", "postBody", "querystring", "sendPhoneVerificationCode", "_performApiRequest", "signInWithPhoneNumber", "linkWithPhoneNumber", "response", "_makeTaggedError", "VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_", "verifyPhoneNumberForExisting", "apiRequest", "PhoneAuthCredential", "verificationId", "verificationCode", "phoneNumber", "temporaryProof", "parseMode", "mode", "parseDeepLink", "url", "link", "querystringDecode", "extractQuerystring", "doubleDeepLink", "iOSDeepLink", "ActionCodeURL", "actionLink", "searchParams", "apiKey", "_a", "code", "_b", "operation", "_c", "_assert", "_d", "_e", "_f", "EmailAuthProvider", "email", "password", "EmailAuthCredential", "emailLink", "actionCodeUrl", "ActionCodeURL", "_assert", "FederatedAuthProvider", "providerId", "languageCode", "customOAuthParameters", "BaseOAuthProvider", "scope", "FacebookAuthProvider", "BaseOAuthProvider", "accessToken", "OAuthCredential", "userCredential", "error", "tokenResponse", "GoogleAuthProvider", "idToken", "oauthIdToken", "oauthAccessToken", "GithubAuthProvider", "TwitterAuthProvider", "BaseOAuthProvider", "token", "secret", "OAuthCredential", "userCredential", "error", "tokenResponse", "oauthAccessToken", "oauthTokenSecret", "UserCredentialImpl", "params", "auth", "operationType", "idTokenResponse", "isAnonymous", "user", "UserImpl", "providerId", "providerIdForResponse", "response", "MultiFactorError", "FirebaseError", "auth", "error", "operationType", "user", "_a", "_processCredentialSavingMfaContextIfNecessary", "credential", "_link", "user", "credential", "bypassAuthState", "response", "_logoutIfInvalidated", "UserCredentialImpl", "_reauthenticate", "user", "credential", "bypassAuthState", "auth", "operationType", "response", "_logoutIfInvalidated", "_processCredentialSavingMfaContextIfNecessary", "_assert", "parsed", "_parseToken", "localId", "UserCredentialImpl", "e", "_fail", "_signInWithCredential", "userCredential", "startEnrollPhoneMfa", "auth", "request", "_performApiRequest", "_addTidIfNecessary", "finalizeEnrollPhoneMfa", "startEnrollTotpMfa", "finalizeEnrollTotpMfa", "STORAGE_AVAILABLE_KEY", "BrowserPersistenceClass", "storageRetriever", "type", "key", "value", "json", "_iframeCannotSyncWebStorage", "ua", "getUA", "_isSafari", "_isIOS", "_POLLING_INTERVAL_MS", "IE10_LOCAL_STORAGE_SYNC_DELAY", "BrowserLocalPersistence", "event", "poll", "_isIframe", "_isMobileBrowser", "cb", "newValue", "oldValue", "_oldValue", "storedValue", "triggerListeners", "_isIE10", "listeners", "listener", "BrowserSessionPersistence", "BrowserPersistenceClass", "_key", "_listener", "_allSettled", "promises", "promise", "reason", "Receiver", "eventTarget", "existingInstance", "receiver", "newInstance", "event", "messageEvent", "eventId", "eventType", "data", "handlers", "handler", "response", "eventHandler", "_generateEventId", "prefix", "digits", "random", "i", "Sender", "target", "timeout", "messageChannel", "completionTimer", "resolve", "reject", "ackTimer", "_window", "_isWorker", "_window", "_getActiveServiceWorker", "_getServiceWorkerController", "_a", "_getWorkerGlobalScope", "DB_NAME", "DB_VERSION", "DB_OBJECTSTORE_NAME", "DB_DATA_KEYPATH", "DBPromise", "request", "resolve", "reject", "getObjectStore", "db", "isReadWrite", "_deleteDatabase", "_openDatabase", "e", "_putObject", "key", "value", "getObject", "data", "_deleteObject", "_POLLING_INTERVAL_MS", "_TRANSACTION_RETRY_COUNT", "IndexedDBLocalPersistence", "op", "numAttempts", "Receiver", "_origin", "_data", "Sender", "results", "_b", "STORAGE_AVAILABLE_KEY", "write", "obj", "result", "getAllRequest", "keys", "keysInResult", "localKey", "newValue", "listeners", "listener", "startSignInPhoneMfa", "auth", "request", "_performApiRequest", "_addTidIfNecessary", "finalizeSignInPhoneMfa", "finalizeSignInTotpMfa", "_JSLOAD_CALLBACK", "jsHelpers._generateCallbackName", "NETWORK_TIMEOUT_DELAY", "Delay", "RECAPTCHA_VERIFIER_TYPE", "_verifyPhoneNumber", "auth", "options", "verifier", "recaptchaToken", "_assert", "RECAPTCHA_VERIFIER_TYPE", "phoneInfoOptions", "session", "startEnrollPhoneMfa", "mfaEnrollmentId", "_a", "startSignInPhoneMfa", "sessionInfo", "sendPhoneVerificationCode", "PhoneAuthProvider", "auth", "_castAuth", "phoneOptions", "applicationVerifier", "_verifyPhoneNumber", "getModularInstance", "verificationId", "verificationCode", "PhoneAuthCredential", "userCredential", "credential", "error", "tokenResponse", "phoneNumber", "temporaryProof", "IdpCredential", "AuthCredential", "params", "auth", "signInWithIdp", "idToken", "request", "_signIn", "_signInWithCredential", "_reauth", "user", "_assert", "_reauthenticate", "_link", "_linkUser", "AbstractPopupRedirectOperation", "filter", "resolver", "bypassAuthState", "resolve", "reject", "e", "event", "urlResponse", "sessionId", "postBody", "tenantId", "error", "type", "_fail", "cred", "debugAssert", "_POLL_WINDOW_CLOSE_TIMEOUT", "Delay", "PopupOperation", "AbstractPopupRedirectOperation", "auth", "filter", "provider", "resolver", "user", "result", "_assert", "debugAssert", "eventId", "_generateEventId", "e", "isSupported", "_createError", "_a", "poll", "_b", "_POLL_WINDOW_CLOSE_TIMEOUT", "EVENT_DUPLICATION_CACHE_DURATION_MS", "NETWORK_TIMEOUT", "Delay", "PING_TIMEOUT", "Delay", "FIREBASE_APP_CHECK_FRAGMENT_ID", "MultiFactorAssertionImpl", "factorId", "auth", "session", "displayName", "debugFail", "PhoneMultiFactorAssertionImpl", "credential", "idToken", "finalizeEnrollPhoneMfa", "mfaPendingCredential", "finalizeSignInPhoneMfa", "PhoneMultiFactorGenerator", "TotpMultiFactorGenerator", "secret", "oneTimePassword", "TotpMultiFactorAssertionImpl", "enrollmentId", "mfaSession", "_assert", "_a", "response", "startEnrollTotpMfa", "TotpSecret", "otp", "finalizeEnrollTotpMfa", "totpVerificationInfo", "finalizeSignInTotpMfa", "secretKey", "hashingAlgorithm", "codeLength", "codeIntervalSeconds", "enrollmentCompletionDeadline", "sessionInfo", "accountName", "issuer", "useDefaults", "_isEmptyString", "input", "AuthInterop", "forceRefresh", "listener", "unsubscribe", "user", "getVersionForPlatform", "clientPlatform", "registerAuth", "_registerComponent", "Component", "container", "deps", "app", "heartbeatServiceProvider", "appCheckServiceProvider", "apiKey", "authDomain", "config", "_getClientVersion", "authInstance", "AuthImpl", "_initializeAuthInstance", "_instanceIdentifier", "_instance", "_castAuth", "registerVersion", "name", "version", "DEFAULT_ID_TOKEN_MAX_AGE", "authIdTokenMaxAge", "getExperimentalSetting", "registerAuth", "import_node", "init_esm", "init_esm", "import_react", "init_esm", "import_react", "useParams", "routeParams", "searchParams", "useSearchParams", "location", "useLocation", "import_jsx_runtime", "withSearchParams", "pathname", "search", "toUrlSearchParams", "getHref", "routes", "payload", "path", "populateWithEncode", "Logger", "getNavigationRegistry", "useSanitizedUser", "user", "ElemasonRemixProvider", "value", "children", "routeParams", "searchParams", "useParams", "navigate", "useNavigate", "sanitizedUser", "navigationRegistry", "ElemasonProvider", "bind", "fn", "thisArg", "toString", "getPrototypeOf", "kindOf", "cache", "thing", "str", "kindOfTest", "type", "typeOfTest", "isArray", "isUndefined", "isBuffer", "val", "isFunction", "isArrayBuffer", "isArrayBufferView", "result", "isString", "isNumber", "isObject", "isBoolean", "isPlainObject", "prototype", "isDate", "isFile", "isBlob", "isFileList", "isStream", "isFormData", "kind", "isURLSearchParams", "isReadableStream", "isRequest", "isResponse", "isHeaders", "trim", "forEach", "obj", "fn", "allOwnKeys", "i", "l", "keys", "len", "key", "findKey", "_key", "_global", "isContextDefined", "context", "merge", "caseless", "assignValue", "targetKey", "extend", "a", "b", "thisArg", "bind", "stripBOM", "content", "inherits", "constructor", "superConstructor", "props", "descriptors", "toFlatObject", "sourceObj", "destObj", "filter", "propFilter", "prop", "merged", "endsWith", "searchString", "position", "lastIndex", "toArray", "arr", "isTypedArray", "TypedArray", "forEachEntry", "iterator", "pair", "matchAll", "regExp", "matches", "isHTMLForm", "toCamelCase", "m", "p1", "p2", "hasOwnProperty", "isRegExp", "reduceDescriptors", "reducer", "reducedDescriptors", "descriptor", "name", "ret", "freezeMethods", "value", "toObjectSet", "arrayOrString", "delimiter", "define", "noop", "toFiniteNumber", "defaultValue", "ALPHA", "DIGIT", "ALPHABET", "generateString", "size", "alphabet", "length", "isSpecCompliantForm", "toJSONObject", "stack", "visit", "source", "target", "reducedValue", "isAsyncFn", "isThenable", "utils_default", "AxiosError", "message", "code", "config", "request", "response", "utils_default", "prototype", "descriptors", "error", "customProps", "axiosError", "obj", "prop", "AxiosError_default", "null_default", "isVisitable", "thing", "utils_default", "removeBrackets", "key", "renderKey", "path", "dots", "token", "isFlatArray", "arr", "predicates", "prop", "toFormData", "obj", "formData", "options", "null_default", "option", "source", "metaTokens", "visitor", "defaultVisitor", "indexes", "useBlob", "convertValue", "value", "AxiosError_default", "el", "index", "stack", "exposedHelpers", "build", "toFormData_default", "encode", "str", "charMap", "match", "AxiosURLSearchParams", "params", "options", "toFormData_default", "prototype", "name", "value", "encoder", "_encode", "pair", "AxiosURLSearchParams_default", "encode", "val", "buildURL", "url", "params", "options", "_encode", "serializeFn", "serializedParams", "utils_default", "AxiosURLSearchParams_default", "hashmarkIndex", "InterceptorManager", "fulfilled", "rejected", "options", "id", "fn", "utils_default", "h", "InterceptorManager_default", "transitional_default", "URLSearchParams_default", "AxiosURLSearchParams_default", "FormData_default", "Blob_default", "browser_default", "URLSearchParams_default", "FormData_default", "Blob_default", "utils_exports", "__export", "hasBrowserEnv", "hasStandardBrowserEnv", "hasStandardBrowserWebWorkerEnv", "origin", "product", "platform_default", "utils_exports", "browser_default", "toURLEncodedForm", "data", "options", "toFormData_default", "platform_default", "value", "key", "path", "helpers", "utils_default", "parsePropPath", "name", "utils_default", "match", "arrayToObject", "arr", "obj", "keys", "i", "len", "key", "formDataToJSON", "formData", "buildPath", "path", "value", "target", "index", "isNumericKey", "isLast", "formDataToJSON_default", "stringifySafely", "rawValue", "parser", "encoder", "utils_default", "e", "defaults", "transitional_default", "data", "headers", "contentType", "hasJSONContentType", "isObjectPayload", "formDataToJSON_default", "isFileList", "toURLEncodedForm", "_FormData", "toFormData_default", "transitional", "forcedJSONParsing", "JSONRequested", "strictJSONParsing", "AxiosError_default", "platform_default", "status", "method", "defaults_default", "ignoreDuplicateOf", "utils_default", "parseHeaders_default", "rawHeaders", "parsed", "key", "val", "i", "line", "$internals", "normalizeHeader", "header", "normalizeValue", "value", "utils_default", "parseTokens", "str", "tokens", "tokensRE", "match", "isValidHeaderName", "matchHeaderValue", "context", "filter", "isHeaderNameFilter", "formatHeader", "w", "char", "buildAccessors", "obj", "accessorName", "methodName", "arg1", "arg2", "arg3", "AxiosHeaders", "headers", "valueOrRewrite", "rewrite", "self", "setHeader", "_value", "_header", "_rewrite", "lHeader", "key", "setHeaders", "parseHeaders_default", "parser", "matcher", "deleted", "deleteHeader", "keys", "i", "format", "normalized", "targets", "asStrings", "thing", "first", "computed", "target", "accessors", "prototype", "defineAccessor", "mapped", "headerValue", "AxiosHeaders_default", "transformData", "fns", "response", "config", "defaults_default", "context", "headers", "AxiosHeaders_default", "data", "utils_default", "fn", "isCancel", "value", "CanceledError", "message", "config", "request", "AxiosError_default", "utils_default", "CanceledError_default", "settle", "resolve", "reject", "response", "validateStatus", "AxiosError_default", "parseProtocol", "url", "match", "speedometer", "samplesCount", "min", "bytes", "timestamps", "head", "tail", "firstSampleTS", "chunkLength", "now", "startedAt", "i", "bytesCount", "passed", "speedometer_default", "throttle", "fn", "freq", "timestamp", "threshold", "timer", "force", "now", "throttle_default", "progressEventReducer_default", "listener", "isDownloadStream", "freq", "bytesNotified", "_speedometer", "speedometer_default", "throttle_default", "e", "loaded", "total", "progressBytes", "rate", "inRange", "data", "isURLSameOrigin_default", "platform_default", "msie", "urlParsingNode", "originURL", "resolveURL", "url", "href", "requestURL", "parsed", "utils_default", "cookies_default", "platform_default", "name", "value", "expires", "path", "domain", "secure", "cookie", "utils_default", "match", "isAbsoluteURL", "url", "combineURLs", "baseURL", "relativeURL", "buildFullPath", "baseURL", "requestedURL", "isAbsoluteURL", "combineURLs", "headersToObject", "thing", "AxiosHeaders_default", "mergeConfig", "config1", "config2", "config", "getMergedValue", "target", "source", "caseless", "utils_default", "mergeDeepProperties", "a", "b", "valueFromConfig2", "defaultToConfig2", "mergeDirectKeys", "prop", "mergeMap", "merge", "configValue", "resolveConfig_default", "config", "newConfig", "mergeConfig", "data", "withXSRFToken", "xsrfHeaderName", "xsrfCookieName", "headers", "auth", "AxiosHeaders_default", "buildURL", "buildFullPath", "contentType", "utils_default", "platform_default", "type", "tokens", "token", "isURLSameOrigin_default", "xsrfValue", "cookies_default", "isXHRAdapterSupported", "xhr_default", "config", "resolve", "reject", "_config", "resolveConfig_default", "requestData", "requestHeaders", "AxiosHeaders_default", "responseType", "onCanceled", "done", "request", "onloadend", "responseHeaders", "response", "settle", "value", "err", "AxiosError_default", "timeoutErrorMessage", "transitional", "transitional_default", "utils_default", "val", "key", "progressEventReducer_default", "cancel", "CanceledError_default", "protocol", "parseProtocol", "platform_default", "composeSignals", "signals", "timeout", "controller", "aborted", "onabort", "cancel", "unsubscribe", "err", "AxiosError_default", "CanceledError_default", "timer", "signal", "composeSignals_default", "streamChunk", "chunk", "chunkSize", "len", "pos", "end", "encoder", "readBytes", "iterable", "trackStream", "stream", "onProgress", "onFinish", "iterator", "bytes", "controller", "done", "value", "reason", "fetchProgressDecorator", "total", "fn", "lengthComputable", "loaded", "isFetchSupported", "isReadableStreamSupported", "supportsRequestStream", "duplexAccessed", "hasContentType", "platform_default", "DEFAULT_CHUNK_SIZE", "supportsResponseStream", "utils_default", "resolvers", "res", "type", "_", "config", "AxiosError_default", "getBodyLength", "body", "resolveBodyLength", "headers", "length", "fetch_default", "url", "method", "data", "signal", "cancelToken", "timeout", "onDownloadProgress", "onUploadProgress", "responseType", "withCredentials", "fetchOptions", "resolveConfig_default", "composedSignal", "stopTimeout", "composeSignals_default", "finished", "request", "onFinish", "requestContentLength", "_request", "contentTypeHeader", "trackStream", "progressEventReducer_default", "response", "isStreamResponse", "options", "prop", "responseContentLength", "responseData", "resolve", "reject", "settle", "AxiosHeaders_default", "err", "knownAdapters", "null_default", "xhr_default", "fetch_default", "utils_default", "fn", "value", "renderReason", "reason", "isResolvedHandle", "adapter", "adapters_default", "adapters", "length", "nameOrAdapter", "rejectedReasons", "id", "AxiosError_default", "reasons", "state", "throwIfCancellationRequested", "config", "CanceledError_default", "dispatchRequest", "AxiosHeaders_default", "transformData", "adapters_default", "defaults_default", "response", "reason", "isCancel", "VERSION", "validators", "type", "i", "thing", "deprecatedWarnings", "validator", "version", "message", "formatMessage", "opt", "desc", "VERSION", "value", "opts", "AxiosError_default", "assertOptions", "options", "schema", "allowUnknown", "keys", "result", "validator_default", "validators", "validator_default", "Axios", "instanceConfig", "InterceptorManager_default", "configOrUrl", "config", "err", "dummy", "stack", "mergeConfig", "transitional", "paramsSerializer", "headers", "utils_default", "contextHeaders", "method", "AxiosHeaders_default", "requestInterceptorChain", "synchronousRequestInterceptors", "interceptor", "responseInterceptorChain", "promise", "i", "len", "chain", "dispatchRequest", "newConfig", "onFulfilled", "onRejected", "error", "fullPath", "buildFullPath", "buildURL", "url", "generateHTTPMethod", "isForm", "data", "Axios_default", "CancelToken", "executor", "resolvePromise", "resolve", "token", "cancel", "onfulfilled", "_resolve", "promise", "message", "config", "request", "CanceledError_default", "listener", "index", "c", "CancelToken_default", "spread", "callback", "arr", "isAxiosError", "payload", "utils_default", "HttpStatusCode", "key", "value", "HttpStatusCode_default", "createInstance", "defaultConfig", "context", "Axios_default", "instance", "bind", "utils_default", "instanceConfig", "mergeConfig", "axios", "defaults_default", "CanceledError_default", "CancelToken_default", "isCancel", "VERSION", "toFormData_default", "AxiosError_default", "promises", "spread", "isAxiosError", "AxiosHeaders_default", "thing", "formDataToJSON_default", "adapters_default", "HttpStatusCode_default", "axios_default", "Axios", "AxiosError", "CanceledError", "isCancel", "CancelToken", "VERSION", "all", "Cancel", "isAxiosError", "spread", "toFormData", "AxiosHeaders", "HttpStatusCode", "formToJSON", "getAdapter", "mergeConfig", "axios_default", "import_react", "import_use_dehydrated_state", "import_react", "import_jsx_runtime", "getFps", "LocalStorage", "fp", "isEmpty_default", "FingerprintsDisplay", "fingerprints", "setFingerprints", "fps", "_", "Fingerprints_default", "Fingerprints_default", "import_react", "OIB", "isEvaluated", "SessionStorage", "isEmpty_default", "oibResp", "getOIBInfo", "url", "error", "Logger", "OIB_default", "OIB_default", "init_esm", "import_react", "import_jsx_runtime", "isLoading", "state", "isIdle", "FAKE_MAX_PROGRESS", "FRAME_DELAY", "useProgress", "progress", "setProgress", "animationRef", "navState", "useNavigation", "timerRef", "animate", "prevProgress", "newProgress", "start", "end", "Transition", "indicatorStyle", "$67824d98245208a0$export$b25a304ec7d746bb", "clsx_default", "$67824d98245208a0$export$2b776f7e7ee60dbd", "Transition_default", "Transition_default", "init_esm", "import_react", "init_esm", "objectToString", "isBuiltin", "wat", "className", "objectToString", "isPlainObject", "wat", "isBuiltin", "isThenable", "wat", "SDK_VERSION", "GLOBAL_OBJ", "getGlobalSingleton", "name", "creator", "obj", "gbl", "__SENTRY__", "versionedCarrier", "SDK_VERSION", "DEBUG_BUILD", "PREFIX", "CONSOLE_LEVELS", "originalConsoleMethods", "consoleSandbox", "callback", "GLOBAL_OBJ", "console", "wrappedFuncs", "wrappedLevels", "level", "originalConsoleMethod", "makeLogger", "enabled", "logger", "DEBUG_BUILD", "name", "args", "addNonEnumerableProperty", "obj", "name", "value", "DEBUG_BUILD", "logger", "ONE_SECOND_IN_MS", "dateTimestampInSeconds", "createUnixTimestampInSecondsFunc", "performance", "GLOBAL_OBJ", "approxStartingTimeOrigin", "timeOrigin", "timestampInSeconds", "_browserPerformanceTimeOriginMode", "browserPerformanceTimeOrigin", "threshold", "performanceNow", "dateNow", "timeOriginDelta", "timeOriginIsReliable", "navigationStart", "navigationStartDelta", "navigationStartIsReliable", "uuid4", "gbl", "GLOBAL_OBJ", "crypto", "getRandomByte", "typedArray", "c", "generatePropagationContext", "uuid4", "getMainCarrier", "getSentryCarrier", "GLOBAL_OBJ", "carrier", "__SENTRY__", "SDK_VERSION", "updateSession", "session", "context", "timestampInSeconds", "uuid4", "duration", "SCOPE_SPAN_FIELD", "_setSpanForScope", "scope", "span", "addNonEnumerableProperty", "_getSpanForScope", "DEFAULT_MAX_BREADCRUMBS", "ScopeClass", "generatePropagationContext", "newScope", "_setSpanForScope", "_getSpanForScope", "client", "lastEventId", "callback", "user", "updateSession", "requestSession", "tags", "key", "value", "extras", "extra", "fingerprint", "level", "name", "context", "session", "captureContext", "scopeToMerge", "scopeInstance", "Scope", "isPlainObject", "contexts", "propagationContext", "breadcrumb", "maxBreadcrumbs", "maxCrumbs", "mergedBreadcrumb", "dateTimestampInSeconds", "breadcrumbs", "attachment", "newData", "exception", "hint", "eventId", "uuid4", "logger", "syntheticException", "message", "event", "getDefaultCurrentScope", "getGlobalSingleton", "ScopeClass", "getDefaultIsolationScope", "AsyncContextStack", "scope", "isolationScope", "assignedScope", "Scope", "assignedIsolationScope", "callback", "maybePromiseResult", "e", "isThenable", "res", "getAsyncContextStack", "registry", "getMainCarrier", "sentry", "getSentryCarrier", "getDefaultCurrentScope", "getDefaultIsolationScope", "withScope", "withSetScope", "stack", "withIsolationScope", "getStackAsyncContextStrategy", "_isolationScope", "getAsyncContextStrategy", "carrier", "sentry", "getSentryCarrier", "getStackAsyncContextStrategy", "getIsolationScope", "carrier", "getMainCarrier", "getAsyncContextStrategy", "setUser", "user", "getIsolationScope", "import_react", "e", "o", "a", "e", "n", "c", "u", "f", "r", "s", "d", "i", "l", "p", "v", "m", "h", "g", "T", "y", "E", "C", "b", "S", "L", "w", "t", "A", "I", "P", "M", "k", "F", "D", "x", "R", "B", "H", "q", "O", "N", "j", "_", "z", "G", "J", "K", "Q", "init_esm", "import_react", "getScrollPercentage", "scrollTop", "scrollHeight", "getScrollHeight", "winHeight", "percent", "usePageDurationTracker", "scrollDepthRef", "location", "useLocation", "params", "useParams", "paramsRef", "usePrevious", "onScroll", "sPercent", "useOnWindowScroll", "timeEvent", "pageParams", "payload", "trackEvent", "init_esm", "import_react", "usePageViewTracker", "location", "useLocation", "params", "useParams", "paramsRef", "usePrevious", "prevLocationRef", "payload", "toAnalyticsEventPayload", "trackPageView", "init_esm", "import_react", "useSessionDurationTracker", "location", "useLocation", "initialLocationRef", "usePrevious", "timeEvent", "landingUrl", "createPath", "payload", "trackEvent", "useSessionDurationTracker_default", "useAnalyticsStoreEffect", "setParams", "useAnalyticsStore", "state", "location", "useLocation", "prevLocationRef", "usePrevious", "previousUrl", "createPath", "useAnalyticsInitEffect", "env", "ttTester", "sessionInfo", "MIXPANEL_PROJECT_TOKEN", "MIXPANEL_PROXY_DOMAIN", "MIXPANEL_DEBUG_MODE", "NODE_ENV", "session", "mixpanel", "id", "rest", "initializeAnalytics", "useAnalyticsUserEffect", "currentUser", "userId", "simpleId", "isAnonymous", "isNil_default", "setGlobalProperties", "setUser", "setUserProperties", "useGtagEffect", "GTAG_HOST", "GTAG_ID", "GTAG_JS_URL", "ORGANIZATION", "loadScript", "useRUMEffect", "w", "trackWebVitalMetric", "Q", "j", "S", "G", "useGtmEffect", "GTM_ID", "isEmpty_default", "GTM_JS_URL", "useClartiyEffect", "user", "CLARITY_TOKEN", "externalUserId", "sessionId", "landingUrl", "CLARITY_URL", "useClientFPEffect", "ENABLE_FP_PRO", "FP_PRO_KEY", "FP_PRO_REGION", "fpData", "initializeFingerprintProProxy", "LocalStorage", "initializeFingerprintV3", "fp", "generateV0Fp", "useAnalyticsEffect", "usePageViewTracker", "usePageDurationTracker", "useSessionDurationTracker_default", "import_react", "getFirebaseConfig", "env", "setupFirebase", "config", "module", "initializeApp", "error", "Logger", "useFirebaseEffect", "context", "useFirebaseEffect_default", "useDebugHelpers", "currentUser", "sessionInfo", "searchParams", "useSearchParams", "isTester", "LocalStorage", "injectEnvs", "env", "useAppLaunchEffect", "context", "useFirebaseEffect_default", "useAnalyticsEffect", "useAppLaunchEffect_default", "import_jsx_runtime", "minifyCSS", "css", "getBrowserEnv", "context", "env", "GTAG_HOST", "GTAG_ID", "ORGANIZATION", "API_HOST", "GTM_ID", "placeholders", "populate", "cachedCss", "loaderGen", "mainCss", "request", "populateEnvs", "isMobile", "axios_default", "App", "colors", "routes", "title", "cssHref", "svgHref", "description", "head", "widgets", "body", "dehydratedState", "queryClient", "QueryClient", "env", "currentUser", "sessionInfo", "ttTester", "isMobile", "serverTime", "css", "currentCookies", "useLoaderData", "useAppLaunchEffect_default", "memoOIB", "OIB_default", "Meta", "Links", "Fingerprints_default", "RootProvider", "Transition_default", "ThemeProvider", "ElemasonRemixProvider", "QueryClientProvider", "HydrationBoundary", "Outlet", "ScrollRestoration", "Scripts", "LiveReload", "import_react", "colors", "routes_default", "import_jsx_runtime", "description", "meta", "data", "Body", "links", "App", "routes_default", "main_default", "generateTWColors", "colors", "loader", "loaderGen", "ErrorBoundary", "error", "useRouteError", "captureRemixErrorBoundaryError", "Logger", "root_default", "App"] }