{ "version": 3, "sources": ["../../../ui/node_modules/@babel/runtime/helpers/typeof.js", "../../../ui/node_modules/@babel/runtime/helpers/regeneratorRuntime.js", "../../../ui/node_modules/@babel/runtime/regenerator/index.js", "../../../ui/node_modules/react/cjs/react.production.min.js", "../../../ui/node_modules/react/index.js", "../../../ui/node_modules/tiny-emitter/index.js", "../../../ui/node_modules/cross-fetch/dist/browser-ponyfill.js", "../../../ui/node_modules/p-cancelable/index.js", "../../../ui/node_modules/scheduler/cjs/scheduler.production.min.js", "../../../ui/node_modules/scheduler/index.js", "../../../ui/node_modules/react-dom/cjs/react-dom.production.min.js", "../../../ui/node_modules/react-dom/index.js", "../../../ui/node_modules/react-dom/client.js", "../../../ui/node_modules/classnames/index.js", "../../../ui/node_modules/react/cjs/react-jsx-runtime.production.min.js", "../../../ui/node_modules/react/jsx-runtime.js", "../../../ui/node_modules/json-logic-js/logic.js", "../../../ui/node_modules/react-is/cjs/react-is.production.min.js", "../../../ui/node_modules/react-is/index.js", "../../../ui/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js", "../../../ui/node_modules/prop-types/lib/ReactPropTypesSecret.js", "../../../ui/node_modules/prop-types/factoryWithThrowingShims.js", "../../../ui/node_modules/prop-types/index.js", "../../../ui/node_modules/react-avatar-editor/dist/index.js", "../../../ui/node_modules/lodash.debounce/index.js", "../../../ui/node_modules/invariant/browser.js", "../../../ui/node_modules/odometer/odometer.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/arrayLikeToArray.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/unsupportedIterableToArray.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/slicedToArray.js", "../../../ui/node_modules/@okta/src/OktaContext.ts", "../../../ui/node_modules/@okta/src/OktaError.tsx", "../../../ui/node_modules/@okta/src/Security.tsx", "../../../ui/node_modules/@okta/src/withOktaAuth.tsx", "../../../ui/node_modules/@okta/src/LoginCallback.tsx", "../../../ui/node_modules/@okta/src/SecureRoute.tsx", "../../../ui/node_modules/@okta/lib/idx/types/api.ts", "../../../ui/node_modules/@okta/lib/util/console.ts", "../../../ui/node_modules/@okta/lib/util/object.ts", "../../../ui/node_modules/@okta/lib/errors/CustomError.ts", "../../../ui/node_modules/@okta/lib/util/types.ts", "../../../ui/node_modules/@okta/lib/errors/WWWAuthError.ts", "../../../ui/node_modules/@okta/lib/util/misc.ts", "../../../ui/node_modules/@okta/lib/util/url.ts", "../../../ui/node_modules/@okta/lib/errors/AuthSdkError.ts", "../../../ui/node_modules/@okta/lib/oidc/util/oauth.ts", "../../../ui/node_modules/@okta/lib/oidc/util/oauthMeta.ts", "../../../ui/node_modules/js-cookie/dist/js.cookie.mjs", "../../../ui/node_modules/@okta/lib/oidc/types/Token.ts", "../../../ui/node_modules/@okta/lib/idx/transactionMeta.ts", "../../../ui/node_modules/@okta/lib/constants.ts", "../../../ui/node_modules/@okta/lib/errors/AuthApiError.ts", "../../../ui/node_modules/@okta/lib/errors/OAuthError.ts", "../../../ui/node_modules/@okta/lib/http/request.ts", "../../../ui/node_modules/@okta/lib/idx/interact.ts", "../../../ui/node_modules/@okta/okta-auth-js/esm/browser/_virtual/_tslib.js", "../../../ui/node_modules/@okta/lib/idx/idxState/v1/actionParser.ts", "../../../ui/node_modules/@okta/lib/idx/idxState/v1/generateIdxAction.ts", "../../../ui/node_modules/@okta/lib/idx/idxState/v1/remediationParser.ts", "../../../ui/node_modules/@okta/lib/util/jsonpath.ts", "../../../ui/node_modules/@okta/lib/idx/idxState/v1/idxResponseParser.ts", "../../../ui/node_modules/@okta/lib/idx/idxState/v1/makeIdxState.ts", "../../../ui/node_modules/@okta/lib/idx/idxState/v1/parsers.ts", "../../../ui/node_modules/@okta/lib/idx/idxState/index.ts", "../../../ui/node_modules/@okta/lib/idx/types/idx-js.ts", "../../../ui/node_modules/@okta/lib/errors/index.ts", "../../../ui/node_modules/@okta/lib/idx/introspect.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/util.ts", "../../../ui/node_modules/@okta/lib/idx/authenticator/util.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/Base/Remediator.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/GenericRemediator/util.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/GenericRemediator/GenericRemediator.ts", "../../../ui/node_modules/@okta/lib/idx/util.ts", "../../../ui/node_modules/@okta/lib/idx/remediate.ts", "../../../ui/node_modules/@okta/lib/idx/run.ts", "../../../ui/node_modules/@okta/lib/idx/authenticate.ts", "../../../ui/node_modules/@okta/lib/idx/authenticator/Authenticator.ts", "../../../ui/node_modules/@okta/lib/idx/authenticator/VerificationCodeAuthenticator.ts", "../../../ui/node_modules/@okta/lib/idx/authenticator/OktaVerifyTotp.ts", "../../../ui/node_modules/@okta/lib/idx/authenticator/OktaPassword.ts", "../../../ui/node_modules/@okta/lib/idx/authenticator/SecurityQuestionEnrollment.ts", "../../../ui/node_modules/@okta/lib/idx/authenticator/SecurityQuestionVerification.ts", "../../../ui/node_modules/@okta/lib/idx/authenticator/WebauthnEnrollment.ts", "../../../ui/node_modules/@okta/lib/idx/authenticator/WebauthnVerification.ts", "../../../ui/node_modules/@okta/lib/idx/authenticator/getAuthenticator.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/Base/VerifyAuthenticator.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/EnrollAuthenticator.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/EnrollPoll.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/SelectEnrollmentChannel.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/EnrollmentChannelData.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/ChallengeAuthenticator.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/ChallengePoll.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/ResetAuthenticator.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/EnrollProfile.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/Identify.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/ReEnrollAuthenticator.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/ReEnrollAuthenticatorWarning.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/RedirectIdp.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/Base/SelectAuthenticator.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/SelectAuthenticatorAuthenticate.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/SelectAuthenticatorEnroll.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/SelectAuthenticatorUnlockAccount.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/SelectEnrollProfile.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/Base/AuthenticatorData.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/AuthenticatorVerificationData.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/AuthenticatorEnrollmentData.ts", "../../../ui/node_modules/@okta/lib/idx/remediators/Skip.ts", "../../../ui/node_modules/@okta/lib/idx/flow/AuthenticationFlow.ts", "../../../ui/node_modules/@okta/lib/idx/flow/PasswordRecoveryFlow.ts", "../../../ui/node_modules/@okta/lib/idx/flow/RegistrationFlow.ts", "../../../ui/node_modules/@okta/lib/idx/flow/AccountUnlockFlow.ts", "../../../ui/node_modules/@okta/lib/idx/flow/FlowSpecification.ts", "../../../ui/node_modules/@okta/lib/idx/cancel.ts", "../../../ui/node_modules/@okta/lib/oidc/util/urlParams.ts", "../../../ui/node_modules/@okta/lib/idx/emailVerify.ts", "../../../ui/node_modules/@okta/lib/idx/proceed.ts", "../../../ui/node_modules/@okta/lib/idx/poll.ts", "../../../ui/node_modules/@okta/lib/idx/startTransaction.ts", "../../../ui/node_modules/@okta/lib/idx/register.ts", "../../../ui/node_modules/@okta/lib/idx/recoverPassword.ts", "../../../ui/node_modules/@okta/lib/idx/handleInteractionCodeRedirect.ts", "../../../ui/node_modules/@okta/lib/idx/unlockAccount.ts", "../../../ui/node_modules/@okta/lib/oidc/util/errors.ts", "../../../ui/node_modules/@okta/lib/oidc/util/loginRedirect.ts", "../../../ui/node_modules/@okta/okta-auth-js/esm/browser/idx/remediators/index.js", "../../../ui/node_modules/@okta/lib/idx/factory/api.ts", "../../../ui/node_modules/@okta/lib/crypto/browser.ts", "../../../ui/node_modules/@okta/lib/features.ts", "../../../ui/node_modules/@okta/lib/base/factory.ts", "../../../ui/node_modules/@okta/lib/storage/mixin.ts", "../../../ui/node_modules/@okta/lib/http/OktaUserAgent.ts", "../../../ui/node_modules/@okta/lib/http/headers.ts", "../../../ui/node_modules/@okta/lib/http/mixin.ts", "../../../ui/node_modules/@okta/okta-auth-js/esm/browser/crypto/index.js", "../../../ui/node_modules/@okta/lib/crypto/base64.ts", "../../../ui/node_modules/@okta/lib/crypto/oidcHash.ts", "../../../ui/node_modules/@okta/lib/crypto/verifyToken.ts", "../../../ui/node_modules/@okta/lib/util/PromiseQueue.ts", "../../../ui/node_modules/@okta/lib/oidc/util/pkce.ts", "../../../ui/node_modules/@okta/lib/oidc/decodeToken.ts", "../../../ui/node_modules/@okta/lib/oidc/util/defaultTokenParams.ts", "../../../ui/node_modules/@okta/lib/oidc/dpop.ts", "../../../ui/node_modules/@okta/lib/oidc/endpoints/token.ts", "../../../ui/node_modules/@okta/lib/oidc/endpoints/well-known.ts", "../../../ui/node_modules/@okta/lib/oidc/util/validateClaims.ts", "../../../ui/node_modules/@okta/lib/oidc/verifyToken.ts", "../../../ui/node_modules/@okta/lib/oidc/handleOAuthResponse.ts", "../../../ui/node_modules/@okta/lib/oidc/exchangeCodeForTokens.ts", "../../../ui/node_modules/@okta/lib/oidc/getUserInfo.ts", "../../../ui/node_modules/@okta/lib/oidc/util/browser.ts", "../../../ui/node_modules/@okta/lib/oidc/util/prepareTokenParams.ts", "../../../ui/node_modules/@okta/lib/oidc/endpoints/authorize.ts", "../../../ui/node_modules/@okta/lib/oidc/getToken.ts", "../../../ui/node_modules/@okta/lib/oidc/getWithoutPrompt.ts", "../../../ui/node_modules/@okta/lib/oidc/getWithPopup.ts", "../../../ui/node_modules/@okta/lib/oidc/getWithRedirect.ts", "../../../ui/node_modules/@okta/lib/oidc/parseFromUrl.ts", "../../../ui/node_modules/@okta/lib/oidc/util/refreshToken.ts", "../../../ui/node_modules/@okta/lib/oidc/renewTokensWithRefresh.ts", "../../../ui/node_modules/@okta/lib/oidc/renewToken.ts", "../../../ui/node_modules/@okta/lib/oidc/renewTokens.ts", "../../../ui/node_modules/@okta/lib/oidc/revokeToken.ts", "../../../ui/node_modules/@okta/lib/oidc/introspect.ts", "../../../ui/node_modules/@okta/lib/oidc/util/enrollAuthenticatorMeta.ts", "../../../ui/node_modules/@okta/lib/oidc/util/defaultEnrollAuthenticatorParams.ts", "../../../ui/node_modules/@okta/lib/oidc/util/prepareEnrollAuthenticatorParams.ts", "../../../ui/node_modules/@okta/lib/oidc/enrollAuthenticator.ts", "../../../ui/node_modules/@okta/lib/oidc/factory/api.ts", "../../../ui/node_modules/@okta/lib/oidc/util/validateToken.ts", "../../../ui/node_modules/@okta/lib/clock.ts", "../../../ui/node_modules/@okta/lib/oidc/types/TokenManager.ts", "../../../ui/node_modules/@okta/lib/oidc/TokenManager.ts", "../../../ui/node_modules/@okta/lib/browser/browserStorage.ts", "../../../ui/node_modules/@okta/lib/oidc/mixin/browser.ts", "../../../ui/node_modules/@okta/lib/oidc/mixin/index.ts", "../../../ui/node_modules/@okta/lib/core/AuthStateManager.ts", "../../../ui/node_modules/@okta/lib/services/AutoRenewService.ts", "../../../ui/node_modules/broadcast-channel/dist/esbrowser/util.js", "../../../ui/node_modules/broadcast-channel/dist/esbrowser/methods/native.js", "../../../ui/node_modules/oblivious-set/src/index.ts", "../../../ui/node_modules/broadcast-channel/dist/esbrowser/options.js", "../../../ui/node_modules/broadcast-channel/dist/esbrowser/methods/indexed-db.js", "../../../ui/node_modules/broadcast-channel/dist/esbrowser/methods/localstorage.js", "../../../ui/node_modules/broadcast-channel/dist/esbrowser/methods/simulate.js", "../../../ui/node_modules/broadcast-channel/dist/esbrowser/method-chooser.js", "../../../ui/node_modules/broadcast-channel/dist/esbrowser/broadcast-channel.js", "../../../ui/node_modules/unload/dist/es/browser.js", "../../../ui/node_modules/unload/dist/es/node.js", "../../../ui/node_modules/unload/dist/es/index.js", "../../../ui/node_modules/broadcast-channel/dist/esbrowser/leader-election-util.js", "../../../ui/node_modules/broadcast-channel/dist/esbrowser/leader-election-web-lock.js", "../../../ui/node_modules/broadcast-channel/dist/esbrowser/leader-election.js", "../../../ui/node_modules/@okta/lib/services/SyncStorageService.ts", "../../../ui/node_modules/@okta/lib/services/LeaderElectionService.ts", "../../../ui/node_modules/@okta/lib/services/RenewOnTabActivationService.ts", "../../../ui/node_modules/@okta/lib/core/ServiceManager/browser.ts", "../../../ui/node_modules/@okta/lib/core/mixin.ts", "../../../ui/node_modules/@okta/lib/session/api.ts", "../../../ui/node_modules/@okta/lib/session/factory.ts", "../../../ui/node_modules/@okta/lib/session/mixin.ts", "../../../ui/node_modules/@okta/lib/core/factory.ts", "../../../ui/node_modules/@okta/lib/browser/fingerprint.ts", "../../../ui/node_modules/@okta/lib/idx/webauthn.ts", "../../../ui/node_modules/@okta/lib/idx/mixin.ts", "../../../ui/node_modules/@okta/lib/idx/factory/OktaAuthIdx.ts", "../../../ui/node_modules/@okta/lib/base/options.ts", "../../../ui/node_modules/@okta/lib/storage/options/browser.ts", "../../../ui/node_modules/@okta/lib/storage/options/StorageOptionsConstructor.ts", "../../../ui/node_modules/@okta/lib/fetch/fetchRequest.ts", "../../../ui/node_modules/@okta/lib/http/options.ts", "../../../ui/node_modules/@okta/lib/oidc/options/OAuthOptionsConstructor.ts", "../../../ui/node_modules/@okta/lib/core/options.ts", "../../../ui/node_modules/@okta/lib/idx/options.ts", "../../../ui/node_modules/@okta/lib/storage/SavedObject.ts", "../../../ui/node_modules/@okta/lib/storage/BaseStorageManager.ts", "../../../ui/node_modules/@okta/lib/oidc/storage.ts", "../../../ui/node_modules/@okta/lib/core/storage.ts", "../../../ui/node_modules/@okta/lib/idx/storage.ts", "../../../ui/node_modules/@okta/lib/oidc/types/Transaction.ts", "../../../ui/node_modules/@okta/lib/oidc/util/sharedStorage.ts", "../../../ui/node_modules/@okta/lib/oidc/TransactionManager.ts", "../../../ui/node_modules/@okta/lib/idx/IdxTransactionManager.ts", "../../../ui/node_modules/@okta/lib/myaccount/transactions/Base.ts", "../../../ui/node_modules/@okta/lib/myaccount/request.ts", "../../../ui/node_modules/@okta/lib/myaccount/transactions/ProfileTransaction.ts", "../../../ui/node_modules/@okta/lib/myaccount/transactions/ProfileSchemaTransaction.ts", "../../../ui/node_modules/@okta/lib/myaccount/types.ts", "../../../ui/node_modules/@okta/lib/myaccount/profileApi.ts", "../../../ui/node_modules/@okta/lib/myaccount/transactions/EmailStatusTransaction.ts", "../../../ui/node_modules/@okta/lib/myaccount/transactions/EmailChallengeTransaction.ts", "../../../ui/node_modules/@okta/lib/myaccount/transactions/EmailTransaction.ts", "../../../ui/node_modules/@okta/lib/myaccount/emailApi.ts", "../../../ui/node_modules/@okta/lib/myaccount/transactions/PhoneTransaction.ts", "../../../ui/node_modules/@okta/lib/myaccount/phoneApi.ts", "../../../ui/node_modules/@okta/lib/myaccount/transactions/PasswordTransaction.ts", "../../../ui/node_modules/@okta/lib/myaccount/passwordApi.ts", "../../../ui/node_modules/@okta/okta-auth-js/esm/browser/myaccount/api.js", "../../../ui/node_modules/@okta/lib/myaccount/mixin.ts", "../../../ui/node_modules/@okta/lib/authn/util/stateToken.ts", "../../../ui/node_modules/@okta/lib/authn/api.ts", "../../../ui/node_modules/@okta/lib/authn/util/link2fn.ts", "../../../ui/node_modules/@okta/lib/errors/AuthPollStopError.ts", "../../../ui/node_modules/@okta/lib/authn/util/poll.ts", "../../../ui/node_modules/@okta/lib/authn/util/links2fns.ts", "../../../ui/node_modules/@okta/lib/authn/util/flattenEmbedded.ts", "../../../ui/node_modules/@okta/lib/authn/AuthnTransactionImpl.ts", "../../../ui/node_modules/@okta/lib/authn/factory.ts", "../../../ui/node_modules/@okta/lib/authn/mixin.ts", "../../../ui/node_modules/@okta/lib/exports/default.ts", "../../../ui/node_modules/compare-versions/index.mjs", "../../../ui/node_modules/@babel/runtime/helpers/esm/typeof.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/toPrimitive.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/toPropertyKey.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/defineProperty.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js", "../../../ui/node_modules/@remix-run/router/history.ts", "../../../ui/node_modules/@remix-run/router/utils.ts", "../../../ui/node_modules/@remix-run/router/router.ts", "../../../ui/node_modules/react-router/lib/context.ts", "../../../ui/node_modules/react-router/lib/hooks.tsx", "../../../ui/node_modules/react-router/lib/components.tsx", "../../../ui/node_modules/react-router/index.ts", "../../../ui/node_modules/react-router-dom/dom.ts", "../../../ui/node_modules/react-router-dom/index.tsx", "../../../ui/src/main.tsx", "../../../ui/src/Loading.tsx", "../../../ui/src/constants.ts", "../../../ui/src/okta.ts", "../../../ui/src/ProtectedApp.tsx", "../../../ui/src/SecureRoute.tsx", "../../../ui/src/translations/english.ts", "../../../ui/src/translations/translations.ts", "../../../ui/src/common/AppProvider.tsx", "../../../ui/src/api.ts", "../../../ui/src/pendo.ts", "../../../ui/src/storage.ts", "../../../ui/src/utils/utils.ts", "../../../ui/node_modules/@boomi/exosphere/dist/react/accordion/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/createReactComponent-58f9bea8.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/property-9daa16cd.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/class-map-2994e95e.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/icon-20d7c313.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/base-e16d29d8.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/query-d94c86d2.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/button-7600b6ca.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/tooltip-a9885c40.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/icon-button-5cbe6df0.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/dialog/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/helpers-770f41c9.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/slot-controller-fa97ce97.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/card/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/tile/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/if-defined-47693dfa.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/state-7560d4dc.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/dropdown-c2227eb7.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/toggle/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/radio-dc6c080b.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/radio-group/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/checkbox-a99697a0.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/style-map-c3339321.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/loader-33afc335.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/menu-3df3d7c3.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/menu-item-c52ff6c2.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/live-6c85dd15.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/purify.es-295db11b.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/pill-0e505c8d.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/pill-group-9b613185.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/menu-item-group-b8ae84a0.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/leftmenubar/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/avatar-e534285e.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/segmentedcontrol-362be3d5.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/segmentedcontrols/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/alert-banner/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/alert-toast/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/file-uploader/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/alert-popup/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/pagination/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/table/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/query-async-a940115b.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/textarea-ee3d82e5.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/side-drawer/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/structured-list/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/tab/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/tab-item/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/chart/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/breadcrumb/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/breadcrumb-item/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/date-picker-eacf03bc.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/page-header/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/empty-state/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/link-cd38e97f.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/filter/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/navigationdrawer/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/combobox/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/json-editor/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/_commonjsHelpers-10dfc225.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/rich-text-editor/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/tree/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/carousel/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/wizard/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/badge/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/checkbox-group/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/container/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/resize-handle/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/rich-input/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/rich-input-suggestion-ae5d08aa.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/footer/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/footer-link-group/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/footer-link/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/time-range-picker/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/button/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/icon/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/icon-button/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/dropdown/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/radio/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/checkbox/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/loader/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/menu/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/menu-item/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/input/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/select/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/tooltip/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/textarea/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/pill/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/segmentedcontrol/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/date-picker/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/menu-item-group/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/avatar/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/link/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/rich-input-suggestion/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/pill-group/index.mjs", "../../../ui/node_modules/@boomi/exosphere/dist/react/index.mjs", "../../../ui/src/alertPopups/AlertPopup.tsx", "../../../ui/src/alertPopups/AlertPopupList.tsx", "../../../ui/src/common/Content.tsx", "../../../ui/src/common/Footer.tsx", "../../../ui/src/common/TaskAutomationHeader.tsx", "../../../ui/src/common/AnimatedLink.tsx", "../../../ui/src/common/BoomiNavigationMenu.tsx", "../../../ui/src/common/BoomiNavigationMenuLinks.ts", "../../../ui/src/common/BoomiNavigationMenuMobile.tsx", "../../../ui/src/connections/Connections.tsx", "../../../ui/src/common/TextWithArrows.tsx", "../../../ui/src/common/ItemList.tsx", "../../../ui/src/connections/AuthenticatedConnector.tsx", "../../../ui/src/common/ConfirmAction.tsx", "../../../ui/src/common/FlipCard.tsx", "../../../ui/src/common/IconCircle.tsx", "../../../ui/src/notifications/Notifications.tsx", "../../../ui/node_modules/@babel/runtime/helpers/esm/objectSpread2.js", "../../../ui/node_modules/react-select/dist/useStateManager-7e1e8489.esm.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/extends.js", "../../../ui/node_modules/react-select/dist/react-select.esm.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/classCallCheck.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/createClass.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/inherits.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/isNativeReflectConstruct.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/createSuper.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/iterableToArray.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js", "../../../ui/node_modules/react-select/dist/Select-1b4bdd99.esm.js", "../../../ui/node_modules/@emotion/react/dist/emotion-element-5486c51c.browser.esm.js", "../../../ui/node_modules/@emotion/sheet/dist/emotion-sheet.esm.js", "../../../ui/node_modules/stylis/src/Enum.js", "../../../ui/node_modules/stylis/src/Utility.js", "../../../ui/node_modules/stylis/src/Tokenizer.js", "../../../ui/node_modules/stylis/src/Parser.js", "../../../ui/node_modules/stylis/src/Serializer.js", "../../../ui/node_modules/stylis/src/Middleware.js", "../../../ui/node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js", "../../../ui/node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js", "../../../ui/node_modules/@emotion/hash/dist/emotion-hash.esm.js", "../../../ui/node_modules/@emotion/serialize/node_modules/@emotion/unitless/dist/emotion-unitless.esm.js", "../../../ui/node_modules/@emotion/serialize/node_modules/@emotion/memoize/dist/emotion-memoize.esm.js", "../../../ui/node_modules/@emotion/serialize/dist/emotion-serialize.esm.js", "../../../ui/node_modules/@emotion/use-insertion-effect-with-fallbacks/dist/emotion-use-insertion-effect-with-fallbacks.browser.esm.js", "../../../ui/node_modules/@emotion/react/dist/emotion-react.browser.esm.js", "../../../ui/node_modules/@babel/runtime/helpers/esm/taggedTemplateLiteral.js", "../../../ui/node_modules/react-select/dist/index-baa8dc4f.esm.js", "../../../ui/node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs", "../../../ui/node_modules/@floating-ui/utils/dom/dist/floating-ui.utils.dom.mjs", "../../../ui/node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs", "../../../ui/node_modules/use-isomorphic-layout-effect/dist/use-isomorphic-layout-effect.browser.esm.js", "../../../ui/node_modules/memoize-one/dist/memoize-one.esm.js", "../../../ui/src/notifications/NotificationItem.tsx", "../../../ui/src/common/Indicator.tsx", "../../../ui/src/profile/Profile.tsx", "../../../ui/src/task-editor/TaskEditor.tsx", "../../../ui/src/task-editor/Drawer.tsx", "../../../ui/src/task-editor/TaskEditorFooter.tsx", "../../../ui/src/task-editor/TaskEditorHeader.tsx", "../../../ui/src/common/Toggle.tsx", "../../../ui/src/task-editor/AutosizeInput.tsx", "../../../ui/src/task-editor/TriggerOrActionDrawerManager.tsx", "../../../ui/src/hooks/useAuthentication.tsx", "../../../ui/src/task-editor/ConnectorPicker.tsx", "../../../ui/src/task-editor/SelectedConnector.tsx", "../../../ui/src/task-editor/TriggerOrActionConfiguration.tsx", "../../../ui/src/task-editor/Option.tsx", "../../../ui/src/task-editor/optionFields/ExoField.tsx", "../../../ui/node_modules/@phosphor-icons/react/dist/lib/context.mjs", "../../../ui/node_modules/@phosphor-icons/react/dist/lib/IconBase.mjs", "../../../ui/node_modules/@phosphor-icons/react/dist/defs/At.mjs", "../../../ui/node_modules/@phosphor-icons/react/dist/defs/ClockClockwise.mjs", "../../../ui/node_modules/@phosphor-icons/react/dist/defs/ClockCounterClockwise.mjs", "../../../ui/node_modules/@phosphor-icons/react/dist/defs/Warning.mjs", "../../../ui/node_modules/@phosphor-icons/react/dist/csr/At.mjs", "../../../ui/node_modules/@phosphor-icons/react/dist/csr/ClockClockwise.mjs", "../../../ui/node_modules/@phosphor-icons/react/dist/csr/ClockCounterClockwise.mjs", "../../../ui/node_modules/@phosphor-icons/react/dist/csr/Warning.mjs", "../../../ui/src/task-editor/optionFields/TimeOffset.tsx", "../../../ui/src/task-editor/optionFields/NumberField.tsx", "../../../ui/src/task-editor/optionFields/SelectButtonsField.tsx", "../../../ui/src/task-editor/optionFields/SelectField.tsx", "../../../ui/src/task-editor/optionFields/InputWithTokens.tsx", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/iterableToArray.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/toConsumableArray.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/extends.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/classCallCheck.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/createClass.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/inherits.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/typeof.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/defineProperty.js", "../../../ui/node_modules/react-mentions/dist/react-mentions.esm.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/nonIterableRest.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/slicedToArray.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js", "../../../ui/node_modules/react-mentions/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js", "../../../ui/node_modules/substyle/es6/PropsDecoratorProvider.js", "../../../ui/node_modules/substyle/es6/utils.js", "../../../ui/node_modules/substyle/es6/filterKeys.js", "../../../ui/node_modules/substyle/es6/pickStyles.js", "../../../ui/node_modules/substyle/es6/defaultPropsDecorator.js", "../../../ui/node_modules/substyle/es6/createSubstyle.js", "../../../ui/node_modules/substyle/es6/coerceSelection.js", "../../../ui/node_modules/substyle/es6/memoize.js", "../../../ui/node_modules/substyle/es6/inline.js", "../../../ui/node_modules/substyle/es6/useStyles.js", "../../../ui/node_modules/substyle/es6/index.js", "../../../ui/src/task-editor/optionFields/StringField.tsx", "../../../ui/src/task-editor/optionFields/StringMultiLineField.tsx", "../../../ui/src/task-editor/optionFields/triggerOptionFieldRegistry.ts", "../../../ui/src/task-editor/TriggerOrActionPicker.tsx", "../../../ui/src/task-editor/TriggerOrActionSummary.tsx", "../../../ui/src/task-editor/taskReducer.ts", "../../../ui/src/taskLogs/TaskLogs.tsx", "../../../ui/src/tasks-new/NewTaskBuilder.tsx", "../../../ui/src/common/TaskItemPicker.tsx", "../../../ui/src/tasks/Tasks.tsx", "../../../ui/node_modules/react-odometerjs/dist/index.js", "../../../ui/src/tasks/StatInfo.tsx", "../../../ui/src/tasks/TaskNotificationBar.tsx", "../../../ui/src/tasks/TaskItem.tsx", "../../../ui/src/tasks/TasksFilters.tsx", "../../../ui/src/hooks/useMobile.ts", "../../../ui/src/tasks/WelcomeBanner.tsx", "../../../ui/src/webhooks/webhooks.tsx"], "sourcesContent": ["function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return (module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports), _typeof(obj);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction _regeneratorRuntime() {\n \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */\n module.exports = _regeneratorRuntime = function _regeneratorRuntime() {\n return exports;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;\n var exports = {},\n Op = Object.prototype,\n hasOwn = Op.hasOwnProperty,\n defineProperty = Object.defineProperty || function (obj, key, desc) {\n obj[key] = desc.value;\n },\n $Symbol = \"function\" == typeof Symbol ? Symbol : {},\n iteratorSymbol = $Symbol.iterator || \"@@iterator\",\n asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\",\n toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n function define(obj, key, value) {\n return Object.defineProperty(obj, key, {\n value: value,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }), obj[key];\n }\n try {\n define({}, \"\");\n } catch (err) {\n define = function define(obj, key, value) {\n return obj[key] = value;\n };\n }\n function wrap(innerFn, outerFn, self, tryLocsList) {\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,\n generator = Object.create(protoGenerator.prototype),\n context = new Context(tryLocsList || []);\n return defineProperty(generator, \"_invoke\", {\n value: makeInvokeMethod(innerFn, self, context)\n }), generator;\n }\n function tryCatch(fn, obj, arg) {\n try {\n return {\n type: \"normal\",\n arg: fn.call(obj, arg)\n };\n } catch (err) {\n return {\n type: \"throw\",\n arg: err\n };\n }\n }\n exports.wrap = wrap;\n var ContinueSentinel = {};\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n var getProto = Object.getPrototypeOf,\n NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);\n var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function (method) {\n define(prototype, method, function (arg) {\n return this._invoke(method, arg);\n });\n });\n }\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (\"throw\" !== record.type) {\n var result = record.arg,\n value = result.value;\n return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) {\n invoke(\"next\", value, resolve, reject);\n }, function (err) {\n invoke(\"throw\", err, resolve, reject);\n }) : PromiseImpl.resolve(value).then(function (unwrapped) {\n result.value = unwrapped, resolve(result);\n }, function (error) {\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n reject(record.arg);\n }\n var previousPromise;\n defineProperty(this, \"_invoke\", {\n value: function value(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function (resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();\n }\n });\n }\n function makeInvokeMethod(innerFn, self, context) {\n var state = \"suspendedStart\";\n return function (method, arg) {\n if (\"executing\" === state) throw new Error(\"Generator is already running\");\n if (\"completed\" === state) {\n if (\"throw\" === method) throw arg;\n return {\n value: void 0,\n done: !0\n };\n }\n for (context.method = method, context.arg = arg;;) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) {\n if (\"suspendedStart\" === state) throw state = \"completed\", context.arg;\n context.dispatchException(context.arg);\n } else \"return\" === context.method && context.abrupt(\"return\", context.arg);\n state = \"executing\";\n var record = tryCatch(innerFn, self, context);\n if (\"normal\" === record.type) {\n if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue;\n return {\n value: record.arg,\n done: context.done\n };\n }\n \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg);\n }\n };\n }\n function maybeInvokeDelegate(delegate, context) {\n var methodName = context.method,\n method = delegate.iterator[methodName];\n if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel;\n var record = tryCatch(method, delegate.iterator, context.arg);\n if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel;\n var info = record.arg;\n return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel);\n }\n function pushTryEntry(locs) {\n var entry = {\n tryLoc: locs[0]\n };\n 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);\n }\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\", delete record.arg, entry.completion = record;\n }\n function Context(tryLocsList) {\n this.tryEntries = [{\n tryLoc: \"root\"\n }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);\n }\n function values(iterable) {\n if (iterable || \"\" === iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) return iteratorMethod.call(iterable);\n if (\"function\" == typeof iterable.next) return iterable;\n if (!isNaN(iterable.length)) {\n var i = -1,\n next = function next() {\n for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;\n return next.value = undefined, next.done = !0, next;\n };\n return next.next = next;\n }\n }\n throw new TypeError(_typeof(iterable) + \" is not iterable\");\n }\n return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", {\n value: GeneratorFunctionPrototype,\n configurable: !0\n }), defineProperty(GeneratorFunctionPrototype, \"constructor\", {\n value: GeneratorFunction,\n configurable: !0\n }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) {\n var ctor = \"function\" == typeof genFun && genFun.constructor;\n return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name));\n }, exports.mark = function (genFun) {\n return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun;\n }, exports.awrap = function (arg) {\n return {\n __await: arg\n };\n }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n void 0 === PromiseImpl && (PromiseImpl = Promise);\n var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);\n return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {\n return result.done ? result.value : iter.next();\n });\n }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () {\n return this;\n }), define(Gp, \"toString\", function () {\n return \"[object Generator]\";\n }), exports.keys = function (val) {\n var object = Object(val),\n keys = [];\n for (var key in object) keys.push(key);\n return keys.reverse(), function next() {\n for (; keys.length;) {\n var key = keys.pop();\n if (key in object) return next.value = key, next.done = !1, next;\n }\n return next.done = !0, next;\n };\n }, exports.values = values, Context.prototype = {\n constructor: Context,\n reset: function reset(skipTempReset) {\n if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);\n },\n stop: function stop() {\n this.done = !0;\n var rootRecord = this.tryEntries[0].completion;\n if (\"throw\" === rootRecord.type) throw rootRecord.arg;\n return this.rval;\n },\n dispatchException: function dispatchException(exception) {\n if (this.done) throw exception;\n var context = this;\n function handle(loc, caught) {\n return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught;\n }\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i],\n record = entry.completion;\n if (\"root\" === entry.tryLoc) return handle(\"end\");\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\"),\n hasFinally = hasOwn.call(entry, \"finallyLoc\");\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n } else {\n if (!hasFinally) throw new Error(\"try statement without catch or finally\");\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n }\n }\n }\n },\n abrupt: function abrupt(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);\n var record = finallyEntry ? finallyEntry.completion : {};\n return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);\n },\n complete: function complete(record, afterLoc) {\n if (\"throw\" === record.type) throw record.arg;\n return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;\n },\n finish: function finish(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;\n }\n },\n \"catch\": function _catch(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (\"throw\" === record.type) {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n throw new Error(\"illegal catch attempt\");\n },\n delegateYield: function delegateYield(iterable, resultName, nextLoc) {\n return this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel;\n }\n }, exports;\n}\nmodule.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;", "// TODO(Babel 8): Remove this file.\n\nvar runtime = require(\"../helpers/regeneratorRuntime\")();\nmodule.exports = runtime;\n\n// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n", "/**\n * @license React\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=Symbol.for(\"react.element\"),n=Symbol.for(\"react.portal\"),p=Symbol.for(\"react.fragment\"),q=Symbol.for(\"react.strict_mode\"),r=Symbol.for(\"react.profiler\"),t=Symbol.for(\"react.provider\"),u=Symbol.for(\"react.context\"),v=Symbol.for(\"react.forward_ref\"),w=Symbol.for(\"react.suspense\"),x=Symbol.for(\"react.memo\"),y=Symbol.for(\"react.lazy\"),z=Symbol.iterator;function A(a){if(null===a||\"object\"!==typeof a)return null;a=z&&a[z]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}\nvar B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};\nE.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(\"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\");this.updater.enqueueSetState(this,a,b,\"setState\")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;\nH.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};\nfunction M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1 -1\n };\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name);\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value);\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift();\n return {done: value === undefined, value: value}\n }\n };\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n };\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {};\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value);\n }, this);\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1]);\n }, this);\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name]);\n }, this);\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name);\n value = normalizeValue(value);\n var oldValue = this.map[name];\n this.map[name] = oldValue ? oldValue + ', ' + value : value;\n };\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)];\n };\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name);\n return this.has(name) ? this.map[name] : null\n };\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n };\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value);\n };\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this);\n }\n }\n };\n\n Headers.prototype.keys = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push(name);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.values = function() {\n var items = [];\n this.forEach(function(value) {\n items.push(value);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.entries = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push([name, value]);\n });\n return iteratorFor(items)\n };\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries;\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true;\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result);\n };\n reader.onerror = function() {\n reject(reader.error);\n };\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsArrayBuffer(blob);\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsText(blob);\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf);\n var chars = new Array(view.length);\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i]);\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength);\n view.set(new Uint8Array(buf));\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false;\n\n this._initBody = function(body) {\n this._bodyInit = body;\n if (!body) {\n this._bodyText = '';\n } else if (typeof body === 'string') {\n this._bodyText = body;\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body;\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body;\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString();\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer);\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer]);\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body);\n } else {\n this._bodyText = body = Object.prototype.toString.call(body);\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8');\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type);\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n }\n }\n };\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n };\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n };\n }\n\n this.text = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n };\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n };\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n };\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase();\n return methods.indexOf(upcased) > -1 ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {};\n var body = options.body;\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url;\n this.credentials = input.credentials;\n if (!options.headers) {\n this.headers = new Headers(input.headers);\n }\n this.method = input.method;\n this.mode = input.mode;\n this.signal = input.signal;\n if (!body && input._bodyInit != null) {\n body = input._bodyInit;\n input.bodyUsed = true;\n }\n } else {\n this.url = String(input);\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin';\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers);\n }\n this.method = normalizeMethod(options.method || this.method || 'GET');\n this.mode = options.mode || this.mode || null;\n this.signal = options.signal || this.signal;\n this.referrer = null;\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body);\n }\n\n Request.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n };\n\n function decode(body) {\n var form = new FormData();\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=');\n var name = split.shift().replace(/\\+/g, ' ');\n var value = split.join('=').replace(/\\+/g, ' ');\n form.append(decodeURIComponent(name), decodeURIComponent(value));\n }\n });\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers();\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ');\n preProcessedHeaders.split(/\\r?\\n/).forEach(function(line) {\n var parts = line.split(':');\n var key = parts.shift().trim();\n if (key) {\n var value = parts.join(':').trim();\n headers.append(key, value);\n }\n });\n return headers\n }\n\n Body.call(Request.prototype);\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {};\n }\n\n this.type = 'default';\n this.status = options.status === undefined ? 200 : options.status;\n this.ok = this.status >= 200 && this.status < 300;\n this.statusText = 'statusText' in options ? options.statusText : 'OK';\n this.headers = new Headers(options.headers);\n this.url = options.url || '';\n this._initBody(bodyInit);\n }\n\n Body.call(Response.prototype);\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n };\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''});\n response.type = 'error';\n return response\n };\n\n var redirectStatuses = [301, 302, 303, 307, 308];\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n };\n\n exports.DOMException = self.DOMException;\n try {\n new exports.DOMException();\n } catch (err) {\n exports.DOMException = function(message, name) {\n this.message = message;\n this.name = name;\n var error = Error(message);\n this.stack = error.stack;\n };\n exports.DOMException.prototype = Object.create(Error.prototype);\n exports.DOMException.prototype.constructor = exports.DOMException;\n }\n\n function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init);\n\n if (request.signal && request.signal.aborted) {\n return reject(new exports.DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest();\n\n function abortXhr() {\n xhr.abort();\n }\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n };\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');\n var body = 'response' in xhr ? xhr.response : xhr.responseText;\n resolve(new Response(body, options));\n };\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.onabort = function() {\n reject(new exports.DOMException('Aborted', 'AbortError'));\n };\n\n xhr.open(request.method, request.url, true);\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true;\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false;\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob';\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value);\n });\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr);\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr);\n }\n };\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);\n })\n }\n\n fetch.polyfill = true;\n\n if (!self.fetch) {\n self.fetch = fetch;\n self.Headers = Headers;\n self.Request = Request;\n self.Response = Response;\n }\n\n exports.Headers = Headers;\n exports.Request = Request;\n exports.Response = Response;\n exports.fetch = fetch;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n return exports;\n\n})({});\n})(__self__);\n__self__.fetch.ponyfill = true;\n// Remove \"polyfill\" property added by whatwg-fetch\ndelete __self__.fetch.polyfill;\n// Choose between native implementation (global) or custom implementation (__self__)\n// var ctx = global.fetch ? global : __self__;\nvar ctx = __self__; // this line disable service worker support temporarily\nexports = ctx.fetch // To enable: import fetch from 'cross-fetch'\nexports.default = ctx.fetch // For TypeScript consumers without esModuleInterop.\nexports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch'\nexports.Headers = ctx.Headers\nexports.Request = ctx.Request\nexports.Response = ctx.Response\nmodule.exports = exports\n", "'use strict';\n\nclass CancelError extends Error {\n\tconstructor(reason) {\n\t\tsuper(reason || 'Promise was canceled');\n\t\tthis.name = 'CancelError';\n\t}\n\n\tget isCanceled() {\n\t\treturn true;\n\t}\n}\n\nclass PCancelable {\n\tstatic fn(userFn) {\n\t\treturn (...arguments_) => {\n\t\t\treturn new PCancelable((resolve, reject, onCancel) => {\n\t\t\t\targuments_.push(onCancel);\n\t\t\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\t\t\tuserFn(...arguments_).then(resolve, reject);\n\t\t\t});\n\t\t};\n\t}\n\n\tconstructor(executor) {\n\t\tthis._cancelHandlers = [];\n\t\tthis._isPending = true;\n\t\tthis._isCanceled = false;\n\t\tthis._rejectOnCancel = true;\n\n\t\tthis._promise = new Promise((resolve, reject) => {\n\t\t\tthis._reject = reject;\n\n\t\t\tconst onResolve = value => {\n\t\t\t\tif (!this._isCanceled || !onCancel.shouldReject) {\n\t\t\t\t\tthis._isPending = false;\n\t\t\t\t\tresolve(value);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst onReject = error => {\n\t\t\t\tthis._isPending = false;\n\t\t\t\treject(error);\n\t\t\t};\n\n\t\t\tconst onCancel = handler => {\n\t\t\t\tif (!this._isPending) {\n\t\t\t\t\tthrow new Error('The `onCancel` handler was attached after the promise settled.');\n\t\t\t\t}\n\n\t\t\t\tthis._cancelHandlers.push(handler);\n\t\t\t};\n\n\t\t\tObject.defineProperties(onCancel, {\n\t\t\t\tshouldReject: {\n\t\t\t\t\tget: () => this._rejectOnCancel,\n\t\t\t\t\tset: boolean => {\n\t\t\t\t\t\tthis._rejectOnCancel = boolean;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn executor(onResolve, onReject, onCancel);\n\t\t});\n\t}\n\n\tthen(onFulfilled, onRejected) {\n\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\treturn this._promise.then(onFulfilled, onRejected);\n\t}\n\n\tcatch(onRejected) {\n\t\treturn this._promise.catch(onRejected);\n\t}\n\n\tfinally(onFinally) {\n\t\treturn this._promise.finally(onFinally);\n\t}\n\n\tcancel(reason) {\n\t\tif (!this._isPending || this._isCanceled) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._isCanceled = true;\n\n\t\tif (this._cancelHandlers.length > 0) {\n\t\t\ttry {\n\t\t\t\tfor (const handler of this._cancelHandlers) {\n\t\t\t\t\thandler();\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis._reject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (this._rejectOnCancel) {\n\t\t\tthis._reject(new CancelError(reason));\n\t\t}\n\t}\n\n\tget isCanceled() {\n\t\treturn this._isCanceled;\n\t}\n}\n\nObject.setPrototypeOf(PCancelable.prototype, Promise.prototype);\n\nmodule.exports = PCancelable;\nmodule.exports.CancelError = CancelError;\n", "/**\n * @license React\n * scheduler.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n", "/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=zh(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,\"\");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a)}E(Eh);G(Eh,b)}function Jh(){E(Eh);E(Fh);E(Gh)}\nfunction Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c))}function Lh(a){Fh.current===a&&(E(Eh),E(Fh))}var M=Uf(0);\nfunction Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||\"$?\"===c.data||\"$!\"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var Nh=[];\nfunction Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b()}finally{C=c,Qh.transition=d}}function Fi(){return di().memoizedState}\nfunction Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d)}}\nfunction ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d))}}\nfunction Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308,\n4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return[d.memoizedState,a]},useRef:function(a){var b=\nci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d,\nf,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Uh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304)}else{if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(),\nnull;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Nj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Oj=!1;\nfunction Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Oj;Oj=!1;return n}\nfunction Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f)}e=e.next}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}\nfunction Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling}\nfunction ak(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0;\nZj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c)}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else{a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b)}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c))}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c)}\nfunction ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c)}var Wk;\nWk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c)}b=b.child}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\nhj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Yi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)}\nfunction al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction $k(a){if(\"function\"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction yh(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)bj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3\": function(a, b) {\n return a > b;\n },\n \">=\": function(a, b) {\n return a >= b;\n },\n \"<\": function(a, b, c) {\n return (c === undefined) ? a < b : (a < b) && (b < c);\n },\n \"<=\": function(a, b, c) {\n return (c === undefined) ? a <= b : (a <= b) && (b <= c);\n },\n \"!!\": function(a) {\n return jsonLogic.truthy(a);\n },\n \"!\": function(a) {\n return !jsonLogic.truthy(a);\n },\n \"%\": function(a, b) {\n return a % b;\n },\n \"log\": function(a) {\n console.log(a); return a;\n },\n \"in\": function(a, b) {\n if (!b || typeof b.indexOf === \"undefined\") return false;\n return (b.indexOf(a) !== -1);\n },\n \"cat\": function() {\n return Array.prototype.join.call(arguments, \"\");\n },\n \"substr\": function(source, start, end) {\n if (end < 0) {\n // JavaScript doesn't support negative end, this emulates PHP behavior\n var temp = String(source).substr(start);\n return temp.substr(0, temp.length + end);\n }\n return String(source).substr(start, end);\n },\n \"+\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return parseFloat(a, 10) + parseFloat(b, 10);\n }, 0);\n },\n \"*\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return parseFloat(a, 10) * parseFloat(b, 10);\n });\n },\n \"-\": function(a, b) {\n if (b === undefined) {\n return -a;\n } else {\n return a - b;\n }\n },\n \"/\": function(a, b) {\n return a / b;\n },\n \"min\": function() {\n return Math.min.apply(this, arguments);\n },\n \"max\": function() {\n return Math.max.apply(this, arguments);\n },\n \"merge\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return a.concat(b);\n }, []);\n },\n \"var\": function(a, b) {\n var not_found = (b === undefined) ? null : b;\n var data = this;\n if (typeof a === \"undefined\" || a===\"\" || a===null) {\n return data;\n }\n var sub_props = String(a).split(\".\");\n for (var i = 0; i < sub_props.length; i++) {\n if (data === null || data === undefined) {\n return not_found;\n }\n // Descending into data\n data = data[sub_props[i]];\n if (data === undefined) {\n return not_found;\n }\n }\n return data;\n },\n \"missing\": function() {\n /*\n Missing can receive many keys as many arguments, like {\"missing:[1,2]}\n Missing can also receive *one* argument that is an array of keys,\n which typically happens if it's actually acting on the output of another command\n (like 'if' or 'merge')\n */\n\n var missing = [];\n var keys = Array.isArray(arguments[0]) ? arguments[0] : arguments;\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = jsonLogic.apply({\"var\": key}, this);\n if (value === null || value === \"\") {\n missing.push(key);\n }\n }\n\n return missing;\n },\n \"missing_some\": function(need_count, options) {\n // missing_some takes two arguments, how many (minimum) items must be present, and an array of keys (just like 'missing') to check for presence.\n var are_missing = jsonLogic.apply({\"missing\": options}, this);\n\n if (options.length - are_missing.length >= need_count) {\n return [];\n } else {\n return are_missing;\n }\n },\n };\n\n jsonLogic.is_logic = function(logic) {\n return (\n typeof logic === \"object\" && // An object\n logic !== null && // but not null\n ! Array.isArray(logic) && // and not an array\n Object.keys(logic).length === 1 // with exactly one key\n );\n };\n\n /*\n This helper will defer to the JsonLogic spec as a tie-breaker when different language interpreters define different behavior for the truthiness of primitives. E.g., PHP considers empty arrays to be falsy, but Javascript considers them to be truthy. JsonLogic, as an ecosystem, needs one consistent answer.\n\n Spec and rationale here: http://jsonlogic.com/truthy\n */\n jsonLogic.truthy = function(value) {\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n return !! value;\n };\n\n\n jsonLogic.get_operator = function(logic) {\n return Object.keys(logic)[0];\n };\n\n jsonLogic.get_values = function(logic) {\n return logic[jsonLogic.get_operator(logic)];\n };\n\n jsonLogic.apply = function(logic, data) {\n // Does this array contain logic? Only one way to find out.\n if (Array.isArray(logic)) {\n return logic.map(function(l) {\n return jsonLogic.apply(l, data);\n });\n }\n // You've recursed to a primitive, stop!\n if ( ! jsonLogic.is_logic(logic) ) {\n return logic;\n }\n\n var op = jsonLogic.get_operator(logic);\n var values = logic[op];\n var i;\n var current;\n var scopedLogic;\n var scopedData;\n var initial;\n\n // easy syntax for unary operators, like {\"var\" : \"x\"} instead of strict {\"var\" : [\"x\"]}\n if ( ! Array.isArray(values)) {\n values = [values];\n }\n\n // 'if', 'and', and 'or' violate the normal rule of depth-first calculating consequents, let each manage recursion as needed.\n if (op === \"if\" || op == \"?:\") {\n /* 'if' should be called with a odd number of parameters, 3 or greater\n This works on the pattern:\n if( 0 ){ 1 }else{ 2 };\n if( 0 ){ 1 }else if( 2 ){ 3 }else{ 4 };\n if( 0 ){ 1 }else if( 2 ){ 3 }else if( 4 ){ 5 }else{ 6 };\n\n The implementation is:\n For pairs of values (0,1 then 2,3 then 4,5 etc)\n If the first evaluates truthy, evaluate and return the second\n If the first evaluates falsy, jump to the next pair (e.g, 0,1 to 2,3)\n given one parameter, evaluate and return it. (it's an Else and all the If/ElseIf were false)\n given 0 parameters, return NULL (not great practice, but there was no Else)\n */\n for (i = 0; i < values.length - 1; i += 2) {\n if ( jsonLogic.truthy( jsonLogic.apply(values[i], data) ) ) {\n return jsonLogic.apply(values[i+1], data);\n }\n }\n if (values.length === i+1) {\n return jsonLogic.apply(values[i], data);\n }\n return null;\n } else if (op === \"and\") { // Return first falsy, or last\n for (i=0; i < values.length; i+=1) {\n current = jsonLogic.apply(values[i], data);\n if ( ! jsonLogic.truthy(current)) {\n return current;\n }\n }\n return current; // Last\n } else if (op === \"or\") {// Return first truthy, or last\n for (i=0; i < values.length; i+=1) {\n current = jsonLogic.apply(values[i], data);\n if ( jsonLogic.truthy(current) ) {\n return current;\n }\n }\n return current; // Last\n } else if (op === \"filter\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData)) {\n return [];\n }\n // Return only the elements from the array in the first argument,\n // that return truthy when passed to the logic in the second argument.\n // For parity with JavaScript, reindex the returned array\n return scopedData.filter(function(datum) {\n return jsonLogic.truthy( jsonLogic.apply(scopedLogic, datum));\n });\n } else if (op === \"map\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData)) {\n return [];\n }\n\n return scopedData.map(function(datum) {\n return jsonLogic.apply(scopedLogic, datum);\n });\n } else if (op === \"reduce\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n initial = typeof values[2] !== \"undefined\" ? values[2] : null;\n\n if ( ! Array.isArray(scopedData)) {\n return initial;\n }\n\n return scopedData.reduce(\n function(accumulator, current) {\n return jsonLogic.apply(\n scopedLogic,\n {current: current, accumulator: accumulator}\n );\n },\n initial\n );\n } else if (op === \"all\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n // All of an empty set is false. Note, some and none have correct fallback after the for loop\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return false;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( ! jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return false; // First falsy, short circuit\n }\n }\n return true; // All were truthy\n } else if (op === \"none\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return true;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return false; // First truthy, short circuit\n }\n }\n return true; // None were truthy\n } else if (op === \"some\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return false;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return true; // First truthy, short circuit\n }\n }\n return false; // None were truthy\n }\n\n // Everyone else gets immediate depth-first recursion\n values = values.map(function(val) {\n return jsonLogic.apply(val, data);\n });\n\n\n // The operation is called with \"data\" bound to its \"this\" and \"values\" passed as arguments.\n // Structured commands like % or > can name formal arguments while flexible commands (like missing or merge) can operate on the pseudo-array arguments\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments\n if (operations.hasOwnProperty(op) && typeof operations[op] === \"function\") {\n return operations[op].apply(data, values);\n } else if (op.indexOf(\".\") > 0) { // Contains a dot, and not in the 0th position\n var sub_ops = String(op).split(\".\");\n var operation = operations;\n for (i = 0; i < sub_ops.length; i++) {\n if (!operation.hasOwnProperty(sub_ops[i])) {\n throw new Error(\"Unrecognized operation \" + op +\n \" (failed at \" + sub_ops.slice(0, i+1).join(\".\") + \")\");\n }\n // Descending into operations\n operation = operation[sub_ops[i]];\n }\n\n return operation.apply(data, values);\n }\n\n throw new Error(\"Unrecognized operation \" + op );\n };\n\n jsonLogic.uses_data = function(logic) {\n var collection = [];\n\n if (jsonLogic.is_logic(logic)) {\n var op = jsonLogic.get_operator(logic);\n var values = logic[op];\n\n if ( ! Array.isArray(values)) {\n values = [values];\n }\n\n if (op === \"var\") {\n // This doesn't cover the case where the arg to var is itself a rule.\n collection.push(values[0]);\n } else {\n // Recursion!\n values.forEach(function(val) {\n collection.push.apply(collection, jsonLogic.uses_data(val) );\n });\n }\n }\n\n return arrayUnique(collection);\n };\n\n jsonLogic.add_operation = function(name, code) {\n operations[name] = code;\n };\n\n jsonLogic.rm_operation = function(name) {\n delete operations[name];\n };\n\n jsonLogic.rule_like = function(rule, pattern) {\n // console.log(\"Is \". JSON.stringify(rule) . \" like \" . JSON.stringify(pattern) . \"?\");\n if (pattern === rule) {\n return true;\n } // TODO : Deep object equivalency?\n if (pattern === \"@\") {\n return true;\n } // Wildcard!\n if (pattern === \"number\") {\n return (typeof rule === \"number\");\n }\n if (pattern === \"string\") {\n return (typeof rule === \"string\");\n }\n if (pattern === \"array\") {\n // !logic test might be superfluous in JavaScript\n return Array.isArray(rule) && ! jsonLogic.is_logic(rule);\n }\n\n if (jsonLogic.is_logic(pattern)) {\n if (jsonLogic.is_logic(rule)) {\n var pattern_op = jsonLogic.get_operator(pattern);\n var rule_op = jsonLogic.get_operator(rule);\n\n if (pattern_op === \"@\" || pattern_op === rule_op) {\n // echo \"\\nOperators match, go deeper\\n\";\n return jsonLogic.rule_like(\n jsonLogic.get_values(rule, false),\n jsonLogic.get_values(pattern, false)\n );\n }\n }\n return false; // pattern is logic, rule isn't, can't be eq\n }\n\n if (Array.isArray(pattern)) {\n if (Array.isArray(rule)) {\n if (pattern.length !== rule.length) {\n return false;\n }\n /*\n Note, array order MATTERS, because we're using this array test logic to consider arguments, where order can matter. (e.g., + is commutative, but '-' or 'if' or 'var' are NOT)\n */\n for (var i = 0; i < pattern.length; i += 1) {\n // If any fail, we fail\n if ( ! jsonLogic.rule_like(rule[i], pattern[i])) {\n return false;\n }\n }\n return true; // If they *all* passed, we pass\n } else {\n return false; // Pattern is array, rule isn't\n }\n }\n\n // Not logic, not array, not a === match for rule.\n return false;\n };\n\n return jsonLogic;\n}));\n", "/** @license React v16.13.1\n * react-is.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';var b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\nSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\nfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;\nexports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};\nexports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;\n", "'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n", "'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n", "/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n", "/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bigint: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n", "/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n", "!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=t(require(\"prop-types\"),require(\"react\")):\"function\"==typeof define&&define.amd?define([\"prop-types\",\"react\"],t):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).AvatarEditor=t(e.PropTypes,e.React)}(this,function(e,t){\"use strict\";function o(e){return e&&\"object\"==typeof e&&\"default\"in e?e:{default:e}}var n=o(e),i=o(t);function r(e,t){for(var o=0;oe.length)&&(t=e.length);for(var o=0,n=new Array(t);o\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the `TypeError` message for \"Functions\" methods. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n result = wait - timeSinceLastCall;\n\n return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return !!value && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return !!value && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && objectToString.call(value) == symbolTag);\n}\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = debounce;\n", "/**\n * Copyright (c) 2013-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\n/**\n * Use invariant() to assert state which your program assumes to be true.\n *\n * Provide sprintf-style format (only %s is supported) and arguments\n * to provide information about what broke and what you were\n * expecting.\n *\n * The invariant message will be stripped in production, but the invariant\n * will remain to ensure logic does not differ in production.\n */\n\nvar invariant = function(condition, format, a, b, c, d, e, f) {\n if (process.env.NODE_ENV !== 'production') {\n if (format === undefined) {\n throw new Error('invariant requires an error message argument');\n }\n }\n\n if (!condition) {\n var error;\n if (format === undefined) {\n error = new Error(\n 'Minified exception occurred; use the non-minified dev environment ' +\n 'for the full error message and additional helpful warnings.'\n );\n } else {\n var args = [a, b, c, d, e, f];\n var argIndex = 0;\n error = new Error(\n format.replace(/%s/g, function() { return args[argIndex++]; })\n );\n error.name = 'Invariant Violation';\n }\n\n error.framesToPop = 1; // we don't care about invariant's own frame\n throw error;\n }\n};\n\nmodule.exports = invariant;\n", "(function() {\n var COUNT_FRAMERATE, COUNT_MS_PER_FRAME, DIGIT_FORMAT, DIGIT_HTML, DIGIT_SPEEDBOOST, DURATION, FORMAT_MARK_HTML, FORMAT_PARSER, FRAMERATE, FRAMES_PER_VALUE, MS_PER_FRAME, MutationObserver, Odometer, RIBBON_HTML, TRANSITION_END_EVENTS, TRANSITION_SUPPORT, VALUE_HTML, addClass, createFromHTML, fractionalPart, now, removeClass, requestAnimationFrame, round, transitionCheckStyles, trigger, truncate, wrapJQuery, _jQueryWrapped, _old, _ref, _ref1,\n __slice = [].slice;\n\n VALUE_HTML = '';\n\n RIBBON_HTML = '' + VALUE_HTML + '';\n\n DIGIT_HTML = '8' + RIBBON_HTML + '';\n\n FORMAT_MARK_HTML = '';\n\n DIGIT_FORMAT = '(,ddd).dd';\n\n FORMAT_PARSER = /^\\(?([^)]*)\\)?(?:(.)(d+))?$/;\n\n FRAMERATE = 30;\n\n DURATION = 2000;\n\n COUNT_FRAMERATE = 20;\n\n FRAMES_PER_VALUE = 2;\n\n DIGIT_SPEEDBOOST = .5;\n\n MS_PER_FRAME = 1000 / FRAMERATE;\n\n COUNT_MS_PER_FRAME = 1000 / COUNT_FRAMERATE;\n\n TRANSITION_END_EVENTS = 'transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd';\n\n transitionCheckStyles = document.createElement('div').style;\n\n TRANSITION_SUPPORT = (transitionCheckStyles.transition != null) || (transitionCheckStyles.webkitTransition != null) || (transitionCheckStyles.mozTransition != null) || (transitionCheckStyles.oTransition != null);\n\n requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;\n\n MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;\n\n createFromHTML = function(html) {\n var el;\n el = document.createElement('div');\n el.innerHTML = html;\n return el.children[0];\n };\n\n removeClass = function(el, name) {\n return el.className = el.className.replace(new RegExp(\"(^| )\" + (name.split(' ').join('|')) + \"( |$)\", 'gi'), ' ');\n };\n\n addClass = function(el, name) {\n removeClass(el, name);\n return el.className += \" \" + name;\n };\n\n trigger = function(el, name) {\n var evt;\n if (document.createEvent != null) {\n evt = document.createEvent('HTMLEvents');\n evt.initEvent(name, true, true);\n return el.dispatchEvent(evt);\n }\n };\n\n now = function() {\n var _ref, _ref1;\n return (_ref = (_ref1 = window.performance) != null ? typeof _ref1.now === \"function\" ? _ref1.now() : void 0 : void 0) != null ? _ref : +(new Date);\n };\n\n round = function(val, precision) {\n if (precision == null) {\n precision = 0;\n }\n if (!precision) {\n return Math.round(val);\n }\n val *= Math.pow(10, precision);\n val += 0.5;\n val = Math.floor(val);\n return val /= Math.pow(10, precision);\n };\n\n truncate = function(val) {\n if (val < 0) {\n return Math.ceil(val);\n } else {\n return Math.floor(val);\n }\n };\n\n fractionalPart = function(val) {\n return val - round(val);\n };\n\n _jQueryWrapped = false;\n\n (wrapJQuery = function() {\n var property, _i, _len, _ref, _results;\n if (_jQueryWrapped) {\n return;\n }\n if (window.jQuery != null) {\n _jQueryWrapped = true;\n _ref = ['html', 'text'];\n _results = [];\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n property = _ref[_i];\n _results.push((function(property) {\n var old;\n old = window.jQuery.fn[property];\n return window.jQuery.fn[property] = function(val) {\n var _ref1;\n if ((val == null) || (((_ref1 = this[0]) != null ? _ref1.odometer : void 0) == null)) {\n return old.apply(this, arguments);\n }\n return this[0].odometer.update(val);\n };\n })(property));\n }\n return _results;\n }\n })();\n\n setTimeout(wrapJQuery, 0);\n\n Odometer = (function() {\n function Odometer(options) {\n var e, k, property, v, _base, _i, _len, _ref, _ref1, _ref2,\n _this = this;\n this.options = options;\n this.el = this.options.el;\n if (this.el.odometer != null) {\n return this.el.odometer;\n }\n this.el.odometer = this;\n _ref = Odometer.options;\n for (k in _ref) {\n v = _ref[k];\n if (this.options[k] == null) {\n this.options[k] = v;\n }\n }\n if ((_base = this.options).duration == null) {\n _base.duration = DURATION;\n }\n this.MAX_VALUES = ((this.options.duration / MS_PER_FRAME) / FRAMES_PER_VALUE) | 0;\n this.resetFormat();\n this.value = this.cleanValue((_ref1 = this.options.value) != null ? _ref1 : '');\n this.renderInside();\n this.render();\n try {\n _ref2 = ['innerHTML', 'innerText', 'textContent'];\n for (_i = 0, _len = _ref2.length; _i < _len; _i++) {\n property = _ref2[_i];\n if (this.el[property] != null) {\n (function(property) {\n return Object.defineProperty(_this.el, property, {\n get: function() {\n var _ref3;\n if (property === 'innerHTML') {\n return _this.inside.outerHTML;\n } else {\n return (_ref3 = _this.inside.innerText) != null ? _ref3 : _this.inside.textContent;\n }\n },\n set: function(val) {\n return _this.update(val);\n }\n });\n })(property);\n }\n }\n } catch (_error) {\n e = _error;\n this.watchForMutations();\n }\n this;\n }\n\n Odometer.prototype.renderInside = function() {\n this.inside = document.createElement('div');\n this.inside.className = 'odometer-inside';\n this.el.innerHTML = '';\n return this.el.appendChild(this.inside);\n };\n\n Odometer.prototype.watchForMutations = function() {\n var e,\n _this = this;\n if (MutationObserver == null) {\n return;\n }\n try {\n if (this.observer == null) {\n this.observer = new MutationObserver(function(mutations) {\n var newVal;\n newVal = _this.el.innerText;\n _this.renderInside();\n _this.render(_this.value);\n return _this.update(newVal);\n });\n }\n this.watchMutations = true;\n return this.startWatchingMutations();\n } catch (_error) {\n e = _error;\n }\n };\n\n Odometer.prototype.startWatchingMutations = function() {\n if (this.watchMutations) {\n return this.observer.observe(this.el, {\n childList: true\n });\n }\n };\n\n Odometer.prototype.stopWatchingMutations = function() {\n var _ref;\n return (_ref = this.observer) != null ? _ref.disconnect() : void 0;\n };\n\n Odometer.prototype.cleanValue = function(val) {\n var _ref;\n if (typeof val === 'string') {\n val = val.replace((_ref = this.format.radix) != null ? _ref : '.', '');\n val = val.replace(/[.,]/g, '');\n val = val.replace('', '.');\n val = parseFloat(val, 10) || 0;\n }\n return round(val, this.format.precision);\n };\n\n Odometer.prototype.bindTransitionEnd = function() {\n var event, renderEnqueued, _i, _len, _ref, _results,\n _this = this;\n if (this.transitionEndBound) {\n return;\n }\n this.transitionEndBound = true;\n renderEnqueued = false;\n _ref = TRANSITION_END_EVENTS.split(' ');\n _results = [];\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n event = _ref[_i];\n _results.push(this.el.addEventListener(event, function() {\n if (renderEnqueued) {\n return true;\n }\n renderEnqueued = true;\n setTimeout(function() {\n _this.render();\n renderEnqueued = false;\n return trigger(_this.el, 'odometerdone');\n }, 0);\n return true;\n }, false));\n }\n return _results;\n };\n\n Odometer.prototype.resetFormat = function() {\n var format, fractional, parsed, precision, radix, repeating, _ref, _ref1;\n format = (_ref = this.options.format) != null ? _ref : DIGIT_FORMAT;\n format || (format = 'd');\n parsed = FORMAT_PARSER.exec(format);\n if (!parsed) {\n throw new Error(\"Odometer: Unparsable digit format\");\n }\n _ref1 = parsed.slice(1, 4), repeating = _ref1[0], radix = _ref1[1], fractional = _ref1[2];\n precision = (fractional != null ? fractional.length : void 0) || 0;\n return this.format = {\n repeating: repeating,\n radix: radix,\n precision: precision\n };\n };\n\n Odometer.prototype.render = function(value) {\n var classes, cls, match, newClasses, theme, _i, _len;\n if (value == null) {\n value = this.value;\n }\n this.stopWatchingMutations();\n this.resetFormat();\n this.inside.innerHTML = '';\n theme = this.options.theme;\n classes = this.el.className.split(' ');\n newClasses = [];\n for (_i = 0, _len = classes.length; _i < _len; _i++) {\n cls = classes[_i];\n if (!cls.length) {\n continue;\n }\n if (match = /^odometer-theme-(.+)$/.exec(cls)) {\n theme = match[1];\n continue;\n }\n if (/^odometer(-|$)/.test(cls)) {\n continue;\n }\n newClasses.push(cls);\n }\n newClasses.push('odometer');\n if (!TRANSITION_SUPPORT) {\n newClasses.push('odometer-no-transitions');\n }\n if (theme) {\n newClasses.push(\"odometer-theme-\" + theme);\n } else {\n newClasses.push(\"odometer-auto-theme\");\n }\n this.el.className = newClasses.join(' ');\n this.ribbons = {};\n this.formatDigits(value);\n return this.startWatchingMutations();\n };\n\n Odometer.prototype.formatDigits = function(value) {\n var digit, valueDigit, valueString, wholePart, _i, _j, _len, _len1, _ref, _ref1;\n this.digits = [];\n if (this.options.formatFunction) {\n valueString = this.options.formatFunction(value);\n _ref = valueString.split('').reverse();\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n valueDigit = _ref[_i];\n if (valueDigit.match(/0-9/)) {\n digit = this.renderDigit();\n digit.querySelector('.odometer-value').innerHTML = valueDigit;\n this.digits.push(digit);\n this.insertDigit(digit);\n } else {\n this.addSpacer(valueDigit);\n }\n }\n } else {\n wholePart = !this.format.precision || !fractionalPart(value) || false;\n _ref1 = value.toString().split('').reverse();\n for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {\n digit = _ref1[_j];\n if (digit === '.') {\n wholePart = true;\n }\n this.addDigit(digit, wholePart);\n }\n }\n };\n\n Odometer.prototype.update = function(newValue) {\n var diff,\n _this = this;\n newValue = this.cleanValue(newValue);\n if (!(diff = newValue - this.value)) {\n return;\n }\n removeClass(this.el, 'odometer-animating-up odometer-animating-down odometer-animating');\n if (diff > 0) {\n addClass(this.el, 'odometer-animating-up');\n } else {\n addClass(this.el, 'odometer-animating-down');\n }\n this.stopWatchingMutations();\n this.animate(newValue);\n this.startWatchingMutations();\n setTimeout(function() {\n _this.el.offsetHeight;\n return addClass(_this.el, 'odometer-animating');\n }, 0);\n return this.value = newValue;\n };\n\n Odometer.prototype.renderDigit = function() {\n return createFromHTML(DIGIT_HTML);\n };\n\n Odometer.prototype.insertDigit = function(digit, before) {\n if (before != null) {\n return this.inside.insertBefore(digit, before);\n } else if (!this.inside.children.length) {\n return this.inside.appendChild(digit);\n } else {\n return this.inside.insertBefore(digit, this.inside.children[0]);\n }\n };\n\n Odometer.prototype.addSpacer = function(chr, before, extraClasses) {\n var spacer;\n spacer = createFromHTML(FORMAT_MARK_HTML);\n spacer.innerHTML = chr;\n if (extraClasses) {\n addClass(spacer, extraClasses);\n }\n return this.insertDigit(spacer, before);\n };\n\n Odometer.prototype.addDigit = function(value, repeating) {\n var chr, digit, resetted, _ref;\n if (repeating == null) {\n repeating = true;\n }\n if (value === '-') {\n return this.addSpacer(value, null, 'odometer-negation-mark');\n }\n if (value === '.') {\n return this.addSpacer((_ref = this.format.radix) != null ? _ref : '.', null, 'odometer-radix-mark');\n }\n if (repeating) {\n resetted = false;\n while (true) {\n if (!this.format.repeating.length) {\n if (resetted) {\n throw new Error(\"Bad odometer format without digits\");\n }\n this.resetFormat();\n resetted = true;\n }\n chr = this.format.repeating[this.format.repeating.length - 1];\n this.format.repeating = this.format.repeating.substring(0, this.format.repeating.length - 1);\n if (chr === 'd') {\n break;\n }\n this.addSpacer(chr);\n }\n }\n digit = this.renderDigit();\n digit.querySelector('.odometer-value').innerHTML = value;\n this.digits.push(digit);\n return this.insertDigit(digit);\n };\n\n Odometer.prototype.animate = function(newValue) {\n if (!TRANSITION_SUPPORT || this.options.animation === 'count') {\n return this.animateCount(newValue);\n } else {\n return this.animateSlide(newValue);\n }\n };\n\n Odometer.prototype.animateCount = function(newValue) {\n var cur, diff, last, start, tick,\n _this = this;\n if (!(diff = +newValue - this.value)) {\n return;\n }\n start = last = now();\n cur = this.value;\n return (tick = function() {\n var delta, dist, fraction;\n if ((now() - start) > _this.options.duration) {\n _this.value = newValue;\n _this.render();\n trigger(_this.el, 'odometerdone');\n return;\n }\n delta = now() - last;\n if (delta > COUNT_MS_PER_FRAME) {\n last = now();\n fraction = delta / _this.options.duration;\n dist = diff * fraction;\n cur += dist;\n _this.render(Math.round(cur));\n }\n if (requestAnimationFrame != null) {\n return requestAnimationFrame(tick);\n } else {\n return setTimeout(tick, COUNT_MS_PER_FRAME);\n }\n })();\n };\n\n Odometer.prototype.getDigitCount = function() {\n var i, max, value, values, _i, _len;\n values = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n for (i = _i = 0, _len = values.length; _i < _len; i = ++_i) {\n value = values[i];\n values[i] = Math.abs(value);\n }\n max = Math.max.apply(Math, values);\n return Math.ceil(Math.log(max + 1) / Math.log(10));\n };\n\n Odometer.prototype.getFractionalDigitCount = function() {\n var i, parser, parts, value, values, _i, _len;\n values = 1 <= arguments.length ? __slice.call(arguments, 0) : [];\n parser = /^\\-?\\d*\\.(\\d*?)0*$/;\n for (i = _i = 0, _len = values.length; _i < _len; i = ++_i) {\n value = values[i];\n values[i] = value.toString();\n parts = parser.exec(values[i]);\n if (parts == null) {\n values[i] = 0;\n } else {\n values[i] = parts[1].length;\n }\n }\n return Math.max.apply(Math, values);\n };\n\n Odometer.prototype.resetDigits = function() {\n this.digits = [];\n this.ribbons = [];\n this.inside.innerHTML = '';\n return this.resetFormat();\n };\n\n Odometer.prototype.animateSlide = function(newValue) {\n var boosted, cur, diff, digitCount, digits, dist, end, fractionalCount, frame, frames, i, incr, j, mark, numEl, oldValue, start, _base, _i, _j, _k, _l, _len, _len1, _len2, _m, _ref, _results;\n oldValue = this.value;\n fractionalCount = this.getFractionalDigitCount(oldValue, newValue);\n if (fractionalCount) {\n newValue = newValue * Math.pow(10, fractionalCount);\n oldValue = oldValue * Math.pow(10, fractionalCount);\n }\n if (!(diff = newValue - oldValue)) {\n return;\n }\n this.bindTransitionEnd();\n digitCount = this.getDigitCount(oldValue, newValue);\n digits = [];\n boosted = 0;\n for (i = _i = 0; 0 <= digitCount ? _i < digitCount : _i > digitCount; i = 0 <= digitCount ? ++_i : --_i) {\n start = truncate(oldValue / Math.pow(10, digitCount - i - 1));\n end = truncate(newValue / Math.pow(10, digitCount - i - 1));\n dist = end - start;\n if (Math.abs(dist) > this.MAX_VALUES) {\n frames = [];\n incr = dist / (this.MAX_VALUES + this.MAX_VALUES * boosted * DIGIT_SPEEDBOOST);\n cur = start;\n while ((dist > 0 && cur < end) || (dist < 0 && cur > end)) {\n frames.push(Math.round(cur));\n cur += incr;\n }\n if (frames[frames.length - 1] !== end) {\n frames.push(end);\n }\n boosted++;\n } else {\n frames = (function() {\n _results = [];\n for (var _j = start; start <= end ? _j <= end : _j >= end; start <= end ? _j++ : _j--){ _results.push(_j); }\n return _results;\n }).apply(this);\n }\n for (i = _k = 0, _len = frames.length; _k < _len; i = ++_k) {\n frame = frames[i];\n frames[i] = Math.abs(frame % 10);\n }\n digits.push(frames);\n }\n this.resetDigits();\n _ref = digits.reverse();\n for (i = _l = 0, _len1 = _ref.length; _l < _len1; i = ++_l) {\n frames = _ref[i];\n if (!this.digits[i]) {\n this.addDigit(' ', i >= fractionalCount);\n }\n if ((_base = this.ribbons)[i] == null) {\n _base[i] = this.digits[i].querySelector('.odometer-ribbon-inner');\n }\n this.ribbons[i].innerHTML = '';\n if (diff < 0) {\n frames = frames.reverse();\n }\n for (j = _m = 0, _len2 = frames.length; _m < _len2; j = ++_m) {\n frame = frames[j];\n numEl = document.createElement('div');\n numEl.className = 'odometer-value';\n numEl.innerHTML = frame;\n this.ribbons[i].appendChild(numEl);\n if (j === frames.length - 1) {\n addClass(numEl, 'odometer-last-value');\n }\n if (j === 0) {\n addClass(numEl, 'odometer-first-value');\n }\n }\n }\n if (start < 0) {\n this.addDigit('-');\n }\n mark = this.inside.querySelector('.odometer-radix-mark');\n if (mark != null) {\n mark.parent.removeChild(mark);\n }\n if (fractionalCount) {\n return this.addSpacer(this.format.radix, this.digits[fractionalCount - 1], 'odometer-radix-mark');\n }\n };\n\n return Odometer;\n\n })();\n\n Odometer.options = (_ref = window.odometerOptions) != null ? _ref : {};\n\n setTimeout(function() {\n var k, v, _base, _ref1, _results;\n if (window.odometerOptions) {\n _ref1 = window.odometerOptions;\n _results = [];\n for (k in _ref1) {\n v = _ref1[k];\n _results.push((_base = Odometer.options)[k] != null ? (_base = Odometer.options)[k] : _base[k] = v);\n }\n return _results;\n }\n }, 0);\n\n Odometer.init = function() {\n var el, elements, _i, _len, _ref1, _results;\n if (document.querySelectorAll == null) {\n return;\n }\n elements = document.querySelectorAll(Odometer.options.selector || '.odometer');\n _results = [];\n for (_i = 0, _len = elements.length; _i < _len; _i++) {\n el = elements[_i];\n _results.push(el.odometer = new Odometer({\n el: el,\n value: (_ref1 = el.innerText) != null ? _ref1 : el.textContent\n }));\n }\n return _results;\n };\n\n if ((((_ref1 = document.documentElement) != null ? _ref1.doScroll : void 0) != null) && (document.createEventObject != null)) {\n _old = document.onreadystatechange;\n document.onreadystatechange = function() {\n if (document.readyState === 'complete' && Odometer.options.auto !== false) {\n Odometer.init();\n }\n return _old != null ? _old.apply(this, arguments) : void 0;\n };\n } else {\n document.addEventListener('DOMContentLoaded', function() {\n if (Odometer.options.auto !== false) {\n return Odometer.init();\n }\n }, false);\n }\n\n if (typeof define === 'function' && define.amd) {\n define([], function() {\n return Odometer;\n });\n } else if (typeof exports !== \"undefined\" && exports !== null) {\n module.exports = Odometer;\n } else {\n window.Odometer = Odometer;\n }\n\n}).call(this);\n", "function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\nexport default function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}", "export default function _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}", "export default function _iterableToArrayLimit(arr, i) {\n var _i = null == arr ? null : \"undefined\" != typeof Symbol && arr[Symbol.iterator] || arr[\"@@iterator\"];\n if (null != _i) {\n var _s,\n _e,\n _x,\n _r,\n _arr = [],\n _n = !0,\n _d = !1;\n try {\n if (_x = (_i = _i.call(arr)).next, 0 === i) {\n if (Object(_i) !== _i) return;\n _n = !1;\n } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);\n } catch (err) {\n _d = !0, _e = err;\n } finally {\n try {\n if (!_n && null != _i[\"return\"] && (_r = _i[\"return\"](), Object(_r) !== _r)) return;\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n}", "export default function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n return arr2;\n}", "import arrayLikeToArray from \"./arrayLikeToArray.js\";\nexport default function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);\n}", "export default function _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}", "import arrayWithHoles from \"./arrayWithHoles.js\";\nimport iterableToArrayLimit from \"./iterableToArrayLimit.js\";\nimport unsupportedIterableToArray from \"./unsupportedIterableToArray.js\";\nimport nonIterableRest from \"./nonIterableRest.js\";\nexport default function _slicedToArray(arr, i) {\n return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();\n}", "/*\n * Copyright (c) 2020-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\nimport * as React from 'react';\nimport { AuthState, OktaAuth } from '@okta/okta-auth-js';\n\nexport type OnAuthRequiredFunction = (oktaAuth: OktaAuth) => Promise | void;\nexport type OnAuthResumeFunction = () => void;\n\nexport type RestoreOriginalUriFunction = (oktaAuth: OktaAuth, originalUri: string) => Promise | void;\n\nexport interface IOktaContext {\n oktaAuth: OktaAuth;\n authState: AuthState | null;\n _onAuthRequired?: OnAuthRequiredFunction;\n}\n\nconst OktaContext = React.createContext(null);\n\nexport const useOktaAuth = (): IOktaContext => React.useContext(OktaContext) as IOktaContext;\n\nexport default OktaContext;\n", "/*\n * Copyright (c) 2020-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport * as React from 'react';\n\nconst OktaError: React.FC<{ error: Error }> = ({ error }) => { \n if(error.name && error.message) { \n return

{error.name}: {error.message}

;\n }\n return

Error: {error.toString()}

;\n};\n\nexport default OktaError;\n", "/*!\n * Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport * as React from 'react';\nimport { AuthSdkError, AuthState, OktaAuth } from '@okta/okta-auth-js';\nimport OktaContext, { OnAuthRequiredFunction, RestoreOriginalUriFunction } from './OktaContext';\nimport OktaError from './OktaError';\nimport { compare as compareVersions } from 'compare-versions';\n\ndeclare const AUTH_JS: {\n minSupportedVersion: string;\n}\n\ndeclare const PACKAGE_NAME: string;\ndeclare const PACKAGE_VERSION: string;\ndeclare const SKIP_VERSION_CHECK: string;\n\nconst Security: React.FC<{\n oktaAuth: OktaAuth,\n restoreOriginalUri: RestoreOriginalUriFunction, \n onAuthRequired?: OnAuthRequiredFunction,\n children?: React.ReactNode\n} & React.HTMLAttributes> = ({ \n oktaAuth,\n restoreOriginalUri, \n onAuthRequired, \n children\n}) => { \n const [authState, setAuthState] = React.useState(() => {\n if (!oktaAuth) {\n return null;\n }\n return oktaAuth.authStateManager.getAuthState();\n });\n\n React.useEffect(() => {\n if (!oktaAuth || !restoreOriginalUri) {\n return;\n }\n\n // Add default restoreOriginalUri callback\n // props.restoreOriginalUri is required, therefore if options.restoreOriginalUri exists, there are 2 callbacks\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n if (oktaAuth.options.restoreOriginalUri) {\n console.warn('Two custom restoreOriginalUri callbacks are detected. The one from the OktaAuth configuration will be overridden by the provided restoreOriginalUri prop from the Security component.');\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n oktaAuth.options.restoreOriginalUri = (async (oktaAuth: unknown, originalUri: string) => {\n restoreOriginalUri(oktaAuth as OktaAuth, originalUri);\n }) as ((oktaAuth: OktaAuth, originalUri?: string) => Promise);\n\n }, []); // empty array, only check on component mount\n\n React.useEffect(() => {\n if (!oktaAuth) {\n return;\n }\n\n // Add okta-react userAgent\n if (oktaAuth._oktaUserAgent) {\n oktaAuth._oktaUserAgent.addEnvironment(`${PACKAGE_NAME}/${PACKAGE_VERSION}`);\n } else {\n console.warn('_oktaUserAgent is not available on auth SDK instance. Please use okta-auth-js@^5.3.1 .');\n }\n\n // Update Security provider with latest authState\n const currentAuthState = oktaAuth.authStateManager.getAuthState();\n if (currentAuthState !== authState) {\n setAuthState(currentAuthState);\n }\n const handler = (authState: AuthState) => {\n setAuthState(authState);\n };\n oktaAuth.authStateManager.subscribe(handler);\n\n // Trigger an initial change event to make sure authState is latest\n oktaAuth.start();\n\n return () => {\n oktaAuth.authStateManager.unsubscribe(handler);\n };\n }, [oktaAuth]);\n\n if (!oktaAuth) {\n const err = new AuthSdkError('No oktaAuth instance passed to Security Component.');\n return ;\n }\n\n if (!restoreOriginalUri) {\n const err = new AuthSdkError('No restoreOriginalUri callback passed to Security Component.');\n return ;\n }\n\n if (!oktaAuth._oktaUserAgent) {\n console.warn('_oktaUserAgent is not available on auth SDK instance. Please use okta-auth-js@^5.3.1 .');\n }\n else {\n // use SKIP_VERSION_CHECK flag to control version check in tests\n // OKTA-465157: remove SKIP_VERSION_CHECK\n const isAuthJsSupported = SKIP_VERSION_CHECK === '1' ||\n compareVersions(oktaAuth._oktaUserAgent.getVersion(), AUTH_JS.minSupportedVersion, '>=');\n if (!isAuthJsSupported) {\n const err = new AuthSdkError(`\n Passed in oktaAuth is not compatible with the SDK,\n minimum supported okta-auth-js version is ${AUTH_JS.minSupportedVersion}.\n `);\n return ;\n }\n }\n\n return (\n \n {children}\n \n );\n};\n\nexport default Security;\n", "/*\n * Copyright (c) 2020-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport * as React from 'react';\nimport { useOktaAuth, IOktaContext } from './OktaContext';\n\nconst withOktaAuth =

(\n ComponentToWrap: React.ComponentType

\n): React.FC> => { \n const WrappedComponent = (props: Omit) => { \n const oktaAuthProps = useOktaAuth();\n return ;\n };\n WrappedComponent.displayName = 'withOktaAuth_' + (ComponentToWrap.displayName || ComponentToWrap.name);\n return WrappedComponent;\n};\n\nexport default withOktaAuth;\n", "/*\n * Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport * as React from 'react';\nimport { useOktaAuth, OnAuthResumeFunction } from './OktaContext';\nimport OktaError from './OktaError';\n\ninterface LoginCallbackProps {\n errorComponent?: React.ComponentType<{ error: Error }>;\n onAuthResume?: OnAuthResumeFunction;\n loadingElement?: React.ReactElement;\n}\n\nconst LoginCallback: React.FC = ({ errorComponent, loadingElement = null, onAuthResume }) => { \n const { oktaAuth, authState } = useOktaAuth();\n const [callbackError, setCallbackError] = React.useState(null);\n\n const ErrorReporter = errorComponent || OktaError;\n React.useEffect(() => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore OKTA-464505: backward compatibility support for auth-js@5\n const isInteractionRequired = oktaAuth.idx.isInteractionRequired || oktaAuth.isInteractionRequired.bind(oktaAuth);\n if (onAuthResume && isInteractionRequired()) {\n onAuthResume();\n return;\n }\n oktaAuth.handleLoginRedirect().catch(e => {\n setCallbackError(e);\n });\n }, [oktaAuth]);\n\n const authError = authState?.error;\n const displayError = callbackError || authError;\n if (displayError) { \n return ;\n }\n\n return loadingElement;\n};\n\nexport default LoginCallback;\n", "/*\n * Copyright (c) 2017-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport * as React from 'react';\nimport { useOktaAuth, OnAuthRequiredFunction } from './OktaContext';\nimport * as ReactRouterDom from 'react-router-dom';\nimport { toRelativeUrl, AuthSdkError } from '@okta/okta-auth-js';\nimport OktaError from './OktaError';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet useMatch: any;\nif ('useRouteMatch' in ReactRouterDom) {\n // trick static analyzer to avoid \"'useRouteMatch' is not exported\" error\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n useMatch = (ReactRouterDom as any)['useRouteMatch' in ReactRouterDom ? 'useRouteMatch' : ''];\n} else {\n // throw when useMatch is triggered\n useMatch = () => { \n throw new AuthSdkError('Unsupported: SecureRoute only works with react-router-dom v5 or any router library with compatible APIs. See examples under the \"samples\" folder for how to implement your own custom SecureRoute Component.');\n };\n}\n\nconst SecureRoute: React.FC<{\n onAuthRequired?: OnAuthRequiredFunction;\n errorComponent?: React.ComponentType<{ error: Error }>;\n} & ReactRouterDom.RouteProps & React.HTMLAttributes> = ({ \n onAuthRequired,\n errorComponent,\n ...routeProps\n}) => { \n const { oktaAuth, authState, _onAuthRequired } = useOktaAuth();\n const match = useMatch(routeProps);\n const pendingLogin = React.useRef(false);\n const [handleLoginError, setHandleLoginError] = React.useState(null);\n const ErrorReporter = errorComponent || OktaError;\n\n React.useEffect(() => {\n const handleLogin = async () => {\n if (pendingLogin.current) {\n return;\n }\n\n pendingLogin.current = true;\n\n const originalUri = toRelativeUrl(window.location.href, window.location.origin);\n oktaAuth.setOriginalUri(originalUri);\n const onAuthRequiredFn = onAuthRequired || _onAuthRequired;\n if (onAuthRequiredFn) {\n await onAuthRequiredFn(oktaAuth);\n } else {\n await oktaAuth.signInWithRedirect();\n }\n };\n\n // Only process logic if the route matches\n if (!match) {\n return;\n }\n\n if (!authState) {\n return;\n }\n\n if (authState.isAuthenticated) {\n pendingLogin.current = false;\n return;\n }\n\n // Start login if app has decided it is not logged in and there is no pending signin\n if(!authState.isAuthenticated) { \n handleLogin().catch(err => {\n setHandleLoginError(err as Error);\n });\n } \n\n }, [\n authState,\n oktaAuth, \n match, \n onAuthRequired, \n _onAuthRequired\n ]);\n\n if (handleLoginError) {\n return ;\n }\n\n if (!authState || !authState.isAuthenticated) {\n return null;\n }\n\n return (\n \n );\n};\n\nexport default SecureRoute;\n", "/*!\n * Copyright (c) 2021-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { APIError } from '../../errors/types';\nimport {\n OktaAuthOAuthInterface,\n MinimalOktaOAuthInterface,\n Tokens,\n TransactionManagerConstructor,\n TransactionManagerInterface\n} from '../../oidc/types';\nimport { FlowIdentifier } from './FlowIdentifier';\nimport {\n IdxActions,\n IdxAuthenticator,\n IdxContext,\n IdxForm,\n IdxMessage,\n IdxOption,\n IdxRemediation,\n IdxResponse,\n RawIdxResponse,\n IdxActionParams,\n IdpConfig,\n IdxToPersist,\n ChallengeData,\n ActivationData,\n} from './idx-js';\nimport {\n AccountUnlockOptions,\n AuthenticationOptions,\n CancelOptions,\n InteractOptions,\n IntrospectOptions,\n OktaAuthIdxOptions,\n PasswordRecoveryOptions,\n ProceedOptions,\n RegistrationOptions,\n StartOptions,\n IdxTransactionMetaOptions\n} from './options';\nimport { IdxTransactionMeta } from './meta';\nimport { IdxStorageManagerInterface, SavedIdxResponse } from './storage';\nimport type {\n WebauthnEnrollValues,\n WebauthnVerificationValues\n} from '../authenticator';\nimport { OktaAuthConstructor, FingerprintAPI } from '../../base/types';\n\nexport enum IdxStatus {\n SUCCESS = 'SUCCESS',\n PENDING = 'PENDING',\n FAILURE = 'FAILURE',\n TERMINAL = 'TERMINAL',\n CANCELED = 'CANCELED',\n}\n\nexport enum AuthenticatorKey {\n OKTA_PASSWORD = 'okta_password',\n OKTA_EMAIL = 'okta_email',\n PHONE_NUMBER = 'phone_number',\n GOOGLE_AUTHENTICATOR = 'google_otp',\n SECURITY_QUESTION = 'security_question',\n OKTA_VERIFY = 'okta_verify',\n WEBAUTHN = 'webauthn',\n}\n\nexport type Input = {\n name: string;\n key?: string;\n type?: string;\n label?: string;\n value?: string | {form: IdxForm} | Input[];\n minLength?: number;\n maxLength?: number;\n secret?: boolean;\n required?: boolean;\n options?: IdxOption[];\n mutable?: boolean;\n visible?: boolean;\n customLabel?: boolean\n}\n\n\nexport interface IdxPollOptions {\n required?: boolean;\n refresh?: number;\n}\n\nexport type NextStep = {\n name: string;\n authenticator?: IdxAuthenticator;\n canSkip?: boolean;\n canResend?: boolean;\n inputs?: Input[];\n poll?: IdxPollOptions;\n authenticatorEnrollments?: IdxAuthenticator[];\n // eslint-disable-next-line no-use-before-define\n action?: (params?: IdxActionParams) => Promise;\n idp?: IdpConfig;\n href?: string;\n relatesTo?: {\n type?: string;\n value: IdxAuthenticator;\n };\n refresh?: number;\n}\n\nexport enum IdxFeature {\n PASSWORD_RECOVERY = 'recover-password',\n REGISTRATION = 'enroll-profile',\n SOCIAL_IDP = 'redirect-idp',\n ACCOUNT_UNLOCK = 'unlock-account',\n}\n\n\nexport interface IdxTransaction {\n status: IdxStatus;\n tokens?: Tokens;\n nextStep?: NextStep;\n messages?: IdxMessage[];\n error?: APIError | IdxResponse;\n meta?: IdxTransactionMeta;\n enabledFeatures?: IdxFeature[];\n availableSteps?: NextStep[];\n requestDidSucceed?: boolean;\n stepUp?: boolean;\n \n // from idx-js, used by signin widget\n proceed: (remediationName: string, params: unknown) => Promise;\n neededToProceed: IdxRemediation[];\n rawIdxState: RawIdxResponse;\n interactionCode?: string;\n actions: IdxActions;\n context: IdxContext;\n}\n\n\nexport type Authenticator = {\n id?: string;\n key?: string;\n methodType?: string;\n phoneNumber?: string;\n channel?: string;\n};\n\nexport function isAuthenticator(obj: any): obj is Authenticator {\n return obj && (obj.key || obj.id);\n}\n\nexport interface RemediationResponse {\n idxResponse: IdxResponse;\n nextStep?: NextStep;\n messages?: IdxMessage[];\n terminal?: boolean;\n canceled?: boolean;\n}\n\nexport interface InteractResponse {\n state?: string;\n interactionHandle: string;\n meta: IdxTransactionMeta;\n}\n\nexport interface EmailVerifyCallbackResponse {\n state: string;\n otp: string;\n}\n\nexport interface MinimalIdxAPI {\n // lowest level api\n makeIdxResponse: (rawIdxResponse: RawIdxResponse, toPersist: IdxToPersist, requestDidSucceed: boolean) => IdxResponse;\n\n // flow control\n start: (options?: StartOptions) => Promise;\n canProceed(options?: ProceedOptions): boolean;\n proceed: (options?: ProceedOptions) => Promise;\n\n // call `start` instead of `startTransaction`. `startTransaction` will be removed in next major version (7.0)\n startTransaction: (options?: StartOptions) => Promise;\n\n // transaction meta\n getSavedTransactionMeta: (options?: IdxTransactionMetaOptions) => IdxTransactionMeta | undefined;\n createTransactionMeta: (options?: IdxTransactionMetaOptions) => Promise;\n getTransactionMeta: (options?: IdxTransactionMetaOptions) => Promise;\n saveTransactionMeta: (meta: unknown) => void;\n clearTransactionMeta: () => void;\n isTransactionMetaValid: (meta: unknown) => boolean;\n}\n\nexport interface IdxAPI {\n // lowest level api\n interact: (options?: InteractOptions) => Promise;\n introspect: (options?: IntrospectOptions) => Promise;\n makeIdxResponse: (rawIdxResponse: RawIdxResponse, toPersist: IdxToPersist, requestDidSucceed: boolean) => IdxResponse;\n\n // flow entrypoints\n authenticate: (options?: AuthenticationOptions) => Promise;\n register: (options?: RegistrationOptions) => Promise;\n recoverPassword: (options?: PasswordRecoveryOptions) => Promise;\n unlockAccount: (options?: AccountUnlockOptions) => Promise;\n poll: (options?: IdxPollOptions) => Promise;\n\n // flow control\n start: (options?: StartOptions) => Promise;\n canProceed(options?: ProceedOptions): boolean;\n proceed: (options?: ProceedOptions) => Promise;\n cancel: (options?: CancelOptions) => Promise;\n getFlow(): FlowIdentifier | undefined;\n setFlow(flow: FlowIdentifier): void;\n\n // call `start` instead of `startTransaction`. `startTransaction` will be removed in next major version (7.0)\n startTransaction: (options?: StartOptions) => Promise;\n\n // redirect callbacks\n isInteractionRequired: (hashOrSearch?: string) => boolean;\n isInteractionRequiredError: (error: Error) => boolean; \n handleInteractionCodeRedirect: (url: string) => Promise;\n isEmailVerifyCallback: (search: string) => boolean;\n parseEmailVerifyCallback: (search: string) => EmailVerifyCallbackResponse;\n handleEmailVerifyCallback: (search: string) => Promise;\n isEmailVerifyCallbackError: (error: Error) => boolean;\n\n // transaction meta\n getSavedTransactionMeta: (options?: IdxTransactionMetaOptions) => IdxTransactionMeta | undefined;\n createTransactionMeta: (options?: IdxTransactionMetaOptions) => Promise;\n getTransactionMeta: (options?: IdxTransactionMetaOptions) => Promise;\n saveTransactionMeta: (meta: unknown) => void;\n clearTransactionMeta: () => void;\n isTransactionMetaValid: (meta: unknown) => boolean;\n}\n\nexport interface IdxTransactionManagerInterface extends TransactionManagerInterface {\n saveIdxResponse(data: SavedIdxResponse): void;\n loadIdxResponse(options?: IntrospectOptions): SavedIdxResponse | null;\n clearIdxResponse(): void;\n}\n\nexport type IdxTransactionManagerConstructor = TransactionManagerConstructor;\n\nexport interface WebauthnAPI {\n getAssertion(credential: PublicKeyCredential): WebauthnVerificationValues;\n getAttestation(credential: PublicKeyCredential): WebauthnEnrollValues;\n buildCredentialRequestOptions(\n challengeData: ChallengeData, authenticatorEnrollments: IdxAuthenticator[]\n ): CredentialRequestOptions;\n buildCredentialCreationOptions(\n activationData: ActivationData, authenticatorEnrollments: IdxAuthenticator[]\n ): CredentialCreationOptions;\n}\n\n\nexport interface OktaAuthIdxInterface\n<\n M extends IdxTransactionMeta = IdxTransactionMeta,\n S extends IdxStorageManagerInterface = IdxStorageManagerInterface,\n O extends OktaAuthIdxOptions = OktaAuthIdxOptions,\n TM extends IdxTransactionManagerInterface = IdxTransactionManagerInterface\n>\n extends OktaAuthOAuthInterface\n{\n idx: IdxAPI;\n fingerprint: FingerprintAPI;\n}\n\nexport interface MinimalOktaAuthIdxInterface\n<\n M extends IdxTransactionMeta = IdxTransactionMeta,\n S extends IdxStorageManagerInterface = IdxStorageManagerInterface,\n O extends OktaAuthIdxOptions = OktaAuthIdxOptions,\n TM extends IdxTransactionManagerInterface = IdxTransactionManagerInterface\n>\n extends MinimalOktaOAuthInterface\n{\n idx: MinimalIdxAPI;\n fingerprint: FingerprintAPI;\n}\n\nexport interface OktaAuthIdxConstructor\n<\n I extends MinimalOktaAuthIdxInterface = OktaAuthIdxInterface\n>\n extends OktaAuthConstructor\n{\n new(...args: any[]): I;\n webauthn: WebauthnAPI;\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n/* global window */\n\nexport function getNativeConsole() {\n if (typeof window !== 'undefined') {\n return window.console;\n } else if (typeof console !== 'undefined') {\n return console;\n } else {\n return undefined;\n }\n}\n\nexport function getConsole() {\n var nativeConsole = getNativeConsole();\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n if (nativeConsole && nativeConsole.log) {\n return nativeConsole;\n }\n return {\n log: function() {},\n warn: function() {},\n group: function() {},\n groupEnd: function() {}\n };\n}\n\nexport function warn(text) {\n /* eslint-disable no-console */\n getConsole().warn('[okta-auth-sdk] WARN: ' + text);\n /* eslint-enable */\n}\n\nexport function deprecate(text) {\n /* eslint-disable no-console */\n getConsole().warn('[okta-auth-sdk] DEPRECATION: ' + text);\n /* eslint-enable */\n}\n\nexport function deprecateWrap(text, fn) {\n return function() {\n deprecate(text);\n return fn.apply(null, arguments);\n };\n}\n\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nexport function bind(fn, ctx) {\n var additionalArgs = Array.prototype.slice.call(arguments, 2);\n return function() {\n var args = Array.prototype.slice.call(arguments);\n args = additionalArgs.concat(args);\n return fn.apply(ctx, args);\n };\n}\n\n// TODO: replace all references with `Object.assign` then remove this function\nexport function extend() {\n // First object will be modified!\n var obj1 = arguments[0];\n // Properties from other objects will be copied over\n var objArray = [].slice.call(arguments, 1);\n objArray.forEach(function(obj) {\n for (var prop in obj) {\n // copy over all properties with defined values\n if (Object.prototype.hasOwnProperty.call(obj, prop) && obj[prop] !== undefined) {\n obj1[prop] = obj[prop];\n }\n }\n });\n return obj1; // return the modified object\n}\n\nexport function removeNils(obj) {\n var cleaned = {};\n for (var prop in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n var value = obj[prop];\n if (value !== null && value !== undefined) {\n cleaned[prop] = value;\n }\n }\n }\n return cleaned;\n}\n\nexport function clone(obj) {\n if (obj) {\n var str = JSON.stringify(obj);\n if (str) {\n return JSON.parse(str);\n }\n }\n return obj;\n}\n\n// Analogous to _.omit\nexport function omit(obj, ...props: any[]) {\n // var props = Array.prototype.slice.call(arguments, 1);\n var newobj = {};\n for (var p in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, p) && props.indexOf(p) == -1) {\n newobj[p] = obj[p];\n }\n }\n return clone(newobj);\n}\n\nexport function find(collection, searchParams) {\n var c = collection.length;\n while (c--) {\n var item = collection[c];\n var found = true;\n for (var prop in searchParams) {\n if (!Object.prototype.hasOwnProperty.call(searchParams, prop)) {\n continue;\n }\n if (item[prop] !== searchParams[prop]) {\n found = false;\n break;\n }\n }\n if (found) {\n return item;\n }\n }\n}\n\nexport function getLink(obj, linkName, altName?) {\n if (!obj || !obj._links) {\n return;\n }\n\n var link = clone(obj._links[linkName]);\n\n // If a link has a name and we have an altName, return if they match\n if (link && link.name && altName) {\n if (link.name === altName) {\n return link;\n }\n } else {\n return link;\n }\n}\n\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nexport default class CustomError extends Error {\n constructor(message: string) {\n // https://stackoverflow.com/questions/41102060/typescript-extending-error-class\n super(message); // 'Error' breaks prototype chain here\n Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nexport function isString(obj: any): obj is string {\n return Object.prototype.toString.call(obj) === '[object String]';\n}\n\nexport function isObject(obj: any): obj is object {\n return Object.prototype.toString.call(obj) === '[object Object]';\n}\n\nexport function isNumber(obj: any): obj is number {\n return Object.prototype.toString.call(obj) === '[object Number]';\n}\n\nexport function isFunction(fn: any): fn is (...any: any[]) => any {\n return !!fn && {}.toString.call(fn) === '[object Function]';\n}\n\nexport function isPromise(obj) {\n return obj && obj.finally && (typeof obj.finally === 'function');\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport type { HttpResponse } from '../http';\nimport CustomError from './CustomError';\nimport { isFunction } from '../util';\n\n// Error thrown after an unsuccessful network request which requires an Authorization header \n// and returns a 4XX error with a www-authenticate header. The header value is parsed to construct \n// an error instance, which contains key/value pairs parsed out\nexport default class WWWAuthError extends CustomError {\n static UNKNOWN_ERROR = 'UNKNOWN_WWW_AUTH_ERROR';\n\n scheme: string;\n parameters: Record;\n name = 'WWWAuthError';\n\n resp: HttpResponse | null = null;\n\n constructor(scheme: string, parameters: Record, resp?: HttpResponse) {\n // defaults to unknown error. `error` being returned in the www-authenticate header is expected\n // but cannot be guaranteed. Throwing an error within a error constructor seems awkward\n super(parameters.error ?? WWWAuthError.UNKNOWN_ERROR);\n this.scheme = scheme;\n this.parameters = parameters;\n\n if (resp) {\n this.resp = resp;\n }\n }\n\n // convenience references\n get error (): string { return this.parameters.error; }\n get errorCode (): string { return this.error; } // parity with other error props\n // eslint-disable-next-line camelcase\n get error_description (): string { return this.parameters.error_description; }\n // eslint-disable-next-line camelcase\n get errorDescription (): string { return this.error_description; }\n get errorSummary (): string { return this.errorDescription; } // parity with other error props\n get realm (): string { return this.parameters.realm; }\n\n // parses the www-authenticate header for releveant\n static parseHeader (header: string): WWWAuthError | null {\n // header cannot be empty string\n if (!header) {\n return null;\n }\n\n // example string: Bearer error=\"invalid_token\", error_description=\"The access token is invalid\"\n // regex will match on `error=\"invalid_token\", error_description=\"The access token is invalid\"`\n // see unit test for more examples of possible www-authenticate values\n // eslint-disable-next-line max-len\n const regex = /(?:,|, )?([a-zA-Z0-9!#$%&'*+\\-.^_`|~]+)=(?:\"([a-zA-Z0-9!#$%&'*+\\-.,^_`|~ /:]+)\"|([a-zA-Z0-9!#$%&'*+\\-.^_`|~/:]+))/g;\n const firstSpace = header.indexOf(' ');\n const scheme = header.slice(0, firstSpace);\n const remaining = header.slice(firstSpace + 1);\n const params = {};\n\n // Reference: foo=\"hello\", bar=\"bye\"\n // i=0, match=[foo=\"hello1\", foo, hello]\n // i=1, match=[bar=\"bye\", bar, bye]\n let match;\n while ((match = regex.exec(remaining)) !== null) {\n params[match[1]] = (match[2] ?? match[3]);\n }\n\n return new WWWAuthError(scheme, params);\n }\n\n // finds the value of the `www-authenticate` header. HeadersInit allows for a few different\n // representations of headers with different access patterns (.get vs [key])\n static getWWWAuthenticateHeader (headers: HeadersInit = {}): string | null {\n if (isFunction((headers as Headers)?.get)) {\n return (headers as Headers).get('WWW-Authenticate');\n }\n return headers['www-authenticate'] ?? headers['WWW-Authenticate'];\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nexport function isoToUTCString(str) {\n var parts = str.match(/\\d+/g),\n isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]),\n isoDate = new Date(isoTime);\n\n return isoDate.toUTCString();\n}\n\nexport function genRandomString(length) {\n var randomCharset = 'abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';\n var random = '';\n for (var c = 0, cl = randomCharset.length; c < length; ++c) {\n random += randomCharset[Math.floor(Math.random() * cl)];\n }\n return random;\n}\n\nexport function delay(ms) {\n return new Promise(function(resolve) {\n setTimeout(resolve, ms);\n });\n}\n\nexport function split2(str, delim) {\n const parts = str.split(delim);\n return [\n parts[0], \n parts.splice(1, parts.length).join(delim),\n ];\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nexport function isAbsoluteUrl(url) {\n return /^[a-z][a-z0-9+.-]*:/i.test(url);\n}\n\nexport function toAbsoluteUrl(url = '', baseUrl) {\n if (isAbsoluteUrl(url)) {\n return url;\n }\n baseUrl = removeTrailingSlash(baseUrl);\n return url[0] === '/' ? `${baseUrl}${url}` : `${baseUrl}/${url}`;\n}\n\nexport function toRelativeUrl(url = '', baseUrl) {\n if (isAbsoluteUrl(url)) {\n url = url.substring(baseUrl.length);\n }\n\n return url[0] === '/' ? url : `/${url}`;\n}\n\nexport function toQueryString(obj) {\n var str = [];\n if (obj !== null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key) &&\n obj[key] !== undefined &&\n obj[key] !== null) {\n str.push(key + '=' + encodeURIComponent(obj[key]) as never);\n }\n }\n }\n if (str.length) {\n return '?' + str.join('&');\n } else {\n return '';\n }\n}\n\nexport function removeTrailingSlash(path) {\n if (!path) {\n return;\n }\n // Remove any whitespace before or after string\n var trimmed = path.replace(/^\\s+|\\s+$/gm,'');\n // Remove trailing slash(es)\n trimmed = trimmed.replace(/\\/+$/, '');\n\n return trimmed;\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport CustomError from './CustomError';\nimport { APIError, FieldError } from './types';\n\nexport default class AuthSdkError extends CustomError implements APIError {\n errorSummary: string;\n errorCode: string;\n errorLink: string;\n errorId: string;\n errorCauses: Array;\n xhr?: XMLHttpRequest;\n\n constructor(msg: string, xhr?: XMLHttpRequest) {\n super(msg);\n this.name = 'AuthSdkError';\n this.errorCode = 'INTERNAL';\n this.errorSummary = msg;\n this.errorLink = 'INTERNAL';\n this.errorId = 'INTERNAL';\n this.errorCauses = [];\n if (xhr) {\n this.xhr = xhr;\n }\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n/* eslint-disable complexity, max-statements */\nimport { genRandomString, removeTrailingSlash } from '../../util';\nimport AuthSdkError from '../../errors/AuthSdkError';\nimport { OktaAuthOAuthInterface, CustomUrls } from '../types';\n\nexport function generateState() {\n return genRandomString(64);\n}\n\nexport function generateNonce() {\n return genRandomString(64);\n}\n\nfunction getIssuer(sdk: OktaAuthOAuthInterface, options: CustomUrls = {}) {\n const issuer = removeTrailingSlash(options.issuer) || sdk.options.issuer;\n return issuer;\n}\n\nexport function getOAuthBaseUrl(sdk: OktaAuthOAuthInterface, options: CustomUrls = {}) {\n const issuer = getIssuer(sdk, options);\n const baseUrl = issuer.indexOf('/oauth2') > 0 ? issuer : issuer + '/oauth2';\n return baseUrl;\n}\n\nexport function getOAuthDomain(sdk: OktaAuthOAuthInterface, options: CustomUrls = {}) {\n const issuer = getIssuer(sdk, options);\n const domain = issuer.split('/oauth2')[0];\n return domain;\n}\n\nexport function getOAuthUrls(sdk: OktaAuthOAuthInterface, options?: CustomUrls): CustomUrls {\n if (arguments.length > 2) {\n throw new AuthSdkError('As of version 3.0, \"getOAuthUrls\" takes only a single set of options');\n }\n options = options || {};\n\n // Get user-supplied arguments\n var authorizeUrl = removeTrailingSlash(options.authorizeUrl) || sdk.options.authorizeUrl;\n var issuer = getIssuer(sdk, options);\n var userinfoUrl = removeTrailingSlash(options.userinfoUrl) || sdk.options.userinfoUrl;\n var tokenUrl = removeTrailingSlash(options.tokenUrl) || sdk.options.tokenUrl;\n var logoutUrl = removeTrailingSlash(options.logoutUrl) || sdk.options.logoutUrl;\n var revokeUrl = removeTrailingSlash(options.revokeUrl) || sdk.options.revokeUrl;\n\n var baseUrl = getOAuthBaseUrl(sdk, options);\n\n authorizeUrl = authorizeUrl || baseUrl + '/v1/authorize';\n userinfoUrl = userinfoUrl || baseUrl + '/v1/userinfo';\n tokenUrl = tokenUrl || baseUrl + '/v1/token';\n revokeUrl = revokeUrl || baseUrl + '/v1/revoke';\n logoutUrl = logoutUrl || baseUrl + '/v1/logout';\n\n return {\n issuer: issuer,\n authorizeUrl: authorizeUrl,\n userinfoUrl: userinfoUrl,\n tokenUrl: tokenUrl,\n revokeUrl: revokeUrl,\n logoutUrl: logoutUrl\n };\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport { OAuthTransactionMeta, OktaAuthOAuthInterface, PKCETransactionMeta, TokenParams } from '../types';\nimport { getOAuthUrls } from './oauth';\n\nexport function createOAuthMeta(\n sdk: OktaAuthOAuthInterface, \n tokenParams: TokenParams\n): OAuthTransactionMeta | PKCETransactionMeta {\n const issuer = sdk.options.issuer!;\n const urls = getOAuthUrls(sdk, tokenParams);\n const oauthMeta: OAuthTransactionMeta = {\n issuer,\n urls,\n clientId: tokenParams.clientId!,\n redirectUri: tokenParams.redirectUri!,\n responseType: tokenParams.responseType!,\n responseMode: tokenParams.responseMode!,\n scopes: tokenParams.scopes!,\n state: tokenParams.state!,\n nonce: tokenParams.nonce!,\n ignoreSignature: tokenParams.ignoreSignature!,\n acrValues: tokenParams.acrValues,\n extraParams: tokenParams.extraParams\n };\n\n if (tokenParams.pkce === false) {\n // Implicit flow or authorization_code without PKCE\n return oauthMeta;\n }\n\n const pkceMeta: PKCETransactionMeta = {\n ...oauthMeta,\n codeVerifier: tokenParams.codeVerifier!,\n codeChallengeMethod: tokenParams.codeChallengeMethod!,\n codeChallenge: tokenParams.codeChallenge!,\n };\n\n return pkceMeta;\n}\n", "/*! js-cookie v3.0.5 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (name, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n name = encodeURIComponent(name)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n name + '=' + converter.write(value, name) + stringifiedAttributes)\n }\n\n function get (name) {\n if (typeof document === 'undefined' || (arguments.length && !name)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var found = decodeURIComponent(parts[0]);\n jar[found] = converter.read(value, found);\n\n if (name === found) {\n break\n }\n } catch (e) {}\n }\n\n return name ? jar[name] : jar\n }\n\n return Object.create(\n {\n set,\n get,\n remove: function (name, attributes) {\n set(\n name,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport { api as default };\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { UserClaims } from './UserClaims';\n\nexport interface AbstractToken {\n expiresAt: number;\n authorizeUrl: string;\n scopes: string[];\n pendingRemove?: boolean;\n extraParams?: Record;\n}\n\nexport interface AccessToken extends AbstractToken {\n accessToken: string;\n claims: UserClaims;\n tokenType: string;\n userinfoUrl: string;\n dpopPairId?: string;\n}\n\nexport interface RefreshToken extends AbstractToken {\n refreshToken: string;\n tokenUrl: string;\n issuer: string;\n dpopPairId?: string;\n}\n\nexport interface IDToken extends AbstractToken {\n idToken: string;\n claims: UserClaims;\n issuer: string;\n clientId: string;\n}\n\nexport type Token = AccessToken | IDToken | RefreshToken;\nexport type RevocableToken = AccessToken | RefreshToken;\n\nexport type TokenType = 'accessToken' | 'idToken' | 'refreshToken';\nexport enum TokenKind {\n ACCESS = 'accessToken',\n ID = 'idToken',\n REFRESH = 'refreshToken',\n}\n\nexport function isToken(obj: any): obj is Token {\n if (obj &&\n (obj.accessToken || obj.idToken || obj.refreshToken) &&\n Array.isArray(obj.scopes)) {\n return true;\n }\n return false;\n}\n\nexport function isAccessToken(obj: any): obj is AccessToken {\n return obj && obj.accessToken;\n}\n\nexport function isIDToken(obj: any): obj is IDToken {\n return obj && obj.idToken;\n}\n\nexport function isRefreshToken(obj: any): obj is RefreshToken {\n return obj && obj.refreshToken;\n}\n\nexport interface Tokens {\n accessToken?: AccessToken;\n idToken?: IDToken;\n refreshToken?: RefreshToken;\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2021, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { OktaAuthIdxInterface, IdxTransactionMeta, IdxTransactionMetaOptions } from './types';\nimport { removeNils, warn } from '../util';\nimport { createOAuthMeta, PKCETransactionMeta } from '../oidc';\n\n// Calculate new values\nexport async function createTransactionMeta(\n authClient: OktaAuthIdxInterface,\n options: IdxTransactionMetaOptions = {}\n): Promise {\n const tokenParams = await authClient.token.prepareTokenParams(options);\n const pkceMeta = createOAuthMeta(authClient, tokenParams) as PKCETransactionMeta;\n let {\n flow = 'default',\n withCredentials = true,\n activationToken = undefined,\n recoveryToken = undefined,\n maxAge = undefined,\n acrValues = undefined,\n } = { ...authClient.options, ...options }; // local options override SDK options\n\n const meta: IdxTransactionMeta = {\n ...pkceMeta,\n flow,\n withCredentials,\n activationToken,\n recoveryToken,\n maxAge,\n acrValues\n };\n return meta;\n}\n\nexport function hasSavedInteractionHandle(\n authClient: OktaAuthIdxInterface,\n options?: IdxTransactionMetaOptions\n): boolean {\n const savedMeta = getSavedTransactionMeta(authClient, options);\n if (savedMeta?.interactionHandle) {\n return true;\n }\n return false;\n}\n\n// Returns the saved transaction meta, if it exists and is valid\nexport function getSavedTransactionMeta(\n authClient: OktaAuthIdxInterface,\n options?: IdxTransactionMetaOptions\n): IdxTransactionMeta | undefined {\n options = removeNils(options);\n options = { ...authClient.options, ...options }; // local options override SDK options\n let savedMeta;\n try {\n savedMeta = authClient.transactionManager.load(options) as IdxTransactionMeta;\n } catch (e) {\n // ignore errors here\n }\n\n if (!savedMeta) {\n return;\n }\n\n if (isTransactionMetaValid(savedMeta, options)) {\n return savedMeta;\n }\n\n // existing meta is not valid for this configuration\n // this is common when changing configuration in local development environment\n // in a production environment, this may indicate that two apps are sharing a storage key\n warn('Saved transaction meta does not match the current configuration. ' + \n 'This may indicate that two apps are sharing a storage key.');\n\n}\n\nexport async function getTransactionMeta(\n authClient: OktaAuthIdxInterface,\n options?: IdxTransactionMetaOptions\n): Promise {\n options = removeNils(options);\n options = { ...authClient.options, ...options }; // local options override SDK options\n // Load existing transaction meta from storage\n const validExistingMeta = getSavedTransactionMeta(authClient, options);\n if (validExistingMeta) {\n return validExistingMeta;\n }\n // No existing? Create new transaction meta.\n return createTransactionMeta(authClient, options);\n}\n\nexport function saveTransactionMeta (authClient: OktaAuthIdxInterface, meta): void {\n authClient.transactionManager.save(meta, { muteWarning: true });\n}\n\nexport function clearTransactionMeta (authClient: OktaAuthIdxInterface): void {\n authClient.transactionManager.clear();\n}\n\nexport function isTransactionMetaValid (meta, options: IdxTransactionMetaOptions = {}): boolean {\n // Validate against certain options. If these exist in options, they must match in meta\n const keys = [\n 'issuer',\n 'clientId',\n 'redirectUri',\n 'state',\n 'codeChallenge',\n 'codeChallengeMethod',\n 'activationToken',\n 'recoveryToken'\n ];\n if (isTransactionMetaValidForOptions(meta, options, keys) === false) {\n return false;\n }\n\n // Validate configured flow\n const { flow } = options;\n if (isTransactionMetaValidForFlow(meta, flow) === false) {\n return false;\n }\n\n return true;\n}\n\nexport function isTransactionMetaValidForFlow(meta, flow) {\n // Specific flows should not share transaction data\n const shouldValidateFlow = flow && flow !== 'default' && flow !== 'proceed';\n if (shouldValidateFlow) {\n if (flow !== meta.flow) {\n // The flow has changed; abandon the old transaction\n return false;\n }\n }\n return true;\n}\n\nexport function isTransactionMetaValidForOptions(meta, options, keys) {\n // returns false if values in meta do not match options\n // if the option does not have a value for a specific key, it is ignored\n const mismatch = keys.some(key => {\n const value = options[key];\n if (value && value !== meta[key]) {\n return true;\n }\n });\n return !mismatch;\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nexport const STATE_TOKEN_KEY_NAME = 'oktaStateToken';\nexport const DEFAULT_POLLING_DELAY = 500;\nexport const DEFAULT_MAX_CLOCK_SKEW = 300;\nexport const DEFAULT_CACHE_DURATION = 86400;\nexport const TOKEN_STORAGE_NAME = 'okta-token-storage';\nexport const CACHE_STORAGE_NAME = 'okta-cache-storage';\nexport const PKCE_STORAGE_NAME = 'okta-pkce-storage';\nexport const TRANSACTION_STORAGE_NAME = 'okta-transaction-storage';\nexport const SHARED_TRANSACTION_STORAGE_NAME = 'okta-shared-transaction-storage';\nexport const ORIGINAL_URI_STORAGE_NAME = 'okta-original-uri-storage';\nexport const IDX_RESPONSE_STORAGE_NAME = 'okta-idx-response-storage';\nexport const ACCESS_TOKEN_STORAGE_KEY = 'accessToken';\nexport const ID_TOKEN_STORAGE_KEY = 'idToken';\nexport const REFRESH_TOKEN_STORAGE_KEY = 'refreshToken';\nexport const REFERRER_PATH_STORAGE_KEY = 'referrerPath';\n\n// Code verifier: Random URL-safe string with a minimum length of 43 characters.\n// Code challenge: Base64 URL-encoded SHA-256 hash of the code verifier.\nexport const MIN_VERIFIER_LENGTH = 43;\nexport const MAX_VERIFIER_LENGTH = 128;\nexport const DEFAULT_CODE_CHALLENGE_METHOD = 'S256';\n\nexport const IDX_API_VERSION = '1.0.0';", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport CustomError from './CustomError';\nimport { HttpResponse } from '../http/types';\nimport { APIError, FieldError } from './types';\n\nexport default class AuthApiError extends CustomError implements APIError {\n errorSummary: string;\n errorCode?: string;\n errorLink?: string;\n errorId?: string;\n errorCauses?: Array;\n xhr?: HttpResponse;\n meta?: Record;\n\n constructor(err: APIError, xhr?: HttpResponse, meta?: Record) {\n const message = err.errorSummary;\n super(message);\n\n this.name = 'AuthApiError';\n this.errorSummary = err.errorSummary;\n this.errorCode = err.errorCode;\n this.errorLink = err.errorLink;\n this.errorId = err.errorId;\n this.errorCauses = err.errorCauses;\n\n if (xhr) {\n this.xhr = xhr;\n }\n\n if (meta) {\n this.meta = meta;\n }\n }\n}\n", "/* eslint-disable camelcase */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport CustomError from './CustomError';\nimport type { HttpResponse } from '../http';\n\nexport default class OAuthError extends CustomError {\n errorCode: string;\n errorSummary: string;\n\n // for widget / idx-js backward compatibility\n error: string;\n error_description: string;\n\n resp: HttpResponse | null = null;\n\n constructor(errorCode: string, summary: string, resp?: HttpResponse) {\n super(summary);\n\n this.name = 'OAuthError';\n this.errorCode = errorCode;\n this.errorSummary = summary;\n\n // for widget / idx-js backward compatibility\n this.error = errorCode;\n this.error_description = summary;\n\n // an OAuth error (should) always result from a network request\n // therefore include that in error for potential error handling\n if (resp) {\n this.resp = resp;\n }\n }\n}\n\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\n/* eslint-disable complexity */\nimport { isString, clone, isAbsoluteUrl, removeNils } from '../util';\nimport { STATE_TOKEN_KEY_NAME, DEFAULT_CACHE_DURATION } from '../constants';\nimport {\n OktaAuthHttpInterface,\n RequestOptions,\n FetchOptions,\n RequestData,\n HttpResponse\n} from './types';\nimport { AuthApiError, OAuthError, APIError, WWWAuthError } from '../errors';\n\n\nconst formatError = (sdk: OktaAuthHttpInterface, error: HttpResponse | Error): AuthApiError | OAuthError => {\n if (error instanceof Error) {\n // fetch() can throw exceptions\n // see https://developer.mozilla.org/en-US/docs/Web/API/fetch#exceptions\n return new AuthApiError({\n errorSummary: error.message,\n });\n }\n\n let resp: HttpResponse = error;\n let err: AuthApiError | OAuthError | WWWAuthError;\n let serverErr: Record = {};\n if (resp.responseText && isString(resp.responseText)) {\n try {\n serverErr = JSON.parse(resp.responseText);\n } catch (e) {\n serverErr = {\n errorSummary: 'Unknown error'\n };\n }\n }\n\n if (resp.status >= 500) {\n serverErr.errorSummary = 'Unknown error';\n }\n\n if (sdk.options.transformErrorXHR) {\n resp = sdk.options.transformErrorXHR(clone(resp));\n }\n\n // \n const wwwAuthHeader = WWWAuthError.getWWWAuthenticateHeader(resp?.headers) ?? '';\n\n if (serverErr.error && serverErr.error_description) {\n err = new OAuthError(serverErr.error, serverErr.error_description, resp);\n } else {\n err = new AuthApiError(serverErr as APIError, resp, { wwwAuthHeader });\n }\n\n if (wwwAuthHeader && resp?.status >= 400 && resp?.status < 500) {\n const wwwAuthErr = WWWAuthError.parseHeader(wwwAuthHeader);\n // check for 403 to avoid breaking change\n if (resp.status === 403 && wwwAuthErr?.error === 'insufficient_authentication_context') {\n // eslint-disable-next-line camelcase\n const { max_age, acr_values } = wwwAuthErr.parameters;\n err = new AuthApiError(\n {\n errorSummary: wwwAuthErr.error,\n errorCauses: [{ errorSummary: wwwAuthErr.errorDescription }]\n },\n resp,\n {\n // eslint-disable-next-line camelcase\n max_age: +max_age,\n // eslint-disable-next-line camelcase\n ...(acr_values && { acr_values })\n }\n );\n }\n else if (wwwAuthErr?.scheme === 'DPoP') {\n err = wwwAuthErr;\n }\n // else {\n // // WWWAuthError.parseHeader may return null, only overwrite if !null\n // err = wwwAuthErr ?? err;\n // }\n }\n\n return err;\n};\n\nexport function httpRequest(sdk: OktaAuthHttpInterface, options: RequestOptions): Promise {\n options = options || {};\n\n if (sdk.options.httpRequestInterceptors) {\n for (const interceptor of sdk.options.httpRequestInterceptors) {\n interceptor(options);\n }\n }\n\n var url = options.url,\n method = options.method,\n args = options.args,\n saveAuthnState = options.saveAuthnState,\n accessToken = options.accessToken,\n withCredentials = options.withCredentials === true, // default value is false\n storageUtil = sdk.options.storageUtil,\n storage = storageUtil!.storage,\n httpCache = sdk.storageManager.getHttpCache(sdk.options.cookies);\n\n if (options.cacheResponse) {\n var cacheContents = httpCache.getStorage();\n var cachedResponse = cacheContents[url as string];\n if (cachedResponse && Date.now()/1000 < cachedResponse.expiresAt) {\n return Promise.resolve(cachedResponse.response);\n }\n }\n\n var oktaUserAgentHeader = sdk._oktaUserAgent.getHttpHeader();\n var headers: HeadersInit = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n ...oktaUserAgentHeader\n };\n Object.assign(headers, sdk.options.headers, options.headers);\n headers = removeNils(headers) as HeadersInit;\n\n if (accessToken && isString(accessToken)) {\n headers['Authorization'] = 'Bearer ' + accessToken;\n }\n\n var ajaxOptions: FetchOptions = {\n headers,\n data: args || undefined,\n withCredentials\n };\n\n var err, res;\n return sdk.options.httpRequestClient!(method!, url!, ajaxOptions)\n .then(function(resp) {\n res = resp.responseText;\n if (res && isString(res)) {\n res = JSON.parse(res);\n if (res && typeof res === 'object' && !res.headers) {\n if (Array.isArray(res)) {\n res.forEach(item => {\n item.headers = resp.headers;\n });\n } else {\n res.headers = resp.headers;\n }\n }\n }\n\n if (saveAuthnState) {\n if (!res.stateToken) {\n storage.delete(STATE_TOKEN_KEY_NAME);\n }\n }\n\n if (res && res.stateToken && res.expiresAt) {\n storage.set(STATE_TOKEN_KEY_NAME, res.stateToken, res.expiresAt, sdk.options.cookies!);\n }\n\n if (res && options.cacheResponse) {\n httpCache.updateStorage(url!, {\n expiresAt: Math.floor(Date.now()/1000) + DEFAULT_CACHE_DURATION,\n response: res\n });\n }\n \n return res;\n })\n .catch(function(resp) {\n err = formatError(sdk, resp);\n\n if (err.errorCode === 'E0000011') {\n storage.delete(STATE_TOKEN_KEY_NAME);\n }\n\n throw err;\n });\n}\n\nexport function get(sdk: OktaAuthHttpInterface, url: string, options?: RequestOptions) {\n url = isAbsoluteUrl(url) ? url : sdk.getIssuerOrigin() + url;\n var getOptions = {\n url: url,\n method: 'GET'\n };\n Object.assign(getOptions, options);\n return httpRequest(sdk, getOptions);\n}\n\nexport function post(sdk: OktaAuthHttpInterface, url: string, args?: RequestData, options?: RequestOptions) {\n url = isAbsoluteUrl(url) ? url : sdk.getIssuerOrigin() + url;\n var postOptions = {\n url: url,\n method: 'POST',\n args: args,\n saveAuthnState: true\n };\n Object.assign(postOptions, options);\n return httpRequest(sdk, postOptions);\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2021, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n/* eslint complexity:[0,8] */\nimport { OktaAuthIdxInterface, IdxTransactionMeta, InteractOptions, InteractResponse } from './types';\nimport { getSavedTransactionMeta, saveTransactionMeta, createTransactionMeta } from './transactionMeta';\nimport { getOAuthBaseUrl } from '../oidc';\nimport { removeNils } from '../util';\nimport { httpRequest } from '../http';\n\n\n/* eslint-disable camelcase */\nexport interface InteractParams {\n client_id: string;\n scope: string;\n redirect_uri: string;\n code_challenge: string;\n code_challenge_method: string;\n state: string;\n activation_token?: string;\n recovery_token?: string;\n client_secret?: string;\n max_age?: string | number;\n acr_values?: string;\n nonce?: string;\n}\n/* eslint-enable camelcase */\n\nfunction getResponse(meta: IdxTransactionMeta): InteractResponse {\n return {\n meta,\n interactionHandle: meta.interactionHandle!,\n state: meta.state\n };\n}\n\n// Begin or resume a transaction. Returns an interaction handle\nexport async function interact (\n authClient: OktaAuthIdxInterface, \n options: InteractOptions = {}\n): Promise {\n options = removeNils(options);\n\n let meta = getSavedTransactionMeta(authClient, options);\n // If meta exists, it has been validated against all options\n\n if (meta?.interactionHandle) {\n return getResponse(meta); // Saved transaction, return meta\n }\n\n // Create new meta, respecting previous meta if it has been set and is not overridden\n meta = await createTransactionMeta(authClient, { ...meta, ...options });\n const baseUrl = getOAuthBaseUrl(authClient);\n let {\n clientId,\n redirectUri,\n state,\n scopes,\n withCredentials,\n codeChallenge,\n codeChallengeMethod,\n activationToken,\n recoveryToken,\n maxAge,\n acrValues,\n nonce\n } = meta as IdxTransactionMeta;\n const clientSecret = options.clientSecret || authClient.options.clientSecret;\n withCredentials = withCredentials ?? true;\n\n /* eslint-disable camelcase */\n const url = `${baseUrl}/v1/interact`;\n const params = {\n client_id: clientId,\n scope: scopes!.join(' '),\n redirect_uri: redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: codeChallengeMethod,\n state,\n ...(activationToken && { activation_token: activationToken }),\n ...(recoveryToken && { recovery_token: recoveryToken }),\n // X-Device-Token header need to pair with `client_secret`\n // eslint-disable-next-line max-len\n // https://oktawiki.atlassian.net/wiki/spaces/eng/pages/2445902453/Support+Device+Binding+in+interact#Scenario-1%3A-Non-User-Agent-with-Confidential-Client-(top-priority)\n ...(clientSecret && { client_secret: clientSecret }),\n ...(maxAge && { max_age: maxAge }),\n ...(acrValues && { acr_values: acrValues }),\n ...(nonce && { nonce }),\n } as InteractParams;\n /* eslint-enable camelcase */\n\n const headers = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n const resp = await httpRequest(authClient, {\n method: 'POST',\n url,\n headers,\n withCredentials,\n args: params\n });\n const interactionHandle = resp.interaction_handle;\n\n const newMeta = {\n ...meta,\n interactionHandle,\n \n // Options which can be passed into interact() should be saved in the meta\n withCredentials,\n state,\n scopes,\n recoveryToken,\n activationToken\n };\n // Save transaction meta so it can be resumed\n saveTransactionMeta(authClient, newMeta);\n\n return getResponse(newMeta);\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\n\nexport { __rest };\n//# sourceMappingURL=_tslib.js.map\n", "/*!\n * Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-nocheck\nconst isFieldMutable = function isFieldMutable(field) {\n // mutable defaults to true, annoyingly\n return ( field.mutable !== false );\n};\n\nconst divideSingleActionParamsByMutability = function divideSingleActionParamsByMutability( action ) {\n const defaultParamsForAction = {}; // mutable and present\n const neededParamsForAction = []; // mutable values\n const immutableParamsForAction = {}; // immutable\n // TODO: remove assumption that form names are unique, neededParams being an array is a temp fix\n // not all actions have value (e.g. redirect)\n // making sure they are not empty and instead hold the remediation object\n if (!action.value) {\n neededParamsForAction.push(action);\n return { defaultParamsForAction, neededParamsForAction, immutableParamsForAction };\n }\n\n for ( let field of action.value ) {\n\n if ( isFieldMutable( field ) ) {\n\n neededParamsForAction.push(field);\n\n if ( field.value ?? false ) {\n defaultParamsForAction[field.name] = field.value;\n }\n\n } else {\n immutableParamsForAction[field.name] = field.value ?? '';\n }\n }\n return { defaultParamsForAction, neededParamsForAction, immutableParamsForAction };\n};\n\nexport const divideActionParamsByMutability = function divideActionParamsByMutability( actionList ) {\n // TODO: when removing form name is unique assumption, this may all be redundant\n actionList = Array.isArray(actionList) ? actionList : [ actionList ];\n const neededParams = [];\n const defaultParams = {};\n const immutableParams = {};\n\n for ( let action of actionList ) {\n const { \n defaultParamsForAction, \n neededParamsForAction, \n immutableParamsForAction \n } = divideSingleActionParamsByMutability(action);\n neededParams.push(neededParamsForAction);\n defaultParams[action.name] = defaultParamsForAction;\n immutableParams[action.name] = immutableParamsForAction;\n }\n\n return { defaultParams, neededParams, immutableParams };\n};\n\n", "/*!\n * Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n/* eslint-disable max-len, complexity */\nimport { httpRequest } from '../../../http';\nimport { OktaAuthIdxInterface } from '../../types'; // auth-js/types\nimport { IdxActionFunction, IdxActionParams, IdxResponse, IdxToPersist } from '../../types/idx-js';\nimport { divideActionParamsByMutability } from './actionParser';\nimport AuthApiError from '../../../errors/AuthApiError';\n\nconst generateDirectFetch = function generateDirectFetch(authClient: OktaAuthIdxInterface, { \n actionDefinition, \n defaultParamsForAction = {}, \n immutableParamsForAction = {}, \n toPersist = {} as IdxToPersist\n}): IdxActionFunction {\n const target = actionDefinition.href;\n return async function(params: IdxActionParams = {}): Promise {\n const headers = {\n 'Content-Type': 'application/json',\n 'Accept': actionDefinition.accepts || 'application/ion+json',\n };\n const body = JSON.stringify({\n ...defaultParamsForAction,\n ...params,\n ...immutableParamsForAction\n });\n\n try {\n const response = await httpRequest(authClient, {\n url: target,\n method: actionDefinition.method,\n headers,\n args: body,\n withCredentials: toPersist?.withCredentials ?? true\n });\n\n return authClient.idx.makeIdxResponse({ ...response }, toPersist, true);\n }\n catch (err) {\n if (!(err instanceof AuthApiError) || !err?.xhr) {\n throw err;\n }\n\n const response = err.xhr;\n const payload = response.responseJSON || JSON.parse(response.responseText);\n const wwwAuthHeader = response.headers['WWW-Authenticate'] || response.headers['www-authenticate'];\n\n const idxResponse = authClient.idx.makeIdxResponse({ ...payload }, toPersist, false);\n if (response.status === 401 && wwwAuthHeader === 'Oktadevicejwt realm=\"Okta Device\"') {\n // Okta server responds 401 status code with WWW-Authenticate header and new remediation\n // so that the iOS/MacOS credential SSO extension (Okta Verify) can intercept\n // the response reaches here when Okta Verify is not installed\n // set `stepUp` to true if flow should be continued without showing any errors\n idxResponse.stepUp = true;\n }\n\n return idxResponse;\n }\n };\n};\n\n// TODO: Resolve in M2: Either build the final polling solution or remove this code\n// const generatePollingFetch = function generatePollingFetch( { actionDefinition, defaultParamsForAction = {}, immutableParamsForAction = {} } ) {\n// // TODO: Discussions ongoing about when/how to terminate polling: OKTA-246581\n// const target = actionDefinition.href;\n// return async function(params) {\n// return fetch(target, {\n// method: actionDefinition.method,\n// headers: {\n// 'content-type': actionDefinition.accepts,\n// },\n// body: JSON.stringify({ ...defaultParamsForAction, ...params, ...immutableParamsForAction })\n// })\n// .then( response => response.ok ? response.json() : response.json().then( err => Promise.reject(err)) )\n// .then( idxResponse => makeIdxState(authClient, idxResponse) );\n// };\n// };\n\nconst generateIdxAction = function generateIdxAction( authClient: OktaAuthIdxInterface, actionDefinition, toPersist ): IdxActionFunction {\n // TODO: leaving this here to see where the polling is EXPECTED to drop into the code, but removing any accidental trigger of incomplete code\n // const generator = actionDefinition.refresh ? generatePollingFetch : generateDirectFetch;\n const generator = generateDirectFetch;\n const { defaultParams, neededParams, immutableParams } = divideActionParamsByMutability( actionDefinition );\n\n const action = generator(authClient, {\n actionDefinition,\n defaultParamsForAction: defaultParams[actionDefinition.name],\n immutableParamsForAction: immutableParams[actionDefinition.name],\n toPersist\n });\n action.neededParams = neededParams;\n return action;\n};\n\nexport default generateIdxAction;\n", "/*!\n * Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { OktaAuthIdxInterface, IdxRemediation } from '../../types'; // auth-js/types\nimport generateIdxAction from './generateIdxAction';\n\nexport const generateRemediationFunctions = function generateRemediationFunctions(\n authClient: OktaAuthIdxInterface,\n remediationValue: IdxRemediation[],\n toPersist = {}\n) {\n return remediationValue.reduce((obj, remediation) => ({\n ...obj,\n [remediation.name]: generateIdxAction(authClient, remediation, toPersist)\n }), {});\n};\n", "const jsonpathRegex = /\\$?(?\\w+)|(?:\\[(?\\d+)\\])/g;\n\n/* eslint complexity:[0,8] */\nexport function jsonpath({ path, json }) {\n const steps: string[] = [];\n let match: RegExpExecArray | null;\n while ((match = jsonpathRegex.exec(path)) !== null) {\n const step = match?.groups?.step ?? match?.groups?.index;\n if (step) {\n steps.push(step);\n }\n }\n\n if (steps.length < 1) {\n return undefined;\n }\n\n // array length check above guarantees .pop() will return a value\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const lastStep = steps.pop()!;\n let curr = json;\n for (const step of steps) {\n if (Object.prototype.hasOwnProperty.call(curr, step)) {\n if (typeof curr[step] !== 'object') {\n return undefined;\n }\n\n curr = curr[step];\n }\n }\n\n return curr[lastStep];\n}\n", "/*!\n * Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n/* eslint-disable max-len */\n\nimport { OktaAuthIdxInterface, IdxResponse, IdxRemediation, IdxContext } from '../../types'; // auth-js/types\nimport { IdxActions } from '../../types/idx-js';\nimport { generateRemediationFunctions } from './remediationParser';\nimport generateIdxAction from './generateIdxAction';\nimport { jsonpath } from '../../../util/jsonpath';\nimport { AuthSdkError } from '../../../errors';\n\nconst SKIP_FIELDS = {\n 'remediation': true, // remediations are put into proceed/neededToProceed\n 'context': true, // the API response of 'context' isn't externally useful. We ignore it and put all non-action (contextual) info into idxState.context\n};\n\nexport const parseNonRemediations = function parseNonRemediations( authClient: OktaAuthIdxInterface, idxResponse: IdxResponse, toPersist = {} ) {\n const actions = {};\n const context = {} as IdxContext;\n\n Object.keys(idxResponse)\n .filter( field => !SKIP_FIELDS[field])\n .forEach( field => {\n const fieldIsObject = typeof idxResponse[field] === 'object' && !!idxResponse[field];\n\n if ( !fieldIsObject ) {\n // simple fields are contextual info\n context[field] = idxResponse[field];\n return;\n }\n\n if ( idxResponse[field].rel ) {\n // top level actions\n actions[idxResponse[field].name] = generateIdxAction(authClient, idxResponse[field], toPersist);\n return;\n }\n\n const { value: fieldValue, type, ...info} = idxResponse[field];\n context[field] = { type, ...info}; // add the non-action parts as context\n\n if ( type !== 'object' ) {\n // only object values hold actions\n context[field].value = fieldValue;\n return;\n }\n\n // We are an object field containing an object value\n context[field].value = {};\n Object.entries(fieldValue)\n .forEach( ([subField, value]) => {\n if (value.rel) { // is [field].value[subField] an action?\n // add any \"action\" value subfields to actions\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n actions[`${field}-${subField.name || subField}`] = generateIdxAction(authClient, value, toPersist);\n } else {\n // add non-action value subfields to context\n context[field].value[subField] = value;\n }\n });\n });\n\n return { context, actions };\n};\n\nconst expandRelatesTo = (idxResponse, value) => {\n Object.keys(value).forEach(k => {\n if (k === 'relatesTo') {\n const query = Array.isArray(value[k]) ? value[k][0] : value[k];\n if (typeof query === 'string') {\n const result = jsonpath({ path: query, json: idxResponse });\n if (result) {\n value[k] = result;\n return;\n } else {\n throw new AuthSdkError(`Cannot resolve relatesTo: ${query}`);\n }\n }\n }\n if (Array.isArray(value[k])) {\n value[k].forEach(innerValue => expandRelatesTo(idxResponse, innerValue));\n }\n });\n};\n\nconst convertRemediationAction = (authClient: OktaAuthIdxInterface, remediation, toPersist) => {\n // Only remediation that has `rel` field (indicator for form submission) can have http action\n if (remediation.rel) {\n const remediationActions = generateRemediationFunctions( authClient, [remediation], toPersist );\n const actionFn = remediationActions[remediation.name];\n return {\n ...remediation,\n action: actionFn,\n };\n }\n\n return remediation;\n};\n\nexport const parseIdxResponse = function parseIdxResponse( authClient: OktaAuthIdxInterface, idxResponse, toPersist = {} ): {\n remediations: IdxRemediation[];\n context: IdxContext;\n actions: IdxActions;\n} {\n const remediationData = idxResponse.remediation?.value || [];\n\n remediationData.forEach(\n remediation => {\n // TODO: remove once IDX is fixed - OKTA-659181\n if (remediation.name === 'launch-authenticator' &&\n remediation?.relatesTo?.[0] === 'authenticatorChallenge' &&\n !idxResponse?.authenticatorChallenge\n ) {\n delete remediation.relatesTo;\n return;\n }\n\n return expandRelatesTo(idxResponse, remediation);\n }\n );\n\n const remediations = remediationData.map(remediation => convertRemediationAction( authClient, remediation, toPersist ));\n\n const { context, actions } = parseNonRemediations( authClient, idxResponse, toPersist );\n\n return {\n remediations,\n context,\n actions,\n };\n};\n", "/*!\n * Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { IdxResponse, IdxToPersist, IdxActionParams } from '../../types/idx-js';\nimport { OktaAuthIdxInterface, RawIdxResponse } from '../../types'; // auth-js/types\nimport { parseIdxResponse } from './idxResponseParser';\n\nexport function makeIdxState( \n authClient: OktaAuthIdxInterface,\n idxResponse: RawIdxResponse,\n toPersist: IdxToPersist,\n requestDidSucceed: boolean\n): IdxResponse {\n const rawIdxResponse = idxResponse;\n const { remediations, context, actions } = parseIdxResponse( authClient, idxResponse, toPersist );\n const neededToProceed = [...remediations];\n\n const proceed: IdxResponse['proceed'] = async function( remediationChoice, paramsFromUser = {} ) {\n /*\n remediationChoice is the name attribute on each form\n name should remain unique for items inside the remediation that are considered forms(identify, select-factor)\n name can be duplicate for items like redirect where its not considered a form(redirect)\n when names are not unique its a redirect to a href, so widget wont POST to idx-js layer.\n */\n const remediationChoiceObject = remediations.find((remediation) => remediation.name === remediationChoice);\n if ( !remediationChoiceObject ) {\n return Promise.reject(`Unknown remediation choice: [${remediationChoice}]`);\n }\n\n const actionFn = remediationChoiceObject.action;\n if (typeof actionFn !== 'function') {\n return Promise.reject(`Current remediation cannot make form submit action: [${remediationChoice}]`);\n }\n\n return remediationChoiceObject.action!(paramsFromUser as IdxActionParams);\n };\n\n const findCode = item => item.name === 'interaction_code';\n const interactionCode = rawIdxResponse.successWithInteractionCode?.value?.find( findCode )?.value as string;\n\n return {\n proceed,\n neededToProceed,\n actions,\n context,\n rawIdxState: rawIdxResponse,\n interactionCode,\n toPersist,\n requestDidSucceed,\n };\n}\n", "/*!\n * Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { makeIdxState } from './makeIdxState';\n\nexport default {\n makeIdxState,\n};\n", "import { OktaAuthIdxInterface } from '../types'; // auth-js/types\nimport { IdxResponse, IdxToPersist, RawIdxResponse } from '../types/idx-js'; // idx/types\nimport { IDX_API_VERSION } from '../../constants';\nimport v1 from './v1/parsers';\n\n\nexport const parsersForVersion = function parsersForVersion( version ) {\n switch (version) {\n case '1.0.0':\n return v1;\n case undefined:\n case null:\n throw new Error('Api version is required');\n default:\n throw new Error(`Unknown api version: ${version}. Use an exact semver version.`);\n }\n};\n\nexport function validateVersionConfig(version) {\n if ( !version ) {\n throw new Error('version is required');\n }\n\n const cleanVersion = (version ?? '').replace(/[^0-9a-zA-Z._-]/, '');\n if ( cleanVersion !== version || !version ) {\n throw new Error('invalid version supplied - version is required and uses semver syntax');\n }\n\n parsersForVersion(version); // will throw for invalid version\n}\n\nexport function makeIdxState ( \n authClient: OktaAuthIdxInterface,\n rawIdxResponse: RawIdxResponse,\n toPersist: IdxToPersist,\n requestDidSucceed: boolean,\n): IdxResponse {\n const version = rawIdxResponse?.version ?? IDX_API_VERSION;\n validateVersionConfig(version);\n \n const { makeIdxState } = parsersForVersion(version);\n return makeIdxState(authClient, rawIdxResponse, toPersist, requestDidSucceed);\n}\n", "/* eslint-disable no-use-before-define */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { Input } from './api';\n\n\n// TODO: remove when idx-js provides type information\n\nexport interface ChallengeData {\n challenge: string; \n userVerification: string; \n extensions?: {\n appid: string;\n };\n}\nexport interface ActivationData {\n challenge: string;\n rp: {\n name: string;\n };\n user: {\n id: string;\n name: string;\n displayName: string;\n };\n pubKeyCredParams: {\n type: string;\n alg: number;\n }[];\n attestation?: string;\n authenticatorSelection?: {\n userVerification?: string;\n authenticatorAttachment?: string;\n requireResidentKey?: boolean;\n residentKey?: string;\n };\n excludeCredentials?: {\n id: string;\n type: string;\n }[];\n}\nexport interface IdxAuthenticatorMethod {\n type: string;\n}\nexport interface IdxAuthenticator {\n displayName: string;\n id: string;\n key: string;\n methods: IdxAuthenticatorMethod[];\n type: string;\n settings?: {\n complexity?: unknown;\n age?: unknown;\n };\n contextualData?: {\n enrolledQuestion?: {\n question: string;\n questionKey: string;\n };\n qrcode?: { \n href: string; \n method: string; \n type: string; \n };\n sharedSecret?: string;\n questions?: {\n questionKey: string;\n question: string;\n }[];\n questionKeys?: string[];\n selectedChannel?: string;\n activationData?: ActivationData;\n challengeData?: ChallengeData;\n };\n credentialId?: string;\n enrollmentId?: string;\n profile?: Record;\n resend?: Record;\n poll?: Record;\n recover?: Record;\n deviceKnown?: boolean;\n nickname?: string;\n}\n\nexport interface IdxForm {\n value: IdxRemediationValue[];\n}\n\nexport interface IdxOption {\n value: string | {form: IdxForm} | Input[];\n label: string;\n relatesTo?: IdxAuthenticator;\n}\n\nexport interface IdpConfig {\n id: string;\n name: string;\n}\n\nexport interface IdxRemediationValueForm {\n form: IdxForm;\n}\n\nexport interface IdxRemediationValue {\n name: string;\n type?: string;\n required?: boolean;\n secret?: boolean;\n visible?: boolean;\n mutable?: boolean;\n value?: string | IdxRemediationValueForm;\n label?: string;\n form?: IdxForm;\n options?: IdxOption[];\n messages?: IdxMessages;\n minLength?: number;\n maxLength?: number;\n relatesTo?: {\n type?: string;\n value: IdxAuthenticator;\n };\n}\n\nexport interface IdxRemediation {\n name: string;\n label?: string;\n value?: IdxRemediationValue[];\n relatesTo?: {\n type?: string;\n value: IdxAuthenticator;\n };\n idp?: IdpConfig;\n href?: string;\n method?: string;\n type?: string;\n accepts?: string;\n produces?: string;\n refresh?: number;\n rel?: string[];\n action?: (payload?: IdxActionParams) => Promise;\n}\n\nexport interface IdxContext {\n version: string;\n stateHandle: string;\n expiresAt: string;\n intent: string;\n currentAuthenticator: {\n type: string;\n value: IdxAuthenticator;\n };\n currentAuthenticatorEnrollment: {\n type: string;\n value: IdxAuthenticator;\n };\n authenticators: {\n type: string;\n value: IdxAuthenticator[];\n };\n authenticatorEnrollments: {\n type: string;\n value: IdxAuthenticator[];\n };\n enrollmentAuthenticator: {\n type: string;\n value: IdxAuthenticator;\n };\n user?: {\n type: string;\n value: Record;\n };\n uiDisplay?: IdxContextUIDisplay\n app: {\n type: string;\n value: Record;\n };\n messages?: IdxMessages;\n success?: IdxRemediation;\n failure?: IdxRemediation;\n}\n\nexport interface IdxContextUIDisplay {\n type: string;\n value: {\n label?: string;\n buttonLabel?: string;\n }\n}\n\nexport interface IdxMessage {\n message: string;\n class: string;\n i18n: {\n key: string;\n params?: unknown[];\n };\n}\n\nexport interface IdxMessages {\n type: 'array';\n value: IdxMessage[];\n}\n\n// JSON response from the server\nexport interface RawIdxResponse {\n version: string;\n stateHandle: string;\n intent?: string;\n expiresAt?: string;\n remediation?: {\n type: 'array';\n value: IdxRemediation[];\n };\n messages?: IdxMessages;\n success?: boolean;\n successWithInteractionCode?: IdxRemediation;\n currentAuthenticator?: {\n type: string;\n value: IdxAuthenticator;\n };\n currentAuthenticatorEnrollment?: {\n type: string;\n value: IdxAuthenticator;\n };\n}\n\nexport function isRawIdxResponse(obj: any): obj is RawIdxResponse {\n return obj && obj.version;\n}\n\nexport interface IdxActionParams {\n [key: string]: string | boolean | number | object;\n}\n\nexport interface IdxActions {\n [key: string]: (params?: IdxActionParams) => Promise;\n}\n\nexport interface IdxToPersist {\n interactionHandle?: string;\n withCredentials?: boolean;\n}\n\nexport interface IdxActionFunction {\n (params: IdxActionParams): Promise;\n neededParams?: Array>;\n}\n\nexport interface IdxResponse {\n proceed: (remediationName: string, params: unknown) => Promise;\n neededToProceed: IdxRemediation[];\n rawIdxState: RawIdxResponse;\n interactionCode?: string;\n actions: IdxActions;\n toPersist: IdxToPersist;\n context?: IdxContext;\n requestDidSucceed?: boolean;\n stepUp?: boolean;\n}\n\nexport function isIdxResponse(obj: any): obj is IdxResponse {\n return obj && isRawIdxResponse(obj.rawIdxState);\n}\n", "\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport AuthApiError from './AuthApiError';\nimport AuthPollStopError from './AuthPollStopError';\nimport AuthSdkError from './AuthSdkError';\nimport OAuthError from './OAuthError';\nimport WWWAuthError from './WWWAuthError';\n\nfunction isAuthApiError(obj: any): obj is AuthApiError {\n return (obj instanceof AuthApiError);\n}\n\nfunction isOAuthError(obj: any): obj is OAuthError {\n return (obj instanceof OAuthError);\n}\n\nfunction isWWWAuthError(obj: any): obj is WWWAuthError {\n return (obj instanceof WWWAuthError);\n}\n\nexport {\n isAuthApiError,\n isOAuthError,\n isWWWAuthError,\n AuthApiError,\n AuthPollStopError,\n AuthSdkError,\n OAuthError,\n WWWAuthError\n};\n\nexport * from './types';\n", "/* eslint-disable complexity */\n/*!\n * Copyright (c) 2021, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { makeIdxState, validateVersionConfig } from './idxState';\nimport { IntrospectOptions, OktaAuthIdxInterface } from './types';\nimport { IdxResponse, isRawIdxResponse } from './types/idx-js';\nimport { getOAuthDomain } from '../oidc';\nimport { IDX_API_VERSION } from '../constants';\nimport { httpRequest } from '../http';\nimport { isAuthApiError } from '../errors';\n\nexport async function introspect (\n authClient: OktaAuthIdxInterface, \n options: IntrospectOptions = {}\n): Promise {\n let rawIdxResponse;\n let requestDidSucceed;\n\n // try load from storage first\n const savedIdxResponse = authClient.transactionManager.loadIdxResponse(options);\n if (savedIdxResponse) {\n rawIdxResponse = savedIdxResponse.rawIdxResponse;\n requestDidSucceed = savedIdxResponse.requestDidSucceed;\n }\n\n // call idx.introspect if no existing idx response available in storage\n if (!rawIdxResponse) {\n const version = options.version || IDX_API_VERSION;\n const domain = getOAuthDomain(authClient);\n const { interactionHandle, stateHandle } = options;\n const withCredentials = options.withCredentials ?? true;\n try {\n requestDidSucceed = true;\n validateVersionConfig(version);\n const url = `${domain}/idp/idx/introspect`;\n const body = stateHandle ? { stateToken: stateHandle } : { interactionHandle };\n const headers = {\n 'Content-Type': `application/ion+json; okta-version=${version}`, // Server wants this version info\n Accept: `application/ion+json; okta-version=${version}`,\n };\n rawIdxResponse = await httpRequest(authClient, {\n method: 'POST',\n url,\n headers,\n withCredentials,\n args: body\n });\n } catch (err) {\n if (isAuthApiError(err) && err.xhr && isRawIdxResponse(err.xhr.responseJSON)) {\n rawIdxResponse = err.xhr.responseJSON;\n requestDidSucceed = false;\n } else {\n throw err;\n }\n }\n }\n\n const { withCredentials } = options;\n return makeIdxState(authClient, rawIdxResponse, { withCredentials }, requestDidSucceed);\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { IdxRemediation, IdxRemediationValue } from '../types/idx-js';\n\nexport function getAllValues(idxRemediation: IdxRemediation) {\n return idxRemediation.value?.map(r => r.name);\n}\n\nexport function getRequiredValues(idxRemediation: IdxRemediation) {\n return idxRemediation.value?.reduce((required, cur) => {\n if (cur.required) {\n required.push(cur.name as never);\n }\n return required;\n }, []);\n}\n\nexport function titleCase(str: string) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n}\n\nexport function getAuthenticatorFromRemediation(\n remediation: IdxRemediation\n): IdxRemediationValue {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return remediation.value!.find(({ name }) => name === 'authenticator') as IdxRemediationValue;\n}\n", "import { Authenticator, isAuthenticator } from '../types';\n\nexport function formatAuthenticator(incoming: unknown): Authenticator {\n let authenticator: Authenticator;\n if (isAuthenticator(incoming)) {\n authenticator = incoming;\n } else if (typeof incoming === 'string') {\n authenticator = {\n key: incoming\n };\n } else {\n throw new Error('Invalid format for authenticator');\n }\n return authenticator;\n}\n\n// Returns true if the authenticators are equivalent\nexport function compareAuthenticators(auth1, auth2) {\n if (!auth1 || !auth2) {\n return false;\n }\n // by id\n if (auth1.id && auth2.id) {\n return (auth1.id === auth2.id);\n }\n // by key\n if (auth1.key && auth2.key) {\n return (auth1.key === auth2.key);\n }\n return false;\n}\n\n// Find matched authenticator in provided order\nexport function findMatchedOption(authenticators, options) {\n let option;\n for (let authenticator of authenticators) {\n option = options\n .find(({ relatesTo }) => relatesTo.key && relatesTo.key === authenticator.key);\n if (option) {\n break;\n }\n }\n return option;\n}", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\n/* eslint-disable complexity */\nimport { OktaAuthIdxInterface, NextStep, IdxMessage, Authenticator, Input, RemediateOptions } from '../../types';\nimport { IdxAuthenticator, IdxRemediation, IdxContext } from '../../types/idx-js';\nimport { getAllValues, getRequiredValues, titleCase, getAuthenticatorFromRemediation } from '../util';\nimport { formatAuthenticator, compareAuthenticators } from '../../authenticator/util';\n\n// A map from IDX data values (server spec) to RemediationValues (client spec)\nexport type IdxToRemediationValueMap = Record;\n\nexport interface RemediationValues {\n stateHandle?: string;\n authenticators?: (Authenticator | string)[];\n authenticator?: string | Authenticator;\n authenticatorsData?: Authenticator[];\n resend?: boolean;\n}\n\nexport interface RemediatorConstructor {\n remediationName: string;\n new(\n remediation: IdxRemediation, \n values?: T, \n options?: RemediateOptions\n ): any;\n}\n\n// Base class - DO NOT expose static remediationName\nexport class Remediator {\n static remediationName: string;\n\n remediation: IdxRemediation;\n values: T;\n options: RemediateOptions;\n map?: IdxToRemediationValueMap;\n\n constructor(\n remediation: IdxRemediation, \n values: T = {} as T, \n options: RemediateOptions = {}\n ) {\n // assign fields to the instance\n this.values = { ...values };\n this.options = { ...options };\n this.formatAuthenticators();\n this.remediation = remediation;\n }\n\n private formatAuthenticators() {\n this.values.authenticators = (this.values.authenticators || []) as Authenticator[];\n\n // ensure authenticators are in the correct format\n this.values.authenticators = this.values.authenticators.map(authenticator => {\n return formatAuthenticator(authenticator);\n });\n\n // add authenticator (if any) to \"authenticators\"\n if (this.values.authenticator) {\n const authenticator = formatAuthenticator(this.values.authenticator);\n const hasAuthenticatorInList = this.values.authenticators.some(existing => {\n return compareAuthenticators(authenticator, existing);\n });\n if (!hasAuthenticatorInList) {\n this.values.authenticators.push(authenticator);\n }\n }\n\n // save non-key meta to \"authenticatorsData\" field\n // authenticators will be removed after selection to avoid select-authenticator loop\n this.values.authenticatorsData = this.values.authenticators.reduce((acc, authenticator) => {\n if (typeof authenticator === 'object' && Object.keys(authenticator).length > 1) {\n // save authenticator meta into authenticator data\n acc.push(authenticator);\n }\n return acc;\n }, this.values.authenticatorsData || []);\n }\n\n getName(): string {\n return this.remediation.name;\n }\n\n // Override this method to provide custom check\n /* eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars */\n canRemediate(context?: IdxContext): boolean {\n const required = getRequiredValues(this.remediation);\n const needed = required!.find((key) => !this.hasData(key));\n if (needed) {\n return false; // missing data for a required field\n }\n return true; // all required fields have available data\n }\n\n // returns an object for the entire remediation form, or just a part\n getData(key?: string) {\n if (!key) {\n let allValues = getAllValues(this.remediation);\n let res = allValues!.reduce((data, key) => {\n data[key] = this.getData(key); // recursive\n return data;\n }, {});\n return res;\n }\n\n // Map value by \"map${Property}\" function in each subClass\n if (typeof this[`map${titleCase(key)}`] === 'function') {\n const val = this[`map${titleCase(key)}`](\n this.remediation.value!.find(({name}) => name === key)\n );\n if (val) {\n return val;\n }\n }\n\n // If a map is defined for this key, return the first aliased property that returns a truthy value\n if (this.map && this.map[key]) {\n const entry = this.map[key];\n for (let i = 0; i < entry.length; i++) {\n let val = this.values[entry[i]];\n if (val) {\n return val;\n }\n }\n }\n\n // fallback: return the value by key\n return this.values[key];\n }\n\n hasData(\n key: string // idx name\n ): boolean \n {\n // no attempt to format, we want simple true/false\n return !!this.getData(key);\n }\n\n getNextStep(_authClient: OktaAuthIdxInterface, _context?: IdxContext): NextStep {\n const name = this.getName();\n const inputs = this.getInputs();\n const authenticator = this.getAuthenticator();\n // TODO: remove type field in the next major version change\n // https://oktainc.atlassian.net/browse/OKTA-431749\n const type = authenticator?.type;\n return { \n name, \n inputs, \n ...(type && { type }),\n ...(authenticator && { authenticator }),\n };\n }\n\n // Get inputs for the next step\n getInputs(): Input[] {\n const inputs: Input[] = [];\n const inputsFromRemediation = this.remediation.value || [];\n inputsFromRemediation.forEach(inputFromRemediation => {\n let input;\n let { name, type, visible, messages } = inputFromRemediation;\n if (visible === false) {\n return; // Filter out invisible inputs, like stateHandle\n }\n if (typeof this[`getInput${titleCase(name)}`] === 'function') {\n input = this[`getInput${titleCase(name)}`](inputFromRemediation);\n } else if (type !== 'object') {\n // handle general primitive types\n let alias;\n const aliases = (this.map ? this.map[name] : null) || [];\n if (aliases.length === 1) {\n alias = aliases[0];\n } else {\n // try find key from values\n alias = aliases.find(name => Object.keys(this.values).includes(name));\n }\n if (alias) {\n input = { ...inputFromRemediation, name: alias };\n }\n }\n if (!input) {\n input = inputFromRemediation;\n }\n if (Array.isArray(input)) {\n input.forEach(i => inputs.push(i));\n } else {\n // guarantees field-level messages are passed back\n if (messages) {\n input.messages = messages;\n }\n inputs.push(input);\n }\n });\n return inputs;\n }\n\n static getMessages(remediation: IdxRemediation): IdxMessage[] | undefined {\n if (!remediation.value) {\n return;\n }\n return remediation.value[0]?.form?.value.reduce((messages: IdxMessage[], field) => {\n if (field.messages) {\n messages = [...messages, ...field.messages.value];\n }\n return messages;\n }, []);\n }\n\n // Prepare values for the next remediation\n // In general, remove used values from inputs for the current remediation\n // Override this method if special cases need be handled\n getValuesAfterProceed(): T {\n const inputsFromRemediation = this.remediation.value || []; // \"raw\" inputs from server response\n const inputsFromRemediator = this.getInputs(); // \"aliased\" inputs from SDK remediator\n const inputs = [\n ...inputsFromRemediation,\n ...inputsFromRemediator\n ];\n // scrub all values related to this remediation\n for (const input of inputs) {\n delete this.values[input.name];\n }\n return this.values;\n }\n\n protected getAuthenticator(): IdxAuthenticator | undefined {\n // relatesTo value may be an authenticator or an authenticatorEnrollment\n const relatesTo = this.remediation.relatesTo?.value;\n if (!relatesTo) {\n return;\n }\n\n const authenticatorFromRemediation = getAuthenticatorFromRemediation(this.remediation);\n if (!authenticatorFromRemediation) {\n // Hopefully value is an authenticator\n return relatesTo;\n }\n\n // If relatesTo is an authenticatorEnrollment, the id is actually the enrollmentId\n // Let's get the correct authenticator id from the form value\n const id = authenticatorFromRemediation.form!.value\n .find(({ name }) => name === 'id')!.value as string;\n const enrollmentId = authenticatorFromRemediation.form!.value\n .find(({ name }) => name === 'enrollmentId')?.value as string;\n\n return {\n ...relatesTo,\n id,\n enrollmentId\n };\n }\n}\n", "/* eslint-disable complexity */\nimport { AuthSdkError } from '../../../errors';\nimport { Input } from '../../types';\n\nexport function unwrapFormValue(remediation): Input { \n if (Array.isArray(remediation)) {\n return remediation\n .map(item => {\n if (typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean') {\n return item;\n }\n return unwrapFormValue(item);\n }) as any;\n }\n\n const res = {};\n for (const [key, value] of Object.entries(remediation)) {\n if (value === null || typeof value === 'undefined') {\n continue;\n }\n\n if (typeof value === 'object') {\n const formKeys = Object.keys(value as object);\n // detect patterns like:\n // value -> form -> value | form -> value\n if (['value', 'form'].includes(key) \n && formKeys.length === 1 \n && ['value', 'form'].includes(formKeys[0])\n ) {\n // unwrap nested form\n const unwrappedForm = unwrapFormValue(value);\n Object.entries(unwrappedForm).forEach(([key, value]) => {\n res[key] = value;\n });\n } else {\n // dfs\n res[key] = unwrapFormValue(value);\n }\n } else {\n // handle primitive value\n res[key] = value;\n }\n }\n\n return res as Input;\n}\n\n// only check if value is required for now\n// TODO: support SDK layer type based input validation\nexport function hasValidInputValue(input, values) {\n const fn = (input, values, requiredTracker) => {\n const { name, value, type, options, required } = input;\n const isRequired = required || requiredTracker;\n\n // handle nested value - all required fields should be avaiable in values \n if (Array.isArray(value)) {\n return value.reduce((acc, item) => {\n return acc && fn(item, values[name], isRequired); // recursive call\n }, true);\n }\n\n // handle options field\n // 1. object type options - check if each object field is required and value can be found from the selectedOption\n // 2. primitive options - required field is avaiable from top level\n // 3. unknown format - pass to backend for validation\n if (options) {\n // object type options\n if (type === 'object') {\n const selectedOption = values[name];\n if (!selectedOption) {\n return false;\n }\n if (!selectedOption.id) {\n // unknown option format, pass to backend for validation\n return true;\n }\n const optionSchema = options.find((option) => {\n const idSchema = option.value.find(({ name }) => name === 'id' );\n return idSchema.value === selectedOption.id;\n });\n if (!optionSchema) {\n return false;\n }\n return optionSchema.value\n .filter(({ required }) => !!required)\n .reduce((acc, { name }) => {\n return acc && !!selectedOption[name];\n }, true);\n }\n\n // primitive options, not required - always valid\n if (required === false) {\n return true;\n }\n\n // primitive options, required - check if value is available\n if (required === true) {\n return !!values[name];\n }\n\n // unknown options, throw\n throw new AuthSdkError(`Unknown options type, ${JSON.stringify(input)}`);\n }\n\n // base case\n if (!isRequired) {\n return true;\n }\n \n return !!(values && values[name]);\n };\n\n return fn(input, values, false);\n}\n", "import { OktaAuthIdxInterface, IdxContext, NextStep, Input } from '../../types';\nimport { Remediator } from '../Base/Remediator';\nimport { unwrapFormValue } from './util';\n\nexport class GenericRemediator extends Remediator {\n canRemediate(): boolean {\n // only handle remediations that are able to submit form (xhr)\n if (typeof this.remediation.action !== 'function') {\n return false;\n }\n\n // DO NOT REMOVE - bring it back when enable client side validation for GenericRemediator - OKTA-512003\n // const inputs = this.getInputs();\n // const res = inputs.reduce((acc, input) => {\n // return acc && hasValidInputValue(input, this.values);\n // }, true);\n // return res;\n\n if (this.remediation.name === 'poll' || this.remediation.name.endsWith('-poll')) {\n return true;\n }\n\n if (this.options.step) {\n return true;\n }\n \n // disable auto proceed for unknown remediations\n return false;\n }\n\n getData() {\n const data = this.getInputs().reduce((acc, { name }) => {\n acc[name] = this.values[name];\n return acc;\n }, {});\n return data;\n }\n\n getNextStep(authClient: OktaAuthIdxInterface, _context?: IdxContext): NextStep {\n const name = this.getName();\n const inputs = this.getInputs();\n \n /* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */\n // excludes transformed fields\n const { \n // http metas have been transformed to action\n href, \n method, \n rel, \n accepts, \n produces, \n // value has been transform to inputs\n value,\n // will be transformed to a function that resolves IdxTransaction\n action,\n ...rest \n } = this.remediation;\n /* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */\n\n // step to handle form submission\n if (action) {\n return { \n ...rest,\n ...(!!inputs.length && { inputs }),\n action: async (params?) => {\n return authClient.idx.proceed({\n step: name,\n ...params\n });\n }\n };\n }\n\n // return whole remediation data for other steps, eg \"redirect-idp\"\n return { ...this.remediation } as NextStep;\n \n }\n\n getInputs(): Input[] {\n return (this.remediation.value || [])\n .filter(({ name }) => name !== 'stateHandle')\n .map(unwrapFormValue)\n .map(input => {\n // use string as default input type\n input.type = input.type || 'string';\n return input;\n });\n }\n\n}\n", "import { warn, split2 } from '../util';\nimport { RemediationValues, Remediator, RemediatorConstructor } from './remediators';\nimport { GenericRemediator } from './remediators/GenericRemediator';\nimport {\n OktaAuthIdxInterface,\n IdxFeature,\n NextStep,\n RemediateOptions,\n RemediationResponse,\n RunOptions,\n FlowIdentifier,\n FlowSpecification\n} from './types';\nimport { IdxMessage, IdxRemediation, IdxRemediationValue, IdxResponse } from './types/idx-js';\n\ntype GetFlowSpecification = (\n oktaAuth: OktaAuthIdxInterface,\n flow: FlowIdentifier\n) => FlowSpecification;\n\nconst ctx: {\n remediators: Record,\n getFlowSpecification: GetFlowSpecification,\n} = {\n // default values to be used by minimal IDX API\n remediators: {},\n getFlowSpecification: function(_oktaAuth: OktaAuthIdxInterface, _flow: FlowIdentifier = 'default') {\n return {\n remediators: {}\n } as FlowSpecification;\n }\n};\n\n// should be set in createIdxAPI() factory\nexport function setRemediatorsCtx(newCtx: Partial) {\n Object.assign(ctx, newCtx);\n}\n\nexport function getFlowSpecification(oktaAuth: OktaAuthIdxInterface, flow: FlowIdentifier = 'default') {\n return ctx.getFlowSpecification(oktaAuth, flow);\n}\n\nexport function isTerminalResponse(idxResponse: IdxResponse) {\n const { neededToProceed, interactionCode } = idxResponse;\n return !neededToProceed.length && !interactionCode;\n}\n\nexport function canSkipFn(idxResponse: IdxResponse) {\n return idxResponse.neededToProceed.some(({ name }) => name === 'skip');\n}\n\nexport function canResendFn(idxResponse: IdxResponse) {\n return Object.keys(idxResponse.actions).some(actionName => actionName.includes('resend'));\n}\n\nexport function getMessagesFromIdxRemediationValue(\n value?: IdxRemediationValue[]\n): IdxMessage[] | undefined {\n if (!value || !Array.isArray(value)) {\n return;\n }\n return value.reduce((messages, value) => {\n if (value.messages) {\n messages = [...messages, ...value.messages.value] as never;\n }\n if (value.form) {\n const messagesFromForm = getMessagesFromIdxRemediationValue(value.form.value) || [];\n messages = [...messages, ...messagesFromForm] as never;\n } \n if (value.options) {\n let optionValues = [];\n value.options.forEach(option => {\n if (!option.value || typeof option.value === 'string') {\n return;\n }\n optionValues = [...optionValues, option.value] as never;\n });\n const messagesFromOptions = getMessagesFromIdxRemediationValue(optionValues) || [];\n messages = [...messages, ...messagesFromOptions] as never;\n }\n return messages;\n }, []);\n}\n\nexport function getMessagesFromResponse(idxResponse: IdxResponse, options: RunOptions): IdxMessage[] {\n let messages: IdxMessage[] = [];\n const { rawIdxState, neededToProceed } = idxResponse;\n\n // Handle global messages\n const globalMessages = rawIdxState.messages?.value.map(message => message);\n if (globalMessages) {\n messages = [...messages, ...globalMessages] as never;\n }\n\n // Handle field messages for current flow\n // Preserve existing logic for general cases, remove in the next major version\n // Follow ion response format for top level messages when useGenericRemediator is true\n if (!options.useGenericRemediator) {\n for (let remediation of neededToProceed) {\n const fieldMessages = getMessagesFromIdxRemediationValue(remediation.value);\n if (fieldMessages) {\n messages = [...messages, ...fieldMessages] as never;\n }\n }\n }\n\n // API may return identical error on same field, filter by i18n key\n const seen = {};\n messages = messages.reduce((filtered, message) => {\n const key = message.i18n?.key;\n if (key && seen[key] && message.message === seen[key].message) {\n return filtered;\n }\n seen[key] = message;\n filtered = [...filtered, message] as never;\n return filtered;\n }, []);\n\n return messages;\n}\n\n\nexport function getEnabledFeatures(idxResponse: IdxResponse): IdxFeature[] {\n const res = [];\n const { actions, neededToProceed } = idxResponse;\n\n if (actions['currentAuthenticator-recover']) {\n res.push(IdxFeature.PASSWORD_RECOVERY as never);\n }\n\n if (neededToProceed.some(({ name }) => name === 'select-enroll-profile')) {\n res.push(IdxFeature.REGISTRATION as never);\n }\n\n if (neededToProceed.some(({ name }) => name === 'redirect-idp')) {\n res.push(IdxFeature.SOCIAL_IDP as never);\n }\n\n if (neededToProceed.some(({ name }) => name === 'unlock-account')) {\n res.push(IdxFeature.ACCOUNT_UNLOCK as never);\n }\n\n return res;\n}\n\nexport function getAvailableSteps(\n authClient: OktaAuthIdxInterface, \n idxResponse: IdxResponse, \n useGenericRemediator?: boolean\n): NextStep[] {\n const res: NextStep[] = [];\n\n const remediatorMap: Record = Object.values(ctx.remediators)\n .reduce((map, remediatorClass) => {\n // Only add concrete subclasses to the map\n if (remediatorClass.remediationName) {\n map[remediatorClass.remediationName] = remediatorClass;\n }\n return map;\n }, {});\n\n for (let remediation of idxResponse.neededToProceed) {\n const T = getRemediatorClass(remediation, { useGenericRemediator, remediators: remediatorMap });\n if (T) {\n const remediator: Remediator = new T(remediation);\n res.push (remediator.getNextStep(authClient, idxResponse.context) as never);\n }\n }\n\n for (const [name] of Object.entries((idxResponse.actions || {}))) {\n let stepObj = {\n name, \n action: async (params?) => {\n return authClient.idx.proceed({ \n actions: [{ name, params }] \n });\n }\n };\n if (name.startsWith('currentAuthenticator')) {\n const [part1, part2] = split2(name, '-');\n const actionObj = idxResponse.rawIdxState[part1].value[part2];\n /* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */\n const {\n href, \n method, \n rel, \n accepts, \n produces, \n ...rest\n } = actionObj;\n /* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */\n const value = actionObj.value?.filter(item => item.name !== 'stateHandle');\n stepObj = { \n ...rest, \n ...(value && { value }),\n ...stepObj,\n };\n }\n res.push(stepObj);\n }\n\n return res;\n}\n\nexport function filterValuesForRemediation(\n idxResponse: IdxResponse,\n remediationName: string,\n values: RemediationValues\n): RemediationValues {\n const remediations = idxResponse.neededToProceed || [];\n const remediation = remediations.find(r => r.name === remediationName);\n if (!remediation) {\n // step was specified, but remediation was not found. This is unexpected!\n warn(`filterValuesForRemediation: \"${remediationName}\" did not match any remediations`);\n return values;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const valuesForRemediation = remediation.value!.reduce((res, entry) => {\n const { name, value } = entry;\n if (name === 'stateHandle') {\n res[name] = value; // use the stateHandle value in the remediation\n } else {\n res[name] = values[name]; // use the value provided by the caller\n }\n return res;\n }, {});\n return valuesForRemediation;\n}\n\nfunction getRemediatorClass(remediation: IdxRemediation, options: RemediateOptions) {\n const { useGenericRemediator, remediators } = options;\n \n if (!remediation) {\n return undefined;\n }\n\n if (useGenericRemediator) {\n return GenericRemediator;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return remediators![remediation.name];\n}\n\n// Return first match idxRemediation in allowed remediators\n// eslint-disable-next-line complexity\nexport function getRemediator(\n idxResponse: IdxResponse,\n values: RemediationValues,\n options: RemediateOptions,\n): Remediator | undefined {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const remediators = options.remediators!;\n const useGenericRemediator = options.useGenericRemediator;\n const {neededToProceed: idxRemediations, context} = idxResponse;\n\n let remediator: Remediator;\n // remediation name specified by caller - fast-track remediator lookup \n if (options.step) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const remediation = idxRemediations.find(({ name }) => name === options.step)!;\n if (remediation) {\n const T = getRemediatorClass(remediation, options);\n return T ? new T(remediation, values, options) : undefined;\n } else {\n // step was specified, but remediation was not found. This is unexpected!\n warn(`step \"${options.step}\" did not match any remediations`);\n return;\n }\n }\n\n const remediatorCandidates: Remediator[] = [];\n if (useGenericRemediator) {\n // always pick the first remediation for when use GenericRemediator\n remediatorCandidates.push(new GenericRemediator(idxRemediations[0], values, options));\n } else {\n for (let remediation of idxRemediations) {\n const isRemeditionInFlow = Object.keys(remediators as object).includes(remediation.name);\n if (!isRemeditionInFlow) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const T = getRemediatorClass(remediation, options)!;\n remediator = new T(remediation, values, options);\n if (remediator.canRemediate(context)) {\n // found the remediator\n return remediator;\n }\n // remediator cannot handle the current values\n // maybe return for next step\n remediatorCandidates.push(remediator); \n }\n }\n \n return remediatorCandidates[0];\n}\n\n\nexport function getNextStep(\n authClient: OktaAuthIdxInterface, remediator: Remediator, idxResponse: IdxResponse\n): NextStep {\n const nextStep = remediator.getNextStep(authClient, idxResponse.context);\n const canSkip = canSkipFn(idxResponse);\n const canResend = canResendFn(idxResponse);\n return {\n ...nextStep,\n ...(canSkip && {canSkip}),\n ...(canResend && {canResend}),\n };\n}\n\nexport function handleFailedResponse(\n authClient: OktaAuthIdxInterface,\n idxResponse: IdxResponse,\n options = {}\n): RemediationResponse {\n const terminal = isTerminalResponse(idxResponse);\n const messages = getMessagesFromResponse(idxResponse, options);\n if (terminal) {\n return { idxResponse, terminal, messages };\n } else {\n const remediator = getRemediator(idxResponse, {}, options);\n const nextStep = remediator && getNextStep(authClient, remediator, idxResponse);\n return {\n idxResponse,\n messages,\n ...(nextStep && { nextStep }),\n };\n }\n \n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\n/* eslint-disable max-statements, max-depth, complexity */\nimport { AuthSdkError } from '../errors';\nimport { RemediationValues } from './remediators';\nimport { OktaAuthIdxInterface, RemediateOptions, RemediationResponse } from './types';\nimport { \n IdxResponse,\n IdxActionParams, \n} from './types/idx-js';\nimport {\n isTerminalResponse,\n filterValuesForRemediation,\n getRemediator,\n getNextStep,\n handleFailedResponse\n} from './util';\n\nexport interface RemediateActionWithOptionalParams {\n name: string;\n params?: IdxActionParams;\n}\n\nexport type RemediateAction = string | RemediateActionWithOptionalParams;\n\n\nfunction getActionFromValues(values: RemediationValues, idxResponse: IdxResponse): string | undefined {\n // Currently support resend actions only\n return Object.keys(idxResponse.actions).find(action => !!values.resend && action.includes('-resend'));\n}\n\nfunction removeActionFromValues(values: RemediationValues): RemediationValues {\n // Currently support resend actions only\n return {\n ...values,\n resend: undefined\n };\n}\n\nfunction removeActionFromOptions(options: RemediateOptions, actionName: string): RemediateOptions {\n let actions = options.actions || [];\n actions = actions.filter(entry => {\n if (typeof entry === 'string') {\n return entry !== actionName;\n }\n return entry.name !== actionName;\n });\n\n return { ...options, actions };\n}\n\n// This function is called recursively until it reaches success or cannot be remediated\nexport async function remediate(\n authClient: OktaAuthIdxInterface,\n idxResponse: IdxResponse,\n values: RemediationValues,\n options: RemediateOptions\n): Promise {\n let { neededToProceed, interactionCode } = idxResponse;\n const { flow } = options;\n\n // If the response contains an interaction code, there is no need to remediate\n if (interactionCode) {\n return { idxResponse };\n }\n\n const remediator = getRemediator(idxResponse, values, options);\n\n // Try actions in idxResponse first\n const actionFromValues = getActionFromValues(values, idxResponse);\n const actionFromOptions = options.actions || [];\n const actions = [\n ...actionFromOptions,\n ...(actionFromValues && [actionFromValues] || []),\n ];\n if (actions) {\n for (let action of actions) {\n // Action can either be specified as a string, or as an object with name and optional params\n let params: IdxActionParams = {};\n if (typeof action !== 'string') {\n params = action.params || {};\n action = action.name;\n }\n let valuesWithoutExecutedAction = removeActionFromValues(values);\n let optionsWithoutExecutedAction = removeActionFromOptions(options, action);\n\n if (typeof idxResponse.actions[action] === 'function') {\n idxResponse = await idxResponse.actions[action](params);\n if (idxResponse.requestDidSucceed === false) {\n return handleFailedResponse(authClient, idxResponse, options);\n }\n if (action === 'cancel') {\n return { idxResponse, canceled: true };\n }\n return remediate(\n authClient, \n idxResponse, \n valuesWithoutExecutedAction, \n optionsWithoutExecutedAction\n ); // recursive call\n }\n\n // search for action in remediation list\n const remediationAction = neededToProceed.find(({ name }) => name === action);\n if (remediationAction) {\n idxResponse = await idxResponse.proceed(action, params);\n if (idxResponse.requestDidSucceed === false) {\n return handleFailedResponse(authClient, idxResponse, options);\n }\n return remediate(authClient, idxResponse, values, optionsWithoutExecutedAction); // recursive call\n }\n }\n }\n\n // Do not attempt to remediate if response is in terminal state\n const terminal = isTerminalResponse(idxResponse);\n if (terminal) {\n return { idxResponse, terminal };\n }\n\n if (!remediator) {\n // With options.step, remediator is not required\n if (options.step) {\n values = filterValuesForRemediation(idxResponse, options.step, values); // include only requested values\n idxResponse = await idxResponse.proceed(options.step, values);\n if (idxResponse.requestDidSucceed === false) {\n return handleFailedResponse(authClient, idxResponse, options);\n }\n return { idxResponse };\n }\n\n // With default flow, remediator is not required\n if (flow === 'default') {\n return { idxResponse };\n }\n throw new AuthSdkError(`\n No remediation can match current flow, check policy settings in your org.\n Remediations: [${neededToProceed.reduce((acc, curr) => acc ? acc + ' ,' + curr.name : curr.name, '')}]\n `);\n }\n\n // Return next step to the caller\n if (!remediator.canRemediate()) {\n const nextStep = getNextStep(authClient, remediator, idxResponse);\n return {\n idxResponse,\n nextStep,\n };\n }\n\n const name = remediator.getName();\n const data = remediator.getData();\n\n idxResponse = await idxResponse.proceed(name, data);\n if (idxResponse.requestDidSucceed === false) {\n return handleFailedResponse(authClient, idxResponse, options);\n }\n // We may want to trim the values bag for the next remediation\n // Let the remediator decide what the values should be (default to current values)\n values = remediator.getValuesAfterProceed();\n options = { ...options, step: undefined }; // do not re-use the step\n\n // generic remediator should not auto proceed in pending status\n // return nextStep directly\n if (options.useGenericRemediator && !idxResponse.interactionCode && !isTerminalResponse(idxResponse)) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const gr = getRemediator(idxResponse, values, options)!;\n const nextStep = getNextStep(authClient, gr, idxResponse);\n return {\n idxResponse,\n nextStep,\n };\n }\n \n return remediate(authClient, idxResponse, values, options); // recursive call\n\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\n/* eslint-disable max-statements, complexity, max-depth */\nimport { interact } from './interact';\nimport { introspect } from './introspect';\nimport { remediate } from './remediate';\nimport { RemediationValues } from './remediators/Base/Remediator';\nimport { \n OktaAuthIdxInterface,\n IdxStatus,\n IdxTransaction,\n IdxFeature,\n NextStep,\n RunOptions,\n IdxTransactionMeta,\n} from './types';\nimport { IdxMessage, IdxResponse } from './types/idx-js';\nimport { getSavedTransactionMeta, saveTransactionMeta } from './transactionMeta';\nimport {\n getAvailableSteps,\n getEnabledFeatures,\n getMessagesFromResponse,\n isTerminalResponse,\n getFlowSpecification\n} from './util';\nimport { Tokens } from '../oidc/types';\nimport { APIError } from '../errors/types';\ndeclare interface RunData {\n options: RunOptions;\n values: RemediationValues;\n status?: IdxStatus;\n tokens?: Tokens;\n nextStep?: NextStep;\n messages?: IdxMessage[];\n error?: APIError | IdxResponse;\n meta?: IdxTransactionMeta;\n enabledFeatures?: IdxFeature[];\n availableSteps?: NextStep[];\n idxResponse?: IdxResponse;\n canceled?: boolean;\n interactionCode?: string;\n shouldSaveResponse?: boolean;\n shouldClearTransaction?: boolean;\n clearSharedStorage?: boolean;\n terminal?: boolean;\n}\n\nfunction initializeValues(options: RunOptions) {\n // remove known options, everything else is assumed to be a value\n const knownOptions = [\n 'flow', \n 'remediators', \n 'actions', \n 'withCredentials', \n 'step',\n 'useGenericRemediator',\n 'exchangeCodeForTokens',\n ];\n const values = { ...options };\n knownOptions.forEach(option => {\n delete values[option];\n });\n return values;\n}\n\nfunction initializeData(authClient: OktaAuthIdxInterface, data: RunData): RunData {\n let { options } = data;\n options = {\n ...authClient.options.idx,\n ...options\n };\n let {\n flow,\n withCredentials,\n remediators,\n actions,\n } = options;\n\n const status = IdxStatus.PENDING;\n\n // certain options can be set by the flow specification\n flow = flow || authClient.idx.getFlow?.() || 'default';\n if (flow) {\n authClient.idx.setFlow?.(flow);\n const flowSpec = getFlowSpecification(authClient, flow);\n // Favor option values over flow spec\n withCredentials = (typeof withCredentials !== 'undefined') ? withCredentials : flowSpec.withCredentials;\n remediators = remediators || flowSpec.remediators;\n actions = actions || flowSpec.actions;\n }\n\n return { \n ...data,\n options: { \n ...options, \n flow, \n withCredentials, \n remediators, \n actions,\n },\n status\n };\n}\n\nasync function getDataFromIntrospect(authClient: OktaAuthIdxInterface, data: RunData): Promise {\n const { options } = data;\n const {\n stateHandle,\n withCredentials,\n version,\n state,\n scopes,\n recoveryToken,\n activationToken,\n maxAge,\n acrValues,\n nonce,\n useGenericRemediator,\n } = options;\n\n let idxResponse;\n let meta = getSavedTransactionMeta(authClient, { state, recoveryToken, activationToken }); // may be undefined\n\n if (stateHandle) {\n idxResponse = await introspect(authClient, { withCredentials, version, stateHandle, useGenericRemediator });\n } else {\n let interactionHandle = meta?.interactionHandle; // may be undefined\n if (!interactionHandle) {\n // start a new transaction\n authClient.transactionManager.clear();\n const interactResponse = await interact(authClient, {\n withCredentials,\n state,\n scopes,\n activationToken,\n recoveryToken,\n maxAge,\n acrValues,\n nonce,\n }); \n interactionHandle = interactResponse.interactionHandle;\n meta = interactResponse.meta;\n }\n \n // Introspect to get idx response\n idxResponse = await introspect(authClient, { withCredentials, version, interactionHandle, useGenericRemediator });\n }\n return { ...data, idxResponse, meta };\n}\n\nasync function getDataFromRemediate(authClient: OktaAuthIdxInterface, data: RunData): Promise {\n let {\n idxResponse,\n options,\n values\n } = data;\n\n const {\n autoRemediate,\n remediators,\n actions,\n flow,\n step,\n useGenericRemediator,\n } = options;\n \n const shouldRemediate = (autoRemediate !== false && (remediators || actions || step));\n if (!shouldRemediate) {\n return data;\n }\n\n values = { \n ...values, \n stateHandle: idxResponse!.rawIdxState.stateHandle \n };\n\n // Can we handle the remediations?\n const { \n idxResponse: idxResponseFromRemediation, \n nextStep,\n canceled,\n } = await remediate(\n authClient,\n idxResponse!, \n values, \n {\n remediators,\n actions,\n flow,\n step,\n useGenericRemediator,\n }\n );\n idxResponse = idxResponseFromRemediation;\n\n return { ...data, idxResponse, nextStep, canceled };\n}\n\nasync function getTokens(authClient: OktaAuthIdxInterface, data: RunData): Promise {\n let { meta, idxResponse } = data;\n const { interactionCode } = idxResponse as IdxResponse;\n const {\n clientId,\n codeVerifier,\n ignoreSignature,\n redirectUri,\n urls,\n scopes,\n } = meta as IdxTransactionMeta;\n const tokenResponse = await authClient.token.exchangeCodeForTokens({\n interactionCode,\n clientId,\n codeVerifier,\n ignoreSignature,\n redirectUri,\n scopes\n }, urls);\n return tokenResponse.tokens;\n}\n\nasync function finalizeData(authClient: OktaAuthIdxInterface, data: RunData): Promise {\n let {\n options,\n idxResponse,\n canceled,\n status,\n } = data;\n const { exchangeCodeForTokens } = options;\n let shouldSaveResponse = false;\n let shouldClearTransaction = false;\n let clearSharedStorage = true;\n let interactionCode;\n let tokens;\n let enabledFeatures;\n let availableSteps;\n let messages;\n let terminal;\n\n if (idxResponse) {\n shouldSaveResponse = !!(idxResponse.requestDidSucceed || idxResponse.stepUp);\n enabledFeatures = getEnabledFeatures(idxResponse);\n availableSteps = getAvailableSteps(authClient, idxResponse, options.useGenericRemediator);\n messages = getMessagesFromResponse(idxResponse, options);\n terminal = isTerminalResponse(idxResponse);\n }\n\n if (terminal) {\n status = IdxStatus.TERMINAL;\n\n // In most cases a terminal response should not clear transaction data. The user should cancel or skip to continue.\n // A terminal \"success\" is a non-error response with no further actions available.\n // In these narrow cases, saved transaction data should be cleared.\n // One example of a terminal success is when the email verify flow is continued in another tab\n const hasActions = Object.keys(idxResponse!.actions).length > 0;\n const hasErrors = !!messages.find(msg => msg.class === 'ERROR');\n const isTerminalSuccess = !hasActions && !hasErrors && idxResponse!.requestDidSucceed === true;\n if (isTerminalSuccess) {\n shouldClearTransaction = true;\n } else {\n // save response if there are actions available (ignore messages)\n shouldSaveResponse = !!hasActions;\n }\n // leave shared storage intact so the transaction can be continued in another tab\n clearSharedStorage = false;\n } else if (canceled) {\n status = IdxStatus.CANCELED;\n shouldClearTransaction = true;\n } else if (idxResponse?.interactionCode) { \n interactionCode = idxResponse.interactionCode;\n if (exchangeCodeForTokens === false) {\n status = IdxStatus.SUCCESS;\n shouldClearTransaction = false;\n } else {\n tokens = await getTokens(authClient, data);\n status = IdxStatus.SUCCESS;\n shouldClearTransaction = true;\n }\n }\n return {\n ...data,\n status,\n interactionCode,\n tokens,\n shouldSaveResponse,\n shouldClearTransaction,\n clearSharedStorage,\n enabledFeatures,\n availableSteps,\n messages,\n terminal\n };\n}\n\nexport async function run(\n authClient: OktaAuthIdxInterface, \n options: RunOptions = {},\n): Promise {\n let data: RunData = {\n options,\n values: initializeValues(options)\n };\n\n data = initializeData(authClient, data);\n data = await getDataFromIntrospect(authClient, data);\n data = await getDataFromRemediate(authClient, data);\n data = await finalizeData(authClient, data);\n\n const {\n idxResponse,\n meta,\n shouldSaveResponse,\n shouldClearTransaction,\n clearSharedStorage,\n status,\n enabledFeatures,\n availableSteps,\n tokens,\n nextStep,\n messages,\n error,\n interactionCode\n } = data;\n\n if (shouldClearTransaction) {\n authClient.transactionManager.clear({ clearSharedStorage });\n }\n else {\n // ensures state is saved to sessionStorage\n saveTransactionMeta(authClient, { ...meta });\n\n if (shouldSaveResponse) {\n // Save intermediate idx response in storage to reduce introspect call\n const { rawIdxState: rawIdxResponse, requestDidSucceed } = idxResponse!;\n authClient.transactionManager.saveIdxResponse({\n rawIdxResponse,\n requestDidSucceed,\n stateHandle: idxResponse!.context?.stateHandle,\n interactionHandle: meta?.interactionHandle\n });\n }\n }\n \n // copy all fields from idxResponse which are needed by the widget\n const { actions, context, neededToProceed, proceed, rawIdxState, requestDidSucceed, stepUp } = idxResponse || {};\n return {\n status: status!,\n ...(meta && { meta }),\n ...(enabledFeatures && { enabledFeatures }),\n ...(availableSteps && { availableSteps }),\n ...(tokens && { tokens }),\n ...(nextStep && { nextStep }),\n ...(messages && messages.length && { messages }),\n ...(error && { error }),\n ...(stepUp && { stepUp }),\n interactionCode, // if options.exchangeCodeForTokens is false\n\n // from idx-js\n actions: actions!,\n context: context!,\n neededToProceed: neededToProceed!,\n proceed: proceed!,\n rawIdxState: rawIdxState!,\n requestDidSucceed\n };\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { \n OktaAuthIdxInterface,\n IdxTransaction,\n AuthenticatorKey,\n AuthenticationOptions\n} from './types';\nimport { run } from './run';\n\nexport async function authenticate(\n authClient: OktaAuthIdxInterface, options: AuthenticationOptions = {}\n): Promise {\n if (options.password && !options.authenticator) {\n options.authenticator = AuthenticatorKey.OKTA_PASSWORD;\n }\n return run(authClient, { \n ...options, \n flow: 'authenticate'\n });\n}\n", "import { IdxAuthenticator, IdxRemediationValue } from '../types/idx-js';\n\n\nexport interface Credentials {\n [key: string]: string | boolean | number | undefined;\n}\n\nexport abstract class Authenticator {\n meta: IdxAuthenticator;\n\n constructor(authenticator: IdxAuthenticator) {\n this.meta = authenticator;\n }\n\n abstract canVerify(values: Values): boolean;\n\n abstract mapCredentials(values: Values): Credentials | undefined;\n\n abstract getInputs(idxRemediationValue: IdxRemediationValue): any; // TODO: add type\n}\n", "import { Authenticator, Credentials } from './Authenticator';\n\nexport interface VerificationCodeValues {\n verificationCode?: string;\n otp?: string;\n credentials?: Credentials;\n}\n\ninterface VerificationCodeCredentials extends Credentials {\n passcode: string;\n}\n\n// general authenticator to handle \"verificationCode\" input\n// it can be used for \"email\", \"phone\", \"google authenticator\"\n// a new authenticator class should be created if special cases need to be handled\nexport class VerificationCodeAuthenticator extends Authenticator {\n canVerify(values: VerificationCodeValues) {\n return !!(values.credentials ||values.verificationCode || values.otp);\n }\n\n mapCredentials(values): VerificationCodeCredentials | Credentials | undefined {\n const { credentials, verificationCode, otp } = values;\n if (!credentials && !verificationCode && !otp) {\n return;\n }\n return credentials || { passcode: verificationCode || otp };\n }\n\n getInputs(idxRemediationValue) {\n return {\n ...idxRemediationValue.form?.value[0],\n name: 'verificationCode',\n type: 'string',\n required: idxRemediationValue.required\n };\n }\n}\n", "import { Credentials } from './Authenticator';\nimport { VerificationCodeAuthenticator } from './VerificationCodeAuthenticator';\n\ninterface TotpCredentials extends Credentials {\n totp: string;\n}\n\nexport class OktaVerifyTotp extends VerificationCodeAuthenticator {\n mapCredentials(values): TotpCredentials | undefined {\n const { verificationCode } = values;\n if (!verificationCode) {\n return;\n }\n return { totp: verificationCode };\n }\n}\n", "import { Authenticator, Credentials } from './Authenticator';\n\nexport interface OktaPasswordInputValues {\n password?: string;\n passcode?: string;\n credentials?: Credentials;\n // for ResetAuthenticator\n revokeSessions?: boolean;\n}\n\nexport class OktaPassword extends Authenticator {\n canVerify(values: OktaPasswordInputValues) {\n return !!(values.credentials || values.password || values.passcode);\n }\n\n mapCredentials(values: OktaPasswordInputValues): Credentials | undefined {\n const { credentials, password, passcode, revokeSessions } = values;\n if (!credentials && !password && !passcode) {\n return;\n }\n return credentials || {\n passcode: passcode || password,\n revokeSessions,\n };\n }\n\n getInputs(idxRemediationValue) {\n const inputs = [{\n ...idxRemediationValue.form?.value[0],\n name: 'password',\n type: 'string',\n required: idxRemediationValue.required,\n }];\n const revokeSessions = idxRemediationValue.form?.value.find(\n input => input.name === 'revokeSessions'\n );\n if (revokeSessions) {\n inputs.push({\n name: 'revokeSessions',\n type: 'boolean',\n label: 'Sign me out of all other devices',\n required: false,\n });\n }\n return inputs;\n }\n}\n", "import { Authenticator, Credentials } from './Authenticator';\n\nexport interface SecurityQuestionEnrollValues {\n questionKey?: string;\n question?: string;\n answer?: string;\n credentials?: Credentials;\n}\n\nexport class SecurityQuestionEnrollment extends Authenticator {\n canVerify(values: SecurityQuestionEnrollValues) {\n const { credentials } = values;\n if (credentials && credentials.questionKey && credentials.answer) {\n return true;\n }\n const { questionKey, question, answer } = values;\n return !!(questionKey && answer) || !!(question && answer);\n }\n\n mapCredentials(values: SecurityQuestionEnrollValues): Credentials | undefined {\n const { questionKey, question, answer } = values;\n if (!answer || (!questionKey && !question)) {\n return;\n }\n return {\n questionKey: question ? 'custom' : questionKey,\n question,\n answer\n };\n }\n\n getInputs() {\n return [\n { name: 'questionKey', type: 'string', required: true },\n { name: 'question', type: 'string', label: 'Create a security question' },\n { name: 'answer', type: 'string', label: 'Answer', required: true },\n ];\n }\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport { Authenticator, Credentials } from './Authenticator';\n\nexport interface SecurityQuestionVerificationValues {\n answer?: string;\n credentials?: Credentials;\n}\n\nexport class SecurityQuestionVerification extends Authenticator {\n canVerify(values: SecurityQuestionVerificationValues) {\n const { credentials } = values;\n if (credentials && credentials.answer) {\n return true;\n }\n const { answer } = values;\n return !!answer;\n }\n\n mapCredentials(values: SecurityQuestionVerificationValues): Credentials | undefined {\n const { answer } = values;\n if (!answer) {\n return;\n }\n return {\n questionKey: this.meta.contextualData!.enrolledQuestion!.questionKey,\n answer\n };\n }\n\n getInputs() {\n return [\n { name: 'answer', type: 'string', label: 'Answer', required: true }\n ];\n }\n}\n", "import { Authenticator, Credentials } from './Authenticator';\n\nexport interface WebauthnEnrollValues {\n clientData?: string;\n attestation?: string;\n credentials?: Credentials;\n}\n\nexport class WebauthnEnrollment extends Authenticator {\n canVerify(values: WebauthnEnrollValues) {\n const { credentials } = values;\n const obj = credentials || values;\n const { clientData, attestation } = obj;\n return !!(clientData && attestation);\n }\n\n mapCredentials(values: WebauthnEnrollValues): Credentials | undefined {\n const { credentials, clientData, attestation } = values;\n if (!credentials && !clientData && !attestation) {\n return;\n }\n return credentials || ({\n clientData,\n attestation\n });\n }\n\n getInputs() {\n return [\n { name: 'clientData', type: 'string', required: true, visible: false, label: 'Client Data' },\n { name: 'attestation', type: 'string', required: true, visible: false, label: 'Attestation' },\n ];\n }\n}\n", "import { Authenticator, Credentials } from './Authenticator';\n\nexport interface WebauthnVerificationValues {\n clientData?: string;\n authenticatorData?: string;\n signatureData?: string;\n credentials?: Credentials;\n}\n\nexport class WebauthnVerification extends Authenticator {\n canVerify(values: WebauthnVerificationValues) {\n const { credentials } = values;\n const obj = credentials || values;\n const { clientData, authenticatorData, signatureData } = obj;\n return !!(clientData && authenticatorData && signatureData);\n }\n\n mapCredentials(values: WebauthnVerificationValues): Credentials | undefined {\n const { credentials, authenticatorData, clientData, signatureData } = values;\n if (!credentials && !authenticatorData && !clientData && !signatureData) {\n return;\n }\n return credentials || ({\n authenticatorData,\n clientData,\n signatureData\n });\n }\n\n getInputs() {\n return [\n { name: 'authenticatorData', type: 'string', label: 'Authenticator Data', required: true, visible: false },\n { name: 'clientData', type: 'string', label: 'Client Data', required: true, visible: false },\n { name: 'signatureData', type: 'string', label: 'Signature Data', required: true, visible: false },\n ];\n }\n}\n", "import { OktaVerifyTotp } from './OktaVerifyTotp';\nimport { Authenticator } from './Authenticator';\nimport { VerificationCodeAuthenticator } from './VerificationCodeAuthenticator';\nimport { OktaPassword } from './OktaPassword';\nimport { SecurityQuestionEnrollment } from './SecurityQuestionEnrollment';\nimport { SecurityQuestionVerification } from './SecurityQuestionVerification';\nimport { WebauthnEnrollment } from './WebauthnEnrollment';\nimport { WebauthnVerification } from './WebauthnVerification';\nimport { IdxAuthenticator, IdxRemediation } from '../types/idx-js';\nimport { AuthenticatorKey } from '../types';\n\n/* eslint complexity:[0,8] */\nexport function getAuthenticator(remediation: IdxRemediation): Authenticator {\n const relatesTo = remediation.relatesTo;\n const value = relatesTo?.value || {} as IdxAuthenticator;\n switch (value.key) {\n case AuthenticatorKey.OKTA_PASSWORD:\n return new OktaPassword(value);\n case AuthenticatorKey.SECURITY_QUESTION:\n if (value.contextualData?.enrolledQuestion) {\n return new SecurityQuestionVerification(value);\n } else {\n return new SecurityQuestionEnrollment(value);\n }\n case AuthenticatorKey.OKTA_VERIFY:\n return new OktaVerifyTotp(value);\n case AuthenticatorKey.WEBAUTHN:\n if (value.contextualData?.challengeData) {\n return new WebauthnVerification(value);\n } else {\n return new WebauthnEnrollment(value);\n }\n default:\n return new VerificationCodeAuthenticator(value);\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { Remediator, RemediationValues } from './Remediator';\nimport { getAuthenticator, Authenticator, AuthenticatorValues } from '../../authenticator';\nimport { IdxRemediation, IdxContext } from '../../types/idx-js';\nimport { OktaAuthIdxInterface, NextStep } from '../../types';\n\nexport type VerifyAuthenticatorValues = AuthenticatorValues & RemediationValues;\n\n// Base class - DO NOT expose static remediationName\nexport class VerifyAuthenticator\n extends Remediator {\n\n authenticator: Authenticator;\n\n constructor(remediation: IdxRemediation, values: T = {} as T) {\n super(remediation, values);\n this.authenticator = getAuthenticator(remediation);\n }\n\n getNextStep(authClient: OktaAuthIdxInterface, context?: IdxContext): NextStep {\n const nextStep = super.getNextStep(authClient, context);\n const authenticatorEnrollments = context?.authenticatorEnrollments?.value;\n\n return {\n ...nextStep,\n authenticatorEnrollments\n };\n }\n\n canRemediate() {\n return this.authenticator.canVerify(this.values);\n }\n\n mapCredentials() {\n return this.authenticator.mapCredentials(this.values);\n }\n\n getInputCredentials(input) {\n return this.authenticator.getInputs(input);\n }\n\n getValuesAfterProceed(): T {\n this.values = super.getValuesAfterProceed();\n let trimmedValues = Object.keys(this.values).filter(valueKey => valueKey !== 'credentials');\n return trimmedValues.reduce((values, valueKey) => ({...values, [valueKey]: this.values[valueKey]}), {} as T);\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { VerifyAuthenticator, VerifyAuthenticatorValues } from './Base/VerifyAuthenticator';\n\nexport type EnrollAuthenticatorValues = VerifyAuthenticatorValues;\n\nexport class EnrollAuthenticator extends VerifyAuthenticator {\n static remediationName = 'enroll-authenticator';\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { Remediator, RemediationValues } from './Base/Remediator';\nimport { NextStep, OktaAuthIdxInterface } from '../types';\nimport { IdxContext } from '../types/idx-js';\n\nexport interface EnrollPollValues extends RemediationValues {\n startPolling?: boolean;\n}\n\nexport class EnrollPoll extends Remediator {\n static remediationName = 'enroll-poll';\n\n canRemediate() {\n return !!this.values.startPolling || this.options.step === 'enroll-poll';\n }\n\n getNextStep(authClient: OktaAuthIdxInterface, context?: IdxContext): NextStep {\n const common = super.getNextStep(authClient, context);\n let authenticator = this.getAuthenticator();\n if (!authenticator && context?.currentAuthenticator) {\n authenticator = context.currentAuthenticator.value;\n }\n return {\n ...common,\n authenticator,\n poll: {\n required: true,\n refresh: this.remediation.refresh\n },\n };\n }\n\n getValuesAfterProceed(): EnrollPollValues {\n let trimmedValues = Object.keys(this.values).filter(valueKey => valueKey !== 'startPolling');\n return trimmedValues.reduce((values, valueKey) => ({...values, [valueKey]: this.values[valueKey]}), {});\n }\n}\n", "/*!\n * Copyright (c) 2021-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { Remediator, RemediationValues } from './Base/Remediator';\nimport { IdxRemediationValueForm, IdxContext } from '../types/idx-js';\nimport { Authenticator, OktaAuthIdxInterface } from '../types/api';\n\n\nexport type SelectEnrollmentChannelValues = RemediationValues & {\n channel?: string;\n};\n\nexport class SelectEnrollmentChannel extends Remediator {\n static remediationName = 'select-enrollment-channel';\n\n canRemediate() {\n if (this.values.channel) {\n return true;\n }\n\n if (this.values.authenticator) {\n const { id, channel } = this.values.authenticator as Authenticator;\n if (!!id && !!channel) {\n return true;\n }\n }\n\n return false;\n }\n\n getNextStep(authClient: OktaAuthIdxInterface, context: IdxContext) {\n const common = super.getNextStep(authClient, context);\n const authenticator = context.currentAuthenticator.value;\n return {\n ...common,\n authenticator,\n };\n }\n\n getData() {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const remediationValue = this.remediation!.value![0].value as IdxRemediationValueForm;\n return {\n authenticator: {\n id: remediationValue.form.value[0].value,\n channel: (this.values.authenticator as Authenticator)?.channel || this.values.channel,\n },\n stateHandle: this.values.stateHandle,\n\n };\n }\n\n getValuesAfterProceed(): SelectEnrollmentChannelValues {\n this.values = super.getValuesAfterProceed();\n delete this.values.authenticators; // required to prevent infinite loops from auto-remediating via values\n const filterKey = this.values.channel ? 'channel' : 'authenticator';\n let trimmedValues = Object.keys(this.values).filter(valueKey => valueKey !== filterKey);\n return trimmedValues.reduce((values, valueKey) => ({...values, [valueKey]: this.values[valueKey]}), {});\n }\n}\n", "/*!\n * Copyright (c) 2021-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { Remediator, RemediationValues } from './Base/Remediator';\nimport { IdxContext } from '../types/idx-js';\nimport { OktaAuthIdxInterface } from '../types';\n\n\nexport type EnrollmentChannelDataValues = RemediationValues & {\n email?: string;\n phoneNumber?: string;\n};\n\nexport class EnrollmentChannelData extends Remediator {\n static remediationName = 'enrollment-channel-data';\n\n getInputEmail() {\n return [\n { name: 'email', type: 'string', required: true, label: 'Email' },\n ];\n }\n\n getInputPhoneNumber() {\n return [\n { name: 'phoneNumber', type: 'string', required: true, label: 'Phone Number' },\n ];\n }\n\n canRemediate() {\n return Boolean(this.values.email || this.values.phoneNumber);\n }\n\n getNextStep(authClient: OktaAuthIdxInterface, context: IdxContext) {\n const common = super.getNextStep(authClient, context);\n const authenticator = context.currentAuthenticator.value;\n return {\n ...common,\n authenticator,\n };\n }\n\n getData() {\n return {\n stateHandle: this.values.stateHandle,\n email: this.values.email,\n phoneNumber: this.values.phoneNumber\n };\n }\n\n getValuesAfterProceed(): EnrollmentChannelDataValues {\n let trimmedValues = Object.keys(this.values).filter(valueKey => !['email', 'phoneNumber'].includes(valueKey));\n return trimmedValues.reduce((values, valueKey) => ({...values, [valueKey]: this.values[valueKey]}), {});\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { VerifyAuthenticator, VerifyAuthenticatorValues } from './Base/VerifyAuthenticator';\n\nexport type ChallengeAuthenticatorValues = VerifyAuthenticatorValues;\n\nexport class ChallengeAuthenticator extends VerifyAuthenticator {\n static remediationName = 'challenge-authenticator';\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { EnrollPoll } from './EnrollPoll';\n\nexport class ChallengePoll extends EnrollPoll{\n static remediationName = 'challenge-poll';\n\n canRemediate() {\n return !!this.values.startPolling || this.options.step === 'challenge-poll';\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { VerifyAuthenticator, VerifyAuthenticatorValues } from './Base/VerifyAuthenticator';\n\nexport type ResetAuthenticatorValues = VerifyAuthenticatorValues;\n\nexport class ResetAuthenticator extends VerifyAuthenticator {\n static remediationName = 'reset-authenticator';\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { IdxRemediation, IdxRemediationValue, IdxAuthenticator } from '../types/idx-js';\nimport { RemediateOptions } from '../types';\nimport { Remediator, RemediationValues } from './Base/Remediator';\nimport { Authenticator, Credentials, OktaPassword } from '../authenticator';\n\nexport interface EnrollProfileValues extends RemediationValues {\n firstName?: string;\n lastName?: string;\n email?: string;\n credentials?: Credentials;\n password?: string;\n passcode?: string;\n}\n\nexport class EnrollProfile extends Remediator {\n static remediationName = 'enroll-profile';\n\n authenticator: Authenticator | null = null;\n\n constructor(\n remediation: IdxRemediation,\n values: EnrollProfileValues = {},\n options: RemediateOptions = {}\n ) {\n super(remediation, values, options);\n\n // credentials are only required when Profile Enrollment policy requires them\n // if credentials are included in the remediation, they are considered required\n // otherwise it will be omitted\n const credentials = this.getCredentialsFromRemediation();\n if (credentials) {\n this.authenticator = this.authenticator = new OktaPassword({} as IdxAuthenticator);\n }\n }\n\n canRemediate() {\n // ensure credentials can be verified, if required\n if (this.authenticator && !this.authenticator.canVerify(this.values)) {\n return false;\n }\n\n const userProfileFromValues = this.getData().userProfile;\n if (!userProfileFromValues) {\n return false;\n }\n // eslint-disable-next-line max-len\n const userProfileFromRemediation = this.remediation.value!.find(({ name }) => name === 'userProfile') as IdxRemediationValue;\n return userProfileFromRemediation.form!.value.reduce((canRemediate, curr) => {\n if (curr.required) {\n canRemediate = canRemediate && !!userProfileFromValues[curr.name];\n }\n return canRemediate;\n }, true);\n }\n\n getCredentialsFromRemediation () {\n return this.remediation.value!.find(({ name }) => name === 'credentials');\n }\n\n mapUserProfile({form: { value: profileAttributes }}) {\n const attributeNames = profileAttributes.map(({name}) => name);\n const data = attributeNames.reduce((attributeValues, attributeName) => (\n this.values[attributeName] ? {\n ...attributeValues,\n [attributeName]: this.values[attributeName]\n } : attributeValues), {});\n if (Object.keys(data).length === 0) {\n return;\n }\n return data;\n }\n\n mapCredentials() {\n const val = this.authenticator && this.authenticator.mapCredentials(this.values);\n if (!val) {\n return;\n }\n return val;\n }\n\n getInputUserProfile(input) {\n return [...input.form.value];\n }\n\n getInputCredentials(input) {\n return [...input.form.value];\n }\n\n getErrorMessages(errorRemediation) {\n return errorRemediation.value[0].form.value.reduce((errors, field) => {\n if (field.messages) {\n errors.push(field.messages.value[0].message);\n }\n return errors;\n }, []);\n }\n}", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { Credentials } from '../authenticator';\nimport { Remediator, RemediationValues } from './Base/Remediator';\n\nexport interface IdentifyValues extends RemediationValues {\n username?: string;\n password?: string;\n credentials?: Credentials;\n rememberMe?: boolean;\n}\n\nexport class Identify extends Remediator {\n static remediationName = 'identify';\n\n map = {\n 'identifier': ['username']\n };\n\n canRemediate(): boolean {\n const { identifier } = this.getData();\n return !!identifier;\n }\n\n mapCredentials() {\n const { credentials, password } = this.values;\n if (!credentials && !password) {\n return;\n }\n return credentials || { passcode: password };\n }\n\n getInputCredentials(input) {\n return {\n ...input.form.value[0],\n name: 'password',\n required: input.required\n };\n }\n\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { Remediator, RemediationValues } from './Base/Remediator';\n\nexport interface ReEnrollAuthenticatorValues extends RemediationValues {\n newPassword?: string;\n}\n\nexport class ReEnrollAuthenticator extends Remediator {\n static remediationName = 'reenroll-authenticator';\n\n mapCredentials() {\n const { newPassword } = this.values;\n if (!newPassword) {\n return;\n }\n return { \n passcode: newPassword,\n };\n }\n\n getInputCredentials(input) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const challengeType = this.getAuthenticator()!.type;\n const name = challengeType === 'password' ? 'newPassword' : 'verificationCode';\n return {\n ...input.form.value[0],\n name\n };\n }\n\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { ReEnrollAuthenticator } from './ReEnrollAuthenticator';\n\nexport class ReEnrollAuthenticatorWarning extends ReEnrollAuthenticator {\n static remediationName = 'reenroll-authenticator-warning';\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { Remediator } from './Base/Remediator';\n\nexport class RedirectIdp extends Remediator {\n static remediationName = 'redirect-idp';\n\n canRemediate() {\n return false;\n }\n\n getNextStep() {\n const { name, type, idp, href } = this.remediation;\n return {\n name,\n type,\n idp,\n href\n };\n }\n\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { Remediator, RemediationValues } from './Remediator';\nimport { getAuthenticatorFromRemediation } from '../util';\nimport { IdxRemediationValue, IdxContext, IdxOption } from '../../types/idx-js';\nimport { Authenticator, isAuthenticator } from '../../types/api';\nimport { compareAuthenticators, findMatchedOption} from '../../authenticator/util';\n\nexport type SelectAuthenticatorValues = RemediationValues & {\n authenticator?: string | Authenticator;\n};\n\n// Base class - DO NOT expose static remediationName\nexport class SelectAuthenticator\n extends Remediator {\n selectedAuthenticator?: Authenticator;\n selectedOption?: any;\n\n // Find matched authenticator in provided order\n findMatchedOption(authenticators, options) {\n let option: IdxOption | undefined;\n for (let authenticator of authenticators) {\n option = options\n .find(({ relatesTo }) => relatesTo.key && relatesTo.key === authenticator.key);\n if (option) {\n break;\n }\n }\n return option;\n }\n\n /* eslint complexity:[0,9] */\n canRemediate(context?: IdxContext) {\n const { authenticators, authenticator } = this.values;\n const authenticatorFromRemediation = getAuthenticatorFromRemediation(this.remediation);\n const { options } = authenticatorFromRemediation;\n // Let users select authenticator if no input is provided\n if (!authenticators || !authenticators.length) {\n return false;\n }\n\n // Authenticator is explicitly specified by id\n if (isAuthenticator(authenticator) && authenticator.id) {\n return true;\n }\n\n // Proceed with provided authenticators\n const matchedOption = this.findMatchedOption(authenticators, options!);\n if (matchedOption) {\n // Don't select current authenticator (OKTA-612939)\n const isCurrentAuthenticator = context?.currentAuthenticator\n && context?.currentAuthenticator.value.id === matchedOption.relatesTo?.id;\n const isCurrentAuthenticatorEnrollment = context?.currentAuthenticatorEnrollment\n && context?.currentAuthenticatorEnrollment.value.id === matchedOption.relatesTo?.id;\n return !isCurrentAuthenticator && !isCurrentAuthenticatorEnrollment;\n }\n \n return false;\n }\n\n mapAuthenticator(remediationValue: IdxRemediationValue) {\n const { authenticators, authenticator } = this.values;\n\n // Authenticator is explicitly specified by id\n if (isAuthenticator(authenticator) && authenticator.id) {\n this.selectedAuthenticator = authenticator; // track the selected authenticator\n return authenticator;\n }\n\n const { options } = remediationValue;\n const selectedOption = findMatchedOption(authenticators, options);\n this.selectedAuthenticator = selectedOption.relatesTo; // track the selected authenticator\n this.selectedOption = selectedOption;\n return {\n id: selectedOption?.value.form.value.find(({ name }) => name === 'id').value\n };\n }\n\n getInputAuthenticator(remediation) {\n const options = remediation.options.map(({ label, relatesTo }) => {\n return {\n label,\n value: relatesTo.key\n };\n });\n return { name: 'authenticator', type: 'string', options };\n }\n\n getValuesAfterProceed(): T {\n this.values = super.getValuesAfterProceed();\n // remove used authenticators\n const authenticators = (this.values.authenticators as Authenticator[])\n .filter(authenticator => {\n return compareAuthenticators(authenticator, this.selectedAuthenticator) !== true;\n });\n return { ...this.values, authenticators };\n }\n\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { SelectAuthenticator, SelectAuthenticatorValues } from './Base/SelectAuthenticator';\nimport { getAuthenticatorFromRemediation } from './util';\nimport { IdxRemediation } from '../types/idx-js';\nimport { AuthenticatorKey, Authenticator, RemediateOptions } from '../types';\n\nexport type SelectAuthenticatorAuthenticateValues = SelectAuthenticatorValues & {\n password?: string;\n};\n\nexport class SelectAuthenticatorAuthenticate extends SelectAuthenticator {\n static remediationName = 'select-authenticator-authenticate';\n\n constructor(\n remediation: IdxRemediation, \n values: SelectAuthenticatorValues = {}, \n options: RemediateOptions = {}\n ) {\n super(remediation, values, options);\n\n // Preset password authenticator to trigger recover action\n const isRecoveryFlow = this.options.flow === 'recoverPassword';\n const hasPasswordInOptions = getAuthenticatorFromRemediation(remediation)\n .options?.some(({ relatesTo }) => relatesTo?.key === AuthenticatorKey.OKTA_PASSWORD);\n if (hasPasswordInOptions && (isRecoveryFlow || this.values.password)) {\n this.values.authenticators = [\n ...this.values.authenticators || [],\n { key: AuthenticatorKey.OKTA_PASSWORD }\n ] as Authenticator[];\n }\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { SelectAuthenticator, SelectAuthenticatorValues } from './Base/SelectAuthenticator';\n\nexport type SelectAuthenticatorEnrollValues = SelectAuthenticatorValues;\n\nexport class SelectAuthenticatorEnroll extends SelectAuthenticator {\n static remediationName = 'select-authenticator-enroll';\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { SelectAuthenticator, SelectAuthenticatorValues } from './Base/SelectAuthenticator';\nimport { Authenticator } from '../types';\nimport { IdxRemediationValue } from '../types/idx-js';\n\n\nexport type SelectAuthenticatorUnlockAccountValues = SelectAuthenticatorValues & {\n identifier?: string;\n methodType?: string;\n};\n\nexport class SelectAuthenticatorUnlockAccount extends SelectAuthenticator {\n static remediationName = 'select-authenticator-unlock-account';\n authenticator?: Authenticator;\n\n map = {\n identifier: ['username']\n };\n\n canRemediate() {\n const identifier = this.getData('identifier');\n return !!identifier && super.canRemediate();\n }\n\n mapAuthenticator(remediationValue: IdxRemediationValue) {\n const authenticatorMap = super.mapAuthenticator(remediationValue);\n const methodTypeOption = this.selectedOption?.value.form.value.find(({ name }) => name === 'methodType');\n\n // defaults to 'manually defined' value\n // 2nd: option may have pre-defined value, like stateHandle\n // 3rd: if only a single OV option is available, default to that option\n const methodTypeValue = this.values.methodType ||\n methodTypeOption?.value as string || methodTypeOption?.options?.[0]?.value as string;\n\n if (methodTypeValue) {\n return {\n ...authenticatorMap,\n methodType: methodTypeValue\n };\n }\n\n return authenticatorMap;\n }\n\n getInputUsername () {\n return { name: 'username', type: 'string' };\n }\n\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { Remediator, RemediationValues } from './Base/Remediator';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface SelectEnrollProfileValues extends RemediationValues {}\n\nexport class SelectEnrollProfile extends Remediator {\n static remediationName = 'select-enroll-profile';\n\n canRemediate() {\n return true;\n }\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { Remediator, RemediationValues } from './Remediator';\nimport { IdxRemediationValue, IdxRemediation, IdxAuthenticator } from '../../types/idx-js';\nimport { isAuthenticator } from '../../types/api';\nimport { compareAuthenticators } from '../../authenticator/util';\n\nexport type AuthenticatorDataValues = RemediationValues & {\n methodType?: string;\n};\n\n// Base class - DO NOT expose static remediationName\nexport class AuthenticatorData extends Remediator {\n authenticator: IdxAuthenticator;\n\n constructor(remediation: IdxRemediation, values: T = {} as T) {\n super(remediation, values);\n\n // set before other data calculation\n this.authenticator = this.getAuthenticator()!;\n\n this.formatAuthenticatorData();\n }\n\n protected formatAuthenticatorData() {\n const authenticatorData = this.getAuthenticatorData();\n if (authenticatorData) {\n this.values.authenticatorsData = this.values.authenticatorsData!.map(data => {\n if (compareAuthenticators(this.authenticator, data)) {\n return this.mapAuthenticatorDataFromValues(data);\n }\n return data;\n });\n } else {\n const data = this.mapAuthenticatorDataFromValues();\n if (data) {\n this.values.authenticatorsData!.push(data);\n }\n }\n }\n\n protected getAuthenticatorData() {\n return this.values.authenticatorsData!\n .find((data) => compareAuthenticators(this.authenticator, data));\n }\n\n canRemediate() {\n return this.values.authenticatorsData!\n .some(data => compareAuthenticators(this.authenticator, data));\n }\n\n protected mapAuthenticatorDataFromValues(authenticatorData?) {\n // add methodType to authenticatorData if it exists in values\n let { methodType, authenticator } = this.values;\n if (!methodType && isAuthenticator(authenticator)) {\n methodType = authenticator?.methodType;\n }\n \n const { id, enrollmentId } = this.authenticator;\n const data = { \n id,\n enrollmentId,\n ...(authenticatorData && authenticatorData),\n ...(methodType && { methodType }) \n };\n\n return data.methodType ? data : null;\n }\n\n protected getAuthenticatorFromRemediation(): IdxRemediationValue {\n const authenticator = this.remediation.value!\n .find(({ name }) => name === 'authenticator') as IdxRemediationValue;\n return authenticator;\n }\n\n getValuesAfterProceed(): T {\n this.values = super.getValuesAfterProceed();\n // remove used authenticatorData\n const authenticatorsData = this.values.authenticatorsData!\n .filter(data => compareAuthenticators(this.authenticator, data) !== true);\n return { ...this.values, authenticatorsData };\n }\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { AuthenticatorData, AuthenticatorDataValues } from './Base/AuthenticatorData';\n\nexport type AuthenticatorVerificationDataValues = AuthenticatorDataValues;\n\nexport class AuthenticatorVerificationData extends AuthenticatorData {\n static remediationName = 'authenticator-verification-data';\n\n mapAuthenticator() {\n return this.getAuthenticatorData();\n }\n\n getInputAuthenticator() {\n const authenticator = this.getAuthenticatorFromRemediation();\n const methodType = authenticator.form!.value.find(({ name }) => name === 'methodType');\n // if has methodType in form, let user select the methodType\n if (methodType && methodType.options) {\n return { \n name: 'methodType', \n type: 'string', \n required: true, \n options: methodType.options \n };\n }\n // no methodType, then return form values\n const inputs = [...authenticator.form!.value];\n return inputs;\n }\n\n getValuesAfterProceed(): AuthenticatorVerificationDataValues {\n this.values = super.getValuesAfterProceed();\n let trimmedValues = Object.keys(this.values).filter(valueKey => valueKey !== 'authenticator');\n return trimmedValues.reduce((values, valueKey) => ({...values, [valueKey]: this.values[valueKey]}), {});\n }\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { AuthenticatorData, AuthenticatorDataValues } from './Base/AuthenticatorData';\nimport { getAuthenticatorFromRemediation } from './util';\n\nexport type AuthenticatorEnrollmentDataValues = AuthenticatorDataValues & {\n phoneNumber?: string;\n resend?: boolean; // resend is not a remediator value - revise when IdxResponse structure is updated\n}\nexport class AuthenticatorEnrollmentData extends AuthenticatorData {\n static remediationName = 'authenticator-enrollment-data';\n\n mapAuthenticator() {\n const authenticatorData = this.getAuthenticatorData();\n const authenticatorFromRemediation = getAuthenticatorFromRemediation(this.remediation)!;\n return { \n id: authenticatorFromRemediation.form!.value\n .find(({ name }) => name === 'id')!.value,\n methodType: authenticatorData!.methodType,\n phoneNumber: authenticatorData!.phoneNumber,\n };\n }\n\n getInputAuthenticator(remediation) {\n return [\n { name: 'methodType', type: 'string' }, \n { name: 'phoneNumber', label: 'Phone Number', type: 'string' }\n ].map(item => {\n const value = remediation.form.value.find(val => val.name === item.name);\n return { ...value, ...item };\n });\n }\n\n protected mapAuthenticatorDataFromValues(data?) {\n // get mapped authenticator from base class\n data = super.mapAuthenticatorDataFromValues(data);\n // add phoneNumber to authenticator if it exists in values\n const { phoneNumber } = this.values;\n if (!data && !phoneNumber) {\n return;\n }\n\n return { \n ...(data && data), \n ...(phoneNumber && { phoneNumber }) \n };\n }\n\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { Remediator, RemediationValues } from './Base/Remediator';\n\nexport interface SkipValues extends RemediationValues {\n skip?: boolean;\n}\n\nexport class Skip extends Remediator {\n static remediationName = 'skip';\n\n canRemediate() {\n return !!this.values.skip || this.options.step === 'skip';\n }\n\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { RemediationFlow } from './RemediationFlow';\nimport { \n Identify,\n SelectAuthenticatorAuthenticate,\n ChallengeAuthenticator,\n ReEnrollAuthenticator,\n ReEnrollAuthenticatorWarning,\n RedirectIdp,\n AuthenticatorEnrollmentData,\n SelectAuthenticatorEnroll,\n EnrollAuthenticator,\n AuthenticatorVerificationData,\n EnrollPoll,\n ChallengePoll,\n SelectEnrollmentChannel,\n EnrollmentChannelData,\n Skip\n} from '../remediators';\n\nexport const AuthenticationFlow: RemediationFlow = {\n 'identify': Identify,\n 'select-authenticator-authenticate': SelectAuthenticatorAuthenticate,\n 'select-authenticator-enroll': SelectAuthenticatorEnroll,\n 'authenticator-enrollment-data': AuthenticatorEnrollmentData,\n 'authenticator-verification-data': AuthenticatorVerificationData,\n 'enroll-authenticator': EnrollAuthenticator,\n 'challenge-authenticator': ChallengeAuthenticator,\n 'challenge-poll': ChallengePoll,\n 'reenroll-authenticator': ReEnrollAuthenticator,\n 'reenroll-authenticator-warning': ReEnrollAuthenticatorWarning,\n 'enroll-poll': EnrollPoll,\n 'select-enrollment-channel': SelectEnrollmentChannel,\n 'enrollment-channel-data': EnrollmentChannelData,\n 'redirect-idp': RedirectIdp,\n 'skip': Skip,\n};\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { RemediationFlow } from './RemediationFlow';\nimport {\n Identify,\n SelectAuthenticatorAuthenticate,\n ChallengeAuthenticator,\n AuthenticatorVerificationData,\n ResetAuthenticator,\n ReEnrollAuthenticator,\n ReEnrollAuthenticatorWarning,\n SelectAuthenticatorEnroll,\n AuthenticatorEnrollmentData,\n EnrollPoll\n} from '../remediators';\n\nexport const PasswordRecoveryFlow: RemediationFlow = {\n 'identify': Identify,\n 'identify-recovery': Identify,\n 'select-authenticator-authenticate': SelectAuthenticatorAuthenticate,\n 'select-authenticator-enroll': SelectAuthenticatorEnroll,\n 'challenge-authenticator': ChallengeAuthenticator,\n 'authenticator-verification-data': AuthenticatorVerificationData,\n 'authenticator-enrollment-data': AuthenticatorEnrollmentData,\n 'reset-authenticator': ResetAuthenticator,\n 'reenroll-authenticator': ReEnrollAuthenticator,\n 'reenroll-authenticator-warning': ReEnrollAuthenticatorWarning,\n 'enroll-poll': EnrollPoll,\n};\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { RemediationFlow } from './RemediationFlow';\nimport { \n SelectEnrollProfile,\n EnrollPoll,\n SelectEnrollmentChannel,\n EnrollmentChannelData,\n EnrollProfile,\n SelectAuthenticatorEnroll,\n EnrollAuthenticator,\n AuthenticatorEnrollmentData,\n Skip,\n} from '../remediators';\n\nexport const RegistrationFlow: RemediationFlow = {\n 'select-enroll-profile': SelectEnrollProfile,\n 'enroll-profile': EnrollProfile,\n 'authenticator-enrollment-data': AuthenticatorEnrollmentData,\n 'select-authenticator-enroll': SelectAuthenticatorEnroll,\n 'enroll-poll': EnrollPoll,\n 'select-enrollment-channel': SelectEnrollmentChannel,\n 'enrollment-channel-data': EnrollmentChannelData,\n 'enroll-authenticator': EnrollAuthenticator,\n 'skip': Skip,\n};\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { RemediationFlow } from './RemediationFlow';\nimport {\n Identify,\n SelectAuthenticatorUnlockAccount,\n SelectAuthenticatorAuthenticate,\n ChallengeAuthenticator,\n ChallengePoll,\n AuthenticatorVerificationData,\n ReEnrollAuthenticatorWarning\n} from '../remediators';\n\nexport const AccountUnlockFlow: RemediationFlow = {\n 'identify': Identify,\n // NOTE: unlock-account is purposely not included. Handled as action\n // because it's a rememdiation which requires no input\n // 'unlock-account': UnlockAccount,\n 'select-authenticator-unlock-account': SelectAuthenticatorUnlockAccount,\n 'select-authenticator-authenticate': SelectAuthenticatorAuthenticate,\n 'challenge-authenticator': ChallengeAuthenticator,\n 'challenge-poll': ChallengePoll,\n 'authenticator-verification-data': AuthenticatorVerificationData,\n 'reenroll-authenticator-warning': ReEnrollAuthenticatorWarning,\n};\n", "import { OktaAuthIdxInterface, FlowIdentifier, FlowSpecification } from '../types';\nimport { AuthenticationFlow } from './AuthenticationFlow';\nimport { PasswordRecoveryFlow } from './PasswordRecoveryFlow';\nimport { RegistrationFlow } from './RegistrationFlow';\nimport { AccountUnlockFlow } from './AccountUnlockFlow';\n\n// eslint-disable-next-line complexity\nexport function getFlowSpecification(\n oktaAuth: OktaAuthIdxInterface,\n flow: FlowIdentifier = 'default'\n): FlowSpecification {\n let remediators, actions, withCredentials = true;\n switch (flow) {\n case 'register':\n case 'signup':\n case 'enrollProfile':\n remediators = RegistrationFlow;\n withCredentials = false;\n break;\n case 'recoverPassword':\n case 'resetPassword':\n remediators = PasswordRecoveryFlow;\n actions = [\n 'currentAuthenticator-recover', \n 'currentAuthenticatorEnrollment-recover'\n ];\n withCredentials = false;\n break;\n case 'unlockAccount':\n remediators = AccountUnlockFlow;\n withCredentials = false;\n actions = [\n 'unlock-account'\n ];\n break;\n case 'authenticate':\n case 'login':\n case 'signin':\n remediators = AuthenticationFlow;\n break;\n default:\n // default case has no flow monitor\n remediators = AuthenticationFlow;\n break;\n }\n return { flow, remediators, actions, withCredentials };\n}\n", "/*!\n * Copyright (c) 2021, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { OktaAuthIdxInterface, CancelOptions, IdxTransactionMeta } from './types';\nimport { run } from './run';\nimport { getFlowSpecification } from './flow';\n\nexport async function cancel (authClient: OktaAuthIdxInterface, options?: CancelOptions) {\n const meta = authClient.transactionManager.load() as IdxTransactionMeta;\n const flowSpec = getFlowSpecification(authClient, meta.flow);\n return run(authClient, {\n ...options,\n ...flowSpec,\n actions: ['cancel']\n });\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n/* eslint-disable complexity, max-statements */\n\nexport function urlParamsToObject(hashOrSearch: string) {\n // Predefine regexs for parsing hash\n var plus2space = /\\+/g;\n var paramSplit = /([^&=]+)=?([^&]*)/g;\n var fragment = hashOrSearch || '';\n\n // Some hash based routers will automatically add a / character after the hash\n if (fragment.charAt(0) === '#' && fragment.charAt(1) === '/') {\n fragment = fragment.substring(2);\n }\n\n // Remove the leading # or ?\n if (fragment.charAt(0) === '#' || fragment.charAt(0) === '?') {\n fragment = fragment.substring(1);\n }\n\n\n var obj = {};\n\n // Loop until we have no more params\n var param;\n while (true) { // eslint-disable-line no-constant-condition\n param = paramSplit.exec(fragment);\n if (!param) { break; }\n\n var key = param[1];\n var value = param[2];\n\n // id_token should remain base64url encoded\n if (key === 'id_token' || key === 'access_token' || key === 'code') {\n obj[key] = value;\n } else {\n obj[key] = decodeURIComponent(value.replace(plus2space, ' '));\n }\n }\n return obj;\n}\n", "\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { OktaAuthIdxInterface } from './types';\n\nimport CustomError from '../errors/CustomError';\nimport { urlParamsToObject } from '../oidc/util/urlParams';\nimport { EmailVerifyCallbackResponse } from './types/api';\n\nexport class EmailVerifyCallbackError extends CustomError {\n state: string;\n otp: string;\n\n constructor(state: string, otp: string) {\n super(`Enter the OTP code in the originating client: ${otp}`);\n this.name = 'EmailVerifyCallbackError';\n this.state = state;\n this.otp = otp;\n }\n}\n\nexport function isEmailVerifyCallbackError(error: Error) {\n return (error.name === 'EmailVerifyCallbackError');\n}\n\n// Check if state && otp have been passed back in the url\nexport function isEmailVerifyCallback (urlPath: string): boolean {\n return /(otp=)/i.test(urlPath) && /(state=)/i.test(urlPath);\n}\n\n// Parse state and otp from a urlPath (should be either a search or fragment from the URL)\nexport function parseEmailVerifyCallback(urlPath: string): EmailVerifyCallbackResponse {\n return urlParamsToObject(urlPath) as EmailVerifyCallbackResponse;\n}\n\nexport async function handleEmailVerifyCallback(authClient: OktaAuthIdxInterface, search: string) {\n if (isEmailVerifyCallback(search)) {\n const { state, otp } = parseEmailVerifyCallback(search);\n if (authClient.idx.canProceed({ state })) {\n // same browser / device\n return await authClient.idx.proceed({ state, otp });\n } else {\n // different browser or device\n throw new EmailVerifyCallbackError(state, otp);\n }\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { \n OktaAuthIdxInterface,\n IdxTransaction,\n ProceedOptions,\n} from './types';\nimport { run } from './run';\nimport { getSavedTransactionMeta } from './transactionMeta';\nimport { AuthSdkError } from '../errors';\n\nexport function canProceed(authClient: OktaAuthIdxInterface, options: ProceedOptions = {}): boolean {\n const meta = getSavedTransactionMeta(authClient, options);\n return !!(meta || options.stateHandle);\n}\n\nexport async function proceed(\n authClient: OktaAuthIdxInterface,\n options: ProceedOptions = {}\n): Promise {\n\n if (!canProceed(authClient, options)) {\n throw new AuthSdkError('Unable to proceed: saved transaction could not be loaded');\n }\n\n let { flow, state } = options;\n if (!flow) {\n const meta = getSavedTransactionMeta(authClient, { state });\n flow = meta?.flow;\n }\n\n return run(authClient, { \n ...options, \n flow\n });\n}\n", "/*!\n * Copyright (c) 2021-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { proceed } from './proceed';\n\nimport { \n IdxPollOptions,\n IdxTransaction,\n OktaAuthIdxInterface,\n} from './types';\nimport { getSavedTransactionMeta } from './transactionMeta';\nimport { warn } from '../util';\n\nexport async function poll(authClient: OktaAuthIdxInterface, options: IdxPollOptions = {}): Promise {\n let transaction = await proceed(authClient, {\n startPolling: true\n });\n\n const meta = getSavedTransactionMeta(authClient);\n let availablePollingRemeditaions = meta?.remediations?.find(remediation => remediation.includes('poll'));\n if (!availablePollingRemeditaions?.length) {\n warn('No polling remediations available at the current IDX flow stage');\n }\n\n if (Number.isInteger(options.refresh)) {\n return new Promise(function (resolve, reject) {\n setTimeout(async function () {\n try {\n const refresh = transaction.nextStep?.poll?.refresh;\n if (refresh) {\n resolve(poll(authClient, {\n refresh\n }));\n } else {\n resolve(transaction);\n }\n } catch (err) {\n reject(err);\n }\n }, options.refresh);\n });\n }\n\n return transaction;\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { run } from './run';\nimport { OktaAuthIdxInterface, IdxTransaction, StartOptions } from './types';\n\nexport async function startTransaction(\n authClient: OktaAuthIdxInterface, \n options: StartOptions = {}\n): Promise {\n // Clear IDX response cache and saved transaction meta (if any)\n authClient.transactionManager.clear();\n\n return run(authClient, {\n exchangeCodeForTokens: false,\n ...options\n });\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { run } from './run';\nimport { hasSavedInteractionHandle } from './transactionMeta';\nimport { startTransaction } from './startTransaction';\nimport { AuthSdkError } from '../errors';\nimport { \n RegistrationOptions, \n IdxTransaction, \n OktaAuthIdxInterface, \n IdxFeature,\n} from './types';\n\nexport async function register(\n authClient: OktaAuthIdxInterface, options: RegistrationOptions = {}\n): Promise {\n\n // Only check at the beginning of the transaction\n if (!hasSavedInteractionHandle(authClient)) {\n const { enabledFeatures } = await startTransaction(authClient, {\n ...options,\n flow: 'register',\n autoRemediate: false\n });\n if (!options.activationToken && enabledFeatures && !enabledFeatures.includes(IdxFeature.REGISTRATION)) {\n throw new AuthSdkError('Registration is not supported based on your current org configuration.');\n }\n }\n\n return run(authClient, {\n ...options,\n flow: 'register'\n });\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { run } from './run';\nimport { getFlowSpecification } from './flow';\nimport { \n OktaAuthIdxInterface, \n PasswordRecoveryOptions, \n IdxTransaction,\n} from './types';\n\nexport async function recoverPassword(\n authClient: OktaAuthIdxInterface, options: PasswordRecoveryOptions = {}\n): Promise {\n const flowSpec = getFlowSpecification(authClient, 'recoverPassword');\n return run(\n authClient, \n { \n ...options,\n ...flowSpec,\n }\n );\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { AuthSdkError, OAuthError } from '../errors';\nimport { IdxTransactionMeta } from './types/meta';\nimport { OktaAuthIdxInterface } from './types';\n\nexport async function handleInteractionCodeRedirect(\n authClient: OktaAuthIdxInterface, \n url: string\n): Promise {\n const meta = authClient.transactionManager.load() as IdxTransactionMeta;\n if (!meta) {\n throw new AuthSdkError('No transaction data was found in storage');\n }\n\n const { \n codeVerifier,\n state: savedState \n } = meta;\n const { \n searchParams\n // URL API has been added to the polyfill\n // eslint-disable-next-line compat/compat\n } = new URL(url); \n const state = searchParams.get('state');\n const interactionCode = searchParams.get('interaction_code');\n\n // Error handling\n const error = searchParams.get('error');\n if (error) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n throw new OAuthError(error, searchParams.get('error_description')!);\n }\n if (state !== savedState) {\n throw new AuthSdkError('State in redirect uri does not match with transaction state');\n }\n if (!interactionCode) {\n throw new AuthSdkError('Unable to parse interaction_code from the url');\n }\n \n // Save tokens to storage\n const { tokens } = await authClient.token.exchangeCodeForTokens({ interactionCode, codeVerifier });\n authClient.tokenManager.setTokens(tokens);\n}", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { run } from './run';\nimport { hasSavedInteractionHandle } from './transactionMeta';\nimport { startTransaction } from './startTransaction';\nimport { AuthSdkError } from '../errors';\nimport { \n OktaAuthIdxInterface, \n AccountUnlockOptions, \n IdxTransaction,\n IdxFeature,\n} from './types';\n\nexport async function unlockAccount(\n authClient: OktaAuthIdxInterface, options: AccountUnlockOptions = {}\n): Promise {\n options.flow = 'unlockAccount';\n\n // Only check at the beginning of the transaction\n if (!hasSavedInteractionHandle(authClient)) {\n const { enabledFeatures } = await startTransaction(authClient, { ...options, autoRemediate: false });\n if (enabledFeatures && !enabledFeatures.includes(IdxFeature.ACCOUNT_UNLOCK)) {\n throw new AuthSdkError(\n 'Self Service Account Unlock is not supported based on your current org configuration.'\n );\n }\n }\n\n return run(authClient, { ...options });\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { OktaAuthOAuthInterface } from '../types';\nimport { OAuthError, AuthApiError, isOAuthError } from '../../errors';\n\nexport function isInteractionRequiredError(error: Error) {\n if (error.name !== 'OAuthError') {\n return false;\n }\n const oauthError = error as OAuthError;\n return (oauthError.errorCode === 'interaction_required');\n}\n\nexport function isAuthorizationCodeError(sdk: OktaAuthOAuthInterface, error: Error) {\n if (error.name !== 'AuthApiError') {\n return false;\n }\n const authApiError = error as AuthApiError;\n // xhr property doesn't seem to match XMLHttpRequest type\n const errorResponse = authApiError.xhr as unknown as Record;\n const responseJSON = errorResponse?.responseJSON as Record;\n return sdk.options.pkce && (responseJSON?.error as string === 'invalid_grant');\n}\n\nexport function isRefreshTokenInvalidError(error: unknown): boolean {\n // error: {\"error\":\"invalid_grant\",\"error_description\":\"The refresh token is invalid or expired.\"}\n return isOAuthError(error) &&\n error.errorCode === 'invalid_grant' &&\n error.errorSummary === 'The refresh token is invalid or expired.';\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n/* global window */\n/* eslint-disable complexity, max-statements */\nimport { OktaAuthOAuthOptions, OktaAuthOAuthInterface, OAuthResponseType } from '../types';\n\nexport function hasTokensInHash(hash: string): boolean {\n return /((id|access)_token=)/i.test(hash);\n}\n\n// authorization_code\nexport function hasAuthorizationCode(hashOrSearch: string): boolean {\n return /(code=)/i.test(hashOrSearch);\n}\n\n// interaction_code\nexport function hasInteractionCode(hashOrSearch: string): boolean {\n return /(interaction_code=)/i.test(hashOrSearch);\n}\n\nexport function hasErrorInUrl(hashOrSearch: string): boolean {\n return /(error=)/i.test(hashOrSearch) || /(error_description)/i.test(hashOrSearch);\n}\n\nexport function isRedirectUri(uri: string, sdk: OktaAuthOAuthInterface): boolean {\n var authParams = sdk.options;\n if (!uri || !authParams.redirectUri) {\n return false;\n }\n return uri.indexOf(authParams.redirectUri) === 0;\n}\n\nexport function isCodeFlow(options: OktaAuthOAuthOptions) {\n return options.pkce || options.responseType === 'code' || options.responseMode === 'query';\n}\n\nexport function hasResponseType(responseType: OAuthResponseType, options: OktaAuthOAuthOptions): boolean {\n let hasResponseType = false;\n if (Array.isArray(options.responseType) && options.responseType.length) {\n hasResponseType = options.responseType.indexOf(responseType) >= 0;\n } else {\n hasResponseType = options.responseType === responseType;\n }\n return hasResponseType;\n}\n\nexport function getHashOrSearch(options: OktaAuthOAuthOptions) {\n var codeFlow = isCodeFlow(options);\n var useQuery = codeFlow && options.responseMode !== 'fragment';\n return useQuery ? window.location.search : window.location.hash;\n}\n\n/**\n * Check if tokens or a code have been passed back into the url, which happens in\n * the OIDC (including social auth IDP) redirect flow.\n */\nexport function isLoginRedirect (sdk: OktaAuthOAuthInterface) {\n // First check, is this a redirect URI?\n if (!isRedirectUri(window.location.href, sdk)){\n return false;\n }\n\n // The location contains either a code, token, or an error + error_description\n var codeFlow = isCodeFlow(sdk.options);\n var hashOrSearch = getHashOrSearch(sdk.options);\n\n if (hasErrorInUrl(hashOrSearch)) {\n return true;\n }\n\n if (codeFlow) {\n var hasCode = hasAuthorizationCode(hashOrSearch) || hasInteractionCode(hashOrSearch);\n return hasCode;\n }\n\n // implicit flow, will always be hash fragment\n return hasTokensInHash(window.location.hash);\n}\n\n/**\n * Check if error=interaction_required has been passed back in the url, which happens in\n * the social auth IDP redirect flow.\n */\nexport function isInteractionRequired (sdk: OktaAuthOAuthInterface, hashOrSearch?: string) {\n if (!hashOrSearch) { // web only\n // First check, is this a redirect URI?\n if (!isLoginRedirect(sdk)){\n return false;\n }\n \n hashOrSearch = getHashOrSearch(sdk.options);\n }\n return /(error=interaction_required)/i.test(hashOrSearch);\n}", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nexport { Remediator } from './Base/Remediator.js';\nexport { EnrollAuthenticator } from './EnrollAuthenticator.js';\nexport { EnrollPoll } from './EnrollPoll.js';\nexport { SelectEnrollmentChannel } from './SelectEnrollmentChannel.js';\nexport { EnrollmentChannelData } from './EnrollmentChannelData.js';\nexport { ChallengeAuthenticator } from './ChallengeAuthenticator.js';\nexport { ChallengePoll } from './ChallengePoll.js';\nexport { ResetAuthenticator } from './ResetAuthenticator.js';\nexport { EnrollProfile } from './EnrollProfile.js';\nexport { Identify } from './Identify.js';\nexport { ReEnrollAuthenticator } from './ReEnrollAuthenticator.js';\nexport { ReEnrollAuthenticatorWarning } from './ReEnrollAuthenticatorWarning.js';\nexport { RedirectIdp } from './RedirectIdp.js';\nexport { SelectAuthenticatorAuthenticate } from './SelectAuthenticatorAuthenticate.js';\nexport { SelectAuthenticatorEnroll } from './SelectAuthenticatorEnroll.js';\nexport { SelectAuthenticatorUnlockAccount } from './SelectAuthenticatorUnlockAccount.js';\nexport { SelectEnrollProfile } from './SelectEnrollProfile.js';\nexport { AuthenticatorVerificationData } from './AuthenticatorVerificationData.js';\nexport { AuthenticatorEnrollmentData } from './AuthenticatorEnrollmentData.js';\nexport { Skip } from './Skip.js';\nexport { GenericRemediator } from './GenericRemediator/GenericRemediator.js';\n//# sourceMappingURL=index.js.map\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\nimport { isInteractionRequired, isInteractionRequiredError } from '../../oidc';\nimport { authenticate } from '../authenticate';\nimport { cancel } from '../cancel';\nimport {\n handleEmailVerifyCallback,\n isEmailVerifyCallback,\n isEmailVerifyCallbackError,\n parseEmailVerifyCallback\n} from '../emailVerify';\nimport { handleInteractionCodeRedirect } from '../handleInteractionCodeRedirect';\nimport { makeIdxState } from '../idxState';\nimport { interact } from '../interact';\nimport { introspect } from '../introspect';\nimport { poll } from '../poll';\nimport { canProceed, proceed } from '../proceed';\nimport { recoverPassword } from '../recoverPassword';\nimport { register } from '../register';\nimport { startTransaction } from '../startTransaction';\nimport {\n clearTransactionMeta,\n createTransactionMeta,\n getSavedTransactionMeta,\n getTransactionMeta,\n isTransactionMetaValid,\n saveTransactionMeta\n} from '../transactionMeta';\nimport { FlowIdentifier, IdxAPI, OktaAuthIdxInterface } from '../types';\nimport { unlockAccount } from '../unlockAccount';\nimport * as remediators from '../remediators';\nimport { getFlowSpecification } from '../flow/FlowSpecification';\nimport { setRemediatorsCtx } from '../util';\n\n// Factory\nexport function createIdxAPI(sdk: OktaAuthIdxInterface): IdxAPI {\n setRemediatorsCtx({\n remediators,\n getFlowSpecification,\n });\n const boundStartTransaction = startTransaction.bind(null, sdk);\n const idx = {\n interact: interact.bind(null, sdk),\n introspect: introspect.bind(null, sdk),\n makeIdxResponse: makeIdxState.bind(null, sdk),\n \n authenticate: authenticate.bind(null, sdk),\n register: register.bind(null, sdk),\n start: boundStartTransaction,\n startTransaction: boundStartTransaction, // Use `start` instead. `startTransaction` will be removed in 7.0\n poll: poll.bind(null, sdk),\n proceed: proceed.bind(null, sdk),\n cancel: cancel.bind(null, sdk),\n recoverPassword: recoverPassword.bind(null, sdk),\n\n // oauth redirect callback\n handleInteractionCodeRedirect: handleInteractionCodeRedirect.bind(null, sdk),\n\n // interaction required callback\n isInteractionRequired: isInteractionRequired.bind(null, sdk),\n isInteractionRequiredError,\n\n // email verify callback\n handleEmailVerifyCallback: handleEmailVerifyCallback.bind(null, sdk),\n isEmailVerifyCallback,\n parseEmailVerifyCallback,\n isEmailVerifyCallbackError,\n \n getSavedTransactionMeta: getSavedTransactionMeta.bind(null, sdk),\n createTransactionMeta: createTransactionMeta.bind(null, sdk),\n getTransactionMeta: getTransactionMeta.bind(null, sdk),\n saveTransactionMeta: saveTransactionMeta.bind(null, sdk),\n clearTransactionMeta: clearTransactionMeta.bind(null, sdk),\n isTransactionMetaValid,\n setFlow: (flow: FlowIdentifier) => {\n sdk.options.flow = flow;\n },\n getFlow: (): FlowIdentifier | undefined => {\n return sdk.options.flow;\n },\n canProceed: canProceed.bind(null, sdk),\n unlockAccount: unlockAccount.bind(null, sdk),\n };\n return idx;\n}\n\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\n/* global atob, btoa, crypto */\nconst a = function(str) { return atob(str); };\nconst b = function (str) { return btoa(str); };\nconst c = typeof crypto === 'undefined' ? null : crypto;\n\nexport { a as atob, b as btoa, c as webcrypto };\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n/* eslint-disable node/no-unsupported-features/node-builtins */\n/* global document, window, TextEncoder, navigator */\n\nimport { webcrypto } from './crypto';\n\nconst isWindowsPhone = /windows phone|iemobile|wpdesktop/i;\t\n\nexport function isBrowser() {\n return typeof document !== 'undefined' && typeof window !== 'undefined';\n}\n\nexport function isIE11OrLess() {\n if (!isBrowser()) {\n return false;\n }\n const documentMode = (document as any).documentMode;\n return !!documentMode && documentMode <= 11;\n}\n\nexport function getUserAgent() {\n return navigator.userAgent;\n}\n\nexport function isFingerprintSupported() {\n const agent = getUserAgent();\n return agent && !isWindowsPhone.test(agent);\t\n}\n\nexport function isPopupPostMessageSupported() {\n if (!isBrowser()) {\n return false;\n }\n const documentMode = (document as any).documentMode;\n var isIE8or9 = documentMode && documentMode < 10;\n if (typeof window.postMessage !== 'undefined' && !isIE8or9) {\n return true;\n }\n return false;\n}\n\nfunction isWebCryptoSubtleSupported () {\n return typeof webcrypto !== 'undefined'\n && webcrypto !== null\n && typeof webcrypto.subtle !== 'undefined'\n && typeof Uint8Array !== 'undefined';\n}\n\nexport function isTokenVerifySupported() {\n return isWebCryptoSubtleSupported();\n}\n\nexport function hasTextEncoder() {\n return typeof TextEncoder !== 'undefined';\n}\n\nexport function isPKCESupported() {\n return isTokenVerifySupported() && hasTextEncoder();\n}\n\nexport function isHTTPS() {\n if (!isBrowser()) {\n return false;\n }\n return window.location.protocol === 'https:';\n}\n\nexport function isLocalhost() {\n // eslint-disable-next-line compat/compat\n return isBrowser() && window.location.hostname === 'localhost';\n}\n\n// For now, DPoP is only supported on browsers\nexport function isDPoPSupported () {\n return !isIE11OrLess() &&\n typeof window.indexedDB !== 'undefined' &&\n hasTextEncoder() &&\n isWebCryptoSubtleSupported();\n}\n", "\n\n// Do not use this type in code, so it won't be emitted in the declaration output\nimport { removeNils } from '../util';\n\nimport * as features from '../features';\nimport * as constants from '../constants';\n\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore \n// Do not use this type in code, so it won't be emitted in the declaration output\nimport Emitter from 'tiny-emitter';\n\nimport {\n EventEmitter,\n OktaAuthConstructor,\n OktaAuthBaseInterface,\n OktaAuthBaseOptions,\n OktaAuthOptionsConstructor, \n FeaturesAPI,\n} from './types';\n\nexport function createOktaAuthBase\n<\n O extends OktaAuthBaseOptions = OktaAuthBaseOptions,\n>\n(\n OptionsConstructor: OktaAuthOptionsConstructor\n): OktaAuthConstructor>\n{\n class OktaAuthBase implements OktaAuthBaseInterface\n {\n options: O;\n emitter: EventEmitter;\n features: FeaturesAPI;\n static features: FeaturesAPI = features;\n static constants = constants;\n \n constructor(...args: any[]) {\n const options = new OptionsConstructor(args.length ? args[0] || {} : {});\n this.options = removeNils(options) as O; // clear out undefined values\n this.emitter = new Emitter();\n this.features = features;\n }\n }\n\n // Hoist feature detection functions to prototype & static type\n OktaAuthBase.features = OktaAuthBase.prototype.features = features;\n\n // Also hoist constants for CommonJS users\n Object.assign(OktaAuthBase, {\n constants\n });\n\n return OktaAuthBase;\n}\n", "import { OktaAuthBaseInterface, OktaAuthConstructor } from '../base/types';\nimport {\n OktaAuthStorageInterface,\n OktaAuthStorageOptions,\n StorageManagerConstructor,\n StorageManagerInterface,\n} from './types';\n\nexport function mixinStorage\n<\n S extends StorageManagerInterface = StorageManagerInterface,\n O extends OktaAuthStorageOptions = OktaAuthStorageOptions,\n TBase extends OktaAuthConstructor> = OktaAuthConstructor>\n>\n(\n Base: TBase, StorageManager: StorageManagerConstructor\n): TBase & OktaAuthConstructor>\n{\n return class OktaAuthStorage extends Base implements OktaAuthStorageInterface\n {\n storageManager: S;\n constructor(...args: any[]) {\n super(...args);\n const { storageManager, cookies, storageUtil } = this.options;\n this.storageManager = new StorageManager(storageManager!, cookies!, storageUtil!);\n }\n clearStorage(): void {\n // override in subclass\n }\n };\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\n/* global SDK_VERSION */\n\nimport { isBrowser } from '../features';\nexport class OktaUserAgent {\n environments: string[];\n\n constructor() {\n // add base sdk env\n this.environments = [`okta-auth-js/${SDK_VERSION}`];\n this.maybeAddNodeEnvironment();\n }\n\n addEnvironment(env: string) {\n this.environments.push(env);\n }\n\n getHttpHeader() {\n return { 'X-Okta-User-Agent-Extended': this.environments.join(' ') };\n }\n\n getVersion() {\n return SDK_VERSION;\n }\n\n maybeAddNodeEnvironment() {\n if (isBrowser() || !process || !process.versions) {\n return;\n }\n const { node: version } = process.versions;\n this.environments.push(`nodejs/${version}`);\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { OktaAuthHttpInterface } from './types';\n\nexport function setRequestHeader(authClient: OktaAuthHttpInterface, headerName, headerValue) {\n authClient.options.headers = authClient.options.headers || {};\n authClient.options.headers[headerName] = headerValue;\n}", "import { OktaAuthStorageInterface, StorageManagerInterface } from '../storage/types';\nimport { OktaAuthConstructor } from '../base/types';\nimport {\n HttpAPI,\n OktaAuthHttpInterface,\n OktaAuthHttpOptions,\n} from './types';\nimport { OktaUserAgent } from './OktaUserAgent';\nimport { setRequestHeader } from './headers';\nimport { toQueryString } from '../util';\nimport { get } from './request';\n\nexport function mixinHttp\n<\n S extends StorageManagerInterface = StorageManagerInterface,\n O extends OktaAuthHttpOptions = OktaAuthHttpOptions,\n TBase extends OktaAuthConstructor>\n = OktaAuthConstructor>\n>\n(Base: TBase): TBase & OktaAuthConstructor>\n{\n return class OktaAuthHttp extends Base implements OktaAuthHttpInterface\n {\n _oktaUserAgent: OktaUserAgent;\n http: HttpAPI;\n \n constructor(...args: any[]) {\n super(...args);\n\n this._oktaUserAgent = new OktaUserAgent();\n\n // HTTP\n this.http = {\n setRequestHeader: setRequestHeader.bind(null, this)\n };\n }\n\n setHeaders(headers) {\n this.options.headers = Object.assign({}, this.options.headers, headers);\n }\n \n getIssuerOrigin(): string {\n // Infer the URL from the issuer URL, omitting the /oauth2/{authServerId}\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this.options.issuer!.split('/oauth2/')[0];\n }\n \n webfinger(opts): Promise {\n var url = '/.well-known/webfinger' + toQueryString(opts);\n var options = {\n headers: {\n 'Accept': 'application/jrd+json'\n }\n };\n return get(this, url, options);\n }\n };\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nexport { base64ToBase64Url, base64UrlDecode, base64UrlToBase64, base64UrlToBuffer, base64UrlToString, bufferToBase64Url, stringToBase64Url, stringToBuffer } from './base64.js';\nexport { getOidcHash } from './oidcHash.js';\nexport { verifyToken } from './verifyToken.js';\nexport { atob, btoa, webcrypto } from './browser.js';\n//# sourceMappingURL=index.js.map\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { AuthSdkError } from '../errors';\nimport { atob, btoa } from './webcrypto';\n\n// converts a string to base64 (url/filename safe variant)\nexport function stringToBase64Url(str) {\n var b64 = btoa(str);\n return base64ToBase64Url(b64);\n}\n\n// converts a standard base64-encoded string to a \"url/filename safe\" variant\nexport function base64ToBase64Url(b64) {\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n// converts a \"url/filename safe\" base64 string to a \"standard\" base64 string\nexport function base64UrlToBase64(b64u) {\n return b64u.replace(/-/g, '+').replace(/_/g, '/');\n}\n\nexport function base64UrlToString(b64u) {\n var b64 = base64UrlToBase64(b64u);\n switch (b64.length % 4) {\n case 0:\n break;\n case 2:\n b64 += '==';\n break;\n case 3:\n b64 += '=';\n break;\n default:\n throw new AuthSdkError('Not a valid Base64Url');\n }\n var utf8 = atob(b64);\n try {\n return decodeURIComponent(escape(utf8));\n } catch (e) {\n return utf8;\n }\n}\n\nexport function stringToBuffer(str) {\n var buffer = new Uint8Array(str.length);\n for (var i = 0; i < str.length; i++) {\n buffer[i] = str.charCodeAt(i);\n }\n return buffer;\n}\n\nexport function base64UrlDecode(str) {\n return atob(base64UrlToBase64(str));\n}\n\n// Converts base64 string to binary data view\nexport function base64UrlToBuffer(b64u) {\n return Uint8Array.from(base64UrlDecode(b64u), (c: string) => c.charCodeAt(0));\n}\n\n// Converts an ArrayBuffer object that contains binary data to base64 encoded string\nexport function bufferToBase64Url(bin) {\n return btoa(new Uint8Array(bin).reduce((s, byte) => s + String.fromCharCode(byte), ''));\n}\n\n\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n/* global TextEncoder */\nimport { stringToBase64Url } from './base64';\nimport { webcrypto } from './webcrypto';\n\nexport function getOidcHash(str) { \n var buffer = new TextEncoder().encode(str);\n return webcrypto.subtle.digest('SHA-256', buffer).then(function(arrayBuffer) {\n var intBuffer = new Uint8Array(arrayBuffer);\n var firstHalf = intBuffer.slice(0, 16);\n var hash = String.fromCharCode.apply(null, firstHalf as unknown as number[]);\n var b64u = stringToBase64Url(hash); // url-safe base64 variant\n return b64u;\n });\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { clone } from '../util';\nimport { stringToBuffer, base64UrlDecode } from './base64';\nimport { webcrypto } from './webcrypto';\n\nexport function verifyToken(idToken, key) {\n key = clone(key);\n\n var format = 'jwk';\n var algo = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n };\n var extractable = true;\n var usages = ['verify'];\n\n // https://connect.microsoft.com/IE/feedback/details/2242108/webcryptoapi-importing-jwk-with-use-field-fails\n // This is a metadata tag that specifies the intent of how the key should be used.\n // It's not necessary to properly verify the jwt's signature.\n delete key.use;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return webcrypto.subtle.importKey(\n format,\n key,\n algo,\n extractable,\n usages\n )\n .then(function(cryptoKey) {\n var jwt = idToken.split('.');\n var payload = stringToBuffer(jwt[0] + '.' + jwt[1]);\n var b64Signature = base64UrlDecode(jwt[2]);\n var signature = stringToBuffer(b64Signature);\n\n return webcrypto.subtle.verify(\n algo,\n cryptoKey,\n signature,\n payload\n );\n });\n}\n\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n// Implements a queue for synchronous or asynchronous methods\n// Methods will be wrapped in a promise and execute sequentially\n// This can be used to prevent concurrent calls to a single method or a set of methods\n\nimport { isPromise } from './types';\nimport { warn } from './console';\n\ninterface QueueItem {\n method: () => void;\n thisObject: object;\n args: any[];\n resolve: (value?: unknown) => void;\n reject: (reason?: unknown) => void;\n}\n\ninterface PromiseQueueOptions {\n quiet?: boolean; // if false, concurrrency warnings will not be logged\n}\nexport class PromiseQueue {\n queue: QueueItem[];\n running: boolean;\n options: PromiseQueueOptions;\n\n constructor(options: PromiseQueueOptions = { quiet: false }) {\n this.queue = [];\n this.running = false;\n this.options = options;\n }\n\n // Returns a promise\n // If the method is synchronous, it will resolve when the method completes\n // If the method returns a promise, it will resolve (or reject) with the value from the method's promise\n push(method: (...args: any) => any, thisObject: any, ...args: any[]) {\n return new Promise((resolve, reject) => {\n if (this.queue.length > 0) {\n // There is at least one other pending call.\n // The PromiseQueue will prevent these methods from running concurrently.\n if (this.options.quiet !== false) {\n warn(\n 'Async method is being called but another async method is already running. ' +\n 'The new method will be delayed until the previous method completes.'\n );\n }\n }\n this.queue.push({\n method,\n thisObject,\n args,\n resolve,\n reject\n });\n this.run();\n });\n }\n\n run() {\n if (this.running) {\n return;\n }\n if (this.queue.length === 0) {\n return;\n }\n this.running = true;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n var queueItem = this.queue.shift()!;\n var res = queueItem.method.apply(queueItem.thisObject, queueItem.args as never) as unknown;\n if (isPromise(res)) {\n (res as Promise).then(queueItem.resolve, queueItem.reject).finally(() => {\n this.running = false;\n this.run();\n });\n } else {\n queueItem.resolve(res);\n this.running = false;\n this.run();\n }\n }\n}\n", "/*!\n * Copyright (c) 2019-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\n /* eslint-disable complexity, max-statements */\nimport { stringToBase64Url, webcrypto } from '../../crypto';\nimport { MIN_VERIFIER_LENGTH, MAX_VERIFIER_LENGTH, DEFAULT_CODE_CHALLENGE_METHOD } from '../../constants';\n\nfunction dec2hex (dec) {\n return ('0' + dec.toString(16)).substr(-2);\n}\n\nfunction getRandomString(length) {\n var a = new Uint8Array(Math.ceil(length / 2));\n webcrypto.getRandomValues(a);\n var str = Array.from(a, dec2hex).join('');\n return str.slice(0, length);\n}\n\nfunction generateVerifier(prefix?: string): string {\n var verifier = prefix || '';\n if (verifier.length < MIN_VERIFIER_LENGTH) {\n verifier = verifier + getRandomString(MIN_VERIFIER_LENGTH - verifier.length);\n }\n return encodeURIComponent(verifier).slice(0, MAX_VERIFIER_LENGTH);\n}\n\nfunction computeChallenge(str: string): PromiseLike { \n var buffer = new TextEncoder().encode(str);\n return webcrypto.subtle.digest('SHA-256', buffer).then(function(arrayBuffer) {\n var hash = String.fromCharCode.apply(null, new Uint8Array(arrayBuffer) as unknown as number[]);\n var b64u = stringToBase64Url(hash); // url-safe base64 variant\n return b64u;\n });\n}\n\nexport default {\n DEFAULT_CODE_CHALLENGE_METHOD,\n generateVerifier,\n computeChallenge\n};\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { AuthSdkError } from '../errors';\nimport { JWTObject } from './types';\nimport { base64UrlToString } from '../crypto';\n\nexport function decodeToken(token: string): JWTObject {\n var jwt = token.split('.');\n var decodedToken: JWTObject;\n\n try {\n decodedToken = {\n header: JSON.parse(base64UrlToString(jwt[0])),\n payload: JSON.parse(base64UrlToString(jwt[1])),\n signature: jwt[2]\n };\n } catch (e) {\n throw new AuthSdkError('Malformed token');\n }\n\n return decodedToken;\n}\n", "\n/* global window */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { generateNonce, generateState } from './oauth';\nimport { OktaAuthOAuthInterface, TokenParams } from '../types';\nimport { isBrowser } from '../../features';\nimport { removeNils } from '../../util';\n\nexport function getDefaultTokenParams(sdk: OktaAuthOAuthInterface): TokenParams {\n const {\n pkce,\n clientId,\n redirectUri,\n responseType,\n responseMode,\n scopes,\n acrValues,\n maxAge,\n state,\n ignoreSignature,\n dpop\n } = sdk.options;\n const defaultRedirectUri = isBrowser() ? window.location.href : undefined;\n return removeNils({\n pkce,\n clientId,\n redirectUri: redirectUri || defaultRedirectUri,\n responseType: responseType || ['token', 'id_token'],\n responseMode,\n state: state || generateState(),\n nonce: generateNonce(),\n scopes: scopes || ['openid', 'email'],\n acrValues,\n maxAge,\n ignoreSignature,\n dpop,\n });\n}", "// References:\n// https://www.w3.org/TR/WebCryptoAPI/#concepts-key-storage\n// https://datatracker.ietf.org/doc/html/rfc9449\n\nimport {\n webcrypto,\n stringToBase64Url,\n stringToBuffer,\n bufferToBase64Url,\n base64ToBase64Url,\n btoa\n} from '../crypto';\nimport { AuthSdkError, OAuthError, WWWAuthError, isOAuthError, isWWWAuthError } from '../errors';\nimport { Tokens } from './types';\n\nexport interface DPoPClaims {\n htm: string;\n htu: string;\n iat: number;\n jti: string;\n nonce?: string;\n ath?: string;\n}\n\nexport interface DPoPProofParams {\n keyPair: CryptoKeyPair;\n url: string;\n method: string;\n nonce?: string;\n accessToken?: string;\n}\n\nexport type ResourceDPoPProofParams = Omit;\ntype DPoPProofTokenRequestParams = Omit;\n\nconst INDEXEDDB_NAME = 'OktaAuthJs';\nconst DB_KEY = 'DPoPKeys';\n\nexport function isDPoPNonceError(obj: any): obj is OAuthError | WWWAuthError {\n return (\n (isOAuthError(obj) || isWWWAuthError(obj)) &&\n obj.errorCode === 'use_dpop_nonce'\n );\n}\n\n/////////// crypto ///////////\n\nexport async function createJwt(header: object, claims: object, signingKey: CryptoKey): Promise {\n const head = stringToBase64Url(JSON.stringify(header));\n const body = stringToBase64Url(JSON.stringify(claims));\n const signature = await webcrypto.subtle.sign(\n { name: signingKey.algorithm.name }, signingKey, stringToBuffer(`${head}.${body}`)\n );\n return `${head}.${body}.${base64ToBase64Url(bufferToBase64Url(signature))}`;\n}\n\nexport function cryptoRandomValue (byteLen = 32) {\n return [...webcrypto.getRandomValues(new Uint8Array(byteLen))].map(v => v.toString(16)).join('');\n}\n\nexport async function generateKeyPair (): Promise {\n const algorithm = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: 'SHA-256',\n modulusLength: 2048,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n };\n\n // The \"false\" here makes it non-exportable\n // https://caniuse.com/mdn-api_subtlecrypto_generatekey\n return webcrypto.subtle.generateKey(algorithm, false, ['sign', 'verify']);\n}\n\nasync function hashAccessToken (accessToken: string): Promise {\n const buffer = new TextEncoder().encode(accessToken);\n const hash = await webcrypto.subtle.digest('SHA-256', buffer);\n\n return btoa(String.fromCharCode.apply(null, new Uint8Array(hash) as unknown as number[]))\n .replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/////////// indexeddb / keystore ///////////\n\n\n// https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore#instance_methods\n// add additional methods as needed\nexport type StoreMethod = 'get' | 'add' | 'delete' | 'clear';\n\n// convenience abstraction for exposing IDBObjectStore instance\nfunction keyStore (): Promise {\n return new Promise((resolve, reject) => {\n try {\n const indexedDB = window.indexedDB;\n const req = indexedDB.open(INDEXEDDB_NAME, 1);\n\n req.onerror = function () {\n reject(req.error!);\n };\n\n req.onupgradeneeded = function () {\n const db = req.result;\n db.createObjectStore(DB_KEY);\n };\n\n req.onsuccess = function () {\n const db = req.result;\n const tx = db.transaction(DB_KEY, 'readwrite');\n\n tx.onerror = function () {\n reject(tx.error!);\n };\n\n const store = tx.objectStore(DB_KEY);\n\n resolve(store);\n\n tx.oncomplete = function () {\n db.close();\n };\n };\n }\n catch (err) {\n reject(err);\n }\n });\n}\n\n// convenience abstraction for wrapping IDBObjectStore methods in promises\nasync function invokeStoreMethod (method: StoreMethod, ...args: any[]): Promise {\n const store = await keyStore();\n return new Promise((resolve, reject) => {\n // https://github.com/microsoft/TypeScript/issues/49700\n // https://github.com/microsoft/TypeScript/issues/49802\n // @ts-expect-error ts(2556)\n const req = store[method](...args);\n req.onsuccess = function () {\n resolve(req);\n };\n req.onerror = function () {\n reject(req.error);\n };\n });\n}\n\nasync function storeKeyPair (pairId: string, keyPair: CryptoKeyPair) {\n await invokeStoreMethod('add', keyPair, pairId);\n return keyPair;\n}\n\n// attempts to find keyPair stored at given key, otherwise throws\nexport async function findKeyPair (pairId?: string): Promise {\n if (pairId) {\n const req = await invokeStoreMethod('get', pairId);\n if (req.result) {\n return req.result;\n }\n }\n\n // defaults to throwing unless keyPair is found\n throw new AuthSdkError(`Unable to locate dpop key pair required for refresh${pairId ? ` (${pairId})` : ''}`);\n}\n\nexport async function clearDPoPKeyPair (pairId: string): Promise {\n await invokeStoreMethod('delete', pairId);\n}\n\nexport async function clearAllDPoPKeyPairs (): Promise {\n await invokeStoreMethod('clear');\n}\n\n// generates a crypto (non-extractable) private key pair and writes it to indexeddb, returns key (id)\nexport async function createDPoPKeyPair (): Promise<{keyPair: CryptoKeyPair, keyPairId: string}> {\n const keyPairId = cryptoRandomValue(4);\n const keyPair = await generateKeyPair();\n await storeKeyPair(keyPairId, keyPair);\n return { keyPair, keyPairId };\n}\n\n// will clear PK from storage if certain token conditions are met\n/* eslint max-len: [2, 132], complexity: [2, 12] */\nexport async function clearDPoPKeyPairAfterRevoke (revokedToken: 'access' | 'refresh', tokens: Tokens): Promise {\n let shouldClear = false;\n\n const { accessToken, refreshToken } = tokens;\n\n // revoking access token and refresh token doesn't exist\n if (revokedToken === 'access' && accessToken && accessToken.tokenType === 'DPoP' && !refreshToken) {\n shouldClear = true;\n }\n\n // revoking refresh token and access token doesn't exist\n if (revokedToken === 'refresh' && refreshToken && !accessToken) {\n shouldClear = true;\n }\n\n const pairId = accessToken?.dpopPairId ?? refreshToken?.dpopPairId;\n if (shouldClear && pairId) {\n await clearDPoPKeyPair(pairId);\n }\n}\n\n/////////// proof generation methods ///////////\n\nexport async function generateDPoPProof ({ keyPair, url, method, nonce, accessToken }: DPoPProofParams): Promise {\n const { kty, crv, e, n, x, y } = await webcrypto.subtle.exportKey('jwk', keyPair.publicKey);\n const header = {\n alg: 'RS256',\n typ: 'dpop+jwt',\n jwk: { kty, crv, e, n, x, y }\n };\n\n const claims: DPoPClaims = {\n htm: method,\n htu: url,\n iat: Math.floor(Date.now() / 1000),\n jti: cryptoRandomValue(),\n };\n\n if (nonce) {\n claims.nonce = nonce;\n }\n\n // encode access token\n if (accessToken) {\n claims.ath = await hashAccessToken(accessToken);\n }\n\n return createJwt(header, claims, keyPair.privateKey);\n}\n\n/* eslint max-len: [2, 132] */\nexport async function generateDPoPForTokenRequest ({ keyPair, url, method, nonce }: DPoPProofTokenRequestParams): Promise {\n const params: DPoPProofParams = { keyPair, url, method };\n if (nonce) {\n params.nonce = nonce;\n }\n\n return generateDPoPProof(params);\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { AuthSdkError, AuthApiError } from '../../errors';\nimport { CustomUrls, OAuthParams, OAuthResponse, RefreshToken, TokenParams } from '../types';\nimport { removeNils, toQueryString } from '../../util';\nimport { httpRequest, OktaAuthHttpInterface } from '../../http';\nimport { generateDPoPForTokenRequest, isDPoPNonceError } from '../dpop';\n\nexport interface TokenEndpointParams extends TokenParams {\n dpopKeyPair?: CryptoKeyPair;\n}\n\ninterface TokenRequestParams {\n url: string;\n data: any;\n dpopKeyPair?: CryptoKeyPair;\n nonce?: string;\n}\n\nfunction validateOptions(options: TokenEndpointParams) {\n // Quick validation\n if (!options.clientId) {\n throw new AuthSdkError('A clientId must be specified in the OktaAuth constructor to get a token');\n }\n\n if (!options.redirectUri) {\n throw new AuthSdkError('The redirectUri passed to /authorize must also be passed to /token');\n }\n\n if (!options.authorizationCode && !options.interactionCode) {\n throw new AuthSdkError('An authorization code (returned from /authorize) must be passed to /token');\n }\n\n if (!options.codeVerifier) {\n throw new AuthSdkError('The \"codeVerifier\" (generated and saved by your app) must be passed to /token');\n }\n}\n\nfunction getPostData(sdk, options: TokenParams): string {\n // Convert Token params to OAuth params, sent to the /token endpoint\n var params: OAuthParams = removeNils({\n 'client_id': options.clientId,\n 'redirect_uri': options.redirectUri,\n 'grant_type': options.interactionCode ? 'interaction_code' : 'authorization_code',\n 'code_verifier': options.codeVerifier\n });\n\n if (options.interactionCode) {\n params['interaction_code'] = options.interactionCode;\n } else if (options.authorizationCode) {\n params.code = options.authorizationCode;\n }\n\n const { clientSecret } = sdk.options;\n if (clientSecret) {\n params['client_secret'] = clientSecret;\n }\n\n // Encode as URL string\n return toQueryString(params).slice(1);\n}\n\n/* eslint complexity: [2, 10] */\nasync function makeTokenRequest (sdk, { url, data, nonce, dpopKeyPair }: TokenRequestParams): Promise {\n const method = 'POST';\n const headers: any = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (sdk.options.dpop) {\n if (!dpopKeyPair) {\n throw new AuthSdkError('DPoP is configured but no key pair was provided');\n }\n\n const proof = await generateDPoPForTokenRequest({ url, method, nonce, keyPair: dpopKeyPair });\n headers.DPoP = proof;\n }\n\n try {\n const resp = await httpRequest(sdk, {\n url,\n method,\n args: data,\n headers\n });\n return resp;\n }\n catch (err) {\n if (isDPoPNonceError(err) && !nonce) {\n const dpopNonce = err.resp?.headers['dpop-nonce'];\n if (!dpopNonce) {\n // throws error is dpop-nonce header cannot be found, prevents infinite loop\n throw new AuthApiError(\n {errorSummary: 'No `dpop-nonce` header found when required'},\n err.resp ?? undefined // yay ts\n );\n }\n return makeTokenRequest(sdk, { url, data, dpopKeyPair, nonce: dpopNonce });\n }\n throw err;\n }\n}\n\n// exchange authorization code for an access token\nexport async function postToTokenEndpoint(sdk, options: TokenEndpointParams, urls: CustomUrls): Promise {\n validateOptions(options);\n var data = getPostData(sdk, options);\n\n const params: TokenRequestParams = {\n url: urls.tokenUrl!,\n data,\n dpopKeyPair: options?.dpopKeyPair\n };\n\n return makeTokenRequest(sdk, params);\n}\n\nexport async function postRefreshToken(\n sdk: OktaAuthHttpInterface,\n options: TokenEndpointParams,\n refreshToken: RefreshToken\n): Promise {\n const data = Object.entries({\n client_id: options.clientId, // eslint-disable-line camelcase\n grant_type: 'refresh_token', // eslint-disable-line camelcase\n scope: refreshToken.scopes.join(' '),\n refresh_token: refreshToken.refreshToken, // eslint-disable-line camelcase\n }).map(function ([name, value]) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return name + '=' + encodeURIComponent(value!);\n }).join('&');\n\n let url = refreshToken.tokenUrl;\n if (options.extraParams && Object.keys(options.extraParams).length >= 1) {\n url += toQueryString(options.extraParams);\n }\n\n const params: TokenRequestParams = {\n url,\n data,\n dpopKeyPair: options?.dpopKeyPair\n };\n\n return makeTokenRequest(sdk, params);\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { get } from '../../http';\nimport { find } from '../../util';\nimport { OktaAuthOAuthInterface, WellKnownResponse } from '../types';\nimport AuthSdkError from '../../errors/AuthSdkError';\n\nexport function getWellKnown(sdk: OktaAuthOAuthInterface, issuer?: string): Promise {\n var authServerUri = (issuer || sdk.options.issuer);\n return get(sdk, authServerUri + '/.well-known/openid-configuration', {\n cacheResponse: true\n });\n}\n\nexport function getKey(sdk: OktaAuthOAuthInterface, issuer: string, kid: string): Promise {\n var httpCache = sdk.storageManager.getHttpCache(sdk.options.cookies);\n\n return getWellKnown(sdk, issuer)\n .then(function(wellKnown) {\n var jwksUri = wellKnown['jwks_uri'];\n\n // Check our kid against the cached version (if it exists and isn't expired)\n var cacheContents = httpCache.getStorage();\n var cachedResponse = cacheContents[jwksUri];\n if (cachedResponse && Date.now()/1000 < cachedResponse.expiresAt) {\n var cachedKey = find(cachedResponse.response.keys, {\n kid: kid\n });\n\n if (cachedKey) {\n return cachedKey;\n }\n }\n\n // Remove cache for the key\n httpCache.clearStorage(jwksUri);\n\n // Pull the latest keys if the key wasn't in the cache\n return get(sdk, jwksUri, {\n cacheResponse: true\n })\n .then(function(res) {\n var key = find(res.keys, {\n kid: kid\n });\n\n if (key) {\n return key;\n }\n\n throw new AuthSdkError('The key id, ' + kid + ', was not found in the server\\'s keys');\n });\n });\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n/* eslint-disable complexity, max-statements */\n\nimport AuthSdkError from '../../errors/AuthSdkError';\nimport { OktaAuthOAuthInterface, TokenVerifyParams, UserClaims } from '../../oidc/types';\n\nexport function validateClaims(sdk: OktaAuthOAuthInterface, claims: UserClaims, validationParams: TokenVerifyParams) {\n const aud = validationParams.clientId;\n const iss = validationParams.issuer;\n const nonce = validationParams.nonce;\n const acr = validationParams.acrValues;\n\n if (!claims || !iss || !aud) {\n throw new AuthSdkError('The jwt, iss, and aud arguments are all required');\n }\n\n if (nonce && claims.nonce !== nonce) {\n throw new AuthSdkError('OAuth flow response nonce doesn\\'t match request nonce');\n }\n\n const now = Math.floor(Date.now()/1000);\n\n if (claims.iss !== iss) {\n throw new AuthSdkError('The issuer [' + claims.iss + '] ' +\n 'does not match [' + iss + ']');\n }\n\n if ((Array.isArray(claims.aud) && claims.aud.indexOf(aud) < 0) ||\n (!Array.isArray(claims.aud) && claims.aud !== aud))\n {\n throw new AuthSdkError('The audience [' + claims.aud + '] ' +\n 'does not match [' + aud + ']');\n }\n\n if (acr && claims.acr !== acr) {\n throw new AuthSdkError('The acr [' + claims.acr + '] ' +\n 'does not match acr_values [' + acr + ']');\n }\n\n if (claims.iat! > claims.exp!) {\n throw new AuthSdkError('The JWT expired before it was issued');\n }\n\n if (!sdk.options.ignoreLifetime) {\n if ((now - sdk.options.maxClockSkew!) > claims.exp!) {\n throw new AuthSdkError('The JWT expired and is no longer valid');\n }\n\n if (claims.iat! > (now + sdk.options.maxClockSkew!)) {\n throw new AuthSdkError('The JWT was issued in the future');\n }\n }\n}\n", "/* eslint-disable max-len */\n/* eslint-disable complexity */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { getWellKnown, getKey } from './endpoints/well-known';\nimport { validateClaims } from './util';\nimport { AuthSdkError } from '../errors';\nimport { IDToken, OktaAuthOAuthInterface, TokenVerifyParams } from '../oidc/types';\nimport { decodeToken } from './decodeToken';\nimport * as sdkCrypto from '../crypto';\n\n// Verify the id token\nexport async function verifyToken(sdk: OktaAuthOAuthInterface, token: IDToken, validationParams: TokenVerifyParams): Promise {\n if (!token || !token.idToken) {\n throw new AuthSdkError('Only idTokens may be verified');\n }\n\n // Decode the Jwt object (may throw)\n const jwt = decodeToken(token.idToken);\n\n // The configured issuer may point to a frontend proxy.\n // Get the \"real\" issuer from .well-known/openid-configuration\n const configuredIssuer = validationParams?.issuer || sdk.options.issuer;\n const { issuer } = await getWellKnown(sdk, configuredIssuer);\n\n const validationOptions: TokenVerifyParams = Object.assign({\n // base options, can be overridden by params\n clientId: sdk.options.clientId,\n ignoreSignature: sdk.options.ignoreSignature\n }, validationParams, {\n // final options, cannot be overridden\n issuer\n });\n\n // Standard claim validation (may throw)\n validateClaims(sdk, jwt.payload, validationOptions);\n\n // If the browser doesn't support native crypto or we choose not\n // to verify the signature, bail early\n if (validationOptions.ignoreSignature == true || !sdk.features.isTokenVerifySupported()) {\n return token;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const key = await getKey(sdk, token.issuer, jwt.header.kid!);\n const valid = await sdkCrypto.verifyToken(token.idToken, key);\n if (!valid) {\n throw new AuthSdkError('The token signature is not valid');\n }\n if (validationParams && validationParams.accessToken && token.claims.at_hash) {\n const hash = await sdkCrypto.getOidcHash(validationParams.accessToken);\n if (hash !== token.claims.at_hash) {\n throw new AuthSdkError('Token hash verification failed');\n }\n }\n return token;\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n\n/* eslint-disable complexity, max-statements */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { clone } from '../util';\nimport {\n getOAuthUrls,\n} from './util/oauth';\nimport { AuthSdkError, OAuthError } from '../errors';\nimport {\n OktaAuthOAuthInterface,\n TokenVerifyParams,\n IDToken,\n OAuthResponse,\n TokenParams,\n TokenResponse,\n CustomUrls,\n Tokens,\n} from './types';\nimport { verifyToken } from './verifyToken';\nimport { getDefaultTokenParams } from './util';\n\nfunction validateResponse(res: OAuthResponse, oauthParams: TokenParams) {\n if (res['error'] && res['error_description']) {\n throw new OAuthError(res['error'], res['error_description']);\n }\n\n if (res.state !== oauthParams.state) {\n throw new AuthSdkError('OAuth flow response state doesn\\'t match request state');\n }\n\n // https://datatracker.ietf.org/doc/html/rfc9449#token-response\n // \"A token_type of DPoP MUST be included in the access token response to signal to the client\"\n if (oauthParams.dpop && res.token_type !== 'DPoP') {\n throw new AuthSdkError('Unable to parse OAuth flow response: DPoP was configured but \"token_type\" was not DPoP');\n }\n}\n\nexport async function handleOAuthResponse(\n sdk: OktaAuthOAuthInterface,\n tokenParams: TokenParams,\n res: OAuthResponse,\n urls?: CustomUrls\n): Promise {\n const pkce = sdk.options.pkce !== false;\n\n\n // The result contains an authorization_code and PKCE is enabled \n // `exchangeCodeForTokens` will call /token then call `handleOauthResponse` recursively with the result\n if (pkce && (res.code || res.interaction_code)) {\n return sdk.token.exchangeCodeForTokens(Object.assign({}, tokenParams, {\n authorizationCode: res.code,\n interactionCode: res.interaction_code\n }), urls);\n }\n\n tokenParams = tokenParams || getDefaultTokenParams(sdk);\n urls = urls || getOAuthUrls(sdk, tokenParams);\n\n let responseType = tokenParams.responseType || [];\n if (!Array.isArray(responseType) && responseType !== 'none') {\n responseType = [responseType];\n }\n\n let scopes;\n if (res.scope) {\n scopes = res.scope.split(' ');\n } else {\n scopes = clone(tokenParams.scopes);\n }\n const clientId = tokenParams.clientId || sdk.options.clientId;\n\n // Handling the result from implicit flow or PKCE token exchange\n validateResponse(res, tokenParams);\n\n const tokenDict = {} as Tokens;\n const expiresIn = res.expires_in;\n const tokenType = res.token_type;\n const accessToken = res.access_token;\n const idToken = res.id_token;\n const refreshToken = res.refresh_token;\n const now = Math.floor(Date.now()/1000);\n\n if (accessToken) {\n const accessJwt = sdk.token.decode(accessToken);\n tokenDict.accessToken = {\n accessToken: accessToken,\n claims: accessJwt.payload,\n expiresAt: Number(expiresIn) + now,\n tokenType: tokenType!,\n scopes: scopes,\n authorizeUrl: urls.authorizeUrl!,\n userinfoUrl: urls.userinfoUrl!\n };\n\n if (tokenParams.dpopPairId) {\n tokenDict.accessToken.dpopPairId = tokenParams.dpopPairId;\n }\n\n if (tokenParams.extraParams) {\n tokenDict.accessToken.extraParams = tokenParams.extraParams;\n }\n }\n\n if (refreshToken) {\n tokenDict.refreshToken = {\n refreshToken: refreshToken,\n // should not be used, this is the accessToken expire time\n // TODO: remove \"expiresAt\" in the next major version OKTA-407224\n expiresAt: Number(expiresIn) + now, \n scopes: scopes,\n tokenUrl: urls.tokenUrl!,\n authorizeUrl: urls.authorizeUrl!,\n issuer: urls.issuer!,\n };\n\n if (tokenParams.dpopPairId) {\n tokenDict.refreshToken.dpopPairId = tokenParams.dpopPairId;\n }\n\n if (tokenParams.extraParams) {\n tokenDict.refreshToken.extraParams = tokenParams.extraParams;\n }\n }\n\n if (idToken) {\n const idJwt = sdk.token.decode(idToken);\n const idTokenObj: IDToken = {\n idToken: idToken,\n claims: idJwt.payload,\n expiresAt: idJwt.payload.exp! - idJwt.payload.iat! + now, // adjusting expiresAt to be in local time\n scopes: scopes,\n authorizeUrl: urls.authorizeUrl!,\n issuer: urls.issuer!,\n clientId: clientId!\n };\n\n if (tokenParams.extraParams) {\n idTokenObj.extraParams = tokenParams.extraParams;\n }\n\n const validationParams: TokenVerifyParams = {\n clientId: clientId!,\n issuer: urls.issuer!,\n nonce: tokenParams.nonce,\n accessToken: accessToken,\n acrValues: tokenParams.acrValues\n };\n\n if (tokenParams.ignoreSignature !== undefined) {\n validationParams.ignoreSignature = tokenParams.ignoreSignature;\n }\n\n await verifyToken(sdk, idTokenObj, validationParams);\n tokenDict.idToken = idTokenObj;\n }\n\n // Validate received tokens against requested response types \n if (responseType.indexOf('token') !== -1 && !tokenDict.accessToken) {\n // eslint-disable-next-line max-len\n throw new AuthSdkError('Unable to parse OAuth flow response: response type \"token\" was requested but \"access_token\" was not returned.');\n }\n if (responseType.indexOf('id_token') !== -1 && !tokenDict.idToken) {\n // eslint-disable-next-line max-len\n throw new AuthSdkError('Unable to parse OAuth flow response: response type \"id_token\" was requested but \"id_token\" was not returned.');\n }\n\n return {\n tokens: tokenDict,\n state: res.state!,\n code: res.code,\n responseType\n };\n \n}", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/* eslint-disable max-len */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { CustomUrls, OAuthResponse, OAuthResponseType, OktaAuthOAuthInterface, TokenParams, TokenResponse } from './types';\nimport { getOAuthUrls, getDefaultTokenParams } from './util';\nimport { clone } from '../util';\nimport { postToTokenEndpoint, TokenEndpointParams } from './endpoints/token';\nimport { handleOAuthResponse } from './handleOAuthResponse';\nimport { createDPoPKeyPair, findKeyPair } from './dpop';\n\n// codeVerifier is required. May pass either an authorizationCode or interactionCode\nexport async function exchangeCodeForTokens(sdk: OktaAuthOAuthInterface, tokenParams: TokenParams, urls?: CustomUrls): Promise {\n urls = urls || getOAuthUrls(sdk, tokenParams);\n // build params using defaults + options\n tokenParams = Object.assign({}, getDefaultTokenParams(sdk), clone(tokenParams));\n\n const {\n authorizationCode,\n interactionCode,\n codeVerifier,\n clientId,\n redirectUri,\n scopes,\n ignoreSignature,\n state,\n acrValues,\n dpop,\n dpopPairId,\n extraParams\n } = tokenParams;\n\n // postToTokenEndpoint() params\n const getTokenOptions: TokenEndpointParams = {\n clientId,\n redirectUri,\n authorizationCode,\n interactionCode,\n codeVerifier,\n dpop,\n };\n\n // `handleOAuthResponse` hanadles responses from both `/authorize` and `/token` endpoints\n // Here we modify the response from `/token` so that it more closely matches a response from `/authorize`\n // `responseType` is used to validate that the expected tokens were returned\n const responseType: OAuthResponseType[] = ['token']; // an accessToken will always be returned\n if (scopes!.indexOf('openid') !== -1) {\n responseType.push('id_token'); // an idToken will be returned if \"openid\" is in the scopes\n }\n // handleOAuthResponse() params\n const handleResponseOptions: TokenParams = {\n clientId,\n redirectUri,\n scopes,\n responseType,\n ignoreSignature,\n acrValues,\n extraParams\n };\n\n try {\n if (dpop) {\n // token refresh, KP should already exist\n if (dpopPairId) {\n const keyPair = await findKeyPair(dpopPairId);\n getTokenOptions.dpopKeyPair = keyPair;\n handleResponseOptions.dpop = dpop;\n handleResponseOptions.dpopPairId = dpopPairId;\n }\n else {\n const { keyPair, keyPairId } = await createDPoPKeyPair();\n getTokenOptions.dpopKeyPair = keyPair;\n handleResponseOptions.dpop = dpop;\n handleResponseOptions.dpopPairId = keyPairId;\n }\n }\n\n const oauthResponse: OAuthResponse = await postToTokenEndpoint(sdk, getTokenOptions, urls);\n\n const tokenResponse: TokenResponse = await handleOAuthResponse(sdk, handleResponseOptions, oauthResponse, urls!);\n tokenResponse.code = authorizationCode;\n tokenResponse.state = state!;\n return tokenResponse;\n }\n finally {\n sdk.transactionManager.clear();\n }\n}\n", "/* eslint-disable complexity */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { AuthSdkError, OAuthError, WWWAuthError, AuthApiError } from '../errors';\nimport { httpRequest } from '../http';\nimport { AccessToken, IDToken, UserClaims, isAccessToken, isIDToken, CustomUserClaims } from './types';\n\nexport async function getUserInfo(\n sdk, accessTokenObject: AccessToken,\n idTokenObject: IDToken\n): Promise> {\n // If token objects were not passed, attempt to read from the TokenManager\n if (!accessTokenObject) {\n accessTokenObject = (await sdk.tokenManager.getTokens()).accessToken as AccessToken;\n }\n if (!idTokenObject) {\n idTokenObject = (await sdk.tokenManager.getTokens()).idToken as IDToken;\n }\n\n if (!accessTokenObject || !isAccessToken(accessTokenObject)) {\n return Promise.reject(new AuthSdkError('getUserInfo requires an access token object'));\n }\n\n if (!idTokenObject || !isIDToken(idTokenObject)) {\n return Promise.reject(new AuthSdkError('getUserInfo requires an ID token object'));\n }\n\n const options: any = {\n url: accessTokenObject.userinfoUrl,\n method: 'GET',\n accessToken: accessTokenObject.accessToken\n };\n\n if (sdk.options.dpop) {\n const headers = await sdk.getDPoPAuthorizationHeaders({...options, accessToken: accessTokenObject });\n options.headers = headers;\n delete options.accessToken; // unset to prevent overriding Auth header with Bearer Token\n }\n\n return httpRequest(sdk, options)\n .then(userInfo => {\n // Only return the userinfo response if subjects match to mitigate token substitution attacks\n if (userInfo.sub === idTokenObject.claims.sub) {\n return userInfo;\n }\n return Promise.reject(new AuthSdkError('getUserInfo request was rejected due to token mismatch'));\n })\n .catch(function (err) {\n // throw OAuthError to avoid breaking change (when dpop is not being used)\n if (err instanceof WWWAuthError && !sdk.options.dpop) {\n const { error, errorDescription } = err;\n throw new OAuthError(error, errorDescription);\n }\n\n // throw OAuthError to avoid breaking change (when dpop is not being used)\n if (!sdk.options.dpop) {\n let e = err;\n if (err instanceof AuthApiError && err?.meta?.wwwAuthHeader) {\n e = WWWAuthError.parseHeader(err.meta.wwwAuthHeader as string);\n }\n\n if (e instanceof WWWAuthError) {\n const { error, errorDescription } = e;\n throw new OAuthError(error, errorDescription);\n }\n }\n\n throw err;\n });\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n/* global window, document */\n/* eslint-disable complexity, max-statements */\nimport { AuthSdkError } from '../../errors';\nimport { OktaAuthOAuthInterface } from '../types';\n\nexport function addListener(eventTarget, name, fn) {\n if (eventTarget.addEventListener) {\n eventTarget.addEventListener(name, fn);\n } else {\n eventTarget.attachEvent('on' + name, fn);\n }\n}\n\nexport function removeListener(eventTarget, name, fn) {\n if (eventTarget.removeEventListener) {\n eventTarget.removeEventListener(name, fn);\n } else {\n eventTarget.detachEvent('on' + name, fn);\n }\n}\n\nexport function loadFrame(src) {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n iframe.src = src;\n\n return document.body.appendChild(iframe);\n}\n\nexport function loadPopup(src, options) {\n var title = options.popupTitle || 'External Identity Provider User Authentication';\n var appearance = 'toolbar=no, scrollbars=yes, resizable=yes, ' +\n 'top=100, left=500, width=600, height=600';\n return window.open(src, title, appearance);\n}\n\nexport function addPostMessageListener(sdk: OktaAuthOAuthInterface, timeout, state) {\n var responseHandler;\n var timeoutId;\n var msgReceivedOrTimeout = new Promise(function (resolve, reject) {\n\n responseHandler = function responseHandler(e) {\n if (!e.data || e.data.state !== state) {\n // A message not meant for us\n return;\n }\n\n // Configuration mismatch between saved token and current app instance\n // This may happen if apps with different issuers are running on the same host url\n // If they share the same storage key, they may read and write tokens in the same location.\n // Common when developing against http://localhost\n if (e.origin !== sdk.getIssuerOrigin()) {\n return reject(new AuthSdkError('The request does not match client configuration'));\n }\n resolve(e.data);\n };\n\n addListener(window, 'message', responseHandler);\n\n timeoutId = setTimeout(function () {\n reject(new AuthSdkError('OAuth flow timed out'));\n }, timeout || 120000);\n });\n\n return msgReceivedOrTimeout\n .finally(function () {\n clearTimeout(timeoutId);\n removeListener(window, 'message', responseHandler);\n });\n}\n", "/* eslint-disable complexity */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { getWellKnown } from '../endpoints/well-known';\nimport { AuthSdkError } from '../../errors';\nimport { OktaAuthOAuthInterface, TokenParams } from '../types';\nimport { getDefaultTokenParams } from './defaultTokenParams';\nimport { DEFAULT_CODE_CHALLENGE_METHOD } from '../../constants';\nimport PKCE from './pkce';\nimport { OktaAuthBaseInterface } from '../../base/types';\n\nexport function assertPKCESupport(sdk: OktaAuthBaseInterface) {\n if (!sdk.features.isPKCESupported()) {\n var errorMessage = 'PKCE requires a modern browser with encryption support running in a secure context.';\n if (!sdk.features.isHTTPS()) {\n // eslint-disable-next-line max-len\n errorMessage += '\\nThe current page is not being served with HTTPS protocol. PKCE requires secure HTTPS protocol.';\n }\n if (!sdk.features.hasTextEncoder()) {\n // eslint-disable-next-line max-len\n errorMessage += '\\n\"TextEncoder\" is not defined. To use PKCE, you may need to include a polyfill/shim for this browser.';\n }\n throw new AuthSdkError(errorMessage);\n }\n}\n\nexport async function validateCodeChallengeMethod(sdk: OktaAuthOAuthInterface, codeChallengeMethod?: string) {\n // set default code challenge method, if none provided\n codeChallengeMethod = codeChallengeMethod || sdk.options.codeChallengeMethod || DEFAULT_CODE_CHALLENGE_METHOD;\n\n // validate against .well-known/openid-configuration\n const wellKnownResponse = await getWellKnown(sdk);\n var methods = wellKnownResponse['code_challenge_methods_supported'] || [];\n if (methods.indexOf(codeChallengeMethod) === -1) {\n throw new AuthSdkError('Invalid code_challenge_method');\n }\n return codeChallengeMethod;\n}\n\nexport async function preparePKCE(\n sdk: OktaAuthOAuthInterface, \n tokenParams: TokenParams\n): Promise {\n let {\n codeVerifier,\n codeChallenge,\n codeChallengeMethod\n } = tokenParams;\n\n // PKCE calculations can be avoided by passing a codeChallenge\n codeChallenge = codeChallenge || sdk.options.codeChallenge;\n if (!codeChallenge) {\n assertPKCESupport(sdk);\n codeVerifier = codeVerifier || PKCE.generateVerifier();\n codeChallenge = await PKCE.computeChallenge(codeVerifier);\n }\n codeChallengeMethod = await validateCodeChallengeMethod(sdk, codeChallengeMethod);\n\n // Clone/copy the params. Set PKCE values\n tokenParams = {\n ...tokenParams,\n responseType: 'code', // responseType is forced\n codeVerifier,\n codeChallenge,\n codeChallengeMethod\n };\n\n return tokenParams;\n}\n\n// Prepares params for a call to /authorize or /token\nexport async function prepareTokenParams(\n sdk: OktaAuthOAuthInterface,\n tokenParams: TokenParams = {}\n): Promise {\n // build params using defaults + options\n const defaults = getDefaultTokenParams(sdk);\n tokenParams = { ...defaults, ...tokenParams };\n\n if (tokenParams.dpop && !sdk.features.isDPoPSupported()) {\n throw new AuthSdkError('DPoP has been configured, but is not supported by browser');\n }\n\n if (tokenParams.pkce === false) {\n // Implicit flow or authorization_code without PKCE\n return tokenParams;\n }\n\n return preparePKCE(sdk, tokenParams);\n}", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { isString, removeNils, toQueryString } from '../../util';\nimport { AuthSdkError } from '../../errors';\nimport { OAuthParams, TokenParams } from '../types';\n\nexport function convertTokenParamsToOAuthParams(tokenParams: TokenParams) {\n // Quick validation\n if (!tokenParams.clientId) {\n throw new AuthSdkError('A clientId must be specified in the OktaAuth constructor to get a token');\n }\n\n if (isString(tokenParams.responseType) && tokenParams.responseType.indexOf(' ') !== -1) {\n throw new AuthSdkError('Multiple OAuth responseTypes must be defined as an array');\n }\n\n // Convert our params to their actual OAuth equivalents\n var oauthParams: OAuthParams = {\n 'client_id': tokenParams.clientId,\n 'code_challenge': tokenParams.codeChallenge,\n 'code_challenge_method': tokenParams.codeChallengeMethod,\n 'display': tokenParams.display,\n 'idp': tokenParams.idp,\n 'idp_scope': tokenParams.idpScope,\n 'login_hint': tokenParams.loginHint,\n 'max_age': tokenParams.maxAge,\n 'nonce': tokenParams.nonce,\n 'prompt': tokenParams.prompt,\n 'redirect_uri': tokenParams.redirectUri,\n 'response_mode': tokenParams.responseMode,\n 'response_type': tokenParams.responseType,\n 'sessionToken': tokenParams.sessionToken,\n 'state': tokenParams.state,\n 'acr_values': tokenParams.acrValues,\n 'enroll_amr_values': tokenParams.enrollAmrValues,\n };\n oauthParams = removeNils(oauthParams) as OAuthParams;\n\n ['idp_scope', 'response_type', 'enroll_amr_values'].forEach(function (mayBeArray) {\n if (Array.isArray(oauthParams[mayBeArray])) {\n oauthParams[mayBeArray] = oauthParams[mayBeArray].join(' ');\n }\n });\n\n if (tokenParams.responseType!.indexOf('id_token') !== -1 &&\n tokenParams.scopes!.indexOf('openid') === -1) {\n throw new AuthSdkError('openid scope must be specified in the scopes argument when requesting an id_token');\n } else if (tokenParams.scopes) {\n oauthParams.scope = tokenParams.scopes!.join(' ');\n }\n\n return oauthParams;\n}\n\nexport function buildAuthorizeParams(tokenParams: TokenParams) {\n var oauthQueryParams = convertTokenParamsToOAuthParams(tokenParams);\n return toQueryString({ \n ...oauthQueryParams, \n ...(tokenParams.extraParams && { ...tokenParams.extraParams })\n });\n}\n", "\n/* global document */\n/* eslint-disable complexity, max-statements */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport {\n getOAuthUrls,\n loadFrame,\n addPostMessageListener\n} from './util';\n\nimport AuthSdkError from '../errors/AuthSdkError';\n\nimport {\n OktaAuthOAuthInterface,\n TokenParams,\n PopupParams,\n OAuthResponse,\n} from './types';\n\nimport { prepareTokenParams } from './util/prepareTokenParams';\nimport { buildAuthorizeParams } from './endpoints/authorize';\nimport { handleOAuthResponse } from './handleOAuthResponse';\n/*\n * Retrieve an idToken from an Okta or a third party idp\n *\n * Two main flows:\n *\n * 1) Exchange a sessionToken for a token\n *\n * Required:\n * clientId: passed via the OktaAuth constructor or into getToken\n * sessionToken: 'yourtoken'\n *\n * Optional:\n * redirectUri: defaults to window.location.href\n * scopes: defaults to ['openid', 'email']\n *\n * Forced:\n * prompt: 'none'\n * responseMode: 'okta_post_message'\n * display: undefined\n *\n * 2) Get a token from an idp\n *\n * Required:\n * clientId: passed via the OktaAuth constructor or into getToken\n *\n * Optional:\n * redirectUri: defaults to window.location.href\n * scopes: defaults to ['openid', 'email']\n * idp: defaults to Okta as an idp\n * prompt: no default. Pass 'none' to throw an error if user is not signed in\n *\n * Forced:\n * display: 'popup'\n *\n * Only common optional params shown. Any OAuth parameters not explicitly forced are available to override\n *\n * @param {Object} oauthOptions\n * @param {String} [oauthOptions.clientId] ID of this client\n * @param {String} [oauthOptions.redirectUri] URI that the iframe or popup will go to once authenticated\n * @param {String[]} [oauthOptions.scopes] OAuth 2.0 scopes to request (openid must be specified)\n * @param {String} [oauthOptions.idp] ID of an external IdP to use for user authentication\n * @param {String} [oauthOptions.sessionToken] Bootstrap Session Token returned by the Okta Authentication API\n * @param {String} [oauthOptions.prompt] Determines whether the Okta login will be displayed on failure.\n * Use 'none' to prevent this behavior\n *\n * @param {Object} options\n * @param {Integer} [options.timeout] Time in ms before the flow is automatically terminated. Defaults to 120000\n * @param {String} [options.popupTitle] Title dispayed in the popup.\n * Defaults to 'External Identity Provider User Authentication'\n */\nexport function getToken(sdk: OktaAuthOAuthInterface, options: TokenParams & PopupParams) {\n if (arguments.length > 2) {\n return Promise.reject(new AuthSdkError('As of version 3.0, \"getToken\" takes only a single set of options'));\n }\n\n options = options || {};\n\n // window object cannot be serialized, save for later use\n // TODO: move popup related params into a separate options object\n const popupWindow = options.popupWindow;\n options.popupWindow = undefined;\n\n return prepareTokenParams(sdk, options)\n .then(function (tokenParams: TokenParams) {\n\n // Start overriding any options that don't make sense\n var sessionTokenOverrides = {\n prompt: 'none',\n responseMode: 'okta_post_message',\n display: null\n };\n\n var idpOverrides = {\n display: 'popup'\n };\n\n if (options.sessionToken) {\n Object.assign(tokenParams, sessionTokenOverrides);\n } else if (options.idp) {\n Object.assign(tokenParams, idpOverrides);\n }\n\n // Use the query params to build the authorize url\n var requestUrl,\n endpoint,\n urls;\n\n // Get authorizeUrl and issuer\n urls = getOAuthUrls(sdk, tokenParams);\n endpoint = options.codeVerifier ? urls.tokenUrl : urls.authorizeUrl;\n requestUrl = endpoint + buildAuthorizeParams(tokenParams);\n\n // Determine the flow type\n var flowType;\n if (tokenParams.sessionToken || tokenParams.display === null) {\n flowType = 'IFRAME';\n } else if (tokenParams.display === 'popup') {\n flowType = 'POPUP';\n } else {\n flowType = 'IMPLICIT';\n }\n\n // Execute the flow type\n switch (flowType) {\n case 'IFRAME':\n var iframePromise = addPostMessageListener(sdk, options.timeout, tokenParams.state);\n var iframeEl = loadFrame(requestUrl);\n return iframePromise\n .then(function (res) {\n return handleOAuthResponse(sdk, tokenParams, res as OAuthResponse, urls);\n })\n .finally(function () {\n if (document.body.contains(iframeEl)) {\n iframeEl.parentElement?.removeChild(iframeEl);\n }\n });\n\n case 'POPUP':\n var oauthPromise; // resolves with OAuth response\n\n // Add listener on postMessage before window creation, so\n // postMessage isn't triggered before we're listening\n if (tokenParams.responseMode === 'okta_post_message') {\n if (!sdk.features.isPopupPostMessageSupported()) {\n throw new AuthSdkError('This browser doesn\\'t have full postMessage support');\n }\n oauthPromise = addPostMessageListener(sdk, options.timeout, tokenParams.state);\n }\n\n // Redirect for authorization\n // popupWindown can be null when popup is blocked\n if (popupWindow) { \n popupWindow.location.assign(requestUrl);\n }\n\n // The popup may be closed without receiving an OAuth response. Setup a poller to monitor the window.\n var popupPromise = new Promise(function (resolve, reject) {\n var closePoller = setInterval(function () {\n if (!popupWindow || popupWindow.closed) {\n clearInterval(closePoller);\n reject(new AuthSdkError('Unable to parse OAuth flow response'));\n }\n }, 100);\n\n // Proxy the OAuth promise results\n oauthPromise\n .then(function (res) {\n clearInterval(closePoller);\n resolve(res);\n })\n .catch(function (err) {\n clearInterval(closePoller);\n reject(err);\n });\n });\n\n return popupPromise\n .then(function (res) {\n return handleOAuthResponse(sdk, tokenParams, res as OAuthResponse, urls);\n })\n .finally(function () {\n if (popupWindow && !popupWindow.closed) {\n popupWindow.close();\n }\n });\n\n default:\n throw new AuthSdkError('The full page redirect flow is not supported');\n }\n });\n}", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { AuthSdkError } from '../errors';\nimport { OktaAuthOAuthInterface, TokenParams, TokenResponse } from './types';\nimport { clone } from '../util';\nimport { getToken } from './getToken';\n\nexport function getWithoutPrompt(sdk: OktaAuthOAuthInterface, options: TokenParams): Promise {\n if (arguments.length > 2) {\n return Promise.reject(new AuthSdkError('As of version 3.0, \"getWithoutPrompt\" takes only a single set of options'));\n }\n \n options = clone(options) || {};\n Object.assign(options, {\n prompt: 'none',\n responseMode: 'okta_post_message',\n display: null\n });\n return getToken(sdk, options);\n}\n\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { AuthSdkError } from '../errors';\nimport { OktaAuthOAuthInterface, TokenParams, TokenResponse } from './types';\nimport { clone } from '../util';\nimport { getToken } from './getToken';\nimport { loadPopup } from './util';\n\nexport function getWithPopup(sdk: OktaAuthOAuthInterface, options: TokenParams): Promise {\n if (arguments.length > 2) {\n return Promise.reject(new AuthSdkError('As of version 3.0, \"getWithPopup\" takes only a single set of options'));\n }\n\n // some browsers (safari, firefox) block popup if it's initialed from an async process\n // here we create the popup window immediately after user interaction\n // then redirect to the /authorize endpoint when the requestUrl is available\n const popupWindow = loadPopup('/', options);\n options = clone(options) || {};\n Object.assign(options, {\n display: 'popup',\n responseMode: 'okta_post_message',\n popupWindow\n });\n return getToken(sdk, options);\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { AuthSdkError } from '../errors';\nimport { OktaAuthOAuthInterface, TokenParams } from './types';\nimport { clone } from '../util';\nimport { prepareTokenParams, createOAuthMeta } from './util';\nimport { buildAuthorizeParams } from './endpoints/authorize';\n\nexport async function getWithRedirect(sdk: OktaAuthOAuthInterface, options?: TokenParams): Promise {\n if (arguments.length > 2) {\n return Promise.reject(new AuthSdkError('As of version 3.0, \"getWithRedirect\" takes only a single set of options'));\n }\n\n options = clone(options) || {};\n\n const tokenParams = await prepareTokenParams(sdk, options);\n const meta = createOAuthMeta(sdk, tokenParams);\n const requestUrl = meta.urls.authorizeUrl + buildAuthorizeParams(tokenParams);\n sdk.transactionManager.save(meta);\n if (sdk.options.setLocation) {\n sdk.options.setLocation(requestUrl);\n } else {\n window.location.assign(requestUrl);\n }\n}\n", "/* eslint-disable complexity */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { AuthSdkError } from '../errors';\nimport { isInteractionRequiredError, urlParamsToObject } from './util';\nimport {\n ParseFromUrlOptions,\n TokenResponse,\n CustomUrls,\n TransactionMeta,\n OAuthResponse\n} from './types';\nimport { isString } from '../util';\nimport { handleOAuthResponse } from './handleOAuthResponse';\n\nfunction removeHash(sdk) {\n var nativeHistory = sdk.token.parseFromUrl._getHistory();\n var nativeDoc = sdk.token.parseFromUrl._getDocument();\n var nativeLoc = sdk.token.parseFromUrl._getLocation();\n if (nativeHistory && nativeHistory.replaceState) {\n nativeHistory.replaceState(null, nativeDoc.title, nativeLoc.pathname + nativeLoc.search);\n } else {\n nativeLoc.hash = '';\n }\n}\n\nfunction removeSearch(sdk) {\n var nativeHistory = sdk.token.parseFromUrl._getHistory();\n var nativeDoc = sdk.token.parseFromUrl._getDocument();\n var nativeLoc = sdk.token.parseFromUrl._getLocation();\n if (nativeHistory && nativeHistory.replaceState) {\n nativeHistory.replaceState(null, nativeDoc.title, nativeLoc.pathname + nativeLoc.hash);\n } else {\n nativeLoc.search = '';\n }\n}\n\nexport function getResponseMode(sdk): 'query' | 'fragment' {\n // https://openid.net/specs/openid-connect-core-1_0.html#Authentication\n var defaultResponseMode = sdk.options.pkce ? 'query' : 'fragment';\n var responseMode = sdk.options.responseMode || defaultResponseMode;\n return responseMode;\n}\n\nexport function parseOAuthResponseFromUrl(sdk, options: string | ParseFromUrlOptions): OAuthResponse {\n options = options || {};\n if (isString(options)) {\n options = { url: options } as ParseFromUrlOptions;\n } else {\n options = options as ParseFromUrlOptions;\n }\n\n var url = options.url;\n var responseMode = options.responseMode || getResponseMode(sdk);\n var nativeLoc = sdk.token.parseFromUrl._getLocation();\n var paramStr;\n\n if (responseMode === 'query') {\n paramStr = url ? url.substring(url.indexOf('?')) : nativeLoc.search;\n } else {\n paramStr = url ? url.substring(url.indexOf('#')) : nativeLoc.hash;\n }\n\n if (!paramStr) {\n throw new AuthSdkError('Unable to parse a token from the url');\n }\n\n return urlParamsToObject(paramStr);\n}\n\nexport function cleanOAuthResponseFromUrl(sdk, options: ParseFromUrlOptions) {\n // Clean hash or search from the url\n const responseMode = options.responseMode || getResponseMode(sdk);\n responseMode === 'query' ? removeSearch(sdk) : removeHash(sdk);\n}\n\nexport async function parseFromUrl(sdk, options?: string | ParseFromUrlOptions): Promise {\n options = options || {};\n if (isString(options)) {\n options = { url: options } as ParseFromUrlOptions;\n } else {\n options = options as ParseFromUrlOptions;\n }\n\n const res: OAuthResponse = parseOAuthResponseFromUrl(sdk, options);\n const state = res.state;\n const oauthParams: TransactionMeta = sdk.transactionManager.load({\n state\n });\n if (!oauthParams) {\n if (sdk.options.pkce) {\n // eslint-disable-next-line max-len\n throw new AuthSdkError('Could not load PKCE codeVerifier from storage. This may indicate the auth flow has already completed or multiple auth flows are executing concurrently.', undefined);\n }\n throw new AuthSdkError('Unable to retrieve OAuth redirect params from storage');\n }\n const urls: CustomUrls = oauthParams.urls as CustomUrls;\n delete oauthParams.urls;\n\n if (!options.url) {\n // Clean hash or search from the url\n cleanOAuthResponseFromUrl(sdk, options);\n }\n\n return handleOAuthResponse(sdk, oauthParams, res, urls)\n .catch(err => {\n if (!isInteractionRequiredError(err)) {\n sdk.transactionManager.clear({\n state\n });\n }\n throw err;\n })\n .then(res => {\n sdk.transactionManager.clear({\n state\n });\n return res;\n });\n\n}\n", "import { RefreshToken } from '../types';\nimport { isAuthApiError } from '../../errors';\n\nexport function isSameRefreshToken(a: RefreshToken, b: RefreshToken) {\n return (a.refreshToken === b.refreshToken);\n}\n\nexport function isRefreshTokenError(err: Error) {\n if (!isAuthApiError(err)) {\n return false;\n }\n\n if (!err.xhr || !err.xhr.responseJSON) {\n return false;\n }\n\n const { responseJSON } = err.xhr;\n if (responseJSON.error === 'invalid_grant') {\n return true;\n }\n\n return false;\n}", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { AuthSdkError } from '../errors';\nimport { getOAuthUrls } from './util/oauth';\nimport { isSameRefreshToken } from './util/refreshToken';\nimport { OktaAuthOAuthInterface, TokenParams, RefreshToken, Tokens } from './types';\nimport { handleOAuthResponse } from './handleOAuthResponse';\nimport { TokenEndpointParams, postRefreshToken } from './endpoints/token';\nimport { findKeyPair } from './dpop';\nimport { isRefreshTokenInvalidError } from './util/errors';\n\n/* eslint complexity:[0,8] */\nexport async function renewTokensWithRefresh(\n sdk: OktaAuthOAuthInterface,\n tokenParams: TokenParams,\n refreshTokenObject: RefreshToken\n): Promise {\n const { clientId, dpop } = sdk.options;\n if (!clientId) {\n throw new AuthSdkError('A clientId must be specified in the OktaAuth constructor to renew tokens');\n }\n\n try {\n const renewTokenParams: TokenParams = Object.assign({}, tokenParams, { clientId });\n\n if (refreshTokenObject.extraParams) {\n renewTokenParams.extraParams = refreshTokenObject.extraParams;\n }\n\n const endpointParams: TokenEndpointParams = {...renewTokenParams};\n\n if (dpop) {\n const keyPair = await findKeyPair(refreshTokenObject?.dpopPairId); // will throw if KP cannot be found\n endpointParams.dpopKeyPair = keyPair;\n renewTokenParams.dpop = dpop;\n renewTokenParams.dpopPairId = refreshTokenObject.dpopPairId;\n }\n\n const tokenResponse = await postRefreshToken(sdk, endpointParams, refreshTokenObject);\n const urls = getOAuthUrls(sdk, tokenParams);\n const { tokens } = await handleOAuthResponse(sdk, renewTokenParams, tokenResponse, urls);\n\n // Support rotating refresh tokens\n const { refreshToken } = tokens;\n if (refreshToken && !isSameRefreshToken(refreshToken, refreshTokenObject)) {\n sdk.tokenManager.updateRefreshToken(refreshToken);\n }\n\n return tokens;\n }\n catch (err) {\n if (isRefreshTokenInvalidError(err)) {\n // if the refresh token is invalid, remove it from storage\n sdk.tokenManager.removeRefreshToken();\n }\n throw err;\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { AuthSdkError } from '../errors';\nimport { OktaAuthOAuthInterface, Token, Tokens, isAccessToken, AccessToken, IDToken, isIDToken } from './types';\nimport { getWithoutPrompt } from './getWithoutPrompt';\nimport { renewTokensWithRefresh } from './renewTokensWithRefresh';\n\nfunction throwInvalidTokenError() {\n throw new AuthSdkError(\n 'Renew must be passed a token with an array of scopes and an accessToken or idToken'\n );\n}\n\n// Multiple tokens may have come back. Return only the token which was requested.\nfunction getSingleToken(originalToken: Token, tokens: Tokens) {\n if (isIDToken(originalToken)) {\n return tokens.idToken;\n }\n if (isAccessToken(originalToken)) {\n return tokens.accessToken;\n }\n throwInvalidTokenError();\n}\n\n// If we have a refresh token, renew using that, otherwise getWithoutPrompt\nexport async function renewToken(sdk: OktaAuthOAuthInterface, token: Token): Promise {\n if (!isIDToken(token) && !isAccessToken(token)) {\n throwInvalidTokenError();\n }\n\n let tokens = sdk.tokenManager.getTokensSync();\n if (tokens.refreshToken) {\n tokens = await renewTokensWithRefresh(sdk, {\n scopes: token.scopes,\n }, tokens.refreshToken);\n return getSingleToken(token, tokens);\n }\n\n var responseType;\n if (sdk.options.pkce) {\n responseType = 'code';\n } else if (isAccessToken(token)) {\n responseType = 'token';\n } else {\n responseType = 'id_token';\n }\n\n const { scopes, authorizeUrl, userinfoUrl, issuer, dpopPairId, extraParams } = token as (AccessToken & IDToken);\n return getWithoutPrompt(sdk, {\n responseType,\n scopes,\n authorizeUrl,\n userinfoUrl,\n issuer,\n dpopPairId,\n extraParams\n })\n .then(function (res) {\n return getSingleToken(token, res.tokens);\n });\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { AuthSdkError } from '../errors';\nimport { RenewTokensParams, Tokens } from './types';\nimport { getWithoutPrompt } from './getWithoutPrompt';\nimport { renewTokensWithRefresh } from './renewTokensWithRefresh';\nimport { getDefaultTokenParams } from './util';\n\n// If we have a refresh token, renew using that, otherwise getWithoutPrompt\n// eslint-disable-next-line complexity\nexport async function renewTokens(sdk, options?: RenewTokensParams): Promise {\n const tokens = options?.tokens ?? sdk.tokenManager.getTokensSync();\n if (tokens.refreshToken) {\n return renewTokensWithRefresh(sdk, options || {}, tokens.refreshToken);\n }\n\n if (!tokens.accessToken && !tokens.idToken) {\n throw new AuthSdkError('renewTokens() was called but there is no existing token');\n }\n\n const accessToken = tokens.accessToken || {};\n const idToken = tokens.idToken || {};\n const scopes = accessToken.scopes || idToken.scopes;\n if (!scopes) {\n throw new AuthSdkError('renewTokens: invalid tokens: could not read scopes');\n }\n const authorizeUrl = accessToken.authorizeUrl || idToken.authorizeUrl;\n if (!authorizeUrl) {\n throw new AuthSdkError('renewTokens: invalid tokens: could not read authorizeUrl');\n }\n const userinfoUrl = accessToken.userinfoUrl || sdk.options.userinfoUrl;\n const issuer = idToken.issuer || sdk.options.issuer;\n const dpopPairId = accessToken?.dpopPairId;\n const extraParams = accessToken?.extraParams || idToken?.extraParams;\n\n // Get tokens using the SSO cookie\n options = Object.assign({\n scopes,\n authorizeUrl,\n userinfoUrl,\n issuer,\n dpopPairId,\n extraParams\n }, options);\n\n if (sdk.options.pkce) {\n options.responseType = 'code';\n } else {\n const { responseType } = getDefaultTokenParams(sdk);\n options.responseType = responseType;\n }\n\n return getWithoutPrompt(sdk, options)\n .then(res => res.tokens);\n \n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\n/* eslint complexity:[0,8] */\nimport { post } from '../http';\nimport { toQueryString } from '../util';\nimport {\n getOAuthUrls,\n} from './util/oauth';\nimport { btoa } from '../crypto';\nimport AuthSdkError from '../errors/AuthSdkError';\nimport {\n OktaAuthOAuthInterface,\n RevocableToken,\n AccessToken,\n RefreshToken\n} from './types';\n\n// refresh tokens have precedence to be revoked if no token is specified\nexport async function revokeToken(sdk: OktaAuthOAuthInterface, token: RevocableToken): Promise {\n let accessToken = '';\n let refreshToken = '';\n if (token) { \n accessToken = (token as AccessToken).accessToken;\n refreshToken = (token as RefreshToken).refreshToken; \n }\n if(!accessToken && !refreshToken) { \n throw new AuthSdkError('A valid access or refresh token object is required');\n }\n var clientId = sdk.options.clientId;\n var clientSecret = sdk.options.clientSecret;\n if (!clientId) {\n throw new AuthSdkError('A clientId must be specified in the OktaAuth constructor to revoke a token');\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n var revokeUrl = getOAuthUrls(sdk).revokeUrl!;\n var args = toQueryString({\n // eslint-disable-next-line camelcase\n token_type_hint: refreshToken ? 'refresh_token' : 'access_token', \n token: refreshToken || accessToken,\n }).slice(1);\n var creds = clientSecret ? btoa(`${clientId}:${clientSecret}`) : btoa(clientId);\n return post(sdk, revokeUrl, args, {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Authorization': 'Basic ' + creds\n }\n });\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\nimport { AuthSdkError } from '../errors';\nimport { getWellKnown } from './endpoints/well-known';\nimport { post } from '../http';\nimport { toQueryString } from '../util';\nimport { btoa } from '../crypto';\nimport { Token, TokenKind } from './types';\n\nconst hintMap = {\n accessToken: 'access_token',\n idToken: 'id_token',\n refreshToken: 'refresh_token'\n};\n\n/* eslint complexity: [2, 9] */\nexport async function oidcIntrospect (sdk, kind: TokenKind, token?: Token) {\n let issuer: string;\n let clientId: string = sdk.options.clientId;\n let clientSecret: string | undefined = sdk.options.clientSecret;\n\n if (!token) {\n token = sdk.tokenManager.getTokens()[kind];\n }\n\n if (!token) {\n throw new AuthSdkError(`unable to find ${kind} in storage or fn params`);\n }\n\n if (kind !== TokenKind.ACCESS) {\n issuer = (token as any)?.issuer;\n }\n else {\n issuer = (token as any)?.claims?.iss;\n }\n issuer = issuer || sdk.options.issuer;\n\n if (!clientId) {\n throw new AuthSdkError('A clientId must be specified in the OktaAuth constructor to introspect a token');\n }\n if (!issuer) {\n throw new AuthSdkError('Unable to find issuer');\n }\n\n const { introspection_endpoint: introspectUrl } = await getWellKnown(sdk, issuer);\n const authHeader = clientSecret ? btoa(`${clientId}:${clientSecret}`) : btoa(clientId);\n const args = toQueryString({\n // eslint-disable-next-line camelcase\n token_type_hint: hintMap[kind],\n token: token[kind] // extract raw token string from token object\n }).slice(1);\n return post(sdk, introspectUrl, args, {\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Authorization': 'Basic ' + authHeader\n }\n });\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport { OAuthTransactionMeta, OktaAuthOAuthInterface, EnrollAuthenticatorOptions } from '../types';\nimport { getOAuthUrls } from './oauth';\n\nexport function createEnrollAuthenticatorMeta(\n sdk: OktaAuthOAuthInterface, \n params: EnrollAuthenticatorOptions\n): OAuthTransactionMeta {\n const issuer = sdk.options.issuer!;\n const urls = getOAuthUrls(sdk, params);\n const oauthMeta: OAuthTransactionMeta = {\n issuer,\n urls,\n clientId: params.clientId!,\n redirectUri: params.redirectUri!,\n responseType: params.responseType!,\n responseMode: params.responseMode!,\n state: params.state!,\n acrValues: params.acrValues,\n enrollAmrValues: params.enrollAmrValues,\n };\n\n return oauthMeta;\n}\n", "\n/* global window */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { generateState } from './oauth';\nimport { OktaAuthOAuthInterface, TokenParams } from '../types';\nimport { isBrowser } from '../../features';\nimport { removeNils } from '../../util';\n\nexport function getDefaultEnrollAuthenticatorParams(sdk: OktaAuthOAuthInterface): TokenParams {\n const {\n clientId,\n redirectUri,\n responseMode,\n state,\n } = sdk.options;\n const defaultRedirectUri = isBrowser() ? window.location.href : undefined;\n return removeNils({\n clientId,\n redirectUri: redirectUri || defaultRedirectUri,\n responseMode,\n state: state || generateState(),\n responseType: 'none',\n prompt: 'enroll_authenticator',\n });\n}", "/* eslint-disable complexity */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { AuthSdkError } from '../../errors';\nimport { OktaAuthOAuthInterface, EnrollAuthenticatorOptions } from '../types';\nimport { getDefaultEnrollAuthenticatorParams } from './defaultEnrollAuthenticatorParams';\n\nfunction prepareParams(\n params: EnrollAuthenticatorOptions\n): EnrollAuthenticatorOptions {\n params = {\n ...params,\n // forced params:\n responseType: 'none',\n prompt: 'enroll_authenticator',\n maxAge: 0,\n };\n\n if (!params.enrollAmrValues) {\n throw new AuthSdkError('enroll_amr_values must be specified');\n }\n if (!params.acrValues) {\n // `acr_values` is required and should equal 'urn:okta:2fa:any:ifpossible'\n // But this can be changed in future\n throw new AuthSdkError('acr_values must be specified');\n }\n\n // `scope`, `nonce` must be omitted\n delete params.scopes;\n delete params.nonce;\n\n return params;\n}\n\n// Prepares params for a call to /authorize\nexport function prepareEnrollAuthenticatorParams(\n sdk: OktaAuthOAuthInterface,\n options: EnrollAuthenticatorOptions\n): EnrollAuthenticatorOptions {\n return prepareParams({\n ...getDefaultEnrollAuthenticatorParams(sdk),\n ...options\n });\n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { OktaAuthOAuthInterface, EnrollAuthenticatorOptions } from './types';\nimport { clone } from '../util';\nimport { prepareEnrollAuthenticatorParams, createEnrollAuthenticatorMeta } from './util';\nimport { buildAuthorizeParams } from './endpoints/authorize';\n\nexport function enrollAuthenticator(\n sdk: OktaAuthOAuthInterface, \n options: EnrollAuthenticatorOptions\n): void {\n options = clone(options) || {};\n\n const params = prepareEnrollAuthenticatorParams(sdk, options);\n const meta = createEnrollAuthenticatorMeta(sdk, params);\n const requestUrl = meta.urls.authorizeUrl + buildAuthorizeParams(params);\n sdk.transactionManager.save(meta);\n if (sdk.options.setLocation) {\n sdk.options.setLocation(requestUrl);\n } else {\n window.location.assign(requestUrl);\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\nimport { PromiseQueue } from '../../util';\nimport { decodeToken } from '../decodeToken';\nimport { exchangeCodeForTokens } from '../exchangeCodeForTokens';\nimport { getUserInfo } from '../getUserInfo';\nimport { getWithoutPrompt } from '../getWithoutPrompt';\nimport { getWithPopup } from '../getWithPopup';\nimport { getWithRedirect } from '../getWithRedirect';\nimport { parseFromUrl } from '../parseFromUrl';\nimport { renewToken } from '../renewToken';\nimport { renewTokens } from '../renewTokens';\nimport { renewTokensWithRefresh } from '../renewTokensWithRefresh';\nimport { revokeToken } from '../revokeToken';\nimport { oidcIntrospect } from '../introspect';\nimport {\n AccessToken,\n CustomUserClaims,\n GetWithRedirectFunction,\n IDToken,\n OktaAuthOAuthInterface,\n ParseFromUrlInterface,\n TokenAPI,\n UserClaims,\n Endpoints,\n} from '../types';\nimport { isLoginRedirect, prepareTokenParams } from '../util';\nimport { verifyToken } from '../verifyToken';\nimport { enrollAuthenticator } from '../enrollAuthenticator';\n\n// Factory\nexport function createTokenAPI(sdk: OktaAuthOAuthInterface, queue: PromiseQueue): TokenAPI {\n const useQueue = (method) => {\n return PromiseQueue.prototype.push.bind(queue, method, null);\n };\n\n const getWithRedirectFn = useQueue(getWithRedirect.bind(null, sdk)) as GetWithRedirectFunction;\n\n // eslint-disable-next-line max-len\n const parseFromUrlFn = useQueue(parseFromUrl.bind(null, sdk)) as ParseFromUrlInterface;\n const parseFromUrlApi: ParseFromUrlInterface = Object.assign(parseFromUrlFn, {\n // This is exposed so we can mock getting window.history in our tests\n _getHistory: function() {\n return window.history;\n },\n\n // This is exposed so we can mock getting window.location in our tests\n _getLocation: function() {\n return window.location;\n },\n\n // This is exposed so we can mock getting window.document in our tests\n _getDocument: function() {\n return window.document;\n }\n });\n\n const token: TokenAPI ={\n prepareTokenParams: prepareTokenParams.bind(null, sdk),\n exchangeCodeForTokens: exchangeCodeForTokens.bind(null, sdk),\n getWithoutPrompt: getWithoutPrompt.bind(null, sdk),\n getWithPopup: getWithPopup.bind(null, sdk),\n getWithRedirect: getWithRedirectFn,\n parseFromUrl: parseFromUrlApi,\n decode: decodeToken,\n revoke: revokeToken.bind(null, sdk),\n renew: renewToken.bind(null, sdk),\n renewTokensWithRefresh: renewTokensWithRefresh.bind(null, sdk),\n renewTokens: renewTokens.bind(null, sdk),\n getUserInfo: (\n accessTokenObject: AccessToken,\n idTokenObject: IDToken\n ): Promise> => {\n return getUserInfo(sdk, accessTokenObject, idTokenObject);\n },\n verify: verifyToken.bind(null, sdk),\n isLoginRedirect: isLoginRedirect.bind(null, sdk),\n introspect: oidcIntrospect.bind(null, sdk),\n };\n\n // Wrap certain async token API methods using PromiseQueue to avoid issues with concurrency\n // 'getWithRedirect' and 'parseFromUrl' are already wrapped\n const toWrap = [\n 'getWithoutPrompt',\n 'getWithPopup',\n 'revoke',\n 'renew',\n 'renewTokensWithRefresh',\n 'renewTokens'\n ];\n toWrap.forEach(key => {\n token[key] = useQueue(token[key]);\n });\n\n return token;\n}\n\nexport function createEndpoints(sdk: OktaAuthOAuthInterface): Endpoints {\n return {\n authorize: {\n enrollAuthenticator: enrollAuthenticator.bind(null, sdk),\n }\n };\n}\n", "/* eslint-disable complexity */\n\nimport { AuthSdkError } from '../../errors';\nimport { isAccessToken, isIDToken, isRefreshToken, Token, TokenType } from '../../oidc/types';\n\nexport function validateToken(token: Token, type?: TokenType) {\n if (!isIDToken(token) && !isAccessToken(token) && !isRefreshToken(token)) {\n throw new AuthSdkError(\n 'Token must be an Object with scopes, expiresAt, and one of: an idToken, accessToken, or refreshToken property'\n );\n }\n \n if (type === 'accessToken' && !isAccessToken(token)) {\n throw new AuthSdkError('invalid accessToken');\n } \n if (type === 'idToken' && !isIDToken(token)) {\n throw new AuthSdkError('invalid idToken');\n }\n\n if (type === 'refreshToken' && !isRefreshToken(token)) {\n throw new AuthSdkError('invalid refreshToken');\n }\n}", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nexport default class SdkClock {\n localOffset: number;\n\n constructor(localOffset) {\n // Calculated local clock offset from server time (in milliseconds). Can be positive or negative.\n this.localOffset = parseInt(localOffset || 0);\n }\n\n // factory method. Create an instance of a clock from current context.\n static create(/* sdk, options */): SdkClock {\n // TODO: calculate localOffset\n var localOffset = 0;\n return new SdkClock(localOffset);\n }\n\n // Return the current time (in seconds)\n now() {\n var now = (Date.now() + this.localOffset) / 1000;\n return now;\n }\n}\n", "/* eslint-disable max-len */\nimport { StorageProvider } from '../../storage/types';\nimport { TokenManagerOptions } from './options';\nimport { AccessToken, IDToken, RefreshToken, Token, Tokens, TokenType } from './Token';\n\nexport interface TokenManagerError {\n errorSummary: string;\n errorCode: string;\n message: string;\n name: string;\n tokenKey: string;\n}\n\nexport declare type AccessTokenCallback = (key: string, token: AccessToken) => void;\nexport declare type IDTokenCallback = (key: string, token: IDToken) => void;\nexport declare type RefreshTokenCallback = (key: string, token: RefreshToken) => void;\n\nexport const EVENT_EXPIRED = 'expired';\nexport const EVENT_RENEWED = 'renewed';\nexport const EVENT_ADDED = 'added';\nexport const EVENT_REMOVED = 'removed';\nexport const EVENT_ERROR = 'error';\nexport const EVENT_SET_STORAGE = 'set_storage';\n\nexport declare type TokenManagerErrorEventHandler = (error: TokenManagerError) => void;\nexport declare type TokenManagerEventHandler = (key: string, token: Token) => void;\nexport declare type TokenManagerRenewEventHandler = (key: string, token: Token, oldtoken: Token) => void;\nexport declare type TokenManagerSetStorageEventHandler = (storage: Tokens) => void;\n\nexport declare type TokenManagerAnyEventHandler = TokenManagerErrorEventHandler | TokenManagerRenewEventHandler | TokenManagerSetStorageEventHandler | TokenManagerEventHandler;\nexport declare type TokenManagerAnyEvent = typeof EVENT_RENEWED | typeof EVENT_ERROR | typeof EVENT_SET_STORAGE | typeof EVENT_EXPIRED | typeof EVENT_ADDED | typeof EVENT_REMOVED;\n\n// only add methods needed internally\nexport interface TokenManagerInterface {\n on(event: typeof EVENT_RENEWED, handler: TokenManagerRenewEventHandler, context?: object): void;\n on(event: typeof EVENT_ERROR, handler: TokenManagerErrorEventHandler, context?: object): void;\n on(event: typeof EVENT_SET_STORAGE, handler: TokenManagerSetStorageEventHandler, context?: object): void;\n on(event: typeof EVENT_EXPIRED | typeof EVENT_ADDED | typeof EVENT_REMOVED, handler: TokenManagerEventHandler, context?: object): void;\n\n off(event: typeof EVENT_RENEWED, handler?: TokenManagerRenewEventHandler): void;\n off(event: typeof EVENT_ERROR, handler?: TokenManagerErrorEventHandler): void;\n off(event: typeof EVENT_SET_STORAGE, handler?: TokenManagerSetStorageEventHandler): void;\n off(event: typeof EVENT_EXPIRED | typeof EVENT_ADDED | typeof EVENT_REMOVED, handler?: TokenManagerEventHandler): void;\n\n clear(): void;\n setExpireEventTimeout(key: string, token: Token): void;\n clearExpireEventTimeout(key: string): void;\n clearExpireEventTimeoutAll(): void;\n emitAdded(key: string, token: Token): void;\n emitError(error: Error): void;\n emitRemoved(key: string, token: Token): void;\n emitRenewed(key: string, token: Token, oldToken?: Token): void;\n renew(key: string): Promise;\n remove(key: string): void;\n hasExpired(token: Token): boolean;\n getExpireTime(token: Token): number;\n\n get(key): Promise;\n getSync(key): Token | undefined;\n getTokens(): Promise;\n getTokensSync(): Tokens;\n setTokens({ accessToken, idToken, refreshToken }: Tokens, accessTokenCb?: AccessTokenCallback, idTokenCb?: IDTokenCallback, refreshTokenCb?: RefreshTokenCallback): void;\n getStorageKeyByType(type: TokenType): string;\n add(key: any, token: Token): void;\n updateRefreshToken(token: RefreshToken);\n removeRefreshToken(): void;\n clearPendingRemoveTokens(): void;\n\n getOptions(): TokenManagerOptions;\n getStorage(): StorageProvider;\n\n start();\n stop();\n isStarted(): boolean;\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\nimport { removeNils, clone } from '../util';\nimport { AuthSdkError } from '../errors';\nimport { validateToken } from '../oidc/util';\nimport { isLocalhost, isIE11OrLess } from '../features';\nimport SdkClock from '../clock';\nimport {\n Token, \n Tokens, \n TokenType, \n TokenManagerOptions, \n isIDToken, \n isAccessToken,\n isRefreshToken,\n TokenManagerErrorEventHandler,\n TokenManagerSetStorageEventHandler,\n TokenManagerRenewEventHandler,\n TokenManagerEventHandler,\n TokenManagerInterface,\n RefreshToken,\n AccessTokenCallback,\n IDTokenCallback,\n RefreshTokenCallback,\n EVENT_RENEWED,\n EVENT_ADDED,\n EVENT_ERROR,\n EVENT_EXPIRED,\n EVENT_REMOVED,\n EVENT_SET_STORAGE,\n TokenManagerAnyEventHandler,\n TokenManagerAnyEvent,\n OktaAuthOAuthInterface\n} from './types';\nimport { REFRESH_TOKEN_STORAGE_KEY, TOKEN_STORAGE_NAME } from '../constants';\nimport { EventEmitter } from '../base/types';\nimport { StorageOptions, StorageProvider, StorageType } from '../storage/types';\n\nconst DEFAULT_OPTIONS = {\n // TODO: remove in next major version - OKTA-473815\n autoRenew: true,\n autoRemove: true,\n syncStorage: true,\n // --- //\n clearPendingRemoveTokens: true,\n storage: undefined, // will use value from storageManager config\n expireEarlySeconds: 30,\n storageKey: TOKEN_STORAGE_NAME\n};\n\ninterface TokenManagerState {\n expireTimeouts: Record;\n renewPromise: Promise | null;\n started?: boolean;\n}\nfunction defaultState(): TokenManagerState {\n return {\n expireTimeouts: {},\n renewPromise: null\n };\n}\nexport class TokenManager implements TokenManagerInterface {\n private sdk: OktaAuthOAuthInterface;\n private clock: SdkClock;\n private emitter: EventEmitter;\n private storage: StorageProvider;\n private state: TokenManagerState;\n private options: TokenManagerOptions;\n\n on(event: typeof EVENT_RENEWED, handler: TokenManagerRenewEventHandler, context?: object): void;\n on(event: typeof EVENT_ERROR, handler: TokenManagerErrorEventHandler, context?: object): void;\n on(event: typeof EVENT_SET_STORAGE, handler: TokenManagerSetStorageEventHandler, context?: object): void;\n on(event: typeof EVENT_EXPIRED | typeof EVENT_ADDED | typeof EVENT_REMOVED, \n handler: TokenManagerEventHandler, context?: object): void;\n on(event: TokenManagerAnyEvent, handler: TokenManagerAnyEventHandler, context?: object): void {\n if (context) {\n this.emitter.on(event, handler, context);\n } else {\n this.emitter.on(event, handler);\n }\n }\n\n off(event: typeof EVENT_RENEWED, handler?: TokenManagerRenewEventHandler): void;\n off(event: typeof EVENT_ERROR, handler?: TokenManagerErrorEventHandler): void;\n off(event: typeof EVENT_SET_STORAGE, handler?: TokenManagerSetStorageEventHandler): void;\n off(event: typeof EVENT_EXPIRED | typeof EVENT_ADDED | typeof EVENT_REMOVED, \n handler?: TokenManagerEventHandler): void;\n off(event: TokenManagerAnyEvent, handler?: TokenManagerAnyEventHandler): void {\n if (handler) {\n this.emitter.off(event, handler);\n } else {\n this.emitter.off(event);\n }\n }\n\n // eslint-disable-next-line complexity\n constructor(sdk: OktaAuthOAuthInterface, options: TokenManagerOptions = {}) {\n this.sdk = sdk;\n this.emitter = (sdk as any).emitter;\n if (!this.emitter) {\n throw new AuthSdkError('Emitter should be initialized before TokenManager');\n }\n \n options = Object.assign({}, DEFAULT_OPTIONS, removeNils(options));\n if (!isLocalhost()) {\n options.expireEarlySeconds = DEFAULT_OPTIONS.expireEarlySeconds;\n }\n\n this.options = options;\n\n const storageOptions: StorageOptions = removeNils({\n storageKey: options.storageKey,\n secure: options.secure,\n });\n if (typeof options.storage === 'object') {\n // A custom storage provider must implement getItem(key) and setItem(key, val)\n storageOptions.storageProvider = options.storage;\n } else if (options.storage) {\n storageOptions.storageType = options.storage as StorageType;\n }\n\n this.storage = sdk.storageManager.getTokenStorage({...storageOptions, useSeparateCookies: true});\n this.clock = SdkClock.create(/* sdk, options */);\n this.state = defaultState();\n }\n\n start() {\n if (this.options.clearPendingRemoveTokens) {\n this.clearPendingRemoveTokens();\n }\n this.setExpireEventTimeoutAll();\n this.state.started = true;\n }\n \n stop() {\n this.clearExpireEventTimeoutAll();\n this.state.started = false;\n }\n\n isStarted() {\n return !!this.state.started;\n }\n\n getOptions(): TokenManagerOptions {\n return clone(this.options);\n }\n \n getExpireTime(token) {\n const expireEarlySeconds = this.options.expireEarlySeconds || 0;\n var expireTime = token.expiresAt - expireEarlySeconds;\n return expireTime;\n }\n \n hasExpired(token) {\n var expireTime = this.getExpireTime(token);\n return expireTime <= this.clock.now();\n }\n \n emitExpired(key, token) {\n this.emitter.emit(EVENT_EXPIRED, key, token);\n }\n \n emitRenewed(key, freshToken, oldToken) {\n this.emitter.emit(EVENT_RENEWED, key, freshToken, oldToken);\n }\n \n emitAdded(key, token) {\n this.emitter.emit(EVENT_ADDED, key, token);\n }\n \n emitRemoved(key, token?) {\n this.emitter.emit(EVENT_REMOVED, key, token);\n }\n \n emitError(error) {\n this.emitter.emit(EVENT_ERROR, error);\n }\n \n clearExpireEventTimeout(key) {\n clearTimeout(this.state.expireTimeouts[key] as any);\n delete this.state.expireTimeouts[key];\n \n // Remove the renew promise (if it exists)\n this.state.renewPromise = null;\n }\n \n clearExpireEventTimeoutAll() {\n var expireTimeouts = this.state.expireTimeouts;\n for (var key in expireTimeouts) {\n if (!Object.prototype.hasOwnProperty.call(expireTimeouts, key)) {\n continue;\n }\n this.clearExpireEventTimeout(key);\n }\n }\n \n setExpireEventTimeout(key, token) {\n if (isRefreshToken(token)) {\n return;\n }\n\n var expireTime = this.getExpireTime(token);\n var expireEventWait = Math.max(expireTime - this.clock.now(), 0) * 1000;\n \n // Clear any existing timeout\n this.clearExpireEventTimeout(key);\n \n var expireEventTimeout = setTimeout(() => {\n this.emitExpired(key, token);\n }, expireEventWait);\n \n // Add a new timeout\n this.state.expireTimeouts[key] = expireEventTimeout;\n }\n \n setExpireEventTimeoutAll() {\n var tokenStorage = this.storage.getStorage();\n for(var key in tokenStorage) {\n if (!Object.prototype.hasOwnProperty.call(tokenStorage, key)) {\n continue;\n }\n var token = tokenStorage[key];\n this.setExpireEventTimeout(key, token);\n }\n }\n \n // reset timeouts to setup autoRenew for tokens from other document context (tabs)\n resetExpireEventTimeoutAll() {\n this.clearExpireEventTimeoutAll();\n this.setExpireEventTimeoutAll();\n }\n \n add(key, token: Token) {\n var tokenStorage = this.storage.getStorage();\n validateToken(token);\n tokenStorage[key] = token;\n this.storage.setStorage(tokenStorage);\n this.emitSetStorageEvent();\n this.emitAdded(key, token);\n this.setExpireEventTimeout(key, token);\n }\n \n getSync(key): Token | undefined {\n var tokenStorage = this.storage.getStorage();\n return tokenStorage[key];\n }\n \n async get(key): Promise {\n return this.getSync(key);\n }\n \n getTokensSync(): Tokens {\n const tokens = {} as Tokens;\n const tokenStorage = this.storage.getStorage();\n Object.keys(tokenStorage).forEach(key => {\n const token = tokenStorage[key];\n if (isAccessToken(token)) {\n tokens.accessToken = token;\n } else if (isIDToken(token)) {\n tokens.idToken = token;\n } else if (isRefreshToken(token)) { \n tokens.refreshToken = token;\n }\n });\n return tokens;\n }\n \n async getTokens(): Promise {\n return this.getTokensSync();\n }\n\n getStorageKeyByType(type: TokenType): string {\n const tokenStorage = this.storage.getStorage();\n const key = Object.keys(tokenStorage).filter(key => {\n const token = tokenStorage[key];\n return (isAccessToken(token) && type === 'accessToken') \n || (isIDToken(token) && type === 'idToken')\n || (isRefreshToken(token) && type === 'refreshToken');\n })[0];\n return key;\n }\n\n private getTokenType(token: Token): TokenType {\n if (isAccessToken(token)) {\n return 'accessToken';\n }\n if (isIDToken(token)) {\n return 'idToken';\n }\n if(isRefreshToken(token)) {\n return 'refreshToken';\n }\n throw new AuthSdkError('Unknown token type');\n }\n\n // for synchronization of LocalStorage cross tabs for IE11\n private emitSetStorageEvent() {\n if (isIE11OrLess()) {\n const storage = this.storage.getStorage();\n this.emitter.emit(EVENT_SET_STORAGE, storage);\n }\n }\n\n // used in `SyncStorageService` for synchronization of LocalStorage cross tabs for IE11\n public getStorage() {\n return this.storage;\n }\n\n setTokens(\n tokens: Tokens,\n // TODO: callbacks can be removed in the next major version OKTA-407224\n accessTokenCb?: AccessTokenCallback, \n idTokenCb?: IDTokenCallback,\n refreshTokenCb?: RefreshTokenCallback\n ): void {\n const handleTokenCallback = (key, token) => {\n const type = this.getTokenType(token);\n if (type === 'accessToken') {\n accessTokenCb && accessTokenCb(key, token);\n } else if (type === 'idToken') {\n idTokenCb && idTokenCb(key, token);\n } else if (type === 'refreshToken') {\n refreshTokenCb && refreshTokenCb(key, token);\n }\n };\n const handleAdded = (key, token) => {\n this.emitAdded(key, token);\n this.setExpireEventTimeout(key, token);\n handleTokenCallback(key, token);\n };\n const handleRenewed = (key, token, oldToken) => {\n this.emitRenewed(key, token, oldToken);\n this.clearExpireEventTimeout(key);\n this.setExpireEventTimeout(key, token);\n handleTokenCallback(key, token);\n };\n const handleRemoved = (key, token) => {\n this.clearExpireEventTimeout(key);\n this.emitRemoved(key, token);\n handleTokenCallback(key, token);\n };\n \n const types: TokenType[] = ['idToken', 'accessToken', 'refreshToken'];\n const existingTokens = this.getTokensSync();\n\n // valid tokens\n types.forEach((type) => {\n const token = tokens[type];\n if (token) {\n validateToken(token, type);\n }\n });\n \n // add token to storage\n const storage = types.reduce((storage, type) => {\n const token = tokens[type];\n if (token) {\n const storageKey = this.getStorageKeyByType(type) || type;\n storage[storageKey] = token;\n }\n return storage;\n }, {});\n this.storage.setStorage(storage);\n this.emitSetStorageEvent();\n\n // emit event and start expiration timer\n types.forEach(type => {\n const newToken = tokens[type];\n const existingToken = existingTokens[type];\n const storageKey = this.getStorageKeyByType(type) || type;\n if (newToken && existingToken) { // renew\n // call handleRemoved first, since it clears timers\n handleRemoved(storageKey, existingToken);\n handleAdded(storageKey, newToken);\n handleRenewed(storageKey, newToken, existingToken);\n } else if (newToken) { // add\n handleAdded(storageKey, newToken);\n } else if (existingToken) { //remove\n handleRemoved(storageKey, existingToken);\n }\n });\n }\n \n remove(key) {\n // Clear any listener for this token\n this.clearExpireEventTimeout(key);\n \n var tokenStorage = this.storage.getStorage();\n var removedToken = tokenStorage[key];\n delete tokenStorage[key];\n this.storage.setStorage(tokenStorage);\n this.emitSetStorageEvent();\n \n this.emitRemoved(key, removedToken);\n }\n \n // TODO: this methods is redundant and can be removed in the next major version OKTA-407224\n async renewToken(token) {\n return this.sdk.token?.renew(token);\n }\n // TODO: this methods is redundant and can be removed in the next major version OKTA-407224\n validateToken(token: Token) {\n return validateToken(token);\n }\n\n // TODO: renew method should take no param, change in the next major version OKTA-407224\n renew(key): Promise {\n // Multiple callers may receive the same promise. They will all resolve or reject from the same request.\n if (this.state.renewPromise) {\n return this.state.renewPromise;\n }\n\n try {\n var token = this.getSync(key);\n let shouldRenew = token !== undefined;\n // explicitly check if key='accessToken' because token keys are not guaranteed (long story, features dragons)\n if (!token && key === 'accessToken') {\n // attempt token renewal if refresh token is present (improves consistency of autoRenew)\n const refreshKey = this.getStorageKeyByType('refreshToken');\n const refreshToken = this.getSync(refreshKey);\n shouldRenew = refreshToken !== undefined;\n }\n\n if (!shouldRenew) {\n throw new AuthSdkError('The tokenManager has no token for the key: ' + key);\n }\n }\n catch (err) {\n this.emitError(err);\n return Promise.reject(err);\n }\n\n // Remove existing autoRenew timeout\n this.clearExpireEventTimeout(key);\n \n // A refresh token means a replace instead of renewal\n // Store the renew promise state, to avoid renewing again\n const renewPromise = this.state.renewPromise = this.sdk.token.renewTokens()\n .then(tokens => {\n this.setTokens(tokens);\n\n // return accessToken in case where access token doesn't exist\n // but refresh token exists\n if (!token && key === 'accessToken') {\n const accessToken = tokens['accessToken'];\n this.emitRenewed(key, accessToken, null);\n return accessToken;\n }\n\n // resolve token based on the key\n const tokenType = this.getTokenType(token!);\n return tokens[tokenType];\n })\n .catch(err => {\n // If renew fails, remove token from storage and emit error\n this.remove(key);\n err.tokenKey = key;\n this.emitError(err);\n throw err;\n })\n .finally(() => {\n // Remove existing promise key\n this.state.renewPromise = null;\n });\n \n return renewPromise;\n }\n \n clear() {\n const tokens = this.getTokensSync();\n this.clearExpireEventTimeoutAll();\n this.storage.clearStorage();\n this.emitSetStorageEvent();\n\n Object.keys(tokens).forEach(key => {\n this.emitRemoved(key, tokens[key]);\n });\n }\n\n clearPendingRemoveTokens() {\n const tokenStorage = this.storage.getStorage();\n const removedTokens = {};\n Object.keys(tokenStorage).forEach(key => {\n if (tokenStorage[key].pendingRemove) {\n removedTokens[key] = tokenStorage[key];\n delete tokenStorage[key];\n }\n });\n this.storage.setStorage(tokenStorage);\n this.emitSetStorageEvent();\n Object.keys(removedTokens).forEach(key => {\n this.clearExpireEventTimeout(key);\n this.emitRemoved(key, removedTokens[key]);\n });\n }\n\n updateRefreshToken(token: RefreshToken) {\n const key = this.getStorageKeyByType('refreshToken') || REFRESH_TOKEN_STORAGE_KEY;\n\n // do not emit any event\n var tokenStorage = this.storage.getStorage();\n validateToken(token);\n tokenStorage[key] = token;\n this.storage.setStorage(tokenStorage);\n this.emitSetStorageEvent();\n }\n\n removeRefreshToken () {\n const key = this.getStorageKeyByType('refreshToken') || REFRESH_TOKEN_STORAGE_KEY;\n this.remove(key);\n }\n\n addPendingRemoveFlags() {\n const tokens = this.getTokensSync();\n Object.keys(tokens).forEach(key => {\n tokens[key].pendingRemove = true;\n });\n this.setTokens(tokens);\n }\n \n}\n", "/* eslint-disable @typescript-eslint/no-non-null-assertion */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\nimport Cookies from 'js-cookie';\nimport AuthSdkError from '../errors/AuthSdkError';\nimport {\n StorageOptions,\n CookieOptions,\n SimpleStorage,\n StorageType,\n StorageUtil,\n} from '../storage/types';\nimport { warn } from '../util';\nimport { isIE11OrLess } from '../features';\n\nexport interface CookieStorage extends SimpleStorage {\n setItem(key: string, value: any, expiresAt?: string | null): void; // can customize expiresAt\n getItem(key?: string): any; // if no key is passed, all cookies are returned\n removeItem(key: string); // remove a cookie\n}\n\nexport interface BrowserStorageUtil extends StorageUtil {\n browserHasLocalStorage(): boolean;\n browserHasSessionStorage(): boolean;\n getStorageByType(storageType: StorageType, options: StorageOptions): SimpleStorage;\n getLocalStorage(): Storage;\n getSessionStorage(): Storage;\n getInMemoryStorage(): SimpleStorage;\n getCookieStorage(options?: StorageOptions): CookieStorage;\n testStorage(storage: any): boolean;\n storage: Cookies;\n inMemoryStore: Record;\n}\n\n// Building this as an object allows us to mock the functions in our tests\nvar storageUtil: BrowserStorageUtil = {\n\n // IE11 bug that Microsoft doesn't plan to fix\n // https://connect.microsoft.com/IE/Feedback/Details/1496040\n browserHasLocalStorage: function() {\n try {\n var storage = this.getLocalStorage();\n return this.testStorage(storage);\n } catch (e) {\n return false;\n }\n },\n\n browserHasSessionStorage: function() {\n try {\n var storage = this.getSessionStorage();\n return this.testStorage(storage);\n } catch (e) {\n return false;\n }\n },\n\n testStorageType: function(storageType: StorageType): boolean {\n var supported = false;\n switch (storageType) {\n case 'sessionStorage':\n supported = this.browserHasSessionStorage();\n break;\n case 'localStorage':\n supported = this.browserHasLocalStorage();\n break;\n case 'cookie':\n case 'memory':\n supported = true;\n break;\n default:\n supported = false;\n break;\n }\n return supported;\n },\n\n getStorageByType: function(storageType: StorageType, options?: StorageOptions): SimpleStorage {\n let storageProvider;\n switch (storageType) {\n case 'sessionStorage':\n storageProvider = this.getSessionStorage();\n break;\n case 'localStorage':\n storageProvider = this.getLocalStorage();\n break;\n case 'cookie':\n storageProvider = this.getCookieStorage(options);\n break;\n case 'memory':\n storageProvider = this.getInMemoryStorage();\n break;\n default:\n throw new AuthSdkError(`Unrecognized storage option: ${storageType}`);\n break;\n }\n return storageProvider;\n },\n\n findStorageType: function(types: StorageType[]) {\n let curType;\n let nextType;\n \n types = types.slice(); // copy array\n curType = types.shift();\n nextType = types.length ? types[0] : null;\n if (!nextType) {\n return curType;\n }\n\n if (this.testStorageType(curType)) {\n return curType;\n }\n\n // preferred type was unsupported.\n warn(`This browser doesn't support ${curType}. Switching to ${nextType}.`);\n\n // fallback to the next type. this is a recursive call\n return this.findStorageType(types);\n },\n\n getLocalStorage: function() {\n // Workaound for synchronization issue of LocalStorage cross tabs in IE11\n if (isIE11OrLess() && !window.onstorage) {\n window.onstorage = function() {};\n }\n \n return localStorage;\n },\n\n getSessionStorage: function() {\n return sessionStorage;\n },\n\n // Provides webStorage-like interface for cookies\n getCookieStorage: function(options): CookieStorage {\n const secure = options!.secure;\n const sameSite = options!.sameSite;\n const sessionCookie = options!.sessionCookie;\n if (typeof secure === 'undefined' || typeof sameSite === 'undefined') {\n throw new AuthSdkError('getCookieStorage: \"secure\" and \"sameSite\" options must be provided');\n }\n const storage: CookieStorage = {\n getItem: this.storage.get,\n setItem: (key, value, expiresAt = '2200-01-01T00:00:00.000Z') => {\n // By defauilt, cookie shouldn't expire\n expiresAt = (sessionCookie ? null : expiresAt) as string;\n this.storage.set(key, value, expiresAt, {\n secure: secure, \n sameSite: sameSite,\n });\n },\n removeItem: (key) => {\n this.storage.delete(key);\n },\n };\n\n if (!options!.useSeparateCookies) {\n return storage;\n }\n\n // Tokens are stored separately because cookies have size limits.\n // Can only be used when storing an object value. Object properties will be saved to separate cookies.\n // Each property of the object must also be an object.\n return {\n getItem: function(key) {\n var data = storage.getItem(); // read all cookies\n var value = {};\n Object.keys(data).forEach(k => {\n if (k.indexOf(key!) === 0) { // filter out unrelated cookies\n value[k.replace(`${key}_`, '')] = JSON.parse(data[k]); // populate with cookie data\n }\n });\n return JSON.stringify(value);\n },\n setItem: function(key, value) {\n var existingValues = JSON.parse(this.getItem(key));\n value = JSON.parse(value);\n // Set key-value pairs from input to cookies\n Object.keys(value).forEach(k => {\n var storageKey = key + '_' + k;\n var valueToStore = JSON.stringify(value[k]);\n storage.setItem(storageKey, valueToStore);\n delete existingValues[k];\n });\n // Delete unmatched keys from existing cookies\n Object.keys(existingValues).forEach(k => {\n storage.removeItem(key + '_' + k);\n });\n },\n removeItem: function(key) {\n var existingValues = JSON.parse(this.getItem(key));\n Object.keys(existingValues).forEach(k => {\n storage.removeItem(key + '_' + k);\n });\n },\n };\n },\n\n // Provides an in-memory solution\n inMemoryStore: {}, // override this for a unique memory store per instance\n getInMemoryStorage: function() {\n return {\n getItem: (key) => {\n return this.inMemoryStore[key];\n },\n setItem: (key, value) => {\n this.inMemoryStore[key] = value;\n },\n };\n },\n\n testStorage: function(storage) {\n var key = 'okta-test-storage';\n try {\n storage.setItem(key, key);\n storage.removeItem(key);\n return true;\n } catch (e) {\n return false;\n }\n },\n\n storage: {\n set: function(name: string, value: string, expiresAt: string, options: CookieOptions): string {\n const { sameSite, secure } = options;\n if (typeof secure === 'undefined' || typeof sameSite === 'undefined') {\n throw new AuthSdkError('storage.set: \"secure\" and \"sameSite\" options must be provided');\n }\n var cookieOptions: CookieOptions = {\n path: options.path || '/',\n secure,\n sameSite\n };\n\n // eslint-disable-next-line no-extra-boolean-cast\n if (!!(Date.parse(expiresAt))) {\n // Expires value can be converted to a Date object.\n //\n // If the 'expiresAt' value is not provided, or the value cannot be\n // parsed as a Date object, the cookie will set as a session cookie.\n cookieOptions.expires = new Date(expiresAt);\n }\n\n Cookies.set(name, value, cookieOptions);\n return this.get(name);\n },\n\n get: function(name?: string): string {\n // return all cookies when no args is provided\n if (!arguments.length) {\n return Cookies.get();\n }\n return Cookies.get(name);\n },\n\n delete: function(name: string): string {\n return Cookies.remove(name, { path: '/' });\n }\n }\n};\n\nexport default storageUtil;\n", "import { REFERRER_PATH_STORAGE_KEY } from '../../constants';\nimport browserStorage from '../../browser/browserStorage';\nimport { OktaAuthStorageInterface } from '../../storage';\nimport { OktaAuthConstructor } from '../../base';\nimport {\n OAuthStorageManagerInterface,\n OAuthTransactionMeta,\n OktaAuthOAuthOptions,\n OriginalUriApi,\n PKCETransactionMeta,\n} from '../types';\n\nexport function provideOriginalUri\n<\n M extends OAuthTransactionMeta = PKCETransactionMeta,\n S extends OAuthStorageManagerInterface = OAuthStorageManagerInterface,\n O extends OktaAuthOAuthOptions = OktaAuthOAuthOptions,\n TBase extends OktaAuthConstructor>\n = OktaAuthConstructor> \n>\n(BaseClass: TBase) {\n return class WithOriginalUri extends BaseClass implements OriginalUriApi {\n setOriginalUri(originalUri: string, state?: string): void {\n // always store in session storage\n const sessionStorage = browserStorage.getSessionStorage();\n sessionStorage.setItem(REFERRER_PATH_STORAGE_KEY, originalUri);\n \n // to support multi-tab flows, set a state in constructor or pass as param\n state = state || this.options.state;\n if (state) {\n const sharedStorage = this.storageManager.getOriginalUriStorage();\n sharedStorage.setItem(state, originalUri);\n }\n }\n \n getOriginalUri(state?: string): string | undefined {\n // Prefer shared storage (if state is available)\n state = state || this.options.state;\n if (state) {\n const sharedStorage = this.storageManager.getOriginalUriStorage();\n const originalUri = sharedStorage.getItem(state);\n if (originalUri) {\n return originalUri;\n }\n }\n \n // Try to load from session storage\n const storage = browserStorage.getSessionStorage();\n return storage ? storage.getItem(REFERRER_PATH_STORAGE_KEY) || undefined : undefined;\n }\n \n removeOriginalUri(state?: string): void {\n // Remove from sessionStorage\n const storage = browserStorage.getSessionStorage();\n storage.removeItem(REFERRER_PATH_STORAGE_KEY);\n \n // Also remove from shared storage\n state = state || this.options.state;\n if (state) {\n const sharedStorage = this.storageManager.getOriginalUriStorage();\n sharedStorage.removeItem && sharedStorage.removeItem(state);\n }\n }\n };\n}\n", "import { httpRequest, RequestOptions } from '../../http';\nimport { OktaAuthConstructor } from '../../base/types';\nimport { \n PromiseQueue,\n isFunction\n} from '../../util';\nimport { CryptoAPI } from '../../crypto/types';\nimport * as crypto from '../../crypto';\nimport {\n AccessToken,\n CustomUserClaims,\n IDToken,\n IsAuthenticatedOptions,\n OAuthResponseType,\n OAuthStorageManagerInterface,\n OAuthTransactionMeta,\n OktaAuthOAuthInterface,\n OktaAuthOAuthOptions,\n PkceAPI,\n PKCETransactionMeta,\n RefreshToken,\n SigninWithRedirectOptions,\n SignoutOptions,\n SignoutRedirectUrlOptions,\n TokenAPI,\n TransactionManagerInterface,\n TransactionManagerConstructor,\n UserClaims,\n Endpoints,\n DPoPRequest,\n DPoPHeaders\n} from '../types';\nimport PKCE from '../util/pkce';\nimport { createEndpoints, createTokenAPI } from '../factory/api';\nimport { TokenManager } from '../TokenManager';\nimport { getOAuthUrls, isLoginRedirect, hasResponseType } from '../util';\nimport { \n generateDPoPProof,\n clearDPoPKeyPair,\n clearAllDPoPKeyPairs,\n clearDPoPKeyPairAfterRevoke,\n findKeyPair,\n isDPoPNonceError\n} from '../dpop';\nimport { AuthSdkError, WWWAuthError } from '../../errors';\n\nimport { OktaAuthSessionInterface } from '../../session/types';\nimport { provideOriginalUri } from './node';\nexport function mixinOAuth\n<\n M extends OAuthTransactionMeta = PKCETransactionMeta,\n S extends OAuthStorageManagerInterface = OAuthStorageManagerInterface,\n O extends OktaAuthOAuthOptions = OktaAuthOAuthOptions,\n TM extends TransactionManagerInterface = TransactionManagerInterface,\n TBase extends OktaAuthConstructor>\n = OktaAuthConstructor>\n>\n(\n Base: TBase,\n TransactionManagerConstructor: TransactionManagerConstructor,\n): TBase & OktaAuthConstructor>\n{\n const WithOriginalUri = provideOriginalUri(Base);\n return class OktaAuthOAuth extends WithOriginalUri\n implements OktaAuthOAuthInterface\n {\n static crypto: CryptoAPI = crypto;\n token: TokenAPI;\n tokenManager: TokenManager;\n transactionManager: TM;\n pkce: PkceAPI;\n endpoints: Endpoints;\n\n _pending: { handleLogin: boolean };\n _tokenQueue: PromiseQueue;\n \n constructor(...args: any[]) {\n super(...args);\n\n this.transactionManager = new TransactionManagerConstructor(Object.assign({\n storageManager: this.storageManager,\n }, this.options.transactionManager));\n \n this.pkce = {\n DEFAULT_CODE_CHALLENGE_METHOD: PKCE.DEFAULT_CODE_CHALLENGE_METHOD,\n generateVerifier: PKCE.generateVerifier,\n computeChallenge: PKCE.computeChallenge\n };\n \n this._pending = { handleLogin: false };\n\n this._tokenQueue = new PromiseQueue();\n\n this.token = createTokenAPI(this, this._tokenQueue);\n\n // TokenManager\n this.tokenManager = new TokenManager(this, this.options.tokenManager);\n\n this.endpoints = createEndpoints(this);\n }\n\n // inherited from subclass\n clearStorage(): void {\n super.clearStorage();\n \n // Clear all local tokens\n this.tokenManager.clear();\n }\n\n // Returns true if both accessToken and idToken are not expired\n // If `autoRenew` option is set, will attempt to renew expired tokens before returning.\n // eslint-disable-next-line complexity\n async isAuthenticated(options: IsAuthenticatedOptions = {}): Promise {\n // TODO: remove dependency on tokenManager options in next major version - OKTA-473815\n const { autoRenew, autoRemove } = this.tokenManager.getOptions();\n\n const shouldRenew = options.onExpiredToken ? options.onExpiredToken === 'renew' : autoRenew;\n const shouldRemove = options.onExpiredToken ? options.onExpiredToken === 'remove' : autoRemove;\n\n let { accessToken } = this.tokenManager.getTokensSync();\n if (accessToken && this.tokenManager.hasExpired(accessToken)) {\n accessToken = undefined;\n if (shouldRenew) {\n try {\n accessToken = await this.tokenManager.renew('accessToken') as AccessToken;\n } catch {\n // Renew errors will emit an \"error\" event \n }\n } else if (shouldRemove) {\n this.tokenManager.remove('accessToken');\n }\n }\n\n let { idToken } = this.tokenManager.getTokensSync();\n if (idToken && this.tokenManager.hasExpired(idToken)) {\n idToken = undefined;\n if (shouldRenew) {\n try {\n idToken = await this.tokenManager.renew('idToken') as IDToken;\n } catch {\n // Renew errors will emit an \"error\" event \n }\n } else if (shouldRemove) {\n this.tokenManager.remove('idToken');\n }\n }\n\n return !!(accessToken && idToken);\n }\n\n\n async signInWithRedirect(opts: SigninWithRedirectOptions = {}) {\n const { originalUri, ...additionalParams } = opts;\n if(this._pending.handleLogin) { \n // Don't trigger second round\n return;\n }\n\n this._pending.handleLogin = true;\n try {\n // Trigger default signIn redirect flow\n if (originalUri) {\n this.setOriginalUri(originalUri);\n }\n const params = Object.assign({\n // TODO: remove this line when default scopes are changed OKTA-343294\n scopes: this.options.scopes || ['openid', 'email', 'profile']\n }, additionalParams);\n await this.token.getWithRedirect(params);\n } finally {\n this._pending.handleLogin = false;\n }\n }\n\n async getUser(): Promise> {\n const { idToken, accessToken } = this.tokenManager.getTokensSync();\n return this.token.getUserInfo(accessToken, idToken);\n }\n \n getIdToken(): string | undefined {\n const { idToken } = this.tokenManager.getTokensSync();\n return idToken ? idToken.idToken : undefined;\n }\n \n getAccessToken(): string | undefined {\n const { accessToken } = this.tokenManager.getTokensSync();\n return accessToken ? accessToken.accessToken : undefined;\n }\n \n getRefreshToken(): string | undefined {\n const { refreshToken } = this.tokenManager.getTokensSync();\n return refreshToken ? refreshToken.refreshToken : undefined;\n }\n\n async getOrRenewAccessToken(): Promise {\n const { accessToken } = this.tokenManager.getTokensSync();\n if (accessToken && !this.tokenManager.hasExpired(accessToken)) {\n return accessToken.accessToken;\n }\n try {\n const key = this.tokenManager.getStorageKeyByType('accessToken');\n const token = await this.tokenManager.renew(key ?? 'accessToken');\n return (token as AccessToken)?.accessToken ?? null;\n }\n catch (err) {\n this.emitter.emit('error', err);\n return null;\n }\n }\n \n /**\n * Store parsed tokens from redirect url\n */\n async storeTokensFromRedirect(): Promise {\n const { tokens, responseType } = await this.token.parseFromUrl();\n if (responseType !== 'none') {\n this.tokenManager.setTokens(tokens);\n }\n }\n \n isLoginRedirect(): boolean {\n return isLoginRedirect(this);\n }\n\n isPKCE(): boolean {\n return !!this.options.pkce;\n }\n\n hasResponseType(responseType: OAuthResponseType): boolean {\n return hasResponseType(responseType, this.options);\n }\n \n isAuthorizationCodeFlow(): boolean {\n return this.hasResponseType('code');\n }\n\n // Escape hatch method to make arbitrary OKTA API call\n async invokeApiMethod(options: RequestOptions): Promise {\n if (!options.accessToken) {\n const accessToken = (await this.tokenManager.getTokens()).accessToken as AccessToken;\n options.accessToken = accessToken?.accessToken;\n }\n return httpRequest(this, options);\n }\n \n // Revokes the access token for the application session\n async revokeAccessToken(accessToken?: AccessToken): Promise {\n if (!accessToken) {\n const tokens = await this.tokenManager.getTokens();\n accessToken = tokens.accessToken;\n const accessTokenKey = this.tokenManager.getStorageKeyByType('accessToken');\n this.tokenManager.remove(accessTokenKey);\n\n if (this.options.dpop) {\n await clearDPoPKeyPairAfterRevoke('access', tokens);\n }\n }\n // Access token may have been removed. In this case, we will silently succeed.\n if (!accessToken) {\n return Promise.resolve(null);\n }\n return this.token.revoke(accessToken);\n }\n\n // Revokes the refresh token for the application session\n async revokeRefreshToken(refreshToken?: RefreshToken): Promise {\n if (!refreshToken) {\n const tokens = await this.tokenManager.getTokens();\n refreshToken = tokens.refreshToken;\n const refreshTokenKey = this.tokenManager.getStorageKeyByType('refreshToken');\n this.tokenManager.remove(refreshTokenKey);\n\n if (this.options.dpop) {\n await clearDPoPKeyPairAfterRevoke('refresh', tokens);\n }\n }\n // Refresh token may have been removed. In this case, we will silently succeed.\n if (!refreshToken) {\n return Promise.resolve(null);\n }\n return this.token.revoke(refreshToken);\n }\n\n getSignOutRedirectUrl(options: SignoutRedirectUrlOptions = {}) {\n let {\n idToken,\n postLogoutRedirectUri,\n state,\n } = options;\n if (!idToken) {\n idToken = this.tokenManager.getTokensSync().idToken as IDToken;\n }\n if (!idToken) {\n return '';\n }\n if (postLogoutRedirectUri === undefined) {\n postLogoutRedirectUri = this.options.postLogoutRedirectUri;\n }\n\n const logoutUrl = getOAuthUrls(this).logoutUrl;\n const idTokenHint = idToken.idToken; // a string\n let logoutUri = logoutUrl + '?id_token_hint=' + encodeURIComponent(idTokenHint);\n if (postLogoutRedirectUri) {\n logoutUri += '&post_logout_redirect_uri=' + encodeURIComponent(postLogoutRedirectUri);\n } \n // State allows option parameters to be passed to logout redirect uri\n if (state) {\n logoutUri += '&state=' + encodeURIComponent(state);\n }\n\n return logoutUri;\n }\n\n // Revokes refreshToken or accessToken, clears all local tokens, then redirects to Okta to end the SSO session.\n // eslint-disable-next-line complexity, max-statements\n async signOut(options?: SignoutOptions): Promise {\n options = Object.assign({}, options);\n \n // postLogoutRedirectUri must be whitelisted in Okta Admin UI\n const defaultUri = window.location.origin;\n const currentUri = window.location.href;\n // Fix for issue/1410 - allow for no postLogoutRedirectUri to be passed, resulting in /logout default behavior\n // \"If no Okta session exists, this endpoint has no effect and the browser is redirected immediately to the\n // Okta sign-in page or the post_logout_redirect_uri (if specified).\"\n // - https://developer.okta.com/docs/reference/api/oidc/#logout\n const postLogoutRedirectUri = options.postLogoutRedirectUri === null ? null :\n (options.postLogoutRedirectUri\n || this.options.postLogoutRedirectUri\n || defaultUri);\n const state = options?.state;\n \n \n let accessToken = options.accessToken;\n let refreshToken = options.refreshToken;\n const revokeAccessToken = options.revokeAccessToken !== false;\n const revokeRefreshToken = options.revokeRefreshToken !== false;\n \n if (revokeRefreshToken && typeof refreshToken === 'undefined') {\n refreshToken = this.tokenManager.getTokensSync().refreshToken as RefreshToken;\n }\n\n if (revokeAccessToken && typeof accessToken === 'undefined') {\n accessToken = this.tokenManager.getTokensSync().accessToken as AccessToken;\n }\n \n if (!options.idToken) {\n options.idToken = this.tokenManager.getTokensSync().idToken as IDToken;\n }\n\n if (revokeRefreshToken && refreshToken) {\n await this.revokeRefreshToken(refreshToken);\n }\n\n if (revokeAccessToken && accessToken) {\n await this.revokeAccessToken(accessToken);\n }\n\n const dpopPairId = accessToken?.dpopPairId ?? refreshToken?.dpopPairId;\n if (this.options.dpop && dpopPairId) {\n await clearDPoPKeyPair(dpopPairId);\n }\n\n const logoutUri = this.getSignOutRedirectUrl({ ...options, postLogoutRedirectUri });\n // No logoutUri? This can happen if the storage was cleared.\n // Fallback to XHR signOut, then simulate a redirect to the post logout uri\n if (!logoutUri) {\n // local tokens are cleared once session is closed\n const sessionClosed = await this.closeSession(); // can throw if the user cannot be signed out\n const redirectUri = new URL(postLogoutRedirectUri || defaultUri); // during fallback, redirectUri cannot be null\n if (state) {\n redirectUri.searchParams.append('state', state);\n }\n if (postLogoutRedirectUri === currentUri) {\n // window.location.reload(); // force a hard reload if URI is not changing\n window.location.href = redirectUri.href;\n } else {\n window.location.assign(redirectUri.href);\n }\n return sessionClosed;\n } else {\n if (options.clearTokensBeforeRedirect) {\n // Clear all local tokens\n this.tokenManager.clear();\n } else {\n this.tokenManager.addPendingRemoveFlags();\n }\n // Flow ends with logout redirect\n window.location.assign(logoutUri);\n return true;\n }\n }\n\n async getDPoPAuthorizationHeaders (params: DPoPRequest): Promise {\n if (!this.options.dpop) {\n throw new AuthSdkError('DPoP is not configured for this client instance');\n }\n\n let { accessToken } = params;\n if (!accessToken) {\n accessToken = (this.tokenManager.getTokensSync()).accessToken;\n }\n\n if (!accessToken) {\n throw new AuthSdkError('AccessToken is required to generate a DPoP Proof');\n }\n\n const keyPair = await findKeyPair(accessToken?.dpopPairId);\n const proof = await generateDPoPProof({...params, keyPair, accessToken: accessToken.accessToken});\n return {\n Authorization: `DPoP ${accessToken.accessToken}`,\n Dpop: proof\n };\n }\n\n async clearDPoPStorage (clearAll=false): Promise {\n if (clearAll) {\n return clearAllDPoPKeyPairs();\n }\n\n const tokens = await this.tokenManager.getTokens();\n const keyPair = tokens.accessToken?.dpopPairId || tokens.refreshToken?.dpopPairId;\n\n if (keyPair) {\n await clearDPoPKeyPair(keyPair);\n }\n }\n\n parseUseDPoPNonceError (headers: HeadersInit): string | null {\n const wwwAuth = WWWAuthError.getWWWAuthenticateHeader(headers);\n const wwwErr = WWWAuthError.parseHeader(wwwAuth ?? '');\n if (isDPoPNonceError(wwwErr)) {\n let nonce: string | null = null;\n if (isFunction((headers as Headers)?.get)) {\n nonce = (headers as Headers).get('DPoP-Nonce');\n }\n nonce = nonce ?? headers['dpop-nonce'] ?? headers['DPoP-Nonce'];\n return nonce;\n }\n\n return null;\n }\n };\n\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n \n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore \n// Do not use this type in code, so it won't be emitted in the declaration output\nimport PCancelable from 'p-cancelable';\nimport { AuthSdkError } from '../errors';\nimport {\n EVENT_ADDED,\n EVENT_REMOVED,\n OAuthStorageManagerInterface,\n OAuthTransactionMeta,\n OktaAuthOAuthInterface\n} from '../oidc';\nimport {\n AuthState,\n AuthStateLogOptions,\n OktaAuthCoreOptions,\n} from './types';\nimport { PromiseQueue, getConsole } from '../util';\n\nexport const INITIAL_AUTH_STATE = null;\nconst DEFAULT_PENDING = {\n updateAuthStatePromise: null,\n canceledTimes: 0\n};\nconst EVENT_AUTH_STATE_CHANGE = 'authStateChange';\nconst MAX_PROMISE_CANCEL_TIMES = 10;\n\n// only compare first level of authState\nconst isSameAuthState = (prevState: AuthState | null, state: AuthState) => {\n // initial state is null\n if (!prevState) {\n return false;\n }\n\n return prevState.isAuthenticated === state.isAuthenticated \n && JSON.stringify(prevState.idToken) === JSON.stringify(state.idToken)\n && JSON.stringify(prevState.accessToken) === JSON.stringify(state.accessToken)\n && prevState.error === state.error;\n};\n\n\nexport class AuthStateManager\n<\n M extends OAuthTransactionMeta,\n S extends OAuthStorageManagerInterface,\n O extends OktaAuthCoreOptions\n>\n{\n _sdk: OktaAuthOAuthInterface;\n _pending: { \n updateAuthStatePromise: any;\n canceledTimes: number; \n };\n _authState: AuthState | null;\n _prevAuthState: AuthState | null;\n _logOptions: AuthStateLogOptions;\n _transformQueue: PromiseQueue;\n\n constructor(sdk: OktaAuthOAuthInterface) {\n if (!sdk.emitter) {\n throw new AuthSdkError('Emitter should be initialized before AuthStateManager');\n }\n\n this._sdk = sdk;\n this._pending = { ...DEFAULT_PENDING };\n this._authState = INITIAL_AUTH_STATE;\n this._logOptions = {};\n this._prevAuthState = null;\n this._transformQueue = new PromiseQueue({\n quiet: true\n });\n\n // Listen on tokenManager events to start updateState process\n // \"added\" event is emitted in both add and renew process\n // Only listen on \"added\" event to update auth state\n sdk.tokenManager.on(EVENT_ADDED, (key, token) => {\n this._setLogOptions({ event: EVENT_ADDED, key, token });\n this.updateAuthState();\n });\n sdk.tokenManager.on(EVENT_REMOVED, (key, token) => {\n this._setLogOptions({ event: EVENT_REMOVED, key, token });\n this.updateAuthState();\n });\n }\n\n _setLogOptions(options) {\n this._logOptions = options;\n }\n\n getAuthState(): AuthState | null {\n return this._authState;\n }\n\n getPreviousAuthState(): AuthState | null {\n return this._prevAuthState;\n }\n\n async updateAuthState(): Promise {\n const { transformAuthState, devMode } = this._sdk.options;\n\n const log = (status) => {\n const { event, key, token } = this._logOptions;\n getConsole().group(`OKTA-AUTH-JS:updateAuthState: Event:${event} Status:${status}`);\n getConsole().log(key, token);\n getConsole().log('Current authState', this._authState);\n getConsole().groupEnd();\n \n // clear log options after logging\n this._logOptions = {};\n };\n\n const emitAuthStateChange = (authState) => {\n if (isSameAuthState(this._authState, authState)) {\n devMode && log('unchanged'); \n return;\n }\n this._prevAuthState = this._authState;\n this._authState = authState;\n // emit new authState object\n this._sdk.emitter.emit(EVENT_AUTH_STATE_CHANGE, { ...authState });\n devMode && log('emitted');\n };\n\n const finalPromise = (origPromise) => { \n return this._pending.updateAuthStatePromise.then(() => {\n const curPromise = this._pending.updateAuthStatePromise;\n if (curPromise && curPromise !== origPromise) {\n return finalPromise(curPromise);\n }\n return this.getAuthState();\n });\n };\n\n if (this._pending.updateAuthStatePromise) {\n if (this._pending.canceledTimes >= MAX_PROMISE_CANCEL_TIMES) {\n // stop canceling then starting a new promise\n // let existing promise finish to prevent running into loops\n devMode && log('terminated');\n return finalPromise(this._pending.updateAuthStatePromise);\n } else {\n this._pending.updateAuthStatePromise.cancel();\n }\n }\n\n /* eslint-disable complexity */\n const cancelablePromise = new PCancelable((resolve, _, onCancel) => {\n onCancel.shouldReject = false;\n onCancel(() => {\n this._pending.updateAuthStatePromise = null;\n this._pending.canceledTimes = this._pending.canceledTimes + 1;\n devMode && log('canceled');\n });\n\n const emitAndResolve = (authState) => {\n if (cancelablePromise.isCanceled) {\n resolve();\n return;\n }\n // emit event and resolve promise \n emitAuthStateChange(authState);\n resolve();\n\n // clear pending states after resolve\n this._pending = { ...DEFAULT_PENDING };\n };\n\n this._sdk.isAuthenticated()\n .then(() => {\n if (cancelablePromise.isCanceled) {\n resolve();\n return;\n }\n\n const { accessToken, idToken, refreshToken } = this._sdk.tokenManager.getTokensSync();\n const authState = {\n accessToken,\n idToken,\n refreshToken,\n isAuthenticated: !!(accessToken && idToken)\n };\n\n // Enqueue transformAuthState so that it does not run concurrently\n const promise: Promise = transformAuthState\n ? this._transformQueue.push(transformAuthState, null, this._sdk, authState) as Promise\n : Promise.resolve(authState);\n\n promise\n .then(authState => emitAndResolve(authState))\n .catch(error => emitAndResolve({\n accessToken, \n idToken, \n refreshToken,\n isAuthenticated: false, \n error\n }));\n });\n });\n /* eslint-enable complexity */\n this._pending.updateAuthStatePromise = cancelablePromise;\n\n return finalPromise(cancelablePromise);\n }\n\n subscribe(handler): void {\n this._sdk.emitter.on(EVENT_AUTH_STATE_CHANGE, handler);\n }\n\n unsubscribe(handler?): void {\n this._sdk.emitter.off(EVENT_AUTH_STATE_CHANGE, handler);\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { AuthSdkError } from '../errors';\nimport { ServiceInterface, ServiceManagerOptions } from '../core/types';\nimport { EVENT_EXPIRED, TokenManagerInterface, isRefreshToken } from '../oidc/types';\nimport { isBrowser } from '../features';\n\nexport class AutoRenewService implements ServiceInterface {\n private tokenManager: TokenManagerInterface;\n private options: ServiceManagerOptions;\n private renewTimeQueue: Array;\n private started = false;\n\n constructor(tokenManager: TokenManagerInterface, options: ServiceManagerOptions = {}) {\n this.tokenManager = tokenManager;\n this.options = options;\n this.renewTimeQueue = [];\n this.onTokenExpiredHandler = this.onTokenExpiredHandler.bind(this);\n }\n \n private shouldThrottleRenew(): boolean {\n let res = false;\n this.renewTimeQueue.push(Date.now());\n if (this.renewTimeQueue.length >= 10) {\n // get and remove first item from queue\n const firstTime = this.renewTimeQueue.shift() as number;\n const lastTime = this.renewTimeQueue[this.renewTimeQueue.length - 1];\n res = (lastTime - firstTime) < 30 * 1000;\n }\n return res;\n }\n\n requiresLeadership() {\n // If tokens sync storage is enabled, handle tokens expiration only in 1 leader tab\n return !!this.options.syncStorage && isBrowser();\n }\n\n private processExpiredTokens() {\n const tokenStorage = this.tokenManager.getStorage();\n const tokens = tokenStorage.getStorage();\n Object.keys(tokens).forEach(key => {\n const token = tokens[key];\n if (!isRefreshToken(token) && this.tokenManager.hasExpired(token)) {\n this.onTokenExpiredHandler(key);\n }\n });\n }\n\n private onTokenExpiredHandler(key: string) {\n if (this.options.autoRenew) {\n if (this.shouldThrottleRenew()) {\n const error = new AuthSdkError('Too many token renew requests');\n this.tokenManager.emitError(error);\n } else {\n this.tokenManager.renew(key).catch(() => {}); // Renew errors will emit an \"error\" event \n }\n } else if (this.options.autoRemove) {\n this.tokenManager.remove(key);\n }\n }\n\n canStart() {\n return (!!this.options.autoRenew || !!this.options.autoRemove) && !this.started;\n }\n\n async start() {\n if (this.canStart()) {\n this.tokenManager.on(EVENT_EXPIRED, this.onTokenExpiredHandler);\n if (this.tokenManager.isStarted()) {\n // If token manager has been already started, we could miss token expire events,\n // so need to process expired tokens manually.\n this.processExpiredTokens();\n }\n this.started = true;\n }\n }\n\n async stop() {\n if (this.started) {\n this.tokenManager.off(EVENT_EXPIRED, this.onTokenExpiredHandler);\n this.renewTimeQueue = [];\n this.started = false;\n }\n }\n\n isStarted() {\n return this.started;\n }\n}\n", "/**\n * returns true if the given object is a promise\n */\nexport function isPromise(obj) {\n return obj && typeof obj.then === 'function';\n}\nexport var PROMISE_RESOLVED_FALSE = Promise.resolve(false);\nexport var PROMISE_RESOLVED_TRUE = Promise.resolve(true);\nexport var PROMISE_RESOLVED_VOID = Promise.resolve();\nexport function sleep(time, resolveWith) {\n if (!time) time = 0;\n return new Promise(function (res) {\n return setTimeout(function () {\n return res(resolveWith);\n }, time);\n });\n}\nexport function randomInt(min, max) {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n\n/**\n * https://stackoverflow.com/a/8084248\n */\nexport function randomToken() {\n return Math.random().toString(36).substring(2);\n}\nvar lastMs = 0;\nvar additional = 0;\n\n/**\n * returns the current time in micro-seconds,\n * WARNING: This is a pseudo-function\n * Performance.now is not reliable in webworkers, so we just make sure to never return the same time.\n * This is enough in browsers, and this function will not be used in nodejs.\n * The main reason for this hack is to ensure that BroadcastChannel behaves equal to production when it is used in fast-running unit tests.\n */\nexport function microSeconds() {\n var ms = new Date().getTime();\n if (ms === lastMs) {\n additional++;\n return ms * 1000 + additional;\n } else {\n lastMs = ms;\n additional = 0;\n return ms * 1000;\n }\n}\n\n/**\n * Check if WebLock API is supported.\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API\n */\nexport function supportsWebLockAPI() {\n if (typeof navigator !== 'undefined' && typeof navigator.locks !== 'undefined' && typeof navigator.locks.request === 'function') {\n return true;\n } else {\n return false;\n }\n}", "import { microSeconds as micro, PROMISE_RESOLVED_VOID } from '../util.js';\nexport var microSeconds = micro;\nexport var type = 'native';\nexport function create(channelName) {\n var state = {\n messagesCallback: null,\n bc: new BroadcastChannel(channelName),\n subFns: [] // subscriberFunctions\n };\n\n state.bc.onmessage = function (msg) {\n if (state.messagesCallback) {\n state.messagesCallback(msg.data);\n }\n };\n return state;\n}\nexport function close(channelState) {\n channelState.bc.close();\n channelState.subFns = [];\n}\nexport function postMessage(channelState, messageJson) {\n try {\n channelState.bc.postMessage(messageJson, false);\n return PROMISE_RESOLVED_VOID;\n } catch (err) {\n return Promise.reject(err);\n }\n}\nexport function onMessage(channelState, fn) {\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n if ((typeof window !== 'undefined' || typeof self !== 'undefined') && typeof BroadcastChannel === 'function') {\n if (BroadcastChannel._pubkey) {\n throw new Error('BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill');\n }\n return true;\n } else {\n return false;\n }\n}\nexport function averageResponseTime() {\n return 150;\n}\nexport var NativeMethod = {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};", "\n/**\n * this is a set which automatically forgets\n * a given entry when a new entry is set and the ttl\n * of the old one is over\n */\nexport class ObliviousSet {\n public readonly map = new Map();\n\n /**\n * Creating calls to setTimeout() is expensive,\n * so we only do that if there is not timeout already open.\n */\n public _to: boolean = false;\n constructor(\n public readonly ttl: number\n ) { }\n\n has(value: T): boolean {\n return this.map.has(value);\n }\n\n add(value: T): void {\n this.map.set(value, now());\n\n /**\n * When a new value is added,\n * start the cleanup at the next tick\n * to not block the cpu for more important stuff\n * that might happen.\n */\n if (!this._to) {\n this._to = true;\n setTimeout(() => {\n this._to = false;\n removeTooOldValues(this);\n }, 0);\n }\n }\n\n clear() {\n this.map.clear();\n }\n}\n\n\n/**\n * Removes all entries from the set\n * where the TTL has expired\n */\nexport function removeTooOldValues(\n obliviousSet: ObliviousSet\n) {\n const olderThen = now() - obliviousSet.ttl;\n const iterator = obliviousSet.map[Symbol.iterator]();\n\n /**\n * Because we can assume the new values are added at the bottom,\n * we start from the top and stop as soon as we reach a non-too-old value.\n */\n while (true) {\n\n const next = iterator.next().value;\n\n if (!next) {\n return; // no more elements\n }\n const value = next[0];\n const time = next[1];\n if (time < olderThen) {\n obliviousSet.map.delete(value);\n } else {\n // We reached a value that is not old enough\n return;\n }\n }\n}\n\nexport function now(): number {\n return new Date().getTime();\n}\n\n\n", "export function fillOptionsWithDefaults() {\n var originalOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var options = JSON.parse(JSON.stringify(originalOptions));\n\n // main\n if (typeof options.webWorkerSupport === 'undefined') options.webWorkerSupport = true;\n\n // indexed-db\n if (!options.idb) options.idb = {};\n // after this time the messages get deleted\n if (!options.idb.ttl) options.idb.ttl = 1000 * 45;\n if (!options.idb.fallbackInterval) options.idb.fallbackInterval = 150;\n // handles abrupt db onclose events.\n if (originalOptions.idb && typeof originalOptions.idb.onclose === 'function') options.idb.onclose = originalOptions.idb.onclose;\n\n // localstorage\n if (!options.localstorage) options.localstorage = {};\n if (!options.localstorage.removeTimeout) options.localstorage.removeTimeout = 1000 * 60;\n\n // custom methods\n if (originalOptions.methods) options.methods = originalOptions.methods;\n\n // node\n if (!options.node) options.node = {};\n if (!options.node.ttl) options.node.ttl = 1000 * 60 * 2; // 2 minutes;\n /**\n * On linux use 'ulimit -Hn' to get the limit of open files.\n * On ubuntu this was 4096 for me, so we use half of that as maxParallelWrites default.\n */\n if (!options.node.maxParallelWrites) options.node.maxParallelWrites = 2048;\n if (typeof options.node.useFastPath === 'undefined') options.node.useFastPath = true;\n return options;\n}", "/**\n * this method uses indexeddb to store the messages\n * There is currently no observerAPI for idb\n * @link https://github.com/w3c/IndexedDB/issues/51\n * \n * When working on this, ensure to use these performance optimizations:\n * @link https://rxdb.info/slow-indexeddb.html\n */\n\nimport { sleep, randomInt, randomToken, microSeconds as micro, PROMISE_RESOLVED_VOID } from '../util.js';\nexport var microSeconds = micro;\nimport { ObliviousSet } from 'oblivious-set';\nimport { fillOptionsWithDefaults } from '../options.js';\nvar DB_PREFIX = 'pubkey.broadcast-channel-0-';\nvar OBJECT_STORE_ID = 'messages';\n\n/**\n * Use relaxed durability for faster performance on all transactions.\n * @link https://nolanlawson.com/2021/08/22/speeding-up-indexeddb-reads-and-writes/\n */\nexport var TRANSACTION_SETTINGS = {\n durability: 'relaxed'\n};\nexport var type = 'idb';\nexport function getIdb() {\n if (typeof indexedDB !== 'undefined') return indexedDB;\n if (typeof window !== 'undefined') {\n if (typeof window.mozIndexedDB !== 'undefined') return window.mozIndexedDB;\n if (typeof window.webkitIndexedDB !== 'undefined') return window.webkitIndexedDB;\n if (typeof window.msIndexedDB !== 'undefined') return window.msIndexedDB;\n }\n return false;\n}\n\n/**\n * If possible, we should explicitly commit IndexedDB transactions\n * for better performance.\n * @link https://nolanlawson.com/2021/08/22/speeding-up-indexeddb-reads-and-writes/\n */\nexport function commitIndexedDBTransaction(tx) {\n if (tx.commit) {\n tx.commit();\n }\n}\nexport function createDatabase(channelName) {\n var IndexedDB = getIdb();\n\n // create table\n var dbName = DB_PREFIX + channelName;\n\n /**\n * All IndexedDB databases are opened without version\n * because it is a bit faster, especially on firefox\n * @link http://nparashuram.com/IndexedDB/perf/#Open%20Database%20with%20version\n */\n var openRequest = IndexedDB.open(dbName);\n openRequest.onupgradeneeded = function (ev) {\n var db = ev.target.result;\n db.createObjectStore(OBJECT_STORE_ID, {\n keyPath: 'id',\n autoIncrement: true\n });\n };\n return new Promise(function (res, rej) {\n openRequest.onerror = function (ev) {\n return rej(ev);\n };\n openRequest.onsuccess = function () {\n res(openRequest.result);\n };\n });\n}\n\n/**\n * writes the new message to the database\n * so other readers can find it\n */\nexport function writeMessage(db, readerUuid, messageJson) {\n var time = new Date().getTime();\n var writeObject = {\n uuid: readerUuid,\n time: time,\n data: messageJson\n };\n var tx = db.transaction([OBJECT_STORE_ID], 'readwrite', TRANSACTION_SETTINGS);\n return new Promise(function (res, rej) {\n tx.oncomplete = function () {\n return res();\n };\n tx.onerror = function (ev) {\n return rej(ev);\n };\n var objectStore = tx.objectStore(OBJECT_STORE_ID);\n objectStore.add(writeObject);\n commitIndexedDBTransaction(tx);\n });\n}\nexport function getAllMessages(db) {\n var tx = db.transaction(OBJECT_STORE_ID, 'readonly', TRANSACTION_SETTINGS);\n var objectStore = tx.objectStore(OBJECT_STORE_ID);\n var ret = [];\n return new Promise(function (res) {\n objectStore.openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n if (cursor) {\n ret.push(cursor.value);\n //alert(\"Name for SSN \" + cursor.key + \" is \" + cursor.value.name);\n cursor[\"continue\"]();\n } else {\n commitIndexedDBTransaction(tx);\n res(ret);\n }\n };\n });\n}\nexport function getMessagesHigherThan(db, lastCursorId) {\n var tx = db.transaction(OBJECT_STORE_ID, 'readonly', TRANSACTION_SETTINGS);\n var objectStore = tx.objectStore(OBJECT_STORE_ID);\n var ret = [];\n var keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity);\n\n /**\n * Optimization shortcut,\n * if getAll() can be used, do not use a cursor.\n * @link https://rxdb.info/slow-indexeddb.html\n */\n if (objectStore.getAll) {\n var getAllRequest = objectStore.getAll(keyRangeValue);\n return new Promise(function (res, rej) {\n getAllRequest.onerror = function (err) {\n return rej(err);\n };\n getAllRequest.onsuccess = function (e) {\n res(e.target.result);\n };\n });\n }\n function openCursor() {\n // Occasionally Safari will fail on IDBKeyRange.bound, this\n // catches that error, having it open the cursor to the first\n // item. When it gets data it will advance to the desired key.\n try {\n keyRangeValue = IDBKeyRange.bound(lastCursorId + 1, Infinity);\n return objectStore.openCursor(keyRangeValue);\n } catch (e) {\n return objectStore.openCursor();\n }\n }\n return new Promise(function (res, rej) {\n var openCursorRequest = openCursor();\n openCursorRequest.onerror = function (err) {\n return rej(err);\n };\n openCursorRequest.onsuccess = function (ev) {\n var cursor = ev.target.result;\n if (cursor) {\n if (cursor.value.id < lastCursorId + 1) {\n cursor[\"continue\"](lastCursorId + 1);\n } else {\n ret.push(cursor.value);\n cursor[\"continue\"]();\n }\n } else {\n commitIndexedDBTransaction(tx);\n res(ret);\n }\n };\n });\n}\nexport function removeMessagesById(channelState, ids) {\n if (channelState.closed) {\n return Promise.resolve([]);\n }\n var tx = channelState.db.transaction(OBJECT_STORE_ID, 'readwrite', TRANSACTION_SETTINGS);\n var objectStore = tx.objectStore(OBJECT_STORE_ID);\n return Promise.all(ids.map(function (id) {\n var deleteRequest = objectStore[\"delete\"](id);\n return new Promise(function (res) {\n deleteRequest.onsuccess = function () {\n return res();\n };\n });\n }));\n}\nexport function getOldMessages(db, ttl) {\n var olderThen = new Date().getTime() - ttl;\n var tx = db.transaction(OBJECT_STORE_ID, 'readonly', TRANSACTION_SETTINGS);\n var objectStore = tx.objectStore(OBJECT_STORE_ID);\n var ret = [];\n return new Promise(function (res) {\n objectStore.openCursor().onsuccess = function (ev) {\n var cursor = ev.target.result;\n if (cursor) {\n var msgObk = cursor.value;\n if (msgObk.time < olderThen) {\n ret.push(msgObk);\n //alert(\"Name for SSN \" + cursor.key + \" is \" + cursor.value.name);\n cursor[\"continue\"]();\n } else {\n // no more old messages,\n commitIndexedDBTransaction(tx);\n res(ret);\n }\n } else {\n res(ret);\n }\n };\n });\n}\nexport function cleanOldMessages(channelState) {\n return getOldMessages(channelState.db, channelState.options.idb.ttl).then(function (tooOld) {\n return removeMessagesById(channelState, tooOld.map(function (msg) {\n return msg.id;\n }));\n });\n}\nexport function create(channelName, options) {\n options = fillOptionsWithDefaults(options);\n return createDatabase(channelName).then(function (db) {\n var state = {\n closed: false,\n lastCursorId: 0,\n channelName: channelName,\n options: options,\n uuid: randomToken(),\n /**\n * emittedMessagesIds\n * contains all messages that have been emitted before\n * @type {ObliviousSet}\n */\n eMIs: new ObliviousSet(options.idb.ttl * 2),\n // ensures we do not read messages in parallel\n writeBlockPromise: PROMISE_RESOLVED_VOID,\n messagesCallback: null,\n readQueuePromises: [],\n db: db\n };\n\n /**\n * Handle abrupt closes that do not originate from db.close().\n * This could happen, for example, if the underlying storage is\n * removed or if the user clears the database in the browser's\n * history preferences.\n */\n db.onclose = function () {\n state.closed = true;\n if (options.idb.onclose) options.idb.onclose();\n };\n\n /**\n * if service-workers are used,\n * we have no 'storage'-event if they post a message,\n * therefore we also have to set an interval\n */\n _readLoop(state);\n return state;\n });\n}\nfunction _readLoop(state) {\n if (state.closed) return;\n readNewMessages(state).then(function () {\n return sleep(state.options.idb.fallbackInterval);\n }).then(function () {\n return _readLoop(state);\n });\n}\nfunction _filterMessage(msgObj, state) {\n if (msgObj.uuid === state.uuid) return false; // send by own\n if (state.eMIs.has(msgObj.id)) return false; // already emitted\n if (msgObj.data.time < state.messagesCallbackTime) return false; // older then onMessageCallback\n return true;\n}\n\n/**\n * reads all new messages from the database and emits them\n */\nfunction readNewMessages(state) {\n // channel already closed\n if (state.closed) return PROMISE_RESOLVED_VOID;\n\n // if no one is listening, we do not need to scan for new messages\n if (!state.messagesCallback) return PROMISE_RESOLVED_VOID;\n return getMessagesHigherThan(state.db, state.lastCursorId).then(function (newerMessages) {\n var useMessages = newerMessages\n /**\n * there is a bug in iOS where the msgObj can be undefined sometimes\n * so we filter them out\n * @link https://github.com/pubkey/broadcast-channel/issues/19\n */.filter(function (msgObj) {\n return !!msgObj;\n }).map(function (msgObj) {\n if (msgObj.id > state.lastCursorId) {\n state.lastCursorId = msgObj.id;\n }\n return msgObj;\n }).filter(function (msgObj) {\n return _filterMessage(msgObj, state);\n }).sort(function (msgObjA, msgObjB) {\n return msgObjA.time - msgObjB.time;\n }); // sort by time\n useMessages.forEach(function (msgObj) {\n if (state.messagesCallback) {\n state.eMIs.add(msgObj.id);\n state.messagesCallback(msgObj.data);\n }\n });\n return PROMISE_RESOLVED_VOID;\n });\n}\nexport function close(channelState) {\n channelState.closed = true;\n channelState.db.close();\n}\nexport function postMessage(channelState, messageJson) {\n channelState.writeBlockPromise = channelState.writeBlockPromise.then(function () {\n return writeMessage(channelState.db, channelState.uuid, messageJson);\n }).then(function () {\n if (randomInt(0, 10) === 0) {\n /* await (do not await) */\n cleanOldMessages(channelState);\n }\n });\n return channelState.writeBlockPromise;\n}\nexport function onMessage(channelState, fn, time) {\n channelState.messagesCallbackTime = time;\n channelState.messagesCallback = fn;\n readNewMessages(channelState);\n}\nexport function canBeUsed() {\n return !!getIdb();\n}\nexport function averageResponseTime(options) {\n return options.idb.fallbackInterval * 2;\n}\nexport var IndexedDBMethod = {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};", "/**\n * A localStorage-only method which uses localstorage and its 'storage'-event\n * This does not work inside webworkers because they have no access to localstorage\n * This is basically implemented to support IE9 or your grandmother's toaster.\n * @link https://caniuse.com/#feat=namevalue-storage\n * @link https://caniuse.com/#feat=indexeddb\n */\n\nimport { ObliviousSet } from 'oblivious-set';\nimport { fillOptionsWithDefaults } from '../options.js';\nimport { sleep, randomToken, microSeconds as micro } from '../util.js';\nexport var microSeconds = micro;\nvar KEY_PREFIX = 'pubkey.broadcastChannel-';\nexport var type = 'localstorage';\n\n/**\n * copied from crosstab\n * @link https://github.com/tejacques/crosstab/blob/master/src/crosstab.js#L32\n */\nexport function getLocalStorage() {\n var localStorage;\n if (typeof window === 'undefined') return null;\n try {\n localStorage = window.localStorage;\n localStorage = window['ie8-eventlistener/storage'] || window.localStorage;\n } catch (e) {\n // New versions of Firefox throw a Security exception\n // if cookies are disabled. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1028153\n }\n return localStorage;\n}\nexport function storageKey(channelName) {\n return KEY_PREFIX + channelName;\n}\n\n/**\n* writes the new message to the storage\n* and fires the storage-event so other readers can find it\n*/\nexport function postMessage(channelState, messageJson) {\n return new Promise(function (res) {\n sleep().then(function () {\n var key = storageKey(channelState.channelName);\n var writeObj = {\n token: randomToken(),\n time: new Date().getTime(),\n data: messageJson,\n uuid: channelState.uuid\n };\n var value = JSON.stringify(writeObj);\n getLocalStorage().setItem(key, value);\n\n /**\n * StorageEvent does not fire the 'storage' event\n * in the window that changes the state of the local storage.\n * So we fire it manually\n */\n var ev = document.createEvent('Event');\n ev.initEvent('storage', true, true);\n ev.key = key;\n ev.newValue = value;\n window.dispatchEvent(ev);\n res();\n });\n });\n}\nexport function addStorageEventListener(channelName, fn) {\n var key = storageKey(channelName);\n var listener = function listener(ev) {\n if (ev.key === key) {\n fn(JSON.parse(ev.newValue));\n }\n };\n window.addEventListener('storage', listener);\n return listener;\n}\nexport function removeStorageEventListener(listener) {\n window.removeEventListener('storage', listener);\n}\nexport function create(channelName, options) {\n options = fillOptionsWithDefaults(options);\n if (!canBeUsed()) {\n throw new Error('BroadcastChannel: localstorage cannot be used');\n }\n var uuid = randomToken();\n\n /**\n * eMIs\n * contains all messages that have been emitted before\n * @type {ObliviousSet}\n */\n var eMIs = new ObliviousSet(options.localstorage.removeTimeout);\n var state = {\n channelName: channelName,\n uuid: uuid,\n eMIs: eMIs // emittedMessagesIds\n };\n\n state.listener = addStorageEventListener(channelName, function (msgObj) {\n if (!state.messagesCallback) return; // no listener\n if (msgObj.uuid === uuid) return; // own message\n if (!msgObj.token || eMIs.has(msgObj.token)) return; // already emitted\n if (msgObj.data.time && msgObj.data.time < state.messagesCallbackTime) return; // too old\n\n eMIs.add(msgObj.token);\n state.messagesCallback(msgObj.data);\n });\n return state;\n}\nexport function close(channelState) {\n removeStorageEventListener(channelState.listener);\n}\nexport function onMessage(channelState, fn, time) {\n channelState.messagesCallbackTime = time;\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n var ls = getLocalStorage();\n if (!ls) return false;\n try {\n var key = '__broadcastchannel_check';\n ls.setItem(key, 'works');\n ls.removeItem(key);\n } catch (e) {\n // Safari 10 in private mode will not allow write access to local\n // storage and fail with a QuotaExceededError. See\n // https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API#Private_Browsing_Incognito_modes\n return false;\n }\n return true;\n}\nexport function averageResponseTime() {\n var defaultTime = 120;\n var userAgent = navigator.userAgent.toLowerCase();\n if (userAgent.includes('safari') && !userAgent.includes('chrome')) {\n // safari is much slower so this time is higher\n return defaultTime * 2;\n }\n return defaultTime;\n}\nexport var LocalstorageMethod = {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};", "import { microSeconds as micro } from '../util.js';\nexport var microSeconds = micro;\nexport var type = 'simulate';\nvar SIMULATE_CHANNELS = new Set();\nexport function create(channelName) {\n var state = {\n name: channelName,\n messagesCallback: null\n };\n SIMULATE_CHANNELS.add(state);\n return state;\n}\nexport function close(channelState) {\n SIMULATE_CHANNELS[\"delete\"](channelState);\n}\nexport function postMessage(channelState, messageJson) {\n return new Promise(function (res) {\n return setTimeout(function () {\n var channelArray = Array.from(SIMULATE_CHANNELS);\n channelArray.filter(function (channel) {\n return channel.name === channelState.name;\n }).filter(function (channel) {\n return channel !== channelState;\n }).filter(function (channel) {\n return !!channel.messagesCallback;\n }).forEach(function (channel) {\n return channel.messagesCallback(messageJson);\n });\n res();\n }, 5);\n });\n}\nexport function onMessage(channelState, fn) {\n channelState.messagesCallback = fn;\n}\nexport function canBeUsed() {\n return true;\n}\nexport function averageResponseTime() {\n return 5;\n}\nexport var SimulateMethod = {\n create: create,\n close: close,\n onMessage: onMessage,\n postMessage: postMessage,\n canBeUsed: canBeUsed,\n type: type,\n averageResponseTime: averageResponseTime,\n microSeconds: microSeconds\n};", "import { NativeMethod } from './methods/native.js';\nimport { IndexedDBMethod } from './methods/indexed-db.js';\nimport { LocalstorageMethod } from './methods/localstorage.js';\nimport { SimulateMethod } from './methods/simulate.js';\n// the line below will be removed from es5/browser builds\n\n// order is important\nvar METHODS = [NativeMethod,\n// fastest\nIndexedDBMethod, LocalstorageMethod];\nexport function chooseMethod(options) {\n var chooseMethods = [].concat(options.methods, METHODS).filter(Boolean);\n\n // the line below will be removed from es5/browser builds\n\n // directly chosen\n if (options.type) {\n if (options.type === 'simulate') {\n // only use simulate-method if directly chosen\n return SimulateMethod;\n }\n var ret = chooseMethods.find(function (m) {\n return m.type === options.type;\n });\n if (!ret) throw new Error('method-type ' + options.type + ' not found');else return ret;\n }\n\n /**\n * if no webworker support is needed,\n * remove idb from the list so that localstorage will be chosen\n */\n if (!options.webWorkerSupport) {\n chooseMethods = chooseMethods.filter(function (m) {\n return m.type !== 'idb';\n });\n }\n var useMethod = chooseMethods.find(function (method) {\n return method.canBeUsed();\n });\n if (!useMethod) {\n throw new Error(\"No usable method found in \" + JSON.stringify(METHODS.map(function (m) {\n return m.type;\n })));\n } else {\n return useMethod;\n }\n}", "import { isPromise, PROMISE_RESOLVED_FALSE, PROMISE_RESOLVED_VOID } from './util.js';\nimport { chooseMethod } from './method-chooser.js';\nimport { fillOptionsWithDefaults } from './options.js';\n\n/**\n * Contains all open channels,\n * used in tests to ensure everything is closed.\n */\nexport var OPEN_BROADCAST_CHANNELS = new Set();\nvar lastId = 0;\nexport var BroadcastChannel = function BroadcastChannel(name, options) {\n // identifier of the channel to debug stuff\n this.id = lastId++;\n OPEN_BROADCAST_CHANNELS.add(this);\n this.name = name;\n if (ENFORCED_OPTIONS) {\n options = ENFORCED_OPTIONS;\n }\n this.options = fillOptionsWithDefaults(options);\n this.method = chooseMethod(this.options);\n\n // isListening\n this._iL = false;\n\n /**\n * _onMessageListener\n * setting onmessage twice,\n * will overwrite the first listener\n */\n this._onML = null;\n\n /**\n * _addEventListeners\n */\n this._addEL = {\n message: [],\n internal: []\n };\n\n /**\n * Unsent message promises\n * where the sending is still in progress\n * @type {Set}\n */\n this._uMP = new Set();\n\n /**\n * _beforeClose\n * array of promises that will be awaited\n * before the channel is closed\n */\n this._befC = [];\n\n /**\n * _preparePromise\n */\n this._prepP = null;\n _prepareChannel(this);\n};\n\n// STATICS\n\n/**\n * used to identify if someone overwrites\n * window.BroadcastChannel with this\n * See methods/native.js\n */\nBroadcastChannel._pubkey = true;\n\n/**\n * clears the tmp-folder if is node\n * @return {Promise} true if has run, false if not node\n */\nexport function clearNodeFolder(options) {\n options = fillOptionsWithDefaults(options);\n var method = chooseMethod(options);\n if (method.type === 'node') {\n return method.clearNodeFolder().then(function () {\n return true;\n });\n } else {\n return PROMISE_RESOLVED_FALSE;\n }\n}\n\n/**\n * if set, this method is enforced,\n * no mather what the options are\n */\nvar ENFORCED_OPTIONS;\nexport function enforceOptions(options) {\n ENFORCED_OPTIONS = options;\n}\n\n// PROTOTYPE\nBroadcastChannel.prototype = {\n postMessage: function postMessage(msg) {\n if (this.closed) {\n throw new Error('BroadcastChannel.postMessage(): ' + 'Cannot post message after channel has closed ' +\n /**\n * In the past when this error appeared, it was really hard to debug.\n * So now we log the msg together with the error so it at least\n * gives some clue about where in your application this happens.\n */\n JSON.stringify(msg));\n }\n return _post(this, 'message', msg);\n },\n postInternal: function postInternal(msg) {\n return _post(this, 'internal', msg);\n },\n set onmessage(fn) {\n var time = this.method.microSeconds();\n var listenObj = {\n time: time,\n fn: fn\n };\n _removeListenerObject(this, 'message', this._onML);\n if (fn && typeof fn === 'function') {\n this._onML = listenObj;\n _addListenerObject(this, 'message', listenObj);\n } else {\n this._onML = null;\n }\n },\n addEventListener: function addEventListener(type, fn) {\n var time = this.method.microSeconds();\n var listenObj = {\n time: time,\n fn: fn\n };\n _addListenerObject(this, type, listenObj);\n },\n removeEventListener: function removeEventListener(type, fn) {\n var obj = this._addEL[type].find(function (obj) {\n return obj.fn === fn;\n });\n _removeListenerObject(this, type, obj);\n },\n close: function close() {\n var _this = this;\n if (this.closed) {\n return;\n }\n OPEN_BROADCAST_CHANNELS[\"delete\"](this);\n this.closed = true;\n var awaitPrepare = this._prepP ? this._prepP : PROMISE_RESOLVED_VOID;\n this._onML = null;\n this._addEL.message = [];\n return awaitPrepare\n // wait until all current sending are processed\n .then(function () {\n return Promise.all(Array.from(_this._uMP));\n })\n // run before-close hooks\n .then(function () {\n return Promise.all(_this._befC.map(function (fn) {\n return fn();\n }));\n })\n // close the channel\n .then(function () {\n return _this.method.close(_this._state);\n });\n },\n get type() {\n return this.method.type;\n },\n get isClosed() {\n return this.closed;\n }\n};\n\n/**\n * Post a message over the channel\n * @returns {Promise} that resolved when the message sending is done\n */\nfunction _post(broadcastChannel, type, msg) {\n var time = broadcastChannel.method.microSeconds();\n var msgObj = {\n time: time,\n type: type,\n data: msg\n };\n var awaitPrepare = broadcastChannel._prepP ? broadcastChannel._prepP : PROMISE_RESOLVED_VOID;\n return awaitPrepare.then(function () {\n var sendPromise = broadcastChannel.method.postMessage(broadcastChannel._state, msgObj);\n\n // add/remove to unsent messages list\n broadcastChannel._uMP.add(sendPromise);\n sendPromise[\"catch\"]().then(function () {\n return broadcastChannel._uMP[\"delete\"](sendPromise);\n });\n return sendPromise;\n });\n}\nfunction _prepareChannel(channel) {\n var maybePromise = channel.method.create(channel.name, channel.options);\n if (isPromise(maybePromise)) {\n channel._prepP = maybePromise;\n maybePromise.then(function (s) {\n // used in tests to simulate slow runtime\n /*if (channel.options.prepareDelay) {\n await new Promise(res => setTimeout(res, this.options.prepareDelay));\n }*/\n channel._state = s;\n });\n } else {\n channel._state = maybePromise;\n }\n}\nfunction _hasMessageListeners(channel) {\n if (channel._addEL.message.length > 0) return true;\n if (channel._addEL.internal.length > 0) return true;\n return false;\n}\nfunction _addListenerObject(channel, type, obj) {\n channel._addEL[type].push(obj);\n _startListening(channel);\n}\nfunction _removeListenerObject(channel, type, obj) {\n channel._addEL[type] = channel._addEL[type].filter(function (o) {\n return o !== obj;\n });\n _stopListening(channel);\n}\nfunction _startListening(channel) {\n if (!channel._iL && _hasMessageListeners(channel)) {\n // someone is listening, start subscribing\n\n var listenerFn = function listenerFn(msgObj) {\n channel._addEL[msgObj.type].forEach(function (listenerObject) {\n /**\n * Getting the current time in JavaScript has no good precision.\n * So instead of only listening to events that happened 'after' the listener\n * was added, we also listen to events that happened 100ms before it.\n * This ensures that when another process, like a WebWorker, sends events\n * we do not miss them out because their timestamp is a bit off compared to the main process.\n * Not doing this would make messages missing when we send data directly after subscribing and awaiting a response.\n * @link https://johnresig.com/blog/accuracy-of-javascript-time/\n */\n var hundredMsInMicro = 100 * 1000;\n var minMessageTime = listenerObject.time - hundredMsInMicro;\n if (msgObj.time >= minMessageTime) {\n listenerObject.fn(msgObj.data);\n }\n });\n };\n var time = channel.method.microSeconds();\n if (channel._prepP) {\n channel._prepP.then(function () {\n channel._iL = true;\n channel.method.onMessage(channel._state, listenerFn, time);\n });\n } else {\n channel._iL = true;\n channel.method.onMessage(channel._state, listenerFn, time);\n }\n }\n}\nfunction _stopListening(channel) {\n if (channel._iL && !_hasMessageListeners(channel)) {\n // no one is listening, stop subscribing\n channel._iL = false;\n var time = channel.method.microSeconds();\n channel.method.onMessage(channel._state, null, time);\n }\n}", "/* global WorkerGlobalScope */\n\nexport function addBrowser(fn) {\n if (typeof WorkerGlobalScope === 'function' && self instanceof WorkerGlobalScope) {\n /**\n * Because killing a worker does directly stop the excution\n * of the code, our only chance is to overwrite the close function\n * which could work some times.\n * @link https://stackoverflow.com/q/72903255/3443137\n */\n var oldClose = self.close.bind(self);\n self.close = function () {\n fn();\n return oldClose();\n };\n } else {\n /**\n * if we are on react-native, there is no window.addEventListener\n * @link https://github.com/pubkey/unload/issues/6\n */\n if (typeof window.addEventListener !== 'function') {\n return;\n }\n\n /**\n * for normal browser-windows, we use the beforeunload-event\n */\n window.addEventListener('beforeunload', function () {\n fn();\n }, true);\n\n /**\n * for iframes, we have to use the unload-event\n * @link https://stackoverflow.com/q/47533670/3443137\n */\n window.addEventListener('unload', function () {\n fn();\n }, true);\n }\n\n /**\n * TODO add fallback for safari-mobile\n * @link https://stackoverflow.com/a/26193516/3443137\n */\n}", "export function addNode(fn) {\n process.on('exit', function () {\n return fn();\n });\n\n /**\n * on the following events,\n * the process will not end if there are\n * event-handlers attached,\n * therefore we have to call process.exit()\n */\n process.on('beforeExit', function () {\n return fn().then(function () {\n return process.exit();\n });\n });\n // catches ctrl+c event\n process.on('SIGINT', function () {\n return fn().then(function () {\n return process.exit();\n });\n });\n // catches uncaught exceptions\n process.on('uncaughtException', function (err) {\n return fn().then(function () {\n console.trace(err);\n process.exit(101);\n });\n });\n}", "import { addBrowser } from './browser.js';\nimport { addNode } from './node.js';\n\n/**\n * Use the code directly to prevent import problems\n * with the detect-node package.\n * @link https://github.com/iliakan/detect-node/blob/master/index.js\n */\nvar isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';\nvar USE_METHOD = isNode ? addNode : addBrowser;\nvar LISTENERS = new Set();\nvar startedListening = false;\nfunction startListening() {\n if (startedListening) {\n return;\n }\n startedListening = true;\n USE_METHOD(runAll);\n}\nexport function add(fn) {\n startListening();\n if (typeof fn !== 'function') {\n throw new Error('Listener is no function');\n }\n LISTENERS.add(fn);\n var addReturn = {\n remove: function remove() {\n return LISTENERS[\"delete\"](fn);\n },\n run: function run() {\n LISTENERS[\"delete\"](fn);\n return fn();\n }\n };\n return addReturn;\n}\nexport function runAll() {\n var promises = [];\n LISTENERS.forEach(function (fn) {\n promises.push(fn());\n LISTENERS[\"delete\"](fn);\n });\n return Promise.all(promises);\n}\nexport function removeAll() {\n LISTENERS.clear();\n}\nexport function getSize() {\n return LISTENERS.size;\n}", "import { add as unloadAdd } from 'unload';\n\n/**\n * sends and internal message over the broadcast-channel\n */\nexport function sendLeaderMessage(leaderElector, action) {\n var msgJson = {\n context: 'leader',\n action: action,\n token: leaderElector.token\n };\n return leaderElector.broadcastChannel.postInternal(msgJson);\n}\nexport function beLeader(leaderElector) {\n leaderElector.isLeader = true;\n leaderElector._hasLeader = true;\n var unloadFn = unloadAdd(function () {\n return leaderElector.die();\n });\n leaderElector._unl.push(unloadFn);\n var isLeaderListener = function isLeaderListener(msg) {\n if (msg.context === 'leader' && msg.action === 'apply') {\n sendLeaderMessage(leaderElector, 'tell');\n }\n if (msg.context === 'leader' && msg.action === 'tell' && !leaderElector._dpLC) {\n /**\n * another instance is also leader!\n * This can happen on rare events\n * like when the CPU is at 100% for long time\n * or the tabs are open very long and the browser throttles them.\n * @link https://github.com/pubkey/broadcast-channel/issues/414\n * @link https://github.com/pubkey/broadcast-channel/issues/385\n */\n leaderElector._dpLC = true;\n leaderElector._dpL(); // message the lib user so the app can handle the problem\n sendLeaderMessage(leaderElector, 'tell'); // ensure other leader also knows the problem\n }\n };\n\n leaderElector.broadcastChannel.addEventListener('internal', isLeaderListener);\n leaderElector._lstns.push(isLeaderListener);\n return sendLeaderMessage(leaderElector, 'tell');\n}", "import { randomToken } from './util.js';\nimport { sendLeaderMessage, beLeader } from './leader-election-util.js';\n\n/**\n * A faster version of the leader elector that uses the WebLock API\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API\n */\nexport var LeaderElectionWebLock = function LeaderElectionWebLock(broadcastChannel, options) {\n var _this = this;\n this.broadcastChannel = broadcastChannel;\n broadcastChannel._befC.push(function () {\n return _this.die();\n });\n this._options = options;\n this.isLeader = false;\n this.isDead = false;\n this.token = randomToken();\n this._lstns = [];\n this._unl = [];\n this._dpL = function () {}; // onduplicate listener\n this._dpLC = false; // true when onduplicate called\n\n this._wKMC = {}; // stuff for cleanup\n\n // lock name\n this.lN = 'pubkey-bc||' + broadcastChannel.method.type + '||' + broadcastChannel.name;\n};\nLeaderElectionWebLock.prototype = {\n hasLeader: function hasLeader() {\n var _this2 = this;\n return navigator.locks.query().then(function (locks) {\n var relevantLocks = locks.held ? locks.held.filter(function (lock) {\n return lock.name === _this2.lN;\n }) : [];\n if (relevantLocks && relevantLocks.length > 0) {\n return true;\n } else {\n return false;\n }\n });\n },\n awaitLeadership: function awaitLeadership() {\n var _this3 = this;\n if (!this._wLMP) {\n this._wKMC.c = new AbortController();\n var returnPromise = new Promise(function (res, rej) {\n _this3._wKMC.res = res;\n _this3._wKMC.rej = rej;\n });\n this._wLMP = new Promise(function (res) {\n navigator.locks.request(_this3.lN, {\n signal: _this3._wKMC.c.signal\n }, function () {\n // if the lock resolved, we can drop the abort controller\n _this3._wKMC.c = undefined;\n beLeader(_this3);\n res();\n return returnPromise;\n })[\"catch\"](function () {});\n });\n }\n return this._wLMP;\n },\n set onduplicate(_fn) {\n // Do nothing because there are no duplicates in the WebLock version\n },\n die: function die() {\n var _this4 = this;\n this._lstns.forEach(function (listener) {\n return _this4.broadcastChannel.removeEventListener('internal', listener);\n });\n this._lstns = [];\n this._unl.forEach(function (uFn) {\n return uFn.remove();\n });\n this._unl = [];\n if (this.isLeader) {\n this.isLeader = false;\n }\n this.isDead = true;\n if (this._wKMC.res) {\n this._wKMC.res();\n }\n if (this._wKMC.c) {\n this._wKMC.c.abort('LeaderElectionWebLock.die() called');\n }\n return sendLeaderMessage(this, 'death');\n }\n};", "import { sleep, randomToken, PROMISE_RESOLVED_VOID, PROMISE_RESOLVED_TRUE, supportsWebLockAPI } from './util.js';\nimport { sendLeaderMessage, beLeader } from './leader-election-util.js';\nimport { LeaderElectionWebLock } from './leader-election-web-lock.js';\nvar LeaderElection = function LeaderElection(broadcastChannel, options) {\n var _this = this;\n this.broadcastChannel = broadcastChannel;\n this._options = options;\n this.isLeader = false;\n this._hasLeader = false;\n this.isDead = false;\n this.token = randomToken();\n\n /**\n * Apply Queue,\n * used to ensure we do not run applyOnce()\n * in parallel.\n */\n this._aplQ = PROMISE_RESOLVED_VOID;\n // amount of unfinished applyOnce() calls\n this._aplQC = 0;\n\n // things to clean up\n this._unl = []; // _unloads\n this._lstns = []; // _listeners\n this._dpL = function () {}; // onduplicate listener\n this._dpLC = false; // true when onduplicate called\n\n /**\n * Even when the own instance is not applying,\n * we still listen to messages to ensure the hasLeader flag\n * is set correctly.\n */\n var hasLeaderListener = function hasLeaderListener(msg) {\n if (msg.context === 'leader') {\n if (msg.action === 'death') {\n _this._hasLeader = false;\n }\n if (msg.action === 'tell') {\n _this._hasLeader = true;\n }\n }\n };\n this.broadcastChannel.addEventListener('internal', hasLeaderListener);\n this._lstns.push(hasLeaderListener);\n};\nLeaderElection.prototype = {\n hasLeader: function hasLeader() {\n return Promise.resolve(this._hasLeader);\n },\n /**\n * Returns true if the instance is leader,\n * false if not.\n * @async\n */\n applyOnce: function applyOnce(\n // true if the applyOnce() call came from the fallbackInterval cycle\n isFromFallbackInterval) {\n var _this2 = this;\n if (this.isLeader) {\n return sleep(0, true);\n }\n if (this.isDead) {\n return sleep(0, false);\n }\n\n /**\n * Already applying more than once,\n * -> wait for the apply queue to be finished.\n */\n if (this._aplQC > 1) {\n return this._aplQ;\n }\n\n /**\n * Add a new apply-run\n */\n var applyRun = function applyRun() {\n /**\n * Optimization shortcuts.\n * Directly return if a previous run\n * has already elected a leader.\n */\n if (_this2.isLeader) {\n return PROMISE_RESOLVED_TRUE;\n }\n var stopCriteria = false;\n var stopCriteriaPromiseResolve;\n /**\n * Resolves when a stop criteria is reached.\n * Uses as a performance shortcut so we do not\n * have to await the responseTime when it is already clear\n * that the election failed.\n */\n var stopCriteriaPromise = new Promise(function (res) {\n stopCriteriaPromiseResolve = function stopCriteriaPromiseResolve() {\n stopCriteria = true;\n res();\n };\n });\n var handleMessage = function handleMessage(msg) {\n if (msg.context === 'leader' && msg.token != _this2.token) {\n if (msg.action === 'apply') {\n // other is applying\n if (msg.token > _this2.token) {\n /**\n * other has higher token\n * -> stop applying and let other become leader.\n */\n stopCriteriaPromiseResolve();\n }\n }\n if (msg.action === 'tell') {\n // other is already leader\n stopCriteriaPromiseResolve();\n _this2._hasLeader = true;\n }\n }\n };\n _this2.broadcastChannel.addEventListener('internal', handleMessage);\n\n /**\n * If the applyOnce() call came from the fallbackInterval,\n * we can assume that the election runs in the background and\n * not critical process is waiting for it.\n * When this is true, we give the other instances\n * more time to answer to messages in the election cycle.\n * This makes it less likely to elect duplicate leaders.\n * But also it takes longer which is not a problem because we anyway\n * run in the background.\n */\n var waitForAnswerTime = isFromFallbackInterval ? _this2._options.responseTime * 4 : _this2._options.responseTime;\n return sendLeaderMessage(_this2, 'apply') // send out that this one is applying\n .then(function () {\n return Promise.race([sleep(waitForAnswerTime), stopCriteriaPromise.then(function () {\n return Promise.reject(new Error());\n })]);\n })\n // send again in case another instance was just created\n .then(function () {\n return sendLeaderMessage(_this2, 'apply');\n })\n // let others time to respond\n .then(function () {\n return Promise.race([sleep(waitForAnswerTime), stopCriteriaPromise.then(function () {\n return Promise.reject(new Error());\n })]);\n })[\"catch\"](function () {}).then(function () {\n _this2.broadcastChannel.removeEventListener('internal', handleMessage);\n if (!stopCriteria) {\n // no stop criteria -> own is leader\n return beLeader(_this2).then(function () {\n return true;\n });\n } else {\n // other is leader\n return false;\n }\n });\n };\n this._aplQC = this._aplQC + 1;\n this._aplQ = this._aplQ.then(function () {\n return applyRun();\n }).then(function () {\n _this2._aplQC = _this2._aplQC - 1;\n });\n return this._aplQ.then(function () {\n return _this2.isLeader;\n });\n },\n awaitLeadership: function awaitLeadership() {\n if ( /* _awaitLeadershipPromise */\n !this._aLP) {\n this._aLP = _awaitLeadershipOnce(this);\n }\n return this._aLP;\n },\n set onduplicate(fn) {\n this._dpL = fn;\n },\n die: function die() {\n var _this3 = this;\n this._lstns.forEach(function (listener) {\n return _this3.broadcastChannel.removeEventListener('internal', listener);\n });\n this._lstns = [];\n this._unl.forEach(function (uFn) {\n return uFn.remove();\n });\n this._unl = [];\n if (this.isLeader) {\n this._hasLeader = false;\n this.isLeader = false;\n }\n this.isDead = true;\n return sendLeaderMessage(this, 'death');\n }\n};\n\n/**\n * @param leaderElector {LeaderElector}\n */\nfunction _awaitLeadershipOnce(leaderElector) {\n if (leaderElector.isLeader) {\n return PROMISE_RESOLVED_VOID;\n }\n return new Promise(function (res) {\n var resolved = false;\n function finish() {\n if (resolved) {\n return;\n }\n resolved = true;\n leaderElector.broadcastChannel.removeEventListener('internal', whenDeathListener);\n res(true);\n }\n\n // try once now\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) {\n finish();\n }\n });\n\n /**\n * Try on fallbackInterval\n * @recursive\n */\n var tryOnFallBack = function tryOnFallBack() {\n return sleep(leaderElector._options.fallbackInterval).then(function () {\n if (leaderElector.isDead || resolved) {\n return;\n }\n if (leaderElector.isLeader) {\n finish();\n } else {\n return leaderElector.applyOnce(true).then(function () {\n if (leaderElector.isLeader) {\n finish();\n } else {\n tryOnFallBack();\n }\n });\n }\n });\n };\n tryOnFallBack();\n\n // try when other leader dies\n var whenDeathListener = function whenDeathListener(msg) {\n if (msg.context === 'leader' && msg.action === 'death') {\n leaderElector._hasLeader = false;\n leaderElector.applyOnce().then(function () {\n if (leaderElector.isLeader) {\n finish();\n }\n });\n }\n };\n leaderElector.broadcastChannel.addEventListener('internal', whenDeathListener);\n leaderElector._lstns.push(whenDeathListener);\n });\n}\nfunction fillOptionsWithDefaults(options, channel) {\n if (!options) options = {};\n options = JSON.parse(JSON.stringify(options));\n if (!options.fallbackInterval) {\n options.fallbackInterval = 3000;\n }\n if (!options.responseTime) {\n options.responseTime = channel.method.averageResponseTime(channel.options);\n }\n return options;\n}\nexport function createLeaderElection(channel, options) {\n if (channel._leaderElector) {\n throw new Error('BroadcastChannel already has a leader-elector');\n }\n options = fillOptionsWithDefaults(options, channel);\n var elector = supportsWebLockAPI() ? new LeaderElectionWebLock(channel, options) : new LeaderElection(channel, options);\n channel._befC.push(function () {\n return elector.die();\n });\n channel._leaderElector = elector;\n return elector;\n}", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { BroadcastChannel } from 'broadcast-channel';\nimport { isBrowser } from '../features';\nimport {\n ServiceManagerOptions, ServiceInterface\n} from '../core/types';\nimport {\n Token, Tokens, \n EVENT_ADDED, EVENT_REMOVED, EVENT_RENEWED, EVENT_SET_STORAGE, TokenManagerInterface\n} from '../oidc/types';\nimport { AuthSdkError } from '../errors';\n\nexport type SyncMessage = {\n type: string;\n key?: string;\n token?: Token;\n oldToken?: Token;\n storage?: Tokens;\n};\nexport class SyncStorageService implements ServiceInterface {\n private tokenManager: TokenManagerInterface;\n private options: ServiceManagerOptions;\n private channel?: BroadcastChannel;\n private started = false;\n private enablePostMessage = true;\n\n constructor(tokenManager: TokenManagerInterface, options: ServiceManagerOptions = {}) {\n this.tokenManager = tokenManager;\n this.options = options;\n this.onTokenAddedHandler = this.onTokenAddedHandler.bind(this);\n this.onTokenRemovedHandler = this.onTokenRemovedHandler.bind(this);\n this.onTokenRenewedHandler = this.onTokenRenewedHandler.bind(this);\n this.onSetStorageHandler = this.onSetStorageHandler.bind(this);\n this.onSyncMessageHandler = this.onSyncMessageHandler.bind(this);\n }\n\n requiresLeadership() {\n return false;\n }\n\n isStarted() {\n return this.started;\n }\n\n canStart() {\n return !!this.options.syncStorage && isBrowser() && !this.started;\n }\n\n async start() {\n if (!this.canStart()) {\n return;\n }\n \n const { syncChannelName } = this.options;\n try {\n // BroadcastChannel throws if no supported method can be found\n this.channel = new BroadcastChannel(syncChannelName as string);\n } catch (err) {\n throw new AuthSdkError('SyncStorageService is not supported in current browser.');\n }\n\n this.tokenManager.on(EVENT_ADDED, this.onTokenAddedHandler);\n this.tokenManager.on(EVENT_REMOVED, this.onTokenRemovedHandler);\n this.tokenManager.on(EVENT_RENEWED, this.onTokenRenewedHandler);\n this.tokenManager.on(EVENT_SET_STORAGE, this.onSetStorageHandler);\n this.channel.addEventListener('message', this.onSyncMessageHandler);\n this.started = true;\n }\n\n async stop() {\n if (this.started) {\n this.tokenManager.off(EVENT_ADDED, this.onTokenAddedHandler);\n this.tokenManager.off(EVENT_REMOVED, this.onTokenRemovedHandler);\n this.tokenManager.off(EVENT_RENEWED, this.onTokenRenewedHandler);\n this.tokenManager.off(EVENT_SET_STORAGE, this.onSetStorageHandler);\n this.channel?.removeEventListener('message', this.onSyncMessageHandler);\n await this.channel?.close();\n this.channel = undefined;\n this.started = false;\n }\n }\n\n private onTokenAddedHandler(key: string, token: Token) {\n if (!this.enablePostMessage) {\n return;\n }\n this.channel?.postMessage({\n type: EVENT_ADDED,\n key,\n token\n });\n }\n\n private onTokenRemovedHandler(key: string, token: Token) {\n if (!this.enablePostMessage) {\n return;\n }\n this.channel?.postMessage({\n type: EVENT_REMOVED,\n key,\n token\n });\n }\n\n private onTokenRenewedHandler(key: string, token: Token, oldToken?: Token) {\n if (!this.enablePostMessage) {\n return;\n }\n this.channel?.postMessage({\n type: EVENT_RENEWED,\n key,\n token,\n oldToken\n });\n }\n\n private onSetStorageHandler(storage: Tokens) {\n this.channel?.postMessage({\n type: EVENT_SET_STORAGE,\n storage\n });\n }\n\n /* eslint-disable complexity */\n private onSyncMessageHandler(msg: SyncMessage) {\n // Notes:\n // 1. Using `enablePostMessage` flag here to prevent sync message loop.\n // If this flag is on, tokenManager event handlers do not post sync message.\n // 2. IE11 has known issue with synchronization of LocalStorage cross tabs.\n // One workaround is to set empty event handler for `window.onstorage`.\n // But it's not 100% working, sometimes you still get old value from LocalStorage.\n // Better approch is to explicitly udpate LocalStorage with `setStorage`.\n\n this.enablePostMessage = false;\n switch (msg.type) {\n case EVENT_SET_STORAGE:\n this.tokenManager.getStorage().setStorage(msg.storage);\n break;\n case EVENT_ADDED:\n this.tokenManager.emitAdded(msg.key!, msg.token!);\n this.tokenManager.setExpireEventTimeout(msg.key!, msg.token!);\n break;\n case EVENT_REMOVED:\n this.tokenManager.clearExpireEventTimeout(msg.key!);\n this.tokenManager.emitRemoved(msg.key!, msg.token!);\n break;\n case EVENT_RENEWED:\n this.tokenManager.emitRenewed(msg.key!, msg.token!, msg.oldToken);\n break;\n default:\n break;\n }\n this.enablePostMessage = true;\n }\n} ", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { ServiceInterface, ServiceManagerOptions } from '../core/types';\nimport {\n BroadcastChannel,\n createLeaderElection,\n LeaderElector\n} from 'broadcast-channel';\nimport { isBrowser } from '../features';\n\ndeclare type OnLeaderHandler = (() => Promise);\ndeclare type ServiceOptions = ServiceManagerOptions & {\n onLeader?: OnLeaderHandler;\n};\n\nexport class LeaderElectionService implements ServiceInterface {\n private options: ServiceOptions;\n private channel?: BroadcastChannel;\n private elector?: LeaderElector;\n private started = false;\n\n constructor(options: ServiceOptions = {}) {\n this.options = options;\n this.onLeaderDuplicate = this.onLeaderDuplicate.bind(this);\n this.onLeader = this.onLeader.bind(this);\n }\n\n private onLeaderDuplicate() {\n }\n\n private async onLeader() {\n await this.options.onLeader?.();\n }\n\n isLeader() {\n return !!this.elector?.isLeader;\n }\n\n hasLeader() {\n return !!this.elector?.hasLeader;\n }\n\n async start() {\n if (this.canStart()) {\n const { electionChannelName } = this.options;\n this.channel = new BroadcastChannel(electionChannelName as string);\n this.elector = createLeaderElection(this.channel);\n this.elector.onduplicate = this.onLeaderDuplicate;\n this.elector.awaitLeadership().then(this.onLeader);\n this.started = true;\n }\n }\n\n async stop() {\n if (this.started) {\n if (this.elector) {\n await this.elector.die();\n this.elector = undefined;\n }\n if (this.channel) {\n // Workaround to fix error `Failed to execute 'postMessage' on 'BroadcastChannel': Channel is closed`\n (this.channel as any).postInternal = () => Promise.resolve();\n await this.channel.close();\n this.channel = undefined;\n }\n this.started = false;\n }\n }\n\n requiresLeadership() {\n return false;\n }\n\n isStarted() {\n return this.started;\n }\n\n canStart() {\n return isBrowser() && !this.started;\n }\n\n}\n", "import { ServiceInterface, ServiceManagerOptions } from '../core/types';\nimport { TokenManagerInterface } from '../oidc/types';\nimport { isBrowser } from '../features';\n\nconst getNow = () => Math.floor(Date.now() / 1000);\n\nexport class RenewOnTabActivationService implements ServiceInterface {\n private tokenManager: TokenManagerInterface;\n private started = false;\n private options: ServiceManagerOptions;\n private lastHidden = -1;\n onPageVisbilityChange: () => void;\n\n constructor(tokenManager: TokenManagerInterface, options: ServiceManagerOptions = {}) {\n this.tokenManager = tokenManager;\n this.options = options;\n // store this context for event handler\n this.onPageVisbilityChange = this._onPageVisbilityChange.bind(this);\n }\n\n // do not use directly, use `onPageVisbilityChange` (with binded this context)\n /* eslint complexity: [0, 10] */\n private _onPageVisbilityChange () {\n if (document.hidden) {\n this.lastHidden = getNow();\n }\n // renew will only attempt if tab was inactive for duration\n else if (this.lastHidden > 0 && (getNow() - this.lastHidden >= this.options.tabInactivityDuration!)) {\n const { accessToken, idToken } = this.tokenManager.getTokensSync();\n if (!!accessToken && this.tokenManager.hasExpired(accessToken)) {\n const key = this.tokenManager.getStorageKeyByType('accessToken');\n // Renew errors will emit an \"error\" event\n this.tokenManager.renew(key).catch(() => {});\n }\n else if (!!idToken && this.tokenManager.hasExpired(idToken)) {\n const key = this.tokenManager.getStorageKeyByType('idToken');\n // Renew errors will emit an \"error\" event\n this.tokenManager.renew(key).catch(() => {});\n }\n }\n }\n\n async start () {\n if (this.canStart() && !!document) {\n document.addEventListener('visibilitychange', this.onPageVisbilityChange);\n this.started = true;\n }\n }\n\n async stop () {\n if (document) {\n document.removeEventListener('visibilitychange', this.onPageVisbilityChange);\n this.started = false;\n }\n }\n\n canStart(): boolean {\n return isBrowser() &&\n !!this.options.autoRenew &&\n !!this.options.renewOnTabActivation &&\n !this.started;\n }\n\n requiresLeadership(): boolean {\n return false;\n }\n\n isStarted(): boolean {\n return this.started;\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport {\n OAuthTransactionMeta,\n OAuthStorageManagerInterface,\n} from '../../oidc';\n\nimport {\n ServiceManagerInterface,\n ServiceInterface,\n ServiceManagerOptions,\n OktaAuthCoreInterface,\n OktaAuthCoreOptions\n} from '../types';\nimport { AutoRenewService,\n SyncStorageService,\n LeaderElectionService,\n RenewOnTabActivationService\n} from '../../services';\nimport { removeNils } from '../../util';\n\nconst AUTO_RENEW = 'autoRenew';\nconst SYNC_STORAGE = 'syncStorage';\nconst LEADER_ELECTION = 'leaderElection';\nconst RENEW_ON_TAB_ACTIVATION = 'renewOnTabActivation';\n\nexport class ServiceManager\n<\n M extends OAuthTransactionMeta,\n S extends OAuthStorageManagerInterface,\n O extends OktaAuthCoreOptions\n>\nimplements ServiceManagerInterface \n{\n private sdk: OktaAuthCoreInterface;\n private options: ServiceManagerOptions;\n private services: Map;\n private started: boolean;\n\n private static knownServices = [AUTO_RENEW, SYNC_STORAGE, LEADER_ELECTION, RENEW_ON_TAB_ACTIVATION];\n\n private static defaultOptions: ServiceManagerOptions = {\n autoRenew: true,\n autoRemove: true,\n syncStorage: true,\n renewOnTabActivation: true,\n tabInactivityDuration: 1800, // 30 mins in seconds\n };\n\n constructor(sdk: OktaAuthCoreInterface, options: ServiceManagerOptions = {}) {\n this.sdk = sdk;\n this.onLeader = this.onLeader.bind(this);\n\n // TODO: backwards compatibility, remove in next major version - OKTA-473815\n const { autoRenew, autoRemove, syncStorage } = sdk.tokenManager.getOptions();\n options.electionChannelName = options.electionChannelName || options.broadcastChannelName;\n this.options = Object.assign({}, \n ServiceManager.defaultOptions,\n { autoRenew, autoRemove, syncStorage }, \n {\n electionChannelName: `${sdk.options.clientId}-election`,\n syncChannelName: `${sdk.options.clientId}-sync`,\n },\n removeNils(options)\n );\n\n this.started = false;\n this.services = new Map();\n\n ServiceManager.knownServices.forEach(name => {\n const svc = this.createService(name);\n if (svc) {\n this.services.set(name, svc);\n }\n });\n }\n\n private async onLeader() {\n if (this.started) {\n // Start services that requires leadership\n await this.startServices();\n }\n }\n\n isLeader() {\n return (this.getService(LEADER_ELECTION) as LeaderElectionService)?.isLeader();\n }\n\n isLeaderRequired() {\n return [...this.services.values()].some(srv => srv.canStart() && srv.requiresLeadership());\n }\n\n async start() {\n if (this.started) {\n return; // noop if services have already started\n }\n await this.startServices();\n this.started = true;\n }\n \n async stop() {\n await this.stopServices();\n this.started = false;\n }\n\n getService(name: string): ServiceInterface | undefined {\n return this.services.get(name);\n }\n\n private async startServices() {\n for (const [name, srv] of this.services.entries()) {\n if (this.canStartService(name, srv)) {\n await srv.start();\n }\n }\n }\n\n private async stopServices() {\n for (const srv of this.services.values()) {\n await srv.stop();\n }\n }\n\n // eslint-disable-next-line complexity\n private canStartService(name: string, srv: ServiceInterface): boolean {\n let canStart = srv.canStart() && !srv.isStarted();\n // only start election if a leader is required\n if (name === LEADER_ELECTION) {\n canStart &&= this.isLeaderRequired();\n } else if (srv.requiresLeadership()) {\n canStart &&= this.isLeader();\n }\n return canStart;\n }\n\n private createService(name: string): ServiceInterface {\n const tokenManager = this.sdk.tokenManager;\n\n let service: ServiceInterface;\n switch (name) {\n case LEADER_ELECTION:\n service = new LeaderElectionService({...this.options, onLeader: this.onLeader});\n break;\n case AUTO_RENEW:\n service = new AutoRenewService(tokenManager, {...this.options});\n break;\n case SYNC_STORAGE:\n service = new SyncStorageService(tokenManager, {...this.options});\n break;\n case RENEW_ON_TAB_ACTIVATION:\n service = new RenewOnTabActivationService(tokenManager, {...this.options});\n break;\n default:\n throw new Error(`Unknown service ${name}`);\n }\n return service;\n }\n\n}\n", "import { parseOAuthResponseFromUrl } from '../oidc/parseFromUrl';\nimport { OktaAuthConstructor } from '../base/types';\nimport {\n OAuthStorageManagerInterface,\n OAuthTransactionMeta,\n OktaAuthOAuthInterface,\n PKCETransactionMeta,\n Tokens,\n TransactionManagerInterface,\n} from '../oidc/types';\nimport { AuthStateManager } from './AuthStateManager';\nimport { ServiceManager } from './ServiceManager';\nimport { OktaAuthCoreInterface, OktaAuthCoreOptions } from './types';\n\nexport function mixinCore\n<\n M extends OAuthTransactionMeta = PKCETransactionMeta,\n S extends OAuthStorageManagerInterface = OAuthStorageManagerInterface,\n O extends OktaAuthCoreOptions = OktaAuthCoreOptions,\n TM extends TransactionManagerInterface = TransactionManagerInterface,\n TBase extends OktaAuthConstructor>\n = OktaAuthConstructor>\n>\n(Base: TBase): TBase & OktaAuthConstructor>\n{\n return class OktaAuthCore extends Base implements OktaAuthCoreInterface\n {\n authStateManager: AuthStateManager;\n serviceManager: ServiceManager;\n \n constructor(...args: any[]) {\n super(...args);\n\n // AuthStateManager\n this.authStateManager = new AuthStateManager(this);\n\n // ServiceManager\n this.serviceManager = new ServiceManager(this, this.options.services);\n }\n\n async start() {\n await this.serviceManager.start();\n // TODO: review tokenManager.start\n this.tokenManager.start();\n if (!this.token.isLoginRedirect()) {\n await this.authStateManager.updateAuthState();\n }\n }\n \n async stop() {\n // TODO: review tokenManager.stop\n this.tokenManager.stop();\n await this.serviceManager.stop();\n }\n\n async handleRedirect(originalUri?: string): Promise {\n await this.handleLoginRedirect(undefined, originalUri);\n }\n\n // eslint-disable-next-line complexity\n async handleLoginRedirect(tokens?: Tokens, originalUri?: string): Promise {\n let state = this.options.state;\n \n // Store tokens and update AuthState by the emitted events\n if (tokens) {\n this.tokenManager.setTokens(tokens);\n originalUri = originalUri || this.getOriginalUri(this.options.state);\n } else if (this.isLoginRedirect()) {\n try {\n // For redirect flow, get state from the URL and use it to retrieve the originalUri\n const oAuthResponse = await parseOAuthResponseFromUrl(this, {});\n state = oAuthResponse.state;\n originalUri = originalUri || this.getOriginalUri(state);\n await this.storeTokensFromRedirect();\n } catch(e) {\n // auth state should be updated\n await this.authStateManager.updateAuthState();\n throw e;\n }\n } else {\n return; // nothing to do\n }\n \n // ensure auth state has been updated\n await this.authStateManager.updateAuthState();\n \n // clear originalUri from storage\n this.removeOriginalUri(state);\n \n // Redirect to originalUri\n const { restoreOriginalUri } = this.options;\n if (restoreOriginalUri) {\n await restoreOriginalUri(this, originalUri);\n } else if (originalUri) {\n window.location.replace(originalUri);\n }\n }\n };\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n/* global window */\nimport { omit, getLink, toQueryString } from '../util';\nimport { get, post, httpRequest } from '../http';\n\nfunction sessionExists(sdk) {\n return sdk.session.get()\n .then(function(res) {\n if (res.status === 'ACTIVE') {\n return true;\n }\n return false;\n })\n .catch(function() {\n return false;\n });\n}\n\nfunction getSession(sdk) { \n return get(sdk, '/api/v1/sessions/me', { withCredentials: true })\n .then(function(session) {\n var res = omit(session, '_links');\n\n res.refresh = function() {\n return post(sdk, getLink(session, 'refresh').href, {}, { withCredentials: true });\n };\n\n res.user = function() {\n return get(sdk, getLink(session, 'user').href, { withCredentials: true });\n };\n\n return res;\n })\n .catch(function() {\n // Return INACTIVE status on failure\n return {status: 'INACTIVE'};\n });\n}\n\nfunction closeSession(sdk) {\n return httpRequest(sdk, {\n url: sdk.getIssuerOrigin() + '/api/v1/sessions/me',\n method: 'DELETE',\n withCredentials: true\n });\n}\n\nfunction refreshSession(sdk) {\n return post(sdk, '/api/v1/sessions/me/lifecycle/refresh', {}, { withCredentials: true });\n}\n\nfunction setCookieAndRedirect(sdk, sessionToken, redirectUrl) {\n redirectUrl = redirectUrl || window.location.href;\n window.location.assign(sdk.getIssuerOrigin() + '/login/sessionCookieRedirect' +\n toQueryString({\n checkAccountSetupComplete: true,\n token: sessionToken,\n redirectUrl: redirectUrl\n }));\n}\n\nexport {\n sessionExists,\n getSession,\n closeSession,\n refreshSession,\n setCookieAndRedirect\n};\n", "import { SessionAPI } from './types';\nimport { closeSession, getSession, refreshSession, sessionExists, setCookieAndRedirect } from './api';\nimport { OktaAuthBaseInterface } from '../base/types';\n\nexport function createSessionApi(sdk: OktaAuthBaseInterface): SessionAPI {\n const session = {\n close: closeSession.bind(null, sdk),\n exists: sessionExists.bind(null, sdk),\n get: getSession.bind(null, sdk),\n refresh: refreshSession.bind(null, sdk),\n setCookieAndRedirect: setCookieAndRedirect.bind(null, sdk)\n };\n return session;\n}\n", "import { OktaAuthHttpInterface, OktaAuthHttpOptions } from '../http/types';\nimport { OktaAuthConstructor } from '../base/types';\nimport { createSessionApi } from './factory';\nimport {\n OktaAuthSessionInterface, SessionAPI,\n} from './types';\nimport { StorageManagerInterface } from '../storage/types';\n\nexport function mixinSession\n<\n S extends StorageManagerInterface = StorageManagerInterface,\n O extends OktaAuthHttpOptions = OktaAuthHttpOptions,\n TBase extends OktaAuthConstructor>\n = OktaAuthConstructor>\n>\n(Base: TBase): TBase & OktaAuthConstructor>\n{\n return class OktaAuthSession extends Base implements OktaAuthSessionInterface\n {\n session: SessionAPI;\n\n constructor(...args: any[]) {\n super(...args);\n\n this.session = createSessionApi(this);\n }\n\n // Ends the current Okta SSO session without redirecting to Okta.\n closeSession(): Promise {\n return this.session.close() // DELETE /api/v1/sessions/me\n .then(async () => {\n // Clear all local tokens\n this.clearStorage();\n return true;\n })\n .catch(function(e) {\n if (e.name === 'AuthApiError' && e.errorCode === 'E0000007') {\n // Session does not exist or has already been closed\n return false;\n }\n throw e;\n });\n }\n };\n}\n", "import { StorageManagerConstructor } from '../storage/types';\nimport { OktaAuthConstructor, OktaAuthOptionsConstructor } from '../base/types';\n\nimport { OktaAuthCoreInterface, OktaAuthCoreOptions } from './types';\nimport { createOktaAuthBase } from '../base';\nimport { mixinStorage } from '../storage/mixin';\nimport { mixinHttp } from '../http/mixin';\nimport { mixinOAuth } from '../oidc/mixin';\nimport {\n OAuthStorageManagerInterface,\n PKCETransactionMeta,\n TransactionManagerConstructor,\n TransactionManagerInterface\n} from '../oidc/types';\nimport { mixinCore } from './mixin';\nimport { mixinSession } from '../session/mixin';\n\nexport function createOktaAuthCore<\n M extends PKCETransactionMeta = PKCETransactionMeta,\n S extends OAuthStorageManagerInterface = OAuthStorageManagerInterface,\n O extends OktaAuthCoreOptions = OktaAuthCoreOptions,\n TM extends TransactionManagerInterface = TransactionManagerInterface\n>(\n StorageManagerConstructor: StorageManagerConstructor,\n OptionsConstructor: OktaAuthOptionsConstructor,\n TransactionManagerConstructor: TransactionManagerConstructor\n): OktaAuthConstructor>\n{\n const Base = createOktaAuthBase(OptionsConstructor);\n const WithStorage = mixinStorage(Base, StorageManagerConstructor);\n const WithHttp = mixinHttp(WithStorage);\n const WithSession = mixinSession(WithHttp);\n const WithOAuth = mixinOAuth(WithSession, TransactionManagerConstructor);\n const Core = mixinCore(WithOAuth);\n return Core;\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { AuthSdkError } from '../errors';\nimport { isFingerprintSupported } from '../features';\nimport {\n addListener,\n removeListener\n} from '../oidc';\nimport { FingerprintOptions } from '../base/types';\nimport { OktaAuthHttpInterface } from '../http/types';\n\nconst isMessageFromCorrectSource = (iframe: HTMLIFrameElement, event: MessageEvent)\n: boolean => event.source === iframe.contentWindow;\n\nexport default function fingerprint(sdk: OktaAuthHttpInterface, options?: FingerprintOptions): Promise {\n if (!isFingerprintSupported()) {\n return Promise.reject(new AuthSdkError('Fingerprinting is not supported on this device'));\n }\n\n const container = options?.container ?? document.body;\n let timeout: NodeJS.Timeout;\n let iframe: HTMLIFrameElement;\n let listener: (this: Window, ev: MessageEvent) => void;\n const promise = new Promise(function (resolve, reject) {\n iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n\n // eslint-disable-next-line complexity\n listener = function listener(e: MessageEvent) {\n if (!isMessageFromCorrectSource(iframe, e)) {\n return;\n }\n\n if (!e || !e.data || e.origin !== sdk.getIssuerOrigin()) {\n return;\n }\n\n let msg;\n try {\n msg = JSON.parse(e.data);\n } catch (err) {\n // iframe messages should all be parsable\n // skip not parsable messages come from other sources in same origin (browser extensions)\n // TODO: add namespace flag in okta-core to distinguish messages that come from other sources\n return;\n }\n\n if (!msg) { return; }\n if (msg.type === 'FingerprintAvailable') {\n return resolve(msg.fingerprint as string);\n } else if (msg.type === 'FingerprintServiceReady') {\n iframe?.contentWindow?.postMessage(JSON.stringify({\n type: 'GetFingerprint'\n }), e.origin);\n } else {\n return reject(new AuthSdkError('No data'));\n }\n };\n addListener(window, 'message', listener);\n\n iframe.src = sdk.getIssuerOrigin() + '/auth/services/devicefingerprint';\n container.appendChild(iframe);\n\n timeout = setTimeout(function() {\n reject(new AuthSdkError('Fingerprinting timed out'));\n }, options?.timeout || 15000);\n });\n\n return promise.finally(function() {\n clearTimeout(timeout);\n removeListener(window, 'message', listener);\n if (container.contains(iframe)) {\n iframe.parentElement?.removeChild(iframe);\n }\n }) as Promise;\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { base64UrlToBuffer, bufferToBase64Url } from '../crypto/base64';\nimport {\n ActivationData,\n ChallengeData,\n IdxAuthenticator,\n} from './types';\n\n\n// Get known credentials from list of enrolled authenticators\nconst getEnrolledCredentials = (authenticatorEnrollments: IdxAuthenticator[] = []) => {\n const credentials: PublicKeyCredentialDescriptor[] = [];\n authenticatorEnrollments.forEach((enrollement) => {\n if (enrollement.key === 'webauthn') {\n credentials.push({\n type: 'public-key',\n id: base64UrlToBuffer(enrollement.credentialId),\n });\n }\n });\n return credentials;\n};\n\n// Build options for navigator.credentials.create\n// https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create\nexport const buildCredentialCreationOptions = (\n activationData: ActivationData, authenticatorEnrollments: IdxAuthenticator[]\n) => {\n return {\n publicKey: {\n rp: activationData.rp,\n user: {\n id: base64UrlToBuffer(activationData.user.id),\n name: activationData.user.name,\n displayName: activationData.user.displayName\n },\n challenge: base64UrlToBuffer(activationData.challenge),\n pubKeyCredParams: activationData.pubKeyCredParams,\n attestation: activationData.attestation,\n authenticatorSelection: activationData.authenticatorSelection,\n excludeCredentials: getEnrolledCredentials(authenticatorEnrollments),\n }\n } as CredentialCreationOptions;\n};\n\n\n// Build options for navigator.credentials.get\n// https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get\nexport const buildCredentialRequestOptions = (\n challengeData: ChallengeData, authenticatorEnrollments: IdxAuthenticator[]\n) => {\n return {\n publicKey: {\n challenge: base64UrlToBuffer(challengeData.challenge),\n userVerification: challengeData.userVerification,\n allowCredentials: getEnrolledCredentials(authenticatorEnrollments),\n }\n } as CredentialRequestOptions;\n};\n\n// Build attestation for webauthn enroll\n// https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse\nexport const getAttestation = (credential: PublicKeyCredential) => {\n const response = credential.response as AuthenticatorAttestationResponse;\n const id = credential.id;\n const clientData = bufferToBase64Url(response.clientDataJSON);\n const attestation = bufferToBase64Url(response.attestationObject);\n return {\n id,\n clientData,\n attestation\n };\n};\n\n// Build assertion for webauthn verification\n// https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAssertionResponse\nexport const getAssertion = (credential: PublicKeyCredential) => {\n const response = credential.response as AuthenticatorAssertionResponse;\n const id = credential.id;\n const clientData = bufferToBase64Url(response.clientDataJSON);\n const authenticatorData = bufferToBase64Url(response.authenticatorData);\n const signatureData = bufferToBase64Url(response.signature);\n return {\n id,\n clientData,\n authenticatorData,\n signatureData\n };\n};\n", "import { FingerprintAPI, OktaAuthConstructor } from '../base/types';\nimport { OktaAuthOAuthInterface } from '../oidc/types';\nimport {\n IdxAPI, \n IdxTransactionManagerInterface, \n OktaAuthIdxInterface, \n OktaAuthIdxConstructor, \n OktaAuthIdxOptions, \n WebauthnAPI\n} from './types';\nimport { IdxTransactionMeta } from './types/meta';\nimport { IdxStorageManagerInterface } from './types/storage';\nimport { createIdxAPI } from './factory/api';\nimport fingerprint from '../browser/fingerprint';\nimport * as webauthn from './webauthn';\n\nexport function mixinIdx\n<\n M extends IdxTransactionMeta = IdxTransactionMeta,\n S extends IdxStorageManagerInterface = IdxStorageManagerInterface,\n O extends OktaAuthIdxOptions = OktaAuthIdxOptions,\n TM extends IdxTransactionManagerInterface = IdxTransactionManagerInterface,\n TBase extends OktaAuthConstructor>\n = OktaAuthConstructor>\n>\n(Base: TBase): TBase & OktaAuthIdxConstructor>\n{\n return class OktaAuthIdx extends Base implements OktaAuthIdxInterface\n {\n idx: IdxAPI;\n fingerprint: FingerprintAPI;\n static webauthn: WebauthnAPI = webauthn;\n \n constructor(...args: any[]) {\n super(...args);\n this.idx = createIdxAPI(this);\n this.fingerprint = fingerprint.bind(null, this);\n }\n };\n}\n", "import { createOktaAuthCore } from '../../core/factory';\nimport { OktaAuthOptionsConstructor } from '../../base/types';\nimport { StorageManagerConstructor } from '../../storage/types';\nimport { IdxTransactionManagerInterface, OktaAuthIdxInterface, OktaAuthIdxConstructor } from '../types/api';\nimport { IdxTransactionMeta } from '../types/meta';\nimport { IdxStorageManagerInterface } from '../types/storage';\nimport { OktaAuthIdxOptions } from '../types/options';\nimport { mixinIdx } from '../mixin';\nimport { TransactionManagerConstructor } from '../../oidc/types';\nimport { OktaAuthCoreInterface } from '../../core/types';\n\nexport function createOktaAuthIdx<\n M extends IdxTransactionMeta = IdxTransactionMeta,\n S extends IdxStorageManagerInterface = IdxStorageManagerInterface,\n O extends OktaAuthIdxOptions = OktaAuthIdxOptions,\n TM extends IdxTransactionManagerInterface = IdxTransactionManagerInterface\n>(\n StorageManagerConstructor: StorageManagerConstructor,\n OptionsConstructor: OktaAuthOptionsConstructor,\n TransactionManagerConstructor: TransactionManagerConstructor\n)\n: OktaAuthIdxConstructor & OktaAuthCoreInterface>\n{\n const Core = createOktaAuthCore(\n StorageManagerConstructor,\n OptionsConstructor,\n TransactionManagerConstructor\n );\n const WithIdx = mixinIdx(Core);\n return WithIdx;\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { OktaAuthBaseOptions } from './types';\n\nexport function createBaseOptionsConstructor() {\n\n return class BaseOptionsConstructor implements Required {\n devMode: boolean;\n\n constructor(args: any) {\n this.devMode = !!args.devMode;\n }\n };\n\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n/* eslint-disable complexity */\nimport { StorageManagerOptions, StorageUtil, OktaAuthStorageOptions } from '../types';\nimport { warn } from '../../util';\n\nimport { default as browserStorage } from '../../browser/browserStorage';\n\nexport function getStorage(): StorageUtil {\n const storageUtil = Object.assign({}, browserStorage, {\n inMemoryStore: {} // create unique storage for this instance\n });\n return storageUtil;\n}\n\nexport const STORAGE_MANAGER_OPTIONS: StorageManagerOptions = {\n token: {\n storageTypes: [\n 'localStorage',\n 'sessionStorage',\n 'cookie'\n ]\n },\n cache: {\n storageTypes: [\n 'localStorage',\n 'sessionStorage',\n 'cookie'\n ]\n },\n transaction: {\n storageTypes: [\n 'sessionStorage',\n 'localStorage',\n 'cookie'\n ]\n },\n 'shared-transaction': {\n storageTypes: [\n 'localStorage'\n ]\n },\n 'original-uri': {\n storageTypes: [\n 'localStorage'\n ]\n }\n};\n\nexport function getCookieSettings(args: OktaAuthStorageOptions = {}, isHTTPS: boolean) {\n // Secure cookies will be automatically used on a HTTPS connection\n // Non-secure cookies will be automatically used on a HTTP connection\n // secure option can override the automatic behavior\n var cookieSettings = args.cookies || {};\n if (typeof cookieSettings.secure === 'undefined') {\n cookieSettings.secure = isHTTPS;\n }\n if (typeof cookieSettings.sameSite === 'undefined') {\n cookieSettings.sameSite = cookieSettings.secure ? 'none' : 'lax';\n }\n\n // If secure=true, but the connection is not HTTPS, set secure=false.\n if (cookieSettings.secure && !isHTTPS) {\n // eslint-disable-next-line no-console\n warn(\n 'The current page is not being served with the HTTPS protocol.\\n' +\n 'For security reasons, we strongly recommend using HTTPS.\\n' +\n 'If you cannot use HTTPS, set \"cookies.secure\" option to false.'\n );\n cookieSettings.secure = false;\n }\n\n // Chrome >= 80 will block cookies with SameSite=None unless they are also Secure\n // If sameSite=none, but the connection is not HTTPS, set sameSite=lax.\n if (cookieSettings.sameSite === 'none' && !cookieSettings.secure) {\n cookieSettings.sameSite = 'lax';\n }\n\n return cookieSettings;\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { createBaseOptionsConstructor } from '../../base';\nimport { CookieOptions, OktaAuthStorageOptions, StorageManagerOptions, StorageUtil } from '../types';\nimport { getStorage, STORAGE_MANAGER_OPTIONS, getCookieSettings } from './node';\nimport { isHTTPS } from '../../features';\n\nexport function createStorageOptionsConstructor() {\n\n const BaseOptionsConstructor = createBaseOptionsConstructor();\n return class StorageOptionsConstructor extends BaseOptionsConstructor implements Required {\n cookies: CookieOptions;\n storageUtil: StorageUtil;\n storageManager: StorageManagerOptions;\n \n constructor(args: any) {\n super(args);\n this.cookies = getCookieSettings(args, isHTTPS())!;\n this.storageUtil = args.storageUtil || getStorage();\n this.storageManager = { ...STORAGE_MANAGER_OPTIONS, ...args.storageManager };\n }\n };\n}\n", "/*!\n * Copyright (c) 2018-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport crossFetch from 'cross-fetch';\nimport { FetchOptions, HttpResponse } from '../http/types';\n\n// content-type = application/json OR application/ion+json\nconst appJsonContentTypeRegex = /application\\/\\w*\\+?json/;\n\nfunction readData(response: Response): Promise {\n if (response.headers.get('Content-Type') &&\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n response.headers.get('Content-Type')!.toLowerCase().indexOf('application/json') >= 0) {\n return response.json()\n // JSON parse can fail if response is not a valid object\n .catch(e => {\n return {\n error: e,\n errorSummary: 'Could not parse server response'\n };\n });\n } else {\n return response.text();\n }\n}\n\nfunction formatResult(status: number, data: object | string, response: Response) {\n const isObject = typeof data === 'object';\n const headers = {};\n for (const pair of (response.headers as any).entries()) {\n headers[pair[0]] = pair[1];\n }\n const result: HttpResponse = {\n responseText: isObject ? JSON.stringify(data) : data as string,\n status: status,\n headers\n };\n if (isObject) {\n result.responseType = 'json';\n result.responseJSON = data as object;\n }\n return result;\n}\n\n/* eslint-disable complexity */\nfunction fetchRequest(method: string, url: string, args: FetchOptions) {\n var body = args.data;\n var headers = args.headers || {};\n var contentType = (headers['Content-Type'] || headers['content-type'] || '');\n\n if (body && typeof body !== 'string') {\n // JSON encode body (if appropriate)\n if (appJsonContentTypeRegex.test(contentType)) {\n body = JSON.stringify(body);\n }\n else if (contentType === 'application/x-www-form-urlencoded') {\n body = Object.entries(body)\n .map( ([param, value]) => `${param}=${encodeURIComponent(value)}` )\n .join('&');\n }\n }\n\n var fetch = global.fetch || crossFetch;\n var fetchPromise = fetch(url, {\n method: method,\n headers: args.headers,\n body: body as string,\n credentials: args.withCredentials ? 'include' : 'omit'\n });\n\n if (!fetchPromise.finally) {\n fetchPromise = Promise.resolve(fetchPromise);\n }\n\n return fetchPromise.then(function(response) {\n var error = !response.ok;\n var status = response.status;\n return readData(response)\n .then(data => {\n return formatResult(status, data, response);\n })\n .then(result => {\n if (error || result.responseJSON?.error) {\n // Throwing result object since error handling is done in http.js\n throw result;\n }\n return result;\n });\n });\n}\n\nexport default fetchRequest;\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { createStorageOptionsConstructor } from '../storage';\nimport { HttpRequestClient, OktaAuthHttpOptions, RequestOptions } from './types';\nimport fetchRequest from '../fetch/fetchRequest';\n\nexport function createHttpOptionsConstructor() {\n const StorageOptionsConstructor = createStorageOptionsConstructor();\n return class HttpOptionsConstructor extends StorageOptionsConstructor implements Required {\n issuer: string;\n transformErrorXHR: (xhr: object) => any;\n headers: object;\n httpRequestClient: HttpRequestClient;\n httpRequestInterceptors: ((request: RequestOptions) => void)[];\n \n constructor(args: any) {\n super(args);\n this.issuer = args.issuer;\n this.transformErrorXHR = args.transformErrorXHR;\n this.headers = args.headers;\n this.httpRequestClient = args.httpRequestClient || fetchRequest;\n this.httpRequestInterceptors = args.httpRequestInterceptors;\n }\n };\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { DEFAULT_MAX_CLOCK_SKEW } from '../../constants';\nimport { removeTrailingSlash, toAbsoluteUrl } from '../../util/url';\nimport { isBrowser } from '../../features';\nimport { createHttpOptionsConstructor } from '../../http/options';\nimport {\n OAuthResponseMode,\n OAuthResponseType,\n OktaAuthOAuthInterface,\n OktaAuthOAuthOptions,\n SetLocationFunction,\n TokenManagerOptions,\n TransactionManagerOptions\n} from '../types';\nimport { enableSharedStorage } from './node';\nimport AuthSdkError from '../../errors/AuthSdkError';\n\nfunction assertValidConfig(args) {\n args = args || {};\n\n var scopes = args.scopes;\n if (scopes && !Array.isArray(scopes)) {\n throw new AuthSdkError('scopes must be a array of strings. ' +\n 'Required usage: new OktaAuth({scopes: [\"openid\", \"email\"]})');\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n var issuer = args.issuer!;\n if (!issuer) {\n throw new AuthSdkError('No issuer passed to constructor. ' + \n 'Required usage: new OktaAuth({issuer: \"https://{yourOktaDomain}.com/oauth2/{authServerId}\"})');\n }\n\n var isUrlRegex = new RegExp('^http?s?://.+');\n if (!isUrlRegex.test(issuer)) {\n throw new AuthSdkError('Issuer must be a valid URL. ' + \n 'Required usage: new OktaAuth({issuer: \"https://{yourOktaDomain}.com/oauth2/{authServerId}\"})');\n }\n\n if (issuer.indexOf('-admin.okta') !== -1) {\n throw new AuthSdkError('Issuer URL passed to constructor contains \"-admin\" in subdomain. ' +\n 'Required usage: new OktaAuth({issuer: \"https://{yourOktaDomain}.com})');\n }\n}\n\nexport function createOAuthOptionsConstructor() {\n const HttpOptionsConstructor = createHttpOptionsConstructor();\n return class OAuthOptionsConstructor\n extends HttpOptionsConstructor\n implements Required\n {\n // CustomUrls\n issuer: string;\n authorizeUrl: string;\n userinfoUrl: string;\n tokenUrl: string;\n revokeUrl: string;\n logoutUrl: string;\n \n // TokenParams\n pkce: boolean;\n clientId: string;\n redirectUri: string;\n responseType: OAuthResponseType | OAuthResponseType[];\n responseMode: OAuthResponseMode;\n state: string;\n scopes: string[];\n ignoreSignature: boolean;\n codeChallenge: string;\n codeChallengeMethod: string;\n acrValues: string;\n maxAge: string | number;\n dpop: boolean;\n\n // Additional options\n tokenManager: TokenManagerOptions;\n postLogoutRedirectUri: string;\n restoreOriginalUri: (oktaAuth: OktaAuthOAuthInterface, originalUri?: string) => Promise;\n transactionManager: TransactionManagerOptions;\n\n // For server-side web applications ONLY!\n clientSecret: string;\n setLocation: SetLocationFunction;\n\n // Workaround for bad client time/clock\n ignoreLifetime: boolean;\n maxClockSkew: number;\n\n\n // eslint-disable-next-line max-statements\n constructor(options: any) {\n super(options);\n \n assertValidConfig(options);\n \n this.issuer = removeTrailingSlash(options.issuer);\n this.tokenUrl = removeTrailingSlash(options.tokenUrl);\n this.authorizeUrl = removeTrailingSlash(options.authorizeUrl);\n this.userinfoUrl = removeTrailingSlash(options.userinfoUrl);\n this.revokeUrl = removeTrailingSlash(options.revokeUrl);\n this.logoutUrl = removeTrailingSlash(options.logoutUrl);\n\n this.pkce = options.pkce === false ? false : true; // PKCE defaults to true\n this.clientId = options.clientId;\n this.redirectUri = options.redirectUri;\n if (isBrowser()) {\n this.redirectUri = toAbsoluteUrl(options.redirectUri, window.location.origin); // allow relative URIs\n }\n this.responseType = options.responseType;\n this.responseMode = options.responseMode;\n this.state = options.state;\n this.scopes = options.scopes;\n // Give the developer the ability to disable token signature validation.\n this.ignoreSignature = !!options.ignoreSignature;\n this.codeChallenge = options.codeChallenge;\n this.codeChallengeMethod = options.codeChallengeMethod;\n this.acrValues = options.acrValues;\n this.maxAge = options.maxAge;\n this.dpop = options.dpop === true; // dpop defaults to false\n\n this.tokenManager = options.tokenManager;\n this.postLogoutRedirectUri = options.postLogoutRedirectUri;\n this.restoreOriginalUri = options.restoreOriginalUri;\n this.transactionManager = { enableSharedStorage, ...options.transactionManager };\n \n this.clientSecret = options.clientSecret;\n this.setLocation = options.setLocation;\n \n // As some end user's devices can have their date \n // and time incorrectly set, allow for the disabling\n // of the jwt liftetime validation\n this.ignoreLifetime = !!options.ignoreLifetime;\n\n // Digital clocks will drift over time, so the server\n // can misalign with the time reported by the browser.\n // The maxClockSkew allows relaxing the time-based\n // validation of tokens (in seconds, not milliseconds).\n // It currently defaults to 300, because 5 min is the\n // default maximum tolerance allowed by Kerberos.\n // (https://technet.microsoft.com/en-us/library/cc976357.aspx)\n if (!options.maxClockSkew && options.maxClockSkew !== 0) {\n this.maxClockSkew = DEFAULT_MAX_CLOCK_SKEW;\n } else {\n this.maxClockSkew = options.maxClockSkew;\n }\n\n }\n };\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { createOAuthOptionsConstructor } from '../oidc';\nimport { AuthState, OktaAuthCoreInterface, OktaAuthCoreOptions, ServiceManagerOptions } from './types';\n\n\nexport function createCoreOptionsConstructor()\n{\n const OAuthOptionsConstructor = createOAuthOptionsConstructor();\n return class CoreOptionsConstructor\n extends OAuthOptionsConstructor\n implements Required\n {\n services: ServiceManagerOptions;\n transformAuthState: (oktaAuth: OktaAuthCoreInterface, authState: AuthState) => Promise;\n\n constructor(options: any) {\n super(options);\n this.services = options.services;\n this.transformAuthState = options.transformAuthState;\n }\n };\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { createCoreOptionsConstructor } from '../core/options';\nimport { FlowIdentifier } from './types/FlowIdentifier';\nimport { OktaAuthIdxOptions } from './types/options';\n\n\nexport function createIdxOptionsConstructor() {\n const CoreOptionsConstructor = createCoreOptionsConstructor();\n return class IdxOptionsConstructor\n extends CoreOptionsConstructor \n implements Required\n {\n flow: FlowIdentifier;\n activationToken: string;\n recoveryToken: string;\n \n // BETA WARNING: configs in this section are subject to change without a breaking change notice\n idx: {\n useGenericRemediator?: boolean;\n exchangeCodeForTokens?: boolean;\n };\n \n constructor(options: any) {\n super(options);\n \n this.flow = options.flow;\n this.activationToken = options.activationToken;\n this.recoveryToken = options.recoveryToken;\n this.idx = options.idx;\n }\n };\n \n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\nimport AuthSdkError from '../errors/AuthSdkError';\nimport { StorageProvider, SimpleStorage } from './types';\n\n// formerly known as \"storageBuilder\". Represents an object saved under a key/name.\nexport class SavedObject implements StorageProvider {\n storageProvider: SimpleStorage;\n storageName: string;\n\n constructor(storage: SimpleStorage, storageName: string) {\n if (!storage) {\n throw new AuthSdkError('\"storage\" is required');\n }\n\n if (typeof storageName !== 'string' || !storageName.length) {\n throw new AuthSdkError('\"storageName\" is required');\n }\n\n this.storageName = storageName;\n this.storageProvider = storage;\n }\n\n //\n // SimpleStorage interface\n //\n\n getItem(key: string) {\n return this.getStorage()[key];\n }\n\n setItem(key: string, value: any) {\n return this.updateStorage(key, value);\n }\n\n removeItem(key: string) {\n return this.clearStorage(key);\n }\n\n //\n // StorageProvider interface\n //\n\n getStorage() {\n var storageString = this.storageProvider.getItem(this.storageName);\n storageString = storageString || '{}';\n try {\n return JSON.parse(storageString);\n } catch(e) {\n throw new AuthSdkError('Unable to parse storage string: ' + this.storageName);\n }\n }\n\n setStorage(obj?: any) {\n try {\n var storageString = obj ? JSON.stringify(obj) : '{}';\n this.storageProvider.setItem(this.storageName, storageString);\n } catch(e) {\n throw new AuthSdkError('Unable to set storage: ' + this.storageName);\n }\n }\n\n clearStorage(key?: string) {\n if (!key) {\n // clear all\n if (this.storageProvider.removeItem) {\n this.storageProvider.removeItem(this.storageName);\n } else {\n this.setStorage();\n }\n return;\n }\n\n var obj = this.getStorage();\n delete obj[key];\n this.setStorage(obj);\n }\n\n updateStorage(key, value) {\n var obj = this.getStorage();\n obj[key] = value;\n this.setStorage(obj);\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\n\nimport {\n TOKEN_STORAGE_NAME,\n CACHE_STORAGE_NAME,\n} from '../constants';\nimport {\n StorageUtil,\n StorageProvider,\n StorageOptions,\n CookieOptions,\n StorageManagerOptions,\n SimpleStorage,\n StorageManagerInterface\n} from './types';\nimport { SavedObject } from './SavedObject';\nimport { isBrowser } from '../features';\nimport { warn } from '../util';\n\nexport function logServerSideMemoryStorageWarning(options: StorageOptions) {\n if (!isBrowser() && !options.storageProvider && !options.storageKey) {\n // eslint-disable-next-line max-len\n warn('Memory storage can only support simple single user use case on server side, please provide custom storageProvider or storageKey if advanced scenarios need to be supported.');\n }\n}\n\n\nexport class BaseStorageManager implements StorageManagerInterface {\n storageManagerOptions: StorageManagerOptions;\n cookieOptions: CookieOptions;\n storageUtil: StorageUtil;\n\n constructor(storageManagerOptions: StorageManagerOptions, cookieOptions: CookieOptions, storageUtil: StorageUtil) {\n this.storageManagerOptions = storageManagerOptions;\n this.cookieOptions = cookieOptions;\n this.storageUtil = storageUtil;\n }\n\n // combines defaults in order\n getOptionsForSection(sectionName: string, overrideOptions?: StorageOptions) {\n return Object.assign({}, this.storageManagerOptions[sectionName], overrideOptions);\n }\n \n // generic method to get any available storage provider\n // eslint-disable-next-line complexity\n getStorage(options: StorageOptions): SimpleStorage {\n options = Object.assign({}, this.cookieOptions, options); // set defaults\n\n if (options.storageProvider) {\n return options.storageProvider;\n }\n\n let { storageType, storageTypes } = options;\n\n if(storageType === 'sessionStorage') {\n options.sessionCookie = true;\n }\n\n // If both storageType and storageTypes are specified, then storageType will be used first\n // If storageType cannot be used but it matches an entry in storageTypes, subsequent entries may be used as fallback\n // if storageType does not match an entry in storageTypes then storageType is used with no fallback.\n if (storageType && storageTypes) {\n const idx = storageTypes.indexOf(storageType);\n if (idx >= 0) {\n storageTypes = storageTypes.slice(idx);\n storageType = undefined;\n }\n }\n\n if (!storageType) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n storageType = this.storageUtil.findStorageType(storageTypes!);\n }\n return this.storageUtil.getStorageByType(storageType, options);\n }\n\n // access_token, id_token, refresh_token\n getTokenStorage(options?: StorageOptions): StorageProvider {\n options = this.getOptionsForSection('token', options);\n logServerSideMemoryStorageWarning(options);\n const storage = this.getStorage(options);\n const storageKey = options.storageKey || TOKEN_STORAGE_NAME;\n return new SavedObject(storage, storageKey);\n }\n\n // caches well-known response, among others\n getHttpCache(options?: StorageOptions): StorageProvider {\n options = this.getOptionsForSection('cache', options);\n const storage = this.getStorage(options);\n const storageKey = options.storageKey || CACHE_STORAGE_NAME;\n return new SavedObject(storage, storageKey);\n }\n\n}\n", "import {\n CookieOptions,\n StorageManagerOptions,\n StorageOptions,\n StorageUtil\n} from '../storage/types';\nimport { BaseStorageManager, logServerSideMemoryStorageWarning } from '../storage/BaseStorageManager';\nimport { TransactionStorage, OAuthTransactionMeta, OAuthStorageManagerInterface, PKCETransactionMeta } from './types';\nimport { SavedObject } from '../storage';\nimport { ORIGINAL_URI_STORAGE_NAME, SHARED_TRANSACTION_STORAGE_NAME, TRANSACTION_STORAGE_NAME } from '../constants';\n\n\nexport function createOAuthStorageManager()\n{\n return class OAuthStorageManager\n extends BaseStorageManager\n implements OAuthStorageManagerInterface\n {\n constructor(storageManagerOptions: StorageManagerOptions, cookieOptions: CookieOptions, storageUtil: StorageUtil) {\n super(storageManagerOptions, cookieOptions, storageUtil);\n }\n\n getTransactionStorage(options?: StorageOptions): TransactionStorage {\n options = this.getOptionsForSection('transaction', options);\n logServerSideMemoryStorageWarning(options);\n const storage = this.getStorage(options);\n const storageKey = options.storageKey || TRANSACTION_STORAGE_NAME;\n return new SavedObject(storage, storageKey);\n }\n\n getSharedTansactionStorage(options?: StorageOptions): TransactionStorage {\n options = this.getOptionsForSection('shared-transaction', options);\n logServerSideMemoryStorageWarning(options);\n const storage = this.getStorage(options);\n const storageKey = options.storageKey || SHARED_TRANSACTION_STORAGE_NAME;\n return new SavedObject(storage, storageKey);\n }\n\n getOriginalUriStorage(options?: StorageOptions): TransactionStorage {\n options = this.getOptionsForSection('original-uri', options);\n logServerSideMemoryStorageWarning(options);\n const storage = this.getStorage(options);\n const storageKey = options.storageKey || ORIGINAL_URI_STORAGE_NAME;\n return new SavedObject(storage, storageKey);\n }\n };\n\n}\n", "import { createOAuthStorageManager } from '../oidc/storage';\nimport { PKCETransactionMeta } from '../oidc/types';\n\nexport function createCoreStorageManager() {\n return createOAuthStorageManager();\n}\n", "import { CookieOptions, StorageManagerOptions, StorageOptions, StorageUtil } from '../storage/types';\nimport { IdxTransactionMeta } from './types';\nimport { SavedObject } from '../storage';\nimport { IDX_RESPONSE_STORAGE_NAME } from '../constants';\nimport { createCoreStorageManager } from '../core/storage';\nimport { IdxResponseStorage } from './types/storage';\nimport { isBrowser } from '../features';\nimport { warn } from '../util';\nimport AuthSdkError from '../errors/AuthSdkError';\n\nexport function createIdxStorageManager()\n{\n const CoreStorageManager = createCoreStorageManager();\n return class IdxStorageManager extends CoreStorageManager\n {\n constructor(storageManagerOptions: StorageManagerOptions, cookieOptions: CookieOptions, storageUtil: StorageUtil) {\n super(storageManagerOptions, cookieOptions, storageUtil);\n }\n\n // intermediate idxResponse\n // store for network traffic optimazation purpose\n // TODO: revisit in auth-js 6.0 epic JIRA: OKTA-399791\n getIdxResponseStorage(options?: StorageOptions): IdxResponseStorage | null {\n let storage;\n if (isBrowser()) {\n // on browser side only use memory storage \n try {\n storage = this.storageUtil.getStorageByType('memory', options);\n } catch (e) {\n // it's ok to miss response storage\n // eslint-disable-next-line max-len\n warn('No response storage found, you may want to provide custom implementation for intermediate idx responses to optimize the network traffic');\n }\n } else {\n // on server side re-use transaction custom storage\n const transactionStorage = this.getTransactionStorage(options);\n if (transactionStorage) {\n storage = {\n getItem: (key) => {\n const transaction = transactionStorage.getStorage();\n if (transaction && transaction[key]) {\n return transaction[key];\n }\n return null;\n },\n setItem: (key, val) => {\n const transaction = transactionStorage.getStorage();\n if (!transaction) {\n throw new AuthSdkError('Transaction has been cleared, failed to save idxState');\n }\n transaction[key] = val;\n transactionStorage.setStorage(transaction);\n },\n removeItem: (key) => {\n const transaction = transactionStorage.getStorage();\n if (!transaction) {\n return;\n }\n delete transaction[key];\n transactionStorage.setStorage(transaction);\n }\n };\n }\n }\n\n if (!storage) {\n return null;\n }\n\n return new SavedObject(storage, IDX_RESPONSE_STORAGE_NAME);\n }\n };\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\n\nimport { IdxTransactionMeta } from '../../idx/types/meta';\nimport { OAuthTransactionMeta, PKCETransactionMeta } from './meta';\nimport { OAuthStorageManagerInterface } from './storage';\n\nexport interface TransactionManagerOptions\n{\n storageManager?: OAuthStorageManagerInterface;\n enableSharedStorage?: boolean; // default true\n saveNonceCookie?: boolean; // default true\n saveStateCookie?: boolean; // default true\n saveParamsCookie?: boolean; // default true\n saveLastResponse?: boolean; // default true\n}\n\n\nexport type CustomAuthTransactionMeta = Record;\n\nexport type TransactionMeta =\n IdxTransactionMeta |\n PKCETransactionMeta |\n OAuthTransactionMeta |\n CustomAuthTransactionMeta;\n\n\nfunction isObjectWithProperties(obj) {\n if (!obj || typeof obj !== 'object' || Object.values(obj).length === 0) {\n return false;\n }\n return true;\n}\n\nexport function isOAuthTransactionMeta(obj: any): obj is OAuthTransactionMeta {\n if (!isObjectWithProperties(obj)) {\n return false;\n }\n return !!obj.redirectUri || !!obj.responseType;\n}\n\nexport function isPKCETransactionMeta(obj: any): obj is PKCETransactionMeta {\n if (!isOAuthTransactionMeta(obj)) {\n return false;\n }\n return !!(obj as any).codeVerifier;\n}\n\nexport function isIdxTransactionMeta(obj: any): obj is IdxTransactionMeta {\n if (!isPKCETransactionMeta(obj)) {\n return false;\n }\n return !!(obj as any).interactionHandle;\n}\n\nexport function isCustomAuthTransactionMeta(obj: any): obj is CustomAuthTransactionMeta {\n if (!isObjectWithProperties(obj)) {\n return false;\n }\n const isAllStringValues = Object.values(obj).find((value) => (typeof value !== 'string')) === undefined;\n return isAllStringValues;\n}\n\nexport function isTransactionMeta(obj: any): obj is TransactionMeta {\n if (isOAuthTransactionMeta(obj) || isCustomAuthTransactionMeta(obj)) {\n return true;\n }\n return false;\n}\n", "import { OAuthStorageManagerInterface, OAuthTransactionMeta, isTransactionMeta } from '../types';\n\nconst MAX_ENTRY_LIFETIME = 30 * 60 * 1000; // 30 minutes\n\nexport function pruneSharedStorage(storageManager: OAuthStorageManagerInterface) {\n const sharedStorage = storageManager.getSharedTansactionStorage();\n const entries = sharedStorage.getStorage();\n Object.keys(entries).forEach(state => {\n const entry = entries[state];\n const age = Date.now() - entry.dateCreated;\n if (age > MAX_ENTRY_LIFETIME) {\n delete entries[state];\n }\n });\n sharedStorage.setStorage(entries);\n}\n\nexport function saveTransactionToSharedStorage(\n storageManager: OAuthStorageManagerInterface, state: string, meta: M\n) {\n const sharedStorage = storageManager.getSharedTansactionStorage();\n const entries = sharedStorage.getStorage();\n entries[state] = {\n dateCreated: Date.now(),\n transaction: meta\n };\n sharedStorage.setStorage(entries);\n}\n\n\nexport function loadTransactionFromSharedStorage(\n storageManager: OAuthStorageManagerInterface, state: string\n) {\n const sharedStorage = storageManager.getSharedTansactionStorage();\n const entries = sharedStorage.getStorage();\n const entry = entries[state];\n if (entry && entry.transaction && isTransactionMeta(entry.transaction)) {\n return entry.transaction;\n }\n return null;\n}\n\nexport function clearTransactionFromSharedStorage(\n storageManager: OAuthStorageManagerInterface, state: string\n) {\n const sharedStorage = storageManager.getSharedTansactionStorage();\n const entries = sharedStorage.getStorage();\n delete entries[state];\n sharedStorage.setStorage(entries);\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { StorageProvider } from '../storage/types';\nimport {\n TransactionMeta,\n isTransactionMeta,\n TransactionMetaOptions,\n TransactionManagerOptions,\n OAuthTransactionMeta,\n OAuthStorageManagerInterface,\n ClearTransactionMetaOptions,\n TransactionManagerInterface,\n PKCETransactionMeta\n} from './types';\nimport { warn } from '../util';\nimport {\n clearTransactionFromSharedStorage,\n loadTransactionFromSharedStorage,\n pruneSharedStorage,\n saveTransactionToSharedStorage\n} from './util/sharedStorage';\n\n\nexport function createTransactionManager\n<\n M extends OAuthTransactionMeta = PKCETransactionMeta,\n S extends OAuthStorageManagerInterface = OAuthStorageManagerInterface\n>\n()\n{\n return class TransactionManager implements TransactionManagerInterface\n {\n options: TransactionManagerOptions;\n storageManager: S;\n enableSharedStorage: boolean;\n saveLastResponse: boolean;\n\n constructor(options: TransactionManagerOptions) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this.storageManager = options.storageManager! as S;\n this.enableSharedStorage = options.enableSharedStorage === false ? false : true;\n this.saveLastResponse = options.saveLastResponse === false ? false : true;\n this.options = options;\n }\n\n // eslint-disable-next-line complexity\n clear(options: ClearTransactionMetaOptions = {}) {\n const transactionStorage: StorageProvider = this.storageManager.getTransactionStorage();\n const meta = transactionStorage.getStorage();\n\n // Clear primary storage (by default, sessionStorage on browser)\n transactionStorage.clearStorage();\n\n // Usually we want to also clear shared storage unless another tab may need it to continue/complete a flow\n if (this.enableSharedStorage && options.clearSharedStorage !== false) {\n const state = options.state || meta?.state;\n if (state) {\n clearTransactionFromSharedStorage(this.storageManager, state);\n }\n }\n }\n\n // eslint-disable-next-line complexity\n save(meta: M, options: TransactionMetaOptions = {}) {\n // There must be only one transaction executing at a time.\n // Before saving, check to see if a transaction is already stored.\n // An existing transaction indicates a concurrency/race/overlap condition\n\n let storage: StorageProvider = this.storageManager.getTransactionStorage();\n const obj = storage.getStorage();\n // oie process may need to update transaction in the middle of process for tracking purpose\n // false alarm might be caused \n // TODO: revisit for a better solution, https://oktainc.atlassian.net/browse/OKTA-430919\n if (isTransactionMeta(obj) && !options.muteWarning) {\n // eslint-disable-next-line max-len\n warn('a saved auth transaction exists in storage. This may indicate another auth flow is already in progress.');\n }\n\n storage.setStorage(meta);\n\n // Shared storage allows continuation of transaction in another tab\n if (this.enableSharedStorage && meta.state) {\n saveTransactionToSharedStorage(this.storageManager, meta.state, meta);\n }\n }\n\n exists(options: TransactionMetaOptions = {}): boolean {\n try {\n const meta = this.load(options);\n return !!meta;\n } catch {\n return false;\n }\n }\n\n // load transaction meta from storage\n // eslint-disable-next-line complexity,max-statements\n load(options: TransactionMetaOptions = {}): TransactionMeta | null {\n\n let meta: TransactionMeta;\n\n // If state was passed, try loading transaction data from shared storage\n if (this.enableSharedStorage && options.state) {\n pruneSharedStorage(this.storageManager); // prune before load\n meta = loadTransactionFromSharedStorage(this.storageManager, options.state);\n if (isTransactionMeta(meta)) {\n return meta;\n }\n }\n\n let storage: StorageProvider = this.storageManager.getTransactionStorage();\n meta = storage.getStorage();\n if (isTransactionMeta(meta)) {\n // if we have meta in the new location, there is no need to go further\n return meta;\n }\n\n return null;\n }\n\n };\n}\n", "import { ClearTransactionMetaOptions, TransactionManagerOptions } from '../oidc/types';\nimport { createTransactionManager } from '../oidc/TransactionManager';\nimport { IdxTransactionMeta, IntrospectOptions } from './types';\nimport { isRawIdxResponse } from './types/idx-js';\nimport { IdxStorageManagerInterface, SavedIdxResponse } from './types/storage';\n\nexport function createIdxTransactionManager\n<\n M extends IdxTransactionMeta = IdxTransactionMeta,\n S extends IdxStorageManagerInterface = IdxStorageManagerInterface\n>\n()\n{\n const TransactionManager = createTransactionManager();\n return class IdxTransactionManager extends TransactionManager\n {\n constructor(options: TransactionManagerOptions) {\n super(options);\n }\n\n clear(options: ClearTransactionMetaOptions = {}) {\n super.clear(options);\n\n if (options.clearIdxResponse !== false) {\n this.clearIdxResponse();\n }\n }\n \n saveIdxResponse(data: SavedIdxResponse): void {\n if (!this.saveLastResponse) {\n return;\n }\n const storage = this.storageManager.getIdxResponseStorage();\n if (!storage) {\n return;\n }\n storage.setStorage(data);\n }\n\n // eslint-disable-next-line complexity\n loadIdxResponse(options?: IntrospectOptions): SavedIdxResponse | null {\n if (!this.saveLastResponse) {\n return null;\n }\n const storage = this.storageManager.getIdxResponseStorage();\n if (!storage) {\n return null;\n }\n const storedValue = storage.getStorage();\n if (!storedValue || !isRawIdxResponse(storedValue.rawIdxResponse)) {\n return null;\n }\n\n if (options) {\n const { stateHandle, interactionHandle } = options;\n // only perform this check if NOT using generic remediator\n if (!options.useGenericRemediator && stateHandle && storedValue.stateHandle !== stateHandle) {\n return null;\n }\n if (interactionHandle && storedValue.interactionHandle !== interactionHandle) {\n return null;\n }\n }\n\n return storedValue;\n }\n\n clearIdxResponse(): void {\n if (!this.saveLastResponse) {\n return;\n }\n const storage = this.storageManager.getIdxResponseStorage();\n storage?.clearStorage();\n }\n };\n}\n", "import { OktaAuthHttpInterface } from '../../http/types';\n\nexport type TransactionLink = {\n href: string;\n hints?: {\n allow?: string[];\n };\n}\n\nexport type TransactionLinks = {\n self: TransactionLink;\n [property: string]: TransactionLink;\n}\n\ntype TransactionOptions = {\n // TODO: move res type to http module\n res: {\n headers: Record;\n _links?: Record;\n [property: string]: unknown;\n };\n accessToken: string;\n};\n\nexport default class BaseTransaction {\n // Deprecated\n headers?: Record;\n\n constructor(oktaAuth: OktaAuthHttpInterface, options: TransactionOptions) {\n const { res } = options;\n const { headers, ...rest } = res;\n \n // assign required fields from res\n if (headers) {\n this.headers = headers;\n }\n\n // add all rest fields from res\n Object.keys(rest).forEach(key => {\n if (key === '_links') {\n return;\n }\n this[key] = rest[key];\n });\n }\n}\n\nexport interface TransactionType extends Function {\n new (oktaAuth: OktaAuthHttpInterface, options: TransactionOptions): T;\n prototype: T;\n}\n", "import { \n default as BaseTransaction,\n TransactionType,\n TransactionLinks\n} from './transactions/Base';\nimport { httpRequest } from '../http';\nimport { AuthSdkError } from '../errors';\nimport { MyAccountRequestOptions as RequestOptions } from './types';\nimport { OktaAuthOAuthInterface } from '../oidc/types';\n\ntype SendRequestOptions = RequestOptions & {\n url: string;\n method: string;\n}\n\n/* eslint-disable complexity */\nexport async function sendRequest<\n T extends BaseTransaction = BaseTransaction,\n N extends 'plural' | 'single' = 'single',\n NT = N extends 'plural' ? T[] : T\n> (\n oktaAuth: OktaAuthOAuthInterface, \n options: SendRequestOptions,\n TransactionClass: TransactionType = BaseTransaction as TransactionType,\n): Promise {\n const {\n accessToken: accessTokenObj\n } = oktaAuth.tokenManager.getTokensSync();\n \n const accessToken = options.accessToken || accessTokenObj?.accessToken;\n const issuer = oktaAuth.getIssuerOrigin();\n const { url, method, payload } = options;\n const requestUrl = url.startsWith(issuer!) ? url : `${issuer}${url}`;\n\n if (!accessToken) {\n throw new AuthSdkError('AccessToken is required to request MyAccount API endpoints.');\n }\n \n const res = await httpRequest(oktaAuth, {\n headers: { 'Accept': '*/*;okta-version=1.0.0' },\n accessToken,\n url: requestUrl,\n method,\n ...(payload && { args: payload })\n });\n\n let ret: T | T[];\n if (Array.isArray(res)) {\n ret = res.map(item => new TransactionClass(oktaAuth, { \n res: item, \n accessToken\n }));\n } else {\n ret = new TransactionClass(oktaAuth, { \n res, \n accessToken\n });\n }\n return ret as NT;\n}\n/* eslint-enable complexity */\n\nexport type GenerateRequestFnFromLinksOptions = {\n oktaAuth: OktaAuthOAuthInterface;\n accessToken: string;\n methodName: string;\n links: TransactionLinks;\n}\n\ntype IRequestFnFromLinks = (payload?) => Promise;\n\nexport function generateRequestFnFromLinks(\n {\n oktaAuth, \n accessToken,\n methodName,\n links,\n }: GenerateRequestFnFromLinksOptions,\n TransactionClass: TransactionType = BaseTransaction as TransactionType,\n): IRequestFnFromLinks {\n for (const method of ['GET', 'POST', 'PUT', 'DELETE']) {\n if (method.toLowerCase() === methodName) {\n const link = links.self;\n return (async (payload?) => sendRequest(oktaAuth, {\n accessToken,\n url: link.href,\n method,\n payload,\n }, TransactionClass));\n }\n }\n \n const link = links[methodName];\n if (!link) {\n throw new AuthSdkError(`No link is found with methodName: ${methodName}`);\n }\n\n return (async (payload?) => sendRequest(oktaAuth, {\n accessToken,\n url: link.href,\n method: link.hints!.allow![0],\n payload,\n }, TransactionClass));\n}\n", "import BaseTransaction from './Base';\n\nexport default class ProfileTransaction extends BaseTransaction {\n createdAt: string;\n modifiedAt: string;\n profile: Record;\n\n constructor(oktaAuth, options) {\n super(oktaAuth, options);\n\n const { createdAt, modifiedAt, profile } = options.res;\n this.createdAt = createdAt;\n this.modifiedAt = modifiedAt;\n this.profile = profile;\n }\n}\n", "import BaseTransaction from './Base';\n\nexport default class ProfileSchemaTransaction extends BaseTransaction {\n properties: Record;\n\n constructor(oktaAuth, options) {\n super(oktaAuth, options);\n\n this.properties = options.res.properties;\n }\n}\n", "import {\n OAuthStorageManagerInterface,\n OAuthTransactionMeta,\n OktaAuthOAuthInterface,\n OktaAuthOAuthOptions,\n PKCETransactionMeta\n} from '../oidc/types';\n\nexport type { \n EmailTransaction, \n EmailStatusTransaction,\n EmailChallengeTransaction,\n PhoneTransaction,\n ProfileTransaction,\n ProfileSchemaTransaction,\n PasswordTransaction,\n BaseTransaction\n} from './transactions';\n\nexport enum EmailRole {\n PRIMARY = 'PRIMARY',\n SECONDARY = 'SECONDARY'\n}\n\nexport enum Status {\n VERIFIED = 'VERIFIED',\n UNVERIFIED = 'UNVERIFIED'\n}\n\nexport enum PasswordStatus {\n NOT_ENROLLED = 'NOT_ENROLLED',\n ACTIVE = 'ACTIVE'\n}\n\nexport type EmailProfile = {\n email: string;\n}\n\nexport type AddEmailPayload = {\n profile: {\n email: string;\n };\n sendEmail: boolean;\n role: EmailRole;\n}\n\nexport type PhoneProfile = {\n profile: {\n phoneNumber: string;\n };\n}\n\nexport type AddPhonePayload = {\n profile: {\n phoneNumber: string;\n };\n sendCode: boolean;\n method: string;\n};\n\nexport type ChallengePhonePayload = {\n method: string;\n}\n\nexport type VerificationPayload = {\n verificationCode: string;\n};\n\nexport type EnrollPasswordPayload = {\n profile: {\n password: string;\n }\n}\n\nexport type UpdatePasswordPayload = {\n profile: {\n password: string;\n currentPassword?: string;\n }\n}\n\nexport type UpdateProfilePayload = {\n profile: {\n firstName?: string;\n lastName?: string;\n email?: string;\n login?: string;\n [property: string]: any;\n };\n};\n\nexport type MyAccountRequestOptions = {\n id?: string;\n emailId?: string;\n challengeId?: string;\n payload?: AddEmailPayload \n | AddPhonePayload \n | ChallengePhonePayload\n | VerificationPayload \n | UpdateProfilePayload\n | EnrollPasswordPayload\n | UpdatePasswordPayload;\n accessToken?: string;\n}\n\nexport type IAPIFunction = (\n oktaAuth: OktaAuthOAuthInterface, \n options?: MyAccountRequestOptions\n) => Promise;\n\nexport interface OktaAuthMyAccountInterface\n<\n M extends OAuthTransactionMeta = PKCETransactionMeta,\n S extends OAuthStorageManagerInterface = OAuthStorageManagerInterface,\n O extends OktaAuthOAuthOptions = OktaAuthOAuthOptions\n> \n extends OktaAuthOAuthInterface\n{\n myaccount;\n}\n", "import { sendRequest } from './request';\nimport { IAPIFunction } from './types';\nimport {\n ProfileTransaction,\n ProfileSchemaTransaction\n} from './transactions';\n\n/**\n * @scope: okta.myAccount.profile.read\n */\nexport const getProfile: IAPIFunction = async (oktaAuth, options?) => {\n const transaction = await sendRequest(oktaAuth, {\n url: '/idp/myaccount/profile',\n method: 'GET',\n accessToken: options?.accessToken,\n }, ProfileTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.profile.manage\n */\nexport const updateProfile: IAPIFunction = async (\n oktaAuth, \n options\n) => {\n const { payload, accessToken } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: '/idp/myaccount/profile',\n method: 'PUT',\n payload,\n accessToken,\n }, ProfileTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.profile.read\n */\nexport const getProfileSchema: IAPIFunction = async (\n oktaAuth, \n options?\n): Promise => {\n const transaction = await sendRequest(oktaAuth, {\n url: '/idp/myaccount/profile/schema',\n method: 'GET',\n accessToken: options?.accessToken,\n }, ProfileSchemaTransaction);\n return transaction;\n};\n", "import { EmailProfile, Status } from '../types';\nimport BaseTransaction from './Base';\n\nexport default class EmailStatusTransaction extends BaseTransaction {\n id: string;\n expiresAt: string;\n profile: EmailProfile;\n status: Status;\n\n constructor(oktaAuth, options) {\n super(oktaAuth, options);\n\n const { res } = options;\n // assign required fields from res\n const { id, profile, expiresAt, status } = res;\n this.id = id;\n this.expiresAt = expiresAt;\n this.profile = profile;\n this.status = status;\n }\n}\n", "import EmailStatusTransaction from './EmailStatusTransaction';\nimport { \n EmailProfile, \n Status,\n VerificationPayload, \n} from '../types';\nimport BaseTransaction from './Base';\nimport { generateRequestFnFromLinks } from '../request';\n\nexport default class EmailChallengeTransaction extends BaseTransaction {\n id: string;\n expiresAt: string;\n profile: EmailProfile;\n status: Status;\n\n poll: () => Promise;\n // eslint-disable-next-line no-use-before-define\n verify: (payload: VerificationPayload) => Promise;\n\n constructor(oktaAuth, options) {\n super(oktaAuth, options);\n\n const { accessToken, res } = options;\n // assign required fields from res\n const { id, expiresAt, profile, status, _links } = res;\n this.id = id;\n this.expiresAt = expiresAt;\n this.profile = profile;\n this.status = status;\n\n // assign transformed fns to transaction\n this.poll = async () => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'poll', \n links: _links,\n }, EmailStatusTransaction);\n return await fn();\n };\n this.verify = async (payload) => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'verify', \n links: _links,\n }, EmailChallengeTransaction);\n return await fn(payload);\n };\n }\n}\n", "import EmailChallengeTransaction from './EmailChallengeTransaction';\nimport EmailStatusTransaction from './EmailStatusTransaction';\nimport { EmailProfile, EmailRole, Status, VerificationPayload } from '../types';\nimport BaseTransaction from './Base';\nimport { generateRequestFnFromLinks } from '../request';\n\nexport default class EmailTransaction extends BaseTransaction {\n id: string;\n profile: EmailProfile;\n roles: EmailRole[];\n status: Status;\n\n // eslint-disable-next-line no-use-before-define\n get: () => Promise;\n delete: () => Promise;\n challenge: () => Promise;\n poll?: () => Promise;\n verify?: (payload: VerificationPayload) => Promise;\n\n constructor(oktaAuth, options) {\n super(oktaAuth, options);\n\n const { accessToken, res } = options;\n // assign required fields from res\n const { id, profile, roles, status, _links } = res;\n this.id = id;\n this.profile = profile;\n this.roles = roles;\n this.status = status;\n\n // assign transformed fns to transaction\n this.get = async () => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'get', \n links: _links,\n }, EmailTransaction);\n return await fn();\n };\n this.delete = async () => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'delete', \n links: _links \n });\n return await fn();\n };\n this.challenge = async () => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'challenge', \n links: _links,\n }, EmailChallengeTransaction);\n return await fn();\n };\n if (_links.poll) {\n this.poll = async () => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'poll', \n links: _links,\n }, EmailStatusTransaction);\n return await fn();\n };\n }\n if (_links.verify) {\n this.verify = async (payload: VerificationPayload) => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'verify', \n links: _links,\n });\n return await fn(payload);\n };\n }\n }\n}\n", "import { sendRequest } from './request';\nimport { IAPIFunction } from './types';\nimport {\n BaseTransaction, \n EmailTransaction, \n EmailChallengeTransaction \n} from './transactions';\n\n/**\n * @scope: okta.myAccount.email.read\n */\nexport const getEmails: IAPIFunction = async (\n oktaAuth,\n options?\n) => {\n const transaction = await sendRequest(oktaAuth, {\n url: '/idp/myaccount/emails',\n method: 'GET',\n accessToken: options?.accessToken\n }, EmailTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.email.read\n */\nexport const getEmail: IAPIFunction = async (\n oktaAuth, \n options\n) => {\n const { id, accessToken } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: `/idp/myaccount/emails/${id}`,\n method: 'GET',\n accessToken,\n }, EmailTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.email.manage\n */\nexport const addEmail: IAPIFunction = async (\n oktaAuth, \n options\n): Promise => {\n const { accessToken, payload } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: '/idp/myaccount/emails',\n method: 'POST',\n payload,\n accessToken,\n }, EmailTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.email.manage\n */\nexport const deleteEmail: IAPIFunction = async (\n oktaAuth, \n options\n) => {\n const { id, accessToken } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: `/idp/myaccount/emails/${id}`,\n method: 'DELETE',\n accessToken\n });\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.email.read\n */\nexport const sendEmailChallenge: IAPIFunction = async (\n oktaAuth, \n options\n) => {\n const { id, accessToken } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: `/idp/myaccount/emails/${id}/challenge`,\n method: 'POST',\n accessToken,\n }, EmailChallengeTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.email.read\n */\nexport const getEmailChallenge: IAPIFunction = async (\n oktaAuth, \n options\n) => {\n const { emailId, challengeId, accessToken } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: `/idp/myaccount/emails/${emailId}/challenge/${challengeId}`,\n method: 'POST',\n accessToken,\n }, EmailChallengeTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.email.manage\n */\nexport const verifyEmailChallenge: IAPIFunction = async (\n oktaAuth,\n options\n) => {\n const { emailId, challengeId, payload, accessToken } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: `/idp/myaccount/emails/${emailId}/challenge/${challengeId}/verify`,\n method: 'POST',\n payload,\n accessToken\n });\n return transaction;\n};\n", "import { ChallengePhonePayload, PhoneProfile, Status, VerificationPayload } from '../types';\nimport BaseTransaction from './Base';\nimport { generateRequestFnFromLinks } from '../request';\n\nexport default class PhoneTransaction extends BaseTransaction {\n id: string;\n profile: PhoneProfile;\n status: Status;\n\n // eslint-disable-next-line no-use-before-define\n get: () => Promise;\n delete: () => Promise;\n challenge: (payload: ChallengePhonePayload) => Promise;\n verify?: (payload: VerificationPayload) => Promise;\n\n constructor(oktaAuth, options) {\n super(oktaAuth, options);\n\n const { res, accessToken } = options;\n // assign required fields from res\n const { id, profile, status, _links } = res;\n this.id = id;\n this.profile = profile;\n this.status = status;\n\n // assign transformed fns to transaction\n this.get = async () => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'get', \n links: _links,\n }, PhoneTransaction);\n return await fn();\n };\n this.delete = async () => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'delete', \n links: _links \n });\n return await fn();\n };\n this.challenge = async (payload) => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'challenge', \n links: _links \n });\n return await fn(payload);\n };\n if (_links.verify) {\n this.verify = async (payload) => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'verify', \n links: _links \n });\n return await fn(payload);\n } ;\n }\n }\n}\n", "import { sendRequest } from './request';\nimport { IAPIFunction } from './types';\nimport {\n BaseTransaction, \n PhoneTransaction\n} from './transactions';\n\n/**\n * @scope: okta.myAccount.phone.read\n */\nexport const getPhones: IAPIFunction = async (\n oktaAuth,\n options?\n) => {\n const transaction = await sendRequest(oktaAuth, {\n url: '/idp/myaccount/phones',\n method: 'GET',\n accessToken: options?.accessToken,\n }, PhoneTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.phone.read\n */\nexport const getPhone: IAPIFunction = async (\n oktaAuth,\n options\n) => {\n const { accessToken, id } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: `/idp/myaccount/phones/${id}`,\n method: 'GET',\n accessToken,\n }, PhoneTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.phone.manage\n */\nexport const addPhone: IAPIFunction = async (\n oktaAuth, \n options\n): Promise => {\n const { accessToken, payload } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: '/idp/myaccount/phones',\n method: 'POST',\n payload,\n accessToken,\n }, PhoneTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.phone.manage\n */\nexport const deletePhone: IAPIFunction = async (\n oktaAuth, \n options\n) => {\n const { id, accessToken } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: `/idp/myaccount/phones/${id}`,\n method: 'DELETE',\n accessToken,\n });\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.phone.manage\n */\nexport const sendPhoneChallenge: IAPIFunction = async (\n oktaAuth, \n options\n) => {\n const { accessToken, id, payload } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: `/idp/myaccount/phones/${id}/challenge`,\n method: 'POST',\n payload,\n accessToken\n });\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.phone.manage\n */\nexport const verifyPhoneChallenge: IAPIFunction = async (\n oktaAuth,\n options\n) => {\n const { id, payload, accessToken } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: `/idp/myaccount/phones/${id}/verify`,\n method: 'POST',\n payload,\n accessToken\n });\n return transaction;\n};\n", "import { EnrollPasswordPayload, UpdatePasswordPayload, PasswordStatus } from '../types';\nimport BaseTransaction from './Base';\nimport { generateRequestFnFromLinks } from '../request';\n\nexport default class PasswordTransaction extends BaseTransaction {\n id: string;\n created: string;\n lastUpdated: string;\n status: PasswordStatus;\n\n // eslint-disable-next-line no-use-before-define\n get?: () => Promise;\n // eslint-disable-next-line no-use-before-define\n enroll?: (payload: EnrollPasswordPayload) => Promise;\n // eslint-disable-next-line no-use-before-define\n update?: (payload: UpdatePasswordPayload) => Promise;\n delete?: () => Promise;\n\n constructor(oktaAuth, options) {\n super(oktaAuth, options);\n\n const { res, accessToken } = options;\n // assign required fields from res\n const { id, status, created, lastUpdated, _links } = res;\n this.id = id;\n this.status = status;\n this.created = created;\n this.lastUpdated = lastUpdated;\n\n // assign transformed fns to transaction\n if (this.status == PasswordStatus.NOT_ENROLLED) {\n this.enroll = async (payload) => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'enroll',\n links: _links,\n }, PasswordTransaction);\n return await fn(payload);\n };\n }\n else {\n this.get = async () => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'get',\n links: _links,\n }, PasswordTransaction);\n return await fn();\n };\n\n this.update = async (payload) => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'put', \n links: _links,\n }, PasswordTransaction);\n return await fn(payload);\n };\n \n this.delete = async () => {\n const fn = generateRequestFnFromLinks({ \n oktaAuth, \n accessToken, \n methodName: 'delete', \n links: _links \n });\n return await fn();\n };\n }\n }\n}\n", "import { sendRequest } from './request';\nimport { IAPIFunction } from './types';\nimport {\n BaseTransaction, \n PasswordTransaction\n} from './transactions';\n\n/**\n * @scope: okta.myAccount.password.read\n */\nexport const getPassword: IAPIFunction = async (\n oktaAuth,\n options\n) => {\n const transaction = await sendRequest(oktaAuth, {\n url: `/idp/myaccount/password`,\n method: 'GET',\n accessToken: options?.accessToken,\n }, PasswordTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.password.manage\n */\nexport const enrollPassword: IAPIFunction = async (\n oktaAuth, \n options\n): Promise => {\n const { accessToken, payload } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: '/idp/myaccount/password',\n method: 'POST',\n payload,\n accessToken,\n }, PasswordTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.password.manage\n */\nexport const updatePassword: IAPIFunction = async (\n oktaAuth, \n options\n): Promise => {\n const { accessToken, payload } = options!;\n const transaction = await sendRequest(oktaAuth, {\n url: '/idp/myaccount/password',\n method: 'PUT',\n payload,\n accessToken,\n }, PasswordTransaction);\n return transaction;\n};\n\n/**\n * @scope: okta.myAccount.password.manage\n */\nexport const deletePassword: IAPIFunction = async (\n oktaAuth, \n options?\n) => {\n const transaction = await sendRequest(oktaAuth, {\n url: `/idp/myaccount/password`,\n method: 'DELETE',\n accessToken: options?.accessToken,\n });\n return transaction;\n};\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * \n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nexport { getProfile, getProfileSchema, updateProfile } from './profileApi.js';\nexport { addEmail, deleteEmail, getEmail, getEmailChallenge, getEmails, sendEmailChallenge, verifyEmailChallenge } from './emailApi.js';\nexport { addPhone, deletePhone, getPhone, getPhones, sendPhoneChallenge, verifyPhoneChallenge } from './phoneApi.js';\nexport { deletePassword, enrollPassword, getPassword, updatePassword } from './passwordApi.js';\n//# sourceMappingURL=api.js.map\n", "import { OktaAuthConstructor } from '../base/types';\nimport {\n OAuthStorageManagerInterface,\n OAuthTransactionMeta,\n OktaAuthOAuthInterface,\n OktaAuthOAuthOptions,\n PKCETransactionMeta,\n} from '../oidc/types';\nimport { OktaAuthMyAccountInterface } from './types';\n\nimport * as MyAccountMethods from './api';\n\nexport function mixinMyAccount\n<\n M extends OAuthTransactionMeta = PKCETransactionMeta,\n S extends OAuthStorageManagerInterface = OAuthStorageManagerInterface,\n O extends OktaAuthOAuthOptions = OktaAuthOAuthOptions,\n TBase extends OktaAuthConstructor>\n = OktaAuthConstructor>\n>\n(Base: TBase): TBase & OktaAuthConstructor>\n{\n return class OktaAuthMyAccount extends Base implements OktaAuthMyAccountInterface\n {\n myaccount: any;\n \n constructor(...args: any[]) {\n super(...args);\n\n this.myaccount = Object.entries(MyAccountMethods)\n .filter(([ name ]) => name !== 'default')\n .reduce((acc, [name, fn]) => {\n acc[name] = (fn as any).bind(null, this);\n return acc;\n }, {});\n }\n };\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\n\nimport { AuthnTransactionState } from '../types';\n\nexport function addStateToken(res, options?) {\n var builtArgs = {} as AuthnTransactionState;\n Object.assign(builtArgs, options);\n\n // Add the stateToken if one isn't passed and we have one\n if (!builtArgs.stateToken && res.stateToken) {\n builtArgs.stateToken = res.stateToken;\n }\n\n return builtArgs;\n}\n\nexport function getStateToken(res) {\n return addStateToken(res);\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\n/* eslint-disable complexity, max-statements */\nimport { post } from '../http';\nimport AuthSdkError from '../errors/AuthSdkError';\nimport { STATE_TOKEN_KEY_NAME } from '../constants';\nimport { OktaAuthHttpInterface } from '../http/types';\nimport { OktaAuthStorageOptions } from '../storage/types';\nimport { addStateToken } from './util/stateToken';\nimport { AuthnTransactionAPI } from './types';\nimport { OktaAuthBaseInterface } from '../base/types';\n\nexport function transactionStatus(sdk: OktaAuthHttpInterface, args) {\n args = addStateToken(sdk, args);\n return post(sdk, sdk.getIssuerOrigin() + '/api/v1/authn', args, { withCredentials: true });\n}\n\nexport function resumeTransaction(sdk: OktaAuthHttpInterface, tx: AuthnTransactionAPI, args) {\n if (!args || !args.stateToken) {\n var stateToken = getSavedStateToken(sdk);\n if (stateToken) {\n args = {\n stateToken: stateToken\n };\n } else {\n return Promise.reject(new AuthSdkError('No transaction to resume'));\n }\n }\n return transactionStatus(sdk, args)\n .then(function(res) {\n return tx.createTransaction(res);\n });\n}\n\nexport function introspectAuthn (sdk: OktaAuthHttpInterface, tx: AuthnTransactionAPI, args) {\n if (!args || !args.stateToken) {\n var stateToken = getSavedStateToken(sdk);\n if (stateToken) {\n args = {\n stateToken: stateToken\n };\n } else {\n return Promise.reject(new AuthSdkError('No transaction to evaluate'));\n }\n }\n return transactionStep(sdk, args)\n .then(function (res) {\n return tx.createTransaction(res);\n });\n}\n\nexport function transactionStep(sdk: OktaAuthHttpInterface, args) {\n args = addStateToken(sdk, args);\n // v1 pipeline introspect API\n return post(sdk, sdk.getIssuerOrigin() + '/api/v1/authn/introspect', args, { withCredentials: true });\n}\n\nexport function transactionExists(sdk: OktaAuthBaseInterface) {\n // We have a cookie state token\n return !!getSavedStateToken(sdk);\n}\n\nexport function postToTransaction(sdk: OktaAuthHttpInterface, tx: AuthnTransactionAPI, url: string, args, options?) {\n options = Object.assign({ withCredentials: true }, options);\n return post(sdk, url, args, options)\n .then(function(res) {\n return tx.createTransaction(res);\n });\n}\n\nexport function getSavedStateToken(sdk: OktaAuthBaseInterface) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const storage = sdk.options.storageUtil!.storage;\n return storage.get(STATE_TOKEN_KEY_NAME);\n}\n", "import { OktaAuthHttpInterface } from '../../http/types';\nimport { find, omit, toQueryString } from '../../util';\nimport AuthSdkError from '../../errors/AuthSdkError';\nimport { get } from '../../http';\nimport { AuthnTransactionAPI, AuthnTransactionState } from '../types';\nimport { postToTransaction } from '../api';\nimport { addStateToken } from './stateToken';\n\n\n// query parameters to post url\ninterface PostToTransactionParams {\n autoPush?: boolean;\n rememberDevice?: boolean;\n updatePhone?: boolean;\n}\n\n// eslint-disable-next-line max-params\nexport function link2fn(sdk: OktaAuthHttpInterface, tx: AuthnTransactionAPI, res, obj, link, ref) {\n if (Array.isArray(link)) {\n return function(name, opts?) {\n if (!name) {\n throw new AuthSdkError('Must provide a link name');\n }\n\n var lk = find(link, {name: name});\n if (!lk) {\n throw new AuthSdkError('No link found for that name');\n }\n\n return link2fn(sdk, tx, res, obj, lk, ref)(opts);\n };\n\n } else if (link.hints &&\n link.hints.allow &&\n link.hints.allow.length === 1) {\n var method = link.hints.allow[0];\n switch (method) {\n\n case 'GET':\n return function() {\n return get(sdk, link.href, { withCredentials: true });\n };\n\n case 'POST':\n // eslint-disable-next-line max-statements,complexity\n return function(opts: AuthnTransactionState) {\n if (ref && ref.isPolling) {\n ref.isPolling = false;\n }\n\n var data = addStateToken(res, opts);\n\n if (res.status === 'MFA_ENROLL' || res.status === 'FACTOR_ENROLL') {\n // Add factorType and provider\n Object.assign(data, {\n factorType: obj.factorType,\n provider: obj.provider\n });\n }\n\n var params = {} as PostToTransactionParams;\n var autoPush = data.autoPush;\n if (autoPush !== undefined) {\n if (typeof autoPush === 'function') {\n try {\n params.autoPush = !!autoPush();\n }\n catch (e) {\n return Promise.reject(new AuthSdkError('AutoPush resulted in an error.'));\n }\n }\n else if (autoPush !== null) {\n params.autoPush = !!autoPush;\n }\n data = omit(data, 'autoPush');\n }\n\n var rememberDevice = data.rememberDevice;\n if (rememberDevice !== undefined) {\n if (typeof rememberDevice === 'function') {\n try {\n params.rememberDevice = !!rememberDevice();\n }\n catch (e) {\n return Promise.reject(new AuthSdkError('RememberDevice resulted in an error.'));\n }\n }\n else if (rememberDevice !== null) {\n params.rememberDevice = !!rememberDevice;\n }\n data = omit(data, 'rememberDevice');\n\n } else if (data.profile &&\n data.profile.updatePhone !== undefined) {\n if (data.profile.updatePhone) {\n params.updatePhone = true;\n }\n data.profile = omit(data.profile, 'updatePhone');\n }\n var href = link.href + toQueryString(params);\n return postToTransaction(sdk, tx, href, data);\n };\n }\n }\n}\n\n\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport CustomError from './CustomError';\n\nexport default class AuthPollStopError extends CustomError {\n constructor() {\n const message = 'The poll was stopped by the sdk';\n super(message);\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\nimport { post } from '../../http';\nimport { isNumber, isObject, getLink, toQueryString, delay as delayFn } from '../../util';\nimport { DEFAULT_POLLING_DELAY } from '../../constants';\nimport AuthSdkError from '../../errors/AuthSdkError';\nimport AuthPollStopError from '../../errors/AuthPollStopError';\nimport { AuthnTransactionState } from '../types';\nimport { getStateToken } from './stateToken';\n\ninterface PollOptions {\n delay?: number;\n rememberDevice?: boolean;\n autoPush?: boolean;\n transactionCallBack?: (AuthnTransactionState) => void;\n}\n\nexport function getPollFn(sdk, res: AuthnTransactionState, ref) {\n return function (options: PollOptions | number) {\n var delay;\n var rememberDevice;\n var autoPush;\n var transactionCallBack;\n\n if (isNumber(options)) {\n delay = options;\n } else if (isObject(options)) {\n options = options as PollOptions;\n delay = options.delay;\n rememberDevice = options.rememberDevice;\n autoPush = options.autoPush;\n transactionCallBack = options.transactionCallBack;\n }\n\n if (!delay && delay !== 0) {\n delay = DEFAULT_POLLING_DELAY;\n }\n\n // Get the poll function\n var pollLink = getLink(res, 'next', 'poll');\n // eslint-disable-next-line complexity\n function pollFn() {\n var opts = {} as PollOptions;\n if (typeof autoPush === 'function') {\n try {\n opts.autoPush = !!autoPush();\n }\n catch (e) {\n return Promise.reject(new AuthSdkError('AutoPush resulted in an error.'));\n }\n }\n else if (autoPush !== undefined && autoPush !== null) {\n opts.autoPush = !!autoPush;\n }\n if (typeof rememberDevice === 'function') {\n try {\n opts.rememberDevice = !!rememberDevice();\n }\n catch (e) {\n return Promise.reject(new AuthSdkError('RememberDevice resulted in an error.'));\n }\n }\n else if (rememberDevice !== undefined && rememberDevice !== null) {\n opts.rememberDevice = !!rememberDevice;\n }\n\n var href = pollLink.href + toQueryString(opts);\n return post(sdk, href, getStateToken(res), {\n saveAuthnState: false,\n withCredentials: true\n });\n }\n\n ref.isPolling = true;\n\n var retryCount = 0;\n var recursivePoll = function () {\n // If the poll was manually stopped during the delay\n if (!ref.isPolling) {\n return Promise.reject(new AuthPollStopError());\n }\n return pollFn()\n .then(function (pollRes) {\n // Reset our retry counter on success\n retryCount = 0;\n\n // If we're still waiting\n if (pollRes.factorResult && pollRes.factorResult === 'WAITING') {\n\n // If the poll was manually stopped while the pollFn was called\n if (!ref.isPolling) {\n throw new AuthPollStopError();\n }\n\n if (typeof transactionCallBack === 'function') {\n transactionCallBack(pollRes);\n }\n\n // Continue poll\n return delayFn(delay).then(recursivePoll);\n\n } else {\n // Any non-waiting result, even if polling was stopped\n // during a request, will return\n ref.isPolling = false;\n return sdk.tx.createTransaction(pollRes);\n }\n })\n .catch(function(err) {\n // Exponential backoff, up to 16 seconds\n if (err.xhr &&\n (err.xhr.status === 0 || err.xhr.status === 429) &&\n retryCount <= 4) {\n var delayLength = Math.pow(2, retryCount) * 1000;\n retryCount++;\n return delayFn(delayLength)\n .then(recursivePoll);\n }\n throw err;\n });\n };\n return recursivePoll()\n .catch(function(err) {\n ref.isPolling = false;\n throw err;\n });\n };\n}\n", "import { OktaAuthHttpInterface } from '../../http/types';\nimport { AuthnTransactionFunctions, AuthnTransactionAPI } from '../types';\nimport { link2fn } from './link2fn';\nimport { getPollFn } from './poll';\n\nexport function links2fns(sdk: OktaAuthHttpInterface, tx: AuthnTransactionAPI, res, obj, ref) {\n var fns = {} as AuthnTransactionFunctions;\n for (var linkName in obj._links) {\n if (!Object.prototype.hasOwnProperty.call(obj._links, linkName)) {\n continue;\n }\n\n var link = obj._links[linkName];\n \n if (linkName === 'next') {\n linkName = link.name;\n }\n\n if (link.type) {\n fns[linkName] = link;\n continue;\n }\n\n switch (linkName) {\n // poll is only found at the transaction\n // level, so we don't need to pass the link\n case 'poll':\n fns.poll = getPollFn(sdk, res, ref);\n break;\n\n default:\n var fn = link2fn(sdk, tx, res, obj, link, ref);\n if (fn) {\n fns[linkName] = fn;\n }\n }\n }\n return fns;\n}\n", "/* eslint-disable complexity */\nimport { OktaAuthHttpInterface } from '../../http/types';\nimport { clone, isObject, omit } from '../../util';\nimport { AuthnTransactionAPI } from '../types';\nimport { links2fns } from './links2fns';\n\nexport function flattenEmbedded(sdk: OktaAuthHttpInterface, tx: AuthnTransactionAPI, res, obj, ref) {\n obj = obj || res;\n obj = clone(obj);\n\n if (Array.isArray(obj)) {\n var objArr = [];\n for (var o = 0, ol = obj.length; o < ol; o++) {\n objArr.push(flattenEmbedded(sdk, tx, res, obj[o], ref) as never);\n }\n return objArr;\n }\n\n var embedded = obj._embedded || {};\n\n for (var key in embedded) {\n if (!Object.prototype.hasOwnProperty.call(embedded, key)) {\n continue;\n }\n\n // Flatten any nested _embedded objects\n if (isObject(embedded[key]) || Array.isArray(embedded[key])) {\n embedded[key] = flattenEmbedded(sdk, tx, res, embedded[key], ref);\n }\n }\n\n // Convert any links on the embedded object\n var fns = links2fns(sdk, tx, res, obj, ref);\n Object.assign(embedded, fns);\n\n obj = omit(obj, '_embedded', '_links');\n Object.assign(obj, embedded);\n return obj;\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\nimport { OktaAuthHttpInterface } from '../http/types';\nimport {\n AuthnTransactionFunction,\n AuthnTransaction,\n AuthnTransactionAPI,\n AuthnTransactionState\n} from './types';\nimport { flattenEmbedded } from './util/flattenEmbedded';\n\nexport class AuthnTransactionImpl implements AuthnTransaction {\n next?: AuthnTransactionFunction;\n cancel?: AuthnTransactionFunction;\n skip?: AuthnTransactionFunction;\n unlock?: AuthnTransactionFunction;\n changePassword?: AuthnTransactionFunction;\n resetPassword?: AuthnTransactionFunction;\n answer?: AuthnTransactionFunction;\n recovery?: AuthnTransactionFunction;\n verify?: AuthnTransactionFunction;\n resend?: AuthnTransactionFunction;\n activate?: AuthnTransactionFunction;\n poll?: AuthnTransactionFunction;\n prev?: AuthnTransactionFunction;\n\n data?: AuthnTransactionState;\n stateToken?: string;\n sessionToken?: string;\n status: string;\n user?: Record;\n factor?: Record;\n factors?: Array >;\n policy?: Record;\n scopes?: Array >;\n target?: Record;\n authentication?: Record;\n constructor(sdk: OktaAuthHttpInterface, tx: AuthnTransactionAPI, res: AuthnTransactionState | null = null) {\n this.data = undefined;\n this.status = undefined as unknown as string;\n if (res) {\n this.data = res;\n\n // Parse response from Authn V1\n Object.assign(this, flattenEmbedded(sdk, tx, res, res, {}));\n delete this.stateToken;\n\n // RECOVERY_CHALLENGE has some responses without _links.\n // Without _links, we emulate cancel to make it intuitive\n // to return to the starting state. We may remove this\n // when OKTA-75434 is resolved\n if (res.status === 'RECOVERY_CHALLENGE' && !res._links) {\n this.cancel = function() {\n return Promise.resolve(tx.createTransaction());\n };\n }\n }\n }\n}\n", "/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n *\n */\n\nimport { RequestData, RequestOptions, OktaAuthHttpInterface } from '../http/types';\nimport {\n introspectAuthn,\n transactionStatus,\n transactionExists,\n resumeTransaction,\n postToTransaction\n} from './api';\nimport { AuthnTransactionImpl } from './AuthnTransactionImpl';\nimport { AuthnTransactionAPI, AuthnTransactionState } from './types';\n\n// Factory\nexport function createAuthnTransactionAPI(sdk: OktaAuthHttpInterface): AuthnTransactionAPI {\n const tx: AuthnTransactionAPI = {\n status: transactionStatus.bind(null, sdk),\n resume(args) {\n return resumeTransaction(sdk, tx, args);\n },\n exists: transactionExists.bind(null, sdk),\n introspect(args) {\n return introspectAuthn(sdk, tx, args);\n },\n createTransaction: (res?: AuthnTransactionState) => {\n return new AuthnTransactionImpl(sdk, tx, res);\n },\n postToTransaction: (url: string, args?: RequestData, options?: RequestOptions) => {\n return postToTransaction(sdk, tx, url, args, options);\n }\n };\n return tx;\n}\n", "/* eslint-disable max-statements */\n/* eslint-disable complexity */\n/*!\n * Copyright (c) 2015-present, Okta, Inc. and/or its affiliates. All rights reserved.\n * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the \"License.\")\n *\n * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\n * See the License for the specific language governing permissions and limitations under the License.\n */\n\nimport { \n clone,\n} from '../util';\nimport fingerprint from '../browser/fingerprint';\nimport {\n SigninWithCredentialsOptions,\n ForgotPasswordOptions,\n VerifyRecoveryTokenOptions,\n SigninOptions,\n OktaAuthTxInterface,\n AuthnTransaction,\n AuthnTransactionAPI\n} from './types';\nimport {\n createAuthnTransactionAPI,\n} from './factory';\nimport { StorageManagerInterface } from '../storage/types';\nimport { OktaAuthHttpInterface, OktaAuthHttpOptions } from '../http/types';\nimport { FingerprintAPI, OktaAuthConstructor } from '../base/types';\n\nexport function mixinAuthn\n<\n S extends StorageManagerInterface = StorageManagerInterface,\n O extends OktaAuthHttpOptions = OktaAuthHttpOptions,\n TBase extends OktaAuthConstructor>\n = OktaAuthConstructor>\n>\n(Base: TBase): TBase & OktaAuthConstructor>\n{\n return class OktaAuthTx extends Base implements OktaAuthTxInterface {\n tx: AuthnTransactionAPI; // legacy, may be removed in future version\n authn: AuthnTransactionAPI;\n fingerprint: FingerprintAPI;\n\n constructor(...args: any[]) {\n super(...args);\n\n this.authn = this.tx = createAuthnTransactionAPI(this);\n \n // Fingerprint API\n this.fingerprint = fingerprint.bind(null, this);\n }\n\n // Authn V1\n async signIn(opts: SigninOptions): Promise {\n opts = clone(opts || {});\n const _postToTransaction = (options?) => {\n delete opts.sendFingerprint;\n return this.tx.postToTransaction('/api/v1/authn', opts, options);\n };\n if (!opts.sendFingerprint) {\n return _postToTransaction();\n }\n return this.fingerprint()\n .then(function(fingerprint) {\n return _postToTransaction({\n headers: {\n 'X-Device-Fingerprint': fingerprint\n }\n });\n });\n }\n\n // Authn V1\n async signInWithCredentials(opts: SigninWithCredentialsOptions): Promise {\n return this.signIn(opts);\n }\n\n // { username, (relayState) }\n forgotPassword(opts): Promise {\n return this.tx.postToTransaction('/api/v1/authn/recovery/password', opts);\n }\n\n // { username, (relayState) }\n unlockAccount(opts: ForgotPasswordOptions): Promise {\n return this.tx.postToTransaction('/api/v1/authn/recovery/unlock', opts);\n }\n\n // { recoveryToken }\n verifyRecoveryToken(opts: VerifyRecoveryTokenOptions): Promise {\n return this.tx.postToTransaction('/api/v1/authn/recovery/token', opts);\n }\n\n };\n}\n", "import {\n OktaAuthOptionsConstructor,\n} from '../base';\n\nimport {\n IdxStorageManagerConstructor,\n IdxTransactionManagerConstructor,\n OktaAuthIdxOptions,\n createIdxTransactionManager,\n createOktaAuthIdx,\n createIdxStorageManager,\n createIdxOptionsConstructor\n} from '../idx';\n\nimport { mixinMyAccount } from '../myaccount';\nimport { mixinAuthn } from '../authn';\n\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface OktaAuthOptions extends OktaAuthIdxOptions {}\n\nconst OptionsConstructor: OktaAuthOptionsConstructor = createIdxOptionsConstructor();\nconst StorageManager: IdxStorageManagerConstructor = createIdxStorageManager();\nconst TransactionManager: IdxTransactionManagerConstructor = createIdxTransactionManager();\n\n// Default bundle includes everything\nconst WithIdx = createOktaAuthIdx(StorageManager, OptionsConstructor, TransactionManager);\nconst WithMyAccount = mixinMyAccount(WithIdx);\nconst WithAuthn = mixinAuthn(WithMyAccount);\n\nclass OktaAuth extends WithAuthn {\n constructor(options: OktaAuthOptions) {\n super(options);\n }\n}\n\nexport default OktaAuth;\nexport { OktaAuth };\nexport * from './common';\nexport * from '../idx';\nexport * from '../myaccount';\nexport * from '../authn';\n", "export default function compareVersions(v1, v2) {\n // validate input and split into segments\n const n1 = validateAndParse(v1);\n const n2 = validateAndParse(v2);\n\n // pop off the patch\n const p1 = n1.pop();\n const p2 = n2.pop();\n\n // validate numbers\n const r = compareSegments(n1, n2);\n if (r !== 0) return r;\n\n // validate pre-release\n if (p1 && p2) {\n return compareSegments(p1.split('.'), p2.split('.'));\n } else if (p1 || p2) {\n return p1 ? -1 : 1;\n }\n\n return 0;\n}\n\nexport const validate = (v) =>\n typeof v === 'string' && /^[v\\d]/.test(v) && semver.test(v);\n\nexport const compare = (v1, v2, operator) => {\n // validate input operator\n assertValidOperator(operator);\n\n // since result of compareVersions can only be -1 or 0 or 1\n // a simple map can be used to replace switch\n const res = compareVersions(v1, v2);\n\n return operatorResMap[operator].includes(res);\n};\n\nexport const satisfies = (v, r) => {\n // if no range operator then \"=\"\n const m = r.match(/^([<>=~^]+)/);\n const op = m ? m[1] : '=';\n\n // if gt/lt/eq then operator compare\n if (op !== '^' && op !== '~') return compare(v, r, op);\n\n // else range of either \"~\" or \"^\" is assumed\n const [v1, v2, v3] = validateAndParse(v);\n const [r1, r2, r3] = validateAndParse(r);\n if (compareStrings(v1, r1) !== 0) return false;\n if (op === '^') {\n return compareSegments([v2, v3], [r2, r3]) >= 0;\n }\n if (compareStrings(v2, r2) !== 0) return false;\n return compareStrings(v3, r3) >= 0;\n};\n\n// export CJS style for parity\ncompareVersions.validate = validate;\ncompareVersions.compare = compare;\ncompareVersions.satisfies = satisfies;\n\nconst semver =\n /^[v^~<>=]*?(\\d+)(?:\\.([x*]|\\d+)(?:\\.([x*]|\\d+)(?:\\.([x*]|\\d+))?(?:-([\\da-z\\-]+(?:\\.[\\da-z\\-]+)*))?(?:\\+[\\da-z\\-]+(?:\\.[\\da-z\\-]+)*)?)?)?$/i;\n\nconst validateAndParse = (v) => {\n if (typeof v !== 'string') {\n throw new TypeError('Invalid argument expected string');\n }\n const match = v.match(semver);\n if (!match) {\n throw new Error(`Invalid argument not valid semver ('${v}' received)`);\n }\n match.shift();\n return match;\n};\n\nconst isWildcard = (s) => s === '*' || s === 'x' || s === 'X';\n\nconst tryParse = (v) => {\n const n = parseInt(v, 10);\n return isNaN(n) ? v : n;\n};\n\nconst forceType = (a, b) =>\n typeof a !== typeof b ? [String(a), String(b)] : [a, b];\n\nconst compareStrings = (a, b) => {\n if (isWildcard(a) || isWildcard(b)) return 0;\n const [ap, bp] = forceType(tryParse(a), tryParse(b));\n if (ap > bp) return 1;\n if (ap < bp) return -1;\n return 0;\n};\n\nconst compareSegments = (a, b) => {\n for (let i = 0; i < Math.max(a.length, b.length); i++) {\n const r = compareStrings(a[i] || 0, b[i] || 0);\n if (r !== 0) return r;\n }\n return 0;\n};\n\nconst operatorResMap = {\n '>': [1],\n '>=': [0, 1],\n '=': [0],\n '<=': [-1, 0],\n '<': [-1],\n};\n\nconst allowedOperators = Object.keys(operatorResMap);\n\nconst assertValidOperator = (op) => {\n if (typeof op !== 'string') {\n throw new TypeError(\n `Invalid operator type, expected string but got ${typeof op}`\n );\n }\n if (allowedOperators.indexOf(op) === -1) {\n throw new Error(\n `Invalid operator, expected one of ${allowedOperators.join('|')}`\n );\n }\n};\n", "export default function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}", "import _typeof from \"./typeof.js\";\nexport default function _toPrimitive(input, hint) {\n if (_typeof(input) !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (_typeof(res) !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}", "import _typeof from \"./typeof.js\";\nimport toPrimitive from \"./toPrimitive.js\";\nexport default function _toPropertyKey(arg) {\n var key = toPrimitive(arg, \"string\");\n return _typeof(key) === \"symbol\" ? key : String(key);\n}", "import toPropertyKey from \"./toPropertyKey.js\";\nexport default function _defineProperty(obj, key, value) {\n key = toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}", "export default function _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}", "import objectWithoutPropertiesLoose from \"./objectWithoutPropertiesLoose.js\";\nexport default function _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n return target;\n}", "////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Actions represent the type of change to a location value.\n */\nexport enum Action {\n /**\n * A POP indicates a change to an arbitrary index in the history stack, such\n * as a back or forward navigation. It does not describe the direction of the\n * navigation, only that the current index changed.\n *\n * Note: This is the default action for newly created history objects.\n */\n Pop = \"POP\",\n\n /**\n * A PUSH indicates a new entry being added to the history stack, such as when\n * a link is clicked and a new page loads. When this happens, all subsequent\n * entries in the stack are lost.\n */\n Push = \"PUSH\",\n\n /**\n * A REPLACE indicates the entry at the current index in the history stack\n * being replaced by a new one.\n */\n Replace = \"REPLACE\",\n}\n\n/**\n * The pathname, search, and hash values of a URL.\n */\nexport interface Path {\n /**\n * A URL pathname, beginning with a /.\n */\n pathname: string;\n\n /**\n * A URL search string, beginning with a ?.\n */\n search: string;\n\n /**\n * A URL fragment identifier, beginning with a #.\n */\n hash: string;\n}\n\n/**\n * An entry in a history stack. A location contains information about the\n * URL path, as well as possibly some arbitrary state and a key.\n */\nexport interface Location extends Path {\n /**\n * A value of arbitrary data associated with this location.\n */\n state: any;\n\n /**\n * A unique string associated with this location. May be used to safely store\n * and retrieve data in some other storage API, like `localStorage`.\n *\n * Note: This value is always \"default\" on the initial location.\n */\n key: string;\n}\n\n/**\n * A change to the current location.\n */\nexport interface Update {\n /**\n * The action that triggered the change.\n */\n action: Action;\n\n /**\n * The new location.\n */\n location: Location;\n\n /**\n * The delta between this location and the former location in the history stack\n */\n delta: number | null;\n}\n\n/**\n * A function that receives notifications about location changes.\n */\nexport interface Listener {\n (update: Update): void;\n}\n\n/**\n * Describes a location that is the destination of some navigation, either via\n * `history.push` or `history.replace`. May be either a URL or the pieces of a\n * URL path.\n */\nexport type To = string | Partial;\n\n/**\n * A history is an interface to the navigation stack. The history serves as the\n * source of truth for the current location, as well as provides a set of\n * methods that may be used to change it.\n *\n * It is similar to the DOM's `window.history` object, but with a smaller, more\n * focused API.\n */\nexport interface History {\n /**\n * The last action that modified the current location. This will always be\n * Action.Pop when a history instance is first created. This value is mutable.\n */\n readonly action: Action;\n\n /**\n * The current location. This value is mutable.\n */\n readonly location: Location;\n\n /**\n * Returns a valid href for the given `to` value that may be used as\n * the value of an attribute.\n *\n * @param to - The destination URL\n */\n createHref(to: To): string;\n\n /**\n * Returns a URL for the given `to` value\n *\n * @param to - The destination URL\n */\n createURL(to: To): URL;\n\n /**\n * Encode a location the same way window.history would do (no-op for memory\n * history) so we ensure our PUSH/REPLACE navigations for data routers\n * behave the same as POP\n *\n * @param to Unencoded path\n */\n encodeLocation(to: To): Path;\n\n /**\n * Pushes a new location onto the history stack, increasing its length by one.\n * If there were any entries in the stack after the current one, they are\n * lost.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n push(to: To, state?: any): void;\n\n /**\n * Replaces the current location in the history stack with a new one. The\n * location that was replaced will no longer be available.\n *\n * @param to - The new URL\n * @param state - Data to associate with the new location\n */\n replace(to: To, state?: any): void;\n\n /**\n * Navigates `n` entries backward/forward in the history stack relative to the\n * current index. For example, a \"back\" navigation would use go(-1).\n *\n * @param delta - The delta in the stack index\n */\n go(delta: number): void;\n\n /**\n * Sets up a listener that will be called whenever the current location\n * changes.\n *\n * @param listener - A function that will be called when the location changes\n * @returns unlisten - A function that may be used to stop listening\n */\n listen(listener: Listener): () => void;\n}\n\ntype HistoryState = {\n usr: any;\n key?: string;\n idx: number;\n};\n\nconst PopStateEventType = \"popstate\";\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Memory History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A user-supplied object that describes a location. Used when providing\n * entries to `createMemoryHistory` via its `initialEntries` option.\n */\nexport type InitialEntry = string | Partial;\n\nexport type MemoryHistoryOptions = {\n initialEntries?: InitialEntry[];\n initialIndex?: number;\n v5Compat?: boolean;\n};\n\n/**\n * A memory history stores locations in memory. This is useful in stateful\n * environments where there is no web browser, such as node tests or React\n * Native.\n */\nexport interface MemoryHistory extends History {\n /**\n * The current index in the history stack.\n */\n readonly index: number;\n}\n\n/**\n * Memory history stores the current location in memory. It is designed for use\n * in stateful non-browser environments like tests and React Native.\n */\nexport function createMemoryHistory(\n options: MemoryHistoryOptions = {}\n): MemoryHistory {\n let { initialEntries = [\"/\"], initialIndex, v5Compat = false } = options;\n let entries: Location[]; // Declare so we can access from createMemoryLocation\n entries = initialEntries.map((entry, index) =>\n createMemoryLocation(\n entry,\n typeof entry === \"string\" ? null : entry.state,\n index === 0 ? \"default\" : undefined\n )\n );\n let index = clampIndex(\n initialIndex == null ? entries.length - 1 : initialIndex\n );\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n function clampIndex(n: number): number {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation(): Location {\n return entries[index];\n }\n function createMemoryLocation(\n to: To,\n state: any = null,\n key?: string\n ): Location {\n let location = createLocation(\n entries ? getCurrentLocation().pathname : \"/\",\n to,\n state,\n key\n );\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in memory history: ${JSON.stringify(\n to\n )}`\n );\n return location;\n }\n\n function createHref(to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n let history: MemoryHistory = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to: To) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\",\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 1 });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({ action, location: nextLocation, delta: 0 });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({ action, location: nextLocation, delta });\n }\n },\n listen(fn: Listener) {\n listener = fn;\n return () => {\n listener = null;\n };\n },\n };\n\n return history;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Browser History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A browser history stores the current location in regular URLs in a web\n * browser environment. This is the standard for most web apps and provides the\n * cleanest URLs the browser's address bar.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#browserhistory\n */\nexport interface BrowserHistory extends UrlHistory {}\n\nexport type BrowserHistoryOptions = UrlHistoryOptions;\n\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nexport function createBrowserHistory(\n options: BrowserHistoryOptions = {}\n): BrowserHistory {\n function createBrowserLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let { pathname, search, hash } = window.location;\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createBrowserHref(window: Window, to: To) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n\n return getUrlBasedHistory(\n createBrowserLocation,\n createBrowserHref,\n null,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Hash History\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A hash history stores the current location in the fragment identifier portion\n * of the URL in a web browser environment.\n *\n * This is ideal for apps that do not control the server for some reason\n * (because the fragment identifier is never sent to the server), including some\n * shared hosting environments that do not provide fine-grained controls over\n * which pages are served at which URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#hashhistory\n */\nexport interface HashHistory extends UrlHistory {}\n\nexport type HashHistoryOptions = UrlHistoryOptions;\n\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nexport function createHashHistory(\n options: HashHistoryOptions = {}\n): HashHistory {\n function createHashLocation(\n window: Window,\n globalHistory: Window[\"history\"]\n ) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n } = parsePath(window.location.hash.substr(1));\n return createLocation(\n \"\",\n { pathname, search, hash },\n // state defaults to `null` because `window.history.state` does\n (globalHistory.state && globalHistory.state.usr) || null,\n (globalHistory.state && globalHistory.state.key) || \"default\"\n );\n }\n\n function createHashHref(window: Window, to: To) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n\n function validateHashLocation(location: Location, to: To) {\n warning(\n location.pathname.charAt(0) === \"/\",\n `relative pathnames are not supported in hash history.push(${JSON.stringify(\n to\n )})`\n );\n }\n\n return getUrlBasedHistory(\n createHashLocation,\n createHashHref,\n validateHashLocation,\n options\n );\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region UTILS\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * @private\n */\nexport function invariant(value: boolean, message?: string): asserts value;\nexport function invariant(\n value: T | null | undefined,\n message?: string\n): asserts value is T;\nexport function invariant(value: any, message?: string) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\n\nexport function warning(cond: any, message: string) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\n\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location: Location, index: number): HistoryState {\n return {\n usr: location.state,\n key: location.key,\n idx: index,\n };\n}\n\n/**\n * Creates a Location object with a unique key from the given Path\n */\nexport function createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string\n): Readonly {\n let location: Readonly = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n };\n return location;\n}\n\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nexport function createPath({\n pathname = \"/\",\n search = \"\",\n hash = \"\",\n}: Partial) {\n if (search && search !== \"?\")\n pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\")\n pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nexport function parsePath(path: string): Partial {\n let parsedPath: Partial = {};\n\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n\n if (path) {\n parsedPath.pathname = path;\n }\n }\n\n return parsedPath;\n}\n\nexport interface UrlHistory extends History {}\n\nexport type UrlHistoryOptions = {\n window?: Window;\n v5Compat?: boolean;\n};\n\nfunction getUrlBasedHistory(\n getLocation: (window: Window, globalHistory: Window[\"history\"]) => Location,\n createHref: (window: Window, to: To) => string,\n validateLocation: ((location: Location, to: To) => void) | null,\n options: UrlHistoryOptions = {}\n): UrlHistory {\n let { window = document.defaultView!, v5Compat = false } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener: Listener | null = null;\n\n let index = getIndex()!;\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState({ ...globalHistory.state, idx: index }, \"\");\n }\n\n function getIndex(): number {\n let state = globalHistory.state || { idx: null };\n return state.idx;\n }\n\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({ action, location: history.location, delta });\n }\n }\n\n function push(to: To, state?: any) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 1 });\n }\n }\n\n function replace(to: To, state?: any) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n\n if (v5Compat && listener) {\n listener({ action, location: history.location, delta: 0 });\n }\n }\n\n function createURL(to: To): URL {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base =\n window.location.origin !== \"null\"\n ? window.location.origin\n : window.location.href;\n\n let href = typeof to === \"string\" ? to : createPath(to);\n invariant(\n base,\n `No window.location.(origin|href) available to create URL for href: ${href}`\n );\n return new URL(href, base);\n }\n\n let history: History = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn: Listener) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n },\n };\n\n return history;\n}\n\n//#endregion\n", "import type { Location, Path, To } from \"./history\";\nimport { warning, invariant, parsePath } from \"./history\";\n\n/**\n * Map of routeId -> data returned from a loader/action/error\n */\nexport interface RouteData {\n [routeId: string]: any;\n}\n\nexport enum ResultType {\n data = \"data\",\n deferred = \"deferred\",\n redirect = \"redirect\",\n error = \"error\",\n}\n\n/**\n * Successful result from a loader or action\n */\nexport interface SuccessResult {\n type: ResultType.data;\n data: any;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Successful defer() result from a loader or action\n */\nexport interface DeferredResult {\n type: ResultType.deferred;\n deferredData: DeferredData;\n statusCode?: number;\n headers?: Headers;\n}\n\n/**\n * Redirect result from a loader or action\n */\nexport interface RedirectResult {\n type: ResultType.redirect;\n status: number;\n location: string;\n revalidate: boolean;\n}\n\n/**\n * Unsuccessful result from a loader or action\n */\nexport interface ErrorResult {\n type: ResultType.error;\n error: any;\n headers?: Headers;\n}\n\n/**\n * Result from a loader or action - potentially successful or unsuccessful\n */\nexport type DataResult =\n | SuccessResult\n | DeferredResult\n | RedirectResult\n | ErrorResult;\n\ntype LowerCaseFormMethod = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\ntype UpperCaseFormMethod = Uppercase;\n\n/**\n * Users can specify either lowercase or uppercase form methods on
,\n * useSubmit(), , etc.\n */\nexport type HTMLFormMethod = LowerCaseFormMethod | UpperCaseFormMethod;\n\n/**\n * Active navigation/fetcher form methods are exposed in lowercase on the\n * RouterState\n */\nexport type FormMethod = LowerCaseFormMethod;\nexport type MutationFormMethod = Exclude;\n\n/**\n * In v7, active navigation/fetcher form methods are exposed in uppercase on the\n * RouterState. This is to align with the normalization done via fetch().\n */\nexport type V7_FormMethod = UpperCaseFormMethod;\nexport type V7_MutationFormMethod = Exclude;\n\nexport type FormEncType =\n | \"application/x-www-form-urlencoded\"\n | \"multipart/form-data\"\n | \"application/json\"\n | \"text/plain\";\n\n// Thanks https://github.com/sindresorhus/type-fest!\ntype JsonObject = { [Key in string]: JsonValue } & {\n [Key in string]?: JsonValue | undefined;\n};\ntype JsonArray = JsonValue[] | readonly JsonValue[];\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | JsonObject | JsonArray;\n\n/**\n * @private\n * Internal interface to pass around for action submissions, not intended for\n * external consumption\n */\nexport type Submission =\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: FormData;\n json: undefined;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: JsonValue;\n text: undefined;\n }\n | {\n formMethod: FormMethod | V7_FormMethod;\n formAction: string;\n formEncType: FormEncType;\n formData: undefined;\n json: undefined;\n text: string;\n };\n\n/**\n * @private\n * Arguments passed to route loader/action functions. Same for now but we keep\n * this as a private implementation detail in case they diverge in the future.\n */\ninterface DataFunctionArgs {\n request: Request;\n params: Params;\n context?: any;\n}\n\n/**\n * Arguments passed to loader functions\n */\nexport interface LoaderFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Arguments passed to action functions\n */\nexport interface ActionFunctionArgs extends DataFunctionArgs {}\n\n/**\n * Loaders and actions can return anything except `undefined` (`null` is a\n * valid return value if there is no data to return). Responses are preferred\n * and will ease any future migration to Remix\n */\ntype DataFunctionValue = Response | NonNullable | null;\n\n/**\n * Route loader function signature\n */\nexport interface LoaderFunction {\n (args: LoaderFunctionArgs): Promise | DataFunctionValue;\n}\n\n/**\n * Route action function signature\n */\nexport interface ActionFunction {\n (args: ActionFunctionArgs): Promise | DataFunctionValue;\n}\n\n/**\n * Route shouldRevalidate function signature. This runs after any submission\n * (navigation or fetcher), so we flatten the navigation/fetcher submission\n * onto the arguments. It shouldn't matter whether it came from a navigation\n * or a fetcher, what really matters is the URLs and the formData since loaders\n * have to re-run based on the data models that were potentially mutated.\n */\nexport interface ShouldRevalidateFunction {\n (args: {\n currentUrl: URL;\n currentParams: AgnosticDataRouteMatch[\"params\"];\n nextUrl: URL;\n nextParams: AgnosticDataRouteMatch[\"params\"];\n formMethod?: Submission[\"formMethod\"];\n formAction?: Submission[\"formAction\"];\n formEncType?: Submission[\"formEncType\"];\n text?: Submission[\"text\"];\n formData?: Submission[\"formData\"];\n json?: Submission[\"json\"];\n actionResult?: DataResult;\n defaultShouldRevalidate: boolean;\n }): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set `hasErrorBoundary`\n * from the framework-aware `errorElement` prop\n *\n * @deprecated Use `mapRouteProperties` instead\n */\nexport interface DetectErrorBoundaryFunction {\n (route: AgnosticRouteObject): boolean;\n}\n\n/**\n * Function provided by the framework-aware layers to set any framework-specific\n * properties from framework-agnostic properties\n */\nexport interface MapRoutePropertiesFunction {\n (route: AgnosticRouteObject): {\n hasErrorBoundary: boolean;\n } & Record;\n}\n\n/**\n * Keys we cannot change from within a lazy() function. We spread all other keys\n * onto the route. Either they're meaningful to the router, or they'll get\n * ignored.\n */\nexport type ImmutableRouteKey =\n | \"lazy\"\n | \"caseSensitive\"\n | \"path\"\n | \"id\"\n | \"index\"\n | \"children\";\n\nexport const immutableRouteKeys = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n]);\n\ntype RequireOne = Exclude<\n {\n [K in keyof T]: K extends Key ? Omit & Required> : never;\n }[keyof T],\n undefined\n>;\n\n/**\n * lazy() function to load a route definition, which can add non-matching\n * related properties to a route\n */\nexport interface LazyRouteFunction {\n (): Promise>>;\n}\n\n/**\n * Base RouteObject with common props shared by all types of routes\n */\ntype AgnosticBaseRouteObject = {\n caseSensitive?: boolean;\n path?: string;\n id?: string;\n loader?: LoaderFunction;\n action?: ActionFunction;\n hasErrorBoundary?: boolean;\n shouldRevalidate?: ShouldRevalidateFunction;\n handle?: any;\n lazy?: LazyRouteFunction;\n};\n\n/**\n * Index routes must not have children\n */\nexport type AgnosticIndexRouteObject = AgnosticBaseRouteObject & {\n children?: undefined;\n index: true;\n};\n\n/**\n * Non-index routes may have children, but cannot have index\n */\nexport type AgnosticNonIndexRouteObject = AgnosticBaseRouteObject & {\n children?: AgnosticRouteObject[];\n index?: false;\n};\n\n/**\n * A route object represents a logical route, with (optionally) its child\n * routes organized in a tree-like structure.\n */\nexport type AgnosticRouteObject =\n | AgnosticIndexRouteObject\n | AgnosticNonIndexRouteObject;\n\nexport type AgnosticDataIndexRouteObject = AgnosticIndexRouteObject & {\n id: string;\n};\n\nexport type AgnosticDataNonIndexRouteObject = AgnosticNonIndexRouteObject & {\n children?: AgnosticDataRouteObject[];\n id: string;\n};\n\n/**\n * A data route object, which is just a RouteObject with a required unique ID\n */\nexport type AgnosticDataRouteObject =\n | AgnosticDataIndexRouteObject\n | AgnosticDataNonIndexRouteObject;\n\nexport type RouteManifest = Record;\n\n// Recursive helper for finding path parameters in the absence of wildcards\ntype _PathParam =\n // split path into individual path segments\n Path extends `${infer L}/${infer R}`\n ? _PathParam | _PathParam\n : // find params after `:`\n Path extends `:${infer Param}`\n ? Param extends `${infer Optional}?`\n ? Optional\n : Param\n : // otherwise, there aren't any params present\n never;\n\n/**\n * Examples:\n * \"/a/b/*\" -> \"*\"\n * \":a\" -> \"a\"\n * \"/a/:b\" -> \"b\"\n * \"/a/blahblahblah:b\" -> \"b\"\n * \"/:a/:b\" -> \"a\" | \"b\"\n * \"/:a/b/:c/*\" -> \"a\" | \"c\" | \"*\"\n */\ntype PathParam =\n // check if path is just a wildcard\n Path extends \"*\" | \"/*\"\n ? \"*\"\n : // look for wildcard at the end of the path\n Path extends `${infer Rest}/*`\n ? \"*\" | _PathParam\n : // look for params in the absence of wildcards\n _PathParam;\n\n// Attempt to parse the given string segment. If it fails, then just return the\n// plain string type as a default fallback. Otherwise return the union of the\n// parsed string literals that were referenced as dynamic segments in the route.\nexport type ParamParseKey =\n // if could not find path params, fallback to `string`\n [PathParam] extends [never] ? string : PathParam;\n\n/**\n * The parameters that were parsed from the URL path.\n */\nexport type Params = {\n readonly [key in Key]: string | undefined;\n};\n\n/**\n * A RouteMatch contains info about how a route matched a URL.\n */\nexport interface AgnosticRouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The route object that was used to match.\n */\n route: RouteObjectType;\n}\n\nexport interface AgnosticDataRouteMatch\n extends AgnosticRouteMatch {}\n\nfunction isIndexRoute(\n route: AgnosticRouteObject\n): route is AgnosticIndexRouteObject {\n return route.index === true;\n}\n\n// Walk the route tree generating unique IDs where necessary so we are working\n// solely with AgnosticDataRouteObject's within the Router\nexport function convertRoutesToDataRoutes(\n routes: AgnosticRouteObject[],\n mapRouteProperties: MapRoutePropertiesFunction,\n parentPath: number[] = [],\n manifest: RouteManifest = {}\n): AgnosticDataRouteObject[] {\n return routes.map((route, index) => {\n let treePath = [...parentPath, index];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(\n route.index !== true || !route.children,\n `Cannot specify children on an index route`\n );\n invariant(\n !manifest[id],\n `Found a route id collision on id \"${id}\". Route ` +\n \"id's must be globally unique within Data Router usages\"\n );\n\n if (isIndexRoute(route)) {\n let indexRoute: AgnosticDataIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n };\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute: AgnosticDataNonIndexRouteObject = {\n ...route,\n ...mapRouteProperties(route),\n id,\n children: undefined,\n };\n manifest[id] = pathOrLayoutRoute;\n\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(\n route.children,\n mapRouteProperties,\n treePath,\n manifest\n );\n }\n\n return pathOrLayoutRoute;\n }\n });\n}\n\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\nexport function matchRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n locationArg: Partial | string,\n basename = \"/\"\n): AgnosticRouteMatch[] | null {\n let location =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n let pathname = stripBasename(location.pathname || \"/\", basename);\n\n if (pathname == null) {\n return null;\n }\n\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n matches = matchRouteBranch(\n branches[i],\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n safelyDecodeURI(pathname)\n );\n }\n\n return matches;\n}\n\ninterface RouteMeta<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n relativePath: string;\n caseSensitive: boolean;\n childrenIndex: number;\n route: RouteObjectType;\n}\n\ninterface RouteBranch<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n> {\n path: string;\n score: number;\n routesMeta: RouteMeta[];\n}\n\nfunction flattenRoutes<\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n routes: RouteObjectType[],\n branches: RouteBranch[] = [],\n parentsMeta: RouteMeta[] = [],\n parentPath = \"\"\n): RouteBranch[] {\n let flattenRoute = (\n route: RouteObjectType,\n index: number,\n relativePath?: string\n ) => {\n let meta: RouteMeta = {\n relativePath:\n relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route,\n };\n\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(\n meta.relativePath.startsWith(parentPath),\n `Absolute route path \"${meta.relativePath}\" nested under path ` +\n `\"${parentPath}\" is not valid. An absolute child route path ` +\n `must start with the combined path of all its parent routes.`\n );\n\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n\n // Add the children before adding this route to the array so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true,\n `Index routes must not have child routes. Please remove ` +\n `all child routes from route path \"${path}\".`\n );\n\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta,\n });\n };\n routes.forEach((route, index) => {\n // coarse-grain check for optional params\n if (route.path === \"\" || !route.path?.includes(\"?\")) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n\n return branches;\n}\n\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path: string): string[] {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n\n let [first, ...rest] = segments;\n\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n\n let result: string[] = [];\n\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explodes _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(\n ...restExploded.map((subpath) =>\n subpath === \"\" ? required : [required, subpath].join(\"/\")\n )\n );\n\n // Then if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n\n // for absolute paths, ensure `/` instead of empty segment\n return result.map((exploded) =>\n path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded\n );\n}\n\nfunction rankRouteBranches(branches: RouteBranch[]): void {\n branches.sort((a, b) =>\n a.score !== b.score\n ? b.score - a.score // Higher score first\n : compareIndexes(\n a.routesMeta.map((meta) => meta.childrenIndex),\n b.routesMeta.map((meta) => meta.childrenIndex)\n )\n );\n}\n\nconst paramRe = /^:\\w+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = (s: string) => s === \"*\";\n\nfunction computeScore(path: string, index: boolean | undefined): number {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n\n if (index) {\n initialScore += indexRouteValue;\n }\n\n return segments\n .filter((s) => !isSplat(s))\n .reduce(\n (score, segment) =>\n score +\n (paramRe.test(segment)\n ? dynamicSegmentValue\n : segment === \"\"\n ? emptySegmentValue\n : staticSegmentValue),\n initialScore\n );\n}\n\nfunction compareIndexes(a: number[], b: number[]): number {\n let siblings =\n a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n\n return siblings\n ? // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1]\n : // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\n\nfunction matchRouteBranch<\n ParamKey extends string = string,\n RouteObjectType extends AgnosticRouteObject = AgnosticRouteObject\n>(\n branch: RouteBranch,\n pathname: string\n): AgnosticRouteMatch[] | null {\n let { routesMeta } = branch;\n\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches: AgnosticRouteMatch[] = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname =\n matchedPathname === \"/\"\n ? pathname\n : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath(\n { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },\n remainingPathname\n );\n\n if (!match) return null;\n\n Object.assign(matchedParams, match.params);\n\n let route = meta.route;\n\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams as Params,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(\n joinPaths([matchedPathname, match.pathnameBase])\n ),\n route,\n });\n\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n\n return matches;\n}\n\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nexport function generatePath(\n originalPath: Path,\n params: {\n [key in PathParam]: string | null;\n } = {} as any\n): string {\n let path: string = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(\n false,\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n path = path.replace(/\\*$/, \"/*\") as Path;\n }\n\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n\n const stringify = (p: any) =>\n p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n\n const segments = path\n .split(/\\/+/)\n .map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\" as PathParam;\n // Apply the splat\n return stringify(params[star]);\n }\n\n const keyMatch = segment.match(/^:(\\w+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key as PathParam];\n invariant(optional === \"?\" || param != null, `Missing \":${key}\" param`);\n return stringify(param);\n }\n\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter((segment) => !!segment);\n\n return prefix + segments.join(\"/\");\n}\n\n/**\n * A PathPattern is used to match on some portion of a URL pathname.\n */\nexport interface PathPattern {\n /**\n * A string to match against a URL pathname. May contain `:id`-style segments\n * to indicate placeholders for dynamic parameters. May also end with `/*` to\n * indicate matching the rest of the URL pathname.\n */\n path: Path;\n /**\n * Should be `true` if the static portions of the `path` should be matched in\n * the same case.\n */\n caseSensitive?: boolean;\n /**\n * Should be `true` if this pattern should match the entire URL pathname.\n */\n end?: boolean;\n}\n\n/**\n * A PathMatch contains info about how a PathPattern matched on a URL pathname.\n */\nexport interface PathMatch {\n /**\n * The names and values of dynamic parameters in the URL.\n */\n params: Params;\n /**\n * The portion of the URL pathname that was matched.\n */\n pathname: string;\n /**\n * The portion of the URL pathname that was matched before child routes.\n */\n pathnameBase: string;\n /**\n * The pattern that was used to match.\n */\n pattern: PathPattern;\n}\n\ntype Mutable = {\n -readonly [P in keyof T]: T[P];\n};\n\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nexport function matchPath<\n ParamKey extends ParamParseKey,\n Path extends string\n>(\n pattern: PathPattern | Path,\n pathname: string\n): PathMatch | null {\n if (typeof pattern === \"string\") {\n pattern = { path: pattern, caseSensitive: false, end: true };\n }\n\n let [matcher, paramNames] = compilePath(\n pattern.path,\n pattern.caseSensitive,\n pattern.end\n );\n\n let match = pathname.match(matcher);\n if (!match) return null;\n\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params: Params = paramNames.reduce>(\n (memo, paramName, index) => {\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname\n .slice(0, matchedPathname.length - splatValue.length)\n .replace(/(.)\\/+$/, \"$1\");\n }\n\n memo[paramName] = safelyDecodeURIComponent(\n captureGroups[index] || \"\",\n paramName\n );\n return memo;\n },\n {}\n );\n\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern,\n };\n}\n\nfunction compilePath(\n path: string,\n caseSensitive = false,\n end = true\n): [RegExp, string[]] {\n warning(\n path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"),\n `Route path \"${path}\" will be treated as if it were ` +\n `\"${path.replace(/\\*$/, \"/*\")}\" because the \\`*\\` character must ` +\n `always follow a \\`/\\` in the pattern. To get rid of this warning, ` +\n `please change the route path to \"${path.replace(/\\*$/, \"/*\")}\".`\n );\n\n let paramNames: string[] = [];\n let regexpSource =\n \"^\" +\n path\n .replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^$?{}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(/\\/:(\\w+)/g, (_: string, paramName: string) => {\n paramNames.push(paramName);\n return \"/([^\\\\/]+)\";\n });\n\n if (path.endsWith(\"*\")) {\n paramNames.push(\"*\");\n regexpSource +=\n path === \"*\" || path === \"/*\"\n ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else {\n // Nothing to match for \"\" or \"/\"\n }\n\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n\n return [matcher, paramNames];\n}\n\nfunction safelyDecodeURI(value: string) {\n try {\n return decodeURI(value);\n } catch (error) {\n warning(\n false,\n `The URL path \"${value}\" could not be decoded because it is is a ` +\n `malformed URL segment. This is probably due to a bad percent ` +\n `encoding (${error}).`\n );\n\n return value;\n }\n}\n\nfunction safelyDecodeURIComponent(value: string, paramName: string) {\n try {\n return decodeURIComponent(value);\n } catch (error) {\n warning(\n false,\n `The value for the URL param \"${paramName}\" will not be decoded because` +\n ` the string \"${value}\" is a malformed URL segment. This is probably` +\n ` due to a bad percent encoding (${error}).`\n );\n\n return value;\n }\n}\n\n/**\n * @private\n */\nexport function stripBasename(\n pathname: string,\n basename: string\n): string | null {\n if (basename === \"/\") return pathname;\n\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\")\n ? basename.length - 1\n : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n\n return pathname.slice(startIndex) || \"/\";\n}\n\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nexport function resolvePath(to: To, fromPathname = \"/\"): Path {\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\",\n } = typeof to === \"string\" ? parsePath(to) : to;\n\n let pathname = toPathname\n ? toPathname.startsWith(\"/\")\n ? toPathname\n : resolvePathname(toPathname, fromPathname)\n : fromPathname;\n\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash),\n };\n}\n\nfunction resolvePathname(relativePath: string, fromPathname: string): string {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n\n relativeSegments.forEach((segment) => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\n\nfunction getInvalidPathError(\n char: string,\n field: string,\n dest: string,\n path: Partial\n) {\n return (\n `Cannot include a '${char}' character in a manually specified ` +\n `\\`to.${field}\\` field [${JSON.stringify(\n path\n )}]. Please separate it out to the ` +\n `\\`to.${dest}\\` field. Alternatively you may provide the full path as ` +\n `a string in and the router will parse it for you.`\n );\n}\n\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nexport function getPathContributingMatches<\n T extends AgnosticRouteMatch = AgnosticRouteMatch\n>(matches: T[]) {\n return matches.filter(\n (match, index) =>\n index === 0 || (match.route.path && match.route.path.length > 0)\n );\n}\n\n/**\n * @private\n */\nexport function resolveTo(\n toArg: To,\n routePathnames: string[],\n locationPathname: string,\n isPathRelative = false\n): Path {\n let to: Partial;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = { ...toArg };\n\n invariant(\n !to.pathname || !to.pathname.includes(\"?\"),\n getInvalidPathError(\"?\", \"pathname\", \"search\", to)\n );\n invariant(\n !to.pathname || !to.pathname.includes(\"#\"),\n getInvalidPathError(\"#\", \"pathname\", \"hash\", to)\n );\n invariant(\n !to.search || !to.search.includes(\"#\"),\n getInvalidPathError(\"#\", \"search\", \"hash\", to)\n );\n }\n\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n\n let from: string;\n\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (isPathRelative || toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n\n if (toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n\n // Each leading .. segment means \"go up one route\" instead of \"go up one\n // URL segment\". This is a key difference from how works and a\n // major reason we call this a \"to\" value instead of a \"href\".\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n\n to.pathname = toSegments.join(\"/\");\n }\n\n // If there are more \"..\" segments than parent routes, resolve relative to\n // the root / URL.\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n\n let path = resolvePath(to, from);\n\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash =\n toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash =\n (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (\n !path.pathname.endsWith(\"/\") &&\n (hasExplicitTrailingSlash || hasCurrentTrailingSlash)\n ) {\n path.pathname += \"/\";\n }\n\n return path;\n}\n\n/**\n * @private\n */\nexport function getToPathname(to: To): string | undefined {\n // Empty strings should be treated the same as / paths\n return to === \"\" || (to as Path).pathname === \"\"\n ? \"/\"\n : typeof to === \"string\"\n ? parsePath(to).pathname\n : to.pathname;\n}\n\n/**\n * @private\n */\nexport const joinPaths = (paths: string[]): string =>\n paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n\n/**\n * @private\n */\nexport const normalizePathname = (pathname: string): string =>\n pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n\n/**\n * @private\n */\nexport const normalizeSearch = (search: string): string =>\n !search || search === \"?\"\n ? \"\"\n : search.startsWith(\"?\")\n ? search\n : \"?\" + search;\n\n/**\n * @private\n */\nexport const normalizeHash = (hash: string): string =>\n !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n\nexport type JsonFunction = (\n data: Data,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nexport const json: JsonFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n\n return new Response(JSON.stringify(data), {\n ...responseInit,\n headers,\n });\n};\n\nexport interface TrackedPromise extends Promise {\n _tracked?: boolean;\n _data?: any;\n _error?: any;\n}\n\nexport class AbortedDeferredError extends Error {}\n\nexport class DeferredData {\n private pendingKeysSet: Set = new Set();\n private controller: AbortController;\n private abortPromise: Promise;\n private unlistenAbortSignal: () => void;\n private subscribers: Set<(aborted: boolean, settledKey?: string) => void> =\n new Set();\n data: Record;\n init?: ResponseInit;\n deferredKeys: string[] = [];\n\n constructor(data: Record, responseInit?: ResponseInit) {\n invariant(\n data && typeof data === \"object\" && !Array.isArray(data),\n \"defer() only accepts plain objects\"\n );\n\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject: (e: AbortedDeferredError) => void;\n this.abortPromise = new Promise((_, r) => (reject = r));\n this.controller = new AbortController();\n let onAbort = () =>\n reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () =>\n this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n\n this.data = Object.entries(data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: this.trackPromise(key, value),\n }),\n {}\n );\n\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n\n this.init = responseInit;\n }\n\n private trackPromise(\n key: string,\n value: Promise | unknown\n ): TrackedPromise | unknown {\n if (!(value instanceof Promise)) {\n return value;\n }\n\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise: TrackedPromise = Promise.race([value, this.abortPromise]).then(\n (data) => this.onSettle(promise, key, undefined, data as unknown),\n (error) => this.onSettle(promise, key, error as unknown)\n );\n\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n\n Object.defineProperty(promise, \"_tracked\", { get: () => true });\n return promise;\n }\n\n private onSettle(\n promise: TrackedPromise,\n key: string,\n error: unknown,\n data?: unknown\n ): unknown {\n if (\n this.controller.signal.aborted &&\n error instanceof AbortedDeferredError\n ) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", { get: () => error });\n return Promise.reject(error);\n }\n\n this.pendingKeysSet.delete(key);\n\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\n `Deferred data for key \"${key}\" resolved/rejected with \\`undefined\\`, ` +\n `you must resolve/reject with a value or \\`null\\`.`\n );\n Object.defineProperty(promise, \"_error\", { get: () => undefinedError });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", { get: () => error });\n this.emit(false, key);\n return Promise.reject(error);\n }\n\n Object.defineProperty(promise, \"_data\", { get: () => data });\n this.emit(false, key);\n return data;\n }\n\n private emit(aborted: boolean, settledKey?: string) {\n this.subscribers.forEach((subscriber) => subscriber(aborted, settledKey));\n }\n\n subscribe(fn: (aborted: boolean, settledKey?: string) => void) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n\n async resolveData(signal: AbortSignal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise((resolve) => {\n this.subscribe((aborted) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n\n get unwrappedData() {\n invariant(\n this.data !== null && this.done,\n \"Can only unwrap data on initialized and settled deferreds\"\n );\n\n return Object.entries(this.data).reduce(\n (acc, [key, value]) =>\n Object.assign(acc, {\n [key]: unwrapTrackedPromise(value),\n }),\n {}\n );\n }\n\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\n\nfunction isTrackedPromise(value: any): value is TrackedPromise {\n return (\n value instanceof Promise && (value as TrackedPromise)._tracked === true\n );\n}\n\nfunction unwrapTrackedPromise(value: any) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\n\nexport type DeferFunction = (\n data: Record,\n init?: number | ResponseInit\n) => DeferredData;\n\nexport const defer: DeferFunction = (data, init = {}) => {\n let responseInit = typeof init === \"number\" ? { status: init } : init;\n\n return new DeferredData(data, responseInit);\n};\n\nexport type RedirectFunction = (\n url: string,\n init?: number | ResponseInit\n) => Response;\n\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nexport const redirect: RedirectFunction = (url, init = 302) => {\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = { status: responseInit };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n\n return new Response(null, {\n ...responseInit,\n headers,\n });\n};\n\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n */\nexport class ErrorResponse {\n status: number;\n statusText: string;\n data: any;\n error?: Error;\n internal: boolean;\n\n constructor(\n status: number,\n statusText: string | undefined,\n data: any,\n internal = false\n ) {\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nexport function isRouteErrorResponse(error: any): error is ErrorResponse {\n return (\n error != null &&\n typeof error.status === \"number\" &&\n typeof error.statusText === \"string\" &&\n typeof error.internal === \"boolean\" &&\n \"data\" in error\n );\n}\n", "import type { History, Location, Path, To } from \"./history\";\nimport {\n Action as HistoryAction,\n createLocation,\n createPath,\n invariant,\n parsePath,\n warning,\n} from \"./history\";\nimport type {\n DataResult,\n DeferredData,\n AgnosticDataRouteMatch,\n AgnosticDataRouteObject,\n DeferredResult,\n ErrorResult,\n FormEncType,\n FormMethod,\n DetectErrorBoundaryFunction,\n RedirectResult,\n RouteData,\n AgnosticRouteObject,\n Submission,\n SuccessResult,\n AgnosticRouteMatch,\n ShouldRevalidateFunction,\n RouteManifest,\n ImmutableRouteKey,\n ActionFunction,\n LoaderFunction,\n V7_MutationFormMethod,\n V7_FormMethod,\n HTMLFormMethod,\n MutationFormMethod,\n MapRoutePropertiesFunction,\n} from \"./utils\";\nimport {\n ErrorResponse,\n ResultType,\n convertRoutesToDataRoutes,\n getPathContributingMatches,\n immutableRouteKeys,\n isRouteErrorResponse,\n joinPaths,\n matchRoutes,\n resolveTo,\n stripBasename,\n} from \"./utils\";\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Types and Constants\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * A Router instance manages all navigation and data loading/mutations\n */\nexport interface Router {\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the basename for the router\n */\n get basename(): RouterInit[\"basename\"];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the current state of the router\n */\n get state(): RouterState;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Return the routes for this router instance\n */\n get routes(): AgnosticDataRouteObject[];\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Initialize the router, including adding history listeners and kicking off\n * initial data fetches. Returns a function to cleanup listeners and abort\n * any in-progress loads\n */\n initialize(): Router;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Subscribe to router.state updates\n *\n * @param fn function to call with the new state\n */\n subscribe(fn: RouterSubscriber): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Enable scroll restoration behavior in the router\n *\n * @param savedScrollPositions Object that will manage positions, in case\n * it's being restored from sessionStorage\n * @param getScrollPosition Function to get the active Y scroll position\n * @param getKey Function to get the key to use for restoration\n */\n enableScrollRestoration(\n savedScrollPositions: Record,\n getScrollPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ): () => void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Navigate forward/backward in the history stack\n * @param to Delta to move in the history stack\n */\n navigate(to: number): Promise;\n\n /**\n * Navigate to the given path\n * @param to Path to navigate to\n * @param opts Navigation options (method, submission, etc.)\n */\n navigate(to: To | null, opts?: RouterNavigateOptions): Promise;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a fetcher load/submission\n *\n * @param key Fetcher key\n * @param routeId Route that owns the fetcher\n * @param href href to fetch\n * @param opts Fetcher options, (method, submission, etc.)\n */\n fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Trigger a revalidation of all current route loaders and fetcher loads\n */\n revalidate(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to create an href for the given location\n * @param location\n */\n createHref(location: Location | URL): string;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Utility function to URL encode a destination path according to the internal\n * history implementation\n * @param to\n */\n encodeLocation(to: To): Path;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get/create a fetcher for the given key\n * @param key\n */\n getFetcher(key?: string): Fetcher;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete the fetcher for a given key\n * @param key\n */\n deleteFetcher(key?: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Cleanup listeners and abort any in-progress loads\n */\n dispose(): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Get a navigation blocker\n * @param key The identifier for the blocker\n * @param fn The blocker function implementation\n */\n getBlocker(key: string, fn: BlockerFunction): Blocker;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Delete a navigation blocker\n * @param key The identifier for the blocker\n */\n deleteBlocker(key: string): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * HMR needs to pass in-flight route updates to React Router\n * TODO: Replace this with granular route update APIs (addRoute, updateRoute, deleteRoute)\n */\n _internalSetRoutes(routes: AgnosticRouteObject[]): void;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal fetch AbortControllers accessed by unit tests\n */\n _internalFetchControllers: Map;\n\n /**\n * @internal\n * PRIVATE - DO NOT USE\n *\n * Internal pending DeferredData instances accessed by unit tests\n */\n _internalActiveDeferreds: Map;\n}\n\n/**\n * State maintained internally by the router. During a navigation, all states\n * reflect the the \"old\" location unless otherwise noted.\n */\nexport interface RouterState {\n /**\n * The action of the most recent navigation\n */\n historyAction: HistoryAction;\n\n /**\n * The current location reflected by the router\n */\n location: Location;\n\n /**\n * The current set of route matches\n */\n matches: AgnosticDataRouteMatch[];\n\n /**\n * Tracks whether we've completed our initial data load\n */\n initialized: boolean;\n\n /**\n * Current scroll position we should start at for a new view\n * - number -> scroll position to restore to\n * - false -> do not restore scroll at all (used during submissions)\n * - null -> don't have a saved position, scroll to hash or top of page\n */\n restoreScrollPosition: number | false | null;\n\n /**\n * Indicate whether this navigation should skip resetting the scroll position\n * if we are unable to restore the scroll position\n */\n preventScrollReset: boolean;\n\n /**\n * Tracks the state of the current navigation\n */\n navigation: Navigation;\n\n /**\n * Tracks any in-progress revalidations\n */\n revalidation: RevalidationState;\n\n /**\n * Data from the loaders for the current matches\n */\n loaderData: RouteData;\n\n /**\n * Data from the action for the current matches\n */\n actionData: RouteData | null;\n\n /**\n * Errors caught from loaders for the current matches\n */\n errors: RouteData | null;\n\n /**\n * Map of current fetchers\n */\n fetchers: Map;\n\n /**\n * Map of current blockers\n */\n blockers: Map;\n}\n\n/**\n * Data that can be passed into hydrate a Router from SSR\n */\nexport type HydrationState = Partial<\n Pick\n>;\n\n/**\n * Future flags to toggle new feature behavior\n */\nexport interface FutureConfig {\n v7_normalizeFormMethod: boolean;\n v7_prependBasename: boolean;\n}\n\n/**\n * Initialization options for createRouter\n */\nexport interface RouterInit {\n routes: AgnosticRouteObject[];\n history: History;\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n future?: Partial;\n hydrationData?: HydrationState;\n window?: Window;\n}\n\n/**\n * State returned from a server-side query() call\n */\nexport interface StaticHandlerContext {\n basename: Router[\"basename\"];\n location: RouterState[\"location\"];\n matches: RouterState[\"matches\"];\n loaderData: RouterState[\"loaderData\"];\n actionData: RouterState[\"actionData\"];\n errors: RouterState[\"errors\"];\n statusCode: number;\n loaderHeaders: Record;\n actionHeaders: Record;\n activeDeferreds: Record | null;\n _deepestRenderedBoundaryId?: string | null;\n}\n\n/**\n * A StaticHandler instance manages a singular SSR navigation/fetch event\n */\nexport interface StaticHandler {\n dataRoutes: AgnosticDataRouteObject[];\n query(\n request: Request,\n opts?: { requestContext?: unknown }\n ): Promise;\n queryRoute(\n request: Request,\n opts?: { routeId?: string; requestContext?: unknown }\n ): Promise;\n}\n\n/**\n * Subscriber function signature for changes to router state\n */\nexport interface RouterSubscriber {\n (state: RouterState): void;\n}\n\ninterface UseMatchesMatch {\n id: string;\n pathname: string;\n params: AgnosticRouteMatch[\"params\"];\n data: unknown;\n handle: unknown;\n}\n\n/**\n * Function signature for determining the key to be used in scroll restoration\n * for a given location\n */\nexport interface GetScrollRestorationKeyFunction {\n (location: Location, matches: UseMatchesMatch[]): string | null;\n}\n\n/**\n * Function signature for determining the current scroll position\n */\nexport interface GetScrollPositionFunction {\n (): number;\n}\n\nexport type RelativeRoutingType = \"route\" | \"path\";\n\n// Allowed for any navigation or fetch\ntype BaseNavigateOrFetchOptions = {\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n};\n\n// Only allowed for navigations\ntype BaseNavigateOptions = BaseNavigateOrFetchOptions & {\n replace?: boolean;\n state?: any;\n fromRouteId?: string;\n};\n\n// Only allowed for submission navigations\ntype BaseSubmissionOptions = {\n formMethod?: HTMLFormMethod;\n formEncType?: FormEncType;\n} & (\n | { formData: FormData; body?: undefined }\n | { formData?: undefined; body: any }\n);\n\n/**\n * Options for a navigate() call for a normal (non-submission) navigation\n */\ntype LinkNavigateOptions = BaseNavigateOptions;\n\n/**\n * Options for a navigate() call for a submission navigation\n */\ntype SubmissionNavigateOptions = BaseNavigateOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to navigate() for a navigation\n */\nexport type RouterNavigateOptions =\n | LinkNavigateOptions\n | SubmissionNavigateOptions;\n\n/**\n * Options for a fetch() load\n */\ntype LoadFetchOptions = BaseNavigateOrFetchOptions;\n\n/**\n * Options for a fetch() submission\n */\ntype SubmitFetchOptions = BaseNavigateOrFetchOptions & BaseSubmissionOptions;\n\n/**\n * Options to pass to fetch()\n */\nexport type RouterFetchOptions = LoadFetchOptions | SubmitFetchOptions;\n\n/**\n * Potential states for state.navigation\n */\nexport type NavigationStates = {\n Idle: {\n state: \"idle\";\n location: undefined;\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n formData: undefined;\n json: undefined;\n text: undefined;\n };\n Loading: {\n state: \"loading\";\n location: Location;\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n text: Submission[\"text\"] | undefined;\n };\n Submitting: {\n state: \"submitting\";\n location: Location;\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n text: Submission[\"text\"];\n };\n};\n\nexport type Navigation = NavigationStates[keyof NavigationStates];\n\nexport type RevalidationState = \"idle\" | \"loading\";\n\n/**\n * Potential states for fetchers\n */\ntype FetcherStates = {\n Idle: {\n state: \"idle\";\n formMethod: undefined;\n formAction: undefined;\n formEncType: undefined;\n text: undefined;\n formData: undefined;\n json: undefined;\n data: TData | undefined;\n \" _hasFetcherDoneAnything \"?: boolean;\n };\n Loading: {\n state: \"loading\";\n formMethod: Submission[\"formMethod\"] | undefined;\n formAction: Submission[\"formAction\"] | undefined;\n formEncType: Submission[\"formEncType\"] | undefined;\n text: Submission[\"text\"] | undefined;\n formData: Submission[\"formData\"] | undefined;\n json: Submission[\"json\"] | undefined;\n data: TData | undefined;\n \" _hasFetcherDoneAnything \"?: boolean;\n };\n Submitting: {\n state: \"submitting\";\n formMethod: Submission[\"formMethod\"];\n formAction: Submission[\"formAction\"];\n formEncType: Submission[\"formEncType\"];\n text: Submission[\"text\"];\n formData: Submission[\"formData\"];\n json: Submission[\"json\"];\n data: TData | undefined;\n \" _hasFetcherDoneAnything \"?: boolean;\n };\n};\n\nexport type Fetcher =\n FetcherStates[keyof FetcherStates];\n\ninterface BlockerBlocked {\n state: \"blocked\";\n reset(): void;\n proceed(): void;\n location: Location;\n}\n\ninterface BlockerUnblocked {\n state: \"unblocked\";\n reset: undefined;\n proceed: undefined;\n location: undefined;\n}\n\ninterface BlockerProceeding {\n state: \"proceeding\";\n reset: undefined;\n proceed: undefined;\n location: Location;\n}\n\nexport type Blocker = BlockerUnblocked | BlockerBlocked | BlockerProceeding;\n\nexport type BlockerFunction = (args: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n}) => boolean;\n\ninterface ShortCircuitable {\n /**\n * startNavigation does not need to complete the navigation because we\n * redirected or got interrupted\n */\n shortCircuited?: boolean;\n}\n\ninterface HandleActionResult extends ShortCircuitable {\n /**\n * Error thrown from the current action, keyed by the route containing the\n * error boundary to render the error. To be committed to the state after\n * loaders have completed\n */\n pendingActionError?: RouteData;\n /**\n * Data returned from the current action, keyed by the route owning the action.\n * To be committed to the state after loaders have completed\n */\n pendingActionData?: RouteData;\n}\n\ninterface HandleLoadersResult extends ShortCircuitable {\n /**\n * loaderData returned from the current set of loaders\n */\n loaderData?: RouterState[\"loaderData\"];\n /**\n * errors thrown from the current set of loaders\n */\n errors?: RouterState[\"errors\"];\n}\n\n/**\n * Cached info for active fetcher.load() instances so they can participate\n * in revalidation\n */\ninterface FetchLoadMatch {\n routeId: string;\n path: string;\n}\n\n/**\n * Identified fetcher.load() calls that need to be revalidated\n */\ninterface RevalidatingFetcher extends FetchLoadMatch {\n key: string;\n match: AgnosticDataRouteMatch | null;\n matches: AgnosticDataRouteMatch[] | null;\n controller: AbortController | null;\n}\n\n/**\n * Wrapper object to allow us to throw any response out from callLoaderOrAction\n * for queryRouter while preserving whether or not it was thrown or returned\n * from the loader/action\n */\ninterface QueryRouteResponse {\n type: ResultType.data | ResultType.error;\n response: Response;\n}\n\nconst validMutationMethodsArr: MutationFormMethod[] = [\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n];\nconst validMutationMethods = new Set(\n validMutationMethodsArr\n);\n\nconst validRequestMethodsArr: FormMethod[] = [\n \"get\",\n ...validMutationMethodsArr,\n];\nconst validRequestMethods = new Set(validRequestMethodsArr);\n\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\n\nexport const IDLE_NAVIGATION: NavigationStates[\"Idle\"] = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_FETCHER: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n};\n\nexport const IDLE_BLOCKER: BlockerUnblocked = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined,\n};\n\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\n\nconst defaultMapRouteProperties: MapRoutePropertiesFunction = (route) => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary),\n});\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Create a router and listen to history POP navigations\n */\nexport function createRouter(init: RouterInit): Router {\n const routerWindow = init.window\n ? init.window\n : typeof window !== \"undefined\"\n ? window\n : undefined;\n const isBrowser =\n typeof routerWindow !== \"undefined\" &&\n typeof routerWindow.document !== \"undefined\" &&\n typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n\n invariant(\n init.routes.length > 0,\n \"You must provide a non-empty routes array to createRouter\"\n );\n\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n // Routes keyed by ID\n let manifest: RouteManifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(\n init.routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined;\n let basename = init.basename || \"/\";\n // Config driven behavior flags\n let future: FutureConfig = {\n v7_normalizeFormMethod: false,\n v7_prependBasename: false,\n ...init.future,\n };\n // Cleanup function for history\n let unlistenHistory: (() => void) | null = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions: Record | null = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey: GetScrollRestorationKeyFunction | null = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition: GetScrollPositionFunction | null = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialErrors: RouteData | null = null;\n\n if (initialMatches == null) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname,\n });\n let { matches, route } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = { [route.id]: error };\n }\n\n let initialized =\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n !initialMatches.some((m) => m.route.lazy) &&\n // And we have to either have no loaders or have been provided hydrationData\n (!initialMatches.some((m) => m.route.loader) || init.hydrationData != null);\n\n let router: Router;\n let state: RouterState = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: (init.hydrationData && init.hydrationData.loaderData) || {},\n actionData: (init.hydrationData && init.hydrationData.actionData) || null,\n errors: (init.hydrationData && init.hydrationData.errors) || initialErrors,\n fetchers: new Map(),\n blockers: new Map(),\n };\n\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction: HistoryAction = HistoryAction.Pop;\n\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n\n // AbortController for the active navigation\n let pendingNavigationController: AbortController | null;\n\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes: string[] = [];\n\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads: string[] = [];\n\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(\n ({ action: historyAction, location, delta }) => {\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n\n warning(\n blockerFunctions.size === 0 || delta != null,\n \"You are trying to use a blocker on a POP navigation to a location \" +\n \"that was not created by @remix-run/router. This will fail silently in \" +\n \"production. This can happen if you are navigating outside the router \" +\n \"via `window.history.pushState`/`window.location.hash` instead of using \" +\n \"router navigation APIs. This can also happen if you are using \" +\n \"createHashRouter and the user manually changes the URL.\"\n );\n\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction,\n });\n\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location,\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return startNavigation(historyAction, location);\n }\n );\n\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(HistoryAction.Pop, state.location);\n }\n\n return router;\n }\n\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n\n // Subscribe to state updates for the router\n function subscribe(fn: RouterSubscriber) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n\n // Update our state and notify the calling context of the change\n function updateState(newState: Partial): void {\n state = {\n ...state,\n ...newState,\n };\n subscribers.forEach((subscriber) => subscriber(state));\n }\n\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(\n location: Location,\n newState: Partial>\n ): void {\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload =\n state.actionData != null &&\n state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n state.navigation.state === \"loading\" &&\n location.state?._isRedirect !== true;\n\n let actionData: RouteData | null;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData\n ? mergeLoaderData(\n state.loaderData,\n newState.loaderData,\n newState.matches || [],\n newState.errors\n )\n : state.loaderData;\n\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset =\n pendingPreventScrollReset === true ||\n (state.navigation.formMethod != null &&\n isMutationMethod(state.navigation.formMethod) &&\n location.state?._isRedirect !== true);\n\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n\n if (isUninterruptedRevalidation) {\n // If this was an uninterrupted revalidation then do not touch history\n } else if (pendingAction === HistoryAction.Pop) {\n // Do nothing for POP - URL has already been updated\n } else if (pendingAction === HistoryAction.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === HistoryAction.Replace) {\n init.history.replace(location, location.state);\n }\n\n updateState({\n ...newState, // matches, errors, fetchers go through as-is\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(\n location,\n newState.matches || state.matches\n ),\n preventScrollReset,\n blockers,\n });\n\n // Reset stateful navigation vars\n pendingAction = HistoryAction.Pop;\n pendingPreventScrollReset = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n }\n\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(\n to: number | To | null,\n opts?: RouterNavigateOptions\n ): Promise {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n to,\n opts?.fromRouteId,\n opts?.relative\n );\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n false,\n normalizedPath,\n opts\n );\n\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = {\n ...nextLocation,\n ...init.history.encodeLocation(nextLocation),\n };\n\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n\n let historyAction = HistoryAction.Push;\n\n if (userReplace === true) {\n historyAction = HistoryAction.Replace;\n } else if (userReplace === false) {\n // no-op\n } else if (\n submission != null &&\n isMutationMethod(submission.formMethod) &&\n submission.formAction === state.location.pathname + state.location.search\n ) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = HistoryAction.Replace;\n }\n\n let preventScrollReset =\n opts && \"preventScrollReset\" in opts\n ? opts.preventScrollReset === true\n : undefined;\n\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n });\n\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey!, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation,\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey!, IDLE_BLOCKER);\n updateState({ blockers });\n },\n });\n return;\n }\n\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n });\n }\n\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({ revalidation: \"loading\" });\n\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true,\n });\n return;\n }\n\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(\n pendingAction || state.historyAction,\n state.navigation.location,\n { overrideNavigation: state.navigation }\n );\n }\n\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(\n historyAction: HistoryAction,\n location: Location,\n opts?: {\n submission?: Submission;\n fetcherSubmission?: Submission;\n overrideNavigation?: Navigation;\n pendingError?: ErrorResponse;\n startUninterruptedRevalidation?: boolean;\n preventScrollReset?: boolean;\n replace?: boolean;\n }\n ): Promise {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation =\n (opts && opts.startUninterruptedRevalidation) === true;\n\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error,\n },\n });\n return;\n }\n\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a \n // which will default to a navigation to /page\n if (\n state.initialized &&\n !isRevalidationRequired &&\n isHashChangeOnly(state.location, location) &&\n !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))\n ) {\n completeNavigation(location, { matches });\n return;\n }\n\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(\n init.history,\n location,\n pendingNavigationController.signal,\n opts && opts.submission\n );\n let pendingActionData: RouteData | undefined;\n let pendingError: RouteData | undefined;\n\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingError = {\n [findNearestBoundary(matches).route.id]: opts.pendingError,\n };\n } else if (\n opts &&\n opts.submission &&\n isMutationMethod(opts.submission.formMethod)\n ) {\n // Call action if we received an action submission\n let actionOutput = await handleAction(\n request,\n location,\n opts.submission,\n matches,\n { replace: opts.replace }\n );\n\n if (actionOutput.shortCircuited) {\n return;\n }\n\n pendingActionData = actionOutput.pendingActionData;\n pendingError = actionOutput.pendingActionError;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n\n // Create a GET request for the loaders\n request = new Request(request.url, { signal: request.signal });\n }\n\n // Call loaders\n let { shortCircuited, loaderData, errors } = await handleLoaders(\n request,\n location,\n matches,\n loadingNavigation,\n opts && opts.submission,\n opts && opts.fetcherSubmission,\n opts && opts.replace,\n pendingActionData,\n pendingError\n );\n\n if (shortCircuited) {\n return;\n }\n\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n\n completeNavigation(location, {\n matches,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n loaderData,\n errors,\n });\n }\n\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(\n request: Request,\n location: Location,\n submission: Submission,\n matches: AgnosticDataRouteMatch[],\n opts: { replace?: boolean } = {}\n ): Promise {\n interruptActiveLoads();\n\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({ navigation });\n\n // Call our action and get the result\n let result: DataResult;\n let actionMatch = getTargetMatch(matches, location);\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id,\n }),\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n }\n\n if (isRedirectResult(result)) {\n let replace: boolean;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n replace =\n result.location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(state, result, { submission, replace });\n return { shortCircuited: true };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n\n // By default, all submissions are REPLACE navigations, but if the\n // action threw an error that'll be rendered in an errorElement, we fall\n // back to PUSH so that the user can use the back button to get back to\n // the pre-submission form location to try again\n if ((opts && opts.replace) !== true) {\n pendingAction = HistoryAction.Push;\n }\n\n return {\n // Send back an empty object we can use to clear out any prior actionData\n pendingActionData: {},\n pendingActionError: { [boundaryMatch.route.id]: result.error },\n };\n }\n\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n return {\n pendingActionData: { [actionMatch.route.id]: result.data },\n };\n }\n\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n overrideNavigation?: Navigation,\n submission?: Submission,\n fetcherSubmission?: Submission,\n replace?: boolean,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n ): Promise {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation =\n overrideNavigation || getLoadingNavigation(location, submission);\n\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission =\n submission ||\n fetcherSubmission ||\n getSubmissionFromNavigation(loadingNavigation);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n activeSubmission,\n location,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n pendingActionData,\n pendingError\n );\n\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(\n (routeId) =>\n !(matches && matches.some((m) => m.route.id === routeId)) ||\n (matchesToLoad && matchesToLoad.some((m) => m.route.id === routeId))\n );\n\n pendingNavigationLoadId = ++incrementingLoadId;\n\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(location, {\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingError || null,\n ...(pendingActionData ? { actionData: pendingActionData } : {}),\n ...(updatedFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n });\n return { shortCircuited: true };\n }\n\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n if (!isUninterruptedRevalidation) {\n revalidatingFetchers.forEach((rf) => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n fetcher ? fetcher.data : undefined\n );\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n let actionData = pendingActionData || state.actionData;\n updateState({\n navigation: loadingNavigation,\n ...(actionData\n ? Object.keys(actionData).length === 0\n ? { actionData: null }\n : { actionData }\n : {}),\n ...(revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n });\n }\n\n revalidatingFetchers.forEach((rf) => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((f) => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n request\n );\n\n if (request.signal.aborted) {\n return { shortCircuited: true };\n }\n\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n }\n revalidatingFetchers.forEach((rf) => fetchControllers.delete(rf.key));\n\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(state, redirect.result, { replace });\n return { shortCircuited: true };\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n matches,\n matchesToLoad,\n loaderResults,\n pendingError,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe((aborted) => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers =\n updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n\n return {\n loaderData,\n errors,\n ...(shouldUpdateFetchers ? { fetchers: new Map(state.fetchers) } : {}),\n };\n }\n\n function getFetcher(key: string): Fetcher {\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(\n key: string,\n routeId: string,\n href: string | null,\n opts?: RouterFetchOptions\n ) {\n if (isServer) {\n throw new Error(\n \"router.fetch() was called during the server render, but it shouldn't be. \" +\n \"You are likely calling a useFetcher() method in the body of your component. \" +\n \"Try moving it to a useEffect or a callback.\"\n );\n }\n\n if (fetchControllers.has(key)) abortFetcher(key);\n\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(\n state.location,\n state.matches,\n basename,\n future.v7_prependBasename,\n href,\n routeId,\n opts?.relative\n );\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n\n if (!matches) {\n setFetcherError(\n key,\n routeId,\n getInternalRouterError(404, { pathname: normalizedPath })\n );\n return;\n }\n\n let { path, submission, error } = normalizeNavigateOptions(\n future.v7_normalizeFormMethod,\n true,\n normalizedPath,\n opts\n );\n\n if (error) {\n setFetcherError(key, routeId, error);\n return;\n }\n\n let match = getTargetMatch(matches, path);\n\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(key, routeId, path, match, matches, submission);\n return;\n }\n\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, { routeId, path });\n handleFetcherLoader(key, routeId, path, match, matches, submission);\n }\n\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n requestMatches: AgnosticDataRouteMatch[],\n submission: Submission\n ) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n\n if (!match.route.action && !match.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId,\n });\n setFetcherError(key, routeId, error);\n return;\n }\n\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n let fetcher = getSubmittingFetcher(submission, existingFetcher);\n state.fetchers.set(key, fetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n // Call the action for the fetcher\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal,\n submission\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let actionResult = await callLoaderOrAction(\n \"action\",\n fetchRequest,\n match,\n requestMatches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by ou our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n let doneFetcher = getDoneFetcher(undefined);\n state.fetchers.set(key, doneFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n return;\n } else {\n fetchRedirectIds.add(key);\n let loadingFetcher = getLoadingFetcher(submission);\n state.fetchers.set(key, loadingFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n return startRedirectNavigation(state, actionResult, {\n submission,\n isFetchActionRedirect: true,\n });\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, { type: \"defer-action\" });\n }\n\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(\n init.history,\n nextLocation,\n abortController.signal\n );\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches =\n state.navigation.state !== \"idle\"\n ? matchRoutes(routesToUse, state.navigation.location, basename)\n : state.matches;\n\n invariant(matches, \"Didn't find any matches after fetcher action\");\n\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(\n init.history,\n state,\n matches,\n submission,\n nextLocation,\n isRevalidationRequired,\n cancelledDeferredRoutes,\n cancelledFetcherLoads,\n fetchLoadMatches,\n fetchRedirectIds,\n routesToUse,\n basename,\n { [match.route.id]: actionResult.data },\n undefined // No need to send through errors since we short circuit above\n );\n\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers\n .filter((rf) => rf.key !== key)\n .forEach((rf) => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(\n undefined,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n\n updateState({ fetchers: new Map(state.fetchers) });\n\n let abortPendingFetchRevalidations = () =>\n revalidatingFetchers.forEach((rf) => abortFetcher(rf.key));\n\n abortController.signal.addEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n let { results, loaderResults, fetcherResults } =\n await callLoadersAndMaybeResolveData(\n state.matches,\n matches,\n matchesToLoad,\n revalidatingFetchers,\n revalidationRequest\n );\n\n if (abortController.signal.aborted) {\n return;\n }\n\n abortController.signal.removeEventListener(\n \"abort\",\n abortPendingFetchRevalidations\n );\n\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach((r) => fetchControllers.delete(r.key));\n\n let redirect = findRedirect(results);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey =\n revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(state, redirect.result);\n }\n\n // Process and commit output from loaders\n let { loaderData, errors } = processLoaderData(\n state,\n state.matches,\n matchesToLoad,\n loaderResults,\n undefined,\n revalidatingFetchers,\n fetcherResults,\n activeDeferreds\n );\n\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n\n let didAbortFetchLoads = abortStaleFetchLoads(loadId);\n\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (\n state.navigation.state === \"loading\" &&\n loadId > pendingNavigationLoadId\n ) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers),\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(\n state.loaderData,\n loaderData,\n matches,\n errors\n ),\n ...(didAbortFetchLoads || revalidatingFetchers.length > 0\n ? { fetchers: new Map(state.fetchers) }\n : {}),\n });\n isRevalidationRequired = false;\n }\n }\n\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(\n key: string,\n routeId: string,\n path: string,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n submission?: Submission\n ) {\n let existingFetcher = state.fetchers.get(key);\n // Put this fetcher into it's loading state\n let loadingFetcher = getLoadingFetcher(\n submission,\n existingFetcher ? existingFetcher.data : undefined\n );\n state.fetchers.set(key, loadingFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n\n // Call the loader for this fetcher route match\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(\n init.history,\n path,\n abortController.signal\n );\n fetchControllers.set(key, abortController);\n\n let originatingLoadId = incrementingLoadId;\n let result: DataResult = await callLoaderOrAction(\n \"loader\",\n fetchRequest,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename\n );\n\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result =\n (await resolveDeferredData(result, fetchRequest.signal, true)) ||\n result;\n }\n\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n\n if (fetchRequest.signal.aborted) {\n return;\n }\n\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n let doneFetcher = getDoneFetcher(undefined);\n state.fetchers.set(key, doneFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(state, result);\n return;\n }\n }\n\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n state.fetchers.delete(key);\n // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -\n // do we need to behave any differently with our non-redirect errors?\n // What if it was a non-redirect Response?\n updateState({\n fetchers: new Map(state.fetchers),\n errors: {\n [boundaryMatch.route.id]: result.error,\n },\n });\n return;\n }\n\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n\n // Put the fetcher back into an idle state\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n updateState({ fetchers: new Map(state.fetchers) });\n }\n\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(\n state: RouterState,\n redirect: RedirectResult,\n {\n submission,\n replace,\n isFetchActionRedirect,\n }: {\n submission?: Submission;\n replace?: boolean;\n isFetchActionRedirect?: boolean;\n } = {}\n ) {\n if (redirect.revalidate) {\n isRevalidationRequired = true;\n }\n\n let redirectLocation = createLocation(\n state.location,\n redirect.location,\n // TODO: This can be removed once we get rid of useTransition in Remix v2\n {\n _isRedirect: true,\n ...(isFetchActionRedirect ? { _isFetchActionRedirect: true } : {}),\n }\n );\n invariant(\n redirectLocation,\n \"Expected a location on the redirect navigation\"\n );\n // Check if this an absolute external redirect that goes to a new origin\n if (ABSOLUTE_URL_REGEX.test(redirect.location) && isBrowser) {\n let url = init.history.createURL(redirect.location);\n let isDifferentBasename = stripBasename(url.pathname, basename) == null;\n\n if (routerWindow.location.origin !== url.origin || isDifferentBasename) {\n if (replace) {\n routerWindow.location.replace(redirect.location);\n } else {\n routerWindow.location.assign(redirect.location);\n }\n return;\n }\n }\n\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n\n let redirectHistoryAction =\n replace === true ? HistoryAction.Replace : HistoryAction.Push;\n\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let activeSubmission =\n submission || getSubmissionFromNavigation(state.navigation);\n\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n if (\n redirectPreserveMethodStatusCodes.has(redirect.status) &&\n activeSubmission &&\n isMutationMethod(activeSubmission.formMethod)\n ) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: {\n ...activeSubmission,\n formAction: redirect.location,\n },\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else if (isFetchActionRedirect) {\n // For a fetch action redirect, we kick off a new loading navigation\n // without the fetcher submission, but we send it along for shouldRevalidate\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation: getLoadingNavigation(redirectLocation),\n fetcherSubmission: activeSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n } else {\n // If we have a submission, we will preserve it through the redirect navigation\n let overrideNavigation = getLoadingNavigation(\n redirectLocation,\n activeSubmission\n );\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset,\n });\n }\n }\n\n async function callLoadersAndMaybeResolveData(\n currentMatches: AgnosticDataRouteMatch[],\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n fetchersToLoad: RevalidatingFetcher[],\n request: Request\n ) {\n // Call all navigation loaders and revalidating fetcher loaders in parallel,\n // then slice off the results into separate arrays so we can handle them\n // accordingly\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename\n )\n ),\n ...fetchersToLoad.map((f) => {\n if (f.matches && f.match && f.controller) {\n return callLoaderOrAction(\n \"loader\",\n createClientSideRequest(init.history, f.path, f.controller.signal),\n f.match,\n f.matches,\n manifest,\n mapRouteProperties,\n basename\n );\n } else {\n let error: ErrorResult = {\n type: ResultType.error,\n error: getInternalRouterError(404, { pathname: f.path }),\n };\n return error;\n }\n }),\n ]);\n let loaderResults = results.slice(0, matchesToLoad.length);\n let fetcherResults = results.slice(matchesToLoad.length);\n\n await Promise.all([\n resolveDeferredResults(\n currentMatches,\n matchesToLoad,\n loaderResults,\n loaderResults.map(() => request.signal),\n false,\n state.loaderData\n ),\n resolveDeferredResults(\n currentMatches,\n fetchersToLoad.map((f) => f.match),\n fetcherResults,\n fetchersToLoad.map((f) => (f.controller ? f.controller.signal : null)),\n true\n ),\n ]);\n\n return { results, loaderResults, fetcherResults };\n }\n\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\n });\n }\n\n function setFetcherError(key: string, routeId: string, error: any) {\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState({\n errors: {\n [boundaryMatch.route.id]: error,\n },\n fetchers: new Map(state.fetchers),\n });\n }\n\n function deleteFetcher(key: string): void {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (\n fetchControllers.has(key) &&\n !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))\n ) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n state.fetchers.delete(key);\n }\n\n function abortFetcher(key: string) {\n let controller = fetchControllers.get(key);\n invariant(controller, `Expected fetch controller: ${key}`);\n controller.abort();\n fetchControllers.delete(key);\n }\n\n function markFetchersDone(keys: string[]) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n function markFetchRedirectsDone(): boolean {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n\n function abortStaleFetchLoads(landedId: number): boolean {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, `Expected fetcher: ${key}`);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n\n function getBlocker(key: string, fn: BlockerFunction) {\n let blocker: Blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n\n return blocker;\n }\n\n function deleteBlocker(key: string) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key: string, newBlocker: Blocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(\n (blocker.state === \"unblocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"blocked\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"proceeding\") ||\n (blocker.state === \"blocked\" && newBlocker.state === \"unblocked\") ||\n (blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\"),\n `Invalid blocker state transition: ${blocker.state} -> ${newBlocker.state}`\n );\n\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({ blockers });\n }\n\n function shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction,\n }: {\n currentLocation: Location;\n nextLocation: Location;\n historyAction: HistoryAction;\n }): string | undefined {\n if (blockerFunctions.size === 0) {\n return;\n }\n\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({ currentLocation, nextLocation, historyAction })) {\n return blockerKey;\n }\n }\n\n function cancelActiveDeferreds(\n predicate?: (routeId: string) => boolean\n ): string[] {\n let cancelledRouteIds: string[] = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(\n positions: Record,\n getPosition: GetScrollPositionFunction,\n getKey?: GetScrollRestorationKeyFunction\n ) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({ restoreScrollPosition: y });\n }\n }\n\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n\n function getScrollKey(location: Location, matches: AgnosticDataRouteMatch[]) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(\n location,\n matches.map((m) => createUseMatchesMatch(m, state.loaderData))\n );\n return key || location.key;\n }\n return location.key;\n }\n\n function saveScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): void {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n\n function getSavedScrollPosition(\n location: Location,\n matches: AgnosticDataRouteMatch[]\n ): number | null {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n\n function _internalSetRoutes(newRoutes: AgnosticDataRouteObject[]) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(\n newRoutes,\n mapRouteProperties,\n undefined,\n manifest\n );\n }\n\n router = {\n get basename() {\n return basename;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: (to: To) => init.history.createHref(to),\n encodeLocation: (to: To) => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher,\n dispose,\n getBlocker,\n deleteBlocker,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes,\n };\n\n return router;\n}\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\n\nexport const UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\n\nexport interface CreateStaticHandlerOptions {\n basename?: string;\n /**\n * @deprecated Use `mapRouteProperties` instead\n */\n detectErrorBoundary?: DetectErrorBoundaryFunction;\n mapRouteProperties?: MapRoutePropertiesFunction;\n}\n\nexport function createStaticHandler(\n routes: AgnosticRouteObject[],\n opts?: CreateStaticHandlerOptions\n): StaticHandler {\n invariant(\n routes.length > 0,\n \"You must provide a non-empty routes array to createStaticHandler\"\n );\n\n let manifest: RouteManifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties: MapRoutePropertiesFunction;\n if (opts?.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts?.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = (route) => ({\n hasErrorBoundary: detectErrorBoundary(route),\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n\n let dataRoutes = convertRoutesToDataRoutes(\n routes,\n mapRouteProperties,\n undefined,\n manifest\n );\n\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n */\n async function query(\n request: Request,\n { requestContext }: { requestContext?: unknown } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, { method });\n let { matches: methodNotAllowedMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, { pathname: location.pathname });\n let { matches: notFoundMatches, route } =\n getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error,\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let result = await queryImpl(request, location, matches, requestContext);\n if (isResponse(result)) {\n return result;\n }\n\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return { location, basename, ...result };\n }\n\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n */\n async function queryRoute(\n request: Request,\n {\n routeId,\n requestContext,\n }: { requestContext?: unknown; routeId?: string } = {}\n ): Promise {\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, { method });\n } else if (!matches) {\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let match = routeId\n ? matches.find((m) => m.route.id === routeId)\n : getTargetMatch(matches, location);\n\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId,\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, { pathname: location.pathname });\n }\n\n let result = await queryImpl(\n request,\n location,\n matches,\n requestContext,\n match\n );\n if (isResponse(result)) {\n return result;\n }\n\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n\n if (result.loaderData) {\n let data = Object.values(result.loaderData)[0];\n if (result.activeDeferreds?.[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n\n return undefined;\n }\n\n async function queryImpl(\n request: Request,\n location: Location,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch\n ): Promise | Response> {\n invariant(\n request.signal,\n \"query()/queryRoute() requests must contain an AbortController signal\"\n );\n\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(\n request,\n matches,\n routeMatch || getTargetMatch(matches, location),\n requestContext,\n routeMatch != null\n );\n return result;\n }\n\n let result = await loadRouteData(\n request,\n matches,\n requestContext,\n routeMatch\n );\n return isResponse(result)\n ? result\n : {\n ...result,\n actionData: null,\n actionHeaders: {},\n };\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction, we throw\n // it to bail out and then return or throw here based on whether the user\n // returned or threw\n if (isQueryRouteResponse(e)) {\n if (e.type === ResultType.error && !isRedirectResponse(e.response)) {\n throw e.response;\n }\n return e.response;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n\n async function submit(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n actionMatch: AgnosticDataRouteMatch,\n requestContext: unknown,\n isRouteRequest: boolean\n ): Promise | Response> {\n let result: DataResult;\n\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id,\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n } else {\n result = await callLoaderOrAction(\n \"action\",\n request,\n actionMatch,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n { isStaticRequest: true, isRouteRequest, requestContext }\n );\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted`);\n }\n }\n\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.status,\n headers: {\n Location: result.location,\n },\n });\n }\n\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, { type: \"defer-action\" });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error,\n };\n }\n\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: { [actionMatch.route.id]: result.data },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null,\n };\n }\n\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n let context = await loadRouteData(\n request,\n matches,\n requestContext,\n undefined,\n {\n [boundaryMatch.route.id]: result.error,\n }\n );\n\n // action status codes take precedence over loader status codes\n return {\n ...context,\n statusCode: isRouteErrorResponse(result.error)\n ? result.error.status\n : 500,\n actionData: null,\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal,\n });\n let context = await loadRouteData(loaderRequest, matches, requestContext);\n\n return {\n ...context,\n // action status codes take precedence over loader status codes\n ...(result.statusCode ? { statusCode: result.statusCode } : {}),\n actionData: {\n [actionMatch.route.id]: result.data,\n },\n actionHeaders: {\n ...(result.headers ? { [actionMatch.route.id]: result.headers } : {}),\n },\n };\n }\n\n async function loadRouteData(\n request: Request,\n matches: AgnosticDataRouteMatch[],\n requestContext: unknown,\n routeMatch?: AgnosticDataRouteMatch,\n pendingActionError?: RouteData\n ): Promise<\n | Omit<\n StaticHandlerContext,\n \"location\" | \"basename\" | \"actionData\" | \"actionHeaders\"\n >\n | Response\n > {\n let isRouteRequest = routeMatch != null;\n\n // Short circuit if we have no loaders to run (queryRoute())\n if (\n isRouteRequest &&\n !routeMatch?.route.loader &&\n !routeMatch?.route.lazy\n ) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch?.route.id,\n });\n }\n\n let requestMatches = routeMatch\n ? [routeMatch]\n : getLoaderMatchesUntilBoundary(\n matches,\n Object.keys(pendingActionError || {})[0]\n );\n let matchesToLoad = requestMatches.filter(\n (m) => m.route.loader || m.route.lazy\n );\n\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce(\n (acc, m) => Object.assign(acc, { [m.route.id]: null }),\n {}\n ),\n errors: pendingActionError || null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null,\n };\n }\n\n let results = await Promise.all([\n ...matchesToLoad.map((match) =>\n callLoaderOrAction(\n \"loader\",\n request,\n match,\n matches,\n manifest,\n mapRouteProperties,\n basename,\n { isStaticRequest: true, isRouteRequest, requestContext }\n )\n ),\n ]);\n\n if (request.signal.aborted) {\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(`${method}() call aborted`);\n }\n\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingActionError,\n activeDeferreds\n );\n\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(\n matchesToLoad.map((match) => match.route.id)\n );\n matches.forEach((match) => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n\n return {\n ...context,\n matches,\n activeDeferreds:\n activeDeferreds.size > 0\n ? Object.fromEntries(activeDeferreds.entries())\n : null,\n };\n }\n\n return {\n dataRoutes,\n query,\n queryRoute,\n };\n}\n\n//#endregion\n\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nexport function getStaticContextFromError(\n routes: AgnosticDataRouteObject[],\n context: StaticHandlerContext,\n error: any\n) {\n let newContext: StaticHandlerContext = {\n ...context,\n statusCode: 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error,\n },\n };\n return newContext;\n}\n\nfunction isSubmissionNavigation(\n opts: RouterNavigateOptions\n): opts is SubmissionNavigateOptions {\n return (\n opts != null &&\n ((\"formData\" in opts && opts.formData != null) ||\n (\"body\" in opts && opts.body !== undefined))\n );\n}\n\nfunction normalizeTo(\n location: Path,\n matches: AgnosticDataRouteMatch[],\n basename: string,\n prependBasename: boolean,\n to: To | null,\n fromRouteId?: string,\n relative?: RelativeRoutingType\n) {\n let contextualMatches: AgnosticDataRouteMatch[];\n let activeRouteMatch: AgnosticDataRouteMatch | undefined;\n if (fromRouteId != null && relative !== \"path\") {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route. When using relative:path,\n // fromRouteId is ignored since that is always relative to the current\n // location path\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n\n // Resolve the relative path\n let path = resolveTo(\n to ? to : \".\",\n getPathContributingMatches(contextualMatches).map((m) => m.pathnameBase),\n stripBasename(location.pathname, basename) || location.pathname,\n relative === \"path\"\n );\n\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n\n // Add an ?index param for matched index routes if we don't already have one\n if (\n (to == null || to === \"\" || to === \".\") &&\n activeRouteMatch &&\n activeRouteMatch.route.index &&\n !hasNakedIndexQuery(path.search)\n ) {\n path.search = path.search\n ? path.search.replace(/^\\?/, \"?index&\")\n : \"?index\";\n }\n\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n\n return createPath(path);\n}\n\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(\n normalizeFormMethod: boolean,\n isFetcher: boolean,\n path: string,\n opts?: RouterNavigateOptions\n): {\n path: string;\n submission?: Submission;\n error?: ErrorResponse;\n} {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return { path };\n }\n\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, { method: opts.formMethod }),\n };\n }\n\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, { type: \"invalid-body\" }),\n });\n\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod\n ? (rawFormMethod.toUpperCase() as V7_FormMethod)\n : (rawFormMethod.toLowerCase() as FormMethod);\n let formAction = stripHashFromPath(path);\n\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n let text =\n typeof opts.body === \"string\"\n ? opts.body\n : opts.body instanceof FormData ||\n opts.body instanceof URLSearchParams\n ? // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce(\n (acc, [name, value]) => `${acc}${name}=${value}\\n`,\n \"\"\n )\n : String(opts.body);\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text,\n },\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n\n try {\n let json =\n typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined,\n },\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n\n invariant(\n typeof FormData === \"function\",\n \"FormData is not available in this environment\"\n );\n\n let searchParams: URLSearchParams;\n let formData: FormData;\n\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n\n let submission: Submission = {\n formMethod,\n formAction,\n formEncType:\n (opts && opts.formEncType) || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined,\n };\n\n if (isMutationMethod(submission.formMethod)) {\n return { path, submission };\n }\n\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = `?${searchParams}`;\n\n return { path: createPath(parsedPath), submission };\n}\n\n// Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(\n matches: AgnosticDataRouteMatch[],\n boundaryId?: string\n) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex((m) => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\n\nfunction getMatchesToLoad(\n history: History,\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n submission: Submission | undefined,\n location: Location,\n isRevalidationRequired: boolean,\n cancelledDeferredRoutes: string[],\n cancelledFetcherLoads: string[],\n fetchLoadMatches: Map,\n fetchRedirectIds: Set,\n routesToUse: AgnosticDataRouteObject[],\n basename: string | undefined,\n pendingActionData?: RouteData,\n pendingError?: RouteData\n): [AgnosticDataRouteMatch[], RevalidatingFetcher[]] {\n let actionResult = pendingError\n ? Object.values(pendingError)[0]\n : pendingActionData\n ? Object.values(pendingActionData)[0]\n : undefined;\n\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;\n let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);\n\n let navigationMatches = boundaryMatches.filter((match, index) => {\n if (match.route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n if (match.route.loader == null) {\n return false;\n }\n\n // Always call the loader on new route instances and pending defer cancellations\n if (\n isNewLoader(state.loaderData, state.matches[index], match) ||\n cancelledDeferredRoutes.some((id) => id === match.route.id)\n ) {\n return true;\n }\n\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n\n return shouldRevalidateLoader(match, {\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params,\n ...submission,\n actionResult,\n defaultShouldRevalidate:\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired ||\n // Clicked the same link, resubmitted a GET form\n currentUrl.pathname + currentUrl.search ===\n nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search ||\n isNewRouteInstance(currentRouteMatch, nextRouteMatch),\n });\n });\n\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers: RevalidatingFetcher[] = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate if fetcher won't be present in the subsequent render\n if (!matches.some((m) => m.route.id === f.routeId)) {\n return;\n }\n\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null,\n });\n return;\n }\n\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (\n fetcher &&\n fetcher.state !== \"idle\" &&\n fetcher.data === undefined\n ) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, {\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params,\n ...submission,\n actionResult,\n defaultShouldRevalidate: isRevalidationRequired,\n });\n }\n\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController(),\n });\n }\n });\n\n return [navigationMatches, revalidatingFetchers];\n}\n\nfunction isNewLoader(\n currentLoaderData: RouteData,\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\n\nfunction isNewRouteInstance(\n currentMatch: AgnosticDataRouteMatch,\n match: AgnosticDataRouteMatch\n) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n (currentPath != null &&\n currentPath.endsWith(\"*\") &&\n currentMatch.params[\"*\"] !== match.params[\"*\"])\n );\n}\n\nfunction shouldRevalidateLoader(\n loaderMatch: AgnosticDataRouteMatch,\n arg: Parameters[0]\n) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n\n return arg.defaultShouldRevalidate;\n}\n\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(\n route: AgnosticDataRouteObject,\n mapRouteProperties: MapRoutePropertiesFunction,\n manifest: RouteManifest\n) {\n if (!route.lazy) {\n return;\n }\n\n let lazyRoute = await route.lazy();\n\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates: Record = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue =\n routeToUpdate[lazyRouteProperty as keyof typeof routeToUpdate];\n\n let isPropertyStaticallyDefined =\n staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n\n warning(\n !isPropertyStaticallyDefined,\n `Route \"${routeToUpdate.id}\" has a static property \"${lazyRouteProperty}\" ` +\n `defined but its lazy function is also returning a value for this property. ` +\n `The lazy route property \"${lazyRouteProperty}\" will be ignored.`\n );\n\n if (\n !isPropertyStaticallyDefined &&\n !immutableRouteKeys.has(lazyRouteProperty as ImmutableRouteKey)\n ) {\n routeUpdates[lazyRouteProperty] =\n lazyRoute[lazyRouteProperty as keyof typeof lazyRoute];\n }\n }\n\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, {\n // To keep things framework agnostic, we use the provided\n // `mapRouteProperties` (or wrapped `detectErrorBoundary`) function to\n // set the framework-aware properties (`element`/`hasErrorBoundary`) since\n // the logic will differ between frameworks.\n ...mapRouteProperties(routeToUpdate),\n lazy: undefined,\n });\n}\n\nasync function callLoaderOrAction(\n type: \"loader\" | \"action\",\n request: Request,\n match: AgnosticDataRouteMatch,\n matches: AgnosticDataRouteMatch[],\n manifest: RouteManifest,\n mapRouteProperties: MapRoutePropertiesFunction,\n basename: string,\n opts: {\n isStaticRequest?: boolean;\n isRouteRequest?: boolean;\n requestContext?: unknown;\n } = {}\n): Promise {\n let resultType;\n let result;\n let onReject: (() => void) | undefined;\n\n let runHandler = (handler: ActionFunction | LoaderFunction) => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject: () => void;\n let abortPromise = new Promise((_, r) => (reject = r));\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n return Promise.race([\n handler({\n request,\n params: match.params,\n context: opts.requestContext,\n }),\n abortPromise,\n ]);\n };\n\n try {\n let handler = match.route[type];\n\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let values = await Promise.all([\n runHandler(handler),\n loadLazyRouteModule(match.route, mapRouteProperties, manifest),\n ]);\n result = values[0];\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n\n handler = match.route[type];\n if (handler) {\n // Handler still run even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id,\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return { type: ResultType.data, data: undefined };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname,\n });\n } else {\n result = await runHandler(handler);\n }\n\n invariant(\n result !== undefined,\n `You defined ${type === \"action\" ? \"an action\" : \"a loader\"} for route ` +\n `\"${match.route.id}\" but didn't return anything from your \\`${type}\\` ` +\n `function. Please return a value or \\`null\\`.`\n );\n } catch (e) {\n resultType = ResultType.error;\n result = e;\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n\n if (isResponse(result)) {\n let status = result.status;\n\n // Process redirects\n if (redirectStatusCodes.has(status)) {\n let location = result.headers.get(\"Location\");\n invariant(\n location,\n \"Redirects returned/thrown from loaders/actions must have a Location header\"\n );\n\n // Support relative routing in internal redirects\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n location = normalizeTo(\n new URL(request.url),\n matches.slice(0, matches.indexOf(match) + 1),\n basename,\n true,\n location\n );\n } else if (!opts.isStaticRequest) {\n // Strip off the protocol+origin for same-origin + same-basename absolute\n // redirects. If this is a static request, we can let it go back to the\n // browser as-is\n let currentUrl = new URL(request.url);\n let url = location.startsWith(\"//\")\n ? new URL(currentUrl.protocol + location)\n : new URL(location);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n location = url.pathname + url.search + url.hash;\n }\n }\n\n // Don't process redirects in the router during static requests requests.\n // Instead, throw the Response and let the server handle it with an HTTP\n // redirect. We also update the Location header in place in this flow so\n // basename and relative routing is taken into account\n if (opts.isStaticRequest) {\n result.headers.set(\"Location\", location);\n throw result;\n }\n\n return {\n type: ResultType.redirect,\n status,\n location,\n revalidate: result.headers.get(\"X-Remix-Revalidate\") !== null,\n };\n }\n\n // For SSR single-route requests, we want to hand Responses back directly\n // without unwrapping. We do this with the QueryRouteResponse wrapper\n // interface so we can know whether it was returned or thrown\n if (opts.isRouteRequest) {\n // eslint-disable-next-line no-throw-literal\n throw {\n type: resultType || ResultType.data,\n response: result,\n };\n }\n\n let data: any;\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n data = await result.json();\n } else {\n data = await result.text();\n }\n\n if (resultType === ResultType.error) {\n return {\n type: resultType,\n error: new ErrorResponse(status, result.statusText, data),\n headers: result.headers,\n };\n }\n\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers,\n };\n }\n\n if (resultType === ResultType.error) {\n return { type: resultType, error: result };\n }\n\n if (isDeferredData(result)) {\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: result.init?.status,\n headers: result.init?.headers && new Headers(result.init.headers),\n };\n }\n\n return { type: ResultType.data, data: result };\n}\n\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(\n history: History,\n location: string | Location,\n signal: AbortSignal,\n submission?: Submission\n): Request {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init: RequestInit = { signal };\n\n if (submission && isMutationMethod(submission.formMethod)) {\n let { formMethod, formEncType } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n\n if (formEncType === \"application/json\") {\n init.headers = new Headers({ \"Content-Type\": formEncType });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (\n formEncType === \"application/x-www-form-urlencoded\" &&\n submission.formData\n ) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n\n return new Request(url, init);\n}\n\nfunction convertFormDataToSearchParams(formData: FormData): URLSearchParams {\n let searchParams = new URLSearchParams();\n\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n\n return searchParams;\n}\n\nfunction convertSearchParamsToFormData(\n searchParams: URLSearchParams\n): FormData {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\n\nfunction processRouteLoaderData(\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors: RouterState[\"errors\"] | null;\n statusCode: number;\n loaderHeaders: Record;\n} {\n // Fill in loaderData/errors from our loaders\n let loaderData: RouterState[\"loaderData\"] = {};\n let errors: RouterState[\"errors\"] | null = null;\n let statusCode: number | undefined;\n let foundError = false;\n let loaderHeaders: Record = {};\n\n // Process loader results into state.loaderData/state.errors\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(\n !isRedirectResult(result),\n \"Cannot handle redirect results in processLoaderData\"\n );\n if (isErrorResult(result)) {\n // Look upwards from the matched route for the closest ancestor\n // error boundary, defaulting to the root match\n let boundaryMatch = findNearestBoundary(matches, id);\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError) {\n error = Object.values(pendingError)[0];\n pendingError = undefined;\n }\n\n errors = errors || {};\n\n // Prefer higher error values if lower errors bubble to the same boundary\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error)\n ? result.error.status\n : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n } else {\n loaderData[id] = result.data;\n }\n\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (\n result.statusCode != null &&\n result.statusCode !== 200 &&\n !foundError\n ) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n });\n\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError) {\n errors = pendingError;\n loaderData[Object.keys(pendingError)[0]] = undefined;\n }\n\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders,\n };\n}\n\nfunction processLoaderData(\n state: RouterState,\n matches: AgnosticDataRouteMatch[],\n matchesToLoad: AgnosticDataRouteMatch[],\n results: DataResult[],\n pendingError: RouteData | undefined,\n revalidatingFetchers: RevalidatingFetcher[],\n fetcherResults: DataResult[],\n activeDeferreds: Map\n): {\n loaderData: RouterState[\"loaderData\"];\n errors?: RouterState[\"errors\"];\n} {\n let { loaderData, errors } = processRouteLoaderData(\n matches,\n matchesToLoad,\n results,\n pendingError,\n activeDeferreds\n );\n\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let { key, match, controller } = revalidatingFetchers[index];\n invariant(\n fetcherResults !== undefined && fetcherResults[index] !== undefined,\n \"Did not find corresponding fetcher result\"\n );\n let result = fetcherResults[index];\n\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match?.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = {\n ...errors,\n [boundaryMatch.route.id]: result.error,\n };\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n\n return { loaderData, errors };\n}\n\nfunction mergeLoaderData(\n loaderData: RouteData,\n newLoaderData: RouteData,\n matches: AgnosticDataRouteMatch[],\n errors: RouteData | null | undefined\n): RouteData {\n let mergedLoaderData = { ...newLoaderData };\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n } else {\n // No-op - this is so we ignore existing data if we have a key in the\n // incoming object with an undefined value, which is how we unset a prior\n // loaderData if we encounter a loader error\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\n\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(\n matches: AgnosticDataRouteMatch[],\n routeId?: string\n): AgnosticDataRouteMatch {\n let eligibleMatches = routeId\n ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1)\n : [...matches];\n return (\n eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) ||\n matches[0]\n );\n}\n\nfunction getShortCircuitMatches(routes: AgnosticDataRouteObject[]): {\n matches: AgnosticDataRouteMatch[];\n route: AgnosticDataRouteObject;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route = routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: `__shim-error-route__`,\n };\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n };\n}\n\nfunction getInternalRouterError(\n status: number,\n {\n pathname,\n routeId,\n method,\n type,\n }: {\n pathname?: string;\n routeId?: string;\n method?: string;\n type?: \"defer-action\" | \"invalid-body\";\n } = {}\n) {\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n\n if (status === 400) {\n statusText = \"Bad Request\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method} request to \"${pathname}\" but ` +\n `did not provide a \\`loader\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = `Route \"${routeId}\" does not match URL \"${pathname}\"`;\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = `No route matches URL \"${pathname}\"`;\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage =\n `You made a ${method.toUpperCase()} request to \"${pathname}\" but ` +\n `did not provide an \\`action\\` for route \"${routeId}\", ` +\n `so there is no way to handle the request.`;\n } else if (method) {\n errorMessage = `Invalid request method \"${method.toUpperCase()}\"`;\n }\n }\n\n return new ErrorResponse(\n status || 500,\n statusText,\n new Error(errorMessage),\n true\n );\n}\n\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(\n results: DataResult[]\n): { result: RedirectResult; idx: number } | undefined {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return { result, idx: i };\n }\n }\n}\n\nfunction stripHashFromPath(path: To) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath({ ...parsedPath, hash: \"\" });\n}\n\nfunction isHashChangeOnly(a: Location, b: Location): boolean {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\n\nfunction isDeferredResult(result: DataResult): result is DeferredResult {\n return result.type === ResultType.deferred;\n}\n\nfunction isErrorResult(result: DataResult): result is ErrorResult {\n return result.type === ResultType.error;\n}\n\nfunction isRedirectResult(result?: DataResult): result is RedirectResult {\n return (result && result.type) === ResultType.redirect;\n}\n\nexport function isDeferredData(value: any): value is DeferredData {\n let deferred: DeferredData = value;\n return (\n deferred &&\n typeof deferred === \"object\" &&\n typeof deferred.data === \"object\" &&\n typeof deferred.subscribe === \"function\" &&\n typeof deferred.cancel === \"function\" &&\n typeof deferred.resolveData === \"function\"\n );\n}\n\nfunction isResponse(value: any): value is Response {\n return (\n value != null &&\n typeof value.status === \"number\" &&\n typeof value.statusText === \"string\" &&\n typeof value.headers === \"object\" &&\n typeof value.body !== \"undefined\"\n );\n}\n\nfunction isRedirectResponse(result: any): result is Response {\n if (!isResponse(result)) {\n return false;\n }\n\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\n\nfunction isQueryRouteResponse(obj: any): obj is QueryRouteResponse {\n return (\n obj &&\n isResponse(obj.response) &&\n (obj.type === ResultType.data || ResultType.error)\n );\n}\n\nfunction isValidMethod(method: string): method is FormMethod | V7_FormMethod {\n return validRequestMethods.has(method.toLowerCase() as FormMethod);\n}\n\nfunction isMutationMethod(\n method: string\n): method is MutationFormMethod | V7_MutationFormMethod {\n return validMutationMethods.has(method.toLowerCase() as MutationFormMethod);\n}\n\nasync function resolveDeferredResults(\n currentMatches: AgnosticDataRouteMatch[],\n matchesToLoad: (AgnosticDataRouteMatch | null)[],\n results: DataResult[],\n signals: (AbortSignal | null)[],\n isFetcher: boolean,\n currentLoaderData?: RouteData\n) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n\n let currentMatch = currentMatches.find(\n (m) => m.route.id === match!.route.id\n );\n let isRevalidatingLoader =\n currentMatch != null &&\n !isNewRouteInstance(currentMatch, match) &&\n (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(\n signal,\n \"Expected an AbortSignal for revalidating fetcher deferred result\"\n );\n await resolveDeferredData(result, signal, isFetcher).then((result) => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\n\nasync function resolveDeferredData(\n result: DeferredResult,\n signal: AbortSignal,\n unwrap = false\n): Promise {\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData,\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e,\n };\n }\n }\n\n return {\n type: ResultType.data,\n data: result.deferredData.data,\n };\n}\n\nfunction hasNakedIndexQuery(search: string): boolean {\n return new URLSearchParams(search).getAll(\"index\").some((v) => v === \"\");\n}\n\n// Note: This should match the format exported by useMatches, so if you change\n// this please also change that :) Eventually we'll DRY this up\nfunction createUseMatchesMatch(\n match: AgnosticDataRouteMatch,\n loaderData: RouteData\n): UseMatchesMatch {\n let { route, pathname, params } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id] as unknown,\n handle: route.handle as unknown,\n };\n}\n\nfunction getTargetMatch(\n matches: AgnosticDataRouteMatch[],\n location: Location | string\n) {\n let search =\n typeof location === \"string\" ? parsePath(location).search : location.search;\n if (\n matches[matches.length - 1].route.index &&\n hasNakedIndexQuery(search || \"\")\n ) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\n\nfunction getSubmissionFromNavigation(\n navigation: Navigation\n): Submission | undefined {\n let { formMethod, formAction, formEncType, text, formData, json } =\n navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text,\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined,\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined,\n };\n }\n}\n\nfunction getLoadingNavigation(\n location: Location,\n submission?: Submission\n): NavigationStates[\"Loading\"] {\n if (submission) {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n } else {\n let navigation: NavigationStates[\"Loading\"] = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n };\n return navigation;\n }\n}\n\nfunction getSubmittingNavigation(\n location: Location,\n submission: Submission\n): NavigationStates[\"Submitting\"] {\n let navigation: NavigationStates[\"Submitting\"] = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n };\n return navigation;\n}\n\nfunction getLoadingFetcher(\n submission?: Submission,\n data?: Fetcher[\"data\"]\n): FetcherStates[\"Loading\"] {\n if (submission) {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data,\n \" _hasFetcherDoneAnything \": true,\n };\n return fetcher;\n } else {\n let fetcher: FetcherStates[\"Loading\"] = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n \" _hasFetcherDoneAnything \": true,\n };\n return fetcher;\n }\n}\n\nfunction getSubmittingFetcher(\n submission: Submission,\n existingFetcher?: Fetcher\n): FetcherStates[\"Submitting\"] {\n let fetcher: FetcherStates[\"Submitting\"] = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined,\n \" _hasFetcherDoneAnything \": true,\n };\n return fetcher;\n}\n\nfunction getDoneFetcher(data: Fetcher[\"data\"]): FetcherStates[\"Idle\"] {\n let fetcher: FetcherStates[\"Idle\"] = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data,\n \" _hasFetcherDoneAnything \": true,\n };\n return fetcher;\n}\n//#endregion\n", "import * as React from \"react\";\nimport type {\n AgnosticRouteMatch,\n AgnosticIndexRouteObject,\n AgnosticNonIndexRouteObject,\n History,\n Location,\n RelativeRoutingType,\n Router,\n StaticHandlerContext,\n To,\n TrackedPromise,\n LazyRouteFunction,\n} from \"@remix-run/router\";\nimport type { Action as NavigationType } from \"@remix-run/router\";\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nexport interface IndexRouteObject {\n caseSensitive?: AgnosticIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticIndexRouteObject[\"path\"];\n id?: AgnosticIndexRouteObject[\"id\"];\n loader?: AgnosticIndexRouteObject[\"loader\"];\n action?: AgnosticIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticIndexRouteObject[\"handle\"];\n index: true;\n children?: undefined;\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction;\n}\n\nexport interface NonIndexRouteObject {\n caseSensitive?: AgnosticNonIndexRouteObject[\"caseSensitive\"];\n path?: AgnosticNonIndexRouteObject[\"path\"];\n id?: AgnosticNonIndexRouteObject[\"id\"];\n loader?: AgnosticNonIndexRouteObject[\"loader\"];\n action?: AgnosticNonIndexRouteObject[\"action\"];\n hasErrorBoundary?: AgnosticNonIndexRouteObject[\"hasErrorBoundary\"];\n shouldRevalidate?: AgnosticNonIndexRouteObject[\"shouldRevalidate\"];\n handle?: AgnosticNonIndexRouteObject[\"handle\"];\n index?: false;\n children?: RouteObject[];\n element?: React.ReactNode | null;\n errorElement?: React.ReactNode | null;\n Component?: React.ComponentType | null;\n ErrorBoundary?: React.ComponentType | null;\n lazy?: LazyRouteFunction;\n}\n\nexport type RouteObject = IndexRouteObject | NonIndexRouteObject;\n\nexport type DataRouteObject = RouteObject & {\n children?: DataRouteObject[];\n id: string;\n};\n\nexport interface RouteMatch<\n ParamKey extends string = string,\n RouteObjectType extends RouteObject = RouteObject\n> extends AgnosticRouteMatch {}\n\nexport interface DataRouteMatch extends RouteMatch {}\n\nexport interface DataRouterContextObject extends NavigationContextObject {\n router: Router;\n staticContext?: StaticHandlerContext;\n}\n\nexport const DataRouterContext =\n React.createContext(null);\nif (__DEV__) {\n DataRouterContext.displayName = \"DataRouter\";\n}\n\nexport const DataRouterStateContext = React.createContext<\n Router[\"state\"] | null\n>(null);\nif (__DEV__) {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\n\nexport const AwaitContext = React.createContext(null);\nif (__DEV__) {\n AwaitContext.displayName = \"Await\";\n}\n\nexport interface NavigateOptions {\n replace?: boolean;\n state?: any;\n preventScrollReset?: boolean;\n relative?: RelativeRoutingType;\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\nexport interface Navigator {\n createHref: History[\"createHref\"];\n // Optional for backwards-compat with Router/HistoryRouter usage (edge case)\n encodeLocation?: History[\"encodeLocation\"];\n go: History[\"go\"];\n push(to: To, state?: any, opts?: NavigateOptions): void;\n replace(to: To, state?: any, opts?: NavigateOptions): void;\n}\n\ninterface NavigationContextObject {\n basename: string;\n navigator: Navigator;\n static: boolean;\n}\n\nexport const NavigationContext = React.createContext(\n null!\n);\n\nif (__DEV__) {\n NavigationContext.displayName = \"Navigation\";\n}\n\ninterface LocationContextObject {\n location: Location;\n navigationType: NavigationType;\n}\n\nexport const LocationContext = React.createContext(\n null!\n);\n\nif (__DEV__) {\n LocationContext.displayName = \"Location\";\n}\n\nexport interface RouteContextObject {\n outlet: React.ReactElement | null;\n matches: RouteMatch[];\n isDataRoute: boolean;\n}\n\nexport const RouteContext = React.createContext({\n outlet: null,\n matches: [],\n isDataRoute: false,\n});\n\nif (__DEV__) {\n RouteContext.displayName = \"Route\";\n}\n\nexport const RouteErrorContext = React.createContext(null);\n\nif (__DEV__) {\n RouteErrorContext.displayName = \"RouteError\";\n}\n", "import * as React from \"react\";\nimport type {\n Blocker,\n BlockerFunction,\n Location,\n ParamParseKey,\n Params,\n Path,\n PathMatch,\n PathPattern,\n RelativeRoutingType,\n Router as RemixRouter,\n RevalidationState,\n To,\n} from \"@remix-run/router\";\nimport {\n Action as NavigationType,\n UNSAFE_invariant as invariant,\n isRouteErrorResponse,\n joinPaths,\n matchPath,\n matchRoutes,\n parsePath,\n resolveTo,\n stripBasename,\n IDLE_BLOCKER,\n UNSAFE_getPathContributingMatches as getPathContributingMatches,\n UNSAFE_warning as warning,\n} from \"@remix-run/router\";\n\nimport type {\n NavigateOptions,\n RouteContextObject,\n RouteMatch,\n RouteObject,\n DataRouteMatch,\n} from \"./context\";\nimport {\n DataRouterContext,\n DataRouterStateContext,\n LocationContext,\n NavigationContext,\n RouteContext,\n RouteErrorContext,\n AwaitContext,\n} from \"./context\";\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/hooks/use-href\n */\nexport function useHref(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): string {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useHref() may be used only in the context of a component.`\n );\n\n let { basename, navigator } = React.useContext(NavigationContext);\n let { hash, pathname, search } = useResolvedPath(to, { relative });\n\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname =\n pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n\n return navigator.createHref({ pathname: joinedPathname, search, hash });\n}\n\n/**\n * Returns true if this component is a descendant of a .\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\nexport function useInRouterContext(): boolean {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/hooks/use-location\n */\nexport function useLocation(): Location {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useLocation() may be used only in the context of a component.`\n );\n\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/hooks/use-navigation-type\n */\nexport function useNavigationType(): NavigationType {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * .\n *\n * @see https://reactrouter.com/hooks/use-match\n */\nexport function useMatch<\n ParamKey extends ParamParseKey,\n Path extends string\n>(pattern: PathPattern | Path): PathMatch | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useMatch() may be used only in the context of a component.`\n );\n\n let { pathname } = useLocation();\n return React.useMemo(\n () => matchPath(pattern, pathname),\n [pathname, pattern]\n );\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\nexport interface NavigateFunction {\n (to: To, options?: NavigateOptions): void;\n (delta: number): void;\n}\n\nconst navigateEffectWarning =\n `You should call navigate() in a React.useEffect(), not when ` +\n `your component is first rendered.`;\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(\n cb: Parameters[0]\n) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/hooks/use-navigate\n */\nexport function useNavigate(): NavigateFunction {\n let { isDataRoute } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\n\nfunction useNavigateUnstable(): NavigateFunction {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useNavigate() may be used only in the context of a component.`\n );\n\n let dataRouterContext = React.useContext(DataRouterContext);\n let { basename, navigator } = React.useContext(NavigationContext);\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(\n getPathContributingMatches(matches).map((match) => match.pathnameBase)\n );\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n\n let path = resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n options.relative === \"path\"\n );\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname =\n path.pathname === \"/\"\n ? basename\n : joinPaths([basename, path.pathname]);\n }\n\n (!!options.replace ? navigator.replace : navigator.push)(\n path,\n options.state,\n options\n );\n },\n [\n basename,\n navigator,\n routePathnamesJson,\n locationPathname,\n dataRouterContext,\n ]\n );\n\n return navigate;\n}\n\nconst OutletContext = React.createContext(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/hooks/use-outlet-context\n */\nexport function useOutletContext(): Context {\n return React.useContext(OutletContext) as Context;\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\nexport function useOutlet(context?: unknown): React.ReactElement | null {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return (\n {outlet}\n );\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/hooks/use-params\n */\nexport function useParams<\n ParamsOrKey extends string | Record = string\n>(): Readonly<\n [ParamsOrKey] extends [string] ? Params : Partial\n> {\n let { matches } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? (routeMatch.params as any) : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\nexport function useResolvedPath(\n to: To,\n { relative }: { relative?: RelativeRoutingType } = {}\n): Path {\n let { matches } = React.useContext(RouteContext);\n let { pathname: locationPathname } = useLocation();\n\n let routePathnamesJson = JSON.stringify(\n getPathContributingMatches(matches).map((match) => match.pathnameBase)\n );\n\n return React.useMemo(\n () =>\n resolveTo(\n to,\n JSON.parse(routePathnamesJson),\n locationPathname,\n relative === \"path\"\n ),\n [to, routePathnamesJson, locationPathname, relative]\n );\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\nexport function useRoutes(\n routes: RouteObject[],\n locationArg?: Partial | string\n): React.ReactElement | null {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nexport function useRoutesImpl(\n routes: RouteObject[],\n locationArg?: Partial | string,\n dataRouterState?: RemixRouter[\"state\"]\n): React.ReactElement | null {\n invariant(\n useInRouterContext(),\n // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n `useRoutes() may be used only in the context of a component.`\n );\n\n let { navigator } = React.useContext(NavigationContext);\n let { matches: parentMatches } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n\n if (__DEV__) {\n // You won't get a warning about 2 different under a \n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // \n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // } />\n // } />\n // \n //\n // function Blog() {\n // return (\n // \n // } />\n // \n // );\n // }\n let parentPath = (parentRoute && parentRoute.path) || \"\";\n warningOnce(\n parentPathname,\n !parentRoute || parentPath.endsWith(\"*\"),\n `You rendered descendant (or called \\`useRoutes()\\`) at ` +\n `\"${parentPathname}\" (under ) but the ` +\n `parent route path has no trailing \"*\". This means if you navigate ` +\n `deeper, the parent won't match anymore and therefore the child ` +\n `routes will never render.\\n\\n` +\n `Please change the parent to .`\n );\n }\n\n let locationFromContext = useLocation();\n\n let location;\n if (locationArg) {\n let parsedLocationArg =\n typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n\n invariant(\n parentPathnameBase === \"/\" ||\n parsedLocationArg.pathname?.startsWith(parentPathnameBase),\n `When overriding the location using \\`\\` or \\`useRoutes(routes, location)\\`, ` +\n `the location pathname must begin with the portion of the URL pathname that was ` +\n `matched by all parent routes. The current pathname base is \"${parentPathnameBase}\" ` +\n `but pathname \"${parsedLocationArg.pathname}\" was given in the \\`location\\` prop.`\n );\n\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n\n let pathname = location.pathname || \"/\";\n let remainingPathname =\n parentPathnameBase === \"/\"\n ? pathname\n : pathname.slice(parentPathnameBase.length) || \"/\";\n\n let matches = matchRoutes(routes, { pathname: remainingPathname });\n\n if (__DEV__) {\n warning(\n parentRoute || matches != null,\n `No routes matched location \"${location.pathname}${location.search}${location.hash}\" `\n );\n\n warning(\n matches == null ||\n matches[matches.length - 1].route.element !== undefined ||\n matches[matches.length - 1].route.Component !== undefined,\n `Matched leaf route at location \"${location.pathname}${location.search}${location.hash}\" ` +\n `does not have an element or Component. This means it will render an with a ` +\n `null value by default resulting in an \"empty\" page.`\n );\n }\n\n let renderedMatches = _renderMatches(\n matches &&\n matches.map((match) =>\n Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathname).pathname\n : match.pathname,\n ]),\n pathnameBase:\n match.pathnameBase === \"/\"\n ? parentPathnameBase\n : joinPaths([\n parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation\n ? navigator.encodeLocation(match.pathnameBase).pathname\n : match.pathnameBase,\n ]),\n })\n ),\n parentMatches,\n dataRouterState\n );\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return (\n \n {renderedMatches}\n \n );\n }\n\n return renderedMatches;\n}\n\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error)\n ? `${error.status} ${error.statusText}`\n : error instanceof Error\n ? error.message\n : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = { padding: \"0.5rem\", backgroundColor: lightgrey };\n let codeStyles = { padding: \"2px 4px\", backgroundColor: lightgrey };\n\n let devInfo = null;\n if (__DEV__) {\n console.error(\n \"Error handled by React Router default ErrorBoundary:\",\n error\n );\n\n devInfo = (\n <>\n

💿 Hey developer 👋

\n

\n You can provide a way better UX than this when your app throws errors\n by providing your own ErrorBoundary or{\" \"}\n errorElement prop on your route.\n

\n \n );\n }\n\n return (\n <>\n

Unexpected Application Error!

\n

{message}

\n {stack ?
{stack}
: null}\n {devInfo}\n \n );\n}\n\nconst defaultErrorElement = ;\n\ntype RenderErrorBoundaryProps = React.PropsWithChildren<{\n location: Location;\n revalidation: RevalidationState;\n error: any;\n component: React.ReactNode;\n routeContext: RouteContextObject;\n}>;\n\ntype RenderErrorBoundaryState = {\n location: Location;\n revalidation: RevalidationState;\n error: any;\n};\n\nexport class RenderErrorBoundary extends React.Component<\n RenderErrorBoundaryProps,\n RenderErrorBoundaryState\n> {\n constructor(props: RenderErrorBoundaryProps) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error,\n };\n }\n\n static getDerivedStateFromError(error: any) {\n return { error: error };\n }\n\n static getDerivedStateFromProps(\n props: RenderErrorBoundaryProps,\n state: RenderErrorBoundaryState\n ) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (\n state.location !== props.location ||\n (state.revalidation !== \"idle\" && props.revalidation === \"idle\")\n ) {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation,\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error || state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation,\n };\n }\n\n componentDidCatch(error: any, errorInfo: any) {\n console.error(\n \"React Router caught the following error during render\",\n error,\n errorInfo\n );\n }\n\n render() {\n return this.state.error ? (\n \n \n \n ) : (\n this.props.children\n );\n }\n}\n\ninterface RenderedRouteProps {\n routeContext: RouteContextObject;\n match: RouteMatch;\n children: React.ReactNode | null;\n}\n\nfunction RenderedRoute({ routeContext, match, children }: RenderedRouteProps) {\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (\n dataRouterContext &&\n dataRouterContext.static &&\n dataRouterContext.staticContext &&\n (match.route.errorElement || match.route.ErrorBoundary)\n ) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n\n return (\n \n {children}\n \n );\n}\n\nexport function _renderMatches(\n matches: RouteMatch[] | null,\n parentMatches: RouteMatch[] = [],\n dataRouterState: RemixRouter[\"state\"] | null = null\n): React.ReactElement | null {\n if (matches == null) {\n if (dataRouterState?.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches as DataRouteMatch[];\n } else {\n return null;\n }\n }\n\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = dataRouterState?.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(\n (m) => m.route.id && errors?.[m.route.id]\n );\n invariant(\n errorIndex >= 0,\n `Could not find a matching route for errors on route IDs: ${Object.keys(\n errors\n ).join(\",\")}`\n );\n renderedMatches = renderedMatches.slice(\n 0,\n Math.min(renderedMatches.length, errorIndex + 1)\n );\n }\n\n return renderedMatches.reduceRight((outlet, match, index) => {\n let error = match.route.id ? errors?.[match.route.id] : null;\n // Only data routers handle errors\n let errorElement: React.ReactNode | null = null;\n if (dataRouterState) {\n errorElement = match.route.errorElement || defaultErrorElement;\n }\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children: React.ReactNode;\n if (error) {\n children = errorElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `` in `` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = ;\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return (\n \n );\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState &&\n (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? (\n \n ) : (\n getChildren()\n );\n }, null as React.ReactElement | null);\n}\n\nenum DataRouterHook {\n UseBlocker = \"useBlocker\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n}\n\nenum DataRouterStateHook {\n UseBlocker = \"useBlocker\",\n UseLoaderData = \"useLoaderData\",\n UseActionData = \"useActionData\",\n UseRouteError = \"useRouteError\",\n UseNavigation = \"useNavigation\",\n UseRouteLoaderData = \"useRouteLoaderData\",\n UseMatches = \"useMatches\",\n UseRevalidator = \"useRevalidator\",\n UseNavigateStable = \"useNavigate\",\n UseRouteId = \"useRouteId\",\n}\n\nfunction getDataRouterConsoleError(\n hookName: DataRouterHook | DataRouterStateHook\n) {\n return `${hookName} must be used within a data router. See https://reactrouter.com/routers/picking-a-router.`;\n}\n\nfunction useDataRouterContext(hookName: DataRouterHook) {\n let ctx = React.useContext(DataRouterContext);\n invariant(ctx, getDataRouterConsoleError(hookName));\n return ctx;\n}\n\nfunction useDataRouterState(hookName: DataRouterStateHook) {\n let state = React.useContext(DataRouterStateContext);\n invariant(state, getDataRouterConsoleError(hookName));\n return state;\n}\n\nfunction useRouteContext(hookName: DataRouterStateHook) {\n let route = React.useContext(RouteContext);\n invariant(route, getDataRouterConsoleError(hookName));\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName: DataRouterStateHook) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n invariant(\n thisRoute.route.id,\n `${hookName} can only be used on routes that contain a unique \"id\"`\n );\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nexport function useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nexport function useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nexport function useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return {\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation,\n };\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nexport function useMatches() {\n let { matches, loaderData } = useDataRouterState(\n DataRouterStateHook.UseMatches\n );\n return React.useMemo(\n () =>\n matches.map((match) => {\n let { pathname, params } = match;\n // Note: This structure matches that created by createUseMatchesMatch\n // in the @remix-run/router , so if you change this please also change\n // that :) Eventually we'll DRY this up\n return {\n id: match.route.id,\n pathname,\n params,\n data: loaderData[match.route.id] as unknown,\n handle: match.route.handle as unknown,\n };\n }),\n [matches, loaderData]\n );\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nexport function useLoaderData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n\n if (state.errors && state.errors[routeId] != null) {\n console.error(\n `You cannot \\`useLoaderData\\` in an errorElement (routeId: ${routeId})`\n );\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nexport function useRouteLoaderData(routeId: string): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nexport function useActionData(): unknown {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n\n let route = React.useContext(RouteContext);\n invariant(route, `useActionData must be used inside a RouteContext`);\n\n return Object.values(state?.actionData || {})[0];\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nexport function useRouteError(): unknown {\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return state.errors?.[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor value\n */\nexport function useAsyncValue(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._data;\n}\n\n/**\n * Returns the error from the nearest ancestor value\n */\nexport function useAsyncError(): unknown {\n let value = React.useContext(AwaitContext);\n return value?._error;\n}\n\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nexport function useBlocker(shouldBlock: boolean | BlockerFunction): Blocker {\n let { router, basename } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback(\n (arg) => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let { currentLocation, nextLocation, historyAction } = arg;\n return shouldBlock({\n currentLocation: {\n ...currentLocation,\n pathname:\n stripBasename(currentLocation.pathname, basename) ||\n currentLocation.pathname,\n },\n nextLocation: {\n ...nextLocation,\n pathname:\n stripBasename(nextLocation.pathname, basename) ||\n nextLocation.pathname,\n },\n historyAction,\n });\n },\n [basename, shouldBlock]\n );\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey)\n ? state.blockers.get(blockerKey)!\n : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable(): NavigateFunction {\n let { router } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n\n let navigate: NavigateFunction = React.useCallback(\n (to: To | number, options: NavigateOptions = {}) => {\n warning(activeRef.current, navigateEffectWarning);\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, { fromRouteId: id, ...options });\n }\n },\n [router, id]\n );\n\n return navigate;\n}\n\nconst alreadyWarned: Record = {};\n\nfunction warningOnce(key: string, cond: boolean, message: string) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n warning(false, message);\n }\n}\n", "import * as React from \"react\";\nimport type {\n TrackedPromise,\n InitialEntry,\n Location,\n MemoryHistory,\n Router as RemixRouter,\n To,\n LazyRouteFunction,\n RelativeRoutingType,\n RouterState,\n} from \"@remix-run/router\";\nimport {\n Action as NavigationType,\n AbortedDeferredError,\n createMemoryHistory,\n UNSAFE_invariant as invariant,\n parsePath,\n resolveTo,\n stripBasename,\n UNSAFE_warning as warning,\n UNSAFE_getPathContributingMatches as getPathContributingMatches,\n} from \"@remix-run/router\";\n\nimport type {\n DataRouteObject,\n IndexRouteObject,\n RouteMatch,\n RouteObject,\n Navigator,\n NonIndexRouteObject,\n} from \"./context\";\nimport {\n LocationContext,\n NavigationContext,\n DataRouterContext,\n DataRouterStateContext,\n AwaitContext,\n RouteContext,\n} from \"./context\";\nimport {\n useAsyncValue,\n useInRouterContext,\n useNavigate,\n useOutlet,\n useRoutes,\n _renderMatches,\n useRoutesImpl,\n useLocation,\n} from \"./hooks\";\n\nexport interface FutureConfig {\n v7_startTransition: boolean;\n}\n\nexport interface RouterProviderProps {\n fallbackElement?: React.ReactNode;\n router: RemixRouter;\n future?: FutureConfig;\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nexport function RouterProvider({\n fallbackElement,\n router,\n future,\n}: RouterProviderProps): React.ReactElement {\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/)\n let [state, setStateImpl] = React.useState(router.state);\n let { v7_startTransition } = future || {};\n let setState = React.useCallback(\n (newState: RouterState) => {\n v7_startTransition && startTransitionImpl\n ? startTransitionImpl(() => setStateImpl(newState))\n : setStateImpl(newState);\n },\n [setStateImpl, v7_startTransition]\n );\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n\n let navigator = React.useMemo((): Navigator => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: (n) => router.navigate(n),\n push: (to, state, opts) =>\n router.navigate(to, {\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n replace: (to, state, opts) =>\n router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts?.preventScrollReset,\n }),\n };\n }, [router]);\n\n let basename = router.basename || \"/\";\n\n let dataRouterContext = React.useMemo(\n () => ({\n router,\n navigator,\n static: false,\n basename,\n }),\n [router, navigator, basename]\n );\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a