foundation-sdk 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/@aws-amplify/core/src/constants.ts","../../../node_modules/@aws-amplify/core/src/Logger/types.ts","../../../node_modules/@aws-amplify/core/src/Logger/ConsoleLogger.ts","../../../node_modules/@aws-amplify/core/src/errors/AmplifyError.ts","../../../node_modules/@aws-amplify/core/src/types/errors.ts","../../../node_modules/@aws-amplify/core/src/errors/createAssertionFunction.ts","../../../node_modules/@aws-amplify/core/src/Hub/index.ts","../../../node_modules/@aws-amplify/core/src/utils/globalHelpers/index.ts","../../../node_modules/@aws-amplify/core/src/utils/convert/base64/base64Decoder.ts","../../../node_modules/@aws-amplify/core/src/singleton/Auth/utils/errorHelpers.ts","../../../node_modules/@aws-amplify/core/src/singleton/Auth/utils/index.ts","../../../node_modules/@aws-amplify/core/src/utils/deepFreeze.ts","../../../node_modules/@aws-amplify/core/src/parseAWSExports.ts","../../../node_modules/@aws-amplify/core/src/singleton/constants.ts","../../../node_modules/uuid/dist/esm/stringify.js","../../../node_modules/uuid/dist/esm/rng.js","../../../node_modules/uuid/dist/esm/native.js","../../../node_modules/uuid/dist/esm/v4.js","../../../node_modules/uuid/dist/esm/index.js","../../../node_modules/@aws-amplify/core/src/parseAmplifyOutputs.ts","../../../node_modules/@aws-amplify/core/src/utils/parseAmplifyConfig.ts","../../../node_modules/tslib/tslib.es6.mjs","../../../node_modules/@aws-crypto/sha256-js/src/constants.ts","../../../node_modules/@aws-crypto/sha256-js/src/RawSha256.ts","../../../node_modules/@smithy/util-utf8/node_modules/@smithy/is-array-buffer/dist-es/index.js","../../../node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-es/index.js","../../../node_modules/@smithy/util-utf8/dist-es/fromUtf8.js","../../../node_modules/@smithy/util-utf8/dist-es/toUint8Array.js","../../../node_modules/@smithy/util-utf8/dist-es/toUtf8.js","../../../node_modules/@smithy/util-utf8/dist-es/index.js","../../../node_modules/@aws-crypto/util/src/convertToBuffer.ts","../../../node_modules/@aws-crypto/util/src/isEmptyData.ts","../../../node_modules/@aws-crypto/util/src/numToUint8.ts","../../../node_modules/@aws-crypto/util/src/uint32ArrayFrom.ts","../../../node_modules/@aws-crypto/util/src/index.ts","../../../node_modules/@aws-crypto/sha256-js/src/jsSha256.ts","../../../node_modules/@aws-crypto/sha256-js/src/index.ts","../../../node_modules/@smithy/util-hex-encoding/dist-es/index.js","../../../node_modules/@aws-amplify/core/src/Platform/types.ts","../../../node_modules/@aws-amplify/core/src/Platform/version.ts","../../../node_modules/@aws-amplify/core/src/Platform/detection/helpers.ts","../../../node_modules/@aws-amplify/core/src/Platform/detection/React.ts","../../../node_modules/@aws-amplify/core/src/Platform/detection/Vue.ts","../../../node_modules/@aws-amplify/core/src/Platform/detection/Svelte.ts","../../../node_modules/@aws-amplify/core/src/Platform/detection/Next.ts","../../../node_modules/@aws-amplify/core/src/Platform/detection/Nuxt.ts","../../../node_modules/@aws-amplify/core/src/Platform/detection/Angular.ts","../../../node_modules/@aws-amplify/core/src/Platform/detection/ReactNative.ts","../../../node_modules/@aws-amplify/core/src/Platform/detection/Expo.ts","../../../node_modules/@aws-amplify/core/src/Platform/detection/Web.ts","../../../node_modules/@aws-amplify/core/src/Platform/detection/index.ts","../../../node_modules/@aws-amplify/core/src/Platform/detectFramework.ts","../../../node_modules/@aws-amplify/core/src/Platform/customUserAgent.ts","../../../node_modules/@aws-amplify/core/src/Platform/index.ts","../../../node_modules/@aws-amplify/core/src/utils/isBrowser.ts","../../../node_modules/@aws-amplify/core/src/singleton/Auth/index.ts","../../../node_modules/@aws-amplify/core/src/singleton/Amplify.ts","../../../node_modules/@aws-amplify/core/src/singleton/apis/internal/fetchAuthSession.ts","../../../node_modules/@aws-amplify/core/src/singleton/apis/fetchAuthSession.ts","../../../node_modules/@aws-amplify/core/src/singleton/apis/clearCredentials.ts","../../../node_modules/@aws-amplify/core/src/clients/serde/responseInfo.ts","../../../node_modules/@aws-amplify/core/src/clients/serde/json.ts","../../../node_modules/@aws-amplify/core/src/clients/internal/composeServiceApi.ts","../../../node_modules/@aws-amplify/core/src/utils/retry/jitteredBackoff.ts","../../../node_modules/@aws-amplify/core/src/clients/middleware/retry/constants.ts","../../../node_modules/@aws-amplify/core/src/clients/middleware/retry/jitteredBackoff.ts","../../../node_modules/@aws-amplify/core/src/clients/middleware/retry/isClockSkewError.ts","../../../node_modules/@aws-amplify/core/src/clients/middleware/retry/defaultRetryDecider.ts","../../../node_modules/@aws-amplify/core/src/foundation/factories/serviceClients/cognitoIdentity/constants.ts","../../../node_modules/@aws-amplify/core/src/clients/middleware/retry/retryMiddleware.ts","../../../node_modules/@aws-amplify/core/src/utils/amplifyUuid/index.ts","../../../node_modules/@aws-amplify/core/src/clients/middleware/retry/amzSdkInvocationIdHeaderMiddleware.ts","../../../node_modules/@aws-amplify/core/src/clients/middleware/retry/amzSdkRequestHeaderMiddleware.ts","../../../node_modules/@aws-amplify/core/src/clients/middleware/userAgent/middleware.ts","../../../node_modules/@aws-amplify/core/src/clients/internal/composeTransferHandler.ts","../../../node_modules/@aws-amplify/core/src/clients/utils/memoization.ts","../../../node_modules/@aws-amplify/core/src/clients/handlers/fetch.ts","../../../node_modules/@aws-amplify/core/src/clients/handlers/aws/unauthenticated.ts","../../../node_modules/@aws-amplify/core/src/foundation/factories/middleware/createDisableCacheMiddleware.ts","../../../node_modules/@aws-amplify/core/src/foundation/factories/serviceClients/cognitoIdentity/handler/cognitoIdentityTransferHandler.ts","../../../node_modules/@aws-amplify/core/src/foundation/factories/serviceClients/cognitoIdentity/serde/createClientSerializer.ts","../../../node_modules/@aws-amplify/core/src/foundation/factories/serviceClients/cognitoIdentity/createGetCredentialsForIdentityClient.ts","../../../node_modules/@aws-amplify/core/src/foundation/factories/serviceClients/cognitoIdentity/createGetIdClient.ts","../../../node_modules/@aws-amplify/core/src/clients/endpoints/partitions.ts","../../../node_modules/@aws-amplify/core/src/clients/endpoints/getDnsSuffix.ts","../../../node_modules/@aws-amplify/core/src/utils/amplifyUrl/index.ts","../../../node_modules/@aws-amplify/core/src/foundation/factories/serviceClients/cognitoIdentity/cognitoIdentityPoolEndpointResolver.ts","../../../node_modules/@aws-amplify/core/src/errors/PlatformNotSupportedError.ts","../../../node_modules/@aws-amplify/core/src/storage/KeyValueStorage.ts","../../../node_modules/@aws-amplify/core/src/storage/InMemoryStorage.ts","../../../node_modules/@aws-amplify/core/src/storage/utils.ts","../../../node_modules/@aws-amplify/core/src/storage/DefaultStorage.ts","../../../node_modules/@aws-amplify/core/src/storage/SessionStorage.ts","../../../node_modules/@aws-amplify/core/src/storage/SyncKeyValueStorage.ts","../../../node_modules/@aws-amplify/core/src/storage/SyncSessionStorage.ts","../../../node_modules/js-cookie/dist/js.cookie.mjs","../../../node_modules/@aws-amplify/core/src/storage/CookieStorage.ts","../../../node_modules/@aws-amplify/core/src/storage/index.ts","../../../node_modules/@aws-amplify/core/src/Cache/constants.ts","../../../node_modules/@aws-amplify/core/src/Cache/utils/cacheHelpers.ts","../../../node_modules/@aws-amplify/core/src/Cache/utils/errorHelpers.ts","../../../node_modules/@aws-amplify/core/src/Cache/StorageCacheCommon.ts","../../../node_modules/@aws-amplify/core/src/Cache/StorageCache.ts","../../../node_modules/@aws-amplify/core/src/Cache/index.ts","../../../node_modules/@aws-amplify/core/src/I18n/I18n.ts","../../../node_modules/@aws-amplify/core/src/I18n/errorHelpers.ts","../../../node_modules/@aws-amplify/core/src/I18n/index.ts","../../../node_modules/@aws-amplify/core/dist/esm/index.mjs","../../../node_modules/@aws-amplify/core/src/utils/generateRandomString.ts","../../../node_modules/@aws-amplify/core/src/utils/urlSafeDecode.ts","../../../node_modules/@aws-amplify/core/src/utils/urlSafeEncode.ts","../../../node_modules/@aws-amplify/core/src/utils/deDupeAsyncFunction.ts","../../../node_modules/@aws-amplify/core/src/utils/isTokenExpired.ts","../../../node_modules/@aws-amplify/core/src/utils/deviceName/getDeviceName.ts","../../../node_modules/@aws-amplify/core/src/utils/convert/base64/bytesToString.ts","../../../node_modules/@aws-amplify/core/src/utils/convert/base64/base64Encoder.ts","../../../node_modules/@aws-amplify/core/src/utils/cryptoSecureRandomInt.ts","../../../node_modules/@aws-amplify/core/src/utils/WordArray.ts","../../../node_modules/@aws-amplify/core/dist/esm/libraryUtils.mjs","../../../node_modules/@aws-amplify/auth/src/errors/types/validation.ts","../../../node_modules/@aws-amplify/auth/src/common/AuthErrorStrings.ts","../../../node_modules/@aws-amplify/auth/src/errors/AuthError.ts","../../../node_modules/@aws-amplify/auth/src/errors/utils/assertValidationError.ts","../../../node_modules/@aws-amplify/auth/src/foundation/parsers/regionParsers.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/apiHelpers.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/types/errors.ts","../../../node_modules/@aws-amplify/auth/src/errors/constants.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/types.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/internal/getCurrentUser.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/getCurrentUser.ts","../../../node_modules/@aws-amplify/auth/src/utils/getAuthUserAgentValue.ts","../../../node_modules/@aws-amplify/core/dist/esm/clients/internal/index.mjs","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolSerializer.ts","../../../node_modules/@aws-amplify/core/dist/esm/clients/index.mjs","../../../node_modules/@aws-amplify/auth/src/errors/utils/assertServiceError.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolDeserializer.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.ts","../../../node_modules/@aws-amplify/auth/src/foundation/constants.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/constants.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.ts","../../../node_modules/@aws-amplify/auth/src/foundation/cognitoUserPoolEndpointResolver.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/factories/createCognitoUserPoolEndpointResolver.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetTokensFromRefreshTokenClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/refreshAuthTokens.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/types.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/errorHelpers.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/constants.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/TokenStore.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/signInWithRedirectStore.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/oAuthStore.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/inflightPromise.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/CognitoUserPoolsTokenProvider.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/tokenProvider.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/tokenProvider/cacheTokens.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/dispatchSignedInHubEvent.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/store/autoSignInStore.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/store/signInStore.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/passkey/errors/passkeyErrorPlatformConstants.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/passkey/errors/passkeyError.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/passkey/errors/handlePasskeyError.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/passkey/errors/handlePasskeyAuthenticationError.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/passkey/getIsPasskeySupported.ts","../../../node_modules/@aws-amplify/auth/src/foundation/convert/base64url/convertArrayBufferToBase64Url.ts","../../../node_modules/@aws-amplify/auth/src/foundation/convert/base64url/convertBase64UrlToArrayBuffer.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/passkey/serde.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/passkey/types/shared.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/passkey/types/index.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/passkey/getPasskey.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/textEncoder/index.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/BigInteger/BigInteger.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/calculate/calculateS.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/constants.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getBytesFromHex.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getHexFromBytes.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getHashFromData.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getHashFromHex.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getPaddedHex.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/calculate/calculateU.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getHkdfKey.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getRandomBytes.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getRandomString.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/AuthenticationHelper/AuthenticationHelper.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/calculate/calculateA.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getAuthenticationHelper.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/getNewDeviceMetadata.ts","../../../node_modules/@aws-amplify/auth/src/client/flows/userAuth/handleWebAuthnSignInResult.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/userContextData.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getNowString.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/srp/getSignatureString.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/handleDeviceSRPAuth.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/handlePasswordVerifierChallenge.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/retryOnResourceNotFoundException.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/setActiveSignInUsername.ts","../../../node_modules/@aws-amplify/auth/src/client/flows/shared/handlePasswordSRP.ts","../../../node_modules/@aws-amplify/auth/src/client/flows/userAuth/handleSelectChallenge.ts","../../../node_modules/@aws-amplify/auth/src/client/flows/userAuth/handleSelectChallengeWithPassword.ts","../../../node_modules/@aws-amplify/auth/src/client/flows/userAuth/handleSelectChallengeWithPasswordSRP.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/signInHelpers.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signInWithCustomAuth.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/autoSignIn.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signInWithSRP.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signInWithUserPassword.ts","../../../node_modules/@aws-amplify/auth/src/client/flows/userAuth/handleUserAuthFlow.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signInWithUserAuth.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signIn.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/signUpHelpers.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signUp.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/resetPassword.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/confirmResetPassword.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/resendSignUpCode.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/confirmSignUp.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/confirmSignIn.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createSetUserMFAPreferenceClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/updateMFAPreference.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/fetchMFAPreference.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/verifyTOTPSetup.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createChangePasswordClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/updatePassword.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/setUpTOTP.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateUserAttributesClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/updateUserAttributes.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/updateUserAttribute.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/confirmUserAttribute.ts","../../../node_modules/@aws-amplify/auth/src/Errors.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/createOAuthError.ts","../../../node_modules/@aws-amplify/auth/src/types/Auth.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/validateState.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/completeOAuthFlow.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/getRedirectUrl.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/handleFailure.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/enableOAuthListener.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/types/models.ts","../../../node_modules/@aws-amplify/auth/src/utils/openAuthSession.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/generateCodeVerifier.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/generateState.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/cancelOAuthFlow.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signInWithRedirect.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/fetchUserAttributes.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/completeOAuthSignOut.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/signOut.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserAttributesClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/deleteUserAttributes.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createEmptyResponseDeserializer.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteUserClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/deleteUser.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createUpdateDeviceStatusClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/rememberDevice.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createForgetDeviceClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/forgetDevice.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListDevicesClient.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/apis/fetchDevices.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/types.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/factories/createCognitoIdentityPoolEndpointResolver.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/utils.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts","../../../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/passkey/errors/handlePasskeyRegistrationError.ts","../../../node_modules/@aws-amplify/auth/src/client/utils/passkey/registerPasskey.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createStartWebAuthnRegistrationClient.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createCompleteWebAuthnRegistrationClient.ts","../../../node_modules/@aws-amplify/auth/src/client/apis/associateWebAuthnCredential.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createListWebAuthnCredentialsClient.ts","../../../node_modules/@aws-amplify/auth/src/foundation/apis/listWebAuthnCredentials.ts","../../../node_modules/@aws-amplify/auth/src/client/apis/listWebAuthnCredentials.ts","../../../node_modules/@aws-amplify/auth/src/foundation/factories/serviceClients/cognitoIdentityProvider/createDeleteWebAuthnCredentialClient.ts","../../../node_modules/@aws-amplify/auth/src/foundation/apis/deleteWebAuthnCredential.ts","../../../node_modules/@aws-amplify/auth/src/client/apis/deleteWebAuthnCredential.ts","../../../node_modules/@aws-amplify/auth/dist/esm/index.mjs","../../../node_modules/aws-amplify/dist/esm/auth/index.mjs","../../../node_modules/@aws-amplify/auth/src/providers/cognito/credentialsProvider/index.ts","../../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/index.mjs","../../../node_modules/aws-amplify/src/initSingleton.ts","../../../node_modules/aws-amplify/dist/esm/index.mjs","../src/index.ts","../src/http.ts","../src/auth.ts","../src/jwt.ts","../src/foundation.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Logging constants\nexport const AWS_CLOUDWATCH_CATEGORY = 'Logging';\nexport const USER_AGENT_HEADER = 'x-amz-user-agent';\n// Error exception code constants\nexport const NO_HUBCALLBACK_PROVIDED_EXCEPTION = 'NoHubcallbackProvidedException';\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport var LogType;\n(function (LogType) {\n LogType[\"DEBUG\"] = \"DEBUG\";\n LogType[\"ERROR\"] = \"ERROR\";\n LogType[\"INFO\"] = \"INFO\";\n LogType[\"WARN\"] = \"WARN\";\n LogType[\"VERBOSE\"] = \"VERBOSE\";\n LogType[\"NONE\"] = \"NONE\";\n})(LogType || (LogType = {}));\n","/* eslint-disable no-console */\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AWS_CLOUDWATCH_CATEGORY } from '../constants';\nimport { LogType } from './types';\nconst LOG_LEVELS = {\n VERBOSE: 1,\n DEBUG: 2,\n INFO: 3,\n WARN: 4,\n ERROR: 5,\n NONE: 6,\n};\n/**\n * Write logs\n * @class Logger\n */\nexport class ConsoleLogger {\n /**\n * @constructor\n * @param {string} name - Name of the logger\n */\n constructor(name, level = LogType.WARN) {\n this.name = name;\n this.level = level;\n this._pluggables = [];\n }\n _padding(n) {\n return n < 10 ? '0' + n : '' + n;\n }\n _ts() {\n const dt = new Date();\n return ([this._padding(dt.getMinutes()), this._padding(dt.getSeconds())].join(':') +\n '.' +\n dt.getMilliseconds());\n }\n configure(config) {\n if (!config)\n return this._config;\n this._config = config;\n return this._config;\n }\n /**\n * Write log\n * @method\n * @memeberof Logger\n * @param {LogType|string} type - log type, default INFO\n * @param {string|object} msg - Logging message or object\n */\n _log(type, ...msg) {\n let loggerLevelName = this.level;\n if (ConsoleLogger.LOG_LEVEL) {\n loggerLevelName = ConsoleLogger.LOG_LEVEL;\n }\n if (typeof window !== 'undefined' && window.LOG_LEVEL) {\n loggerLevelName = window.LOG_LEVEL;\n }\n const loggerLevel = LOG_LEVELS[loggerLevelName];\n const typeLevel = LOG_LEVELS[type];\n if (!(typeLevel >= loggerLevel)) {\n // Do nothing if type is not greater than or equal to logger level (handle undefined)\n return;\n }\n let log = console.log.bind(console);\n if (type === LogType.ERROR && console.error) {\n log = console.error.bind(console);\n }\n if (type === LogType.WARN && console.warn) {\n log = console.warn.bind(console);\n }\n if (ConsoleLogger.BIND_ALL_LOG_LEVELS) {\n if (type === LogType.INFO && console.info) {\n log = console.info.bind(console);\n }\n if (type === LogType.DEBUG && console.debug) {\n log = console.debug.bind(console);\n }\n }\n const prefix = `[${type}] ${this._ts()} ${this.name}`;\n let message = '';\n if (msg.length === 1 && typeof msg[0] === 'string') {\n message = `${prefix} - ${msg[0]}`;\n log(message);\n }\n else if (msg.length === 1) {\n message = `${prefix} ${msg[0]}`;\n log(prefix, msg[0]);\n }\n else if (typeof msg[0] === 'string') {\n let obj = msg.slice(1);\n if (obj.length === 1) {\n obj = obj[0];\n }\n message = `${prefix} - ${msg[0]} ${obj}`;\n log(`${prefix} - ${msg[0]}`, obj);\n }\n else {\n message = `${prefix} ${msg}`;\n log(prefix, msg);\n }\n for (const plugin of this._pluggables) {\n const logEvent = { message, timestamp: Date.now() };\n plugin.pushLogs([logEvent]);\n }\n }\n /**\n * Write General log. Default to INFO\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n log(...msg) {\n this._log(LogType.INFO, ...msg);\n }\n /**\n * Write INFO log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n info(...msg) {\n this._log(LogType.INFO, ...msg);\n }\n /**\n * Write WARN log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n warn(...msg) {\n this._log(LogType.WARN, ...msg);\n }\n /**\n * Write ERROR log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n error(...msg) {\n this._log(LogType.ERROR, ...msg);\n }\n /**\n * Write DEBUG log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n debug(...msg) {\n this._log(LogType.DEBUG, ...msg);\n }\n /**\n * Write VERBOSE log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n verbose(...msg) {\n this._log(LogType.VERBOSE, ...msg);\n }\n addPluggable(pluggable) {\n if (pluggable && pluggable.getCategoryName() === AWS_CLOUDWATCH_CATEGORY) {\n this._pluggables.push(pluggable);\n pluggable.configure(this._config);\n }\n }\n listPluggables() {\n return this._pluggables;\n }\n}\nConsoleLogger.LOG_LEVEL = null;\nConsoleLogger.BIND_ALL_LOG_LEVELS = false;\n","export class AmplifyError extends Error {\n /**\n * Constructs an AmplifyError.\n *\n * @param message text that describes the main problem.\n * @param underlyingError the underlying cause of the error.\n * @param recoverySuggestion suggestion to recover from the error.\n *\n */\n constructor({ message, name, recoverySuggestion, underlyingError, metadata, }) {\n super(message);\n this.name = name;\n this.underlyingError = underlyingError;\n this.recoverySuggestion = recoverySuggestion;\n if (metadata) {\n // If metadata exists, explicitly only record the following properties.\n const { extendedRequestId, httpStatusCode, requestId } = metadata;\n this.metadata = { extendedRequestId, httpStatusCode, requestId };\n }\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = AmplifyError;\n Object.setPrototypeOf(this, AmplifyError.prototype);\n }\n}\n","export var AmplifyErrorCode;\n(function (AmplifyErrorCode) {\n AmplifyErrorCode[\"NoEndpointId\"] = \"NoEndpointId\";\n AmplifyErrorCode[\"PlatformNotSupported\"] = \"PlatformNotSupported\";\n AmplifyErrorCode[\"Unknown\"] = \"Unknown\";\n AmplifyErrorCode[\"NetworkError\"] = \"NetworkError\";\n})(AmplifyErrorCode || (AmplifyErrorCode = {}));\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AmplifyError } from './AmplifyError';\nexport const createAssertionFunction = (errorMap, AssertionError = AmplifyError) => (assertion, name, additionalContext) => {\n const { message, recoverySuggestion } = errorMap[name];\n if (!assertion) {\n throw new AssertionError({\n name,\n message: additionalContext\n ? `${message} ${additionalContext}`\n : message,\n recoverySuggestion,\n });\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger } from '../Logger';\nimport { NO_HUBCALLBACK_PROVIDED_EXCEPTION } from '../constants';\nimport { AmplifyError } from '../errors';\nexport const AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined'\n ? Symbol('amplify_default')\n : '@@amplify_default');\nconst logger = new ConsoleLogger('Hub');\nexport class HubClass {\n constructor(name) {\n this.listeners = new Map();\n this.protectedChannels = [\n 'core',\n 'auth',\n 'api',\n 'analytics',\n 'interactions',\n 'pubsub',\n 'storage',\n 'ui',\n 'xr',\n ];\n this.name = name;\n }\n /**\n * Used internally to remove a Hub listener.\n *\n * @remarks\n * This private method is for internal use only. Instead of calling Hub.remove, call the result of Hub.listen.\n */\n _remove(channel, listener) {\n const holder = this.listeners.get(channel);\n if (!holder) {\n logger.warn(`No listeners for ${channel}`);\n return;\n }\n this.listeners.set(channel, [\n ...holder.filter(({ callback }) => callback !== listener),\n ]);\n }\n dispatch(channel, payload, source, ampSymbol) {\n if (typeof channel === 'string' &&\n this.protectedChannels.indexOf(channel) > -1) {\n const hasAccess = ampSymbol === AMPLIFY_SYMBOL;\n if (!hasAccess) {\n logger.warn(`WARNING: ${channel} is protected and dispatching on it can have unintended consequences`);\n }\n }\n const capsule = {\n channel,\n payload: { ...payload },\n source,\n patternInfo: [],\n };\n try {\n this._toListeners(capsule);\n }\n catch (e) {\n logger.error(e);\n }\n }\n listen(channel, callback, listenerName = 'noname') {\n let cb;\n if (typeof callback !== 'function') {\n throw new AmplifyError({\n name: NO_HUBCALLBACK_PROVIDED_EXCEPTION,\n message: 'No callback supplied to Hub',\n });\n }\n else {\n // Needs to be casted as a more generic type\n cb = callback;\n }\n let holder = this.listeners.get(channel);\n if (!holder) {\n holder = [];\n this.listeners.set(channel, holder);\n }\n holder.push({\n name: listenerName,\n callback: cb,\n });\n return () => {\n this._remove(channel, cb);\n };\n }\n _toListeners(capsule) {\n const { channel, payload } = capsule;\n const holder = this.listeners.get(channel);\n if (holder) {\n holder.forEach(listener => {\n logger.debug(`Dispatching to ${channel} with `, payload);\n try {\n listener.callback(capsule);\n }\n catch (e) {\n logger.error(e);\n }\n });\n }\n }\n}\n/* We export a __default__ instance of HubClass to use it as a\npseudo Singleton for the main messaging bus, however you can still create\nyour own instance of HubClass() for a separate \"private bus\" of events. */\nexport const Hub = new HubClass('__default__');\n/**\n * @internal\n *\n * Internal hub used for core Amplify functionality. Not intended for use outside of Amplify.\n *\n */\nexport const HubInternal = new HubClass('internal-hub');\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AmplifyError } from '../../errors';\nexport const getCrypto = () => {\n if (typeof window === 'object' && typeof window.crypto === 'object') {\n return window.crypto;\n }\n // Next.js global polyfill\n if (typeof crypto === 'object') {\n return crypto;\n }\n throw new AmplifyError({\n name: 'MissingPolyfill',\n message: 'Cannot resolve the `crypto` function from the environment.',\n });\n};\nexport const getBtoa = () => {\n // browser\n if (typeof window !== 'undefined' && typeof window.btoa === 'function') {\n return window.btoa;\n }\n // Next.js global polyfill\n if (typeof btoa === 'function') {\n return btoa;\n }\n throw new AmplifyError({\n name: 'Base64EncoderError',\n message: 'Cannot resolve the `btoa` function from the environment.',\n });\n};\nexport const getAtob = () => {\n // browser\n if (typeof window !== 'undefined' && typeof window.atob === 'function') {\n return window.atob;\n }\n // Next.js global polyfill\n if (typeof atob === 'function') {\n return atob;\n }\n throw new AmplifyError({\n name: 'Base64EncoderError',\n message: 'Cannot resolve the `atob` function from the environment.',\n });\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { getAtob } from '../../globalHelpers';\nexport const base64Decoder = {\n convert(input, options) {\n let inputStr = input;\n // urlSafe character replacement options conform to the base64 url spec\n // https://datatracker.ietf.org/doc/html/rfc4648#page-7\n if (options?.urlSafe) {\n inputStr = inputStr.replace(/-/g, '+').replace(/_/g, '/');\n }\n return getAtob()(inputStr);\n },\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { createAssertionFunction } from '../../../errors';\nexport var AuthConfigurationErrorCode;\n(function (AuthConfigurationErrorCode) {\n AuthConfigurationErrorCode[\"AuthTokenConfigException\"] = \"AuthTokenConfigException\";\n AuthConfigurationErrorCode[\"AuthUserPoolAndIdentityPoolException\"] = \"AuthUserPoolAndIdentityPoolException\";\n AuthConfigurationErrorCode[\"AuthUserPoolException\"] = \"AuthUserPoolException\";\n AuthConfigurationErrorCode[\"InvalidIdentityPoolIdException\"] = \"InvalidIdentityPoolIdException\";\n AuthConfigurationErrorCode[\"OAuthNotConfigureException\"] = \"OAuthNotConfigureException\";\n})(AuthConfigurationErrorCode || (AuthConfigurationErrorCode = {}));\nconst authConfigurationErrorMap = {\n [AuthConfigurationErrorCode.AuthTokenConfigException]: {\n message: 'Auth Token Provider not configured.',\n recoverySuggestion: 'Make sure to call Amplify.configure in your app.',\n },\n [AuthConfigurationErrorCode.AuthUserPoolAndIdentityPoolException]: {\n message: 'Auth UserPool or IdentityPool not configured.',\n recoverySuggestion: 'Make sure to call Amplify.configure in your app with UserPoolId and IdentityPoolId.',\n },\n [AuthConfigurationErrorCode.AuthUserPoolException]: {\n message: 'Auth UserPool not configured.',\n recoverySuggestion: 'Make sure to call Amplify.configure in your app with userPoolId and userPoolClientId.',\n },\n [AuthConfigurationErrorCode.InvalidIdentityPoolIdException]: {\n message: 'Invalid identity pool id provided.',\n recoverySuggestion: 'Make sure a valid identityPoolId is given in the config.',\n },\n [AuthConfigurationErrorCode.OAuthNotConfigureException]: {\n message: 'oauth param not configured.',\n recoverySuggestion: 'Make sure to call Amplify.configure with oauth parameter in your app.',\n },\n};\nexport const assert = createAssertionFunction(authConfigurationErrorMap);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { base64Decoder } from '../../../utils/convert';\nimport { AuthConfigurationErrorCode, assert } from './errorHelpers';\nexport function assertTokenProviderConfig(cognitoConfig) {\n let assertionValid = true; // assume valid until otherwise proveed\n if (!cognitoConfig) {\n assertionValid = false;\n }\n else {\n assertionValid =\n !!cognitoConfig.userPoolId && !!cognitoConfig.userPoolClientId;\n }\n assert(assertionValid, AuthConfigurationErrorCode.AuthUserPoolException);\n}\nexport function assertOAuthConfig(cognitoConfig) {\n const validOAuthConfig = !!cognitoConfig?.loginWith?.oauth?.domain &&\n !!cognitoConfig?.loginWith?.oauth?.redirectSignOut &&\n !!cognitoConfig?.loginWith?.oauth?.redirectSignIn &&\n !!cognitoConfig?.loginWith?.oauth?.responseType;\n assert(validOAuthConfig, AuthConfigurationErrorCode.OAuthNotConfigureException);\n}\nexport function assertIdentityPoolIdConfig(cognitoConfig) {\n const validConfig = !!cognitoConfig?.identityPoolId;\n assert(validConfig, AuthConfigurationErrorCode.InvalidIdentityPoolIdException);\n}\n/**\n * Decodes payload of JWT token\n *\n * @param {String} token A string representing a token to be decoded\n * @throws {@link Error} - Throws error when token is invalid or payload malformed.\n */\nexport function decodeJWT(token) {\n const tokenParts = token.split('.');\n if (tokenParts.length !== 3) {\n throw new Error('Invalid token');\n }\n try {\n const base64WithUrlSafe = tokenParts[1];\n const base64 = base64WithUrlSafe.replace(/-/g, '+').replace(/_/g, '/');\n const jsonStr = decodeURIComponent(base64Decoder\n .convert(base64)\n .split('')\n .map(char => `%${`00${char.charCodeAt(0).toString(16)}`.slice(-2)}`)\n .join(''));\n const payload = JSON.parse(jsonStr);\n return {\n toString: () => token,\n payload,\n };\n }\n catch (err) {\n throw new Error('Invalid token payload');\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const deepFreeze = (object) => {\n const propNames = Reflect.ownKeys(object);\n for (const name of propNames) {\n const value = object[name];\n if ((value && typeof value === 'object') || typeof value === 'function') {\n deepFreeze(value);\n }\n }\n return Object.freeze(object);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger } from './Logger';\nimport { AmplifyError } from './errors';\nconst logger = new ConsoleLogger('parseAWSExports');\nconst authTypeMapping = {\n API_KEY: 'apiKey',\n AWS_IAM: 'iam',\n AMAZON_COGNITO_USER_POOLS: 'userPool',\n OPENID_CONNECT: 'oidc',\n NONE: 'none',\n AWS_LAMBDA: 'lambda',\n // `LAMBDA` is an incorrect value that was added during the v6 rewrite.\n // Keeping it as a valid value until v7 to prevent breaking customers who might\n // be relying on it as a workaround.\n // ref: https://github.com/aws-amplify/amplify-js/pull/12922\n // TODO: @v7 remove next line\n LAMBDA: 'lambda',\n};\n/**\n * Converts the object imported from `aws-exports.js` or `amplifyconfiguration.json` files generated by\n * the Amplify CLI into an object that conforms to the {@link ResourcesConfig}.\n *\n * @param config A configuration object imported from `aws-exports.js` or `amplifyconfiguration.json`.\n *\n * @returns An object that conforms to the {@link ResourcesConfig} .\n */\nexport const parseAWSExports = (config = {}) => {\n if (!Object.prototype.hasOwnProperty.call(config, 'aws_project_region')) {\n throw new AmplifyError({\n name: 'InvalidParameterException',\n message: 'Invalid config parameter.',\n recoverySuggestion: 'Ensure passing the config object imported from `amplifyconfiguration.json`.',\n });\n }\n const { aws_appsync_apiKey, aws_appsync_authenticationType, aws_appsync_graphqlEndpoint, aws_appsync_region, aws_bots_config, aws_cognito_identity_pool_id, aws_cognito_sign_up_verification_method, aws_cognito_mfa_configuration, aws_cognito_mfa_types, aws_cognito_password_protection_settings, aws_cognito_verification_mechanisms, aws_cognito_signup_attributes, aws_cognito_social_providers, aws_cognito_username_attributes, aws_mandatory_sign_in, aws_mobile_analytics_app_id, aws_mobile_analytics_app_region, aws_user_files_s3_bucket, aws_user_files_s3_bucket_region, aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing, aws_user_pools_id, aws_user_pools_web_client_id, geo, oauth, predictions, aws_cloud_logic_custom, Notifications, modelIntrospection, } = config;\n const amplifyConfig = {};\n // Analytics\n if (aws_mobile_analytics_app_id) {\n amplifyConfig.Analytics = {\n Pinpoint: {\n appId: aws_mobile_analytics_app_id,\n region: aws_mobile_analytics_app_region,\n },\n };\n }\n // Notifications\n const { InAppMessaging, Push } = Notifications ?? {};\n if (InAppMessaging?.AWSPinpoint || Push?.AWSPinpoint) {\n if (InAppMessaging?.AWSPinpoint) {\n const { appId, region } = InAppMessaging.AWSPinpoint;\n amplifyConfig.Notifications = {\n InAppMessaging: {\n Pinpoint: {\n appId,\n region,\n },\n },\n };\n }\n if (Push?.AWSPinpoint) {\n const { appId, region } = Push.AWSPinpoint;\n amplifyConfig.Notifications = {\n ...amplifyConfig.Notifications,\n PushNotification: {\n Pinpoint: {\n appId,\n region,\n },\n },\n };\n }\n }\n // Interactions\n if (Array.isArray(aws_bots_config)) {\n amplifyConfig.Interactions = {\n LexV1: Object.fromEntries(aws_bots_config.map(bot => [bot.name, bot])),\n };\n }\n // API\n if (aws_appsync_graphqlEndpoint) {\n const defaultAuthMode = authTypeMapping[aws_appsync_authenticationType];\n if (!defaultAuthMode) {\n logger.debug(`Invalid authentication type ${aws_appsync_authenticationType}. Falling back to IAM.`);\n }\n amplifyConfig.API = {\n GraphQL: {\n endpoint: aws_appsync_graphqlEndpoint,\n apiKey: aws_appsync_apiKey,\n region: aws_appsync_region,\n defaultAuthMode: defaultAuthMode ?? 'iam',\n },\n };\n if (modelIntrospection) {\n amplifyConfig.API.GraphQL.modelIntrospection = modelIntrospection;\n }\n }\n // Auth\n const mfaConfig = aws_cognito_mfa_configuration\n ? {\n status: aws_cognito_mfa_configuration &&\n aws_cognito_mfa_configuration.toLowerCase(),\n totpEnabled: aws_cognito_mfa_types?.includes('TOTP') ?? false,\n smsEnabled: aws_cognito_mfa_types?.includes('SMS') ?? false,\n }\n : undefined;\n const passwordFormatConfig = aws_cognito_password_protection_settings\n ? {\n minLength: aws_cognito_password_protection_settings.passwordPolicyMinLength,\n requireLowercase: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_LOWERCASE') ?? false,\n requireUppercase: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_UPPERCASE') ?? false,\n requireNumbers: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_NUMBERS') ?? false,\n requireSpecialCharacters: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_SYMBOLS') ?? false,\n }\n : undefined;\n const mergedUserAttributes = Array.from(new Set([\n ...(aws_cognito_verification_mechanisms ?? []),\n ...(aws_cognito_signup_attributes ?? []),\n ]));\n const userAttributes = mergedUserAttributes.reduce((attributes, key) => ({\n ...attributes,\n // All user attributes generated by the CLI are required\n [key.toLowerCase()]: { required: true },\n }), {});\n const loginWithEmailEnabled = aws_cognito_username_attributes?.includes('EMAIL') ?? false;\n const loginWithPhoneEnabled = aws_cognito_username_attributes?.includes('PHONE_NUMBER') ?? false;\n if (aws_cognito_identity_pool_id || aws_user_pools_id) {\n amplifyConfig.Auth = {\n Cognito: {\n identityPoolId: aws_cognito_identity_pool_id,\n allowGuestAccess: aws_mandatory_sign_in !== 'enable',\n signUpVerificationMethod: aws_cognito_sign_up_verification_method,\n userAttributes,\n userPoolClientId: aws_user_pools_web_client_id,\n userPoolId: aws_user_pools_id,\n mfa: mfaConfig,\n passwordFormat: passwordFormatConfig,\n loginWith: {\n username: !(loginWithEmailEnabled || loginWithPhoneEnabled),\n email: loginWithEmailEnabled,\n phone: loginWithPhoneEnabled,\n },\n },\n };\n }\n const hasOAuthConfig = oauth ? Object.keys(oauth).length > 0 : false;\n const hasSocialProviderConfig = aws_cognito_social_providers\n ? aws_cognito_social_providers.length > 0\n : false;\n if (amplifyConfig.Auth && hasOAuthConfig) {\n amplifyConfig.Auth.Cognito.loginWith = {\n ...amplifyConfig.Auth.Cognito.loginWith,\n oauth: {\n ...getOAuthConfig(oauth),\n ...(hasSocialProviderConfig && {\n providers: parseSocialProviders(aws_cognito_social_providers),\n }),\n },\n };\n }\n // Storage\n if (aws_user_files_s3_bucket) {\n amplifyConfig.Storage = {\n S3: {\n bucket: aws_user_files_s3_bucket,\n region: aws_user_files_s3_bucket_region,\n dangerouslyConnectToHttpEndpointForTesting: aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing,\n },\n };\n }\n // Geo\n if (geo) {\n const { amazon_location_service } = geo;\n amplifyConfig.Geo = {\n LocationService: {\n maps: amazon_location_service.maps,\n geofenceCollections: amazon_location_service.geofenceCollections,\n searchIndices: amazon_location_service.search_indices,\n region: amazon_location_service.region,\n },\n };\n }\n // REST API\n if (aws_cloud_logic_custom) {\n amplifyConfig.API = {\n ...amplifyConfig.API,\n REST: aws_cloud_logic_custom.reduce((acc, api) => {\n const { name, endpoint, region, service } = api;\n return {\n ...acc,\n [name]: {\n endpoint,\n ...(service ? { service } : undefined),\n ...(region ? { region } : undefined),\n },\n };\n }, {}),\n };\n }\n // Predictions\n if (predictions) {\n // map VoiceId from speechGenerator defaults to voiceId\n const { VoiceId: voiceId } = predictions?.convert?.speechGenerator?.defaults ?? {};\n amplifyConfig.Predictions = voiceId\n ? {\n ...predictions,\n convert: {\n ...predictions.convert,\n speechGenerator: {\n ...predictions.convert.speechGenerator,\n defaults: { voiceId },\n },\n },\n }\n : predictions;\n }\n return amplifyConfig;\n};\nconst getRedirectUrl = (redirectStr) => redirectStr?.split(',') ?? [];\nconst getOAuthConfig = ({ domain, scope, redirectSignIn, redirectSignOut, responseType, }) => ({\n domain,\n scopes: scope,\n redirectSignIn: getRedirectUrl(redirectSignIn),\n redirectSignOut: getRedirectUrl(redirectSignOut),\n responseType,\n});\nconst parseSocialProviders = (aws_cognito_social_providers) => {\n return aws_cognito_social_providers.map((provider) => {\n const updatedProvider = provider.toLowerCase();\n return updatedProvider.charAt(0).toUpperCase() + updatedProvider.slice(1);\n });\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const ADD_OAUTH_LISTENER = Symbol('oauth-listener');\n","import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;\n","import { randomFillSync } from 'crypto';\nconst rnds8Pool = new Uint8Array(256);\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, (poolPtr += 16));\n}\n","import { randomUUID } from 'crypto';\nexport default { randomUUID };\n","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n const rnds = options.random ?? options.rng?.() ?? rng();\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16');\n }\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n }\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;\n","export { default as MAX } from './max.js';\nexport { default as NIL } from './nil.js';\nexport { default as parse } from './parse.js';\nexport { default as stringify } from './stringify.js';\nexport { default as v1 } from './v1.js';\nexport { default as v1ToV6 } from './v1ToV6.js';\nexport { default as v3 } from './v3.js';\nexport { default as v4 } from './v4.js';\nexport { default as v5 } from './v5.js';\nexport { default as v6 } from './v6.js';\nexport { default as v6ToV1 } from './v6ToV1.js';\nexport { default as v7 } from './v7.js';\nexport { default as validate } from './validate.js';\nexport { default as version } from './version.js';\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport function isAmplifyOutputs(config) {\n // version format initially will be '1' but is expected to be something like x.y where x is major and y minor version\n const { version } = config;\n if (!version) {\n return false;\n }\n return version.startsWith('1');\n}\nfunction parseStorage(amplifyOutputsStorageProperties) {\n if (!amplifyOutputsStorageProperties) {\n return undefined;\n }\n const { bucket_name, aws_region, buckets } = amplifyOutputsStorageProperties;\n return {\n S3: {\n bucket: bucket_name,\n region: aws_region,\n buckets: buckets && createBucketInfoMap(buckets),\n },\n };\n}\nfunction parseAuth(amplifyOutputsAuthProperties) {\n if (!amplifyOutputsAuthProperties) {\n return undefined;\n }\n const { user_pool_id, user_pool_client_id, identity_pool_id, password_policy, mfa_configuration, mfa_methods, unauthenticated_identities_enabled, oauth, username_attributes, standard_required_attributes, groups, } = amplifyOutputsAuthProperties;\n const authConfig = {\n Cognito: {\n userPoolId: user_pool_id,\n userPoolClientId: user_pool_client_id,\n groups,\n },\n };\n if (identity_pool_id) {\n authConfig.Cognito = {\n ...authConfig.Cognito,\n identityPoolId: identity_pool_id,\n };\n }\n if (password_policy) {\n authConfig.Cognito.passwordFormat = {\n requireLowercase: password_policy.require_lowercase,\n requireNumbers: password_policy.require_numbers,\n requireUppercase: password_policy.require_uppercase,\n requireSpecialCharacters: password_policy.require_symbols,\n minLength: password_policy.min_length ?? 6,\n };\n }\n if (mfa_configuration) {\n authConfig.Cognito.mfa = {\n status: getMfaStatus(mfa_configuration),\n smsEnabled: mfa_methods?.includes('SMS'),\n totpEnabled: mfa_methods?.includes('TOTP'),\n };\n }\n if (unauthenticated_identities_enabled) {\n authConfig.Cognito.allowGuestAccess = unauthenticated_identities_enabled;\n }\n if (oauth) {\n authConfig.Cognito.loginWith = {\n oauth: {\n domain: oauth.domain,\n redirectSignIn: oauth.redirect_sign_in_uri,\n redirectSignOut: oauth.redirect_sign_out_uri,\n responseType: oauth.response_type === 'token' ? 'token' : 'code',\n scopes: oauth.scopes,\n providers: getOAuthProviders(oauth.identity_providers),\n },\n };\n }\n if (username_attributes) {\n authConfig.Cognito.loginWith = {\n ...authConfig.Cognito.loginWith,\n email: username_attributes.includes('email'),\n phone: username_attributes.includes('phone_number'),\n // Signing in with a username is not currently supported in Gen2, this should always evaluate to false\n username: username_attributes.includes('username'),\n };\n }\n if (standard_required_attributes) {\n authConfig.Cognito.userAttributes = standard_required_attributes.reduce((acc, curr) => ({ ...acc, [curr]: { required: true } }), {});\n }\n return authConfig;\n}\nexport function parseAnalytics(amplifyOutputsAnalyticsProperties) {\n if (!amplifyOutputsAnalyticsProperties?.amazon_pinpoint) {\n return undefined;\n }\n const { amazon_pinpoint } = amplifyOutputsAnalyticsProperties;\n return {\n Pinpoint: {\n appId: amazon_pinpoint.app_id,\n region: amazon_pinpoint.aws_region,\n },\n };\n}\nfunction parseGeo(amplifyOutputsAnalyticsProperties) {\n if (!amplifyOutputsAnalyticsProperties) {\n return undefined;\n }\n const { aws_region, geofence_collections, maps, search_indices } = amplifyOutputsAnalyticsProperties;\n return {\n LocationService: {\n region: aws_region,\n searchIndices: search_indices,\n geofenceCollections: geofence_collections,\n maps,\n },\n };\n}\nfunction parseData(amplifyOutputsDataProperties) {\n if (!amplifyOutputsDataProperties) {\n return undefined;\n }\n const { aws_region, default_authorization_type, url, api_key, model_introspection, } = amplifyOutputsDataProperties;\n const GraphQL = {\n endpoint: url,\n defaultAuthMode: getGraphQLAuthMode(default_authorization_type),\n region: aws_region,\n apiKey: api_key,\n modelIntrospection: model_introspection,\n };\n return {\n GraphQL,\n };\n}\nfunction parseCustom(amplifyOutputsCustomProperties) {\n if (!amplifyOutputsCustomProperties?.events) {\n return undefined;\n }\n const { url, aws_region, api_key, default_authorization_type } = amplifyOutputsCustomProperties.events;\n const Events = {\n endpoint: url,\n defaultAuthMode: getGraphQLAuthMode(default_authorization_type),\n region: aws_region,\n apiKey: api_key,\n };\n return {\n Events,\n };\n}\nfunction parseNotifications(amplifyOutputsNotificationsProperties) {\n if (!amplifyOutputsNotificationsProperties) {\n return undefined;\n }\n const { aws_region, channels, amazon_pinpoint_app_id } = amplifyOutputsNotificationsProperties;\n const hasInAppMessaging = channels.includes('IN_APP_MESSAGING');\n const hasPushNotification = channels.includes('APNS') || channels.includes('FCM');\n if (!(hasInAppMessaging || hasPushNotification)) {\n return undefined;\n }\n // At this point, we know the Amplify outputs contains at least one supported channel\n const notificationsConfig = {};\n if (hasInAppMessaging) {\n notificationsConfig.InAppMessaging = {\n Pinpoint: {\n appId: amazon_pinpoint_app_id,\n region: aws_region,\n },\n };\n }\n if (hasPushNotification) {\n notificationsConfig.PushNotification = {\n Pinpoint: {\n appId: amazon_pinpoint_app_id,\n region: aws_region,\n },\n };\n }\n return notificationsConfig;\n}\nexport function parseAmplifyOutputs(amplifyOutputs) {\n const resourcesConfig = {};\n if (amplifyOutputs.storage) {\n resourcesConfig.Storage = parseStorage(amplifyOutputs.storage);\n }\n if (amplifyOutputs.auth) {\n resourcesConfig.Auth = parseAuth(amplifyOutputs.auth);\n }\n if (amplifyOutputs.analytics) {\n resourcesConfig.Analytics = parseAnalytics(amplifyOutputs.analytics);\n }\n if (amplifyOutputs.geo) {\n resourcesConfig.Geo = parseGeo(amplifyOutputs.geo);\n }\n if (amplifyOutputs.data) {\n resourcesConfig.API = parseData(amplifyOutputs.data);\n }\n if (amplifyOutputs.custom) {\n const customConfig = parseCustom(amplifyOutputs.custom);\n if (customConfig && 'Events' in customConfig) {\n resourcesConfig.API = { ...resourcesConfig.API, ...customConfig };\n }\n }\n if (amplifyOutputs.notifications) {\n resourcesConfig.Notifications = parseNotifications(amplifyOutputs.notifications);\n }\n return resourcesConfig;\n}\nconst authModeNames = {\n AMAZON_COGNITO_USER_POOLS: 'userPool',\n API_KEY: 'apiKey',\n AWS_IAM: 'iam',\n AWS_LAMBDA: 'lambda',\n OPENID_CONNECT: 'oidc',\n};\nfunction getGraphQLAuthMode(authType) {\n return authModeNames[authType];\n}\nconst providerNames = {\n GOOGLE: 'Google',\n LOGIN_WITH_AMAZON: 'Amazon',\n FACEBOOK: 'Facebook',\n SIGN_IN_WITH_APPLE: 'Apple',\n};\nfunction getOAuthProviders(providers = []) {\n return providers.reduce((oAuthProviders, provider) => {\n if (providerNames[provider] !== undefined) {\n oAuthProviders.push(providerNames[provider]);\n }\n return oAuthProviders;\n }, []);\n}\nfunction getMfaStatus(mfaConfiguration) {\n if (mfaConfiguration === 'OPTIONAL')\n return 'optional';\n if (mfaConfiguration === 'REQUIRED')\n return 'on';\n return 'off';\n}\nfunction createBucketInfoMap(buckets) {\n const mappedBuckets = {};\n buckets.forEach(({ name, bucket_name: bucketName, aws_region: region, paths }) => {\n if (name in mappedBuckets) {\n throw new Error(`Duplicate friendly name found: ${name}. Name must be unique.`);\n }\n const sanitizedPaths = paths\n ? Object.entries(paths).reduce((acc, [key, value]) => {\n if (value !== undefined) {\n acc[key] = value;\n }\n return acc;\n }, {})\n : undefined;\n mappedBuckets[name] = {\n bucketName,\n region,\n paths: sanitizedPaths,\n };\n });\n return mappedBuckets;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { parseAWSExports } from '../parseAWSExports';\nimport { isAmplifyOutputs, parseAmplifyOutputs } from '../parseAmplifyOutputs';\n/**\n * Parses the variety of configuration shapes that Amplify can accept into a ResourcesConfig.\n *\n * @param amplifyConfig An Amplify configuration object conforming to one of the supported schemas.\n * @return A ResourcesConfig for the provided configuration object.\n */\nexport const parseAmplifyConfig = (amplifyConfig) => {\n if (Object.keys(amplifyConfig).some(key => key.startsWith('aws_'))) {\n return parseAWSExports(amplifyConfig);\n }\n else if (isAmplifyOutputs(amplifyConfig)) {\n return parseAmplifyOutputs(amplifyConfig);\n }\n else {\n return amplifyConfig;\n }\n};\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n","/**\n * @internal\n */\nexport const BLOCK_SIZE: number = 64;\n\n/**\n * @internal\n */\nexport const DIGEST_LENGTH: number = 32;\n\n/**\n * @internal\n */\nexport const KEY = new Uint32Array([\n 0x428a2f98,\n 0x71374491,\n 0xb5c0fbcf,\n 0xe9b5dba5,\n 0x3956c25b,\n 0x59f111f1,\n 0x923f82a4,\n 0xab1c5ed5,\n 0xd807aa98,\n 0x12835b01,\n 0x243185be,\n 0x550c7dc3,\n 0x72be5d74,\n 0x80deb1fe,\n 0x9bdc06a7,\n 0xc19bf174,\n 0xe49b69c1,\n 0xefbe4786,\n 0x0fc19dc6,\n 0x240ca1cc,\n 0x2de92c6f,\n 0x4a7484aa,\n 0x5cb0a9dc,\n 0x76f988da,\n 0x983e5152,\n 0xa831c66d,\n 0xb00327c8,\n 0xbf597fc7,\n 0xc6e00bf3,\n 0xd5a79147,\n 0x06ca6351,\n 0x14292967,\n 0x27b70a85,\n 0x2e1b2138,\n 0x4d2c6dfc,\n 0x53380d13,\n 0x650a7354,\n 0x766a0abb,\n 0x81c2c92e,\n 0x92722c85,\n 0xa2bfe8a1,\n 0xa81a664b,\n 0xc24b8b70,\n 0xc76c51a3,\n 0xd192e819,\n 0xd6990624,\n 0xf40e3585,\n 0x106aa070,\n 0x19a4c116,\n 0x1e376c08,\n 0x2748774c,\n 0x34b0bcb5,\n 0x391c0cb3,\n 0x4ed8aa4a,\n 0x5b9cca4f,\n 0x682e6ff3,\n 0x748f82ee,\n 0x78a5636f,\n 0x84c87814,\n 0x8cc70208,\n 0x90befffa,\n 0xa4506ceb,\n 0xbef9a3f7,\n 0xc67178f2\n]);\n\n/**\n * @internal\n */\nexport const INIT = [\n 0x6a09e667,\n 0xbb67ae85,\n 0x3c6ef372,\n 0xa54ff53a,\n 0x510e527f,\n 0x9b05688c,\n 0x1f83d9ab,\n 0x5be0cd19\n];\n\n/**\n * @internal\n */\nexport const MAX_HASHABLE_LENGTH = 2 ** 53 - 1;\n","import {\n BLOCK_SIZE,\n DIGEST_LENGTH,\n INIT,\n KEY,\n MAX_HASHABLE_LENGTH\n} from \"./constants\";\n\n/**\n * @internal\n */\nexport class RawSha256 {\n private state: Int32Array = Int32Array.from(INIT);\n private temp: Int32Array = new Int32Array(64);\n private buffer: Uint8Array = new Uint8Array(64);\n private bufferLength: number = 0;\n private bytesHashed: number = 0;\n\n /**\n * @internal\n */\n finished: boolean = false;\n\n update(data: Uint8Array): void {\n if (this.finished) {\n throw new Error(\"Attempted to update an already finished hash.\");\n }\n\n let position = 0;\n let { byteLength } = data;\n this.bytesHashed += byteLength;\n\n if (this.bytesHashed * 8 > MAX_HASHABLE_LENGTH) {\n throw new Error(\"Cannot hash more than 2^53 - 1 bits\");\n }\n\n while (byteLength > 0) {\n this.buffer[this.bufferLength++] = data[position++];\n byteLength--;\n\n if (this.bufferLength === BLOCK_SIZE) {\n this.hashBuffer();\n this.bufferLength = 0;\n }\n }\n }\n\n digest(): Uint8Array {\n if (!this.finished) {\n const bitsHashed = this.bytesHashed * 8;\n const bufferView = new DataView(\n this.buffer.buffer,\n this.buffer.byteOffset,\n this.buffer.byteLength\n );\n\n const undecoratedLength = this.bufferLength;\n bufferView.setUint8(this.bufferLength++, 0x80);\n\n // Ensure the final block has enough room for the hashed length\n if (undecoratedLength % BLOCK_SIZE >= BLOCK_SIZE - 8) {\n for (let i = this.bufferLength; i < BLOCK_SIZE; i++) {\n bufferView.setUint8(i, 0);\n }\n this.hashBuffer();\n this.bufferLength = 0;\n }\n\n for (let i = this.bufferLength; i < BLOCK_SIZE - 8; i++) {\n bufferView.setUint8(i, 0);\n }\n bufferView.setUint32(\n BLOCK_SIZE - 8,\n Math.floor(bitsHashed / 0x100000000),\n true\n );\n bufferView.setUint32(BLOCK_SIZE - 4, bitsHashed);\n\n this.hashBuffer();\n\n this.finished = true;\n }\n\n // The value in state is little-endian rather than big-endian, so flip\n // each word into a new Uint8Array\n const out = new Uint8Array(DIGEST_LENGTH);\n for (let i = 0; i < 8; i++) {\n out[i * 4] = (this.state[i] >>> 24) & 0xff;\n out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff;\n out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff;\n out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff;\n }\n\n return out;\n }\n\n private hashBuffer(): void {\n const { buffer, state } = this;\n\n let state0 = state[0],\n state1 = state[1],\n state2 = state[2],\n state3 = state[3],\n state4 = state[4],\n state5 = state[5],\n state6 = state[6],\n state7 = state[7];\n\n for (let i = 0; i < BLOCK_SIZE; i++) {\n if (i < 16) {\n this.temp[i] =\n ((buffer[i * 4] & 0xff) << 24) |\n ((buffer[i * 4 + 1] & 0xff) << 16) |\n ((buffer[i * 4 + 2] & 0xff) << 8) |\n (buffer[i * 4 + 3] & 0xff);\n } else {\n let u = this.temp[i - 2];\n const t1 =\n ((u >>> 17) | (u << 15)) ^ ((u >>> 19) | (u << 13)) ^ (u >>> 10);\n\n u = this.temp[i - 15];\n const t2 =\n ((u >>> 7) | (u << 25)) ^ ((u >>> 18) | (u << 14)) ^ (u >>> 3);\n\n this.temp[i] =\n ((t1 + this.temp[i - 7]) | 0) + ((t2 + this.temp[i - 16]) | 0);\n }\n\n const t1 =\n ((((((state4 >>> 6) | (state4 << 26)) ^\n ((state4 >>> 11) | (state4 << 21)) ^\n ((state4 >>> 25) | (state4 << 7))) +\n ((state4 & state5) ^ (~state4 & state6))) |\n 0) +\n ((state7 + ((KEY[i] + this.temp[i]) | 0)) | 0)) |\n 0;\n\n const t2 =\n ((((state0 >>> 2) | (state0 << 30)) ^\n ((state0 >>> 13) | (state0 << 19)) ^\n ((state0 >>> 22) | (state0 << 10))) +\n ((state0 & state1) ^ (state0 & state2) ^ (state1 & state2))) |\n 0;\n\n state7 = state6;\n state6 = state5;\n state5 = state4;\n state4 = (state3 + t1) | 0;\n state3 = state2;\n state2 = state1;\n state1 = state0;\n state0 = (t1 + t2) | 0;\n }\n\n state[0] += state0;\n state[1] += state1;\n state[2] += state2;\n state[3] += state3;\n state[4] += state4;\n state[5] += state5;\n state[6] += state6;\n state[7] += state7;\n }\n}\n","export const isArrayBuffer = (arg) => (typeof ArrayBuffer === \"function\" && arg instanceof ArrayBuffer) ||\n Object.prototype.toString.call(arg) === \"[object ArrayBuffer]\";\n","import { isArrayBuffer } from \"@smithy/is-array-buffer\";\nimport { Buffer } from \"buffer\";\nexport const fromArrayBuffer = (input, offset = 0, length = input.byteLength - offset) => {\n if (!isArrayBuffer(input)) {\n throw new TypeError(`The \"input\" argument must be ArrayBuffer. Received type ${typeof input} (${input})`);\n }\n return Buffer.from(input, offset, length);\n};\nexport const fromString = (input, encoding) => {\n if (typeof input !== \"string\") {\n throw new TypeError(`The \"input\" argument must be of type string. Received type ${typeof input} (${input})`);\n }\n return encoding ? Buffer.from(input, encoding) : Buffer.from(input);\n};\n","import { fromString } from \"@smithy/util-buffer-from\";\nexport const fromUtf8 = (input) => {\n const buf = fromString(input, \"utf8\");\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT);\n};\n","import { fromUtf8 } from \"./fromUtf8\";\nexport const toUint8Array = (data) => {\n if (typeof data === \"string\") {\n return fromUtf8(data);\n }\n if (ArrayBuffer.isView(data)) {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);\n }\n return new Uint8Array(data);\n};\n","import { fromArrayBuffer } from \"@smithy/util-buffer-from\";\nexport const toUtf8 = (input) => fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString(\"utf8\");\n","export * from \"./fromUtf8\";\nexport * from \"./toUint8Array\";\nexport * from \"./toUtf8\";\n","// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { SourceData } from \"@aws-sdk/types\";\nimport { fromUtf8 as fromUtf8Browser } from \"@smithy/util-utf8\";\n\n// Quick polyfill\nconst fromUtf8 =\n typeof Buffer !== \"undefined\" && Buffer.from\n ? (input: string) => Buffer.from(input, \"utf8\")\n : fromUtf8Browser;\n\nexport function convertToBuffer(data: SourceData): Uint8Array {\n // Already a Uint8, do nothing\n if (data instanceof Uint8Array) return data;\n\n if (typeof data === \"string\") {\n return fromUtf8(data);\n }\n\n if (ArrayBuffer.isView(data)) {\n return new Uint8Array(\n data.buffer,\n data.byteOffset,\n data.byteLength / Uint8Array.BYTES_PER_ELEMENT\n );\n }\n\n return new Uint8Array(data);\n}\n","// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { SourceData } from \"@aws-sdk/types\";\n\nexport function isEmptyData(data: SourceData): boolean {\n if (typeof data === \"string\") {\n return data.length === 0;\n }\n\n return data.byteLength === 0;\n}\n","// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nexport function numToUint8(num: number) {\n return new Uint8Array([\n (num & 0xff000000) >> 24,\n (num & 0x00ff0000) >> 16,\n (num & 0x0000ff00) >> 8,\n num & 0x000000ff,\n ]);\n}\n","// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n\n// IE 11 does not support Array.from, so we do it manually\nexport function uint32ArrayFrom(a_lookUpTable: Array<number>): Uint32Array {\n if (!Uint32Array.from) {\n const return_array = new Uint32Array(a_lookUpTable.length)\n let a_index = 0\n while (a_index < a_lookUpTable.length) {\n return_array[a_index] = a_lookUpTable[a_index]\n a_index += 1\n }\n return return_array\n }\n return Uint32Array.from(a_lookUpTable)\n}\n","// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nexport { convertToBuffer } from \"./convertToBuffer\";\nexport { isEmptyData } from \"./isEmptyData\";\nexport { numToUint8 } from \"./numToUint8\";\nexport {uint32ArrayFrom} from './uint32ArrayFrom';\n","import { BLOCK_SIZE } from \"./constants\";\nimport { RawSha256 } from \"./RawSha256\";\nimport { Checksum, SourceData } from \"@aws-sdk/types\";\nimport { isEmptyData, convertToBuffer } from \"@aws-crypto/util\";\n\nexport class Sha256 implements Checksum {\n private readonly secret?: SourceData;\n private hash: RawSha256;\n private outer?: RawSha256;\n private error: any;\n\n constructor(secret?: SourceData) {\n this.secret = secret;\n this.hash = new RawSha256();\n this.reset();\n }\n\n update(toHash: SourceData): void {\n if (isEmptyData(toHash) || this.error) {\n return;\n }\n\n try {\n this.hash.update(convertToBuffer(toHash));\n } catch (e) {\n this.error = e;\n }\n }\n\n /* This synchronous method keeps compatibility\n * with the v2 aws-sdk.\n */\n digestSync(): Uint8Array {\n if (this.error) {\n throw this.error;\n }\n\n if (this.outer) {\n if (!this.outer.finished) {\n this.outer.update(this.hash.digest());\n }\n\n return this.outer.digest();\n }\n\n return this.hash.digest();\n }\n\n /* The underlying digest method here is synchronous.\n * To keep the same interface with the other hash functions\n * the default is to expose this as an async method.\n * However, it can sometimes be useful to have a sync method.\n */\n async digest(): Promise<Uint8Array> {\n return this.digestSync();\n }\n\n reset(): void {\n this.hash = new RawSha256();\n if (this.secret) {\n this.outer = new RawSha256();\n const inner = bufferFromSecret(this.secret);\n const outer = new Uint8Array(BLOCK_SIZE);\n outer.set(inner);\n\n for (let i = 0; i < BLOCK_SIZE; i++) {\n inner[i] ^= 0x36;\n outer[i] ^= 0x5c;\n }\n\n this.hash.update(inner);\n this.outer.update(outer);\n\n // overwrite the copied key in memory\n for (let i = 0; i < inner.byteLength; i++) {\n inner[i] = 0;\n }\n }\n }\n}\n\nfunction bufferFromSecret(secret: SourceData): Uint8Array {\n let input = convertToBuffer(secret);\n\n if (input.byteLength > BLOCK_SIZE) {\n const bufferHash = new RawSha256();\n bufferHash.update(input);\n input = bufferHash.digest();\n }\n\n const buffer = new Uint8Array(BLOCK_SIZE);\n buffer.set(input);\n return buffer;\n}\n","export * from \"./jsSha256\";\n","const SHORT_TO_HEX = {};\nconst HEX_TO_SHORT = {};\nfor (let i = 0; i < 256; i++) {\n let encodedByte = i.toString(16).toLowerCase();\n if (encodedByte.length === 1) {\n encodedByte = `0${encodedByte}`;\n }\n SHORT_TO_HEX[i] = encodedByte;\n HEX_TO_SHORT[encodedByte] = i;\n}\nexport function fromHex(encoded) {\n if (encoded.length % 2 !== 0) {\n throw new Error(\"Hex encoded strings must have an even number length\");\n }\n const out = new Uint8Array(encoded.length / 2);\n for (let i = 0; i < encoded.length; i += 2) {\n const encodedByte = encoded.slice(i, i + 2).toLowerCase();\n if (encodedByte in HEX_TO_SHORT) {\n out[i / 2] = HEX_TO_SHORT[encodedByte];\n }\n else {\n throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);\n }\n }\n return out;\n}\nexport function toHex(bytes) {\n let out = \"\";\n for (let i = 0; i < bytes.byteLength; i++) {\n out += SHORT_TO_HEX[bytes[i]];\n }\n return out;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport var Framework;\n(function (Framework) {\n // < 100 - Web frameworks\n Framework[\"WebUnknown\"] = \"0\";\n Framework[\"React\"] = \"1\";\n Framework[\"NextJs\"] = \"2\";\n Framework[\"Angular\"] = \"3\";\n Framework[\"VueJs\"] = \"4\";\n Framework[\"Nuxt\"] = \"5\";\n Framework[\"Svelte\"] = \"6\";\n // 100s - Server side frameworks\n Framework[\"ServerSideUnknown\"] = \"100\";\n Framework[\"ReactSSR\"] = \"101\";\n Framework[\"NextJsSSR\"] = \"102\";\n Framework[\"AngularSSR\"] = \"103\";\n Framework[\"VueJsSSR\"] = \"104\";\n Framework[\"NuxtSSR\"] = \"105\";\n Framework[\"SvelteSSR\"] = \"106\";\n // 200s - Mobile framework\n Framework[\"ReactNative\"] = \"201\";\n Framework[\"Expo\"] = \"202\";\n})(Framework || (Framework = {}));\nexport var Category;\n(function (Category) {\n Category[\"AI\"] = \"ai\";\n Category[\"API\"] = \"api\";\n Category[\"Auth\"] = \"auth\";\n Category[\"Analytics\"] = \"analytics\";\n Category[\"DataStore\"] = \"datastore\";\n Category[\"Geo\"] = \"geo\";\n Category[\"InAppMessaging\"] = \"inappmessaging\";\n Category[\"Interactions\"] = \"interactions\";\n Category[\"Predictions\"] = \"predictions\";\n Category[\"PubSub\"] = \"pubsub\";\n Category[\"PushNotification\"] = \"pushnotification\";\n Category[\"Storage\"] = \"storage\";\n})(Category || (Category = {}));\nexport var AiAction;\n(function (AiAction) {\n AiAction[\"CreateConversation\"] = \"1\";\n AiAction[\"GetConversation\"] = \"2\";\n AiAction[\"ListConversations\"] = \"3\";\n AiAction[\"DeleteConversation\"] = \"4\";\n AiAction[\"SendMessage\"] = \"5\";\n AiAction[\"ListMessages\"] = \"6\";\n AiAction[\"OnMessage\"] = \"7\";\n AiAction[\"Generation\"] = \"8\";\n AiAction[\"UpdateConversation\"] = \"9\";\n})(AiAction || (AiAction = {}));\nexport var AnalyticsAction;\n(function (AnalyticsAction) {\n AnalyticsAction[\"Record\"] = \"1\";\n AnalyticsAction[\"IdentifyUser\"] = \"2\";\n})(AnalyticsAction || (AnalyticsAction = {}));\nexport var ApiAction;\n(function (ApiAction) {\n ApiAction[\"GraphQl\"] = \"1\";\n ApiAction[\"Get\"] = \"2\";\n ApiAction[\"Post\"] = \"3\";\n ApiAction[\"Put\"] = \"4\";\n ApiAction[\"Patch\"] = \"5\";\n ApiAction[\"Del\"] = \"6\";\n ApiAction[\"Head\"] = \"7\";\n})(ApiAction || (ApiAction = {}));\nexport var AuthAction;\n(function (AuthAction) {\n AuthAction[\"SignUp\"] = \"1\";\n AuthAction[\"ConfirmSignUp\"] = \"2\";\n AuthAction[\"ResendSignUpCode\"] = \"3\";\n AuthAction[\"SignIn\"] = \"4\";\n AuthAction[\"FetchMFAPreference\"] = \"6\";\n AuthAction[\"UpdateMFAPreference\"] = \"7\";\n AuthAction[\"SetUpTOTP\"] = \"10\";\n AuthAction[\"VerifyTOTPSetup\"] = \"11\";\n AuthAction[\"ConfirmSignIn\"] = \"12\";\n AuthAction[\"DeleteUserAttributes\"] = \"15\";\n AuthAction[\"DeleteUser\"] = \"16\";\n AuthAction[\"UpdateUserAttributes\"] = \"17\";\n AuthAction[\"FetchUserAttributes\"] = \"18\";\n AuthAction[\"ConfirmUserAttribute\"] = \"22\";\n AuthAction[\"SignOut\"] = \"26\";\n AuthAction[\"UpdatePassword\"] = \"27\";\n AuthAction[\"ResetPassword\"] = \"28\";\n AuthAction[\"ConfirmResetPassword\"] = \"29\";\n AuthAction[\"FederatedSignIn\"] = \"30\";\n AuthAction[\"RememberDevice\"] = \"32\";\n AuthAction[\"ForgetDevice\"] = \"33\";\n AuthAction[\"FetchDevices\"] = \"34\";\n AuthAction[\"SendUserAttributeVerificationCode\"] = \"35\";\n AuthAction[\"SignInWithRedirect\"] = \"36\";\n AuthAction[\"StartWebAuthnRegistration\"] = \"37\";\n AuthAction[\"CompleteWebAuthnRegistration\"] = \"38\";\n AuthAction[\"ListWebAuthnCredentials\"] = \"39\";\n AuthAction[\"DeleteWebAuthnCredential\"] = \"40\";\n})(AuthAction || (AuthAction = {}));\nexport var DataStoreAction;\n(function (DataStoreAction) {\n DataStoreAction[\"Subscribe\"] = \"1\";\n DataStoreAction[\"GraphQl\"] = \"2\";\n})(DataStoreAction || (DataStoreAction = {}));\nexport var GeoAction;\n(function (GeoAction) {\n GeoAction[\"SearchByText\"] = \"0\";\n GeoAction[\"SearchByCoordinates\"] = \"1\";\n GeoAction[\"SearchForSuggestions\"] = \"2\";\n GeoAction[\"SearchByPlaceId\"] = \"3\";\n GeoAction[\"SaveGeofences\"] = \"4\";\n GeoAction[\"GetGeofence\"] = \"5\";\n GeoAction[\"ListGeofences\"] = \"6\";\n GeoAction[\"DeleteGeofences\"] = \"7\";\n})(GeoAction || (GeoAction = {}));\nexport var InAppMessagingAction;\n(function (InAppMessagingAction) {\n InAppMessagingAction[\"SyncMessages\"] = \"1\";\n InAppMessagingAction[\"IdentifyUser\"] = \"2\";\n InAppMessagingAction[\"NotifyMessageInteraction\"] = \"3\";\n})(InAppMessagingAction || (InAppMessagingAction = {}));\nexport var InteractionsAction;\n(function (InteractionsAction) {\n InteractionsAction[\"None\"] = \"0\";\n})(InteractionsAction || (InteractionsAction = {}));\nexport var PredictionsAction;\n(function (PredictionsAction) {\n PredictionsAction[\"Convert\"] = \"1\";\n PredictionsAction[\"Identify\"] = \"2\";\n PredictionsAction[\"Interpret\"] = \"3\";\n})(PredictionsAction || (PredictionsAction = {}));\nexport var PubSubAction;\n(function (PubSubAction) {\n PubSubAction[\"Subscribe\"] = \"1\";\n})(PubSubAction || (PubSubAction = {}));\nexport var PushNotificationAction;\n(function (PushNotificationAction) {\n PushNotificationAction[\"InitializePushNotifications\"] = \"1\";\n PushNotificationAction[\"IdentifyUser\"] = \"2\";\n})(PushNotificationAction || (PushNotificationAction = {}));\nexport var StorageAction;\n(function (StorageAction) {\n StorageAction[\"UploadData\"] = \"1\";\n StorageAction[\"DownloadData\"] = \"2\";\n StorageAction[\"List\"] = \"3\";\n StorageAction[\"Copy\"] = \"4\";\n StorageAction[\"Remove\"] = \"5\";\n StorageAction[\"GetProperties\"] = \"6\";\n StorageAction[\"GetUrl\"] = \"7\";\n StorageAction[\"GetDataAccess\"] = \"8\";\n StorageAction[\"ListCallerAccessGrants\"] = \"9\";\n})(StorageAction || (StorageAction = {}));\n","// generated by genversion\nexport const version = '6.15.9';\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const globalExists = () => {\n return typeof global !== 'undefined';\n};\nexport const globalThisExists = () => {\n return typeof globalThis !== 'undefined';\n};\nexport const windowExists = () => {\n return typeof window !== 'undefined';\n};\nexport const documentExists = () => {\n return typeof document !== 'undefined';\n};\nexport const processExists = () => {\n return typeof process !== 'undefined';\n};\nexport const keyPrefixMatch = (object, prefix) => {\n return !!Object.keys(object).find(key => key.startsWith(prefix));\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { documentExists, processExists } from './helpers';\n// Tested with react 18.2 - built using Vite\nexport function reactWebDetect() {\n const elementKeyPrefixedWithReact = (key) => {\n return key.startsWith('_react') || key.startsWith('__react');\n };\n const elementIsReactEnabled = (element) => {\n return Object.keys(element).find(elementKeyPrefixedWithReact);\n };\n const allElementsWithId = () => Array.from(document.querySelectorAll('[id]'));\n return documentExists() && allElementsWithId().some(elementIsReactEnabled);\n}\nexport function reactSSRDetect() {\n return (processExists() &&\n typeof process.env !== 'undefined' &&\n !!Object.keys(process.env).find(key => key.includes('react')));\n}\n// use the some\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { globalExists, keyPrefixMatch, windowExists } from './helpers';\n// Tested with vue 3.3.2\nexport function vueWebDetect() {\n return windowExists() && keyPrefixMatch(window, '__VUE');\n}\nexport function vueSSRDetect() {\n return globalExists() && keyPrefixMatch(global, '__VUE');\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { keyPrefixMatch, processExists, windowExists } from './helpers';\n// Tested with svelte 3.59\nexport function svelteWebDetect() {\n return windowExists() && keyPrefixMatch(window, '__SVELTE');\n}\nexport function svelteSSRDetect() {\n return (processExists() &&\n typeof process.env !== 'undefined' &&\n !!Object.keys(process.env).find(key => key.includes('svelte')));\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { globalExists, keyPrefixMatch, windowExists } from './helpers';\n// Tested with next 13.4 / react 18.2\nexport function nextWebDetect() {\n return (windowExists() &&\n window.next &&\n typeof window.next === 'object');\n}\nexport function nextSSRDetect() {\n return (globalExists() &&\n (keyPrefixMatch(global, '__next') || keyPrefixMatch(global, '__NEXT')));\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { globalExists, windowExists } from './helpers';\n// Tested with nuxt 2.15 / vue 2.7\nexport function nuxtWebDetect() {\n return (windowExists() &&\n (window.__NUXT__ !== undefined ||\n window.$nuxt !== undefined));\n}\nexport function nuxtSSRDetect() {\n return (globalExists() && typeof global.__NUXT_PATHS__ !== 'undefined');\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { documentExists, processExists, windowExists } from './helpers';\n// Tested with @angular/core 16.0.0\nexport function angularWebDetect() {\n const angularVersionSetInDocument = Boolean(documentExists() && document.querySelector('[ng-version]'));\n const angularContentSetInWindow = Boolean(windowExists() && typeof window.ng !== 'undefined');\n return angularVersionSetInDocument || angularContentSetInWindow;\n}\nexport function angularSSRDetect() {\n return ((processExists() &&\n typeof process.env === 'object' &&\n process.env.npm_lifecycle_script?.startsWith('ng ')) ||\n false);\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with react-native 0.17.7\nexport function reactNativeDetect() {\n return (typeof navigator !== 'undefined' &&\n typeof navigator.product !== 'undefined' &&\n navigator.product === 'ReactNative');\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { globalExists } from './helpers';\n// Tested with expo 48 / react-native 0.71.3\nexport function expoDetect() {\n return globalExists() && typeof global.expo !== 'undefined';\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { windowExists } from './helpers';\nexport function webDetect() {\n return windowExists();\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Framework } from '../types';\nimport { reactSSRDetect, reactWebDetect } from './React';\nimport { vueSSRDetect, vueWebDetect } from './Vue';\nimport { svelteSSRDetect, svelteWebDetect } from './Svelte';\nimport { nextSSRDetect, nextWebDetect } from './Next';\nimport { nuxtSSRDetect, nuxtWebDetect } from './Nuxt';\nimport { angularSSRDetect, angularWebDetect } from './Angular';\nimport { reactNativeDetect } from './ReactNative';\nimport { expoDetect } from './Expo';\nimport { webDetect } from './Web';\n// These are in the order of detection where when both are detectable, the early Framework will be reported\nconst detectionMap = [\n // First, detect mobile\n { platform: Framework.Expo, detectionMethod: expoDetect },\n { platform: Framework.ReactNative, detectionMethod: reactNativeDetect },\n // Next, detect web frameworks\n { platform: Framework.NextJs, detectionMethod: nextWebDetect },\n { platform: Framework.Nuxt, detectionMethod: nuxtWebDetect },\n { platform: Framework.Angular, detectionMethod: angularWebDetect },\n { platform: Framework.React, detectionMethod: reactWebDetect },\n { platform: Framework.VueJs, detectionMethod: vueWebDetect },\n { platform: Framework.Svelte, detectionMethod: svelteWebDetect },\n { platform: Framework.WebUnknown, detectionMethod: webDetect },\n // Last, detect ssr frameworks\n { platform: Framework.NextJsSSR, detectionMethod: nextSSRDetect },\n { platform: Framework.NuxtSSR, detectionMethod: nuxtSSRDetect },\n { platform: Framework.ReactSSR, detectionMethod: reactSSRDetect },\n { platform: Framework.VueJsSSR, detectionMethod: vueSSRDetect },\n { platform: Framework.AngularSSR, detectionMethod: angularSSRDetect },\n { platform: Framework.SvelteSSR, detectionMethod: svelteSSRDetect },\n];\nexport function detect() {\n return (detectionMap.find(detectionEntry => detectionEntry.detectionMethod())\n ?.platform || Framework.ServerSideUnknown);\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Framework } from './types';\nimport { detect } from './detection';\n// We want to cache detection since the framework won't change\nlet frameworkCache;\nexport const frameworkChangeObservers = [];\n// Setup the detection reset tracking / timeout delays\nlet resetTriggered = false;\nconst SSR_RESET_TIMEOUT = 10; // ms\nconst WEB_RESET_TIMEOUT = 10; // ms\nconst PRIME_FRAMEWORK_DELAY = 1000; // ms\nexport const detectFramework = () => {\n if (!frameworkCache) {\n frameworkCache = detect();\n if (resetTriggered) {\n // The final run of detectFramework:\n // Starting from this point, the `frameworkCache` becomes \"final\".\n // So we don't need to notify the observers again so the observer\n // can be removed after the final notice.\n while (frameworkChangeObservers.length) {\n frameworkChangeObservers.pop()?.();\n }\n }\n else {\n // The first run of detectFramework:\n // Every time we update the cache, call each observer function\n frameworkChangeObservers.forEach(fcn => {\n fcn();\n });\n }\n // Retry once for either Unknown type after a delay (explained below)\n resetTimeout(Framework.ServerSideUnknown, SSR_RESET_TIMEOUT);\n resetTimeout(Framework.WebUnknown, WEB_RESET_TIMEOUT);\n }\n return frameworkCache;\n};\n/**\n * @internal Setup observer callback that will be called everytime the framework changes\n */\nexport const observeFrameworkChanges = (fcn) => {\n // When the `frameworkCache` won't be updated again, we ignore all incoming\n // observers.\n if (resetTriggered) {\n return;\n }\n frameworkChangeObservers.push(fcn);\n};\nexport function clearCache() {\n frameworkCache = undefined;\n}\n// For a framework type and a delay amount, setup the event to re-detect\n// During the runtime boot, it is possible that framework detection will\n// be triggered before the framework has made modifications to the\n// global/window/etc needed for detection. When no framework is detected\n// we will reset and try again to ensure we don't use a cached\n// non-framework detection result for all requests.\nfunction resetTimeout(framework, delay) {\n if (frameworkCache === framework && !resetTriggered) {\n setTimeout(() => {\n clearCache();\n resetTriggered = true;\n setTimeout(detectFramework, PRIME_FRAMEWORK_DELAY);\n }, delay);\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Maintains custom user-agent state set by external consumers.\nconst customUserAgentState = {};\n/**\n * Sets custom user agent state which will be appended to applicable requests. Returns a function that can be used to\n * clean up any custom state set with this API.\n *\n * @note\n * This API operates globally. Calling this API multiple times will result in the most recently set values for a\n * particular API being used.\n *\n * @note\n * This utility IS NOT compatible with SSR.\n *\n * @param input - SetCustomUserAgentInput that defines custom state to apply to the specified APIs.\n */\nexport const setCustomUserAgent = (input) => {\n // Save custom user-agent state & increment reference counter\n // TODO Remove `any` when we upgrade to TypeScript 5.2, see: https://github.com/microsoft/TypeScript/issues/44373\n customUserAgentState[input.category] = input.apis.reduce((acc, api) => ({\n ...acc,\n [api]: {\n refCount: acc[api]?.refCount ? acc[api].refCount + 1 : 1,\n additionalDetails: input.additionalDetails,\n },\n }), customUserAgentState[input.category] ?? {});\n // Callback that cleans up state for APIs recorded by this call\n let cleanUpCallbackCalled = false;\n const cleanUpCallback = () => {\n // Only allow the cleanup callback to be called once\n if (cleanUpCallbackCalled) {\n return;\n }\n cleanUpCallbackCalled = true;\n input.apis.forEach(api => {\n const apiRefCount = customUserAgentState[input.category][api].refCount;\n if (apiRefCount > 1) {\n customUserAgentState[input.category][api].refCount = apiRefCount - 1;\n }\n else {\n delete customUserAgentState[input.category][api];\n // Clean up category if no more APIs set\n if (!Object.keys(customUserAgentState[input.category]).length) {\n delete customUserAgentState[input.category];\n }\n }\n });\n };\n return cleanUpCallback;\n};\nexport const getCustomUserAgent = (category, api) => customUserAgentState[category]?.[api]?.additionalDetails;\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Framework } from './types';\nimport { version } from './version';\nimport { detectFramework, observeFrameworkChanges } from './detectFramework';\nimport { getCustomUserAgent } from './customUserAgent';\nconst BASE_USER_AGENT = `aws-amplify`;\n/** Sanitize Amplify version string be removing special character + and character post the special character */\nexport const sanitizeAmplifyVersion = (amplifyVersion) => amplifyVersion.replace(/\\+.*/, '');\nclass PlatformBuilder {\n constructor() {\n this.userAgent = `${BASE_USER_AGENT}/${sanitizeAmplifyVersion(version)}`;\n }\n get framework() {\n return detectFramework();\n }\n get isReactNative() {\n return (this.framework === Framework.ReactNative ||\n this.framework === Framework.Expo);\n }\n observeFrameworkChanges(fcn) {\n observeFrameworkChanges(fcn);\n }\n}\nexport const Platform = new PlatformBuilder();\nexport const getAmplifyUserAgentObject = ({ category, action, } = {}) => {\n const userAgent = [\n [BASE_USER_AGENT, sanitizeAmplifyVersion(version)],\n ];\n if (category) {\n userAgent.push([category, action]);\n }\n userAgent.push(['framework', detectFramework()]);\n if (category && action) {\n const customState = getCustomUserAgent(category, action);\n if (customState) {\n customState.forEach(state => {\n userAgent.push(state);\n });\n }\n }\n return userAgent;\n};\nexport const getAmplifyUserAgent = (customUserAgentDetails) => {\n const userAgent = getAmplifyUserAgentObject(customUserAgentDetails);\n const userAgentString = userAgent\n .map(([agentKey, agentValue]) => agentKey && agentValue ? `${agentKey}/${agentValue}` : agentKey)\n .join(' ');\n return userAgentString;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const isBrowser = () => typeof window !== 'undefined' && typeof window.document !== 'undefined';\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger } from '../../Logger';\nconst logger = new ConsoleLogger('Auth');\nexport class AuthClass {\n /**\n * Configure Auth category\n *\n * @internal\n *\n * @param authResourcesConfig - Resources configurations required by Auth providers.\n * @param authOptions - Client options used by library\n *\n * @returns void\n */\n configure(authResourcesConfig, authOptions) {\n this.authConfig = authResourcesConfig;\n this.authOptions = authOptions;\n if (authResourcesConfig && authResourcesConfig.Cognito?.userPoolEndpoint) {\n logger.warn(getCustomEndpointWarningMessage('Amazon Cognito User Pool'));\n }\n if (authResourcesConfig &&\n authResourcesConfig.Cognito?.identityPoolEndpoint) {\n logger.warn(getCustomEndpointWarningMessage('Amazon Cognito Identity Pool'));\n }\n }\n /**\n * Fetch the auth tokens, and the temporary AWS credentials and identity if they are configured. By default it\n * will automatically refresh expired auth tokens if a valid refresh token is present. You can force a refresh\n * of non-expired tokens with `{ forceRefresh: true }` input.\n *\n * @param options - Options configuring the fetch behavior.\n *\n * @returns Promise of current auth session {@link AuthSession}.\n */\n async fetchAuthSession(options = {}) {\n let credentialsAndIdentityId;\n let userSub;\n // Get tokens will throw if session cannot be refreshed (network or service error) or return null if not available\n const tokens = await this.getTokens(options);\n if (tokens) {\n userSub = tokens.accessToken?.payload?.sub;\n // getCredentialsAndIdentityId will throw if cannot get credentials (network or service error)\n credentialsAndIdentityId =\n await this.authOptions?.credentialsProvider?.getCredentialsAndIdentityId({\n authConfig: this.authConfig,\n tokens,\n authenticated: true,\n forceRefresh: options.forceRefresh,\n });\n }\n else {\n // getCredentialsAndIdentityId will throw if cannot get credentials (network or service error)\n credentialsAndIdentityId =\n await this.authOptions?.credentialsProvider?.getCredentialsAndIdentityId({\n authConfig: this.authConfig,\n authenticated: false,\n forceRefresh: options.forceRefresh,\n });\n }\n return {\n tokens,\n credentials: credentialsAndIdentityId?.credentials,\n identityId: credentialsAndIdentityId?.identityId,\n userSub,\n };\n }\n async clearCredentials() {\n await this.authOptions?.credentialsProvider?.clearCredentialsAndIdentityId();\n }\n async getTokens(options) {\n return ((await this.authOptions?.tokenProvider?.getTokens(options)) ?? undefined);\n }\n}\nconst getCustomEndpointWarningMessage = (target) => `You are using a custom Amazon ${target} endpoint, ensure the endpoint is correct.`;\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AMPLIFY_SYMBOL, Hub } from '../Hub';\nimport { deepFreeze } from '../utils';\nimport { parseAmplifyConfig } from '../libraryUtils';\nimport { AuthClass } from './Auth';\nimport { ADD_OAUTH_LISTENER } from './constants';\nexport class AmplifyClass {\n constructor() {\n this.oAuthListener = undefined;\n this.isConfigured = false;\n this.resourcesConfig = {};\n this.libraryOptions = {};\n this.Auth = new AuthClass();\n }\n /**\n * Configures Amplify for use with your back-end resources.\n *\n * @remarks\n * This API does not perform any merging of either `resourcesConfig` or `libraryOptions`. The most recently\n * provided values will be used after configuration.\n *\n * @remarks\n * `configure` can be used to specify additional library options where available for supported categories.\n *\n * @param resourceConfig - Back-end resource configuration. Typically provided via the `aws-exports.js` file.\n * @param libraryOptions - Additional options for customizing the behavior of the library.\n */\n configure(resourcesConfig, libraryOptions) {\n const resolvedResourceConfig = parseAmplifyConfig(resourcesConfig);\n this.resourcesConfig = resolvedResourceConfig;\n if (libraryOptions) {\n this.libraryOptions = libraryOptions;\n }\n // Make resource config immutable\n this.resourcesConfig = deepFreeze(this.resourcesConfig);\n this.Auth.configure(this.resourcesConfig.Auth, this.libraryOptions.Auth);\n Hub.dispatch('core', {\n event: 'configure',\n data: this.resourcesConfig,\n }, 'Configure', AMPLIFY_SYMBOL);\n this.notifyOAuthListener();\n this.isConfigured = true;\n }\n /**\n * Provides access to the current back-end resource configuration for the Library.\n *\n * @returns Returns the immutable back-end resource configuration.\n */\n getConfig() {\n if (!this.isConfigured) {\n // eslint-disable-next-line no-console\n console.warn(`Amplify has not been configured. Please call Amplify.configure() before using this service.`);\n }\n return this.resourcesConfig;\n }\n /** @internal */\n [ADD_OAUTH_LISTENER](listener) {\n if (this.resourcesConfig.Auth?.Cognito.loginWith?.oauth) {\n // when Amplify has been configured with a valid OAuth config while adding the listener, run it directly\n listener(this.resourcesConfig.Auth?.Cognito);\n }\n else {\n // otherwise register the listener and run it later when Amplify gets configured with a valid oauth config\n this.oAuthListener = listener;\n }\n }\n notifyOAuthListener() {\n if (!this.resourcesConfig.Auth?.Cognito.loginWith?.oauth ||\n !this.oAuthListener) {\n return;\n }\n this.oAuthListener(this.resourcesConfig.Auth?.Cognito);\n // the listener should only be notified once with a valid oauth config\n this.oAuthListener = undefined;\n }\n}\n/**\n * The `Amplify` utility is used to configure the library.\n *\n * @remarks\n * `Amplify` orchestrates cross-category communication within the library.\n */\nexport const Amplify = new AmplifyClass();\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const fetchAuthSession = (amplify, options) => {\n return amplify.Auth.fetchAuthSession(options);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '../Amplify';\nimport { fetchAuthSession as fetchAuthSessionInternal } from './internal/fetchAuthSession';\n/**\n * Fetch the auth session including the tokens and credentials if they are available. By default it\n * will automatically refresh expired auth tokens if a valid refresh token is present. You can force a refresh\n * of non-expired tokens with `{ forceRefresh: true }` input.\n *\n * @param options - Options configuring the fetch behavior.\n * @throws {@link AuthError} - Throws error when session information cannot be refreshed.\n * @returns Promise<AuthSession>\n */\nexport const fetchAuthSession = (options) => {\n return fetchAuthSessionInternal(Amplify, options);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '../Amplify';\nexport function clearCredentials() {\n return Amplify.Auth.clearCredentials();\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const parseMetadata = (response) => {\n const { headers, statusCode } = response;\n return {\n ...(isMetadataBearer(response) ? response.$metadata : {}),\n httpStatusCode: statusCode,\n requestId: headers['x-amzn-requestid'] ??\n headers['x-amzn-request-id'] ??\n headers['x-amz-request-id'],\n extendedRequestId: headers['x-amz-id-2'],\n cfId: headers['x-amz-cf-id'],\n };\n};\nconst isMetadataBearer = (response) => typeof response?.$metadata === 'object';\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { parseMetadata } from './responseInfo';\n/**\n * Utility functions for serializing and deserializing of JSON protocol in general(including: REST-JSON, JSON-RPC, etc.)\n */\n/**\n * Error parser for AWS JSON protocol.\n */\nexport const parseJsonError = async (response) => {\n if (!response || response.statusCode < 300) {\n return;\n }\n const body = await parseJsonBody(response);\n const sanitizeErrorCode = (rawValue) => {\n const [cleanValue] = rawValue.toString().split(/[,:]+/);\n if (cleanValue.includes('#')) {\n return cleanValue.split('#')[1];\n }\n return cleanValue;\n };\n const code = sanitizeErrorCode(response.headers['x-amzn-errortype'] ??\n body.code ??\n body.__type ??\n 'UnknownError');\n const message = body.message ?? body.Message ?? 'Unknown error';\n const error = new Error(message);\n return Object.assign(error, {\n name: code,\n $metadata: parseMetadata(response),\n });\n};\n/**\n * Parse JSON response body to JavaScript object.\n */\nexport const parseJsonBody = async (response) => {\n if (!response.body) {\n throw new Error('Missing response payload');\n }\n const output = await response.body.json();\n return Object.assign(output, {\n $metadata: parseMetadata(response),\n });\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Compose a service API handler that accepts input as defined shape and responds conforming to defined output shape.\n * A service API handler is composed with:\n * * A transfer handler\n * * A serializer function\n * * A deserializer function\n * * A default config object\n *\n * The returned service API handler, when called, will trigger the following workflow:\n * 1. When calling the service API handler function, the default config object is merged into the input config\n * object to assign the default values of some omitted configs, resulting to a resolved config object.\n * 2. The `endpointResolver` function from the default config object will be invoked with the resolved config object and\n * API input object resulting to an endpoint instance.\n * 3. The serializer function is invoked with API input object and the endpoint instance resulting to an HTTP request\n * instance.\n * 4. The HTTP request instance and the resolved config object is passed to the transfer handler function.\n * 5. The transfer handler function resolves to an HTTP response instance(can be either successful or failed status code).\n * 6. The deserializer function is invoked with the HTTP response instance resulting to the API output object, and\n * return to the caller.\n *\n *\n * @param transferHandler Async function for dispatching HTTP requests and returning HTTP response.\n * @param serializer Async function for converting object in defined input shape into HTTP request targeting a given\n * \tendpoint.\n * @param deserializer Async function for converting HTTP response into output object in defined output shape, or error\n * \tshape.\n * @param defaultConfig object containing default options to be consumed by transfer handler, serializer and\n * deserializer.\n * @returns a async service API handler function that accepts a config object and input object in defined shape, returns\n * \tan output object in defined shape. It may also throw error instance in defined shape in deserializer. The config\n * object type is composed with options type of transferHandler, endpointResolver function as well as endpointResolver\n * function's input options type, region string. The config object property will be marked as optional if it's also\n * \tdefined in defaultConfig.\n *\n * @internal\n */\nexport const composeServiceApi = (transferHandler, serializer, deserializer, defaultConfig) => {\n return async (config, input) => {\n const resolvedConfig = {\n ...defaultConfig,\n ...config,\n };\n // We need to allow different endpoints based on both given config(other than region) and input.\n // However for most of non-S3 services, region is the only input for endpoint resolver.\n const endpoint = await resolvedConfig.endpointResolver(resolvedConfig, input);\n // Unlike AWS SDK clients, a serializer should NOT populate the `host` or `content-length` headers.\n // Both of these headers are prohibited per Spec(https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name).\n // They will be populated automatically by browser, or node-fetch polyfill.\n const request = await serializer(input, endpoint);\n const response = await transferHandler(request, {\n ...resolvedConfig,\n });\n return deserializer(response);\n };\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { MAX_DELAY_MS } from './constants';\n/**\n * @private\n * Internal use of Amplify only\n */\nexport function jitteredBackoff(maxDelayMs = MAX_DELAY_MS) {\n const BASE_TIME_MS = 100;\n const JITTER_FACTOR = 100;\n return attempt => {\n const delay = 2 ** attempt * BASE_TIME_MS + JITTER_FACTOR * Math.random();\n return delay > maxDelayMs ? false : delay;\n };\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const DEFAULT_RETRY_ATTEMPTS = 3;\nexport const AMZ_SDK_INVOCATION_ID_HEADER = 'amz-sdk-invocation-id';\nexport const AMZ_SDK_REQUEST_HEADER = 'amz-sdk-request';\nexport const DEFAULT_MAX_DELAY_MS = 5 * 60 * 1000;\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { jitteredBackoff as jitteredBackoffUtil } from '../../../utils';\nimport { DEFAULT_MAX_DELAY_MS } from './constants';\n// TODO: [v6] The separate retry utility is used by Data packages now and will replaced by retry middleware.\nexport const jitteredBackoff = attempt => {\n const delayFunction = jitteredBackoffUtil(DEFAULT_MAX_DELAY_MS);\n const delay = delayFunction(attempt);\n // The delayFunction returns false when the delay is greater than the max delay(5 mins).\n // In this case, the retry middleware will delay 5 mins instead, as a ceiling of the delay.\n return delay === false ? DEFAULT_MAX_DELAY_MS : delay;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// via https://github.com/aws/aws-sdk-js-v3/blob/ab0e7be36e7e7f8a0c04834357aaad643c7912c3/packages/service-error-classification/src/constants.ts#L8\nconst CLOCK_SKEW_ERROR_CODES = [\n 'AuthFailure',\n 'InvalidSignatureException',\n 'RequestExpired',\n 'RequestInTheFuture',\n 'RequestTimeTooSkewed',\n 'SignatureDoesNotMatch',\n 'BadRequestException', // API Gateway\n];\n/**\n * Given an error code, returns true if it is related to a clock skew error.\n *\n * @param errorCode String representation of some error.\n * @returns True if given error is present in `CLOCK_SKEW_ERROR_CODES`, false otherwise.\n *\n * @internal\n */\nexport const isClockSkewError = (errorCode) => !!errorCode && CLOCK_SKEW_ERROR_CODES.includes(errorCode);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AmplifyErrorCode } from '../../../types';\nimport { isClockSkewError } from './isClockSkewError';\n/**\n * Get retry decider function\n * @param errorParser Function to load JavaScript error from HTTP response\n */\nexport const getRetryDecider = (errorParser) => async (response, error) => {\n const parsedError = error ??\n (await errorParser(response)) ??\n undefined;\n const errorCode = parsedError?.code || parsedError?.name;\n const statusCode = response?.statusCode;\n const isRetryable = isConnectionError(error) ||\n isThrottlingError(statusCode, errorCode) ||\n isClockSkewError(errorCode) ||\n isServerSideError(statusCode, errorCode);\n return {\n retryable: isRetryable,\n };\n};\n// reference: https://github.com/aws/aws-sdk-js-v3/blob/ab0e7be36e7e7f8a0c04834357aaad643c7912c3/packages/service-error-classification/src/constants.ts#L22-L37\nconst THROTTLING_ERROR_CODES = [\n 'BandwidthLimitExceeded',\n 'EC2ThrottledException',\n 'LimitExceededException',\n 'PriorRequestNotComplete',\n 'ProvisionedThroughputExceededException',\n 'RequestLimitExceeded',\n 'RequestThrottled',\n 'RequestThrottledException',\n 'SlowDown',\n 'ThrottledException',\n 'Throttling',\n 'ThrottlingException',\n 'TooManyRequestsException',\n];\nconst TIMEOUT_ERROR_CODES = [\n 'TimeoutError',\n 'RequestTimeout',\n 'RequestTimeoutException',\n];\nconst isThrottlingError = (statusCode, errorCode) => statusCode === 429 ||\n (!!errorCode && THROTTLING_ERROR_CODES.includes(errorCode));\nconst isConnectionError = (error) => [\n AmplifyErrorCode.NetworkError,\n // TODO(vNext): unify the error code `ERR_NETWORK` used by the Storage XHR handler\n 'ERR_NETWORK',\n].includes(error?.name);\nconst isServerSideError = (statusCode, errorCode) => (!!statusCode && [500, 502, 503, 504].includes(statusCode)) ||\n (!!errorCode && TIMEOUT_ERROR_CODES.includes(errorCode));\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { getRetryDecider, jitteredBackoff, parseJsonError, } from '../../../../clients';\n/**\n * The service name used to sign requests if the API requires authentication.\n */\nexport const COGNITO_IDENTITY_SERVICE_NAME = 'cognito-identity';\nexport const DEFAULT_SERVICE_CLIENT_API_CONFIG = {\n service: COGNITO_IDENTITY_SERVICE_NAME,\n retryDecider: getRetryDecider(parseJsonError),\n computeDelay: jitteredBackoff,\n cache: 'no-store',\n};\n","import { DEFAULT_RETRY_ATTEMPTS } from './constants';\n/**\n * Middleware that executes the retry logic.\n */\nexport const retryMiddlewareFactory = ({ maxAttempts = DEFAULT_RETRY_ATTEMPTS, retryDecider, computeDelay, abortSignal, }) => {\n if (maxAttempts < 1) {\n throw new Error('maxAttempts must be greater than 0');\n }\n return (next, context) => async function retryMiddleware(request) {\n let error;\n let attemptsCount = context.attemptsCount ?? 0;\n let response;\n // When retry is not needed or max attempts is reached, either error or response will be set. This function handles either cases.\n const handleTerminalErrorOrResponse = () => {\n if (response) {\n addOrIncrementMetadataAttempts(response, attemptsCount);\n return response;\n }\n else {\n addOrIncrementMetadataAttempts(error, attemptsCount);\n throw error;\n }\n };\n while (!abortSignal?.aborted && attemptsCount < maxAttempts) {\n try {\n response = await next(request);\n error = undefined;\n }\n catch (e) {\n error = e;\n response = undefined;\n }\n // context.attemptsCount may be updated after calling next handler which may retry the request by itself.\n attemptsCount =\n (context.attemptsCount ?? 0) > attemptsCount\n ? (context.attemptsCount ?? 0)\n : attemptsCount + 1;\n context.attemptsCount = attemptsCount;\n const { isCredentialsExpiredError, retryable } = await retryDecider(response, error, context);\n if (retryable) {\n // Setting isCredentialsInvalid flag to notify signing middleware to forceRefresh credentials provider.\n context.isCredentialsExpired = !!isCredentialsExpiredError;\n if (!abortSignal?.aborted && attemptsCount < maxAttempts) {\n // prevent sleep for last attempt or cancelled request;\n const delay = computeDelay(attemptsCount);\n await cancellableSleep(delay, abortSignal);\n }\n continue;\n }\n else {\n return handleTerminalErrorOrResponse();\n }\n }\n if (abortSignal?.aborted) {\n throw new Error('Request aborted.');\n }\n else {\n return handleTerminalErrorOrResponse();\n }\n };\n};\nconst cancellableSleep = (timeoutMs, abortSignal) => {\n if (abortSignal?.aborted) {\n return Promise.resolve();\n }\n let timeoutId;\n let sleepPromiseResolveFn;\n const sleepPromise = new Promise(resolve => {\n sleepPromiseResolveFn = resolve;\n timeoutId = setTimeout(resolve, timeoutMs);\n });\n abortSignal?.addEventListener('abort', function cancelSleep(_) {\n clearTimeout(timeoutId);\n abortSignal?.removeEventListener('abort', cancelSleep);\n sleepPromiseResolveFn();\n });\n return sleepPromise;\n};\nconst addOrIncrementMetadataAttempts = (nextHandlerOutput, attempts) => {\n if (Object.prototype.toString.call(nextHandlerOutput) !== '[object Object]') {\n return;\n }\n nextHandlerOutput.$metadata = {\n ...(nextHandlerOutput.$metadata ?? {}),\n attempts,\n };\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { v4 } from 'uuid';\nconst amplifyUuid = v4;\nexport { amplifyUuid };\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { amplifyUuid } from '../../../libraryUtils';\nimport { AMZ_SDK_INVOCATION_ID_HEADER } from './constants';\n/**\n * Middleware injects a UUID string to `amz-sdk-invocation-id` header.\n * if the header is not set already. This header is helpful to provide\n * observability to group the requests caused by automatic retry.\n *\n * This middleware is standalone because of extra UUID dependency, we will\n * NOT use this middleware for API categories.\n *\n * Ref: https://sdk.amazonaws.com/kotlin/api/smithy-kotlin/api/1.0.9/http-client/aws.smithy.kotlin.runtime.http.operation/-http-operation-context/-sdk-invocation-id.html\n */\nexport const amzSdkInvocationIdHeaderMiddlewareFactory = () => next => {\n return async function amzSdkInvocationIdHeaderMiddleware(request) {\n if (!request.headers[AMZ_SDK_INVOCATION_ID_HEADER]) {\n request.headers[AMZ_SDK_INVOCATION_ID_HEADER] = amplifyUuid();\n }\n return next(request);\n };\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AMZ_SDK_REQUEST_HEADER, DEFAULT_RETRY_ATTEMPTS } from './constants';\n/**\n * Middleware injects `amz-sdk-request` header to indicate the retry state at the time an HTTP request is made.\n * This middleware should co-exist with retryMiddleware as it relies on the retryAttempts value in middleware context\n * set by the retry middleware.\n *\n * Example header: `amz-sdk-request: attempt=1; max=3`.\n *\n * This middleware is standalone because of extra headers may conflict with custom endpoint settings(e.g. CORS), we will\n * NOT use this middleware for API categories.\n */\nexport const amzSdkRequestHeaderMiddlewareFactory = ({ maxAttempts = DEFAULT_RETRY_ATTEMPTS }) => (next, context) => {\n return async function amzSdkRequestHeaderMiddleware(request) {\n const attemptsCount = context.attemptsCount ?? 0;\n request.headers[AMZ_SDK_REQUEST_HEADER] =\n `attempt=${attemptsCount + 1}; max=${maxAttempts}`;\n return next(request);\n };\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Middleware injects user agent string to specified header(default to 'x-amz-user-agent'),\n * if the header is not set already.\n *\n * TODO: incorporate new user agent design\n */\nexport const userAgentMiddlewareFactory = ({ userAgentHeader = 'x-amz-user-agent', userAgentValue = '', }) => next => {\n return async function userAgentMiddleware(request) {\n if (userAgentValue.trim().length === 0) {\n const result = await next(request);\n return result;\n }\n else {\n const headerName = userAgentHeader.toLowerCase();\n request.headers[headerName] = request.headers[headerName]\n ? `${request.headers[headerName]} ${userAgentValue}`\n : userAgentValue;\n const response = await next(request);\n return response;\n }\n };\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Compose a transfer handler with a core transfer handler and a list of middleware.\n * @param coreHandler Core transfer handler\n * @param middleware\tList of middleware\n * @returns A transfer handler whose option type is the union of the core\n * \ttransfer handler's option type and the middleware's option type.\n * @internal\n */\nexport const composeTransferHandler = (coreHandler, middleware) => (request, options) => {\n const context = {};\n let composedHandler = (composeHandlerRequest) => coreHandler(composeHandlerRequest, options);\n for (let i = middleware.length - 1; i >= 0; i--) {\n const m = middleware[i];\n const resolvedMiddleware = m(options);\n composedHandler = resolvedMiddleware(composedHandler, context);\n }\n return composedHandler(request);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Cache the payload of a response body. It allows multiple calls to the body,\n * for example, when reading the body in both retry decider and error deserializer.\n * Caching body is allowed here because we call the body accessor(blob(), json(),\n * etc.) when body is small or streaming implementation is not available(RN).\n *\n * @internal\n */\nexport const withMemoization = (payloadAccessor) => {\n let cached;\n return () => {\n if (!cached) {\n // Explicitly not awaiting. Intermediate await would add overhead and\n // introduce a possible race in the event that this wrapper is called\n // again before the first `payloadAccessor` call resolves.\n cached = payloadAccessor();\n }\n return cached;\n };\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AmplifyError } from '../../errors';\nimport { withMemoization } from '../utils/memoization';\nimport { AmplifyErrorCode } from '../../types';\nconst shouldSendBody = (method) => !['HEAD', 'GET'].includes(method.toUpperCase());\n// TODO[AllanZhengYP]: we need to provide isCanceledError utility\nexport const fetchTransferHandler = async ({ url, method, headers, body }, { abortSignal, cache, withCrossDomainCredentials }) => {\n let resp;\n try {\n resp = await fetch(url, {\n method,\n headers,\n body: shouldSendBody(method) ? body : undefined,\n signal: abortSignal,\n cache,\n credentials: withCrossDomainCredentials ? 'include' : 'same-origin',\n });\n }\n catch (e) {\n if (e instanceof TypeError) {\n throw new AmplifyError({\n name: AmplifyErrorCode.NetworkError,\n message: 'A network error has occurred.',\n underlyingError: e,\n });\n }\n throw e;\n }\n const responseHeaders = {};\n resp.headers?.forEach((value, key) => {\n responseHeaders[key.toLowerCase()] = value;\n });\n const httpResponse = {\n statusCode: resp.status,\n headers: responseHeaders,\n body: null,\n };\n // resp.body is a ReadableStream according to Fetch API spec, but React Native\n // does not implement it.\n const bodyWithMixin = Object.assign(resp.body ?? {}, {\n text: withMemoization(() => resp.text()),\n blob: withMemoization(() => resp.blob()),\n json: withMemoization(() => resp.json()),\n });\n return {\n ...httpResponse,\n body: bodyWithMixin,\n };\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { amzSdkInvocationIdHeaderMiddlewareFactory, amzSdkRequestHeaderMiddlewareFactory, retryMiddlewareFactory, } from '../../middleware/retry';\nimport { userAgentMiddlewareFactory, } from '../../middleware/userAgent';\nimport { composeTransferHandler } from '../../internal/composeTransferHandler';\nimport { fetchTransferHandler } from '../fetch';\nexport const unauthenticatedHandler = composeTransferHandler(fetchTransferHandler, [\n userAgentMiddlewareFactory,\n amzSdkInvocationIdHeaderMiddlewareFactory,\n retryMiddlewareFactory,\n amzSdkRequestHeaderMiddlewareFactory,\n]);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * A Cognito Identity-specific middleware that disables caching for all requests.\n */\nexport const createDisableCacheMiddleware = () => next => async function disableCacheMiddleware(request) {\n request.headers['cache-control'] = 'no-store';\n return next(request);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { unauthenticatedHandler, } from '../../../../../clients';\nimport { composeTransferHandler } from '../../../../../clients/internal';\nimport { createDisableCacheMiddleware } from '../../../middleware';\n/**\n * A Cognito Identity-specific transfer handler that does NOT sign requests, and\n * disables caching.\n *\n * @internal\n */\nexport const cognitoIdentityTransferHandler = composeTransferHandler(unauthenticatedHandler, [createDisableCacheMiddleware]);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const createClientSerializer = (operation) => (input, endpoint) => {\n const headers = getSharedHeaders(operation);\n const body = JSON.stringify(input);\n return buildHttpRpcRequest(endpoint, headers, body);\n};\nconst getSharedHeaders = (operation) => ({\n 'content-type': 'application/x-amz-json-1.1',\n 'x-amz-target': `AWSCognitoIdentityService.${operation}`,\n});\nexport const buildHttpRpcRequest = ({ url }, headers, body) => ({\n headers,\n url,\n body,\n method: 'POST',\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { parseJsonBody, parseJsonError, parseMetadata, } from '../../../../clients';\nimport { composeServiceApi } from '../../../../clients/internal';\nimport { getAmplifyUserAgent } from '../../../../Platform';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nimport { cognitoIdentityTransferHandler } from './handler';\nimport { createClientSerializer } from './serde';\nexport const createGetCredentialsForIdentityClient = (config) => composeServiceApi(cognitoIdentityTransferHandler, createClientSerializer('GetCredentialsForIdentity'), getCredentialsForIdentityDeserializer, {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n userAgentValue: getAmplifyUserAgent(),\n});\nconst getCredentialsForIdentityDeserializer = async (response) => {\n if (response.statusCode >= 300) {\n const error = await parseJsonError(response);\n throw error;\n }\n const body = await parseJsonBody(response);\n return {\n IdentityId: body.IdentityId,\n Credentials: deserializeCredentials(body.Credentials),\n $metadata: parseMetadata(response),\n };\n};\nconst deserializeCredentials = ({ Expiration, ...rest } = {}) => ({\n ...rest,\n Expiration: Expiration && new Date(Expiration * 1000),\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { parseJsonBody, parseJsonError, parseMetadata, } from '../../../../clients';\nimport { composeServiceApi } from '../../../../clients/internal';\nimport { getAmplifyUserAgent } from '../../../../Platform';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nimport { cognitoIdentityTransferHandler } from './handler';\nimport { createClientSerializer } from './serde';\nexport const createGetIdClient = (config) => composeServiceApi(cognitoIdentityTransferHandler, createClientSerializer('GetId'), getIdDeserializer, {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n userAgentValue: getAmplifyUserAgent(),\n});\nconst getIdDeserializer = async (response) => {\n if (response.statusCode >= 300) {\n const error = await parseJsonError(response);\n throw error;\n }\n const body = await parseJsonBody(response);\n return {\n IdentityId: body.IdentityId,\n $metadata: parseMetadata(response),\n };\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Default partition for AWS services. This is used when the region is not provided or the region is not recognized.\n *\n * @internal\n */\nexport const defaultPartition = {\n id: 'aws',\n outputs: {\n dnsSuffix: 'amazonaws.com',\n },\n regionRegex: '^(us|eu|ap|sa|ca|me|af)\\\\-\\\\w+\\\\-\\\\d+$',\n regions: ['aws-global'],\n};\n/**\n * This data is adapted from the partition file from AWS SDK shared utilities but remove some contents for bundle size\n * concern. Information removed are `dualStackDnsSuffix`, `supportDualStack`, `supportFIPS`, restricted partitions, and\n * list of regions for each partition other than global regions.\n *\n * * Ref: https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints\n * * Ref: https://github.com/aws/aws-sdk-js-v3/blob/0201baef03c2379f1f6f7150b9d401d4b230d488/packages/util-endpoints/src/lib/aws/partitions.json#L1\n *\n * @internal\n */\nexport const partitionsInfo = {\n partitions: [\n defaultPartition,\n {\n id: 'aws-cn',\n outputs: {\n dnsSuffix: 'amazonaws.com.cn',\n },\n regionRegex: '^cn\\\\-\\\\w+\\\\-\\\\d+$',\n regions: ['aws-cn-global'],\n },\n ],\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { defaultPartition, partitionsInfo } from './partitions';\n/**\n * Get the AWS Services endpoint URL's DNS suffix for a given region. A typical AWS regional service endpoint URL will\n * follow this pattern: {endpointPrefix}.{region}.{dnsSuffix}. For example, the endpoint URL for Cognito Identity in\n * us-east-1 will be cognito-identity.us-east-1.amazonaws.com. Here the DnsSuffix is `amazonaws.com`.\n *\n * @param region\n * @returns The DNS suffix\n *\n * @internal\n */\nexport const getDnsSuffix = (region) => {\n const { partitions } = partitionsInfo;\n for (const { regions, outputs, regionRegex } of partitions) {\n const regex = new RegExp(regionRegex);\n if (regions.includes(region) || regex.test(region)) {\n return outputs.dnsSuffix;\n }\n }\n return defaultPartition.outputs.dnsSuffix;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst AmplifyUrl = URL;\nconst AmplifyUrlSearchParams = URLSearchParams;\nexport { AmplifyUrl, AmplifyUrlSearchParams };\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { getDnsSuffix } from '../../../../clients';\nimport { AmplifyUrl } from '../../../../libraryUtils';\nimport { COGNITO_IDENTITY_SERVICE_NAME } from './constants';\nexport const cognitoIdentityPoolEndpointResolver = ({ region, }) => ({\n url: new AmplifyUrl(`https://${COGNITO_IDENTITY_SERVICE_NAME}.${region}.${getDnsSuffix(region)}`),\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AmplifyErrorCode } from '../types';\nimport { AmplifyError } from './AmplifyError';\nexport class PlatformNotSupportedError extends AmplifyError {\n constructor() {\n super({\n name: AmplifyErrorCode.PlatformNotSupported,\n message: 'Function not supported on current platform',\n });\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { PlatformNotSupportedError } from '../errors';\n/**\n * @internal\n */\nexport class KeyValueStorage {\n constructor(storage) {\n this.storage = storage;\n }\n /**\n * This is used to set a specific item in storage\n * @param {string} key - the key for the item\n * @param {object} value - the value\n * @returns {string} value that was set\n */\n async setItem(key, value) {\n if (!this.storage)\n throw new PlatformNotSupportedError();\n this.storage.setItem(key, value);\n }\n /**\n * This is used to get a specific key from storage\n * @param {string} key - the key for the item\n * This is used to clear the storage\n * @returns {string} the data item\n */\n async getItem(key) {\n if (!this.storage)\n throw new PlatformNotSupportedError();\n return this.storage.getItem(key);\n }\n /**\n * This is used to remove an item from storage\n * @param {string} key - the key being set\n * @returns {string} value - value that was deleted\n */\n async removeItem(key) {\n if (!this.storage)\n throw new PlatformNotSupportedError();\n this.storage.removeItem(key);\n }\n /**\n * This is used to clear the storage\n * @returns {string} nothing\n */\n async clear() {\n if (!this.storage)\n throw new PlatformNotSupportedError();\n this.storage.clear();\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n */\nexport class InMemoryStorage {\n constructor() {\n this.storage = new Map();\n }\n get length() {\n return this.storage.size;\n }\n key(index) {\n if (index > this.length - 1) {\n return null;\n }\n return Array.from(this.storage.keys())[index];\n }\n setItem(key, value) {\n this.storage.set(key, value);\n }\n getItem(key) {\n return this.storage.get(key) ?? null;\n }\n removeItem(key) {\n this.storage.delete(key);\n }\n clear() {\n this.storage.clear();\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger } from '../Logger';\nimport { InMemoryStorage } from './InMemoryStorage';\n/**\n * @internal\n * @returns Either a reference to window.localStorage or an in-memory storage as fallback\n */\nconst logger = new ConsoleLogger('CoreStorageUtils');\nexport const getLocalStorageWithFallback = () => {\n try {\n // Attempt to use localStorage directly\n if (typeof window !== 'undefined' && window.localStorage) {\n return window.localStorage;\n }\n }\n catch (e) {\n // Handle any errors related to localStorage access\n logger.info('localStorage not found. InMemoryStorage is used as a fallback.');\n }\n // Return in-memory storage as a fallback if localStorage is not accessible\n return new InMemoryStorage();\n};\n/**\n * @internal\n * @returns Either a reference to window.sessionStorage or an in-memory storage as fallback\n */\nexport const getSessionStorageWithFallback = () => {\n try {\n // Attempt to use sessionStorage directly\n if (typeof window !== 'undefined' && window.sessionStorage) {\n // Verify we can actually use it by testing access\n window.sessionStorage.getItem('test');\n return window.sessionStorage;\n }\n throw new Error('sessionStorage is not defined');\n }\n catch (e) {\n // Handle any errors related to sessionStorage access\n logger.info('sessionStorage not found. InMemoryStorage is used as a fallback.');\n return new InMemoryStorage();\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { KeyValueStorage } from './KeyValueStorage';\nimport { getLocalStorageWithFallback } from './utils';\n/**\n * @internal\n */\nexport class DefaultStorage extends KeyValueStorage {\n constructor() {\n super(getLocalStorageWithFallback());\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { KeyValueStorage } from './KeyValueStorage';\nimport { getSessionStorageWithFallback } from './utils';\n/**\n * @internal\n */\nexport class SessionStorage extends KeyValueStorage {\n constructor() {\n super(getSessionStorageWithFallback());\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { PlatformNotSupportedError } from '../errors';\n/**\n * @internal\n */\nexport class SyncKeyValueStorage {\n constructor(storage) {\n this._storage = storage;\n }\n get storage() {\n if (!this._storage)\n throw new PlatformNotSupportedError();\n return this._storage;\n }\n /**\n * This is used to set a specific item in storage\n * @param {string} key - the key for the item\n * @param {object} value - the value\n * @returns {string} value that was set\n */\n setItem(key, value) {\n this.storage.setItem(key, value);\n }\n /**\n * This is used to get a specific key from storage\n * @param {string} key - the key for the item\n * This is used to clear the storage\n * @returns {string} the data item\n */\n getItem(key) {\n return this.storage.getItem(key);\n }\n /**\n * This is used to remove an item from storage\n * @param {string} key - the key being set\n * @returns {string} value - value that was deleted\n */\n removeItem(key) {\n this.storage.removeItem(key);\n }\n /**\n * This is used to clear the storage\n * @returns {string} nothing\n */\n clear() {\n this.storage.clear();\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { SyncKeyValueStorage } from './SyncKeyValueStorage';\nimport { getSessionStorageWithFallback } from './utils';\n/**\n * @internal\n */\nexport class SyncSessionStorage extends SyncKeyValueStorage {\n constructor() {\n super(getSessionStorageWithFallback());\n }\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","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport JsCookie from 'js-cookie';\nexport class CookieStorage {\n constructor(data = {}) {\n const { path, domain, expires, sameSite, secure } = data;\n this.domain = domain;\n this.path = path || '/';\n this.expires = Object.prototype.hasOwnProperty.call(data, 'expires')\n ? expires\n : 365;\n this.secure = Object.prototype.hasOwnProperty.call(data, 'secure')\n ? secure\n : true;\n if (Object.prototype.hasOwnProperty.call(data, 'sameSite')) {\n if (!sameSite || !['strict', 'lax', 'none'].includes(sameSite)) {\n throw new Error('The sameSite value of cookieStorage must be \"lax\", \"strict\" or \"none\".');\n }\n if (sameSite === 'none' && !this.secure) {\n throw new Error('sameSite = None requires the Secure attribute in latest browser versions.');\n }\n this.sameSite = sameSite;\n }\n }\n async setItem(key, value) {\n JsCookie.set(key, value, this.getData());\n }\n async getItem(key) {\n const item = JsCookie.get(key);\n return item ?? null;\n }\n async removeItem(key) {\n JsCookie.remove(key, this.getData());\n }\n async clear() {\n const cookie = JsCookie.get();\n const promises = Object.keys(cookie).map(key => this.removeItem(key));\n await Promise.all(promises);\n }\n getData() {\n return {\n path: this.path,\n expires: this.expires,\n domain: this.domain,\n secure: this.secure,\n ...(this.sameSite && { sameSite: this.sameSite }),\n };\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { DefaultStorage } from './DefaultStorage';\nimport { InMemoryStorage } from './InMemoryStorage';\nimport { KeyValueStorage } from './KeyValueStorage';\nimport { SessionStorage } from './SessionStorage';\nimport { SyncSessionStorage } from './SyncSessionStorage';\nexport { CookieStorage } from './CookieStorage';\nexport const defaultStorage = new DefaultStorage();\nexport const sessionStorage = new SessionStorage();\nexport const syncSessionStorage = new SyncSessionStorage();\nexport const sharedInMemoryStorage = new KeyValueStorage(new InMemoryStorage());\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Default cache config\n */\nexport const defaultConfig = {\n keyPrefix: 'aws-amplify-cache',\n capacityInBytes: 1048576, // 1MB\n itemMaxSize: 210000, // about 200kb\n defaultTTL: 259200000, // about 3 days\n defaultPriority: 5,\n warningThreshold: 0.8,\n};\nexport const currentSizeKey = 'CurSize';\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { currentSizeKey } from '../constants';\n/**\n * return the byte size of the string\n * @param str\n */\nexport function getByteLength(str) {\n let ret = 0;\n ret = str.length;\n for (let i = str.length; i >= 0; i -= 1) {\n const charCode = str.charCodeAt(i);\n if (charCode > 0x7f && charCode <= 0x7ff) {\n ret += 1;\n }\n else if (charCode > 0x7ff && charCode <= 0xffff) {\n ret += 2;\n }\n // trail surrogate\n if (charCode >= 0xdc00 && charCode <= 0xdfff) {\n i -= 1;\n }\n }\n return ret;\n}\n/**\n * get current time\n */\nexport function getCurrentTime() {\n const currentTime = new Date();\n return currentTime.getTime();\n}\n/**\n * check if passed value is an integer\n */\nexport function isInteger(value) {\n if (Number.isInteger) {\n return Number.isInteger(value);\n }\n return (typeof value === 'number' && isFinite(value) && Math.floor(value) === value);\n}\nexport const getCurrentSizeKey = (keyPrefix) => `${keyPrefix}${currentSizeKey}`;\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { createAssertionFunction } from '../../errors';\nexport var CacheErrorCode;\n(function (CacheErrorCode) {\n CacheErrorCode[\"NoCacheItem\"] = \"NoCacheItem\";\n CacheErrorCode[\"NullNextNode\"] = \"NullNextNode\";\n CacheErrorCode[\"NullPreviousNode\"] = \"NullPreviousNode\";\n})(CacheErrorCode || (CacheErrorCode = {}));\nconst cacheErrorMap = {\n [CacheErrorCode.NoCacheItem]: {\n message: 'Item not found in the cache storage.',\n },\n [CacheErrorCode.NullNextNode]: {\n message: 'Next node is null.',\n },\n [CacheErrorCode.NullPreviousNode]: {\n message: 'Previous node is null.',\n },\n};\nexport const assert = createAssertionFunction(cacheErrorMap);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger } from '../Logger';\nimport { currentSizeKey, defaultConfig } from './constants';\nimport { getByteLength, getCurrentSizeKey, getCurrentTime } from './utils';\nimport { CacheErrorCode, assert } from './utils/errorHelpers';\nconst logger = new ConsoleLogger('StorageCache');\n/**\n * Initialization of the cache\n *\n */\nexport class StorageCacheCommon {\n /**\n * Initialize the cache\n *\n * @param config - Custom configuration for this instance.\n */\n constructor({ config, keyValueStorage, }) {\n this.config = {\n ...defaultConfig,\n ...config,\n };\n this.keyValueStorage = keyValueStorage;\n this.sanitizeConfig();\n }\n getModuleName() {\n return 'Cache';\n }\n /**\n * Set custom configuration for the cache instance.\n *\n * @param config - customized configuration (without keyPrefix, which can't be changed)\n *\n * @return - the current configuration\n */\n configure(config) {\n if (config) {\n if (config.keyPrefix) {\n logger.warn('keyPrefix can not be re-configured on an existing Cache instance.');\n }\n this.config = {\n ...this.config,\n ...config,\n };\n }\n this.sanitizeConfig();\n return this.config;\n }\n /**\n * return the current size of the cache\n * @return {Promise}\n */\n async getCurrentCacheSize() {\n let size = await this.getStorage().getItem(getCurrentSizeKey(this.config.keyPrefix));\n if (!size) {\n await this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), '0');\n size = '0';\n }\n return Number(size);\n }\n /**\n * Set item into cache. You can put number, string, boolean or object.\n * The cache will first check whether has the same key.\n * If it has, it will delete the old item and then put the new item in\n * The cache will pop out items if it is full\n * You can specify the cache item options. The cache will abort and output a warning:\n * If the key is invalid\n * If the size of the item exceeds itemMaxSize.\n * If the value is undefined\n * If incorrect cache item configuration\n * If error happened with browser storage\n *\n * @param {String} key - the key of the item\n * @param {Object} value - the value of the item\n * @param {Object} [options] - optional, the specified meta-data\n *\n * @return {Promise}\n */\n async setItem(key, value, options) {\n logger.debug(`Set item: key is ${key}, value is ${value} with options: ${options}`);\n if (!key || key === currentSizeKey) {\n logger.warn(`Invalid key: should not be empty or reserved key: '${currentSizeKey}'`);\n return;\n }\n if (typeof value === 'undefined') {\n logger.warn(`The value of item should not be undefined!`);\n return;\n }\n const cacheItemOptions = {\n priority: options?.priority !== undefined\n ? options.priority\n : this.config.defaultPriority,\n expires: options?.expires !== undefined\n ? options.expires\n : this.config.defaultTTL + getCurrentTime(),\n };\n if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {\n logger.warn(`Invalid parameter: priority due to out or range. It should be within 1 and 5.`);\n return;\n }\n const prefixedKey = `${this.config.keyPrefix}${key}`;\n const item = this.fillCacheItem(prefixedKey, value, cacheItemOptions);\n // check whether this item is too big;\n if (item.byteSize > this.config.itemMaxSize) {\n logger.warn(`Item with key: ${key} you are trying to put into is too big!`);\n return;\n }\n try {\n // first look into the storage, if it exists, delete it.\n const val = await this.getStorage().getItem(prefixedKey);\n if (val) {\n await this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize);\n }\n // check whether the cache is full\n if (await this.isCacheFull(item.byteSize)) {\n const validKeys = await this.clearInvalidAndGetRemainingKeys();\n if (await this.isCacheFull(item.byteSize)) {\n const sizeToPop = await this.sizeToPop(item.byteSize);\n await this.popOutItems(validKeys, sizeToPop);\n }\n }\n // put item in the cache\n return this.setCacheItem(prefixedKey, item);\n }\n catch (e) {\n logger.warn(`setItem failed! ${e}`);\n }\n }\n /**\n * Get item from cache. It will return null if item doesn’t exist or it has been expired.\n * If you specified callback function in the options,\n * then the function will be executed if no such item in the cache\n * and finally put the return value into cache.\n * Please make sure the callback function will return the value you want to put into the cache.\n * The cache will abort output a warning:\n * If the key is invalid\n * If error happened with AsyncStorage\n *\n * @param {String} key - the key of the item\n * @param {Object} [options] - the options of callback function\n *\n * @return {Promise} - return a promise resolves to be the value of the item\n */\n async getItem(key, options) {\n logger.debug(`Get item: key is ${key} with options ${options}`);\n let cached;\n if (!key || key === currentSizeKey) {\n logger.warn(`Invalid key: should not be empty or reserved key: '${currentSizeKey}'`);\n return null;\n }\n const prefixedKey = `${this.config.keyPrefix}${key}`;\n try {\n cached = await this.getStorage().getItem(prefixedKey);\n if (cached != null) {\n if (await this.isExpired(prefixedKey)) {\n // if expired, remove that item and return null\n await this.removeCacheItem(prefixedKey, JSON.parse(cached).byteSize);\n }\n else {\n // if not expired, update its visitedTime and return the value\n const item = await this.updateVisitedTime(JSON.parse(cached), prefixedKey);\n return item.data;\n }\n }\n if (options?.callback) {\n const val = options.callback();\n if (val !== null) {\n await this.setItem(key, val, options);\n }\n return val;\n }\n return null;\n }\n catch (e) {\n logger.warn(`getItem failed! ${e}`);\n return null;\n }\n }\n /**\n * remove item from the cache\n * The cache will abort output a warning:\n * If error happened with AsyncStorage\n * @param {String} key - the key of the item\n * @return {Promise}\n */\n async removeItem(key) {\n logger.debug(`Remove item: key is ${key}`);\n if (!key || key === currentSizeKey) {\n logger.warn(`Invalid key: should not be empty or reserved key: '${currentSizeKey}'`);\n return;\n }\n const prefixedKey = `${this.config.keyPrefix}${key}`;\n try {\n const val = await this.getStorage().getItem(prefixedKey);\n if (val) {\n await this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize);\n }\n }\n catch (e) {\n logger.warn(`removeItem failed! ${e}`);\n }\n }\n /**\n * Return all the keys owned by this cache.\n * Will return an empty array if error occurred.\n *\n * @return {Promise}\n */\n async getAllKeys() {\n try {\n return await this.getAllCacheKeys();\n }\n catch (e) {\n logger.warn(`getAllkeys failed! ${e}`);\n return [];\n }\n }\n getStorage() {\n return this.keyValueStorage;\n }\n /**\n * check whether item is expired\n *\n * @param key - the key of the item\n *\n * @return true if the item is expired.\n */\n async isExpired(key) {\n const text = await this.getStorage().getItem(key);\n assert(text !== null, CacheErrorCode.NoCacheItem, `Key: ${key}`);\n const item = JSON.parse(text);\n if (getCurrentTime() >= item.expires) {\n return true;\n }\n return false;\n }\n /**\n * delete item from cache\n *\n * @param prefixedKey - the key of the item\n * @param size - optional, the byte size of the item\n */\n async removeCacheItem(prefixedKey, size) {\n const item = await this.getStorage().getItem(prefixedKey);\n assert(item !== null, CacheErrorCode.NoCacheItem, `Key: ${prefixedKey}`);\n const itemSize = size ?? JSON.parse(item).byteSize;\n // first try to update the current size of the cache\n await this.decreaseCurrentSizeInBytes(itemSize);\n // try to remove the item from cache\n try {\n await this.getStorage().removeItem(prefixedKey);\n }\n catch (removeItemError) {\n // if some error happened, we need to rollback the current size\n await this.increaseCurrentSizeInBytes(itemSize);\n logger.error(`Failed to remove item: ${removeItemError}`);\n }\n }\n /**\n * produce a JSON object with meta-data and data value\n * @param value - the value of the item\n * @param options - optional, the specified meta-data\n *\n * @return - the item which has the meta-data and the value\n */\n fillCacheItem(key, value, options) {\n const item = {\n key,\n data: value,\n timestamp: getCurrentTime(),\n visitedTime: getCurrentTime(),\n priority: options.priority ?? 0,\n expires: options.expires ?? 0,\n type: typeof value,\n byteSize: 0,\n };\n // calculate byte size\n item.byteSize = getByteLength(JSON.stringify(item));\n // re-calculate using cache item with updated byteSize property\n item.byteSize = getByteLength(JSON.stringify(item));\n return item;\n }\n sanitizeConfig() {\n if (this.config.itemMaxSize > this.config.capacityInBytes) {\n logger.error('Invalid parameter: itemMaxSize. It should be smaller than capacityInBytes. Setting back to default.');\n this.config.itemMaxSize = defaultConfig.itemMaxSize;\n }\n if (this.config.defaultPriority > 5 || this.config.defaultPriority < 1) {\n logger.error('Invalid parameter: defaultPriority. It should be between 1 and 5. Setting back to default.');\n this.config.defaultPriority = defaultConfig.defaultPriority;\n }\n if (Number(this.config.warningThreshold) > 1 ||\n Number(this.config.warningThreshold) < 0) {\n logger.error('Invalid parameter: warningThreshold. It should be between 0 and 1. Setting back to default.');\n this.config.warningThreshold = defaultConfig.warningThreshold;\n }\n // Set 5MB limit\n const cacheLimit = 5 * 1024 * 1024;\n if (this.config.capacityInBytes > cacheLimit) {\n logger.error('Cache Capacity should be less than 5MB. Setting back to default. Setting back to default.');\n this.config.capacityInBytes = defaultConfig.capacityInBytes;\n }\n }\n /**\n * increase current size of the cache\n *\n * @param amount - the amount of the cache szie which need to be increased\n */\n async increaseCurrentSizeInBytes(amount) {\n const size = await this.getCurrentCacheSize();\n await this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), (size + amount).toString());\n }\n /**\n * decrease current size of the cache\n *\n * @param amount - the amount of the cache size which needs to be decreased\n */\n async decreaseCurrentSizeInBytes(amount) {\n const size = await this.getCurrentCacheSize();\n await this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), (size - amount).toString());\n }\n /**\n * update the visited time if item has been visited\n *\n * @param item - the item which need to be updated\n * @param prefixedKey - the key of the item\n *\n * @return the updated item\n */\n async updateVisitedTime(item, prefixedKey) {\n item.visitedTime = getCurrentTime();\n await this.getStorage().setItem(prefixedKey, JSON.stringify(item));\n return item;\n }\n /**\n * put item into cache\n *\n * @param prefixedKey - the key of the item\n * @param itemData - the value of the item\n * @param itemSizeInBytes - the byte size of the item\n */\n async setCacheItem(prefixedKey, item) {\n // first try to update the current size of the cache.\n await this.increaseCurrentSizeInBytes(item.byteSize);\n // try to add the item into cache\n try {\n await this.getStorage().setItem(prefixedKey, JSON.stringify(item));\n }\n catch (setItemErr) {\n // if some error happened, we need to rollback the current size\n await this.decreaseCurrentSizeInBytes(item.byteSize);\n logger.error(`Failed to set item ${setItemErr}`);\n }\n }\n /**\n * total space needed when poping out items\n *\n * @param itemSize\n *\n * @return total space needed\n */\n async sizeToPop(itemSize) {\n const cur = await this.getCurrentCacheSize();\n const spaceItemNeed = cur + itemSize - this.config.capacityInBytes;\n const cacheThresholdSpace = (1 - this.config.warningThreshold) * this.config.capacityInBytes;\n return spaceItemNeed > cacheThresholdSpace\n ? spaceItemNeed\n : cacheThresholdSpace;\n }\n /**\n * see whether cache is full\n *\n * @param itemSize\n *\n * @return true if cache is full\n */\n async isCacheFull(itemSize) {\n const cur = await this.getCurrentCacheSize();\n return itemSize + cur > this.config.capacityInBytes;\n }\n /**\n * get all the items we have, sort them by their priority,\n * if priority is same, sort them by their last visited time\n * pop out items from the low priority (5 is the lowest)\n * @private\n * @param keys - all the keys in this cache\n * @param sizeToPop - the total size of the items which needed to be poped out\n */\n async popOutItems(keys, sizeToPop) {\n const items = [];\n let remainedSize = sizeToPop;\n for (const key of keys) {\n const val = await this.getStorage().getItem(key);\n if (val != null) {\n const item = JSON.parse(val);\n items.push(item);\n }\n }\n // first compare priority\n // then compare visited time\n items.sort((a, b) => {\n if (a.priority > b.priority) {\n return -1;\n }\n else if (a.priority < b.priority) {\n return 1;\n }\n else {\n if (a.visitedTime < b.visitedTime) {\n return -1;\n }\n else\n return 1;\n }\n });\n for (const item of items) {\n // pop out items until we have enough room for new item\n await this.removeCacheItem(item.key, item.byteSize);\n remainedSize -= item.byteSize;\n if (remainedSize <= 0) {\n return;\n }\n }\n }\n /**\n * Scan the storage and combine the following operations for efficiency\n * 1. Clear out all expired keys owned by this cache, not including the size key.\n * 2. Return the remaining keys.\n *\n * @return The remaining valid keys\n */\n async clearInvalidAndGetRemainingKeys() {\n const remainingKeys = [];\n const keys = await this.getAllCacheKeys({\n omitSizeKey: true,\n });\n for (const key of keys) {\n if (await this.isExpired(key)) {\n await this.removeCacheItem(key);\n }\n else {\n remainingKeys.push(key);\n }\n }\n return remainingKeys;\n }\n /**\n * clear the entire cache\n * The cache will abort and output a warning if error occurs\n * @return {Promise}\n */\n async clear() {\n logger.debug(`Clear Cache`);\n try {\n const keys = await this.getAllKeys();\n for (const key of keys) {\n const prefixedKey = `${this.config.keyPrefix}${key}`;\n await this.getStorage().removeItem(prefixedKey);\n }\n }\n catch (e) {\n logger.warn(`clear failed! ${e}`);\n }\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger } from '../Logger';\nimport { KeyValueStorage } from '../storage/KeyValueStorage';\nimport { getLocalStorageWithFallback } from '../storage/utils';\nimport { defaultConfig } from './constants';\nimport { StorageCacheCommon } from './StorageCacheCommon';\nimport { getCurrentSizeKey, getCurrentTime } from './utils';\nconst logger = new ConsoleLogger('StorageCache');\n/**\n * Customized storage based on the SessionStorage or LocalStorage with LRU implemented\n */\nexport class StorageCache extends StorageCacheCommon {\n /**\n * initialize the cache\n * @param config - the configuration of the cache\n */\n constructor(config) {\n const storage = getLocalStorageWithFallback();\n super({ config, keyValueStorage: new KeyValueStorage(storage) });\n this.storage = storage;\n this.getItem = this.getItem.bind(this);\n this.setItem = this.setItem.bind(this);\n this.removeItem = this.removeItem.bind(this);\n }\n async getAllCacheKeys(options) {\n const { omitSizeKey } = options ?? {};\n const keys = [];\n for (let i = 0; i < this.storage.length; i++) {\n const key = this.storage.key(i);\n if (omitSizeKey && key === getCurrentSizeKey(this.config.keyPrefix)) {\n continue;\n }\n if (key?.startsWith(this.config.keyPrefix)) {\n keys.push(key.substring(this.config.keyPrefix.length));\n }\n }\n return keys;\n }\n /**\n * Return a new instance of cache with customized configuration.\n * @param {Object} config - the customized configuration\n * @return {Object} - the new instance of Cache\n */\n createInstance(config) {\n if (!config.keyPrefix || config.keyPrefix === defaultConfig.keyPrefix) {\n logger.error('invalid keyPrefix, setting keyPrefix with timeStamp');\n config.keyPrefix = getCurrentTime.toString();\n }\n return new StorageCache(config);\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { StorageCache } from './StorageCache';\nexport const Cache = new StorageCache();\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger } from '../Logger';\nconst logger = new ConsoleLogger('I18n');\n/**\n * Language translation utility.\n */\nexport class I18n {\n constructor() {\n /**\n * @private\n */\n this._options = null;\n /**\n * @private\n */\n this._lang = null;\n /**\n * @private\n */\n this._dict = {};\n }\n /**\n * Sets the default language from the configuration when required.\n */\n setDefaultLanguage() {\n // Default to window language if not set in instance\n if (!this._lang &&\n typeof window !== 'undefined' &&\n window &&\n window.navigator) {\n this._lang = window.navigator.language;\n }\n logger.debug(this._lang);\n }\n /**\n * @method\n * Explicitly setting language\n * @param {String} lang\n */\n setLanguage(lang) {\n this._lang = lang;\n }\n /**\n * @method\n * Get value\n * @param {String} key\n * @param {String} defVal - Default value\n */\n get(key, defVal = undefined) {\n this.setDefaultLanguage();\n if (!this._lang) {\n return typeof defVal !== 'undefined' ? defVal : key;\n }\n const lang = this._lang;\n let val = this.getByLanguage(key, lang);\n if (val) {\n return val;\n }\n if (lang.indexOf('-') > 0) {\n val = this.getByLanguage(key, lang.split('-')[0]);\n }\n if (val) {\n return val;\n }\n return typeof defVal !== 'undefined' ? defVal : key;\n }\n /**\n * @method\n * Get value according to specified language\n * @param {String} key\n * @param {String} language - Specified langurage to be used\n * @param {String} defVal - Default value\n */\n getByLanguage(key, language, defVal = null) {\n if (!language) {\n return defVal;\n }\n const langDict = this._dict[language];\n if (!langDict) {\n return defVal;\n }\n return langDict[key];\n }\n /**\n * @method\n * Add vocabularies for one language\n * @param {String} language - Language of the dictionary\n * @param {Object} vocabularies - Object that has key-value as dictionary entry\n */\n putVocabulariesForLanguage(language, vocabularies) {\n let langDict = this._dict[language];\n if (!langDict) {\n langDict = this._dict[language] = {};\n }\n this._dict[language] = { ...langDict, ...vocabularies };\n }\n /**\n * @method\n * Add vocabularies for one language\n * @param {Object} vocabularies - Object that has language as key,\n * vocabularies of each language as value\n */\n putVocabularies(vocabularies) {\n Object.keys(vocabularies).forEach(key => {\n this.putVocabulariesForLanguage(key, vocabularies[key]);\n });\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { createAssertionFunction } from '../errors';\nexport var I18nErrorCode;\n(function (I18nErrorCode) {\n I18nErrorCode[\"NotConfigured\"] = \"NotConfigured\";\n})(I18nErrorCode || (I18nErrorCode = {}));\nconst i18nErrorMap = {\n [I18nErrorCode.NotConfigured]: {\n message: 'i18n is not configured.',\n },\n};\nexport const assert = createAssertionFunction(i18nErrorMap);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger } from '../Logger';\nimport { I18n as I18nClass } from './I18n';\nimport { I18nErrorCode, assert } from './errorHelpers';\nconst logger = new ConsoleLogger('I18n');\nlet _config = { language: null };\nlet _i18n = null;\n/**\n * Export I18n APIs\n */\nexport class I18n {\n /**\n * @static\n * @method\n * Configure I18n part\n * @param {Object} config - Configuration of the I18n\n */\n static configure(config) {\n logger.debug('configure I18n');\n if (!config) {\n return _config;\n }\n _config = Object.assign({}, _config, config.I18n || config);\n I18n.createInstance();\n return _config;\n }\n static getModuleName() {\n return 'I18n';\n }\n /**\n * @static\n * @method\n * Create an instance of I18n for the library\n */\n static createInstance() {\n logger.debug('create I18n instance');\n if (_i18n) {\n return;\n }\n _i18n = new I18nClass();\n }\n /**\n * @static @method\n * Explicitly setting language\n * @param {String} lang\n */\n static setLanguage(lang) {\n I18n.checkConfig();\n assert(!!_i18n, I18nErrorCode.NotConfigured);\n _i18n.setLanguage(lang);\n }\n /**\n * @static @method\n * Get value\n * @param {String} key\n * @param {String} defVal - Default value\n */\n static get(key, defVal) {\n if (!I18n.checkConfig()) {\n return typeof defVal === 'undefined' ? key : defVal;\n }\n assert(!!_i18n, I18nErrorCode.NotConfigured);\n return _i18n.get(key, defVal);\n }\n /**\n * @static\n * @method\n * Add vocabularies for one language\n * @param {String} language - Language of the dictionary\n * @param {Object} vocabularies - Object that has key-value as dictionary entry\n */\n static putVocabulariesForLanguage(language, vocabularies) {\n I18n.checkConfig();\n assert(!!_i18n, I18nErrorCode.NotConfigured);\n _i18n.putVocabulariesForLanguage(language, vocabularies);\n }\n /**\n * @static\n * @method\n * Add vocabularies for one language\n * @param {Object} vocabularies - Object that has language as key,\n * vocabularies of each language as value\n */\n static putVocabularies(vocabularies) {\n I18n.checkConfig();\n assert(!!_i18n, I18nErrorCode.NotConfigured);\n _i18n.putVocabularies(vocabularies);\n }\n static checkConfig() {\n if (!_i18n) {\n I18n.createInstance();\n }\n return true;\n }\n}\n// Create an instance of I18n in the static class\nI18n.createInstance();\n","export { Hub } from './Hub/index.mjs';\nexport { decodeJWT } from './singleton/Auth/utils/index.mjs';\nexport { Amplify, AmplifyClass as AmplifyClassV6 } from './singleton/Amplify.mjs';\nexport { fetchAuthSession } from './singleton/apis/fetchAuthSession.mjs';\nexport { clearCredentials } from './singleton/apis/clearCredentials.mjs';\nexport { createGetCredentialsForIdentityClient } from './foundation/factories/serviceClients/cognitoIdentity/createGetCredentialsForIdentityClient.mjs';\nexport { createGetIdClient } from './foundation/factories/serviceClients/cognitoIdentity/createGetIdClient.mjs';\nexport { cognitoIdentityPoolEndpointResolver } from './foundation/factories/serviceClients/cognitoIdentity/cognitoIdentityPoolEndpointResolver.mjs';\nexport { defaultStorage, sessionStorage, sharedInMemoryStorage, syncSessionStorage } from './storage/index.mjs';\nexport { Cache } from './Cache/index.mjs';\nexport { I18n } from './I18n/index.mjs';\nexport { ConsoleLogger } from './Logger/ConsoleLogger.mjs';\nexport { ServiceWorkerClass as ServiceWorker } from './ServiceWorker/ServiceWorker.mjs';\nexport { CookieStorage } from './storage/CookieStorage.mjs';\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { getCrypto } from './globalHelpers';\nexport const generateRandomString = (length) => {\n const STATE_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n const result = [];\n const randomNums = new Uint8Array(length);\n getCrypto().getRandomValues(randomNums);\n for (const num of randomNums) {\n result.push(STATE_CHARSET[num % STATE_CHARSET.length]);\n }\n return result.join('');\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport function urlSafeDecode(hex) {\n const matchArr = hex.match(/.{2}/g) || [];\n return matchArr.map(char => String.fromCharCode(parseInt(char, 16))).join('');\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport function urlSafeEncode(str) {\n return str\n .split('')\n .map(char => char.charCodeAt(0).toString(16).padStart(2, '0'))\n .join('');\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * returns in-flight promise if there is one\n *\n * @param asyncFunction - asyncFunction to be deduped.\n * @returns - the return type of the callback\n */\nexport const deDupeAsyncFunction = (asyncFunction) => {\n let inflightPromise;\n return async (...args) => {\n if (inflightPromise)\n return inflightPromise;\n inflightPromise = new Promise((resolve, reject) => {\n asyncFunction(...args)\n .then(result => {\n resolve(result);\n })\n .catch(error => {\n reject(error);\n })\n .finally(() => {\n inflightPromise = undefined;\n });\n });\n return inflightPromise;\n };\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport function isTokenExpired({ expiresAt, clockDrift, tolerance = 5000, }) {\n const currentTime = Date.now();\n return currentTime + clockDrift + tolerance > expiresAt;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Retrieves the device name using the User-Agent Client Hints API if available,\n * falling back to the traditional userAgent string if not.\n *\n * @returns {Promise<string>} A promise that resolves with a string representing the device name.\n *\n * Example Output:\n * navigator.userAgentData:\n * 'macOS 14.2.1 arm macOS Not A(Brand/99.0.0.0;Google Chrome/121.0.6167.160;Chromium/121.0.6167.160'\n * navigator.userAgent:\n * 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/115.0'\n */\nexport const getDeviceName = async () => {\n const { userAgentData } = navigator;\n if (!userAgentData)\n return navigator.userAgent;\n const { platform = '', platformVersion = '', model = '', architecture = '', fullVersionList = [], } = await userAgentData.getHighEntropyValues([\n 'platform',\n 'platformVersion',\n 'architecture',\n 'model',\n 'fullVersionList',\n ]);\n const versionList = fullVersionList\n .map((v) => `${v.brand}/${v.version}`)\n .join(';');\n const deviceName = [\n platform,\n platformVersion,\n architecture,\n model,\n platform,\n versionList,\n ]\n .filter(value => value)\n .join(' ');\n return deviceName || navigator.userAgent;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport function bytesToString(input) {\n return Array.from(input, byte => String.fromCodePoint(byte)).join('');\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { getBtoa } from '../../globalHelpers';\nimport { bytesToString } from './bytesToString';\nexport const base64Encoder = {\n /**\n * Convert input to base64-encoded string\n * @param input - string to convert to base64\n * @param options - encoding options that can optionally produce a base64url string\n * @returns base64-encoded string\n */\n convert(input, options = {\n urlSafe: false,\n skipPadding: false,\n }) {\n const inputStr = typeof input === 'string' ? input : bytesToString(input);\n let encodedStr = getBtoa()(inputStr);\n // urlSafe char replacement and skipPadding options conform to the base64url spec\n // https://datatracker.ietf.org/doc/html/rfc4648#section-5\n if (options.urlSafe) {\n encodedStr = encodedStr.replace(/\\+/g, '-').replace(/\\//g, '_');\n }\n if (options.skipPadding) {\n encodedStr = encodedStr.replace(/=/g, '');\n }\n return encodedStr;\n },\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { getCrypto } from './globalHelpers';\n/*\n * Cryptographically secure pseudorandom number generator\n * As Math.random() is cryptographically not safe to use\n */\nexport function cryptoSecureRandomInt() {\n const crypto = getCrypto();\n const randomResult = crypto.getRandomValues(new Uint32Array(1))[0];\n return randomResult;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { cryptoSecureRandomInt } from './cryptoSecureRandomInt';\n/**\n * Hex encoding strategy.\n * Converts a word array to a hex string.\n * @param {WordArray} wordArray The word array.\n * @return {string} The hex string.\n * @static\n */\nfunction hexStringify(wordArray) {\n // Shortcuts\n const { words } = wordArray;\n const { sigBytes } = wordArray;\n // Convert\n const hexChars = [];\n for (let i = 0; i < sigBytes; i++) {\n const bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;\n hexChars.push((bite >>> 4).toString(16));\n hexChars.push((bite & 0x0f).toString(16));\n }\n return hexChars.join('');\n}\nexport class WordArray {\n constructor(words, sigBytes) {\n this.words = [];\n let Words = words;\n Words = this.words = Words || [];\n if (sigBytes !== undefined) {\n this.sigBytes = sigBytes;\n }\n else {\n this.sigBytes = Words.length * 4;\n }\n }\n random(nBytes) {\n const words = [];\n for (let i = 0; i < nBytes; i += 4) {\n words.push(cryptoSecureRandomInt());\n }\n return new WordArray(words, nBytes);\n }\n toString() {\n return hexStringify(this);\n }\n}\n","export { generateRandomString } from './utils/generateRandomString.mjs';\nexport { getClientInfo } from './utils/getClientInfo/getClientInfo.mjs';\nexport { isBrowser } from './utils/isBrowser.mjs';\nexport { isWebWorker } from './utils/isWebWorker.mjs';\nexport { NonRetryableError } from './utils/retry/NonRetryableError.mjs';\nexport { isNonRetryableError } from './utils/retry/isNonRetryableError.mjs';\nexport { jitteredBackoff } from './utils/retry/jitteredBackoff.mjs';\nexport { jitteredExponentialRetry } from './utils/retry/jitteredExponentialRetry.mjs';\nexport { retry } from './utils/retry/retry.mjs';\nexport { urlSafeDecode } from './utils/urlSafeDecode.mjs';\nexport { urlSafeEncode } from './utils/urlSafeEncode.mjs';\nexport { deDupeAsyncFunction } from './utils/deDupeAsyncFunction.mjs';\nexport { isTokenExpired } from './utils/isTokenExpired.mjs';\nexport { parseAWSExports } from './parseAWSExports.mjs';\nexport { isAmplifyOutputs, parseAmplifyOutputs } from './parseAmplifyOutputs.mjs';\nexport { ADD_OAUTH_LISTENER } from './singleton/constants.mjs';\nexport { amplifyUuid } from './utils/amplifyUuid/index.mjs';\nexport { AmplifyUrl, AmplifyUrlSearchParams } from './utils/amplifyUrl/index.mjs';\nexport { parseAmplifyConfig } from './utils/parseAmplifyConfig.mjs';\nexport { getDeviceName } from './utils/deviceName/getDeviceName.mjs';\nexport { assertIdentityPoolIdConfig, assertOAuthConfig, assertTokenProviderConfig, decodeJWT } from './singleton/Auth/utils/index.mjs';\nexport { Signer } from './Signer/Signer.mjs';\nexport { haveCredentialsChanged } from './utils/haveCredentialsChanged.mjs';\nexport { Platform, getAmplifyUserAgent, getAmplifyUserAgentObject } from './Platform/index.mjs';\nexport { AiAction, AnalyticsAction, ApiAction, AuthAction, Category, DataStoreAction, Framework, GeoAction, InAppMessagingAction, InteractionsAction, PredictionsAction, PubSubAction, PushNotificationAction, StorageAction } from './Platform/types.mjs';\nexport { setCustomUserAgent } from './Platform/customUserAgent.mjs';\nexport { AmplifyError } from './errors/AmplifyError.mjs';\nexport { ApiError } from './errors/APIError.mjs';\nexport { createAssertionFunction } from './errors/createAssertionFunction.mjs';\nexport { PlatformNotSupportedError } from './errors/PlatformNotSupportedError.mjs';\nimport './errors/errorHelpers.mjs';\nexport { AmplifyErrorCode } from './types/errors.mjs';\nexport { BackgroundProcessManager } from './BackgroundProcessManager/BackgroundProcessManager.mjs';\nexport { Mutex } from './Mutex/Mutex.mjs';\nexport { Reachability } from './Reachability/Reachability.mjs';\nexport { USER_AGENT_HEADER } from './constants.mjs';\nexport { fetchAuthSession } from './singleton/apis/internal/fetchAuthSession.mjs';\nexport { AMPLIFY_SYMBOL, HubInternal } from './Hub/index.mjs';\nexport { base64Decoder } from './utils/convert/base64/base64Decoder.mjs';\nexport { base64Encoder } from './utils/convert/base64/base64Encoder.mjs';\nexport { getCrypto } from './utils/globalHelpers/index.mjs';\nexport { cryptoSecureRandomInt } from './utils/cryptoSecureRandomInt.mjs';\nexport { WordArray } from './utils/WordArray.mjs';\nexport { sessionListener } from './utils/sessionListener/index.mjs';\nexport { SESSION_START_EVENT, SESSION_STOP_EVENT } from './utils/sessionListener/constants.mjs';\n//# sourceMappingURL=libraryUtils.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport var AuthValidationErrorCode;\n(function (AuthValidationErrorCode) {\n AuthValidationErrorCode[\"EmptySignInUsername\"] = \"EmptySignInUsername\";\n AuthValidationErrorCode[\"EmptySignInPassword\"] = \"EmptySignInPassword\";\n AuthValidationErrorCode[\"CustomAuthSignInPassword\"] = \"CustomAuthSignInPassword\";\n AuthValidationErrorCode[\"EmptySignUpUsername\"] = \"EmptySignUpUsername\";\n AuthValidationErrorCode[\"EmptySignUpPassword\"] = \"EmptySignUpPassword\";\n AuthValidationErrorCode[\"EmptyConfirmSignUpUsername\"] = \"EmptyConfirmSignUpUsername\";\n AuthValidationErrorCode[\"EmptyConfirmSignUpCode\"] = \"EmptyConfirmSignUpCode\";\n AuthValidationErrorCode[\"EmptyResendSignUpCodeUsername\"] = \"EmptyresendSignUpCodeUsername\";\n AuthValidationErrorCode[\"EmptyChallengeResponse\"] = \"EmptyChallengeResponse\";\n AuthValidationErrorCode[\"EmptyConfirmResetPasswordUsername\"] = \"EmptyConfirmResetPasswordUsername\";\n AuthValidationErrorCode[\"EmptyConfirmResetPasswordNewPassword\"] = \"EmptyConfirmResetPasswordNewPassword\";\n AuthValidationErrorCode[\"EmptyConfirmResetPasswordConfirmationCode\"] = \"EmptyConfirmResetPasswordConfirmationCode\";\n AuthValidationErrorCode[\"EmptyResetPasswordUsername\"] = \"EmptyResetPasswordUsername\";\n AuthValidationErrorCode[\"EmptyVerifyTOTPSetupCode\"] = \"EmptyVerifyTOTPSetupCode\";\n AuthValidationErrorCode[\"EmptyConfirmUserAttributeCode\"] = \"EmptyConfirmUserAttributeCode\";\n AuthValidationErrorCode[\"IncorrectMFAMethod\"] = \"IncorrectMFAMethod\";\n AuthValidationErrorCode[\"EmptyUpdatePassword\"] = \"EmptyUpdatePassword\";\n})(AuthValidationErrorCode || (AuthValidationErrorCode = {}));\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthValidationErrorCode } from '../errors/types/validation';\nexport const validationErrorMap = {\n [AuthValidationErrorCode.EmptyChallengeResponse]: {\n message: 'challengeResponse is required to confirmSignIn',\n },\n [AuthValidationErrorCode.EmptyConfirmResetPasswordUsername]: {\n message: 'username is required to confirmResetPassword',\n },\n [AuthValidationErrorCode.EmptyConfirmSignUpCode]: {\n message: 'code is required to confirmSignUp',\n },\n [AuthValidationErrorCode.EmptyConfirmSignUpUsername]: {\n message: 'username is required to confirmSignUp',\n },\n [AuthValidationErrorCode.EmptyConfirmResetPasswordConfirmationCode]: {\n message: 'confirmationCode is required to confirmResetPassword',\n },\n [AuthValidationErrorCode.EmptyConfirmResetPasswordNewPassword]: {\n message: 'newPassword is required to confirmResetPassword',\n },\n [AuthValidationErrorCode.EmptyResendSignUpCodeUsername]: {\n message: 'username is required to confirmSignUp',\n },\n [AuthValidationErrorCode.EmptyResetPasswordUsername]: {\n message: 'username is required to resetPassword',\n },\n [AuthValidationErrorCode.EmptySignInPassword]: {\n message: 'password is required to signIn',\n },\n [AuthValidationErrorCode.EmptySignInUsername]: {\n message: 'username is required to signIn',\n },\n [AuthValidationErrorCode.EmptySignUpPassword]: {\n message: 'password is required to signUp',\n },\n [AuthValidationErrorCode.EmptySignUpUsername]: {\n message: 'username is required to signUp',\n },\n [AuthValidationErrorCode.CustomAuthSignInPassword]: {\n message: 'A password is not needed when signing in with CUSTOM_WITHOUT_SRP',\n recoverySuggestion: 'Do not include a password in your signIn call.',\n },\n [AuthValidationErrorCode.IncorrectMFAMethod]: {\n message: 'Incorrect MFA method was chosen. It should be either SMS, TOTP, or EMAIL',\n recoverySuggestion: 'Try to pass SMS, TOTP, or EMAIL as the challengeResponse',\n },\n [AuthValidationErrorCode.EmptyVerifyTOTPSetupCode]: {\n message: 'code is required to verifyTotpSetup',\n },\n [AuthValidationErrorCode.EmptyUpdatePassword]: {\n message: 'oldPassword and newPassword are required to changePassword',\n },\n [AuthValidationErrorCode.EmptyConfirmUserAttributeCode]: {\n message: 'confirmation code is required to confirmUserAttribute',\n },\n};\n// TODO: delete this code when the Auth class is removed.\nexport var AuthErrorStrings;\n(function (AuthErrorStrings) {\n AuthErrorStrings[\"DEFAULT_MSG\"] = \"Authentication Error\";\n AuthErrorStrings[\"EMPTY_EMAIL\"] = \"Email cannot be empty\";\n AuthErrorStrings[\"EMPTY_PHONE\"] = \"Phone number cannot be empty\";\n AuthErrorStrings[\"EMPTY_USERNAME\"] = \"Username cannot be empty\";\n AuthErrorStrings[\"INVALID_USERNAME\"] = \"The username should either be a string or one of the sign in types\";\n AuthErrorStrings[\"EMPTY_PASSWORD\"] = \"Password cannot be empty\";\n AuthErrorStrings[\"EMPTY_CODE\"] = \"Confirmation code cannot be empty\";\n AuthErrorStrings[\"SIGN_UP_ERROR\"] = \"Error creating account\";\n AuthErrorStrings[\"NO_MFA\"] = \"No valid MFA method provided\";\n AuthErrorStrings[\"INVALID_MFA\"] = \"Invalid MFA type\";\n AuthErrorStrings[\"EMPTY_CHALLENGE\"] = \"Challenge response cannot be empty\";\n AuthErrorStrings[\"NO_USER_SESSION\"] = \"Failed to get the session because the user is empty\";\n AuthErrorStrings[\"NETWORK_ERROR\"] = \"Network Error\";\n AuthErrorStrings[\"DEVICE_CONFIG\"] = \"Device tracking has not been configured in this User Pool\";\n AuthErrorStrings[\"AUTOSIGNIN_ERROR\"] = \"Please use your credentials to sign in\";\n AuthErrorStrings[\"OAUTH_ERROR\"] = \"Couldn't finish OAuth flow, check your User Pool HostedUI settings\";\n})(AuthErrorStrings || (AuthErrorStrings = {}));\nexport var AuthErrorCodes;\n(function (AuthErrorCodes) {\n AuthErrorCodes[\"SignInException\"] = \"SignInException\";\n AuthErrorCodes[\"OAuthSignInError\"] = \"OAuthSignInException\";\n})(AuthErrorCodes || (AuthErrorCodes = {}));\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AmplifyError, } from '@aws-amplify/core/internals/utils';\nexport class AuthError extends AmplifyError {\n constructor(params) {\n super(params);\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = AuthError;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { validationErrorMap } from '../../common/AuthErrorStrings';\nimport { AuthError } from '../AuthError';\nexport function assertValidationError(assertion, name) {\n const { message, recoverySuggestion } = validationErrorMap[name];\n if (!assertion) {\n throw new AuthError({ name, message, recoverySuggestion });\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthError } from '../../errors/AuthError';\nexport function getRegionFromUserPoolId(userPoolId) {\n const region = userPoolId?.split('_')[0];\n if (!userPoolId ||\n userPoolId.indexOf('_') < 0 ||\n !region ||\n typeof region !== 'string')\n throw new AuthError({\n name: 'InvalidUserPoolId',\n message: 'Invalid user pool id provided.',\n });\n return region;\n}\nexport function getRegionFromIdentityPoolId(identityPoolId) {\n if (!identityPoolId || !identityPoolId.includes(':')) {\n throw new AuthError({\n name: 'InvalidIdentityPoolIdException',\n message: 'Invalid identity pool id provided.',\n recoverySuggestion: 'Make sure a valid identityPoolId is given in the config.',\n });\n }\n return identityPoolId.split(':')[0];\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Transforms a user attributes object into an array of AttributeType objects.\n * @param attributes user attributes to be mapped to AttributeType objects.\n * @returns an array of AttributeType objects.\n */\nexport function toAttributeType(attributes) {\n return Object.entries(attributes).map(([key, value]) => ({\n Name: key,\n Value: value,\n }));\n}\n/**\n * Transforms an array of AttributeType objects into a user attributes object.\n *\n * @param attributes - an array of AttributeType objects.\n * @returns AuthUserAttributes object.\n */\nexport function toAuthUserAttribute(attributes) {\n const userAttributes = {};\n attributes?.forEach(attribute => {\n if (attribute.Name)\n userAttributes[attribute.Name] = attribute.Value;\n });\n return userAttributes;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport var AssociateSoftwareTokenException;\n(function (AssociateSoftwareTokenException) {\n AssociateSoftwareTokenException[\"ConcurrentModificationException\"] = \"ConcurrentModificationException\";\n AssociateSoftwareTokenException[\"ForbiddenException\"] = \"ForbiddenException\";\n AssociateSoftwareTokenException[\"InternalErrorException\"] = \"InternalErrorException\";\n AssociateSoftwareTokenException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n AssociateSoftwareTokenException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n AssociateSoftwareTokenException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n AssociateSoftwareTokenException[\"SoftwareTokenMFANotFoundException\"] = \"SoftwareTokenMFANotFoundException\";\n})(AssociateSoftwareTokenException || (AssociateSoftwareTokenException = {}));\nexport var ChangePasswordException;\n(function (ChangePasswordException) {\n ChangePasswordException[\"ForbiddenException\"] = \"ForbiddenException\";\n ChangePasswordException[\"InternalErrorException\"] = \"InternalErrorException\";\n ChangePasswordException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ChangePasswordException[\"InvalidPasswordException\"] = \"InvalidPasswordException\";\n ChangePasswordException[\"LimitExceededException\"] = \"LimitExceededException\";\n ChangePasswordException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ChangePasswordException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n ChangePasswordException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ChangePasswordException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ChangePasswordException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n ChangePasswordException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ChangePasswordException || (ChangePasswordException = {}));\nexport var ConfirmDeviceException;\n(function (ConfirmDeviceException) {\n ConfirmDeviceException[\"ForbiddenException\"] = \"ForbiddenException\";\n ConfirmDeviceException[\"InternalErrorException\"] = \"InternalErrorException\";\n ConfirmDeviceException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n ConfirmDeviceException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ConfirmDeviceException[\"InvalidPasswordException\"] = \"InvalidPasswordException\";\n ConfirmDeviceException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n ConfirmDeviceException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ConfirmDeviceException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n ConfirmDeviceException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ConfirmDeviceException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ConfirmDeviceException[\"UsernameExistsException\"] = \"UsernameExistsException\";\n ConfirmDeviceException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n ConfirmDeviceException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ConfirmDeviceException || (ConfirmDeviceException = {}));\nexport var ConfirmForgotPasswordException;\n(function (ConfirmForgotPasswordException) {\n ConfirmForgotPasswordException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n ConfirmForgotPasswordException[\"ExpiredCodeException\"] = \"ExpiredCodeException\";\n ConfirmForgotPasswordException[\"ForbiddenException\"] = \"ForbiddenException\";\n ConfirmForgotPasswordException[\"InternalErrorException\"] = \"InternalErrorException\";\n ConfirmForgotPasswordException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n ConfirmForgotPasswordException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ConfirmForgotPasswordException[\"InvalidPasswordException\"] = \"InvalidPasswordException\";\n ConfirmForgotPasswordException[\"LimitExceededException\"] = \"LimitExceededException\";\n ConfirmForgotPasswordException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ConfirmForgotPasswordException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ConfirmForgotPasswordException[\"TooManyFailedAttemptsException\"] = \"TooManyFailedAttemptsException\";\n ConfirmForgotPasswordException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ConfirmForgotPasswordException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n ConfirmForgotPasswordException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n ConfirmForgotPasswordException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n ConfirmForgotPasswordException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ConfirmForgotPasswordException || (ConfirmForgotPasswordException = {}));\nexport var ConfirmSignUpException;\n(function (ConfirmSignUpException) {\n ConfirmSignUpException[\"AliasExistsException\"] = \"AliasExistsException\";\n ConfirmSignUpException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n ConfirmSignUpException[\"ExpiredCodeException\"] = \"ExpiredCodeException\";\n ConfirmSignUpException[\"ForbiddenException\"] = \"ForbiddenException\";\n ConfirmSignUpException[\"InternalErrorException\"] = \"InternalErrorException\";\n ConfirmSignUpException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n ConfirmSignUpException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ConfirmSignUpException[\"LimitExceededException\"] = \"LimitExceededException\";\n ConfirmSignUpException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ConfirmSignUpException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ConfirmSignUpException[\"TooManyFailedAttemptsException\"] = \"TooManyFailedAttemptsException\";\n ConfirmSignUpException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ConfirmSignUpException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n ConfirmSignUpException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n ConfirmSignUpException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ConfirmSignUpException || (ConfirmSignUpException = {}));\nexport var DeleteUserAttributesException;\n(function (DeleteUserAttributesException) {\n DeleteUserAttributesException[\"ForbiddenException\"] = \"ForbiddenException\";\n DeleteUserAttributesException[\"InternalErrorException\"] = \"InternalErrorException\";\n DeleteUserAttributesException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n DeleteUserAttributesException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n DeleteUserAttributesException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n DeleteUserAttributesException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n DeleteUserAttributesException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n DeleteUserAttributesException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n DeleteUserAttributesException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(DeleteUserAttributesException || (DeleteUserAttributesException = {}));\nexport var DeleteUserException;\n(function (DeleteUserException) {\n DeleteUserException[\"ForbiddenException\"] = \"ForbiddenException\";\n DeleteUserException[\"InternalErrorException\"] = \"InternalErrorException\";\n DeleteUserException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n DeleteUserException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n DeleteUserException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n DeleteUserException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n DeleteUserException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n DeleteUserException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n DeleteUserException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(DeleteUserException || (DeleteUserException = {}));\nexport var ForgetDeviceException;\n(function (ForgetDeviceException) {\n ForgetDeviceException[\"ForbiddenException\"] = \"ForbiddenException\";\n ForgetDeviceException[\"InternalErrorException\"] = \"InternalErrorException\";\n ForgetDeviceException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ForgetDeviceException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n ForgetDeviceException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ForgetDeviceException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n ForgetDeviceException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ForgetDeviceException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ForgetDeviceException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n ForgetDeviceException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ForgetDeviceException || (ForgetDeviceException = {}));\nexport var ForgotPasswordException;\n(function (ForgotPasswordException) {\n ForgotPasswordException[\"CodeDeliveryFailureException\"] = \"CodeDeliveryFailureException\";\n ForgotPasswordException[\"ForbiddenException\"] = \"ForbiddenException\";\n ForgotPasswordException[\"InternalErrorException\"] = \"InternalErrorException\";\n ForgotPasswordException[\"InvalidEmailRoleAccessPolicyException\"] = \"InvalidEmailRoleAccessPolicyException\";\n ForgotPasswordException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n ForgotPasswordException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ForgotPasswordException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n ForgotPasswordException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n ForgotPasswordException[\"LimitExceededException\"] = \"LimitExceededException\";\n ForgotPasswordException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ForgotPasswordException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ForgotPasswordException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ForgotPasswordException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n ForgotPasswordException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n ForgotPasswordException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ForgotPasswordException || (ForgotPasswordException = {}));\nexport var GetUserException;\n(function (GetUserException) {\n GetUserException[\"ForbiddenException\"] = \"ForbiddenException\";\n GetUserException[\"InternalErrorException\"] = \"InternalErrorException\";\n GetUserException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n GetUserException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n GetUserException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n GetUserException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n GetUserException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n GetUserException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n GetUserException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(GetUserException || (GetUserException = {}));\nexport var GetIdException;\n(function (GetIdException) {\n GetIdException[\"ExternalServiceException\"] = \"ExternalServiceException\";\n GetIdException[\"InternalErrorException\"] = \"InternalErrorException\";\n GetIdException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n GetIdException[\"LimitExceededException\"] = \"LimitExceededException\";\n GetIdException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n GetIdException[\"ResourceConflictException\"] = \"ResourceConflictException\";\n GetIdException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n GetIdException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n})(GetIdException || (GetIdException = {}));\nexport var GetCredentialsForIdentityException;\n(function (GetCredentialsForIdentityException) {\n GetCredentialsForIdentityException[\"ExternalServiceException\"] = \"ExternalServiceException\";\n GetCredentialsForIdentityException[\"InternalErrorException\"] = \"InternalErrorException\";\n GetCredentialsForIdentityException[\"InvalidIdentityPoolConfigurationException\"] = \"InvalidIdentityPoolConfigurationException\";\n GetCredentialsForIdentityException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n GetCredentialsForIdentityException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n GetCredentialsForIdentityException[\"ResourceConflictException\"] = \"ResourceConflictException\";\n GetCredentialsForIdentityException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n GetCredentialsForIdentityException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n})(GetCredentialsForIdentityException || (GetCredentialsForIdentityException = {}));\nexport var GetUserAttributeVerificationException;\n(function (GetUserAttributeVerificationException) {\n GetUserAttributeVerificationException[\"CodeDeliveryFailureException\"] = \"CodeDeliveryFailureException\";\n GetUserAttributeVerificationException[\"ForbiddenException\"] = \"ForbiddenException\";\n GetUserAttributeVerificationException[\"InternalErrorException\"] = \"InternalErrorException\";\n GetUserAttributeVerificationException[\"InvalidEmailRoleAccessPolicyException\"] = \"InvalidEmailRoleAccessPolicyException\";\n GetUserAttributeVerificationException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n GetUserAttributeVerificationException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n GetUserAttributeVerificationException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n GetUserAttributeVerificationException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n GetUserAttributeVerificationException[\"LimitExceededException\"] = \"LimitExceededException\";\n GetUserAttributeVerificationException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n GetUserAttributeVerificationException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n GetUserAttributeVerificationException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n GetUserAttributeVerificationException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n GetUserAttributeVerificationException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n GetUserAttributeVerificationException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n GetUserAttributeVerificationException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n GetUserAttributeVerificationException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(GetUserAttributeVerificationException || (GetUserAttributeVerificationException = {}));\nexport var GlobalSignOutException;\n(function (GlobalSignOutException) {\n GlobalSignOutException[\"ForbiddenException\"] = \"ForbiddenException\";\n GlobalSignOutException[\"InternalErrorException\"] = \"InternalErrorException\";\n GlobalSignOutException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n GlobalSignOutException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n GlobalSignOutException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n GlobalSignOutException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n GlobalSignOutException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n GlobalSignOutException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n})(GlobalSignOutException || (GlobalSignOutException = {}));\nexport var InitiateAuthException;\n(function (InitiateAuthException) {\n InitiateAuthException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n InitiateAuthException[\"ForbiddenException\"] = \"ForbiddenException\";\n InitiateAuthException[\"InternalErrorException\"] = \"InternalErrorException\";\n InitiateAuthException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n InitiateAuthException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n InitiateAuthException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n InitiateAuthException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n InitiateAuthException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n InitiateAuthException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n InitiateAuthException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n InitiateAuthException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n InitiateAuthException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n InitiateAuthException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n InitiateAuthException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n InitiateAuthException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(InitiateAuthException || (InitiateAuthException = {}));\nexport var ResendConfirmationException;\n(function (ResendConfirmationException) {\n ResendConfirmationException[\"CodeDeliveryFailureException\"] = \"CodeDeliveryFailureException\";\n ResendConfirmationException[\"ForbiddenException\"] = \"ForbiddenException\";\n ResendConfirmationException[\"InternalErrorException\"] = \"InternalErrorException\";\n ResendConfirmationException[\"InvalidEmailRoleAccessPolicyException\"] = \"InvalidEmailRoleAccessPolicyException\";\n ResendConfirmationException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n ResendConfirmationException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ResendConfirmationException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n ResendConfirmationException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n ResendConfirmationException[\"LimitExceededException\"] = \"LimitExceededException\";\n ResendConfirmationException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ResendConfirmationException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ResendConfirmationException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ResendConfirmationException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n ResendConfirmationException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n ResendConfirmationException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ResendConfirmationException || (ResendConfirmationException = {}));\nexport var RespondToAuthChallengeException;\n(function (RespondToAuthChallengeException) {\n RespondToAuthChallengeException[\"AliasExistsException\"] = \"AliasExistsException\";\n RespondToAuthChallengeException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n RespondToAuthChallengeException[\"ExpiredCodeException\"] = \"ExpiredCodeException\";\n RespondToAuthChallengeException[\"ForbiddenException\"] = \"ForbiddenException\";\n RespondToAuthChallengeException[\"InternalErrorException\"] = \"InternalErrorException\";\n RespondToAuthChallengeException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n RespondToAuthChallengeException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n RespondToAuthChallengeException[\"InvalidPasswordException\"] = \"InvalidPasswordException\";\n RespondToAuthChallengeException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n RespondToAuthChallengeException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n RespondToAuthChallengeException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n RespondToAuthChallengeException[\"MFAMethodNotFoundException\"] = \"MFAMethodNotFoundException\";\n RespondToAuthChallengeException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n RespondToAuthChallengeException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n RespondToAuthChallengeException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n RespondToAuthChallengeException[\"SoftwareTokenMFANotFoundException\"] = \"SoftwareTokenMFANotFoundException\";\n RespondToAuthChallengeException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n RespondToAuthChallengeException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n RespondToAuthChallengeException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n RespondToAuthChallengeException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n RespondToAuthChallengeException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(RespondToAuthChallengeException || (RespondToAuthChallengeException = {}));\nexport var SetUserMFAPreferenceException;\n(function (SetUserMFAPreferenceException) {\n SetUserMFAPreferenceException[\"ForbiddenException\"] = \"ForbiddenException\";\n SetUserMFAPreferenceException[\"InternalErrorException\"] = \"InternalErrorException\";\n SetUserMFAPreferenceException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n SetUserMFAPreferenceException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n SetUserMFAPreferenceException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n SetUserMFAPreferenceException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n SetUserMFAPreferenceException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n SetUserMFAPreferenceException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(SetUserMFAPreferenceException || (SetUserMFAPreferenceException = {}));\nexport var SignUpException;\n(function (SignUpException) {\n SignUpException[\"CodeDeliveryFailureException\"] = \"CodeDeliveryFailureException\";\n SignUpException[\"InternalErrorException\"] = \"InternalErrorException\";\n SignUpException[\"InvalidEmailRoleAccessPolicyException\"] = \"InvalidEmailRoleAccessPolicyException\";\n SignUpException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n SignUpException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n SignUpException[\"InvalidPasswordException\"] = \"InvalidPasswordException\";\n SignUpException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n SignUpException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n SignUpException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n SignUpException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n SignUpException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n SignUpException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n SignUpException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n SignUpException[\"UsernameExistsException\"] = \"UsernameExistsException\";\n})(SignUpException || (SignUpException = {}));\nexport var UpdateUserAttributesException;\n(function (UpdateUserAttributesException) {\n UpdateUserAttributesException[\"AliasExistsException\"] = \"AliasExistsException\";\n UpdateUserAttributesException[\"CodeDeliveryFailureException\"] = \"CodeDeliveryFailureException\";\n UpdateUserAttributesException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n UpdateUserAttributesException[\"ExpiredCodeException\"] = \"ExpiredCodeException\";\n UpdateUserAttributesException[\"ForbiddenException\"] = \"ForbiddenException\";\n UpdateUserAttributesException[\"InternalErrorException\"] = \"InternalErrorException\";\n UpdateUserAttributesException[\"InvalidEmailRoleAccessPolicyException\"] = \"InvalidEmailRoleAccessPolicyException\";\n UpdateUserAttributesException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n UpdateUserAttributesException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n UpdateUserAttributesException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n UpdateUserAttributesException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n UpdateUserAttributesException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n UpdateUserAttributesException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n UpdateUserAttributesException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n UpdateUserAttributesException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n UpdateUserAttributesException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n UpdateUserAttributesException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n UpdateUserAttributesException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n UpdateUserAttributesException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(UpdateUserAttributesException || (UpdateUserAttributesException = {}));\nexport var VerifySoftwareTokenException;\n(function (VerifySoftwareTokenException) {\n VerifySoftwareTokenException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n VerifySoftwareTokenException[\"EnableSoftwareTokenMFAException\"] = \"EnableSoftwareTokenMFAException\";\n VerifySoftwareTokenException[\"ForbiddenException\"] = \"ForbiddenException\";\n VerifySoftwareTokenException[\"InternalErrorException\"] = \"InternalErrorException\";\n VerifySoftwareTokenException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n VerifySoftwareTokenException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n VerifySoftwareTokenException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n VerifySoftwareTokenException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n VerifySoftwareTokenException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n VerifySoftwareTokenException[\"SoftwareTokenMFANotFoundException\"] = \"SoftwareTokenMFANotFoundException\";\n VerifySoftwareTokenException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n VerifySoftwareTokenException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n VerifySoftwareTokenException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(VerifySoftwareTokenException || (VerifySoftwareTokenException = {}));\nexport var VerifyUserAttributeException;\n(function (VerifyUserAttributeException) {\n VerifyUserAttributeException[\"AliasExistsException\"] = \"AliasExistsException\";\n VerifyUserAttributeException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n VerifyUserAttributeException[\"ExpiredCodeException\"] = \"ExpiredCodeException\";\n VerifyUserAttributeException[\"ForbiddenException\"] = \"ForbiddenException\";\n VerifyUserAttributeException[\"InternalErrorException\"] = \"InternalErrorException\";\n VerifyUserAttributeException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n VerifyUserAttributeException[\"LimitExceededException\"] = \"LimitExceededException\";\n VerifyUserAttributeException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n VerifyUserAttributeException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n VerifyUserAttributeException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n VerifyUserAttributeException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n VerifyUserAttributeException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n VerifyUserAttributeException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(VerifyUserAttributeException || (VerifyUserAttributeException = {}));\nexport var UpdateDeviceStatusException;\n(function (UpdateDeviceStatusException) {\n UpdateDeviceStatusException[\"ForbiddenException\"] = \"ForbiddenException\";\n UpdateDeviceStatusException[\"InternalErrorException\"] = \"InternalErrorException\";\n UpdateDeviceStatusException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n UpdateDeviceStatusException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n UpdateDeviceStatusException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n UpdateDeviceStatusException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n UpdateDeviceStatusException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n UpdateDeviceStatusException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n UpdateDeviceStatusException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n UpdateDeviceStatusException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(UpdateDeviceStatusException || (UpdateDeviceStatusException = {}));\nexport var ListDevicesException;\n(function (ListDevicesException) {\n ListDevicesException[\"ForbiddenException\"] = \"ForbiddenException\";\n ListDevicesException[\"InternalErrorException\"] = \"InternalErrorException\";\n ListDevicesException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ListDevicesException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n ListDevicesException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ListDevicesException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n ListDevicesException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ListDevicesException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ListDevicesException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n ListDevicesException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ListDevicesException || (ListDevicesException = {}));\nexport const SETUP_TOTP_EXCEPTION = 'SetUpTOTPException';\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthError } from './AuthError';\nexport const USER_UNAUTHENTICATED_EXCEPTION = 'UserUnAuthenticatedException';\nexport const USER_ALREADY_AUTHENTICATED_EXCEPTION = 'UserAlreadyAuthenticatedException';\nexport const DEVICE_METADATA_NOT_FOUND_EXCEPTION = 'DeviceMetadataNotFoundException';\nexport const AUTO_SIGN_IN_EXCEPTION = 'AutoSignInException';\nexport const INVALID_REDIRECT_EXCEPTION = 'InvalidRedirectException';\nexport const INVALID_APP_SCHEME_EXCEPTION = 'InvalidAppSchemeException';\nexport const INVALID_PREFERRED_REDIRECT_EXCEPTION = 'InvalidPreferredRedirectUrlException';\nexport const invalidRedirectException = new AuthError({\n name: INVALID_REDIRECT_EXCEPTION,\n message: 'signInRedirect or signOutRedirect had an invalid format or was not found.',\n recoverySuggestion: 'Please make sure the signIn/Out redirect in your oauth config is valid.',\n});\nexport const invalidAppSchemeException = new AuthError({\n name: INVALID_APP_SCHEME_EXCEPTION,\n message: 'A valid non-http app scheme was not found in the config.',\n recoverySuggestion: 'Please make sure a valid custom app scheme is present in the config.',\n});\nexport const invalidPreferredRedirectUrlException = new AuthError({\n name: INVALID_PREFERRED_REDIRECT_EXCEPTION,\n message: 'The given preferredRedirectUrl does not match any items in the redirectSignOutUrls array from the config.',\n recoverySuggestion: 'Please make sure a matching preferredRedirectUrl is provided.',\n});\nexport const INVALID_ORIGIN_EXCEPTION = 'InvalidOriginException';\nexport const invalidOriginException = new AuthError({\n name: INVALID_ORIGIN_EXCEPTION,\n message: 'redirect is coming from a different origin. The oauth flow needs to be initiated from the same origin',\n recoverySuggestion: 'Please call signInWithRedirect from the same origin.',\n});\nexport const OAUTH_SIGNOUT_EXCEPTION = 'OAuthSignOutException';\nexport const TOKEN_REFRESH_EXCEPTION = 'TokenRefreshException';\nexport const UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION = 'UnexpectedSignInInterruptionException';\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthError } from '../../../errors/AuthError';\nimport { DEVICE_METADATA_NOT_FOUND_EXCEPTION, TOKEN_REFRESH_EXCEPTION, USER_UNAUTHENTICATED_EXCEPTION, } from '../../../errors/constants';\nexport function isTypeUserPoolConfig(authConfig) {\n if (authConfig &&\n authConfig.Cognito.userPoolId &&\n authConfig.Cognito.userPoolClientId) {\n return true;\n }\n return false;\n}\nexport function assertAuthTokens(tokens) {\n if (!tokens || !tokens.accessToken) {\n throw new AuthError({\n name: USER_UNAUTHENTICATED_EXCEPTION,\n message: 'User needs to be authenticated to call this API.',\n recoverySuggestion: 'Sign in before calling this API again.',\n });\n }\n}\nexport function assertIdTokenInAuthTokens(tokens) {\n if (!tokens || !tokens.idToken) {\n throw new AuthError({\n name: USER_UNAUTHENTICATED_EXCEPTION,\n message: 'User needs to be authenticated to call this API.',\n recoverySuggestion: 'Sign in before calling this API again.',\n });\n }\n}\nexport const oAuthTokenRefreshException = new AuthError({\n name: TOKEN_REFRESH_EXCEPTION,\n message: `Token refresh is not supported when authenticated with the 'implicit grant' (token) oauth flow. \n\tPlease change your oauth configuration to use 'code grant' flow.`,\n recoverySuggestion: `Please logout and change your Amplify configuration to use \"code grant\" flow. \n\tE.g { responseType: 'code' }`,\n});\nexport const tokenRefreshException = new AuthError({\n name: USER_UNAUTHENTICATED_EXCEPTION,\n message: 'User needs to be authenticated to call this API.',\n recoverySuggestion: 'Sign in before calling this API again.',\n});\nexport function assertAuthTokensWithRefreshToken(tokens) {\n if (isAuthenticatedWithImplicitOauthFlow(tokens)) {\n throw oAuthTokenRefreshException;\n }\n if (!isAuthenticatedWithRefreshToken(tokens)) {\n throw tokenRefreshException;\n }\n}\nexport function assertDeviceMetadata(deviceMetadata) {\n if (!deviceMetadata ||\n !deviceMetadata.deviceKey ||\n !deviceMetadata.deviceGroupKey ||\n !deviceMetadata.randomPassword) {\n throw new AuthError({\n name: DEVICE_METADATA_NOT_FOUND_EXCEPTION,\n message: 'Either deviceKey, deviceGroupKey or secretPassword were not found during the sign-in process.',\n recoverySuggestion: 'Make sure to not clear storage after calling the signIn API.',\n });\n }\n}\nexport const OAuthStorageKeys = {\n inflightOAuth: 'inflightOAuth',\n oauthSignIn: 'oauthSignIn',\n oauthPKCE: 'oauthPKCE',\n oauthState: 'oauthState',\n};\nfunction isAuthenticated(tokens) {\n return tokens?.accessToken || tokens?.idToken;\n}\nfunction isAuthenticatedWithRefreshToken(tokens) {\n return isAuthenticated(tokens) && tokens?.refreshToken;\n}\nfunction isAuthenticatedWithImplicitOauthFlow(tokens) {\n return isAuthenticated(tokens) && !tokens?.refreshToken;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { assertAuthTokens } from '../../utils/types';\nexport const getCurrentUser = async (amplify) => {\n const authConfig = amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const tokens = await amplify.Auth.getTokens({ forceRefresh: false });\n assertAuthTokens(tokens);\n const { 'cognito:username': username, sub } = tokens.idToken?.payload ?? {};\n const authUser = {\n username: username,\n userId: sub,\n };\n const signInDetails = getSignInDetailsFromTokens(tokens);\n if (signInDetails) {\n authUser.signInDetails = signInDetails;\n }\n return authUser;\n};\nfunction getSignInDetailsFromTokens(tokens) {\n return tokens?.signInDetails;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { getCurrentUser as getCurrentUserInternal } from './internal/getCurrentUser';\n/**\n * Gets the current user from the idToken.\n *\n * @param input - The GetCurrentUserInput object.\n * @returns GetCurrentUserOutput\n * @throws - {@link InitiateAuthException} - Thrown when the service fails to refresh the tokens.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport const getCurrentUser = async () => {\n return getCurrentUserInternal(Amplify);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Category, getAmplifyUserAgent, } from '@aws-amplify/core/internals/utils';\nexport const getAuthUserAgentValue = (action, customUserAgentDetails) => getAmplifyUserAgent({\n category: Category.Auth,\n action,\n ...customUserAgentDetails,\n});\n","export { composeServiceApi } from './composeServiceApi.mjs';\nexport { composeTransferHandler } from './composeTransferHandler.mjs';\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const createUserPoolSerializer = (operation) => (input, endpoint) => {\n const headers = getSharedHeaders(operation);\n const body = JSON.stringify(input);\n return buildHttpRpcRequest(endpoint, headers, body);\n};\nconst getSharedHeaders = (operation) => ({\n 'content-type': 'application/x-amz-json-1.1',\n 'x-amz-target': `AWSCognitoIdentityProviderService.${operation}`,\n});\nconst buildHttpRpcRequest = ({ url }, headers, body) => ({\n headers,\n url,\n body,\n method: 'POST',\n});\n","export { getDnsSuffix } from './endpoints/getDnsSuffix.mjs';\nexport { fetchTransferHandler } from './handlers/fetch.mjs';\nexport { unauthenticatedHandler } from './handlers/aws/unauthenticated.mjs';\nexport { authenticatedHandler } from './handlers/aws/authenticated.mjs';\nexport { signRequest } from './middleware/signing/signer/signatureV4/signRequest.mjs';\nexport { presignUrl } from './middleware/signing/signer/signatureV4/presignUrl.mjs';\nexport { EMPTY_HASH as EMPTY_SHA256_HASH, UNSIGNED_PAYLOAD } from './middleware/signing/signer/signatureV4/constants.mjs';\nexport { getHashedPayload } from './middleware/signing/signer/signatureV4/utils/getHashedPayload.mjs';\nexport { extendedEncodeURIComponent } from './middleware/signing/utils/extendedEncodeURIComponent.mjs';\nexport { signingMiddlewareFactory } from './middleware/signing/middleware.mjs';\nexport { retryMiddlewareFactory } from './middleware/retry/retryMiddleware.mjs';\nexport { jitteredBackoff } from './middleware/retry/jitteredBackoff.mjs';\nexport { getRetryDecider } from './middleware/retry/defaultRetryDecider.mjs';\nexport { amzSdkInvocationIdHeaderMiddlewareFactory } from './middleware/retry/amzSdkInvocationIdHeaderMiddleware.mjs';\nexport { amzSdkRequestHeaderMiddlewareFactory } from './middleware/retry/amzSdkRequestHeaderMiddleware.mjs';\nexport { userAgentMiddlewareFactory } from './middleware/userAgent/middleware.mjs';\nexport { parseMetadata } from './serde/responseInfo.mjs';\nexport { parseJsonBody, parseJsonError } from './serde/json.mjs';\nexport { withMemoization } from './utils/memoization.mjs';\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AmplifyErrorCode, } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../AuthError';\nexport function assertServiceError(error) {\n if (!error ||\n error.name === 'Error' ||\n error instanceof TypeError) {\n throw new AuthError({\n name: AmplifyErrorCode.Unknown,\n message: 'An unknown error has occurred.',\n underlyingError: error,\n });\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { parseJsonBody, parseJsonError, } from '@aws-amplify/core/internals/aws-client-utils';\nimport { assertServiceError } from '../../../../../../errors/utils/assertServiceError';\nimport { AuthError } from '../../../../../../errors/AuthError';\nexport const createUserPoolDeserializer = () => async (response) => {\n if (response.statusCode >= 300) {\n const error = await parseJsonError(response);\n assertServiceError(error);\n throw new AuthError({\n name: error.name,\n message: error.message,\n metadata: error.$metadata,\n });\n }\n return parseJsonBody(response);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeTransferHandler } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { unauthenticatedHandler, } from '@aws-amplify/core/internals/aws-client-utils';\n/**\n * A Cognito Identity-specific middleware that disables caching for all requests.\n */\nconst disableCacheMiddlewareFactory = () => (next, _) => async function disableCacheMiddleware(request) {\n request.headers['cache-control'] = 'no-store';\n return next(request);\n};\n/**\n * A Cognito Identity-specific transfer handler that does NOT sign requests, and\n * disables caching.\n *\n * @internal\n */\nexport const cognitoUserPoolTransferHandler = composeTransferHandler(unauthenticatedHandler, [disableCacheMiddlewareFactory]);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * The service name used to sign requests if the API requires authentication.\n */\nexport const COGNITO_IDP_SERVICE_NAME = 'cognito-idp';\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { getRetryDecider, jitteredBackoff, parseJsonError, } from '@aws-amplify/core/internals/aws-client-utils';\nimport { getAmplifyUserAgent } from '@aws-amplify/core/internals/utils';\nimport { COGNITO_IDP_SERVICE_NAME } from '../../../constants';\nexport const DEFAULT_SERVICE_CLIENT_API_CONFIG = {\n service: COGNITO_IDP_SERVICE_NAME,\n retryDecider: getRetryDecider(parseJsonError),\n computeDelay: jitteredBackoff,\n get userAgentValue() {\n return getAmplifyUserAgent();\n },\n cache: 'no-store',\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createInitiateAuthClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('InitiateAuth'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createRespondToAuthChallengeClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('RespondToAuthChallenge'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createVerifySoftwareTokenClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('VerifySoftwareToken'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createAssociateSoftwareTokenClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('AssociateSoftwareToken'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { getDnsSuffix, } from '@aws-amplify/core/internals/aws-client-utils';\nimport { AmplifyUrl } from '@aws-amplify/core/internals/utils';\nimport { COGNITO_IDP_SERVICE_NAME } from './constants';\nexport const cognitoUserPoolEndpointResolver = ({ region, }) => ({\n url: new AmplifyUrl(`https://${COGNITO_IDP_SERVICE_NAME}.${region}.${getDnsSuffix(region)}`),\n});\n","import { AmplifyUrl } from '@aws-amplify/core/internals/utils';\nimport { cognitoUserPoolEndpointResolver } from '../../../foundation/cognitoUserPoolEndpointResolver';\nexport const createCognitoUserPoolEndpointResolver = ({ endpointOverride }) => (input) => {\n if (endpointOverride) {\n return { url: new AmplifyUrl(endpointOverride) };\n }\n return cognitoUserPoolEndpointResolver(input);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createGetTokensFromRefreshTokenClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('GetTokensFromRefreshToken'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { assertTokenProviderConfig, deDupeAsyncFunction, decodeJWT, } from '@aws-amplify/core/internals/utils';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { assertAuthTokensWithRefreshToken } from '../utils/types';\nimport { AuthError } from '../../../errors/AuthError';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\nimport { createGetTokensFromRefreshTokenClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nconst refreshAuthTokensFunction = async ({ tokens, authConfig, username, clientMetadata, }) => {\n assertTokenProviderConfig(authConfig?.Cognito);\n const { userPoolId, userPoolClientId, userPoolEndpoint } = authConfig.Cognito;\n const region = getRegionFromUserPoolId(userPoolId);\n assertAuthTokensWithRefreshToken(tokens);\n const getTokensFromRefreshToken = createGetTokensFromRefreshTokenClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { AuthenticationResult } = await getTokensFromRefreshToken({ region }, {\n ClientId: userPoolClientId,\n RefreshToken: tokens.refreshToken,\n DeviceKey: tokens.deviceMetadata?.deviceKey,\n ClientMetadata: clientMetadata,\n });\n const accessToken = decodeJWT(AuthenticationResult?.AccessToken ?? '');\n const idToken = AuthenticationResult?.IdToken\n ? decodeJWT(AuthenticationResult.IdToken)\n : undefined;\n const { iat } = accessToken.payload;\n // This should never happen. If it does, it's a bug from the service.\n if (!iat) {\n throw new AuthError({\n name: 'iatNotFoundException',\n message: 'iat not found in access token',\n });\n }\n const clockDrift = iat * 1000 - new Date().getTime();\n return {\n accessToken,\n idToken,\n clockDrift,\n refreshToken: AuthenticationResult?.RefreshToken ?? tokens.refreshToken,\n username,\n };\n};\nexport const refreshAuthTokens = deDupeAsyncFunction(refreshAuthTokensFunction);\nexport const refreshAuthTokensWithoutDedupe = refreshAuthTokensFunction;\n","export const AuthTokenStorageKeys = {\n accessToken: 'accessToken',\n idToken: 'idToken',\n oidcProvider: 'oidcProvider',\n clockDrift: 'clockDrift',\n refreshToken: 'refreshToken',\n deviceKey: 'deviceKey',\n randomPasswordKey: 'randomPasswordKey',\n deviceGroupKey: 'deviceGroupKey',\n signInDetails: 'signInDetails',\n oauthMetadata: 'oauthMetadata',\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { createAssertionFunction, } from '@aws-amplify/core/internals/utils';\nexport var TokenProviderErrorCode;\n(function (TokenProviderErrorCode) {\n TokenProviderErrorCode[\"InvalidAuthTokens\"] = \"InvalidAuthTokens\";\n})(TokenProviderErrorCode || (TokenProviderErrorCode = {}));\nconst tokenValidationErrorMap = {\n [TokenProviderErrorCode.InvalidAuthTokens]: {\n message: 'Invalid tokens.',\n recoverySuggestion: 'Make sure the tokens are valid.',\n },\n};\nexport const assert = createAssertionFunction(tokenValidationErrorMap);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const AUTH_KEY_PREFIX = 'CognitoIdentityServiceProvider';\n","import { assertTokenProviderConfig, decodeJWT, } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError';\nimport { AuthTokenStorageKeys, } from './types';\nimport { TokenProviderErrorCode, assert } from './errorHelpers';\nimport { AUTH_KEY_PREFIX } from './constants';\nexport class DefaultTokenStore {\n getKeyValueStorage() {\n if (!this.keyValueStorage) {\n throw new AuthError({\n name: 'KeyValueStorageNotFoundException',\n message: 'KeyValueStorage was not found in TokenStore',\n });\n }\n return this.keyValueStorage;\n }\n setKeyValueStorage(keyValueStorage) {\n this.keyValueStorage = keyValueStorage;\n }\n setAuthConfig(authConfig) {\n this.authConfig = authConfig;\n }\n async loadTokens() {\n // TODO(v6): migration logic should be here\n // Reading V5 tokens old format\n try {\n const authKeys = await this.getAuthKeys();\n const accessTokenString = await this.getKeyValueStorage().getItem(authKeys.accessToken);\n if (!accessTokenString) {\n throw new AuthError({\n name: 'NoSessionFoundException',\n message: 'Auth session was not found. Make sure to call signIn.',\n });\n }\n const accessToken = decodeJWT(accessTokenString);\n const itString = await this.getKeyValueStorage().getItem(authKeys.idToken);\n const idToken = itString ? decodeJWT(itString) : undefined;\n const refreshToken = (await this.getKeyValueStorage().getItem(authKeys.refreshToken)) ??\n undefined;\n const clockDriftString = (await this.getKeyValueStorage().getItem(authKeys.clockDrift)) ?? '0';\n const clockDrift = Number.parseInt(clockDriftString);\n const signInDetails = await this.getKeyValueStorage().getItem(authKeys.signInDetails);\n const tokens = {\n accessToken,\n idToken,\n refreshToken,\n deviceMetadata: (await this.getDeviceMetadata()) ?? undefined,\n clockDrift,\n username: await this.getLastAuthUser(),\n };\n if (signInDetails) {\n tokens.signInDetails = JSON.parse(signInDetails);\n }\n return tokens;\n }\n catch (err) {\n return null;\n }\n }\n async storeTokens(tokens) {\n assert(tokens !== undefined, TokenProviderErrorCode.InvalidAuthTokens);\n const lastAuthUser = tokens.username;\n await this.getKeyValueStorage().setItem(this.getLastAuthUserKey(), lastAuthUser);\n const authKeys = await this.getAuthKeys();\n await this.getKeyValueStorage().setItem(authKeys.accessToken, tokens.accessToken.toString());\n if (tokens.idToken) {\n await this.getKeyValueStorage().setItem(authKeys.idToken, tokens.idToken.toString());\n }\n else {\n await this.getKeyValueStorage().removeItem(authKeys.idToken);\n }\n if (tokens.refreshToken) {\n await this.getKeyValueStorage().setItem(authKeys.refreshToken, tokens.refreshToken);\n }\n else {\n await this.getKeyValueStorage().removeItem(authKeys.refreshToken);\n }\n if (tokens.deviceMetadata) {\n if (tokens.deviceMetadata.deviceKey) {\n await this.getKeyValueStorage().setItem(authKeys.deviceKey, tokens.deviceMetadata.deviceKey);\n }\n if (tokens.deviceMetadata.deviceGroupKey) {\n await this.getKeyValueStorage().setItem(authKeys.deviceGroupKey, tokens.deviceMetadata.deviceGroupKey);\n }\n await this.getKeyValueStorage().setItem(authKeys.randomPasswordKey, tokens.deviceMetadata.randomPassword);\n }\n if (tokens.signInDetails) {\n await this.getKeyValueStorage().setItem(authKeys.signInDetails, JSON.stringify(tokens.signInDetails));\n }\n else {\n await this.getKeyValueStorage().removeItem(authKeys.signInDetails);\n }\n await this.getKeyValueStorage().setItem(authKeys.clockDrift, `${tokens.clockDrift}`);\n }\n async clearTokens() {\n const authKeys = await this.getAuthKeys();\n // Not calling clear because it can remove data that is not managed by AuthTokenStore\n await Promise.all([\n this.getKeyValueStorage().removeItem(authKeys.accessToken),\n this.getKeyValueStorage().removeItem(authKeys.idToken),\n this.getKeyValueStorage().removeItem(authKeys.clockDrift),\n this.getKeyValueStorage().removeItem(authKeys.refreshToken),\n this.getKeyValueStorage().removeItem(authKeys.signInDetails),\n this.getKeyValueStorage().removeItem(this.getLastAuthUserKey()),\n this.getKeyValueStorage().removeItem(authKeys.oauthMetadata),\n ]);\n }\n async getDeviceMetadata(username) {\n const authKeys = await this.getAuthKeys(username);\n const deviceKey = await this.getKeyValueStorage().getItem(authKeys.deviceKey);\n const deviceGroupKey = await this.getKeyValueStorage().getItem(authKeys.deviceGroupKey);\n const randomPassword = await this.getKeyValueStorage().getItem(authKeys.randomPasswordKey);\n return randomPassword && deviceGroupKey && deviceKey\n ? {\n deviceKey,\n deviceGroupKey,\n randomPassword,\n }\n : null;\n }\n async clearDeviceMetadata(username) {\n const authKeys = await this.getAuthKeys(username);\n await Promise.all([\n this.getKeyValueStorage().removeItem(authKeys.deviceKey),\n this.getKeyValueStorage().removeItem(authKeys.deviceGroupKey),\n this.getKeyValueStorage().removeItem(authKeys.randomPasswordKey),\n ]);\n }\n async getAuthKeys(username) {\n assertTokenProviderConfig(this.authConfig?.Cognito);\n const lastAuthUser = username ?? (await this.getLastAuthUser());\n return createKeysForAuthStorage(AUTH_KEY_PREFIX, `${this.authConfig.Cognito.userPoolClientId}.${lastAuthUser}`);\n }\n getLastAuthUserKey() {\n assertTokenProviderConfig(this.authConfig?.Cognito);\n const identifier = this.authConfig.Cognito.userPoolClientId;\n return `${AUTH_KEY_PREFIX}.${identifier}.LastAuthUser`;\n }\n async getLastAuthUser() {\n const lastAuthUser = (await this.getKeyValueStorage().getItem(this.getLastAuthUserKey())) ??\n 'username';\n return lastAuthUser;\n }\n async setOAuthMetadata(metadata) {\n const { oauthMetadata: oauthMetadataKey } = await this.getAuthKeys();\n await this.getKeyValueStorage().setItem(oauthMetadataKey, JSON.stringify(metadata));\n }\n async getOAuthMetadata() {\n const { oauthMetadata: oauthMetadataKey } = await this.getAuthKeys();\n const oauthMetadata = await this.getKeyValueStorage().getItem(oauthMetadataKey);\n return oauthMetadata && JSON.parse(oauthMetadata);\n }\n}\nexport const createKeysForAuthStorage = (provider, identifier) => {\n return getAuthStorageKeys(AuthTokenStorageKeys)(`${provider}`, identifier);\n};\nexport function getAuthStorageKeys(authKeys) {\n const keys = Object.values({ ...authKeys });\n return (prefix, identifier) => keys.reduce((acc, authKey) => ({\n ...acc,\n [authKey]: `${prefix}.${identifier}.${authKey}`,\n }), {});\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { getAuthStorageKeys } from '../tokenProvider/TokenStore';\nimport { OAuthStorageKeys } from './types';\nconst V5_HOSTED_UI_KEY = 'amplify-signin-with-hostedUI';\nconst name = 'CognitoIdentityServiceProvider';\nexport class DefaultOAuthStore {\n constructor(keyValueStorage) {\n this.keyValueStorage = keyValueStorage;\n }\n async clearOAuthInflightData() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n await Promise.all([\n this.keyValueStorage.removeItem(authKeys.inflightOAuth),\n this.keyValueStorage.removeItem(authKeys.oauthPKCE),\n this.keyValueStorage.removeItem(authKeys.oauthState),\n ]);\n }\n async clearOAuthData() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n await this.clearOAuthInflightData();\n await this.keyValueStorage.removeItem(V5_HOSTED_UI_KEY); // remove in case a customer migrated an App from v5 to v6\n return this.keyValueStorage.removeItem(authKeys.oauthSignIn);\n }\n loadOAuthState() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n return this.keyValueStorage.getItem(authKeys.oauthState);\n }\n storeOAuthState(state) {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n return this.keyValueStorage.setItem(authKeys.oauthState, state);\n }\n loadPKCE() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n return this.keyValueStorage.getItem(authKeys.oauthPKCE);\n }\n storePKCE(pkce) {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n return this.keyValueStorage.setItem(authKeys.oauthPKCE, pkce);\n }\n setAuthConfig(authConfigParam) {\n this.cognitoConfig = authConfigParam;\n }\n async loadOAuthInFlight() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n return ((await this.keyValueStorage.getItem(authKeys.inflightOAuth)) === 'true');\n }\n async storeOAuthInFlight(inflight) {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n await this.keyValueStorage.setItem(authKeys.inflightOAuth, `${inflight}`);\n }\n async loadOAuthSignIn() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n const isLegacyHostedUISignIn = await this.keyValueStorage.getItem(V5_HOSTED_UI_KEY);\n const [isOAuthSignIn, preferPrivateSession] = (await this.keyValueStorage.getItem(authKeys.oauthSignIn))?.split(',') ??\n [];\n return {\n isOAuthSignIn: isOAuthSignIn === 'true' || isLegacyHostedUISignIn === 'true',\n preferPrivateSession: preferPrivateSession === 'true',\n };\n }\n async storeOAuthSignIn(oauthSignIn, preferPrivateSession = false) {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n await this.keyValueStorage.setItem(authKeys.oauthSignIn, `${oauthSignIn},${preferPrivateSession}`);\n }\n}\nconst createKeysForAuthStorage = (provider, identifier) => {\n return getAuthStorageKeys(OAuthStorageKeys)(provider, identifier);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { defaultStorage } from '@aws-amplify/core';\nimport { DefaultOAuthStore } from '../signInWithRedirectStore';\nexport const oAuthStore = new DefaultOAuthStore(defaultStorage);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst inflightPromises = [];\nexport const addInflightPromise = (resolver) => {\n inflightPromises.push(resolver);\n};\nexport const resolveAndClearInflightPromises = () => {\n while (inflightPromises.length) {\n inflightPromises.pop()?.();\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Hub, } from '@aws-amplify/core';\nimport { AMPLIFY_SYMBOL, assertTokenProviderConfig, isBrowser, isTokenExpired, } from '@aws-amplify/core/internals/utils';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError';\nimport { AuthError } from '../../../errors/AuthError';\nimport { oAuthStore } from '../utils/oauth/oAuthStore';\nimport { addInflightPromise } from '../utils/oauth/inflightPromise';\nexport class TokenOrchestrator {\n constructor() {\n this.waitForInflightOAuth = isBrowser()\n ? async () => {\n if (!(await oAuthStore.loadOAuthInFlight())) {\n return;\n }\n if (this.inflightPromise) {\n return this.inflightPromise;\n }\n // when there is valid oauth config and there is an inflight oauth flow, try\n // to block async calls that require fetching tokens before the oauth flow completes\n // e.g. getCurrentUser, fetchAuthSession etc.\n this.inflightPromise = new Promise((resolve, _reject) => {\n addInflightPromise(resolve);\n });\n return this.inflightPromise;\n }\n : async () => {\n // no-op for non-browser environments\n };\n }\n setAuthConfig(authConfig) {\n oAuthStore.setAuthConfig(authConfig.Cognito);\n this.authConfig = authConfig;\n }\n setTokenRefresher(tokenRefresher) {\n this.tokenRefresher = tokenRefresher;\n }\n setAuthTokenStore(tokenStore) {\n this.tokenStore = tokenStore;\n }\n getTokenStore() {\n if (!this.tokenStore) {\n throw new AuthError({\n name: 'EmptyTokenStoreException',\n message: 'TokenStore not set',\n });\n }\n return this.tokenStore;\n }\n getTokenRefresher() {\n if (!this.tokenRefresher) {\n throw new AuthError({\n name: 'EmptyTokenRefresherException',\n message: 'TokenRefresher not set',\n });\n }\n return this.tokenRefresher;\n }\n setClientMetadataProvider(clientMetadataProvider) {\n this.clientMetadataProvider = clientMetadataProvider;\n }\n async getTokens(options) {\n let tokens;\n try {\n assertTokenProviderConfig(this.authConfig?.Cognito);\n }\n catch (_err) {\n // Token provider not configured\n return null;\n }\n await this.waitForInflightOAuth();\n this.inflightPromise = undefined;\n tokens = await this.getTokenStore().loadTokens();\n const username = await this.getTokenStore().getLastAuthUser();\n if (tokens === null) {\n return null;\n }\n const idTokenExpired = !!tokens?.idToken &&\n isTokenExpired({\n expiresAt: (tokens.idToken?.payload?.exp ?? 0) * 1000,\n clockDrift: tokens.clockDrift ?? 0,\n });\n const accessTokenExpired = isTokenExpired({\n expiresAt: (tokens.accessToken?.payload?.exp ?? 0) * 1000,\n clockDrift: tokens.clockDrift ?? 0,\n });\n if (options?.forceRefresh || idTokenExpired || accessTokenExpired) {\n tokens = await this.refreshTokens({\n tokens,\n username,\n clientMetadata: options?.clientMetadata ?? (await this.clientMetadataProvider?.()),\n });\n if (tokens === null) {\n return null;\n }\n }\n return {\n accessToken: tokens?.accessToken,\n idToken: tokens?.idToken,\n signInDetails: tokens?.signInDetails,\n };\n }\n async refreshTokens({ tokens, username, clientMetadata, }) {\n try {\n const { signInDetails } = tokens;\n const newTokens = await this.getTokenRefresher()({\n tokens,\n authConfig: this.authConfig,\n username,\n clientMetadata,\n });\n newTokens.signInDetails = signInDetails;\n await this.setTokens({ tokens: newTokens });\n Hub.dispatch('auth', { event: 'tokenRefresh' }, 'Auth', AMPLIFY_SYMBOL);\n return newTokens;\n }\n catch (err) {\n return this.handleErrors(err);\n }\n }\n handleErrors(err) {\n assertServiceError(err);\n // Only clear tokens for definitive authentication failures\n // Do NOT clear tokens for transient errors like service issues, rate limits, etc.\n const shouldClearTokens = this.isAuthenticationError(err);\n if (shouldClearTokens) {\n this.clearTokens();\n }\n Hub.dispatch('auth', {\n event: 'tokenRefresh_failure',\n data: { error: err },\n }, 'Auth', AMPLIFY_SYMBOL);\n if (err.name.startsWith('NotAuthorizedException')) {\n return null;\n }\n throw err;\n }\n isAuthenticationError(err) {\n // Only clear tokens for errors that definitively indicate the tokens are invalid\n // and re-authentication is required. All other errors (service errors, rate limits, etc.)\n // should preserve the tokens to allow for retry.\n // See: https://github.com/aws-amplify/amplify-js/issues/14534\n const authErrorNames = [\n 'NotAuthorizedException', // Refresh token is expired or invalid\n 'TokenRevokedException', // Token was revoked by admin\n 'UserNotFoundException', // User no longer exists\n 'PasswordResetRequiredException', // User must reset password\n 'UserNotConfirmedException', // User account is not confirmed\n 'RefreshTokenReuseException', // Refresh token invalidated by rotation\n ];\n return authErrorNames.some(errorName => err?.name?.startsWith?.(errorName));\n }\n async setTokens({ tokens }) {\n return this.getTokenStore().storeTokens(tokens);\n }\n async clearTokens() {\n return this.getTokenStore().clearTokens();\n }\n getDeviceMetadata(username) {\n return this.getTokenStore().getDeviceMetadata(username);\n }\n clearDeviceMetadata(username) {\n return this.getTokenStore().clearDeviceMetadata(username);\n }\n setOAuthMetadata(metadata) {\n return this.getTokenStore().setOAuthMetadata(metadata);\n }\n getOAuthMetadata() {\n return this.getTokenStore().getOAuthMetadata();\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { defaultStorage, } from '@aws-amplify/core';\nimport { refreshAuthTokens } from '../utils/refreshAuthTokens';\nimport { DefaultTokenStore } from './TokenStore';\nimport { TokenOrchestrator } from './TokenOrchestrator';\nexport class CognitoUserPoolsTokenProvider {\n constructor() {\n this.authTokenStore = new DefaultTokenStore();\n this.authTokenStore.setKeyValueStorage(defaultStorage);\n this.tokenOrchestrator = new TokenOrchestrator();\n this.tokenOrchestrator.setAuthTokenStore(this.authTokenStore);\n this.tokenOrchestrator.setTokenRefresher(refreshAuthTokens);\n }\n getTokens(options = {}) {\n return this.tokenOrchestrator.getTokens(options);\n }\n setKeyValueStorage(keyValueStorage) {\n this.authTokenStore.setKeyValueStorage(keyValueStorage);\n }\n setClientMetadataProvider(clientMetadataProvider) {\n this.tokenOrchestrator.setClientMetadataProvider(clientMetadataProvider);\n }\n setAuthConfig(authConfig) {\n this.authTokenStore.setAuthConfig(authConfig);\n this.tokenOrchestrator.setAuthConfig(authConfig);\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { CognitoUserPoolsTokenProvider } from './CognitoUserPoolsTokenProvider';\n/**\n * The default provider for the JWT access token and ID token issued from the configured Cognito user pool. It manages\n * the refresh and storage of the tokens. It stores the tokens in `window.localStorage` if available, and falls back to\n * in-memory storage if not.\n */\nexport const cognitoUserPoolsTokenProvider = new CognitoUserPoolsTokenProvider();\nexport const { tokenOrchestrator } = cognitoUserPoolsTokenProvider;\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AmplifyError, decodeJWT } from '@aws-amplify/core/internals/utils';\nimport { tokenOrchestrator } from './tokenProvider';\nexport async function cacheCognitoTokens(AuthenticationResult) {\n if (AuthenticationResult.AccessToken) {\n const accessToken = decodeJWT(AuthenticationResult.AccessToken);\n const accessTokenIssuedAtInMillis = (accessToken.payload.iat || 0) * 1000;\n const currentTime = new Date().getTime();\n const clockDrift = accessTokenIssuedAtInMillis > 0\n ? accessTokenIssuedAtInMillis - currentTime\n : 0;\n let idToken;\n let refreshToken;\n let deviceMetadata;\n if (AuthenticationResult.RefreshToken) {\n refreshToken = AuthenticationResult.RefreshToken;\n }\n if (AuthenticationResult.IdToken) {\n idToken = decodeJWT(AuthenticationResult.IdToken);\n }\n if (AuthenticationResult?.NewDeviceMetadata) {\n deviceMetadata = AuthenticationResult.NewDeviceMetadata;\n }\n const tokens = {\n accessToken,\n idToken,\n refreshToken,\n clockDrift,\n deviceMetadata,\n username: AuthenticationResult.username,\n };\n if (AuthenticationResult?.signInDetails) {\n tokens.signInDetails = AuthenticationResult.signInDetails;\n }\n await tokenOrchestrator.setTokens({\n tokens,\n });\n }\n else {\n // This would be a service error\n throw new AmplifyError({\n message: 'Invalid tokens',\n name: 'InvalidTokens',\n recoverySuggestion: 'Check Cognito UserPool settings',\n });\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Hub } from '@aws-amplify/core';\nimport { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';\nimport { getCurrentUser } from '../apis/getCurrentUser';\nimport { UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION, USER_UNAUTHENTICATED_EXCEPTION, } from '../../../errors/constants';\nimport { AuthError } from '../../../errors/AuthError';\nexport const ERROR_MESSAGE = 'Unable to get user session following successful sign-in.';\nexport const dispatchSignedInHubEvent = async () => {\n try {\n Hub.dispatch('auth', {\n event: 'signedIn',\n data: await getCurrentUser(),\n }, 'Auth', AMPLIFY_SYMBOL);\n }\n catch (error) {\n if (error.name === USER_UNAUTHENTICATED_EXCEPTION) {\n throw new AuthError({\n name: UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION,\n message: ERROR_MESSAGE,\n recoverySuggestion: 'This most likely is due to auth tokens not being persisted. If you are using cookie store, please ensure cookies can be correctly set from your server.',\n });\n }\n throw error;\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction defaultState() {\n return {\n active: false,\n };\n}\nconst autoSignInReducer = (state, action) => {\n switch (action.type) {\n case 'SET_USERNAME':\n return {\n ...state,\n username: action.value,\n };\n case 'SET_SESSION':\n return {\n ...state,\n session: action.value,\n };\n case 'START':\n return {\n ...state,\n active: true,\n };\n case 'RESET':\n return defaultState();\n default:\n return state;\n }\n};\nconst createAutoSignInStore = (reducer) => {\n let currentState = reducer(defaultState(), { type: 'RESET' });\n return {\n getState: () => currentState,\n dispatch: action => {\n currentState = reducer(currentState, action);\n },\n };\n};\nexport const autoSignInStore = createAutoSignInStore(autoSignInReducer);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { syncSessionStorage } from '@aws-amplify/core';\n// Minutes until stored session invalidates is defaulted to 3 minutes\n// to maintain parity with Amazon Cognito user pools API behavior\nconst MS_TO_EXPIRY = 3 * 60 * 1000;\nconst TGT_STATE = 'CognitoSignInState';\nconst SIGN_IN_STATE_KEYS = {\n username: `${TGT_STATE}.username`,\n challengeName: `${TGT_STATE}.challengeName`,\n signInSession: `${TGT_STATE}.signInSession`,\n expiry: `${TGT_STATE}.expiry`,\n};\nconst signInReducer = (state, action) => {\n switch (action.type) {\n case 'SET_SIGN_IN_SESSION':\n persistSignInState({ signInSession: action.value });\n return {\n ...state,\n signInSession: action.value,\n };\n case 'SET_SIGN_IN_STATE':\n persistSignInState(action.value);\n return {\n ...action.value,\n };\n case 'SET_CHALLENGE_NAME':\n persistSignInState({ challengeName: action.value });\n return {\n ...state,\n challengeName: action.value,\n };\n case 'SET_USERNAME':\n persistSignInState({ username: action.value });\n return {\n ...state,\n username: action.value,\n };\n case 'SET_INITIAL_STATE':\n return getInitialState();\n case 'RESET_STATE':\n clearPersistedSignInState();\n return getDefaultState();\n // this state is never reachable\n default:\n return state;\n }\n};\nconst isExpired = (expiryDate) => {\n const expiryTimestamp = Number(expiryDate);\n const currentTimestamp = Date.now();\n return expiryTimestamp <= currentTimestamp;\n};\nexport const resetActiveSignInState = () => {\n signInStore.dispatch({ type: 'RESET_STATE' });\n};\nconst clearPersistedSignInState = () => {\n for (const stateKey of Object.values(SIGN_IN_STATE_KEYS)) {\n syncSessionStorage.removeItem(stateKey);\n }\n};\nconst getDefaultState = () => ({\n username: undefined,\n challengeName: undefined,\n signInSession: undefined,\n});\n// Hydrate signInStore from syncSessionStorage if the session has not expired\nconst getInitialState = () => {\n const expiry = syncSessionStorage.getItem(SIGN_IN_STATE_KEYS.expiry);\n if (!expiry || isExpired(expiry)) {\n clearPersistedSignInState();\n return getDefaultState();\n }\n const username = syncSessionStorage.getItem(SIGN_IN_STATE_KEYS.username) ?? undefined;\n const challengeName = (syncSessionStorage.getItem(SIGN_IN_STATE_KEYS.challengeName) ?? undefined);\n const signInSession = syncSessionStorage.getItem(SIGN_IN_STATE_KEYS.signInSession) ?? undefined;\n return {\n username,\n challengeName,\n signInSession,\n };\n};\nconst createStore = reducer => {\n let currentState = reducer(getDefaultState(), { type: 'SET_INITIAL_STATE' });\n return {\n getState: () => currentState,\n dispatch: action => {\n currentState = reducer(currentState, action);\n },\n };\n};\nexport const signInStore = createStore(signInReducer);\nexport function setActiveSignInState(state) {\n signInStore.dispatch({\n type: 'SET_SIGN_IN_STATE',\n value: state,\n });\n}\n// Save local state into Session Storage\nexport const persistSignInState = ({ challengeName, signInSession, username, }) => {\n username && syncSessionStorage.setItem(SIGN_IN_STATE_KEYS.username, username);\n challengeName &&\n syncSessionStorage.setItem(SIGN_IN_STATE_KEYS.challengeName, challengeName);\n if (signInSession) {\n syncSessionStorage.setItem(SIGN_IN_STATE_KEYS.signInSession, signInSession);\n // Updates expiry when session is passed\n syncSessionStorage.setItem(SIGN_IN_STATE_KEYS.expiry, String(Date.now() + MS_TO_EXPIRY));\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const NOT_SUPPORTED_RECOVERY_SUGGESTION = 'Passkeys may not be supported on this device. Ensure your application is running in a secure context (HTTPS) and Web Authentication API is supported.';\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AmplifyError, createAssertionFunction, } from '@aws-amplify/core/internals/utils';\nimport { NOT_SUPPORTED_RECOVERY_SUGGESTION } from './passkeyErrorPlatformConstants';\nexport class PasskeyError extends AmplifyError {\n constructor(params) {\n super(params);\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = PasskeyError;\n Object.setPrototypeOf(this, PasskeyError.prototype);\n }\n}\nexport var PasskeyErrorCode;\n(function (PasskeyErrorCode) {\n // not supported\n PasskeyErrorCode[\"PasskeyNotSupported\"] = \"PasskeyNotSupported\";\n // duplicate passkey\n PasskeyErrorCode[\"PasskeyAlreadyExists\"] = \"PasskeyAlreadyExists\";\n // misconfigurations\n PasskeyErrorCode[\"InvalidPasskeyRegistrationOptions\"] = \"InvalidPasskeyRegistrationOptions\";\n PasskeyErrorCode[\"InvalidPasskeyAuthenticationOptions\"] = \"InvalidPasskeyAuthenticationOptions\";\n PasskeyErrorCode[\"RelyingPartyMismatch\"] = \"RelyingPartyMismatch\";\n // failed credential creation / retrieval\n PasskeyErrorCode[\"PasskeyRegistrationFailed\"] = \"PasskeyRegistrationFailed\";\n PasskeyErrorCode[\"PasskeyRetrievalFailed\"] = \"PasskeyRetrievalFailed\";\n // cancel / aborts\n PasskeyErrorCode[\"PasskeyRegistrationCanceled\"] = \"PasskeyRegistrationCanceled\";\n PasskeyErrorCode[\"PasskeyAuthenticationCanceled\"] = \"PasskeyAuthenticationCanceled\";\n PasskeyErrorCode[\"PasskeyOperationAborted\"] = \"PasskeyOperationAborted\";\n})(PasskeyErrorCode || (PasskeyErrorCode = {}));\nconst ABORT_OR_CANCEL_RECOVERY_SUGGESTION = 'User may have canceled the ceremony or another interruption has occurred. Check underlying error for details.';\nconst MISCONFIGURATION_RECOVERY_SUGGESTION = 'Ensure your user pool is configured to support the WEB_AUTHN as an authentication factor.';\nexport const passkeyErrorMap = {\n [PasskeyErrorCode.PasskeyNotSupported]: {\n message: 'Passkeys may not be supported on this device.',\n recoverySuggestion: NOT_SUPPORTED_RECOVERY_SUGGESTION,\n },\n [PasskeyErrorCode.InvalidPasskeyRegistrationOptions]: {\n message: 'Invalid passkey registration options.',\n recoverySuggestion: MISCONFIGURATION_RECOVERY_SUGGESTION,\n },\n [PasskeyErrorCode.InvalidPasskeyAuthenticationOptions]: {\n message: 'Invalid passkey authentication options.',\n recoverySuggestion: MISCONFIGURATION_RECOVERY_SUGGESTION,\n },\n [PasskeyErrorCode.PasskeyRegistrationFailed]: {\n message: 'Device failed to create passkey.',\n recoverySuggestion: NOT_SUPPORTED_RECOVERY_SUGGESTION,\n },\n [PasskeyErrorCode.PasskeyRetrievalFailed]: {\n message: 'Device failed to retrieve passkey.',\n recoverySuggestion: 'Passkeys may not be available on this device. Try an alternative authentication factor like PASSWORD, EMAIL_OTP, or SMS_OTP.',\n },\n [PasskeyErrorCode.PasskeyAlreadyExists]: {\n message: 'Passkey already exists in authenticator.',\n recoverySuggestion: 'Proceed with existing passkey or try again after deleting the credential.',\n },\n [PasskeyErrorCode.PasskeyRegistrationCanceled]: {\n message: 'Passkey registration ceremony has been canceled.',\n recoverySuggestion: ABORT_OR_CANCEL_RECOVERY_SUGGESTION,\n },\n [PasskeyErrorCode.PasskeyAuthenticationCanceled]: {\n message: 'Passkey authentication ceremony has been canceled.',\n recoverySuggestion: ABORT_OR_CANCEL_RECOVERY_SUGGESTION,\n },\n [PasskeyErrorCode.PasskeyOperationAborted]: {\n message: 'Passkey operation has been aborted.',\n recoverySuggestion: ABORT_OR_CANCEL_RECOVERY_SUGGESTION,\n },\n [PasskeyErrorCode.RelyingPartyMismatch]: {\n message: 'Relying party does not match current domain.',\n recoverySuggestion: 'Ensure relying party identifier matches current domain.',\n },\n};\nexport const assertPasskeyError = createAssertionFunction(passkeyErrorMap, PasskeyError);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AmplifyErrorCode } from '@aws-amplify/core/internals/utils';\nimport { PasskeyError, PasskeyErrorCode, passkeyErrorMap, } from './passkeyError';\n/**\n * Handles Overlapping Passkey Errors Between Registration & Authentication\n * https://w3c.github.io/webauthn/#sctn-create-request-exceptions\n * https://w3c.github.io/webauthn/#sctn-get-request-exceptions\n *\n * @param err unknown\n * @returns PasskeyError\n */\nexport const handlePasskeyError = (err) => {\n if (err instanceof Error) {\n // Passkey Operation Aborted\n if (err.name === 'AbortError') {\n const { message, recoverySuggestion } = passkeyErrorMap[PasskeyErrorCode.PasskeyOperationAborted];\n return new PasskeyError({\n name: PasskeyErrorCode.PasskeyOperationAborted,\n message,\n recoverySuggestion,\n underlyingError: err,\n });\n }\n // Relying Party / Domain Mismatch\n if (err.name === 'SecurityError') {\n const { message, recoverySuggestion } = passkeyErrorMap[PasskeyErrorCode.RelyingPartyMismatch];\n return new PasskeyError({\n name: PasskeyErrorCode.RelyingPartyMismatch,\n message,\n recoverySuggestion,\n underlyingError: err,\n });\n }\n }\n return new PasskeyError({\n name: AmplifyErrorCode.Unknown,\n message: 'An unknown error has occurred.',\n underlyingError: err,\n });\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { handlePasskeyError } from './handlePasskeyError';\nimport { PasskeyError, PasskeyErrorCode, passkeyErrorMap, } from './passkeyError';\n/**\n * Handle Passkey Authentication Errors\n * https://w3c.github.io/webauthn/#sctn-get-request-exceptions\n *\n * @param err unknown\n * @returns PasskeyError\n */\nexport const handlePasskeyAuthenticationError = (err) => {\n if (err instanceof PasskeyError) {\n return err;\n }\n if (err instanceof Error) {\n if (err.name === 'NotAllowedError') {\n const { message, recoverySuggestion } = passkeyErrorMap[PasskeyErrorCode.PasskeyAuthenticationCanceled];\n return new PasskeyError({\n name: PasskeyErrorCode.PasskeyAuthenticationCanceled,\n message,\n recoverySuggestion,\n underlyingError: err,\n });\n }\n }\n return handlePasskeyError(err);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { isBrowser } from '@aws-amplify/core/internals/utils';\n/**\n * Determines if passkey is supported in current context\n * Will return false if executed in non-secure context\n * @returns boolean\n */\nexport const getIsPasskeySupported = () => {\n return (isBrowser() &&\n window.isSecureContext &&\n 'credentials' in navigator &&\n typeof window.PublicKeyCredential === 'function');\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { base64Encoder } from '@aws-amplify/core/internals/utils';\n// https://datatracker.ietf.org/doc/html/rfc4648#page-7\n/**\n * Converts an ArrayBuffer to a base64url encoded string\n * @param buffer - the ArrayBuffer instance of a Uint8Array\n * @returns string - a base64url encoded string\n */\nexport const convertArrayBufferToBase64Url = (buffer) => {\n return base64Encoder.convert(new Uint8Array(buffer), {\n urlSafe: true,\n skipPadding: true,\n });\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { base64Decoder } from '@aws-amplify/core/internals/utils';\n/**\n * Converts a base64url encoded string to an ArrayBuffer\n * @param base64url - a base64url encoded string\n * @returns ArrayBuffer\n */\nexport const convertBase64UrlToArrayBuffer = (base64url) => {\n return Uint8Array.from(base64Decoder.convert(base64url, { urlSafe: true }), x => x.charCodeAt(0)).buffer;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { convertArrayBufferToBase64Url, convertBase64UrlToArrayBuffer, } from '../../../foundation/convert';\n/**\n * Deserializes Public Key Credential Creation Options JSON\n * @param input PasskeyCreateOptionsJson\n * @returns PublicKeyCredentialCreationOptions\n */\nexport const deserializeJsonToPkcCreationOptions = (input) => {\n const userIdBuffer = convertBase64UrlToArrayBuffer(input.user.id);\n const challengeBuffer = convertBase64UrlToArrayBuffer(input.challenge);\n const excludeCredentialsWithBuffer = (input.excludeCredentials || []).map(excludeCred => ({\n ...excludeCred,\n id: convertBase64UrlToArrayBuffer(excludeCred.id),\n }));\n return {\n ...input,\n excludeCredentials: excludeCredentialsWithBuffer,\n challenge: challengeBuffer,\n user: {\n ...input.user,\n id: userIdBuffer,\n },\n };\n};\n/**\n * Serializes a Public Key Credential With Attestation to JSON\n * @param input PasskeyCreateResult\n * @returns PasskeyCreateResultJson\n */\nexport const serializePkcWithAttestationToJson = (input) => {\n const response = {\n clientDataJSON: convertArrayBufferToBase64Url(input.response.clientDataJSON),\n attestationObject: convertArrayBufferToBase64Url(input.response.attestationObject),\n transports: input.response.getTransports(),\n publicKeyAlgorithm: input.response.getPublicKeyAlgorithm(),\n authenticatorData: convertArrayBufferToBase64Url(input.response.getAuthenticatorData()),\n };\n const publicKey = input.response.getPublicKey();\n if (publicKey) {\n response.publicKey = convertArrayBufferToBase64Url(publicKey);\n }\n const resultJson = {\n type: input.type,\n id: input.id,\n rawId: convertArrayBufferToBase64Url(input.rawId),\n clientExtensionResults: input.getClientExtensionResults(),\n response,\n };\n if (input.authenticatorAttachment) {\n resultJson.authenticatorAttachment = input.authenticatorAttachment;\n }\n return resultJson;\n};\n/**\n * Deserializes Public Key Credential Get Options JSON\n * @param input PasskeyGetOptionsJson\n * @returns PublicKeyCredentialRequestOptions\n */\nexport const deserializeJsonToPkcGetOptions = (input) => {\n const challengeBuffer = convertBase64UrlToArrayBuffer(input.challenge);\n const allowedCredentialsWithBuffer = (input.allowCredentials || []).map(allowedCred => ({\n ...allowedCred,\n id: convertBase64UrlToArrayBuffer(allowedCred.id),\n }));\n return {\n ...input,\n challenge: challengeBuffer,\n allowCredentials: allowedCredentialsWithBuffer,\n };\n};\n/**\n * Serializes a Public Key Credential With Attestation to JSON\n * @param input PasskeyGetResult\n * @returns PasskeyGetResultJson\n */\nexport const serializePkcWithAssertionToJson = (input) => {\n const response = {\n clientDataJSON: convertArrayBufferToBase64Url(input.response.clientDataJSON),\n authenticatorData: convertArrayBufferToBase64Url(input.response.authenticatorData),\n signature: convertArrayBufferToBase64Url(input.response.signature),\n };\n if (input.response.userHandle) {\n response.userHandle = convertArrayBufferToBase64Url(input.response.userHandle);\n }\n const resultJson = {\n id: input.id,\n rawId: convertArrayBufferToBase64Url(input.rawId),\n type: input.type,\n clientExtensionResults: input.getClientExtensionResults(),\n response,\n };\n if (input.authenticatorAttachment) {\n resultJson.authenticatorAttachment = input.authenticatorAttachment;\n }\n return resultJson;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { PasskeyErrorCode, assertPasskeyError } from '../errors';\nexport function assertValidCredentialCreationOptions(credentialCreationOptions) {\n assertPasskeyError([\n !!credentialCreationOptions,\n !!credentialCreationOptions?.challenge,\n !!credentialCreationOptions?.user,\n !!credentialCreationOptions?.rp,\n !!credentialCreationOptions?.pubKeyCredParams,\n ].every(Boolean), PasskeyErrorCode.InvalidPasskeyRegistrationOptions);\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { PasskeyErrorCode, assertPasskeyError } from '../errors';\n/**\n * Passkey Create Types\n */\nexport { assertValidCredentialCreationOptions, } from './shared';\nexport function assertCredentialIsPkcWithAuthenticatorAttestationResponse(credential) {\n assertPasskeyError(credential &&\n credential instanceof PublicKeyCredential &&\n credential.response instanceof AuthenticatorAttestationResponse, PasskeyErrorCode.PasskeyRegistrationFailed);\n}\nexport function assertCredentialIsPkcWithAuthenticatorAssertionResponse(credential) {\n assertPasskeyError(credential &&\n credential instanceof PublicKeyCredential &&\n credential.response instanceof AuthenticatorAssertionResponse, PasskeyErrorCode.PasskeyRetrievalFailed);\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { PasskeyErrorCode, assertPasskeyError, handlePasskeyAuthenticationError, } from './errors';\nimport { getIsPasskeySupported } from './getIsPasskeySupported';\nimport { deserializeJsonToPkcGetOptions, serializePkcWithAssertionToJson, } from './serde';\nimport { assertCredentialIsPkcWithAuthenticatorAssertionResponse, } from './types';\nexport const getPasskey = async (input) => {\n try {\n const isPasskeySupported = getIsPasskeySupported();\n assertPasskeyError(isPasskeySupported, PasskeyErrorCode.PasskeyNotSupported);\n const passkeyGetOptions = deserializeJsonToPkcGetOptions(input);\n const credential = await navigator.credentials.get({\n publicKey: passkeyGetOptions,\n });\n assertCredentialIsPkcWithAuthenticatorAssertionResponse(credential);\n return serializePkcWithAssertionToJson(credential);\n }\n catch (err) {\n throw handlePasskeyAuthenticationError(err);\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createConfirmDeviceClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ConfirmDevice'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const textEncoder = {\n convert(input) {\n return new TextEncoder().encode(input);\n },\n};\n","/* eslint-disable */\n// @ts-nocheck -> BigInteger is already a vended utility\n// A small implementation of BigInteger based on http://www-cs-students.stanford.edu/~tjw/jsbn/\n//\n// All public methods have been removed except the following:\n// new BigInteger(a, b) (only radix 2, 4, 8, 16 and 32 supported)\n// toString (only radix 2, 4, 8, 16 and 32 supported)\n// negate\n// abs\n// compareTo\n// bitLength\n// mod\n// equals\n// add\n// subtract\n// multiply\n// divide\n// modPow\nexport default BigInteger;\n/*\n * Copyright (c) 2003-2005 Tom Wu\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY\n * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,\n * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER\n * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF\n * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT\n * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n * In addition, the following condition applies:\n *\n * All redistributions must retain an intact copy of this copyright notice\n * and disclaimer.\n */\n// (public) Constructor\nfunction BigInteger(a, b) {\n if (a != null)\n this.fromString(a, b);\n}\n// return new, unset BigInteger\nfunction nbi() {\n return new BigInteger(null, null);\n}\n// Bits per digit\nlet dbits;\n// JavaScript engine analysis\nconst canary = 0xdeadbeefcafe;\nconst j_lm = (canary & 0xffffff) === 0xefcafe;\n// am: Compute w_j += (x*this_i), propagate carries,\n// c is initial carry, returns final carry.\n// c < 3*dvalue, x < 2*dvalue, this_i < dvalue\n// We need to select the fastest one that works in this environment.\n// am1: use a single mult and divide to get the high bits,\n// max digit bits should be 26 because\n// max internal value = 2*dvalue^2-2*dvalue (< 2^53)\nfunction am1(i, x, w, j, c, n) {\n while (--n >= 0) {\n const v = x * this[i++] + w[j] + c;\n c = Math.floor(v / 0x4000000);\n w[j++] = v & 0x3ffffff;\n }\n return c;\n}\n// am2 avoids a big mult-and-extract completely.\n// Max digit bits should be <= 30 because we do bitwise ops\n// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\nfunction am2(i, x, w, j, c, n) {\n const xl = x & 0x7fff;\n const xh = x >> 15;\n while (--n >= 0) {\n let l = this[i] & 0x7fff;\n const h = this[i++] >> 15;\n const m = xh * l + h * xl;\n l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);\n c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);\n w[j++] = l & 0x3fffffff;\n }\n return c;\n}\n// Alternately, set max digit bits to 28 since some\n// browsers slow down when dealing with 32-bit numbers.\nfunction am3(i, x, w, j, c, n) {\n const xl = x & 0x3fff;\n const xh = x >> 14;\n while (--n >= 0) {\n let l = this[i] & 0x3fff;\n const h = this[i++] >> 14;\n const m = xh * l + h * xl;\n l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;\n c = (l >> 28) + (m >> 14) + xh * h;\n w[j++] = l & 0xfffffff;\n }\n return c;\n}\nconst inBrowser = typeof navigator !== 'undefined';\nif (inBrowser && j_lm && navigator.appName === 'Microsoft Internet Explorer') {\n BigInteger.prototype.am = am2;\n dbits = 30;\n}\nelse if (inBrowser && j_lm && navigator.appName !== 'Netscape') {\n BigInteger.prototype.am = am1;\n dbits = 26;\n}\nelse {\n // Mozilla/Netscape seems to prefer am3\n BigInteger.prototype.am = am3;\n dbits = 28;\n}\nBigInteger.prototype.DB = dbits;\nBigInteger.prototype.DM = (1 << dbits) - 1;\nBigInteger.prototype.DV = 1 << dbits;\nconst BI_FP = 52;\nBigInteger.prototype.FV = Math.pow(2, BI_FP);\nBigInteger.prototype.F1 = BI_FP - dbits;\nBigInteger.prototype.F2 = 2 * dbits - BI_FP;\n// Digit conversions\nconst BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz';\nconst BI_RC = [];\nlet rr, vv;\nrr = '0'.charCodeAt(0);\nfor (vv = 0; vv <= 9; ++vv)\n BI_RC[rr++] = vv;\nrr = 'a'.charCodeAt(0);\nfor (vv = 10; vv < 36; ++vv)\n BI_RC[rr++] = vv;\nrr = 'A'.charCodeAt(0);\nfor (vv = 10; vv < 36; ++vv)\n BI_RC[rr++] = vv;\nfunction int2char(n) {\n return BI_RM.charAt(n);\n}\nfunction intAt(s, i) {\n const c = BI_RC[s.charCodeAt(i)];\n return c == null ? -1 : c;\n}\n// (protected) copy this to r\nfunction bnpCopyTo(r) {\n for (let i = this.t - 1; i >= 0; --i)\n r[i] = this[i];\n r.t = this.t;\n r.s = this.s;\n}\n// (protected) set from integer value x, -DV <= x < DV\nfunction bnpFromInt(x) {\n this.t = 1;\n this.s = x < 0 ? -1 : 0;\n if (x > 0)\n this[0] = x;\n else if (x < -1)\n this[0] = x + this.DV;\n else\n this.t = 0;\n}\n// return bigint initialized to value\nfunction nbv(i) {\n const r = nbi();\n r.fromInt(i);\n return r;\n}\n// (protected) set from string and radix\nfunction bnpFromString(s, b) {\n let k;\n if (b === 16)\n k = 4;\n else if (b === 8)\n k = 3;\n else if (b === 2)\n k = 1;\n else if (b === 32)\n k = 5;\n else if (b === 4)\n k = 2;\n else\n throw new Error('Only radix 2, 4, 8, 16, 32 are supported');\n this.t = 0;\n this.s = 0;\n let i = s.length;\n let mi = false;\n let sh = 0;\n while (--i >= 0) {\n const x = intAt(s, i);\n if (x < 0) {\n if (s.charAt(i) === '-')\n mi = true;\n continue;\n }\n mi = false;\n if (sh === 0)\n this[this.t++] = x;\n else if (sh + k > this.DB) {\n this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;\n this[this.t++] = x >> (this.DB - sh);\n }\n else\n this[this.t - 1] |= x << sh;\n sh += k;\n if (sh >= this.DB)\n sh -= this.DB;\n }\n this.clamp();\n if (mi)\n BigInteger.ZERO.subTo(this, this);\n}\n// (protected) clamp off excess high words\nfunction bnpClamp() {\n const c = this.s & this.DM;\n while (this.t > 0 && this[this.t - 1] == c)\n --this.t;\n}\n// (public) return string representation in given radix\nfunction bnToString(b) {\n if (this.s < 0)\n return '-' + this.negate().toString(b);\n let k;\n if (b == 16)\n k = 4;\n else if (b === 8)\n k = 3;\n else if (b === 2)\n k = 1;\n else if (b === 32)\n k = 5;\n else if (b === 4)\n k = 2;\n else\n throw new Error('Only radix 2, 4, 8, 16, 32 are supported');\n const km = (1 << k) - 1;\n let d;\n let m = false;\n let r = '';\n let i = this.t;\n let p = this.DB - ((i * this.DB) % k);\n if (i-- > 0) {\n if (p < this.DB && (d = this[i] >> p) > 0) {\n m = true;\n r = int2char(d);\n }\n while (i >= 0) {\n if (p < k) {\n d = (this[i] & ((1 << p) - 1)) << (k - p);\n d |= this[--i] >> (p += this.DB - k);\n }\n else {\n d = (this[i] >> (p -= k)) & km;\n if (p <= 0) {\n p += this.DB;\n --i;\n }\n }\n if (d > 0)\n m = true;\n if (m)\n r += int2char(d);\n }\n }\n return m ? r : '0';\n}\n// (public) -this\nfunction bnNegate() {\n const r = nbi();\n BigInteger.ZERO.subTo(this, r);\n return r;\n}\n// (public) |this|\nfunction bnAbs() {\n return this.s < 0 ? this.negate() : this;\n}\n// (public) return + if this > a, - if this < a, 0 if equal\nfunction bnCompareTo(a) {\n let r = this.s - a.s;\n if (r != 0)\n return r;\n let i = this.t;\n r = i - a.t;\n if (r != 0)\n return this.s < 0 ? -r : r;\n while (--i >= 0)\n if ((r = this[i] - a[i]) != 0)\n return r;\n return 0;\n}\n// returns bit length of the integer x\nfunction nbits(x) {\n let r = 1;\n let t;\n if ((t = x >>> 16) !== 0) {\n x = t;\n r += 16;\n }\n if ((t = x >> 8) !== 0) {\n x = t;\n r += 8;\n }\n if ((t = x >> 4) !== 0) {\n x = t;\n r += 4;\n }\n if ((t = x >> 2) !== 0) {\n x = t;\n r += 2;\n }\n if ((t = x >> 1) !== 0) {\n x = t;\n r += 1;\n }\n return r;\n}\n// (public) return the number of bits in \"this\"\nfunction bnBitLength() {\n if (this.t <= 0)\n return 0;\n return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));\n}\n// (protected) r = this << n*DB\nfunction bnpDLShiftTo(n, r) {\n let i;\n for (i = this.t - 1; i >= 0; --i)\n r[i + n] = this[i];\n for (i = n - 1; i >= 0; --i)\n r[i] = 0;\n r.t = this.t + n;\n r.s = this.s;\n}\n// (protected) r = this >> n*DB\nfunction bnpDRShiftTo(n, r) {\n for (let i = n; i < this.t; ++i)\n r[i - n] = this[i];\n r.t = Math.max(this.t - n, 0);\n r.s = this.s;\n}\n// (protected) r = this << n\nfunction bnpLShiftTo(n, r) {\n const bs = n % this.DB;\n const cbs = this.DB - bs;\n const bm = (1 << cbs) - 1;\n const ds = Math.floor(n / this.DB);\n let c = (this.s << bs) & this.DM;\n let i;\n for (i = this.t - 1; i >= 0; --i) {\n r[i + ds + 1] = (this[i] >> cbs) | c;\n c = (this[i] & bm) << bs;\n }\n for (i = ds - 1; i >= 0; --i)\n r[i] = 0;\n r[ds] = c;\n r.t = this.t + ds + 1;\n r.s = this.s;\n r.clamp();\n}\n// (protected) r = this >> n\nfunction bnpRShiftTo(n, r) {\n r.s = this.s;\n const ds = Math.floor(n / this.DB);\n if (ds >= this.t) {\n r.t = 0;\n return;\n }\n const bs = n % this.DB;\n const cbs = this.DB - bs;\n const bm = (1 << bs) - 1;\n r[0] = this[ds] >> bs;\n for (let i = ds + 1; i < this.t; ++i) {\n r[i - ds - 1] |= (this[i] & bm) << cbs;\n r[i - ds] = this[i] >> bs;\n }\n if (bs > 0)\n r[this.t - ds - 1] |= (this.s & bm) << cbs;\n r.t = this.t - ds;\n r.clamp();\n}\n// (protected) r = this - a\nfunction bnpSubTo(a, r) {\n let i = 0;\n let c = 0;\n const m = Math.min(a.t, this.t);\n while (i < m) {\n c += this[i] - a[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n if (a.t < this.t) {\n c -= a.s;\n while (i < this.t) {\n c += this[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n c += this.s;\n }\n else {\n c += this.s;\n while (i < a.t) {\n c -= a[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n c -= a.s;\n }\n r.s = c < 0 ? -1 : 0;\n if (c < -1)\n r[i++] = this.DV + c;\n else if (c > 0)\n r[i++] = c;\n r.t = i;\n r.clamp();\n}\n// (protected) r = this * a, r != this,a (HAC 14.12)\n// \"this\" should be the larger one if appropriate.\nfunction bnpMultiplyTo(a, r) {\n const x = this.abs();\n const y = a.abs();\n let i = x.t;\n r.t = i + y.t;\n while (--i >= 0)\n r[i] = 0;\n for (i = 0; i < y.t; ++i)\n r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);\n r.s = 0;\n r.clamp();\n if (this.s !== a.s)\n BigInteger.ZERO.subTo(r, r);\n}\n// (protected) r = this^2, r != this (HAC 14.16)\nfunction bnpSquareTo(r) {\n const x = this.abs();\n let i = (r.t = 2 * x.t);\n while (--i >= 0)\n r[i] = 0;\n for (i = 0; i < x.t - 1; ++i) {\n const c = x.am(i, x[i], r, 2 * i, 0, 1);\n if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >=\n x.DV) {\n r[i + x.t] -= x.DV;\n r[i + x.t + 1] = 1;\n }\n }\n if (r.t > 0)\n r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);\n r.s = 0;\n r.clamp();\n}\n// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)\n// r != q, this != m. q or r may be null.\nfunction bnpDivRemTo(m, q, r) {\n const pm = m.abs();\n if (pm.t <= 0)\n return;\n const pt = this.abs();\n if (pt.t < pm.t) {\n if (q != null)\n q.fromInt(0);\n if (r != null)\n this.copyTo(r);\n return;\n }\n if (r === null)\n r = nbi();\n const y = nbi();\n const ts = this.s;\n const ms = m.s;\n const nsh = this.DB - nbits(pm[pm.t - 1]);\n // normalize modulus\n if (nsh > 0) {\n pm.lShiftTo(nsh, y);\n pt.lShiftTo(nsh, r);\n }\n else {\n pm.copyTo(y);\n pt.copyTo(r);\n }\n const ys = y.t;\n const y0 = y[ys - 1];\n if (y0 === 0)\n return;\n const yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0);\n const d1 = this.FV / yt;\n const d2 = (1 << this.F1) / yt;\n const e = 1 << this.F2;\n let i = r.t;\n let j = i - ys;\n const t = q === null ? nbi() : q;\n y.dlShiftTo(j, t);\n if (r.compareTo(t) >= 0) {\n r[r.t++] = 1;\n r.subTo(t, r);\n }\n BigInteger.ONE.dlShiftTo(ys, t);\n t.subTo(y, y);\n // \"negative\" y so we can replace sub with am later\n while (y.t < ys)\n y[y.t++] = 0;\n while (--j >= 0) {\n // Estimate quotient digit\n let qd = r[--i] === y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);\n if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) {\n // Try it out\n y.dlShiftTo(j, t);\n r.subTo(t, r);\n while (r[i] < --qd)\n r.subTo(t, r);\n }\n }\n if (q !== null) {\n r.drShiftTo(ys, q);\n if (ts !== ms)\n BigInteger.ZERO.subTo(q, q);\n }\n r.t = ys;\n r.clamp();\n if (nsh > 0)\n r.rShiftTo(nsh, r);\n // Denormalize remainder\n if (ts < 0)\n BigInteger.ZERO.subTo(r, r);\n}\n// (public) this mod a\nfunction bnMod(a) {\n const r = nbi();\n this.abs().divRemTo(a, null, r);\n if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0)\n a.subTo(r, r);\n return r;\n}\n// (protected) return \"-1/this % 2^DB\"; useful for Mont. reduction\n// justification:\n// xy == 1 (mod m)\n// xy = 1+km\n// xy(2-xy) = (1+km)(1-km)\n// x[y(2-xy)] = 1-k^2m^2\n// x[y(2-xy)] == 1 (mod m^2)\n// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\n// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\n// JS multiply \"overflows\" differently from C/C++, so care is needed here.\nfunction bnpInvDigit() {\n if (this.t < 1)\n return 0;\n const x = this[0];\n if ((x & 1) === 0)\n return 0;\n let y = x & 3;\n // y == 1/x mod 2^2\n y = (y * (2 - (x & 0xf) * y)) & 0xf;\n // y == 1/x mod 2^4\n y = (y * (2 - (x & 0xff) * y)) & 0xff;\n // y == 1/x mod 2^8\n y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff;\n // y == 1/x mod 2^16\n // last step - calculate inverse mod DV directly;\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\n y = (y * (2 - ((x * y) % this.DV))) % this.DV;\n // y == 1/x mod 2^dbits\n // we really want the negative inverse, and -DV < y < DV\n return y > 0 ? this.DV - y : -y;\n}\nfunction bnEquals(a) {\n return this.compareTo(a) === 0;\n}\n// (protected) r = this + a\nfunction bnpAddTo(a, r) {\n let i = 0;\n let c = 0;\n const m = Math.min(a.t, this.t);\n while (i < m) {\n c += this[i] + a[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n if (a.t < this.t) {\n c += a.s;\n while (i < this.t) {\n c += this[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n c += this.s;\n }\n else {\n c += this.s;\n while (i < a.t) {\n c += a[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n c += a.s;\n }\n r.s = c < 0 ? -1 : 0;\n if (c > 0)\n r[i++] = c;\n else if (c < -1)\n r[i++] = this.DV + c;\n r.t = i;\n r.clamp();\n}\n// (public) this + a\nfunction bnAdd(a) {\n const r = nbi();\n this.addTo(a, r);\n return r;\n}\n// (public) this - a\nfunction bnSubtract(a) {\n const r = nbi();\n this.subTo(a, r);\n return r;\n}\n// (public) this * a\nfunction bnMultiply(a) {\n const r = nbi();\n this.multiplyTo(a, r);\n return r;\n}\n// (public) this / a\nfunction bnDivide(a) {\n const r = nbi();\n this.divRemTo(a, r, null);\n return r;\n}\n// Montgomery reduction\nfunction Montgomery(m) {\n this.m = m;\n this.mp = m.invDigit();\n this.mpl = this.mp & 0x7fff;\n this.mph = this.mp >> 15;\n this.um = (1 << (m.DB - 15)) - 1;\n this.mt2 = 2 * m.t;\n}\n// xR mod m\nfunction montConvert(x) {\n const r = nbi();\n x.abs().dlShiftTo(this.m.t, r);\n r.divRemTo(this.m, null, r);\n if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0)\n this.m.subTo(r, r);\n return r;\n}\n// x/R mod m\nfunction montRevert(x) {\n const r = nbi();\n x.copyTo(r);\n this.reduce(r);\n return r;\n}\n// x = x/R mod m (HAC 14.32)\nfunction montReduce(x) {\n while (x.t <= this.mt2)\n // pad x so am has enough room later\n x[x.t++] = 0;\n for (let i = 0; i < this.m.t; ++i) {\n // faster way of calculating u0 = x[i]*mp mod DV\n let j = x[i] & 0x7fff;\n const u0 = (j * this.mpl +\n (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) &\n x.DM;\n // use am to combine the multiply-shift-add into one call\n j = i + this.m.t;\n x[j] += this.m.am(0, u0, x, i, 0, this.m.t);\n // propagate carry\n while (x[j] >= x.DV) {\n x[j] -= x.DV;\n x[++j]++;\n }\n }\n x.clamp();\n x.drShiftTo(this.m.t, x);\n if (x.compareTo(this.m) >= 0)\n x.subTo(this.m, x);\n}\n// r = \"x^2/R mod m\"; x != r\nfunction montSqrTo(x, r) {\n x.squareTo(r);\n this.reduce(r);\n}\n// r = \"xy/R mod m\"; x,y != r\nfunction montMulTo(x, y, r) {\n x.multiplyTo(y, r);\n this.reduce(r);\n}\nMontgomery.prototype.convert = montConvert;\nMontgomery.prototype.revert = montRevert;\nMontgomery.prototype.reduce = montReduce;\nMontgomery.prototype.mulTo = montMulTo;\nMontgomery.prototype.sqrTo = montSqrTo;\n// (public) this^e % m (HAC 14.85)\nfunction bnModPow(e, m, callback) {\n let i = e.bitLength();\n let k;\n let r = nbv(1);\n const z = new Montgomery(m);\n if (i <= 0)\n return r;\n else if (i < 18)\n k = 1;\n else if (i < 48)\n k = 3;\n else if (i < 144)\n k = 4;\n else if (i < 768)\n k = 5;\n else\n k = 6;\n // precomputation\n const g = [];\n let n = 3;\n const k1 = k - 1;\n const km = (1 << k) - 1;\n g[1] = z.convert(this);\n if (k > 1) {\n const g2 = nbi();\n z.sqrTo(g[1], g2);\n while (n <= km) {\n g[n] = nbi();\n z.mulTo(g2, g[n - 2], g[n]);\n n += 2;\n }\n }\n let j = e.t - 1;\n let w;\n let is1 = true;\n let r2 = nbi();\n let t;\n i = nbits(e[j]) - 1;\n while (j >= 0) {\n if (i >= k1)\n w = (e[j] >> (i - k1)) & km;\n else {\n w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);\n if (j > 0)\n w |= e[j - 1] >> (this.DB + i - k1);\n }\n n = k;\n while ((w & 1) === 0) {\n w >>= 1;\n --n;\n }\n if ((i -= n) < 0) {\n i += this.DB;\n --j;\n }\n if (is1) {\n // ret == 1, don't bother squaring or multiplying it\n g[w].copyTo(r);\n is1 = false;\n }\n else {\n while (n > 1) {\n z.sqrTo(r, r2);\n z.sqrTo(r2, r);\n n -= 2;\n }\n if (n > 0)\n z.sqrTo(r, r2);\n else {\n t = r;\n r = r2;\n r2 = t;\n }\n z.mulTo(r2, g[w], r);\n }\n while (j >= 0 && (e[j] & (1 << i)) === 0) {\n z.sqrTo(r, r2);\n t = r;\n r = r2;\n r2 = t;\n if (--i < 0) {\n i = this.DB - 1;\n --j;\n }\n }\n }\n const result = z.revert(r);\n callback(null, result);\n return result;\n}\n// protected\nBigInteger.prototype.copyTo = bnpCopyTo;\nBigInteger.prototype.fromInt = bnpFromInt;\nBigInteger.prototype.fromString = bnpFromString;\nBigInteger.prototype.clamp = bnpClamp;\nBigInteger.prototype.dlShiftTo = bnpDLShiftTo;\nBigInteger.prototype.drShiftTo = bnpDRShiftTo;\nBigInteger.prototype.lShiftTo = bnpLShiftTo;\nBigInteger.prototype.rShiftTo = bnpRShiftTo;\nBigInteger.prototype.subTo = bnpSubTo;\nBigInteger.prototype.multiplyTo = bnpMultiplyTo;\nBigInteger.prototype.squareTo = bnpSquareTo;\nBigInteger.prototype.divRemTo = bnpDivRemTo;\nBigInteger.prototype.invDigit = bnpInvDigit;\nBigInteger.prototype.addTo = bnpAddTo;\n// public\nBigInteger.prototype.toString = bnToString;\nBigInteger.prototype.negate = bnNegate;\nBigInteger.prototype.abs = bnAbs;\nBigInteger.prototype.compareTo = bnCompareTo;\nBigInteger.prototype.bitLength = bnBitLength;\nBigInteger.prototype.mod = bnMod;\nBigInteger.prototype.equals = bnEquals;\nBigInteger.prototype.add = bnAdd;\nBigInteger.prototype.subtract = bnSubtract;\nBigInteger.prototype.multiply = bnMultiply;\nBigInteger.prototype.divide = bnDivide;\nBigInteger.prototype.modPow = bnModPow;\n// \"constants\"\nBigInteger.ZERO = nbv(0);\nBigInteger.ONE = nbv(1);\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n */\nexport const calculateS = async ({ a, g, k, x, B, N, U, }) => {\n return new Promise((resolve, reject) => {\n g.modPow(x, N, (outerErr, outerResult) => {\n if (outerErr) {\n reject(outerErr);\n return;\n }\n B.subtract(k.multiply(outerResult)).modPow(a.add(U.multiply(x)), N, (innerErr, innerResult) => {\n if (innerErr) {\n reject(innerErr);\n return;\n }\n resolve(innerResult.mod(N));\n });\n });\n });\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const INIT_N = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' +\n '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' +\n 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' +\n 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' +\n 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' +\n 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' +\n '83655D23DCA3AD961C62F356208552BB9ED529077096966D' +\n '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' +\n 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' +\n 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' +\n '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' +\n 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' +\n 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' +\n 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' +\n 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' +\n '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF';\nexport const SHORT_TO_HEX = {};\nexport const HEX_TO_SHORT = {};\nfor (let i = 0; i < 256; i++) {\n let encodedByte = i.toString(16).toLowerCase();\n if (encodedByte.length === 1) {\n encodedByte = `0${encodedByte}`;\n }\n SHORT_TO_HEX[i] = encodedByte;\n HEX_TO_SHORT[encodedByte] = i;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { HEX_TO_SHORT } from './constants';\n/**\n * Converts a hexadecimal encoded string to a Uint8Array of bytes.\n *\n * @param encoded The hexadecimal encoded string\n */\nexport const getBytesFromHex = (encoded) => {\n if (encoded.length % 2 !== 0) {\n throw new Error('Hex encoded strings must have an even number length');\n }\n const out = new Uint8Array(encoded.length / 2);\n for (let i = 0; i < encoded.length; i += 2) {\n const encodedByte = encoded.slice(i, i + 2).toLowerCase();\n if (encodedByte in HEX_TO_SHORT) {\n out[i / 2] = HEX_TO_SHORT[encodedByte];\n }\n else {\n throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);\n }\n }\n return out;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { SHORT_TO_HEX } from './constants';\n/**\n * Converts a Uint8Array of binary data to a hexadecimal encoded string.\n *\n * @param bytes The binary data to encode\n */\nexport const getHexFromBytes = (bytes) => {\n let out = '';\n for (let i = 0; i < bytes.byteLength; i++) {\n out += SHORT_TO_HEX[bytes[i]];\n }\n return out;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Sha256 } from '@aws-crypto/sha256-js';\nimport { getHexFromBytes } from './getHexFromBytes';\n/**\n * Calculate a hash from a `SourceData`\n * @param {SourceData} data Value to hash.\n * @returns {string} Hex-encoded hash.\n * @private\n */\nexport const getHashFromData = (data) => {\n const sha256 = new Sha256();\n sha256.update(data);\n const hashedData = sha256.digestSync();\n const hashHexFromUint8 = getHexFromBytes(hashedData);\n return new Array(64 - hashHexFromUint8.length).join('0') + hashHexFromUint8;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { getBytesFromHex } from './getBytesFromHex';\nimport { getHashFromData } from './getHashFromData';\n/**\n * Calculate a hash from a hex string\n * @param {string} hexStr Value to hash.\n * @returns {string} Hex-encoded hash.\n * @private\n */\nexport const getHashFromHex = (hexStr) => getHashFromData(getBytesFromHex(hexStr));\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { BigInteger } from './BigInteger';\n/**\n * Tests if a hex string has it most significant bit set (case-insensitive regex)\n */\nconst HEX_MSB_REGEX = /^[89a-f]/i;\n/**\n * Returns an unambiguous, even-length hex string of the two's complement encoding of an integer.\n *\n * It is compatible with the hex encoding of Java's BigInteger's toByteArray(), wich returns a\n * byte array containing the two's-complement representation of a BigInteger. The array contains\n * the minimum number of bytes required to represent the BigInteger, including at least one sign bit.\n *\n * Examples showing how ambiguity is avoided by left padding with:\n * \t\"00\" (for positive values where the most-significant-bit is set)\n * \"FF\" (for negative values where the most-significant-bit is set)\n *\n * padHex(bigInteger.fromInt(-236)) === \"FF14\"\n * padHex(bigInteger.fromInt(20)) === \"14\"\n *\n * padHex(bigInteger.fromInt(-200)) === \"FF38\"\n * padHex(bigInteger.fromInt(56)) === \"38\"\n *\n * padHex(bigInteger.fromInt(-20)) === \"EC\"\n * padHex(bigInteger.fromInt(236)) === \"00EC\"\n *\n * padHex(bigInteger.fromInt(-56)) === \"C8\"\n * padHex(bigInteger.fromInt(200)) === \"00C8\"\n *\n * @param {AuthBigInteger} bigInt Number to encode.\n * @returns {String} even-length hex string of the two's complement encoding.\n */\nexport const getPaddedHex = (bigInt) => {\n if (!(bigInt instanceof BigInteger)) {\n throw new Error('Not a BigInteger');\n }\n const isNegative = bigInt.compareTo(BigInteger.ZERO) < 0;\n /* Get a hex string for abs(bigInt) */\n let hexStr = bigInt.abs().toString(16);\n /* Pad hex to even length if needed */\n hexStr = hexStr.length % 2 !== 0 ? `0${hexStr}` : hexStr;\n /* Prepend \"00\" if the most significant bit is set */\n hexStr = HEX_MSB_REGEX.test(hexStr) ? `00${hexStr}` : hexStr;\n if (isNegative) {\n /* Flip the bits of the representation */\n const invertedNibbles = hexStr\n .split('')\n .map((x) => {\n const invertedNibble = ~parseInt(x, 16) & 0xf;\n return '0123456789ABCDEF'.charAt(invertedNibble);\n })\n .join('');\n /* After flipping the bits, add one to get the 2's complement representation */\n const flippedBitsBI = new BigInteger(invertedNibbles, 16).add(BigInteger.ONE);\n hexStr = flippedBitsBI.toString(16);\n /*\n For hex strings starting with 'FF8', 'FF' can be dropped, e.g. 0xFFFF80=0xFF80=0x80=-128\n\n Any sequence of '1' bits on the left can always be substituted with a single '1' bit\n without changing the represented value.\n\n This only happens in the case when the input is 80...00\n */\n if (hexStr.toUpperCase().startsWith('FF8')) {\n hexStr = hexStr.substring(2);\n }\n }\n return hexStr;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { BigInteger } from '../BigInteger';\nimport { getHashFromHex } from '../getHashFromHex';\nimport { getPaddedHex } from '../getPaddedHex';\n/**\n * @internal\n */\nexport const calculateU = ({ A, B, }) => {\n const U = new BigInteger(getHashFromHex(getPaddedHex(A) + getPaddedHex(B)), 16);\n if (U.equals(BigInteger.ZERO)) {\n throw new Error('U cannot be zero.');\n }\n return U;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Sha256 } from '@aws-crypto/sha256-js';\n/**\n * Standard HKDF algorithm.\n *\n * @param {Uint8Array} ikm Input key material.\n * @param {Uint8Array} salt Salt value.\n * @param {Uint8Array} info Context and application specific info.\n *\n * @returns {Uint8Array} Strong key material.\n *\n * @internal\n */\nexport const getHkdfKey = (ikm, salt, info) => {\n const awsCryptoHash = new Sha256(salt);\n awsCryptoHash.update(ikm);\n const resultFromAWSCryptoPrk = awsCryptoHash.digestSync();\n const awsCryptoHashHmac = new Sha256(resultFromAWSCryptoPrk);\n awsCryptoHashHmac.update(info);\n const resultFromAWSCryptoHmac = awsCryptoHashHmac.digestSync();\n const hashHexFromAWSCrypto = resultFromAWSCryptoHmac;\n return hashHexFromAWSCrypto.slice(0, 16);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { WordArray } from '@aws-amplify/core/internals/utils';\nimport { getBytesFromHex } from './getBytesFromHex';\n/**\n * Returns a Uint8Array with a sequence of random nBytes\n *\n * @param {number} nBytes\n * @returns {Uint8Array} fixed-length sequence of random bytes\n */\nexport const getRandomBytes = (nBytes) => {\n const str = new WordArray().random(nBytes).toString();\n return getBytesFromHex(str);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { base64Encoder } from '@aws-amplify/core/internals/utils';\nimport { getRandomBytes } from './getRandomBytes';\n/**\n * Helper function to generate a random string\n * @returns {string} a random value.\n *\n * @internal\n */\nexport const getRandomString = () => base64Encoder.convert(getRandomBytes(40));\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthError } from '../../../../../errors/AuthError';\nimport { textEncoder } from '../../textEncoder';\nimport { BigInteger } from '../BigInteger';\nimport { calculateS, calculateU } from '../calculate';\nimport { getBytesFromHex } from '../getBytesFromHex';\nimport { getHashFromData } from '../getHashFromData';\nimport { getHashFromHex } from '../getHashFromHex';\nimport { getHexFromBytes } from '../getHexFromBytes';\nimport { getHkdfKey } from '../getHkdfKey';\nimport { getPaddedHex } from '../getPaddedHex';\nimport { getRandomBytes } from '../getRandomBytes';\nimport { getRandomString } from '../getRandomString';\n/** @class */\nexport default class AuthenticationHelper {\n constructor({ userPoolName, a, g, A, N, }) {\n this.encoder = textEncoder;\n this.userPoolName = userPoolName;\n this.a = a;\n this.g = g;\n this.A = A;\n this.N = N;\n this.k = new BigInteger(getHashFromHex(`${getPaddedHex(N)}${getPaddedHex(g)}`), 16);\n }\n /**\n * @returns {string} Generated random value included in password hash.\n */\n getRandomPassword() {\n if (!this.randomPassword) {\n throw new AuthError({\n name: 'EmptyBigIntegerRandomPassword',\n message: 'random password is empty',\n });\n }\n return this.randomPassword;\n }\n /**\n * @returns {string} Generated random value included in devices hash.\n */\n getSaltToHashDevices() {\n if (!this.saltToHashDevices) {\n throw new AuthError({\n name: 'EmptyBigIntegersaltToHashDevices',\n message: 'saltToHashDevices is empty',\n });\n }\n return this.saltToHashDevices;\n }\n /**\n * @returns {string} Value used to verify devices.\n */\n getVerifierDevices() {\n if (!this.verifierDevices) {\n throw new AuthError({\n name: 'EmptyBigIntegerVerifierDevices',\n message: 'verifyDevices is empty',\n });\n }\n return this.verifierDevices;\n }\n /**\n * Generate salts and compute verifier.\n *\n * @param {string} deviceGroupKey Devices to generate verifier for.\n * @param {string} username User to generate verifier for.\n *\n * @returns {Promise<void>}\n */\n async generateHashDevice(deviceGroupKey, username) {\n this.randomPassword = getRandomString();\n const combinedString = `${deviceGroupKey}${username}:${this.randomPassword}`;\n const hashedString = getHashFromData(combinedString);\n const hexRandom = getHexFromBytes(getRandomBytes(16));\n // The random hex will be unambiguously represented as a postive integer\n this.saltToHashDevices = getPaddedHex(new BigInteger(hexRandom, 16));\n return new Promise((resolve, reject) => {\n this.g.modPow(new BigInteger(getHashFromHex(this.saltToHashDevices + hashedString), 16), this.N, (err, result) => {\n if (err) {\n reject(err);\n return;\n }\n this.verifierDevices = getPaddedHex(result);\n resolve();\n });\n });\n }\n /**\n * Calculates the final HKDF key based on computed S value, computed U value and the key\n *\n * @param {String} username Username.\n * @param {String} password Password.\n * @param {AuthBigInteger} B Server B value.\n * @param {AuthBigInteger} salt Generated salt.\n */\n async getPasswordAuthenticationKey({ username, password, serverBValue, salt, }) {\n if (serverBValue.mod(this.N).equals(BigInteger.ZERO)) {\n throw new Error('B cannot be zero.');\n }\n const U = calculateU({\n A: this.A,\n B: serverBValue,\n });\n const usernamePassword = `${this.userPoolName}${username}:${password}`;\n const usernamePasswordHash = getHashFromData(usernamePassword);\n const x = new BigInteger(getHashFromHex(getPaddedHex(salt) + usernamePasswordHash), 16);\n const S = await calculateS({\n a: this.a,\n g: this.g,\n k: this.k,\n x,\n B: serverBValue,\n N: this.N,\n U,\n });\n const context = this.encoder.convert('Caldera Derived Key');\n const spacer = this.encoder.convert(String.fromCharCode(1));\n const info = new Uint8Array(context.byteLength + spacer.byteLength);\n info.set(context, 0);\n info.set(spacer, context.byteLength);\n const hkdfKey = getHkdfKey(getBytesFromHex(getPaddedHex(S)), getBytesFromHex(getPaddedHex(U)), info);\n return hkdfKey;\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { BigInteger } from '../BigInteger';\n/**\n * @internal\n */\nexport const calculateA = async ({ a, g, N, }) => {\n return new Promise((resolve, reject) => {\n g.modPow(a, N, (err, A) => {\n if (err) {\n reject(err);\n return;\n }\n if (A.mod(N).equals(BigInteger.ZERO)) {\n reject(new Error('Illegal parameter. A mod N cannot be 0.'));\n return;\n }\n resolve(A);\n });\n });\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthenticationHelper } from './AuthenticationHelper';\nimport { BigInteger } from './BigInteger';\nimport { calculateA } from './calculate';\nimport { INIT_N } from './constants';\nimport { getHexFromBytes } from './getHexFromBytes';\nimport { getRandomBytes } from './getRandomBytes';\n/**\n * Returns a new {@link AuthenticationHelper} instance with randomly generated BigInteger seed\n *\n * @param userPoolName Cognito user pool name.\n * @returns An {@link AuthenticationHelper} instance.\n *\n * @internal\n */\nexport const getAuthenticationHelper = async (userPoolName) => {\n const N = new BigInteger(INIT_N, 16);\n const g = new BigInteger('2', 16);\n const a = generateRandomBigInteger();\n const A = await calculateA({ a, g, N });\n return new AuthenticationHelper({ userPoolName, a, g, A, N });\n};\n/**\n * Generates a random BigInteger.\n *\n * @returns {BigInteger} a random value.\n */\nconst generateRandomBigInteger = () => {\n // This will be interpreted as a postive 128-bit integer\n const hexRandom = getHexFromBytes(getRandomBytes(128));\n // There is no need to do randomBigInt.mod(this.N - 1) as N (3072-bit) is > 128 bytes (1024-bit)\n return new BigInteger(hexRandom, 16);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { base64Encoder, getDeviceName, } from '@aws-amplify/core/internals/utils';\nimport { createConfirmDeviceClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getAuthenticationHelper, getBytesFromHex } from './srp';\n/**\n * This function is used to kick off the device management flow.\n *\n * If an error is thrown while generating a hash device or calling the `ConfirmDevice`\n * client, then this API will ignore the error and return undefined. Otherwise the authentication\n * flow will not complete and the user won't be able to be signed in.\n *\n * @returns DeviceMetadata | undefined\n */\nexport async function getNewDeviceMetadata({ userPoolId, userPoolEndpoint, newDeviceMetadata, accessToken, }) {\n if (!newDeviceMetadata)\n return undefined;\n const userPoolName = userPoolId.split('_')[1] || '';\n const authenticationHelper = await getAuthenticationHelper(userPoolName);\n const deviceKey = newDeviceMetadata?.DeviceKey;\n const deviceGroupKey = newDeviceMetadata?.DeviceGroupKey;\n try {\n await authenticationHelper.generateHashDevice(deviceGroupKey ?? '', deviceKey ?? '');\n }\n catch (errGenHash) {\n // TODO: log error here\n return undefined;\n }\n const deviceSecretVerifierConfig = {\n Salt: base64Encoder.convert(getBytesFromHex(authenticationHelper.getSaltToHashDevices())),\n PasswordVerifier: base64Encoder.convert(getBytesFromHex(authenticationHelper.getVerifierDevices())),\n };\n const randomPassword = authenticationHelper.getRandomPassword();\n try {\n const confirmDevice = createConfirmDeviceClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await confirmDevice({ region: getRegionFromUserPoolId(userPoolId) }, {\n AccessToken: accessToken,\n DeviceName: await getDeviceName(),\n DeviceKey: newDeviceMetadata?.DeviceKey,\n DeviceSecretVerifierConfig: deviceSecretVerifierConfig,\n });\n return {\n deviceKey,\n deviceGroupKey,\n randomPassword,\n };\n }\n catch (error) {\n // TODO: log error here\n return undefined;\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthErrorCodes } from '../../../common/AuthErrorStrings';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories';\nimport { cacheCognitoTokens } from '../../../providers/cognito/tokenProvider/cacheTokens';\nimport { dispatchSignedInHubEvent } from '../../../providers/cognito/utils/dispatchSignedInHubEvent';\nimport { setActiveSignInState, signInStore } from '../../../client/utils/store';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { getPasskey } from '../../utils/passkey';\nimport { PasskeyErrorCode, assertPasskeyError, } from '../../utils/passkey/errors';\nimport { AuthError } from '../../../errors/AuthError';\nimport { getNewDeviceMetadata } from '../../../providers/cognito/utils/getNewDeviceMetadata';\nexport async function handleWebAuthnSignInResult(challengeParameters) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { username, signInSession, signInDetails, challengeName } = signInStore.getState();\n if (challengeName !== 'WEB_AUTHN' || !username) {\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: 'Unable to proceed due to invalid sign in state.',\n });\n }\n const { CREDENTIAL_REQUEST_OPTIONS: credentialRequestOptions } = challengeParameters;\n assertPasskeyError(!!credentialRequestOptions, PasskeyErrorCode.InvalidPasskeyAuthenticationOptions);\n const cred = await getPasskey(JSON.parse(credentialRequestOptions));\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: authConfig.userPoolEndpoint,\n }),\n });\n const { ChallengeName: nextChallengeName, ChallengeParameters: nextChallengeParameters, AuthenticationResult: authenticationResult, Session: nextSession, } = await respondToAuthChallenge({\n region: getRegionFromUserPoolId(authConfig.userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, {\n ChallengeName: 'WEB_AUTHN',\n ChallengeResponses: {\n USERNAME: username,\n CREDENTIAL: JSON.stringify(cred),\n },\n ClientId: authConfig.userPoolClientId,\n Session: signInSession,\n });\n setActiveSignInState({\n signInSession: nextSession,\n username,\n challengeName: nextChallengeName,\n signInDetails,\n });\n if (authenticationResult) {\n await cacheCognitoTokens({\n ...authenticationResult,\n username,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: authenticationResult.NewDeviceMetadata,\n accessToken: authenticationResult.AccessToken,\n }),\n signInDetails,\n });\n signInStore.dispatch({ type: 'RESET_STATE' });\n await dispatchSignedInHubEvent();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n if (nextChallengeName === 'WEB_AUTHN') {\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: 'Sequential WEB_AUTHN challenges returned from underlying service cannot be handled.',\n });\n }\n return {\n challengeName: nextChallengeName,\n challengeParameters: nextChallengeParameters,\n };\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport function getUserContextData({ username, userPoolId, userPoolClientId, }) {\n if (typeof window === 'undefined') {\n return undefined;\n }\n const amazonCognitoAdvancedSecurityData = window\n .AmazonCognitoAdvancedSecurityData;\n if (typeof amazonCognitoAdvancedSecurityData === 'undefined') {\n return undefined;\n }\n const advancedSecurityData = amazonCognitoAdvancedSecurityData.getData(username, userPoolId, userPoolClientId);\n if (advancedSecurityData) {\n const userContextData = {\n EncodedData: advancedSecurityData,\n };\n return userContextData;\n }\n return {};\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst MONTH_NAMES = [\n 'Jan',\n 'Feb',\n 'Mar',\n 'Apr',\n 'May',\n 'Jun',\n 'Jul',\n 'Aug',\n 'Sep',\n 'Oct',\n 'Nov',\n 'Dec',\n];\nconst WEEK_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];\nexport const getNowString = () => {\n const now = new Date();\n const weekDay = WEEK_NAMES[now.getUTCDay()];\n const month = MONTH_NAMES[now.getUTCMonth()];\n const day = now.getUTCDate();\n let hours = now.getUTCHours();\n if (hours < 10) {\n hours = `0${hours}`;\n }\n let minutes = now.getUTCMinutes();\n if (minutes < 10) {\n minutes = `0${minutes}`;\n }\n let seconds = now.getUTCSeconds();\n if (seconds < 10) {\n seconds = `0${seconds}`;\n }\n const year = now.getUTCFullYear();\n // ddd MMM D HH:mm:ss UTC YYYY\n const dateNow = `${weekDay} ${month} ${day} ${hours}:${minutes}:${seconds} UTC ${year}`;\n return dateNow;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Sha256 } from '@aws-crypto/sha256-js';\nimport { base64Decoder, base64Encoder, } from '@aws-amplify/core/internals/utils';\nimport { textEncoder } from '../textEncoder';\nexport const getSignatureString = ({ userPoolName, username, challengeParameters, dateNow, hkdf, }) => {\n const bufUPIDaToB = textEncoder.convert(userPoolName);\n const bufUNaToB = textEncoder.convert(username);\n const bufSBaToB = urlB64ToUint8Array(challengeParameters.SECRET_BLOCK);\n const bufDNaToB = textEncoder.convert(dateNow);\n const bufConcat = new Uint8Array(bufUPIDaToB.byteLength +\n bufUNaToB.byteLength +\n bufSBaToB.byteLength +\n bufDNaToB.byteLength);\n bufConcat.set(bufUPIDaToB, 0);\n bufConcat.set(bufUNaToB, bufUPIDaToB.byteLength);\n bufConcat.set(bufSBaToB, bufUPIDaToB.byteLength + bufUNaToB.byteLength);\n bufConcat.set(bufDNaToB, bufUPIDaToB.byteLength + bufUNaToB.byteLength + bufSBaToB.byteLength);\n const awsCryptoHash = new Sha256(hkdf);\n awsCryptoHash.update(bufConcat);\n const resultFromAWSCrypto = awsCryptoHash.digestSync();\n const signatureString = base64Encoder.convert(resultFromAWSCrypto);\n return signatureString;\n};\nconst urlB64ToUint8Array = (base64String) => {\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\n const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');\n const rawData = base64Decoder.convert(base64);\n const outputArray = new Uint8Array(rawData.length);\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i);\n }\n return outputArray;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { assertDeviceMetadata } from './types';\nimport { getAuthenticationHelper, getNowString, getSignatureString, } from './srp';\nimport { BigInteger } from './srp/BigInteger';\nimport { getUserContextData } from './userContextData';\nexport async function handleDeviceSRPAuth({ username, config, clientMetadata, session, tokenOrchestrator, }) {\n const { userPoolId, userPoolEndpoint } = config;\n const clientId = config.userPoolClientId;\n const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username);\n assertDeviceMetadata(deviceMetadata);\n const authenticationHelper = await getAuthenticationHelper(deviceMetadata.deviceGroupKey);\n const challengeResponses = {\n USERNAME: username,\n SRP_A: authenticationHelper.A.toString(16),\n DEVICE_KEY: deviceMetadata.deviceKey,\n };\n const jsonReqResponseChallenge = {\n ChallengeName: 'DEVICE_SRP_AUTH',\n ClientId: clientId,\n ChallengeResponses: challengeResponses,\n ClientMetadata: clientMetadata,\n Session: session,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { ChallengeParameters: respondedChallengeParameters, Session } = await respondToAuthChallenge({ region: getRegionFromUserPoolId(userPoolId) }, jsonReqResponseChallenge);\n return handleDevicePasswordVerifier(username, respondedChallengeParameters, clientMetadata, Session, authenticationHelper, config, tokenOrchestrator);\n}\nasync function handleDevicePasswordVerifier(username, challengeParameters, clientMetadata, session, authenticationHelper, { userPoolId, userPoolClientId, userPoolEndpoint }, tokenOrchestrator) {\n const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username);\n assertDeviceMetadata(deviceMetadata);\n const serverBValue = new BigInteger(challengeParameters?.SRP_B, 16);\n const salt = new BigInteger(challengeParameters?.SALT, 16);\n const { deviceKey } = deviceMetadata;\n const { deviceGroupKey } = deviceMetadata;\n const hkdf = await authenticationHelper.getPasswordAuthenticationKey({\n username: deviceMetadata.deviceKey,\n password: deviceMetadata.randomPassword,\n serverBValue,\n salt,\n });\n const dateNow = getNowString();\n const challengeResponses = {\n USERNAME: challengeParameters?.USERNAME ?? username,\n PASSWORD_CLAIM_SECRET_BLOCK: challengeParameters?.SECRET_BLOCK,\n TIMESTAMP: dateNow,\n PASSWORD_CLAIM_SIGNATURE: getSignatureString({\n username: deviceKey,\n userPoolName: deviceGroupKey,\n challengeParameters,\n dateNow,\n hkdf,\n }),\n DEVICE_KEY: deviceKey,\n };\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReqResponseChallenge = {\n ChallengeName: 'DEVICE_PASSWORD_VERIFIER',\n ClientId: userPoolClientId,\n ChallengeResponses: challengeResponses,\n Session: session,\n ClientMetadata: clientMetadata,\n UserContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({ region: getRegionFromUserPoolId(userPoolId) }, jsonReqResponseChallenge);\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthError } from '../../../errors/AuthError';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getNowString, getSignatureString } from './srp';\nimport { BigInteger } from './srp/BigInteger';\nimport { getUserContextData } from './userContextData';\nimport { handleDeviceSRPAuth } from './handleDeviceSRPAuth';\nexport async function handlePasswordVerifierChallenge(password, challengeParameters, clientMetadata, session, authenticationHelper, config, tokenOrchestrator) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const userPoolName = userPoolId?.split('_')[1] || '';\n const serverBValue = new BigInteger(challengeParameters?.SRP_B, 16);\n const salt = new BigInteger(challengeParameters?.SALT, 16);\n const username = challengeParameters?.USER_ID_FOR_SRP;\n if (!username)\n throw new AuthError({\n name: 'EmptyUserIdForSRPException',\n message: 'USER_ID_FOR_SRP was not found in challengeParameters',\n });\n const hkdf = await authenticationHelper.getPasswordAuthenticationKey({\n username,\n password,\n serverBValue,\n salt,\n });\n const dateNow = getNowString();\n const challengeResponses = {\n USERNAME: username,\n PASSWORD_CLAIM_SECRET_BLOCK: challengeParameters?.SECRET_BLOCK,\n TIMESTAMP: dateNow,\n PASSWORD_CLAIM_SIGNATURE: getSignatureString({\n username,\n userPoolName,\n challengeParameters,\n dateNow,\n hkdf,\n }),\n };\n const deviceMetadata = await tokenOrchestrator.getDeviceMetadata(username);\n if (deviceMetadata && deviceMetadata.deviceKey) {\n challengeResponses.DEVICE_KEY = deviceMetadata.deviceKey;\n }\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReqResponseChallenge = {\n ChallengeName: 'PASSWORD_VERIFIER',\n ChallengeResponses: challengeResponses,\n ClientMetadata: clientMetadata,\n Session: session,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await respondToAuthChallenge({ region: getRegionFromUserPoolId(userPoolId) }, jsonReqResponseChallenge);\n if (response.ChallengeName === 'DEVICE_SRP_AUTH')\n return handleDeviceSRPAuth({\n username,\n config,\n clientMetadata,\n session: response.Session,\n tokenOrchestrator,\n });\n return response;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthError } from '../../../errors/AuthError';\n/**\n * It will retry the function if the error is a `ResourceNotFoundException` and\n * will clean the device keys stored in the storage mechanism.\n *\n */\nexport async function retryOnResourceNotFoundException(func, args, username, tokenOrchestrator) {\n try {\n return await func(...args);\n }\n catch (error) {\n if (error instanceof AuthError &&\n error.name === 'ResourceNotFoundException' &&\n error.message.includes('Device does not exist.')) {\n await tokenOrchestrator.clearDeviceMetadata(username);\n return func(...args);\n }\n throw error;\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { signInStore } from '../../../client/utils/store';\nexport function setActiveSignInUsername(username) {\n const { dispatch } = signInStore;\n dispatch({ type: 'SET_USERNAME', value: username });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthAction } from '@aws-amplify/core/internals/utils';\nimport { getUserContextData } from '../../../providers/cognito/utils/userContextData';\nimport { getAuthenticationHelper } from '../../../providers/cognito/utils/srp';\nimport { createInitiateAuthClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { handlePasswordVerifierChallenge } from '../../../providers/cognito/utils/handlePasswordVerifierChallenge';\nimport { retryOnResourceNotFoundException } from '../../../providers/cognito/utils/retryOnResourceNotFoundException';\nimport { setActiveSignInUsername } from '../../../providers/cognito/utils/setActiveSignInUsername';\n/**\n * Handles the Password SRP (Secure Remote Password) authentication flow.\n * This function can be used with both USER_SRP_AUTH and USER_AUTH flows.\n *\n * @param {Object} params - The parameters for the Password SRP authentication\n * @param {string} params.username - The username for authentication\n * @param {string} params.password - The user's password\n * @param {ClientMetadata} [params.clientMetadata] - Optional metadata to be sent with auth requests\n * @param {CognitoUserPoolConfig} params.config - Cognito User Pool configuration\n * @param {AuthTokenOrchestrator} params.tokenOrchestrator - Token orchestrator for managing auth tokens\n * @param {AuthFlowType} params.authFlow - The type of authentication flow ('USER_SRP_AUTH' or 'USER_AUTH')\n * @param {AuthFactorType} [params.preferredChallenge] - Optional preferred challenge type when using USER_AUTH flow\n *\n * @returns {Promise<RespondToAuthChallengeCommandOutput>} The authentication response\n */\nexport async function handlePasswordSRP({ username, password, clientMetadata, config, tokenOrchestrator, authFlow, preferredChallenge, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const userPoolName = userPoolId?.split('_')[1] || '';\n const authenticationHelper = await getAuthenticationHelper(userPoolName);\n const authParameters = {\n USERNAME: username,\n SRP_A: authenticationHelper.A.toString(16),\n };\n if (authFlow === 'USER_AUTH' && preferredChallenge) {\n authParameters.PREFERRED_CHALLENGE = preferredChallenge;\n }\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n AuthFlow: authFlow,\n AuthParameters: authParameters,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const initiateAuth = createInitiateAuthClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const resp = await initiateAuth({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignIn),\n }, jsonReq);\n const { ChallengeParameters: challengeParameters, Session: session } = resp;\n const activeUsername = challengeParameters?.USERNAME ?? username;\n setActiveSignInUsername(activeUsername);\n if (resp.ChallengeName === 'PASSWORD_VERIFIER') {\n return retryOnResourceNotFoundException(handlePasswordVerifierChallenge, [\n password,\n challengeParameters,\n clientMetadata,\n session,\n authenticationHelper,\n config,\n tokenOrchestrator,\n ], activeUsername, tokenOrchestrator);\n }\n return resp;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthAction } from '@aws-amplify/core/internals/utils';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getAuthUserAgentValue } from '../../../utils';\n/**\n * Handles the SELECT_CHALLENGE response for authentication.\n * Initiates the selected authentication challenge based on user choice.\n *\n * @param {Object} params - The parameters for handling the selected challenge\n * @param {string} params.username - The username for authentication\n * @param {string} params.session - The current authentication session token\n * @param {string} params.selectedChallenge - The challenge type selected by the user\n * @param {CognitoUserPoolConfig} params.config - Cognito User Pool configuration\n * @param {ClientMetadata} [params.clientMetadata] - Optional metadata to be sent with auth requests\n *\n * @returns {Promise<RespondToAuthChallengeCommandOutput>} The challenge response\n */\nexport async function initiateSelectedChallenge({ username, session, selectedChallenge, config, clientMetadata, }) {\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: config.userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({\n region: getRegionFromUserPoolId(config.userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, {\n ChallengeName: 'SELECT_CHALLENGE',\n ChallengeResponses: {\n USERNAME: username,\n ANSWER: selectedChallenge,\n },\n ClientId: config.userPoolClientId,\n Session: session,\n ClientMetadata: clientMetadata,\n });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthAction } from '@aws-amplify/core/internals/utils';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { getUserContextData } from '../../../providers/cognito/utils/userContextData';\nimport { setActiveSignInUsername } from '../../../providers/cognito/utils/setActiveSignInUsername';\n/**\n * Handles the SELECT_CHALLENGE response specifically for Password authentication.\n * This function combines the SELECT_CHALLENGE flow with standard password authentication.\n *\n * @param {string} username - The username for authentication\n * @param {string} password - The user's password\n * @param {ClientMetadata} [clientMetadata] - Optional metadata to be sent with auth requests\n * @param {CognitoUserPoolConfig} config - Cognito User Pool configuration\n * @param {string} session - The current authentication session token\n *\n * @returns {Promise<RespondToAuthChallengeCommandOutput>} The challenge response\n */\nexport async function handleSelectChallengeWithPassword(username, password, clientMetadata, config, session) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const authParameters = {\n ANSWER: 'PASSWORD',\n USERNAME: username,\n PASSWORD: password,\n };\n const userContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, {\n ChallengeName: 'SELECT_CHALLENGE',\n ChallengeResponses: authParameters,\n ClientId: userPoolClientId,\n ClientMetadata: clientMetadata,\n Session: session,\n UserContextData: userContextData,\n });\n const activeUsername = response.ChallengeParameters?.USERNAME ?? username;\n setActiveSignInUsername(activeUsername);\n return response;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthAction } from '@aws-amplify/core/internals/utils';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { getAuthenticationHelper } from '../../../providers/cognito/utils/srp';\nimport { getUserContextData } from '../../../providers/cognito/utils/userContextData';\nimport { setActiveSignInUsername } from '../../../providers/cognito/utils/setActiveSignInUsername';\nimport { retryOnResourceNotFoundException } from '../../../providers/cognito/utils/retryOnResourceNotFoundException';\nimport { handlePasswordVerifierChallenge } from '../../../providers/cognito/utils/handlePasswordVerifierChallenge';\n/**\n * Handles the SELECT_CHALLENGE response specifically for Password SRP authentication.\n * This function combines the SELECT_CHALLENGE flow with Password SRP protocol.\n *\n * @param {string} username - The username for authentication\n * @param {string} password - The user's password\n * @param {ClientMetadata} [clientMetadata] - Optional metadata to be sent with auth requests\n * @param {CognitoUserPoolConfig} config - Cognito User Pool configuration\n * @param {string} session - The current authentication session token\n * @param {AuthTokenOrchestrator} tokenOrchestrator - Token orchestrator for managing auth tokens\n *\n * @returns {Promise<RespondToAuthChallengeCommandOutput>} The challenge response\n */\nexport async function handleSelectChallengeWithPasswordSRP(username, password, clientMetadata, config, session, tokenOrchestrator) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const userPoolName = userPoolId.split('_')[1] || '';\n const authenticationHelper = await getAuthenticationHelper(userPoolName);\n const authParameters = {\n ANSWER: 'PASSWORD_SRP',\n USERNAME: username,\n SRP_A: authenticationHelper.A.toString(16),\n };\n const userContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, {\n ChallengeName: 'SELECT_CHALLENGE',\n ChallengeResponses: authParameters,\n ClientId: userPoolClientId,\n ClientMetadata: clientMetadata,\n Session: session,\n UserContextData: userContextData,\n });\n const activeUsername = response.ChallengeParameters?.USERNAME ?? username;\n setActiveSignInUsername(activeUsername);\n if (response.ChallengeName === 'PASSWORD_VERIFIER') {\n return retryOnResourceNotFoundException(handlePasswordVerifierChallenge, [\n password,\n response.ChallengeParameters,\n clientMetadata,\n response.Session,\n authenticationHelper,\n config,\n tokenOrchestrator,\n ], activeUsername, tokenOrchestrator);\n }\n return response;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { AmplifyUrl, AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError';\nimport { InitiateAuthException } from '../types/errors';\nimport { AuthErrorCodes } from '../../../common/AuthErrorStrings';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { USER_ALREADY_AUTHENTICATED_EXCEPTION } from '../../../errors/constants';\nimport { getCurrentUser } from '../apis/getCurrentUser';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createAssociateSoftwareTokenClient, createInitiateAuthClient, createRespondToAuthChallengeClient, createVerifySoftwareTokenClient, } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { handleWebAuthnSignInResult } from '../../../client/flows/userAuth/handleWebAuthnSignInResult';\nimport { handlePasswordSRP } from '../../../client/flows/shared/handlePasswordSRP';\nimport { initiateSelectedChallenge } from '../../../client/flows/userAuth/handleSelectChallenge';\nimport { handleSelectChallengeWithPassword } from '../../../client/flows/userAuth/handleSelectChallengeWithPassword';\nimport { handleSelectChallengeWithPasswordSRP } from '../../../client/flows/userAuth/handleSelectChallengeWithPasswordSRP';\nimport { signInStore } from '../../../client/utils/store';\nimport { getAuthenticationHelper } from './srp';\nimport { getUserContextData } from './userContextData';\nimport { handlePasswordVerifierChallenge } from './handlePasswordVerifierChallenge';\nimport { handleDeviceSRPAuth } from './handleDeviceSRPAuth';\nimport { retryOnResourceNotFoundException } from './retryOnResourceNotFoundException';\nimport { setActiveSignInUsername } from './setActiveSignInUsername';\nconst USER_ATTRIBUTES = 'userAttributes.';\nfunction isWebAuthnResultAuthSignInOutput(result) {\n return 'isSignedIn' in result && 'nextStep' in result;\n}\nexport async function handleCustomChallenge({ challengeResponse, clientMetadata, session, username, config, tokenOrchestrator, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const challengeResponses = {\n USERNAME: username,\n ANSWER: challengeResponse,\n };\n const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username);\n if (deviceMetadata && deviceMetadata.deviceKey) {\n challengeResponses.DEVICE_KEY = deviceMetadata.deviceKey;\n }\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n ChallengeName: 'CUSTOM_CHALLENGE',\n ChallengeResponses: challengeResponses,\n Session: session,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n if (response.ChallengeName === 'DEVICE_SRP_AUTH') {\n return handleDeviceSRPAuth({\n username,\n config,\n clientMetadata,\n session: response.Session,\n tokenOrchestrator,\n });\n }\n return response;\n}\nexport async function handleMFASetupChallenge({ challengeResponse, username, clientMetadata, session, deviceName, config, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n if (challengeResponse === 'EMAIL') {\n return {\n ChallengeName: 'MFA_SETUP',\n Session: session,\n ChallengeParameters: {\n MFAS_CAN_SETUP: '[\"EMAIL_OTP\"]',\n },\n $metadata: {},\n };\n }\n if (challengeResponse === 'TOTP') {\n return {\n ChallengeName: 'MFA_SETUP',\n Session: session,\n ChallengeParameters: {\n MFAS_CAN_SETUP: '[\"SOFTWARE_TOKEN_MFA\"]',\n },\n $metadata: {},\n };\n }\n const challengeResponses = {\n USERNAME: username,\n };\n const isTOTPCode = /^\\d+$/.test(challengeResponse);\n if (isTOTPCode) {\n const verifySoftwareToken = createVerifySoftwareTokenClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { Session } = await verifySoftwareToken({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, {\n UserCode: challengeResponse,\n Session: session,\n FriendlyDeviceName: deviceName,\n });\n signInStore.dispatch({\n type: 'SET_SIGN_IN_SESSION',\n value: Session,\n });\n const jsonReq = {\n ChallengeName: 'MFA_SETUP',\n ChallengeResponses: challengeResponses,\n Session,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n }\n const isEmail = challengeResponse.includes('@');\n if (isEmail) {\n challengeResponses.EMAIL = challengeResponse;\n const jsonReq = {\n ChallengeName: 'MFA_SETUP',\n ChallengeResponses: challengeResponses,\n Session: session,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n }\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: `Cannot proceed with MFA setup using challengeResponse: ${challengeResponse}`,\n recoverySuggestion: 'Try passing \"EMAIL\", \"TOTP\", a valid email, or OTP code as the challengeResponse.',\n });\n}\nexport async function handleSelectMFATypeChallenge({ challengeResponse, username, clientMetadata, session, config, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n assertValidationError(challengeResponse === 'TOTP' ||\n challengeResponse === 'SMS' ||\n challengeResponse === 'EMAIL', AuthValidationErrorCode.IncorrectMFAMethod);\n const challengeResponses = {\n USERNAME: username,\n ANSWER: mapMfaType(challengeResponse),\n };\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n ChallengeName: 'SELECT_MFA_TYPE',\n ChallengeResponses: challengeResponses,\n Session: session,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n}\nexport async function handleCompleteNewPasswordChallenge({ challengeResponse, clientMetadata, session, username, requiredAttributes, config, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const challengeResponses = {\n ...createAttributes(requiredAttributes),\n NEW_PASSWORD: challengeResponse,\n USERNAME: username,\n };\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n ChallengeName: 'NEW_PASSWORD_REQUIRED',\n ChallengeResponses: challengeResponses,\n ClientMetadata: clientMetadata,\n Session: session,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n}\nexport async function handleUserPasswordAuthFlow(username, password, clientMetadata, config, tokenOrchestrator) {\n const { userPoolClientId, userPoolId, userPoolEndpoint } = config;\n const authParameters = {\n USERNAME: username,\n PASSWORD: password,\n };\n const deviceMetadata = await tokenOrchestrator.getDeviceMetadata(username);\n if (deviceMetadata && deviceMetadata.deviceKey) {\n authParameters.DEVICE_KEY = deviceMetadata.deviceKey;\n }\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n AuthFlow: 'USER_PASSWORD_AUTH',\n AuthParameters: authParameters,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const initiateAuth = createInitiateAuthClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await initiateAuth({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignIn),\n }, jsonReq);\n const activeUsername = response.ChallengeParameters?.USERNAME ??\n response.ChallengeParameters?.USER_ID_FOR_SRP ??\n username;\n setActiveSignInUsername(activeUsername);\n if (response.ChallengeName === 'DEVICE_SRP_AUTH')\n return handleDeviceSRPAuth({\n username: activeUsername,\n config,\n clientMetadata,\n session: response.Session,\n tokenOrchestrator,\n });\n return response;\n}\nexport async function handleUserSRPAuthFlow(username, password, clientMetadata, config, tokenOrchestrator) {\n return handlePasswordSRP({\n username,\n password,\n clientMetadata,\n config,\n tokenOrchestrator,\n authFlow: 'USER_SRP_AUTH',\n });\n}\nexport async function handleCustomAuthFlowWithoutSRP(username, clientMetadata, config, tokenOrchestrator) {\n const { userPoolClientId, userPoolId, userPoolEndpoint } = config;\n const authParameters = {\n USERNAME: username,\n };\n const deviceMetadata = await tokenOrchestrator.getDeviceMetadata(username);\n if (deviceMetadata && deviceMetadata.deviceKey) {\n authParameters.DEVICE_KEY = deviceMetadata.deviceKey;\n }\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n AuthFlow: 'CUSTOM_AUTH',\n AuthParameters: authParameters,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const initiateAuth = createInitiateAuthClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await initiateAuth({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignIn),\n }, jsonReq);\n const activeUsername = response.ChallengeParameters?.USERNAME ?? username;\n setActiveSignInUsername(activeUsername);\n if (response.ChallengeName === 'DEVICE_SRP_AUTH')\n return handleDeviceSRPAuth({\n username: activeUsername,\n config,\n clientMetadata,\n session: response.Session,\n tokenOrchestrator,\n });\n return response;\n}\nexport async function handleCustomSRPAuthFlow(username, password, clientMetadata, config, tokenOrchestrator) {\n assertTokenProviderConfig(config);\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const userPoolName = userPoolId?.split('_')[1] || '';\n const authenticationHelper = await getAuthenticationHelper(userPoolName);\n const authParameters = {\n USERNAME: username,\n SRP_A: authenticationHelper.A.toString(16),\n CHALLENGE_NAME: 'SRP_A',\n };\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n AuthFlow: 'CUSTOM_AUTH',\n AuthParameters: authParameters,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const initiateAuth = createInitiateAuthClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { ChallengeParameters: challengeParameters, Session: session } = await initiateAuth({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignIn),\n }, jsonReq);\n const activeUsername = challengeParameters?.USERNAME ?? username;\n setActiveSignInUsername(activeUsername);\n return retryOnResourceNotFoundException(handlePasswordVerifierChallenge, [\n password,\n challengeParameters,\n clientMetadata,\n session,\n authenticationHelper,\n config,\n tokenOrchestrator,\n ], activeUsername, tokenOrchestrator);\n}\nexport async function getSignInResult(params) {\n const { challengeName, challengeParameters, availableChallenges } = params;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n switch (challengeName) {\n case 'CUSTOM_CHALLENGE':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE',\n additionalInfo: challengeParameters,\n },\n };\n case 'MFA_SETUP': {\n const { signInSession, username } = signInStore.getState();\n const mfaSetupTypes = getMFATypes(parseMFATypes(challengeParameters.MFAS_CAN_SETUP)) || [];\n const allowedMfaSetupTypes = getAllowedMfaSetupTypes(mfaSetupTypes);\n const isTotpMfaSetupAvailable = allowedMfaSetupTypes.includes('TOTP');\n const isEmailMfaSetupAvailable = allowedMfaSetupTypes.includes('EMAIL');\n if (isTotpMfaSetupAvailable && isEmailMfaSetupAvailable) {\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONTINUE_SIGN_IN_WITH_MFA_SETUP_SELECTION',\n allowedMFATypes: allowedMfaSetupTypes,\n },\n };\n }\n if (isEmailMfaSetupAvailable) {\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONTINUE_SIGN_IN_WITH_EMAIL_SETUP',\n },\n };\n }\n if (isTotpMfaSetupAvailable) {\n const associateSoftwareToken = createAssociateSoftwareTokenClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: authConfig.userPoolEndpoint,\n }),\n });\n const { Session, SecretCode: secretCode } = await associateSoftwareToken({ region: getRegionFromUserPoolId(authConfig.userPoolId) }, {\n Session: signInSession,\n });\n signInStore.dispatch({\n type: 'SET_SIGN_IN_SESSION',\n value: Session,\n });\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONTINUE_SIGN_IN_WITH_TOTP_SETUP',\n totpSetupDetails: getTOTPSetupDetails(secretCode, username),\n },\n };\n }\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: `Cannot initiate MFA setup from available types: ${mfaSetupTypes}`,\n });\n }\n case 'NEW_PASSWORD_REQUIRED':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED',\n missingAttributes: parseAttributes(challengeParameters.requiredAttributes),\n },\n };\n case 'SELECT_MFA_TYPE':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONTINUE_SIGN_IN_WITH_MFA_SELECTION',\n allowedMFATypes: getMFATypes(parseMFATypes(challengeParameters.MFAS_CAN_CHOOSE)),\n },\n };\n case 'SMS_OTP':\n case 'SMS_MFA':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_SMS_CODE',\n codeDeliveryDetails: {\n deliveryMedium: challengeParameters.CODE_DELIVERY_DELIVERY_MEDIUM,\n destination: challengeParameters.CODE_DELIVERY_DESTINATION,\n },\n },\n };\n case 'SOFTWARE_TOKEN_MFA':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_TOTP_CODE',\n },\n };\n case 'EMAIL_OTP':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_EMAIL_CODE',\n codeDeliveryDetails: {\n deliveryMedium: challengeParameters.CODE_DELIVERY_DELIVERY_MEDIUM,\n destination: challengeParameters.CODE_DELIVERY_DESTINATION,\n },\n },\n };\n case 'WEB_AUTHN': {\n const result = await handleWebAuthnSignInResult(challengeParameters);\n if (isWebAuthnResultAuthSignInOutput(result)) {\n return result;\n }\n return getSignInResult(result);\n }\n case 'PASSWORD':\n case 'PASSWORD_SRP':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_PASSWORD',\n },\n };\n case 'SELECT_CHALLENGE':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONTINUE_SIGN_IN_WITH_FIRST_FACTOR_SELECTION',\n availableChallenges,\n },\n };\n case 'ADMIN_NO_SRP_AUTH':\n break;\n case 'DEVICE_PASSWORD_VERIFIER':\n break;\n case 'DEVICE_SRP_AUTH':\n break;\n case 'PASSWORD_VERIFIER':\n break;\n }\n // TODO: remove this error message for production apps\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: 'An error occurred during the sign in process. ' +\n `${challengeName} challengeName returned by the underlying service was not addressed.`,\n });\n}\nexport function getTOTPSetupDetails(secretCode, username) {\n return {\n sharedSecret: secretCode,\n getSetupUri: (appName, accountName) => {\n const totpUri = `otpauth://totp/${appName}:${accountName ?? username}?secret=${secretCode}&issuer=${appName}`;\n return new AmplifyUrl(totpUri);\n },\n };\n}\nexport function getSignInResultFromError(errorName) {\n if (errorName === InitiateAuthException.PasswordResetRequiredException) {\n return {\n isSignedIn: false,\n nextStep: { signInStep: 'RESET_PASSWORD' },\n };\n }\n else if (errorName === InitiateAuthException.UserNotConfirmedException) {\n return {\n isSignedIn: false,\n nextStep: { signInStep: 'CONFIRM_SIGN_UP' },\n };\n }\n}\nexport function parseAttributes(attributes) {\n if (!attributes)\n return [];\n const parsedAttributes = JSON.parse(attributes).map(att => att.includes(USER_ATTRIBUTES) ? att.replace(USER_ATTRIBUTES, '') : att);\n return parsedAttributes;\n}\nexport function createAttributes(attributes) {\n if (!attributes)\n return {};\n const newAttributes = {};\n Object.entries(attributes).forEach(([key, value]) => {\n if (value)\n newAttributes[`${USER_ATTRIBUTES}${key}`] = value;\n });\n return newAttributes;\n}\nexport async function handleChallengeName(username, challengeName, session, challengeResponse, config, tokenOrchestrator, clientMetadata, options) {\n const userAttributes = options?.userAttributes;\n const deviceName = options?.friendlyDeviceName;\n switch (challengeName) {\n case 'WEB_AUTHN':\n case 'SELECT_CHALLENGE':\n if (challengeResponse === 'PASSWORD_SRP' ||\n challengeResponse === 'PASSWORD') {\n return {\n ChallengeName: challengeResponse,\n Session: session,\n $metadata: {},\n };\n }\n return initiateSelectedChallenge({\n username,\n session,\n selectedChallenge: challengeResponse,\n config,\n clientMetadata,\n });\n case 'SELECT_MFA_TYPE':\n return handleSelectMFATypeChallenge({\n challengeResponse,\n clientMetadata,\n session,\n username,\n config,\n tokenOrchestrator,\n });\n case 'MFA_SETUP':\n return handleMFASetupChallenge({\n challengeResponse,\n clientMetadata,\n session,\n username,\n deviceName,\n config,\n tokenOrchestrator,\n });\n case 'NEW_PASSWORD_REQUIRED':\n return handleCompleteNewPasswordChallenge({\n challengeResponse,\n clientMetadata,\n session,\n username,\n requiredAttributes: userAttributes,\n config,\n tokenOrchestrator,\n });\n case 'CUSTOM_CHALLENGE':\n return retryOnResourceNotFoundException(handleCustomChallenge, [\n {\n challengeResponse,\n clientMetadata,\n session,\n username,\n config,\n tokenOrchestrator,\n },\n ], username, tokenOrchestrator);\n case 'SMS_MFA':\n case 'SOFTWARE_TOKEN_MFA':\n case 'SMS_OTP':\n case 'EMAIL_OTP':\n return handleMFAChallenge({\n challengeName,\n challengeResponse,\n clientMetadata,\n session,\n username,\n config,\n tokenOrchestrator,\n });\n case 'PASSWORD':\n return handleSelectChallengeWithPassword(username, challengeResponse, clientMetadata, config, session);\n case 'PASSWORD_SRP':\n return handleSelectChallengeWithPasswordSRP(username, challengeResponse, // This is the actual password\n clientMetadata, config, session, tokenOrchestrator);\n }\n // TODO: remove this error message for production apps\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: `An error occurred during the sign in process.\n\t\t${challengeName} challengeName returned by the underlying service was not addressed.`,\n });\n}\nexport function mapMfaType(mfa) {\n let mfaType = 'SMS_MFA';\n if (mfa === 'TOTP')\n mfaType = 'SOFTWARE_TOKEN_MFA';\n if (mfa === 'EMAIL')\n mfaType = 'EMAIL_OTP';\n return mfaType;\n}\nexport function getMFAType(type) {\n if (type === 'SMS_MFA')\n return 'SMS';\n if (type === 'SOFTWARE_TOKEN_MFA')\n return 'TOTP';\n if (type === 'EMAIL_OTP')\n return 'EMAIL';\n // TODO: log warning for unknown MFA type\n}\nexport function getMFATypes(types) {\n if (!types)\n return undefined;\n return types.map(getMFAType).filter(Boolean);\n}\nexport function parseMFATypes(mfa) {\n if (!mfa)\n return [];\n return JSON.parse(mfa);\n}\nexport function getAllowedMfaSetupTypes(availableMfaSetupTypes) {\n return availableMfaSetupTypes.filter(authMfaType => authMfaType === 'EMAIL' || authMfaType === 'TOTP');\n}\nexport async function assertUserNotAuthenticated() {\n let authUser;\n try {\n authUser = await getCurrentUser();\n }\n catch (error) { }\n if (authUser && authUser.userId && authUser.username) {\n throw new AuthError({\n name: USER_ALREADY_AUTHENTICATED_EXCEPTION,\n message: 'There is already a signed in user.',\n recoverySuggestion: 'Call signOut before calling signIn again.',\n });\n }\n}\nexport function getActiveSignInUsername(username) {\n const state = signInStore.getState();\n return state.username ?? username;\n}\nexport async function handleMFAChallenge({ challengeName, challengeResponse, clientMetadata, session, username, config, tokenOrchestrator, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const challengeResponses = {\n USERNAME: username,\n };\n if (challengeName === 'EMAIL_OTP') {\n challengeResponses.EMAIL_OTP_CODE = challengeResponse;\n }\n if (challengeName === 'SMS_MFA') {\n challengeResponses.SMS_MFA_CODE = challengeResponse;\n }\n if (challengeName === 'SMS_OTP') {\n challengeResponses.SMS_OTP_CODE = challengeResponse;\n }\n if (challengeName === 'SOFTWARE_TOKEN_MFA') {\n challengeResponses.SOFTWARE_TOKEN_MFA_CODE = challengeResponse;\n }\n const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username);\n if (deviceMetadata && deviceMetadata.deviceKey) {\n challengeResponses.DEVICE_KEY = deviceMetadata.deviceKey;\n }\n const userContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n ChallengeName: challengeName,\n ChallengeResponses: challengeResponses,\n Session: session,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData: userContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n if (response.ChallengeName === 'DEVICE_SRP_AUTH') {\n return handleDeviceSRPAuth({\n username,\n config,\n clientMetadata,\n session: response.Session,\n tokenOrchestrator,\n });\n }\n return response;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError';\nimport { getActiveSignInUsername, getSignInResult, getSignInResultFromError, handleCustomAuthFlowWithoutSRP, } from '../utils/signInHelpers';\nimport { resetActiveSignInState, setActiveSignInState, } from '../../../client/utils/store/signInStore';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens';\nimport { tokenOrchestrator } from '../tokenProvider';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent';\nimport { retryOnResourceNotFoundException } from '../utils/retryOnResourceNotFoundException';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata';\n/**\n * Signs a user in using a custom authentication flow without password\n *\n * @param input - The SignInWithCustomAuthInput object\n * @returns AuthSignInResult\n * @throws service: {@link InitiateAuthException } - Cognito service errors thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password\n * are not defined.\n * @throws SignInWithCustomAuthOutput - Thrown when the token provider config is invalid.\n */\nexport async function signInWithCustomAuth(input) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { username, password, options } = input;\n const signInDetails = {\n loginId: username,\n authFlowType: 'CUSTOM_WITHOUT_SRP',\n };\n const metadata = options?.clientMetadata;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignInUsername);\n assertValidationError(!password, AuthValidationErrorCode.CustomAuthSignInPassword);\n try {\n const { ChallengeName: retriedChallengeName, ChallengeParameters: retiredChallengeParameters, AuthenticationResult, Session, } = await retryOnResourceNotFoundException(handleCustomAuthFlowWithoutSRP, [username, metadata, authConfig, tokenOrchestrator], username, tokenOrchestrator);\n const activeUsername = getActiveSignInUsername(username);\n // sets up local state used during the sign-in process\n setActiveSignInState({\n signInSession: Session,\n username: activeUsername,\n challengeName: retriedChallengeName,\n signInDetails,\n });\n if (AuthenticationResult) {\n await cacheCognitoTokens({\n username: activeUsername,\n ...AuthenticationResult,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: AuthenticationResult.NewDeviceMetadata,\n accessToken: AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: retriedChallengeName,\n challengeParameters: retiredChallengeParameters,\n });\n }\n catch (error) {\n resetActiveSignInState();\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError';\nimport { getActiveSignInUsername, getSignInResult, getSignInResultFromError, handleCustomSRPAuthFlow, } from '../utils/signInHelpers';\nimport { resetActiveSignInState, setActiveSignInState, } from '../../../client/utils/store/signInStore';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens';\nimport { tokenOrchestrator } from '../tokenProvider';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata';\n/**\n * Signs a user in using a custom authentication flow with SRP\n *\n * @param input - The SignInWithCustomSRPAuthInput object\n * @returns SignInWithCustomSRPAuthOutput\n * @throws service: {@link InitiateAuthException }, {@link RespondToAuthChallengeException } - Cognito\n * service errors thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function signInWithCustomSRPAuth(input) {\n const { username, password, options } = input;\n const signInDetails = {\n loginId: username,\n authFlowType: 'CUSTOM_WITH_SRP',\n };\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const metadata = options?.clientMetadata;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignInUsername);\n assertValidationError(!!password, AuthValidationErrorCode.EmptySignInPassword);\n try {\n const { ChallengeName: handledChallengeName, ChallengeParameters: handledChallengeParameters, AuthenticationResult, Session, } = await handleCustomSRPAuthFlow(username, password, metadata, authConfig, tokenOrchestrator);\n const activeUsername = getActiveSignInUsername(username);\n // sets up local state used during the sign-in process\n setActiveSignInState({\n signInSession: Session,\n username: activeUsername,\n challengeName: handledChallengeName,\n signInDetails,\n });\n if (AuthenticationResult) {\n await cacheCognitoTokens({\n username: activeUsername,\n ...AuthenticationResult,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: AuthenticationResult.NewDeviceMetadata,\n accessToken: AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: handledChallengeName,\n challengeParameters: handledChallengeParameters,\n });\n }\n catch (error) {\n resetActiveSignInState();\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { autoSignInStore } from '../../../client/utils/store';\nimport { AuthError } from '../../../errors/AuthError';\nimport { AUTO_SIGN_IN_EXCEPTION } from '../../../errors/constants';\nconst initialAutoSignIn = async () => {\n throw new AuthError({\n name: AUTO_SIGN_IN_EXCEPTION,\n message: 'The autoSignIn flow has not started, or has been cancelled/completed.',\n recoverySuggestion: 'Please try to use the signIn API or log out before starting a new autoSignIn flow.',\n });\n};\n/**\n * Signs a user in automatically after finishing the sign-up process.\n *\n * This API will automatically sign a user in if the autoSignIn flow has been completed in the following cases:\n * - User confirmed their account with a verification code sent to their phone or email (default option).\n * - User confirmed their account with a verification link sent to their phone or email. In order to\n * enable this option you need to go to the Amazon Cognito [console](https://aws.amazon.com/pm/cognito),\n * look for your userpool, then go to the `Messaging` tab and enable `link` mode inside the `Verification message` option.\n * Finally you need to define the `signUpVerificationMethod` in your `Auth` config.\n *\n * @example\n * ```typescript\n * Amplify.configure({\n * Auth: {\n * Cognito: {\n * ...cognitoConfig,\n * signUpVerificationMethod: \"link\" // the default value is \"code\"\n * }\n *\t}});\n * ```\n *\n * @throws AutoSignInException - Thrown when the autoSignIn flow has not started, or has been cancelled/completed.\n * @returns The signInOutput.\n *\n * @example\n * ```typescript\n * // handleSignUp.ts\n * async function handleSignUp(\n * username:string,\n * password:string\n * ){\n * try {\n * const { nextStep } = await signUp({\n * username,\n * password,\n * options: {\n * userAttributes:{ email:'email@email.com'},\n * autoSignIn: true // This enables the auto sign-in flow.\n * },\n * });\n *\n * handleSignUpStep(nextStep);\n *\n * } catch (error) {\n * console.log(error);\n * }\n * }\n *\n * // handleConfirmSignUp.ts\n * async function handleConfirmSignUp(username:string, confirmationCode:string) {\n * try {\n * const { nextStep } = await confirmSignUp({\n * username,\n * confirmationCode,\n * });\n *\n * handleSignUpStep(nextStep);\n * } catch (error) {\n * console.log(error);\n * }\n * }\n *\n * // signUpUtils.ts\n * async function handleSignUpStep( step: SignUpOutput[\"nextStep\"]) {\n * switch (step.signUpStep) {\n * case \"CONFIRM_SIGN_UP\":\n *\n * // Redirect end-user to confirm-sign up screen.\n *\n * case \"COMPLETE_AUTO_SIGN_IN\":\n *\t const codeDeliveryDetails = step.codeDeliveryDetails;\n * if (codeDeliveryDetails) {\n * // Redirect user to confirm-sign-up with link screen.\n * }\n * const signInOutput = await autoSignIn();\n * // handle sign-in steps\n * }\n *\n * ```\n */\n// TODO(Eslint): can this be refactored not using `let` on exported member?\n// eslint-disable-next-line import/no-mutable-exports\nexport let autoSignIn = initialAutoSignIn;\n/**\n * Sets the context of autoSignIn at run time.\n * @internal\n */\nexport function setAutoSignIn(callback) {\n autoSignIn = callback;\n}\n/**\n * Resets the context\n *\n * @internal\n */\nexport function resetAutoSignIn(resetCallback = true) {\n if (resetCallback) {\n autoSignIn = initialAutoSignIn;\n }\n autoSignInStore.dispatch({ type: 'RESET' });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError';\nimport { getActiveSignInUsername, getSignInResult, getSignInResultFromError, handleUserSRPAuthFlow, } from '../utils/signInHelpers';\nimport { resetActiveSignInState, setActiveSignInState, } from '../../../client/utils/store/signInStore';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens';\nimport { tokenOrchestrator } from '../tokenProvider';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata';\nimport { resetAutoSignIn } from './autoSignIn';\n/**\n * Signs a user in\n *\n * @param input - The SignInWithSRPInput object\n * @returns SignInWithSRPOutput\n * @throws service: {@link InitiateAuthException }, {@link RespondToAuthChallengeException } - Cognito service errors\n * thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function signInWithSRP(input) {\n const { username, password } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n const signInDetails = {\n loginId: username,\n authFlowType: 'USER_SRP_AUTH',\n };\n assertTokenProviderConfig(authConfig);\n const clientMetaData = input.options?.clientMetadata;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignInUsername);\n assertValidationError(!!password, AuthValidationErrorCode.EmptySignInPassword);\n try {\n const { ChallengeName: handledChallengeName, ChallengeParameters: handledChallengeParameters, AuthenticationResult, Session, } = await handleUserSRPAuthFlow(username, password, clientMetaData, authConfig, tokenOrchestrator);\n const activeUsername = getActiveSignInUsername(username);\n // sets up local state used during the sign-in process\n setActiveSignInState({\n signInSession: Session,\n username: activeUsername,\n challengeName: handledChallengeName,\n signInDetails,\n });\n if (AuthenticationResult) {\n await cacheCognitoTokens({\n username: activeUsername,\n ...AuthenticationResult,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: AuthenticationResult.NewDeviceMetadata,\n accessToken: AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n resetAutoSignIn();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: handledChallengeName,\n challengeParameters: handledChallengeParameters,\n });\n }\n catch (error) {\n resetActiveSignInState();\n resetAutoSignIn();\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { getActiveSignInUsername, getSignInResult, getSignInResultFromError, handleUserPasswordAuthFlow, } from '../utils/signInHelpers';\nimport { resetActiveSignInState, setActiveSignInState, } from '../../../client/utils/store/signInStore';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens';\nimport { tokenOrchestrator } from '../tokenProvider';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent';\nimport { retryOnResourceNotFoundException } from '../utils/retryOnResourceNotFoundException';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata';\nimport { resetAutoSignIn } from './autoSignIn';\n/**\n * Signs a user in using USER_PASSWORD_AUTH AuthFlowType\n *\n * @param input - The SignInWithUserPasswordInput object\n * @returns SignInWithUserPasswordOutput\n * @throws service: {@link InitiateAuthException } - Cognito service error thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function signInWithUserPassword(input) {\n const { username, password, options } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n const signInDetails = {\n loginId: username,\n authFlowType: 'USER_PASSWORD_AUTH',\n };\n assertTokenProviderConfig(authConfig);\n const metadata = options?.clientMetadata;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignInUsername);\n assertValidationError(!!password, AuthValidationErrorCode.EmptySignInPassword);\n try {\n const { ChallengeName: retiredChallengeName, ChallengeParameters: retriedChallengeParameters, AuthenticationResult, Session, } = await retryOnResourceNotFoundException(handleUserPasswordAuthFlow, [username, password, metadata, authConfig, tokenOrchestrator], username, tokenOrchestrator);\n const activeUsername = getActiveSignInUsername(username);\n // sets up local state used during the sign-in process\n setActiveSignInState({\n signInSession: Session,\n username: activeUsername,\n challengeName: retiredChallengeName,\n signInDetails,\n });\n if (AuthenticationResult) {\n await cacheCognitoTokens({\n ...AuthenticationResult,\n username: activeUsername,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: AuthenticationResult.NewDeviceMetadata,\n accessToken: AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n resetAutoSignIn();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: retiredChallengeName,\n challengeParameters: retriedChallengeParameters,\n });\n }\n catch (error) {\n resetActiveSignInState();\n resetAutoSignIn();\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthAction } from '@aws-amplify/core/internals/utils';\nimport { getUserContextData } from '../../../providers/cognito/utils/userContextData';\nimport { createInitiateAuthClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { handlePasswordSRP } from '../shared/handlePasswordSRP';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { setActiveSignInUsername } from '../../../providers/cognito/utils/setActiveSignInUsername';\n/**\n * Handles user authentication flow with configurable challenge preferences.\n * Supports AuthFactorType challenges through the USER_AUTH flow.\n *\n * @param {HandleUserAuthFlowInput} params - Authentication flow parameters\n * @param {string} params.username - The username for authentication\n * @param {Record<string, string>} [params.clientMetadata] - Optional metadata to pass to authentication service\n * @param {CognitoUserPoolConfig} params.config - Cognito User Pool configuration\n * @param {AuthTokenOrchestrator} params.tokenOrchestrator - Manages authentication tokens and device tracking\n * @param {AuthFactorType} [params.preferredChallenge] - Optional preferred authentication method\n * @param {string} [params.password] - Required when preferredChallenge is 'PASSWORD' or 'PASSWORD_SRP'\n *\n * @returns {Promise<InitiateAuthCommandOutput>} The authentication response from Cognito\n */\nexport async function handleUserAuthFlow({ username, clientMetadata, config, tokenOrchestrator, preferredChallenge, password, session, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const authParameters = { USERNAME: username };\n if (preferredChallenge) {\n if (preferredChallenge === 'PASSWORD_SRP') {\n assertValidationError(!!password, AuthValidationErrorCode.EmptySignInPassword);\n return handlePasswordSRP({\n username,\n password,\n clientMetadata,\n config,\n tokenOrchestrator,\n authFlow: 'USER_AUTH',\n preferredChallenge,\n });\n }\n if (preferredChallenge === 'PASSWORD') {\n assertValidationError(!!password, AuthValidationErrorCode.EmptySignInPassword);\n authParameters.PASSWORD = password;\n }\n authParameters.PREFERRED_CHALLENGE = preferredChallenge;\n }\n const jsonReq = {\n AuthFlow: 'USER_AUTH',\n AuthParameters: authParameters,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n if (session) {\n jsonReq.Session = session;\n }\n const initiateAuth = createInitiateAuthClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await initiateAuth({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignIn),\n }, jsonReq);\n // Set the active username immediately after successful authentication attempt\n // If a user starts a new sign-in while another sign-in is incomplete,\n // this ensures we're tracking the correct user for subsequent auth challenges.\n setActiveSignInUsername(username);\n return response;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError';\nimport { getActiveSignInUsername, getSignInResult, getSignInResultFromError, } from '../utils/signInHelpers';\nimport { autoSignInStore } from '../../../client/utils/store';\nimport { resetActiveSignInState, setActiveSignInState, } from '../../../client/utils/store/signInStore';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent';\nimport { tokenOrchestrator } from '../tokenProvider';\nimport { handleUserAuthFlow, } from '../../../client/flows/userAuth/handleUserAuthFlow';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata';\nimport { resetAutoSignIn } from './autoSignIn';\n/**\n * Signs a user in through a registered email or phone number without a password by by receiving and entering an OTP.\n *\n * @param input - The SignInWithUserAuthInput object\n * @returns SignInWithUserAuthOutput\n * @throws service: {@link InitiateAuthException }, {@link RespondToAuthChallengeException } - Cognito service errors\n * thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password -- needs to change\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function signInWithUserAuth(input) {\n const { username, password, options } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n const signInDetails = {\n loginId: username,\n authFlowType: 'USER_AUTH',\n };\n assertTokenProviderConfig(authConfig);\n const clientMetaData = options?.clientMetadata;\n const preferredChallenge = options?.preferredChallenge;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignInUsername);\n try {\n const handleUserAuthFlowInput = {\n username,\n config: authConfig,\n tokenOrchestrator,\n clientMetadata: clientMetaData,\n preferredChallenge,\n password,\n };\n const autoSignInStoreState = autoSignInStore.getState();\n if (autoSignInStoreState.active &&\n autoSignInStoreState.username === username) {\n handleUserAuthFlowInput.session = autoSignInStoreState.session;\n }\n const response = await handleUserAuthFlow(handleUserAuthFlowInput);\n const activeUsername = getActiveSignInUsername(username);\n setActiveSignInState({\n signInSession: response.Session,\n username: activeUsername,\n challengeName: response.ChallengeName,\n signInDetails,\n });\n if (response.AuthenticationResult) {\n await cacheCognitoTokens({\n username: activeUsername,\n ...response.AuthenticationResult,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: response.AuthenticationResult.NewDeviceMetadata,\n accessToken: response.AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n resetAutoSignIn();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: response.ChallengeName,\n challengeParameters: response.ChallengeParameters,\n availableChallenges: 'AvailableChallenges' in response\n ? response.AvailableChallenges\n : undefined,\n });\n }\n catch (error) {\n resetActiveSignInState();\n resetAutoSignIn();\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { assertUserNotAuthenticated } from '../utils/signInHelpers';\nimport { signInWithCustomAuth } from './signInWithCustomAuth';\nimport { signInWithCustomSRPAuth } from './signInWithCustomSRPAuth';\nimport { signInWithSRP } from './signInWithSRP';\nimport { signInWithUserPassword } from './signInWithUserPassword';\nimport { signInWithUserAuth } from './signInWithUserAuth';\nimport { resetAutoSignIn } from './autoSignIn';\n/**\n * Signs a user in\n *\n * @param input - The SignInInput object\n * @returns SignInOutput\n * @throws service: {@link InitiateAuthException }, {@link RespondToAuthChallengeException }\n * - Cognito service errors thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function signIn(input) {\n // Here we want to reset the store but not reassign the callback.\n // The callback is reset when the underlying promise resolves or rejects.\n // With the advent of session based sign in, this guarantees that the signIn API initiates a new auth flow,\n // regardless of whether it is called for a user currently engaged in an active auto sign in session.\n resetAutoSignIn(false);\n const authFlowType = input.options?.authFlowType;\n await assertUserNotAuthenticated();\n switch (authFlowType) {\n case 'USER_SRP_AUTH':\n return signInWithSRP(input);\n case 'USER_PASSWORD_AUTH':\n return signInWithUserPassword(input);\n case 'CUSTOM_WITHOUT_SRP':\n return signInWithCustomAuth(input);\n case 'CUSTOM_WITH_SRP':\n return signInWithCustomSRPAuth(input);\n case 'USER_AUTH':\n return signInWithUserAuth(input);\n default:\n return signInWithSRP(input);\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { HubInternal } from '@aws-amplify/core/internals/utils';\nimport { signIn } from '../apis/signIn';\nimport { AuthError } from '../../../errors/AuthError';\nimport { resetAutoSignIn, setAutoSignIn } from '../apis/autoSignIn';\nimport { AUTO_SIGN_IN_EXCEPTION } from '../../../errors/constants';\nimport { signInWithUserAuth } from '../apis/signInWithUserAuth';\nconst MAX_AUTOSIGNIN_POLLING_MS = 3 * 60 * 1000;\nexport function handleCodeAutoSignIn(signInInput) {\n const stopHubListener = HubInternal.listen('auth-internal', async ({ payload }) => {\n switch (payload.event) {\n case 'confirmSignUp': {\n const response = payload.data;\n if (response?.isSignUpComplete) {\n HubInternal.dispatch('auth-internal', {\n event: 'autoSignIn',\n });\n setAutoSignIn(autoSignInWithCode(signInInput));\n stopHubListener();\n }\n }\n }\n });\n // This will stop the listener if confirmSignUp is not resolved.\n const timeOutId = setTimeout(() => {\n stopHubListener();\n clearTimeout(timeOutId);\n resetAutoSignIn();\n }, MAX_AUTOSIGNIN_POLLING_MS);\n}\nfunction debounce(fun, delay) {\n let timer;\n return (args) => {\n if (!timer) {\n fun(...args);\n }\n clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n }, delay);\n };\n}\nfunction handleAutoSignInWithLink(signInInput, resolve, reject) {\n const start = Date.now();\n const autoSignInPollingIntervalId = setInterval(async () => {\n const elapsedTime = Date.now() - start;\n const maxTime = MAX_AUTOSIGNIN_POLLING_MS;\n if (elapsedTime > maxTime) {\n clearInterval(autoSignInPollingIntervalId);\n reject(new AuthError({\n name: AUTO_SIGN_IN_EXCEPTION,\n message: 'The account was not confirmed on time.',\n recoverySuggestion: 'Try to verify your account by clicking the link sent your email or phone and then login manually.',\n }));\n resetAutoSignIn();\n }\n else {\n try {\n const signInOutput = await signIn(signInInput);\n if (signInOutput.nextStep.signInStep !== 'CONFIRM_SIGN_UP') {\n resolve(signInOutput);\n clearInterval(autoSignInPollingIntervalId);\n resetAutoSignIn();\n }\n }\n catch (error) {\n clearInterval(autoSignInPollingIntervalId);\n reject(error);\n resetAutoSignIn();\n }\n }\n }, 5000);\n}\nconst debouncedAutoSignInWithLink = debounce(handleAutoSignInWithLink, 300);\nconst debouncedAutoSignWithCodeOrUserConfirmed = debounce(handleAutoSignInWithCodeOrUserConfirmed, 300);\nexport function autoSignInWhenUserIsConfirmedWithLink(signInInput) {\n return async () => {\n return new Promise((resolve, reject) => {\n debouncedAutoSignInWithLink([signInInput, resolve, reject]);\n });\n };\n}\nasync function handleAutoSignInWithCodeOrUserConfirmed(signInInput, resolve, reject) {\n try {\n const output = signInInput?.options?.authFlowType === 'USER_AUTH'\n ? await signInWithUserAuth(signInInput)\n : await signIn(signInInput);\n resolve(output);\n resetAutoSignIn();\n }\n catch (error) {\n reject(error);\n resetAutoSignIn();\n }\n}\nfunction autoSignInWithCode(signInInput) {\n return async () => {\n return new Promise((resolve, reject) => {\n debouncedAutoSignWithCodeOrUserConfirmed([signInInput, resolve, reject]);\n });\n };\n}\nexport const autoSignInUserConfirmed = autoSignInWithCode;\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { parseJsonBody, parseJsonError, } from '@aws-amplify/core/internals/aws-client-utils';\nimport { validationErrorMap } from '../../../../common/AuthErrorStrings';\nimport { AuthError } from '../../../../errors/AuthError';\nimport { AuthValidationErrorCode } from '../../../../errors/types/validation';\nimport { assertServiceError } from '../../../../errors/utils/assertServiceError';\nimport { SignUpException } from '../../../../providers/cognito/types/errors';\nimport { createUserPoolSerializer } from './shared/serde';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createSignUpClientDeserializer = () => async (response) => {\n if (response.statusCode >= 300) {\n const error = await parseJsonError(response);\n assertServiceError(error);\n if (\n // Missing Password Error\n // 1 validation error detected: Value at 'password'failed to satisfy constraint: Member must not be null\n error.name === SignUpException.InvalidParameterException &&\n /'password'/.test(error.message) &&\n /Member must not be null/.test(error.message)) {\n const name = AuthValidationErrorCode.EmptySignUpPassword;\n const { message, recoverySuggestion } = validationErrorMap[name];\n throw new AuthError({\n name,\n message,\n recoverySuggestion,\n });\n }\n throw new AuthError({ name: error.name, message: error.message });\n }\n return parseJsonBody(response);\n};\nexport const createSignUpClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('SignUp'), createSignUpClientDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { toAttributeType } from '../utils/apiHelpers';\nimport { autoSignInUserConfirmed, autoSignInWhenUserIsConfirmedWithLink, handleCodeAutoSignIn, } from '../utils/signUpHelpers';\nimport { getUserContextData } from '../utils/userContextData';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createSignUpClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\nimport { autoSignInStore } from '../../../client/utils/store';\nimport { setAutoSignIn } from './autoSignIn';\n/**\n * Creates a user\n *\n * @param input - The SignUpInput object\n * @returns SignUpOutput\n * @throws service: {@link SignUpException } - Cognito service errors thrown during the sign-up process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown either username or password\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function signUp(input) {\n const { username, password, options } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n const signUpVerificationMethod = authConfig?.signUpVerificationMethod ?? 'code';\n const { clientMetadata, validationData, autoSignIn } = input.options ?? {};\n assertTokenProviderConfig(authConfig);\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignUpUsername);\n const signInServiceOptions = typeof autoSignIn !== 'boolean' ? autoSignIn : undefined;\n const signInInput = {\n username,\n options: signInServiceOptions,\n };\n // if the authFlowType is 'CUSTOM_WITHOUT_SRP' then we don't include the password\n if (signInServiceOptions?.authFlowType !== 'CUSTOM_WITHOUT_SRP') {\n signInInput.password = password;\n }\n const { userPoolId, userPoolClientId, userPoolEndpoint } = authConfig;\n const signUpClient = createSignUpClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const signUpClientInput = {\n Username: username,\n Password: undefined,\n UserAttributes: options?.userAttributes && toAttributeType(options?.userAttributes),\n ClientMetadata: clientMetadata,\n ValidationData: validationData && toAttributeType(validationData),\n ClientId: userPoolClientId,\n UserContextData: getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n }),\n };\n if (password) {\n signUpClientInput.Password = password;\n }\n const { UserSub: userId, CodeDeliveryDetails: cdd, UserConfirmed: userConfirmed, Session: session, } = await signUpClient({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignUp),\n }, signUpClientInput);\n if (signInServiceOptions || autoSignIn === true) {\n autoSignInStore.dispatch({ type: 'START' });\n autoSignInStore.dispatch({ type: 'SET_USERNAME', value: username });\n autoSignInStore.dispatch({ type: 'SET_SESSION', value: session });\n }\n const codeDeliveryDetails = {\n destination: cdd?.Destination,\n deliveryMedium: cdd?.DeliveryMedium,\n attributeName: cdd?.AttributeName,\n };\n const isSignUpComplete = !!userConfirmed;\n const isAutoSignInStarted = autoSignInStore.getState().active;\n // Sign Up Complete\n // No Confirm Sign In Step Required\n if (isSignUpComplete) {\n if (isAutoSignInStarted) {\n setAutoSignIn(autoSignInUserConfirmed(signInInput));\n return {\n isSignUpComplete: true,\n nextStep: {\n signUpStep: 'COMPLETE_AUTO_SIGN_IN',\n },\n userId,\n };\n }\n return {\n isSignUpComplete: true,\n nextStep: {\n signUpStep: 'DONE',\n },\n userId,\n };\n }\n // Sign Up Not Complete\n // Confirm Sign Up Step Required\n if (isAutoSignInStarted) {\n // Confirmation Via Link Occurs In Separate Context\n // AutoSignIn Fn Will Initiate Polling Once Executed\n if (signUpVerificationMethod === 'link') {\n setAutoSignIn(autoSignInWhenUserIsConfirmedWithLink(signInInput));\n return {\n isSignUpComplete: false,\n nextStep: {\n signUpStep: 'COMPLETE_AUTO_SIGN_IN',\n codeDeliveryDetails,\n },\n userId,\n };\n }\n // Confirmation Via Code Occurs In Same Context\n // AutoSignIn Next Step Will Be Returned From Confirm Sign Up\n handleCodeAutoSignIn(signInInput);\n }\n return {\n isSignUpComplete: false,\n nextStep: {\n signUpStep: 'CONFIRM_SIGN_UP',\n codeDeliveryDetails,\n },\n userId,\n };\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createForgotPasswordClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ForgotPassword'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { getUserContextData } from '../utils/userContextData';\nimport { createForgotPasswordClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Resets a user's password.\n *\n * @param input - The ResetPasswordInput object.\n * @returns ResetPasswordOutput\n * @throws -{@link ForgotPasswordException }\n * Thrown due to an invalid confirmation code or password.\n * @throws -{@link AuthValidationErrorCode }\n * Thrown due to an empty username.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n **/\nexport async function resetPassword(input) {\n const { username } = input;\n assertValidationError(!!username, AuthValidationErrorCode.EmptyResetPasswordUsername);\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolClientId, userPoolId, userPoolEndpoint } = authConfig;\n const clientMetadata = input.options?.clientMetadata;\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const forgotPassword = createForgotPasswordClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const res = await forgotPassword({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ResetPassword),\n }, {\n Username: username,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n });\n const codeDeliveryDetails = res.CodeDeliveryDetails;\n return {\n isPasswordReset: false,\n nextStep: {\n resetPasswordStep: 'CONFIRM_RESET_PASSWORD_WITH_CODE',\n codeDeliveryDetails: {\n deliveryMedium: codeDeliveryDetails?.DeliveryMedium,\n destination: codeDeliveryDetails?.Destination,\n attributeName: codeDeliveryDetails?.AttributeName,\n },\n },\n };\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createConfirmForgotPasswordClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ConfirmForgotPassword'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { getUserContextData } from '../utils/userContextData';\nimport { createConfirmForgotPasswordClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\n/**\n * Confirms the new password and verification code to reset the password.\n *\n * @param input - The ConfirmResetPasswordInput object.\n * @throws -{@link ConfirmForgotPasswordException }\n * Thrown due to an invalid confirmation code or password.\n * @throws -{@link AuthValidationErrorCode }\n * Thrown due to an empty confirmation code, password or username.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function confirmResetPassword(input) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolClientId, userPoolId, userPoolEndpoint } = authConfig;\n const { username, newPassword } = input;\n assertValidationError(!!username, AuthValidationErrorCode.EmptyConfirmResetPasswordUsername);\n assertValidationError(!!newPassword, AuthValidationErrorCode.EmptyConfirmResetPasswordNewPassword);\n const code = input.confirmationCode;\n assertValidationError(!!code, AuthValidationErrorCode.EmptyConfirmResetPasswordConfirmationCode);\n const metadata = input.options?.clientMetadata;\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const confirmForgotPassword = createConfirmForgotPasswordClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await confirmForgotPassword({\n region: getRegionFromUserPoolId(authConfig.userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmResetPassword),\n }, {\n Username: username,\n ConfirmationCode: code,\n Password: newPassword,\n ClientMetadata: metadata,\n ClientId: authConfig.userPoolClientId,\n UserContextData,\n });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createResendConfirmationCodeClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ResendConfirmationCode'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { getUserContextData } from '../utils/userContextData';\nimport { createResendConfirmationCodeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Resend the confirmation code while signing up\n *\n * @param input - The ResendSignUpCodeInput object\n * @returns ResendSignUpCodeOutput\n * @throws service: {@link ResendConfirmationException } - Cognito service errors thrown when resending the code.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown either username are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function resendSignUpCode(input) {\n const { username } = input;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignUpUsername);\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolClientId, userPoolId, userPoolEndpoint } = authConfig;\n const clientMetadata = input.options?.clientMetadata;\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const resendConfirmationCode = createResendConfirmationCodeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { CodeDeliveryDetails } = await resendConfirmationCode({\n region: getRegionFromUserPoolId(authConfig.userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ResendSignUpCode),\n }, {\n Username: username,\n ClientMetadata: clientMetadata,\n ClientId: authConfig.userPoolClientId,\n UserContextData,\n });\n const { DeliveryMedium, AttributeName, Destination } = {\n ...CodeDeliveryDetails,\n };\n return {\n destination: Destination,\n deliveryMedium: DeliveryMedium,\n attributeName: AttributeName\n ? AttributeName\n : undefined,\n };\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nexport const createConfirmSignUpClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ConfirmSignUp'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { AuthAction, HubInternal, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { getUserContextData } from '../utils/userContextData';\nimport { createConfirmSignUpClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\nimport { autoSignInStore } from '../../../client/utils/store';\nimport { resetAutoSignIn } from './autoSignIn';\n/**\n * Confirms a new user account.\n *\n * @param input - The ConfirmSignUpInput object.\n * @returns ConfirmSignUpOutput\n * @throws -{@link ConfirmSignUpException }\n * Thrown due to an invalid confirmation code.\n * @throws -{@link AuthValidationErrorCode }\n * Thrown due to an empty confirmation code\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function confirmSignUp(input) {\n const { username, confirmationCode, options } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolId, userPoolClientId, userPoolEndpoint } = authConfig;\n const clientMetadata = options?.clientMetadata;\n assertValidationError(!!username, AuthValidationErrorCode.EmptyConfirmSignUpUsername);\n assertValidationError(!!confirmationCode, AuthValidationErrorCode.EmptyConfirmSignUpCode);\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const confirmSignUpClient = createConfirmSignUpClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { Session: session } = await confirmSignUpClient({\n region: getRegionFromUserPoolId(authConfig.userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignUp),\n }, {\n Username: username,\n ConfirmationCode: confirmationCode,\n ClientMetadata: clientMetadata,\n ForceAliasCreation: options?.forceAliasCreation,\n ClientId: authConfig.userPoolClientId,\n UserContextData,\n });\n return new Promise((resolve, reject) => {\n try {\n const signUpOut = {\n isSignUpComplete: true,\n nextStep: {\n signUpStep: 'DONE',\n },\n };\n const autoSignInStoreState = autoSignInStore.getState();\n if (!autoSignInStoreState.active ||\n autoSignInStoreState.username !== username) {\n resolve(signUpOut);\n resetAutoSignIn();\n return;\n }\n autoSignInStore.dispatch({ type: 'SET_SESSION', value: session });\n const stopListener = HubInternal.listen('auth-internal', ({ payload }) => {\n switch (payload.event) {\n case 'autoSignIn':\n resolve({\n isSignUpComplete: true,\n nextStep: {\n signUpStep: 'COMPLETE_AUTO_SIGN_IN',\n },\n });\n stopListener();\n }\n });\n HubInternal.dispatch('auth-internal', {\n event: 'confirmSignUp',\n data: signUpOut,\n });\n }\n catch (error) {\n reject(error);\n }\n });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { resetActiveSignInState, setActiveSignInState, signInStore, } from '../../../client/utils/store';\nimport { AuthError } from '../../../errors/AuthError';\nimport { getSignInResult, getSignInResultFromError, handleChallengeName, } from '../utils/signInHelpers';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { AuthErrorCodes } from '../../../common/AuthErrorStrings';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens';\nimport { tokenOrchestrator } from '../tokenProvider';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata';\n/**\n * Continues or completes the sign in process when required by the initial call to `signIn`.\n *\n * @param input - The ConfirmSignInInput object\n * @returns ConfirmSignInOutput\n * @throws -{@link VerifySoftwareTokenException }:\n * Thrown due to an invalid MFA token.\n * @throws -{@link RespondToAuthChallengeException }:\n * Thrown due to an invalid auth challenge response.\n * @throws -{@link AssociateSoftwareTokenException}:\n * Thrown due to a service error during the MFA setup process.\n * @throws -{@link AuthValidationErrorCode }:\n * Thrown when `challengeResponse` is not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function confirmSignIn(input) {\n const { challengeResponse, options } = input;\n const { username, challengeName, signInSession, signInDetails } = signInStore.getState();\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const clientMetaData = options?.clientMetadata;\n assertValidationError(!!challengeResponse, AuthValidationErrorCode.EmptyChallengeResponse);\n if (!username || !challengeName || !signInSession)\n // TODO: remove this error message for production apps\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: `\n\t\t\tAn error occurred during the sign in process.\n\n\t\t\tThis most likely occurred due to:\n\t\t\t1. signIn was not called before confirmSignIn.\n\t\t\t2. signIn threw an exception.\n\t\t\t3. page was refreshed during the sign in flow and session has expired.\n\t\t\t`,\n recoverySuggestion: 'Make sure a successful call to signIn is made before calling confirmSignIn' +\n 'and that the session has not expired.',\n });\n try {\n const { Session, ChallengeName: handledChallengeName, AuthenticationResult, ChallengeParameters: handledChallengeParameters, } = await handleChallengeName(username, challengeName, signInSession, challengeResponse, authConfig, tokenOrchestrator, clientMetaData, options);\n // sets up local state used during the sign-in process\n setActiveSignInState({\n signInSession: Session,\n username,\n challengeName: handledChallengeName,\n signInDetails,\n });\n if (AuthenticationResult) {\n await cacheCognitoTokens({\n username,\n ...AuthenticationResult,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: AuthenticationResult.NewDeviceMetadata,\n accessToken: AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: handledChallengeName,\n challengeParameters: handledChallengeParameters,\n });\n }\n catch (error) {\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createSetUserMFAPreferenceClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('SetUserMFAPreference'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { assertAuthTokens } from '../utils/types';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createSetUserMFAPreferenceClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Updates the MFA preference of the user.\n *\n * @param input - The UpdateMFAPreferenceInput object.\n * @throws -{@link SetUserMFAPreferenceException } - Service error thrown when the MFA preference cannot be updated.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function updateMFAPreference(input) {\n const { sms, totp, email } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession({ forceRefresh: false });\n assertAuthTokens(tokens);\n const setUserMFAPreference = createSetUserMFAPreferenceClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await setUserMFAPreference({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.UpdateMFAPreference),\n }, {\n AccessToken: tokens.accessToken.toString(),\n SMSMfaSettings: getMFASettings(sms),\n SoftwareTokenMfaSettings: getMFASettings(totp),\n EmailMfaSettings: getMFASettings(email),\n });\n}\nexport function getMFASettings(mfaPreference) {\n if (mfaPreference === 'DISABLED') {\n return {\n Enabled: false,\n };\n }\n else if (mfaPreference === 'PREFERRED') {\n return {\n Enabled: true,\n PreferredMfa: true,\n };\n }\n else if (mfaPreference === 'ENABLED') {\n return {\n Enabled: true,\n };\n }\n else if (mfaPreference === 'NOT_PREFERRED') {\n return {\n Enabled: true,\n PreferredMfa: false,\n };\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createGetUserClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('GetUser'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { getMFAType, getMFATypes } from '../utils/signInHelpers';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { assertAuthTokens } from '../utils/types';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createGetUserClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Fetches the preferred MFA setting and enabled MFA settings for the user.\n *\n * @returns FetchMFAPreferenceOutput\n * @throws -{@link GetUserException} : error thrown when the service fails to fetch MFA preference\n * and settings.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function fetchMFAPreference() {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession({ forceRefresh: false });\n assertAuthTokens(tokens);\n const getUser = createGetUserClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { PreferredMfaSetting, UserMFASettingList } = await getUser({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.FetchMFAPreference),\n }, {\n AccessToken: tokens.accessToken.toString(),\n });\n return {\n preferred: getMFAType(PreferredMfaSetting),\n enabled: getMFATypes(UserMFASettingList),\n };\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { assertAuthTokens } from '../utils/types';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createVerifySoftwareTokenClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Verifies an OTP code retrieved from an associated authentication app.\n *\n * @param input - The VerifyTOTPSetupInput\n * @throws -{@link VerifySoftwareTokenException }:\n * Thrown due to an invalid MFA token.\n * @throws -{@link AuthValidationErrorCode }:\n * Thrown when `code` is not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function verifyTOTPSetup(input) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { code, options } = input;\n assertValidationError(!!code, AuthValidationErrorCode.EmptyVerifyTOTPSetupCode);\n const { tokens } = await fetchAuthSession({ forceRefresh: false });\n assertAuthTokens(tokens);\n const verifySoftwareToken = createVerifySoftwareTokenClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await verifySoftwareToken({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.VerifyTOTPSetup),\n }, {\n AccessToken: tokens.accessToken.toString(),\n UserCode: code,\n FriendlyDeviceName: options?.friendlyDeviceName,\n });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createChangePasswordClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ChangePassword'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { assertAuthTokens } from '../utils/types';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createChangePasswordClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Updates user's password while authenticated.\n *\n * @param input - The UpdatePasswordInput object.\n * @throws - {@link ChangePasswordException} - Cognito service errors thrown when updating a password.\n * @throws - {@link AuthValidationErrorCode} - Validation errors thrown when oldPassword or newPassword are empty.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function updatePassword(input) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { oldPassword, newPassword } = input;\n assertValidationError(!!oldPassword, AuthValidationErrorCode.EmptyUpdatePassword);\n assertValidationError(!!newPassword, AuthValidationErrorCode.EmptyUpdatePassword);\n const { tokens } = await fetchAuthSession({ forceRefresh: false });\n assertAuthTokens(tokens);\n const changePassword = createChangePasswordClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await changePassword({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.UpdatePassword),\n }, {\n AccessToken: tokens.accessToken.toString(),\n PreviousPassword: oldPassword,\n ProposedPassword: newPassword,\n });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError';\nimport { SETUP_TOTP_EXCEPTION, } from '../types/errors';\nimport { getTOTPSetupDetails } from '../utils/signInHelpers';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { assertAuthTokens } from '../utils/types';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createAssociateSoftwareTokenClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Sets up TOTP for the user.\n *\n * @returns SetUpTOTPOutput\n * @throws -{@link AssociateSoftwareTokenException}\n * Thrown if a service occurs while setting up TOTP.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n **/\nexport async function setUpTOTP() {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession({ forceRefresh: false });\n assertAuthTokens(tokens);\n const username = tokens.idToken?.payload['cognito:username'] ?? '';\n const associateSoftwareToken = createAssociateSoftwareTokenClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { SecretCode } = await associateSoftwareToken({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SetUpTOTP),\n }, {\n AccessToken: tokens.accessToken.toString(),\n });\n if (!SecretCode) {\n // This should never happen.\n throw new AuthError({\n name: SETUP_TOTP_EXCEPTION,\n message: 'Failed to set up TOTP.',\n });\n }\n return getTOTPSetupDetails(SecretCode, JSON.stringify(username));\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createUpdateUserAttributesClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('UpdateUserAttributes'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { assertAuthTokens } from '../utils/types';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { toAttributeType } from '../utils/apiHelpers';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createUpdateUserAttributesClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Updates user's attributes while authenticated.\n *\n * @param input - The UpdateUserAttributesInput object\n * @returns UpdateUserAttributesOutput\n * @throws - {@link UpdateUserAttributesException}\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport const updateUserAttributes = async (input) => {\n const { userAttributes, options } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n const clientMetadata = options?.clientMetadata;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession({ forceRefresh: false });\n assertAuthTokens(tokens);\n const updateUserAttributesClient = createUpdateUserAttributesClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { CodeDeliveryDetailsList } = await updateUserAttributesClient({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.UpdateUserAttributes),\n }, {\n AccessToken: tokens.accessToken.toString(),\n ClientMetadata: clientMetadata,\n UserAttributes: toAttributeType(userAttributes),\n });\n return {\n ...getConfirmedAttributes(userAttributes),\n ...getUnConfirmedAttributes(CodeDeliveryDetailsList),\n };\n};\nfunction getConfirmedAttributes(attributes) {\n const confirmedAttributes = {};\n Object.keys(attributes)?.forEach(key => {\n confirmedAttributes[key] = {\n isUpdated: true,\n nextStep: {\n updateAttributeStep: 'DONE',\n },\n };\n });\n return confirmedAttributes;\n}\nfunction getUnConfirmedAttributes(codeDeliveryDetailsList) {\n const unConfirmedAttributes = {};\n codeDeliveryDetailsList?.forEach(codeDeliveryDetails => {\n const { AttributeName, DeliveryMedium, Destination } = codeDeliveryDetails;\n if (AttributeName)\n unConfirmedAttributes[AttributeName] = {\n isUpdated: false,\n nextStep: {\n updateAttributeStep: 'CONFIRM_ATTRIBUTE_WITH_CODE',\n codeDeliveryDetails: {\n attributeName: AttributeName,\n deliveryMedium: DeliveryMedium,\n destination: Destination,\n },\n },\n };\n });\n return unConfirmedAttributes;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { updateUserAttributes } from './updateUserAttributes';\n/**\n * Updates user's attribute while authenticated.\n *\n * @param input - The UpdateUserAttributeInput object\n * @returns UpdateUserAttributeOutput\n * @throws - {@link UpdateUserAttributesException}\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport const updateUserAttribute = async (input) => {\n const { userAttribute: { attributeKey, value }, options, } = input;\n const output = await updateUserAttributes({\n userAttributes: { [attributeKey]: value },\n options,\n });\n return Object.values(output)[0];\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createVerifyUserAttributeClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('VerifyUserAttribute'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { assertAuthTokens } from '../utils/types';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createVerifyUserAttributeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Confirms a user attribute with the confirmation code.\n *\n * @param input - The ConfirmUserAttributeInput object\n * @throws -{@link AuthValidationErrorCode } -\n * Thrown when `confirmationCode` is not defined.\n * @throws -{@link VerifyUserAttributeException } - Thrown due to an invalid confirmation code or attribute.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function confirmUserAttribute(input) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { confirmationCode, userAttributeKey } = input;\n assertValidationError(!!confirmationCode, AuthValidationErrorCode.EmptyConfirmUserAttributeCode);\n const { tokens } = await fetchAuthSession({ forceRefresh: false });\n assertAuthTokens(tokens);\n const verifyUserAttribute = createVerifyUserAttributeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await verifyUserAttribute({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmUserAttribute),\n }, {\n AccessToken: tokens.accessToken.toString(),\n AttributeName: userAttributeKey,\n Code: confirmationCode,\n });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// TODO: delete this module when the Auth class is removed.\nimport { ConsoleLogger } from '@aws-amplify/core';\nimport { AuthErrorStrings } from './common/AuthErrorStrings';\nconst logger = new ConsoleLogger('AuthError');\nexport class AuthError extends Error {\n constructor(type) {\n const { message, log } = authErrorMessages[type];\n super(message);\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = AuthError;\n Object.setPrototypeOf(this, AuthError.prototype);\n this.name = 'AuthError';\n this.log = log || message;\n logger.error(this.log);\n }\n}\nexport class NoUserPoolError extends AuthError {\n constructor(type) {\n super(type);\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = NoUserPoolError;\n Object.setPrototypeOf(this, NoUserPoolError.prototype);\n this.name = 'NoUserPoolError';\n }\n}\nexport const authErrorMessages = {\n oauthSignInError: {\n message: AuthErrorStrings.OAUTH_ERROR,\n log: 'Make sure Cognito Hosted UI has been configured correctly',\n },\n noConfig: {\n message: AuthErrorStrings.DEFAULT_MSG,\n log: `\n Error: Amplify has not been configured correctly.\n This error is typically caused by one of the following scenarios:\n\n 1. Make sure you're passing the awsconfig object to Amplify.configure() in your app's entry point\n See https://aws-amplify.github.io/docs/js/authentication#configure-your-app for more information\n \n 2. There might be multiple conflicting versions of amplify packages in your node_modules.\n\t\t\t\tRefer to our docs site for help upgrading Amplify packages (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js)\n `,\n },\n missingAuthConfig: {\n message: AuthErrorStrings.DEFAULT_MSG,\n log: `\n Error: Amplify has not been configured correctly. \n The configuration object is missing required auth properties.\n This error is typically caused by one of the following scenarios:\n\n 1. Did you run \\`amplify push\\` after adding auth via \\`amplify add auth\\`?\n See https://aws-amplify.github.io/docs/js/authentication#amplify-project-setup for more information\n\n 2. This could also be caused by multiple conflicting versions of amplify packages, see (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js) for help upgrading Amplify packages.\n `,\n },\n emptyUsername: {\n message: AuthErrorStrings.EMPTY_USERNAME,\n },\n // TODO: should include a list of valid sign-in types\n invalidUsername: {\n message: AuthErrorStrings.INVALID_USERNAME,\n },\n emptyPassword: {\n message: AuthErrorStrings.EMPTY_PASSWORD,\n },\n emptyCode: {\n message: AuthErrorStrings.EMPTY_CODE,\n },\n signUpError: {\n message: AuthErrorStrings.SIGN_UP_ERROR,\n log: 'The first parameter should either be non-null string or object',\n },\n noMFA: {\n message: AuthErrorStrings.NO_MFA,\n },\n invalidMFA: {\n message: AuthErrorStrings.INVALID_MFA,\n },\n emptyChallengeResponse: {\n message: AuthErrorStrings.EMPTY_CHALLENGE,\n },\n noUserSession: {\n message: AuthErrorStrings.NO_USER_SESSION,\n },\n deviceConfig: {\n message: AuthErrorStrings.DEVICE_CONFIG,\n },\n networkError: {\n message: AuthErrorStrings.NETWORK_ERROR,\n },\n autoSignInError: {\n message: AuthErrorStrings.AUTOSIGNIN_ERROR,\n },\n default: {\n message: AuthErrorStrings.DEFAULT_MSG,\n },\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { authErrorMessages } from '../../../../Errors';\nimport { AuthErrorCodes } from '../../../../common/AuthErrorStrings';\nimport { AuthError } from '../../../../errors/AuthError';\nexport const createOAuthError = (message, recoverySuggestion) => new AuthError({\n message: message ?? 'An error has occurred during the oauth process.',\n name: AuthErrorCodes.OAuthSignInError,\n recoverySuggestion: recoverySuggestion ?? authErrorMessages.oauthSignInError.log,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport var AuthErrorTypes;\n(function (AuthErrorTypes) {\n AuthErrorTypes[\"NoConfig\"] = \"noConfig\";\n AuthErrorTypes[\"MissingAuthConfig\"] = \"missingAuthConfig\";\n AuthErrorTypes[\"EmptyUsername\"] = \"emptyUsername\";\n AuthErrorTypes[\"InvalidUsername\"] = \"invalidUsername\";\n AuthErrorTypes[\"EmptyPassword\"] = \"emptyPassword\";\n AuthErrorTypes[\"EmptyCode\"] = \"emptyCode\";\n AuthErrorTypes[\"SignUpError\"] = \"signUpError\";\n AuthErrorTypes[\"NoMFA\"] = \"noMFA\";\n AuthErrorTypes[\"InvalidMFA\"] = \"invalidMFA\";\n AuthErrorTypes[\"EmptyChallengeResponse\"] = \"emptyChallengeResponse\";\n AuthErrorTypes[\"NoUserSession\"] = \"noUserSession\";\n AuthErrorTypes[\"Default\"] = \"default\";\n AuthErrorTypes[\"DeviceConfig\"] = \"deviceConfig\";\n AuthErrorTypes[\"NetworkError\"] = \"networkError\";\n AuthErrorTypes[\"AutoSignInError\"] = \"autoSignInError\";\n AuthErrorTypes[\"OAuthSignInError\"] = \"oauthSignInError\";\n})(AuthErrorTypes || (AuthErrorTypes = {}));\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthError } from '../../../../errors/AuthError';\nimport { AuthErrorTypes } from '../../../../types/Auth';\nimport { oAuthStore } from './oAuthStore';\nexport const flowCancelledMessage = '`signInWithRedirect` has been canceled.';\nexport const validationFailedMessage = 'An error occurred while validating the state.';\nexport const validationRecoverySuggestion = 'Try to initiate an OAuth flow from Amplify';\nexport const validateState = async (state) => {\n const savedState = await oAuthStore.loadOAuthState();\n // This is because savedState only exists if the flow was initiated by Amplify\n const validatedState = state === savedState ? savedState : undefined;\n if (!validatedState) {\n throw new AuthError({\n name: AuthErrorTypes.OAuthSignInError,\n message: state === null ? flowCancelledMessage : validationFailedMessage,\n recoverySuggestion: state === null ? undefined : validationRecoverySuggestion,\n });\n }\n return validatedState;\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AMPLIFY_SYMBOL, AmplifyUrl, USER_AGENT_HEADER, urlSafeDecode, } from '@aws-amplify/core/internals/utils';\nimport { Hub, decodeJWT } from '@aws-amplify/core';\nimport { cacheCognitoTokens } from '../../tokenProvider/cacheTokens';\nimport { dispatchSignedInHubEvent } from '../dispatchSignedInHubEvent';\nimport { tokenOrchestrator } from '../../tokenProvider';\nimport { createOAuthError } from './createOAuthError';\nimport { resolveAndClearInflightPromises } from './inflightPromise';\nimport { validateState } from './validateState';\nimport { oAuthStore } from './oAuthStore';\nexport const completeOAuthFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, responseType, domain, preferPrivateSession, }) => {\n const urlParams = new AmplifyUrl(currentUrl);\n const error = urlParams.searchParams.get('error');\n const errorMessage = urlParams.searchParams.get('error_description');\n if (error) {\n throw createOAuthError(errorMessage ?? error);\n }\n if (responseType === 'code') {\n return handleCodeFlow({\n currentUrl,\n userAgentValue,\n clientId,\n redirectUri,\n domain,\n preferPrivateSession,\n });\n }\n return handleImplicitFlow({\n currentUrl,\n redirectUri,\n preferPrivateSession,\n });\n};\nconst handleCodeFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, domain, preferPrivateSession, }) => {\n /* Convert URL into an object with parameters as keys\n{ redirect_uri: 'http://localhost:3000/', response_type: 'code', ...} */\n const url = new AmplifyUrl(currentUrl);\n const code = url.searchParams.get('code');\n const state = url.searchParams.get('state');\n // if `code` or `state` is not presented in the redirect url, most likely\n // that the end user cancelled the inflight oauth flow by:\n // 1. clicking the back button of browser\n // 2. closing the provider hosted UI page and coming back to the app\n if (!code || !state) {\n throw createOAuthError('User cancelled OAuth flow.');\n }\n // may throw error is being caught in attemptCompleteOAuthFlow.ts\n const validatedState = await validateState(state);\n const oAuthTokenEndpoint = 'https://' + domain + '/oauth2/token';\n // TODO(v6): check hub events\n // dispatchAuthEvent(\n // \t'codeFlow',\n // \t{},\n // \t`Retrieving tokens from ${oAuthTokenEndpoint}`\n // );\n const codeVerifier = await oAuthStore.loadPKCE();\n const oAuthTokenBody = {\n grant_type: 'authorization_code',\n code,\n client_id: clientId,\n redirect_uri: redirectUri,\n ...(codeVerifier ? { code_verifier: codeVerifier } : {}),\n };\n const body = Object.entries(oAuthTokenBody)\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join('&');\n const { access_token, refresh_token: refreshToken, id_token, error, error_message: errorMessage, token_type, expires_in, } = await (await fetch(oAuthTokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n [USER_AGENT_HEADER]: userAgentValue,\n },\n body,\n })).json();\n if (error) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw createOAuthError(errorMessage ?? error);\n }\n const username = (access_token && decodeJWT(access_token).payload.username) ?? 'username';\n await cacheCognitoTokens({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n RefreshToken: refreshToken,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst handleImplicitFlow = async ({ currentUrl, redirectUri, preferPrivateSession, }) => {\n // hash is `null` if `#` doesn't exist on URL\n const url = new AmplifyUrl(currentUrl);\n const { id_token, access_token, state, token_type, expires_in, error_description, error, } = (url.hash ?? '#')\n .substring(1) // Remove # from returned code\n .split('&')\n .map(pairings => pairings.split('='))\n .reduce((accum, [k, v]) => ({ ...accum, [k]: v }), {\n id_token: undefined,\n access_token: undefined,\n state: undefined,\n token_type: undefined,\n expires_in: undefined,\n error_description: undefined,\n error: undefined,\n });\n if (error) {\n throw createOAuthError(error_description ?? error);\n }\n if (!access_token) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw createOAuthError('No access token returned from OAuth flow.');\n }\n const validatedState = await validateState(state);\n const username = (access_token && decodeJWT(access_token).payload.username) ?? 'username';\n await cacheCognitoTokens({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst completeFlow = async ({ redirectUri, state, preferPrivateSession, }) => {\n await tokenOrchestrator.setOAuthMetadata({\n oauthSignIn: true,\n });\n await oAuthStore.clearOAuthData();\n await oAuthStore.storeOAuthSignIn(true, preferPrivateSession);\n // this should be called before any call that involves `fetchAuthSession`\n // e.g. `getCurrentUser()` below, so it allows every inflight async calls to\n // `fetchAuthSession` can be resolved\n resolveAndClearInflightPromises();\n // clear history before sending out final Hub events\n clearHistory(redirectUri);\n if (isCustomState(state)) {\n Hub.dispatch('auth', {\n event: 'customOAuthState',\n data: urlSafeDecode(getCustomState(state)),\n }, 'Auth', AMPLIFY_SYMBOL);\n }\n Hub.dispatch('auth', { event: 'signInWithRedirect' }, 'Auth', AMPLIFY_SYMBOL);\n await dispatchSignedInHubEvent();\n};\nconst isCustomState = (state) => {\n return /-/.test(state);\n};\nconst getCustomState = (state) => {\n return state.split('-').splice(1).join('-');\n};\nconst clearHistory = (redirectUri) => {\n if (typeof window !== 'undefined' && typeof window.history !== 'undefined') {\n window.history.replaceState(window.history.state, '', redirectUri);\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { invalidOriginException, invalidPreferredRedirectUrlException, invalidRedirectException, } from '../../../../errors/constants';\n/** @internal */\nexport function getRedirectUrl(redirects, preferredRedirectUrl) {\n if (preferredRedirectUrl) {\n const redirectUrl = redirects?.find(redirect => redirect === preferredRedirectUrl);\n if (!redirectUrl) {\n throw invalidPreferredRedirectUrlException;\n }\n return redirectUrl;\n }\n else {\n const redirectUrlFromTheSameOrigin = redirects?.find(isSameOriginAndPathName) ??\n redirects?.find(isTheSameDomain);\n const redirectUrlFromDifferentOrigin = redirects?.find(isHttps) ?? redirects?.find(isHttp);\n if (redirectUrlFromTheSameOrigin) {\n return redirectUrlFromTheSameOrigin;\n }\n else if (redirectUrlFromDifferentOrigin) {\n throw invalidOriginException;\n }\n throw invalidRedirectException;\n }\n}\n// origin + pathname => https://example.com/app\nconst isSameOriginAndPathName = (redirect) => redirect.startsWith(String(window.location.origin + (window.location.pathname || '/')));\n// domain => outlook.live.com, github.com\nconst isTheSameDomain = (redirect) => redirect.includes(String(window.location.hostname));\nconst isHttp = (redirect) => redirect.startsWith('http://');\nconst isHttps = (redirect) => redirect.startsWith('https://');\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Hub } from '@aws-amplify/core';\nimport { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';\nimport { oAuthStore } from './oAuthStore';\nimport { resolveAndClearInflightPromises } from './inflightPromise';\nexport const handleFailure = async (error) => {\n resolveAndClearInflightPromises();\n await oAuthStore.clearOAuthInflightData();\n Hub.dispatch('auth', { event: 'signInWithRedirect_failure', data: { error } }, 'Auth', AMPLIFY_SYMBOL);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthAction, assertOAuthConfig, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { getAuthUserAgentValue } from '../../../../utils';\nimport { oAuthStore } from './oAuthStore';\nimport { completeOAuthFlow } from './completeOAuthFlow';\nimport { getRedirectUrl } from './getRedirectUrl';\nimport { handleFailure } from './handleFailure';\nexport const attemptCompleteOAuthFlow = async (authConfig) => {\n try {\n assertTokenProviderConfig(authConfig);\n assertOAuthConfig(authConfig);\n oAuthStore.setAuthConfig(authConfig);\n }\n catch (_) {\n // no-op\n // This should not happen as Amplify singleton checks the oauth config key\n // unless the oauth config object doesn't contain required properties\n return;\n }\n // No inflight OAuth\n if (!(await oAuthStore.loadOAuthInFlight())) {\n return;\n }\n try {\n const currentUrl = window.location.href;\n const { loginWith, userPoolClientId } = authConfig;\n const { domain, redirectSignIn, responseType } = loginWith.oauth;\n const redirectUri = getRedirectUrl(redirectSignIn);\n await completeOAuthFlow({\n currentUrl,\n clientId: userPoolClientId,\n domain,\n redirectUri,\n responseType,\n userAgentValue: getAuthUserAgentValue(AuthAction.SignInWithRedirect),\n });\n }\n catch (err) {\n await handleFailure(err);\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { ADD_OAUTH_LISTENER, isBrowser, } from '@aws-amplify/core/internals/utils';\nimport { attemptCompleteOAuthFlow } from './attemptCompleteOAuthFlow';\n// attach the side effect for handling the completion of an inflight oauth flow\n// this side effect works only on Web\nisBrowser() &&\n (() => {\n // add the listener to the singleton for triggering\n Amplify[ADD_OAUTH_LISTENER](attemptCompleteOAuthFlow);\n })();\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const cognitoHostedUIIdentityProviderMap = {\n Google: 'Google',\n Facebook: 'Facebook',\n Amazon: 'LoginWithAmazon',\n Apple: 'SignInWithApple',\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const openAuthSession = async (url) => {\n if (!window?.location) {\n return;\n }\n // enforce HTTPS\n window.location.href = url.replace('http://', 'https://');\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Sha256 } from '@aws-crypto/sha256-js';\nimport { base64Encoder, getCrypto } from '@aws-amplify/core/internals/utils';\nconst CODE_VERIFIER_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n/**\n *\n * @param length Desired length of the code verifier.\n *\n * **NOTE:** According to the [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636#section-4.1)\n * A code verifier must be with a length >= 43 and <= 128.\n *\n * @returns An object that contains the generated `codeVerifier` and a method\n * `toCodeChallenge` to generate the code challenge from the `codeVerifier`\n * following the spec of [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636#section-4.2).\n */\nexport const generateCodeVerifier = (length) => {\n const randomBytes = new Uint8Array(length);\n getCrypto().getRandomValues(randomBytes);\n let value = '';\n let codeChallenge;\n for (const byte of randomBytes) {\n value += CODE_VERIFIER_CHARSET.charAt(byte % CODE_VERIFIER_CHARSET.length);\n }\n return {\n value,\n method: 'S256',\n toCodeChallenge() {\n if (codeChallenge) {\n return codeChallenge;\n }\n codeChallenge = generateCodeChallenge(value);\n return codeChallenge;\n },\n };\n};\nfunction generateCodeChallenge(codeVerifier) {\n const awsCryptoHash = new Sha256();\n awsCryptoHash.update(codeVerifier);\n const codeChallenge = removePaddingChar(base64Encoder.convert(awsCryptoHash.digestSync(), { urlSafe: true }));\n return codeChallenge;\n}\nfunction removePaddingChar(base64Encoded) {\n return base64Encoded.replace(/=/g, '');\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { generateRandomString } from '@aws-amplify/core/internals/utils';\nexport const generateState = () => {\n return generateRandomString(32);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { createOAuthError } from './createOAuthError';\nimport { handleFailure } from './handleFailure';\nexport const listenForOAuthFlowCancellation = (store) => {\n async function handleCancelOAuthFlow(event) {\n const isBfcache = event.persisted;\n if (isBfcache && (await store.loadOAuthInFlight())) {\n const error = createOAuthError('User cancelled OAuth flow.');\n await handleFailure(error);\n }\n window.removeEventListener('pageshow', handleCancelOAuthFlow);\n }\n window.addEventListener('pageshow', handleCancelOAuthFlow);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { AuthAction, assertOAuthConfig, assertTokenProviderConfig, isBrowser, urlSafeEncode, } from '@aws-amplify/core/internals/utils';\nimport '../utils/oauth/enableOAuthListener';\nimport { cognitoHostedUIIdentityProviderMap } from '../types/models';\nimport { openAuthSession as _openAuthSession, getAuthUserAgentValue, } from '../../../utils';\nimport { assertUserNotAuthenticated } from '../utils/signInHelpers';\nimport { completeOAuthFlow, generateCodeVerifier, generateState, getRedirectUrl, handleFailure, oAuthStore, } from '../utils/oauth';\nimport { createOAuthError } from '../utils/oauth/createOAuthError';\nimport { listenForOAuthFlowCancellation } from '../utils/oauth/cancelOAuthFlow';\n/**\n * Signs in a user with OAuth. Redirects the application to an Identity Provider.\n *\n * @param input - The SignInWithRedirectInput object, if empty it will redirect to Cognito HostedUI\n *\n * @throws AuthTokenConfigException - Thrown when the user pool config is invalid.\n * @throws OAuthNotConfigureException - Thrown when the oauth config is invalid.\n */\nexport async function signInWithRedirect(input) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n assertOAuthConfig(authConfig);\n oAuthStore.setAuthConfig(authConfig);\n if (!input?.options?.prompt) {\n await assertUserNotAuthenticated();\n }\n let provider = 'COGNITO'; // Default\n let idpIdentifier;\n if (typeof input?.provider === 'string') {\n provider = cognitoHostedUIIdentityProviderMap[input.provider];\n }\n else if (input?.provider?.custom) {\n provider = input.provider.custom;\n }\n else if (input?.provider?.idpIdentifier) {\n ({ idpIdentifier } = input.provider);\n }\n return oauthSignIn({\n oauthConfig: authConfig.loginWith.oauth,\n clientId: authConfig.userPoolClientId,\n provider,\n idpIdentifier,\n customState: input?.customState,\n preferPrivateSession: input?.options?.preferPrivateSession,\n options: {\n loginHint: input?.options?.loginHint,\n lang: input?.options?.lang,\n nonce: input?.options?.nonce,\n prompt: input?.options?.prompt,\n },\n authSessionOpener: input?.options?.authSessionOpener,\n });\n}\nconst oauthSignIn = async ({ oauthConfig, provider, idpIdentifier, clientId, customState, preferPrivateSession, options, authSessionOpener, }) => {\n const { domain, redirectSignIn, responseType, scopes } = oauthConfig;\n const { loginHint, lang, nonce, prompt } = options ?? {};\n const randomState = generateState();\n const openAuthSession = authSessionOpener || _openAuthSession;\n /* encodeURIComponent is not URL safe, use urlSafeEncode instead. Cognito\n single-encodes/decodes url on first sign in and double-encodes/decodes url\n when user already signed in. Using encodeURIComponent, Base32, Base64 add\n characters % or = which on further encoding becomes unsafe. '=' create issue\n for parsing query params.\n Refer: https://github.com/aws-amplify/amplify-js/issues/5218 */\n const state = customState\n ? `${randomState}-${urlSafeEncode(customState)}`\n : randomState;\n const { value, method, toCodeChallenge } = generateCodeVerifier(128);\n const redirectUri = getRedirectUrl(oauthConfig.redirectSignIn);\n if (isBrowser())\n oAuthStore.storeOAuthInFlight(true);\n oAuthStore.storeOAuthState(state);\n oAuthStore.storePKCE(value);\n const params = new URLSearchParams([\n ['redirect_uri', redirectUri],\n ['response_type', responseType],\n ['client_id', clientId],\n ]);\n // Add either identity_provider or idp_identifier, but not both\n if (idpIdentifier) {\n params.append('idp_identifier', idpIdentifier);\n }\n else {\n params.append('identity_provider', provider);\n }\n params.append('scope', scopes.join(' '));\n loginHint && params.append('login_hint', loginHint);\n lang && params.append('lang', lang);\n nonce && params.append('nonce', nonce);\n prompt && params.append('prompt', prompt.toLowerCase());\n params.append('state', state);\n if (responseType === 'code') {\n params.append('code_challenge', toCodeChallenge());\n params.append('code_challenge_method', method);\n }\n // Using URL object is not supported in React Native as the `search` property is read-only\n // See: https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Blob/URL.js\n const oAuthUrl = `https://${domain}/oauth2/authorize?${params.toString()}`;\n // this will only take effect in the following scenarios:\n // 1. the user cancels the OAuth flow on web via back button, and\n // 2. when bfcache is enabled\n listenForOAuthFlowCancellation(oAuthStore);\n // the following is effective only in react-native as openAuthSession resolves only in react-native\n const { type, error, url } = (await openAuthSession(oAuthUrl, redirectSignIn, preferPrivateSession)) ??\n {};\n try {\n if (type === 'error') {\n throw createOAuthError(String(error));\n }\n if (type === 'canceled') {\n throw createOAuthError(String(type));\n }\n if (type === 'success' && url) {\n await completeOAuthFlow({\n currentUrl: url,\n clientId,\n domain,\n redirectUri,\n responseType,\n userAgentValue: getAuthUserAgentValue(AuthAction.SignInWithRedirect),\n preferPrivateSession,\n });\n }\n }\n catch (err) {\n await handleFailure(err);\n // rethrow the error so it can be caught by `await signInWithRedirect()` in react-native\n throw err;\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthAction, assertTokenProviderConfig, fetchAuthSession, } from '@aws-amplify/core/internals/utils';\nimport { getRegionFromUserPoolId } from '../../../../foundation/parsers';\nimport { assertAuthTokens } from '../../utils/types';\nimport { toAuthUserAttribute } from '../../utils/apiHelpers';\nimport { getAuthUserAgentValue } from '../../../../utils';\nimport { createGetUserClient } from '../../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../../factories';\nexport const fetchUserAttributes = async (amplify) => {\n const authConfig = amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession(amplify, {\n forceRefresh: false,\n });\n assertAuthTokens(tokens);\n const getUser = createGetUserClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { UserAttributes } = await getUser({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.FetchUserAttributes),\n }, {\n AccessToken: tokens.accessToken.toString(),\n });\n return toAuthUserAttribute(UserAttributes);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { fetchUserAttributes as fetchUserAttributesInternal } from './internal/fetchUserAttributes';\n/**\n * Fetches the current user attributes while authenticated.\n *\n * @throws - {@link GetUserException} - Cognito service errors thrown when the service is not able to get the user.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport const fetchUserAttributes = () => {\n return fetchUserAttributesInternal(Amplify);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Hub, clearCredentials } from '@aws-amplify/core';\nimport { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';\nimport { tokenOrchestrator } from '../../tokenProvider';\nexport const completeOAuthSignOut = async (store) => {\n await store.clearOAuthData();\n tokenOrchestrator.clearTokens();\n await clearCredentials();\n Hub.dispatch('auth', { event: 'signedOut' }, 'Auth', AMPLIFY_SYMBOL);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { assertOAuthConfig } from '@aws-amplify/core/internals/utils';\nimport { openAuthSession } from '../../../../utils';\nimport { getRedirectUrl } from './getRedirectUrl';\nexport const oAuthSignOutRedirect = async (authConfig, preferPrivateSession = false, redirectUrl) => {\n assertOAuthConfig(authConfig);\n const { loginWith, userPoolClientId } = authConfig;\n const { domain, redirectSignOut } = loginWith.oauth;\n const signoutUri = getRedirectUrl(redirectSignOut, redirectUrl);\n const oAuthLogoutEndpoint = `https://${domain}/logout?${Object.entries({\n client_id: userPoolClientId,\n logout_uri: encodeURIComponent(signoutUri),\n })\n .map(([k, v]) => `${k}=${v}`)\n .join('&')}`;\n return openAuthSession(oAuthLogoutEndpoint, redirectSignOut, preferPrivateSession);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { completeOAuthSignOut } from './completeOAuthSignOut';\nimport { oAuthSignOutRedirect } from './oAuthSignOutRedirect';\nexport const handleOAuthSignOut = async (cognitoConfig, store, tokenOrchestrator, redirectUrl) => {\n const { isOAuthSignIn } = await store.loadOAuthSignIn();\n const oauthMetadata = await tokenOrchestrator.getOAuthMetadata();\n // Clear everything before attempting to visted logout endpoint since the current application\n // state could be wiped away on redirect\n await completeOAuthSignOut(store);\n // The isOAuthSignIn flag is propagated by the oAuthToken store which manages oauth keys in local storage only.\n // These keys are used to determine if a user is in an inflight or signedIn oauth states.\n // However, this behavior represents an issue when 2 apps share the same set of tokens in Cookie storage because the app that didn't\n // start the OAuth will not have access to the oauth keys.\n // A heuristic solution is to add oauth metadata to the tokenOrchestrator which will have access to the underlying\n // storage mechanism that is used by Amplify.\n if (isOAuthSignIn || oauthMetadata?.oauthSignIn) {\n // On web, this will always end up being a void action\n return oAuthSignOutRedirect(cognitoConfig, false, redirectUrl);\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createRevokeTokenClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('RevokeToken'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createGlobalSignOutClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('GlobalSignOut'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, ConsoleLogger, Hub, clearCredentials, defaultStorage, } from '@aws-amplify/core';\nimport { AMPLIFY_SYMBOL, AuthAction, assertOAuthConfig, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { tokenOrchestrator } from '../tokenProvider';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { assertAuthTokens, assertAuthTokensWithRefreshToken, } from '../utils/types';\nimport { handleOAuthSignOut } from '../utils/oauth';\nimport { DefaultOAuthStore } from '../utils/signInWithRedirectStore';\nimport { AuthError } from '../../../errors/AuthError';\nimport { OAUTH_SIGNOUT_EXCEPTION } from '../../../errors/constants';\nimport { createGlobalSignOutClient, createRevokeTokenClient, } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\nconst logger = new ConsoleLogger('Auth');\n/**\n * Signs a user out\n *\n * @param input - The SignOutInput object\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function signOut(input) {\n const cognitoConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(cognitoConfig);\n if (input?.global) {\n await globalSignOut(cognitoConfig);\n }\n else {\n await clientSignOut(cognitoConfig);\n }\n let hasOAuthConfig;\n try {\n assertOAuthConfig(cognitoConfig);\n hasOAuthConfig = true;\n }\n catch (err) {\n hasOAuthConfig = false;\n }\n if (hasOAuthConfig) {\n const oAuthStore = new DefaultOAuthStore(defaultStorage);\n oAuthStore.setAuthConfig(cognitoConfig);\n const { type } = (await handleOAuthSignOut(cognitoConfig, oAuthStore, tokenOrchestrator, input?.oauth?.redirectUrl)) ?? {};\n if (type === 'error') {\n throw new AuthError({\n name: OAUTH_SIGNOUT_EXCEPTION,\n message: `An error occurred when attempting to log out from OAuth provider.`,\n });\n }\n }\n else {\n // complete sign out\n tokenOrchestrator.clearTokens();\n await clearCredentials();\n Hub.dispatch('auth', { event: 'signedOut' }, 'Auth', AMPLIFY_SYMBOL);\n }\n}\nasync function clientSignOut(cognitoConfig) {\n try {\n const { userPoolEndpoint, userPoolId, userPoolClientId } = cognitoConfig;\n const authTokens = await tokenOrchestrator.getTokenStore().loadTokens();\n assertAuthTokensWithRefreshToken(authTokens);\n if (isSessionRevocable(authTokens.accessToken)) {\n const revokeToken = createRevokeTokenClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await revokeToken({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignOut),\n }, {\n ClientId: userPoolClientId,\n Token: authTokens.refreshToken,\n });\n }\n }\n catch (err) {\n // this shouldn't throw\n logger.debug('Client signOut error caught but will proceed with token removal');\n }\n}\nasync function globalSignOut(cognitoConfig) {\n try {\n const { userPoolEndpoint, userPoolId } = cognitoConfig;\n const authTokens = await tokenOrchestrator.getTokenStore().loadTokens();\n assertAuthTokens(authTokens);\n const globalSignOutClient = createGlobalSignOutClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await globalSignOutClient({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignOut),\n }, {\n AccessToken: authTokens.accessToken.toString(),\n });\n }\n catch (err) {\n // it should not throw\n logger.debug('Global signOut error caught but will proceed with token removal');\n }\n}\nconst isSessionRevocable = (token) => !!token?.payload?.origin_jti;\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createGetUserAttributeVerificationCodeClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('GetUserAttributeVerificationCode'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { assertAuthTokens } from '../utils/types';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createGetUserAttributeVerificationCodeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Resends user's confirmation code when updating attributes while authenticated.\n *\n * @param input - The SendUserAttributeVerificationCodeInput object\n * @returns SendUserAttributeVerificationCodeOutput\n * @throws - {@link GetUserAttributeVerificationException}\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport const sendUserAttributeVerificationCode = async (input) => {\n const { userAttributeKey, options } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n const clientMetadata = options?.clientMetadata;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession({ forceRefresh: false });\n assertAuthTokens(tokens);\n const getUserAttributeVerificationCode = createGetUserAttributeVerificationCodeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { CodeDeliveryDetails } = await getUserAttributeVerificationCode({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SendUserAttributeVerificationCode),\n }, {\n AccessToken: tokens.accessToken.toString(),\n ClientMetadata: clientMetadata,\n AttributeName: userAttributeKey,\n });\n const { DeliveryMedium, AttributeName, Destination } = {\n ...CodeDeliveryDetails,\n };\n return {\n destination: Destination,\n deliveryMedium: DeliveryMedium,\n attributeName: AttributeName,\n };\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createDeleteUserAttributesClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('DeleteUserAttributes'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { assertAuthTokens } from '../utils/types';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createDeleteUserAttributesClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Deletes user attributes.\n *\n * @param input - The DeleteUserAttributesInput object\n * @throws -{@link DeleteUserAttributesException } - Thrown due to invalid attribute.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function deleteUserAttributes(input) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userAttributeKeys } = input;\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession({ forceRefresh: false });\n assertAuthTokens(tokens);\n const deleteUserAttributesClient = createDeleteUserAttributesClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await deleteUserAttributesClient({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.DeleteUserAttributes),\n }, {\n AccessToken: tokens.accessToken.toString(),\n UserAttributeNames: userAttributeKeys,\n });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { parseJsonError, } from '@aws-amplify/core/internals/aws-client-utils';\nimport { assertServiceError } from '../../../../../../errors/utils/assertServiceError';\nimport { AuthError } from '../../../../../../errors/AuthError';\nexport const createEmptyResponseDeserializer = () => async (response) => {\n if (response.statusCode >= 300) {\n const error = await parseJsonError(response);\n assertServiceError(error);\n throw new AuthError({ name: error.name, message: error.message });\n }\n else {\n return undefined;\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createEmptyResponseDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createDeleteUserClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('DeleteUser'), createEmptyResponseDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { assertAuthTokens } from '../utils/types';\nimport { tokenOrchestrator } from '../tokenProvider';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createDeleteUserClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\nimport { signOut } from './signOut';\n/**\n * Deletes a user from the user pool while authenticated.\n *\n * @throws - {@link DeleteUserException}\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function deleteUser() {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession();\n assertAuthTokens(tokens);\n const serviceDeleteUser = createDeleteUserClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await serviceDeleteUser({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.DeleteUser),\n }, {\n AccessToken: tokens.accessToken.toString(),\n });\n await tokenOrchestrator.clearDeviceMetadata();\n await signOut();\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createUpdateDeviceStatusClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('UpdateDeviceStatus'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { assertAuthTokens, assertDeviceMetadata } from '../utils/types';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { tokenOrchestrator } from '../tokenProvider';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createUpdateDeviceStatusClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Marks device as remembered while authenticated.\n *\n * @throws - {@link UpdateDeviceStatusException} - Cognito service errors thrown when\n * setting device status to remembered using an invalid device key.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function rememberDevice() {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession();\n assertAuthTokens(tokens);\n const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata();\n assertDeviceMetadata(deviceMetadata);\n const updateDeviceStatus = createUpdateDeviceStatusClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await updateDeviceStatus({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.RememberDevice),\n }, {\n AccessToken: tokens.accessToken.toString(),\n DeviceKey: deviceMetadata.deviceKey,\n DeviceRememberedStatus: 'remembered',\n });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createEmptyResponseDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createForgetDeviceClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ForgetDevice'), createEmptyResponseDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { assertAuthTokens, assertDeviceMetadata } from '../utils/types';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { tokenOrchestrator } from '../tokenProvider';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createForgetDeviceClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n/**\n * Forget a remembered device while authenticated.\n *\n * @param input - The ForgetDeviceInput object.\n * @throws - {@link ForgetDeviceException} - Cognito service errors thrown when\n * forgetting device with invalid device key\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function forgetDevice(input) {\n const { device: { id: externalDeviceKey } = { id: undefined } } = input ?? {};\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession();\n assertAuthTokens(tokens);\n const deviceMetadata = await tokenOrchestrator.getDeviceMetadata();\n const currentDeviceKey = deviceMetadata?.deviceKey;\n if (!externalDeviceKey)\n assertDeviceMetadata(deviceMetadata);\n const serviceForgetDevice = createForgetDeviceClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await serviceForgetDevice({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ForgetDevice),\n }, {\n AccessToken: tokens.accessToken.toString(),\n DeviceKey: externalDeviceKey ?? currentDeviceKey,\n });\n if (!externalDeviceKey || externalDeviceKey === currentDeviceKey)\n await tokenOrchestrator.clearDeviceMetadata();\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createListDevicesClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ListDevices'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { assertAuthTokens } from '../utils/types';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers';\nimport { getAuthUserAgentValue } from '../../../utils';\nimport { createListDevicesClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { createCognitoUserPoolEndpointResolver } from '../factories';\n// Cognito Documentation for max device\n// https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListDevices.html#API_ListDevices_RequestSyntax\nconst MAX_DEVICES = 60;\n/**\n * Fetches devices that have been remembered using {@link rememberDevice}\n * for the currently authenticated user.\n *\n * @returns FetchDevicesOutput\n * @throws {@link ListDevicesException}\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nexport async function fetchDevices() {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession();\n assertAuthTokens(tokens);\n const listDevices = createListDevicesClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await listDevices({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.FetchDevices),\n }, {\n AccessToken: tokens.accessToken.toString(),\n Limit: MAX_DEVICES,\n });\n return parseDevicesResponse(response.Devices ?? []);\n}\nconst parseDevicesResponse = async (devices) => {\n return devices.map(({ DeviceKey: id = '', DeviceAttributes = [], DeviceCreateDate, DeviceLastModifiedDate, DeviceLastAuthenticatedDate, }) => {\n let deviceName;\n const attributes = DeviceAttributes.reduce((attrs, { Name, Value }) => {\n if (Name && Value) {\n if (Name === 'device_name')\n deviceName = Value;\n attrs[Name] = Value;\n }\n return attrs;\n }, {});\n const result = {\n id,\n name: deviceName,\n attributes,\n createDate: DeviceCreateDate\n ? new Date(DeviceCreateDate * 1000)\n : undefined,\n lastModifiedDate: DeviceLastModifiedDate\n ? new Date(DeviceLastModifiedDate * 1000)\n : undefined,\n lastAuthenticatedDate: DeviceLastAuthenticatedDate\n ? new Date(DeviceLastAuthenticatedDate * 1000)\n : undefined,\n };\n return result;\n });\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport const IdentityIdStorageKeys = {\n identityId: 'identityId',\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger, } from '@aws-amplify/core';\nimport { assertIdentityPoolIdConfig } from '@aws-amplify/core/internals/utils';\nimport { getAuthStorageKeys } from '../tokenProvider/TokenStore';\nimport { IdentityIdStorageKeys } from './types';\nconst logger = new ConsoleLogger('DefaultIdentityIdStore');\nexport class DefaultIdentityIdStore {\n setAuthConfig(authConfigParam) {\n assertIdentityPoolIdConfig(authConfigParam.Cognito);\n this.authConfig = authConfigParam;\n this._authKeys = createKeysForAuthStorage('Cognito', authConfigParam.Cognito.identityPoolId);\n }\n constructor(keyValueStorage) {\n this._authKeys = {};\n this._hasGuestIdentityId = false;\n this.keyValueStorage = keyValueStorage;\n }\n async loadIdentityId() {\n assertIdentityPoolIdConfig(this.authConfig?.Cognito);\n try {\n if (this._primaryIdentityId) {\n return {\n id: this._primaryIdentityId,\n type: 'primary',\n };\n }\n else {\n const storedIdentityId = await this.keyValueStorage.getItem(this._authKeys.identityId);\n if (storedIdentityId) {\n this._hasGuestIdentityId = true;\n return {\n id: storedIdentityId,\n type: 'guest',\n };\n }\n return null;\n }\n }\n catch (err) {\n logger.log('Error getting stored IdentityId.', err);\n return null;\n }\n }\n async storeIdentityId(identity) {\n assertIdentityPoolIdConfig(this.authConfig?.Cognito);\n if (identity.type === 'guest') {\n this.keyValueStorage.setItem(this._authKeys.identityId, identity.id);\n // Clear in-memory storage of primary identityId\n this._primaryIdentityId = undefined;\n this._hasGuestIdentityId = true;\n }\n else {\n this._primaryIdentityId = identity.id;\n // Clear locally stored guest id\n if (this._hasGuestIdentityId) {\n this.keyValueStorage.removeItem(this._authKeys.identityId);\n this._hasGuestIdentityId = false;\n }\n }\n }\n async clearIdentityId() {\n this._primaryIdentityId = undefined;\n await this.keyValueStorage.removeItem(this._authKeys.identityId);\n }\n}\nconst createKeysForAuthStorage = (provider, identifier) => {\n return getAuthStorageKeys(IdentityIdStorageKeys)(`com.amplify.${provider}`, identifier);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { cognitoIdentityPoolEndpointResolver } from '@aws-amplify/core';\nimport { AmplifyUrl } from '@aws-amplify/core/internals/utils';\nexport const createCognitoIdentityPoolEndpointResolver = ({ endpointOverride }) => (input) => {\n if (endpointOverride) {\n return { url: new AmplifyUrl(endpointOverride) };\n }\n return cognitoIdentityPoolEndpointResolver(input);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { decodeJWT } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError';\nexport function formLoginsMap(idToken) {\n const issuer = decodeJWT(idToken).payload.iss;\n const res = {};\n if (!issuer) {\n throw new AuthError({\n name: 'InvalidIdTokenException',\n message: 'Invalid Idtoken.',\n });\n }\n const domainName = issuer.replace(/(^\\w+:|^)\\/\\//, '');\n res[domainName] = idToken;\n return res;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { createGetIdClient } from '@aws-amplify/core';\nimport { AuthError } from '../../../errors/AuthError';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError';\nimport { getRegionFromIdentityPoolId } from '../../../foundation/parsers';\nimport { createCognitoIdentityPoolEndpointResolver } from '../factories';\nimport { formLoginsMap } from './utils';\n/**\n * Provides a Cognito identityId\n *\n * @param tokens - The AuthTokens received after SignIn\n * @returns string\n * @throws configuration exceptions: `InvalidIdentityPoolIdException`\n * - Auth errors that may arise from misconfiguration.\n * @throws service exceptions: {@link GetIdException }\n */\nexport async function cognitoIdentityIdProvider({ tokens, authConfig, identityIdStore, }) {\n identityIdStore.setAuthConfig({ Cognito: authConfig });\n // will return null only if there is no identityId cached or if there is an error retrieving it\n const identityId = await identityIdStore.loadIdentityId();\n if (identityId) {\n return identityId.id;\n }\n const logins = tokens?.idToken\n ? formLoginsMap(tokens.idToken.toString())\n : {};\n const generatedIdentityId = await generateIdentityId(logins, authConfig);\n // Store generated identityId\n identityIdStore.storeIdentityId({\n id: generatedIdentityId,\n type: tokens ? 'primary' : 'guest',\n });\n return generatedIdentityId;\n}\nasync function generateIdentityId(logins, authConfig) {\n const identityPoolId = authConfig?.identityPoolId;\n const region = getRegionFromIdentityPoolId(identityPoolId);\n const getId = createGetIdClient({\n endpointResolver: createCognitoIdentityPoolEndpointResolver({\n endpointOverride: authConfig.identityPoolEndpoint,\n }),\n });\n // IdentityId is absent so get it using IdentityPoolId with Cognito's GetId API\n let idResult;\n // for a first-time user, this will return a brand new identity\n // for a returning user, this will retrieve the previous identity assocaited with the logins\n try {\n idResult = (await getId({\n region,\n }, {\n IdentityPoolId: identityPoolId,\n Logins: logins,\n })).IdentityId;\n }\n catch (e) {\n assertServiceError(e);\n throw new AuthError(e);\n }\n if (!idResult) {\n throw new AuthError({\n name: 'GetIdResponseException',\n message: 'Received undefined response from getId operation',\n recoverySuggestion: 'Make sure to pass a valid identityPoolId in the configuration.',\n });\n }\n return idResult;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { ConsoleLogger, createGetCredentialsForIdentityClient, } from '@aws-amplify/core';\nimport { assertIdentityPoolIdConfig, } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError';\nimport { getRegionFromIdentityPoolId } from '../../../foundation/parsers';\nimport { assertIdTokenInAuthTokens } from '../utils/types';\nimport { createCognitoIdentityPoolEndpointResolver } from '../factories';\nimport { cognitoIdentityIdProvider } from './IdentityIdProvider';\nimport { formLoginsMap } from './utils';\nconst logger = new ConsoleLogger('CognitoCredentialsProvider');\nconst CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future\nexport class CognitoAWSCredentialsAndIdentityIdProvider {\n constructor(identityIdStore) {\n this._nextCredentialsRefresh = 0;\n this._identityIdStore = identityIdStore;\n }\n async clearCredentialsAndIdentityId() {\n logger.debug('Clearing out credentials and identityId');\n this._credentialsAndIdentityId = undefined;\n await this._identityIdStore.clearIdentityId();\n }\n async clearCredentials() {\n logger.debug('Clearing out in-memory credentials');\n this._credentialsAndIdentityId = undefined;\n }\n async getCredentialsAndIdentityId(getCredentialsOptions) {\n const isAuthenticated = getCredentialsOptions.authenticated;\n const { tokens } = getCredentialsOptions;\n const { authConfig } = getCredentialsOptions;\n try {\n assertIdentityPoolIdConfig(authConfig?.Cognito);\n }\n catch {\n // No identity pool configured, skipping\n return;\n }\n if (!isAuthenticated && !authConfig.Cognito.allowGuestAccess) {\n // TODO(V6): return partial result like Native platforms\n return;\n }\n const { forceRefresh } = getCredentialsOptions;\n const tokenHasChanged = this.hasTokenChanged(tokens);\n const identityId = await cognitoIdentityIdProvider({\n tokens,\n authConfig: authConfig.Cognito,\n identityIdStore: this._identityIdStore,\n });\n // Clear cached credentials when forceRefresh is true OR the cache token has changed\n if (forceRefresh || tokenHasChanged) {\n this.clearCredentials();\n }\n if (!isAuthenticated) {\n return this.getGuestCredentials(identityId, authConfig.Cognito);\n }\n else {\n assertIdTokenInAuthTokens(tokens);\n return this.credsForOIDCTokens(authConfig.Cognito, tokens, identityId);\n }\n }\n async getGuestCredentials(identityId, authConfig) {\n // Return existing in-memory cached credentials only if it exists, is not past it's lifetime and is unauthenticated credentials\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === false) {\n logger.info('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any authenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n const getCredentialsForIdentity = createGetCredentialsForIdentityClient({\n endpointResolver: createCognitoIdentityPoolEndpointResolver({\n endpointOverride: authConfig.identityPoolEndpoint,\n }),\n });\n // use identityId to obtain guest credentials\n // save credentials in-memory\n // No logins params should be passed for guest creds:\n // https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html\n let clientResult;\n try {\n clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n });\n }\n catch (e) {\n assertServiceError(e);\n throw new AuthError(e);\n }\n if (clientResult?.Credentials?.AccessKeyId &&\n clientResult?.Credentials?.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n if (clientResult.IdentityId) {\n res.identityId = clientResult.IdentityId;\n this._identityIdStore.storeIdentityId({\n id: clientResult.IdentityId,\n type: 'guest',\n });\n }\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: false,\n };\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsNotFoundException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n async credsForOIDCTokens(authConfig, authTokens, identityId) {\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === true) {\n logger.debug('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any unauthenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const logins = authTokens.idToken\n ? formLoginsMap(authTokens.idToken.toString())\n : {};\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n const getCredentialsForIdentity = createGetCredentialsForIdentityClient({\n endpointResolver: createCognitoIdentityPoolEndpointResolver({\n endpointOverride: authConfig.identityPoolEndpoint,\n }),\n });\n let clientResult;\n try {\n clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n Logins: logins,\n });\n }\n catch (e) {\n assertServiceError(e);\n throw new AuthError(e);\n }\n if (clientResult?.Credentials?.AccessKeyId &&\n clientResult?.Credentials?.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n if (clientResult.IdentityId) {\n res.identityId = clientResult.IdentityId;\n // note: the following call removes guest identityId from the persistent store (localStorage)\n this._identityIdStore.storeIdentityId({\n id: clientResult.IdentityId,\n type: 'primary',\n });\n }\n // Store the credentials in-memory along with the expiration\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: true,\n associatedIdToken: authTokens.idToken?.toString(),\n };\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n isPastTTL() {\n return this._nextCredentialsRefresh === undefined\n ? true\n : this._nextCredentialsRefresh <= Date.now();\n }\n hasTokenChanged(tokens) {\n return (!!tokens &&\n !!this._credentialsAndIdentityId?.associatedIdToken &&\n tokens.idToken?.toString() !==\n this._credentialsAndIdentityId.associatedIdToken);\n }\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { handlePasskeyError } from './handlePasskeyError';\nimport { PasskeyError, PasskeyErrorCode, passkeyErrorMap, } from './passkeyError';\n/**\n * Handle Passkey Registration Errors\n * https://w3c.github.io/webauthn/#sctn-create-request-exceptions\n *\n * @param err unknown\n * @returns PasskeyError\n */\nexport const handlePasskeyRegistrationError = (err) => {\n if (err instanceof PasskeyError) {\n return err;\n }\n if (err instanceof Error) {\n // Duplicate Passkey\n if (err.name === 'InvalidStateError') {\n const { message, recoverySuggestion } = passkeyErrorMap[PasskeyErrorCode.PasskeyAlreadyExists];\n return new PasskeyError({\n name: PasskeyErrorCode.PasskeyAlreadyExists,\n message,\n recoverySuggestion,\n underlyingError: err,\n });\n }\n // User Cancels Ceremony / Generic Catch All\n if (err.name === 'NotAllowedError') {\n const { message, recoverySuggestion } = passkeyErrorMap[PasskeyErrorCode.PasskeyRegistrationCanceled];\n return new PasskeyError({\n name: PasskeyErrorCode.PasskeyRegistrationCanceled,\n message,\n recoverySuggestion,\n underlyingError: err,\n });\n }\n }\n return handlePasskeyError(err);\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { assertCredentialIsPkcWithAuthenticatorAttestationResponse, } from './types';\nimport { deserializeJsonToPkcCreationOptions, serializePkcWithAttestationToJson, } from './serde';\nimport { PasskeyErrorCode, assertPasskeyError, handlePasskeyRegistrationError, } from './errors';\nimport { getIsPasskeySupported } from './getIsPasskeySupported';\n/**\n * Registers a new passkey for user\n * @param input - PasskeyCreateOptionsJson\n * @returns serialized PasskeyCreateResult\n */\nexport const registerPasskey = async (input) => {\n try {\n const isPasskeySupported = getIsPasskeySupported();\n assertPasskeyError(isPasskeySupported, PasskeyErrorCode.PasskeyNotSupported);\n const passkeyCreationOptions = deserializeJsonToPkcCreationOptions(input);\n const credential = await navigator.credentials.create({\n publicKey: passkeyCreationOptions,\n });\n assertCredentialIsPkcWithAuthenticatorAttestationResponse(credential);\n return serializePkcWithAttestationToJson(credential);\n }\n catch (err) {\n throw handlePasskeyRegistrationError(err);\n }\n};\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createStartWebAuthnRegistrationClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('StartWebAuthnRegistration'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createCompleteWebAuthnRegistrationClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('CompleteWebAuthnRegistration'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { assertAuthTokens } from '../../providers/cognito/utils/types';\nimport { createCognitoUserPoolEndpointResolver } from '../../providers/cognito/factories';\nimport { getRegionFromUserPoolId } from '../../foundation/parsers';\nimport { getAuthUserAgentValue } from '../../utils';\nimport { registerPasskey } from '../utils';\nimport { createCompleteWebAuthnRegistrationClient, createStartWebAuthnRegistrationClient, } from '../../foundation/factories/serviceClients/cognitoIdentityProvider';\nimport { assertValidCredentialCreationOptions } from '../utils/passkey/types';\n/**\n * Registers a new passkey for an authenticated user\n *\n * @returns Promise<void>\n * @throws - {@link PasskeyError}:\n * - Thrown when intermediate state is invalid\n * @throws - {@link AuthError}:\n * - Thrown when user is unauthenticated\n * @throws - {@link StartWebAuthnRegistrationException}\n * - Thrown due to a service error retrieving WebAuthn registration options\n * @throws - {@link CompleteWebAuthnRegistrationException}\n * - Thrown due to a service error when verifying WebAuthn registration result\n */\nexport async function associateWebAuthnCredential() {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession();\n assertAuthTokens(tokens);\n const startWebAuthnRegistration = createStartWebAuthnRegistrationClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { CredentialCreationOptions: credentialCreationOptions } = await startWebAuthnRegistration({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.StartWebAuthnRegistration),\n }, {\n AccessToken: tokens.accessToken.toString(),\n });\n assertValidCredentialCreationOptions(credentialCreationOptions);\n const cred = await registerPasskey(credentialCreationOptions);\n const completeWebAuthnRegistration = createCompleteWebAuthnRegistrationClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await completeWebAuthnRegistration({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.CompleteWebAuthnRegistration),\n }, {\n AccessToken: tokens.accessToken.toString(),\n Credential: cred,\n });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createListWebAuthnCredentialsClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ListWebAuthnCredentials'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { assertAuthTokens } from '../../providers/cognito/utils/types';\nimport { createCognitoUserPoolEndpointResolver } from '../../providers/cognito/factories';\nimport { getRegionFromUserPoolId } from '../parsers';\nimport { getAuthUserAgentValue } from '../../utils';\nimport { createListWebAuthnCredentialsClient } from '../factories/serviceClients/cognitoIdentityProvider';\nexport async function listWebAuthnCredentials(amplify, input) {\n const authConfig = amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await amplify.Auth.fetchAuthSession();\n assertAuthTokens(tokens);\n const listWebAuthnCredentialsResult = createListWebAuthnCredentialsClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { Credentials: commandCredentials = [], NextToken: nextToken } = await listWebAuthnCredentialsResult({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ListWebAuthnCredentials),\n }, {\n AccessToken: tokens.accessToken.toString(),\n MaxResults: input?.pageSize,\n NextToken: input?.nextToken,\n });\n const credentials = commandCredentials.map(item => ({\n credentialId: item.CredentialId,\n friendlyCredentialName: item.FriendlyCredentialName,\n relyingPartyId: item.RelyingPartyId,\n authenticatorAttachment: item.AuthenticatorAttachment,\n authenticatorTransports: item.AuthenticatorTransports,\n createdAt: item.CreatedAt ? new Date(item.CreatedAt * 1000) : undefined,\n }));\n return {\n credentials,\n nextToken,\n };\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { listWebAuthnCredentials as listWebAuthnCredentialsFoundation } from '../../foundation/apis';\n/**\n * Lists registered credentials for an authenticated user\n *\n * @param {ListWebAuthnCredentialsInput} input The list input parameters including page size and next token.\n * @returns Promise<ListWebAuthnCredentialsOutput>\n * @throws - {@link AuthError}:\n * - Thrown when user is unauthenticated\n * @throws - {@link ListWebAuthnCredentialsException}\n * - Thrown due to a service error when listing WebAuthn credentials\n */\nexport async function listWebAuthnCredentials(input) {\n return listWebAuthnCredentialsFoundation(Amplify, input);\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler';\nimport { createUserPoolDeserializer, createUserPoolSerializer, } from './shared/serde';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants';\nexport const createDeleteWebAuthnCredentialClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('DeleteWebAuthnCredential'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { AuthAction, assertTokenProviderConfig, } from '@aws-amplify/core/internals/utils';\nimport { assertAuthTokens } from '../../providers/cognito/utils/types';\nimport { createCognitoUserPoolEndpointResolver } from '../../providers/cognito/factories';\nimport { getRegionFromUserPoolId } from '../parsers';\nimport { getAuthUserAgentValue } from '../../utils';\nimport { createDeleteWebAuthnCredentialClient } from '../factories/serviceClients/cognitoIdentityProvider';\nexport async function deleteWebAuthnCredential(amplify, input) {\n const authConfig = amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await amplify.Auth.fetchAuthSession();\n assertAuthTokens(tokens);\n const deleteWebAuthnCredentialResult = createDeleteWebAuthnCredentialClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await deleteWebAuthnCredentialResult({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.DeleteWebAuthnCredential),\n }, {\n AccessToken: tokens.accessToken.toString(),\n CredentialId: input.credentialId,\n });\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { deleteWebAuthnCredential as deleteWebAuthnCredentialFoundation } from '../../foundation/apis';\n/**\n * Delete a registered credential for an authenticated user by credentialId\n * @param {DeleteWebAuthnCredentialInput} input The delete input parameters including the credentialId\n * @returns Promise<void>\n * @throws - {@link AuthError}:\n * - Thrown when user is unauthenticated\n * @throws - {@link DeleteWebAuthnCredentialException}\n * - Thrown due to a service error when deleting a WebAuthn credential\n */\nexport async function deleteWebAuthnCredential(input) {\n return deleteWebAuthnCredentialFoundation(Amplify, input);\n}\n","export { signUp } from './providers/cognito/apis/signUp.mjs';\nexport { resetPassword } from './providers/cognito/apis/resetPassword.mjs';\nexport { confirmResetPassword } from './providers/cognito/apis/confirmResetPassword.mjs';\nexport { signIn } from './providers/cognito/apis/signIn.mjs';\nexport { resendSignUpCode } from './providers/cognito/apis/resendSignUpCode.mjs';\nexport { confirmSignUp } from './providers/cognito/apis/confirmSignUp.mjs';\nexport { confirmSignIn } from './providers/cognito/apis/confirmSignIn.mjs';\nexport { updateMFAPreference } from './providers/cognito/apis/updateMFAPreference.mjs';\nexport { fetchMFAPreference } from './providers/cognito/apis/fetchMFAPreference.mjs';\nexport { verifyTOTPSetup } from './providers/cognito/apis/verifyTOTPSetup.mjs';\nexport { updatePassword } from './providers/cognito/apis/updatePassword.mjs';\nexport { setUpTOTP } from './providers/cognito/apis/setUpTOTP.mjs';\nexport { updateUserAttributes } from './providers/cognito/apis/updateUserAttributes.mjs';\nexport { updateUserAttribute } from './providers/cognito/apis/updateUserAttribute.mjs';\nexport { getCurrentUser } from './providers/cognito/apis/getCurrentUser.mjs';\nexport { confirmUserAttribute } from './providers/cognito/apis/confirmUserAttribute.mjs';\nexport { signInWithRedirect } from './providers/cognito/apis/signInWithRedirect.mjs';\nexport { fetchUserAttributes } from './providers/cognito/apis/fetchUserAttributes.mjs';\nexport { signOut } from './providers/cognito/apis/signOut.mjs';\nexport { sendUserAttributeVerificationCode } from './providers/cognito/apis/sendUserAttributeVerificationCode.mjs';\nexport { deleteUserAttributes } from './providers/cognito/apis/deleteUserAttributes.mjs';\nexport { deleteUser } from './providers/cognito/apis/deleteUser.mjs';\nexport { rememberDevice } from './providers/cognito/apis/rememberDevice.mjs';\nexport { forgetDevice } from './providers/cognito/apis/forgetDevice.mjs';\nexport { fetchDevices } from './providers/cognito/apis/fetchDevices.mjs';\nexport { autoSignIn } from './providers/cognito/apis/autoSignIn.mjs';\nexport { decodeJWT, fetchAuthSession } from '@aws-amplify/core';\nimport './providers/cognito/credentialsProvider/IdentityIdStore.mjs';\nimport './providers/cognito/credentialsProvider/credentialsProvider.mjs';\nimport './providers/cognito/utils/refreshAuthTokens.mjs';\nimport '@aws-amplify/core/internals/utils';\nexport { AuthError } from './errors/AuthError.mjs';\nimport './providers/cognito/tokenProvider/errorHelpers.mjs';\nimport './providers/cognito/utils/types.mjs';\nimport './providers/cognito/tokenProvider/tokenProvider.mjs';\nimport '@aws-crypto/sha256-js';\nimport './errors/constants.mjs';\nimport './Errors.mjs';\nimport './common/AuthErrorStrings.mjs';\nimport './types/Auth.mjs';\nexport { associateWebAuthnCredential } from './client/apis/associateWebAuthnCredential.mjs';\nexport { listWebAuthnCredentials } from './client/apis/listWebAuthnCredentials.mjs';\nexport { deleteWebAuthnCredential } from './client/apis/deleteWebAuthnCredential.mjs';\n//# sourceMappingURL=index.mjs.map\n","export * from '@aws-amplify/auth';\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { defaultStorage } from '@aws-amplify/core';\nimport { DefaultIdentityIdStore } from './IdentityIdStore';\nimport { CognitoAWSCredentialsAndIdentityIdProvider } from './credentialsProvider';\n/**\n * Cognito specific implmentation of the CredentialsProvider interface\n * that manages setting and getting of AWS Credentials.\n *\n * @throws configuration expections: `InvalidIdentityPoolIdException`\n * - Auth errors that may arise from misconfiguration.\n * @throws service expections: {@link GetCredentialsForIdentityException}, {@link GetIdException}\n *\n */\nexport const cognitoCredentialsProvider = new CognitoAWSCredentialsAndIdentityIdProvider(new DefaultIdentityIdStore(defaultStorage));\nexport { CognitoAWSCredentialsAndIdentityIdProvider, DefaultIdentityIdStore };\n","export { signUp } from './apis/signUp.mjs';\nexport { resetPassword } from './apis/resetPassword.mjs';\nexport { confirmResetPassword } from './apis/confirmResetPassword.mjs';\nexport { signIn } from './apis/signIn.mjs';\nexport { resendSignUpCode } from './apis/resendSignUpCode.mjs';\nexport { confirmSignUp } from './apis/confirmSignUp.mjs';\nexport { confirmSignIn } from './apis/confirmSignIn.mjs';\nexport { updateMFAPreference } from './apis/updateMFAPreference.mjs';\nexport { fetchMFAPreference } from './apis/fetchMFAPreference.mjs';\nexport { verifyTOTPSetup } from './apis/verifyTOTPSetup.mjs';\nexport { updatePassword } from './apis/updatePassword.mjs';\nexport { setUpTOTP } from './apis/setUpTOTP.mjs';\nexport { updateUserAttributes } from './apis/updateUserAttributes.mjs';\nexport { updateUserAttribute } from './apis/updateUserAttribute.mjs';\nexport { getCurrentUser } from './apis/getCurrentUser.mjs';\nexport { confirmUserAttribute } from './apis/confirmUserAttribute.mjs';\nexport { signInWithRedirect } from './apis/signInWithRedirect.mjs';\nexport { fetchUserAttributes } from './apis/fetchUserAttributes.mjs';\nexport { signOut } from './apis/signOut.mjs';\nexport { sendUserAttributeVerificationCode } from './apis/sendUserAttributeVerificationCode.mjs';\nexport { deleteUserAttributes } from './apis/deleteUserAttributes.mjs';\nexport { deleteUser } from './apis/deleteUser.mjs';\nexport { rememberDevice } from './apis/rememberDevice.mjs';\nexport { forgetDevice } from './apis/forgetDevice.mjs';\nexport { fetchDevices } from './apis/fetchDevices.mjs';\nexport { autoSignIn } from './apis/autoSignIn.mjs';\nexport { cognitoCredentialsProvider } from './credentialsProvider/index.mjs';\nexport { refreshAuthTokens, refreshAuthTokensWithoutDedupe } from './utils/refreshAuthTokens.mjs';\nexport { DefaultTokenStore, createKeysForAuthStorage } from './tokenProvider/TokenStore.mjs';\nexport { TokenOrchestrator } from './tokenProvider/TokenOrchestrator.mjs';\nexport { cognitoUserPoolsTokenProvider } from './tokenProvider/tokenProvider.mjs';\nexport { AUTH_KEY_PREFIX } from './tokenProvider/constants.mjs';\nexport { generateCodeVerifier } from './utils/oauth/generateCodeVerifier.mjs';\nexport { generateState } from './utils/oauth/generateState.mjs';\nimport '@aws-amplify/core';\nimport '@aws-amplify/core/internals/utils';\nexport { getRedirectUrl } from './utils/oauth/getRedirectUrl.mjs';\nimport './utils/types.mjs';\nimport '../../errors/constants.mjs';\nimport '../../Errors.mjs';\nimport '../../common/AuthErrorStrings.mjs';\nexport { validateState } from './utils/oauth/validateState.mjs';\nexport { CognitoAWSCredentialsAndIdentityIdProvider } from './credentialsProvider/credentialsProvider.mjs';\nexport { DefaultIdentityIdStore } from './credentialsProvider/IdentityIdStore.mjs';\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, CookieStorage, defaultStorage, } from '@aws-amplify/core';\nimport { parseAmplifyConfig, } from '@aws-amplify/core/internals/utils';\nimport { CognitoAWSCredentialsAndIdentityIdProvider, DefaultIdentityIdStore, cognitoCredentialsProvider, cognitoUserPoolsTokenProvider, } from './auth/cognito';\nexport const DefaultAmplify = {\n /**\n * Configures Amplify with the {@link resourceConfig} and {@link libraryOptions}.\n *\n * @param resourceConfig The {@link ResourcesConfig} object that is typically imported from the\n * `amplifyconfiguration.json` file. It can also be an object literal created inline when calling `Amplify.configure`.\n * @param libraryOptions The {@link LibraryOptions} additional options for the library.\n *\n * @example\n * import config from './amplifyconfiguration.json';\n *\n * Amplify.configure(config);\n */\n configure(resourceConfig, libraryOptions) {\n const resolvedResourceConfig = parseAmplifyConfig(resourceConfig);\n const cookieBasedKeyValueStorage = new CookieStorage({ sameSite: 'lax' });\n const resolvedKeyValueStorage = libraryOptions?.ssr\n ? cookieBasedKeyValueStorage\n : defaultStorage;\n const resolvedCredentialsProvider = libraryOptions?.ssr\n ? new CognitoAWSCredentialsAndIdentityIdProvider(new DefaultIdentityIdStore(cookieBasedKeyValueStorage))\n : cognitoCredentialsProvider;\n // If no Auth config is provided, no special handling will be required, configure as is.\n // Otherwise, we can assume an Auth config is provided from here on.\n if (!resolvedResourceConfig.Auth) {\n Amplify.configure(resolvedResourceConfig, libraryOptions);\n return;\n }\n // If Auth options are provided, always just configure as is.\n // Otherwise, we can assume no Auth libraryOptions were provided from here on.\n if (libraryOptions?.Auth) {\n Amplify.configure(resolvedResourceConfig, libraryOptions);\n return;\n }\n // If no Auth libraryOptions were previously configured, then always add default providers.\n if (!Amplify.libraryOptions.Auth) {\n cognitoUserPoolsTokenProvider.setAuthConfig(resolvedResourceConfig.Auth);\n cognitoUserPoolsTokenProvider.setKeyValueStorage(\n // TODO: allow configure with a public interface\n resolvedKeyValueStorage);\n Amplify.configure(resolvedResourceConfig, {\n ...libraryOptions,\n Auth: {\n tokenProvider: cognitoUserPoolsTokenProvider,\n credentialsProvider: resolvedCredentialsProvider,\n },\n });\n return;\n }\n // At this point, Auth libraryOptions would have been previously configured and no overriding\n // Auth options were given, so we should preserve the currently configured Auth libraryOptions.\n if (libraryOptions) {\n const authLibraryOptions = Amplify.libraryOptions.Auth;\n // If ssr is provided through libraryOptions, we should respect the intentional reconfiguration.\n if (libraryOptions.ssr !== undefined) {\n cognitoUserPoolsTokenProvider.setKeyValueStorage(\n // TODO: allow configure with a public interface\n resolvedKeyValueStorage);\n authLibraryOptions.credentialsProvider = resolvedCredentialsProvider;\n }\n Amplify.configure(resolvedResourceConfig, {\n Auth: authLibraryOptions,\n ...libraryOptions,\n });\n return;\n }\n // Finally, if there were no libraryOptions given at all, we should simply not touch the currently\n // configured libraryOptions.\n Amplify.configure(resolvedResourceConfig);\n },\n /**\n * Returns the {@link ResourcesConfig} object passed in as the `resourceConfig` parameter when calling\n * `Amplify.configure`.\n *\n * @returns An {@link ResourcesConfig} object.\n */\n getConfig() {\n return Amplify.getConfig();\n },\n};\n","export { DefaultAmplify as Amplify } from './initSingleton.mjs';\n//# sourceMappingURL=index.mjs.map\n","export { createFoundation } from './foundation'\n\nexport type {\n Foundation,\n FoundationConfig,\n FullConfig,\n User,\n FileMetadata,\n EntityChangeEvent,\n AuthClient,\n AuthService,\n DbService,\n FilesService,\n AccountService,\n IntegrationService,\n Integration,\n IntegrationConnection,\n IntegrationDetail,\n OpenApiService,\n LogService\n} from './types'\n","/**\n * HTTP layer for Foundation API calls.\n * Handles request construction, response unwrapping, and error extraction.\n */\n\n/**\n * Unwrap backend response envelope.\n * The API wraps responses in { response: ... } or { data: ... }.\n */\nexport function unwrapResponse(json: Record<string, unknown>): unknown {\n if (json?.response !== undefined) return json.response\n if (json?.data !== undefined) return json.data\n return json\n}\n\n/**\n * Extract a meaningful error from a failed API response.\n */\nexport function extractError(status: number, body: Record<string, unknown>): Error {\n const errorObj = body?.error as Record<string, unknown> | undefined\n\n if (errorObj) {\n let message = errorObj.message as string || 'Unknown error'\n const details = errorObj.details as Array<{ field?: string; message?: string }> | undefined\n if (details?.length) {\n const detailMessages = details\n .map(d => d.field ? `${d.field}: ${d.message}` : d.message)\n .join(', ')\n message = message ? `${message} ${detailMessages}` : detailMessages\n }\n return Object.assign(new Error(message), {\n code: errorObj.code,\n type: errorObj.code,\n details,\n status\n })\n }\n\n const customMessage = (body?.data as Record<string, unknown>)?.message || body?.message\n if (customMessage) {\n return Object.assign(new Error(customMessage as string), { status })\n }\n\n return Object.assign(new Error(`HTTP ${status}`), { status })\n}\n\nexport interface HttpClientConfig {\n appId: string\n tenantId: string\n version: string\n getToken: () => Promise<string>\n}\n\nexport function createHttpClient(config: HttpClientConfig) {\n function headers(token: string): Record<string, string> {\n return {\n 'X-Foundation-Mvp-Application-Id': config.appId,\n 'X-Foundation-Mvp-Tenant-Id': config.tenantId,\n 'X-Foundation-Mvp-Application-Version': config.version,\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n }\n }\n\n async function request(\n baseUrl: string,\n path: string,\n method: string,\n options: { params?: Record<string, unknown>; body?: unknown } = {}\n ): Promise<unknown> {\n const token = await config.getToken()\n const hdrs = headers(token)\n\n let url = `${baseUrl}${path}`\n if (options.params) {\n const searchParams = new URLSearchParams()\n for (const [key, value] of Object.entries(options.params)) {\n if (value !== undefined && value !== null) {\n searchParams.set(key, String(value))\n }\n }\n const qs = searchParams.toString()\n if (qs) url += `?${qs}`\n }\n\n const fetchOptions: RequestInit = { method, headers: hdrs }\n if (options.body !== undefined) {\n fetchOptions.body = JSON.stringify(options.body)\n }\n\n const response = await fetch(url, fetchOptions)\n\n if (!response.ok) {\n let body: Record<string, unknown> = {}\n try { body = await response.json() } catch { /* no json body */ }\n throw extractError(response.status, body)\n }\n\n if (response.status === 204) return null\n\n const json = await response.json()\n return unwrapResponse(json as Record<string, unknown>)\n }\n\n /** Raw fetch with auth headers but no unwrapping (for S3 uploads etc.) */\n async function rawFetch(url: string, options: RequestInit = {}): Promise<Response> {\n return fetch(url, options)\n }\n\n return { request, rawFetch, headers }\n}\n\nexport type HttpClient = ReturnType<typeof createHttpClient>\n","/**\n * Auth provider factory.\n * Creates the right auth client based on config (Cognito/Auth0/none).\n * Supports custom auth client override.\n */\nimport type { AuthClient, AuthService, User } from './types'\n\nconst MAX_LISTENERS = 100\n\n// Dynamic import helpers.\n// Browser builds use `define` flags to enable static imports for their auth provider,\n// so the bundler can resolve and inline them. The other provider stays as a variable\n// import which the bundler ignores.\n// npm builds: both use variable-based imports (bundler can't resolve = won't error).\ndeclare const __BUNDLE_AUTH0__: boolean | undefined\ndeclare const __BUNDLE_COGNITO__: boolean | undefined\n\nasync function importAuth0(): Promise<typeof import('@auth0/auth0-spa-js')> {\n if (typeof __BUNDLE_AUTH0__ !== 'undefined' && __BUNDLE_AUTH0__) {\n return import('@auth0/auth0-spa-js')\n }\n const id = '@auth0/auth0-spa-js'\n return import(/* @vite-ignore */ id)\n}\n\nasync function importAmplifyAuth(): Promise<typeof import('aws-amplify/auth')> {\n if (typeof __BUNDLE_COGNITO__ !== 'undefined' && __BUNDLE_COGNITO__) {\n return import('aws-amplify/auth')\n }\n const id = 'aws-amplify/auth'\n return import(/* @vite-ignore */ id)\n}\n\nasync function importAmplify(): Promise<typeof import('aws-amplify')> {\n if (typeof __BUNDLE_COGNITO__ !== 'undefined' && __BUNDLE_COGNITO__) {\n return import('aws-amplify')\n }\n const id = 'aws-amplify'\n return import(/* @vite-ignore */ id)\n}\n\nexport interface AuthProviderConfig {\n provider: string\n auth0?: { domain: string; clientId: string; audience?: string; scope?: string }\n cognito?: { userPoolId: string; clientId: string; region: string; domain: string; scope?: string }\n apiUrls?: { apiBaseUrl: string; accountBaseUrl?: string; websocketBaseUrl?: string }\n}\n\nexport async function createAuthClient(config: AuthProviderConfig): Promise<AuthClient> {\n switch (config.provider) {\n case 'auth0': {\n if (!config.auth0) throw new Error('Auth0 config required')\n const { createAuth0Client } = await importAuth0()\n const client = await createAuth0Client({\n domain: config.auth0.domain,\n clientId: config.auth0.clientId,\n authorizationParams: {\n audience: config.auth0.audience,\n scope: config.auth0.scope || 'openid profile email',\n redirect_uri: window.location.origin\n },\n useRefreshTokens: true,\n cacheLocation: 'localstorage'\n })\n\n const auth0Domain = config.auth0.domain\n const auth0ClientId = config.auth0.clientId\n\n return {\n login: (options) => client.loginWithRedirect(options),\n logout: (options) => client.logout({ logoutParams: { returnTo: window.location.origin }, ...options }),\n getUser: async () => {\n const user = await client.getUser()\n if (!user) return undefined\n return { id: user.sub || '', email: user.email || '', name: user.name, picture: user.picture }\n },\n getTokenSilently: (options) => client.getTokenSilently(options),\n isAuthenticated: () => client.isAuthenticated(),\n\n async signIn(email: string, password: string) {\n // Auth0 Resource Owner Password Grant\n const response = await fetch(`https://${auth0Domain}/oauth/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'password',\n client_id: auth0ClientId,\n username: email,\n password,\n audience: config.auth0!.audience,\n scope: config.auth0!.scope || 'openid profile email'\n })\n })\n if (!response.ok) {\n const err = await response.json().catch(() => ({}))\n throw new Error(err.error_description || err.message || 'Sign in failed')\n }\n },\n\n async signUp(email: string, password: string, metadata?: Record<string, unknown>) {\n const response = await fetch(`https://${auth0Domain}/dbconnections/signup`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n client_id: auth0ClientId,\n email,\n password,\n connection: 'Username-Password-Authentication',\n ...metadata\n })\n })\n if (!response.ok) {\n const err = await response.json().catch(() => ({}))\n throw new Error(err.description || err.message || 'Sign up failed')\n }\n },\n\n async forgotPassword(email: string) {\n const response = await fetch(`https://${auth0Domain}/dbconnections/change_password`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n client_id: auth0ClientId,\n email,\n connection: 'Username-Password-Authentication'\n })\n })\n if (!response.ok) {\n const err = await response.json().catch(() => ({}))\n throw new Error(err.error_description || err.message || 'Password reset request failed')\n }\n },\n\n async resetPassword(_code: string, _newPassword: string) {\n // Auth0 handles reset via email link, not code-based flow\n throw new Error('Auth0 password reset is completed via the email link, not a code')\n }\n }\n }\n\n case 'cognito': {\n if (!config.cognito) throw new Error('Cognito config required')\n const { fetchAuthSession, signInWithRedirect, signOut, getCurrentUser } = await importAmplifyAuth()\n const { Amplify } = await importAmplify()\n\n Amplify.configure({\n Auth: {\n Cognito: {\n userPoolId: config.cognito.userPoolId,\n userPoolClientId: config.cognito.clientId,\n loginWith: {\n oauth: {\n domain: config.cognito.domain.replace('https://', ''),\n scopes: (config.cognito.scope || 'openid profile email').split(' '),\n redirectSignIn: [window.location.origin],\n redirectSignOut: [window.location.origin],\n responseType: 'code'\n }\n }\n }\n }\n })\n\n return {\n login: async () => { await signInWithRedirect() },\n logout: async () => { await signOut() },\n getUser: async () => {\n try {\n const user = await getCurrentUser()\n return { id: user.userId, email: user.signInDetails?.loginId || '', name: user.username }\n } catch { return undefined }\n },\n getTokenSilently: async () => {\n const session = await fetchAuthSession()\n const token = session.tokens?.accessToken?.toString()\n if (!token) throw new Error('No token available')\n return token\n },\n isAuthenticated: async () => {\n try {\n await getCurrentUser()\n return true\n } catch { return false }\n },\n\n async signIn(email: string, password: string) {\n const { signIn } = await importAmplifyAuth()\n await signIn({ username: email, password })\n },\n\n async signUp(email: string, password: string, metadata?: Record<string, unknown>) {\n const { signUp } = await importAmplifyAuth()\n await signUp({\n username: email,\n password,\n options: { userAttributes: { email, ...metadata } }\n })\n },\n\n async forgotPassword(email: string) {\n const { resetPassword } = await importAmplifyAuth()\n await resetPassword({ username: email })\n },\n\n async resetPassword(code: string, newPassword: string) {\n const { confirmResetPassword } = await importAmplifyAuth()\n // Note: caller must track the username from the forgotPassword call\n await confirmResetPassword({ username: '', confirmationCode: code, newPassword })\n }\n }\n }\n\n case 'none':\n return {\n login: async () => {},\n logout: async () => {},\n getUser: async () => undefined,\n getTokenSilently: async () => 'none',\n isAuthenticated: async () => true\n }\n\n default:\n throw new Error(`Unknown auth provider: ${config.provider}`)\n }\n}\n\n/**\n * Wrap an AuthClient into the reactive AuthService interface.\n */\nexport function createAuthService(client: AuthClient): AuthService {\n let user: User | null = null\n const listeners: Array<(user: User | null) => void> = []\n\n function notifyListeners() {\n listeners.forEach(fn => { try { fn(user) } catch { /* */ } })\n }\n\n return {\n get user() { return user },\n get isAuthenticated() { return !!user },\n\n async getToken() {\n return client.getTokenSilently()\n },\n\n async login(options) {\n await client.login(options)\n const authUser = await client.getUser()\n user = authUser ? { id: authUser.id, email: authUser.email, name: authUser.name, picture: authUser.picture } : null\n notifyListeners()\n },\n\n async logout(options) {\n await client.logout(options)\n user = null\n notifyListeners()\n },\n\n async signIn(email: string, password: string) {\n if (!client.signIn) throw new Error('signIn not supported by this auth provider')\n await client.signIn(email, password)\n const authUser = await client.getUser()\n user = authUser ? { id: authUser.id, email: authUser.email, name: authUser.name, picture: authUser.picture } : null\n notifyListeners()\n },\n\n async signUp(email: string, password: string, metadata?: Record<string, unknown>) {\n if (!client.signUp) throw new Error('signUp not supported by this auth provider')\n await client.signUp(email, password, metadata)\n },\n\n async forgotPassword(email: string) {\n if (!client.forgotPassword) throw new Error('forgotPassword not supported by this auth provider')\n await client.forgotPassword(email)\n },\n\n async resetPassword(code: string, newPassword: string) {\n if (!client.resetPassword) throw new Error('resetPassword not supported by this auth provider')\n await client.resetPassword(code, newPassword)\n },\n\n onChange(callback) {\n if (listeners.length >= MAX_LISTENERS) {\n console.warn('[Foundation SDK] Auth listener limit reached.')\n return () => {}\n }\n listeners.push(callback)\n return () => {\n const idx = listeners.indexOf(callback)\n if (idx > -1) listeners.splice(idx, 1)\n }\n },\n\n /** @internal Initialize user state from auth client */\n async _initUser() {\n const authenticated = await client.isAuthenticated()\n if (authenticated) {\n const authUser = await client.getUser()\n user = authUser ? { id: authUser.id, email: authUser.email, name: authUser.name, picture: authUser.picture } : null\n }\n }\n } as AuthService & { _initUser(): Promise<void> }\n}\n","export interface JwtClaims {\n sub: string\n apiBaseUrl: string\n accountBaseUrl: string\n websocketBaseUrl: string\n userId: string\n namespace?: string\n}\n\nexport function parseJwt(token: string): JwtClaims {\n if (!token) {\n throw new Error('Token parsing failed: Missing auth token')\n }\n\n try {\n // Auth0 tokens can have query params appended: \"jwt?param=value\"\n const [jwtPart, queryPart] = token.split('?')\n\n const parts = jwtPart.split('.')\n if (parts.length !== 3) {\n throw new Error('Invalid JWT format')\n }\n\n const payloadStr = atob(parts[1])\n const jwtPayload = JSON.parse(payloadStr)\n\n // Merge query params if present\n if (queryPart) {\n const params = new URLSearchParams(queryPart)\n params.forEach((value, key) => {\n jwtPayload[key] = value\n })\n }\n\n const apiBaseUrl = jwtPayload['BaseApplication/apiBaseUrl']\n if (!apiBaseUrl) {\n throw new Error('Token missing apiBaseUrl')\n }\n\n const websocketBaseUrl = jwtPayload['BaseApplication/websocketBaseUrl'] || ''\n const accountBaseUrl = jwtPayload['BaseApplication/accountBaseUrl'] || apiBaseUrl\n\n return {\n sub: jwtPayload.sub || '',\n apiBaseUrl,\n accountBaseUrl,\n websocketBaseUrl,\n userId: jwtPayload['BaseApplication/userId'] || '',\n namespace: jwtPayload['BaseApplication/namespace']\n }\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('Token')) {\n throw err\n }\n const message = err instanceof Error ? err.message : 'Failed to parse token'\n throw new Error(`Token parsing failed: ${message}`)\n }\n}\n","/**\n * Foundation SDK — typed API client for the Foundation platform.\n *\n * One input: a config URL. The SDK fetches it, discovers auth, API URLs,\n * features, plans, theme, connectors — everything. Self-configuring.\n */\nimport type {\n Foundation,\n FoundationConfig,\n FullConfig,\n AuthService,\n DbService,\n FilesService,\n AccountService,\n IntegrationService,\n Integration,\n IntegrationConnection,\n IntegrationDetail,\n OpenApiService,\n LogService,\n EntityChangeEvent,\n User\n} from './types'\nimport { createHttpClient, unwrapResponse, type HttpClient } from './http'\nimport { createAuthClient, createAuthService, type AuthProviderConfig } from './auth'\nimport { parseJwt } from './jwt'\n\nexport async function createFoundation(options: FoundationConfig): Promise<Foundation> {\n // 1. Resolve config URL — foundation-env.json wins if it exists (deployed env)\n let configUrl = options.configUrl\n let resolvedAppId = options.appId\n let resolvedTenantId = options.tenantId\n\n try {\n const envResponse = await fetch('/foundation-env.json')\n if (envResponse.ok) {\n const env = await envResponse.json()\n if (env.configUrl) {\n configUrl = env.configUrl\n resolvedAppId = env.applicationId || resolvedAppId\n resolvedTenantId = env.applicationTenant || resolvedTenantId\n }\n }\n } catch { /* no env file — use passed options */ }\n\n if (!configUrl) {\n throw new Error('No configUrl provided and /foundation-env.json not found')\n }\n\n // 2. Fetch public config\n const configHeaders: Record<string, string> = { 'Accept': 'application/json', 'Cache-Control': 'no-cache' }\n if (resolvedAppId) configHeaders['X-Foundation-Mvp-Application-Id'] = resolvedAppId\n if (resolvedTenantId) configHeaders['X-Foundation-Mvp-Tenant-Id'] = resolvedTenantId\n\n const publicConfigResponse = await fetch(configUrl, { headers: configHeaders })\n if (!publicConfigResponse.ok) {\n throw new Error(`Failed to fetch config: ${publicConfigResponse.statusText}`)\n }\n const rawPublicConfig = await publicConfigResponse.json()\n const publicConfig = rawPublicConfig.data ?? rawPublicConfig\n\n // 2. Set up auth\n const authConfig: AuthProviderConfig = publicConfig.auth || { provider: 'none' }\n const authClient = options.auth || await createAuthClient(authConfig)\n const authServiceRaw = createAuthService(authClient)\n const authService = authServiceRaw as AuthService & { _initUser(): Promise<void> }\n await authService._initUser()\n\n // 3. Determine API URLs\n let apiBaseUrl: string\n let accountBaseUrl: string\n\n if (options.baseUrl) {\n // Explicit override (e.g. '/api' with a dev proxy)\n apiBaseUrl = options.baseUrl\n accountBaseUrl = options.baseUrl\n } else if (authConfig.apiUrls?.apiBaseUrl) {\n // API URLs from public config (no-auth mode or explicit)\n apiBaseUrl = authConfig.apiUrls.apiBaseUrl\n accountBaseUrl = authConfig.apiUrls.accountBaseUrl || apiBaseUrl\n } else {\n // API URLs from JWT token\n const token = await authClient.getTokenSilently()\n const claims = parseJwt(token)\n apiBaseUrl = claims.apiBaseUrl\n accountBaseUrl = claims.accountBaseUrl\n }\n\n // 4. Create HTTP client\n const appId = resolvedAppId || publicConfig.app?.id || publicConfig.tenant?.identifier || ''\n const tenantId = resolvedTenantId || publicConfig.tenant?.identifier || ''\n const version = publicConfig.app?.version || publicConfig.core?.version || '0.0.0'\n\n const http = createHttpClient({\n appId,\n tenantId,\n version,\n getToken: () => authClient.getTokenSilently()\n })\n\n // 5. Fetch backend config (authenticated)\n let backendConfig: Record<string, unknown> = {}\n try {\n const cfg = await http.request(apiBaseUrl, '/api/v1/config/init', 'GET')\n backendConfig = (cfg || {}) as Record<string, unknown>\n } catch (err) {\n console.warn('[Foundation SDK] Backend config fetch failed:', err)\n }\n\n // 6. Merge configs\n const mergedConfig = { ...publicConfig, ...backendConfig }\n\n // Determine namespace from JWT if available\n let namespace = ''\n try {\n const token = await authClient.getTokenSilently()\n if (token && token !== 'none') {\n const claims = parseJwt(token)\n namespace = claims.namespace || ''\n }\n } catch { /* no token yet */ }\n\n // 7. Build config service\n const config: FullConfig = {\n get app() {\n const app = mergedConfig.app as Record<string, unknown> || {}\n return {\n id: (app.id || appId) as string,\n name: (app.name || '') as string,\n version: (app.version || version) as string,\n environment: (app.environment || '') as string,\n ...app\n }\n },\n get features() { return (mergedConfig.features || {}) as Record<string, unknown> },\n get plans() { return (mergedConfig.plans || []) as unknown[] },\n get theme() {\n const theme = mergedConfig.theme as Record<string, unknown> || {}\n return {\n colors: (theme.colors || {}) as Record<string, string>,\n dark: (theme.dark || {}) as Record<string, string>,\n defaultColorScheme: theme.defaultColorScheme as string | undefined\n }\n },\n get connectors() { return (mergedConfig.connectors || {}) as Record<string, unknown> },\n get resources() { return (mergedConfig.resources || {}) as Record<string, string> },\n get auth() {\n const { provider, ...rest } = authConfig\n return { provider, ...rest } as { provider: string; [key: string]: unknown }\n },\n get raw() { return mergedConfig }\n }\n\n // 8. Build services\n const db = createDbService(http, apiBaseUrl)\n const files = createFilesService(http, apiBaseUrl, namespace)\n const account = createAccountService(http, accountBaseUrl)\n const integration = createIntegrationService(http, apiBaseUrl, accountBaseUrl, namespace)\n const openapi = createOpenApiService(http, apiBaseUrl)\n const log = createLogService()\n\n // Entity change listeners (WebSocket support is future)\n const entityListeners: Array<(event: EntityChangeEvent) => void> = []\n\n const foundation: Foundation = {\n get ready() { return Promise.resolve() },\n get isReady() { return true },\n auth: authService,\n db,\n files,\n integration,\n account,\n config,\n openapi,\n log,\n on(event, callback) {\n if (event === 'entity.changed') {\n entityListeners.push(callback)\n return () => {\n const idx = entityListeners.indexOf(callback)\n if (idx > -1) entityListeners.splice(idx, 1)\n }\n }\n return () => {}\n }\n }\n\n return foundation\n}\n\n// --- Service factories ---\n\nfunction createDbService(http: HttpClient, apiBase: string): DbService {\n return {\n async list(entity, options = {}) {\n const { filters, limit, cursor, orderBy, orderDir } = options\n const params: Record<string, unknown> = { ...filters }\n if (limit) params.limit = limit\n if (cursor) params.next = cursor\n if (orderBy) params.orderBy = orderBy\n if (orderDir) params.orderDir = orderDir\n return http.request(apiBase, `/api/v1/core/${entity}`, 'GET', { params }) as Promise<any>\n },\n async get(entity, id) {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'GET', { params: { id } }) as Promise<any>\n },\n async create(entity, data) {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'POST', { body: data }) as Promise<any>\n },\n async update(entity, id, updates) {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'PUT', { body: { id, ...updates } }) as Promise<any>\n },\n async save(entity, data) {\n try {\n return await http.request(apiBase, `/api/v1/core/${entity}`, 'PUT', { body: data }) as Promise<any>\n } catch {\n return http.request(apiBase, `/api/v1/core/${entity}`, 'POST', { body: data }) as Promise<any>\n }\n },\n async delete(entity, id) {\n await http.request(apiBase, `/api/v1/core/${entity}`, 'DELETE', { body: { id } })\n }\n }\n}\n\nfunction createFilesService(http: HttpClient, apiBase: string, namespace: string): FilesService {\n return {\n async initiate(options) {\n return http.request(apiBase, '/api/v1/core/upload', 'POST', {\n body: { ...options, __namespace: namespace }\n }) as Promise<any>\n },\n async upload(options) {\n let fileData: ArrayBuffer\n if (options.file instanceof ArrayBuffer) {\n fileData = options.file\n } else {\n fileData = await options.file.arrayBuffer()\n }\n\n const uploadData = await http.request(apiBase, '/api/v1/core/upload', 'POST', {\n body: { name: options.name, contentType: options.contentType, contentLength: fileData.byteLength, sha256: options.sha256, __namespace: namespace }\n }) as { id: string; name: string; signedUrl: string; signedData: Record<string, string> }\n\n if (!uploadData.signedUrl || !uploadData.signedData) {\n throw new Error('Missing signedUrl or signedData in response')\n }\n\n const formData = new FormData()\n Object.entries(uploadData.signedData).forEach(([key, value]) => {\n formData.append(key, value)\n })\n formData.append('file', new Blob([fileData], { type: options.contentType }), options.name)\n\n const s3Response = await fetch(uploadData.signedUrl, { method: 'POST', body: formData })\n if (s3Response.status !== 204) {\n throw new Error(`S3 upload failed: ${s3Response.status}`)\n }\n\n return { id: uploadData.id, name: uploadData.name, status: 'uploaded', s3UploadComplete: true }\n },\n async get(fileId) {\n return http.request(apiBase, '/api/v1/core/files', 'GET', {\n params: { id: fileId, __namespace: namespace }\n }) as Promise<any>\n },\n async delete(fileId) {\n await http.request(apiBase, `/api/v1/core/files/${fileId}`, 'DELETE')\n },\n async list(options = {}) {\n const params: Record<string, unknown> = { __namespace: namespace }\n if (options.limit) params.limit = options.limit\n if (options.cursor) params.cursor = options.cursor\n const result = await http.request(apiBase, '/api/v1/core/files', 'GET', { params }) as {\n items?: unknown[]; next?: string\n }\n return { items: result?.items || [], nextCursor: result?.next } as any\n }\n }\n}\n\nfunction createAccountService(http: HttpClient, accountBase: string): AccountService {\n return {\n async get() {\n return http.request(accountBase, '/api/v1/accounts/account', 'GET') as Promise<any>\n },\n async update(data) {\n await http.request(accountBase, '/api/v1/accounts/account', 'PUT', { body: { user: data } })\n },\n async usage() {\n return http.request(accountBase, '/api/v1/accounts/account/usage', 'GET') as Promise<any>\n },\n async resendVerification() {\n await http.request(accountBase, '/api/v1/accounts/account/resend-verification', 'POST')\n }\n }\n}\n\nfunction createIntegrationService(http: HttpClient, apiBase: string, accountBase: string, namespace: string): IntegrationService {\n const service: IntegrationService = {\n async list() {\n return http.request(apiBase, '/api/v1/config/connectors', 'GET') as Promise<any>\n },\n async connections() {\n return http.request(apiBase, '/api/v1/core/integrations', 'GET', {\n params: { query: 'default', __namespace: namespace }\n }) as Promise<any>\n },\n async all() {\n const [rawCatalog, rawConnections] = await Promise.all([\n service.list(),\n service.connections()\n ])\n\n const catalog = (Array.isArray(rawCatalog) ? rawCatalog : (rawCatalog as any)?.items || []) as Integration[]\n const connections = (Array.isArray(rawConnections) ? rawConnections : (rawConnections as any)?.items || []) as IntegrationConnection[]\n\n const bySource = new Map<string, IntegrationConnection[]>()\n for (const conn of connections) {\n const source = conn.source || conn.id\n if (!bySource.has(source)) bySource.set(source, [])\n bySource.get(source)!.push(conn)\n }\n\n return catalog.map(item => {\n const conns = bySource.get(item.id) || []\n return {\n ...item,\n connections: conns,\n connected: conns.some(c => c.connected),\n connectionCount: conns.filter(c => c.connected).length\n } as IntegrationDetail\n })\n },\n async status(source) {\n const conns = await service.connections()\n const items = (Array.isArray(conns) ? conns : (conns as any)?.items || []) as IntegrationConnection[]\n const filtered = items.filter(c => c.source === source && c.connected)\n return { connected: filtered.length > 0, connections: filtered }\n },\n async connect(source) {\n return http.request(accountBase, `/api/v1/accounts/integrations/${source}/initialize`, 'POST', {\n body: { __namespace: namespace }\n }) as Promise<any>\n },\n async disconnect(source, configurationId) {\n await http.request(accountBase, `/api/v1/accounts/integrations/${source}/remove`, 'POST', {\n body: { configurationId }\n })\n }\n }\n return service\n}\n\nfunction createOpenApiService(http: HttpClient, apiBase: string): OpenApiService {\n return {\n async get() {\n return http.request(apiBase, '/api/v1/config/openapi', 'GET') as Promise<any>\n }\n }\n}\n\nfunction createLogService(): LogService {\n return {\n info: (message, context) => console.log(`[Foundation] ${message}`, context ?? ''),\n warn: (message, context) => console.warn(`[Foundation] ${message}`, context ?? ''),\n error: (message, context) => console.error(`[Foundation] ${message}`, context ?? ''),\n event: (event, data) => console.log(`[Foundation Event] ${event}`, data ?? '')\n }\n}\n"],"mappings":"4uBAAA,IAGaA,GACAC,GAEAC,GANbC,GAAAC,EAAA,kBAGaJ,GAA0B,UAC1BC,GAAoB,mBAEpBC,GAAoC,mCCNjD,IAEWG,GAFXC,GAAAC,EAAA,mBAGC,SAAUF,EAAS,CAChBA,EAAQ,MAAW,QACnBA,EAAQ,MAAW,QACnBA,EAAQ,KAAU,OAClBA,EAAQ,KAAU,OAClBA,EAAQ,QAAa,UACrBA,EAAQ,KAAU,MACtB,GAAGA,KAAYA,GAAU,CAAA,EAAG,QCLtBG,GAYOC,mCAZPD,GAAa,CACf,QAAS,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a,iCAAiCQ,CAAM,UAAW,OAAQ,CACxF,KAAM,CAAE,gBAAAK,CAAgB,CAC1B,CAAC,CACH,CACF,EACA,OAAOZ,CACT,CAEA,SAAS3B,GAAqBpB,EAAkB2B,EAAiC,CAC/E,MAAO,CACL,MAAM,KAAM,CACV,OAAO3B,EAAK,QAAQ2B,EAAS,yBAA0B,KAAK,CAC9D,CACF,CACF,CAEA,SAASL,IAA+B,CACtC,MAAO,CACL,KAAM,CAACsC,EAASC,IAAY,QAAQ,IAAI,gBAAgBD,CAAO,GAAIC,GAAW,EAAE,EAChF,KAAM,CAACD,EAASC,IAAY,QAAQ,KAAK,gBAAgBD,CAAO,GAAIC,GAAW,EAAE,EACjF,MAAO,CAACD,EAASC,IAAY,QAAQ,MAAM,gBAAgBD,CAAO,GAAIC,GAAW,EAAE,EACnF,MAAO,CAACrC,EAAOY,IAAS,QAAQ,IAAI,sBAAsBZ,CAAK,GAAIY,GAAQ,EAAE,CAC/E,CACF","names":["AWS_CLOUDWATCH_CATEGORY","USER_AGENT_HEADER","NO_HUBCALLBACK_PROVIDED_EXCEPTION","init_constants","__esmMin","LogType","init_types","__esmMin","LOG_LEVELS","ConsoleLogger","_ConsoleLogger","name","level","LogType","n","dt","config","type","msg","loggerLevelName","loggerLevel","log","prefix","message","obj","plugin","logEvent","pluggable","AWS_CLOUDWATCH_CATEGORY","AmplifyError","init_AmplifyError","__esmMin","_AmplifyError","message","name","recoverySuggestion","underlyingError","metadata","extendedRequestId","httpStatusCode","requestId","AmplifyErrorCode","init_errors","__esmMin","createAssertionFunction","errorMap","AssertionError","AmplifyError","assertion","name","additionalContext","message","recoverySuggestion","AMPLIFY_SYMBOL","logger","HubClass","Hub","HubInternal","ConsoleLogger","name","channel","listener","holder","callback","payload","source","ampSymbol","capsule","e","listenerName","cb","AmplifyError","NO_HUBCALLBACK_PROVIDED_EXCEPTION","getCrypto","getBtoa","getAtob","AmplifyError","base64Decoder","input","options","inputStr","getAtob","AuthConfigurationErrorCode","authConfigurationErrorMap","assert","createAssertionFunction","assertTokenProviderConfig","cognitoConfig","assertionValid","assert","AuthConfigurationErrorCode","assertOAuthConfig","validOAuthConfig","assertIdentityPoolIdConfig","validConfig","decodeJWT","token","tokenParts","base64","jsonStr","base64Decoder","char","payload","deepFreeze","init_deepFreeze","__esmMin","object","propNames","name","value","logger","authTypeMapping","parseAWSExports","getRedirectUrl","getOAuthConfig","parseSocialProviders","ConsoleLogger","config","AmplifyError","aws_appsync_apiKey","aws_appsync_authenticationType","aws_appsync_graphqlEndpoint","aws_appsync_region","aws_bots_config","aws_cognito_identity_pool_id","aws_cognito_sign_up_verification_method","aws_cognito_mfa_configuration","aws_cognito_mfa_types","aws_cognito_password_protection_settings","aws_cognito_verification_mechanisms","aws_cognito_signup_attributes","aws_cognito_social_providers","aws_cognito_username_attributes","aws_mandatory_sign_in","aws_mobile_analytics_app_id","aws_mobile_analytics_app_region","aws_user_files_s3_bucket","aws_user_files_s3_bucket_region","aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing","aws_user_pools_id","aws_user_pools_web_client_id","geo","oauth","predictions","aws_cloud_logic_custom","Notifications","modelIntrospection","amplifyConfig","InAppMessaging","Push","appId","region","bot","defaultAuthMode","mfaConfig","passwordFormatConfig","userAttributes","attributes","key","loginWithEmailEnabled","loginWithPhoneEnabled","hasOAuthConfig","hasSocialProviderConfig","amazon_location_service","acc","api","name","endpoint","service","voiceId","redirectStr","domain","scope","redirectSignIn","redirectSignOut","responseType","provider","updatedProvider","ADD_OAUTH_LISTENER","init_constants","__esmMin","unsafeStringify","arr","offset","byteToHex","init_stringify","__esmMin","i","rng","poolPtr","rnds8Pool","import_crypto","init_rng","__esmMin","import_crypto","native_default","init_native","__esmMin","v4","options","buf","offset","native_default","rnds","rng","i","unsafeStringify","v4_default","init_v4","__esmMin","init_native","init_rng","init_stringify","init_esm","__esmMin","init_v4","isAmplifyOutputs","config","version","parseStorage","amplifyOutputsStorageProperties","bucket_name","aws_region","buckets","createBucketInfoMap","parseAuth","amplifyOutputsAuthProperties","user_pool_id","user_pool_client_id","identity_pool_id","password_policy","mfa_configuration","mfa_methods","unauthenticated_identities_enabled","oauth","username_attributes","standard_required_attributes","groups","authConfig","getMfaStatus","getOAuthProviders","acc","curr","parseAnalytics","amplifyOutputsAnalyticsProperties","amazon_pinpoint","parseGeo","geofence_collections","maps","search_indices","parseData","amplifyOutputsDataProperties","default_authorization_type","url","api_key","model_introspection","getGraphQLAuthMode","parseCustom","amplifyOutputsCustomProperties","parseNotifications","amplifyOutputsNotificationsProperties","channels","amazon_pinpoint_app_id","hasInAppMessaging","hasPushNotification","notificationsConfig","parseAmplifyOutputs","amplifyOutputs","resourcesConfig","customConfig","authType","authModeNames","providers","oAuthProviders","provider","providerNames","mfaConfiguration","mappedBuckets","name","bucketName","region","paths","sanitizedPaths","key","value","init_parseAmplifyOutputs","__esmMin","parseAmplifyConfig","amplifyConfig","key","parseAWSExports","isAmplifyOutputs","parseAmplifyOutputs","__awaiter","thisArg","_arguments","P","generator","adopt","value","resolve","reject","fulfilled","step","e","rejected","result","__generator","body","_","t","f","y","g","verb","n","v","op","init_tslib_es6","__esmMin","BLOCK_SIZE","DIGEST_LENGTH","KEY","INIT","MAX_HASHABLE_LENGTH","init_constants","__esmMin","RawSha256","init_RawSha256","__esmMin","init_constants","INIT","data","position","byteLength","MAX_HASHABLE_LENGTH","BLOCK_SIZE","bitsHashed","bufferView","undecoratedLength","i","out","DIGEST_LENGTH","_a","buffer","state","state0","state1","state2","state3","state4","state5","state6","state7","u","t1_1","t2_1","t1","KEY","t2","init_dist_es","__esmMin","import_buffer","fromString","init_dist_es","__esmMin","input","encoding","fromUtf8","init_fromUtf8","__esmMin","init_dist_es","input","buf","fromString","init_toUint8Array","__esmMin","init_fromUtf8","init_toUtf8","__esmMin","init_dist_es","init_dist_es","__esmMin","init_fromUtf8","init_toUint8Array","init_toUtf8","convertToBuffer","data","fromUtf8","init_convertToBuffer","__esmMin","init_dist_es","input","isEmptyData","data","init_isEmptyData","__esmMin","init_numToUint8","__esmMin","init_uint32ArrayFrom","__esmMin","init_module","__esmMin","init_convertToBuffer","init_isEmptyData","init_numToUint8","init_uint32ArrayFrom","bufferFromSecret","secret","input","convertToBuffer","BLOCK_SIZE","bufferHash","RawSha256","buffer","Sha256","init_constants","init_RawSha256","init_module","toHash","isEmptyData","e","inner","outer","i","init_module","__esmMin","init_jsSha256","SHORT_TO_HEX","HEX_TO_SHORT","init_dist_es","__esmMin","i","encodedByte","Framework","Category","AiAction","AnalyticsAction","ApiAction","AuthAction","DataStoreAction","GeoAction","InAppMessagingAction","InteractionsAction","PredictionsAction","PubSubAction","PushNotificationAction","StorageAction","init_types","__esmMin","version","init_version","__esmMin","globalExists","windowExists","documentExists","processExists","keyPrefixMatch","init_helpers","__esmMin","object","prefix","key","reactWebDetect","elementKeyPrefixedWithReact","key","elementIsReactEnabled","element","allElementsWithId","documentExists","reactSSRDetect","processExists","vueWebDetect","windowExists","keyPrefixMatch","vueSSRDetect","globalExists","svelteWebDetect","windowExists","keyPrefixMatch","svelteSSRDetect","processExists","key","nextWebDetect","windowExists","nextSSRDetect","globalExists","keyPrefixMatch","nuxtWebDetect","windowExists","nuxtSSRDetect","globalExists","angularWebDetect","angularVersionSetInDocument","documentExists","angularContentSetInWindow","windowExists","angularSSRDetect","processExists","reactNativeDetect","init_ReactNative","__esmMin","expoDetect","globalExists","webDetect","windowExists","detect","detectionMap","detectionEntry","Framework","expoDetect","reactNativeDetect","nextWebDetect","nuxtWebDetect","angularWebDetect","reactWebDetect","vueWebDetect","svelteWebDetect","webDetect","nextSSRDetect","nuxtSSRDetect","reactSSRDetect","vueSSRDetect","angularSSRDetect","svelteSSRDetect","clearCache","frameworkCache","resetTimeout","framework","delay","resetTriggered","detectFramework","PRIME_FRAMEWORK_DELAY","frameworkChangeObservers","SSR_RESET_TIMEOUT","WEB_RESET_TIMEOUT","observeFrameworkChanges","detect","fcn","Framework","customUserAgentState","getCustomUserAgent","init_customUserAgent","__esmMin","category","api","BASE_USER_AGENT","sanitizeAmplifyVersion","PlatformBuilder","Platform","getAmplifyUserAgentObject","getAmplifyUserAgent","amplifyVersion","version","detectFramework","Framework","fcn","observeFrameworkChanges","category","action","userAgent","customState","getCustomUserAgent","state","customUserAgentDetails","agentKey","agentValue","isBrowser","init_isBrowser","__esmMin","logger","AuthClass","getCustomEndpointWarningMessage","ConsoleLogger","authResourcesConfig","authOptions","options","credentialsAndIdentityId","userSub","tokens","target","AmplifyClass","Amplify","AuthClass","resourcesConfig","libraryOptions","resolvedResourceConfig","parseAmplifyConfig","deepFreeze","Hub","AMPLIFY_SYMBOL","ADD_OAUTH_LISTENER","listener","fetchAuthSession","init_fetchAuthSession","__esmMin","amplify","options","fetchAuthSession","options","fetchAuthSessionInternal","Amplify","clearCredentials","Amplify","parseMetadata","isMetadataBearer","init_responseInfo","__esmMin","response","headers","statusCode","parseJsonError","parseJsonBody","response","body","code","rawValue","cleanValue","message","error","parseMetadata","output","composeServiceApi","init_composeServiceApi","__esmMin","transferHandler","serializer","deserializer","defaultConfig","config","input","resolvedConfig","endpoint","request","response","jitteredBackoff","maxDelayMs","attempt","delay","AMZ_SDK_INVOCATION_ID_HEADER","AMZ_SDK_REQUEST_HEADER","init_constants","__esmMin","jitteredBackoff","attempt","delay","jitteredBackoffUtil","CLOCK_SKEW_ERROR_CODES","isClockSkewError","init_isClockSkewError","__esmMin","errorCode","getRetryDecider","THROTTLING_ERROR_CODES","TIMEOUT_ERROR_CODES","isThrottlingError","isConnectionError","isServerSideError","errorParser","response","error","parsedError","errorCode","statusCode","isClockSkewError","AmplifyErrorCode","COGNITO_IDENTITY_SERVICE_NAME","DEFAULT_SERVICE_CLIENT_API_CONFIG","getRetryDecider","parseJsonError","jitteredBackoff","retryMiddlewareFactory","cancellableSleep","addOrIncrementMetadataAttempts","maxAttempts","retryDecider","computeDelay","abortSignal","next","context","request","error","attemptsCount","response","handleTerminalErrorOrResponse","e","isCredentialsExpiredError","retryable","delay","timeoutMs","timeoutId","sleepPromiseResolveFn","sleepPromise","resolve","cancelSleep","_","nextHandlerOutput","attempts","amplifyUuid","v4_default","amzSdkInvocationIdHeaderMiddlewareFactory","next","request","AMZ_SDK_INVOCATION_ID_HEADER","amplifyUuid","amzSdkRequestHeaderMiddlewareFactory","maxAttempts","next","context","request","attemptsCount","AMZ_SDK_REQUEST_HEADER","userAgentMiddlewareFactory","init_middleware","__esmMin","userAgentHeader","userAgentValue","next","request","headerName","composeTransferHandler","init_composeTransferHandler","__esmMin","coreHandler","middleware","request","options","context","composedHandler","composeHandlerRequest","i","m","withMemoization","init_memoization","__esmMin","payloadAccessor","cached","shouldSendBody","fetchTransferHandler","method","url","headers","body","abortSignal","cache","withCrossDomainCredentials","resp","e","AmplifyError","AmplifyErrorCode","responseHeaders","value","key","httpResponse","bodyWithMixin","withMemoization","unauthenticatedHandler","composeTransferHandler","fetchTransferHandler","userAgentMiddlewareFactory","amzSdkInvocationIdHeaderMiddlewareFactory","retryMiddlewareFactory","amzSdkRequestHeaderMiddlewareFactory","createDisableCacheMiddleware","init_createDisableCacheMiddleware","__esmMin","next","request","cognitoIdentityTransferHandler","composeTransferHandler","unauthenticatedHandler","createDisableCacheMiddleware","createClientSerializer","getSharedHeaders","buildHttpRpcRequest","init_createClientSerializer","__esmMin","operation","input","endpoint","headers","body","url","createGetCredentialsForIdentityClient","getCredentialsForIdentityDeserializer","deserializeCredentials","config","composeServiceApi","cognitoIdentityTransferHandler","createClientSerializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","getAmplifyUserAgent","response","parseJsonError","body","parseJsonBody","parseMetadata","Expiration","rest","createGetIdClient","getIdDeserializer","config","composeServiceApi","cognitoIdentityTransferHandler","createClientSerializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","getAmplifyUserAgent","response","parseJsonError","parseJsonBody","parseMetadata","defaultPartition","partitionsInfo","init_partitions","__esmMin","getDnsSuffix","region","partitions","partitionsInfo","regions","outputs","regionRegex","regex","defaultPartition","AmplifyUrl","init_amplifyUrl","__esmMin","cognitoIdentityPoolEndpointResolver","region","AmplifyUrl","COGNITO_IDENTITY_SERVICE_NAME","getDnsSuffix","PlatformNotSupportedError","AmplifyError","AmplifyErrorCode","KeyValueStorage","storage","key","value","PlatformNotSupportedError","InMemoryStorage","init_InMemoryStorage","__esmMin","index","key","value","logger","getLocalStorageWithFallback","getSessionStorageWithFallback","ConsoleLogger","InMemoryStorage","DefaultStorage","KeyValueStorage","getLocalStorageWithFallback","SessionStorage","KeyValueStorage","getSessionStorageWithFallback","SyncKeyValueStorage","storage","PlatformNotSupportedError","key","value","SyncSessionStorage","SyncKeyValueStorage","getSessionStorageWithFallback","assign","target","i","source","key","init","converter","defaultAttributes","set","name","value","attributes","stringifiedAttributes","attributeName","get","cookies","jar","parts","found","defaultConverter","api","init_js_cookie","__esmMin","CookieStorage","data","path","domain","expires","sameSite","secure","key","value","api","cookie","promises","defaultStorage","sessionStorage","syncSessionStorage","sharedInMemoryStorage","DefaultStorage","SessionStorage","SyncSessionStorage","KeyValueStorage","InMemoryStorage","defaultConfig","currentSizeKey","init_constants","__esmMin","getByteLength","str","ret","i","charCode","getCurrentTime","getCurrentSizeKey","keyPrefix","currentSizeKey","CacheErrorCode","cacheErrorMap","assert","createAssertionFunction","logger","StorageCacheCommon","ConsoleLogger","config","keyValueStorage","defaultConfig","size","getCurrentSizeKey","key","value","options","currentSizeKey","cacheItemOptions","getCurrentTime","prefixedKey","item","val","validKeys","sizeToPop","e","cached","text","assert","CacheErrorCode","itemSize","removeItemError","getByteLength","cacheLimit","amount","setItemErr","spaceItemNeed","cacheThresholdSpace","cur","keys","items","remainedSize","a","b","remainingKeys","logger","StorageCache","ConsoleLogger","_StorageCache","StorageCacheCommon","config","storage","getLocalStorageWithFallback","KeyValueStorage","options","omitSizeKey","keys","i","key","getCurrentSizeKey","defaultConfig","getCurrentTime","Cache","StorageCache","logger","ConsoleLogger","lang","key","defVal","val","language","langDict","vocabularies","I18nErrorCode","i18nErrorMap","assert","createAssertionFunction","logger","_config","_i18n","I18n","ConsoleLogger","_I18n","config","I18nClass","lang","assert","I18nErrorCode","key","defVal","language","vocabularies","init_esm","__esmMin","init_Hub","init_utils","init_Amplify","init_fetchAuthSession","init_clearCredentials","init_createGetCredentialsForIdentityClient","init_createGetIdClient","init_cognitoIdentityPoolEndpointResolver","init_storage","init_Cache","init_I18n","init_ConsoleLogger","init_CookieStorage","generateRandomString","length","STATE_CHARSET","result","randomNums","getCrypto","num","urlSafeDecode","hex","char","init_urlSafeDecode","__esmMin","urlSafeEncode","str","char","init_urlSafeEncode","__esmMin","deDupeAsyncFunction","init_deDupeAsyncFunction","__esmMin","asyncFunction","inflightPromise","args","resolve","reject","result","error","isTokenExpired","expiresAt","clockDrift","tolerance","init_isTokenExpired","__esmMin","getDeviceName","init_getDeviceName","__esmMin","userAgentData","platform","platformVersion","model","architecture","fullVersionList","versionList","v","value","bytesToString","input","byte","init_bytesToString","__esmMin","base64Encoder","input","options","inputStr","bytesToString","encodedStr","getBtoa","cryptoSecureRandomInt","getCrypto","hexStringify","wordArray","words","sigBytes","hexChars","i","bite","WordArray","_WordArray","Words","nBytes","cryptoSecureRandomInt","init_libraryUtils","__esmMin","init_generateRandomString","init_isBrowser","init_urlSafeDecode","init_urlSafeEncode","init_deDupeAsyncFunction","init_isTokenExpired","init_constants","init_amplifyUrl","init_parseAmplifyConfig","init_getDeviceName","init_utils","init_Platform","init_types","init_AmplifyError","init_createAssertionFunction","init_errors","init_fetchAuthSession","init_Hub","init_base64Decoder","init_base64Encoder","init_globalHelpers","init_WordArray","AuthValidationErrorCode","init_validation","__esmMin","validationErrorMap","AuthErrorStrings","AuthErrorCodes","AuthValidationErrorCode","AuthError","_AuthError","AmplifyError","params","assertValidationError","assertion","name","message","recoverySuggestion","validationErrorMap","AuthError","getRegionFromUserPoolId","userPoolId","region","AuthError","getRegionFromIdentityPoolId","identityPoolId","toAttributeType","attributes","key","value","toAuthUserAttribute","userAttributes","attribute","init_apiHelpers","__esmMin","AssociateSoftwareTokenException","ChangePasswordException","ConfirmDeviceException","ConfirmForgotPasswordException","ConfirmSignUpException","DeleteUserAttributesException","DeleteUserException","ForgetDeviceException","ForgotPasswordException","GetUserException","GetIdException","GetCredentialsForIdentityException","GetUserAttributeVerificationException","GlobalSignOutException","InitiateAuthException","ResendConfirmationException","RespondToAuthChallengeException","SetUserMFAPreferenceException","SignUpException","UpdateUserAttributesException","VerifySoftwareTokenException","VerifyUserAttributeException","UpdateDeviceStatusException","ListDevicesException","SETUP_TOTP_EXCEPTION","init_errors","__esmMin","USER_UNAUTHENTICATED_EXCEPTION","USER_ALREADY_AUTHENTICATED_EXCEPTION","DEVICE_METADATA_NOT_FOUND_EXCEPTION","AUTO_SIGN_IN_EXCEPTION","INVALID_REDIRECT_EXCEPTION","INVALID_APP_SCHEME_EXCEPTION","INVALID_PREFERRED_REDIRECT_EXCEPTION","invalidRedirectException","invalidAppSchemeException","invalidPreferredRedirectUrlException","INVALID_ORIGIN_EXCEPTION","invalidOriginException","OAUTH_SIGNOUT_EXCEPTION","TOKEN_REFRESH_EXCEPTION","UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION","AuthError","assertAuthTokens","tokens","AuthError","USER_UNAUTHENTICATED_EXCEPTION","assertIdTokenInAuthTokens","assertAuthTokensWithRefreshToken","isAuthenticatedWithImplicitOauthFlow","oAuthTokenRefreshException","isAuthenticatedWithRefreshToken","tokenRefreshException","assertDeviceMetadata","deviceMetadata","DEVICE_METADATA_NOT_FOUND_EXCEPTION","isAuthenticated","OAuthStorageKeys","TOKEN_REFRESH_EXCEPTION","getSignInDetailsFromTokens","tokens","getCurrentUser","amplify","authConfig","assertTokenProviderConfig","assertAuthTokens","username","sub","authUser","signInDetails","getCurrentUser","getCurrentUserInternal","Amplify","getAuthUserAgentValue","action","customUserAgentDetails","getAmplifyUserAgent","Category","init_internal","__esmMin","init_composeServiceApi","init_composeTransferHandler","createUserPoolSerializer","getSharedHeaders","buildHttpRpcRequest","init_createUserPoolSerializer","__esmMin","operation","input","endpoint","headers","body","url","init_clients","__esmMin","init_getDnsSuffix","init_unauthenticated","init_jitteredBackoff","init_defaultRetryDecider","init_json","assertServiceError","error","AuthError","AmplifyErrorCode","createUserPoolDeserializer","response","error","parseJsonError","assertServiceError","AuthError","parseJsonBody","disableCacheMiddlewareFactory","cognitoUserPoolTransferHandler","next","_","request","composeTransferHandler","unauthenticatedHandler","COGNITO_IDP_SERVICE_NAME","init_constants","__esmMin","DEFAULT_SERVICE_CLIENT_API_CONFIG","COGNITO_IDP_SERVICE_NAME","getRetryDecider","parseJsonError","jitteredBackoff","getAmplifyUserAgent","createInitiateAuthClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","createRespondToAuthChallengeClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","createVerifySoftwareTokenClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","createAssociateSoftwareTokenClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","cognitoUserPoolEndpointResolver","region","AmplifyUrl","COGNITO_IDP_SERVICE_NAME","getDnsSuffix","createCognitoUserPoolEndpointResolver","endpointOverride","input","AmplifyUrl","cognitoUserPoolEndpointResolver","createGetTokensFromRefreshTokenClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","refreshAuthTokensFunction","refreshAuthTokens","tokens","authConfig","username","clientMetadata","assertTokenProviderConfig","userPoolId","userPoolClientId","userPoolEndpoint","region","getRegionFromUserPoolId","assertAuthTokensWithRefreshToken","getTokensFromRefreshToken","createGetTokensFromRefreshTokenClient","createCognitoUserPoolEndpointResolver","AuthenticationResult","accessToken","decodeJWT","idToken","iat","AuthError","clockDrift","deDupeAsyncFunction","AuthTokenStorageKeys","init_types","__esmMin","TokenProviderErrorCode","tokenValidationErrorMap","assert","createAssertionFunction","AUTH_KEY_PREFIX","init_constants","__esmMin","getAuthStorageKeys","authKeys","keys","prefix","identifier","acc","authKey","DefaultTokenStore","createKeysForAuthStorage","AuthError","keyValueStorage","authConfig","accessTokenString","accessToken","decodeJWT","itString","idToken","refreshToken","clockDriftString","clockDrift","signInDetails","tokens","assert","TokenProviderErrorCode","lastAuthUser","username","deviceKey","deviceGroupKey","randomPassword","assertTokenProviderConfig","AUTH_KEY_PREFIX","metadata","oauthMetadataKey","oauthMetadata","provider","AuthTokenStorageKeys","V5_HOSTED_UI_KEY","name","DefaultOAuthStore","createKeysForAuthStorage","keyValueStorage","assertTokenProviderConfig","authKeys","state","pkce","authConfigParam","inflight","isLegacyHostedUISignIn","isOAuthSignIn","preferPrivateSession","oauthSignIn","provider","identifier","getAuthStorageKeys","OAuthStorageKeys","oAuthStore","DefaultOAuthStore","defaultStorage","inflightPromises","addInflightPromise","resolveAndClearInflightPromises","init_inflightPromise","__esmMin","resolver","TokenOrchestrator","isBrowser","oAuthStore","resolve","_reject","addInflightPromise","authConfig","tokenRefresher","tokenStore","AuthError","clientMetadataProvider","options","tokens","assertTokenProviderConfig","username","idTokenExpired","isTokenExpired","accessTokenExpired","clientMetadata","signInDetails","newTokens","Hub","AMPLIFY_SYMBOL","err","assertServiceError","errorName","metadata","CognitoUserPoolsTokenProvider","DefaultTokenStore","defaultStorage","TokenOrchestrator","refreshAuthTokens","options","keyValueStorage","clientMetadataProvider","authConfig","cognitoUserPoolsTokenProvider","tokenOrchestrator","CognitoUserPoolsTokenProvider","cacheCognitoTokens","AuthenticationResult","accessToken","decodeJWT","accessTokenIssuedAtInMillis","currentTime","clockDrift","idToken","refreshToken","deviceMetadata","tokens","tokenOrchestrator","AmplifyError","ERROR_MESSAGE","dispatchSignedInHubEvent","Hub","getCurrentUser","AMPLIFY_SYMBOL","error","USER_UNAUTHENTICATED_EXCEPTION","AuthError","UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION","defaultState","autoSignInReducer","createAutoSignInStore","autoSignInStore","init_autoSignInStore","__esmMin","state","action","reducer","currentState","setActiveSignInState","state","signInStore","MS_TO_EXPIRY","TGT_STATE","SIGN_IN_STATE_KEYS","signInReducer","isExpired","resetActiveSignInState","clearPersistedSignInState","getDefaultState","getInitialState","createStore","persistSignInState","action","expiryDate","expiryTimestamp","currentTimestamp","stateKey","syncSessionStorage","expiry","username","challengeName","signInSession","reducer","currentState","NOT_SUPPORTED_RECOVERY_SUGGESTION","init_passkeyErrorPlatformConstants","__esmMin","PasskeyError","PasskeyErrorCode","ABORT_OR_CANCEL_RECOVERY_SUGGESTION","MISCONFIGURATION_RECOVERY_SUGGESTION","passkeyErrorMap","assertPasskeyError","_PasskeyError","AmplifyError","params","NOT_SUPPORTED_RECOVERY_SUGGESTION","createAssertionFunction","handlePasskeyError","err","message","recoverySuggestion","passkeyErrorMap","PasskeyErrorCode","PasskeyError","AmplifyErrorCode","handlePasskeyAuthenticationError","err","PasskeyError","message","recoverySuggestion","passkeyErrorMap","PasskeyErrorCode","handlePasskeyError","getIsPasskeySupported","isBrowser","convertArrayBufferToBase64Url","buffer","base64Encoder","convertBase64UrlToArrayBuffer","base64url","base64Decoder","x","deserializeJsonToPkcCreationOptions","serializePkcWithAttestationToJson","deserializeJsonToPkcGetOptions","serializePkcWithAssertionToJson","input","userIdBuffer","convertBase64UrlToArrayBuffer","challengeBuffer","excludeCredentialsWithBuffer","excludeCred","response","convertArrayBufferToBase64Url","publicKey","resultJson","allowedCredentialsWithBuffer","allowedCred","assertValidCredentialCreationOptions","credentialCreationOptions","assertPasskeyError","PasskeyErrorCode","assertCredentialIsPkcWithAuthenticatorAttestationResponse","credential","assertPasskeyError","PasskeyErrorCode","assertCredentialIsPkcWithAuthenticatorAssertionResponse","getPasskey","input","isPasskeySupported","getIsPasskeySupported","assertPasskeyError","PasskeyErrorCode","passkeyGetOptions","deserializeJsonToPkcGetOptions","credential","assertCredentialIsPkcWithAuthenticatorAssertionResponse","serializePkcWithAssertionToJson","err","handlePasskeyAuthenticationError","createConfirmDeviceClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","textEncoder","init_textEncoder","__esmMin","input","BigInteger","a","b","nbi","am1","i","x","w","j","c","n","v","am2","xl","xh","l","h","m","am3","int2char","BI_RM","intAt","s","BI_RC","bnpCopyTo","r","bnpFromInt","nbv","bnpFromString","k","mi","sh","bnpClamp","bnToString","km","d","p","bnNegate","bnAbs","bnCompareTo","nbits","t","bnBitLength","bnpDLShiftTo","bnpDRShiftTo","bnpLShiftTo","bs","cbs","bm","ds","bnpRShiftTo","bnpSubTo","bnpMultiplyTo","y","bnpSquareTo","bnpDivRemTo","q","pm","pt","ts","ms","nsh","ys","y0","yt","d1","d2","e","qd","bnMod","bnpInvDigit","bnEquals","bnpAddTo","bnAdd","bnSubtract","bnMultiply","bnDivide","Montgomery","montConvert","montRevert","montReduce","u0","montSqrTo","montMulTo","bnModPow","callback","z","g","k1","g2","is1","r2","result","dbits","canary","j_lm","inBrowser","BI_FP","rr","vv","init_BigInteger","__esmMin","calculateS","init_calculateS","__esmMin","a","g","k","x","B","N","U","resolve","reject","outerErr","outerResult","innerErr","innerResult","INIT_N","SHORT_TO_HEX","HEX_TO_SHORT","init_constants","__esmMin","i","encodedByte","getBytesFromHex","encoded","out","i","encodedByte","HEX_TO_SHORT","getHexFromBytes","bytes","out","i","SHORT_TO_HEX","getHashFromData","data","sha256","Sha256","hashedData","hashHexFromUint8","getHexFromBytes","getHashFromHex","hexStr","getHashFromData","getBytesFromHex","HEX_MSB_REGEX","getPaddedHex","bigInt","BigInteger","isNegative","hexStr","invertedNibbles","x","invertedNibble","calculateU","A","B","U","BigInteger","getHashFromHex","getPaddedHex","getHkdfKey","ikm","salt","info","awsCryptoHash","Sha256","resultFromAWSCryptoPrk","awsCryptoHashHmac","getRandomBytes","nBytes","str","WordArray","getBytesFromHex","getRandomString","base64Encoder","getRandomBytes","AuthenticationHelper","userPoolName","a","g","A","N","textEncoder","BigInteger","getHashFromHex","getPaddedHex","AuthError","deviceGroupKey","username","getRandomString","combinedString","hashedString","getHashFromData","hexRandom","getHexFromBytes","getRandomBytes","resolve","reject","err","result","password","serverBValue","salt","U","calculateU","usernamePassword","usernamePasswordHash","x","S","calculateS","context","spacer","info","getHkdfKey","getBytesFromHex","calculateA","a","g","N","resolve","reject","err","A","BigInteger","getAuthenticationHelper","generateRandomBigInteger","userPoolName","N","BigInteger","INIT_N","g","a","A","calculateA","AuthenticationHelper","hexRandom","getHexFromBytes","getRandomBytes","getNewDeviceMetadata","userPoolId","userPoolEndpoint","newDeviceMetadata","accessToken","userPoolName","authenticationHelper","getAuthenticationHelper","deviceKey","deviceGroupKey","deviceSecretVerifierConfig","base64Encoder","getBytesFromHex","randomPassword","createConfirmDeviceClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getDeviceName","handleWebAuthnSignInResult","challengeParameters","authConfig","Amplify","assertTokenProviderConfig","username","signInSession","signInDetails","challengeName","signInStore","AuthError","AuthErrorCodes","credentialRequestOptions","assertPasskeyError","PasskeyErrorCode","cred","getPasskey","respondToAuthChallenge","createRespondToAuthChallengeClient","createCognitoUserPoolEndpointResolver","nextChallengeName","nextChallengeParameters","authenticationResult","nextSession","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","setActiveSignInState","cacheCognitoTokens","getNewDeviceMetadata","dispatchSignedInHubEvent","getUserContextData","username","userPoolId","userPoolClientId","amazonCognitoAdvancedSecurityData","advancedSecurityData","init_userContextData","__esmMin","MONTH_NAMES","WEEK_NAMES","getNowString","init_getNowString","__esmMin","now","weekDay","month","day","hours","minutes","seconds","year","getSignatureString","urlB64ToUint8Array","userPoolName","username","challengeParameters","dateNow","hkdf","bufUPIDaToB","textEncoder","bufUNaToB","bufSBaToB","bufDNaToB","bufConcat","awsCryptoHash","Sha256","resultFromAWSCrypto","base64Encoder","base64String","padding","base64","rawData","base64Decoder","outputArray","handleDeviceSRPAuth","username","config","clientMetadata","session","tokenOrchestrator","userPoolId","userPoolEndpoint","clientId","deviceMetadata","assertDeviceMetadata","authenticationHelper","getAuthenticationHelper","challengeResponses","jsonReqResponseChallenge","respondToAuthChallenge","createRespondToAuthChallengeClient","createCognitoUserPoolEndpointResolver","respondedChallengeParameters","Session","getRegionFromUserPoolId","handleDevicePasswordVerifier","challengeParameters","userPoolClientId","serverBValue","BigInteger","salt","deviceKey","deviceGroupKey","hkdf","dateNow","getNowString","getSignatureString","UserContextData","getUserContextData","handlePasswordVerifierChallenge","password","challengeParameters","clientMetadata","session","authenticationHelper","config","tokenOrchestrator","userPoolId","userPoolClientId","userPoolEndpoint","userPoolName","serverBValue","BigInteger","salt","username","AuthError","hkdf","dateNow","getNowString","challengeResponses","getSignatureString","deviceMetadata","UserContextData","getUserContextData","jsonReqResponseChallenge","response","createRespondToAuthChallengeClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","handleDeviceSRPAuth","retryOnResourceNotFoundException","func","args","username","tokenOrchestrator","error","AuthError","setActiveSignInUsername","username","dispatch","signInStore","handlePasswordSRP","username","password","clientMetadata","config","tokenOrchestrator","authFlow","preferredChallenge","userPoolId","userPoolClientId","userPoolEndpoint","userPoolName","authenticationHelper","getAuthenticationHelper","authParameters","UserContextData","getUserContextData","jsonReq","resp","createInitiateAuthClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","challengeParameters","session","activeUsername","setActiveSignInUsername","retryOnResourceNotFoundException","handlePasswordVerifierChallenge","initiateSelectedChallenge","username","session","selectedChallenge","config","clientMetadata","createRespondToAuthChallengeClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","handleSelectChallengeWithPassword","username","password","clientMetadata","config","session","userPoolId","userPoolClientId","userPoolEndpoint","authParameters","userContextData","getUserContextData","response","createRespondToAuthChallengeClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","activeUsername","setActiveSignInUsername","handleSelectChallengeWithPasswordSRP","username","password","clientMetadata","config","session","tokenOrchestrator","userPoolId","userPoolClientId","userPoolEndpoint","userPoolName","authenticationHelper","getAuthenticationHelper","authParameters","userContextData","getUserContextData","response","createRespondToAuthChallengeClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","activeUsername","setActiveSignInUsername","retryOnResourceNotFoundException","handlePasswordVerifierChallenge","isWebAuthnResultAuthSignInOutput","result","handleCustomChallenge","challengeResponse","clientMetadata","session","username","config","tokenOrchestrator","userPoolId","userPoolClientId","userPoolEndpoint","challengeResponses","deviceMetadata","UserContextData","getUserContextData","jsonReq","response","createRespondToAuthChallengeClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","handleDeviceSRPAuth","handleMFASetupChallenge","deviceName","verifySoftwareToken","createVerifySoftwareTokenClient","Session","signInStore","AuthError","AuthErrorCodes","handleSelectMFATypeChallenge","assertValidationError","AuthValidationErrorCode","mapMfaType","handleCompleteNewPasswordChallenge","requiredAttributes","createAttributes","handleUserPasswordAuthFlow","password","authParameters","createInitiateAuthClient","activeUsername","setActiveSignInUsername","handleUserSRPAuthFlow","handlePasswordSRP","handleCustomAuthFlowWithoutSRP","handleCustomSRPAuthFlow","assertTokenProviderConfig","userPoolName","authenticationHelper","getAuthenticationHelper","initiateAuth","challengeParameters","retryOnResourceNotFoundException","handlePasswordVerifierChallenge","getSignInResult","params","challengeName","availableChallenges","authConfig","Amplify","signInSession","mfaSetupTypes","getMFATypes","parseMFATypes","allowedMfaSetupTypes","getAllowedMfaSetupTypes","isTotpMfaSetupAvailable","isEmailMfaSetupAvailable","associateSoftwareToken","createAssociateSoftwareTokenClient","secretCode","getTOTPSetupDetails","parseAttributes","handleWebAuthnSignInResult","appName","accountName","totpUri","AmplifyUrl","getSignInResultFromError","errorName","InitiateAuthException","attributes","att","USER_ATTRIBUTES","newAttributes","key","value","handleChallengeName","options","userAttributes","initiateSelectedChallenge","handleMFAChallenge","handleSelectChallengeWithPassword","handleSelectChallengeWithPasswordSRP","mfa","mfaType","getMFAType","type","types","availableMfaSetupTypes","authMfaType","assertUserNotAuthenticated","authUser","getCurrentUser","USER_ALREADY_AUTHENTICATED_EXCEPTION","getActiveSignInUsername","userContextData","signInWithCustomAuth","input","authConfig","Amplify","assertTokenProviderConfig","username","password","options","signInDetails","metadata","assertValidationError","AuthValidationErrorCode","retriedChallengeName","retiredChallengeParameters","AuthenticationResult","Session","retryOnResourceNotFoundException","handleCustomAuthFlowWithoutSRP","tokenOrchestrator","activeUsername","getActiveSignInUsername","setActiveSignInState","cacheCognitoTokens","getNewDeviceMetadata","resetActiveSignInState","dispatchSignedInHubEvent","getSignInResult","error","assertServiceError","result","getSignInResultFromError","signInWithCustomSRPAuth","input","username","password","options","signInDetails","authConfig","Amplify","assertTokenProviderConfig","metadata","assertValidationError","AuthValidationErrorCode","handledChallengeName","handledChallengeParameters","AuthenticationResult","Session","handleCustomSRPAuthFlow","tokenOrchestrator","activeUsername","getActiveSignInUsername","setActiveSignInState","cacheCognitoTokens","getNewDeviceMetadata","resetActiveSignInState","dispatchSignedInHubEvent","getSignInResult","error","assertServiceError","result","getSignInResultFromError","setAutoSignIn","callback","autoSignIn","resetAutoSignIn","resetCallback","initialAutoSignIn","autoSignInStore","AuthError","AUTO_SIGN_IN_EXCEPTION","signInWithSRP","input","username","password","authConfig","Amplify","signInDetails","assertTokenProviderConfig","clientMetaData","assertValidationError","AuthValidationErrorCode","handledChallengeName","handledChallengeParameters","AuthenticationResult","Session","handleUserSRPAuthFlow","tokenOrchestrator","activeUsername","getActiveSignInUsername","setActiveSignInState","cacheCognitoTokens","getNewDeviceMetadata","resetActiveSignInState","dispatchSignedInHubEvent","resetAutoSignIn","getSignInResult","error","assertServiceError","result","getSignInResultFromError","signInWithUserPassword","input","username","password","options","authConfig","Amplify","signInDetails","assertTokenProviderConfig","metadata","assertValidationError","AuthValidationErrorCode","retiredChallengeName","retriedChallengeParameters","AuthenticationResult","Session","retryOnResourceNotFoundException","handleUserPasswordAuthFlow","tokenOrchestrator","activeUsername","getActiveSignInUsername","setActiveSignInState","cacheCognitoTokens","getNewDeviceMetadata","resetActiveSignInState","dispatchSignedInHubEvent","resetAutoSignIn","getSignInResult","error","assertServiceError","result","getSignInResultFromError","handleUserAuthFlow","username","clientMetadata","config","tokenOrchestrator","preferredChallenge","password","session","userPoolId","userPoolClientId","userPoolEndpoint","UserContextData","getUserContextData","authParameters","assertValidationError","AuthValidationErrorCode","handlePasswordSRP","jsonReq","response","createInitiateAuthClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","setActiveSignInUsername","signInWithUserAuth","input","username","password","options","authConfig","Amplify","signInDetails","assertTokenProviderConfig","clientMetaData","preferredChallenge","assertValidationError","AuthValidationErrorCode","handleUserAuthFlowInput","tokenOrchestrator","autoSignInStoreState","autoSignInStore","response","handleUserAuthFlow","activeUsername","getActiveSignInUsername","setActiveSignInState","cacheCognitoTokens","getNewDeviceMetadata","resetActiveSignInState","dispatchSignedInHubEvent","resetAutoSignIn","getSignInResult","error","assertServiceError","result","getSignInResultFromError","signIn","input","resetAutoSignIn","authFlowType","assertUserNotAuthenticated","signInWithSRP","signInWithUserPassword","signInWithCustomAuth","signInWithCustomSRPAuth","signInWithUserAuth","handleCodeAutoSignIn","signInInput","stopHubListener","HubInternal","payload","setAutoSignIn","autoSignInWithCode","timeOutId","resetAutoSignIn","MAX_AUTOSIGNIN_POLLING_MS","debounce","fun","delay","timer","args","handleAutoSignInWithLink","resolve","reject","start","autoSignInPollingIntervalId","AuthError","AUTO_SIGN_IN_EXCEPTION","signInOutput","signIn","error","autoSignInWhenUserIsConfirmedWithLink","debouncedAutoSignInWithLink","handleAutoSignInWithCodeOrUserConfirmed","output","signInWithUserAuth","debouncedAutoSignWithCodeOrUserConfirmed","autoSignInUserConfirmed","createSignUpClientDeserializer","createSignUpClient","response","error","parseJsonError","assertServiceError","SignUpException","name","AuthValidationErrorCode","message","recoverySuggestion","validationErrorMap","AuthError","parseJsonBody","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","signUp","input","username","password","options","authConfig","Amplify","signUpVerificationMethod","clientMetadata","validationData","autoSignIn","assertTokenProviderConfig","assertValidationError","AuthValidationErrorCode","signInServiceOptions","signInInput","userPoolId","userPoolClientId","userPoolEndpoint","signUpClient","createSignUpClient","createCognitoUserPoolEndpointResolver","signUpClientInput","toAttributeType","getUserContextData","userId","cdd","userConfirmed","session","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","autoSignInStore","codeDeliveryDetails","isSignUpComplete","isAutoSignInStarted","setAutoSignIn","autoSignInUserConfirmed","autoSignInWhenUserIsConfirmedWithLink","handleCodeAutoSignIn","createForgotPasswordClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","resetPassword","input","username","assertValidationError","AuthValidationErrorCode","authConfig","Amplify","assertTokenProviderConfig","userPoolClientId","userPoolId","userPoolEndpoint","clientMetadata","UserContextData","getUserContextData","codeDeliveryDetails","createForgotPasswordClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","createConfirmForgotPasswordClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","confirmResetPassword","input","authConfig","Amplify","assertTokenProviderConfig","userPoolClientId","userPoolId","userPoolEndpoint","username","newPassword","assertValidationError","AuthValidationErrorCode","code","metadata","UserContextData","getUserContextData","createConfirmForgotPasswordClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","createResendConfirmationCodeClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","resendSignUpCode","input","username","assertValidationError","AuthValidationErrorCode","authConfig","Amplify","assertTokenProviderConfig","userPoolClientId","userPoolId","userPoolEndpoint","clientMetadata","UserContextData","getUserContextData","resendConfirmationCode","createResendConfirmationCodeClient","createCognitoUserPoolEndpointResolver","CodeDeliveryDetails","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","DeliveryMedium","AttributeName","Destination","createConfirmSignUpClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","confirmSignUp","input","username","confirmationCode","options","authConfig","Amplify","assertTokenProviderConfig","userPoolId","userPoolClientId","userPoolEndpoint","clientMetadata","assertValidationError","AuthValidationErrorCode","UserContextData","getUserContextData","confirmSignUpClient","createConfirmSignUpClient","createCognitoUserPoolEndpointResolver","session","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","resolve","reject","signUpOut","autoSignInStoreState","autoSignInStore","resetAutoSignIn","stopListener","HubInternal","payload","error","confirmSignIn","input","challengeResponse","options","username","challengeName","signInSession","signInDetails","signInStore","authConfig","Amplify","assertTokenProviderConfig","clientMetaData","assertValidationError","AuthValidationErrorCode","AuthError","AuthErrorCodes","Session","handledChallengeName","AuthenticationResult","handledChallengeParameters","handleChallengeName","tokenOrchestrator","setActiveSignInState","cacheCognitoTokens","getNewDeviceMetadata","resetActiveSignInState","dispatchSignedInHubEvent","getSignInResult","error","assertServiceError","result","getSignInResultFromError","createSetUserMFAPreferenceClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","updateMFAPreference","input","sms","totp","email","authConfig","Amplify","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","createSetUserMFAPreferenceClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","getMFASettings","mfaPreference","createGetUserClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","fetchMFAPreference","authConfig","Amplify","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","getUser","createGetUserClient","createCognitoUserPoolEndpointResolver","PreferredMfaSetting","UserMFASettingList","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","getMFAType","getMFATypes","verifyTOTPSetup","input","authConfig","Amplify","assertTokenProviderConfig","userPoolEndpoint","userPoolId","code","options","assertValidationError","AuthValidationErrorCode","tokens","fetchAuthSession","assertAuthTokens","createVerifySoftwareTokenClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","createChangePasswordClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","updatePassword","input","authConfig","Amplify","assertTokenProviderConfig","userPoolEndpoint","userPoolId","oldPassword","newPassword","assertValidationError","AuthValidationErrorCode","tokens","fetchAuthSession","assertAuthTokens","createChangePasswordClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","setUpTOTP","authConfig","Amplify","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","username","associateSoftwareToken","createAssociateSoftwareTokenClient","createCognitoUserPoolEndpointResolver","SecretCode","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","AuthError","SETUP_TOTP_EXCEPTION","getTOTPSetupDetails","createUpdateUserAttributesClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","getConfirmedAttributes","attributes","confirmedAttributes","key","getUnConfirmedAttributes","codeDeliveryDetailsList","unConfirmedAttributes","codeDeliveryDetails","AttributeName","DeliveryMedium","Destination","updateUserAttributes","input","userAttributes","options","authConfig","Amplify","clientMetadata","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","updateUserAttributesClient","createUpdateUserAttributesClient","createCognitoUserPoolEndpointResolver","CodeDeliveryDetailsList","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","toAttributeType","updateUserAttribute","input","attributeKey","value","options","output","updateUserAttributes","createVerifyUserAttributeClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","confirmUserAttribute","input","authConfig","Amplify","assertTokenProviderConfig","userPoolEndpoint","userPoolId","confirmationCode","userAttributeKey","assertValidationError","AuthValidationErrorCode","tokens","fetchAuthSession","assertAuthTokens","createVerifyUserAttributeClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","logger","authErrorMessages","ConsoleLogger","AuthErrorStrings","createOAuthError","message","recoverySuggestion","AuthError","AuthErrorCodes","authErrorMessages","AuthErrorTypes","init_Auth","__esmMin","flowCancelledMessage","validationFailedMessage","validationRecoverySuggestion","validateState","state","savedState","oAuthStore","validatedState","AuthError","AuthErrorTypes","completeOAuthFlow","handleCodeFlow","handleImplicitFlow","completeFlow","isCustomState","getCustomState","clearHistory","currentUrl","userAgentValue","clientId","redirectUri","responseType","domain","preferPrivateSession","urlParams","AmplifyUrl","error","errorMessage","createOAuthError","url","code","state","validatedState","validateState","oAuthTokenEndpoint","codeVerifier","oAuthStore","oAuthTokenBody","body","k","v","access_token","refreshToken","id_token","token_type","expires_in","USER_AGENT_HEADER","username","decodeJWT","cacheCognitoTokens","error_description","pairings","accum","tokenOrchestrator","resolveAndClearInflightPromises","Hub","urlSafeDecode","AMPLIFY_SYMBOL","dispatchSignedInHubEvent","getRedirectUrl","redirects","preferredRedirectUrl","redirectUrl","redirect","invalidPreferredRedirectUrlException","redirectUrlFromTheSameOrigin","isSameOriginAndPathName","isTheSameDomain","redirectUrlFromDifferentOrigin","isHttps","isHttp","invalidOriginException","invalidRedirectException","handleFailure","error","resolveAndClearInflightPromises","oAuthStore","Hub","AMPLIFY_SYMBOL","attemptCompleteOAuthFlow","authConfig","assertTokenProviderConfig","assertOAuthConfig","oAuthStore","currentUrl","loginWith","userPoolClientId","domain","redirectSignIn","responseType","redirectUri","getRedirectUrl","completeOAuthFlow","getAuthUserAgentValue","AuthAction","err","handleFailure","isBrowser","Amplify","ADD_OAUTH_LISTENER","attemptCompleteOAuthFlow","cognitoHostedUIIdentityProviderMap","init_models","__esmMin","openAuthSession","init_openAuthSession","__esmMin","url","generateCodeChallenge","codeVerifier","awsCryptoHash","Sha256","removePaddingChar","base64Encoder","base64Encoded","CODE_VERIFIER_CHARSET","generateCodeVerifier","length","randomBytes","getCrypto","value","codeChallenge","byte","generateState","generateRandomString","listenForOAuthFlowCancellation","store","handleCancelOAuthFlow","event","error","createOAuthError","handleFailure","signInWithRedirect","input","authConfig","Amplify","assertTokenProviderConfig","assertOAuthConfig","oAuthStore","assertUserNotAuthenticated","provider","idpIdentifier","cognitoHostedUIIdentityProviderMap","oauthSignIn","oauthConfig","clientId","customState","preferPrivateSession","options","authSessionOpener","domain","redirectSignIn","responseType","scopes","loginHint","lang","nonce","prompt","randomState","generateState","openAuthSession","_openAuthSession","state","urlSafeEncode","value","method","toCodeChallenge","generateCodeVerifier","redirectUri","getRedirectUrl","isBrowser","params","oAuthUrl","listenForOAuthFlowCancellation","type","error","url","createOAuthError","completeOAuthFlow","getAuthUserAgentValue","AuthAction","err","handleFailure","fetchUserAttributes","amplify","authConfig","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","getUser","createGetUserClient","createCognitoUserPoolEndpointResolver","UserAttributes","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","toAuthUserAttribute","fetchUserAttributes","fetchUserAttributesInternal","Amplify","completeOAuthSignOut","store","tokenOrchestrator","clearCredentials","Hub","AMPLIFY_SYMBOL","oAuthSignOutRedirect","authConfig","preferPrivateSession","redirectUrl","assertOAuthConfig","loginWith","userPoolClientId","domain","redirectSignOut","signoutUri","getRedirectUrl","oAuthLogoutEndpoint","k","v","openAuthSession","handleOAuthSignOut","cognitoConfig","store","tokenOrchestrator","redirectUrl","isOAuthSignIn","oauthMetadata","completeOAuthSignOut","oAuthSignOutRedirect","createRevokeTokenClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","createGlobalSignOutClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","signOut","input","cognitoConfig","Amplify","assertTokenProviderConfig","globalSignOut","clientSignOut","hasOAuthConfig","assertOAuthConfig","oAuthStore","DefaultOAuthStore","defaultStorage","type","handleOAuthSignOut","tokenOrchestrator","AuthError","OAUTH_SIGNOUT_EXCEPTION","clearCredentials","Hub","AMPLIFY_SYMBOL","userPoolEndpoint","userPoolId","userPoolClientId","authTokens","assertAuthTokensWithRefreshToken","isSessionRevocable","createRevokeTokenClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","logger","assertAuthTokens","createGlobalSignOutClient","ConsoleLogger","token","createGetUserAttributeVerificationCodeClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","sendUserAttributeVerificationCode","input","userAttributeKey","options","authConfig","Amplify","clientMetadata","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","getUserAttributeVerificationCode","createGetUserAttributeVerificationCodeClient","createCognitoUserPoolEndpointResolver","CodeDeliveryDetails","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","DeliveryMedium","AttributeName","Destination","createDeleteUserAttributesClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","deleteUserAttributes","input","authConfig","Amplify","assertTokenProviderConfig","userAttributeKeys","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","createDeleteUserAttributesClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","createEmptyResponseDeserializer","response","error","parseJsonError","assertServiceError","AuthError","createDeleteUserClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createEmptyResponseDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","deleteUser","authConfig","Amplify","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","createDeleteUserClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","tokenOrchestrator","signOut","createUpdateDeviceStatusClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","rememberDevice","authConfig","Amplify","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","deviceMetadata","tokenOrchestrator","assertDeviceMetadata","createUpdateDeviceStatusClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","createForgetDeviceClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createEmptyResponseDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","forgetDevice","input","externalDeviceKey","authConfig","Amplify","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","deviceMetadata","tokenOrchestrator","currentDeviceKey","assertDeviceMetadata","createForgetDeviceClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","createListDevicesClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","fetchDevices","authConfig","Amplify","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","response","createListDevicesClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","MAX_DEVICES","parseDevicesResponse","devices","id","DeviceAttributes","DeviceCreateDate","DeviceLastModifiedDate","DeviceLastAuthenticatedDate","deviceName","attributes","attrs","Name","Value","IdentityIdStorageKeys","init_types","__esmMin","logger","DefaultIdentityIdStore","createKeysForAuthStorage","ConsoleLogger","authConfigParam","assertIdentityPoolIdConfig","keyValueStorage","storedIdentityId","err","identity","provider","identifier","getAuthStorageKeys","IdentityIdStorageKeys","createCognitoIdentityPoolEndpointResolver","endpointOverride","input","AmplifyUrl","cognitoIdentityPoolEndpointResolver","formLoginsMap","idToken","issuer","decodeJWT","res","AuthError","domainName","cognitoIdentityIdProvider","tokens","authConfig","identityIdStore","identityId","logins","formLoginsMap","generatedIdentityId","generateIdentityId","identityPoolId","region","getRegionFromIdentityPoolId","getId","createGetIdClient","createCognitoIdentityPoolEndpointResolver","idResult","e","assertServiceError","AuthError","logger","CREDENTIALS_TTL","CognitoAWSCredentialsAndIdentityIdProvider","ConsoleLogger","identityIdStore","getCredentialsOptions","isAuthenticated","tokens","authConfig","assertIdentityPoolIdConfig","forceRefresh","tokenHasChanged","identityId","cognitoIdentityIdProvider","assertIdTokenInAuthTokens","region","getRegionFromIdentityPoolId","getCredentialsForIdentity","createGetCredentialsForIdentityClient","createCognitoIdentityPoolEndpointResolver","clientResult","e","assertServiceError","AuthError","res","authTokens","logins","formLoginsMap","handlePasskeyRegistrationError","err","PasskeyError","message","recoverySuggestion","passkeyErrorMap","PasskeyErrorCode","handlePasskeyError","registerPasskey","input","isPasskeySupported","getIsPasskeySupported","assertPasskeyError","PasskeyErrorCode","passkeyCreationOptions","deserializeJsonToPkcCreationOptions","credential","assertCredentialIsPkcWithAuthenticatorAttestationResponse","serializePkcWithAttestationToJson","err","handlePasskeyRegistrationError","createStartWebAuthnRegistrationClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","createCompleteWebAuthnRegistrationClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","associateWebAuthnCredential","authConfig","Amplify","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","fetchAuthSession","assertAuthTokens","startWebAuthnRegistration","createStartWebAuthnRegistrationClient","createCognitoUserPoolEndpointResolver","credentialCreationOptions","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","assertValidCredentialCreationOptions","cred","registerPasskey","createCompleteWebAuthnRegistrationClient","createListWebAuthnCredentialsClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","listWebAuthnCredentials","amplify","input","authConfig","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","assertAuthTokens","listWebAuthnCredentialsResult","createListWebAuthnCredentialsClient","createCognitoUserPoolEndpointResolver","commandCredentials","nextToken","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","item","listWebAuthnCredentials","input","listWebAuthnCredentialsFoundation","Amplify","createDeleteWebAuthnCredentialClient","config","composeServiceApi","cognitoUserPoolTransferHandler","createUserPoolSerializer","createUserPoolDeserializer","DEFAULT_SERVICE_CLIENT_API_CONFIG","deleteWebAuthnCredential","amplify","input","authConfig","assertTokenProviderConfig","userPoolEndpoint","userPoolId","tokens","assertAuthTokens","createDeleteWebAuthnCredentialClient","createCognitoUserPoolEndpointResolver","getRegionFromUserPoolId","getAuthUserAgentValue","AuthAction","deleteWebAuthnCredential","input","deleteWebAuthnCredentialFoundation","Amplify","init_esm","__esmMin","init_signUp","init_resetPassword","init_confirmResetPassword","init_signIn","init_resendSignUpCode","init_confirmSignUp","init_confirmSignIn","init_updateMFAPreference","init_fetchMFAPreference","init_verifyTOTPSetup","init_updatePassword","init_setUpTOTP","init_updateUserAttributes","init_updateUserAttribute","init_getCurrentUser","init_confirmUserAttribute","init_signInWithRedirect","init_fetchUserAttributes","init_signOut","init_sendUserAttributeVerificationCode","init_deleteUserAttributes","init_deleteUser","init_rememberDevice","init_forgetDevice","init_fetchDevices","init_autoSignIn","init_AuthError","init_module","init_associateWebAuthnCredential","init_listWebAuthnCredentials","init_deleteWebAuthnCredential","auth_exports","__export","AuthError","associateWebAuthnCredential","autoSignIn","confirmResetPassword","confirmSignIn","confirmSignUp","confirmUserAttribute","decodeJWT","deleteUser","deleteUserAttributes","deleteWebAuthnCredential","fetchAuthSession","fetchDevices","fetchMFAPreference","fetchUserAttributes","forgetDevice","getCurrentUser","listWebAuthnCredentials","rememberDevice","resendSignUpCode","resetPassword","sendUserAttributeVerificationCode","setUpTOTP","signIn","signInWithRedirect","signOut","signUp","updateMFAPreference","updatePassword","updateUserAttribute","updateUserAttributes","verifyTOTPSetup","init_auth","__esmMin","init_esm","cognitoCredentialsProvider","CognitoAWSCredentialsAndIdentityIdProvider","DefaultIdentityIdStore","defaultStorage","init_cognito","__esmMin","init_signInWithRedirect","init_credentialsProvider","init_tokenProvider","init_IdentityIdStore","DefaultAmplify","resourceConfig","libraryOptions","resolvedResourceConfig","parseAmplifyConfig","cookieBasedKeyValueStorage","CookieStorage","resolvedKeyValueStorage","defaultStorage","resolvedCredentialsProvider","CognitoAWSCredentialsAndIdentityIdProvider","DefaultIdentityIdStore","cognitoCredentialsProvider","Amplify","cognitoUserPoolsTokenProvider","authLibraryOptions","esm_exports","__export","DefaultAmplify","init_esm","__esmMin","init_initSingleton","src_exports","__export","createFoundation","unwrapResponse","json","extractError","status","body","errorObj","message","details","detailMessages","d","customMessage","createHttpClient","config","headers","token","request","baseUrl","path","method","options","hdrs","url","searchParams","key","value","qs","fetchOptions","response","rawFetch","importAuth0","importAmplifyAuth","importAmplify","createAuthClient","config","createAuth0Client","client","auth0Domain","auth0ClientId","options","user","email","password","response","err","metadata","_code","_newPassword","fetchAuthSession","signInWithRedirect","signOut","getCurrentUser","Amplify","token","signIn","signUp","resetPassword","code","newPassword","confirmResetPassword","createAuthService","listeners","notifyListeners","fn","authUser","callback","idx","parseJwt","token","jwtPart","queryPart","parts","payloadStr","jwtPayload","value","key","apiBaseUrl","websocketBaseUrl","accountBaseUrl","err","message","createFoundation","options","configUrl","resolvedAppId","resolvedTenantId","envResponse","env","configHeaders","publicConfigResponse","rawPublicConfig","publicConfig","authConfig","authClient","createAuthClient","authService","createAuthService","apiBaseUrl","accountBaseUrl","token","claims","parseJwt","appId","tenantId","version","http","createHttpClient","backendConfig","err","mergedConfig","namespace","config","app","theme","provider","rest","db","createDbService","files","createFilesService","account","createAccountService","integration","createIntegrationService","openapi","createOpenApiService","log","createLogService","entityListeners","event","callback","idx","apiBase","entity","filters","limit","cursor","orderBy","orderDir","params","id","data","updates","fileData","uploadData","formData","key","value","s3Response","fileId","result","accountBase","service","rawCatalog","rawConnections","catalog","connections","bySource","conn","source","item","conns","c","filtered","configurationId","message","context"]}