From 1fdbb12f85d1a363258c4ebeb5aa7c98ee619e16 Mon Sep 17 00:00:00 2001 From: Chris F <5827964+cshfang@users.noreply.github.com> Date: Thu, 15 Feb 2024 12:36:37 -0800 Subject: [PATCH] chore: Upgrade Prettier (#13017) --- .github/ISSUE_TEMPLATE/1.bug_report.yaml | 14 +- jest.config.js | 6 +- package.json | 2 +- .../__tests__/createServerRunner.test.ts | 16 +- ...torageAdapterFromNextServerContext.test.ts | 52 ++-- ...okieStorageAdapterFromNextServerContext.ts | 2 +- .../createRunWithAmplifyServerContext.ts | 2 +- .../kinesis-firehose/apis/flushEvents.test.ts | 6 +- .../kinesis-firehose/apis/record.test.ts | 6 +- .../utils/getEventBuffer.test.ts | 2 +- .../kinesis/apis/flushEvents.test.ts | 6 +- .../providers/kinesis/apis/record.test.ts | 6 +- .../kinesis/utils/getEventBuffer.test.ts | 2 +- .../personalize/apis/flushEvents.test.ts | 6 +- .../providers/personalize/apis/record.test.ts | 18 +- .../personalize/utils/cachedSession.test.ts | 14 +- .../personalize/utils/getEventBuffer.test.ts | 2 +- .../pinpoint/apis/configureAutoTrack.test.ts | 14 +- .../pinpoint/apis/flushEvents.test.ts | 4 +- .../providers/pinpoint/apis/record.test.ts | 4 +- .../utils/eventBuffer/EventBuffer.test.ts | 10 +- .../AWSAppSyncRealTimeProvider.test.ts | 86 +++--- packages/api-graphql/__tests__/helpers.ts | 22 +- .../internals/generateClient.test.ts | 2 +- .../__tests__/server/generateClient.test.ts | 6 +- .../api-graphql/__tests__/utils/expects.ts | 31 +- packages/api-graphql/__tests__/v6-test.ts | 6 +- packages/api-graphql/src/GraphQLAPI.ts | 4 +- .../AWSAppSyncRealTimeProvider/index.ts | 40 +-- .../api-graphql/src/internals/APIClient.ts | 12 +- .../src/internals/InternalGraphQLAPI.ts | 2 +- .../src/internals/operations/get.ts | 22 +- .../src/internals/operations/list.ts | 20 +- .../src/internals/operations/subscription.ts | 12 +- .../generateClientWithAmplifyInstance.ts | 2 +- packages/api-graphql/src/internals/v6.ts | 10 +- .../api-graphql/src/server/generateClient.ts | 4 +- packages/api-graphql/src/types/index.ts | 95 ++++--- .../src/utils/ConnectionStateMonitor.ts | 12 +- .../src/utils/errors/assertValidationError.ts | 2 +- .../src/utils/findIndexByFields.ts | 6 +- .../api-graphql/src/utils/resolveConfig.ts | 4 +- .../src/utils/resolveOwnerFields.ts | 2 +- packages/api-graphql/tsconfig.json | 4 +- .../apis/common/internalPost.test.ts | 24 +- .../__tests__/apis/common/publicApis.test.ts | 30 +- packages/api-rest/__tests__/server.test.ts | 12 +- packages/api/__tests__/API.test.ts | 4 +- packages/api/src/internals/InternalAPI.ts | 6 +- packages/auth/__tests__/BigInteger.test.ts | 4 +- .../providers/cognito/autoSignIn.test.ts | 4 +- .../cognito/confirmResetPassword.test.ts | 20 +- .../cognito/confirmSignInErrorCases.test.ts | 6 +- .../cognito/confirmSignInHappyCases.test.ts | 42 +-- .../providers/cognito/confirmSignUp.test.ts | 12 +- .../cognito/confirmUserAttribute.test.ts | 10 +- .../cognito/credentialsProvider.test.ts | 54 ++-- .../providers/cognito/deleteUser.test.ts | 6 +- .../cognito/deleteUserAttributes.test.ts | 8 +- .../cognito/fetchAuthSession.test.ts | 10 +- .../providers/cognito/fetchDevices.test.ts | 4 +- .../cognito/fetchMFAPreference.test.ts | 4 +- .../cognito/fetchUserAttributes.test.ts | 4 +- .../providers/cognito/forgetDevice.test.ts | 12 +- .../cognito/getNewDeviceMetadata.test.ts | 8 +- .../__tests__/providers/cognito/hub.test.ts | 6 +- .../cognito/identityIdProvider.test.ts | 20 +- .../providers/cognito/identityIdStore.test.ts | 12 +- .../providers/cognito/refreshToken.test.ts | 18 +- .../providers/cognito/rememberDevice.test.ts | 6 +- .../cognito/resendSignUpCode.test.ts | 10 +- .../providers/cognito/resetPassword.test.ts | 12 +- .../sendUserAttributeVerificationCode.test.ts | 10 +- .../providers/cognito/setUpTOTP.test.ts | 8 +- .../cognito/signInErrorCases.test.ts | 2 +- .../cognito/signInStateManagement.test.ts | 4 +- .../cognito/signInWithCustomAuth.test.ts | 8 +- .../cognito/signInWithCustomSRPAuth.test.ts | 6 +- .../cognito/signInWithRedirect.test.ts | 28 +- .../providers/cognito/signInWithSRP.test.ts | 14 +- .../cognito/signInWithUserPassword.test.ts | 6 +- .../providers/cognito/signOut.test.ts | 20 +- .../providers/cognito/signUp.test.ts | 4 +- .../cognito/testUtils/authApiTestParams.ts | 12 +- .../cognito/tokenOrchestrator.test.ts | 6 +- .../providers/cognito/tokenProvider.test.ts | 158 +++++------ .../tokenProvider/tokenOrchestrator.test.ts | 2 +- .../cognito/updateMFAPreference.test.ts | 10 +- .../providers/cognito/updatePassword.test.ts | 6 +- .../cognito/updateUserAttributes.test.ts | 12 +- .../oauth/attemptCompleteOAuthFlow.test.ts | 14 +- .../utils/oauth/completeOAuthFlow.test.ts | 34 +-- .../utils/oauth/completeOAuthSignOut.test.ts | 2 +- .../oauth/handleOAuthSignOut.native.test.ts | 10 +- .../utils/oauth/handleOAuthSignOut.test.ts | 4 +- .../cognito/utils/oauth/index.test.ts | 2 +- .../utils/oauth/oAuthSignOutRedirect.test.ts | 6 +- .../cognito/utils/oauth/validateState.test.ts | 2 +- .../utils/srp/AuthenticationHelper.test.ts | 12 +- .../utils/srp/calculate/calculateS.test.ts | 6 +- .../providers/cognito/verifyTOTPSetup.test.ts | 8 +- .../src/errors/utils/assertServiceError.ts | 2 +- .../src/errors/utils/assertValidationError.ts | 2 +- .../cognito/apis/confirmResetPassword.ts | 10 +- .../providers/cognito/apis/confirmSignIn.ts | 10 +- .../providers/cognito/apis/confirmSignUp.ts | 10 +- .../cognito/apis/confirmUserAttribute.ts | 6 +- .../src/providers/cognito/apis/deleteUser.ts | 2 +- .../cognito/apis/deleteUserAttributes.ts | 4 +- .../providers/cognito/apis/fetchDevices.ts | 8 +- .../cognito/apis/fetchMFAPreference.ts | 2 +- .../providers/cognito/apis/forgetDevice.ts | 2 +- .../apis/internal/fetchUserAttributes.ts | 4 +- .../cognito/apis/internal/getCurrentUser.ts | 4 +- .../providers/cognito/apis/rememberDevice.ts | 2 +- .../cognito/apis/resendSignUpCode.ts | 6 +- .../providers/cognito/apis/resetPassword.ts | 6 +- .../apis/sendUserAttributeVerificationCode.ts | 6 +- .../apis/server/fetchUserAttributes.ts | 4 +- .../cognito/apis/server/getCurrentUser.ts | 2 +- .../src/providers/cognito/apis/setUpTOTP.ts | 2 +- .../cognito/apis/signInWithCustomAuth.ts | 12 +- .../cognito/apis/signInWithCustomSRPAuth.ts | 12 +- .../cognito/apis/signInWithRedirect.ts | 2 +- .../providers/cognito/apis/signInWithSRP.ts | 12 +- .../cognito/apis/signInWithUserPassword.ts | 12 +- .../src/providers/cognito/apis/signOut.ts | 8 +- .../auth/src/providers/cognito/apis/signUp.ts | 6 +- .../cognito/apis/updateMFAPreference.ts | 6 +- .../providers/cognito/apis/updatePassword.ts | 8 +- .../cognito/apis/updateUserAttribute.ts | 2 +- .../cognito/apis/updateUserAttributes.ts | 8 +- .../providers/cognito/apis/verifyTOTPSetup.ts | 6 +- .../credentialsProvider/IdentityIdProvider.ts | 6 +- .../credentialsProvider/IdentityIdStore.ts | 6 +- .../credentialsProvider.ts | 14 +- .../cognito/credentialsProvider/index.ts | 2 +- .../CognitoUserPoolsTokenProvider.ts | 2 +- .../tokenProvider/TokenOrchestrator.ts | 4 +- .../cognito/tokenProvider/TokenStore.ts | 42 +-- .../cognito/tokenProvider/cacheTokens.ts | 2 +- .../providers/cognito/tokenProvider/types.ts | 2 +- .../src/providers/cognito/utils/apiHelpers.ts | 4 +- .../clients/CognitoIdentityProvider/base.ts | 4 +- .../clients/CognitoIdentityProvider/index.ts | 58 ++-- .../clients/CognitoIdentityProvider/types.ts | 4 +- .../providers/cognito/utils/clients/base.ts | 4 +- .../utils/oauth/attemptCompleteOAuthFlow.ts | 4 +- .../cognito/utils/oauth/completeOAuthFlow.ts | 4 +- .../cognito/utils/oauth/createOAuthError.ts | 2 +- .../utils/oauth/generateCodeVerifier.ts | 4 +- .../utils/oauth/getRedirectUrl.native.ts | 2 +- .../cognito/utils/oauth/getRedirectUrl.ts | 2 +- .../cognito/utils/oauth/handleFailure.ts | 4 +- .../utils/oauth/handleOAuthSignOut.native.ts | 4 +- .../cognito/utils/oauth/handleOAuthSignOut.ts | 2 +- .../utils/oauth/oAuthSignOutRedirect.ts | 4 +- .../cognito/utils/refreshAuthTokens.ts | 2 +- .../providers/cognito/utils/signInHelpers.ts | 82 +++--- .../cognito/utils/signInWithRedirectStore.ts | 26 +- .../providers/cognito/utils/signUpHelpers.ts | 14 +- .../AuthenticationHelper.ts | 12 +- .../utils/srp/BigInteger/BigInteger.ts | 14 +- .../utils/srp/BigInteger/index.native.ts | 2 +- .../cognito/utils/srp/calculate/calculateS.ts | 2 +- .../cognito/utils/srp/calculate/calculateU.ts | 2 +- .../cognito/utils/srp/getBytesFromHex.ts | 2 +- .../providers/cognito/utils/srp/getHkdfKey.ts | 2 +- .../cognito/utils/srp/getPaddedHex.ts | 2 +- .../cognito/utils/srp/getSignatureString.ts | 4 +- .../auth/src/providers/cognito/utils/types.ts | 14 +- .../cognito/utils/userContextData.ts | 2 +- .../auth/src/utils/getAuthUserAgentDetails.ts | 2 +- .../auth/src/utils/getAuthUserAgentValue.ts | 2 +- .../auth/src/utils/openAuthSession.native.ts | 4 +- packages/auth/src/utils/types.ts | 4 +- ...WSCredentialsAndIdentityIdProvider.test.ts | 6 +- .../createUserPoolsTokenProvider.test.ts | 16 +- .../runWithAmplifyServerContext.test.ts | 14 +- ...lueStorageFromCookieStorageAdapter.test.ts | 8 +- .../aws-amplify/__tests__/exports.test.ts | 26 +- .../__tests__/initSingleton.test.ts | 40 +-- packages/core/__mocks__/AsyncStorage.js | 2 +- .../BackgroundProcessManager.test.ts | 30 +- .../core/__tests__/Cache/StorageCache.test.ts | 6 +- .../Cache/StorageCacheCommon.test.ts | 70 ++--- packages/core/__tests__/DateUtils.test.ts | 8 +- packages/core/__tests__/Hub.test.ts | 14 +- packages/core/__tests__/I18n.test.ts | 8 +- packages/core/__tests__/Mutex.test.ts | 12 +- .../Platform/customUserAgent.test.ts | 6 +- .../core/__tests__/Platform/userAgent.test.ts | 14 +- packages/core/__tests__/Retry.test.ts | 10 +- packages/core/__tests__/ServiceWorker.test.ts | 10 +- packages/core/__tests__/Signer.test.ts | 30 +- packages/core/__tests__/StringUtils.test.ts | 2 +- .../adapterCore/serverContext.test.ts | 8 +- .../getCredentialsForIdentity.test.ts | 8 +- .../awsClients/cognitoIdentity/getId.test.ts | 6 +- .../pinpoint/getInAppMessages.test.ts | 6 +- .../awsClients/pinpoint/putEvents.test.ts | 6 +- .../pinpoint/updateEndpoint.test.ts | 6 +- .../clients/composeApiHandler.test.ts | 12 +- .../clients/composeTransferHandler.test.ts | 12 +- packages/core/__tests__/clients/fetch.test.ts | 14 +- .../middleware/retry/middleware.test.ts | 14 +- .../middleware/signing/middleware.test.ts | 18 +- .../signer/signatureV4/presignUrl.test.ts | 10 +- .../signer/signatureV4/signRequest.test.ts | 10 +- .../signatureV4/testUtils/signingTestTable.ts | 2 +- .../signatureV4/utils/dataHashHelpers.test.ts | 18 +- .../utils/getCanonicalQueryString.test.ts | 4 +- .../utils/getCanonicalRequest.test.ts | 2 +- .../utils/getCredentialScope.test.ts | 4 +- .../utils/getHashedPayload.test.ts | 10 +- .../signatureV4/utils/getSignature.test.ts | 2 +- .../signatureV4/utils/getSigningKey.test.ts | 4 +- .../utils/getSigningValues.test.ts | 2 +- .../signatureV4/utils/getStringToSign.test.ts | 6 +- .../utils/getUpdatedSystemClockOffset.test.ts | 6 +- .../signing/utils/isClockSkewed.test.ts | 2 +- .../providers/pinpoint/apis/record.test.ts | 10 +- .../pinpoint/apis/updateEndpoint.test.ts | 10 +- .../pinpoint/utils/cacheEndpointId.test.ts | 2 +- .../pinpoint/utils/resolveEndpointId.test.ts | 6 +- .../singleton/Auth/utils/index.test.ts | 2 +- .../__tests__/singleton/Singleton.test.ts | 12 +- .../__tests__/storage/CookieStorage.test.ts | 4 +- packages/core/__tests__/utils.test.ts | 8 +- .../utils/convert/base64Encoder.test.ts | 2 +- .../utils/getClientInfo/getClientInfo.test.ts | 2 +- .../utils/haveCredentialsChanged.test.ts | 9 +- .../queuedStorage.native.test.ts | 20 +- .../SessionListener.native.test.ts | 2 +- .../sessionListener/SessionListener.test.ts | 2 +- .../internal/composeTransferHandler.ts | 18 +- packages/core/src/parseAWSExports.ts | 8 +- .../createQueuedStorage.native.ts | 2 +- .../__tests__/SQLiteAdapter.test.ts | 2 +- .../__tests__/SQLiteCPKEnabled.test.ts | 2 +- .../__tests__/SQLiteUtils.test.ts | 26 +- .../__tests__/helpers.ts | 6 +- .../ExpoSQLiteAdapter/ExpoSQLiteAdapter.ts | 2 +- .../ExpoSQLiteAdapter/ExpoSQLiteDatabase.ts | 44 +-- .../src/SQLiteAdapter/SQLiteAdapter.ts | 2 +- .../src/SQLiteAdapter/SQLiteDatabase.ts | 16 +- .../src/common/CommonSQLiteAdapter.ts | 62 ++-- .../src/common/SQLiteUtils.ts | 40 +-- .../src/common/types.ts | 10 +- .../datastore/__tests__/AsyncStorage.test.ts | 62 ++-- .../__tests__/AsyncStorageAdapter.test.ts | 28 +- .../DataStore.BasicOperations.test.ts | 76 ++--- .../DataStore.CustomPrimaryKey.test.ts | 70 ++--- .../DataStore.TypeDefinitions.test.ts | 12 +- .../__tests__/DataStore/DataStore.test.ts | 20 +- .../__tests__/DataStore/modelBehavior.test.ts | 52 ++-- .../__tests__/DataStore/observe.test.ts | 64 ++--- .../__tests__/DataStore/observeQuery.test.ts | 76 ++--- .../__tests__/DataStore/sanityCheck.test.ts | 64 +++-- .../__tests__/IndexedDBAdapter.test.ts | 46 +-- packages/datastore/__tests__/Merger.test.ts | 6 +- .../datastore/__tests__/Predicate.test.ts | 214 +++++++------- .../__tests__/authStrategies.test.ts | 4 +- .../datastore/__tests__/commonAdapterTests.ts | 265 +++++++++--------- .../conflictResolutionBehavior.test.ts | 32 +-- .../__tests__/connectivityHandling.test.ts | 111 ++++---- .../identifier-fields.test.tsx | 8 +- .../composite-identifier.test.tsx | 30 +- .../legacy-backwards-compatibility.test.tsx | 130 ++++----- .../managed-identifier.test.tsx | 64 ++--- .../optionally-managed-identifier.test.tsx | 94 +++---- packages/datastore/__tests__/graphql.test.ts | 10 +- .../helpers/UpdateSequenceHarness.ts | 16 +- .../__tests__/helpers/datastoreFactory.ts | 6 +- .../__tests__/helpers/fakes/graphqlService.ts | 42 +-- .../__tests__/helpers/schemas/default.ts | 116 ++++---- .../helpers/schemas/typeOnlyModels.ts | 48 ++-- packages/datastore/__tests__/helpers/util.ts | 26 +- .../datastore/__tests__/indexeddb.test.ts | 54 ++-- .../__tests__/indexeddb.upgrade.test.ts | 4 +- packages/datastore/__tests__/model.ts | 48 ++-- packages/datastore/__tests__/mutation.test.ts | 32 +-- packages/datastore/__tests__/outbox.test.ts | 26 +- packages/datastore/__tests__/storage.test.ts | 96 +++---- .../datastore/__tests__/subscription.test.ts | 90 +++--- packages/datastore/__tests__/sync.test.ts | 12 +- packages/datastore/__tests__/util.test.ts | 52 ++-- packages/datastore/__tests__/utils.test.ts | 6 +- .../authModeStrategies/multiAuthStrategy.ts | 8 +- packages/datastore/src/datastore/datastore.ts | 230 +++++++-------- packages/datastore/src/predicates/index.ts | 18 +- packages/datastore/src/predicates/next.ts | 70 ++--- packages/datastore/src/predicates/sort.ts | 16 +- .../storage/adapter/AsyncStorageAdapter.ts | 26 +- .../storage/adapter/AsyncStorageDatabase.ts | 14 +- .../src/storage/adapter/InMemoryStore.ts | 2 +- .../src/storage/adapter/IndexedDBAdapter.ts | 56 ++-- .../src/storage/adapter/StorageAdapterBase.ts | 80 +++--- .../datastore/src/storage/adapter/index.ts | 10 +- packages/datastore/src/storage/storage.ts | 68 ++--- .../datastoreReachability/index.native.ts | 2 +- packages/datastore/src/sync/index.ts | 94 +++---- packages/datastore/src/sync/merger.ts | 8 +- packages/datastore/src/sync/outbox.ts | 30 +- .../datastore/src/sync/processors/mutation.ts | 54 ++-- .../src/sync/processors/subscription.ts | 90 +++--- .../datastore/src/sync/processors/sync.ts | 50 ++-- packages/datastore/src/sync/utils.ts | 60 ++-- packages/datastore/src/types.ts | 176 ++++++------ packages/datastore/src/util.ts | 82 +++--- packages/geo/__tests__/Geo.test.ts | 42 +-- .../AmazonLocationServiceProvider.test.ts | 144 +++++----- packages/geo/__tests__/util.test.ts | 45 +-- packages/geo/src/Geo.ts | 22 +- .../AmazonLocationServiceProvider.ts | 46 +-- packages/geo/src/types/Provider.ts | 12 +- packages/geo/src/util.ts | 34 +-- .../__tests__/lex-v1/AWSLexProvider.test.ts | 18 +- .../__tests__/lex-v1/apis/onComplete.test.ts | 2 +- .../__tests__/lex-v1/apis/send.test.ts | 2 +- .../__tests__/lex-v2/AWSLexV2Provider.test.ts | 28 +- .../__tests__/lex-v2/apis/onComplete.test.ts | 2 +- .../__tests__/lex-v2/apis/send.test.ts | 2 +- .../src/errors/assertValidationError.ts | 2 +- .../interactions/src/lex-v1/AWSLexProvider.ts | 6 +- .../src/lex-v1/apis/onComplete.ts | 2 +- packages/interactions/src/lex-v1/apis/send.ts | 2 +- .../src/lex-v1/utils/resolveBotConfig.ts | 2 +- .../src/lex-v2/AWSLexV2Provider.ts | 16 +- .../src/lex-v2/apis/onComplete.ts | 2 +- packages/interactions/src/lex-v2/apis/send.ts | 2 +- .../src/lex-v2/utils/resolveBotConfig.ts | 2 +- .../interactions/src/types/Interactions.ts | 2 +- .../interactions/src/utils/utils.native.ts | 2 +- packages/interactions/src/utils/utils.ts | 2 +- .../eventListeners/eventListeners.test.ts | 4 +- .../pinpoint/apis/clearMessages.test.ts | 8 +- .../pinpoint/apis/dispatchEvent.test.ts | 16 +- .../apis/initializeInAppMessaging.test.ts | 6 +- .../pinpoint/apis/interactionEvents.test.ts | 10 +- .../pinpoint/apis/setConflictHandler.test.ts | 2 +- .../pinpoint/apis/syncMessages.test.ts | 8 +- .../providers/pinpoint/utils/helpers.test.ts | 2 +- .../pinpoint/utils/resolveConfig.test.ts | 2 +- .../utils/processInAppMessages.test.ts | 6 +- .../pinpoint/apis/identifyUser.native.test.ts | 2 +- .../pinpoint/apis/identifyUser.test.ts | 2 +- ...initializePushNotifications.native.test.ts | 36 +-- .../apis/onNotificationOpened.native.test.ts | 2 +- ...icationReceivedInBackground.native.test.ts | 2 +- ...icationReceivedInForeground.native.test.ts | 2 +- .../apis/onTokenReceived.native.test.ts | 2 +- .../utils/createMessageEventRecorder.test.ts | 12 +- .../pinpoint/utils/getAnalyticsEvent.test.ts | 14 +- ...getPushNotificationUserAgentString.test.ts | 2 +- .../src/eventListeners/eventListeners.ts | 4 +- .../errors/assertServiceError.ts | 2 +- .../errors/assertValidationError.ts | 2 +- .../providers/pinpoint/apis/dispatchEvent.ts | 4 +- .../providers/pinpoint/apis/identifyUser.ts | 2 +- .../pinpoint/apis/onMessageActionTaken.ts | 2 +- .../pinpoint/apis/onMessageDismissed.ts | 2 +- .../pinpoint/apis/onMessageDisplayed.ts | 2 +- .../pinpoint/apis/onMessageReceived.ts | 2 +- .../providers/pinpoint/apis/syncMessages.ts | 4 +- .../providers/pinpoint/types/types.ts | 4 +- .../providers/pinpoint/utils/helpers.ts | 22 +- .../utils/messageProcessingHelpers.ts | 4 +- .../pinpoint/utils/resolveCredentials.ts | 2 +- .../providers/pinpoint/utils/userAgent.ts | 2 +- .../src/inAppMessaging/utils/statusHelpers.ts | 2 +- .../pushNotifications/errors/errorHelpers.ts | 2 +- .../pinpoint/apis/identifyUser.native.ts | 2 +- .../initializePushNotifications.native.ts | 34 +-- .../providers/pinpoint/types/apis.ts | 10 +- .../utils/createMessageEventRecorder.ts | 2 +- .../pinpoint/utils/getAnalyticsEvent.ts | 4 +- .../types/pushNotifications.ts | 2 +- .../getPushNotificationUserAgentString.ts | 2 +- .../AWSAIConvertPredictionsProvider.test.ts | 54 ++-- .../AWSAIIdentifyPredictionsProvider.test.ts | 72 ++--- .../AWSAIInterpretPredictionsProvider.test.ts | 20 +- packages/predictions/src/Predictions.ts | 6 +- .../src/errors/utils/assertValidationError.ts | 2 +- .../AmazonAIConvertPredictionsProvider.ts | 42 +-- .../AmazonAIIdentifyPredictionsProvider.ts | 46 +-- .../AmazonAIInterpretPredictionsProvider.ts | 34 +-- .../src/providers/IdentifyTextUtils.ts | 14 +- packages/predictions/src/types/Predictions.ts | 10 +- packages/pubsub/__tests__/PubSub.test.ts | 16 +- packages/pubsub/__tests__/helpers.ts | 22 +- packages/pubsub/src/Providers/AWSIot.ts | 2 +- packages/pubsub/src/Providers/MqttOverWS.ts | 14 +- .../src/utils/ConnectionStateMonitor.ts | 12 +- packages/pubsub/src/vendor/paho-mqtt.js | 148 +++++----- packages/react-native/example/metro.config.js | 4 +- .../loadAmplifyPushNotification.ts | 4 +- .../moduleLoaders/loadAmplifyWebBrowser.ts | 4 +- .../src/moduleLoaders/loadAsyncStorage.ts | 4 +- .../src/moduleLoaders/loadGetRandomValues.ts | 2 +- .../src/moduleLoaders/loadNetInfo.ts | 4 +- .../src/moduleLoaders/loadUrlPolyfill.ts | 2 +- packages/react-native/src/nativeModule.ts | 4 +- .../apis/addMessageEventListener.test.ts | 6 +- .../apis/addTokenEventListener.test.ts | 2 +- .../apis/completeNotification.test.ts | 2 +- .../apis/getLaunchNotification.test.ts | 2 +- .../apis/getPermissionStatus.test.ts | 2 +- .../apis/registerHeadlessTask.test.ts | 4 +- .../__tests__/apis/requestPermissions.test.ts | 2 +- .../utils/normalizeNativeMessage.test.ts | 6 +- .../normalizeNativePermissionStatus.test.ts | 6 +- .../src/apis/addMessageEventListener.ts | 6 +- .../src/apis/addTokenEventListener.ts | 2 +- .../src/apis/getLaunchNotification.ts | 2 +- .../src/apis/registerHeadlessTask.ts | 4 +- .../src/apis/requestPermissions.ts | 2 +- .../rtn-push-notification/src/nativeModule.ts | 4 +- .../rtn-push-notification/src/types/native.ts | 2 +- .../src/utils/normalizeNativeMessage.ts | 10 +- .../utils/normalizeNativePermissionStatus.ts | 2 +- .../src/apis/openAuthSessionAsync.ts | 8 +- packages/rtn-web-browser/src/nativeModule.ts | 4 +- packages/rtn-web-browser/src/types/native.ts | 2 +- .../__tests__/providers/s3/apis/copy.test.ts | 6 +- .../providers/s3/apis/downloadData.test.ts | 4 +- .../providers/s3/apis/getProperties.test.ts | 6 +- .../__tests__/providers/s3/apis/list.test.ts | 6 +- .../providers/s3/apis/remove.test.ts | 4 +- .../s3/apis/uploadData/index.test.ts | 10 +- .../apis/uploadData/multipartHandlers.test.ts | 58 ++-- .../s3/apis/uploadData/putObjectJob.test.ts | 6 +- .../s3/apis/utils/downloadTask.test.ts | 2 +- .../s3/apis/utils/resolvePrefix.test.ts | 4 +- .../utils/resolveS3ConfigAndInput.test.ts | 10 +- .../s3/apis/utils/uploadTask.test.ts | 6 +- .../s3/utils/client/S3/cases/getObject.ts | 2 +- .../utils/client/S3/functional-apis.test.ts | 12 +- .../S3/getPresignedGetObjectUrl.test.ts | 12 +- .../s3/utils/client/testUtils/mocks.ts | 6 +- .../client/xhrTransferHandler-util.test.ts | 26 +- .../src/errors/utils/assertValidationError.ts | 2 +- .../src/providers/s3/apis/downloadData.ts | 6 +- .../src/providers/s3/apis/getProperties.ts | 2 +- .../src/providers/s3/apis/internal/copy.ts | 8 +- .../s3/apis/internal/getProperties.ts | 8 +- .../src/providers/s3/apis/internal/getUrl.ts | 10 +- .../src/providers/s3/apis/internal/list.ts | 6 +- .../src/providers/s3/apis/internal/remove.ts | 6 +- .../storage/src/providers/s3/apis/list.ts | 2 +- .../src/providers/s3/apis/server/copy.ts | 2 +- .../providers/s3/apis/server/getProperties.ts | 4 +- .../src/providers/s3/apis/server/getUrl.ts | 2 +- .../src/providers/s3/apis/server/list.ts | 8 +- .../src/providers/s3/apis/server/remove.ts | 2 +- .../src/providers/s3/apis/uploadData/index.ts | 2 +- .../uploadData/multipart/getDataChunker.ts | 4 +- .../uploadData/multipart/initialUpload.ts | 2 +- .../uploadData/multipart/progressTracker.ts | 2 +- .../apis/uploadData/multipart/uploadCache.ts | 10 +- .../uploadData/multipart/uploadHandlers.ts | 16 +- .../multipart/uploadPartExecutor.ts | 2 +- .../s3/apis/uploadData/putObjectJob.ts | 4 +- .../s3/utils/client/abortMultipartUpload.ts | 6 +- .../src/providers/s3/utils/client/base.ts | 4 +- .../utils/client/completeMultipartUpload.ts | 12 +- .../providers/s3/utils/client/copyObject.ts | 6 +- .../s3/utils/client/createMultipartUpload.ts | 6 +- .../providers/s3/utils/client/deleteObject.ts | 6 +- .../providers/s3/utils/client/getObject.ts | 14 +- .../providers/s3/utils/client/headObject.ts | 6 +- .../s3/utils/client/listObjectsV2.ts | 6 +- .../providers/s3/utils/client/listParts.ts | 8 +- .../providers/s3/utils/client/putObject.ts | 6 +- .../client/runtime/base64/index.browser.ts | 2 +- .../client/runtime/xhrTransferHandler.ts | 12 +- .../providers/s3/utils/client/uploadPart.ts | 6 +- .../utils/client/utils/deserializeHelpers.ts | 10 +- .../s3/utils/client/utils/parsePayload.ts | 4 +- .../s3/utils/client/utils/serializeHelpers.ts | 10 +- .../src/providers/s3/utils/md5.native.ts | 2 +- .../storage/src/providers/s3/utils/md5.ts | 2 +- .../s3/utils/resolveS3ConfigAndInput.ts | 6 +- packages/storage/src/utils/resolvePrefix.ts | 4 +- rollup/utils.mjs | 4 +- scripts/dts-bundler/dts-bundler.config.js | 10 +- scripts/test-github-actions.js | 2 +- yarn.lock | 8 +- 488 files changed, 4033 insertions(+), 4005 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/1.bug_report.yaml b/.github/ISSUE_TEMPLATE/1.bug_report.yaml index 18ac87644ae..ed10dbad86d 100644 --- a/.github/ISSUE_TEMPLATE/1.bug_report.yaml +++ b/.github/ISSUE_TEMPLATE/1.bug_report.yaml @@ -96,9 +96,9 @@ body: Which major version of `aws-amplify` are you using? multiple: false options: - - v6 - - v5 - - Older than v5 + - v6 + - v5 + - Older than v5 validations: required: true - type: dropdown @@ -126,10 +126,10 @@ body: How have you deployed the backend resources? multiple: false options: - - Amplify CLI - - Amplify Gen 2 (Preview) - - CDK - - Other + - Amplify CLI + - Amplify Gen 2 (Preview) + - CDK + - Other - type: textarea attributes: label: Environment information diff --git a/jest.config.js b/jest.config.js index cf70f54ed17..99100f706a5 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,11 +1,7 @@ /** @type {import('jest').Config} */ module.exports = { workerIdleMemoryLimit: '512MB', - coveragePathIgnorePatterns: [ - '/node_modules/', - 'dist', - '__tests__', - ], + coveragePathIgnorePatterns: ['/node_modules/', 'dist', '__tests__'], setupFiles: ['../../jest.setup.js'], testEnvironment: 'jsdom', testRegex: '/__tests__/.*\\.(test|spec)\\.[jt]sx?$', diff --git a/package.json b/package.json index cc643ba412f..fb6ef8e4fd5 100644 --- a/package.json +++ b/package.json @@ -110,7 +110,7 @@ "lerna": "^7.4.2", "license-check-and-add": "^4.0.5", "mkdirp": "^3.0.1", - "prettier": "^3.1.0", + "prettier": "^3.2.5", "rimraf": "^2.6.2", "rollup": "^4.9.6", "size-limit": "^8.1.0", diff --git a/packages/adapter-nextjs/__tests__/createServerRunner.test.ts b/packages/adapter-nextjs/__tests__/createServerRunner.test.ts index 56eee26f28e..17ff383720f 100644 --- a/packages/adapter-nextjs/__tests__/createServerRunner.test.ts +++ b/packages/adapter-nextjs/__tests__/createServerRunner.test.ts @@ -24,7 +24,7 @@ jest.mock( '../src/utils/createCookieStorageAdapterFromNextServerContext', () => ({ createCookieStorageAdapterFromNextServerContext: jest.fn(), - }) + }), ); describe('createServerRunner', () => { @@ -92,7 +92,7 @@ describe('createServerRunner', () => { expect(mockRunWithAmplifyServerContextCore).toHaveBeenCalledWith( mockAmplifyConfig, {}, - operation + operation, ); }); }); @@ -106,11 +106,11 @@ describe('createServerRunner', () => { const operation = jest.fn(); runWithAmplifyServerContext({ operation, nextServerContext: null }); expect( - mockCreateAWSCredentialsAndIdentityIdProvider + mockCreateAWSCredentialsAndIdentityIdProvider, ).toHaveBeenCalledWith(mockAmplifyConfig.Auth, sharedInMemoryStorage); expect(mockCreateUserPoolsTokenProvider).toHaveBeenCalledWith( mockAmplifyConfig.Auth, - sharedInMemoryStorage + sharedInMemoryStorage, ); }); }); @@ -124,7 +124,7 @@ describe('createServerRunner', () => { remove: jest.fn(), }; mockCreateKeyValueStorageFromCookieStorageAdapter.mockReturnValueOnce( - mockCookieStorageAdapter + mockCookieStorageAdapter, ); const mockNextServerContext = { req: { @@ -145,14 +145,14 @@ describe('createServerRunner', () => { mockNextServerContext as unknown as NextServer.Context, }); expect( - mockCreateAWSCredentialsAndIdentityIdProvider + mockCreateAWSCredentialsAndIdentityIdProvider, ).toHaveBeenCalledWith( mockAmplifyConfig.Auth, - mockCookieStorageAdapter + mockCookieStorageAdapter, ); expect(mockCreateUserPoolsTokenProvider).toHaveBeenCalledWith( mockAmplifyConfig.Auth, - mockCookieStorageAdapter + mockCookieStorageAdapter, ); }); }); diff --git a/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts b/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts index 7d26d45e12b..857c0369514 100644 --- a/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts +++ b/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts @@ -49,7 +49,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { ({ get: mockGetFunc, getAll: mockGetAllFunc, - }) as any + }) as any, ); jest.spyOn(response, 'cookies', 'get').mockImplementation(() => ({ @@ -75,7 +75,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { it('gets cookie by calling `get` method of the underlying cookie store with a encoded cookie name', () => { result.get(mockKeyWithEncoding); expect(mockGetFunc).toHaveBeenCalledWith( - encodeURIComponent(mockKeyWithEncoding) + encodeURIComponent(mockKeyWithEncoding), ); }); @@ -89,7 +89,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { expect(mockSetFunc).toHaveBeenCalledWith( mockKey, mockValue, - undefined /* didn't specify the options param in the call */ + undefined /* didn't specify the options param in the call */, ); }); @@ -98,7 +98,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { expect(mockSetFunc).toHaveBeenCalledWith( encodeURIComponent(mockKeyWithEncoding), mockValue, - { sameSite: 'lax' } + { sameSite: 'lax' }, ); }); @@ -110,7 +110,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { it('deletes cookie by calling the `delete` method of the underlying cookie store with a encoded cookie name', () => { result.delete(mockKeyWithEncoding); expect(mockDeleteFunc).toHaveBeenCalledWith( - encodeURIComponent(mockKeyWithEncoding) + encodeURIComponent(mockKeyWithEncoding), ); }); }); @@ -124,13 +124,13 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { ({ get: mockGetFunc, getAll: mockGetAllFunc, - }) as any + }) as any, ); jest.spyOn(response, 'headers', 'get').mockImplementation( () => ({ append: mockAppend, - }) as any + }) as any, ); const mockContext = { @@ -156,7 +156,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { it('gets cookie by calling `get` method of the underlying cookie store with a encoded cookie name', () => { result.get(mockKeyWithEncoding); expect(mockGetFunc).toHaveBeenCalledWith( - encodeURIComponent(mockKeyWithEncoding) + encodeURIComponent(mockKeyWithEncoding), ); }); @@ -173,7 +173,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { mockSerializeOptions.domain };Expires=${mockSerializeOptions.expires.toUTCString()};HttpOnly;SameSite=${ mockSerializeOptions.sameSite - };Secure` + };Secure`, ); }); @@ -185,7 +185,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { mockSerializeOptions.domain };Expires=${mockSerializeOptions.expires.toUTCString()};HttpOnly;SameSite=${ mockSerializeOptions.sameSite - };Secure` + };Secure`, ); }); @@ -193,7 +193,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { result.set(mockKey, mockValue, undefined); expect(mockAppend).toHaveBeenCalledWith( 'Set-Cookie', - `${mockKey}=${mockValue};` + `${mockKey}=${mockValue};`, ); }); @@ -205,7 +205,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { }); expect(mockAppend).toHaveBeenCalledWith( 'Set-Cookie', - `${mockKey}=${mockValue};` + `${mockKey}=${mockValue};`, ); }); @@ -213,7 +213,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { result.delete(mockKey); expect(mockAppend).toHaveBeenCalledWith( 'Set-Cookie', - `${mockKey}=;Expires=${DATE_IN_THE_PAST.toUTCString()}` + `${mockKey}=;Expires=${DATE_IN_THE_PAST.toUTCString()}`, ); }); @@ -222,8 +222,8 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { expect(mockAppend).toHaveBeenCalledWith( 'Set-Cookie', `${encodeURIComponent( - mockKeyWithEncoding - )}=;Expires=${DATE_IN_THE_PAST.toUTCString()}` + mockKeyWithEncoding, + )}=;Expires=${DATE_IN_THE_PAST.toUTCString()}`, ); }); }); @@ -241,7 +241,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { it('gets cookie by calling `get` method of the underlying cookie store with a encoded cookie name', () => { result.get(mockKeyWithEncoding); expect(mockNextCookiesFuncReturn.get).toHaveBeenCalledWith( - encodeURIComponent(mockKeyWithEncoding) + encodeURIComponent(mockKeyWithEncoding), ); }); @@ -255,7 +255,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { expect(mockNextCookiesFuncReturn.set).toHaveBeenCalledWith( mockKey, mockValue, - undefined + undefined, ); }); @@ -264,7 +264,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { expect(mockNextCookiesFuncReturn.set).toHaveBeenCalledWith( encodeURIComponent(mockKeyWithEncoding), mockValue, - undefined + undefined, ); }); @@ -276,7 +276,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { it('deletes cookie by calling the `delete` method of the underlying cookie store with a encoded cookie name', () => { result.delete(mockKeyWithEncoding); expect(mockNextCookiesFuncReturn.delete).toHaveBeenCalledWith( - encodeURIComponent(mockKeyWithEncoding) + encodeURIComponent(mockKeyWithEncoding), ); }); }); @@ -318,13 +318,13 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { }); expect(setHeaderSpy).toHaveBeenCalledWith( 'Set-Cookie', - 'key4=value4;HttpOnly' + 'key4=value4;HttpOnly', ); result.delete('key3'); expect(setHeaderSpy).toHaveBeenCalledWith( 'Set-Cookie', - `key3=;Expires=${DATE_IN_THE_PAST.toUTCString()}` + `key3=;Expires=${DATE_IN_THE_PAST.toUTCString()}`, ); }); @@ -332,7 +332,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { // these the auth keys generated by Amplify const encodedCookieName1 = encodeURIComponent('test@email.com.idToken'); const encodedCookieName2 = encodeURIComponent( - 'test@email.com.refreshToken' + 'test@email.com.refreshToken', ); const mockCookies = { @@ -375,18 +375,18 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { }); const encodedCookieName = encodeURIComponent( - 'test@email.com.somethingElse' + 'test@email.com.somethingElse', ); result.set(encodeURIComponent('test@email.com.somethingElse'), 'value5'); expect(setHeaderSpy).toHaveBeenCalledWith( 'Set-Cookie', - `${encodeURIComponent(encodedCookieName)}=value5;` + `${encodeURIComponent(encodedCookieName)}=value5;`, ); result.delete('key3'); expect(setHeaderSpy).toHaveBeenCalledWith( 'Set-Cookie', - `key3=;Expires=${DATE_IN_THE_PAST.toUTCString()}` + `key3=;Expires=${DATE_IN_THE_PAST.toUTCString()}`, ); }); }); @@ -396,7 +396,7 @@ describe('createCookieStorageAdapterFromNextServerContext', () => { createCookieStorageAdapterFromNextServerContext({ request: undefined, response: new ServerResponse({} as any), - } as any) + } as any), ).toThrow(); }); }); diff --git a/packages/adapter-nextjs/src/utils/createCookieStorageAdapterFromNextServerContext.ts b/packages/adapter-nextjs/src/utils/createCookieStorageAdapterFromNextServerContext.ts index 0b6ac3f8726..882860436ac 100644 --- a/packages/adapter-nextjs/src/utils/createCookieStorageAdapterFromNextServerContext.ts +++ b/packages/adapter-nextjs/src/utils/createCookieStorageAdapterFromNextServerContext.ts @@ -164,7 +164,7 @@ const createCookieStorageAdapterFromGetServerSidePropsContext = ( ? { name, value, - } + } : undefined; }, getAll() { diff --git a/packages/adapter-nextjs/src/utils/createRunWithAmplifyServerContext.ts b/packages/adapter-nextjs/src/utils/createRunWithAmplifyServerContext.ts index 1797a1be0ca..787e934c11b 100644 --- a/packages/adapter-nextjs/src/utils/createRunWithAmplifyServerContext.ts +++ b/packages/adapter-nextjs/src/utils/createRunWithAmplifyServerContext.ts @@ -34,7 +34,7 @@ export const createRunWithAmplifyServerContext = ({ createCookieStorageAdapterFromNextServerContext( nextServerContext, ), - ); + ); const credentialsProvider = createAWSCredentialsAndIdentityIdProvider( resourcesConfig.Auth, keyValueStorage, diff --git a/packages/analytics/__tests__/providers/kinesis-firehose/apis/flushEvents.test.ts b/packages/analytics/__tests__/providers/kinesis-firehose/apis/flushEvents.test.ts index 44ad877cc34..2be5defe23c 100644 --- a/packages/analytics/__tests__/providers/kinesis-firehose/apis/flushEvents.test.ts +++ b/packages/analytics/__tests__/providers/kinesis-firehose/apis/flushEvents.test.ts @@ -26,7 +26,7 @@ describe('Analytics Kinesis Firehose API: flushEvents', () => { beforeEach(() => { mockResolveConfig.mockReturnValue(mockKinesisConfig); mockResolveCredentials.mockReturnValue( - Promise.resolve(mockCredentialConfig) + Promise.resolve(mockCredentialConfig), ); mockGetEventBuffer.mockImplementation(() => ({ flushAll: mockFlushAll, @@ -50,7 +50,7 @@ describe('Analytics Kinesis Firehose API: flushEvents', () => { expect.objectContaining({ ...mockKinesisConfig, ...mockCredentialConfig, - }) + }), ); expect(mockFlushAll).toHaveBeenCalledTimes(1); }); @@ -62,7 +62,7 @@ describe('Analytics Kinesis Firehose API: flushEvents', () => { await new Promise(process.nextTick); expect(loggerWarnSpy).toHaveBeenCalledWith( expect.any(String), - expect.any(Error) + expect.any(Error), ); }); }); diff --git a/packages/analytics/__tests__/providers/kinesis-firehose/apis/record.test.ts b/packages/analytics/__tests__/providers/kinesis-firehose/apis/record.test.ts index 9910831f6a1..cff514014d7 100644 --- a/packages/analytics/__tests__/providers/kinesis-firehose/apis/record.test.ts +++ b/packages/analytics/__tests__/providers/kinesis-firehose/apis/record.test.ts @@ -35,7 +35,7 @@ describe('Analytics KinesisFirehose API: record', () => { mockIsAnalyticsEnabled.mockReturnValue(true); mockResolveConfig.mockReturnValue(mockKinesisConfig); mockResolveCredentials.mockReturnValue( - Promise.resolve(mockCredentialConfig) + Promise.resolve(mockCredentialConfig), ); mockGetEventBuffer.mockImplementation(() => ({ append: mockAppend, @@ -60,7 +60,7 @@ describe('Analytics KinesisFirehose API: record', () => { streamName: mockRecordInput.streamName, event: mockRecordInput.data, retryCount: 0, - }) + }), ); }); @@ -72,7 +72,7 @@ describe('Analytics KinesisFirehose API: record', () => { await new Promise(process.nextTick); expect(loggerWarnSpy).toHaveBeenCalledWith( expect.any(String), - expect.any(Error) + expect.any(Error), ); }); diff --git a/packages/analytics/__tests__/providers/kinesis-firehose/utils/getEventBuffer.test.ts b/packages/analytics/__tests__/providers/kinesis-firehose/utils/getEventBuffer.test.ts index ea12c7c8665..3ac9065eb3e 100644 --- a/packages/analytics/__tests__/providers/kinesis-firehose/utils/getEventBuffer.test.ts +++ b/packages/analytics/__tests__/providers/kinesis-firehose/utils/getEventBuffer.test.ts @@ -26,7 +26,7 @@ describe('KinesisFirehose Provider Util: getEventBuffer', () => { expect(mockEventBuffer).toHaveBeenCalledWith( mockBufferConfig, - expect.any(Function) + expect.any(Function), ); expect(testBuffer).toBeInstanceOf(EventBuffer); }); diff --git a/packages/analytics/__tests__/providers/kinesis/apis/flushEvents.test.ts b/packages/analytics/__tests__/providers/kinesis/apis/flushEvents.test.ts index cb6d50c1e33..1f5d1e7afd3 100644 --- a/packages/analytics/__tests__/providers/kinesis/apis/flushEvents.test.ts +++ b/packages/analytics/__tests__/providers/kinesis/apis/flushEvents.test.ts @@ -25,7 +25,7 @@ describe('Analytics Kinesis API: flushEvents', () => { beforeEach(() => { mockResolveConfig.mockReturnValue(mockKinesisConfig); mockResolveCredentials.mockReturnValue( - Promise.resolve(mockCredentialConfig) + Promise.resolve(mockCredentialConfig), ); mockGetEventBuffer.mockImplementation(() => ({ flushAll: mockFlushAll, @@ -49,7 +49,7 @@ describe('Analytics Kinesis API: flushEvents', () => { expect.objectContaining({ ...mockKinesisConfig, ...mockCredentialConfig, - }) + }), ); expect(mockFlushAll).toHaveBeenCalledTimes(1); }); @@ -61,7 +61,7 @@ describe('Analytics Kinesis API: flushEvents', () => { await new Promise(process.nextTick); expect(loggerWarnSpy).toHaveBeenCalledWith( expect.any(String), - expect.any(Error) + expect.any(Error), ); }); }); diff --git a/packages/analytics/__tests__/providers/kinesis/apis/record.test.ts b/packages/analytics/__tests__/providers/kinesis/apis/record.test.ts index 9ea439ed2fc..4003a75330a 100644 --- a/packages/analytics/__tests__/providers/kinesis/apis/record.test.ts +++ b/packages/analytics/__tests__/providers/kinesis/apis/record.test.ts @@ -35,7 +35,7 @@ describe('Analytics Kinesis API: record', () => { mockIsAnalyticsEnabled.mockReturnValue(true); mockResolveConfig.mockReturnValue(mockKinesisConfig); mockResolveCredentials.mockReturnValue( - Promise.resolve(mockCredentialConfig) + Promise.resolve(mockCredentialConfig), ); mockGetEventBuffer.mockImplementation(() => ({ append: mockAppend, @@ -61,7 +61,7 @@ describe('Analytics Kinesis API: record', () => { partitionKey: mockRecordInput.partitionKey, event: mockRecordInput.data, retryCount: 0, - }) + }), ); }); @@ -73,7 +73,7 @@ describe('Analytics Kinesis API: record', () => { await new Promise(process.nextTick); expect(loggerWarnSpy).toHaveBeenCalledWith( expect.any(String), - expect.any(Error) + expect.any(Error), ); }); diff --git a/packages/analytics/__tests__/providers/kinesis/utils/getEventBuffer.test.ts b/packages/analytics/__tests__/providers/kinesis/utils/getEventBuffer.test.ts index 828745f03f3..f19ea488081 100644 --- a/packages/analytics/__tests__/providers/kinesis/utils/getEventBuffer.test.ts +++ b/packages/analytics/__tests__/providers/kinesis/utils/getEventBuffer.test.ts @@ -26,7 +26,7 @@ describe('Kinesis Provider Util: getEventBuffer', () => { expect(mockEventBuffer).toHaveBeenCalledWith( mockBufferConfig, - expect.any(Function) + expect.any(Function), ); expect(testBuffer).toBeInstanceOf(EventBuffer); }); diff --git a/packages/analytics/__tests__/providers/personalize/apis/flushEvents.test.ts b/packages/analytics/__tests__/providers/personalize/apis/flushEvents.test.ts index e74374e8403..2bca0d84701 100644 --- a/packages/analytics/__tests__/providers/personalize/apis/flushEvents.test.ts +++ b/packages/analytics/__tests__/providers/personalize/apis/flushEvents.test.ts @@ -26,7 +26,7 @@ describe('Analytics Personalize API: flushEvents', () => { beforeEach(() => { mockResolveConfig.mockReturnValue(mockPersonalizeConfig); mockResolveCredentials.mockReturnValue( - Promise.resolve(mockCredentialConfig) + Promise.resolve(mockCredentialConfig), ); mockGetEventBuffer.mockImplementation(() => ({ flushAll: mockFlushAll, @@ -51,7 +51,7 @@ describe('Analytics Personalize API: flushEvents', () => { expect.objectContaining({ ...configWithoutTrackingId, ...mockCredentialConfig, - }) + }), ); expect(mockFlushAll).toHaveBeenCalledTimes(1); }); @@ -63,7 +63,7 @@ describe('Analytics Personalize API: flushEvents', () => { await new Promise(process.nextTick); expect(loggerWarnSpy).toHaveBeenCalledWith( expect.any(String), - expect.any(Error) + expect.any(Error), ); }); }); diff --git a/packages/analytics/__tests__/providers/personalize/apis/record.test.ts b/packages/analytics/__tests__/providers/personalize/apis/record.test.ts index 8ba019684bb..7fe7a08aa41 100644 --- a/packages/analytics/__tests__/providers/personalize/apis/record.test.ts +++ b/packages/analytics/__tests__/providers/personalize/apis/record.test.ts @@ -55,7 +55,7 @@ describe('Analytics Personalize API: record', () => { mockResolveConfig.mockReturnValue(mockPersonalizeConfig); mockResolveCachedSession.mockReturnValue(mockCachedSession); mockResolveCredentials.mockReturnValue( - Promise.resolve(mockCredentialConfig) + Promise.resolve(mockCredentialConfig), ); mockGetEventBuffer.mockImplementation(() => mockEventBuffer); }); @@ -80,7 +80,7 @@ describe('Analytics Personalize API: record', () => { trackingId: mockPersonalizeConfig.trackingId, ...mockCachedSession, event: mockRecordInput, - }) + }), ); }); @@ -108,14 +108,14 @@ describe('Analytics Personalize API: record', () => { expect(mockUpdateCachedSession).toHaveBeenCalledWith( newSession.userId, mockCachedSession.sessionId, - mockCachedSession.userId + mockCachedSession.userId, ); expect(mockAppend).toHaveBeenCalledWith( expect.objectContaining({ trackingId: mockPersonalizeConfig.trackingId, ...newSession, event: updatedMockRecordInput, - }) + }), ); }); @@ -139,14 +139,14 @@ describe('Analytics Personalize API: record', () => { expect(mockUpdateCachedSession).toHaveBeenCalledWith( newSession.userId, mockCachedSession.sessionId, - mockCachedSession.userId + mockCachedSession.userId, ); expect(mockAppend).toHaveBeenCalledWith( expect.objectContaining({ trackingId: mockPersonalizeConfig.trackingId, ...newSession, event: mockRecordInput, - }) + }), ); }); @@ -165,7 +165,7 @@ describe('Analytics Personalize API: record', () => { ...mockCachedSession, event: updatedMockRecordInput, }, - mockEventBuffer + mockEventBuffer, ); expect(mockAppend).not.toHaveBeenCalled(); }); @@ -192,7 +192,7 @@ describe('Analytics Personalize API: record', () => { trackingId: mockPersonalizeConfig.trackingId, ...mockCachedSession, event: mockRecordInput, - }) + }), ); expect(mockGetLength).toHaveBeenCalledTimes(1); expect(mockFlushAll).toHaveBeenCalledTimes(1); @@ -206,7 +206,7 @@ describe('Analytics Personalize API: record', () => { await new Promise(process.nextTick); expect(loggerWarnSpy).toHaveBeenCalledWith( expect.any(String), - expect.any(Error) + expect.any(Error), ); }); diff --git a/packages/analytics/__tests__/providers/personalize/utils/cachedSession.test.ts b/packages/analytics/__tests__/providers/personalize/utils/cachedSession.test.ts index 10681b33c6e..0c7846ea5bd 100644 --- a/packages/analytics/__tests__/providers/personalize/utils/cachedSession.test.ts +++ b/packages/analytics/__tests__/providers/personalize/utils/cachedSession.test.ts @@ -62,13 +62,13 @@ describe('Analytics service provider Personalize utils: cachedSession', () => { 1, sessionIdCacheKey, expect.any(String), - expect.any(Object) + expect.any(Object), ); expect(mockCache.setItem).toHaveBeenNthCalledWith( 2, userIdCacheKey, 'newUserId', - expect.any(Object) + expect.any(Object), ); }); @@ -79,13 +79,13 @@ describe('Analytics service provider Personalize utils: cachedSession', () => { 1, sessionIdCacheKey, expect.any(String), - expect.any(Object) + expect.any(Object), ); expect(mockCache.setItem).toHaveBeenNthCalledWith( 2, userIdCacheKey, undefined, - expect.any(Object) + expect.any(Object), ); }); @@ -96,13 +96,13 @@ describe('Analytics service provider Personalize utils: cachedSession', () => { 1, sessionIdCacheKey, expect.any(String), - expect.any(Object) + expect.any(Object), ); expect(mockCache.setItem).toHaveBeenNthCalledWith( 2, userIdCacheKey, 'newUserId', - expect.any(Object) + expect.any(Object), ); }); @@ -113,7 +113,7 @@ describe('Analytics service provider Personalize utils: cachedSession', () => { 1, userIdCacheKey, 'newUserId', - expect.any(Object) + expect.any(Object), ); }); }); diff --git a/packages/analytics/__tests__/providers/personalize/utils/getEventBuffer.test.ts b/packages/analytics/__tests__/providers/personalize/utils/getEventBuffer.test.ts index cce4fc560cf..522a8e9af12 100644 --- a/packages/analytics/__tests__/providers/personalize/utils/getEventBuffer.test.ts +++ b/packages/analytics/__tests__/providers/personalize/utils/getEventBuffer.test.ts @@ -26,7 +26,7 @@ describe('Personalize Provider Util: getEventBuffer', () => { expect(mockEventBuffer).toHaveBeenCalledWith( { ...mockBufferConfig, bufferSize: mockBufferConfig.flushSize + 1 }, - expect.any(Function) + expect.any(Function), ); expect(testBuffer).toBeInstanceOf(EventBuffer); }); diff --git a/packages/analytics/__tests__/providers/pinpoint/apis/configureAutoTrack.test.ts b/packages/analytics/__tests__/providers/pinpoint/apis/configureAutoTrack.test.ts index 41c3b10c45f..62c38ac49d7 100644 --- a/packages/analytics/__tests__/providers/pinpoint/apis/configureAutoTrack.test.ts +++ b/packages/analytics/__tests__/providers/pinpoint/apis/configureAutoTrack.test.ts @@ -67,7 +67,7 @@ describe('Pinpoint API: configureAutoTrack', () => { expect(MockEventTracker).toHaveBeenCalledWith( expect.any(Function), - MOCK_INPUT.options + MOCK_INPUT.options, ); }); @@ -87,7 +87,7 @@ describe('Pinpoint API: configureAutoTrack', () => { expect(MockSessionTracker).toHaveBeenCalledWith( expect.any(Function), - testInput.options + testInput.options, ); }); @@ -107,7 +107,7 @@ describe('Pinpoint API: configureAutoTrack', () => { expect(MockPageViewTracker).toHaveBeenCalledWith( expect.any(Function), - testInput.options + testInput.options, ); }); @@ -121,13 +121,13 @@ describe('Pinpoint API: configureAutoTrack', () => { configureAutoTrack(MOCK_INPUT); expect(MockEventTracker).toHaveBeenCalledWith( expect.any(Function), - MOCK_INPUT.options + MOCK_INPUT.options, ); // Reconfigure the tracker configureAutoTrack(MOCK_INPUT); expect( - MockEventTracker.mock.instances[0].configure + MockEventTracker.mock.instances[0].configure, ).toHaveBeenCalledTimes(1); }); }); @@ -147,13 +147,13 @@ describe('Pinpoint API: configureAutoTrack', () => { configureAutoTrack(MOCK_INPUT); expect(MockEventTracker).toHaveBeenCalledWith( expect.any(Function), - MOCK_INPUT.options + MOCK_INPUT.options, ); // Disable the tracker configureAutoTrack(testInput); expect(MockEventTracker.mock.instances[0].cleanup).toHaveBeenCalledTimes( - 1 + 1, ); }); }); diff --git a/packages/analytics/__tests__/providers/pinpoint/apis/flushEvents.test.ts b/packages/analytics/__tests__/providers/pinpoint/apis/flushEvents.test.ts index b28df4e618d..b2ec6b6c5a2 100644 --- a/packages/analytics/__tests__/providers/pinpoint/apis/flushEvents.test.ts +++ b/packages/analytics/__tests__/providers/pinpoint/apis/flushEvents.test.ts @@ -27,7 +27,7 @@ describe('Pinpoint API: flushEvents', () => { Promise.resolve({ credentials, identityId, - }) + }), ); }); @@ -62,7 +62,7 @@ describe('Pinpoint API: flushEvents', () => { expect(mockPinpointFlushEvents).not.toHaveBeenCalled(); expect(loggerWarnSpy).toHaveBeenCalledWith( expect.any(String), - expect.any(Error) + expect.any(Error), ); }); }); diff --git a/packages/analytics/__tests__/providers/pinpoint/apis/record.test.ts b/packages/analytics/__tests__/providers/pinpoint/apis/record.test.ts index 7ea5fdd0d5b..7f14af730ee 100644 --- a/packages/analytics/__tests__/providers/pinpoint/apis/record.test.ts +++ b/packages/analytics/__tests__/providers/pinpoint/apis/record.test.ts @@ -88,7 +88,7 @@ describe('Pinpoint API: record', () => { expect(mockPinpointRecord).not.toHaveBeenCalled(); expect(loggerWarnSpy).toHaveBeenCalledWith( expect.any(String), - expect.any(Error) + expect.any(Error), ); }); @@ -123,7 +123,7 @@ describe('Pinpoint API: record', () => { 'analytics', { event: 'record', data: event, message: 'Recording Analytics event' }, 'Analytics', - expect.anything() + expect.anything(), ); }); }); diff --git a/packages/analytics/__tests__/utils/eventBuffer/EventBuffer.test.ts b/packages/analytics/__tests__/utils/eventBuffer/EventBuffer.test.ts index 04104f50362..cd13c5f9be1 100644 --- a/packages/analytics/__tests__/utils/eventBuffer/EventBuffer.test.ts +++ b/packages/analytics/__tests__/utils/eventBuffer/EventBuffer.test.ts @@ -20,7 +20,7 @@ describe('EventBuffer', () => { () => events => { result.push(...events); return Promise.resolve([]); - } + }, ); const testEvents: TestEvent[] = [ @@ -53,7 +53,7 @@ describe('EventBuffer', () => { () => events => { results.push(events.length); return Promise.resolve(events); - } + }, ); testEvents.forEach(x => eventBuffer.append(x)); @@ -61,7 +61,7 @@ describe('EventBuffer', () => { eventBuffer.release(); expect(results.filter(x => x === testEvents.length).length).toEqual(1); expect(results.filter(x => x !== testEvents.length).length).toEqual( - results.length - 1 + results.length - 1, ); done(); }, 100); @@ -85,7 +85,7 @@ describe('EventBuffer', () => { () => events => { results.push(...events); return Promise.resolve([]); - } + }, ); testEvents.forEach(x => eventBuffer.append(x)); @@ -97,7 +97,7 @@ describe('EventBuffer', () => { setTimeout(() => { expect(results.length).toEqual(testEvents.length); expect(results.filter(x => x.timestamp > results.length).length).toEqual( - 0 + 0, ); done(); }, 150); diff --git a/packages/api-graphql/__tests__/AWSAppSyncRealTimeProvider.test.ts b/packages/api-graphql/__tests__/AWSAppSyncRealTimeProvider.test.ts index 0675cc0fcaa..29563594a30 100644 --- a/packages/api-graphql/__tests__/AWSAppSyncRealTimeProvider.test.ts +++ b/packages/api-graphql/__tests__/AWSAppSyncRealTimeProvider.test.ts @@ -16,7 +16,7 @@ import { AWSAppSyncRealTimeProvider } from '../src/Providers/AWSAppSyncRealTimeP // Mock all calls to signRequest jest.mock('@aws-amplify/core/internals/aws-client-utils', () => { const original = jest.requireActual( - '@aws-amplify/core/internals/aws-client-utils' + '@aws-amplify/core/internals/aws-client-utils', ); return { ...original, @@ -68,7 +68,7 @@ describe('AWSAppSyncRealTimeProvider', () => { test('Custom domain returns `true`', () => { const provider = new AWSAppSyncRealTimeProvider(); const result = (provider as any).isCustomDomain( - 'https://unit-test.testurl.com/graphql' + 'https://unit-test.testurl.com/graphql', ); expect(result).toBe(true); }); @@ -76,7 +76,7 @@ describe('AWSAppSyncRealTimeProvider', () => { test('Non-custom domain returns `false`', () => { const provider = new AWSAppSyncRealTimeProvider(); const result = (provider as any).isCustomDomain( - 'https://12345678901234567890123456.appsync-api.us-west-2.amazonaws.com/graphql' + 'https://12345678901234567890123456.appsync-api.us-west-2.amazonaws.com/graphql', ); expect(result).toBe(false); }); @@ -84,7 +84,7 @@ describe('AWSAppSyncRealTimeProvider', () => { test('Non-custom domain in the amazonaws.com.cn subdomain space returns `false`', () => { const provider = new AWSAppSyncRealTimeProvider(); const result = (provider as any).isCustomDomain( - 'https://12345678901234567890123456.appsync-api.cn-north-1.amazonaws.com.cn/graphql' + 'https://12345678901234567890123456.appsync-api.cn-north-1.amazonaws.com.cn/graphql', ); expect(result).toBe(false); }); @@ -108,7 +108,7 @@ describe('AWSAppSyncRealTimeProvider', () => { let fakeWebSocketInterface: FakeWebSocketInterface; const loggerSpy: jest.SpyInstance = jest.spyOn( ConsoleLogger.prototype, - '_log' + '_log', ); let provider: AWSAppSyncRealTimeProvider; @@ -177,7 +177,7 @@ describe('AWSAppSyncRealTimeProvider', () => { payload: { connectionTimeoutMs: 100 }, id: fakeWebSocketInterface?.webSocket.subscriptionId, }), - }) + }), ); await fakeWebSocketInterface?.waitUntilConnectionStateIn([ @@ -214,11 +214,11 @@ describe('AWSAppSyncRealTimeProvider', () => { provider.subscribe({}).subscribe({ error(err) { expect(err.errors[0].message).toEqual( - 'Subscribe only available for AWS AppSync endpoint' + 'Subscribe only available for AWS AppSync endpoint', ); mockError(); }, - }) + }), ); expect(mockError).toHaveBeenCalled(); @@ -246,7 +246,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(newSocketSpy).toHaveBeenNthCalledWith( 1, 'ws://localhost:8080/realtime?header=&payload=e30=', - 'graphql-ws' + 'graphql-ws', ); }); @@ -272,7 +272,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(newSocketSpy).toHaveBeenNthCalledWith( 1, 'wss://localhost:8080/realtime?header=&payload=e30=', - 'graphql-ws' + 'graphql-ws', ); }); @@ -299,7 +299,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(newSocketSpy).toHaveBeenNthCalledWith( 1, 'wss://testaccounturl123456789123.appsync-realtime-api.us-east-1.amazonaws.com/graphql?header=&payload=e30=', - 'graphql-ws' + 'graphql-ws', ); }); @@ -314,7 +314,7 @@ describe('AWSAppSyncRealTimeProvider', () => { await fakeWebSocketInterface?.triggerError(); expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'WebSocket connection error' + 'WebSocket connection error', ); }); @@ -339,7 +339,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect.stringContaining('error on bound '), expect.objectContaining({ message: expect.stringMatching('Connection handshake error'), - }) + }), ); await fakeWebSocketInterface?.waitUntilConnectionStateIn([ CS.Connecting, @@ -421,7 +421,7 @@ describe('AWSAppSyncRealTimeProvider', () => { // When the socket throws an error during handshake expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'WebSocket error {"isTrusted":false}' + 'WebSocket error {"isTrusted":false}', ); }); @@ -447,7 +447,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect.stringContaining('error on bound '), expect.objectContaining({ message: expect.stringMatching('{"isTrusted":false}'), - }) + }), ); }); @@ -546,7 +546,7 @@ describe('AWSAppSyncRealTimeProvider', () => { }); expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'Connection failed: {"data":{}}' + 'Connection failed: {"data":{}}', ); await fakeWebSocketInterface?.waitUntilConnectionStateIn([ CS.Connecting, @@ -558,7 +558,7 @@ describe('AWSAppSyncRealTimeProvider', () => { const socketCloseSpy = jest.spyOn( fakeWebSocketInterface.webSocket, - 'close' + 'close', ); fakeWebSocketInterface.webSocket.readyState = WebSocket.OPEN; @@ -569,7 +569,7 @@ describe('AWSAppSyncRealTimeProvider', () => { observer.subscribe({ error: e => { expect(e.errors[0].message).toEqual( - 'Connection failed: Non-retriable Test' + 'Connection failed: Non-retriable Test', ); }, }); @@ -589,7 +589,7 @@ describe('AWSAppSyncRealTimeProvider', () => { }, ], }, - }) + }), ); // Watching for raised exception to be caught and logged @@ -598,7 +598,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect.stringContaining('error on bound '), expect.objectContaining({ message: expect.stringMatching('Non-retriable Test'), - }) + }), ); expect(socketCloseSpy).toHaveBeenNthCalledWith(1, 3001); @@ -619,7 +619,7 @@ describe('AWSAppSyncRealTimeProvider', () => { await fakeWebSocketInterface?.triggerError(); expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'Disconnect error: Connection closed' + 'Disconnect error: Connection closed', ); }); @@ -650,7 +650,7 @@ describe('AWSAppSyncRealTimeProvider', () => { }, ], }, - }) + }), ); await fakeWebSocketInterface?.resetWebsocket(); }; @@ -665,7 +665,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect.stringContaining('error on bound '), expect.objectContaining({ message: expect.stringMatching('Retriable Test'), - }) + }), ); await fakeWebSocketInterface?.waitUntilConnectionStateIn([ @@ -674,7 +674,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'Connection failed: Retriable Test' + 'Connection failed: Retriable Test', ); }); @@ -700,7 +700,7 @@ describe('AWSAppSyncRealTimeProvider', () => { await fakeWebSocketInterface?.startAckMessage(); await fakeWebSocketInterface?.keepAlive(); - } + }, ); await fakeWebSocketInterface?.waitUntilConnectionStateIn([ @@ -713,12 +713,12 @@ describe('AWSAppSyncRealTimeProvider', () => { ]); expect(fakeWebSocketInterface?.observedConnectionStates).toContain( - CS.ConnectedPendingKeepAlive + CS.ConnectedPendingKeepAlive, ); expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'Disconnect error: Timeout disconnect' + 'Disconnect error: Timeout disconnect', ); }); @@ -884,7 +884,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', 'timeoutStartSubscription', - expect.anything() + expect.anything(), ); }); }); @@ -910,7 +910,7 @@ describe('AWSAppSyncRealTimeProvider', () => { // Wait until the socket is automatically disconnected await expect( fakeWebSocketInterface?.hubConnectionListener - ?.currentConnectionState + ?.currentConnectionState, ).toBe(CS.Connecting); // Watching for raised exception to be caught and logged @@ -919,9 +919,9 @@ describe('AWSAppSyncRealTimeProvider', () => { expect.stringContaining('error on bound '), expect.objectContaining({ message: expect.stringMatching( - 'Connection timeout: ack from AWSAppSyncRealTime was not received after' + 'Connection timeout: ack from AWSAppSyncRealTime was not received after', ), - }) + }), ); }); }); @@ -954,9 +954,9 @@ describe('AWSAppSyncRealTimeProvider', () => { expect.stringContaining('error on bound '), expect.objectContaining({ message: expect.stringMatching( - 'Connection timeout: ack from AWSAppSyncRealTime was not received after' + 'Connection timeout: ack from AWSAppSyncRealTime was not received after', ), - }) + }), ); }); }); @@ -977,7 +977,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'Authenticating with "apiKey"' + 'Authenticating with "apiKey"', ); }); @@ -995,7 +995,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'Authenticating with "iam"' + 'Authenticating with "iam"', ); }); @@ -1013,7 +1013,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'Authenticating with "oidc"' + 'Authenticating with "oidc"', ); }); @@ -1030,7 +1030,7 @@ describe('AWSAppSyncRealTimeProvider', () => { await fakeWebSocketInterface?.readyForUse; expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'Authenticating with "oidc"' + 'Authenticating with "oidc"', ); }); @@ -1051,7 +1051,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'Authenticating with "none"' + 'Authenticating with "none"', ); }); @@ -1079,7 +1079,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'Authenticating with "userPool"' + 'Authenticating with "userPool"', ); }); @@ -1100,7 +1100,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(loggerSpy).toBeCalledWith( 'DEBUG', - 'Authenticating with "none"' + 'Authenticating with "none"', ); }); @@ -1116,7 +1116,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect.objectContaining({ queryString: '', url: 'ws://localhost:8080', - }) + }), ); return { Authorization: 'test' }; }, @@ -1127,7 +1127,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'Authenticating with "none"' + 'Authenticating with "none"', ); }); @@ -1149,7 +1149,7 @@ describe('AWSAppSyncRealTimeProvider', () => { expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', - 'AppSync Realtime subscription init error: Error: No auth token specified' + 'AppSync Realtime subscription init error: Error: No auth token specified', ); }); }); diff --git a/packages/api-graphql/__tests__/helpers.ts b/packages/api-graphql/__tests__/helpers.ts index 08a8261546d..ac26232dd90 100644 --- a/packages/api-graphql/__tests__/helpers.ts +++ b/packages/api-graphql/__tests__/helpers.ts @@ -200,7 +200,7 @@ export class FakeWebSocketInterface { type: constants.MESSAGE_TYPES.GQL_CONNECTION_ACK, payload: payload, }), - }) + }), ); } @@ -214,7 +214,7 @@ export class FakeWebSocketInterface { type: constants.MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE, payload: payload, }), - }) + }), ); } @@ -226,7 +226,7 @@ export class FakeWebSocketInterface { payload: payload, id: this.webSocket.subscriptionId, }), - }) + }), ); } @@ -240,7 +240,7 @@ export class FakeWebSocketInterface { ...data, id: this.webSocket.subscriptionId, }), - }) + }), ); } @@ -288,7 +288,7 @@ export class FakeWebSocketInterface { */ async waitUntilConnectionStateIn(connectionStates: CS[]) { return this.hubConnectionListener.waitUntilConnectionStateIn( - connectionStates + connectionStates, ); } } @@ -318,12 +318,12 @@ class FakeWebSocket implements WebSocket { addEventListener( type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, - options?: boolean | AddEventListenerOptions + options?: boolean | AddEventListenerOptions, ): void; addEventListener( type: string, listener: EventListenerOrEventListenerObject, - options?: boolean | AddEventListenerOptions + options?: boolean | AddEventListenerOptions, ): void; addEventListener(type: unknown, listener: unknown, options?: unknown): void { throw new Error('Method not implemented addEventListener.'); @@ -331,17 +331,17 @@ class FakeWebSocket implements WebSocket { removeEventListener( type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, - options?: boolean | EventListenerOptions + options?: boolean | EventListenerOptions, ): void; removeEventListener( type: string, listener: EventListenerOrEventListenerObject, - options?: boolean | EventListenerOptions + options?: boolean | EventListenerOptions, ): void; removeEventListener( type: unknown, listener: unknown, - options?: unknown + options?: unknown, ): void { throw new Error('Method not implemented removeEventListener.'); } @@ -361,7 +361,7 @@ class FakeWebSocket implements WebSocket { export async function replaceConstant( name: string, replacementValue: any, - testFn: () => Promise + testFn: () => Promise, ) { const initialValue = constants[name]; Object.defineProperty(constants, name, { diff --git a/packages/api-graphql/__tests__/internals/generateClient.test.ts b/packages/api-graphql/__tests__/internals/generateClient.test.ts index b206373b526..94c375768df 100644 --- a/packages/api-graphql/__tests__/internals/generateClient.test.ts +++ b/packages/api-graphql/__tests__/internals/generateClient.test.ts @@ -185,7 +185,7 @@ describe('generateClient', () => { const client = generateClient({ amplify: Amplify }); expect(() => { - client.enums.Status.values() + client.enums.Status.values(); }).toThrow( 'Client could not be generated. This is likely due to `Amplify.configure()` not being called prior to `generateClient()` or because the configuration passed to `Amplify.configure()` is missing GraphQL provider configuration.', ); diff --git a/packages/api-graphql/__tests__/server/generateClient.test.ts b/packages/api-graphql/__tests__/server/generateClient.test.ts index 3375f5913f4..9ba0e1a5d3d 100644 --- a/packages/api-graphql/__tests__/server/generateClient.test.ts +++ b/packages/api-graphql/__tests__/server/generateClient.test.ts @@ -27,7 +27,7 @@ jest.mock('../../src/internals/server', () => ({ graphql: mockGraphQLMethod, cancel: jest.fn(), isCancelError: jest.fn(), - }) + }), ), })); @@ -106,13 +106,13 @@ describe('generateClient server edition', () => { client.graphql( mockContextSpec, testGraphQLOptions, - testAdditionalHeaders + testAdditionalHeaders, ); expect(mockGraphQLMethod).toHaveBeenCalledTimes(1); expect(mockGraphQLMethod).toHaveBeenCalledWith( testGraphQLOptions, - testAdditionalHeaders + testAdditionalHeaders, ); }); }); diff --git a/packages/api-graphql/__tests__/utils/expects.ts b/packages/api-graphql/__tests__/utils/expects.ts index d36b30cfdd1..a5416dbdb76 100644 --- a/packages/api-graphql/__tests__/utils/expects.ts +++ b/packages/api-graphql/__tests__/utils/expects.ts @@ -11,7 +11,7 @@ import { CustomHeaders } from '@aws-amplify/data-schema-types'; export function expectMutation( spy: jest.SpyInstance, opName: string, - item: Record + item: Record, ) { expect(spy).toHaveBeenCalledWith({ abortController: expect.any(AbortController), @@ -20,7 +20,7 @@ export function expectMutation( headers: expect.objectContaining({ 'X-Api-Key': 'FAKE-KEY' }), body: expect.objectContaining({ query: expect.stringContaining( - `${opName}(input: $input, condition: $condition)` + `${opName}(input: $input, condition: $condition)`, ), variables: expect.objectContaining({ input: expect.objectContaining(item), @@ -41,14 +41,15 @@ export function expectMutation( export function expectGet( spy: jest.SpyInstance, opName: string, - item: Record + item: Record, ) { expect(spy).toHaveBeenCalledWith( expect.objectContaining({ Auth: expect.any(Object), configure: expect.any(Function), getConfig: expect.any(Function), - }), { + }), + { abortController: expect.any(AbortController), url: new URL('https://localhost/graphql'), options: expect.objectContaining({ @@ -58,7 +59,7 @@ export function expectGet( variables: expect.objectContaining(item), }), }), - } + }, ); } @@ -73,7 +74,7 @@ export function expectGet( export function expectList( spy: jest.SpyInstance, opName: string, - item: Record + item: Record, ) { expect(spy).toHaveBeenCalledWith({ abortController: expect.any(AbortController), @@ -82,7 +83,7 @@ export function expectList( headers: expect.objectContaining({ 'X-Api-Key': 'FAKE-KEY' }), body: expect.objectContaining({ query: expect.stringContaining( - `${opName}(filter: $filter, limit: $limit, nextToken: $nextToken)` + `${opName}(filter: $filter, limit: $limit, nextToken: $nextToken)`, ), variables: expect.objectContaining(item), }), @@ -101,7 +102,7 @@ export function expectList( export function expectSub( spy: jest.SpyInstance, opName: string, - item: Record + item: Record, ) { expect(spy).toHaveBeenCalledWith( expect.objectContaining({ @@ -115,7 +116,7 @@ export function expectSub( { action: '1', category: 'api', - } + }, ); } @@ -133,7 +134,7 @@ export function expectSubWithHeaders( spy: jest.SpyInstance, opName: string, item: Record, - headers?: CustomHeaders + headers?: CustomHeaders, ) { expect(spy).toHaveBeenCalledWith( expect.objectContaining({ @@ -148,7 +149,7 @@ export function expectSubWithHeaders( { action: '1', category: 'api', - } + }, ); } @@ -164,7 +165,7 @@ export function expectSubWithHeaders( export function expectSubWithHeadersFn( spy: jest.SpyInstance, opName: string, - item: Record + item: Record, ) { expect(spy).toHaveBeenCalledWith( expect.objectContaining({ @@ -179,7 +180,7 @@ export function expectSubWithHeadersFn( { action: '1', category: 'api', - } + }, ); } @@ -197,7 +198,7 @@ export function expectSubWithlibraryConfigHeaders( spy: jest.SpyInstance, opName: string, item: Record, - headers?: CustomHeaders + headers?: CustomHeaders, ) { expect(spy).toHaveBeenCalledWith( expect.objectContaining({ @@ -214,6 +215,6 @@ export function expectSubWithlibraryConfigHeaders( { action: '1', category: 'api', - } + }, ); } diff --git a/packages/api-graphql/__tests__/v6-test.ts b/packages/api-graphql/__tests__/v6-test.ts index 568d7e08fa5..5c0db3a9138 100644 --- a/packages/api-graphql/__tests__/v6-test.ts +++ b/packages/api-graphql/__tests__/v6-test.ts @@ -335,7 +335,7 @@ describe('client', () => { next(message: GraphqlSubscriptionMessage) { expectSub(spy, 'onCreateThread', graphqlVariables); expect(message.data?.onCreateThread).toEqual( - graphqlMessage.data.onCreateThread + graphqlMessage.data.onCreateThread, ); done(); }, @@ -866,7 +866,7 @@ describe('client', () => { next(message: any) { expectSub(spy, 'onCreateThread', graphqlVariables); expect(message.data.onCreateThread).toEqual( - graphqlMessage.data.onCreateThread + graphqlMessage.data.onCreateThread, ); done(); }, @@ -1135,7 +1135,7 @@ describe('client', () => { next(message) { expectSub(spy, 'onCreateThread', graphqlVariables); expect(message.data?.onCreateThread).toEqual( - graphqlMessage.data.onCreateThread + graphqlMessage.data.onCreateThread, ); done(); }, diff --git a/packages/api-graphql/src/GraphQLAPI.ts b/packages/api-graphql/src/GraphQLAPI.ts index 31699d6981b..a0b015f031c 100644 --- a/packages/api-graphql/src/GraphQLAPI.ts +++ b/packages/api-graphql/src/GraphQLAPI.ts @@ -10,7 +10,7 @@ import { Observable } from 'rxjs'; export const graphqlOperation = ( query: any, variables = {}, - authToken?: string + authToken?: string, ) => ({ query, variables, @@ -35,7 +35,7 @@ export class GraphQLAPIClass extends InternalGraphQLAPIClass { graphql( amplify: AmplifyClassV6 | (() => Promise), options: GraphQLOptions, - additionalHeaders?: CustomHeaders + additionalHeaders?: CustomHeaders, ): Observable> | Promise> { return super.graphql(amplify, options, additionalHeaders, { category: Category.API, diff --git a/packages/api-graphql/src/Providers/AWSAppSyncRealTimeProvider/index.ts b/packages/api-graphql/src/Providers/AWSAppSyncRealTimeProvider/index.ts index f4d5fdb8a4f..6c16420f365 100644 --- a/packages/api-graphql/src/Providers/AWSAppSyncRealTimeProvider/index.ts +++ b/packages/api-graphql/src/Providers/AWSAppSyncRealTimeProvider/index.ts @@ -158,7 +158,7 @@ export class AWSAppSyncRealTimeProvider { ) { this.reconnectionMonitor.record(ReconnectEvent.HALT_RECONNECT); } - } + }, ); } @@ -191,7 +191,7 @@ export class AWSAppSyncRealTimeProvider { subscribe( options?: AWSAppSyncRealTimeProviderOptions, - customUserAgentDetails?: CustomUserAgentDetails + customUserAgentDetails?: CustomUserAgentDetails, ): Observable> { const { appSyncGraphqlEndpoint, @@ -211,7 +211,7 @@ export class AWSAppSyncRealTimeProvider { errors: [ { ...new GraphQLError( - `Subscribe only available for AWS AppSync endpoint` + `Subscribe only available for AWS AppSync endpoint`, ), }, ], @@ -242,7 +242,7 @@ export class AWSAppSyncRealTimeProvider { customUserAgentDetails, }).catch(err => { logger.debug( - `${CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}` + `${CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`, ); this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED); @@ -428,13 +428,13 @@ export class AWSAppSyncRealTimeProvider { private _logStartSubscriptionError( subscriptionId: string, observer: PubSubContentObserver, - err: { message?: string } + err: { message?: string }, ) { logger.debug({ err }); const message = String(err.message ?? ''); // Resolving to give the state observer time to propogate the update Promise.resolve( - this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED) + this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED), ); // Capture the error only when the network didn't cause disruption @@ -447,7 +447,7 @@ export class AWSAppSyncRealTimeProvider { errors: [ { ...new GraphQLError( - `${CONTROL_MSG.CONNECTION_FAILED}: ${message}` + `${CONTROL_MSG.CONNECTION_FAILED}: ${message}`, ), }, ], @@ -558,7 +558,7 @@ export class AWSAppSyncRealTimeProvider { return; } logger.debug( - `subscription message from AWS AppSync RealTime: ${message.data}` + `subscription message from AWS AppSync RealTime: ${message.data}`, ); const { id = '', @@ -587,7 +587,7 @@ export class AWSAppSyncRealTimeProvider { if (type === MESSAGE_TYPES.GQL_START_ACK) { logger.debug( - `subscription ready for ${JSON.stringify({ query, variables })}` + `subscription ready for ${JSON.stringify({ query, variables })}`, ); if (typeof subscriptionReadyCallback === 'function') { subscriptionReadyCallback(); @@ -611,7 +611,7 @@ export class AWSAppSyncRealTimeProvider { }); } this.connectionStateMonitor.record( - CONNECTION_CHANGE.CONNECTION_ESTABLISHED + CONNECTION_CHANGE.CONNECTION_ESTABLISHED, ); return; @@ -623,7 +623,7 @@ export class AWSAppSyncRealTimeProvider { clearTimeout(this.keepAliveAlertTimeoutId); this.keepAliveTimeoutId = setTimeout( () => this._errorDisconnect(CONTROL_MSG.TIMEOUT_DISCONNECT), - this.keepAliveTimeout + this.keepAliveTimeout, ); this.keepAliveAlertTimeoutId = setTimeout(() => { this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE_MISSED); @@ -646,14 +646,14 @@ export class AWSAppSyncRealTimeProvider { }); logger.debug( - `${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}` + `${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`, ); observer.error({ errors: [ { ...new GraphQLError( - `${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}` + `${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`, ), }, ], @@ -697,7 +697,7 @@ export class AWSAppSyncRealTimeProvider { this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED); logger.debug( 'timeoutStartSubscription', - JSON.stringify({ query, variables }) + JSON.stringify({ query, variables }), ); } } @@ -785,7 +785,7 @@ export class AWSAppSyncRealTimeProvider { await jitteredExponentialRetry( this._initializeHandshake.bind(this), [awsRealTimeUrl], - MAX_DELAY_MS + MAX_DELAY_MS, ); } @@ -827,7 +827,7 @@ export class AWSAppSyncRealTimeProvider { return; } logger.debug( - `subscription message from AWS AppSyncRealTime: ${message.data} ` + `subscription message from AWS AppSyncRealTime: ${message.data} `, ); const data = JSON.parse(message.data) as ParsedMessagePayload; const { @@ -874,12 +874,12 @@ export class AWSAppSyncRealTimeProvider { const checkAckOk = (ackOk: boolean) => { if (!ackOk) { this.connectionStateMonitor.record( - CONNECTION_CHANGE.CONNECTION_FAILED + CONNECTION_CHANGE.CONNECTION_FAILED, ); rej( new Error( - `Connection timeout: ack from AWSAppSyncRealTime was not received after ${CONNECTION_INIT_TIMEOUT} ms` - ) + `Connection timeout: ack from AWSAppSyncRealTime was not received after ${CONNECTION_INIT_TIMEOUT} ms`, + ), ); } }; @@ -1010,7 +1010,7 @@ export class AWSAppSyncRealTimeProvider { credentials: creds!, signingRegion: endpointInfo.region!, signingService: endpointInfo.service, - } + }, ); return signed_params.headers; } diff --git a/packages/api-graphql/src/internals/APIClient.ts b/packages/api-graphql/src/internals/APIClient.ts index 2f84ddcbbbd..cc8561b9ed9 100644 --- a/packages/api-graphql/src/internals/APIClient.ts +++ b/packages/api-graphql/src/internals/APIClient.ts @@ -611,10 +611,10 @@ export function generateGraphQLDocument( return acc; }, {}, - ) + ) : { [primaryKeyFieldName]: `${fields[primaryKeyFieldName].type}!`, - }); + }); graphQLSelectionSet ?? (graphQLSelectionSet = selectionSetFields); case 'LIST': graphQLArguments ?? @@ -658,13 +658,13 @@ export function generateGraphQLDocument( graphQLArguments ? `(${Object.entries(graphQLArguments).map( ([fieldName, type]) => `\$${fieldName}: ${type}`, - )})` + )})` : '' } { ${graphQLFieldName}${ graphQLArguments ? `(${Object.keys(graphQLArguments).map( fieldName => `${fieldName}: \$${fieldName}`, - )})` + )})` : '' } { ${graphQLSelectionSet} } }`; @@ -714,7 +714,7 @@ export function buildGraphQLVariables( return !isReadOnly; }), - ) + ) : {}, }; break; @@ -730,7 +730,7 @@ export function buildGraphQLVariables( return acc; }, {}, - ) + ) : { [primaryKeyFieldName]: arg[primaryKeyFieldName] }; } diff --git a/packages/api-graphql/src/internals/InternalGraphQLAPI.ts b/packages/api-graphql/src/internals/InternalGraphQLAPI.ts index 67d8e4a4da4..63735c64ef1 100644 --- a/packages/api-graphql/src/internals/InternalGraphQLAPI.ts +++ b/packages/api-graphql/src/internals/InternalGraphQLAPI.ts @@ -306,7 +306,7 @@ export class InternalGraphQLAPIClass { amplify, authMode!, additionalCustomHeaders, - ) + ) : {})) || {}), // Custom headers included in Amplify configuration options: diff --git a/packages/api-graphql/src/internals/operations/get.ts b/packages/api-graphql/src/internals/operations/get.ts index 71b2d0c1e6c..74b2512c4c6 100644 --- a/packages/api-graphql/src/internals/operations/get.ts +++ b/packages/api-graphql/src/internals/operations/get.ts @@ -30,12 +30,12 @@ export function getFactory( modelIntrospection: ModelIntrospectionSchema, model: SchemaModel, operation: ModelOperation, - useContext = false + useContext = false, ) { const getWithContext = async ( contextSpec: AmplifyServer.ContextSpec & GraphQLOptionsV6, arg?: any, - options?: any + options?: any, ) => { return _get( client, @@ -44,7 +44,7 @@ export function getFactory( arg, options, operation, - contextSpec + contextSpec, ); }; @@ -62,7 +62,7 @@ async function _get( arg: QueryArgs, options: AuthModeParams & ListArgs, operation: ModelOperation, - context?: AmplifyServer.ContextSpec + context?: AmplifyServer.ContextSpec, ) { const { name } = model; @@ -70,13 +70,13 @@ async function _get( modelIntrospection.models, name, operation, - options + options, ); const variables = buildGraphQLVariables( model, operation, arg, - modelIntrospection + modelIntrospection, ); try { @@ -92,16 +92,16 @@ async function _get( query, variables, }, - headers - )) as GraphQLResult) + headers, + )) as GraphQLResult) : ((await (client as V6Client>).graphql( { ...auth, query, variables, }, - headers - )) as GraphQLResult); + headers, + )) as GraphQLResult); // flatten response if (data) { @@ -119,7 +119,7 @@ async function _get( modelIntrospection, auth.authMode, auth.authToken, - !!context + !!context, ); return { data: initialized, extensions }; diff --git a/packages/api-graphql/src/internals/operations/list.ts b/packages/api-graphql/src/internals/operations/list.ts index 4dad05e71ad..4dab67f9883 100644 --- a/packages/api-graphql/src/internals/operations/list.ts +++ b/packages/api-graphql/src/internals/operations/list.ts @@ -26,11 +26,11 @@ export function listFactory( client: ClientWithModels, modelIntrospection: ModelIntrospectionSchema, model: SchemaModel, - context = false + context = false, ) { const listWithContext = async ( contextSpec: AmplifyServer.ContextSpec, - args?: ListArgs + args?: ListArgs, ) => { return _list(client, modelIntrospection, model, args, contextSpec); }; @@ -47,7 +47,7 @@ async function _list( modelIntrospection: ModelIntrospectionSchema, model: SchemaModel, args?: ListArgs & AuthModeParams, - contextSpec?: AmplifyServer.ContextSpec + contextSpec?: AmplifyServer.ContextSpec, ) { const { name } = model; @@ -55,13 +55,13 @@ async function _list( modelIntrospection.models, name, 'LIST', - args + args, ); const variables = buildGraphQLVariables( model, 'LIST', args, - modelIntrospection + modelIntrospection, ); try { @@ -77,16 +77,16 @@ async function _list( query, variables, }, - headers - )) as GraphQLResult) + headers, + )) as GraphQLResult) : ((await (client as V6Client>).graphql( { ...auth, query, variables, }, - headers - )) as GraphQLResult); + headers, + )) as GraphQLResult); // flatten response if (data !== undefined) { @@ -110,7 +110,7 @@ async function _list( modelIntrospection, auth.authMode, auth.authToken, - !!contextSpec + !!contextSpec, ); return { diff --git a/packages/api-graphql/src/internals/operations/subscription.ts b/packages/api-graphql/src/internals/operations/subscription.ts index 912eb5caa4a..4ff6655b19f 100644 --- a/packages/api-graphql/src/internals/operations/subscription.ts +++ b/packages/api-graphql/src/internals/operations/subscription.ts @@ -20,7 +20,7 @@ export function subscriptionFactory( client: any, modelIntrospection: ModelIntrospectionSchema, model: SchemaModel, - operation: ModelOperation + operation: ModelOperation, ) { const { name } = model as any; @@ -28,13 +28,13 @@ export function subscriptionFactory( const query = generateGraphQLDocument( modelIntrospection.models, name, - operation + operation, ); const variables = buildGraphQLVariables( model, operation, args, - modelIntrospection + modelIntrospection, ); const auth = authModeParams(client, args); @@ -47,7 +47,7 @@ export function subscriptionFactory( query, variables, }, - headers + headers, ) as GraphqlSubscriptionResult; return observable.pipe( @@ -60,10 +60,10 @@ export function subscriptionFactory( [data], modelIntrospection, auth.authMode, - auth.authToken + auth.authToken, ); return initialized; - }) + }), ); }; diff --git a/packages/api-graphql/src/internals/server/generateClientWithAmplifyInstance.ts b/packages/api-graphql/src/internals/server/generateClientWithAmplifyInstance.ts index e578a925d68..4c0d41799cc 100644 --- a/packages/api-graphql/src/internals/server/generateClientWithAmplifyInstance.ts +++ b/packages/api-graphql/src/internals/server/generateClientWithAmplifyInstance.ts @@ -30,7 +30,7 @@ export function generateClientWithAmplifyInstance< | V6ClientSSRRequest | V6ClientSSRCookies = V6ClientSSRCookies, >( - params: ServerClientGenerationParams & CommonPublicClientOptions + params: ServerClientGenerationParams & CommonPublicClientOptions, ): ClientType { const client = { [__amplify]: params.amplify, diff --git a/packages/api-graphql/src/internals/v6.ts b/packages/api-graphql/src/internals/v6.ts index 337758e4451..950fc1d513d 100644 --- a/packages/api-graphql/src/internals/v6.ts +++ b/packages/api-graphql/src/internals/v6.ts @@ -101,12 +101,12 @@ export function graphql< >( this: V6Client, options: GraphQLOptionsV6, - additionalHeaders?: CustomHeaders + additionalHeaders?: CustomHeaders, ): GraphQLResponseV6 { - // inject client-level auth + // inject client-level auth options.authMode = options.authMode || this[__authMode]; options.authToken = options.authToken || this[__authToken]; - + /** * The correctness of these typings depends on correct string branding or overrides. * Neither of these can actually be validated at runtime. Hence, we don't perform @@ -115,7 +115,7 @@ export function graphql< const result = GraphQLAPI.graphql( this[__amplify], options, - additionalHeaders + additionalHeaders, ); return result as any; } @@ -128,7 +128,7 @@ export function graphql< export function cancel( this: V6Client, promise: Promise, - message?: string + message?: string, ): boolean { return GraphQLAPI.cancel(promise, message); } diff --git a/packages/api-graphql/src/server/generateClient.ts b/packages/api-graphql/src/server/generateClient.ts index ede4af9baef..6e35a0e96ba 100644 --- a/packages/api-graphql/src/server/generateClient.ts +++ b/packages/api-graphql/src/server/generateClient.ts @@ -52,13 +52,13 @@ export function generateClient = never>({ const wrappedGraphql = ( contextSpec: AmplifyServer.ContextSpec, options: GraphQLOptionsV6, - additionalHeaders?: CustomHeaders + additionalHeaders?: CustomHeaders, ) => { const amplifyInstance = getAmplifyServerContext(contextSpec).amplify; return prevGraphql.call( { [__amplify]: amplifyInstance }, options, - additionalHeaders as any + additionalHeaders as any, ); }; diff --git a/packages/api-graphql/src/types/index.ts b/packages/api-graphql/src/types/index.ts index 9b920691e1c..66645e7ab51 100644 --- a/packages/api-graphql/src/types/index.ts +++ b/packages/api-graphql/src/types/index.ts @@ -1,7 +1,11 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { AmplifyClassV6, ResourcesConfig } from '@aws-amplify/core'; -import { ModelTypes, CustomHeaders, EnumTypes } from '@aws-amplify/data-schema-types'; +import { + ModelTypes, + CustomHeaders, + EnumTypes, +} from '@aws-amplify/data-schema-types'; import { Source, DocumentNode, GraphQLError } from 'graphql'; export { OperationTypeNode } from 'graphql'; import { Observable } from 'rxjs'; @@ -72,7 +76,7 @@ export type GraphQLSubscription = T & { export type GraphQLReturnType = T extends {} ? { [K in keyof T]?: GraphQLReturnType; - } + } : T; /** @@ -93,13 +97,14 @@ type PagedList = { * array, this will only be the case when we also have errors, * which will then be *thrown*. */ -type WithListsFixed = T extends PagedList - ? PagedList, NAME> - : T extends {} - ? { - [K in keyof T]: WithListsFixed; - } - : T; +type WithListsFixed = + T extends PagedList + ? PagedList, NAME> + : T extends {} + ? { + [K in keyof T]: WithListsFixed; + } + : T; /** * Returns an updated response type to always return a value. @@ -115,14 +120,12 @@ type NeverEmpty = { * If empty members are present, there will also be errors present, * and the response will instead be *thrown*. */ -type FixedQueryResult = Exclude< - T[keyof T], - null | undefined -> extends PagedList - ? { - [K in keyof T]-?: WithListsFixed>; - } - : T; +type FixedQueryResult = + Exclude extends PagedList + ? { + [K in keyof T]-?: WithListsFixed>; + } + : T; /** * The return value from a `graphql({query})` call when `query` is a subscription. @@ -181,7 +184,7 @@ export interface AWSAppSyncRealTimeProviderOptions { export type AWSAppSyncRealTimeProvider = { subscribe( - options?: AWSAppSyncRealTimeProviderOptions + options?: AWSAppSyncRealTimeProviderOptions, ): Observable>; }; @@ -235,15 +238,16 @@ export type UnknownGraphQLResponse = export type GraphQLVariablesV6< FALLBACK_TYPES = unknown, TYPED_GQL_STRING extends string = string, -> = TYPED_GQL_STRING extends GeneratedQuery - ? IN - : TYPED_GQL_STRING extends GeneratedMutation - ? IN - : TYPED_GQL_STRING extends GeneratedSubscription - ? IN - : FALLBACK_TYPES extends GraphQLOperationType - ? IN - : any; +> = + TYPED_GQL_STRING extends GeneratedQuery + ? IN + : TYPED_GQL_STRING extends GeneratedMutation + ? IN + : TYPED_GQL_STRING extends GeneratedSubscription + ? IN + : FALLBACK_TYPES extends GraphQLOperationType + ? IN + : any; /** * The expected return type with respect to the given `FALLBACK_TYPE` @@ -252,22 +256,23 @@ export type GraphQLVariablesV6< export type GraphQLResponseV6< FALLBACK_TYPE = unknown, TYPED_GQL_STRING extends string = string, -> = TYPED_GQL_STRING extends GeneratedQuery - ? Promise>> - : TYPED_GQL_STRING extends GeneratedMutation - ? Promise>> - : TYPED_GQL_STRING extends GeneratedSubscription - ? GraphqlSubscriptionResult> - : FALLBACK_TYPE extends GraphQLQuery - ? Promise> - : FALLBACK_TYPE extends GraphQLSubscription - ? GraphqlSubscriptionResult - : FALLBACK_TYPE extends GraphQLOperationType< - infer IN, - infer CUSTOM_OUT - > - ? CUSTOM_OUT - : UnknownGraphQLResponse; +> = + TYPED_GQL_STRING extends GeneratedQuery + ? Promise>> + : TYPED_GQL_STRING extends GeneratedMutation + ? Promise>> + : TYPED_GQL_STRING extends GeneratedSubscription + ? GraphqlSubscriptionResult> + : FALLBACK_TYPE extends GraphQLQuery + ? Promise> + : FALLBACK_TYPE extends GraphQLSubscription + ? GraphqlSubscriptionResult + : FALLBACK_TYPE extends GraphQLOperationType< + infer IN, + infer CUSTOM_OUT + > + ? CUSTOM_OUT + : UnknownGraphQLResponse; /** * The shape customers can use to provide `T` to `graphql()` to specify both @@ -414,7 +419,7 @@ export type GraphQLMethod = < TYPED_GQL_STRING extends string = string, >( options: GraphQLOptionsV6, - additionalHeaders?: CustomHeaders | undefined + additionalHeaders?: CustomHeaders | undefined, ) => GraphQLResponseV6; export type GraphQLMethodSSR = < @@ -423,7 +428,7 @@ export type GraphQLMethodSSR = < >( contextSpec: AmplifyServer.ContextSpec, options: GraphQLOptionsV6, - additionalHeaders?: CustomHeaders | undefined + additionalHeaders?: CustomHeaders | undefined, ) => GraphQLResponseV6; /** diff --git a/packages/api-graphql/src/utils/ConnectionStateMonitor.ts b/packages/api-graphql/src/utils/ConnectionStateMonitor.ts index fc26700978f..908c6999509 100644 --- a/packages/api-graphql/src/utils/ConnectionStateMonitor.ts +++ b/packages/api-graphql/src/utils/ConnectionStateMonitor.ts @@ -69,10 +69,10 @@ export class ConnectionStateMonitor { this._initialNetworkStateSubscription = ReachabilityMonitor().subscribe( ({ online }) => { this.record( - online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE + online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE, ); this._initialNetworkStateSubscription?.unsubscribe(); - } + }, ); this._linkedConnectionStateObservable = @@ -94,9 +94,9 @@ export class ConnectionStateMonitor { this._networkMonitoringSubscription = ReachabilityMonitor().subscribe( ({ online }) => { this.record( - online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE + online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE, ); - } + }, ); } } @@ -126,14 +126,14 @@ export class ConnectionStateMonitor { .pipe( map(value => { return this.connectionStatesTranslator(value); - }) + }), ) .pipe( filter(current => { const toInclude = current !== previous; previous = current; return toInclude; - }) + }), ); } diff --git a/packages/api-graphql/src/utils/errors/assertValidationError.ts b/packages/api-graphql/src/utils/errors/assertValidationError.ts index 2c2e83dca3a..03303f51852 100644 --- a/packages/api-graphql/src/utils/errors/assertValidationError.ts +++ b/packages/api-graphql/src/utils/errors/assertValidationError.ts @@ -9,7 +9,7 @@ import { APIValidationErrorCode, validationErrorMap } from './validation'; */ export function assertValidationError( assertion: boolean, - name: APIValidationErrorCode + name: APIValidationErrorCode, ): asserts assertion { const { message, recoverySuggestion } = validationErrorMap[name]; diff --git a/packages/api-graphql/src/utils/findIndexByFields.ts b/packages/api-graphql/src/utils/findIndexByFields.ts index 6d342be7530..677ce7d3d64 100644 --- a/packages/api-graphql/src/utils/findIndexByFields.ts +++ b/packages/api-graphql/src/utils/findIndexByFields.ts @@ -11,16 +11,16 @@ export function findIndexByFields( needle: T, haystack: T[], - keyFields: Array + keyFields: Array, ): number { const searchObject = Object.fromEntries( - keyFields.map(fieldName => [fieldName, needle[fieldName]]) + keyFields.map(fieldName => [fieldName, needle[fieldName]]), ); for (let i = 0; i < haystack.length; i++) { if ( Object.keys(searchObject).every( - k => searchObject[k] === (haystack[i] as any)[k] + k => searchObject[k] === (haystack[i] as any)[k], ) ) { return i; diff --git a/packages/api-graphql/src/utils/resolveConfig.ts b/packages/api-graphql/src/utils/resolveConfig.ts index 8662d07bc21..f4d971a7ee6 100644 --- a/packages/api-graphql/src/utils/resolveConfig.ts +++ b/packages/api-graphql/src/utils/resolveConfig.ts @@ -14,7 +14,7 @@ export const resolveConfig = (amplify: AmplifyClassV6) => { if (!config.API?.GraphQL) { logger.warn( - 'The API configuration is missing. This is likely due to Amplify.configure() not being called prior to generateClient().' + 'The API configuration is missing. This is likely due to Amplify.configure() not being called prior to generateClient().', ); } @@ -31,7 +31,7 @@ export const resolveConfig = (amplify: AmplifyClassV6) => { // assertValidationError(!!endpoint, APIValidationErrorCode.NoEndpoint); assertValidationError( !(!customEndpoint && customEndpointRegion), - APIValidationErrorCode.NoCustomEndpoint + APIValidationErrorCode.NoCustomEndpoint, ); return { diff --git a/packages/api-graphql/src/utils/resolveOwnerFields.ts b/packages/api-graphql/src/utils/resolveOwnerFields.ts index da916743069..40f112d7150 100644 --- a/packages/api-graphql/src/utils/resolveOwnerFields.ts +++ b/packages/api-graphql/src/utils/resolveOwnerFields.ts @@ -56,7 +56,7 @@ function isAuthAttribute(attribute: any): attribute is AuthAttribute { if (typeof attribute?.properties === 'object') { if (Array.isArray(attribute?.properties?.rules)) { return (attribute?.properties?.rules as Array).every( - rule => !!rule.allow + rule => !!rule.allow, ); } } diff --git a/packages/api-graphql/tsconfig.json b/packages/api-graphql/tsconfig.json index fa1de5d74f5..11d9d83dd6a 100644 --- a/packages/api-graphql/tsconfig.json +++ b/packages/api-graphql/tsconfig.json @@ -4,7 +4,9 @@ "strictNullChecks": true, "baseUrl": ".", "paths": { - "@aws-amplify/data-schema-types": ["../../node_modules/@aws-amplify/data-schema-types"] + "@aws-amplify/data-schema-types": [ + "../../node_modules/@aws-amplify/data-schema-types" + ] } }, "include": ["./src", "__tests__"] diff --git a/packages/api-rest/__tests__/apis/common/internalPost.test.ts b/packages/api-rest/__tests__/apis/common/internalPost.test.ts index f3f80bf8667..45e543fa75c 100644 --- a/packages/api-rest/__tests__/apis/common/internalPost.test.ts +++ b/packages/api-rest/__tests__/apis/common/internalPost.test.ts @@ -38,7 +38,7 @@ const successResponse = { }, }; const apiGatewayUrl = new URL( - 'https://123.execute-api.us-west-2.amazonaws.com' + 'https://123.execute-api.us-west-2.amazonaws.com', ); const credentials = { accessKeyId: 'accessKeyId', @@ -69,7 +69,7 @@ describe('internal post', () => { method: 'POST', headers: {}, }, - expect.objectContaining({ region: 'us-east-1', service: 'execute-api' }) + expect.objectContaining({ region: 'us-east-1', service: 'execute-api' }), ); }); @@ -88,7 +88,7 @@ describe('internal post', () => { method: 'POST', headers: {}, }, - expect.objectContaining({ region: 'us-west-2', service: 'lambda' }) + expect.objectContaining({ region: 'us-west-2', service: 'lambda' }), ); }); it('should call authenticatedHandler with empty signingServiceInfo', async () => { @@ -104,7 +104,7 @@ describe('internal post', () => { method: 'POST', headers: {}, }, - expect.objectContaining({ region: 'us-west-2', service: 'execute-api' }) + expect.objectContaining({ region: 'us-west-2', service: 'execute-api' }), ); }); @@ -125,7 +125,7 @@ describe('internal post', () => { }, body: '{"foo":"bar"}', }, - expect.anything() + expect.anything(), ); }); @@ -150,7 +150,7 @@ describe('internal post', () => { }), body: formData, }, - expect.anything() + expect.anything(), ); }); @@ -164,7 +164,7 @@ describe('internal post', () => { method: 'POST', headers: {}, }, - expect.anything() + expect.anything(), ); }); @@ -184,7 +184,7 @@ describe('internal post', () => { 'x-api-key': '123', }, }), - expect.anything() + expect.anything(), ); expect(mockAuthenticatedHandler).not.toHaveBeenCalled(); }); @@ -205,7 +205,7 @@ describe('internal post', () => { authorization: '123', }, }), - expect.anything() + expect.anything(), ); expect(mockAuthenticatedHandler).not.toHaveBeenCalled(); }); @@ -213,7 +213,7 @@ describe('internal post', () => { it('should call unauthenticatedHandler if credential is not set', async () => { mockFetchAuthSession.mockClear(); mockFetchAuthSession.mockRejectedValue( - new Error('Mock error as credentials not configured') + new Error('Mock error as credentials not configured'), ); await post(mockAmplifyInstance, { url: apiGatewayUrl, @@ -224,7 +224,7 @@ describe('internal post', () => { method: 'POST', headers: {}, }, - expect.anything() + expect.anything(), ); expect(mockAuthenticatedHandler).not.toHaveBeenCalled(); }); @@ -236,7 +236,7 @@ describe('internal post', () => { mockUnauthenticatedHandler.mockReturnValue( new Promise((_, reject) => { underLyingHandlerReject = reject; - }) + }), ); const abortController = new AbortController(); const promise = post(mockAmplifyInstance, { diff --git a/packages/api-rest/__tests__/apis/common/publicApis.test.ts b/packages/api-rest/__tests__/apis/common/publicApis.test.ts index d1ff0aba4cd..6aa30c3aa59 100644 --- a/packages/api-rest/__tests__/apis/common/publicApis.test.ts +++ b/packages/api-rest/__tests__/apis/common/publicApis.test.ts @@ -108,7 +108,7 @@ describe('public APIs', () => { expect(mockAuthenticatedHandler).toHaveBeenCalledWith( { url: new URL( - 'https://123.execute-api.us-west-2.amazonaws.com/development/items' + 'https://123.execute-api.us-west-2.amazonaws.com/development/items', ), method, headers: {}, @@ -118,7 +118,7 @@ describe('public APIs', () => { region: 'us-west-2', service: 'execute-api', withCrossDomainCredentials: true, - }) + }), ); expect(response.headers).toEqual({ 'response-header': 'response-header-value', @@ -141,7 +141,7 @@ describe('public APIs', () => { expect(mockAuthenticatedHandler).toHaveBeenCalledWith( { url: new URL( - 'https://123.execute-api.us-west-2.amazonaws.com/development/items' + 'https://123.execute-api.us-west-2.amazonaws.com/development/items', ), method, headers: { @@ -152,7 +152,7 @@ describe('public APIs', () => { expect.objectContaining({ region: 'us-west-2', service: 'execute-api', - }) + }), ); }); @@ -169,7 +169,7 @@ describe('public APIs', () => { expect(mockAuthenticatedHandler).toHaveBeenCalledWith( { url: new URL( - 'https://123.execute-api.us-west-2.amazonaws.com/development/items' + 'https://123.execute-api.us-west-2.amazonaws.com/development/items', ), method, headers: { @@ -180,7 +180,7 @@ describe('public APIs', () => { expect.objectContaining({ region: 'us-west-2', service: 'execute-api', - }) + }), ); }); @@ -192,10 +192,10 @@ describe('public APIs', () => { expect(mockAuthenticatedHandler).toHaveBeenCalledWith( expect.objectContaining({ url: new URL( - 'https://123.execute-api.us-west-2.amazonaws.com/development/items/123' + 'https://123.execute-api.us-west-2.amazonaws.com/development/items/123', ), }), - expect.anything() + expect.anything(), ); }); @@ -215,7 +215,7 @@ describe('public APIs', () => { href: 'https://123.execute-api.us-west-2.amazonaws.com/development/items?param1=value1', }), }), - expect.anything() + expect.anything(), ); }); @@ -235,7 +235,7 @@ describe('public APIs', () => { href: 'https://123.execute-api.us-west-2.amazonaws.com/development/items?param1=value1&foo=bar', }), }), - expect.anything() + expect.anything(), ); }); @@ -249,7 +249,7 @@ describe('public APIs', () => { } catch (error) { expect(error).toBeInstanceOf(RestApiError); expect(error).toMatchObject( - validationErrorMap[RestApiValidationErrorCode.InvalidApiName] + validationErrorMap[RestApiValidationErrorCode.InvalidApiName], ); } }); @@ -266,7 +266,7 @@ describe('public APIs', () => { expect(error).toMatchObject({ ...validationErrorMap[RestApiValidationErrorCode.InvalidApiName], recoverySuggestion: expect.stringContaining( - 'Please make sure the REST endpoint URL is a valid URL string.' + 'Please make sure the REST endpoint URL is a valid URL string.', ), }); } @@ -282,10 +282,10 @@ describe('public APIs', () => { expect(mockUnauthenticatedHandler).toHaveBeenCalledWith( expect.objectContaining({ url: new URL( - 'https://123.execute-api.us-west-2.amazonaws.com/development/items/123' + 'https://123.execute-api.us-west-2.amazonaws.com/development/items/123', ), }), - expect.anything() + expect.anything(), ); }); @@ -387,7 +387,7 @@ describe('public APIs', () => { mockAuthenticatedHandler.mockReturnValue( new Promise((_, reject) => { underLyingHandlerReject = reject; - }) + }), ); abortSpy.mockImplementation(() => { const mockAbortError = new Error('AbortError'); diff --git a/packages/api-rest/__tests__/server.test.ts b/packages/api-rest/__tests__/server.test.ts index 8ad5ceda015..e37dc49e3ef 100644 --- a/packages/api-rest/__tests__/server.test.ts +++ b/packages/api-rest/__tests__/server.test.ts @@ -37,7 +37,7 @@ describe('REST API handlers', () => { expect(mockGetAmplifyServerContext).toHaveBeenCalledWith(contextSpec); expect(commonGet).toHaveBeenCalledWith( 'mockedAmplifyServerSideContext', - input + input, ); }); @@ -46,7 +46,7 @@ describe('REST API handlers', () => { expect(mockGetAmplifyServerContext).toHaveBeenCalledWith(contextSpec); expect(commonPost).toHaveBeenCalledWith( 'mockedAmplifyServerSideContext', - input + input, ); }); @@ -55,7 +55,7 @@ describe('REST API handlers', () => { expect(mockGetAmplifyServerContext).toHaveBeenCalledWith(contextSpec); expect(commonPut).toHaveBeenCalledWith( 'mockedAmplifyServerSideContext', - input + input, ); }); @@ -64,7 +64,7 @@ describe('REST API handlers', () => { expect(mockGetAmplifyServerContext).toHaveBeenCalledWith(contextSpec); expect(commonDel).toHaveBeenCalledWith( 'mockedAmplifyServerSideContext', - input + input, ); }); @@ -73,7 +73,7 @@ describe('REST API handlers', () => { expect(mockGetAmplifyServerContext).toHaveBeenCalledWith(contextSpec); expect(commonPatch).toHaveBeenCalledWith( 'mockedAmplifyServerSideContext', - input + input, ); }); @@ -82,7 +82,7 @@ describe('REST API handlers', () => { expect(mockGetAmplifyServerContext).toHaveBeenCalledWith(contextSpec); expect(commonHead).toHaveBeenCalledWith( 'mockedAmplifyServerSideContext', - input + input, ); }); }); diff --git a/packages/api/__tests__/API.test.ts b/packages/api/__tests__/API.test.ts index 188ec6b8e8b..ab95bf9dcc9 100644 --- a/packages/api/__tests__/API.test.ts +++ b/packages/api/__tests__/API.test.ts @@ -34,13 +34,13 @@ describe('API generateClient', () => { { action: '1', category: 'api', - } + }, ); }); test('CONNECTION_STATE_CHANGE importable as a value, not a type', async () => { expect(CONNECTION_STATE_CHANGE).toBe('ConnectionStateChange'); - }) + }); // test('server-side client.graphql', async () => { // const config: ResourcesConfig = { // API: { diff --git a/packages/api/src/internals/InternalAPI.ts b/packages/api/src/internals/InternalAPI.ts index 5b65ca84fb3..fa5c1a2001f 100644 --- a/packages/api/src/internals/InternalAPI.ts +++ b/packages/api/src/internals/InternalAPI.ts @@ -71,11 +71,11 @@ export class InternalAPIClass { ): T extends GraphQLQuery ? Promise> : T extends GraphQLSubscription - ? Observable<{ + ? Observable<{ provider: AWSAppSyncRealTimeProvider; value: GraphQLResult; - }> - : Promise> | Observable; + }> + : Promise> | Observable; graphql<_ = any>( options: GraphQLOptions, diff --git a/packages/auth/__tests__/BigInteger.test.ts b/packages/auth/__tests__/BigInteger.test.ts index 43dce154dfd..7af582e64b3 100644 --- a/packages/auth/__tests__/BigInteger.test.ts +++ b/packages/auth/__tests__/BigInteger.test.ts @@ -7,13 +7,13 @@ describe('BigInteger', () => { describe('.toString(radix)', () => { it('should support positive numbers', () => { expect(new BigInteger('abcd1234', 16).toString(4)).toBe( - '2223303101020310' + '2223303101020310', ); }); it('should support negative numbers', () => { expect(new BigInteger('-abcd1234', 16).toString(4)).toBe( - '-2223303101020310' + '-2223303101020310', ); }); }); diff --git a/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts b/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts index 330a930edbb..b71eb4902e2 100644 --- a/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts +++ b/packages/auth/__tests__/providers/cognito/autoSignIn.test.ts @@ -39,14 +39,14 @@ describe('Auto sign-in API Happy Path Cases:', () => { signUpSpy = jest .spyOn(signUpClient, 'signUp') .mockImplementationOnce( - async () => ({ UserConfirmed: true }) as SignUpCommandOutput + async () => ({ UserConfirmed: true }) as SignUpCommandOutput, ); handleUserSRPAuthflowSpy = jest .spyOn(initiateAuthHelpers, 'handleUserSRPAuthFlow') .mockImplementationOnce( async (): Promise => - authAPITestParams.RespondToAuthChallengeCommandOutput + authAPITestParams.RespondToAuthChallengeCommandOutput, ); }); afterEach(() => { diff --git a/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts b/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts index 19fb9d6c7c1..8b6ad268552 100644 --- a/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts @@ -20,7 +20,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('confirmResetPassword', () => { @@ -33,7 +33,7 @@ describe('confirmResetPassword', () => { beforeEach(() => { mockConfirmForgotPassword.mockResolvedValue( - authAPITestParams.confirmResetPasswordHttpCallResult + authAPITestParams.confirmResetPasswordHttpCallResult, ); }); @@ -43,7 +43,7 @@ describe('confirmResetPassword', () => { it('should call the confirmForgotPassword and return void', async () => { expect( - await confirmResetPassword(authAPITestParams.confirmResetPasswordRequest) + await confirmResetPassword(authAPITestParams.confirmResetPasswordRequest), ).toBeUndefined(); expect(mockConfirmForgotPassword).toHaveBeenCalled(); }); @@ -65,7 +65,7 @@ describe('confirmResetPassword', () => { Password: 'password', ClientMetadata: { fooo: 'fooo' }, ClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - }) + }), ); }); @@ -80,7 +80,7 @@ describe('confirmResetPassword', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - AuthValidationErrorCode.EmptyConfirmResetPasswordUsername + AuthValidationErrorCode.EmptyConfirmResetPasswordUsername, ); } }); @@ -96,7 +96,7 @@ describe('confirmResetPassword', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - AuthValidationErrorCode.EmptyConfirmResetPasswordNewPassword + AuthValidationErrorCode.EmptyConfirmResetPasswordNewPassword, ); } }); @@ -112,7 +112,7 @@ describe('confirmResetPassword', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - AuthValidationErrorCode.EmptyConfirmResetPasswordConfirmationCode + AuthValidationErrorCode.EmptyConfirmResetPasswordConfirmationCode, ); } }); @@ -121,7 +121,7 @@ describe('confirmResetPassword', () => { expect.assertions(2); mockConfirmForgotPassword.mockImplementation(() => { throw getMockError( - ConfirmForgotPasswordException.InvalidParameterException + ConfirmForgotPasswordException.InvalidParameterException, ); }); try { @@ -129,7 +129,7 @@ describe('confirmResetPassword', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - ConfirmForgotPasswordException.InvalidParameterException + ConfirmForgotPasswordException.InvalidParameterException, ); } }); @@ -160,7 +160,7 @@ describe('confirmResetPassword', () => { UserContextData: { EncodedData: 'abcd', }, - }) + }), ); window['AmazonCognitoAdvancedSecurityData'] = undefined; }); diff --git a/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts b/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts index e8a3108205b..2f399ebc87a 100644 --- a/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts @@ -14,7 +14,7 @@ jest.mock('@aws-amplify/core', () => ({ Amplify: { getConfig: jest.fn(() => ({})) }, })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); jest.mock('../../../src/providers/cognito/utils/signInStore'); @@ -63,7 +63,7 @@ describe('confirmSignIn API error path cases:', () => { expect.assertions(2); mockRespondToAuthChallenge.mockImplementation(() => { throw getMockError( - RespondToAuthChallengeException.InvalidParameterException + RespondToAuthChallengeException.InvalidParameterException, ); }); try { @@ -71,7 +71,7 @@ describe('confirmSignIn API error path cases:', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - RespondToAuthChallengeException.InvalidParameterException + RespondToAuthChallengeException.InvalidParameterException, ); } }); diff --git a/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts b/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts index 2e3759ab807..b59a66dd017 100644 --- a/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmSignInHappyCases.test.ts @@ -52,7 +52,7 @@ describe('confirmSignIn API happy path cases', () => { }, Session: 'aaabbbcccddd', $metadata: {}, - }) + }), ); }); @@ -80,7 +80,7 @@ describe('confirmSignIn API happy path cases', () => { CODE_DELIVERY_DELIVERY_MEDIUM: 'SMS', CODE_DELIVERY_DESTINATION: '*******9878', }, - }) + }), ); const signInResult = await signIn({ username, password }); @@ -132,7 +132,7 @@ describe('confirmSignIn API happy path cases', () => { Session: '1234234232', $metadata: {}, ChallengeParameters: {}, - }) + }), ); const signInResult = await signIn({ username, password }); @@ -175,7 +175,7 @@ describe('confirmSignIn API happy path cases', () => { ChallengeParameters: { MFAS_CAN_CHOOSE: '["SMS_MFA","SOFTWARE_TOKEN_MFA"]', }, - }) + }), ); // overrides handleChallengeNameSpy handleChallengeNameSpy.mockImplementation( @@ -187,7 +187,7 @@ describe('confirmSignIn API happy path cases', () => { CODE_DELIVERY_DELIVERY_MEDIUM: 'SMS', CODE_DELIVERY_DESTINATION: '*******9878', }, - }) + }), ); const signInResult = await signIn({ username, password }); @@ -244,7 +244,7 @@ describe('confirmSignIn API happy path cases', () => { CODE_DELIVERY_DELIVERY_MEDIUM: 'SMS', CODE_DELIVERY_DESTINATION: '*******9878', }, - }) + }), ); await signIn({ username, @@ -266,7 +266,7 @@ describe('confirmSignIn API happy path cases', () => { authConfig.Cognito, tokenOrchestrator, authAPITestParams.configWithClientMetadata.clientMetadata, - options + options, ); initiateAuthSpy.mockClear(); }); @@ -308,7 +308,7 @@ describe('Cognito ASF', () => { RefreshToken: 'qwersfsafsfssfasf', }, }; - } + }, ); }); @@ -334,7 +334,7 @@ describe('Cognito ASF', () => { CODE_DELIVERY_DELIVERY_MEDIUM: 'SMS_MFA', CODE_DELIVERY_DESTINATION: 'aaa@awsamplify.com', }, - }) + }), ); const result = await signIn({ username, password }); @@ -359,7 +359,7 @@ describe('Cognito ASF', () => { ClientMetadata: undefined, Session: '1234234232', UserContextData: { EncodedData: 'abcd' }, - }) + }), ); }); @@ -374,13 +374,13 @@ describe('Cognito ASF', () => { MFAS_CAN_CHOOSE: '["SMS_MFA","SOFTWARE_TOKEN_MFA"]', }, $metadata: {}, - }) + }), ); const result = await signIn({ username, password }); expect(result.isSignedIn).toBe(false); expect(result.nextStep.signInStep).toBe( - 'CONTINUE_SIGN_IN_WITH_MFA_SELECTION' + 'CONTINUE_SIGN_IN_WITH_MFA_SELECTION', ); try { await confirmSignIn({ @@ -404,7 +404,7 @@ describe('Cognito ASF', () => { ClientMetadata: undefined, Session: '1234234232', UserContextData: { EncodedData: 'abcd' }, - }) + }), ); }); @@ -420,7 +420,7 @@ describe('Cognito ASF', () => { Session: '1234234232', $metadata: {}, ChallengeParameters: {}, - }) + }), ); const result = await signIn({ username, password }); @@ -449,7 +449,7 @@ describe('Cognito ASF', () => { ClientMetadata: undefined, Session: '1234234232', UserContextData: { EncodedData: 'abcd' }, - }) + }), ); }); @@ -465,14 +465,14 @@ describe('Cognito ASF', () => { Session: '1234234232', $metadata: {}, ChallengeParameters: {}, - }) + }), ); const result = await signIn({ username, password }); expect(result.isSignedIn).toBe(false); expect(result.nextStep.signInStep).toBe( - 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED' + 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED', ); try { await confirmSignIn({ @@ -496,7 +496,7 @@ describe('Cognito ASF', () => { ClientMetadata: undefined, Session: '1234234232', UserContextData: { EncodedData: 'abcd' }, - }) + }), ); }); test(`confirmSignIn tests CUSTOM_CHALLENGE sends UserContextData`, async () => { @@ -511,14 +511,14 @@ describe('Cognito ASF', () => { Session: '1234234232', $metadata: {}, ChallengeParameters: {}, - }) + }), ); const result = await signIn({ username, password }); expect(result.isSignedIn).toBe(false); expect(result.nextStep.signInStep).toBe( - 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE' + 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE', ); try { await confirmSignIn({ @@ -542,7 +542,7 @@ describe('Cognito ASF', () => { ClientMetadata: undefined, Session: '1234234232', UserContextData: { EncodedData: 'abcd' }, - }) + }), ); }); }); diff --git a/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts b/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts index 56f8af67338..9e4678b246d 100644 --- a/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts @@ -21,7 +21,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('confirmSignUp', () => { @@ -61,7 +61,7 @@ describe('confirmSignUp', () => { Username: user1.username, ForceAliasCreation: undefined, ClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - } + }, ); expect(mockConfirmSignUp).toHaveBeenCalledTimes(1); }); @@ -81,7 +81,7 @@ describe('confirmSignUp', () => { ConfirmationCode: confirmationCode, Username: user1.username, ForceAliasCreation: true, - }) + }), ); }); @@ -102,7 +102,7 @@ describe('confirmSignUp', () => { Username: user1.username, ForceAliasCreation: undefined, ClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - }) + }), ); }); @@ -113,7 +113,7 @@ describe('confirmSignUp', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - AuthValidationErrorCode.EmptyConfirmSignUpUsername + AuthValidationErrorCode.EmptyConfirmSignUpUsername, ); } }); @@ -166,7 +166,7 @@ describe('confirmSignUp', () => { ForceAliasCreation: undefined, ClientId: '111111-aaaaa-42d8-891d-ee81a1549398', UserContextData: { EncodedData: 'abcd' }, - } + }, ); expect(mockConfirmSignUp).toHaveBeenCalledTimes(1); window['AmazonCognitoAdvancedSecurityData'] = undefined; diff --git a/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts b/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts index 6c23fb93023..2ba5577e503 100644 --- a/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts @@ -21,7 +21,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('confirmUserAttribute', () => { @@ -58,7 +58,7 @@ describe('confirmUserAttribute', () => { AccessToken: mockAccessToken, AttributeName: 'email', Code: confirmationCode, - }) + }), ); }); @@ -71,7 +71,7 @@ describe('confirmUserAttribute', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - AuthValidationErrorCode.EmptyConfirmUserAttributeCode + AuthValidationErrorCode.EmptyConfirmUserAttributeCode, ); } }); @@ -80,7 +80,7 @@ describe('confirmUserAttribute', () => { expect.assertions(2); mockVerifyUserAttribute.mockImplementation(() => { throw getMockError( - VerifyUserAttributeException.InvalidParameterException + VerifyUserAttributeException.InvalidParameterException, ); }); try { @@ -91,7 +91,7 @@ describe('confirmUserAttribute', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - VerifyUserAttributeException.InvalidParameterException + VerifyUserAttributeException.InvalidParameterException, ); } }); diff --git a/packages/auth/__tests__/providers/cognito/credentialsProvider.test.ts b/packages/auth/__tests__/providers/cognito/credentialsProvider.test.ts index 8aa73f0411f..b119c84ca28 100644 --- a/packages/auth/__tests__/providers/cognito/credentialsProvider.test.ts +++ b/packages/auth/__tests__/providers/cognito/credentialsProvider.test.ts @@ -35,7 +35,7 @@ jest.mock( .mockReturnValueOnce('identity-id-test') .mockReturnValueOnce('identity-id-test') .mockReturnValueOnce(undefined), - }) + }), ); const validAuthConfig: ResourcesConfig = { @@ -71,12 +71,12 @@ describe('Guest Credentials', () => { beforeEach(() => { cognitoCredentialsProvider = new CognitoAWSCredentialsAndIdentityIdProvider( - new DefaultIdentityIdStore(sharedInMemoryStorage) + new DefaultIdentityIdStore(sharedInMemoryStorage), ); credentialsForIdentityIdSpy.mockImplementationOnce( async ({}, params: GetCredentialsForIdentityInput) => { return authAPITestParams.CredentialsForIdentityIdResult as GetCredentialsForIdentityOutput; - } + }, ); }); afterEach(() => { @@ -89,16 +89,17 @@ describe('Guest Credentials', () => { authConfig: validAuthConfig.Auth!, }); expect(res?.credentials.accessKeyId).toEqual( - authAPITestParams.CredentialsForIdentityIdResult.Credentials.AccessKeyId + authAPITestParams.CredentialsForIdentityIdResult.Credentials + .AccessKeyId, ); expect(credentialsForIdentityIdSpy).toHaveBeenCalledTimes(1); expect(credentialsForIdentityIdSpy).toHaveBeenCalledWith( { region: 'us-east-1' }, - { IdentityId: 'identity-id-test' } + { IdentityId: 'identity-id-test' }, ); expect( - cognitoCredentialsProvider['_nextCredentialsRefresh'] + cognitoCredentialsProvider['_nextCredentialsRefresh'], ).toBeGreaterThan(0); }); test('in-memory guest creds are returned if not expired and not past TTL', async () => { @@ -112,7 +113,8 @@ describe('Guest Credentials', () => { authConfig: validAuthConfig.Auth!, }); expect(res?.credentials.accessKeyId).toEqual( - authAPITestParams.CredentialsForIdentityIdResult.Credentials.AccessKeyId + authAPITestParams.CredentialsForIdentityIdResult.Credentials + .AccessKeyId, ); // expecting to be called only once becasue in-memory creds should be returned expect(credentialsForIdentityIdSpy).toHaveBeenCalledTimes(1); @@ -123,12 +125,12 @@ describe('Guest Credentials', () => { beforeEach(() => { cognitoCredentialsProvider = new CognitoAWSCredentialsAndIdentityIdProvider( - new DefaultIdentityIdStore(sharedInMemoryStorage) + new DefaultIdentityIdStore(sharedInMemoryStorage), ); credentialsForIdentityIdSpy.mockImplementationOnce( async ({}, params: GetCredentialsForIdentityInput) => { return authAPITestParams.NoAccessKeyCredentialsForIdentityIdResult as GetCredentialsForIdentityOutput; - } + }, ); }); afterEach(() => { @@ -142,7 +144,7 @@ describe('Guest Credentials', () => { await cognitoCredentialsProvider.getCredentialsAndIdentityId({ authenticated: false, authConfig: disallowGuestAccessConfig.Auth!, - }) + }), ).toBe(undefined); }); test('Should not throw AuthError when there is no Cognito object in the config', async () => { @@ -150,7 +152,7 @@ describe('Guest Credentials', () => { await cognitoCredentialsProvider.getCredentialsAndIdentityId({ authenticated: false, authConfig: inValidAuthConfig.Auth!, - }) + }), ).toBe(undefined); }); }); @@ -162,12 +164,12 @@ describe('Primary Credentials', () => { beforeEach(() => { cognitoCredentialsProvider = new CognitoAWSCredentialsAndIdentityIdProvider( - new DefaultIdentityIdStore(sharedInMemoryStorage) + new DefaultIdentityIdStore(sharedInMemoryStorage), ); credentialsForIdentityIdSpy.mockImplementation( async ({}, params: GetCredentialsForIdentityInput) => { return authAPITestParams.CredentialsForIdentityIdResult as GetCredentialsForIdentityOutput; - } + }, ); }); afterEach(() => { @@ -181,7 +183,8 @@ describe('Primary Credentials', () => { tokens: authAPITestParams.ValidAuthTokens, }); expect(res.credentials.accessKeyId).toEqual( - authAPITestParams.CredentialsForIdentityIdResult.Credentials.AccessKeyId + authAPITestParams.CredentialsForIdentityIdResult.Credentials + .AccessKeyId, ); expect(credentialsForIdentityIdSpy).toHaveBeenCalledTimes(1); @@ -196,7 +199,7 @@ describe('Primary Credentials', () => { { region: authAPITestParams.CredentialsClientRequest.region, }, - authAPITestParams.CredentialsClientRequest.withValidAuthToken + authAPITestParams.CredentialsClientRequest.withValidAuthToken, ); expect(credentialsForIdentityIdSpy).toHaveBeenCalledTimes(1); @@ -206,7 +209,8 @@ describe('Primary Credentials', () => { tokens: authAPITestParams.ValidAuthTokens, }); expect(res.credentials.accessKeyId).toEqual( - authAPITestParams.CredentialsForIdentityIdResult.Credentials.AccessKeyId + authAPITestParams.CredentialsForIdentityIdResult.Credentials + .AccessKeyId, ); // expecting to be called only once becasue in-memory creds should be returned expect(credentialsForIdentityIdSpy).toHaveBeenCalledTimes(1); @@ -221,7 +225,7 @@ describe('Primary Credentials', () => { { region: authAPITestParams.CredentialsClientRequest.region, }, - authAPITestParams.CredentialsClientRequest.withValidAuthToken + authAPITestParams.CredentialsClientRequest.withValidAuthToken, ); expect(credentialsForIdentityIdSpy).toHaveBeenCalledTimes(1); @@ -234,7 +238,7 @@ describe('Primary Credentials', () => { { region: authAPITestParams.CredentialsClientRequest.region, }, - authAPITestParams.CredentialsClientRequest.withNewValidAuthToken + authAPITestParams.CredentialsClientRequest.withNewValidAuthToken, ); expect(credentialsForIdentityIdSpy).toHaveBeenCalledTimes(2); }); @@ -243,7 +247,7 @@ describe('Primary Credentials', () => { beforeEach(() => { cognitoCredentialsProvider = new CognitoAWSCredentialsAndIdentityIdProvider( - new DefaultIdentityIdStore(sharedInMemoryStorage) + new DefaultIdentityIdStore(sharedInMemoryStorage), ); }); afterEach(() => { @@ -256,40 +260,40 @@ describe('Primary Credentials', () => { credentialsForIdentityIdSpy.mockImplementationOnce( async ({}, params: GetCredentialsForIdentityInput) => { return authAPITestParams.NoAccessKeyCredentialsForIdentityIdResult as GetCredentialsForIdentityOutput; - } + }, ); expect( cognitoCredentialsProvider.getCredentialsAndIdentityId({ authenticated: true, authConfig: validAuthConfig.Auth!, tokens: authAPITestParams.ValidAuthTokens, - }) + }), ).rejects.toThrow(AuthError); credentialsForIdentityIdSpy.mockClear(); credentialsForIdentityIdSpy.mockImplementationOnce( async ({}, params: GetCredentialsForIdentityInput) => { return authAPITestParams.NoCredentialsForIdentityIdResult as GetCredentialsForIdentityOutput; - } + }, ); expect( cognitoCredentialsProvider.getCredentialsAndIdentityId({ authenticated: true, authConfig: validAuthConfig.Auth!, tokens: authAPITestParams.ValidAuthTokens, - }) + }), ).rejects.toThrow(AuthError); credentialsForIdentityIdSpy.mockClear(); credentialsForIdentityIdSpy.mockImplementationOnce( async ({}, params: GetCredentialsForIdentityInput) => { return authAPITestParams.NoSecretKeyInCredentialsForIdentityIdResult as GetCredentialsForIdentityOutput; - } + }, ); expect( cognitoCredentialsProvider.getCredentialsAndIdentityId({ authenticated: true, authConfig: validAuthConfig.Auth!, tokens: authAPITestParams.ValidAuthTokens, - }) + }), ).rejects.toThrow(AuthError); }); }); diff --git a/packages/auth/__tests__/providers/cognito/deleteUser.test.ts b/packages/auth/__tests__/providers/cognito/deleteUser.test.ts index 59ac25e856e..813629911b2 100644 --- a/packages/auth/__tests__/providers/cognito/deleteUser.test.ts +++ b/packages/auth/__tests__/providers/cognito/deleteUser.test.ts @@ -22,7 +22,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ })); jest.mock('../../../src/providers/cognito/apis/signOut'); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); jest.mock('../../../src/providers/cognito/tokenProvider'); @@ -58,7 +58,7 @@ describe('deleteUser', () => { expect.objectContaining({ region: 'us-west-2' }), expect.objectContaining({ AccessToken: mockAccessToken, - }) + }), ); expect(mockDeleteUser).toHaveBeenCalledTimes(1); expect(mockClearDeviceMetadata).toHaveBeenCalledTimes(1); @@ -66,7 +66,7 @@ describe('deleteUser', () => { // make sure we clearDeviceToken -> signout, in that order expect(mockClearDeviceMetadata.mock.invocationCallOrder[0]).toBeLessThan( - mockSignOut.mock.invocationCallOrder[0] + mockSignOut.mock.invocationCallOrder[0], ); }); diff --git a/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts index c3e855204ea..840ca287620 100644 --- a/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts @@ -19,7 +19,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('deleteUserAttributes', () => { @@ -53,7 +53,7 @@ describe('deleteUserAttributes', () => { expect.objectContaining({ AccessToken: mockAccessToken, UserAttributeNames: ['given_name', 'address'], - }) + }), ); expect(mockDeleteUserAttributes).toHaveBeenCalledTimes(1); }); @@ -62,7 +62,7 @@ describe('deleteUserAttributes', () => { expect.assertions(2); mockDeleteUserAttributes.mockImplementation(() => { throw getMockError( - DeleteUserAttributesException.InvalidParameterException + DeleteUserAttributesException.InvalidParameterException, ); }); try { @@ -72,7 +72,7 @@ describe('deleteUserAttributes', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - DeleteUserAttributesException.InvalidParameterException + DeleteUserAttributesException.InvalidParameterException, ); } }); diff --git a/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts b/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts index 410cb41e257..6980175e736 100644 --- a/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchAuthSession.test.ts @@ -17,7 +17,7 @@ describe('fetchAuthSession behavior for IdentityPools only', () => { credentialsProviderSpy = jest .spyOn( CognitoAWSCredentialsAndIdentityIdProvider.prototype, - 'getCredentialsAndIdentityId' + 'getCredentialsAndIdentityId', ) .mockImplementation(async () => { return { @@ -45,7 +45,7 @@ describe('fetchAuthSession behavior for IdentityPools only', () => { credentialsProvider: cognitoCredentialsProvider, tokenProvider: cognitoUserPoolsTokenProvider, }, - } + }, ); const session = await fetchAuthSession(); @@ -82,10 +82,10 @@ describe('fetchAuthSession behavior for UserPools only', () => { .mockImplementation(async () => { return { accessToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y', ), idToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y', ), }; }); @@ -106,7 +106,7 @@ describe('fetchAuthSession behavior for UserPools only', () => { credentialsProvider: cognitoCredentialsProvider, tokenProvider: cognitoUserPoolsTokenProvider, }, - } + }, ); const session = await fetchAuthSession(); diff --git a/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts b/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts index ccaacae5d79..a3f6fb40384 100644 --- a/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts @@ -19,7 +19,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('fetchDevices', () => { @@ -72,7 +72,7 @@ describe('fetchDevices', () => { expect.objectContaining({ AccessToken: mockAccessToken, Limit: 60, - }) + }), ); expect(mockListDevices).toHaveBeenCalledTimes(1); }); diff --git a/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts b/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts index 0223513bd41..e52de635585 100644 --- a/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts @@ -15,7 +15,7 @@ jest.mock('@aws-amplify/core', () => ({ Amplify: { getConfig: jest.fn(() => ({})) }, })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('fetchMFAPreference', () => { @@ -56,7 +56,7 @@ describe('fetchMFAPreference', () => { }, { AccessToken: mockAccessToken, - } + }, ); }); diff --git a/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts index a1370c7f190..e53a749c843 100644 --- a/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts @@ -19,7 +19,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ fetchAuthSession: jest.fn(), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('fetchUserAttributes', () => { @@ -65,7 +65,7 @@ describe('fetchUserAttributes', () => { }, { AccessToken: mockAccessToken, - } + }, ); }); diff --git a/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts b/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts index 5ff7709276d..f62f1eb39ab 100644 --- a/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts +++ b/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts @@ -21,7 +21,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); jest.mock('../../../src/providers/cognito/tokenProvider'); @@ -66,7 +66,7 @@ describe('fetchMFAPreference', () => { expect.objectContaining({ AccessToken: mockAccessToken, DeviceKey: 'externalDeviceKey', - }) + }), ); expect(mockForgetDevice).toHaveBeenCalledTimes(1); expect(mockClearDeviceMetadata).not.toHaveBeenCalled(); @@ -80,7 +80,7 @@ describe('fetchMFAPreference', () => { expect.objectContaining({ AccessToken: mockAccessToken, DeviceKey: mockDeviceMetadata.deviceKey, - }) + }), ); expect(mockForgetDevice).toHaveBeenCalledTimes(1); expect(mockClearDeviceMetadata).toHaveBeenCalled(); @@ -94,7 +94,7 @@ describe('fetchMFAPreference', () => { expect.objectContaining({ AccessToken: mockAccessToken, DeviceKey: mockDeviceMetadata.deviceKey, - }) + }), ); expect(mockForgetDevice).toHaveBeenCalledTimes(1); expect(mockClearDeviceMetadata).toHaveBeenCalled(); @@ -108,7 +108,7 @@ describe('fetchMFAPreference', () => { expect.objectContaining({ AccessToken: mockAccessToken, DeviceKey: 'externalDeviceKey', - }) + }), ); expect(mockForgetDevice).toHaveBeenCalledTimes(1); expect(mockClearDeviceMetadata).not.toHaveBeenCalled(); @@ -123,7 +123,7 @@ describe('fetchMFAPreference', () => { expect.objectContaining({ AccessToken: mockAccessToken, DeviceKey: mockDeviceMetadata.deviceKey, - }) + }), ); expect(mockForgetDevice).toHaveBeenCalledTimes(1); expect(mockClearDeviceMetadata).not.toHaveBeenCalled(); diff --git a/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts b/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts index 00a4ee24a69..d275e8cec2f 100644 --- a/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts +++ b/packages/auth/__tests__/providers/cognito/getNewDeviceMetadata.test.ts @@ -36,7 +36,7 @@ describe('test getNewDeviceMetadata API', () => { DeviceKey: mockedDeviceKey, DeviceGroupKey: mockedGroupDeviceKey, }, - mockedAccessToken + mockedAccessToken, ); expect(deviceMetadata?.deviceKey).toBe(mockedDeviceKey); @@ -46,7 +46,7 @@ describe('test getNewDeviceMetadata API', () => { expect.objectContaining({ AccessToken: mockedAccessToken, DeviceKey: mockedDeviceKey, - }) + }), ); confirmDeviceClientSpy.mockClear(); @@ -69,7 +69,7 @@ describe('test getNewDeviceMetadata API', () => { DeviceKey: mockedDeviceKey, DeviceGroupKey: mockedGroupDeviceKey, }, - mockedAccessToken + mockedAccessToken, ); expect(deviceMetadata).toBeUndefined(); @@ -78,7 +78,7 @@ describe('test getNewDeviceMetadata API', () => { expect.objectContaining({ AccessToken: mockedAccessToken, DeviceKey: mockedDeviceKey, - }) + }), ); confirmDeviceClientSpy.mockClear(); diff --git a/packages/auth/__tests__/providers/cognito/hub.test.ts b/packages/auth/__tests__/providers/cognito/hub.test.ts index f1cf8aa98b1..55c1e613957 100644 --- a/packages/auth/__tests__/providers/cognito/hub.test.ts +++ b/packages/auth/__tests__/providers/cognito/hub.test.ts @@ -36,7 +36,7 @@ describe('Hub API happy path cases', () => { 'auth', { event: 'signInWithRedirect' }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); } @@ -67,7 +67,7 @@ describe('Hub API negative path cases', () => { 'auth', { event: 'tokenRefresh_failure' }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); } } @@ -88,7 +88,7 @@ describe('Hub API negative path cases', () => { 'auth', { event: 'signInWithRedirect_failure' }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); } } diff --git a/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts b/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts index ebb37ca3a7a..5468e631187 100644 --- a/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts +++ b/packages/auth/__tests__/providers/cognito/identityIdProvider.test.ts @@ -66,13 +66,13 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { mockDefaultIdentityIdStoreInstance.loadIdentityId.mockImplementationOnce( async () => { return authAPITestParams.GuestIdentityId as Identity; - } + }, ); expect( await cognitoIdentityIdProvider({ authConfig: ampConfig.Auth!.Cognito as CognitoIdentityPoolConfig, identityIdStore: mockDefaultIdentityIdStoreInstance, - }) + }), ).toBe(authAPITestParams.GuestIdentityId.id); expect(mockGetId).toHaveBeenCalledTimes(0); }); @@ -80,13 +80,13 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { mockDefaultIdentityIdStoreInstance.loadIdentityId.mockImplementationOnce( async () => { return undefined; - } + }, ); mockDefaultIdentityIdStoreInstance.storeIdentityId.mockImplementationOnce( async (identity: Identity) => { expect(identity.id).toBe(authAPITestParams.GuestIdentityId.id); expect(identity.type).toBe(authAPITestParams.GuestIdentityId.type); - } + }, ); expect( await cognitoIdentityIdProvider({ @@ -94,7 +94,7 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { identityPoolId: 'us-east-1:test-id', }, identityIdStore: mockDefaultIdentityIdStoreInstance, - }) + }), ).toBe(authAPITestParams.GuestIdentityId.id); expect(mockGetId).toHaveBeenCalledTimes(1); }); @@ -102,14 +102,14 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { mockDefaultIdentityIdStoreInstance.loadIdentityId.mockImplementationOnce( async () => { return authAPITestParams.PrimaryIdentityId as Identity; - } + }, ); expect( await cognitoIdentityIdProvider({ authConfig: ampConfig.Auth!.Cognito as CognitoIdentityPoolConfig, tokens: authAPITestParams.ValidAuthTokens, identityIdStore: mockDefaultIdentityIdStoreInstance, - }) + }), ).toBe(authAPITestParams.PrimaryIdentityId.id); expect(mockGetId).toHaveBeenCalledTimes(0); }); @@ -117,13 +117,13 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { mockDefaultIdentityIdStoreInstance.loadIdentityId.mockImplementationOnce( async () => { return undefined; - } + }, ); mockDefaultIdentityIdStoreInstance.storeIdentityId.mockImplementationOnce( async (identity: Identity) => { expect(identity.id).toBe(authAPITestParams.PrimaryIdentityId.id); expect(identity.type).toBe(authAPITestParams.PrimaryIdentityId.type); - } + }, ); expect( await cognitoIdentityIdProvider({ @@ -132,7 +132,7 @@ describe('Cognito IdentityId Provider Happy Path Cases:', () => { identityPoolId: 'us-east-1:test-id', }, identityIdStore: mockDefaultIdentityIdStoreInstance, - }) + }), ).toBe(authAPITestParams.PrimaryIdentityId.id); expect(mockGetId).toHaveBeenCalledTimes(1); }); diff --git a/packages/auth/__tests__/providers/cognito/identityIdStore.test.ts b/packages/auth/__tests__/providers/cognito/identityIdStore.test.ts index 21e44cc4b5d..f73e4a20c69 100644 --- a/packages/auth/__tests__/providers/cognito/identityIdStore.test.ts +++ b/packages/auth/__tests__/providers/cognito/identityIdStore.test.ts @@ -51,7 +51,7 @@ describe('DefaultIdentityIdStore', () => { defaultIdStore.storeIdentityId(validGuestIdentityId); expect(mockKeyValueStorage.setItem).toHaveBeenCalledWith( validAuthKey.identityId, - validGuestIdentityId.id + validGuestIdentityId.id, ); expect(defaultIdStore._primaryIdentityId).toBeUndefined(); }); @@ -59,27 +59,27 @@ describe('DefaultIdentityIdStore', () => { mockKeyValueStorage.getItem.mockReturnValue(validGuestIdentityId.id); expect(await defaultIdStore.loadIdentityId()).toEqual( - validGuestIdentityId + validGuestIdentityId, ); }); it('Should store primary identityId in keyValueStorage', async () => { defaultIdStore.storeIdentityId(validPrimaryIdentityId); expect(mockKeyValueStorage.removeItem).toHaveBeenCalledWith( - validAuthKey.identityId + validAuthKey.identityId, ); expect(defaultIdStore._primaryIdentityId).toEqual( - validPrimaryIdentityId.id + validPrimaryIdentityId.id, ); }); it('Should load primary identityId from keyValueStorage', async () => { expect(await defaultIdStore.loadIdentityId()).toEqual( - validPrimaryIdentityId + validPrimaryIdentityId, ); }); it('Should clear the cached identityId', async () => { defaultIdStore.clearIdentityId(); expect(mockKeyValueStorage.removeItem).toHaveBeenCalledWith( - validAuthKey.identityId + validAuthKey.identityId, ); expect(defaultIdStore._primaryIdentityId).toBeUndefined(); }); diff --git a/packages/auth/__tests__/providers/cognito/refreshToken.test.ts b/packages/auth/__tests__/providers/cognito/refreshToken.test.ts index 869bbcc5aff..0f17c07da3d 100644 --- a/packages/auth/__tests__/providers/cognito/refreshToken.test.ts +++ b/packages/auth/__tests__/providers/cognito/refreshToken.test.ts @@ -8,7 +8,7 @@ import { tokenRefreshException, } from '../../../src/providers/cognito/utils/types'; jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('refreshToken', () => { @@ -65,7 +65,7 @@ describe('refreshToken', () => { // stringify and re-parse for JWT equality expect(JSON.parse(JSON.stringify(response))).toMatchObject( - JSON.parse(JSON.stringify(expectedOutput)) + JSON.parse(JSON.stringify(expectedOutput)), ); expect(mockInitiateAuth).toHaveBeenCalledWith( expect.objectContaining({ region: 'us-east-1' }), @@ -75,7 +75,7 @@ describe('refreshToken', () => { AuthParameters: { REFRESH_TOKEN: mockedRefreshToken, }, - }) + }), ); }); @@ -89,10 +89,10 @@ describe('refreshToken', () => { username: 'username', tokens: { accessToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.YzDpgJsrB3z-ZU1XxMcXSQsMbgCzwH_e-_76rnfehh0' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.YzDpgJsrB3z-ZU1XxMcXSQsMbgCzwH_e-_76rnfehh0', ), idToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.YzDpgJsrB3z-ZU1XxMcXSQsMbgCzwH_e-_76rnfehh0' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.YzDpgJsrB3z-ZU1XxMcXSQsMbgCzwH_e-_76rnfehh0', ), clockDrift: 0, refreshToken: 'refreshtoken', @@ -112,7 +112,7 @@ describe('refreshToken', () => { AuthParameters: { REFRESH_TOKEN: 'refreshtoken' }, ClientId: 'aaaaaaaaaaaa', UserContextData: { EncodedData: 'abcd' }, - }) + }), ); window['AmazonCognitoAdvancedSecurityData'] = undefined; }); @@ -147,7 +147,7 @@ describe('refreshToken', () => { }, }, username: mockedUsername, - }) + }), ).rejects.toThrow(oAuthTokenRefreshException); }); it('should throw an exception when cognito tokens are not available', async () => { @@ -162,7 +162,7 @@ describe('refreshToken', () => { }, }, username: mockedUsername, - }) + }), ).rejects.toThrow(tokenRefreshException); }); @@ -183,7 +183,7 @@ describe('refreshToken', () => { }, }, username: mockedUsername, - }) + }), ).rejects.toThrow(mockedError); }); }); diff --git a/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts b/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts index 8979cc652a9..f8d228d27cf 100644 --- a/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts +++ b/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts @@ -21,7 +21,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); jest.mock('../../../src/providers/cognito/tokenProvider'); @@ -64,7 +64,7 @@ describe('rememberDevice', () => { AccessToken: mockAccessToken, DeviceKey: mockDeviceMetadata.deviceKey, DeviceRememberedStatus: 'remembered', - }) + }), ); expect(mockUpdateDeviceStatus).toHaveBeenCalledTimes(1); }); @@ -79,7 +79,7 @@ describe('rememberDevice', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - UpdateDeviceStatusException.InvalidParameterException + UpdateDeviceStatusException.InvalidParameterException, ); } }); diff --git a/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts b/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts index a1809ec4c80..f1c7fcd96bb 100644 --- a/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts +++ b/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts @@ -20,7 +20,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('resendSignUpCode', () => { @@ -34,7 +34,7 @@ describe('resendSignUpCode', () => { beforeEach(() => { mockResendConfirmationCode.mockResolvedValue( - authAPITestParams.resendSignUpClientResult + authAPITestParams.resendSignUpClientResult, ); }); @@ -56,7 +56,7 @@ describe('resendSignUpCode', () => { ClientMetadata: undefined, Username: user1.username, ClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - } + }, ); expect(mockResendConfirmationCode).toHaveBeenCalledTimes(1); }); @@ -81,7 +81,7 @@ describe('resendSignUpCode', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - ResendConfirmationException.InvalidParameterException + ResendConfirmationException.InvalidParameterException, ); } }); @@ -106,7 +106,7 @@ describe('resendSignUpCode', () => { Username: user1.username, ClientId: '111111-aaaaa-42d8-891d-ee81a1549398', UserContextData: { EncodedData: 'abcd' }, - } + }, ); expect(mockResendConfirmationCode).toHaveBeenCalledTimes(1); window['AmazonCognitoAdvancedSecurityData'] = undefined; diff --git a/packages/auth/__tests__/providers/cognito/resetPassword.test.ts b/packages/auth/__tests__/providers/cognito/resetPassword.test.ts index ca11c9c9339..2def52d2b1a 100644 --- a/packages/auth/__tests__/providers/cognito/resetPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/resetPassword.test.ts @@ -19,7 +19,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('resetPassword', () => { @@ -32,7 +32,7 @@ describe('resetPassword', () => { beforeEach(() => { mockForgotPassword.mockResolvedValue( - authAPITestParams.resetPasswordHttpCallResult + authAPITestParams.resetPasswordHttpCallResult, ); }); @@ -58,7 +58,7 @@ describe('resetPassword', () => { Username: 'username', ClientMetadata: { foo: 'foo' }, ClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - }) + }), ); }); @@ -69,7 +69,7 @@ describe('resetPassword', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - AuthValidationErrorCode.EmptyResetPasswordUsername + AuthValidationErrorCode.EmptyResetPasswordUsername, ); } }); @@ -84,7 +84,7 @@ describe('resetPassword', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - ForgotPasswordException.InvalidParameterException + ForgotPasswordException.InvalidParameterException, ); } }); @@ -108,7 +108,7 @@ describe('resetPassword', () => { ClientMetadata: { foo: 'foo' }, ClientId: '111111-aaaaa-42d8-891d-ee81a1549398', UserContextData: { EncodedData: 'abcd' }, - }) + }), ); window['AmazonCognitoAdvancedSecurityData'] = undefined; }); diff --git a/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts b/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts index 835b90b78c2..992afa5d606 100644 --- a/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts +++ b/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts @@ -20,7 +20,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('sendUserAttributeVerificationCode', () => { @@ -38,7 +38,7 @@ describe('sendUserAttributeVerificationCode', () => { beforeEach(() => { mockGetUserAttributeVerificationCode.mockResolvedValue( - authAPITestParams.resendSignUpClientResult + authAPITestParams.resendSignUpClientResult, ); }); @@ -62,7 +62,7 @@ describe('sendUserAttributeVerificationCode', () => { AccessToken: mockAccessToken, AttributeName: 'email', ClientMetadata: { foo: 'bar' }, - }) + }), ); expect(mockGetUserAttributeVerificationCode).toHaveBeenCalledTimes(1); }); @@ -71,7 +71,7 @@ describe('sendUserAttributeVerificationCode', () => { expect.assertions(2); mockGetUserAttributeVerificationCode.mockImplementation(() => { throw getMockError( - GetUserAttributeVerificationException.InvalidParameterException + GetUserAttributeVerificationException.InvalidParameterException, ); }); try { @@ -84,7 +84,7 @@ describe('sendUserAttributeVerificationCode', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - GetUserAttributeVerificationException.InvalidParameterException + GetUserAttributeVerificationException.InvalidParameterException, ); } }); diff --git a/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts b/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts index d3c76b99d32..06d350e1930 100644 --- a/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts +++ b/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts @@ -19,7 +19,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('setUpTOTP', () => { @@ -56,7 +56,7 @@ describe('setUpTOTP', () => { }, { AccessToken: mockAccessToken, - } + }, ); expect(result.sharedSecret).toEqual(secretCode); expect(result.getSetupUri('appName', 'amplify')).toBeInstanceOf(URL); @@ -66,7 +66,7 @@ describe('setUpTOTP', () => { expect.assertions(2); mockAssociateSoftwareToken.mockImplementation(() => { throw getMockError( - AssociateSoftwareTokenException.InvalidParameterException + AssociateSoftwareTokenException.InvalidParameterException, ); }); try { @@ -74,7 +74,7 @@ describe('setUpTOTP', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - AssociateSoftwareTokenException.InvalidParameterException + AssociateSoftwareTokenException.InvalidParameterException, ); } }); diff --git a/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts b/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts index 76d62551433..f406f53e195 100644 --- a/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts @@ -22,7 +22,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ })); jest.mock('../../../src/providers/cognito/apis/getCurrentUser'); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('signIn API error path cases:', () => { diff --git a/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts b/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts index c3daea90f67..5728b39c55b 100644 --- a/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInStateManagement.test.ts @@ -41,7 +41,7 @@ describe('local sign-in state management tests', () => { CODE_DELIVERY_DELIVERY_MEDIUM: 'SMS', CODE_DELIVERY_DESTINATION: '*******9878', }, - }) + }), ); Amplify.configure({ @@ -73,7 +73,7 @@ describe('local sign-in state management tests', () => { .spyOn(signInHelpers, 'handleUserSRPAuthFlow') .mockImplementationOnce( async (): Promise => - authAPITestParams.RespondToAuthChallengeCommandOutput + authAPITestParams.RespondToAuthChallengeCommandOutput, ); Amplify.configure({ diff --git a/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts b/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts index d6a13b60801..b2c15cc389a 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithCustomAuth.test.ts @@ -40,7 +40,7 @@ describe('signIn API happy path cases', () => { .spyOn(initiateAuthHelpers, 'handleCustomAuthFlowWithoutSRP') .mockImplementationOnce( async (): Promise => - authAPITestParams.CustomChallengeResponse + authAPITestParams.CustomChallengeResponse, ); }); @@ -77,7 +77,7 @@ describe('signIn API happy path cases', () => { username, authAPITestParams.configWithClientMetadata.clientMetadata, authConfig.Cognito, - tokenOrchestrator + tokenOrchestrator, ); }); }); @@ -100,7 +100,7 @@ describe('Cognito ASF', () => { CODE_DELIVERY_DELIVERY_MEDIUM: 'SMS', CODE_DELIVERY_DESTINATION: '*******9878', }, - }) + }), ); // load Cognito ASF polyfill window['AmazonCognitoAdvancedSecurityData'] = { @@ -132,7 +132,7 @@ describe('Cognito ASF', () => { ClientId: '111111-aaaaa-42d8-891d-ee81a1549398', ClientMetadata: undefined, UserContextData: { EncodedData: 'abcd' }, - } + }, ); }); }); diff --git a/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts b/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts index 869ae829bec..84a09260ee8 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithCustomSRPAuth.test.ts @@ -38,7 +38,7 @@ describe('signIn API happy path cases', () => { .mockImplementationOnce( async (): Promise => { return authAPITestParams.CustomChallengeResponse; - } + }, ); }); @@ -84,7 +84,7 @@ describe('signIn API happy path cases', () => { password, authAPITestParams.configWithClientMetadata.clientMetadata, authConfig.Cognito, - tokenOrchestrator + tokenOrchestrator, ); }); }); @@ -139,7 +139,7 @@ describe('Cognito ASF', () => { UserContextData: { EncodedData: 'abcd', }, - }) + }), ); }); }); diff --git a/packages/auth/__tests__/providers/cognito/signInWithRedirect.test.ts b/packages/auth/__tests__/providers/cognito/signInWithRedirect.test.ts index 7d11bb49129..dd95636e20b 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithRedirect.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithRedirect.test.ts @@ -37,7 +37,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ })); jest.mock('@aws-amplify/core', () => { const { ADD_OAUTH_LISTENER } = jest.requireActual( - '@aws-amplify/core/internals/utils' + '@aws-amplify/core/internals/utils', ); return { Amplify: { @@ -129,7 +129,7 @@ describe('signInWithRedirect', () => { expect(mockAssertTokenProviderConfig).toHaveBeenCalledTimes(1); expect(mockAssertOAuthConfig).toHaveBeenCalledTimes(1); expect(oAuthStore.setAuthConfig).toHaveBeenCalledWith( - mockAuthConfigWithOAuth.Auth.Cognito + mockAuthConfigWithOAuth.Auth.Cognito, ); expect(mockAssertUserNotAuthenticated).toHaveBeenCalledTimes(1); @@ -144,10 +144,10 @@ describe('signInWithRedirect', () => { const [oauthUrl, redirectSignIn, preferPrivateSession] = mockOpenAuthSession.mock.calls[0]; expect(oauthUrl).toStrictEqual( - 'https://oauth.domain.com/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&response_type=code&client_id=userPoolClientId&identity_provider=Google&scope=phone%20email%20openid%20profile%20aws.cognito.signin.user.admin&state=oauth_state&code_challenge=code_challenge&code_challenge_method=S256' + 'https://oauth.domain.com/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&response_type=code&client_id=userPoolClientId&identity_provider=Google&scope=phone%20email%20openid%20profile%20aws.cognito.signin.user.admin&state=oauth_state&code_challenge=code_challenge&code_challenge_method=S256', ); expect(redirectSignIn).toEqual( - mockAuthConfigWithOAuth.Auth.Cognito.loginWith.oauth.redirectSignIn + mockAuthConfigWithOAuth.Auth.Cognito.loginWith.oauth.redirectSignIn, ); expect(preferPrivateSession).toBeUndefined(); }); @@ -157,7 +157,7 @@ describe('signInWithRedirect', () => { await signInWithRedirect(); const [oauthUrl] = mockOpenAuthSession.mock.calls[0]; expect(oauthUrl).toStrictEqual( - `https://oauth.domain.com/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&response_type=code&client_id=userPoolClientId&identity_provider=${expectedDefaultProvider}&scope=phone%20email%20openid%20profile%20aws.cognito.signin.user.admin&state=oauth_state&code_challenge=code_challenge&code_challenge_method=S256` + `https://oauth.domain.com/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&response_type=code&client_id=userPoolClientId&identity_provider=${expectedDefaultProvider}&scope=phone%20email%20openid%20profile%20aws.cognito.signin.user.admin&state=oauth_state&code_challenge=code_challenge&code_challenge_method=S256`, ); }); @@ -166,7 +166,7 @@ describe('signInWithRedirect', () => { await signInWithRedirect({ provider: { custom: expectedCustomProvider } }); const [oauthUrl] = mockOpenAuthSession.mock.calls[0]; expect(oauthUrl).toStrictEqual( - `https://oauth.domain.com/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&response_type=code&client_id=userPoolClientId&identity_provider=${expectedCustomProvider}&scope=phone%20email%20openid%20profile%20aws.cognito.signin.user.admin&state=oauth_state&code_challenge=code_challenge&code_challenge_method=S256` + `https://oauth.domain.com/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&response_type=code&client_id=userPoolClientId&identity_provider=${expectedCustomProvider}&scope=phone%20email%20openid%20profile%20aws.cognito.signin.user.admin&state=oauth_state&code_challenge=code_challenge&code_challenge_method=S256`, ); }); @@ -180,11 +180,11 @@ describe('signInWithRedirect', () => { describe('side effect', () => { it('attaches oauth listener to the Amplify singleton', async () => { (oAuthStore.loadOAuthInFlight as jest.Mock).mockResolvedValueOnce( - false + false, ); expect(Amplify[ADD_OAUTH_LISTENER]).toHaveBeenCalledWith( - attemptCompleteOAuthFlow + attemptCompleteOAuthFlow, ); }); }); @@ -207,7 +207,7 @@ describe('signInWithRedirect', () => { expect.objectContaining({ currentUrl: mockOpenAuthSessionResult.url, preferPrivateSession: true, - }) + }), ); expect(mockGetAuthUserAgentValue).toHaveBeenCalledTimes(1); }); @@ -225,14 +225,14 @@ describe('signInWithRedirect', () => { signInWithRedirect({ provider: 'Google', options: { preferPrivateSession: true }, - }) + }), ).rejects.toThrow(mockOpenAuthSessionResult.error); expect(mockCreateOAuthError).toHaveBeenCalledWith( - String(mockOpenAuthSessionResult.error) + String(mockOpenAuthSessionResult.error), ); expect(mockHandleFailure).toHaveBeenCalledWith( - mockOpenAuthSessionResult.error + mockOpenAuthSessionResult.error, ); }); @@ -249,13 +249,13 @@ describe('signInWithRedirect', () => { signInWithRedirect({ provider: 'Google', options: { preferPrivateSession: true }, - }) + }), ).rejects.toThrow(expectedError); expect(mockCompleteOAuthFlow).toHaveBeenCalledWith( expect.objectContaining({ currentUrl: mockOpenAuthSessionResult.url, - }) + }), ); expect(mockHandleFailure).toHaveBeenCalledWith(expectedError); }); diff --git a/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts b/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts index 38936c7222e..47f4d000e10 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithSRP.test.ts @@ -41,18 +41,18 @@ const mockedDeviceMetadata = { const lastAuthUser = 'lastAuthUser'; const authKeys = createKeysForAuthStorage( 'CognitoIdentityServiceProvider', - `${authConfig.Cognito.userPoolClientId}.${lastAuthUser}` + `${authConfig.Cognito.userPoolClientId}.${lastAuthUser}`, ); function setDeviceKeys() { localStorage.setItem(authKeys.deviceKey, mockedDeviceMetadata.deviceKey); localStorage.setItem( authKeys.deviceGroupKey, - mockedDeviceMetadata.deviceGrouKey + mockedDeviceMetadata.deviceGrouKey, ); localStorage.setItem( authKeys.randomPasswordKey, - mockedDeviceMetadata.randomPasswordKey + mockedDeviceMetadata.randomPasswordKey, ); } @@ -64,7 +64,7 @@ describe('signIn API happy path cases', () => { .spyOn(initiateAuthHelpers, 'handleUserSRPAuthFlow') .mockImplementation( async (): Promise => - authAPITestParams.RespondToAuthChallengeCommandOutput + authAPITestParams.RespondToAuthChallengeCommandOutput, ); }); @@ -93,7 +93,7 @@ describe('signIn API happy path cases', () => { Session: 'aaabbbcccddd', $metadata: {}, }; - } + }, ); const result = await signIn({ @@ -159,7 +159,7 @@ describe('signIn API happy path cases', () => { password, authAPITestParams.configWithClientMetadata.clientMetadata, authConfig.Cognito, - tokenOrchestrator + tokenOrchestrator, ); }); }); @@ -211,7 +211,7 @@ describe('Cognito ASF', () => { UserContextData: { EncodedData: 'abcd', }, - }) + }), ); }); }); diff --git a/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts b/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts index bc49ea94e8c..1faa62e2730 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithUserPassword.test.ts @@ -37,7 +37,7 @@ describe('signIn API happy path cases', () => { .spyOn(initiateAuthHelpers, 'handleUserPasswordAuthFlow') .mockImplementationOnce( async (): Promise => - authAPITestParams.RespondToAuthChallengeCommandOutput + authAPITestParams.RespondToAuthChallengeCommandOutput, ); }); @@ -70,7 +70,7 @@ describe('signIn API happy path cases', () => { password, authAPITestParams.configWithClientMetadata.clientMetadata, authConfig.Cognito, - tokenOrchestrator + tokenOrchestrator, ); }); }); @@ -125,7 +125,7 @@ describe('Cognito ASF', () => { UserContextData: { EncodedData: 'abcd', }, - }) + }), ); }); }); diff --git a/packages/auth/__tests__/providers/cognito/signOut.test.ts b/packages/auth/__tests__/providers/cognito/signOut.test.ts index 63fb94c0f16..6a6f27106b7 100644 --- a/packages/auth/__tests__/providers/cognito/signOut.test.ts +++ b/packages/auth/__tests__/providers/cognito/signOut.test.ts @@ -22,10 +22,10 @@ import { AuthTokenStore } from '../../../src/providers/cognito/tokenProvider/typ jest.mock('@aws-amplify/core'); jest.mock('../../../src/providers/cognito/tokenProvider'); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/utils' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider/utils', ); jest.mock('../../../src/providers/cognito/utils/oauth'); jest.mock('../../../src/providers/cognito/utils/signInWithRedirectStore'); @@ -80,7 +80,7 @@ describe('signOut', () => { 'auth', { event: 'signedOut' }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); }, not: { @@ -95,7 +95,7 @@ describe('signOut', () => { beforeAll(() => { mockGetRegion.mockReturnValue(region); MockDefaultOAuthStore.mockImplementation( - () => mockDefaultOAuthStoreInstance + () => mockDefaultOAuthStoreInstance, ); }); @@ -124,7 +124,7 @@ describe('signOut', () => { expect(mockRevokeToken).toHaveBeenCalledWith( { region }, - { ClientId: cognitoConfig.userPoolClientId, Token: refreshToken } + { ClientId: cognitoConfig.userPoolClientId, Token: refreshToken }, ); expect(mockGetRegion).toHaveBeenCalledTimes(1); expect(mockGlobalSignOut).not.toHaveBeenCalled(); @@ -150,7 +150,7 @@ describe('signOut', () => { expect(mockGlobalSignOut).toHaveBeenCalledWith( { region: 'us-west-2' }, - { AccessToken: accessToken.toString() } + { AccessToken: accessToken.toString() }, ); expect(mockGetRegion).toHaveBeenCalledTimes(1); expect(mockRevokeToken).not.toHaveBeenCalled(); @@ -163,7 +163,7 @@ describe('signOut', () => { await signOut(); expect(loggerDebugSpy).toHaveBeenCalledWith( - expect.stringContaining('Client signOut error caught') + expect.stringContaining('Client signOut error caught'), ); expect(mockGetRegion).toHaveBeenCalledTimes(1); expectSignOut().toComplete(); @@ -175,7 +175,7 @@ describe('signOut', () => { await signOut({ global: true }); expect(loggerDebugSpy).toHaveBeenCalledWith( - expect.stringContaining('Global signOut error caught') + expect.stringContaining('Global signOut error caught'), ); expect(mockGetRegion).toHaveBeenCalledTimes(1); expectSignOut().toComplete(); @@ -213,11 +213,11 @@ describe('signOut', () => { expect(MockDefaultOAuthStore).toHaveBeenCalledTimes(1); expect(mockDefaultOAuthStoreInstance.setAuthConfig).toHaveBeenCalledWith( - cognitoConfigWithOauth + cognitoConfigWithOauth, ); expect(mockHandleOAuthSignOut).toHaveBeenCalledWith( cognitoConfigWithOauth, - mockDefaultOAuthStoreInstance + mockDefaultOAuthStoreInstance, ); // In cases of OAuth, token removal and Hub dispatch should be performed by the OAuth handling since // these actions can be deferred or canceled out of altogether. diff --git a/packages/auth/__tests__/providers/cognito/signUp.test.ts b/packages/auth/__tests__/providers/cognito/signUp.test.ts index bc87d00dae0..bccf0af0078 100644 --- a/packages/auth/__tests__/providers/cognito/signUp.test.ts +++ b/packages/auth/__tests__/providers/cognito/signUp.test.ts @@ -20,7 +20,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('signUp', () => { @@ -72,7 +72,7 @@ describe('signUp', () => { Username: user1.username, ValidationData: undefined, ClientId: '111111-aaaaa-42d8-891d-ee81a1549398', - } + }, ); expect(mockSignUp).toHaveBeenCalledTimes(1); }); diff --git a/packages/auth/__tests__/providers/cognito/testUtils/authApiTestParams.ts b/packages/auth/__tests__/providers/cognito/testUtils/authApiTestParams.ts index 23e580d2e5f..aaf11d8ee08 100644 --- a/packages/auth/__tests__/providers/cognito/testUtils/authApiTestParams.ts +++ b/packages/auth/__tests__/providers/cognito/testUtils/authApiTestParams.ts @@ -148,10 +148,10 @@ export const authAPITestParams = { // Test values ValidAuthTokens: { idToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIHRoZSBzZWNvbmQiLCJpYXQiOjE1MTYyMzkwMjIsImlzcyI6Imh0dHBzOi8vdGVzdC5jb20iLCJleHAiOjE3MTAyOTMxMzB9.kpvsHfKH4JvCecECmb26Pl6HaedVX7PNiiF_8AlAbYc' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIHRoZSBzZWNvbmQiLCJpYXQiOjE1MTYyMzkwMjIsImlzcyI6Imh0dHBzOi8vdGVzdC5jb20iLCJleHAiOjE3MTAyOTMxMzB9.kpvsHfKH4JvCecECmb26Pl6HaedVX7PNiiF_8AlAbYc', ), accessToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIHRoZSBzZWNvbmQiLCJpYXQiOjE1MTYyMzkwMjIsImlzcyI6Imh0dHBzOi8vdGVzdC5jb20iLCJleHAiOjE3MTAyOTMxMzB9.kpvsHfKH4JvCecECmb26Pl6HaedVX7PNiiF_8AlAbYc' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIHRoZSBzZWNvbmQiLCJpYXQiOjE1MTYyMzkwMjIsImlzcyI6Imh0dHBzOi8vdGVzdC5jb20iLCJleHAiOjE3MTAyOTMxMzB9.kpvsHfKH4JvCecECmb26Pl6HaedVX7PNiiF_8AlAbYc', ), accessTokenExpAt: Date.UTC(2023, 8, 24, 18, 55), clockDrift: undefined, @@ -159,10 +159,10 @@ export const authAPITestParams = { }, ExpiredAuthTokens: { idToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTAyOTMxMzB9.1o9dQV9035dCO0nKDgZ-MwFf22Ptmysymt2ENyR5Mko' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTAyOTMxMzB9.1o9dQV9035dCO0nKDgZ-MwFf22Ptmysymt2ENyR5Mko', ), accessToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTAyOTMxMzB9.1o9dQV9035dCO0nKDgZ-MwFf22Ptmysymt2ENyR5Mko' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTAyOTMxMzB9.1o9dQV9035dCO0nKDgZ-MwFf22Ptmysymt2ENyR5Mko', ), accessTokenExpAt: Date.UTC(2023, 8, 24, 18, 55), clockDrift: undefined, @@ -170,10 +170,10 @@ export const authAPITestParams = { }, NewValidAuthTokens: { idToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIHRoZSBzZWNvbmQiLCJpYXQiOjE1MTYyMzkwMjIsImlzcyI6Imh0dHBzOi8vdGVzdC5jb20ifQ.5eGzqDYCAYmagLpVDc1kqRT1da1wPu0_1FAg6ZNAuj8' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIHRoZSBzZWNvbmQiLCJpYXQiOjE1MTYyMzkwMjIsImlzcyI6Imh0dHBzOi8vdGVzdC5jb20ifQ.5eGzqDYCAYmagLpVDc1kqRT1da1wPu0_1FAg6ZNAuj8', ), accessToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIHRoZSBzZWNvbmQiLCJpYXQiOjE1MTYyMzkwMjIsImlzcyI6Imh0dHBzOi8vdGVzdC5jb20ifQ.5eGzqDYCAYmagLpVDc1kqRT1da1wPu0_1FAg6ZNAuj8' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIHRoZSBzZWNvbmQiLCJpYXQiOjE1MTYyMzkwMjIsImlzcyI6Imh0dHBzOi8vdGVzdC5jb20ifQ.5eGzqDYCAYmagLpVDc1kqRT1da1wPu0_1FAg6ZNAuj8', ), accessTokenExpAt: Date.UTC(2023, 8, 24, 18, 55), clockDrift: undefined, diff --git a/packages/auth/__tests__/providers/cognito/tokenOrchestrator.test.ts b/packages/auth/__tests__/providers/cognito/tokenOrchestrator.test.ts index 70d08deca59..0487e4fadbb 100644 --- a/packages/auth/__tests__/providers/cognito/tokenOrchestrator.test.ts +++ b/packages/auth/__tests__/providers/cognito/tokenOrchestrator.test.ts @@ -45,7 +45,7 @@ describe('TokenOrchestrator', () => { }); it('Should get tokens', async () => { mockAuthTokenStore.loadTokens.mockResolvedValue( - authAPITestParams.ValidAuthTokens + authAPITestParams.ValidAuthTokens, ); const tokensRes = await tokenOrchestrator.getTokens(); @@ -57,7 +57,7 @@ describe('TokenOrchestrator', () => { }); it('Should call tokenRefresher and return valid tokens', async () => { mockAuthTokenStore.loadTokens.mockResolvedValue( - authAPITestParams.ExpiredAuthTokens + authAPITestParams.ExpiredAuthTokens, ); mockTokenRefresher.mockResolvedValue(authAPITestParams.ValidAuthTokens); const tokensRes = await tokenOrchestrator.getTokens(); @@ -70,7 +70,7 @@ describe('TokenOrchestrator', () => { 'auth', { event: 'tokenRefresh' }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); }); }); diff --git a/packages/auth/__tests__/providers/cognito/tokenProvider.test.ts b/packages/auth/__tests__/providers/cognito/tokenProvider.test.ts index f9471e66640..73ad533a2aa 100644 --- a/packages/auth/__tests__/providers/cognito/tokenProvider.test.ts +++ b/packages/auth/__tests__/providers/cognito/tokenProvider.test.ts @@ -26,35 +26,35 @@ describe('Loading tokens', () => { const userSub = 'user123'; memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.LastAuthUser`, - userSub + userSub, ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub}.accessToken`, - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub}.idToken`, - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub}.refreshToken`, - 'dsasdasdasdasdasdasdasd' + 'dsasdasdasdasdasdasdasd', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub}.clockDrift`, - '10' + '10', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub}.deviceKey`, - 'device-key' + 'device-key', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub}.deviceGroupKey`, - 'device-group-key' + 'device-group-key', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub}.randomPasswordKey`, - 'random-password' + 'random-password', ); tokenStore.setKeyValueStorage(memoryStorage); @@ -67,10 +67,10 @@ describe('Loading tokens', () => { const result = await tokenStore.loadTokens(); expect(result?.accessToken.toString()).toBe( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y', ); expect(result?.idToken?.toString()).toBe( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y', ); expect(result?.clockDrift).toBe(10); expect(result?.refreshToken).toBe('dsasdasdasdasdasdasdasd'); @@ -96,10 +96,10 @@ describe('saving tokens', () => { const lastAuthUser = 'amplify@user'; await tokenStore.storeTokens({ accessToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.AAA' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.AAA', ), idToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.III' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.III', ), clockDrift: 150, refreshToken: 'refresh-token', @@ -113,53 +113,53 @@ describe('saving tokens', () => { expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.LastAuthUser` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.LastAuthUser`, + ), ).toBe(lastAuthUser); // Refreshed tokens expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.accessToken` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.accessToken`, + ), ).toBe( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.AAA' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.AAA', ); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.idToken` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.idToken`, + ), ).toBe( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.III' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.III', ); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.refreshToken` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.refreshToken`, + ), ).toBe('refresh-token'); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.clockDrift` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.clockDrift`, + ), ).toBe('150'); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.deviceKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.deviceKey`, + ), ).toBe('device-key2'); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.deviceGroupKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.deviceGroupKey`, + ), ).toBe('device-group-key2'); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.randomPasswordKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${lastAuthUser}.randomPasswordKey`, + ), ).toBe('random-password2'); }); it('should save tokens from store clear old tokens', async () => { @@ -170,35 +170,35 @@ describe('saving tokens', () => { memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.LastAuthUser`, - oldUserName + oldUserName, ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.accessToken`, - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.idToken`, - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.Y', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.refreshToken`, - 'dsasdasdasdasdasdasdasd' + 'dsasdasdasdasdasdasdasd', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.clockDrift`, - '10' + '10', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.deviceKey`, - 'device-key' + 'device-key', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.deviceGroupKey`, - 'device-group-key' + 'device-group-key', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.randomPasswordKey`, - 'random-password' + 'random-password', ); tokenStore.setKeyValueStorage(memoryStorage); @@ -211,10 +211,10 @@ describe('saving tokens', () => { await tokenStore.storeTokens({ accessToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.AAA' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.AAA', ), idToken: decodeJWT( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.III' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.III', ), clockDrift: 150, refreshToken: 'refresh-token', @@ -228,54 +228,54 @@ describe('saving tokens', () => { expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.LastAuthUser` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.LastAuthUser`, + ), ).toBe(oldUserName); // Refreshed tokens expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.accessToken` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.accessToken`, + ), ).toBe( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.AAA' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.AAA', ); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.idToken` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.idToken`, + ), ).toBe( - 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.III' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzAsInVzZXJuYW1lIjoiYW1wbGlmeUB1c2VyIn0.III', ); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.refreshToken` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.refreshToken`, + ), ).toBe('refresh-token'); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.clockDrift` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.clockDrift`, + ), ).toBe('150'); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.deviceKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.deviceKey`, + ), ).toBe('device-key2'); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.deviceGroupKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.deviceGroupKey`, + ), ).toBe('device-group-key2'); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.randomPasswordKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${oldUserName}.randomPasswordKey`, + ), ).toBe('random-password2'); }); }); @@ -295,32 +295,32 @@ describe('device tokens', () => { memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub1}.deviceKey`, - 'user1-device-key' + 'user1-device-key', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub1}.deviceGroupKey`, - 'user1-device-group-key' + 'user1-device-group-key', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub1}.randomPasswordKey`, - 'user1-random-password' + 'user1-random-password', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub2}.deviceKey`, - 'user2-device-key' + 'user2-device-key', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub2}.deviceGroupKey`, - 'user2-device-group-key' + 'user2-device-group-key', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub2}.randomPasswordKey`, - 'user2-random-password' + 'user2-random-password', ); memoryStorage.setItem( `CognitoIdentityServiceProvider.${userPoolClientId}.LastAuthUser`, - userSub2 + userSub2, ); tokenStore.setKeyValueStorage(memoryStorage); @@ -348,41 +348,41 @@ describe('device tokens', () => { await tokenStore.clearDeviceMetadata(userSub1); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub1}.deviceKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub1}.deviceKey`, + ), ).toBeUndefined(); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub1}.deviceGroupKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub1}.deviceGroupKey`, + ), ).toBeUndefined(); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub1}.randomPasswordKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub1}.randomPasswordKey`, + ), ).toBeUndefined(); expect( // userSub1 cleared, userSub2 not cleared await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub2}.randomPasswordKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub2}.randomPasswordKey`, + ), ).not.toBeUndefined(); await tokenStore.clearDeviceMetadata(); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub2}.deviceKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub2}.deviceKey`, + ), ).toBeUndefined(); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub2}.deviceGroupKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub2}.deviceGroupKey`, + ), ).toBeUndefined(); expect( await memoryStorage.getItem( - `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub2}.randomPasswordKey` - ) + `CognitoIdentityServiceProvider.${userPoolClientId}.${userSub2}.randomPasswordKey`, + ), ).toBeUndefined(); }); }); diff --git a/packages/auth/__tests__/providers/cognito/tokenProvider/tokenOrchestrator.test.ts b/packages/auth/__tests__/providers/cognito/tokenProvider/tokenOrchestrator.test.ts index a9bdbcaca73..577b648cbb3 100644 --- a/packages/auth/__tests__/providers/cognito/tokenProvider/tokenOrchestrator.test.ts +++ b/packages/auth/__tests__/providers/cognito/tokenProvider/tokenOrchestrator.test.ts @@ -64,7 +64,7 @@ describe('tokenOrchestrator', () => { expect.objectContaining({ tokens: testInputTokens, username: testUsername, - }) + }), ); // async #2 expect(mockTokenStore.storeTokens).toHaveBeenCalledWith(mockTokens); diff --git a/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts b/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts index 0135a2f9710..699158449e6 100644 --- a/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts +++ b/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts @@ -24,7 +24,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); const mfaChoices: UpdateMFAPreferenceInput[] = [ @@ -82,16 +82,16 @@ describe('updateMFAPreference', () => { AccessToken: mockAccessToken, SMSMfaSettings: getMFASettings(sms), SoftwareTokenMfaSettings: getMFASettings(totp), - } + }, ); - } + }, ); it('should throw an error when service returns an error response', async () => { expect.assertions(2); mockSetUserMFAPreference.mockImplementation(() => { throw getMockError( - SetUserMFAPreferenceException.InvalidParameterException + SetUserMFAPreferenceException.InvalidParameterException, ); }); try { @@ -99,7 +99,7 @@ describe('updateMFAPreference', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - SetUserMFAPreferenceException.InvalidParameterException + SetUserMFAPreferenceException.InvalidParameterException, ); } }); diff --git a/packages/auth/__tests__/providers/cognito/updatePassword.test.ts b/packages/auth/__tests__/providers/cognito/updatePassword.test.ts index 21902fd76cf..978377eca52 100644 --- a/packages/auth/__tests__/providers/cognito/updatePassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/updatePassword.test.ts @@ -20,7 +20,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('updatePassword', () => { @@ -55,7 +55,7 @@ describe('updatePassword', () => { AccessToken: mockAccessToken, PreviousPassword: oldPassword, ProposedPassword: newPassword, - }) + }), ); }); @@ -90,7 +90,7 @@ describe('updatePassword', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - ChangePasswordException.InvalidParameterException + ChangePasswordException.InvalidParameterException, ); } }); diff --git a/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts index b30d123e1cf..3128767bd5c 100644 --- a/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts @@ -20,7 +20,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('updateUserAttributes', () => { @@ -115,7 +115,7 @@ describe('updateUserAttributes', () => { AccessToken: mockAccessToken, UserAttributes: toAttributeType(userAttributes), ClientMetadata: { foo: 'bar' }, - }) + }), ); }); @@ -152,7 +152,7 @@ describe('updateUserAttributes', () => { AccessToken: mockAccessToken, UserAttributes: toAttributeType(userAttributes), ClientMetadata: { foo: 'bar' }, - }) + }), ); }); @@ -212,7 +212,7 @@ describe('updateUserAttributes', () => { AccessToken: mockAccessToken, UserAttributes: toAttributeType(userAttributes), ClientMetadata: { foo: 'bar' }, - }) + }), ); }); @@ -220,7 +220,7 @@ describe('updateUserAttributes', () => { expect.assertions(2); mockUpdateUserAttributes.mockImplementation(() => { throw getMockError( - UpdateUserAttributesException.InvalidParameterException + UpdateUserAttributesException.InvalidParameterException, ); }); try { @@ -235,7 +235,7 @@ describe('updateUserAttributes', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - UpdateUserAttributesException.InvalidParameterException + UpdateUserAttributesException.InvalidParameterException, ); } }); diff --git a/packages/auth/__tests__/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.test.ts b/packages/auth/__tests__/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.test.ts index e9d916eb62f..251352cf033 100644 --- a/packages/auth/__tests__/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.test.ts +++ b/packages/auth/__tests__/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.test.ts @@ -36,7 +36,7 @@ jest.mock( clearOAuthData: jest.fn(), clearOAuthInflightData: jest.fn(), } as OAuthStore, - }) + }), ); jest.mock( '../../../../../src/providers/cognito/tokenProvider/tokenProvider', @@ -44,13 +44,13 @@ jest.mock( cognitoUserPoolsTokenProvider: { setWaitForInflightOAuth: jest.fn(), }, - }) + }), ); jest.mock( '../../../../../src/providers/cognito/utils/oauth/inflightPromise', () => ({ addInflightPromise: jest.fn(), - }) + }), ); const mockAssertOAuthConfig = assertOAuthConfig as jest.Mock; @@ -75,7 +75,7 @@ describe('attemptCompleteOAuthFlow', () => { origin: 'http://localhost:3000', pathname: undefined, }, - }) as any + }) as any, ); }); @@ -117,11 +117,11 @@ describe('attemptCompleteOAuthFlow', () => { expect.objectContaining({ currentUrl: 'http://localhost:3000/', redirectUri: 'http://localhost:3000/', - }) + }), ); expect( - cognitoUserPoolsTokenProvider.setWaitForInflightOAuth + cognitoUserPoolsTokenProvider.setWaitForInflightOAuth, ).toHaveBeenCalledTimes(1); expect(mockAddInflightPromise).toHaveBeenCalledTimes(1); @@ -143,7 +143,7 @@ describe('attemptCompleteOAuthFlow', () => { throw new Error('some error'); }); expect( - attemptCompleteOAuthFlow(mockAuthConfigWithOAuth.Auth.Cognito) + attemptCompleteOAuthFlow(mockAuthConfigWithOAuth.Auth.Cognito), ).resolves.toBeUndefined(); }); }); diff --git a/packages/auth/__tests__/providers/cognito/utils/oauth/completeOAuthFlow.test.ts b/packages/auth/__tests__/providers/cognito/utils/oauth/completeOAuthFlow.test.ts index bbfe51e28ea..761d2de05df 100644 --- a/packages/auth/__tests__/providers/cognito/utils/oauth/completeOAuthFlow.test.ts +++ b/packages/auth/__tests__/providers/cognito/utils/oauth/completeOAuthFlow.test.ts @@ -42,7 +42,7 @@ jest.mock( clearOAuthData: jest.fn(), clearOAuthInflightData: jest.fn(), } as OAuthStore, - }) + }), ); jest.mock( '../../../../../src/providers/cognito/tokenProvider/tokenProvider', @@ -50,7 +50,7 @@ jest.mock( cognitoUserPoolsTokenProvider: { setWaitForInflightOAuth: jest.fn(), }, - }) + }), ); const mockHandleFailure = handleFailure as jest.Mock; @@ -66,7 +66,7 @@ describe('completeOAuthFlow', () => { let windowSpy = jest.spyOn(window, 'window', 'get'); const mockFetch = jest.fn(); const mockReplaceState = jest.fn(); - + beforeAll(() => { (global as any).fetch = mockFetch; windowSpy.mockImplementation( @@ -74,9 +74,9 @@ describe('completeOAuthFlow', () => { ({ history: { replaceState: mockReplaceState, - state:'http://localhost:3000/?code=aaaa-111-222&state=aaaaa' + state: 'http://localhost:3000/?code=aaaa-111-222&state=aaaaa', }, - }) as any + }) as any, ); }); @@ -107,7 +107,7 @@ describe('completeOAuthFlow', () => { redirectUri: 'http://localhost:3000/', responseType: 'code', domain: 'localhost:3000', - }) + }), ).rejects.toThrow(expectedErrorMessage); }); @@ -127,7 +127,7 @@ describe('completeOAuthFlow', () => { completeOAuthFlow({ ...testInput, currentUrl: `http://localhost:3000?state=someState123`, - }) + }), ).rejects.toThrow('User cancelled OAuth flow.'); }); @@ -136,7 +136,7 @@ describe('completeOAuthFlow', () => { completeOAuthFlow({ ...testInput, currentUrl: `http://localhost:3000?code=123`, - }) + }), ).rejects.toThrow('User cancelled OAuth flow.'); }); @@ -150,7 +150,7 @@ describe('completeOAuthFlow', () => { }); await expect(completeOAuthFlow(testInput)).rejects.toThrow( - expectedErrorMessage + expectedErrorMessage, ); expect(mockValidateState).toHaveBeenCalledWith(expectedState); }); @@ -182,7 +182,7 @@ describe('completeOAuthFlow', () => { expect.objectContaining({ method: 'POST', body: 'grant_type=authorization_code&code=12345&client_id=clientId&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F&code_verifier=pkce23234a', - }) + }), ); expect(mockCacheCognitoTokens).toHaveBeenLastCalledWith({ username: 'testuser', @@ -195,7 +195,7 @@ describe('completeOAuthFlow', () => { expect(mockReplaceState).toHaveBeenCalledWith( 'http://localhost:3000/?code=aaaa-111-222&state=aaaaa', '', - testInput.redirectUri + testInput.redirectUri, ); expect(oAuthStore.clearOAuthData).toHaveBeenCalledTimes(1); @@ -216,7 +216,7 @@ describe('completeOAuthFlow', () => { }); expect(completeOAuthFlow(testInput)).rejects.toThrow( - mockError.error_message + mockError.error_message, ); }); }); @@ -237,7 +237,7 @@ describe('completeOAuthFlow', () => { completeOAuthFlow({ ...testInput, currentUrl: `http://localhost:3000#error_description=${expectedErrorMessage}&error=invalid_request`, - }) + }), ).rejects.toThrow(expectedErrorMessage); }); @@ -246,7 +246,7 @@ describe('completeOAuthFlow', () => { completeOAuthFlow({ ...testInput, currentUrl: `http://localhost:3000#`, - }) + }), ).rejects.toThrow('No access token returned from OAuth flow.'); }); @@ -260,7 +260,7 @@ describe('completeOAuthFlow', () => { }); await expect(completeOAuthFlow(testInput)).rejects.toThrow( - expectedErrorMessage + expectedErrorMessage, ); }); @@ -293,7 +293,7 @@ describe('completeOAuthFlow', () => { expect(oAuthStore.storeOAuthSignIn).toHaveBeenCalledWith(true, undefined); expect(mockResolveAndClearInflightPromises).toHaveBeenCalledTimes(1); expect( - cognitoUserPoolsTokenProvider.setWaitForInflightOAuth + cognitoUserPoolsTokenProvider.setWaitForInflightOAuth, ).toHaveBeenCalledTimes(1); const waitForInflightOAuth = ( @@ -306,7 +306,7 @@ describe('completeOAuthFlow', () => { expect(mockReplaceState).toHaveBeenCalledWith( 'http://localhost:3000/?code=aaaa-111-222&state=aaaaa', '', - testInput.redirectUri + testInput.redirectUri, ); }); }); diff --git a/packages/auth/__tests__/providers/cognito/utils/oauth/completeOAuthSignOut.test.ts b/packages/auth/__tests__/providers/cognito/utils/oauth/completeOAuthSignOut.test.ts index 0fde8a1cf9a..c8d9471f386 100644 --- a/packages/auth/__tests__/providers/cognito/utils/oauth/completeOAuthSignOut.test.ts +++ b/packages/auth/__tests__/providers/cognito/utils/oauth/completeOAuthSignOut.test.ts @@ -48,7 +48,7 @@ describe('completeOAuthSignOut', () => { 'auth', { event: 'signedOut' }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); }); }); diff --git a/packages/auth/__tests__/providers/cognito/utils/oauth/handleOAuthSignOut.native.test.ts b/packages/auth/__tests__/providers/cognito/utils/oauth/handleOAuthSignOut.native.test.ts index ec4acbc8130..3d56cca1b90 100644 --- a/packages/auth/__tests__/providers/cognito/utils/oauth/handleOAuthSignOut.native.test.ts +++ b/packages/auth/__tests__/providers/cognito/utils/oauth/handleOAuthSignOut.native.test.ts @@ -7,10 +7,10 @@ import { oAuthSignOutRedirect } from '../../../../../src/providers/cognito/utils import { DefaultOAuthStore } from '../../../../../src/providers/cognito/utils/signInWithRedirectStore'; jest.mock( - '../../../../../src/providers/cognito/utils/oauth/completeOAuthSignOut' + '../../../../../src/providers/cognito/utils/oauth/completeOAuthSignOut', ); jest.mock( - '../../../../../src/providers/cognito/utils/oauth/oAuthSignOutRedirect' + '../../../../../src/providers/cognito/utils/oauth/oAuthSignOutRedirect', ); describe('handleOAuthSignOut (native)', () => { @@ -47,7 +47,7 @@ describe('handleOAuthSignOut (native)', () => { expect(mockOAuthSignOutRedirect).toHaveBeenCalledWith( cognitoConfig, - false + false, ); expect(mockCompleteOAuthSignOut).toHaveBeenCalledWith(mockStore); }); @@ -58,7 +58,7 @@ describe('handleOAuthSignOut (native)', () => { expect(mockOAuthSignOutRedirect).toHaveBeenCalledWith( cognitoConfig, - false + false, ); expect(mockCompleteOAuthSignOut).not.toHaveBeenCalled(); }); @@ -69,7 +69,7 @@ describe('handleOAuthSignOut (native)', () => { expect(mockOAuthSignOutRedirect).toHaveBeenCalledWith( cognitoConfig, - false + false, ); expect(mockCompleteOAuthSignOut).not.toHaveBeenCalled(); }); diff --git a/packages/auth/__tests__/providers/cognito/utils/oauth/handleOAuthSignOut.test.ts b/packages/auth/__tests__/providers/cognito/utils/oauth/handleOAuthSignOut.test.ts index cf48e7bbf86..f6fab30158f 100644 --- a/packages/auth/__tests__/providers/cognito/utils/oauth/handleOAuthSignOut.test.ts +++ b/packages/auth/__tests__/providers/cognito/utils/oauth/handleOAuthSignOut.test.ts @@ -7,10 +7,10 @@ import { oAuthSignOutRedirect } from '../../../../../src/providers/cognito/utils import { DefaultOAuthStore } from '../../../../../src/providers/cognito/utils/signInWithRedirectStore'; jest.mock( - '../../../../../src/providers/cognito/utils/oauth/completeOAuthSignOut' + '../../../../../src/providers/cognito/utils/oauth/completeOAuthSignOut', ); jest.mock( - '../../../../../src/providers/cognito/utils/oauth/oAuthSignOutRedirect' + '../../../../../src/providers/cognito/utils/oauth/oAuthSignOutRedirect', ); describe('handleOAuthSignOut', () => { diff --git a/packages/auth/__tests__/providers/cognito/utils/oauth/index.test.ts b/packages/auth/__tests__/providers/cognito/utils/oauth/index.test.ts index e8b548bd00f..510d5ad211a 100644 --- a/packages/auth/__tests__/providers/cognito/utils/oauth/index.test.ts +++ b/packages/auth/__tests__/providers/cognito/utils/oauth/index.test.ts @@ -124,7 +124,7 @@ describe('generateCodeVerifier', () => { it('removes padding char = from the encoded codeChallenge', () => { mockSha256DigestSync.mockReturnValueOnce('digest-result'); mockBase64EncoderConvert.mockReturnValueOnce( - 'base64EncodedCodeChallenge==' + 'base64EncodedCodeChallenge==', ); const codeVerifier = generateCodeVerifier(128); const result = codeVerifier.toCodeChallenge(); diff --git a/packages/auth/__tests__/providers/cognito/utils/oauth/oAuthSignOutRedirect.test.ts b/packages/auth/__tests__/providers/cognito/utils/oauth/oAuthSignOutRedirect.test.ts index cc92e7ae79e..18cedfa47a7 100644 --- a/packages/auth/__tests__/providers/cognito/utils/oauth/oAuthSignOutRedirect.test.ts +++ b/packages/auth/__tests__/providers/cognito/utils/oauth/oAuthSignOutRedirect.test.ts @@ -46,12 +46,12 @@ describe('oAuthSignOutRedirect', () => { await oAuthSignOutRedirect(authConfig); expect(mockGetRedirectUrl).toHaveBeenCalledWith( - authConfig.loginWith.oauth.redirectSignOut + authConfig.loginWith.oauth.redirectSignOut, ); expect(mockOpenAuthSession).toHaveBeenCalledWith( `https://${domain}/logout?client_id=${userPoolClientId}&logout_uri=${encodedSignOutRedirectUrl}`, authConfig.loginWith.oauth.redirectSignOut, - false + false, ); }); @@ -61,7 +61,7 @@ describe('oAuthSignOutRedirect', () => { expect(mockOpenAuthSession).toHaveBeenCalledWith( `https://${domain}/logout?client_id=${userPoolClientId}&logout_uri=${encodedSignOutRedirectUrl}`, authConfig.loginWith.oauth.redirectSignOut, - true + true, ); }); }); diff --git a/packages/auth/__tests__/providers/cognito/utils/oauth/validateState.test.ts b/packages/auth/__tests__/providers/cognito/utils/oauth/validateState.test.ts index ad0e0eeff4e..c0d357b53a0 100644 --- a/packages/auth/__tests__/providers/cognito/utils/oauth/validateState.test.ts +++ b/packages/auth/__tests__/providers/cognito/utils/oauth/validateState.test.ts @@ -28,7 +28,7 @@ jest.mock( clearOAuthData: jest.fn(), clearOAuthInflightData: jest.fn(), } as OAuthStore, - }) + }), ); describe('validateState', () => { diff --git a/packages/auth/__tests__/providers/cognito/utils/srp/AuthenticationHelper.test.ts b/packages/auth/__tests__/providers/cognito/utils/srp/AuthenticationHelper.test.ts index 60d01ef753d..0c8c9a847e5 100644 --- a/packages/auth/__tests__/providers/cognito/utils/srp/AuthenticationHelper.test.ts +++ b/packages/auth/__tests__/providers/cognito/utils/srp/AuthenticationHelper.test.ts @@ -104,7 +104,7 @@ describe('AuthenticationHelper', () => { await instance.generateHashDevice(deviceGroupKey, username); expect(mockGetHashFromData).toHaveBeenCalledWith( - `${deviceGroupKey}${username}:${randomString}` + `${deviceGroupKey}${username}:${randomString}`, ); expect(instance.getVerifierDevices()).toBeDefined(); }); @@ -115,7 +115,7 @@ describe('AuthenticationHelper', () => { }); await expect( - instance.generateHashDevice(deviceGroupKey, username) + instance.generateHashDevice(deviceGroupKey, username), ).rejects.toThrow(); }); }); @@ -159,7 +159,7 @@ describe('AuthenticationHelper', () => { password, serverBValue, salt, - }) + }), ).toBe(hkdfKey); expect(mockCalculateU).toHaveBeenCalledWith({ A, B: serverBValue }); expect(mockGetPaddedHex).toHaveBeenCalledWith(salt); @@ -185,7 +185,7 @@ describe('AuthenticationHelper', () => { password, serverBValue, salt, - }) + }), ).rejects.toThrow(); }); @@ -199,7 +199,7 @@ describe('AuthenticationHelper', () => { password, serverBValue, salt, - }) + }), ).rejects.toThrow(); }); @@ -210,7 +210,7 @@ describe('AuthenticationHelper', () => { password, serverBValue: BigInteger.ZERO, salt, - }) + }), ).rejects.toThrow('B cannot be zero'); }); }); diff --git a/packages/auth/__tests__/providers/cognito/utils/srp/calculate/calculateS.test.ts b/packages/auth/__tests__/providers/cognito/utils/srp/calculate/calculateS.test.ts index 5fde0d5e868..e7612828cfe 100644 --- a/packages/auth/__tests__/providers/cognito/utils/srp/calculate/calculateS.test.ts +++ b/packages/auth/__tests__/providers/cognito/utils/srp/calculate/calculateS.test.ts @@ -29,7 +29,7 @@ describe('calculateS', () => { B, N, U, - }) + }), ).toBeDefined(); expect(modPowSpy).toHaveBeenCalledWith(x, N, expect.any(Function)); }); @@ -48,7 +48,7 @@ describe('calculateS', () => { B, N, U, - }) + }), ).rejects.toThrow(); }); @@ -70,7 +70,7 @@ describe('calculateS', () => { B, N, U, - }) + }), ).rejects.toThrow(); }); }); diff --git a/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts b/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts index 248fc6c4a14..78741c0b214 100644 --- a/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts +++ b/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts @@ -20,7 +20,7 @@ jest.mock('@aws-amplify/core/internals/utils', () => ({ isBrowser: jest.fn(() => false), })); jest.mock( - '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider' + '../../../src/providers/cognito/utils/clients/CognitoIdentityProvider', ); describe('verifyTOTPSetup', () => { @@ -58,7 +58,7 @@ describe('verifyTOTPSetup', () => { AccessToken: mockAccessToken, UserCode: code, FriendlyDeviceName: friendlyDeviceName, - }) + }), ); }); @@ -76,7 +76,7 @@ describe('verifyTOTPSetup', () => { expect.assertions(2); mockVerifySoftwareToken.mockImplementation(() => { throw getMockError( - VerifySoftwareTokenException.InvalidParameterException + VerifySoftwareTokenException.InvalidParameterException, ); }); try { @@ -84,7 +84,7 @@ describe('verifyTOTPSetup', () => { } catch (error: any) { expect(error).toBeInstanceOf(AuthError); expect(error.name).toBe( - VerifySoftwareTokenException.InvalidParameterException + VerifySoftwareTokenException.InvalidParameterException, ); } }); diff --git a/packages/auth/src/errors/utils/assertServiceError.ts b/packages/auth/src/errors/utils/assertServiceError.ts index 8036b4cd755..9d32c43d3de 100644 --- a/packages/auth/src/errors/utils/assertServiceError.ts +++ b/packages/auth/src/errors/utils/assertServiceError.ts @@ -8,7 +8,7 @@ import { } from '@aws-amplify/core/internals/utils'; export function assertServiceError( - error: unknown + error: unknown, ): asserts error is ServiceError { if ( !error || diff --git a/packages/auth/src/errors/utils/assertValidationError.ts b/packages/auth/src/errors/utils/assertValidationError.ts index 6ffb2d237df..3f9ff0135bd 100644 --- a/packages/auth/src/errors/utils/assertValidationError.ts +++ b/packages/auth/src/errors/utils/assertValidationError.ts @@ -7,7 +7,7 @@ import { AuthValidationErrorCode } from '../types/validation'; export function assertValidationError( assertion: boolean, - name: AuthValidationErrorCode + name: AuthValidationErrorCode, ): asserts assertion { const { message, recoverySuggestion } = validationErrorMap[name]; diff --git a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts index 1fcd4867d2f..fa2732515d0 100644 --- a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts @@ -25,7 +25,7 @@ import { getUserContextData } from '../utils/userContextData'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function confirmResetPassword( - input: ConfirmResetPasswordInput + input: ConfirmResetPasswordInput, ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); @@ -33,17 +33,17 @@ export async function confirmResetPassword( const { username, newPassword } = input; assertValidationError( !!username, - AuthValidationErrorCode.EmptyConfirmResetPasswordUsername + AuthValidationErrorCode.EmptyConfirmResetPasswordUsername, ); assertValidationError( !!newPassword, - AuthValidationErrorCode.EmptyConfirmResetPasswordNewPassword + AuthValidationErrorCode.EmptyConfirmResetPasswordNewPassword, ); const code = input.confirmationCode; assertValidationError( !!code, - AuthValidationErrorCode.EmptyConfirmResetPasswordConfirmationCode + AuthValidationErrorCode.EmptyConfirmResetPasswordConfirmationCode, ); const metadata = input.options?.clientMetadata; @@ -65,6 +65,6 @@ export async function confirmResetPassword( ClientMetadata: metadata, ClientId: authConfig.userPoolClientId, UserContextData: UserContextData, - } + }, ); } diff --git a/packages/auth/src/providers/cognito/apis/confirmSignIn.ts b/packages/auth/src/providers/cognito/apis/confirmSignIn.ts index b319416b196..561cae9c504 100644 --- a/packages/auth/src/providers/cognito/apis/confirmSignIn.ts +++ b/packages/auth/src/providers/cognito/apis/confirmSignIn.ts @@ -52,7 +52,7 @@ import { getCurrentUser } from './getCurrentUser'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function confirmSignIn( - input: ConfirmSignInInput + input: ConfirmSignInInput, ): Promise { const { challengeResponse, options } = input; const { username, challengeName, signInSession, signInDetails } = @@ -65,7 +65,7 @@ export async function confirmSignIn( assertValidationError( !!challengeResponse, - AuthValidationErrorCode.EmptyChallengeResponse + AuthValidationErrorCode.EmptyChallengeResponse, ); if (!username || !challengeName || !signInSession) @@ -99,7 +99,7 @@ export async function confirmSignIn( authConfig, tokenOrchestrator, clientMetaData, - options + options, ); // sets up local state used during the sign-in process @@ -118,7 +118,7 @@ export async function confirmSignIn( NewDeviceMetadata: await getNewDeviceMetatada( authConfig.userPoolId, AuthenticationResult.NewDeviceMetadata, - AuthenticationResult.AccessToken + AuthenticationResult.AccessToken, ), signInDetails, }); @@ -129,7 +129,7 @@ export async function confirmSignIn( data: await getCurrentUser(), }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); return { isSignedIn: true, diff --git a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts index 3fe5f79209c..e0fa39b3628 100644 --- a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts +++ b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts @@ -34,7 +34,7 @@ import { getUserContextData } from '../utils/userContextData'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function confirmSignUp( - input: ConfirmSignUpInput + input: ConfirmSignUpInput, ): Promise { const { username, confirmationCode, options } = input; @@ -44,11 +44,11 @@ export async function confirmSignUp( const clientMetadata = options?.clientMetadata; assertValidationError( !!username, - AuthValidationErrorCode.EmptyConfirmSignUpUsername + AuthValidationErrorCode.EmptyConfirmSignUpUsername, ); assertValidationError( !!confirmationCode, - AuthValidationErrorCode.EmptyConfirmSignUpCode + AuthValidationErrorCode.EmptyConfirmSignUpCode, ); const UserContextData = getUserContextData({ @@ -69,7 +69,7 @@ export async function confirmSignUp( ForceAliasCreation: options?.forceAliasCreation, ClientId: authConfig.userPoolClientId, UserContextData, - } + }, ); return new Promise((resolve, reject) => { @@ -102,7 +102,7 @@ export async function confirmSignUp( setAutoSignInStarted(false); stopListener(); } - } + }, ); HubInternal.dispatch('auth-internal', { diff --git a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts index 37dbc5888d4..4d464388929 100644 --- a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts +++ b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts @@ -25,14 +25,14 @@ import { getAuthUserAgentValue } from '../../../utils'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function confirmUserAttribute( - input: ConfirmUserAttributeInput + input: ConfirmUserAttributeInput, ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { confirmationCode, userAttributeKey } = input; assertValidationError( !!confirmationCode, - AuthValidationErrorCode.EmptyConfirmUserAttributeCode + AuthValidationErrorCode.EmptyConfirmUserAttributeCode, ); const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); @@ -45,6 +45,6 @@ export async function confirmUserAttribute( AccessToken: tokens.accessToken.toString(), AttributeName: userAttributeKey, Code: confirmationCode, - } + }, ); } diff --git a/packages/auth/src/providers/cognito/apis/deleteUser.ts b/packages/auth/src/providers/cognito/apis/deleteUser.ts index 1ef4ca242f6..361f06c16df 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUser.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUser.ts @@ -34,7 +34,7 @@ export async function deleteUser(): Promise { }, { AccessToken: tokens.accessToken.toString(), - } + }, ); await tokenOrchestrator.clearDeviceMetadata(); await signOut(); diff --git a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts index 89201a6ef52..7963dffcdfa 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts @@ -21,7 +21,7 @@ import { getAuthUserAgentValue } from '../../../utils'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function deleteUserAttributes( - input: DeleteUserAttributesInput + input: DeleteUserAttributesInput, ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); @@ -36,6 +36,6 @@ export async function deleteUserAttributes( { AccessToken: tokens.accessToken.toString(), UserAttributeNames: userAttributeKeys, - } + }, ); } diff --git a/packages/auth/src/providers/cognito/apis/fetchDevices.ts b/packages/auth/src/providers/cognito/apis/fetchDevices.ts index 3b697ea5c81..a0d746dddf0 100644 --- a/packages/auth/src/providers/cognito/apis/fetchDevices.ts +++ b/packages/auth/src/providers/cognito/apis/fetchDevices.ts @@ -41,13 +41,13 @@ export async function fetchDevices(): Promise { { AccessToken: tokens.accessToken.toString(), Limit: MAX_DEVICES, - } + }, ); return parseDevicesResponse(response.Devices ?? []); } const parseDevicesResponse = async ( - devices: DeviceType[] + devices: DeviceType[], ): Promise => { return devices.map( ({ @@ -64,7 +64,7 @@ const parseDevicesResponse = async ( } return attrs; }, - {} + {}, ); return { id, @@ -79,6 +79,6 @@ const parseDevicesResponse = async ( ? new Date(DeviceLastAuthenticatedDate * 1000) : undefined, }; - } + }, ); }; diff --git a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts index 44dc90415af..104bc401522 100644 --- a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts @@ -34,7 +34,7 @@ export async function fetchMFAPreference(): Promise { }, { AccessToken: tokens.accessToken.toString(), - } + }, ); return { diff --git a/packages/auth/src/providers/cognito/apis/forgetDevice.ts b/packages/auth/src/providers/cognito/apis/forgetDevice.ts index 8ea78399fef..1e5d634a6f9 100644 --- a/packages/auth/src/providers/cognito/apis/forgetDevice.ts +++ b/packages/auth/src/providers/cognito/apis/forgetDevice.ts @@ -42,7 +42,7 @@ export async function forgetDevice(input?: ForgetDeviceInput): Promise { { AccessToken: tokens.accessToken.toString(), DeviceKey: externalDeviceKey ?? currentDeviceKey, - } + }, ); if (!externalDeviceKey || externalDeviceKey === currentDeviceKey) diff --git a/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts b/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts index 718e8ca6ca0..00c6ead5bf3 100644 --- a/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/internal/fetchUserAttributes.ts @@ -15,7 +15,7 @@ import { toAuthUserAttribute } from '../../utils/apiHelpers'; import { getAuthUserAgentValue } from '../../../../utils'; export const fetchUserAttributes = async ( - amplify: AmplifyClassV6 + amplify: AmplifyClassV6, ): Promise => { const authConfig = amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); @@ -31,7 +31,7 @@ export const fetchUserAttributes = async ( }, { AccessToken: tokens.accessToken.toString(), - } + }, ); return toAuthUserAttribute(UserAttributes); diff --git a/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts index 395512d66a4..8c99395b6b0 100644 --- a/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/internal/getCurrentUser.ts @@ -11,7 +11,7 @@ import { } from '../../types'; export const getCurrentUser = async ( - amplify: AmplifyClassV6 + amplify: AmplifyClassV6, ): Promise => { const authConfig = amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); @@ -33,7 +33,7 @@ export const getCurrentUser = async ( }; function getSignInDetailsFromTokens( - tokens: AuthTokens & { signInDetails?: CognitoAuthSignInDetails } + tokens: AuthTokens & { signInDetails?: CognitoAuthSignInDetails }, ): CognitoAuthSignInDetails | undefined { return tokens?.signInDetails; } diff --git a/packages/auth/src/providers/cognito/apis/rememberDevice.ts b/packages/auth/src/providers/cognito/apis/rememberDevice.ts index 0623998cd08..50abd592329 100644 --- a/packages/auth/src/providers/cognito/apis/rememberDevice.ts +++ b/packages/auth/src/providers/cognito/apis/rememberDevice.ts @@ -39,6 +39,6 @@ export async function rememberDevice(): Promise { AccessToken: tokens.accessToken.toString(), DeviceKey: deviceMetadata.deviceKey, DeviceRememberedStatus: 'remembered', - } + }, ); } diff --git a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts index 53446d600d2..857fbf630a2 100644 --- a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts +++ b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts @@ -26,12 +26,12 @@ import { getUserContextData } from '../utils/userContextData'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function resendSignUpCode( - input: ResendSignUpCodeInput + input: ResendSignUpCodeInput, ): Promise { const username = input.username; assertValidationError( !!username, - AuthValidationErrorCode.EmptySignUpUsername + AuthValidationErrorCode.EmptySignUpUsername, ); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); @@ -54,7 +54,7 @@ export async function resendSignUpCode( ClientMetadata: clientMetadata, ClientId: authConfig.userPoolClientId, UserContextData, - } + }, ); const { DeliveryMedium, AttributeName, Destination } = { ...CodeDeliveryDetails, diff --git a/packages/auth/src/providers/cognito/apis/resetPassword.ts b/packages/auth/src/providers/cognito/apis/resetPassword.ts index 17455ada185..b236e416949 100644 --- a/packages/auth/src/providers/cognito/apis/resetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/resetPassword.ts @@ -29,12 +29,12 @@ import { getUserContextData } from '../utils/userContextData'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. **/ export async function resetPassword( - input: ResetPasswordInput + input: ResetPasswordInput, ): Promise { const username = input.username; assertValidationError( !!username, - AuthValidationErrorCode.EmptyResetPasswordUsername + AuthValidationErrorCode.EmptyResetPasswordUsername, ); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); @@ -57,7 +57,7 @@ export async function resetPassword( ClientMetadata: clientMetadata, ClientId: authConfig.userPoolClientId, UserContextData, - } + }, ); const codeDeliveryDetails = res.CodeDeliveryDetails; return { diff --git a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts index d3e7562073a..2e8d37e02a1 100644 --- a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts +++ b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts @@ -27,7 +27,7 @@ import { getAuthUserAgentValue } from '../../../utils'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export const sendUserAttributeVerificationCode = async ( - input: SendUserAttributeVerificationCodeInput + input: SendUserAttributeVerificationCodeInput, ): Promise => { const { userAttributeKey, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; @@ -39,14 +39,14 @@ export const sendUserAttributeVerificationCode = async ( { region: getRegion(authConfig.userPoolId), userAgentValue: getAuthUserAgentValue( - AuthAction.SendUserAttributeVerificationCode + AuthAction.SendUserAttributeVerificationCode, ), }, { AccessToken: tokens.accessToken.toString(), ClientMetadata: clientMetadata, AttributeName: userAttributeKey, - } + }, ); const { DeliveryMedium, AttributeName, Destination } = { ...CodeDeliveryDetails, diff --git a/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts b/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts index b80f5ea4a2f..4266d34197b 100644 --- a/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/server/fetchUserAttributes.ts @@ -9,9 +9,9 @@ import { FetchUserAttributesOutput } from '../../types'; import { fetchUserAttributes as fetchUserAttributesInternal } from '../internal/fetchUserAttributes'; export const fetchUserAttributes = ( - contextSpec: AmplifyServer.ContextSpec + contextSpec: AmplifyServer.ContextSpec, ): Promise => { return fetchUserAttributesInternal( - getAmplifyServerContext(contextSpec).amplify + getAmplifyServerContext(contextSpec).amplify, ); }; diff --git a/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts index daa7d7081eb..7b2a48f9cf3 100644 --- a/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/server/getCurrentUser.ts @@ -16,7 +16,7 @@ import { getCurrentUser as getCurrentUserInternal } from '../internal/getCurrent * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export const getCurrentUser = async ( - contextSpec: AmplifyServer.ContextSpec + contextSpec: AmplifyServer.ContextSpec, ): Promise => { return getCurrentUserInternal(getAmplifyServerContext(contextSpec).amplify); }; diff --git a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts index e3e30f72ae3..f41685551f0 100644 --- a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts +++ b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts @@ -39,7 +39,7 @@ export async function setUpTOTP(): Promise { }, { AccessToken: tokens.accessToken.toString(), - } + }, ); if (!SecretCode) { diff --git a/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts b/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts index ce9a1be44b4..af77338b16a 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts @@ -46,7 +46,7 @@ import { getCurrentUser } from './getCurrentUser'; * @throws SignInWithCustomAuthOutput - Thrown when the token provider config is invalid. */ export async function signInWithCustomAuth( - input: SignInWithCustomAuthInput + input: SignInWithCustomAuthInput, ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); @@ -58,11 +58,11 @@ export async function signInWithCustomAuth( const metadata = options?.clientMetadata; assertValidationError( !!username, - AuthValidationErrorCode.EmptySignInUsername + AuthValidationErrorCode.EmptySignInUsername, ); assertValidationError( !password, - AuthValidationErrorCode.CustomAuthSignInPassword + AuthValidationErrorCode.CustomAuthSignInPassword, ); try { @@ -75,7 +75,7 @@ export async function signInWithCustomAuth( handleCustomAuthFlowWithoutSRP, [username, metadata, authConfig, tokenOrchestrator], username, - tokenOrchestrator + tokenOrchestrator, ); const activeUsername = getActiveSignInUsername(username); // sets up local state used during the sign-in process @@ -94,7 +94,7 @@ export async function signInWithCustomAuth( NewDeviceMetadata: await getNewDeviceMetatada( authConfig.userPoolId, AuthenticationResult.NewDeviceMetadata, - AuthenticationResult.AccessToken + AuthenticationResult.AccessToken, ), signInDetails, }); @@ -102,7 +102,7 @@ export async function signInWithCustomAuth( 'auth', { event: 'signedIn', data: await getCurrentUser() }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); return { isSignedIn: true, diff --git a/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts b/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts index c092bf692fa..b0c760d3630 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts @@ -49,7 +49,7 @@ import { getCurrentUser } from './getCurrentUser'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function signInWithCustomSRPAuth( - input: SignInWithCustomSRPAuthInput + input: SignInWithCustomSRPAuthInput, ): Promise { const { username, password, options } = input; const signInDetails: CognitoAuthSignInDetails = { @@ -61,11 +61,11 @@ export async function signInWithCustomSRPAuth( const metadata = options?.clientMetadata; assertValidationError( !!username, - AuthValidationErrorCode.EmptySignInUsername + AuthValidationErrorCode.EmptySignInUsername, ); assertValidationError( !!password, - AuthValidationErrorCode.EmptySignInPassword + AuthValidationErrorCode.EmptySignInPassword, ); try { @@ -79,7 +79,7 @@ export async function signInWithCustomSRPAuth( password, metadata, authConfig, - tokenOrchestrator + tokenOrchestrator, ); const activeUsername = getActiveSignInUsername(username); @@ -97,7 +97,7 @@ export async function signInWithCustomSRPAuth( NewDeviceMetadata: await getNewDeviceMetatada( authConfig.userPoolId, AuthenticationResult.NewDeviceMetadata, - AuthenticationResult.AccessToken + AuthenticationResult.AccessToken, ), signInDetails, }); @@ -109,7 +109,7 @@ export async function signInWithCustomSRPAuth( data: await getCurrentUser(), }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); return { isSignedIn: true, diff --git a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts index d37bf10d872..d0bbaee9137 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts @@ -33,7 +33,7 @@ import { createOAuthError } from '../utils/oauth/createOAuthError'; * @throws OAuthNotConfigureException - Thrown when the oauth config is invalid. */ export async function signInWithRedirect( - input?: SignInWithRedirectInput + input?: SignInWithRedirectInput, ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); diff --git a/packages/auth/src/providers/cognito/apis/signInWithSRP.ts b/packages/auth/src/providers/cognito/apis/signInWithSRP.ts index 446fb841e32..35e7754cc94 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithSRP.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithSRP.ts @@ -49,7 +49,7 @@ import { getCurrentUser } from './getCurrentUser'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function signInWithSRP( - input: SignInWithSRPInput + input: SignInWithSRPInput, ): Promise { const { username, password } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; @@ -61,11 +61,11 @@ export async function signInWithSRP( const clientMetaData = input.options?.clientMetadata; assertValidationError( !!username, - AuthValidationErrorCode.EmptySignInUsername + AuthValidationErrorCode.EmptySignInUsername, ); assertValidationError( !!password, - AuthValidationErrorCode.EmptySignInPassword + AuthValidationErrorCode.EmptySignInPassword, ); try { @@ -79,7 +79,7 @@ export async function signInWithSRP( password, clientMetaData, authConfig, - tokenOrchestrator + tokenOrchestrator, ); const activeUsername = getActiveSignInUsername(username); @@ -98,7 +98,7 @@ export async function signInWithSRP( NewDeviceMetadata: await getNewDeviceMetatada( authConfig.userPoolId, AuthenticationResult.NewDeviceMetadata, - AuthenticationResult.AccessToken + AuthenticationResult.AccessToken, ), signInDetails, }); @@ -109,7 +109,7 @@ export async function signInWithSRP( data: await getCurrentUser(), }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); return { isSignedIn: true, diff --git a/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts b/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts index 414b15d9d9e..f0da0a7953c 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts @@ -46,7 +46,7 @@ import { getCurrentUser } from './getCurrentUser'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function signInWithUserPassword( - input: SignInWithUserPasswordInput + input: SignInWithUserPasswordInput, ): Promise { const { username, password, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; @@ -58,11 +58,11 @@ export async function signInWithUserPassword( const metadata = options?.clientMetadata; assertValidationError( !!username, - AuthValidationErrorCode.EmptySignInUsername + AuthValidationErrorCode.EmptySignInUsername, ); assertValidationError( !!password, - AuthValidationErrorCode.EmptySignInPassword + AuthValidationErrorCode.EmptySignInPassword, ); try { @@ -75,7 +75,7 @@ export async function signInWithUserPassword( handleUserPasswordAuthFlow, [username, password, metadata, authConfig, tokenOrchestrator], username, - tokenOrchestrator + tokenOrchestrator, ); const activeUsername = getActiveSignInUsername(username); // sets up local state used during the sign-in process @@ -92,7 +92,7 @@ export async function signInWithUserPassword( NewDeviceMetadata: await getNewDeviceMetatada( authConfig.userPoolId, AuthenticationResult.NewDeviceMetadata, - AuthenticationResult.AccessToken + AuthenticationResult.AccessToken, ), signInDetails, }); @@ -104,7 +104,7 @@ export async function signInWithUserPassword( data: await getCurrentUser(), }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); return { isSignedIn: true, diff --git a/packages/auth/src/providers/cognito/apis/signOut.ts b/packages/auth/src/providers/cognito/apis/signOut.ts index 6453d073202..59fde5dcca2 100644 --- a/packages/auth/src/providers/cognito/apis/signOut.ts +++ b/packages/auth/src/providers/cognito/apis/signOut.ts @@ -94,13 +94,13 @@ async function clientSignOut(cognitoConfig: CognitoUserPoolConfig) { { ClientId: cognitoConfig.userPoolClientId, Token: authTokens.refreshToken, - } + }, ); } } catch (err) { // this shouldn't throw logger.debug( - 'Client signOut error caught but will proceed with token removal' + 'Client signOut error caught but will proceed with token removal', ); } } @@ -116,12 +116,12 @@ async function globalSignOut(cognitoConfig: CognitoUserPoolConfig) { }, { AccessToken: authTokens.accessToken.toString(), - } + }, ); } catch (err) { // it should not throw logger.debug( - 'Global signOut error caught but will proceed with token removal' + 'Global signOut error caught but will proceed with token removal', ); } } diff --git a/packages/auth/src/providers/cognito/apis/signUp.ts b/packages/auth/src/providers/cognito/apis/signUp.ts index b5bb844c4ce..4d41baeb170 100644 --- a/packages/auth/src/providers/cognito/apis/signUp.ts +++ b/packages/auth/src/providers/cognito/apis/signUp.ts @@ -46,11 +46,11 @@ export async function signUp(input: SignUpInput): Promise { assertTokenProviderConfig(authConfig); assertValidationError( !!username, - AuthValidationErrorCode.EmptySignUpUsername + AuthValidationErrorCode.EmptySignUpUsername, ); assertValidationError( !!password, - AuthValidationErrorCode.EmptySignUpPassword + AuthValidationErrorCode.EmptySignUpPassword, ); const signInServiceOptions = @@ -82,7 +82,7 @@ export async function signUp(input: SignUpInput): Promise { ClientMetadata: clientMetadata, ValidationData: validationData && toAttributeType(validationData), ClientId: authConfig.userPoolClientId, - } + }, ); const { UserSub, CodeDeliveryDetails } = clientOutput; diff --git a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts index 116a384231c..1a37e7cd75e 100644 --- a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts @@ -23,7 +23,7 @@ import { getAuthUserAgentValue } from '../../../utils'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function updateMFAPreference( - input: UpdateMFAPreferenceInput + input: UpdateMFAPreferenceInput, ): Promise { const { sms, totp } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; @@ -39,12 +39,12 @@ export async function updateMFAPreference( AccessToken: tokens.accessToken.toString(), SMSMfaSettings: getMFASettings(sms), SoftwareTokenMfaSettings: getMFASettings(totp), - } + }, ); } export function getMFASettings( - mfaPreference?: MFAPreference + mfaPreference?: MFAPreference, ): CognitoMFASettings | undefined { if (mfaPreference === 'DISABLED') { return { diff --git a/packages/auth/src/providers/cognito/apis/updatePassword.ts b/packages/auth/src/providers/cognito/apis/updatePassword.ts index 955f4cae51a..33ab12c4eba 100644 --- a/packages/auth/src/providers/cognito/apis/updatePassword.ts +++ b/packages/auth/src/providers/cognito/apis/updatePassword.ts @@ -24,19 +24,19 @@ import { getAuthUserAgentValue } from '../../../utils'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function updatePassword( - input: UpdatePasswordInput + input: UpdatePasswordInput, ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { oldPassword, newPassword } = input; assertValidationError( !!oldPassword, - AuthValidationErrorCode.EmptyUpdatePassword + AuthValidationErrorCode.EmptyUpdatePassword, ); assertValidationError( !!newPassword, - AuthValidationErrorCode.EmptyUpdatePassword + AuthValidationErrorCode.EmptyUpdatePassword, ); const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); @@ -49,6 +49,6 @@ export async function updatePassword( AccessToken: tokens.accessToken.toString(), PreviousPassword: oldPassword, ProposedPassword: newPassword, - } + }, ); } diff --git a/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts b/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts index e8a2af55f78..094fa308297 100644 --- a/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts +++ b/packages/auth/src/providers/cognito/apis/updateUserAttribute.ts @@ -14,7 +14,7 @@ import { updateUserAttributes } from './updateUserAttributes'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export const updateUserAttribute = async ( - input: UpdateUserAttributeInput + input: UpdateUserAttributeInput, ): Promise => { const { userAttribute: { attributeKey, value }, diff --git a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts index f52e68005ed..d2fcd2b5b45 100644 --- a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts @@ -32,7 +32,7 @@ import { getAuthUserAgentValue } from '../../../utils'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export const updateUserAttributes = async ( - input: UpdateUserAttributesInput + input: UpdateUserAttributesInput, ): Promise => { const { userAttributes, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; @@ -49,7 +49,7 @@ export const updateUserAttributes = async ( AccessToken: tokens.accessToken.toString(), ClientMetadata: clientMetadata, UserAttributes: toAttributeType(userAttributes), - } + }, ); return { @@ -59,7 +59,7 @@ export const updateUserAttributes = async ( }; function getConfirmedAttributes( - attributes: AuthUserAttributes + attributes: AuthUserAttributes, ): AuthUpdateUserAttributesOutput { const confirmedAttributes = {} as AuthUpdateUserAttributesOutput; Object.keys(attributes)?.forEach(key => { @@ -75,7 +75,7 @@ function getConfirmedAttributes( } function getUnConfirmedAttributes( - codeDeliveryDetailsList?: CodeDeliveryDetailsType[] + codeDeliveryDetailsList?: CodeDeliveryDetailsType[], ): AuthUpdateUserAttributesOutput { const unConfirmedAttributes = {} as AuthUpdateUserAttributesOutput; codeDeliveryDetailsList?.forEach(codeDeliveryDetails => { diff --git a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts index 597a13750e1..678c758fa14 100644 --- a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts +++ b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts @@ -26,14 +26,14 @@ import { getAuthUserAgentValue } from '../../../utils'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function verifyTOTPSetup( - input: VerifyTOTPSetupInput + input: VerifyTOTPSetupInput, ): Promise { const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { code, options } = input; assertValidationError( !!code, - AuthValidationErrorCode.EmptyVerifyTOTPSetupCode + AuthValidationErrorCode.EmptyVerifyTOTPSetupCode, ); const { tokens } = await fetchAuthSession({ forceRefresh: false }); assertAuthTokens(tokens); @@ -46,6 +46,6 @@ export async function verifyTOTPSetup( AccessToken: tokens.accessToken.toString(), UserCode: code, FriendlyDeviceName: options?.friendlyDeviceName, - } + }, ); } diff --git a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts index 1c8be32d077..2a46ce98d8f 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdProvider.ts @@ -48,7 +48,7 @@ export async function cognitoIdentityIdProvider({ if (identityId && identityId.id === generatedIdentityId) { logger.debug( - `The guest identity ${identityId.id} has become the primary identity.` + `The guest identity ${identityId.id} has become the primary identity.`, ); } identityId = { @@ -75,7 +75,7 @@ export async function cognitoIdentityIdProvider({ async function generateIdentityId( logins: {}, - authConfig: CognitoIdentityPoolConfig + authConfig: CognitoIdentityPoolConfig, ): Promise { const identityPoolId = authConfig?.identityPoolId; const region = getRegionFromIdentityPoolId(identityPoolId); @@ -92,7 +92,7 @@ async function generateIdentityId( { IdentityPoolId: identityPoolId, Logins: logins, - } + }, ) ).IdentityId; if (!idResult) { diff --git a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts index bda71efb5e3..732729ffc1c 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/IdentityIdStore.ts @@ -26,7 +26,7 @@ export class DefaultIdentityIdStore implements IdentityIdStore { this.authConfig = authConfigParam; this._authKeys = createKeysForAuthStorage( 'Cognito', - authConfigParam.Cognito.identityPoolId + authConfigParam.Cognito.identityPoolId, ); return; } @@ -45,7 +45,7 @@ export class DefaultIdentityIdStore implements IdentityIdStore { }; } else { const storedIdentityId = await this.keyValueStorage.getItem( - this._authKeys.identityId + this._authKeys.identityId, ); if (!!storedIdentityId) { return { @@ -84,6 +84,6 @@ export class DefaultIdentityIdStore implements IdentityIdStore { const createKeysForAuthStorage = (provider: string, identifier: string) => { return getAuthStorageKeys(IdentityIdStorageKeys)( `com.amplify.${provider}`, - identifier + identifier, ); }; diff --git a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts index a2ef6bc38d9..0b5fbc7ce1a 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/credentialsProvider.ts @@ -50,7 +50,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider } async getCredentialsAndIdentityId( - getCredentialsOptions: GetCredentialsOptions + getCredentialsOptions: GetCredentialsOptions, ): Promise { const isAuthenticated = getCredentialsOptions.authenticated; const tokens = getCredentialsOptions.tokens; @@ -89,7 +89,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider private async getGuestCredentials( identityId: string, - authConfig: CognitoIdentityPoolConfig + authConfig: CognitoIdentityPoolConfig, ): Promise { // Return existing in-memory cached credentials only if it exists, is not past it's lifetime and is unauthenticated credentials if ( @@ -98,7 +98,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider this._credentialsAndIdentityId.isAuthenticatedCreds === false ) { logger.info( - 'returning stored credentials as they neither past TTL nor expired.' + 'returning stored credentials as they neither past TTL nor expired.', ); return this._credentialsAndIdentityId; } @@ -116,7 +116,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider { region }, { IdentityId: identityId, - } + }, ); if ( @@ -159,7 +159,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider private async credsForOIDCTokens( authConfig: CognitoIdentityPoolConfig, authTokens: AuthTokens, - identityId: string + identityId: string, ): Promise { if ( this._credentialsAndIdentityId && @@ -167,7 +167,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider this._credentialsAndIdentityId.isAuthenticatedCreds === true ) { logger.debug( - 'returning stored credentials as they neither past TTL nor expired.' + 'returning stored credentials as they neither past TTL nor expired.', ); return this._credentialsAndIdentityId; } @@ -186,7 +186,7 @@ export class CognitoAWSCredentialsAndIdentityIdProvider { IdentityId: identityId, Logins: logins, - } + }, ); if ( diff --git a/packages/auth/src/providers/cognito/credentialsProvider/index.ts b/packages/auth/src/providers/cognito/credentialsProvider/index.ts index c85150208e0..db51be1a3f1 100644 --- a/packages/auth/src/providers/cognito/credentialsProvider/index.ts +++ b/packages/auth/src/providers/cognito/credentialsProvider/index.ts @@ -16,7 +16,7 @@ import { defaultStorage } from '@aws-amplify/core'; */ export const cognitoCredentialsProvider = new CognitoAWSCredentialsAndIdentityIdProvider( - new DefaultIdentityIdStore(defaultStorage) + new DefaultIdentityIdStore(defaultStorage), ); export { CognitoAWSCredentialsAndIdentityIdProvider, DefaultIdentityIdStore }; diff --git a/packages/auth/src/providers/cognito/tokenProvider/CognitoUserPoolsTokenProvider.ts b/packages/auth/src/providers/cognito/tokenProvider/CognitoUserPoolsTokenProvider.ts index cae8a50fa36..345877857a5 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/CognitoUserPoolsTokenProvider.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/CognitoUserPoolsTokenProvider.ts @@ -26,7 +26,7 @@ export class CognitoUserPoolsTokenProvider this.tokenOrchestrator.setTokenRefresher(refreshAuthTokens); } getTokens( - { forceRefresh }: FetchAuthSessionOptions = { forceRefresh: false } + { forceRefresh }: FetchAuthSessionOptions = { forceRefresh: false }, ): Promise { return this.tokenOrchestrator.getTokens({ forceRefresh }); } diff --git a/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts b/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts index ca19100691e..073843b036c 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/TokenOrchestrator.ts @@ -62,7 +62,7 @@ export class TokenOrchestrator implements AuthTokenOrchestrator { } async getTokens( - options?: FetchAuthSessionOptions + options?: FetchAuthSessionOptions, ): Promise< (AuthTokens & { signInDetails?: CognitoAuthSignInDetails }) | null > { @@ -146,7 +146,7 @@ export class TokenOrchestrator implements AuthTokenOrchestrator { data: { error: err }, }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); if (err.name.startsWith('NotAuthorizedException')) { diff --git a/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts b/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts index 29adeb9eb43..6eac198ed02 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/TokenStore.ts @@ -41,7 +41,7 @@ export class DefaultTokenStore implements AuthTokenStore { try { const authKeys = await this.getAuthKeys(); const accessTokenString = await this.getKeyValueStorage().getItem( - authKeys.accessToken + authKeys.accessToken, ); if (!accessTokenString) { @@ -53,7 +53,7 @@ export class DefaultTokenStore implements AuthTokenStore { const accessToken = decodeJWT(accessTokenString); const itString = await this.getKeyValueStorage().getItem( - authKeys.idToken + authKeys.idToken, ); const idToken = itString ? decodeJWT(itString) : undefined; @@ -66,7 +66,7 @@ export class DefaultTokenStore implements AuthTokenStore { const clockDrift = Number.parseInt(clockDriftString); const signInDetails = await this.getKeyValueStorage().getItem( - authKeys.signInDetails + authKeys.signInDetails, ); const tokens: CognitoAuthTokens = { accessToken, @@ -92,25 +92,25 @@ export class DefaultTokenStore implements AuthTokenStore { const lastAuthUser = tokens.username; await this.getKeyValueStorage().setItem( this.getLastAuthUserKey(), - lastAuthUser + lastAuthUser, ); const authKeys = await this.getAuthKeys(); await this.getKeyValueStorage().setItem( authKeys.accessToken, - tokens.accessToken.toString() + tokens.accessToken.toString(), ); if (!!tokens.idToken) { await this.getKeyValueStorage().setItem( authKeys.idToken, - tokens.idToken.toString() + tokens.idToken.toString(), ); } if (!!tokens.refreshToken) { await this.getKeyValueStorage().setItem( authKeys.refreshToken, - tokens.refreshToken + tokens.refreshToken, ); } @@ -118,31 +118,31 @@ export class DefaultTokenStore implements AuthTokenStore { if (tokens.deviceMetadata.deviceKey) { await this.getKeyValueStorage().setItem( authKeys.deviceKey, - tokens.deviceMetadata.deviceKey + tokens.deviceMetadata.deviceKey, ); } if (tokens.deviceMetadata.deviceGroupKey) { await this.getKeyValueStorage().setItem( authKeys.deviceGroupKey, - tokens.deviceMetadata.deviceGroupKey + tokens.deviceMetadata.deviceGroupKey, ); } await this.getKeyValueStorage().setItem( authKeys.randomPasswordKey, - tokens.deviceMetadata.randomPassword + tokens.deviceMetadata.randomPassword, ); } if (!!tokens.signInDetails) { await this.getKeyValueStorage().setItem( authKeys.signInDetails, - JSON.stringify(tokens.signInDetails) + JSON.stringify(tokens.signInDetails), ); } await this.getKeyValueStorage().setItem( authKeys.clockDrift, - `${tokens.clockDrift}` + `${tokens.clockDrift}`, ); } @@ -162,13 +162,13 @@ export class DefaultTokenStore implements AuthTokenStore { async getDeviceMetadata(username?: string): Promise { const authKeys = await this.getAuthKeys(username); const deviceKey = await this.getKeyValueStorage().getItem( - authKeys.deviceKey + authKeys.deviceKey, ); const deviceGroupKey = await this.getKeyValueStorage().getItem( - authKeys.deviceGroupKey + authKeys.deviceGroupKey, ); const randomPassword = await this.getKeyValueStorage().getItem( - authKeys.randomPasswordKey + authKeys.randomPasswordKey, ); return !!randomPassword @@ -176,7 +176,7 @@ export class DefaultTokenStore implements AuthTokenStore { deviceKey: deviceKey ?? undefined, deviceGroupKey: deviceGroupKey ?? undefined, randomPassword, - } + } : null; } async clearDeviceMetadata(username?: string): Promise { @@ -189,13 +189,13 @@ export class DefaultTokenStore implements AuthTokenStore { } private async getAuthKeys( - username?: string + username?: string, ): Promise> { assertTokenProviderConfig(this.authConfig?.Cognito); const lastAuthUser = username ?? (await this.getLastAuthUser()); return createKeysForAuthStorage( this.name, - `${this.authConfig.Cognito.userPoolClientId}.${lastAuthUser}` + `${this.authConfig.Cognito.userPoolClientId}.${lastAuthUser}`, ); } @@ -216,13 +216,13 @@ export class DefaultTokenStore implements AuthTokenStore { export const createKeysForAuthStorage = ( provider: string, - identifier: string + identifier: string, ) => { return getAuthStorageKeys(AuthTokenStorageKeys)(`${provider}`, identifier); }; export function getAuthStorageKeys>( - authKeys: T + authKeys: T, ) { const keys = Object.values({ ...authKeys }); return (prefix: string, identifier: string) => @@ -231,6 +231,6 @@ export function getAuthStorageKeys>( ...acc, [authKey]: `${prefix}.${identifier}.${authKey}`, }), - {} as AuthKeys + {} as AuthKeys, ); } diff --git a/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts b/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts index acd5ee07f47..1d7755861dd 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/cacheTokens.ts @@ -11,7 +11,7 @@ export async function cacheCognitoTokens( NewDeviceMetadata?: DeviceMetadata; username: string; signInDetails?: CognitoAuthSignInDetails; - } + }, ): Promise { if (AuthenticationResult.AccessToken) { const accessToken = decodeJWT(AuthenticationResult.AccessToken); diff --git a/packages/auth/src/providers/cognito/tokenProvider/types.ts b/packages/auth/src/providers/cognito/tokenProvider/types.ts index 45fd29ada1e..69478ad5864 100644 --- a/packages/auth/src/providers/cognito/tokenProvider/types.ts +++ b/packages/auth/src/providers/cognito/tokenProvider/types.ts @@ -49,7 +49,7 @@ export interface AuthTokenOrchestrator { setTokenRefresher(tokenRefresher: TokenRefresher): void; setAuthTokenStore(tokenStore: AuthTokenStore): void; getTokens: ( - options?: FetchAuthSessionOptions + options?: FetchAuthSessionOptions, ) => Promise< (AuthTokens & { signInDetails?: CognitoAuthSignInDetails }) | null >; diff --git a/packages/auth/src/providers/cognito/utils/apiHelpers.ts b/packages/auth/src/providers/cognito/utils/apiHelpers.ts index 9b0dfe72519..53a078481a3 100644 --- a/packages/auth/src/providers/cognito/utils/apiHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/apiHelpers.ts @@ -10,7 +10,7 @@ import { AttributeType } from './clients/CognitoIdentityProvider/types'; * @returns an array of AttributeType objects. */ export function toAttributeType>( - attributes: T + attributes: T, ): AttributeType[] { return Object.entries(attributes).map(([key, value]) => ({ Name: key, @@ -25,7 +25,7 @@ export function toAttributeType>( * @returns AuthUserAttributes object. */ export function toAuthUserAttribute( - attributes?: AttributeType[] + attributes?: AttributeType[], ): AuthUserAttributes { const userAttributes: AuthUserAttributes = {}; attributes?.forEach(attribute => { diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts index 21a96c4d429..4e63d1c8b06 100644 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts +++ b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/base.ts @@ -33,7 +33,7 @@ const endpointResolver = ({ region }: EndpointResolverOptions) => { const authConfig = Amplify.getConfig().Auth?.Cognito; const customURL = authConfig?.userPoolEndpoint; const defaultURL = new AmplifyUrl( - `https://${SERVICE_NAME}.${region}.${getDnsSuffix(region)}` + `https://${SERVICE_NAME}.${region}.${getDnsSuffix(region)}`, ); return { @@ -90,7 +90,7 @@ export const getSharedHeaders = (operation: string): Headers => ({ export const buildHttpRpcRequest = ( { url }: Endpoint, headers: Headers, - body: string + body: string, ): HttpRequest => ({ headers, url, diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts index f0ec6fc21b1..037765c2251 100644 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts +++ b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/index.ts @@ -104,7 +104,7 @@ const buildUserPoolSerializer = }; const buildUserPoolDeserializer = (): (( - response: HttpResponse + response: HttpResponse, ) => Promise) => { return async (response: HttpResponse): Promise => { if (response.statusCode >= 300) { @@ -119,7 +119,7 @@ const buildUserPoolDeserializer = (): (( }; const handleEmptyResponseDeserializer = (): (( - response: HttpResponse + response: HttpResponse, ) => Promise) => { return async (response: HttpResponse): Promise => { if (response.statusCode >= 300) { @@ -136,147 +136,147 @@ export const initiateAuth = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('InitiateAuth'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const revokeToken = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('RevokeToken'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const signUp = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('SignUp'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const confirmSignUp = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('ConfirmSignUp'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const forgotPassword = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('ForgotPassword'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const confirmForgotPassword = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('ConfirmForgotPassword'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const respondToAuthChallenge = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer( - 'RespondToAuthChallenge' + 'RespondToAuthChallenge', ), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const resendConfirmationCode = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer( - 'ResendConfirmationCode' + 'ResendConfirmationCode', ), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const verifySoftwareToken = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('VerifySoftwareToken'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const associateSoftwareToken = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer( - 'AssociateSoftwareToken' + 'AssociateSoftwareToken', ), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const setUserMFAPreference = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('SetUserMFAPreference'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const getUser = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('GetUser'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const changePassword = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('ChangePassword'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const confirmDevice = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('ConfirmDevice'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const forgetDevice = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('ForgetDevice'), handleEmptyResponseDeserializer(), - defaultConfig + defaultConfig, ); export const deleteUser = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('DeleteUser'), handleEmptyResponseDeserializer(), - defaultConfig + defaultConfig, ); export const getUserAttributeVerificationCode = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer( - 'GetUserAttributeVerificationCode' + 'GetUserAttributeVerificationCode', ), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const globalSignOut = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('GlobalSignOut'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const updateUserAttributes = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('UpdateUserAttributes'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const verifyUserAttribute = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('VerifyUserAttribute'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const updateDeviceStatus = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('UpdateDeviceStatus'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const listDevices = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('ListDevices'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); export const deleteUserAttributes = composeServiceApi( cognitoUserPoolTransferHandler, buildUserPoolSerializer('DeleteUserAttributes'), buildUserPoolDeserializer(), - defaultConfig + defaultConfig, ); diff --git a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts index 866ec6321e5..939fc23ce3d 100644 --- a/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts +++ b/packages/auth/src/providers/cognito/utils/clients/CognitoIdentityProvider/types.ts @@ -201,7 +201,7 @@ declare namespace GetUserAttributeVerificationCodeRequest { * @internal */ const filterSensitiveLog: ( - obj: GetUserAttributeVerificationCodeRequest + obj: GetUserAttributeVerificationCodeRequest, ) => any; } declare namespace GetUserAttributeVerificationCodeResponse { @@ -209,7 +209,7 @@ declare namespace GetUserAttributeVerificationCodeResponse { * @internal */ const filterSensitiveLog: ( - obj: GetUserAttributeVerificationCodeResponse + obj: GetUserAttributeVerificationCodeResponse, ) => any; } declare namespace GetUserRequest { diff --git a/packages/auth/src/providers/cognito/utils/clients/base.ts b/packages/auth/src/providers/cognito/utils/clients/base.ts index 0b71aa38c21..00035fdc1cc 100644 --- a/packages/auth/src/providers/cognito/utils/clients/base.ts +++ b/packages/auth/src/providers/cognito/utils/clients/base.ts @@ -30,7 +30,7 @@ const SERVICE_NAME = 'cognito-idp'; */ const endpointResolver = ({ region }: EndpointResolverOptions) => ({ url: new AmplifyUrl( - `https://${SERVICE_NAME}.${region}.${getDnsSuffix(region)}` + `https://${SERVICE_NAME}.${region}.${getDnsSuffix(region)}`, ), }); @@ -82,7 +82,7 @@ export const getSharedHeaders = (operation: string): Headers => ({ export const buildHttpRpcRequest = ( { url }: Endpoint, headers: Headers, - body: any + body: any, ): HttpRequest => ({ headers, url, diff --git a/packages/auth/src/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.ts b/packages/auth/src/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.ts index 3dbeba2b7e4..b805e613b6c 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.ts @@ -16,7 +16,7 @@ import { cognitoUserPoolsTokenProvider } from '../../tokenProvider'; import { addInflightPromise } from './inflightPromise'; export const attemptCompleteOAuthFlow = async ( - authConfig: AuthConfig['Cognito'] + authConfig: AuthConfig['Cognito'], ): Promise => { try { assertTokenProviderConfig(authConfig); @@ -41,7 +41,7 @@ export const attemptCompleteOAuthFlow = async ( addInflightPromise(resolve); }); cognitoUserPoolsTokenProvider.setWaitForInflightOAuth( - () => asyncGetSessionBlocker + () => asyncGetSessionBlocker, ); try { diff --git a/packages/auth/src/providers/cognito/utils/oauth/completeOAuthFlow.ts b/packages/auth/src/providers/cognito/utils/oauth/completeOAuthFlow.ts index b15d8ea63cd..b1f2bf2900a 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/completeOAuthFlow.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/completeOAuthFlow.ts @@ -246,7 +246,7 @@ const completeFlow = async ({ data: urlSafeDecode(getCustomState(state)), }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); } Hub.dispatch('auth', { event: 'signInWithRedirect' }, 'Auth', AMPLIFY_SYMBOL); @@ -254,7 +254,7 @@ const completeFlow = async ({ 'auth', { event: 'signedIn', data: await getCurrentUser() }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); clearHistory(redirectUri); }; diff --git a/packages/auth/src/providers/cognito/utils/oauth/createOAuthError.ts b/packages/auth/src/providers/cognito/utils/oauth/createOAuthError.ts index bc0105e9db9..c419d2722dc 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/createOAuthError.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/createOAuthError.ts @@ -7,7 +7,7 @@ import { AuthError } from '../../../../errors/AuthError'; export const createOAuthError = ( message: string, - recoverySuggestion?: string + recoverySuggestion?: string, ) => new AuthError({ message: message ?? 'An error has occurred during the oauth process.', diff --git a/packages/auth/src/providers/cognito/utils/oauth/generateCodeVerifier.ts b/packages/auth/src/providers/cognito/utils/oauth/generateCodeVerifier.ts index 58c27468ac9..8215eec4cf5 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/generateCodeVerifier.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/generateCodeVerifier.ts @@ -19,7 +19,7 @@ const CODE_VERIFIER_CHARSET = * following the spec of [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636#section-4.2). */ export const generateCodeVerifier = ( - length: number + length: number, ): { value: string; method: 'S256'; @@ -53,7 +53,7 @@ function generateCodeChallenge(codeVerifier: string): string { awsCryptoHash.update(codeVerifier); const codeChallenge = removePaddingChar( - base64Encoder.convert(awsCryptoHash.digestSync(), { urlSafe: true }) + base64Encoder.convert(awsCryptoHash.digestSync(), { urlSafe: true }), ); return codeChallenge; diff --git a/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.native.ts b/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.native.ts index 5e138350569..d653b7967ed 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.native.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.native.ts @@ -7,7 +7,7 @@ import { invalidRedirectException } from '../../../../errors/constants'; export function getRedirectUrl(redirects: string[]): string { const redirect = redirects?.find( redirect => - !redirect.startsWith('http://') && !redirect.startsWith('https://') + !redirect.startsWith('http://') && !redirect.startsWith('https://'), ); if (!redirect) { throw invalidRedirectException; diff --git a/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.ts b/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.ts index 46885a38db1..63c343b0e00 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/getRedirectUrl.ts @@ -23,7 +23,7 @@ export function getRedirectUrl(redirects: string[]): string { // origin + pathname => https://example.com/app const isSameOriginAndPathName = (redirect: string) => redirect.startsWith( - String(window.location.origin + window.location.pathname ?? '/') + String(window.location.origin + window.location.pathname ?? '/'), ); // domain => outlook.live.com, github.com const isTheSameDomain = (redirect: string) => diff --git a/packages/auth/src/providers/cognito/utils/oauth/handleFailure.ts b/packages/auth/src/providers/cognito/utils/oauth/handleFailure.ts index e7914594b23..8851c252bb5 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/handleFailure.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/handleFailure.ts @@ -9,7 +9,7 @@ import { oAuthStore } from './oAuthStore'; import { resolveAndClearInflightPromises } from './inflightPromise'; export const handleFailure = async ( - error: AuthError | unknown + error: AuthError | unknown, ): Promise => { resolveAndClearInflightPromises(); await oAuthStore.clearOAuthInflightData(); @@ -17,6 +17,6 @@ export const handleFailure = async ( 'auth', { event: 'signInWithRedirect_failure', data: { error } }, 'Auth', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); }; diff --git a/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts index 3cdb0315a28..5f08c646c94 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.native.ts @@ -9,14 +9,14 @@ import { oAuthSignOutRedirect } from './oAuthSignOutRedirect'; export const handleOAuthSignOut = async ( cognitoConfig: CognitoUserPoolConfig, - store: DefaultOAuthStore + store: DefaultOAuthStore, ): Promise => { const { isOAuthSignIn, preferPrivateSession } = await store.loadOAuthSignIn(); if (isOAuthSignIn) { const result = await oAuthSignOutRedirect( cognitoConfig, - preferPrivateSession + preferPrivateSession, ); // If this was a private session, clear data and tokens regardless of what happened with logout // endpoint. Otherwise, only do so if the logout endpoint was succesfully visited. diff --git a/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts index a583af266fb..db535717759 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/handleOAuthSignOut.ts @@ -9,7 +9,7 @@ import { oAuthSignOutRedirect } from './oAuthSignOutRedirect'; export const handleOAuthSignOut = async ( cognitoConfig: CognitoUserPoolConfig, - store: DefaultOAuthStore + store: DefaultOAuthStore, ): Promise => { const { isOAuthSignIn } = await store.loadOAuthSignIn(); diff --git a/packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts b/packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts index 2cebfefc521..fb5c87ef34d 100644 --- a/packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts +++ b/packages/auth/src/providers/cognito/utils/oauth/oAuthSignOutRedirect.ts @@ -9,7 +9,7 @@ import { getRedirectUrl } from './getRedirectUrl'; export const oAuthSignOutRedirect = async ( authConfig: CognitoUserPoolConfig, - preferPrivateSession: boolean = false + preferPrivateSession: boolean = false, ): Promise => { assertOAuthConfig(authConfig); const { loginWith, userPoolClientId } = authConfig; @@ -25,6 +25,6 @@ export const oAuthSignOutRedirect = async ( return openAuthSession( oAuthLogoutEndpoint, redirectSignOut, - preferPrivateSession + preferPrivateSession, ); }; diff --git a/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts b/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts index 2021b5a4c5b..556b9a7a95a 100644 --- a/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts +++ b/packages/auth/src/providers/cognito/utils/refreshAuthTokens.ts @@ -48,7 +48,7 @@ const refreshAuthTokensFunction: TokenRefresher = async ({ AuthFlow: 'REFRESH_TOKEN_AUTH', AuthParameters, UserContextData, - } + }, ); const accessToken = decodeJWT(AuthenticationResult?.AccessToken ?? ''); diff --git a/packages/auth/src/providers/cognito/utils/signInHelpers.ts b/packages/auth/src/providers/cognito/utils/signInHelpers.ts index 372ed25e700..b31291bfc60 100644 --- a/packages/auth/src/providers/cognito/utils/signInHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/signInHelpers.ts @@ -121,7 +121,7 @@ export async function handleCustomChallenge({ region: getRegion(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn), }, - jsonReq + jsonReq, ); if (response.ChallengeName === 'DEVICE_SRP_AUTH') { @@ -159,7 +159,7 @@ export async function handleMFASetupChallenge({ UserCode: challengeResponse, Session: session, FriendlyDeviceName: deviceName, - } + }, ); signInStore.dispatch({ @@ -187,7 +187,7 @@ export async function handleSelectMFATypeChallenge({ const { userPoolId, userPoolClientId } = config; assertValidationError( challengeResponse === 'TOTP' || challengeResponse === 'SMS', - AuthValidationErrorCode.IncorrectMFAMethod + AuthValidationErrorCode.IncorrectMFAMethod, ); const challengeResponses = { @@ -215,7 +215,7 @@ export async function handleSelectMFATypeChallenge({ region: getRegion(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn), }, - jsonReq + jsonReq, ); } @@ -250,7 +250,7 @@ export async function handleSMSMFAChallenge({ region: getRegion(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn), }, - jsonReq + jsonReq, ); } export async function handleSoftwareTokenMFAChallenge({ @@ -285,7 +285,7 @@ export async function handleSoftwareTokenMFAChallenge({ region: getRegion(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn), }, - jsonReq + jsonReq, ); } export async function handleCompleteNewPasswordChallenge({ @@ -323,7 +323,7 @@ export async function handleCompleteNewPasswordChallenge({ region: getRegion(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn), }, - jsonReq + jsonReq, ); } @@ -332,7 +332,7 @@ export async function handleUserPasswordAuthFlow( password: string, clientMetadata: ClientMetadata | undefined, config: CognitoUserPoolConfig, - tokenOrchestrator: AuthTokenOrchestrator + tokenOrchestrator: AuthTokenOrchestrator, ): Promise { const { userPoolClientId, userPoolId } = config; const authParameters: Record = { @@ -364,7 +364,7 @@ export async function handleUserPasswordAuthFlow( region: getRegion(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SignIn), }, - jsonReq + jsonReq, ); const activeUsername = @@ -390,7 +390,7 @@ export async function handleUserSRPAuthFlow( password: string, clientMetadata: ClientMetadata | undefined, config: CognitoUserPoolConfig, - tokenOrchestrator: AuthTokenOrchestrator + tokenOrchestrator: AuthTokenOrchestrator, ): Promise { const { userPoolId, userPoolClientId } = config; const userPoolName = userPoolId?.split('_')[1] || ''; @@ -420,7 +420,7 @@ export async function handleUserSRPAuthFlow( region: getRegion(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SignIn), }, - jsonReq + jsonReq, ); const { ChallengeParameters: challengeParameters, Session: session } = resp; const activeUsername = challengeParameters?.USERNAME ?? username; @@ -437,7 +437,7 @@ export async function handleUserSRPAuthFlow( tokenOrchestrator, ], activeUsername, - tokenOrchestrator + tokenOrchestrator, ); } @@ -445,7 +445,7 @@ export async function handleCustomAuthFlowWithoutSRP( username: string, clientMetadata: ClientMetadata | undefined, config: CognitoUserPoolConfig, - tokenOrchestrator: AuthTokenOrchestrator + tokenOrchestrator: AuthTokenOrchestrator, ): Promise { const { userPoolClientId, userPoolId } = config; const { dispatch } = signInStore; @@ -477,7 +477,7 @@ export async function handleCustomAuthFlowWithoutSRP( region: getRegion(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SignIn), }, - jsonReq + jsonReq, ); const activeUsername = response.ChallengeParameters?.USERNAME ?? username; setActiveSignInUsername(activeUsername); @@ -497,7 +497,7 @@ export async function handleCustomSRPAuthFlow( password: string, clientMetadata: ClientMetadata | undefined, config: CognitoUserPoolConfig, - tokenOrchestrator: AuthTokenOrchestrator + tokenOrchestrator: AuthTokenOrchestrator, ) { assertTokenProviderConfig(config); const { userPoolId, userPoolClientId } = config; @@ -531,7 +531,7 @@ export async function handleCustomSRPAuthFlow( region: getRegion(userPoolId), userAgentValue: getAuthUserAgentValue(AuthAction.SignIn), }, - jsonReq + jsonReq, ); const activeUsername = challengeParameters?.USERNAME ?? username; setActiveSignInUsername(activeUsername); @@ -548,7 +548,7 @@ export async function handleCustomSRPAuthFlow( tokenOrchestrator, ], activeUsername, - tokenOrchestrator + tokenOrchestrator, ); } @@ -564,7 +564,7 @@ async function handleDeviceSRPAuth({ const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username); assertDeviceMetadata(deviceMetadata); const authenticationHelper = await getAuthenticationHelper( - deviceMetadata.deviceGroupKey + deviceMetadata.deviceGroupKey, ); const challengeResponses: Record = { USERNAME: username, @@ -581,7 +581,7 @@ async function handleDeviceSRPAuth({ }; const { ChallengeParameters, Session } = await respondToAuthChallenge( { region: getRegion(userPoolId) }, - jsonReqResponseChallenge + jsonReqResponseChallenge, ); return handleDevicePasswordVerifier( @@ -591,7 +591,7 @@ async function handleDeviceSRPAuth({ Session, authenticationHelper, config, - tokenOrchestrator + tokenOrchestrator, ); } @@ -602,7 +602,7 @@ async function handleDevicePasswordVerifier( session: string | undefined, authenticationHelper: AuthenticationHelper, { userPoolId, userPoolClientId }: CognitoUserPoolConfig, - tokenOrchestrator?: AuthTokenOrchestrator + tokenOrchestrator?: AuthTokenOrchestrator, ): Promise { const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username); assertDeviceMetadata(deviceMetadata); @@ -650,7 +650,7 @@ async function handleDevicePasswordVerifier( return respondToAuthChallenge( { region: getRegion(userPoolId) }, - jsonReqResponseChallenge + jsonReqResponseChallenge, ); } @@ -661,7 +661,7 @@ export async function handlePasswordVerifierChallenge( session: string | undefined, authenticationHelper: AuthenticationHelper, config: CognitoUserPoolConfig, - tokenOrchestrator: AuthTokenOrchestrator + tokenOrchestrator: AuthTokenOrchestrator, ): Promise { const { userPoolId, userPoolClientId } = config; const userPoolName = userPoolId?.split('_')[1] || ''; @@ -717,7 +717,7 @@ export async function handlePasswordVerifierChallenge( const response = await respondToAuthChallenge( { region: getRegion(userPoolId) }, - jsonReqResponseChallenge + jsonReqResponseChallenge, ); if (response.ChallengeName === 'DEVICE_SRP_AUTH') @@ -755,14 +755,14 @@ export async function getSignInResult(params: { throw new AuthError({ name: AuthErrorCodes.SignInException, message: `Cannot initiate MFA setup from available types: ${getMFATypes( - parseMFATypes(challengeParameters.MFAS_CAN_SETUP) + parseMFATypes(challengeParameters.MFAS_CAN_SETUP), )}`, }); const { Session, SecretCode: secretCode } = await associateSoftwareToken( { region: getRegion(authConfig.userPoolId) }, { Session: signInSession, - } + }, ); signInStore.dispatch({ type: 'SET_SIGN_IN_SESSION', @@ -782,7 +782,7 @@ export async function getSignInResult(params: { nextStep: { signInStep: 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED', missingAttributes: parseAttributes( - challengeParameters.requiredAttributes + challengeParameters.requiredAttributes, ), }, }; @@ -792,7 +792,7 @@ export async function getSignInResult(params: { nextStep: { signInStep: 'CONTINUE_SIGN_IN_WITH_MFA_SELECTION', allowedMFATypes: getMFATypes( - parseMFATypes(challengeParameters.MFAS_CAN_CHOOSE) + parseMFATypes(challengeParameters.MFAS_CAN_CHOOSE), ), }, }; @@ -835,7 +835,7 @@ export async function getSignInResult(params: { export function getTOTPSetupDetails( secretCode: string, - username?: string + username?: string, ): AuthTOTPSetupDetails { return { sharedSecret: secretCode, @@ -850,7 +850,7 @@ export function getTOTPSetupDetails( } export function getSignInResultFromError( - errorName: string + errorName: string, ): AuthSignInOutput | undefined { if (errorName === InitiateAuthException.PasswordResetRequiredException) { return { @@ -868,14 +868,14 @@ export function getSignInResultFromError( export function parseAttributes(attributes: string | undefined): string[] { if (!attributes) return []; const parsedAttributes = (JSON.parse(attributes) as Array).map(att => - att.includes(USER_ATTRIBUTES) ? att.replace(USER_ATTRIBUTES, '') : att + att.includes(USER_ATTRIBUTES) ? att.replace(USER_ATTRIBUTES, '') : att, ); return parsedAttributes; } export function createAttributes( - attributes?: AuthUserAttributes + attributes?: AuthUserAttributes, ): Record { if (!attributes) return {}; @@ -895,7 +895,7 @@ export async function handleChallengeName( config: CognitoUserPoolConfig, tokenOrchestrator: AuthTokenOrchestrator, clientMetadata?: ClientMetadata, - options?: ConfirmSignInOptions + options?: ConfirmSignInOptions, ): Promise { const userAttributes = options?.userAttributes; const deviceName = options?.friendlyDeviceName; @@ -949,7 +949,7 @@ export async function handleChallengeName( }, ], username, - tokenOrchestrator + tokenOrchestrator, ); case 'SOFTWARE_TOKEN_MFA': return handleSoftwareTokenMFAChallenge({ @@ -992,7 +992,7 @@ export function parseMFATypes(mfa?: string): CognitoMFAType[] { export function isMFATypeEnabled( challengeParams: ChallengeParameters, - mfaType: AuthMFAType + mfaType: AuthMFAType, ): boolean { const { MFAS_CAN_SETUP } = challengeParams; const mfaTypes = getMFATypes(parseMFATypes(MFAS_CAN_SETUP)); @@ -1027,7 +1027,7 @@ export async function assertUserNotAuthenticated() { export async function getNewDeviceMetatada( userPoolId: string, newDeviceMetadata?: NewDeviceMetadataType, - accessToken?: string + accessToken?: string, ): Promise { if (!newDeviceMetadata) return undefined; const userPoolName = userPoolId.split('_')[1] || ''; @@ -1038,7 +1038,7 @@ export async function getNewDeviceMetatada( try { await authenticationHelper.generateHashDevice( deviceGroupKey ?? '', - deviceKey ?? '' + deviceKey ?? '', ); } catch (errGenHash) { // TODO: log error here @@ -1047,10 +1047,10 @@ export async function getNewDeviceMetatada( const deviceSecretVerifierConfig = { Salt: base64Encoder.convert( - getBytesFromHex(authenticationHelper.getSaltToHashDevices()) + getBytesFromHex(authenticationHelper.getSaltToHashDevices()), ), PasswordVerifier: base64Encoder.convert( - getBytesFromHex(authenticationHelper.getVerifierDevices()) + getBytesFromHex(authenticationHelper.getVerifierDevices()), ), }; const randomPassword = authenticationHelper.getRandomPassword(); @@ -1062,7 +1062,7 @@ export async function getNewDeviceMetatada( AccessToken: accessToken, DeviceKey: newDeviceMetadata?.DeviceKey, DeviceSecretVerifierConfig: deviceSecretVerifierConfig, - } + }, ); return { @@ -1087,7 +1087,7 @@ export async function retryOnResourceNotFoundException< func: F, args: Parameters, username: string, - tokenOrchestrator: AuthTokenOrchestrator + tokenOrchestrator: AuthTokenOrchestrator, ): Promise> { try { return await func(...args); diff --git a/packages/auth/src/providers/cognito/utils/signInWithRedirectStore.ts b/packages/auth/src/providers/cognito/utils/signInWithRedirectStore.ts index 79b5df9acf7..f449e698070 100644 --- a/packages/auth/src/providers/cognito/utils/signInWithRedirectStore.ts +++ b/packages/auth/src/providers/cognito/utils/signInWithRedirectStore.ts @@ -24,7 +24,7 @@ export class DefaultOAuthStore implements OAuthStore { const authKeys = createKeysForAuthStorage( name, - this.cognitoConfig.userPoolClientId + this.cognitoConfig.userPoolClientId, ); await Promise.all([ this.keyValueStorage.removeItem(authKeys.inflightOAuth), @@ -36,7 +36,7 @@ export class DefaultOAuthStore implements OAuthStore { assertTokenProviderConfig(this.cognitoConfig); const authKeys = createKeysForAuthStorage( name, - this.cognitoConfig.userPoolClientId + this.cognitoConfig.userPoolClientId, ); await this.clearOAuthInflightData(); await this.keyValueStorage.removeItem(V5_HOSTED_UI_KEY); // remove in case a customer migrated an App from v5 to v6 @@ -47,7 +47,7 @@ export class DefaultOAuthStore implements OAuthStore { const authKeys = createKeysForAuthStorage( name, - this.cognitoConfig.userPoolClientId + this.cognitoConfig.userPoolClientId, ); return this.keyValueStorage.getItem(authKeys.oauthState); @@ -57,7 +57,7 @@ export class DefaultOAuthStore implements OAuthStore { const authKeys = createKeysForAuthStorage( name, - this.cognitoConfig.userPoolClientId + this.cognitoConfig.userPoolClientId, ); return this.keyValueStorage.setItem(authKeys.oauthState, state); @@ -67,7 +67,7 @@ export class DefaultOAuthStore implements OAuthStore { const authKeys = createKeysForAuthStorage( name, - this.cognitoConfig.userPoolClientId + this.cognitoConfig.userPoolClientId, ); return this.keyValueStorage.getItem(authKeys.oauthPKCE); @@ -77,7 +77,7 @@ export class DefaultOAuthStore implements OAuthStore { const authKeys = createKeysForAuthStorage( name, - this.cognitoConfig.userPoolClientId + this.cognitoConfig.userPoolClientId, ); return this.keyValueStorage.setItem(authKeys.oauthPKCE, pkce); @@ -91,7 +91,7 @@ export class DefaultOAuthStore implements OAuthStore { const authKeys = createKeysForAuthStorage( name, - this.cognitoConfig.userPoolClientId + this.cognitoConfig.userPoolClientId, ); return ( @@ -103,12 +103,12 @@ export class DefaultOAuthStore implements OAuthStore { assertTokenProviderConfig(this.cognitoConfig); const authKeys = createKeysForAuthStorage( name, - this.cognitoConfig.userPoolClientId + this.cognitoConfig.userPoolClientId, ); return await this.keyValueStorage.setItem( authKeys.inflightOAuth, - `${inflight}` + `${inflight}`, ); } @@ -120,7 +120,7 @@ export class DefaultOAuthStore implements OAuthStore { const authKeys = createKeysForAuthStorage( name, - this.cognitoConfig.userPoolClientId + this.cognitoConfig.userPoolClientId, ); const isLegacyHostedUISignIn = @@ -139,18 +139,18 @@ export class DefaultOAuthStore implements OAuthStore { async storeOAuthSignIn( oauthSignIn: boolean, - preferPrivateSession: boolean = false + preferPrivateSession: boolean = false, ): Promise { assertTokenProviderConfig(this.cognitoConfig); const authKeys = createKeysForAuthStorage( name, - this.cognitoConfig.userPoolClientId + this.cognitoConfig.userPoolClientId, ); return await this.keyValueStorage.setItem( authKeys.oauthSignIn, - `${oauthSignIn},${preferPrivateSession}` + `${oauthSignIn},${preferPrivateSession}`, ); } } diff --git a/packages/auth/src/providers/cognito/utils/signUpHelpers.ts b/packages/auth/src/providers/cognito/utils/signUpHelpers.ts index 55ecd5bb228..b071da039d9 100644 --- a/packages/auth/src/providers/cognito/utils/signUpHelpers.ts +++ b/packages/auth/src/providers/cognito/utils/signUpHelpers.ts @@ -29,7 +29,7 @@ export function handleCodeAutoSignIn(signInInput: SignInInput) { } } } - } + }, ); // This will stop the listener if confirmSignUp is not resolved. @@ -51,7 +51,7 @@ type TimeOutOutput = ReturnType; function debounce any>(fun: F, delay: number) { let timer: TimeOutOutput | undefined; return function ( - args: F extends (...args: infer A) => any ? A : never + args: F extends (...args: infer A) => any ? A : never, ): void { if (!timer) { fun(...args); @@ -66,7 +66,7 @@ function debounce any>(fun: F, delay: number) { function handleAutoSignInWithLink( signInInput: SignInInput, resolve: Function, - reject: Function + reject: Function, ) { const start = Date.now(); const autoSignInPollingIntervalId = setInterval(async () => { @@ -81,7 +81,7 @@ function handleAutoSignInWithLink( message: 'The account was not confirmed on time.', recoverySuggestion: 'Try to verify your account by clicking the link sent your email or phone and then login manually.', - }) + }), ); resetAutoSignIn(); return; @@ -107,7 +107,7 @@ function handleAutoSignInWithLink( const debouncedAutoSignInWithLink = debounce(handleAutoSignInWithLink, 300); const debouncedAutoSignWithCodeOrUserConfirmed = debounce( handleAutoSignInWithCodeOrUserConfirmed, - 300 + 300, ); let autoSignInStarted: boolean = false; @@ -136,7 +136,7 @@ export function isSignUpComplete(output: SignUpCommandOutput): boolean { } export function autoSignInWhenUserIsConfirmedWithLink( - signInInput: SignInInput + signInInput: SignInInput, ): AutoSignInCallback { return async () => { return new Promise(async (resolve, reject) => { @@ -147,7 +147,7 @@ export function autoSignInWhenUserIsConfirmedWithLink( async function handleAutoSignInWithCodeOrUserConfirmed( signInInput: SignInInput, resolve: Function, - reject: Function + reject: Function, ) { try { const output = await signIn(signInInput); diff --git a/packages/auth/src/providers/cognito/utils/srp/AuthenticationHelper/AuthenticationHelper.ts b/packages/auth/src/providers/cognito/utils/srp/AuthenticationHelper/AuthenticationHelper.ts index 49a3cf4142d..29cd9660bd5 100644 --- a/packages/auth/src/providers/cognito/utils/srp/AuthenticationHelper/AuthenticationHelper.ts +++ b/packages/auth/src/providers/cognito/utils/srp/AuthenticationHelper/AuthenticationHelper.ts @@ -48,7 +48,7 @@ export default class AuthenticationHelper { this.N = N; this.k = new BigInteger( getHashFromHex(`${getPaddedHex(N)}${getPaddedHex(g)}`), - 16 + 16, ); } @@ -101,7 +101,7 @@ export default class AuthenticationHelper { */ async generateHashDevice( deviceGroupKey: string, - username: string + username: string, ): Promise { this.randomPassword = getRandomString(); const combinedString = `${deviceGroupKey}${username}:${this.randomPassword}`; @@ -116,7 +116,7 @@ export default class AuthenticationHelper { this.g.modPow( new BigInteger( getHashFromHex(this.saltToHashDevices + hashedString), - 16 + 16, ), this.N, (err: unknown, result: AuthBigInteger) => { @@ -127,7 +127,7 @@ export default class AuthenticationHelper { this.verifierDevices = getPaddedHex(result); resolve(); - } + }, ); }); } @@ -165,7 +165,7 @@ export default class AuthenticationHelper { const x = new BigInteger( getHashFromHex(getPaddedHex(salt) + usernamePasswordHash), - 16 + 16, ); const S = await calculateS({ @@ -186,7 +186,7 @@ export default class AuthenticationHelper { const hkdfKey = getHkdfKey( getBytesFromHex(getPaddedHex(S)), getBytesFromHex(getPaddedHex(U)), - info + info, ); return hkdfKey; } diff --git a/packages/auth/src/providers/cognito/utils/srp/BigInteger/BigInteger.ts b/packages/auth/src/providers/cognito/utils/srp/BigInteger/BigInteger.ts index 634a2ec1c15..03e99647746 100644 --- a/packages/auth/src/providers/cognito/utils/srp/BigInteger/BigInteger.ts +++ b/packages/auth/src/providers/cognito/utils/srp/BigInteger/BigInteger.ts @@ -84,7 +84,7 @@ function am1( w: number, j: number, c: number, - n: number + n: number, ): number { while (--n >= 0) { const v = x * this[i++] + w[j] + c; @@ -102,7 +102,7 @@ function am2( w: number, j: number, c: number, - n: number + n: number, ): number { const xl = x & 0x7fff, xh = x >> 15; @@ -124,7 +124,7 @@ function am3( w: number, j: number, c: number, - n: number + n: number, ): number { const xl = x & 0x3fff, xh = x >> 14; @@ -359,7 +359,7 @@ function bnpDRShiftTo(n: number, r: BNP): void { // (protected) r = this << n function bnpLShiftTo( n: number, - r: { s: number; t: number; clamp: Function } + r: { s: number; t: number; clamp: Function }, ): void { const bs = n % this.DB; const cbs = this.DB - bs; @@ -437,7 +437,7 @@ function bnpSubTo(a: BNP, r: BNP & { clamp: Function }): void { // "this" should be the larger one if appropriate. function bnpMultiplyTo( a: BNP & { abs: Function }, - r: BNP & { clamp: Function } + r: BNP & { clamp: Function }, ): void { const x = this.abs(), y = a.abs(); @@ -481,7 +481,7 @@ function bnpDivRemTo( drShiftTo: Function; clamp: Function; rShiftTo: Function; - } + }, ): void { var pm = m.abs(); if (pm.t <= 0) return; @@ -746,7 +746,7 @@ function bnModPow( DB: number; t: number; }, - callback: Function + callback: Function, ) { let i = e.bitLength(), k: number, diff --git a/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.native.ts b/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.native.ts index 826abb92f09..5aae6ed471b 100644 --- a/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.native.ts +++ b/packages/auth/src/providers/cognito/utils/srp/BigInteger/index.native.ts @@ -9,7 +9,7 @@ import { AuthBigInteger } from './types'; BigInteger.prototype.modPow = function modPow( e: AuthBigInteger, m: AuthBigInteger, - callback: Function + callback: Function, ) { computeModPow({ base: (this as unknown as AuthBigInteger).toString(16), diff --git a/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.ts b/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.ts index 3537fec56fd..c27d14d301d 100644 --- a/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.ts +++ b/packages/auth/src/providers/cognito/utils/srp/calculate/calculateS.ts @@ -39,7 +39,7 @@ export const calculateS = async ({ return; } resolve(innerResult.mod(N)); - } + }, ); }); }); diff --git a/packages/auth/src/providers/cognito/utils/srp/calculate/calculateU.ts b/packages/auth/src/providers/cognito/utils/srp/calculate/calculateU.ts index c73a95c692c..97ff8221f8f 100644 --- a/packages/auth/src/providers/cognito/utils/srp/calculate/calculateU.ts +++ b/packages/auth/src/providers/cognito/utils/srp/calculate/calculateU.ts @@ -17,7 +17,7 @@ export const calculateU = ({ }): AuthBigInteger => { const U = new BigInteger( getHashFromHex(getPaddedHex(A) + getPaddedHex(B)), - 16 + 16, ); if (U.equals(BigInteger.ZERO)) { diff --git a/packages/auth/src/providers/cognito/utils/srp/getBytesFromHex.ts b/packages/auth/src/providers/cognito/utils/srp/getBytesFromHex.ts index ebb9ec398ef..dfc1ff032ca 100644 --- a/packages/auth/src/providers/cognito/utils/srp/getBytesFromHex.ts +++ b/packages/auth/src/providers/cognito/utils/srp/getBytesFromHex.ts @@ -20,7 +20,7 @@ export const getBytesFromHex = (encoded: string): Uint8Array => { out[i / 2] = HEX_TO_SHORT[encodedByte]; } else { throw new Error( - `Cannot decode unrecognized sequence ${encodedByte} as hexadecimal` + `Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`, ); } } diff --git a/packages/auth/src/providers/cognito/utils/srp/getHkdfKey.ts b/packages/auth/src/providers/cognito/utils/srp/getHkdfKey.ts index 39810e7dba4..498a1b30e7d 100644 --- a/packages/auth/src/providers/cognito/utils/srp/getHkdfKey.ts +++ b/packages/auth/src/providers/cognito/utils/srp/getHkdfKey.ts @@ -17,7 +17,7 @@ import { Sha256 } from '@aws-crypto/sha256-js'; export const getHkdfKey = ( ikm: Uint8Array, salt: Uint8Array, - info: Uint8Array + info: Uint8Array, ): Uint8Array => { const awsCryptoHash = new Sha256(salt); awsCryptoHash.update(ikm); diff --git a/packages/auth/src/providers/cognito/utils/srp/getPaddedHex.ts b/packages/auth/src/providers/cognito/utils/srp/getPaddedHex.ts index 0195d8c3d6b..54b83624ad0 100644 --- a/packages/auth/src/providers/cognito/utils/srp/getPaddedHex.ts +++ b/packages/auth/src/providers/cognito/utils/srp/getPaddedHex.ts @@ -62,7 +62,7 @@ export const getPaddedHex = (bigInt: AuthBigInteger): string => { /* After flipping the bits, add one to get the 2's complement representation */ const flippedBitsBI = new BigInteger(invertedNibbles, 16).add( - BigInteger.ONE + BigInteger.ONE, ); hexStr = flippedBitsBI.toString(16); diff --git a/packages/auth/src/providers/cognito/utils/srp/getSignatureString.ts b/packages/auth/src/providers/cognito/utils/srp/getSignatureString.ts index b781bd282f5..06af8a78fed 100644 --- a/packages/auth/src/providers/cognito/utils/srp/getSignatureString.ts +++ b/packages/auth/src/providers/cognito/utils/srp/getSignatureString.ts @@ -31,14 +31,14 @@ export const getSignatureString = ({ bufUPIDaToB.byteLength + bufUNaToB.byteLength + bufSBaToB.byteLength + - bufDNaToB.byteLength + bufDNaToB.byteLength, ); bufConcat.set(bufUPIDaToB, 0); bufConcat.set(bufUNaToB, bufUPIDaToB.byteLength); bufConcat.set(bufSBaToB, bufUPIDaToB.byteLength + bufUNaToB.byteLength); bufConcat.set( bufDNaToB, - bufUPIDaToB.byteLength + bufUNaToB.byteLength + bufSBaToB.byteLength + bufUPIDaToB.byteLength + bufUNaToB.byteLength + bufSBaToB.byteLength, ); const awsCryptoHash = new Sha256(hkdf); diff --git a/packages/auth/src/providers/cognito/utils/types.ts b/packages/auth/src/providers/cognito/utils/types.ts index 82241eeb9c2..e6038366885 100644 --- a/packages/auth/src/providers/cognito/utils/types.ts +++ b/packages/auth/src/providers/cognito/utils/types.ts @@ -17,7 +17,7 @@ import { } from '../../../errors/constants'; export function isTypeUserPoolConfig( - authConfig?: AuthConfig + authConfig?: AuthConfig, ): authConfig is AuthUserPoolConfig { if ( authConfig && @@ -31,7 +31,7 @@ export function isTypeUserPoolConfig( } export function assertAuthTokens( - tokens?: AuthTokens | null + tokens?: AuthTokens | null, ): asserts tokens is AuthTokens { if (!tokens || !tokens.accessToken) { throw new AuthError({ @@ -43,7 +43,7 @@ export function assertAuthTokens( } export function assertIdTokenInAuthTokens( - tokens?: AuthTokens + tokens?: AuthTokens, ): asserts tokens is AuthTokens { if (!tokens || !tokens.idToken) { throw new AuthError({ @@ -69,7 +69,7 @@ export const tokenRefreshException = new AuthError({ }); export function assertAuthTokensWithRefreshToken( - tokens?: CognitoAuthTokens | null + tokens?: CognitoAuthTokens | null, ): asserts tokens is CognitoAuthTokens & { refreshToken: string } { if (isAuthenticatedWithImplicitOauthFlow(tokens)) { throw oAuthTokenRefreshException; @@ -83,7 +83,7 @@ type NonNullableDeviceMetadata = DeviceMetadata & { deviceGroupKey: string; }; export function assertDeviceMetadata( - deviceMetadata?: DeviceMetadata | null + deviceMetadata?: DeviceMetadata | null, ): asserts deviceMetadata is NonNullableDeviceMetadata { if ( !deviceMetadata || @@ -118,7 +118,7 @@ export interface OAuthStore { }>; storeOAuthSignIn( oauthSignIn: boolean, - preferPrivateSession: boolean + preferPrivateSession: boolean, ): Promise; loadOAuthState(): Promise; storeOAuthState(state: string): Promise; @@ -136,7 +136,7 @@ function isAuthenticatedWithRefreshToken(tokens?: CognitoAuthTokens | null) { } function isAuthenticatedWithImplicitOauthFlow( - tokens?: CognitoAuthTokens | null + tokens?: CognitoAuthTokens | null, ) { return isAuthenticated(tokens) && !tokens?.refreshToken; } diff --git a/packages/auth/src/providers/cognito/utils/userContextData.ts b/packages/auth/src/providers/cognito/utils/userContextData.ts index c21cd8d061e..d45cc3250ff 100644 --- a/packages/auth/src/providers/cognito/utils/userContextData.ts +++ b/packages/auth/src/providers/cognito/utils/userContextData.ts @@ -23,7 +23,7 @@ export function getUserContextData({ const advancedSecurityData = amazonCognitoAdvancedSecurityData.getData( username, userPoolId, - userPoolClientId + userPoolClientId, ); if (advancedSecurityData) { diff --git a/packages/auth/src/utils/getAuthUserAgentDetails.ts b/packages/auth/src/utils/getAuthUserAgentDetails.ts index f23ff7622c9..9ad37a92b7d 100644 --- a/packages/auth/src/utils/getAuthUserAgentDetails.ts +++ b/packages/auth/src/utils/getAuthUserAgentDetails.ts @@ -9,7 +9,7 @@ import { export const getAuthUserAgentDetails = ( action: AuthAction, - customUserAgentDetails?: CustomUserAgentDetails + customUserAgentDetails?: CustomUserAgentDetails, ): CustomUserAgentDetails => ({ category: Category.Auth, action, diff --git a/packages/auth/src/utils/getAuthUserAgentValue.ts b/packages/auth/src/utils/getAuthUserAgentValue.ts index b9ebb49aeb0..224b76d9eaa 100644 --- a/packages/auth/src/utils/getAuthUserAgentValue.ts +++ b/packages/auth/src/utils/getAuthUserAgentValue.ts @@ -10,7 +10,7 @@ import { export const getAuthUserAgentValue = ( action: AuthAction, - customUserAgentDetails?: CustomUserAgentDetails + customUserAgentDetails?: CustomUserAgentDetails, ) => getAmplifyUserAgent({ category: Category.Auth, diff --git a/packages/auth/src/utils/openAuthSession.native.ts b/packages/auth/src/utils/openAuthSession.native.ts index a607d55edbd..9315fe86fd4 100644 --- a/packages/auth/src/utils/openAuthSession.native.ts +++ b/packages/auth/src/utils/openAuthSession.native.ts @@ -7,13 +7,13 @@ import { OpenAuthSession, OpenAuthSessionResult } from './types'; export const openAuthSession: OpenAuthSession = async ( url: string, redirectUrls: string[], - prefersEphemeralSession?: boolean + prefersEphemeralSession?: boolean, ): Promise => { try { const redirectUrl = await loadAmplifyWebBrowser().openAuthSessionAsync( url, redirectUrls, - prefersEphemeralSession + prefersEphemeralSession, ); if (!redirectUrl) { return { type: 'canceled' }; diff --git a/packages/auth/src/utils/types.ts b/packages/auth/src/utils/types.ts index 39d48a19d91..65e545cbe93 100644 --- a/packages/auth/src/utils/types.ts +++ b/packages/auth/src/utils/types.ts @@ -4,7 +4,7 @@ export type OpenAuthSession = ( url: string, redirectUrls: string[], - preferPrivateSession?: boolean + preferPrivateSession?: boolean, ) => Promise; type OpenAuthSessionResultType = 'canceled' | 'success' | 'error'; @@ -19,6 +19,6 @@ export type AmplifyWebBrowser = { openAuthSessionAsync: ( url: string, redirectUrls: string[], - prefersEphemeralSession?: boolean + prefersEphemeralSession?: boolean, ) => Promise; }; diff --git a/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts b/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts index d9b09a7c511..d93ffe35aab 100644 --- a/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts +++ b/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts @@ -36,14 +36,14 @@ describe('createAWSCredentialsAndIdentityIdProvider', () => { it('should create a credentials provider', () => { const credentialsProvider = createAWSCredentialsAndIdentityIdProvider( mockAuthConfig, - mockKeyValueStorage + mockKeyValueStorage, ); expect(MockDefaultIdentityIdStore).toHaveBeenCalledWith( - mockKeyValueStorage + mockKeyValueStorage, ); expect( - MockCognitoAWSCredentialsAndIdentityIdProvider + MockCognitoAWSCredentialsAndIdentityIdProvider, ).toHaveBeenCalledTimes(1); const mockCredentialsProviderInstance = MockCognitoAWSCredentialsAndIdentityIdProvider.mock.instances[0]; diff --git a/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createUserPoolsTokenProvider.test.ts b/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createUserPoolsTokenProvider.test.ts index b24b6cab09e..084ed6d68bd 100644 --- a/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createUserPoolsTokenProvider.test.ts +++ b/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createUserPoolsTokenProvider.test.ts @@ -37,29 +37,29 @@ describe('createUserPoolsTokenProvider', () => { it('should create a token provider with underlying dependencies', () => { const tokenProvider = createUserPoolsTokenProvider( mockAuthConfig, - mockKeyValueStorage + mockKeyValueStorage, ); expect(MockDefaultTokenStore).toHaveBeenCalledTimes(1); const mockTokenStoreInstance = MockDefaultTokenStore.mock.instances[0]; expect(mockTokenStoreInstance.setAuthConfig).toHaveBeenCalledWith( - mockAuthConfig + mockAuthConfig, ); expect(mockTokenStoreInstance.setKeyValueStorage).toHaveBeenCalledWith( - mockKeyValueStorage + mockKeyValueStorage, ); expect(MockTokenOrchestrator).toHaveBeenCalledTimes(1); const mockTokenOrchestratorInstance = MockTokenOrchestrator.mock.instances[0]; expect(mockTokenOrchestratorInstance.setAuthConfig).toHaveBeenCalledWith( - mockAuthConfig + mockAuthConfig, ); expect( - mockTokenOrchestratorInstance.setAuthTokenStore + mockTokenOrchestratorInstance.setAuthTokenStore, ).toHaveBeenCalledWith(mockTokenStoreInstance); expect( - mockTokenOrchestratorInstance.setTokenRefresher + mockTokenOrchestratorInstance.setTokenRefresher, ).toHaveBeenCalledWith(mockRefreshAuthTokens); expect(tokenProvider).toBeDefined(); @@ -68,7 +68,7 @@ describe('createUserPoolsTokenProvider', () => { it('should call TokenOrchestrator.getTokens method with the default forceRefresh value', async () => { const tokenProvider = createUserPoolsTokenProvider( mockAuthConfig, - mockKeyValueStorage + mockKeyValueStorage, ); const mockTokenOrchestratorInstance = MockTokenOrchestrator.mock.instances[0]; @@ -83,7 +83,7 @@ describe('createUserPoolsTokenProvider', () => { it('should call TokenOrchestrator.getTokens method with the specified forceRefresh value', async () => { const tokenProvider = createUserPoolsTokenProvider( mockAuthConfig, - mockKeyValueStorage + mockKeyValueStorage, ); const mockTokenOrchestratorInstance = MockTokenOrchestrator.mock.instances[0]; diff --git a/packages/aws-amplify/__tests__/adapterCore/runWithAmplifyServerContext.test.ts b/packages/aws-amplify/__tests__/adapterCore/runWithAmplifyServerContext.test.ts index 1c9c727c627..6208e52fb4c 100644 --- a/packages/aws-amplify/__tests__/adapterCore/runWithAmplifyServerContext.test.ts +++ b/packages/aws-amplify/__tests__/adapterCore/runWithAmplifyServerContext.test.ts @@ -43,7 +43,7 @@ describe('runWithAmplifyServerContext', () => { credentialsProvider: mockCredentialAndIdentityProvider, }, }, - mockOperation + mockOperation, ); expect(mockOperation).toHaveBeenCalledWith(mockContextSpec); @@ -59,11 +59,11 @@ describe('runWithAmplifyServerContext', () => { credentialsProvider: mockCredentialAndIdentityProvider, }, }, - mockOperation + mockOperation, ); expect(mockDestroyAmplifyServerContext).toHaveBeenCalledWith( - mockContextSpec + mockContextSpec, ); }); @@ -81,12 +81,12 @@ describe('runWithAmplifyServerContext', () => { credentialsProvider: mockCredentialAndIdentityProvider, }, }, - mockOperation - ) + mockOperation, + ), ).rejects.toThrow(testError); expect(mockDestroyAmplifyServerContext).toHaveBeenCalledWith( - mockContextSpec + mockContextSpec, ); }); @@ -103,7 +103,7 @@ describe('runWithAmplifyServerContext', () => { credentialsProvider: mockCredentialAndIdentityProvider, }, }, - mockOperation + mockOperation, ); expect(result).toStrictEqual(mockResultValue); diff --git a/packages/aws-amplify/__tests__/adapterCore/storageFactories/createKeyValueStorageFromCookieStorageAdapter.test.ts b/packages/aws-amplify/__tests__/adapterCore/storageFactories/createKeyValueStorageFromCookieStorageAdapter.test.ts index 55bbedc713b..f1d5a878b00 100644 --- a/packages/aws-amplify/__tests__/adapterCore/storageFactories/createKeyValueStorageFromCookieStorageAdapter.test.ts +++ b/packages/aws-amplify/__tests__/adapterCore/storageFactories/createKeyValueStorageFromCookieStorageAdapter.test.ts @@ -15,7 +15,7 @@ describe('keyValueStorage', () => { describe('createKeyValueStorageFromCookiesStorageAdapter', () => { it('should return a key value storage', () => { const keyValueStorage = createKeyValueStorageFromCookieStorageAdapter( - mockCookiesStorageAdapter + mockCookiesStorageAdapter, ); expect(keyValueStorage).toBeDefined(); @@ -23,7 +23,7 @@ describe('keyValueStorage', () => { describe('the returned key value storage', () => { const keyValueStorage = createKeyValueStorageFromCookieStorageAdapter( - mockCookiesStorageAdapter + mockCookiesStorageAdapter, ); it('should set item', async () => { @@ -36,7 +36,7 @@ describe('keyValueStorage', () => { { ...defaultSetCookieOptions, expires: expect.any(Date), - } + }, ); }); @@ -50,7 +50,7 @@ describe('keyValueStorage', () => { { ...defaultSetCookieOptions, expires: expect.any(Date), - } + }, ); }); diff --git a/packages/aws-amplify/__tests__/exports.test.ts b/packages/aws-amplify/__tests__/exports.test.ts index 00f13a71928..c4e2a4dce1e 100644 --- a/packages/aws-amplify/__tests__/exports.test.ts +++ b/packages/aws-amplify/__tests__/exports.test.ts @@ -42,7 +42,7 @@ describe('aws-amplify Exports', () => { 'parseAmplifyConfig', 'sessionStorage', 'sharedInMemoryStorage', - ].sort() + ].sort(), ); }); }); @@ -63,7 +63,7 @@ describe('aws-amplify Exports', () => { 'post', 'put', 'ApiError', - ].sort() + ].sort(), ); }); }); @@ -79,31 +79,31 @@ describe('aws-amplify Exports', () => { 'enable', 'disable', 'AnalyticsError', - ].sort() + ].sort(), ); }); it('should only export expected symbols from the Pinpoint provider', () => { expect(Object.keys(analyticsPinpointExports).sort()).toEqual( - ['record', 'identifyUser', 'configureAutoTrack', 'flushEvents'].sort() + ['record', 'identifyUser', 'configureAutoTrack', 'flushEvents'].sort(), ); }); it('should only export expected symbols from the Kinesis provider', () => { expect(Object.keys(analyticsKinesisExports).sort()).toEqual( - ['record', 'flushEvents'].sort() + ['record', 'flushEvents'].sort(), ); }); it('should only export expected symbols from the Kinesis Firehose provider', () => { expect(Object.keys(analyticsKinesisFirehoseExports).sort()).toEqual( - ['record', 'flushEvents'].sort() + ['record', 'flushEvents'].sort(), ); }); it('should only export expected symbols from the Personalize provider', () => { expect(Object.keys(analyticsPersonalizeExports).sort()).toEqual( - ['record', 'flushEvents'].sort() + ['record', 'flushEvents'].sort(), ); }); }); @@ -123,7 +123,7 @@ describe('aws-amplify Exports', () => { 'onMessageActionTaken', 'notifyMessageInteraction', 'clearMessages', - ].sort() + ].sort(), ); }); @@ -141,7 +141,7 @@ describe('aws-amplify Exports', () => { 'onMessageActionTaken', 'notifyMessageInteraction', 'clearMessages', - ].sort() + ].sort(), ); }); }); @@ -179,7 +179,7 @@ describe('aws-amplify Exports', () => { 'autoSignIn', 'fetchAuthSession', 'decodeJWT', - ].sort() + ].sort(), ); }); @@ -219,7 +219,7 @@ describe('aws-amplify Exports', () => { 'TokenOrchestrator', 'DefaultTokenStore', 'refreshAuthTokens', - ].sort() + ].sort(), ); }); }); @@ -237,7 +237,7 @@ describe('aws-amplify Exports', () => { 'getUrl', 'isCancelError', 'StorageError', - ].sort() + ].sort(), ); }); @@ -251,7 +251,7 @@ describe('aws-amplify Exports', () => { 'getProperties', 'copy', 'getUrl', - ].sort() + ].sort(), ); }); }); diff --git a/packages/aws-amplify/__tests__/initSingleton.test.ts b/packages/aws-amplify/__tests__/initSingleton.test.ts index 39523fe9298..dec181ca74a 100644 --- a/packages/aws-amplify/__tests__/initSingleton.test.ts +++ b/packages/aws-amplify/__tests__/initSingleton.test.ts @@ -122,7 +122,7 @@ describe('initSingleton (DefaultAmplify)', () => { expect(mockAmplifySingletonConfigure).toHaveBeenCalledWith( resourcesConfig, - expect.anything() + expect.anything(), ); }); @@ -133,7 +133,7 @@ describe('initSingleton (DefaultAmplify)', () => { expect(mockAmplifySingletonConfigure).toHaveBeenCalledWith( resourceConfig, - libraryOptions + libraryOptions, ); }); @@ -146,7 +146,7 @@ describe('initSingleton (DefaultAmplify)', () => { expect(mockAmplifySingletonConfigure).toHaveBeenCalledWith( mockResourceConfig, - libraryOptions + libraryOptions, ); }); @@ -156,11 +156,11 @@ describe('initSingleton (DefaultAmplify)', () => { Amplify.configure(mockResourceConfig, libraryOptions); expect( - mockCognitoUserPoolsTokenProviderSetAuthConfig + mockCognitoUserPoolsTokenProviderSetAuthConfig, ).toHaveBeenCalledWith(mockResourceConfig.Auth); expect(MockCookieStorage).toHaveBeenCalledWith({ sameSite: 'lax' }); expect( - mockCognitoUserPoolsTokenProviderSetKeyValueStorage + mockCognitoUserPoolsTokenProviderSetKeyValueStorage, ).toHaveBeenCalledWith(mockCookieStorageInstance); expect(mockAmplifySingletonConfigure).toHaveBeenCalledWith( mockResourceConfig, @@ -170,7 +170,7 @@ describe('initSingleton (DefaultAmplify)', () => { tokenProvider: cognitoUserPoolsTokenProvider, credentialsProvider: cognitoCredentialsProvider, }, - } + }, ); }); @@ -179,10 +179,10 @@ describe('initSingleton (DefaultAmplify)', () => { Amplify.configure(mockResourceConfig, libraryOptions); expect( - mockCognitoUserPoolsTokenProviderSetAuthConfig + mockCognitoUserPoolsTokenProviderSetAuthConfig, ).toHaveBeenCalledWith(mockResourceConfig.Auth); expect( - mockCognitoUserPoolsTokenProviderSetKeyValueStorage + mockCognitoUserPoolsTokenProviderSetKeyValueStorage, ).toHaveBeenCalledWith(defaultStorage); expect(mockAmplifySingletonConfigure).toHaveBeenCalledWith( mockResourceConfig, @@ -192,7 +192,7 @@ describe('initSingleton (DefaultAmplify)', () => { tokenProvider: cognitoUserPoolsTokenProvider, credentialsProvider: cognitoCredentialsProvider, }, - } + }, ); }); }); @@ -212,18 +212,18 @@ describe('initSingleton (DefaultAmplify)', () => { Amplify.configure(mockResourceConfig, libraryOptions); expect( - mockCognitoUserPoolsTokenProviderSetAuthConfig + mockCognitoUserPoolsTokenProviderSetAuthConfig, ).not.toHaveBeenCalled(); expect(MockCookieStorage).toHaveBeenCalledWith({ sameSite: 'lax' }); expect( - mockCognitoUserPoolsTokenProviderSetKeyValueStorage + mockCognitoUserPoolsTokenProviderSetKeyValueStorage, ).toHaveBeenCalledWith(mockCookieStorageInstance); expect(mockAmplifySingletonConfigure).toHaveBeenCalledWith( mockResourceConfig, { Auth: AmplifySingleton.libraryOptions.Auth, ...libraryOptions, - } + }, ); }); @@ -232,17 +232,17 @@ describe('initSingleton (DefaultAmplify)', () => { Amplify.configure(mockResourceConfig, libraryOptions); expect( - mockCognitoUserPoolsTokenProviderSetAuthConfig + mockCognitoUserPoolsTokenProviderSetAuthConfig, ).not.toHaveBeenCalled(); expect( - mockCognitoUserPoolsTokenProviderSetKeyValueStorage + mockCognitoUserPoolsTokenProviderSetKeyValueStorage, ).toHaveBeenCalledWith(defaultStorage); expect(mockAmplifySingletonConfigure).toHaveBeenCalledWith( mockResourceConfig, { Auth: AmplifySingleton.libraryOptions.Auth, ...libraryOptions, - } + }, ); }); @@ -253,18 +253,18 @@ describe('initSingleton (DefaultAmplify)', () => { Amplify.configure(mockResourceConfig, libraryOptions); expect( - mockCognitoUserPoolsTokenProviderSetAuthConfig + mockCognitoUserPoolsTokenProviderSetAuthConfig, ).not.toHaveBeenCalled(); expect(MockCookieStorage).not.toHaveBeenCalled(); expect( - mockCognitoUserPoolsTokenProviderSetKeyValueStorage + mockCognitoUserPoolsTokenProviderSetKeyValueStorage, ).not.toHaveBeenCalled(); expect(mockAmplifySingletonConfigure).toHaveBeenCalledWith( mockResourceConfig, { Auth: AmplifySingleton.libraryOptions.Auth, ...libraryOptions, - } + }, ); }); @@ -272,7 +272,7 @@ describe('initSingleton (DefaultAmplify)', () => { Amplify.configure(mockResourceConfig); expect(mockAmplifySingletonConfigure).toHaveBeenCalledWith( - mockResourceConfig + mockResourceConfig, ); }); }); @@ -304,7 +304,7 @@ describe('initSingleton (DefaultAmplify)', () => { credentialsProvider: cognitoCredentialsProvider, }, ...libraryOptionsWithStorage, - } + }, ); }); }); diff --git a/packages/core/__mocks__/AsyncStorage.js b/packages/core/__mocks__/AsyncStorage.js index 484929fe26a..38a0c023d9a 100644 --- a/packages/core/__mocks__/AsyncStorage.js +++ b/packages/core/__mocks__/AsyncStorage.js @@ -1,5 +1,5 @@ const AsyncStorage = jest.genMockFromModule( - '@react-native-async-storage/async-storage' + '@react-native-async-storage/async-storage', ); var store = {}; diff --git a/packages/core/__tests__/BackgroundProcessManager.test.ts b/packages/core/__tests__/BackgroundProcessManager.test.ts index 8985996c7ab..c06cccc6d46 100644 --- a/packages/core/__tests__/BackgroundProcessManager.test.ts +++ b/packages/core/__tests__/BackgroundProcessManager.test.ts @@ -56,7 +56,7 @@ describe('BackgroundProcessManager', () => { await expect( manager.add(async () => { throw new Error('not today, friend!'); - }) + }), ).rejects.toThrow('not today, friend!'); }); @@ -66,7 +66,7 @@ describe('BackgroundProcessManager', () => { await expect( manager.add(async () => { throw new Error('Enough shenanigans!'); - }) + }), ).rejects.toThrow(); await expect(manager.close()).resolves.not.toThrow(); @@ -126,7 +126,9 @@ describe('BackgroundProcessManager', () => { await manager.close(); expect( - manager.add(async () => Promise.resolve('This should never be returned.')) + manager.add(async () => + Promise.resolve('This should never be returned.'), + ), ).rejects.toThrow('BackgroundManagerNotOpenError'); }); @@ -487,7 +489,7 @@ describe('BackgroundProcessManager', () => { terminateSignalCount++; setTimeout(resolve, 150); }); - }) + }), ); // accumulate a bunch of close promises, only the first of which should @@ -499,7 +501,7 @@ describe('BackgroundProcessManager', () => { expect(terminateSignalCount).toEqual(1); expect(resolved.map(r => r.status).every(v => v === 'fulfilled')).toBe( - true + true, ); }); @@ -516,8 +518,8 @@ describe('BackgroundProcessManager', () => { setTimeout(() => { proof = true; resolve(); - }, 10) - ) + }, 10), + ), ); await outer.close(); @@ -538,8 +540,8 @@ describe('BackgroundProcessManager', () => { onTerminate.then(() => { proof = true; resolve(); - }) - ) + }), + ), ); await new Promise(resolve => setTimeout(resolve, 1)); @@ -555,7 +557,7 @@ describe('BackgroundProcessManager', () => { manager.add( async () => new Promise(unsleep => setTimeout(unsleep, 1)), - 'async function' + 'async function', ); expect(manager.pending.length).toBe(1); @@ -573,7 +575,7 @@ describe('BackgroundProcessManager', () => { new Promise(finishJob => { onTerminate.then(finishJob); }), - 'cancelable async function' + 'cancelable async function', ); expect(manager.pending.length).toBe(1); @@ -626,7 +628,7 @@ describe('BackgroundProcessManager', () => { await manager.close(); await expect(manager.add(async () => {}, 'some job')).rejects.toThrow( - 'some job' + 'some job', ); }); @@ -636,13 +638,13 @@ describe('BackgroundProcessManager', () => { let unblock; manager.add( () => new Promise(_unblock => (unblock = _unblock)), - 'blocking job' + 'blocking job', ); const close = manager.close(); await expect(manager.add(async () => {}, 'some job')).rejects.toThrow( - 'blocking job' + 'blocking job', ); unblock(); diff --git a/packages/core/__tests__/Cache/StorageCache.test.ts b/packages/core/__tests__/Cache/StorageCache.test.ts index 4826662bbd3..c30474f5374 100644 --- a/packages/core/__tests__/Cache/StorageCache.test.ts +++ b/packages/core/__tests__/Cache/StorageCache.test.ts @@ -98,7 +98,7 @@ describe('StorageCache', () => { const cache = getStorageCache(config); expect( - await cache.testGetAllCacheKeys({ omitSizeKey: true }) + await cache.testGetAllCacheKeys({ omitSizeKey: true }), ).toStrictEqual(keys.slice(1)); }); @@ -108,7 +108,7 @@ describe('StorageCache', () => { 'some-other-prefixed-key', ]; mockStorageKey.mockImplementation( - (index: number) => extendedCachedKeys[index] + (index: number) => extendedCachedKeys[index], ); mockGetLocalStorageWithFallback.mockReturnValue({ ...mockStorage, @@ -117,7 +117,7 @@ describe('StorageCache', () => { const cache = getStorageCache(config); expect( - await cache.testGetAllCacheKeys({ omitSizeKey: true }) + await cache.testGetAllCacheKeys({ omitSizeKey: true }), ).toStrictEqual(keys.slice(1)); }); }); diff --git a/packages/core/__tests__/Cache/StorageCacheCommon.test.ts b/packages/core/__tests__/Cache/StorageCacheCommon.test.ts index 3fd95976c96..ea997dac41b 100644 --- a/packages/core/__tests__/Cache/StorageCacheCommon.test.ts +++ b/packages/core/__tests__/Cache/StorageCacheCommon.test.ts @@ -105,7 +105,7 @@ describe('StorageCacheCommon', () => { defaultPriority: 0, }); expect(cache.testGetConfig().defaultPriority).toBe( - defaultConfig.defaultPriority + defaultConfig.defaultPriority, ); expect(loggerSpy.error).toHaveBeenCalled(); }); @@ -116,7 +116,7 @@ describe('StorageCacheCommon', () => { defaultPriority: 6, }); expect(cache.testGetConfig().defaultPriority).toBe( - defaultConfig.defaultPriority + defaultConfig.defaultPriority, ); expect(loggerSpy.error).toHaveBeenCalled(); }); @@ -127,7 +127,7 @@ describe('StorageCacheCommon', () => { warningThreshold: -1, }); expect(cache.testGetConfig().warningThreshold).toBe( - defaultConfig.warningThreshold + defaultConfig.warningThreshold, ); expect(loggerSpy.error).toHaveBeenCalled(); }); @@ -138,7 +138,7 @@ describe('StorageCacheCommon', () => { warningThreshold: 2, }); expect(cache.testGetConfig().warningThreshold).toBe( - defaultConfig.warningThreshold + defaultConfig.warningThreshold, ); expect(loggerSpy.error).toHaveBeenCalled(); }); @@ -150,7 +150,7 @@ describe('StorageCacheCommon', () => { capacityInBytes: cacheLimit + 1, }); expect(cache.testGetConfig().capacityInBytes).toBe( - defaultConfig.capacityInBytes + defaultConfig.capacityInBytes, ); expect(loggerSpy.error).toHaveBeenCalled(); }); @@ -201,7 +201,7 @@ describe('StorageCacheCommon', () => { expect(await cache.getCurrentCacheSize()).toBe(0); expect(mockKeyValueStorageSetItem).toHaveBeenCalledWith( currentSizeKey, - '0' + '0', ); }); }); @@ -225,18 +225,18 @@ describe('StorageCacheCommon', () => { ])('sets an item if it does not exist (%s}', async (_, value: any) => { await cache.setItem(key, value); expect(loggerSpy.debug).toHaveBeenCalledWith( - expect.stringContaining(`Set item: key is ${key}`) + expect.stringContaining(`Set item: key is ${key}`), ); expect(mockKeyValueStorageSetItem).toHaveBeenCalledWith( prefixedKey, - expect.stringContaining(JSON.stringify(value)) + expect.stringContaining(JSON.stringify(value)), ); }); it('aborts on empty key', async () => { await cache.setItem('', 'abc'); expect(loggerSpy.warn).toHaveBeenCalledWith( - expect.stringContaining('Invalid key') + expect.stringContaining('Invalid key'), ); expect(mockKeyValueStorageSetItem).not.toHaveBeenCalled(); }); @@ -244,7 +244,7 @@ describe('StorageCacheCommon', () => { it('aborts on reserved key', async () => { await cache.setItem('CurSize', 'abc'); expect(loggerSpy.warn).toHaveBeenCalledWith( - expect.stringContaining('Invalid key') + expect.stringContaining('Invalid key'), ); expect(mockKeyValueStorageSetItem).not.toHaveBeenCalled(); }); @@ -252,7 +252,7 @@ describe('StorageCacheCommon', () => { it('aborts on undefined value', async () => { await cache.setItem(key, undefined); expect(loggerSpy.warn).toHaveBeenCalledWith( - expect.stringContaining('should not be undefined') + expect.stringContaining('should not be undefined'), ); expect(mockKeyValueStorageGetItem).not.toHaveBeenCalled(); }); @@ -260,7 +260,7 @@ describe('StorageCacheCommon', () => { it('aborts if priority is below minimum', async () => { await cache.setItem(key, 'abc', { priority: 0 }); expect(loggerSpy.warn).toHaveBeenCalledWith( - expect.stringContaining('Invalid parameter') + expect.stringContaining('Invalid parameter'), ); expect(mockKeyValueStorageGetItem).not.toHaveBeenCalled(); }); @@ -268,19 +268,19 @@ describe('StorageCacheCommon', () => { it('aborts if priority is above maximum', async () => { await cache.setItem(key, 'abc', { priority: 6 }); expect(loggerSpy.warn).toHaveBeenCalledWith( - expect.stringContaining('Invalid parameter') + expect.stringContaining('Invalid parameter'), ); expect(mockKeyValueStorageGetItem).not.toHaveBeenCalled(); }); it('aborts if item size is above maximum', async () => { mockGetByteLength.mockImplementation( - jest.requireActual('../../src/Cache/utils').getByteLength + jest.requireActual('../../src/Cache/utils').getByteLength, ); const value = 'x'.repeat(config.itemMaxSize * 2); await cache.setItem(key, value); expect(loggerSpy.warn).toHaveBeenCalledWith( - expect.stringContaining('is too big') + expect.stringContaining('is too big'), ); expect(mockKeyValueStorageGetItem).not.toHaveBeenCalled(); }); @@ -300,12 +300,12 @@ describe('StorageCacheCommon', () => { expect(mockKeyValueStorageGetItem).toHaveBeenCalledTimes(5); expect(mockKeyValueStorageSetItem).toHaveBeenCalledWith( currentSizeKey, - '15' + '15', ); // 25 - 10 expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledTimes(1); expect(mockKeyValueStorageSetItem).toHaveBeenCalledWith( currentSizeKey, - '35' + '35', ); // 15 + 20 expect(mockKeyValueStorageSetItem).toHaveBeenCalledWith( prefixedKey, @@ -318,7 +318,7 @@ describe('StorageCacheCommon', () => { expires: currentTime + config.defaultTTL, type: 'string', byteSize: 20, - }) + }), ); }); @@ -343,7 +343,7 @@ describe('StorageCacheCommon', () => { expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledTimes(1); expect(mockKeyValueStorageSetItem).toHaveBeenCalledWith( prefixedKey, - expect.stringContaining(value) + expect.stringContaining(value), ); }); @@ -392,14 +392,14 @@ describe('StorageCacheCommon', () => { await cache.setItem(key, value); expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledTimes(2); expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith( - lowPriorityItem.key + lowPriorityItem.key, ); expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith( - mediumPriorityItem.key + mediumPriorityItem.key, ); expect(mockKeyValueStorageSetItem).toHaveBeenCalledWith( prefixedKey, - expect.stringContaining(value) + expect.stringContaining(value), ); }); @@ -449,14 +449,14 @@ describe('StorageCacheCommon', () => { await cache.setItem(key, value); expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledTimes(2); expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith( - lastVisitedItem.key + lastVisitedItem.key, ); expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith( - recentlyVistedItem.key + recentlyVistedItem.key, ); expect(mockKeyValueStorageSetItem).toHaveBeenCalledWith( prefixedKey, - expect.stringContaining(value) + expect.stringContaining(value), ); }); }); @@ -473,12 +473,12 @@ describe('StorageCacheCommon', () => { it('gets an item', async () => { mockKeyValueStorageGetItem.mockReturnValue( - JSON.stringify({ data: value }) + JSON.stringify({ data: value }), ); expect(await cache.getItem(key)).toBe(value); expect(loggerSpy.debug).toHaveBeenCalledWith( - expect.stringContaining(`Get item: key is ${key}`) + expect.stringContaining(`Get item: key is ${key}`), ); expect(mockKeyValueStorageGetItem).toHaveBeenCalledWith(prefixedKey); }); @@ -486,7 +486,7 @@ describe('StorageCacheCommon', () => { it('aborts on empty key', async () => { expect(await cache.getItem('')).toBeNull(); expect(loggerSpy.warn).toHaveBeenCalledWith( - expect.stringContaining('Invalid key') + expect.stringContaining('Invalid key'), ); expect(mockKeyValueStorageGetItem).not.toHaveBeenCalled(); }); @@ -494,7 +494,7 @@ describe('StorageCacheCommon', () => { it('aborts on reserved key', async () => { expect(await cache.getItem('CurSize')).toBeNull(); expect(loggerSpy.warn).toHaveBeenCalledWith( - expect.stringContaining('Invalid key') + expect.stringContaining('Invalid key'), ); expect(mockKeyValueStorageGetItem).not.toHaveBeenCalled(); }); @@ -505,7 +505,7 @@ describe('StorageCacheCommon', () => { data: value, byteSize: 10, expires: currentTime - 10, - }) + }), ); expect(await cache.getItem(key)).toBeNull(); @@ -524,7 +524,7 @@ describe('StorageCacheCommon', () => { expect(mockKeyValueStorageGetItem).toHaveBeenCalledWith(prefixedKey); expect(mockKeyValueStorageSetItem).toHaveBeenCalledWith( prefixedKey, - JSON.stringify({ ...item, visitedTime: currentTime }) + JSON.stringify({ ...item, visitedTime: currentTime }), ); }); @@ -544,14 +544,14 @@ describe('StorageCacheCommon', () => { beforeEach(() => { mockKeyValueStorageGetItem.mockReturnValue( - JSON.stringify({ byteSize: 10 }) + JSON.stringify({ byteSize: 10 }), ); }); it('removes an item', async () => { await cache.removeItem(key); expect(loggerSpy.debug).toHaveBeenCalledWith( - expect.stringContaining(`Remove item: key is ${key}`) + expect.stringContaining(`Remove item: key is ${key}`), ); expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith(prefixedKey); }); @@ -559,7 +559,7 @@ describe('StorageCacheCommon', () => { it('aborts on empty key', async () => { await cache.removeItem(''); expect(loggerSpy.warn).toHaveBeenCalledWith( - expect.stringContaining('Invalid key') + expect.stringContaining('Invalid key'), ); expect(mockKeyValueStorageRemoveItem).not.toHaveBeenCalled(); }); @@ -567,7 +567,7 @@ describe('StorageCacheCommon', () => { it('aborts on reserved key', async () => { await cache.removeItem('CurSize'); expect(loggerSpy.warn).toHaveBeenCalledWith( - expect.stringContaining('Invalid key') + expect.stringContaining('Invalid key'), ); expect(mockKeyValueStorageRemoveItem).not.toHaveBeenCalled(); }); diff --git a/packages/core/__tests__/DateUtils.test.ts b/packages/core/__tests__/DateUtils.test.ts index 10541d47dad..d0ed93fd7fe 100644 --- a/packages/core/__tests__/DateUtils.test.ts +++ b/packages/core/__tests__/DateUtils.test.ts @@ -31,7 +31,7 @@ describe('DateUtils', () => { describe('getDateWithClockOffset()', () => { it('should return a new Date()', () => { expect(DateUtils.getDateWithClockOffset()).toEqual( - new Date(new Date().getTime() + 1000) + new Date(new Date().getTime() + 1000), ); }); }); @@ -40,7 +40,7 @@ describe('DateUtils', () => { describe('getHeaderStringFromDate', () => { it('should return YYYYMMDDTHHMMSSZ', () => { expect( - DateUtils.getHeaderStringFromDate(new Date()) + DateUtils.getHeaderStringFromDate(new Date()), ).toMatchInlineSnapshot(`"20200101T000000Z"`); }); }); @@ -48,7 +48,7 @@ describe('DateUtils', () => { describe('getDateFromHeaderString', () => { it('should return YYYYMMDDTHHMMSSZ', () => { expect( - DateUtils.getDateFromHeaderString('20200101T000000Z') + DateUtils.getDateFromHeaderString('20200101T000000Z'), ).toMatchInlineSnapshot(`2020-01-01T00:00:00.000Z`); }); }); @@ -97,7 +97,7 @@ describe('DateUtils', () => { it('should be false for normal errors', () => { expect(DateUtils.isClockSkewError(new Error('Response error'))).toBe( - false + false, ); }); }); diff --git a/packages/core/__tests__/Hub.test.ts b/packages/core/__tests__/Hub.test.ts index 0bf5c17bc11..141ebbed16f 100644 --- a/packages/core/__tests__/Hub.test.ts +++ b/packages/core/__tests__/Hub.test.ts @@ -21,7 +21,7 @@ describe('Hub', () => { message: 'User singout has taken place', }, 'Auth', - Symbol.for('amplify_default') + Symbol.for('amplify_default'), ); expect(listener).toHaveBeenCalled(); @@ -39,13 +39,13 @@ describe('Hub', () => { data: 'the user has been signed out', message: 'User singout has taken place', }, - 'Auth' + 'Auth', ); expect(listener).toHaveBeenCalled(); expect(loggerSpy).toHaveBeenCalledWith( 'WARN', - 'WARNING: auth is protected and dispatching on it can have unintended consequences' + 'WARNING: auth is protected and dispatching on it can have unintended consequences', ); }); @@ -63,7 +63,7 @@ describe('Hub', () => { expect(listener).toHaveBeenCalled(); expect(loggerSpy).toHaveBeenCalledWith( 'WARN', - 'WARNING: ui is protected and dispatching on it can have unintended consequences' + 'WARNING: ui is protected and dispatching on it can have unintended consequences', ); }); test('Remove listener', () => { @@ -79,7 +79,7 @@ describe('Hub', () => { message: 'User signout has taken place', }, 'Auth', - Symbol.for('amplify_default') + Symbol.for('amplify_default'), ); expect(listener).toHaveBeenCalled(); @@ -96,7 +96,7 @@ describe('Hub', () => { message: 'User signout has taken place', }, 'Auth', - Symbol.for('amplify_default') + Symbol.for('amplify_default'), ); expect(listener).not.toHaveBeenCalled(); @@ -134,7 +134,7 @@ describe('Hub', () => { message: 'User signout has taken place', }, 'Auth', - amplifySymbolValue + amplifySymbolValue, ); expect(loggerSpy).not.toHaveBeenCalled(); diff --git a/packages/core/__tests__/I18n.test.ts b/packages/core/__tests__/I18n.test.ts index 1ee77ac8e03..572425870cc 100644 --- a/packages/core/__tests__/I18n.test.ts +++ b/packages/core/__tests__/I18n.test.ts @@ -13,7 +13,7 @@ describe('I18n test', () => { let languageGetterSpy; beforeEach(() => { - languageGetterSpy = jest.spyOn(window.navigator, 'language', 'get') + languageGetterSpy = jest.spyOn(window.navigator, 'language', 'get'); }); test('no language', () => { @@ -67,14 +67,14 @@ describe('I18n test', () => { }); test('sets default language', () => { - languageGetterSpy.mockReturnValue('fr') + languageGetterSpy.mockReturnValue('fr'); const i18n = new I18n(); i18n.putVocabularies({ - 'fr': { + fr: { 'Sign In': 'Se connecter', - } + }, }); expect(i18n.get('Sign In')).toBe('Se connecter'); diff --git a/packages/core/__tests__/Mutex.test.ts b/packages/core/__tests__/Mutex.test.ts index c595e91cf94..e7335f292e5 100644 --- a/packages/core/__tests__/Mutex.test.ts +++ b/packages/core/__tests__/Mutex.test.ts @@ -36,7 +36,7 @@ describe('Mutex', function () { setTimeout(() => { flag = true; release(); - }, 50) + }, 50), ); return mutex.acquire().then(release => { @@ -63,7 +63,7 @@ describe('Mutex', function () { .runExclusive(() => Promise.reject('foo')) .then( () => Promise.reject('should have been rejected'), - value => expect(value).toBe('foo') + value => expect(value).toBe('foo'), ); }); @@ -74,7 +74,7 @@ describe('Mutex', function () { }) .then( () => Promise.reject('should have been rejected'), - value => expect(value).toBe('foo') + value => expect(value).toBe('foo'), ); }); @@ -87,8 +87,8 @@ describe('Mutex', function () { setTimeout(() => { flag = true; resolve(); - }, 50) - ) + }, 50), + ), ); return mutex.runExclusive(() => expect(flag).toBe(true)); @@ -104,7 +104,7 @@ describe('Mutex', function () { }) .then( () => undefined, - () => undefined + () => undefined, ); return mutex.runExclusive(() => expect(flag).toBe(true)); diff --git a/packages/core/__tests__/Platform/customUserAgent.test.ts b/packages/core/__tests__/Platform/customUserAgent.test.ts index 913872eb6db..6ce8a3a2684 100644 --- a/packages/core/__tests__/Platform/customUserAgent.test.ts +++ b/packages/core/__tests__/Platform/customUserAgent.test.ts @@ -35,7 +35,7 @@ describe('Custom user agent utilities', () => { const confirmSignInState = getCustomUserAgent( Category.Auth, - AuthAction.ConfirmSignIn + AuthAction.ConfirmSignIn, ); const signInState = getCustomUserAgent(Category.Auth, AuthAction.SignIn); const copyState = getCustomUserAgent(Category.Storage, StorageAction.Copy); @@ -54,14 +54,14 @@ describe('Custom user agent utilities', () => { cleanUp(); let confirmSignInState = getCustomUserAgent( Category.Auth, - AuthAction.ConfirmSignIn + AuthAction.ConfirmSignIn, ); expect(confirmSignInState).toStrictEqual([['uastate', 'auth']]); cleanUp2(); confirmSignInState = getCustomUserAgent( Category.Auth, - AuthAction.ConfirmSignIn + AuthAction.ConfirmSignIn, ); expect(confirmSignInState).toStrictEqual(undefined); diff --git a/packages/core/__tests__/Platform/userAgent.test.ts b/packages/core/__tests__/Platform/userAgent.test.ts index b363452b55c..88174e3d75f 100644 --- a/packages/core/__tests__/Platform/userAgent.test.ts +++ b/packages/core/__tests__/Platform/userAgent.test.ts @@ -54,7 +54,7 @@ describe('Platform test', () => { getAmplifyUserAgentObject({ category: Category.Auth, action: AuthAction.ConfirmSignIn, - }) + }), ).toStrictEqual([ ['aws-amplify', version], [Category.Auth, AuthAction.ConfirmSignIn], @@ -71,7 +71,7 @@ describe('Platform test', () => { getAmplifyUserAgentObject({ category: Category.Auth, action: AuthAction.ConfirmSignIn, - }) + }), ).toStrictEqual([ ['aws-amplify', version], [Category.Auth, AuthAction.ConfirmSignIn], @@ -85,7 +85,7 @@ describe('Platform test', () => { describe('getAmplifyUserAgent test', () => { test('without customUserAgentDetails', () => { expect(getAmplifyUserAgent()).toBe( - `${Platform.userAgent} framework/${Framework.WebUnknown}` + `${Platform.userAgent} framework/${Framework.WebUnknown}`, ); }); @@ -94,9 +94,9 @@ describe('Platform test', () => { getAmplifyUserAgent({ category: Category.Auth, action: AuthAction.ConfirmSignIn, - }) + }), ).toBe( - `${Platform.userAgent} ${Category.Auth}/${AuthAction.ConfirmSignIn} framework/${Framework.WebUnknown}` + `${Platform.userAgent} ${Category.Auth}/${AuthAction.ConfirmSignIn} framework/${Framework.WebUnknown}`, ); }); @@ -109,9 +109,9 @@ describe('Platform test', () => { getAmplifyUserAgent({ category: Category.Auth, action: AuthAction.ConfirmSignIn, - }) + }), ).toBe( - `${Platform.userAgent} ${Category.Auth}/${AuthAction.ConfirmSignIn} framework/${Framework.WebUnknown} uiversion/1.0.0 flag` + `${Platform.userAgent} ${Category.Auth}/${AuthAction.ConfirmSignIn} framework/${Framework.WebUnknown} uiversion/1.0.0 flag`, ); }); }); diff --git a/packages/core/__tests__/Retry.test.ts b/packages/core/__tests__/Retry.test.ts index a7834ec6151..a7389237985 100644 --- a/packages/core/__tests__/Retry.test.ts +++ b/packages/core/__tests__/Retry.test.ts @@ -30,7 +30,7 @@ describe('retry', () => { } await expect(retry(throwsNonRetryableError, [], () => 1)).rejects.toThrow( - 'bwahahahahaha' + 'bwahahahahaha', ); }); @@ -87,7 +87,7 @@ describe('retry', () => { } await expect(retry(alwaysFails, [], retryThreeTimes)).rejects.toThrow( - 'not today' + 'not today', ); expect(count).toEqual(3); }); @@ -158,7 +158,7 @@ describe('jitteredExponentialRetry', () => { const returnValue = await jitteredExponentialRetry( succeedAfterThirdTry, - [] + [], ); expect(returnValue).toEqual('abc'); @@ -171,7 +171,7 @@ describe('jitteredExponentialRetry', () => { } await expect( - jitteredExponentialRetry(throwsNonRetryableError, []) + jitteredExponentialRetry(throwsNonRetryableError, []), ).rejects.toThrow('bwahahahahaha'); }); @@ -202,7 +202,7 @@ describe('jitteredExponentialRetry', () => { manager .add(async onTerminate => - jitteredExponentialRetry(suchAFailure, [], undefined, onTerminate) + jitteredExponentialRetry(suchAFailure, [], undefined, onTerminate), ) .catch(e => (error = e)); diff --git a/packages/core/__tests__/ServiceWorker.test.ts b/packages/core/__tests__/ServiceWorker.test.ts index 8ee74b3f60c..f63e07aeed5 100644 --- a/packages/core/__tests__/ServiceWorker.test.ts +++ b/packages/core/__tests__/ServiceWorker.test.ts @@ -8,7 +8,7 @@ describe('ServiceWorker test', () => { const serviceWorker = new ServiceWorker(); return expect(serviceWorker.register()).rejects.toThrow( - 'Service Worker not available' + 'Service Worker not available', ); }); test('fails when enablePush and serviceworker is not registered', () => { @@ -97,7 +97,7 @@ describe('ServiceWorker test', () => { serviceWorker.send('A message'); return expect(bla.installing.postMessage).toHaveBeenCalledWith( - 'A message' + 'A message', ); }); test('can send object message after registration', async () => { @@ -115,7 +115,7 @@ describe('ServiceWorker test', () => { serviceWorker.send({ property: 'value' }); return expect(bla.installing.postMessage).toHaveBeenCalledWith( - JSON.stringify({ property: 'value' }) + JSON.stringify({ property: 'value' }), ); }); }); @@ -140,7 +140,7 @@ describe('ServiceWorker test', () => { await serviceWorker.register(); return expect(serviceWorker.enablePush('publickKey')).resolves.toBe( - subscription + subscription, ); }); test('can enable push when user is not subscribed', async () => { @@ -162,7 +162,7 @@ describe('ServiceWorker test', () => { await serviceWorker.register(); return expect(serviceWorker.enablePush('publickKey')).resolves.toBe( - subscription + subscription, ); }); }); diff --git a/packages/core/__tests__/Signer.test.ts b/packages/core/__tests__/Signer.test.ts index b5638ea2269..4e15f008282 100644 --- a/packages/core/__tests__/Signer.test.ts +++ b/packages/core/__tests__/Signer.test.ts @@ -40,15 +40,15 @@ describe('Signer.sign', () => { ...options, }; return [name, updatedRequest, updatedOptions, expectedAuthorization]; - } - ) + }, + ), )( 'signs request with %s', ( _, { url, ...request }, { credentials, signingRegion, signingService }, - expected + expected, ) => { const { accessKeyId, secretAccessKey, sessionToken } = credentials; const accessInfo = { @@ -63,10 +63,10 @@ describe('Signer.sign', () => { const signedRequest = Signer.sign( { ...request, url: url.toString() }, accessInfo as any, - serviceInfo as any + serviceInfo as any, ); expect(signedRequest.headers?.Authorization).toBe(expected); - } + }, ); describe('Error handling', () => { @@ -121,8 +121,8 @@ describe('Signer.sign', () => { } = Signer.sign(request as any, accessInfo as any, undefined as any); expect(Authorization).toEqual( expect.stringContaining( - 'Credential=access-key-id/20200918/us-east-1/foo/aws4_request' - ) + 'Credential=access-key-id/20200918/us-east-1/foo/aws4_request', + ), ); }); }); @@ -147,15 +147,15 @@ describe('Signer.signUrl', () => { ...options, }; return [name, updatedRequest, updatedOptions, expectedUrl]; - } - ) + }, + ), )( 'signs url with %s', ( _, { url, ...request }, { credentials, signingRegion, signingService }, - expected + expected, ) => { const { accessKeyId, secretAccessKey, sessionToken } = credentials; const accessInfo = { @@ -170,10 +170,10 @@ describe('Signer.signUrl', () => { const signedUrl = Signer.signUrl( { ...request, url: url.toString() }, accessInfo, - serviceInfo as any + serviceInfo as any, ); expect(signedUrl).toBe(expected); - } + }, ); test('should populate signing region and service from url', () => { @@ -189,8 +189,8 @@ describe('Signer.signUrl', () => { const signedUrl = Signer.signUrl(request, accessInfo); expect(signedUrl).toEqual( expect.stringContaining( - 'X-Amz-Credential=access-key-id%2F20200918%2Fus-east-1%2Ffoo%2Faws4_request' - ) + 'X-Amz-Credential=access-key-id%2F20200918%2Fus-east-1%2Ffoo%2Faws4_request', + ), ); }); @@ -212,7 +212,7 @@ describe('Signer.signUrl', () => { expect(signedUrl).toEqual(expect.stringContaining('X-Amz-Security-Token')); expect(getSignatureSpy).toBeCalledWith( expect.anything(), - expect.objectContaining({ sessionToken: undefined }) + expect.objectContaining({ sessionToken: undefined }), ); }); }); diff --git a/packages/core/__tests__/StringUtils.test.ts b/packages/core/__tests__/StringUtils.test.ts index b60ad97a958..8fa74b7236d 100644 --- a/packages/core/__tests__/StringUtils.test.ts +++ b/packages/core/__tests__/StringUtils.test.ts @@ -21,7 +21,7 @@ describe('StringUtils', () => { const encodedState = encodeURIComponent(urlSafeState); expect(urlSafeDecode(decodeURIComponent(encodedState))).toEqual( - complexCustomState + complexCustomState, ); }); }); diff --git a/packages/core/__tests__/adapterCore/serverContext.test.ts b/packages/core/__tests__/adapterCore/serverContext.test.ts index b78cb0dd3a6..ea6e2a55f1b 100644 --- a/packages/core/__tests__/adapterCore/serverContext.test.ts +++ b/packages/core/__tests__/adapterCore/serverContext.test.ts @@ -68,9 +68,9 @@ describe('serverContext', () => { it('should throw an error if the context is not found', () => { expect(() => - getAmplifyServerContext({ token: { value: Symbol('test') } }) + getAmplifyServerContext({ token: { value: Symbol('test') } }), ).toThrow( - 'Attempted to get the Amplify Server Context that may have been destroyed.' + 'Attempted to get the Amplify Server Context that may have been destroyed.', ); }); }); @@ -87,7 +87,7 @@ describe('serverContext', () => { destroyAmplifyServerContext(contextSpec); expect(() => getAmplifyServerContext(contextSpec)).toThrow( - 'Attempted to get the Amplify Server Context that may have been destroyed.' + 'Attempted to get the Amplify Server Context that may have been destroyed.', ); }); }); @@ -100,7 +100,7 @@ describe('serverContext', () => { { token: { value: 'bad-value' } }, ].forEach(invalidContextSpec => { expect(() => - getAmplifyServerContext(invalidContextSpec as any) + getAmplifyServerContext(invalidContextSpec as any), ).toThrowError('Invalid `contextSpec`.'); }); }); diff --git a/packages/core/__tests__/awsClients/cognitoIdentity/getCredentialsForIdentity.test.ts b/packages/core/__tests__/awsClients/cognitoIdentity/getCredentialsForIdentity.test.ts index 3c933fb05fc..8125a212b7d 100644 --- a/packages/core/__tests__/awsClients/cognitoIdentity/getCredentialsForIdentity.test.ts +++ b/packages/core/__tests__/awsClients/cognitoIdentity/getCredentialsForIdentity.test.ts @@ -58,16 +58,16 @@ describe('CognitoIdentity - getCredentialsForIdentity', () => { }; (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse(succeedResponse) + mockJsonResponse(succeedResponse), ); const response = await getCredentialsForIdentity( cognitoIdentityHandlerOptions, - params + params, ); expect(response).toEqual(expectedOutput); expect(fetchTransferHandler).toHaveBeenCalledWith( expectedRequest, - expect.anything() + expect.anything(), ); }); @@ -88,7 +88,7 @@ describe('CognitoIdentity - getCredentialsForIdentity', () => { message: failureResponse.body.message, }; (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse(failureResponse) + mockJsonResponse(failureResponse), ); expect.assertions(1); try { diff --git a/packages/core/__tests__/awsClients/cognitoIdentity/getId.test.ts b/packages/core/__tests__/awsClients/cognitoIdentity/getId.test.ts index a7d9794e9e1..4268cb73fe3 100644 --- a/packages/core/__tests__/awsClients/cognitoIdentity/getId.test.ts +++ b/packages/core/__tests__/awsClients/cognitoIdentity/getId.test.ts @@ -55,13 +55,13 @@ describe('CognitoIdentity - getId', () => { }), }; (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse(succeedResponse) + mockJsonResponse(succeedResponse), ); const response = await getId(cognitoIdentityHandlerOptions, params); expect(response).toEqual(expectedOutput); expect(fetchTransferHandler).toHaveBeenCalledWith( expectedRequest, - expect.anything() + expect.anything(), ); }); @@ -82,7 +82,7 @@ describe('CognitoIdentity - getId', () => { message: failureResponse.body.message, }; (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse(failureResponse) + mockJsonResponse(failureResponse), ); expect.assertions(1); try { diff --git a/packages/core/__tests__/awsClients/pinpoint/getInAppMessages.test.ts b/packages/core/__tests__/awsClients/pinpoint/getInAppMessages.test.ts index c0c2824baef..826254af149 100644 --- a/packages/core/__tests__/awsClients/pinpoint/getInAppMessages.test.ts +++ b/packages/core/__tests__/awsClients/pinpoint/getInAppMessages.test.ts @@ -58,13 +58,13 @@ describe('Pinpoint - getInAppMessages', () => { }), }; (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse(successfulResponse) + mockJsonResponse(successfulResponse), ); const response = await getInAppMessages(pinpointHandlerOptions, params); expect(response).toEqual(expectedOutput); expect(fetchTransferHandler).toHaveBeenCalledWith( expectedRequest, - expect.anything() + expect.anything(), ); }); @@ -74,7 +74,7 @@ describe('Pinpoint - getInAppMessages', () => { message: mockFailureResponse.body.message, }; (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse(mockFailureResponse) + mockJsonResponse(mockFailureResponse), ); expect.assertions(1); try { diff --git a/packages/core/__tests__/awsClients/pinpoint/putEvents.test.ts b/packages/core/__tests__/awsClients/pinpoint/putEvents.test.ts index 2dabea88145..f39335eaf60 100644 --- a/packages/core/__tests__/awsClients/pinpoint/putEvents.test.ts +++ b/packages/core/__tests__/awsClients/pinpoint/putEvents.test.ts @@ -57,13 +57,13 @@ describe('Pinpoint - putEvents', () => { }), }; (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse(successfulResponse) + mockJsonResponse(successfulResponse), ); const response = await putEvents(pinpointHandlerOptions, params); expect(response).toEqual(expectedOutput); expect(fetchTransferHandler).toHaveBeenCalledWith( expectedRequest, - expect.anything() + expect.anything(), ); }); @@ -73,7 +73,7 @@ describe('Pinpoint - putEvents', () => { message: mockFailureResponse.body.message, }; (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse(mockFailureResponse) + mockJsonResponse(mockFailureResponse), ); expect.assertions(1); try { diff --git a/packages/core/__tests__/awsClients/pinpoint/updateEndpoint.test.ts b/packages/core/__tests__/awsClients/pinpoint/updateEndpoint.test.ts index ece0cdb4ba0..3927c202a27 100644 --- a/packages/core/__tests__/awsClients/pinpoint/updateEndpoint.test.ts +++ b/packages/core/__tests__/awsClients/pinpoint/updateEndpoint.test.ts @@ -62,13 +62,13 @@ describe('Pinpoint - updateEndpoint', () => { }), }; (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse(successfulResponse) + mockJsonResponse(successfulResponse), ); const response = await updateEndpoint(pinpointHandlerOptions, params); expect(response).toEqual(expectedOutput); expect(fetchTransferHandler).toHaveBeenCalledWith( expectedRequest, - expect.anything() + expect.anything(), ); }); @@ -78,7 +78,7 @@ describe('Pinpoint - updateEndpoint', () => { message: mockFailureResponse.body.message, }; (fetchTransferHandler as jest.Mock).mockResolvedValue( - mockJsonResponse(mockFailureResponse) + mockJsonResponse(mockFailureResponse), ); expect.assertions(1); try { diff --git a/packages/core/__tests__/clients/composeApiHandler.test.ts b/packages/core/__tests__/clients/composeApiHandler.test.ts index 1c8ad49be5c..f9580604432 100644 --- a/packages/core/__tests__/clients/composeApiHandler.test.ts +++ b/packages/core/__tests__/clients/composeApiHandler.test.ts @@ -30,7 +30,7 @@ describe(composeServiceApi.name, () => { async output => ({ Result: 'from API', }), - defaultConfig + defaultConfig, ); const output = await api({ bar: 'baz', foo: 'foo' }, 'Input'); expect(mockTransferHandler).toHaveBeenCalledTimes(1); @@ -39,7 +39,7 @@ describe(composeServiceApi.name, () => { expect.objectContaining({ bar: 'baz', foo: 'foo', - }) + }), ); }); @@ -55,13 +55,13 @@ describe(composeServiceApi.name, () => { async output => ({ Result: 'from API', }), - defaultConfig + defaultConfig, ); await api(config, 'Input'); expect(defaultConfig.endpointResolver).toHaveBeenCalledTimes(1); expect(defaultConfig.endpointResolver).toHaveBeenCalledWith( config, - 'Input' + 'Input', ); }); @@ -79,13 +79,13 @@ describe(composeServiceApi.name, () => { mockTransferHandler, mockSerializer, mockDeserializer, - defaultConfig + defaultConfig, ); const output = await api({ bar: 'baz', foo: 'foo' }, 'Input'); expect(mockSerializer).toHaveBeenCalledTimes(1); expect(mockSerializer).toHaveBeenCalledWith( 'Input', - defaultConfig.endpointResolver.mock.results[0].value + defaultConfig.endpointResolver.mock.results[0].value, ); expect(mockDeserializer).toHaveBeenCalledTimes(1); expect(mockDeserializer).toHaveBeenCalledWith(defaultResponse); diff --git a/packages/core/__tests__/clients/composeTransferHandler.test.ts b/packages/core/__tests__/clients/composeTransferHandler.test.ts index 3cc459ebc0f..de7976c339d 100644 --- a/packages/core/__tests__/clients/composeTransferHandler.test.ts +++ b/packages/core/__tests__/clients/composeTransferHandler.test.ts @@ -20,7 +20,7 @@ describe(composeTransferHandler.name, () => { expect(resp).toEqual({ body: 'Response' }); expect(coreHandler).toHaveBeenCalledWith( { url: new URL('https://a.b') }, - { foo: 'bar' } + { foo: 'bar' }, ); }); @@ -47,19 +47,19 @@ describe(composeTransferHandler.name, () => { .mockResolvedValueOnce({ body: '' } as Response); const handler = composeTransferHandler<[OptionsType, OptionsType]>( coreHandler, - [middlewareA, middlewareB] + [middlewareA, middlewareB], ); const options = { mockFnInOptions: jest.fn(), }; const resp = await handler( { url: new URL('https://a.b'), body: '' }, - options + options, ); expect(resp).toEqual({ body: 'BA' }); expect(coreHandler).toHaveBeenCalledWith( expect.objectContaining({ body: 'AB' }), - expect.anything() + expect.anything(), ); // Validate middleware share a same option object expect(options.mockFnInOptions).toHaveBeenNthCalledWith(1, 'A'); @@ -69,12 +69,12 @@ describe(composeTransferHandler.name, () => { (coreHandler as jest.Mock).mockResolvedValueOnce({ body: '' } as Response); const resp2 = await handler( { url: new URL('https://a.b'), body: '' }, - options + options, ); expect(resp2).toEqual({ body: 'BA' }); expect(coreHandler).toHaveBeenCalledWith( expect.objectContaining({ body: 'AB' }), - expect.anything() + expect.anything(), ); }); }); diff --git a/packages/core/__tests__/clients/fetch.test.ts b/packages/core/__tests__/clients/fetch.test.ts index cc33ccb88d0..db72190c826 100644 --- a/packages/core/__tests__/clients/fetch.test.ts +++ b/packages/core/__tests__/clients/fetch.test.ts @@ -12,7 +12,7 @@ describe(fetchTransferHandler.name, () => { headers: { forEach: jest.fn() }, body: {}, }, - mockBody + mockBody, ); const mockRequest = { method: 'GET' as const, @@ -36,7 +36,7 @@ describe(fetchTransferHandler.name, () => { await fetchTransferHandler(mockRequest, { abortSignal: signal }); expect(mockFetch).toHaveBeenCalledTimes(1); expect(mockFetch.mock.calls[0][1]).toEqual( - expect.objectContaining({ signal }) + expect.objectContaining({ signal }), ); }); @@ -45,7 +45,7 @@ describe(fetchTransferHandler.name, () => { await fetchTransferHandler(mockRequest, { cache: cacheMode }); expect(mockFetch).toHaveBeenCalledTimes(1); expect(mockFetch.mock.calls[0][1]).toEqual( - expect.objectContaining({ cache: cacheMode }) + expect.objectContaining({ cache: cacheMode }), ); }); @@ -55,7 +55,7 @@ describe(fetchTransferHandler.name, () => { }); expect(mockFetch).toHaveBeenCalledTimes(1); expect(mockFetch.mock.calls[0][1]).toEqual( - expect.objectContaining({ credentials: 'include' }) + expect.objectContaining({ credentials: 'include' }), ); }); @@ -63,7 +63,7 @@ describe(fetchTransferHandler.name, () => { await fetchTransferHandler(mockRequest, {}); expect(mockFetch).toHaveBeenCalledTimes(1); expect(mockFetch.mock.calls[0][1]).toEqual( - expect.objectContaining({ credentials: 'same-origin' }) + expect.objectContaining({ credentials: 'same-origin' }), ); }); @@ -113,10 +113,10 @@ describe(fetchTransferHandler.name, () => { async method => { await fetchTransferHandler( { ...mockRequest, method, body: 'Mock Body' }, - {} + {}, ); expect(mockFetch).toHaveBeenCalledTimes(1); expect(mockFetch.mock.calls[0][0].body).toBeUndefined(); - } + }, ); }); diff --git a/packages/core/__tests__/clients/middleware/retry/middleware.test.ts b/packages/core/__tests__/clients/middleware/retry/middleware.test.ts index 3643e2c4f36..f17c422d37b 100644 --- a/packages/core/__tests__/clients/middleware/retry/middleware.test.ts +++ b/packages/core/__tests__/clients/middleware/retry/middleware.test.ts @@ -27,7 +27,9 @@ describe(`${retryMiddlewareFactory.name} middleware`, () => { headers: {}, }; const getRetryableHandler = (nextHandler: MiddlewareHandler) => - composeTransferHandler<[RetryOptions]>(nextHandler, [retryMiddlewareFactory]); + composeTransferHandler<[RetryOptions]>(nextHandler, [ + retryMiddlewareFactory, + ]); test('should retry specified times', async () => { const nextHandler = jest.fn().mockResolvedValue(defaultResponse); @@ -89,7 +91,7 @@ describe(`${retryMiddlewareFactory.name} middleware`, () => { const retryDecider = jest .fn() .mockImplementation( - (resp, error) => error.message !== 'UnretryableError' + (resp, error) => error.message !== 'UnretryableError', ); try { const resp = await retryableHandler(defaultRequest, { @@ -117,7 +119,7 @@ describe(`${retryMiddlewareFactory.name} middleware`, () => { computeDelay, }); expect(res).toEqual( - expect.objectContaining({ $metadata: { attempts: 6 } }) + expect.objectContaining({ $metadata: { attempts: 6 } }), ); expect(nextHandler).toHaveBeenCalledTimes(6); expect(computeDelay).toHaveBeenCalledTimes(5); // no interval after last attempt @@ -189,7 +191,11 @@ describe(`${retryMiddlewareFactory.name} middleware`, () => { const doubleRetryableHandler = composeTransferHandler< [RetryOptions, {}, RetryOptions] - >(coreHandler, [retryMiddlewareFactory, betweenRetryMiddleware, retryMiddlewareFactory]); + >(coreHandler, [ + retryMiddlewareFactory, + betweenRetryMiddleware, + retryMiddlewareFactory, + ]); const retryDecider = jest .fn() diff --git a/packages/core/__tests__/clients/middleware/signing/middleware.test.ts b/packages/core/__tests__/clients/middleware/signing/middleware.test.ts index 1b7a7cd8a8c..6c481ecc34c 100644 --- a/packages/core/__tests__/clients/middleware/signing/middleware.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/middleware.test.ts @@ -23,10 +23,10 @@ import { import { signingTestTable } from './signer/signatureV4/testUtils/signingTestTable'; jest.mock( - '../../../../src/clients/middleware/signing/utils/getSkewCorrectedDate' + '../../../../src/clients/middleware/signing/utils/getSkewCorrectedDate', ); jest.mock( - '../../../../src/clients/middleware/signing/utils/getUpdatedSystemClockOffset' + '../../../../src/clients/middleware/signing/utils/getUpdatedSystemClockOffset', ); const mockGetSkewCorrectedDate = getSkewCorrectedDate as jest.Mock; @@ -50,7 +50,7 @@ describe('Signing middleware', () => { const getSignableHandler = (nextHandler: MiddlewareHandler) => composeTransferHandler<[SigningOptions], HttpRequest, HttpResponse>( nextHandler, - [signingMiddlewareFactory] + [signingMiddlewareFactory], ); beforeEach(() => { jest.clearAllMocks(); @@ -69,7 +69,7 @@ describe('Signing middleware', () => { authorization: basicTestCase.expectedAuthorization, }), }), - expect.objectContaining(defaultSigningOptions) + expect.objectContaining(defaultSigningOptions), ); }); @@ -88,7 +88,7 @@ describe('Signing middleware', () => { expect.objectContaining({ ...defaultSigningOptions, systemClockOffset, - }) + }), ); }); @@ -107,7 +107,7 @@ describe('Signing middleware', () => { authorization: basicTestCase.expectedAuthorization, }), }), - expect.anything() + expect.anything(), ); expect(credentialsProvider).toHaveBeenCalledTimes(1); }); @@ -126,13 +126,13 @@ describe('Signing middleware', () => { }); const middlewareFunction = signingMiddlewareFactory(defaultSigningOptions)( - nextHandler + nextHandler, ); await middlewareFunction(defaultRequest); expect(mockGetUpdatedSystemClockOffset).toHaveBeenCalledWith( parsedServerTime, - 0 + 0, ); jest.clearAllMocks(); @@ -140,7 +140,7 @@ describe('Signing middleware', () => { expect(mockGetSkewCorrectedDate).toHaveBeenCalledWith(updatedOffset); expect(mockGetUpdatedSystemClockOffset).toHaveBeenCalledWith( parsedServerTime, - updatedOffset + updatedOffset, ); expect.assertions(3); }); diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/presignUrl.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/presignUrl.test.ts index cf78c0ce270..c27b1bdb6a8 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/presignUrl.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/presignUrl.test.ts @@ -19,10 +19,10 @@ jest.mock( .fn() .mockImplementation( jest.requireActual( - '../../../../../../src/clients/middleware/signing/signer/signatureV4/utils/getSignature' - ).getSignature + '../../../../../../src/clients/middleware/signing/signer/signatureV4/utils/getSignature', + ).getSignature, ), - }) + }), ); describe('presignUrl', () => { @@ -41,8 +41,8 @@ describe('presignUrl', () => { ...options, }; return [name, updatedRequest, updatedOptions, expectedUrl]; - } - ) + }, + ), )('presigns url with %s', (_, request, options, expected) => { expect(presignUrl(request, options).toString()).toBe(expected); }); diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/signRequest.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/signRequest.test.ts index 96ab22f234e..857f56a310b 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/signRequest.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/signRequest.test.ts @@ -19,10 +19,10 @@ jest.mock( .fn() .mockImplementation( jest.requireActual( - '../../../../../../src/clients/middleware/signing/signer/signatureV4/utils/getSignature' - ).getSignature + '../../../../../../src/clients/middleware/signing/signer/signatureV4/utils/getSignature', + ).getSignature, ), - }) + }), ); describe('signRequest', () => { @@ -41,8 +41,8 @@ describe('signRequest', () => { ...options, }; return [name, updatedRequest, updatedOptions, expectedAuthorization]; - } - ) + }, + ), )('signs request with %s', (_, request, options, expected) => { expect(signRequest(request, options).headers.authorization).toBe(expected); }); diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/testUtils/signingTestTable.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/testUtils/signingTestTable.ts index 2a219223add..575ce159b21 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/testUtils/signingTestTable.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/testUtils/signingTestTable.ts @@ -152,7 +152,7 @@ export const signingTestTable: TestCase[] = [ name: 'unreserved characters in url', request: { url: new URL( - `${url}-._~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz` + `${url}-._~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`, ), }, expectedAuthorization: diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.test.ts index b14eb7e9d74..b0e79a98a84 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.test.ts @@ -19,7 +19,7 @@ describe('dataHashHelpers', () => { 232, 228, 217, 152, 156, 118, 166, 42, 124, 217, 129, 99, 56, 163, 190, 131, 62, 148, 54, 170, 101, 55, 158, 118, 42, 239, 245, 136, 153, 115, 41, 156, - ]) + ]), ); expect(getHashedData(arrayBuffer, arrayBuffer)).toStrictEqual( @@ -27,7 +27,7 @@ describe('dataHashHelpers', () => { 243, 117, 24, 10, 186, 146, 136, 132, 1, 241, 145, 155, 228, 168, 113, 90, 98, 118, 59, 101, 193, 193, 14, 29, 8, 88, 232, 29, 77, 111, 159, 210, - ]) + ]), ); expect(getHashedData(arrayBufferView, arrayBufferView)).toStrictEqual( @@ -35,7 +35,7 @@ describe('dataHashHelpers', () => { 243, 117, 24, 10, 186, 146, 136, 132, 1, 241, 145, 155, 228, 168, 113, 90, 98, 118, 59, 101, 193, 193, 14, 29, 8, 88, 232, 29, 77, 111, 159, 210, - ]) + ]), ); }); @@ -44,7 +44,7 @@ describe('dataHashHelpers', () => { new Uint8Array([ 113, 23, 15, 47, 24, 62, 16, 92, 220, 133, 238, 126, 50, 50, 172, 161, 24, 87, 60, 247, 83, 37, 49, 75, 190, 87, 74, 159, 224, 95, 47, 233, - ]) + ]), ); }); }); @@ -52,23 +52,23 @@ describe('dataHashHelpers', () => { describe('getHashedDataAsHex', () => { test('returns hashed data from a key and data', () => { expect(getHashedDataAsHex(key, data)).toStrictEqual( - 'e8e4d9989c76a62a7cd9816338a3be833e9436aa65379e762aeff5889973299c' + 'e8e4d9989c76a62a7cd9816338a3be833e9436aa65379e762aeff5889973299c', ); expect(getHashedDataAsHex(arrayBuffer, arrayBuffer)).toStrictEqual( - 'f375180aba92888401f1919be4a8715a62763b65c1c10e1d0858e81d4d6f9fd2' + 'f375180aba92888401f1919be4a8715a62763b65c1c10e1d0858e81d4d6f9fd2', ); expect( - getHashedDataAsHex(arrayBufferView, arrayBufferView) + getHashedDataAsHex(arrayBufferView, arrayBufferView), ).toStrictEqual( - 'f375180aba92888401f1919be4a8715a62763b65c1c10e1d0858e81d4d6f9fd2' + 'f375180aba92888401f1919be4a8715a62763b65c1c10e1d0858e81d4d6f9fd2', ); }); test('returns hashed data from just data', () => { expect(getHashedDataAsHex(null, data)).toStrictEqual( - '71170f2f183e105cdc85ee7e3232aca118573cf75325314bbe574a9fe05f2fe9' + '71170f2f183e105cdc85ee7e3232aca118573cf75325314bbe574a9fe05f2fe9', ); }); }); diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCanonicalQueryString.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCanonicalQueryString.test.ts index 2c85aad34bb..aab23b1e64a 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCanonicalQueryString.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCanonicalQueryString.test.ts @@ -7,14 +7,14 @@ describe('getCanonicalQueryString', () => { test('sorts by keys and then by values', () => { const url = new URL('https://sub.domain?baz=qux&foo=foo&bar=bar&baz=baz'); expect(getCanonicalQueryString(url.searchParams)).toBe( - 'bar=bar&baz=baz&baz=qux&foo=foo' + 'bar=bar&baz=baz&baz=qux&foo=foo', ); }); test('encodes both key and value', () => { const url = new URL("https://sub.domain?(f!o'o)=*{f o$o}"); expect(getCanonicalQueryString(url.searchParams)).toBe( - '%28f%21o%27o%29=%2A%7Bf%20o%24o%7D' + '%28f%21o%27o%29=%2A%7Bf%20o%24o%7D', ); }); }); diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCanonicalRequest.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCanonicalRequest.test.ts index 1e8c27ce460..aab5dee3958 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCanonicalRequest.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCanonicalRequest.test.ts @@ -11,7 +11,7 @@ describe('getCanonicalRequest', () => { url: new URL('https://sub.domain'), }; expect(getCanonicalRequest(request)).toBe( - 'POST\n/\n\n\n\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' + 'POST\n/\n\n\n\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', ); }); }); diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCredentialScope.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCredentialScope.test.ts index 146c9513d6f..c0926d78dbd 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCredentialScope.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getCredentialScope.test.ts @@ -15,8 +15,8 @@ describe('getCredentialScope', () => { getCredentialScope( formattedDates.shortDate, signingRegion, - signingService - ) + signingService, + ), ).toBe(credentialScope); }); }); diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getHashedPayload.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getHashedPayload.test.ts index 87c35b68bf3..db7289da109 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getHashedPayload.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getHashedPayload.test.ts @@ -6,26 +6,26 @@ import { getHashedPayload } from '../../../../../../../src/clients/middleware/si describe('getHashedPayload', () => { test('returns empty hash if nullish', () => { expect(getHashedPayload(undefined)).toStrictEqual( - 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' + 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', ); expect(getHashedPayload(null as any)).toStrictEqual( - 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' + 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', ); }); test('returns hashed payload', () => { expect(getHashedPayload('string-body')).toStrictEqual( - 'f4241e27b103e1a1d7f88a1556541718250245fe31c8e695f3e068d3fe837572' + 'f4241e27b103e1a1d7f88a1556541718250245fe31c8e695f3e068d3fe837572', ); }); test('works with ArrayBuffer', () => { expect(getHashedPayload(new ArrayBuffer(8))).toStrictEqual( - 'af5570f5a1810b7af78caf4bc70a660f0df51e42baf91d4de5b2328de0e83dfc' + 'af5570f5a1810b7af78caf4bc70a660f0df51e42baf91d4de5b2328de0e83dfc', ); expect(getHashedPayload(new Uint8Array(new ArrayBuffer(8)))).toStrictEqual( - 'af5570f5a1810b7af78caf4bc70a660f0df51e42baf91d4de5b2328de0e83dfc' + 'af5570f5a1810b7af78caf4bc70a660f0df51e42baf91d4de5b2328de0e83dfc', ); }); diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSignature.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSignature.test.ts index 1cfe4c3a14c..1a796e7bd2e 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSignature.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSignature.test.ts @@ -23,7 +23,7 @@ describe('getSignature', () => { signingService, }; expect(getSignature(getDefaultRequest(), signingValues)).toStrictEqual( - '145191af25230efbe34c7eb79d9d3ce881f7a945d02d0361719107147d0086b3' + '145191af25230efbe34c7eb79d9d3ce881f7a945d02d0361719107147d0086b3', ); }); }); diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSigningKey.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSigningKey.test.ts index 45f6a2aedb0..f3b017a73b1 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSigningKey.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSigningKey.test.ts @@ -6,12 +6,12 @@ import { getSigningKey } from '../../../../../../../src/clients/middleware/signi describe('getSigningKey', () => { test('returns a signing key', () => { expect( - getSigningKey('secret-access-key', '20200918', 'region', 'service') + getSigningKey('secret-access-key', '20200918', 'region', 'service'), ).toStrictEqual( new Uint8Array([ 79, 189, 20, 186, 57, 62, 187, 22, 80, 142, 29, 192, 182, 56, 183, 254, 40, 157, 31, 233, 13, 76, 236, 41, 206, 90, 24, 22, 52, 165, 235, 99, - ]) + ]), ); }); }); diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSigningValues.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSigningValues.test.ts index 571afd5b4b9..3567c2cabed 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSigningValues.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSigningValues.test.ts @@ -20,7 +20,7 @@ describe('getSigningValues', () => { signingDate, signingRegion, signingService, - }) + }), ).toStrictEqual({ ...credentialsWithToken, credentialScope, diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getStringToSign.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getStringToSign.test.ts index 605143f1a67..8e9ad3c40bf 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getStringToSign.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getStringToSign.test.ts @@ -10,10 +10,10 @@ describe('getStringToSign', () => { getStringToSign( formattedDates.longDate, credentialScope, - 'hashed-request' - ) + 'hashed-request', + ), ).toStrictEqual( - 'AWS4-HMAC-SHA256\n20200918T181818Z\n20200918/signing-region/signing-service/aws4_request\nhashed-request' + 'AWS4-HMAC-SHA256\n20200918T181818Z\n20200918/signing-region/signing-service/aws4_request\nhashed-request', ); }); }); diff --git a/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts b/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts index acb53d5c167..82b05ab27ec 100644 --- a/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/utils/getUpdatedSystemClockOffset.test.ts @@ -19,7 +19,7 @@ describe('getUpdatedSystemClockOffset', () => { mockIsClockSkewed.mockReturnValue(false); const offset = 1500; expect(getUpdatedSystemClockOffset(signingDate.getTime(), offset)).toBe( - offset + offset, ); }); @@ -28,7 +28,7 @@ describe('getUpdatedSystemClockOffset', () => { const clockTime = new Date(signingDate); clockTime.setMinutes(signingDate.getMinutes() + 15); expect(getUpdatedSystemClockOffset(clockTime.getTime(), 0)).toBe( - 15 * 60 * 1000 + 15 * 60 * 1000, ); }); @@ -37,7 +37,7 @@ describe('getUpdatedSystemClockOffset', () => { const clockTime = new Date(signingDate); clockTime.setMinutes(signingDate.getMinutes() - 15); expect(getUpdatedSystemClockOffset(clockTime.getTime(), 0)).toBe( - -15 * 60 * 1000 + -15 * 60 * 1000, ); }); diff --git a/packages/core/__tests__/clients/middleware/signing/utils/isClockSkewed.test.ts b/packages/core/__tests__/clients/middleware/signing/utils/isClockSkewed.test.ts index 38df2218091..ec4bb7d57a3 100644 --- a/packages/core/__tests__/clients/middleware/signing/utils/isClockSkewed.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/utils/isClockSkewed.test.ts @@ -6,7 +6,7 @@ import { isClockSkewed } from '../../../../../src/clients/middleware/signing/uti import { signingDate } from '../signer/signatureV4/testUtils/data'; jest.mock( - '../../../../../src/clients/middleware/signing/utils/getSkewCorrectedDate' + '../../../../../src/clients/middleware/signing/utils/getSkewCorrectedDate', ); const mockGetSkewCorrectedDate = getSkewCorrectedDate as jest.Mock; diff --git a/packages/core/__tests__/providers/pinpoint/apis/record.test.ts b/packages/core/__tests__/providers/pinpoint/apis/record.test.ts index 9f466b58e81..fc17952a8c8 100644 --- a/packages/core/__tests__/providers/pinpoint/apis/record.test.ts +++ b/packages/core/__tests__/providers/pinpoint/apis/record.test.ts @@ -67,7 +67,7 @@ describe('Pinpoint Provider API: record', () => { event, session: expect.any(Object), timestamp: expect.any(String), - }) + }), ); }); @@ -111,7 +111,7 @@ describe('Pinpoint Provider API: record', () => { event, session: expect.any(Object), timestamp: expect.any(String), - }) + }), ); }); @@ -143,7 +143,7 @@ describe('Pinpoint Provider API: record', () => { StartTimestamp: expect.any(String), }, timestamp: expect.any(String), - }) + }), ); // End the session @@ -168,7 +168,7 @@ describe('Pinpoint Provider API: record', () => { StopTimestamp: expect.any(String), }, timestamp: expect.any(String), - }) + }), ); }); @@ -178,7 +178,7 @@ describe('Pinpoint Provider API: record', () => { }); await expect( - record({ appId, category, credentials, event, identityId, region }) + record({ appId, category, credentials, event, identityId, region }), ).rejects.toThrow(); }); }); diff --git a/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts b/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts index d9e5d5dc812..5fa35dd912b 100644 --- a/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts +++ b/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts @@ -64,7 +64,7 @@ describe('Pinpoint Provider API: updateEndpoint', () => { await updateEndpoint({ appId, category, credentials, region }); expect(mockClientUpdateEndpoint).toHaveBeenCalledWith( { credentials, region }, - getExpectedInput({}) + getExpectedInput({}), ); }); @@ -115,7 +115,7 @@ describe('Pinpoint Provider API: updateEndpoint', () => { metrics, optOut, userId, - }) + }), ); }); @@ -140,7 +140,7 @@ describe('Pinpoint Provider API: updateEndpoint', () => { make: clientDemographic.make, model: clientDemographic.model, }, - }) + }), ); }); @@ -150,12 +150,12 @@ describe('Pinpoint Provider API: updateEndpoint', () => { await updateEndpoint({ appId, category, credentials, region }); expect(mockClientUpdateEndpoint).toHaveBeenCalledWith( { credentials, region }, - getExpectedInput({ endpointId: createdEndpointId }) + getExpectedInput({ endpointId: createdEndpointId }), ); expect(mockCacheEndpointId).toHaveBeenCalledWith( appId, category, - createdEndpointId + createdEndpointId, ); }); diff --git a/packages/core/__tests__/providers/pinpoint/utils/cacheEndpointId.test.ts b/packages/core/__tests__/providers/pinpoint/utils/cacheEndpointId.test.ts index 98ba5c66da4..3ac05238950 100644 --- a/packages/core/__tests__/providers/pinpoint/utils/cacheEndpointId.test.ts +++ b/packages/core/__tests__/providers/pinpoint/utils/cacheEndpointId.test.ts @@ -30,7 +30,7 @@ describe('Pinpoint Provider Util: cacheEndpointId', () => { expect(setItemSpy).toHaveBeenCalledWith( cacheKey, endpointId, - expect.objectContaining({ priority: 1 }) + expect.objectContaining({ priority: 1 }), ); }); }); diff --git a/packages/core/__tests__/providers/pinpoint/utils/resolveEndpointId.test.ts b/packages/core/__tests__/providers/pinpoint/utils/resolveEndpointId.test.ts index e7ee227a247..fa69c5c5f63 100644 --- a/packages/core/__tests__/providers/pinpoint/utils/resolveEndpointId.test.ts +++ b/packages/core/__tests__/providers/pinpoint/utils/resolveEndpointId.test.ts @@ -40,7 +40,7 @@ describe('Pinpoint Provider Util: resolveEndpointId', () => { credentials, identityId, region, - }) + }), ).toBe(endpointId); }); @@ -53,7 +53,7 @@ describe('Pinpoint Provider Util: resolveEndpointId', () => { credentials, identityId, region, - }) + }), ).toBe(endpointId); expect(mockUpdateEndpoint).toHaveBeenCalledWith({ @@ -74,7 +74,7 @@ describe('Pinpoint Provider Util: resolveEndpointId', () => { credentials, identityId, region, - }) + }), ).rejects.toThrow('Endpoint ID'); }); }); diff --git a/packages/core/__tests__/singleton/Auth/utils/index.test.ts b/packages/core/__tests__/singleton/Auth/utils/index.test.ts index 08e8d1b63d2..6eaeeb0bdee 100644 --- a/packages/core/__tests__/singleton/Auth/utils/index.test.ts +++ b/packages/core/__tests__/singleton/Auth/utils/index.test.ts @@ -33,6 +33,6 @@ describe('decodeJWT', () => { const result = decodeJWT(token); expect(result.payload).toEqual(decoded); expect(result.toString()).toEqual(token); - } + }, ); }); diff --git a/packages/core/__tests__/singleton/Singleton.test.ts b/packages/core/__tests__/singleton/Singleton.test.ts index c98e7fcd448..0b12a8e9bac 100644 --- a/packages/core/__tests__/singleton/Singleton.test.ts +++ b/packages/core/__tests__/singleton/Singleton.test.ts @@ -170,7 +170,7 @@ describe('Amplify.configure() and Amplify.getConfig()', () => { data: expectedResourceConfig, }, 'Configure', - AMPLIFY_SYMBOL + AMPLIFY_SYMBOL, ); }); @@ -296,7 +296,7 @@ describe('Session tests', () => { clearCredentialsAndIdentityId: () => {}, }, }, - } + }, ); const session = await fetchAuthSession(); @@ -373,7 +373,7 @@ describe('Session tests', () => { }, identityId: 'identityIdValue', }; - } + }, ); const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.YzDpgJsrB3z-ZU1XxMcXSQsMbgCzwH_e-_76rnfehh0'; @@ -468,7 +468,7 @@ describe('Session tests', () => { }, identityId: 'identityIdValue', }; - } + }, ); const spyTokenProvider = jest.fn(async () => { @@ -538,7 +538,7 @@ describe('Session tests', () => { tokenProvider: { getTokens: tokenProvider, }, - } + }, ); await auth.fetchAuthSession({ forceRefresh: true }); @@ -566,7 +566,7 @@ describe('Session tests', () => { tokenProvider: { getTokens: tokenProvider, }, - } + }, ); const action = async () => diff --git a/packages/core/__tests__/storage/CookieStorage.test.ts b/packages/core/__tests__/storage/CookieStorage.test.ts index bfa1a363f6c..75ef343691c 100644 --- a/packages/core/__tests__/storage/CookieStorage.test.ts +++ b/packages/core/__tests__/storage/CookieStorage.test.ts @@ -32,7 +32,7 @@ describe('CookieStorage', () => { sameSite: 'none', }); }).toThrow( - 'sameSite = None requires the Secure attribute in latest browser versions.' + 'sameSite = None requires the Secure attribute in latest browser versions.', ); }); @@ -68,7 +68,7 @@ describe('CookieStorage', () => { const tempReference = await cookieStore.getItem('testKey2'); await cookieStore.clear(); expect(await cookieStore.getItem('testKey2')).not.toEqual( - tempReference + tempReference, ); }); }); diff --git a/packages/core/__tests__/utils.test.ts b/packages/core/__tests__/utils.test.ts index 176768ab0b1..09be22a39da 100644 --- a/packages/core/__tests__/utils.test.ts +++ b/packages/core/__tests__/utils.test.ts @@ -26,7 +26,7 @@ describe('Util', () => { date: true, }, }, - }) + }), ).toBeTruthy(); }); @@ -44,13 +44,13 @@ describe('Util', () => { describe('StringUtils', () => { test('urlSafeEncode', () => { expect(urlSafeEncode('some/path?to-whatever')).toBe( - '736f6d652f706174683f746f2d7768617465766572' + '736f6d652f706174683f746f2d7768617465766572', ); }); test('urlSafeDecode', () => { expect(urlSafeDecode('736f6d652f706174683f746f2d7768617465766572')).toBe( - 'some/path?to-whatever' + 'some/path?to-whatever', ); }); }); @@ -103,7 +103,7 @@ describe('Util', () => { } expect(subscribe).toThrow( - 'NetInfo must be passed to networkMonitor to enable reachability in React Native' + 'NetInfo must be passed to networkMonitor to enable reachability in React Native', ); expect(subscribeWithNetInfo).not.toThrow(); }); diff --git a/packages/core/__tests__/utils/convert/base64Encoder.test.ts b/packages/core/__tests__/utils/convert/base64Encoder.test.ts index bbf9325076f..14ffb0064b0 100644 --- a/packages/core/__tests__/utils/convert/base64Encoder.test.ts +++ b/packages/core/__tests__/utils/convert/base64Encoder.test.ts @@ -40,7 +40,7 @@ describe('base64Encoder (non-native)', () => { const mockResult = 'test+test/test'; mockBtoa.mockReturnValue(mockResult); expect(base64Encoder.convert('test', { urlSafe: true })).toBe( - 'test-test_test' + 'test-test_test', ); }); }); diff --git a/packages/core/__tests__/utils/getClientInfo/getClientInfo.test.ts b/packages/core/__tests__/utils/getClientInfo/getClientInfo.test.ts index 800a94c9cb1..bde270d3961 100644 --- a/packages/core/__tests__/utils/getClientInfo/getClientInfo.test.ts +++ b/packages/core/__tests__/utils/getClientInfo/getClientInfo.test.ts @@ -177,6 +177,6 @@ describe('getClientInfo', () => { } as any); const result = getClientInfo(); expect(result).toEqual(expect.objectContaining(expectedResult)); - } + }, ); }); diff --git a/packages/core/__tests__/utils/haveCredentialsChanged.test.ts b/packages/core/__tests__/utils/haveCredentialsChanged.test.ts index 1dc42f6f72b..2ae640bf9f0 100644 --- a/packages/core/__tests__/utils/haveCredentialsChanged.test.ts +++ b/packages/core/__tests__/utils/haveCredentialsChanged.test.ts @@ -3,7 +3,7 @@ import { haveCredentialsChanged } from '../../src/utils/haveCredentialsChanged'; const MOCK_AWS_CREDS = { accessKeyId: 'mock-access-key', secretAccessKey: 'mock-secret-key', - sessionToken: 'mock-session-token' + sessionToken: 'mock-session-token', }; describe('haveCredentialsChanged', () => { @@ -35,8 +35,11 @@ describe('haveCredentialsChanged', () => { }); it('returns false if credentials have not changed', () => { - const credentialsHaveChanged = haveCredentialsChanged(MOCK_AWS_CREDS, MOCK_AWS_CREDS); + const credentialsHaveChanged = haveCredentialsChanged( + MOCK_AWS_CREDS, + MOCK_AWS_CREDS, + ); expect(credentialsHaveChanged).toBe(false); }); -}) +}); diff --git a/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts b/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts index 9f55485421f..a3eef512e09 100644 --- a/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts +++ b/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts @@ -58,7 +58,7 @@ describe('createQueuedStorage', () => { mockQueuedItems.map((item, index) => [ mockKeys[index], JSON.stringify(item), - ]) + ]), ); queuedStorage = createQueuedStorage(); @@ -159,7 +159,7 @@ describe('createQueuedStorage', () => { timestamp: mockTimestamp, bytesSize: getAddItemBytesSize(testInput), key: `${keyPrefix}_123`, - }) + }), ); }); @@ -173,7 +173,7 @@ describe('createQueuedStorage', () => { }, ]; mockMultiGet.mockResolvedValueOnce( - mockQueuedItems.map(item => [item.key, JSON.stringify(item)]) + mockQueuedItems.map(item => [item.key, JSON.stringify(item)]), ); await queuedStorage.add(testInput, { dequeueBeforeEnqueue: true }); @@ -188,7 +188,7 @@ describe('createQueuedStorage', () => { timestamp: mockTimestamp, bytesSize: getAddItemBytesSize(testInput), key: `${keyPrefix}_123`, - }) + }), ); }); }); @@ -228,7 +228,7 @@ describe('createQueuedStorage', () => { test('peek() returns specified number of queued items', async () => { mockGetAllKeys.mockResolvedValueOnce( - mockQueuedItems.map(item => item.key) + mockQueuedItems.map(item => item.key), ); mockMultiGet.mockResolvedValueOnce([ [mockQueuedItems[0].key, JSON.stringify(mockQueuedItems[0])], @@ -244,17 +244,17 @@ describe('createQueuedStorage', () => { test('peekAll() returns all queued items', async () => { mockGetAllKeys.mockResolvedValueOnce( - mockQueuedItems.map(item => item.key) + mockQueuedItems.map(item => item.key), ); mockMultiGet.mockResolvedValueOnce( - mockQueuedItems.map(item => [item.key, JSON.stringify(item)]) + mockQueuedItems.map(item => [item.key, JSON.stringify(item)]), ); const result = await queuedStorage.peekAll(); expect(mockGetAllKeys).toHaveBeenCalledTimes(1); expect(mockMultiGet).toHaveBeenCalledTimes(1); expect(mockMultiGet).toHaveBeenCalledWith( - mockQueuedItems.map(item => item.key) + mockQueuedItems.map(item => item.key), ); expect(result).toHaveLength(mockQueuedItems.length); }); @@ -298,7 +298,7 @@ describe('createQueuedStorage', () => { expect(mockMultiRemove).toHaveBeenCalledTimes(1); expect(mockMultiRemove).toHaveBeenCalledWith( - testItems.map(item => item.key) + testItems.map(item => item.key), ); }); }); @@ -326,7 +326,7 @@ describe('createQueuedStorage', () => { expect(mockGetAllKeys).toHaveBeenCalledTimes(1); expect(mockMultiRemove).toHaveBeenCalledTimes(1); expect(mockMultiRemove).toHaveBeenCalledWith( - testAllKeys.filter(key => key.startsWith(keyPrefix)) + testAllKeys.filter(key => key.startsWith(keyPrefix)), ); }); }); diff --git a/packages/core/__tests__/utils/sessionListener/SessionListener.native.test.ts b/packages/core/__tests__/utils/sessionListener/SessionListener.native.test.ts index 40c040b878b..b007a6aade4 100644 --- a/packages/core/__tests__/utils/sessionListener/SessionListener.native.test.ts +++ b/packages/core/__tests__/utils/sessionListener/SessionListener.native.test.ts @@ -28,7 +28,7 @@ describe('[RN] Session Listener', () => { it('Should register an event listener on initialization', () => { expect(mockAddEventListener).toHaveBeenCalledWith( 'change', - expect.any(Function) + expect.any(Function), ); }); diff --git a/packages/core/__tests__/utils/sessionListener/SessionListener.test.ts b/packages/core/__tests__/utils/sessionListener/SessionListener.test.ts index 0560141d546..90658fec2cb 100644 --- a/packages/core/__tests__/utils/sessionListener/SessionListener.test.ts +++ b/packages/core/__tests__/utils/sessionListener/SessionListener.test.ts @@ -23,7 +23,7 @@ describe('[Web] Session Listener', () => { expect(document.addEventListener).toHaveBeenCalledWith( 'visibilitychange', expect.any(Function), - false + false, ); }); diff --git a/packages/core/src/clients/internal/composeTransferHandler.ts b/packages/core/src/clients/internal/composeTransferHandler.ts index 12015825a08..30680b0bba1 100644 --- a/packages/core/src/clients/internal/composeTransferHandler.ts +++ b/packages/core/src/clients/internal/composeTransferHandler.ts @@ -61,13 +61,13 @@ type OptionToMiddleware< > = Options extends [] ? [] : Options extends [infer LastOption] - ? [Middleware] - : Options extends [infer FirstOption, ...infer RestOptions] - ? [ + ? [Middleware] + : Options extends [infer FirstOption, ...infer RestOptions] + ? [ Middleware, ...OptionToMiddleware, - ] - : never; + ] + : never; /** * Type to intersect multiple types if they have no conflict keys. @@ -77,10 +77,10 @@ type MergeNoConflictKeys = Options extends [ ] ? OnlyOption : Options extends [infer FirstOption, infer SecondOption] - ? FirstOption & SecondOption - : Options extends [infer FirstOption, ...infer RestOptions] - ? FirstOption & MergeNoConflictKeys - : never; + ? FirstOption & SecondOption + : Options extends [infer FirstOption, ...infer RestOptions] + ? FirstOption & MergeNoConflictKeys + : never; /** * Type to infer the option type of a transfer handler type. diff --git a/packages/core/src/parseAWSExports.ts b/packages/core/src/parseAWSExports.ts index 9e4e2be2eab..5bb29e1be37 100644 --- a/packages/core/src/parseAWSExports.ts +++ b/packages/core/src/parseAWSExports.ts @@ -154,7 +154,7 @@ export const parseAWSExports = ( aws_cognito_mfa_configuration.toLowerCase(), totpEnabled: aws_cognito_mfa_types?.includes('TOTP') ?? false, smsEnabled: aws_cognito_mfa_types?.includes('SMS') ?? false, - } + } : undefined; const passwordFormatConfig = aws_cognito_password_protection_settings ? { @@ -176,7 +176,7 @@ export const parseAWSExports = ( aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes( 'REQUIRES_SYMBOLS', ) ?? false, - } + } : undefined; const mergedUserAttributes: LegacyUserAttributeKey[] = Array.from( new Set([ @@ -256,7 +256,7 @@ export const parseAWSExports = ( searchIndices: amazon_location_service.search_indices, region: amazon_location_service.region, }, - } + } : { ...geo }; } @@ -297,7 +297,7 @@ export const parseAWSExports = ( defaults: { voiceId }, }, }, - } + } : predictions; } diff --git a/packages/core/src/utils/queuedStorage/createQueuedStorage.native.ts b/packages/core/src/utils/queuedStorage/createQueuedStorage.native.ts index c21a59c98e7..deee68053cc 100644 --- a/packages/core/src/utils/queuedStorage/createQueuedStorage.native.ts +++ b/packages/core/src/utils/queuedStorage/createQueuedStorage.native.ts @@ -124,7 +124,7 @@ const getQueuedItemKeys = async ( const timestampB = b.split('_').pop() as string; return parseInt(timestampA) - parseInt(timestampB); - }) + }) : keys; }; diff --git a/packages/datastore-storage-adapter/__tests__/SQLiteAdapter.test.ts b/packages/datastore-storage-adapter/__tests__/SQLiteAdapter.test.ts index 4e9fb67b497..9adaab2838a 100644 --- a/packages/datastore-storage-adapter/__tests__/SQLiteAdapter.test.ts +++ b/packages/datastore-storage-adapter/__tests__/SQLiteAdapter.test.ts @@ -168,7 +168,7 @@ describe('SQLiteAdapter', () => { null!, null!, null!, - ] + ], ); const queries = new Set(); diff --git a/packages/datastore-storage-adapter/__tests__/SQLiteCPKEnabled.test.ts b/packages/datastore-storage-adapter/__tests__/SQLiteCPKEnabled.test.ts index 1adf0355f36..68c2a856bb7 100644 --- a/packages/datastore-storage-adapter/__tests__/SQLiteCPKEnabled.test.ts +++ b/packages/datastore-storage-adapter/__tests__/SQLiteCPKEnabled.test.ts @@ -134,7 +134,7 @@ describe('SQLite SPK Enabled', () => { }); await DataStore.start(); expect((console.error as any).mock.calls[0][0]).toMatch( - 'The SQLite adapter does not support schemas using custom primary key. Set `graphQLTransformer.respectPrimaryKeyAttributesOnConnectionField in `amplify/cli.json` to false to disable custom primary key. To regenerate your API, add or remove an empty newline to your GraphQL schema (to change the computed hash) then run `amplify push`.' + 'The SQLite adapter does not support schemas using custom primary key. Set `graphQLTransformer.respectPrimaryKeyAttributesOnConnectionField in `amplify/cli.json` to false to disable custom primary key. To regenerate your API, add or remove an empty newline to your GraphQL schema (to change the computed hash) then run `amplify push`.', ); }); }); diff --git a/packages/datastore-storage-adapter/__tests__/SQLiteUtils.test.ts b/packages/datastore-storage-adapter/__tests__/SQLiteUtils.test.ts index 175a27c9536..3ae37315d99 100644 --- a/packages/datastore-storage-adapter/__tests__/SQLiteUtils.test.ts +++ b/packages/datastore-storage-adapter/__tests__/SQLiteUtils.test.ts @@ -57,7 +57,7 @@ describe('SQLiteUtils tests', () => { const schema: InternalSchema = internalTestSchema(); expect(generateSchemaStatements(schema)).toEqual( - INTERNAL_TEST_SCHEMA_STATEMENTS + INTERNAL_TEST_SCHEMA_STATEMENTS, ); }); }); @@ -65,19 +65,19 @@ describe('SQLiteUtils tests', () => { describe('modelCreateTableStatement', () => { it('should generate a valid CREATE TABLE statement from a M:N join table model with implicit FKs', () => { expect(modelCreateTableStatement(postEditorImplicit, true)).toEqual( - INTERNAL_TEST_SCHEMA_MANY_TO_MANY_STATEMENT + INTERNAL_TEST_SCHEMA_MANY_TO_MANY_STATEMENT, ); }); it('should generate a valid CREATE TABLE statement from a M:N join table model with explicit FKs', () => { expect(modelCreateTableStatement(postEditorExplicit, true)).toEqual( - INTERNAL_TEST_SCHEMA_MANY_TO_MANY_STATEMENT + INTERNAL_TEST_SCHEMA_MANY_TO_MANY_STATEMENT, ); }); it('should generate a valid CREATE TABLE statement from a 1:M join table model', () => { expect(modelCreateTableStatement(postWithRequiredComments, true)).toEqual( - INTERNAL_TEST_SCHEMA_ONE_TO_MANY_STATEMENT + INTERNAL_TEST_SCHEMA_ONE_TO_MANY_STATEMENT, ); }); }); @@ -171,8 +171,8 @@ describe('SQLiteUtils tests', () => { predicateGroup as any, sortPredicateGroup as any, limit, - page - ) + page, + ), ).toEqual(expected); }); }); @@ -295,7 +295,7 @@ describe('SQLiteUtils tests', () => { const expected = [`instr("name", ?) = 1`, ['%']]; expect(whereConditionFromPredicateObject(predicate as any)).toEqual( - expected + expected, ); }); it('should generate valid `contains` condition from predicate object', () => { @@ -308,7 +308,7 @@ describe('SQLiteUtils tests', () => { const expected = [`instr("name", ?) > 0`, ['%']]; expect(whereConditionFromPredicateObject(predicate as any)).toEqual( - expected + expected, ); }); it('should generate valid `notContains` condition from predicate object', () => { @@ -321,7 +321,7 @@ describe('SQLiteUtils tests', () => { const expected = [`instr("name", ?) = 0`, ['%']]; expect(whereConditionFromPredicateObject(predicate as any)).toEqual( - expected + expected, ); }); it('should generate valid `between` condition from predicate object', () => { @@ -334,7 +334,7 @@ describe('SQLiteUtils tests', () => { const expected = [`"name" BETWEEN ? AND ?`, ['a', 'b']]; expect(whereConditionFromPredicateObject(predicate as any)).toEqual( - expected + expected, ); }); }); @@ -370,7 +370,7 @@ describe('SQLiteUtils tests', () => { const expected = 'ORDER BY "sortOrder" ASC, _rowid_ ASC'; expect(orderByClauseFromSort(sortPredicateGroup as any)).toEqual( - expected + expected, ); }); @@ -389,7 +389,7 @@ describe('SQLiteUtils tests', () => { const expected = 'ORDER BY "sortOrder" ASC, "lastName" DESC, _rowid_ ASC'; expect(orderByClauseFromSort(sortPredicateGroup as any)).toEqual( - expected + expected, ); }); }); @@ -431,7 +431,7 @@ describe('SQLiteUtils tests', () => { ]; expect( - deleteByPredicateStatement('Model', predicateGroup as any) + deleteByPredicateStatement('Model', predicateGroup as any), ).toEqual(expected); }); }); diff --git a/packages/datastore-storage-adapter/__tests__/helpers.ts b/packages/datastore-storage-adapter/__tests__/helpers.ts index 6a79923fe09..886df0d5e4a 100644 --- a/packages/datastore-storage-adapter/__tests__/helpers.ts +++ b/packages/datastore-storage-adapter/__tests__/helpers.ts @@ -22,7 +22,7 @@ export declare class Model { static copyOf( src: Model, - mutator: (draft: MutableModel) => void | Model + mutator: (draft: MutableModel) => void | Model, ): Model; } export declare class Metadata { @@ -931,7 +931,7 @@ export class InnerSQLiteDatabase { statement, params: any[] = [], callback: ((...args) => Promise) | undefined = undefined, - logger = undefined + logger = undefined, ) { this.sqlog.push(`${statement}; ${JSON.stringify(params)}`); if (statement.trim().toLowerCase().startsWith('select')) { @@ -958,7 +958,7 @@ export class InnerSQLiteDatabase { }, () => { resolve([resultSet]); - } + }, ); if (typeof callback === 'function') await callback(this, resultSet); diff --git a/packages/datastore-storage-adapter/src/ExpoSQLiteAdapter/ExpoSQLiteAdapter.ts b/packages/datastore-storage-adapter/src/ExpoSQLiteAdapter/ExpoSQLiteAdapter.ts index 64c6eb6d83a..c767ed80981 100644 --- a/packages/datastore-storage-adapter/src/ExpoSQLiteAdapter/ExpoSQLiteAdapter.ts +++ b/packages/datastore-storage-adapter/src/ExpoSQLiteAdapter/ExpoSQLiteAdapter.ts @@ -4,7 +4,7 @@ import { CommonSQLiteAdapter } from '../common/CommonSQLiteAdapter'; import ExpoSQLiteDatabase from './ExpoSQLiteDatabase'; const ExpoSQLiteAdapter: CommonSQLiteAdapter = new CommonSQLiteAdapter( - new ExpoSQLiteDatabase() + new ExpoSQLiteDatabase(), ); export default ExpoSQLiteAdapter; diff --git a/packages/datastore-storage-adapter/src/ExpoSQLiteAdapter/ExpoSQLiteDatabase.ts b/packages/datastore-storage-adapter/src/ExpoSQLiteAdapter/ExpoSQLiteDatabase.ts index bfc6a18b48a..b4536b5f838 100644 --- a/packages/datastore-storage-adapter/src/ExpoSQLiteAdapter/ExpoSQLiteDatabase.ts +++ b/packages/datastore-storage-adapter/src/ExpoSQLiteAdapter/ExpoSQLiteDatabase.ts @@ -53,7 +53,7 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { public async get( statement: string, - params: (string | number)[] + params: (string | number)[], ): Promise { const results: T[] = await this.getAll(statement, params); return results[0]; @@ -61,7 +61,7 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { public getAll( statement: string, - params: (string | number)[] + params: (string | number)[], ): Promise { return new Promise((resolve, reject) => { this.db.readTransaction(transaction => { @@ -75,7 +75,7 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { reject(error); logger.warn(error); return true; - } + }, ); }); }); @@ -94,14 +94,14 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { reject(error); logger.warn(error); return true; - } + }, ); }); }); } public batchQuery( - queryParameterizedStatements: Set = new Set() + queryParameterizedStatements: Set = new Set(), ): Promise { return new Promise((resolveTransaction, rejectTransaction) => { this.db.transaction(async transaction => { @@ -120,10 +120,10 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { reject(error); logger.warn(error); return true; - } + }, ); - }) - ) + }), + ), ); resolveTransaction(results); } catch (error) { @@ -136,7 +136,7 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { public batchSave( saveParameterizedStatements: Set = new Set(), - deleteParameterizedStatements?: Set + deleteParameterizedStatements?: Set, ): Promise { return new Promise((resolveTransaction, rejectTransaction) => { this.db.transaction(async transaction => { @@ -156,10 +156,10 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { reject(error); logger.warn(error); return true; - } + }, ); - }) - ) + }), + ), ); if (deleteParameterizedStatements) { await Promise.all( @@ -176,10 +176,10 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { reject(error); logger.warn(error); return true; - } - ) - ) - ) + }, + ), + ), + ), ); } resolveTransaction(null); @@ -193,7 +193,7 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { public selectAndDelete( queryParameterizedStatement: ParameterizedStatement, - deleteParameterizedStatement: ParameterizedStatement + deleteParameterizedStatement: ParameterizedStatement, ): Promise { const [queryStatement, queryParams] = queryParameterizedStatement; const [deleteStatement, deleteParams] = deleteParameterizedStatement; @@ -212,7 +212,7 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { reject(error); logger.warn(error); return true; - } + }, ); }); await new Promise((resolve, reject) => { @@ -226,7 +226,7 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { reject(error); logger.warn(error); return true; - } + }, ); }); resolveTransaction(result); @@ -255,10 +255,10 @@ class ExpoSQLiteDatabase implements CommonSQLiteDatabase { (_, error) => { reject(error); return true; - } + }, ); - }) - ) + }), + ), ); resolveTransaction(null); } catch (error) { diff --git a/packages/datastore-storage-adapter/src/SQLiteAdapter/SQLiteAdapter.ts b/packages/datastore-storage-adapter/src/SQLiteAdapter/SQLiteAdapter.ts index 6e751b85446..b84e39ffb47 100644 --- a/packages/datastore-storage-adapter/src/SQLiteAdapter/SQLiteAdapter.ts +++ b/packages/datastore-storage-adapter/src/SQLiteAdapter/SQLiteAdapter.ts @@ -4,7 +4,7 @@ import { CommonSQLiteAdapter } from '../common/CommonSQLiteAdapter'; import SQLiteDatabase from './SQLiteDatabase'; const SQLiteAdapter: CommonSQLiteAdapter = new CommonSQLiteAdapter( - new SQLiteDatabase() + new SQLiteDatabase(), ); export default SQLiteAdapter; diff --git a/packages/datastore-storage-adapter/src/SQLiteAdapter/SQLiteDatabase.ts b/packages/datastore-storage-adapter/src/SQLiteAdapter/SQLiteDatabase.ts index 103dcccfa1e..869f8be816f 100644 --- a/packages/datastore-storage-adapter/src/SQLiteAdapter/SQLiteDatabase.ts +++ b/packages/datastore-storage-adapter/src/SQLiteAdapter/SQLiteDatabase.ts @@ -53,7 +53,7 @@ class SQLiteDatabase implements CommonSQLiteDatabase { public async get( statement: string, - params: (string | number)[] + params: (string | number)[], ): Promise { const results: T[] = await this.getAll(statement, params); return results[0]; @@ -61,7 +61,7 @@ class SQLiteDatabase implements CommonSQLiteDatabase { public async getAll( statement: string, - params: (string | number)[] + params: (string | number)[], ): Promise { const [resultSet] = await this.db.executeSql(statement, params); const result = @@ -76,13 +76,13 @@ class SQLiteDatabase implements CommonSQLiteDatabase { public async save( statement: string, - params: (string | number)[] + params: (string | number)[], ): Promise { await this.db.executeSql(statement, params); } public async batchQuery( - queryParameterizedStatements: Set + queryParameterizedStatements: Set, ): Promise { const results = []; @@ -94,7 +94,7 @@ class SQLiteDatabase implements CommonSQLiteDatabase { (_, res) => { results.push(res.rows.raw()[0]); }, - logger.warn + logger.warn, ); } }); @@ -104,7 +104,7 @@ class SQLiteDatabase implements CommonSQLiteDatabase { public async batchSave( saveParameterizedStatements: Set, - deleteParameterizedStatements?: Set + deleteParameterizedStatements?: Set, ): Promise { await this.db.transaction(tx => { for (const [statement, params] of saveParameterizedStatements) { @@ -122,7 +122,7 @@ class SQLiteDatabase implements CommonSQLiteDatabase { public async selectAndDelete( queryParameterizedStatement: ParameterizedStatement, - deleteParameterizedStatement: ParameterizedStatement + deleteParameterizedStatement: ParameterizedStatement, ): Promise { let results: T[] = []; @@ -136,7 +136,7 @@ class SQLiteDatabase implements CommonSQLiteDatabase { (_, res) => { results = res.rows.raw(); }, - logger.warn + logger.warn, ); tx.executeSql(deleteStatement, deleteParams, () => {}, logger.warn); }); diff --git a/packages/datastore-storage-adapter/src/common/CommonSQLiteAdapter.ts b/packages/datastore-storage-adapter/src/common/CommonSQLiteAdapter.ts index a6ccf3a97c2..1caab5f0c8a 100644 --- a/packages/datastore-storage-adapter/src/common/CommonSQLiteAdapter.ts +++ b/packages/datastore-storage-adapter/src/common/CommonSQLiteAdapter.ts @@ -47,7 +47,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { private modelInstanceCreator: ModelInstanceCreator; private getModelConstructorByModelName: ( namsespaceName: string, - modelName: string + modelName: string, ) => PersistentModelConstructor; private db: CommonSQLiteDatabase; private initPromise: Promise; @@ -64,8 +64,8 @@ export class CommonSQLiteAdapter implements StorageAdapter { modelInstanceCreator: ModelInstanceCreator, getModelConstructorByModelName: ( namsespaceName: NAMESPACES, - modelName: string - ) => PersistentModelConstructor + modelName: string, + ) => PersistentModelConstructor, ) { if (!this.initPromise) { this.initPromise = new Promise((res, rej) => { @@ -83,15 +83,15 @@ export class CommonSQLiteAdapter implements StorageAdapter { try { const usesCPKCodegen = Object.values( - this.schema.namespaces.user.models + this.schema.namespaces.user.models, ).some(model => - Object.values(model.fields).some( - field => field.association?.hasOwnProperty('targetNames') - ) + Object.values(model.fields).some(field => + field.association?.hasOwnProperty('targetNames'), + ), ); if (usesCPKCodegen) { logger.error( - 'The SQLite adapter does not support schemas using custom primary key. Set `graphQLTransformer.respectPrimaryKeyAttributesOnConnectionField in `amplify/cli.json` to false to disable custom primary key. To regenerate your API, add or remove an empty newline to your GraphQL schema (to change the computed hash) then run `amplify push`.' + 'The SQLite adapter does not support schemas using custom primary key. Set `graphQLTransformer.respectPrimaryKeyAttributesOnConnectionField in `amplify/cli.json` to false to disable custom primary key. To regenerate your API, add or remove an empty newline to your GraphQL schema (to change the computed hash) then run `amplify push`.', ); } await this.db.init(); @@ -112,7 +112,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { async save( model: T, - condition?: ModelPredicate + condition?: ModelPredicate, ): Promise<[T, OpType.INSERT | OpType.UPDATE][]> { const modelConstructor = Object.getPrototypeOf(model) .constructor as PersistentModelConstructor; @@ -122,12 +122,12 @@ export class CommonSQLiteAdapter implements StorageAdapter { model, this.schema.namespaces[this.namespaceResolver(modelConstructor)], this.modelInstanceCreator, - this.getModelConstructorByModelName + this.getModelConstructorByModelName, ); const connectionStoreNames = Object.values(connectedModels).map( ({ modelName, item, instance }) => { return { modelName, item, instance }; - } + }, ); const [queryStatement, params] = queryByIdStatement(model.id, tableName); @@ -179,7 +179,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { private async load( namespaceName: string, srcModelName: string, - records: T[] + records: T[], ): Promise { const namespace = this.schema.namespaces[namespaceName]; const relations = namespace.relationships[srcModelName].relationTypes; @@ -187,12 +187,12 @@ export class CommonSQLiteAdapter implements StorageAdapter { const modelConstructor = this.getModelConstructorByModelName( namespaceName, - srcModelName + srcModelName, ); if (connectionTableNames.length === 0) { return records.map(record => - this.modelInstanceCreator(modelConstructor, record) + this.modelInstanceCreator(modelConstructor, record), ); } @@ -212,7 +212,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { async query( modelConstructor: PersistentModelConstructor, predicate?: ModelPredicate, - pagination?: PaginationInput + pagination?: PaginationInput, ): Promise { const { name: tableName } = modelConstructor; const namespaceName = this.namespaceResolver(modelConstructor); @@ -239,7 +239,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { predicates, sortPredicates, limit, - page + page, ); return await this.db.getAll(queryStatement, params); @@ -250,7 +250,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { private async getById( tableName: string, - id: string + id: string, ): Promise { const [queryStatement, params] = queryByIdStatement(id, tableName); const record = await this.db.get(queryStatement, params); @@ -259,13 +259,13 @@ export class CommonSQLiteAdapter implements StorageAdapter { } private idFromPredicate( - predicates: PredicatesGroup + predicates: PredicatesGroup, ) { const { predicates: predicateObjs } = predicates; const idPredicate = predicateObjs.length === 1 && (predicateObjs.find( - p => isPredicateObj(p) && p.field === 'id' && p.operator === 'eq' + p => isPredicateObj(p) && p.field === 'id' && p.operator === 'eq', ) as PredicateObject); return idPredicate && idPredicate.operand; @@ -273,7 +273,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { async queryOne( modelConstructor: PersistentModelConstructor, - firstOrLast: QueryOne = QueryOne.FIRST + firstOrLast: QueryOne = QueryOne.FIRST, ): Promise { const { name: tableName } = modelConstructor; const [queryStatement, params] = queryOneStatement(firstOrLast, tableName); @@ -291,7 +291,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { // For Has Many and Has One relations to have SQL handle cascades automatically async delete( modelOrModelConstructor: T | PersistentModelConstructor, - condition?: ModelPredicate + condition?: ModelPredicate, ): Promise<[T[], T[]]> { if (isModelConstructor(modelOrModelConstructor)) { const modelConstructor = modelOrModelConstructor; @@ -306,13 +306,13 @@ export class CommonSQLiteAdapter implements StorageAdapter { const models = await this.db.selectAndDelete( queryStatement, - deleteStatement + deleteStatement, ); const modelInstances = await this.load( namespaceName, modelConstructor.name, - models + models, ); return [modelInstances, modelInstances]; @@ -325,7 +325,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { if (condition) { const [queryStatement, params] = queryByIdStatement( model.id, - tableName + tableName, ); const fromDB = await this.db.get(queryStatement, params); @@ -351,7 +351,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { const [deleteStatement, deleteParams] = deleteByIdStatement( model.id, - tableName + tableName, ); await this.db.save(deleteStatement, deleteParams); @@ -359,7 +359,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { } else { const [deleteStatement, params] = deleteByIdStatement( model.id, - tableName + tableName, ); await this.db.save(deleteStatement, params); @@ -370,7 +370,7 @@ export class CommonSQLiteAdapter implements StorageAdapter { async batchSave( modelConstructor: PersistentModelConstructor, - items: ModelInstanceMetadataWithId[] + items: ModelInstanceMetadataWithId[], ): Promise<[T, OpType][]> { const { name: tableName } = modelConstructor; const result: [T, OpType][] = []; @@ -390,13 +390,13 @@ export class CommonSQLiteAdapter implements StorageAdapter { this.modelInstanceCreator(modelConstructor, item), this.schema.namespaces[this.namespaceResolver(modelConstructor)], this.modelInstanceCreator, - this.getModelConstructorByModelName + this.getModelConstructorByModelName, ); const { id, _deleted } = item; const { instance } = connectedModels.find( - ({ instance }) => instance.id === id + ({ instance }) => instance.id === id, ); if (_deleted) { @@ -420,14 +420,14 @@ export class CommonSQLiteAdapter implements StorageAdapter { if (response === undefined) { const insertStatement = modelInsertStatement( itemsToSave[idx], - tableName + tableName, ); saveStatements.add(insertStatement); result.push([(itemsToSave[idx]), OpType.INSERT]); } else { const updateStatement = modelUpdateStatement( itemsToSave[idx], - tableName + tableName, ); saveStatements.add(updateStatement); result.push([(itemsToSave[idx]), OpType.UPDATE]); diff --git a/packages/datastore-storage-adapter/src/common/SQLiteUtils.ts b/packages/datastore-storage-adapter/src/common/SQLiteUtils.ts index e1434c767c3..431b4918fff 100644 --- a/packages/datastore-storage-adapter/src/common/SQLiteUtils.ts +++ b/packages/datastore-storage-adapter/src/common/SQLiteUtils.ts @@ -77,7 +77,7 @@ export function getSQLiteType( scalar: keyof Omit< typeof GraphQLScalarType, 'getJSType' | 'getValidationFunction' | 'getSQLiteType' - > + >, ): 'TEXT' | 'INTEGER' | 'REAL' | 'BLOB' { switch (scalar) { case 'Boolean': @@ -109,13 +109,13 @@ export function generateSchemaStatements(schema: InternalSchema): string[] { const isUserModel = namespaceName === USER; return Object.values(namespace.models).map(model => - modelCreateTableStatement(model, isUserModel) + modelCreateTableStatement(model, isUserModel), ); }); } export const implicitAuthFieldsForModel: (model: SchemaModel) => string[] = ( - model: SchemaModel + model: SchemaModel, ) => { if (!model.attributes || !model.attributes.length) { return []; @@ -134,7 +134,7 @@ export const implicitAuthFieldsForModel: (model: SchemaModel) => string[] = ( return authFieldsForModel.filter((authField: string) => { const authFieldExplicitlyDefined = Object.values(model.fields).find( - (f: ModelField) => f.name === authField + (f: ModelField) => f.name === authField, ); return !authFieldExplicitlyDefined; }); @@ -142,7 +142,7 @@ export const implicitAuthFieldsForModel: (model: SchemaModel) => string[] = ( export function modelCreateTableStatement( model: SchemaModel, - userModel: boolean = false + userModel: boolean = false, ): string { // implicitly defined auth fields, e.g., `owner`, `groupsField`, etc. const implicitAuthFields = implicitAuthFieldsForModel(model); @@ -169,7 +169,7 @@ export function modelCreateTableStatement( if (isTargetNameAssociation(field.association)) { // check if this field has been explicitly defined in the model const fkDefinedInModel = Object.values(model.fields).find( - (f: ModelField) => f.name === field?.association?.targetName + (f: ModelField) => f.name === field?.association?.targetName, ); // if the FK is not explicitly defined in the model, we have to add it here @@ -215,7 +215,7 @@ export function modelCreateTableStatement( export function modelInsertStatement( model: PersistentModel, - tableName: string + tableName: string, ): ParameterizedStatement { const keys = keysFromModel(model); const [paramaterized, values] = valuesFromModel(model); @@ -227,7 +227,7 @@ export function modelInsertStatement( export function modelUpdateStatement( model: PersistentModel, - tableName: string + tableName: string, ): ParameterizedStatement { const [paramaterized, values] = updateSet(model); @@ -238,7 +238,7 @@ export function modelUpdateStatement( export function queryByIdStatement( id: string, - tableName: string + tableName: string, ): ParameterizedStatement { return [`SELECT * FROM "${tableName}" WHERE "id" = ?`, [id]]; } @@ -305,7 +305,7 @@ export const whereConditionFromPredicateObject = ({ const specialNullClause = buildSpecialNullComparison( field, operator, - operand + operand, ); if (specialNullClause) { return [specialNullClause, []]; @@ -350,7 +350,7 @@ export const whereConditionFromPredicateObject = ({ }; export function whereClauseFromPredicate( - predicate: PredicatesGroup + predicate: PredicatesGroup, ): ParameterizedStatement { const result = []; const params = []; @@ -363,7 +363,7 @@ export function whereClauseFromPredicate( function recurse( predicate: PredicatesGroup | PredicateObject, result = [], - params = [] + params = [], ): void { if (isPredicateGroup(predicate)) { const { type: groupType, predicates: groupPredicates } = predicate; @@ -389,7 +389,7 @@ export function whereClauseFromPredicate( recurse(p, groupResult, params); } result.push( - `${isNegation ? 'NOT' : ''}(${groupResult.join(` ${filterType} `)})` + `${isNegation ? 'NOT' : ''}(${groupResult.join(` ${filterType} `)})`, ); } else if (isPredicateObj(predicate)) { const [condition, conditionParams] = @@ -408,11 +408,11 @@ const sortDirectionMap = { }; export function orderByClauseFromSort( - sortPredicate: SortPredicatesGroup = [] + sortPredicate: SortPredicatesGroup = [], ): string { const orderByParts = sortPredicate.map( ({ field, sortDirection }) => - `"${String(field)}" ${sortDirectionMap[sortDirection]}` + `"${String(field)}" ${sortDirectionMap[sortDirection]}`, ); // We always sort by _rowid_ last @@ -423,7 +423,7 @@ export function orderByClauseFromSort( export function limitClauseFromPagination( limit: number, - page: number = 0 + page: number = 0, ): ParameterizedStatement { const params = [limit]; let clause = 'LIMIT ?'; @@ -441,7 +441,7 @@ export function queryAllStatement( predicate?: PredicatesGroup, sort?: SortPredicatesGroup, limit?: number, - page?: number + page?: number, ): ParameterizedStatement { let statement = `SELECT * FROM "${tableName}"`; const params = []; @@ -466,7 +466,7 @@ export function queryAllStatement( export function queryOneStatement( firstOrLast, - tableName: string + tableName: string, ): ParameterizedStatement { if (firstOrLast === QueryOne.FIRST) { // ORDER BY rowid will no longer work as expected if a customer has @@ -480,7 +480,7 @@ export function queryOneStatement( export function deleteByIdStatement( id: string, - tableName: string + tableName: string, ): ParameterizedStatement { const deleteStatement = `DELETE FROM "${tableName}" WHERE "id"=?`; return [deleteStatement, [id]]; @@ -488,7 +488,7 @@ export function deleteByIdStatement( export function deleteByPredicateStatement( tableName: string, - predicate?: PredicatesGroup + predicate?: PredicatesGroup, ): ParameterizedStatement { let statement = `DELETE FROM "${tableName}"`; const params = []; diff --git a/packages/datastore-storage-adapter/src/common/types.ts b/packages/datastore-storage-adapter/src/common/types.ts index 4d27d6626af..2957233176b 100644 --- a/packages/datastore-storage-adapter/src/common/types.ts +++ b/packages/datastore-storage-adapter/src/common/types.ts @@ -8,23 +8,23 @@ export interface CommonSQLiteDatabase { clear(): Promise; get( statement: string, - params: (string | number)[] + params: (string | number)[], ): Promise; getAll( statement: string, - params: (string | number)[] + params: (string | number)[], ): Promise; save(statement: string, params: (string | number)[]): Promise; batchQuery( - queryParameterizedStatement: Set + queryParameterizedStatement: Set, ): Promise; batchSave( saveParameterizedStatements: Set, - deleteParameterizedStatements?: Set + deleteParameterizedStatements?: Set, ): Promise; selectAndDelete( queryParameterizedStatement: ParameterizedStatement, - deleteParameterizedStatement: ParameterizedStatement + deleteParameterizedStatement: ParameterizedStatement, ): Promise; } diff --git a/packages/datastore/__tests__/AsyncStorage.test.ts b/packages/datastore/__tests__/AsyncStorage.test.ts index 3887ff7fe9d..158bd4345b8 100644 --- a/packages/datastore/__tests__/AsyncStorage.test.ts +++ b/packages/datastore/__tests__/AsyncStorage.test.ts @@ -57,7 +57,7 @@ jest.mock('../src/storage/adapter/InMemoryStore', () => { multiGet = async (keys: string[]) => { return keys.reduce( (res, k) => (res.push([k, inmemoryMap.get(k)!]), res), - [] as [string, string][] + [] as [string, string][], ); }; multiRemove = async (keys: string[]) => { @@ -84,7 +84,7 @@ jest.mock('../src/storage/adapter/InMemoryStore', () => { jest.mock( '../src/storage/adapter/getDefaultAdapter/index', - () => () => AsyncStorageAdapter + () => () => AsyncStorageAdapter, ); /** @@ -151,24 +151,24 @@ describe('AsyncStorage tests', () => { owner = await DataStore.save( new BlogOwner({ name: 'Owner 1', - }) + }), ); owner2 = await DataStore.save( new BlogOwner({ name: 'Owner 2', - }) + }), ); blog = await DataStore.save( new Blog({ name: 'Avatar: Last Airbender', owner, - }) + }), ); blog2 = await DataStore.save( new Blog({ name: 'blog2', owner: owner2, - }) + }), ); blog3 = await DataStore.save( new Blog({ @@ -176,9 +176,9 @@ describe('AsyncStorage tests', () => { owner: await DataStore.save( new BlogOwner({ name: 'owner 3', - }) + }), ), - }) + }), ); await DataStore.start(); @@ -193,8 +193,8 @@ describe('AsyncStorage tests', () => { expect(allKeys).not.toHaveLength(0); // At leaset the settings entry should be present expect(allKeys[0]).toMatch( new RegExp( - `@AmplifyDatastore::${DATASTORE}_Setting::Data::\\w{26}::\\w{26}` - ) + `@AmplifyDatastore::${DATASTORE}_Setting::Data::\\w{26}::\\w{26}`, + ), ); }); @@ -205,8 +205,8 @@ describe('AsyncStorage tests', () => { const get1 = JSON.parse( await AsyncStorage.getItem( - getKeyForAsyncStorage(USER, Blog.name, blog.id) - ) + getKeyForAsyncStorage(USER, Blog.name, blog.id), + ), ); expect({ @@ -218,8 +218,8 @@ describe('AsyncStorage tests', () => { const get2 = JSON.parse( await AsyncStorage.getItem( - getKeyForAsyncStorage(USER, BlogOwner.name, owner.id) - ) + getKeyForAsyncStorage(USER, BlogOwner.name, owner.id), + ), ); expect(owner).toMatchObject(get2); @@ -228,8 +228,8 @@ describe('AsyncStorage tests', () => { const get3 = JSON.parse( await AsyncStorage.getItem( - getKeyForAsyncStorage(USER, Blog.name, blog2.id) - ) + getKeyForAsyncStorage(USER, Blog.name, blog2.id), + ), ); expect({ @@ -254,7 +254,7 @@ describe('AsyncStorage tests', () => { await DataStore.save(p); const postFromDB = JSON.parse( - await AsyncStorage.getItem(getKeyForAsyncStorage(USER, Post.name, p.id)) + await AsyncStorage.getItem(getKeyForAsyncStorage(USER, Post.name, p.id)), ); expect(postFromDB.metadata).toMatchObject({ @@ -272,8 +272,8 @@ describe('AsyncStorage tests', () => { const get1 = JSON.parse( await AsyncStorage.getItem( - getKeyForAsyncStorage(USER, Blog.name, blog.id) - ) + getKeyForAsyncStorage(USER, Blog.name, blog.id), + ), ); expect(get1['blogOwnerId']).toBe(owner.id); @@ -284,8 +284,8 @@ describe('AsyncStorage tests', () => { await DataStore.save(updated); const get2 = JSON.parse( await AsyncStorage.getItem( - getKeyForAsyncStorage(USER, Blog.name, blog.id) - ) + getKeyForAsyncStorage(USER, Blog.name, blog.id), + ), ); expect(get2.name).toEqual(updated.name); @@ -305,7 +305,7 @@ describe('AsyncStorage tests', () => { if (item.owner) { expect(await item.owner).toHaveProperty('name'); } - }) + }), ); }); @@ -404,7 +404,7 @@ describe('AsyncStorage tests', () => { .firstName(SortDirection.ASCENDING) .lastName(SortDirection.ASCENDING) .username(SortDirection.ASCENDING), - } + }, ); expect(sortedPersons[0].username).toEqual('johnsnow'); @@ -428,7 +428,7 @@ describe('AsyncStorage tests', () => { await DataStore.save( Blog.copyOf(blog, draft => { draft; - }) + }), ); await DataStore.save(blog2); await DataStore.save(blog3); @@ -506,17 +506,17 @@ describe('AsyncStorage tests', () => { const a1 = await DataStore.save( new Author({ name: 'author1', - }) + }), ); const a2 = await DataStore.save( new Author({ name: 'author2', - }) + }), ); const a3 = await DataStore.save( new Author({ name: 'author3', - }) + }), ); const blog = await DataStore.save( new Blog({ @@ -524,9 +524,9 @@ describe('AsyncStorage tests', () => { owner: await DataStore.save( new BlogOwner({ name: 'O1', - }) + }), ), - }) + }), ); await DataStore.save(blog); @@ -562,7 +562,7 @@ describe('AsyncStorage tests', () => { expect(deleted).toStrictEqual(author); const fromDB = await AsyncStorage.getItem( - getKeyForAsyncStorage(USER, Author.name, author.id) + getKeyForAsyncStorage(USER, Author.name, author.id), ); expect(fromDB).toBeUndefined(); @@ -611,7 +611,7 @@ describe('AsyncStorage tests', () => { function getKeyForAsyncStorage( namespaceName: string, modelName: string, - id: string + id: string, ) { const collectionInMemoryIndex: Map> = (( AsyncStorageAdapter diff --git a/packages/datastore/__tests__/AsyncStorageAdapter.test.ts b/packages/datastore/__tests__/AsyncStorageAdapter.test.ts index 10f51b3d9ae..ac5f1d61cf6 100644 --- a/packages/datastore/__tests__/AsyncStorageAdapter.test.ts +++ b/packages/datastore/__tests__/AsyncStorageAdapter.test.ts @@ -80,19 +80,19 @@ describe('AsyncStorageAdapter tests', () => { new Model({ field1: 'Some value', dateCreated: baseDate.toISOString(), - }) + }), )); await DataStore.save( new Model({ field1: 'another value', dateCreated: new Date(baseDate.getTime() + 1).toISOString(), - }) + }), ); await DataStore.save( new Model({ field1: 'a third value', dateCreated: new Date(baseDate.getTime() + 2).toISOString(), - }) + }), ); }); @@ -110,7 +110,7 @@ describe('AsyncStorageAdapter tests', () => { it('Should call getAll for query with a predicate', async () => { const results = await DataStore.query(Model, c => - c.field1.contains('value') + c.field1.contains('value'), ); expect(results.length).toEqual(3); @@ -124,7 +124,7 @@ describe('AsyncStorageAdapter tests', () => { c => c.field1.contains('value'), { sort: s => s.dateCreated(SortDirection.DESCENDING), - } + }, ); expect(results.length).toEqual(3); @@ -187,11 +187,11 @@ describe('AsyncStorageAdapter tests', () => { }); ({ id: profile1Id } = await DataStore.save( - new Profile({ firstName: 'Rick', lastName: 'Bob' }) + new Profile({ firstName: 'Rick', lastName: 'Bob' }), )); ({ id: user1Id } = await DataStore.save( - new User({ name: 'test', profileID: profile1Id }) + new User({ name: 'test', profileID: profile1Id }), )); }); @@ -210,7 +210,7 @@ describe('AsyncStorageAdapter tests', () => { ({ id: post1Id } = post); ({ id: comment1Id } = await DataStore.save( - new Comment({ content: 'Test Content', post }) + new Comment({ content: 'Test Content', post }), )); }); @@ -270,13 +270,13 @@ describe('AsyncStorageAdapter tests', () => { }); profile = await DataStore.save( - new Profile({ firstName: 'Rick', lastName: 'Bob' }) + new Profile({ firstName: 'Rick', lastName: 'Bob' }), ); }); it('should allow linking model via model field', async () => { const savedUser = await DataStore.save( - new User({ name: 'test', profile }) + new User({ name: 'test', profile }), ); const user1Id = savedUser.id; @@ -287,7 +287,7 @@ describe('AsyncStorageAdapter tests', () => { it('should allow linking model via FK', async () => { const savedUser = await DataStore.save( - new User({ name: 'test', profileID: profile.id }) + new User({ name: 'test', profileID: profile.id }), ); const user1Id = savedUser.id; @@ -316,13 +316,13 @@ describe('AsyncStorageAdapter tests', () => { }); profile = await DataStore.save( - new Profile({ firstName: 'Rick', lastName: 'Bob' }) + new Profile({ firstName: 'Rick', lastName: 'Bob' }), ); }); it('should allow linking model via model field', async () => { const savedUser = await DataStore.save( - new User({ name: 'test', profile }) + new User({ name: 'test', profile }), ); const user1Id = savedUser.id; @@ -333,7 +333,7 @@ describe('AsyncStorageAdapter tests', () => { it('should allow linking model via FK', async () => { const savedUser = await DataStore.save( - new User({ name: 'test', profileID: profile.id }) + new User({ name: 'test', profileID: profile.id }), ); const user1Id = savedUser.id; diff --git a/packages/datastore/__tests__/DataStore/DataStore.BasicOperations.test.ts b/packages/datastore/__tests__/DataStore/DataStore.BasicOperations.test.ts index 6439f7d9648..f607982d379 100644 --- a/packages/datastore/__tests__/DataStore/DataStore.BasicOperations.test.ts +++ b/packages/datastore/__tests__/DataStore/DataStore.BasicOperations.test.ts @@ -322,7 +322,7 @@ describe('Basic operations', () => { dateCreated: new Date().toISOString(), }); }).toThrow( - 'Field field1 should be of type string, number received. 1234' + 'Field field1 should be of type string, number received. 1234', ); }); @@ -333,7 +333,7 @@ describe('Basic operations', () => { dateCreated: 'not-a-date', }); }).toThrow( - 'Field dateCreated should be of type AWSDateTime, validation failed. not-a-date' + 'Field dateCreated should be of type AWSDateTime, validation failed. not-a-date', ); }); @@ -350,7 +350,7 @@ describe('Basic operations', () => { penNames: [], nominations: [], }), - }).metadata.tags + }).metadata.tags, ).toBeUndefined(); }); @@ -368,7 +368,7 @@ describe('Basic operations', () => { }), }); }).toThrow( - 'All elements in the rewards array should be of type string, [null] received. ' + 'All elements in the rewards array should be of type string, [null] received. ', ); }); @@ -387,7 +387,7 @@ describe('Basic operations', () => { }, }); }).toThrow( - 'All elements in the rewards array should be of type string, [null] received. ' + 'All elements in the rewards array should be of type string, [null] received. ', ); }); @@ -443,7 +443,7 @@ describe('Basic operations', () => { }); const copied = Model.copyOf( original, - d => (d.optionalField1 = undefined) + d => (d.optionalField1 = undefined), ); expect(copied.optionalField1).toBe(null); }); @@ -456,7 +456,7 @@ describe('Basic operations', () => { emails: [null!], }); }).toThrow( - 'All elements in the emails array should be of type string, [null] received. ' + 'All elements in the emails array should be of type string, [null] received. ', ); }); @@ -488,7 +488,7 @@ describe('Basic operations', () => { ips: ['not.an.ip'], }); }).toThrow( - `All elements in the ips array should be of type AWSIPAddress, validation failed for one or more elements. not.an.ip` + `All elements in the ips array should be of type AWSIPAddress, validation failed for one or more elements. not.an.ip`, ); }); @@ -500,7 +500,7 @@ describe('Basic operations', () => { ips: ['1.1.1.1', 'not.an.ip'], }); }).toThrow( - `All elements in the ips array should be of type AWSIPAddress, validation failed for one or more elements. 1.1.1.1,not.an.ip` + `All elements in the ips array should be of type AWSIPAddress, validation failed for one or more elements. 1.1.1.1,not.an.ip`, ); }); @@ -533,7 +533,7 @@ describe('Basic operations', () => { emails: ['not-an-email'], }); }).toThrow( - 'All elements in the emails array should be of type AWSEmail, validation failed for one or more elements. not-an-email' + 'All elements in the emails array should be of type AWSEmail, validation failed for one or more elements. not-an-email', ); }); @@ -583,7 +583,7 @@ describe('Basic operations', () => { }), }); }).toThrow( - 'All elements in the penNames array should be of type string, [undefined] received. ' + 'All elements in the penNames array should be of type string, [undefined] received. ', ); }); @@ -602,7 +602,7 @@ describe('Basic operations', () => { }, }); }).toThrow( - 'All elements in the penNames array should be of type string, [undefined] received. ' + 'All elements in the penNames array should be of type string, [undefined] received. ', ); }); @@ -620,7 +620,7 @@ describe('Basic operations', () => { }), }); }).toThrow( - 'All elements in the tags array should be of type string | null | undefined, [number] received. 1234' + 'All elements in the tags array should be of type string | null | undefined, [number] received. 1234', ); }); @@ -639,7 +639,7 @@ describe('Basic operations', () => { }, }); }).toThrow( - 'All elements in the tags array should be of type string | null | undefined, [number] received. 1234' + 'All elements in the tags array should be of type string | null | undefined, [number] received. 1234', ); }); @@ -785,7 +785,7 @@ describe('Basic operations', () => { }), }); }).toThrow( - 'All elements in the misc array should be of type string | null | undefined, [null,number] received. ,123' + 'All elements in the misc array should be of type string | null | undefined, [null,number] received. ,123', ); }); @@ -803,13 +803,13 @@ describe('Basic operations', () => { }, }); }).toThrow( - 'All elements in the misc array should be of type string | null | undefined, [null,number] received. ,123' + 'All elements in the misc array should be of type string | null | undefined, [null,number] received. ,123', ); }); test('allow extra attribute', () => { expect( - new Model({ extraAttribute: 'some value', field1: 'some value' }) + new Model({ extraAttribute: 'some value', field1: 'some value' }), ).toHaveProperty('extraAttribute'); }); @@ -827,7 +827,7 @@ describe('Basic operations', () => { }); Model.copyOf(source, d => (d.field1 = 1234)); }).toThrow( - 'Field field1 should be of type string, number received. 1234' + 'Field field1 should be of type string, number received. 1234', ); }); @@ -840,7 +840,7 @@ describe('Basic operations', () => { metadata: 'invalid', }); }).toThrow( - 'Field metadata should be of type Metadata, string recieved. invalid' + 'Field metadata should be of type Metadata, string recieved. invalid', ); }); @@ -852,7 +852,7 @@ describe('Basic operations', () => { metadata: null, }); }).not.toThrow( - 'Field metadata should be of type Metadata, string recieved. invalid' + 'Field metadata should be of type Metadata, string recieved. invalid', ); }); @@ -882,7 +882,7 @@ describe('Basic operations', () => { logins: ['bad type', 'another bad type'], }); }).toThrow( - 'All elements in the logins array should be of type Login, [string] received. bad type' + 'All elements in the logins array should be of type Login, [string] received. bad type', ); }); @@ -916,7 +916,7 @@ describe('Basic operations', () => { logins: 'my login', }); }).toThrow( - 'Field logins should be of type [Login | null | undefined], string received. my login' + 'Field logins should be of type [Login | null | undefined], string received. my login', ); }); @@ -933,19 +933,19 @@ describe('Basic operations', () => { test('Delete params', async () => { await expect(DataStore.delete(undefined)).rejects.toThrow( - 'Model or Model Constructor required' + 'Model or Model Constructor required', ); await expect(DataStore.delete(Model)).rejects.toThrow( - 'Id to delete or criteria required. Do you want to delete all? Pass Predicates.ALL' + 'Id to delete or criteria required. Do you want to delete all? Pass Predicates.ALL', ); await expect(DataStore.delete(Model, (() => {}))).rejects.toThrow( - "Invalid predicate. Terminate your predicate with a valid condition (e.g., `p => p.field.eq('value')`) or pass `Predicates.ALL`." + "Invalid predicate. Terminate your predicate with a valid condition (e.g., `p => p.field.eq('value')`) or pass `Predicates.ALL`.", ); await expect(DataStore.delete({})).rejects.toThrow( - 'Object is not an instance of a valid model' + 'Object is not an instance of a valid model', ); await expect( @@ -954,8 +954,8 @@ describe('Basic operations', () => { field1: 'somevalue', dateCreated: new Date().toISOString(), }), - {} - ) + {}, + ), ).rejects.toThrow('Invalid criteria'); }); @@ -1007,12 +1007,12 @@ describe('Basic operations', () => { nominations: [], misc: [null, 'ok'], }), - }) + }), ); } const deleted = await DataStore.delete(Model, m => - m.field1.eq('someField') + m.field1.eq('someField'), ); expect(deleted.length).toEqual(10); @@ -1065,7 +1065,7 @@ describe('Basic operations', () => { nominations: [], misc: [null, 'ok'], }), - }) + }), ); const deleted: Model[] = await DataStore.delete(Model, saved.id); @@ -1076,34 +1076,34 @@ describe('Basic operations', () => { test('Query params', async () => { await expect(DataStore.query(undefined)).rejects.toThrow( - 'Constructor is not for a valid model' + 'Constructor is not for a valid model', ); await expect(DataStore.query(undefined)).rejects.toThrow( - 'Constructor is not for a valid model' + 'Constructor is not for a valid model', ); await expect( - DataStore.query(Model, 'someid', { page: 0 }) + DataStore.query(Model, 'someid', { page: 0 }), ).rejects.toThrow('Limit is required when requesting a page'); await expect( - DataStore.query(Model, 'someid', { page: 'a', limit: 10 }) + DataStore.query(Model, 'someid', { page: 'a', limit: 10 }), ).rejects.toThrow('Page should be a number'); await expect( - DataStore.query(Model, 'someid', { page: -1, limit: 10 }) + DataStore.query(Model, 'someid', { page: -1, limit: 10 }), ).rejects.toThrow("Page can't be negative"); await expect( DataStore.query(Model, 'someid', { page: 0, limit: 'avalue', - }) + }), ).rejects.toThrow('Limit should be a number'); await expect( - DataStore.query(Model, 'someid', { page: 0, limit: -1 }) + DataStore.query(Model, 'someid', { page: 0, limit: -1 }), ).rejects.toThrow("Limit can't be negative"); }); }); diff --git a/packages/datastore/__tests__/DataStore/DataStore.CustomPrimaryKey.test.ts b/packages/datastore/__tests__/DataStore/DataStore.CustomPrimaryKey.test.ts index 53040e76780..fa64684f6dc 100644 --- a/packages/datastore/__tests__/DataStore/DataStore.CustomPrimaryKey.test.ts +++ b/packages/datastore/__tests__/DataStore/DataStore.CustomPrimaryKey.test.ts @@ -82,7 +82,7 @@ describe('DataStore Custom PK tests', () => { }; expect(PostCustomPK).toHaveProperty( - nameOf>('copyOf') + nameOf>('copyOf'), ); expect(typeof PostCustomPK.copyOf).toBe('function'); @@ -169,9 +169,9 @@ describe('DataStore Custom PK tests', () => { // the record's PK, or creating a new record are all breaking changes. expect(consoleWarn).toHaveBeenCalledWith( expect.stringContaining( - "copyOf() does not update PK fields. The 'postId' update is being ignored." + "copyOf() does not update PK fields. The 'postId' update is being ignored.", ), - expect.objectContaining({ source: model1 }) + expect.objectContaining({ source: model1 }), ); }); @@ -389,7 +389,7 @@ describe('DataStore Custom PK tests', () => { expect(result).toMatchObject(model); expect(patches[0].map(p => p.path.join(''))).toEqual( - expectedPatchedFields + expectedPatchedFields, ); }); @@ -626,7 +626,7 @@ describe('DataStore Custom PK tests', () => { dateCreated: 'not-a-date', }); }).toThrow( - 'Field dateCreated should be of type AWSDateTime, validation failed. not-a-date' + 'Field dateCreated should be of type AWSDateTime, validation failed. not-a-date', ); expect(() => { @@ -637,7 +637,7 @@ describe('DataStore Custom PK tests', () => { emails: [null as any], // because we're trying to trigger JS error }); }).toThrow( - 'All elements in the emails array should be of type string, [null] received. ' + 'All elements in the emails array should be of type string, [null] received. ', ); expect(() => { @@ -657,7 +657,7 @@ describe('DataStore Custom PK tests', () => { emails: ['not-an-email'], }); }).toThrow( - 'All elements in the emails array should be of type AWSEmail, validation failed for one or more elements. not-an-email' + 'All elements in the emails array should be of type AWSEmail, validation failed for one or more elements. not-an-email', ); expect({ @@ -680,21 +680,21 @@ describe('DataStore Custom PK tests', () => { test('Delete params', async () => { await expect(DataStore.delete(undefined)).rejects.toThrow( - 'Model or Model Constructor required' + 'Model or Model Constructor required', ); await expect(DataStore.delete(PostCustomPK)).rejects.toThrow( - 'Id to delete or criteria required. Do you want to delete all? Pass Predicates.ALL' + 'Id to delete or criteria required. Do you want to delete all? Pass Predicates.ALL', ); await expect( - DataStore.delete(PostCustomPK, (() => {})) + DataStore.delete(PostCustomPK, (() => {})), ).rejects.toThrow( - "Invalid predicate. Terminate your predicate with a valid condition (e.g., `p => p.field.eq('value')`) or pass `Predicates.ALL`." + "Invalid predicate. Terminate your predicate with a valid condition (e.g., `p => p.field.eq('value')`) or pass `Predicates.ALL`.", ); await expect(DataStore.delete({})).rejects.toThrow( - 'Object is not an instance of a valid model' + 'Object is not an instance of a valid model', ); await expect( @@ -704,8 +704,8 @@ describe('DataStore Custom PK tests', () => { title: 'somevalue', dateCreated: new Date().toISOString(), }), - {} - ) + {}, + ), ).rejects.toThrow('Invalid criteria'); }); @@ -752,17 +752,17 @@ describe('DataStore Custom PK tests', () => { postId: `${i}`, title: 'someField', dateCreated: new Date().toISOString(), - }) + }), ); - }) + }), ); const deleted = await DataStore.delete(PostCustomPK, m => - m.title.eq('someField') + m.title.eq('someField'), ); const sortedRecords = deleted.sort((a, b) => - a.postId < b.postId ? -1 : 1 + a.postId < b.postId ? -1 : 1, ); expect(sortedRecords.length).toEqual(10); @@ -810,12 +810,12 @@ describe('DataStore Custom PK tests', () => { postId: '12345', title: 'someField', dateCreated: new Date().toISOString(), - }) + }), ); const deleted: PostCustomPKType[] = await DataStore.delete( PostCustomPK, - saved.postId + saved.postId, ); expect(deleted.length).toEqual(1); @@ -860,13 +860,13 @@ describe('DataStore Custom PK tests', () => { postId: '12345', title: 'someField', dateCreated: new Date().toISOString(), - }) + }), ); const deleted: PostCustomPKType[] = await DataStore.delete( PostCustomPK, - m => m.postId.eq(saved.postId) + m => m.postId.eq(saved.postId), ); expect(deleted.length).toEqual(1); @@ -875,40 +875,40 @@ describe('DataStore Custom PK tests', () => { test('Query params', async () => { await expect(DataStore.query(undefined)).rejects.toThrow( - 'Constructor is not for a valid model' + 'Constructor is not for a valid model', ); await expect(DataStore.query(undefined)).rejects.toThrow( - 'Constructor is not for a valid model' + 'Constructor is not for a valid model', ); await expect( - DataStore.query(PostCustomPK, 'someid', { page: 0 }) + DataStore.query(PostCustomPK, 'someid', { page: 0 }), ).rejects.toThrow('Limit is required when requesting a page'); await expect( DataStore.query(PostCustomPK, 'someid', { page: 'a', limit: 10, - }) + }), ).rejects.toThrow('Page should be a number'); await expect( - DataStore.query(PostCustomPK, 'someid', { page: -1, limit: 10 }) + DataStore.query(PostCustomPK, 'someid', { page: -1, limit: 10 }), ).rejects.toThrow("Page can't be negative"); await expect( DataStore.query(PostCustomPK, 'someid', { page: 0, limit: 'avalue', - }) + }), ).rejects.toThrow('Limit should be a number'); await expect( DataStore.query(PostCustomPK, 'someid', { page: 0, limit: -1, - }) + }), ).rejects.toThrow("Limit can't be negative"); }); @@ -960,7 +960,7 @@ describe('DataStore Custom PK tests', () => { test('one by custom PK', async () => { const onePostCustomPKById = await DataStore.query( PostCustomPK, - 'someid' + 'someid', ); expectType(onePostCustomPKById!); @@ -970,7 +970,7 @@ describe('DataStore Custom PK tests', () => { test('with criteria', async () => { const multiPostCustomPKWithCriteria = await DataStore.query( PostCustomPK, - c => c.title.contains('something') + c => c.title.contains('something'), ); expectType(multiPostCustomPKWithCriteria); @@ -983,7 +983,7 @@ describe('DataStore Custom PK tests', () => { const allPostCustomPKsPaginated = await DataStore.query( PostCustomPK, Predicates.ALL, - { page: 0, limit: 20 } + { page: 0, limit: 20 }, ); expectType(allPostCustomPKsPaginated); @@ -1007,7 +1007,7 @@ describe('DataStore Custom PK tests', () => { test('one by postId', async () => { const onePostCustomPKById = await DataStore.query( PostCustomPK, - 'someid' + 'someid', ); expectType(onePostCustomPKById!); expect(onePostCustomPKById!.title).toBeDefined(); @@ -1016,7 +1016,7 @@ describe('DataStore Custom PK tests', () => { test('with criteria', async () => { const multiPostCustomPKWithCriteria = await DataStore.query(PostCustomPK, c => - c.title.contains('something') + c.title.contains('something'), ); expectType(multiPostCustomPKWithCriteria); @@ -1030,7 +1030,7 @@ describe('DataStore Custom PK tests', () => { await DataStore.query( PostCustomPK, Predicates.ALL, - { page: 0, limit: 20 } + { page: 0, limit: 20 }, ); expectType(allPostCustomPKsPaginated); diff --git a/packages/datastore/__tests__/DataStore/DataStore.TypeDefinitions.test.ts b/packages/datastore/__tests__/DataStore/DataStore.TypeDefinitions.test.ts index 246317eb65a..b108e0a4641 100644 --- a/packages/datastore/__tests__/DataStore/DataStore.TypeDefinitions.test.ts +++ b/packages/datastore/__tests__/DataStore/DataStore.TypeDefinitions.test.ts @@ -67,7 +67,7 @@ describe('Type definitions', () => { }); test('with criteria', async () => { const multiModelWithCriteria = await DataStore.query(Model, c => - c.field1.contains('something') + c.field1.contains('something'), ); expectType(multiModelWithCriteria); const [one] = multiModelWithCriteria; @@ -109,7 +109,7 @@ describe('Type definitions', () => { }); test('with criteria', async () => { const multiModelWithCriteria = await DataStore.query(Model, c => - c.field1.contains('something') + c.field1.contains('something'), ); expectType(multiModelWithCriteria); const [one] = multiModelWithCriteria; @@ -120,7 +120,7 @@ describe('Type definitions', () => { const allModelsPaginated = await DataStore.query( Model, Predicates.ALL, - { page: 0, limit: 20 } + { page: 0, limit: 20 }, ); expectType(allModelsPaginated); const [one] = allModelsPaginated; @@ -164,7 +164,7 @@ describe('Type definitions', () => { ({ element, model }) => { expectType>(model); expectType(element); - } + }, ); }); }); @@ -192,7 +192,7 @@ describe('Type definitions', () => { ({ element, model }) => { expectType>(model); expectType(element); - } + }, ); }); test('subscribe to model with criteria', async () => { @@ -200,7 +200,7 @@ describe('Type definitions', () => { ({ element, model }) => { expectType>(model); expectType(element); - } + }, ); }); }); diff --git a/packages/datastore/__tests__/DataStore/DataStore.test.ts b/packages/datastore/__tests__/DataStore/DataStore.test.ts index 2cbcc66ff9d..e732db0f0d7 100644 --- a/packages/datastore/__tests__/DataStore/DataStore.test.ts +++ b/packages/datastore/__tests__/DataStore/DataStore.test.ts @@ -93,7 +93,7 @@ describe('DataStore tests', () => { await expect(DataStore.start()).rejects.toThrow(errorRegex); expect(consoleError).toHaveBeenCalledWith( - expect.stringMatching(errorRegex) + expect.stringMatching(errorRegex), ); }); @@ -102,7 +102,7 @@ describe('DataStore tests', () => { await expect(DataStore.clear()).rejects.toThrow(errorRegex); expect(consoleError).toHaveBeenCalledWith( - expect.stringMatching(errorRegex) + expect.stringMatching(errorRegex), ); }); @@ -120,7 +120,7 @@ describe('DataStore tests', () => { }); await expect(DataStore.save(metadata)).rejects.toThrow( - 'Object is not an instance of a valid model' + 'Object is not an instance of a valid model', ); }); @@ -135,7 +135,7 @@ describe('DataStore tests', () => { }; expect(Model).toHaveProperty( - nameOf>('copyOf') + nameOf>('copyOf'), ); expect(typeof Model.copyOf).toBe('function'); @@ -190,7 +190,7 @@ describe('DataStore tests', () => { }).not.toThrow(); expect(consoleWarn).toHaveBeenCalledWith( - 'The schema has already been initialized' + 'The schema has already been initialized', ); }); @@ -202,7 +202,7 @@ describe('DataStore tests', () => { const { Metadata } = classes; expect(Metadata).not.toHaveProperty( - nameOf>('copyOf') + nameOf>('copyOf'), ); }); @@ -252,7 +252,7 @@ describe('DataStore tests', () => { expect(() => { initSchema({ ...testSchema(), codegenVersion }); }).toThrow( - 'Models were generated with an unsupported version of codegen.' + 'Models were generated with an unsupported version of codegen.', ); }); }); @@ -264,7 +264,7 @@ describe('DataStore tests', () => { expect(() => { initSchema({ ...testSchema(), codegenVersion }); }).not.toThrow( - 'Models were generated with an unsupported version of codegen.' + 'Models were generated with an unsupported version of codegen.', ); }); }); @@ -333,9 +333,9 @@ describe('DataStore tests', () => { // the record's PK, or creating a new record are all breaking changes. expect(consoleWarn).toHaveBeenCalledWith( expect.stringContaining( - "copyOf() does not update PK fields. The 'id' update is being ignored." + "copyOf() does not update PK fields. The 'id' update is being ignored.", ), - expect.objectContaining({ source: model1 }) + expect.objectContaining({ source: model1 }), ); }); diff --git a/packages/datastore/__tests__/DataStore/modelBehavior.test.ts b/packages/datastore/__tests__/DataStore/modelBehavior.test.ts index c2f87a2cd20..b86125ad1c2 100644 --- a/packages/datastore/__tests__/DataStore/modelBehavior.test.ts +++ b/packages/datastore/__tests__/DataStore/modelBehavior.test.ts @@ -25,7 +25,7 @@ describe('Model behavior', () => { const parent = await DataStore.save( new DefaultPKParent({ content: 'this is a decoy!', - }) + }), ); const comment = await DataStore.save( @@ -33,7 +33,7 @@ describe('Model behavior', () => { id: "not such a random id, but it's ok", content: 'here is some content', parent, - }) + }), ); const detachedComment = new DefaultPKChild({ @@ -43,7 +43,7 @@ describe('Model behavior', () => { }); expect(detachedComment.defaultPKParentChildrenId).toEqual( - comment.defaultPKParentChildrenId + comment.defaultPKParentChildrenId, ); expect(await detachedComment.parent).toBeUndefined(); @@ -56,7 +56,7 @@ describe('Model behavior', () => { const parent = await DataStore.save( new DefaultPKParent({ content: 'this is a decoy!', - }) + }), ); const comment = await DataStore.save( @@ -64,7 +64,7 @@ describe('Model behavior', () => { id: "not such a random id, but it's ok", content: 'here is some content', parent, - }) + }), ); const detachedParent = new DefaultPKParent({ @@ -86,7 +86,7 @@ describe('Model behavior', () => { const parent = await DataStore.save( new HasOneParent({ child, - }) + }), ); const disconnectedParent = new HasOneParent({ @@ -106,12 +106,12 @@ describe('Model behavior', () => { const { DataStore, HasOneChild, HasOneParent } = getDataStore(); const child = await DataStore.save( - new HasOneChild({ content: 'child content' }) + new HasOneChild({ content: 'child content' }), ); const parent = await DataStore.save( new HasOneParent({ child, - }) + }), ); const parentWithoutChild = HasOneParent.copyOf(parent, draft => { @@ -120,10 +120,10 @@ describe('Model behavior', () => { expect(parentWithoutChild.hasOneParentChildId).toBeNull(); expect( - (await DataStore.save(parentWithoutChild)).hasOneParentChildId + (await DataStore.save(parentWithoutChild)).hasOneParentChildId, ).toBeNull(); expect( - (await DataStore.query(HasOneParent, parent.id))!.hasOneParentChildId + (await DataStore.query(HasOneParent, parent.id))!.hasOneParentChildId, ).toBeNull(); await DataStore.clear(); @@ -136,11 +136,15 @@ describe('Model behavior', () => { new CompositePKParent({ customId: 'customId', content: 'content', - }) + }), ); const child = await DataStore.save( - new CompositePKChild({ childId: 'childId', content: 'content', parent }) + new CompositePKChild({ + childId: 'childId', + content: 'content', + parent, + }), ); const childWithoutParent = CompositePKChild.copyOf(child, draft => { @@ -149,19 +153,19 @@ describe('Model behavior', () => { expect(await childWithoutParent.parent).toBeUndefined(); expect( - await DataStore.save(childWithoutParent).then(c => c.parent) + await DataStore.save(childWithoutParent).then(c => c.parent), ).toBeUndefined(); expect( await DataStore.query(CompositePKChild, { childId: child.childId, content: child.content, - }).then(c => c!.parent) + }).then(c => c!.parent), ).toBeUndefined(); expect( await DataStore.query(CompositePKParent, { customId: parent.customId, content: parent.content, - }).then(c => c!.children.toArray()) + }).then(c => c!.children.toArray()), ).toEqual([]); await DataStore.clear(); @@ -180,12 +184,12 @@ describe('Model behavior', () => { await DataStore.save( new ModelWithBoolean({ boolField: true, - }) + }), ); } const sub = DataStore.observeQuery(ModelWithBoolean, m => - m.boolField.eq(true) + m.boolField.eq(true), ).subscribe(async ({ items, isSynced }) => { // we don't actually expect 0 records in our snapshots after our list runs out. // we just want to make TS happy. @@ -209,7 +213,7 @@ describe('Model behavior', () => { await DataStore.save( ModelWithBoolean.copyOf(itemToUpdate, m => { m.boolField = false; - }) + }), ); // advance time to trigger another snapshot. @@ -235,12 +239,12 @@ describe('Model behavior', () => { await DataStore.save( new ModelWithBoolean({ boolField: true, - }) + }), ); } const sub = DataStore.observeQuery(ModelWithBoolean, m => - m.boolField.ne(false) + m.boolField.ne(false), ).subscribe(({ items, isSynced }) => { // we don't actually expect 0 records in our snapshots after our list runs out. // we just want to make TS happy. @@ -263,7 +267,7 @@ describe('Model behavior', () => { await DataStore.save( ModelWithBoolean.copyOf(itemToUpdate, m => { m.boolField = false; - }) + }), ); // advance time to trigger another snapshot. @@ -288,7 +292,7 @@ describe('Model behavior', () => { title: 'create', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), - }) + }), ); const sub = DataStore.observeQuery(Post, Predicates.ALL, { @@ -313,7 +317,7 @@ describe('Model behavior', () => { Post.copyOf(newPost, updated => { updated.title = 'update'; updated.updatedAt = new Date().toISOString(); - }) + }), ); // observeQuery snapshots are debounced by 2s @@ -323,7 +327,7 @@ describe('Model behavior', () => { Post.copyOf(newPost, updated => { updated.title = 'update2'; updated.updatedAt = new Date().toISOString(); - }) + }), ); }); }); diff --git a/packages/datastore/__tests__/DataStore/observe.test.ts b/packages/datastore/__tests__/DataStore/observe.test.ts index f83c4551a3f..774cd5942c7 100644 --- a/packages/datastore/__tests__/DataStore/observe.test.ts +++ b/packages/datastore/__tests__/DataStore/observe.test.ts @@ -62,7 +62,7 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { field1: 'Smurfs', optionalField1: 'More Smurfs', dateCreated: new Date().toISOString(), - }) + }), ); expect(await DataStore.query(Model)).toHaveLength(1); await DataStore.stop(); @@ -81,14 +81,14 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { expect(element.optionalField1).toEqual('More Smurfs'); sub.unsubscribe(); done(); - } + }, ); DataStore.save( new Model({ field1: 'Smurfs', optionalField1: 'More Smurfs', dateCreated: new Date().toISOString(), - }) + }), ); } catch (error) { done(error); @@ -102,7 +102,7 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { field1: 'somevalue', optionalField1: 'This one should be returned', dateCreated: new Date().toISOString(), - }) + }), ); const sub = DataStore.observe(original).subscribe( @@ -115,7 +115,7 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { // We expect all fields, including ones that haven't been updated, to be returned: expect(element.optionalField1).toEqual('This one should be returned'); sub.unsubscribe(); - } + }, ); // decoy @@ -123,11 +123,11 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { new Model({ field1: "this one shouldn't get through", dateCreated: new Date().toISOString(), - }) + }), ); await DataStore.save( - Model.copyOf(original, m => (m.field1 = 'new field 1 value')) + Model.copyOf(original, m => (m.field1 = 'new field 1 value')), ); }); @@ -138,7 +138,7 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { field1: 'somevalue', optionalField1: 'additional value', dateCreated: new Date().toISOString(), - }) + }), ); const sub = DataStore.observe(Model).subscribe( @@ -150,18 +150,18 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { expect(element.field1).toEqual('new field 1 value'); expect(element.optionalField1).toEqual('additional value'); sub.unsubscribe(); - } + }, ); // decoy await DataStore.save( new Post({ title: "This one's a decoy! (kzazulhk)", - }) + }), ); await DataStore.save( - Model.copyOf(original, m => (m.field1 = 'new field 1 value')) + Model.copyOf(original, m => (m.field1 = 'new field 1 value')), ); }); @@ -171,11 +171,11 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { new Model({ field1: 'somevalue', dateCreated: new Date().toISOString(), - }) + }), ); const sub = DataStore.observe(Model, m => - m.field1.contains('new field 1') + m.field1.contains('new field 1'), ).subscribe(({ element, opType, model }) => { expectType>(model); expectType(element); @@ -190,11 +190,11 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { new Model({ field1: "This one's a decoy! (sfqpjzja)", dateCreated: new Date().toISOString(), - }) + }), ); await DataStore.save( - Model.copyOf(original, m => (m.field1 = 'new field 1 value')) + Model.copyOf(original, m => (m.field1 = 'new field 1 value')), ); }); @@ -204,11 +204,11 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { new Model({ field1: 'somevalue', dateCreated: new Date().toISOString(), - }) + }), ); const sub = DataStore.observe(Model, m => - m.field1.contains('value') + m.field1.contains('value'), ).subscribe(({ element, opType, model }) => { expectType>(model); expectType(element); @@ -223,7 +223,7 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { new Model({ field1: "This one's a decoy! (xgxbubyd)", dateCreated: new Date().toISOString(), - }) + }), ); await DataStore.delete(original); @@ -234,17 +234,17 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { const targetPost = await DataStore.save( new Post({ title: 'this is my post. hooray!', - }) + }), ); const nonTargetPost = await DataStore.save( new Post({ title: 'this is NOT my post. boo!', - }) + }), ); const sub = DataStore.observe(Comment, comment => - comment.post.title.eq(targetPost.title) + comment.post.title.eq(targetPost.title), ).subscribe(({ element: comment, opType, model }) => { expect(comment.content).toEqual('good comment'); sub.unsubscribe(); @@ -254,14 +254,14 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { new Comment({ content: 'bad comment', post: nonTargetPost, - }) + }), ); await DataStore.save( new Comment({ content: 'good comment', post: targetPost, - }) + }), ); await pause(0); @@ -277,35 +277,35 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { const targetPost = await DataStore.save( new Post({ title: 'this is my post. hooray!', - }) + }), ); const nonTargetPost = await DataStore.save( new Post({ title: 'this is NOT my post. boo!', - }) + }), ); await DataStore.save( - new Comment({ content: 'bad comment', post: nonTargetPost }) + new Comment({ content: 'bad comment', post: nonTargetPost }), ); await DataStore.save( - new Comment({ content: 'pre good comment', post: targetPost }) + new Comment({ content: 'pre good comment', post: targetPost }), ); const targetComment = await DataStore.save( new Comment({ content: 'good comment', post: targetPost, - }) + }), ); await DataStore.save( - new Comment({ content: 'post good comment', post: targetPost }) + new Comment({ content: 'post good comment', post: targetPost }), ); const sub = DataStore.observe(Post, post => - post.comments.content.eq(targetComment.content) + post.comments.content.eq(targetComment.content), ).subscribe(async ({ element: post, opType, model }) => { expect(post.title).toEqual('expected update'); sub.unsubscribe(); @@ -313,13 +313,13 @@ describe('DataStore observe, unmocked, with fake-indexeddb', () => { // should not see this one come through the subscription. await DataStore.save( - Post.copyOf(nonTargetPost, p => (p.title = 'decoy update')) + Post.copyOf(nonTargetPost, p => (p.title = 'decoy update')), ); // this is the update we expect to see come through, as it has // 'good comment' in its `comments` field. await DataStore.save( - Post.copyOf(targetPost, p => (p.title = 'expected update')) + Post.copyOf(targetPost, p => (p.title = 'expected update')), ); await pause(0); diff --git a/packages/datastore/__tests__/DataStore/observeQuery.test.ts b/packages/datastore/__tests__/DataStore/observeQuery.test.ts index 97ba55a5b0d..2f9562a087a 100644 --- a/packages/datastore/__tests__/DataStore/observeQuery.test.ts +++ b/packages/datastore/__tests__/DataStore/observeQuery.test.ts @@ -100,7 +100,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { monitor.unsubscribe(); returnSaved(savedItem); } - } + }, ); const savedItem = await DataStore.save(item); }); @@ -134,7 +134,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { await DataStore.save( new Post({ title: `the post ${i}`, - }) + }), ); } @@ -165,14 +165,14 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { if (expecteds.length === 0) { sub.unsubscribe(); } - } + }, ); for (let i = 0; i < 5; i++) { await fullSave( new Post({ title: `the post ${i}`, - }) + }), ); } @@ -184,7 +184,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { const expecteds = [0, 5]; const sub = DataStore.observeQuery(Post, p => - p.title.contains('include') + p.title.contains('include'), ).subscribe(({ items }) => { const expected = expecteds.shift() || 0; expect(items.length).toBe(expected); @@ -202,7 +202,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { await fullSave( new Post({ title: `the post ${i} - ${Boolean(i % 2) ? 'include' : 'omit'}`, - }) + }), ); } @@ -220,7 +220,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { const expecteds = [0, 4, 3]; const sub = DataStore.observeQuery(Post, p => - p.title.contains('include') + p.title.contains('include'), ).subscribe(async ({ items }) => { const expected = expecteds.shift() || 0; expect(items.length).toBe(expected); @@ -239,7 +239,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { // This sanity-checks helps confirms we're testing what we think // we're testing: expect(((DataStore as any).sync as any).getModelSyncedStatus({})).toBe( - true + true, ); await pause(2001); @@ -250,7 +250,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { await fullSave( Post.copyOf(itemToEdit, draft => { draft.title = 'second edited post - omit'; - }) + }), ); jest.advanceTimersByTime(2000); @@ -273,7 +273,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { await fullSave( new Post({ title: `the post ${i} - ${Boolean(i % 2) ? 'include' : 'omit'}`, - }) + }), ); } @@ -294,7 +294,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { await fullSave( Post.copyOf(itemToEdit, draft => { draft.title = 'first edited post - omit'; - }) + }), ); jest.advanceTimersByTime(2000); @@ -308,7 +308,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { await DataStore.save( new Post({ title: `the post ${i}`, - }) + }), ); } @@ -324,14 +324,14 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { if (expecteds.length === 0) { sub.unsubscribe(); } - } + }, ); for (let i = 5; i < 15; i++) { await fullSave( new Post({ title: `the post ${i}`, - }) + }), ); } @@ -346,7 +346,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { await DataStore.save( new Post({ title: `the post ${i}`, - }) + }), ); } @@ -366,7 +366,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { await DataStore.delete(itemToDelete); jest.advanceTimersByTime(2000); } - } + }, ); await pause(0); @@ -381,12 +381,12 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { await DataStore.save( new Post({ title: `the post ${i}`, - }) + }), ); } const sub = DataStore.observeQuery(Post, p => - p.title.beginsWith('the post') + p.title.beginsWith('the post'), ).subscribe(({ items, isSynced }) => { const expected = expecteds.shift() || 0; expect(items.length).toBe(expected); @@ -421,9 +421,9 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { post: await DataStore.save( new Post({ title: `new post ${i}`, - }) + }), ), - }) + }), ); } @@ -441,7 +441,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { if (expecteds.length === 0) { sub.unsubscribe(); } - } + }, ); for (let i = 5; i < 15; i++) { @@ -451,9 +451,9 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { post: await DataStore.save( new Post({ title: `new post ${i}`, - }) + }), ), - }) + }), ); } @@ -472,9 +472,9 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { new Profile({ firstName: `firstName ${i}`, lastName: `lastName ${i}`, - }) + }), ), - }) + }), ); } @@ -493,7 +493,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { if (expecteds.length === 0) { sub.unsubscribe(); } - } + }, ); for (let i = 5; i < 15; i++) { @@ -504,9 +504,9 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { new Profile({ firstName: `firstName ${i}`, lastName: `lastName ${i}`, - }) + }), ), - }) + }), ); } @@ -527,9 +527,9 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { post: await DataStore.save( new Post({ title: `old post ${i}`, - }) + }), ), - }) + }), ); } @@ -547,7 +547,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { if (expecteds.length === 0) { sub.unsubscribe(); } - } + }, ); let postIndex = 0; @@ -556,14 +556,14 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { const newPost = await DataStore.save( new Post({ title: `new post ${postIndex++}`, - }) + }), ); await fullSave( Comment.copyOf(comment, draft => { draft.content = `updated: ${comment.content}`; draft.post = newPost; - }) + }), ); } @@ -597,9 +597,9 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { new Profile({ firstName: `first name ${i}`, lastName: `last name ${i}`, - }) + }), ), - }) + }), ); } @@ -617,7 +617,7 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { if (expecteds.length === 0) { sub.unsubscribe(); } - } + }, ); let userIndex = 0; @@ -627,14 +627,14 @@ describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => { new Profile({ firstName: `new first name ${userIndex++}`, lastName: `new last name ${userIndex}`, - }) + }), ); await fullSave( User.copyOf(user, draft => { draft.name = `updated: ${user.name}`; draft.profile = newProfile; - }) + }), ); } diff --git a/packages/datastore/__tests__/DataStore/sanityCheck.test.ts b/packages/datastore/__tests__/DataStore/sanityCheck.test.ts index 1148d96a5f0..53fb6cddceb 100644 --- a/packages/datastore/__tests__/DataStore/sanityCheck.test.ts +++ b/packages/datastore/__tests__/DataStore/sanityCheck.test.ts @@ -60,10 +60,10 @@ describe('DataStore sanity testing checks', () => { post: new Post({ title: 'newly created post', }), - }) - ) + }), + ), ).rejects.toThrow( - `Data integrity error. You tried to save a Comment` // instructions specific to the instance follow + `Data integrity error. You tried to save a Comment`, // instructions specific to the instance follow ); }); @@ -128,7 +128,7 @@ describe('DataStore sanity testing checks', () => { setTimeout(() => { lastCycle = cycle; unsleep(); - }, 20 * cycle) + }, 20 * cycle), ); }, numberOfCycles); @@ -204,7 +204,7 @@ describe('DataStore sanity testing checks', () => { // At minimum: looking for top-level error, operation that failed, state while in failure. expect(DataStore.start()).rejects.toThrow( - /DataStoreStateError:.+`DataStore\.start\(\)`.+Clearing/ + /DataStoreStateError:.+`DataStore\.start\(\)`.+Clearing/, ); await clearing; @@ -218,7 +218,7 @@ describe('DataStore sanity testing checks', () => { // At minimum: looking for top-level error, operation that failed, state while in failure. expect(DataStore.start()).rejects.toThrow( - /DataStoreStateError:.+`DataStore\.start\(\)`.+Stopping/ + /DataStoreStateError:.+`DataStore\.start\(\)`.+Stopping/, ); await stopping; @@ -306,7 +306,7 @@ describe('DataStore sanity testing checks', () => { test('awaited save', async () => { await expectIsolation( async ({ DataStore, Post }) => - await DataStore.save(new Post({ title: 'some title' })) + await DataStore.save(new Post({ title: 'some title' })), ); }); @@ -324,7 +324,7 @@ describe('DataStore sanity testing checks', () => { (DataStore as any).runningProcesses.add( async () => new Promise(_unblock => (unblock = _unblock)), - 'artificial query blocker' + 'artificial query blocker', ); // begin clearing, which should lock DataStore @@ -351,7 +351,7 @@ describe('DataStore sanity testing checks', () => { let unblock; (DataStore as any).runningProcesses.add( async () => new Promise(_unblock => (unblock = _unblock)), - 'artificial save blocker' + 'artificial save blocker', ); // begin clearing, which should lock DataStore @@ -363,7 +363,7 @@ describe('DataStore sanity testing checks', () => { // and now attempt an ill-fated operation await expect( - DataStore.save(new Post({ title: 'title that should fail' })) + DataStore.save(new Post({ title: 'title that should fail' })), ) // looking top-level error name, operation that failed, state DS was in .rejects.toThrow(/DataStoreStateError.+DataStore\.save\(\).+Clearing/i) @@ -380,7 +380,7 @@ describe('DataStore sanity testing checks', () => { let unblock; (DataStore as any).runningProcesses.add( async () => new Promise(_unblock => (unblock = _unblock)), - 'artificial delete blocker' + 'artificial delete blocker', ); // begin clearing, which should lock DataStore @@ -407,7 +407,7 @@ describe('DataStore sanity testing checks', () => { let unblock; (DataStore as any).runningProcesses.add( async () => new Promise(_unblock => (unblock = _unblock)), - 'artificial observe blocker' + 'artificial observe blocker', ); // begin clearing, which should lock DataStore @@ -440,7 +440,7 @@ describe('DataStore sanity testing checks', () => { let unblock; (DataStore as any).runningProcesses.add( async () => new Promise(_unblock => (unblock = _unblock)), - 'artificial observeQuery blocker' + 'artificial observeQuery blocker', ); // begin clearing, which should lock DataStore @@ -513,14 +513,14 @@ describe('DataStore sanity testing checks', () => { ({ element, opType, model }) => { expect(opType).toEqual('INSERT'); expect(element.title).toEqual( - `a title from polite cycle ${cycle}` + `a title from polite cycle ${cycle}`, ); sub.unsubscribe(); resolve(); - } + }, ); DataStore.save( - new Post({ title: `a title from polite cycle ${cycle}` }) + new Post({ title: `a title from polite cycle ${cycle}` }), ); }); }); @@ -533,16 +533,16 @@ describe('DataStore sanity testing checks', () => { ({ element, opType, model }) => { expect(opType).toEqual('INSERT'); expect(element.title).toEqual( - `a title from impolite cycle ${cycle}` + `a title from impolite cycle ${cycle}`, ); // omitted: // sub.unsubscribe(); // (that's what makes it impolite) resolve(); - } + }, ); DataStore.save( - new Post({ title: `a title from impolite cycle ${cycle}` }) + new Post({ title: `a title from impolite cycle ${cycle}` }), ); }); }); @@ -552,13 +552,13 @@ describe('DataStore sanity testing checks', () => { await expectIsolation(async ({ DataStore, Post, cycle }) => { await pretendModelsAreSynced(DataStore); await DataStore.save( - new Post({ title: `a title from polite cycle ${cycle} post 1` }) + new Post({ title: `a title from polite cycle ${cycle} post 1` }), ); const sanityCheck = await DataStore.query(Post); expect(sanityCheck.length).toEqual(1); expect(sanityCheck[0].title).toEqual( - `a title from polite cycle ${cycle} post 1` + `a title from polite cycle ${cycle} post 1`, ); return new Promise(async resolve => { @@ -568,10 +568,12 @@ describe('DataStore sanity testing checks', () => { first = false; expect(items.length).toEqual(1); expect(items[0].title).toEqual( - `a title from polite cycle ${cycle} post 1` + `a title from polite cycle ${cycle} post 1`, ); DataStore.save( - new Post({ title: `a title from polite cycle ${cycle} post 2` }) + new Post({ + title: `a title from polite cycle ${cycle} post 2`, + }), ); } else { expect(items.length).toEqual(2); @@ -602,12 +604,12 @@ describe('DataStore sanity testing checks', () => { DataStore.save( new Post({ title: `a title from polite unsynced cycle ${cycle} post 1`, - }) + }), ); } else { expect(items.length).toEqual(1); expect(items[0].title).toEqual( - `a title from polite unsynced cycle ${cycle} post 1` + `a title from polite unsynced cycle ${cycle} post 1`, ); sub.unsubscribe(); doneTesting(); @@ -625,12 +627,12 @@ describe('DataStore sanity testing checks', () => { await pretendModelsAreSynced(DataStore); await DataStore.save( - new Post({ title: `a title from impolite cycle ${cycle} post 1` }) + new Post({ title: `a title from impolite cycle ${cycle} post 1` }), ); const sanityCheck = await DataStore.query(Post); expect(sanityCheck.length).toEqual(1); expect(sanityCheck[0].title).toEqual( - `a title from impolite cycle ${cycle} post 1` + `a title from impolite cycle ${cycle} post 1`, ); await new Promise(doneTesting => { @@ -640,12 +642,12 @@ describe('DataStore sanity testing checks', () => { first = false; expect(items.length).toEqual(1); expect(items[0].title).toEqual( - `a title from impolite cycle ${cycle} post 1` + `a title from impolite cycle ${cycle} post 1`, ); DataStore.save( new Post({ title: `a title from impolite cycle ${cycle} post 2`, - }) + }), ); } else { expect(items.length).toEqual(2); @@ -674,7 +676,7 @@ describe('DataStore sanity testing checks', () => { // save an item to kickstart outbox processing. await DataStore.save( - new Post({ title: `post from "sync is cleaned" up cycle ${cycle}` }) + new Post({ title: `post from "sync is cleaned" up cycle ${cycle}` }), ); }); }); @@ -689,7 +691,7 @@ describe('DataStore sanity testing checks', () => { DataStore.save( new Post({ title: `post from "rude synchronized observe-save" up cycle ${cycle}`, - }) + }), ); }); }); diff --git a/packages/datastore/__tests__/IndexedDBAdapter.test.ts b/packages/datastore/__tests__/IndexedDBAdapter.test.ts index af24ad080ae..161bb04428d 100644 --- a/packages/datastore/__tests__/IndexedDBAdapter.test.ts +++ b/packages/datastore/__tests__/IndexedDBAdapter.test.ts @@ -92,19 +92,19 @@ describe('IndexedDBAdapter tests', () => { new Model({ field1: 'field1 value 0', dateCreated: baseDate.toISOString(), - }) + }), )); await DataStore.save( new Model({ field1: 'field1 value 1', dateCreated: new Date(baseDate.getTime() + 1).toISOString(), - }) + }), ); await DataStore.save( new Model({ field1: 'field1 value 2', dateCreated: new Date(baseDate.getTime() + 2).toISOString(), - }) + }), ); jest.clearAllMocks(); @@ -127,7 +127,7 @@ describe('IndexedDBAdapter tests', () => { it('Should call getAll & inMemoryPagination for query with a predicate', async () => { const results = await DataStore.query(Model, c => - c.field1.eq('field1 value 1') + c.field1.eq('field1 value 1'), ); expect(results.length).toEqual(1); @@ -196,11 +196,11 @@ describe('IndexedDBAdapter tests', () => { let user1Id: string; ({ id: profile1Id } = await DataStore.save( - new Profile({ firstName: 'Rick', lastName: 'Bob' }) + new Profile({ firstName: 'Rick', lastName: 'Bob' }), )); ({ id: user1Id } = await DataStore.save( - new User({ name: 'test', profileID: profile1Id }) + new User({ name: 'test', profileID: profile1Id }), )); let user = await DataStore.query(User, user1Id); @@ -230,7 +230,7 @@ describe('IndexedDBAdapter tests', () => { ({ id: post1Id } = newPost); ({ id: comment1Id } = await DataStore.save( - new Comment({ content: 'Test Content', post: newPost }) + new Comment({ content: 'Test Content', post: newPost }), )); let post = await DataStore.query(Post, post1Id); @@ -257,14 +257,14 @@ describe('IndexedDBAdapter tests', () => { const newPost = await DataStore.save( new PostUni({ title: 'post', - }) + }), ); const newComment = await DataStore.save( new CommentUni({ postID: newPost.id, content: 'comment', - }) + }), ); let post = await DataStore.query(PostUni, newPost.id); @@ -297,7 +297,7 @@ describe('IndexedDBAdapter tests', () => { })); profile = await DataStore.save( - new Profile({ firstName: 'Rick', lastName: 'Bob' }) + new Profile({ firstName: 'Rick', lastName: 'Bob' }), ); }); @@ -307,7 +307,7 @@ describe('IndexedDBAdapter tests', () => { it('should allow linking model via model field', async () => { const savedUser = await DataStore.save( - new User({ name: 'test', profile }) + new User({ name: 'test', profile }), ); const user1Id = savedUser.id; @@ -318,7 +318,7 @@ describe('IndexedDBAdapter tests', () => { it('should allow linking model via FK', async () => { const savedUser = await DataStore.save( - new User({ name: 'test', profileID: profile.id }) + new User({ name: 'test', profileID: profile.id }), ); const user1Id = savedUser.id; @@ -383,7 +383,7 @@ describe('IndexedDB benchmarks', () => { const sideloadIDBData = async ( size: number, table: string, - build: (i: number) => T + build: (i: number) => T, ) => { await DataStore.start(); const db = (adapter as any).db; @@ -500,7 +500,7 @@ describe('IndexedDB benchmarks', () => { const byContentTime = await benchmark(async () => { // `content` alone will not be able to use the index. const fetched = await DataStore.query(CompositePKParent, i => - i.content.eq(item.content) + i.content.eq(item.content), ); expect(fetched).toBeDefined(); }); @@ -508,7 +508,7 @@ describe('IndexedDB benchmarks', () => { // check timing of fetch by non-indexed field (name) const byPKEqTime = await benchmark(async () => { const fetched = await DataStore.query(CompositePKParent, ({ and }) => - and(i => [i.customId.eq(item.customId), i.content.eq(item.content)]) + and(i => [i.customId.eq(item.customId), i.content.eq(item.content)]), ); expect(fetched.length).toBe(1); }); @@ -544,8 +544,8 @@ describe('IndexedDB benchmarks', () => { const time = await benchmark(async () => { const fetched = await DataStore.query(DefaultPKParent, p => p.children.parent.children.parent.children.parent.children.parent.children.parent.children.id.eq( - child.id - ) + child.id, + ), ); expect(fetched.length).toBe(1); }, 1); @@ -579,8 +579,8 @@ describe('IndexedDB benchmarks', () => { const time = await benchmark(async () => { const fetched = await DataStore.query(CompositePKParent, p => p.children.parent.children.parent.children.parent.children.parent.children.parent.children.and( - c => [c.childId.eq(child.childId), c.content.eq(child.content)] - ) + c => [c.childId.eq(child.childId), c.content.eq(child.content)], + ), ); expect(fetched.length).toBe(1); }, 1); @@ -613,7 +613,7 @@ describe('IndexedDB benchmarks', () => { const time = await benchmark(async () => { const fetched = await DataStore.query(CompositePKParent, p => - p.children.content.beginsWith('content') + p.children.content.beginsWith('content'), ); expect(fetched.length).toBe(100); }, 1); @@ -645,7 +645,7 @@ describe('IndexedDB benchmarks', () => { const time = await benchmark(async () => { const fetched = await DataStore.query(CompositePKParent, p => - p.children.or(child => children.map(c => child.childId.eq(c.childId))) + p.children.or(child => children.map(c => child.childId.eq(c.childId))), ); expect(fetched.length).toBe(100); }, 1); @@ -679,8 +679,8 @@ describe('IndexedDB benchmarks', () => { const time = await benchmark(async () => { const fetched = await DataStore.query(CompositePKParent, p => p.children.or(child => - children.slice(200, 200 + size).map(c => child.childId.eq(c.childId)) - ) + children.slice(200, 200 + size).map(c => child.childId.eq(c.childId)), + ), ); expect(fetched.length).toBe(size); }, 1); diff --git a/packages/datastore/__tests__/Merger.test.ts b/packages/datastore/__tests__/Merger.test.ts index 3865f0c571d..106dc52fc98 100644 --- a/packages/datastore/__tests__/Merger.test.ts +++ b/packages/datastore/__tests__/Merger.test.ts @@ -208,7 +208,7 @@ describe('Merger', () => { storage, PostCustomPK, items, - modelDefinition + modelDefinition, ); }); @@ -255,7 +255,7 @@ describe('Merger', () => { storage, PostCustomPK, items, - modelDefinition + modelDefinition, ); }); @@ -303,7 +303,7 @@ describe('Merger', () => { storage, PostCustomPK, items, - modelDefinition + modelDefinition, ); }); diff --git a/packages/datastore/__tests__/Predicate.test.ts b/packages/datastore/__tests__/Predicate.test.ts index 99ad55a4ed2..aec937e3bf4 100644 --- a/packages/datastore/__tests__/Predicate.test.ts +++ b/packages/datastore/__tests__/Predicate.test.ts @@ -72,7 +72,7 @@ function getStorageFake(collections) { async query( modelConstructor: PersistentModelConstructor, predicate?: FlatModelPredicate, - pagination?: PaginationInput + pagination?: PaginationInput, ) { const baseSet: T[] = this.collections[modelConstructor.name].map(item => { const itemCopy = { ...item }; @@ -85,7 +85,7 @@ function getStorageFake(collections) { } else { const predicates = ModelPredicateCreator.getPredicates(predicate)!; return baseSet.filter(item => - flatPredicateMatches(item, 'and', [predicates]) + flatPredicateMatches(item, 'and', [predicates]), ); } }, @@ -110,7 +110,7 @@ describe('Predicates', () => { expect(() => { recursivePredicateFor(AuthorMeta).name[operator](); }).toThrow( - `Incorrect usage of \`${operator}()\`: Exactly 1 argument is required.` + `Incorrect usage of \`${operator}()\`: Exactly 1 argument is required.`, ); }); @@ -118,7 +118,7 @@ describe('Predicates', () => { expect(() => { recursivePredicateFor(AuthorMeta).name[operator]('a', 'b'); }).toThrow( - `Incorrect usage of \`${operator}()\`: Exactly 1 argument is required.` + `Incorrect usage of \`${operator}()\`: Exactly 1 argument is required.`, ); }); }); @@ -130,7 +130,7 @@ describe('Predicates', () => { // @ts-ignore recursivePredicateFor(AuthorMeta).name.between(); }).toThrow( - 'Incorrect usage of `between()`: Exactly 2 arguments are required.' + 'Incorrect usage of `between()`: Exactly 2 arguments are required.', ); }); @@ -139,7 +139,7 @@ describe('Predicates', () => { // @ts-ignore recursivePredicateFor(AuthorMeta).name.between('z'); }).toThrow( - 'Incorrect usage of `between()`: Exactly 2 arguments are required.' + 'Incorrect usage of `between()`: Exactly 2 arguments are required.', ); }); @@ -147,7 +147,7 @@ describe('Predicates', () => { expect(() => { recursivePredicateFor(AuthorMeta).name.between('z', 'a'); }).toThrow( - 'Incorrect usage of `between()`: The first argument must be less than or equal to the second argument.' + 'Incorrect usage of `between()`: The first argument must be less than or equal to the second argument.', ); }); @@ -156,7 +156,7 @@ describe('Predicates', () => { // @ts-ignore recursivePredicateFor(AuthorMeta).name.between('a', 'b', 'c'); }).toThrow( - 'Incorrect usage of `between()`: Exactly 2 arguments are required.' + 'Incorrect usage of `between()`: Exactly 2 arguments are required.', ); }); }); @@ -199,7 +199,7 @@ describe('Predicates', () => { name: 'filters', execute: async (query: any) => asyncFilter(getFlatAuthorsArrayFixture(), i => - internals(query).matches(i) + internals(query).matches(i), ), }, { @@ -208,7 +208,7 @@ describe('Predicates', () => { return (await internals(query).fetch( getStorageFake({ [Author.name]: getFlatAuthorsArrayFixture(), - }) as any + }) as any, )) as T[]; }, }, @@ -235,7 +235,7 @@ describe('Predicates', () => { test('match on eq - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.eq('Adam West') + a.name.eq('Adam West'), ); const matches = await mechanism.execute>>(query); @@ -266,7 +266,7 @@ describe('Predicates', () => { test('match on ne - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.ne('Adam West') + a.name.ne('Adam West'), ); const matches = await mechanism.execute>>(query); @@ -297,7 +297,7 @@ describe('Predicates', () => { test('match on gt - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.gt('Clarice Starling') + a.name.gt('Clarice Starling'), ); const matches = await mechanism.execute>>(query); @@ -328,7 +328,7 @@ describe('Predicates', () => { test('match on ge - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.ge('Clarice Starling') + a.name.ge('Clarice Starling'), ); const matches = await mechanism.execute>>(query); @@ -359,7 +359,7 @@ describe('Predicates', () => { test('match on lt - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.lt('Clarice Starling') + a.name.lt('Clarice Starling'), ); const matches = await mechanism.execute>(query); @@ -390,7 +390,7 @@ describe('Predicates', () => { test('match on le - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.le('Clarice Starling') + a.name.le('Clarice Starling'), ); const matches = await mechanism.execute>(query); @@ -421,7 +421,7 @@ describe('Predicates', () => { test('match beginsWith - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.beginsWith('Debbie') + a.name.beginsWith('Debbie'), ); const matches = await mechanism.execute>(query); @@ -440,7 +440,7 @@ describe('Predicates', () => { // `{` is immediately after `z` const query = recursivePredicateFor(AuthorMeta).name.between( '0', - '{' + '{', ); const matches = await mechanism.execute>(query); @@ -458,7 +458,7 @@ describe('Predicates', () => { // `0` is immediately before `A` // `{` is immediately after `z` const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.between('0', '{') + a.name.between('0', '{'), ); const matches = await mechanism.execute>(query); @@ -469,7 +469,7 @@ describe('Predicates', () => { test('match between with equality at both ends', async () => { const query = recursivePredicateFor(AuthorMeta).name.between( 'Bob Jones', - 'Debbie Donut' + 'Debbie Donut', ); const matches = await mechanism.execute>(query); @@ -485,7 +485,7 @@ describe('Predicates', () => { test('match between with equality at both ends - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.between('Bob Jones', 'Debbie Donut') + a.name.between('Bob Jones', 'Debbie Donut'), ); const matches = await mechanism.execute>(query); @@ -502,7 +502,7 @@ describe('Predicates', () => { test('match between an inner range', async () => { const query = recursivePredicateFor(AuthorMeta).name.between( 'Az', - 'E' + 'E', ); const matches = await mechanism.execute>(query); @@ -518,7 +518,7 @@ describe('Predicates', () => { test('match between an inner range - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.between('Az', 'E') + a.name.between('Az', 'E'), ); const matches = await mechanism.execute>(query); @@ -535,7 +535,7 @@ describe('Predicates', () => { test('match nothing between a mismatching range', async () => { const query = recursivePredicateFor(AuthorMeta).name.between( '{', - '}' + '}', ); const matches = await mechanism.execute>(query); @@ -545,7 +545,7 @@ describe('Predicates', () => { test('match nothing between a mismatching range - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.between('{', '}') + a.name.between('{', '}'), ); const matches = await mechanism.execute>(query); @@ -570,7 +570,7 @@ describe('Predicates', () => { test('match contains - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.contains('Jones') + a.name.contains('Jones'), ); const matches = await mechanism.execute>(query); @@ -601,7 +601,7 @@ describe('Predicates', () => { test('match notContains - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.notContains('Jones') + a.name.notContains('Jones'), ); const matches = await mechanism.execute>(query); @@ -633,7 +633,7 @@ describe('Predicates', () => { test('match on eq - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.isActive.eq(true) + a.isActive.eq(true), ); const matches = await mechanism.execute>>(query); @@ -663,7 +663,7 @@ describe('Predicates', () => { test('match on ne - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.isActive.ne(true) + a.isActive.ne(true), ); const matches = await mechanism.execute>>(query); @@ -687,7 +687,7 @@ describe('Predicates', () => { test('match on gt true - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.isActive.gt(true) + a.isActive.gt(true), ); const matches = await mechanism.execute>>(query); @@ -711,7 +711,7 @@ describe('Predicates', () => { test('match on gt false - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.isActive.gt(false) + a.isActive.gt(false), ); const matches = await mechanism.execute>>(query); @@ -727,7 +727,7 @@ describe('Predicates', () => { test('match on ge true - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.isActive.ge(true) + a.isActive.ge(true), ); const matches = await mechanism.execute>>(query); @@ -751,7 +751,7 @@ describe('Predicates', () => { test('match on ge false - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.isActive.ge(false) + a.isActive.ge(false), ); const matches = await mechanism.execute>>(query); @@ -775,7 +775,7 @@ describe('Predicates', () => { test('match on lt true - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.isActive.lt(true) + a.isActive.lt(true), ); const matches = await mechanism.execute>>(query); @@ -799,7 +799,7 @@ describe('Predicates', () => { test('match on lt false - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.isActive.lt(false) + a.isActive.lt(false), ); const matches = await mechanism.execute>>(query); @@ -817,7 +817,7 @@ describe('Predicates', () => { test('match on le true - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.isActive.le(true) + a.isActive.le(true), ); const matches = await mechanism.execute>>(query); @@ -841,7 +841,7 @@ describe('Predicates', () => { test('match on le false - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.isActive.le(false) + a.isActive.le(false), ); const matches = await mechanism.execute>>(query); @@ -873,7 +873,7 @@ describe('Predicates', () => { test('match on eq - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.karma.eq(3) + a.karma.eq(3), ); const matches = await mechanism.execute>>(query); @@ -903,7 +903,7 @@ describe('Predicates', () => { test('match on ne - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.karma.ne(3) + a.karma.ne(3), ); const matches = await mechanism.execute>>(query); @@ -933,7 +933,7 @@ describe('Predicates', () => { test('match on gt - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.karma.gt(3) + a.karma.gt(3), ); const matches = await mechanism.execute>>(query); @@ -963,7 +963,7 @@ describe('Predicates', () => { test('match on ge - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.karma.ge(3) + a.karma.ge(3), ); const matches = await mechanism.execute>>(query); @@ -993,7 +993,7 @@ describe('Predicates', () => { test('match on lt - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.karma.lt(3) + a.karma.lt(3), ); const matches = await mechanism.execute>>(query); @@ -1023,7 +1023,7 @@ describe('Predicates', () => { test('match on le - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.karma.le(3) + a.karma.le(3), ); const matches = await mechanism.execute>>(query); @@ -1053,7 +1053,7 @@ describe('Predicates', () => { test('match on between - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.karma.between(1, 3) + a.karma.between(1, 3), ); const matches = await mechanism.execute>>(query); @@ -1085,7 +1085,7 @@ describe('Predicates', () => { test('match on eq - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.rating.eq(0.75) + a.rating.eq(0.75), ); const matches = await mechanism.execute>>(query); @@ -1115,7 +1115,7 @@ describe('Predicates', () => { test('match on ne - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.rating.ne(0.75) + a.rating.ne(0.75), ); const matches = await mechanism.execute>>(query); @@ -1145,7 +1145,7 @@ describe('Predicates', () => { test('match on gt - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.rating.gt(0.75) + a.rating.gt(0.75), ); const matches = await mechanism.execute>>(query); @@ -1175,7 +1175,7 @@ describe('Predicates', () => { test('match on ge - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.rating.ge(0.75) + a.rating.ge(0.75), ); const matches = await mechanism.execute>>(query); @@ -1205,7 +1205,7 @@ describe('Predicates', () => { test('match on lt - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.rating.lt(0.75) + a.rating.lt(0.75), ); const matches = await mechanism.execute>>(query); @@ -1235,7 +1235,7 @@ describe('Predicates', () => { test('match on le - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.rating.le(0.75) + a.rating.le(0.75), ); const matches = await mechanism.execute>>(query); @@ -1252,7 +1252,7 @@ describe('Predicates', () => { test('match on between', async () => { const query = recursivePredicateFor(AuthorMeta).rating.between( 0.25, - 0.75 + 0.75, ); const matches = await mechanism.execute>>(query); @@ -1268,7 +1268,7 @@ describe('Predicates', () => { test('match on between - NEGATED', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.rating.between(0.25, 0.75) + a.rating.between(0.25, 0.75), ); const matches = await mechanism.execute>>(query); @@ -1290,19 +1290,21 @@ describe('Predicates', () => { // @ts-ignore recursivePredicateFor(AuthorMeta).not(a => [ a.name.contains('Bob'), - ]) + ]), ).toThrow( - "Invalid predicate. Terminate your predicate with a valid condition (e.g., `p => p.field.eq('value')`) or pass `Predicates.ALL`." + "Invalid predicate. Terminate your predicate with a valid condition (e.g., `p => p.field.eq('value')`) or pass `Predicates.ALL`.", ); }); test('and group builders must return an array of child conditions - recursive/relational predicates', async () => { expect(() => - // TODO: @ts-expect-error doesn't work until TS 3.9 ... until then: - // @ts-ignore - recursivePredicateFor(AuthorMeta).and(a => a.name.contains('Bob')) + recursivePredicateFor(AuthorMeta).and(a => + // TODO: @ts-expect-error doesn't work until TS 3.9 ... until then: + // @ts-ignore + a.name.contains('Bob'), + ), ).toThrow( - 'Invalid predicate. `and` groups must return an array of child conditions.' + 'Invalid predicate. `and` groups must return an array of child conditions.', ); }); @@ -1310,9 +1312,9 @@ describe('Predicates', () => { expect(() => // TODO: @ts-expect-error doesn't work until TS 3.9 ... until then: // @ts-ignore - recursivePredicateFor(AuthorMeta).or(a => a.name.contains('Bob')) + recursivePredicateFor(AuthorMeta).or(a => a.name.contains('Bob')), ).toThrow( - 'Invalid predicate. `or` groups must return an array of child conditions.' + 'Invalid predicate. `or` groups must return an array of child conditions.', ); }); @@ -1320,9 +1322,9 @@ describe('Predicates', () => { expect(() => // TODO: @ts-expect-error doesn't work until TS 3.9 ... until then: // @ts-ignore - predicateFor(AuthorMeta).not(a => [a.name.contains('Bob')]) + predicateFor(AuthorMeta).not(a => [a.name.contains('Bob')]), ).toThrow( - "Invalid predicate. Terminate your predicate with a valid condition (e.g., `p => p.field.eq('value')`) or pass `Predicates.ALL`." + "Invalid predicate. Terminate your predicate with a valid condition (e.g., `p => p.field.eq('value')`) or pass `Predicates.ALL`.", ); }); @@ -1330,9 +1332,9 @@ describe('Predicates', () => { expect(() => // TODO: @ts-expect-error doesn't work until TS 3.9 ... until then: // @ts-ignore - predicateFor(AuthorMeta).and(a => a.name.contains('Bob')) + predicateFor(AuthorMeta).and(a => a.name.contains('Bob')), ).toThrow( - 'Invalid predicate. `and` groups must return an array of child conditions.' + 'Invalid predicate. `and` groups must return an array of child conditions.', ); }); @@ -1340,9 +1342,9 @@ describe('Predicates', () => { expect(() => // TODO: @ts-expect-error doesn't work until TS 3.9 ... until then: // @ts-ignore - predicateFor(AuthorMeta).or(a => a.name.contains('Bob')) + predicateFor(AuthorMeta).or(a => a.name.contains('Bob')), ).toThrow( - 'Invalid predicate. `or` groups must return an array of child conditions.' + 'Invalid predicate. `or` groups must return an array of child conditions.', ); }); }); @@ -1365,7 +1367,7 @@ describe('Predicates', () => { negated.and(a => [ a.name.contains('Bob'), a.name.contains('Jones'), - ]) + ]), ); const matches = await mechanism.execute>(query); @@ -1390,7 +1392,7 @@ describe('Predicates', () => { negated.and(a => [ a.name.contains('Adam'), a.name.contains('Donut'), - ]) + ]), ); const matches = await mechanism.execute>(query); @@ -1418,7 +1420,7 @@ describe('Predicates', () => { negated.or(a => [ a.name.contains('Bob'), a.name.contains('Donut'), - ]) + ]), ); const matches = await mechanism.execute>(query); @@ -1445,7 +1447,7 @@ describe('Predicates', () => { negated.or(a => [ a.name.contains('Bob'), a.name.contains('Jones'), - ]) + ]), ); const matches = await mechanism.execute>(query); @@ -1524,7 +1526,7 @@ describe('Predicates', () => { a.name.contains('Debbie'), a.name.contains('from the Legend of Zelda'), ]), - ]) + ]), ); const matches = await mechanism.execute>(query); @@ -1535,7 +1537,7 @@ describe('Predicates', () => { test('can perform simple not() logic, matching all but one item', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.eq('Bob Jones') + a.name.eq('Bob Jones'), ); const matches = await mechanism.execute>(query); @@ -1551,7 +1553,7 @@ describe('Predicates', () => { test('can perform simple not() logic, matching no items', async () => { const query = recursivePredicateFor(AuthorMeta).not(a => - a.name.gt('0') + a.name.gt('0'), ); const matches = await mechanism.execute>(query); @@ -1565,7 +1567,7 @@ describe('Predicates', () => { a.name.eq('Bob Jones'), a.name.eq('Debbie Donut'), a.name.between('C', 'D'), - ]) + ]), ); const matches = await mechanism.execute>(query); @@ -1579,7 +1581,7 @@ describe('Predicates', () => { test('can perform 2-nots', async () => { const query = recursivePredicateFor(AuthorMeta).not(a1 => - a1.not(a2 => a2.name.eq('Bob Jones')) + a1.not(a2 => a2.name.eq('Bob Jones')), ); const matches = await mechanism.execute>(query); @@ -1590,7 +1592,7 @@ describe('Predicates', () => { test('can perform 3-nots', async () => { const query = recursivePredicateFor(AuthorMeta).not(a1 => - a1.not(a2 => a2.not(a3 => a3.name.eq('Bob Jones'))) + a1.not(a2 => a2.not(a3 => a3.name.eq('Bob Jones'))), ); const matches = await mechanism.execute>(query); @@ -1606,7 +1608,7 @@ describe('Predicates', () => { test('can perform 4-nots', async () => { const query = recursivePredicateFor(AuthorMeta).not(a1 => - a1.not(a2 => a2.not(a3 => a3.not(a4 => a4.name.eq('Bob Jones')))) + a1.not(a2 => a2.not(a3 => a3.not(a4 => a4.name.eq('Bob Jones')))), ); const matches = await mechanism.execute>(query); @@ -1625,7 +1627,7 @@ describe('Predicates', () => { test('can fetch ALL with Predicates.ALL', async () => { // Predicates.ALL is expected to return our base match-all predicate as-is. const query = (V1Predicates.ALL as any)( - recursivePredicateFor(AuthorMeta) + recursivePredicateFor(AuthorMeta), ); const matches = await mechanism.execute>(query); @@ -1654,7 +1656,7 @@ describe('Predicates', () => { username: name.includes('null') ? null : name, age: name.includes('null') ? null : parseInt(name.split(' ')[1]), }); - } + }, ); }; @@ -1670,7 +1672,7 @@ describe('Predicates', () => { return (await internals(query).fetch( getStorageFake({ [Person.name]: getFixture(), - }) as any + }) as any, )) as T[]; }, }, @@ -1688,7 +1690,7 @@ describe('Predicates', () => { test('can select non-null values by searching for != null', async () => { const query = recursivePredicateFor(PersonMeta).username.ne( - null as any + null as any, ); const matches = await mechanism.execute>(query); @@ -1715,7 +1717,7 @@ describe('Predicates', () => { test('can select null values by searching for == null', async () => { const query = recursivePredicateFor(PersonMeta).username.eq( - null as any + null as any, ); const matches = await mechanism.execute>(query); @@ -1924,7 +1926,7 @@ describe('Predicates', () => { [BlogOwner.name]: owners, [Blog.name]: blogs, [Post.name]: posts, - }) as any + }) as any, )) as T[]; }, }, @@ -1981,7 +1983,7 @@ describe('Predicates', () => { o.name.contains('Debbie'), o.name.contains('Starling'), ]), - ]) + ]), ); const matches = await mechanism.execute>(query); @@ -2020,7 +2022,7 @@ describe('Predicates', () => { ]), owner.name.contains('Donut'), ]), - ]) + ]), ); const matches = await mechanism.execute>(query); @@ -2039,7 +2041,7 @@ describe('Predicates', () => { test('can filter on child collections - NEGATED', async () => { const query = recursivePredicateFor(BlogMeta).not(negated => - negated.posts.title.contains('Bob Jones') + negated.posts.title.contains('Bob Jones'), ); const matches = await mechanism.execute>(query); @@ -2066,14 +2068,14 @@ describe('Predicates', () => { negated.or(b => [ b.posts.title.contains('Bob Jones'), b.posts.title.contains("Zelda's Blog post"), - ]) + ]), ); const matches = await mechanism.execute>(query); expect(matches.length).toBe(3); expect(matches.map(m => m.name)).not.toContain("Bob Jones's Blog"); expect(matches.map(m => m.name)).not.toContain( - "Zelda from the Legend of Zelda's Blog" + "Zelda from the Legend of Zelda's Blog", ); }); @@ -2096,14 +2098,14 @@ describe('Predicates', () => { negated.posts.or(p => [ p.title.contains('Bob Jones'), p.title.contains("Zelda's Blog post"), - ]) + ]), ); const matches = await mechanism.execute>(query); expect(matches.length).toBe(3); expect(matches.map(m => m.name)).not.toContain("Bob Jones's Blog"); expect(matches.map(m => m.name)).not.toContain( - "Zelda from the Legend of Zelda's Blog" + "Zelda from the Legend of Zelda's Blog", ); }); @@ -2122,7 +2124,7 @@ describe('Predicates', () => { negated.and(b => [ b.name.contains('Bob Jones'), b.posts.title.contains('Zelda'), - ]) + ]), ); const matches = await mechanism.execute>(query); @@ -2182,14 +2184,14 @@ describe('Predicates', () => { (await internals(query).fetch( getStorageFake({ [Post.name]: posts, - }) as any + }) as any, )) as T[], }, ].forEach(mechanism => { describe('as ' + mechanism.name, () => { test('can filter 1 level deep', async () => { const query = recursivePredicateFor(PostMeta).reference.title.eq( - 'Bob Jones post 2 layer 1' + 'Bob Jones post 2 layer 1', ); const matches = await mechanism.execute>(query); @@ -2199,7 +2201,7 @@ describe('Predicates', () => { test('can filter 2 levels deep', async () => { const query = recursivePredicateFor( - PostMeta + PostMeta, ).reference.reference.title.eq('Bob Jones post 2 layer 2'); const matches = await mechanism.execute>(query); @@ -2209,7 +2211,7 @@ describe('Predicates', () => { test('can filter 3 levels deep', async () => { const query = recursivePredicateFor( - PostMeta + PostMeta, ).reference.reference.reference.title.eq('Bob Jones post 2 layer 3'); const matches = await mechanism.execute>(query); @@ -2219,9 +2221,9 @@ describe('Predicates', () => { test('safely returns [] on too many levels deep', async () => { const query = recursivePredicateFor( - PostMeta + PostMeta, ).reference.reference.reference.reference.reference.title.eq( - 'Bob Jones post 2 layer 4' + 'Bob Jones post 2 layer 4', ); const matches = await mechanism.execute>(query); @@ -2231,7 +2233,7 @@ describe('Predicates', () => { test('can filter 4 levels deep to match all', async () => { const query = recursivePredicateFor( - PostMeta + PostMeta, ).reference.reference.reference.reference.title.contains('layer 4'); const matches = await mechanism.execute>(query); @@ -2381,30 +2383,30 @@ describe('Predicates', () => { for (const [i, testCase] of ASTTransalationTestCases.entries()) { test(`can create storage predicate from conditions AST ${i} : ${JSON.stringify( - testCase.gql + testCase.gql, )}`, () => { const condition = testCase.gql; const builder = ModelPredicateCreator.createFromAST( AuthorMeta.schema, - condition + condition, ); const predicate = ModelPredicateCreator.getPredicates(builder)!; const regeneratedCondition = predicateToGraphQLCondition( predicate, - AuthorMeta.schema + AuthorMeta.schema, ); const regeneratedFilter = predicateToGraphQLFilter(predicate); for (const expectedMatch of testCase.matches) { expect(flatPredicateMatches(expectedMatch, 'and', [predicate])).toBe( - true + true, ); } for (const expectedMismatch of testCase.mismatches) { expect( - flatPredicateMatches(expectedMismatch, 'and', [predicate]) + flatPredicateMatches(expectedMismatch, 'and', [predicate]), ).toBe(false); } @@ -2466,20 +2468,20 @@ describe('Predicates', () => { for (const [i, testCase] of predicateTestCases.entries()) { test(`nested predicate builder can produce storage predicate ${i}: ${testCase.predicate}`, () => { const builder = internals( - testCase.predicate(predicateFor(AuthorMeta)) + testCase.predicate(predicateFor(AuthorMeta)), ).toStoragePredicate(); const predicate = ModelPredicateCreator.getPredicates(builder)!; for (const expectedMatch of testCase.matches) { expect(flatPredicateMatches(expectedMatch, 'and', [predicate])).toBe( - true + true, ); } for (const expectedMismatch of testCase.mismatches) { expect( - flatPredicateMatches(expectedMismatch, 'and', [predicate]) + flatPredicateMatches(expectedMismatch, 'and', [predicate]), ).toBe(false); } }); diff --git a/packages/datastore/__tests__/authStrategies.test.ts b/packages/datastore/__tests__/authStrategies.test.ts index 2b0bc3bc8b7..d52861c48ff 100644 --- a/packages/datastore/__tests__/authStrategies.test.ts +++ b/packages/datastore/__tests__/authStrategies.test.ts @@ -427,7 +427,7 @@ describe('Auth Strategies', () => { schema, modelName: 'Post', operation: ModelOperation.READ, - }) + }), ).toEqual([]); }); }); @@ -466,7 +466,7 @@ async function testMultiAuthStrategy({ } function getAuthSchema( - authRules: ModelAttributeAuthProperty[] = [] + authRules: ModelAttributeAuthProperty[] = [], ): InternalSchema { const baseSchema: InternalSchema = { namespaces: { diff --git a/packages/datastore/__tests__/commonAdapterTests.ts b/packages/datastore/__tests__/commonAdapterTests.ts index 76621d2a451..18e9cc49b71 100644 --- a/packages/datastore/__tests__/commonAdapterTests.ts +++ b/packages/datastore/__tests__/commonAdapterTests.ts @@ -90,7 +90,7 @@ export function addCommonQueryTests({ field1: `field1 value ${i}`, dateCreated: new Date(baseDate.getTime() + i).toISOString(), emails: [`field${i}@example.com`], - }) + }), ); } } @@ -135,7 +135,7 @@ export function addCommonQueryTests({ it('should match fields of any non-empty value for `("ne", undefined)`', async () => { const results = await DataStore.query(Model, m => - m.field1.ne(undefined!) + m.field1.ne(undefined!), ); expect(results.length).toEqual(3); }); @@ -147,7 +147,7 @@ export function addCommonQueryTests({ it('should NOT match fields of any non-empty value for `("eq", undefined)`', async () => { const results = await DataStore.query(Model, m => - m.field1.eq(undefined!) + m.field1.eq(undefined!), ); expect(results.length).toEqual(0); }); @@ -179,70 +179,70 @@ export function addCommonQueryTests({ it('should NOT match fields of any non-empty value for `("gt", undefined)`', async () => { const results = await DataStore.query(Model, m => - m.field1.gt(undefined!) + m.field1.gt(undefined!), ); expect(results.length).toEqual(0); }); it('should NOT match fields of any non-empty value for `("ge", undefined)`', async () => { const results = await DataStore.query(Model, m => - m.field1.ge(undefined!) + m.field1.ge(undefined!), ); expect(results.length).toEqual(0); }); it('should NOT match fields of any non-empty value for `("lt", undefined)`', async () => { const results = await DataStore.query(Model, m => - m.field1.lt(undefined!) + m.field1.lt(undefined!), ); expect(results.length).toEqual(0); }); it('should NOT match fields of any non-empty value for `("le", undefined)`', async () => { const results = await DataStore.query(Model, m => - m.field1.le(undefined!) + m.field1.le(undefined!), ); expect(results.length).toEqual(0); }); it('should match gt', async () => { const results = await DataStore.query(Model, m => - m.field1.gt('field1 value 0') + m.field1.gt('field1 value 0'), ); expect(results.length).toEqual(2); }); it('should match ge', async () => { const results = await DataStore.query(Model, m => - m.field1.ge('field1 value 1') + m.field1.ge('field1 value 1'), ); expect(results.length).toEqual(2); }); it('should match lt', async () => { const results = await DataStore.query(Model, m => - m.field1.lt('field1 value 2') + m.field1.lt('field1 value 2'), ); expect(results.length).toEqual(2); }); it('should match le', async () => { const results = await DataStore.query(Model, m => - m.field1.le('field1 value 1') + m.field1.le('field1 value 1'), ); expect(results.length).toEqual(2); }); it('should match eq', async () => { const results = await DataStore.query(Model, m => - m.field1.eq('field1 value 1') + m.field1.eq('field1 value 1'), ); expect(results.length).toEqual(1); }); it('should match ne', async () => { const results = await DataStore.query(Model, m => - m.field1.ne('field1 value 1') + m.field1.ne('field1 value 1'), ); expect(results.length).toEqual(2); }); @@ -251,17 +251,17 @@ export function addCommonQueryTests({ const saved = await DataStore.save( new ModelWithIndexes({ stringField: 'expected value', - }) + }), ); await DataStore.save( new ModelWithIndexes({ stringField: 'decoy value', - }) + }), ); const retrieved = await DataStore.query(ModelWithIndexes, m => - m.stringField.eq('expected value') + m.stringField.eq('expected value'), ); expect(retrieved.map(m => m.stringField)).toEqual(['expected value']); }); @@ -271,12 +271,12 @@ export function addCommonQueryTests({ await DataStore.save( new ModelWithIndexes({ intField, - }) + }), ); } const retrieved = await DataStore.query(ModelWithIndexes, m => - m.intField.eq(2) + m.intField.eq(2), ); expect(retrieved.map(m => m.intField)).toEqual([2]); }); @@ -286,12 +286,12 @@ export function addCommonQueryTests({ await DataStore.save( new ModelWithIndexes({ floatField, - }) + }), ); } const retrieved = await DataStore.query(ModelWithIndexes, m => - m.floatField.eq(1.5) + m.floatField.eq(1.5), ); expect(retrieved.map(m => m.floatField)).toEqual([1.5]); }); @@ -340,11 +340,11 @@ export function addCommonQueryTests({ it('should allow linking model via model field', async () => { const profile = await DataStore.save( - new Profile({ firstName: 'Rick', lastName: 'Bob' }) + new Profile({ firstName: 'Rick', lastName: 'Bob' }), ); const savedUser = await DataStore.save( - new User({ name: 'test', profile }) + new User({ name: 'test', profile }), ); const user1Id = savedUser.id; @@ -355,11 +355,11 @@ export function addCommonQueryTests({ it('should allow linking model via FK', async () => { const profile = await DataStore.save( - new Profile({ firstName: 'Rick', lastName: 'Bob' }) + new Profile({ firstName: 'Rick', lastName: 'Bob' }), ); const savedUser = await DataStore.save( - new User({ name: 'test', profileID: profile.id }) + new User({ name: 'test', profileID: profile.id }), ); const user1Id = savedUser.id; @@ -375,20 +375,20 @@ export function addCommonQueryTests({ const post = await DataStore.save( new Post({ title: 'some post', - }) + }), ); const comment = await DataStore.save( new Comment({ content: 'some comment', post, - }) + }), ); const updatedComment = await DataStore.save( Comment.copyOf(comment, draft => { draft.content = 'updated content'; - }) + }), ); const mutations = await getMutations(adapter); @@ -406,7 +406,7 @@ export function addCommonQueryTests({ it('only includes changed fields in mutations', async () => { const profile = await DataStore.save( - new Profile({ firstName: 'original first', lastName: 'original last' }) + new Profile({ firstName: 'original first', lastName: 'original last' }), ); await clearOutbox(adapter); @@ -414,7 +414,7 @@ export function addCommonQueryTests({ await DataStore.save( Profile.copyOf(profile, draft => { draft.firstName = 'new first'; - }) + }), ); const mutations = await getMutations(adapter); @@ -467,7 +467,7 @@ export function addCommonQueryTests({ const post = await DataStore.save( new Post({ title: 'a simple title', - }) + }), ); // sanity check. make sure it was created. @@ -496,23 +496,23 @@ export function addCommonQueryTests({ DataStore.save( new Post({ title: `Todo ${idx}`, - }) - ) - ) + }), + ), + ), ); // Save a new post with `%` in the title const post1 = await DataStore.save( new Post({ title: 'a % title', - }) + }), ); // Save a new Post with title that begins with `%` const post2 = await DataStore.save( new Post({ title: '%title-100', - }) + }), ); //region: sanity check. make sure posts were created. @@ -549,23 +549,23 @@ export function addCommonQueryTests({ DataStore.save( new Post({ title: `Todo ${idx}`, - }) - ) - ) + }), + ), + ), ); // Save a new post with `%` in the title const post1 = await DataStore.save( new Post({ title: 'a % title', - }) + }), ); // Save a new Post with title that begins with `%` const post2 = await DataStore.save( new Post({ title: '%title-100', - }) + }), ); //region: sanity check. make sure posts were created. @@ -603,23 +603,23 @@ export function addCommonQueryTests({ DataStore.save( new Post({ title: `Todo ${idx}`, - }) - ) - ) + }), + ), + ), ); // Save a new post with `%` in the title const post1 = await DataStore.save( new Post({ title: 'a % title', - }) + }), ); // Save a new Post with title that begins with `%` const post2 = await DataStore.save( new Post({ title: '%title-100', - }) + }), ); //region: sanity check. make sure posts were created. @@ -655,23 +655,23 @@ export function addCommonQueryTests({ DataStore.save( new Post({ title: `Todo ${idx}`, - }) - ) - ) + }), + ), + ), ); // Save a new post with `_` in the title const post1 = await DataStore.save( new Post({ title: 'a _ title', - }) + }), ); // Save a new Post with title that begins with `_` const post2 = await DataStore.save( new Post({ title: '_title-100', - }) + }), ); //region: sanity check. make sure posts were created. @@ -708,23 +708,23 @@ export function addCommonQueryTests({ DataStore.save( new Post({ title: `Todo ${idx}`, - }) - ) - ) + }), + ), + ), ); // Save a new post with `_` in the title const post1 = await DataStore.save( new Post({ title: 'a _ title', - }) + }), ); // Save a new Post with title that begins with `_` const post2 = await DataStore.save( new Post({ title: '_title-100', - }) + }), ); //region: sanity check. make sure posts were created. @@ -762,23 +762,23 @@ export function addCommonQueryTests({ DataStore.save( new Post({ title: `Todo ${idx}`, - }) - ) - ) + }), + ), + ), ); // Save a new post with `_` in the title const post1 = await DataStore.save( new Post({ title: 'a _ title', - }) + }), ); // Save a new Post with title that begins with `_` const post2 = await DataStore.save( new Post({ title: '_title-100', - }) + }), ); //region: sanity check. make sure posts were created. @@ -822,13 +822,13 @@ export function addCommonQueryTests({ const post = await DataStore.save( new Post({ title: 'parent post', - }) + }), ); const comment = await DataStore.save( new Comment({ content: 'first!', post, - }) + }), ); // sanity check. make sure things were created. @@ -847,10 +847,10 @@ export function addCommonQueryTests({ const retrievedDeletedComment = await DataStore.query( Comment, - comment.id + comment.id, ); expect(retrievedDeletedComment).toBeUndefined(); - } + }, ); (isSQLiteAdapter() ? test.skip : test)( @@ -859,13 +859,13 @@ export function addCommonQueryTests({ const post = await DataStore.save( new Post({ title: 'parent post', - }) + }), ); const comment = await DataStore.save( new Comment({ content: 'first!', post, - }) + }), ); // sanity check. make sure things were created. @@ -884,10 +884,10 @@ export function addCommonQueryTests({ const retrievedDeletedComment = await DataStore.query( Comment, - comment.id + comment.id, ); expect(retrievedDeletedComment).toBeUndefined(); - } + }, ); /** @@ -903,14 +903,14 @@ export function addCommonQueryTests({ const blog = await DataStore.save( new Blog({ title: 'my blog', - }) + }), ); const post = await DataStore.save( new Post({ title: 'my post', blogId: blog.id, - }) + }), ); const retrievedBlog = await DataStore.query(Blog, blog.id); @@ -923,20 +923,20 @@ export function addCommonQueryTests({ await DataStore.delete(Blog, blog.id); expect(await DataStore.query(Post, post.id)).toBeUndefined(); - } + }, ); test('deleting belongsTo side of relationship does not cascade', async () => { const post = await DataStore.save( new Post({ title: 'parent post', - }) + }), ); const comment = await DataStore.save( new Comment({ content: 'first!', post, - }) + }), ); // sanity check. make sure things were created. @@ -955,7 +955,7 @@ export function addCommonQueryTests({ const retrievedDeletedComment = await DataStore.query( Comment, - comment.id + comment.id, ); expect(retrievedDeletedComment).toBeUndefined(); }); @@ -968,9 +968,9 @@ export function addCommonQueryTests({ await DataStore.delete(hasOneParent); expect( - await DataStore.query(HasOneParent, hasOneParent.id) + await DataStore.query(HasOneParent, hasOneParent.id), ).toBeUndefined(); - } + }, ); (isSQLiteAdapter() ? test.skip : test)( @@ -978,34 +978,34 @@ export function addCommonQueryTests({ async () => { const hasOneChild = await DataStore.save(new HasOneChild({})); const hasOneParent = await DataStore.save( - new HasOneParent({ child: hasOneChild }) + new HasOneParent({ child: hasOneChild }), ); await DataStore.delete(hasOneParent); expect( - await DataStore.query(HasOneParent, hasOneParent.id) + await DataStore.query(HasOneParent, hasOneParent.id), ).toBeUndefined(); expect( - await DataStore.query(HasOneChild, hasOneChild.id) + await DataStore.query(HasOneChild, hasOneChild.id), ).toBeUndefined(); - } + }, ); (isSQLiteAdapter() ? test.skip : test)( 'deleting disconnected hasOne without cpk', async () => { const hasOneParent = await DataStore.save( - new DefaultPKHasOneParent({}) + new DefaultPKHasOneParent({}), ); await DataStore.delete(hasOneParent); expect( - await DataStore.query(DefaultPKHasOneParent, hasOneParent.id) + await DataStore.query(DefaultPKHasOneParent, hasOneParent.id), ).toBeUndefined(); - } + }, ); (isSQLiteAdapter() ? test.skip : test)( @@ -1013,19 +1013,19 @@ export function addCommonQueryTests({ async () => { const hasOneChild = await DataStore.save(new DefaultPKHasOneChild({})); const hasOneParent = await DataStore.save( - new DefaultPKHasOneParent({ child: hasOneChild }) + new DefaultPKHasOneParent({ child: hasOneChild }), ); await DataStore.delete(hasOneParent); expect( - await DataStore.query(DefaultPKHasOneParent, hasOneParent.id) + await DataStore.query(DefaultPKHasOneParent, hasOneParent.id), ).toBeUndefined(); expect( - await DataStore.query(DefaultPKHasOneChild, hasOneChild.id) + await DataStore.query(DefaultPKHasOneChild, hasOneChild.id), ).toBeUndefined(); - } + }, ); }); @@ -1042,7 +1042,7 @@ export function addCommonQueryTests({ const allFKFields = meta => { const fields = new Set(); const relationships = ModelRelationship.allFrom(meta).filter( - r => r.type === 'BELONGS_TO' + r => r.type === 'BELONGS_TO', ); for (const relationship of relationships) { for (const field of relationship.localJoinFields) { @@ -1163,7 +1163,7 @@ export function addCommonQueryTests({ test(`can lazy load ${testname}`, async () => { // Create the "remote" instance first, because the "local" one will point to it. const remoteInit = new R.remoteModelConstructor( - randomInitializer(R.remoteModelConstructor) + randomInitializer(R.remoteModelConstructor), ); const remote = await DataStore.save(remoteInit); @@ -1175,7 +1175,7 @@ export function addCommonQueryTests({ const fetched = await DataStore.query( R.localConstructor, - extractPrimaryKeysAndValues(local, R.localPKFields) + extractPrimaryKeysAndValues(local, R.localPKFields), ); const lazyLoaded = await fetched[field]; @@ -1189,7 +1189,7 @@ export function addCommonQueryTests({ // Create the "remote" instance first, because the "local" one will point to it. const remoteInit = new R.remoteModelConstructor( - randomInitializer(R.remoteModelConstructor) + randomInitializer(R.remoteModelConstructor), ); const remote = await DataStore.save(remoteInit); @@ -1203,7 +1203,7 @@ export function addCommonQueryTests({ const fetched = await DataStore.query( R.localConstructor, - extractPrimaryKeysAndValues(local, R.localPKFields) + extractPrimaryKeysAndValues(local, R.localPKFields), ); const lazyLoaded = await fetched[field]; @@ -1212,7 +1212,7 @@ export function addCommonQueryTests({ }); test(`can query ${testname}`, async () => { const remoteInit = new R.remoteModelConstructor( - randomInitializer(R.remoteModelConstructor) + randomInitializer(R.remoteModelConstructor), ); const remote = await DataStore.save(remoteInit); @@ -1230,7 +1230,7 @@ export function addCommonQueryTests({ const fetched = await DataStore.query( R.localConstructor, local => - local[field][remoteField!].eq(remoteInit[remoteField!]) + local[field][remoteField!].eq(remoteInit[remoteField!]), ); expect(fetched.length).toBe(1); @@ -1238,7 +1238,7 @@ export function addCommonQueryTests({ }); test(`finds empty sets when target related instance field misatches ${testname}`, async () => { const remoteInit = new R.remoteModelConstructor( - randomInitializer(R.remoteModelConstructor) + randomInitializer(R.remoteModelConstructor), ); const remote = await DataStore.save(remoteInit); @@ -1258,8 +1258,8 @@ export function addCommonQueryTests({ local => // HERE'S THE DIFFERENCE! local[field][remoteField!].eq( - remoteInit[remoteField! + ' MISMATCHED!'] - ) + remoteInit[remoteField! + ' MISMATCHED!'], + ), ); // HERE'S THE DIFFERENT ASSERTION. expecting no results. @@ -1267,7 +1267,7 @@ export function addCommonQueryTests({ }); test(`finds empty sets when target instance isn't related ${testname}`, async () => { const remoteInit = new R.remoteModelConstructor( - randomInitializer(R.remoteModelConstructor) + randomInitializer(R.remoteModelConstructor), ); const remote = await DataStore.save(remoteInit); @@ -1288,7 +1288,7 @@ export function addCommonQueryTests({ R.localConstructor, local => // HERE'S THE DIFFERENCE! - local[field][remoteField!].eq(remoteInit[remoteField!]) + local[field][remoteField!].eq(remoteInit[remoteField!]), ); // HERE'S THE DIFFERENT ASSERTION. expecting no results. @@ -1298,7 +1298,7 @@ export function addCommonQueryTests({ case 'HAS_MANY': test(`can lazy load ${testname}`, async () => { const local = await DataStore.save( - new R.localConstructor(randomInitializer(R.localConstructor)) + new R.localConstructor(randomInitializer(R.localConstructor)), ); const FK = {}; @@ -1317,13 +1317,13 @@ export function addCommonQueryTests({ new R.remoteModelConstructor({ ...randomInitializer(R.remoteModelConstructor), ...FK, - }) + }), ); } const fetched = await DataStore.query( R.localConstructor, - extractPrimaryKeysAndValues(local, R.localPKFields) + extractPrimaryKeysAndValues(local, R.localPKFields), ); const lazyLoaded = await fetched[field].toArray(); @@ -1335,7 +1335,7 @@ export function addCommonQueryTests({ * loading related instances that are not actually related by FK. */ const local = await DataStore.save( - new R.localConstructor(randomInitializer(R.localConstructor)) + new R.localConstructor(randomInitializer(R.localConstructor)), ); const remotes = [1, 2, 3] as any[]; @@ -1346,13 +1346,13 @@ export function addCommonQueryTests({ // HERE'S THE DIFFERENCE! we're not tying the model instances together. // ...FK, - }) + }), ); } const fetched = await DataStore.query( R.localConstructor, - extractPrimaryKeysAndValues(local, R.localPKFields) + extractPrimaryKeysAndValues(local, R.localPKFields), ); const lazyLoaded = await fetched[field].toArray(); @@ -1363,7 +1363,7 @@ export function addCommonQueryTests({ const local = await DataStore.save( new R.localConstructor({ ...randomInitializer(R.localConstructor), - }) + }), ); const FK = {}; @@ -1382,7 +1382,7 @@ export function addCommonQueryTests({ new R.remoteModelConstructor({ ...randomInitializer(R.remoteModelConstructor), ...FK, - }) + }), ); } @@ -1396,7 +1396,8 @@ export function addCommonQueryTests({ for (const remote of remotes) { const fetched = await DataStore.query( R.localConstructor, - local => local[field][remoteField!].eq(remote[remoteField!]) + local => + local[field][remoteField!].eq(remote[remoteField!]), ); expect(fetched.length).toBe(1); expect(fetched[0]).toEqual(local); @@ -1406,7 +1407,7 @@ export function addCommonQueryTests({ const local = await DataStore.save( new R.localConstructor({ ...randomInitializer(R.localConstructor), - }) + }), ); const FK = {}; @@ -1425,7 +1426,7 @@ export function addCommonQueryTests({ new R.remoteModelConstructor({ ...randomInitializer(R.remoteModelConstructor), ...FK, - }) + }), ); } @@ -1442,8 +1443,8 @@ export function addCommonQueryTests({ local => // HERE'S THE DIFFERENCE! local[field][remoteField!].eq( - remote[remoteField! + ' MISMATCHED!'] - ) + remote[remoteField! + ' MISMATCHED!'], + ), ); // DIFFERENCE IN ASSERTION @@ -1454,7 +1455,7 @@ export function addCommonQueryTests({ const local = await DataStore.save( new R.localConstructor({ ...randomInitializer(R.localConstructor), - }) + }), ); const remotes = [1, 2, 3] as any[]; @@ -1465,7 +1466,7 @@ export function addCommonQueryTests({ // HERE'S THE DIFFERENCE // ...FK, - }) + }), ); } @@ -1481,7 +1482,7 @@ export function addCommonQueryTests({ R.localConstructor, local => // HERE'S THE DIFFERENCE! - local[field][remoteField!].eq(remote[remoteField!]) + local[field][remoteField!].eq(remote[remoteField!]), ); // DIFFERENCE IN ASSERTION @@ -1558,7 +1559,7 @@ export function addCommonQueryTests({ */ const saveManyToManys = async ( leftOnes: string[], - rightOnes: string[] + rightOnes: string[], ): Promise => { const left = [] as MtmLeft[]; const right = [] as MtmRight[]; @@ -1591,12 +1592,12 @@ export function addCommonQueryTests({ const refetch = async (item: T) => { const fetched = await DataStore.query( item.constructor as PersistentModelConstructor, - item.id + item.id, ); if (!fetched) { throw new Error( - `Instance of ${item.constructor.name} (${item?.id}) doesn't exist in DataStore!` + `Instance of ${item.constructor.name} (${item?.id}) doesn't exist in DataStore!`, ); } else { return fetched; @@ -1647,11 +1648,11 @@ export function addCommonQueryTests({ test('sets can be established and traversed, cardinality 1x1', async () => { const expectedGroupA = await saveManyToManys( ['left content A'], - ['right content A'] + ['right content A'], ); const expectedGroupB = await saveManyToManys( ['left content B'], - ['right content B'] + ['right content B'], ); await expectMatchingMtmsInDataStore(expectedGroupA); @@ -1661,11 +1662,11 @@ export function addCommonQueryTests({ test('sets can be established and traversed, cardinality 3x3', async () => { const expectedGroupA = await saveManyToManys( ['left content A 1', 'left content A 2', 'left content A 3'], - ['right content A 1', 'right content A 2', 'right content A 3'] + ['right content A 1', 'right content A 2', 'right content A 3'], ); const expectedGroupB = await saveManyToManys( ['left content B 1', 'left content B 2', 'left content B 3'], - ['right content B 1', 'right content B 2', 'right content B 3'] + ['right content B 1', 'right content B 2', 'right content B 3'], ); await expectMatchingMtmsInDataStore(expectedGroupA); @@ -1675,22 +1676,22 @@ export function addCommonQueryTests({ test('sets can be queried by nested predicate, cardinality 1x1', async () => { const expectedGroupA = await saveManyToManys( ['left content A'], - ['right content A'] + ['right content A'], ); const expectedGroupB = await saveManyToManys( ['left content B'], - ['right content B'] + ['right content B'], ); const fetchedRightOnesA = await DataStore.query(MtmRight, r => - r.leftOnes.mtmLeft.content.eq('left content A') + r.leftOnes.mtmLeft.content.eq('left content A'), ); expect(fetchedRightOnesA.map(r => r.content)).toEqual([ 'right content A', ]); const fetchedRightOnesB = await DataStore.query(MtmRight, r => - r.leftOnes.mtmLeft.content.eq('left content B') + r.leftOnes.mtmLeft.content.eq('left content B'), ); expect(fetchedRightOnesB.map(r => r.content)).toEqual([ 'right content B', @@ -1711,26 +1712,26 @@ export function addCommonQueryTests({ const expectedGroupA = await saveManyToManys( ['left content A 1', 'left content A 2', 'left content A 3'], - expectedNamesARight + expectedNamesARight, ); const expectedGroupB = await saveManyToManys( ['left content B 1', 'left content B 2', 'left content B 3'], - expectedNamesBRight + expectedNamesBRight, ); const fetchedRightOnesA = await DataStore.query(MtmRight, r => - r.leftOnes.mtmLeft.content.contains('left content A') + r.leftOnes.mtmLeft.content.contains('left content A'), ); expect(fetchedRightOnesA.map(r => r.content)).toEqual( - expectedNamesARight + expectedNamesARight, ); const fetchedRightOnesB = await DataStore.query(MtmRight, r => - r.leftOnes.mtmLeft.content.contains('left content B') + r.leftOnes.mtmLeft.content.contains('left content B'), ); expect(fetchedRightOnesB.map(r => r.content)).toEqual( - expectedNamesBRight + expectedNamesBRight, ); }); }); diff --git a/packages/datastore/__tests__/conflictResolutionBehavior.test.ts b/packages/datastore/__tests__/conflictResolutionBehavior.test.ts index c82d60f8845..7749461ee84 100644 --- a/packages/datastore/__tests__/conflictResolutionBehavior.test.ts +++ b/packages/datastore/__tests__/conflictResolutionBehavior.test.ts @@ -149,7 +149,7 @@ describe('DataStore sync engine', () => { title: 'original title', blogId: 'blog id', }, - false + false, ); harness.latency = 'high'; @@ -180,7 +180,7 @@ describe('DataStore sync engine', () => { title: 'original title', blogId: 'blog id', }, - false + false, ); harness.userInputDelayed(); @@ -481,7 +481,7 @@ describe('DataStore sync engine', () => { await harness.expectGraphqlSettledWithEventCount(3); expect( - harness.subscriptionLogs(['title', 'blogId', '_version']) + harness.subscriptionLogs(['title', 'blogId', '_version']), ).toEqual([ ['original title', null, 1], ['post title 0', null, 1], @@ -526,7 +526,7 @@ describe('DataStore sync engine', () => { await harness.expectGraphqlSettledWithEventCount(4); expect( - harness.subscriptionLogs(['title', 'blogId', '_version']) + harness.subscriptionLogs(['title', 'blogId', '_version']), ).toEqual([ ['original title', null, 1], ['post title 0', null, 1], @@ -566,7 +566,7 @@ describe('DataStore sync engine', () => { await harness.expectGraphqlSettledWithEventCount(4); expect( - harness.subscriptionLogs(['title', 'blogId', '_version']) + harness.subscriptionLogs(['title', 'blogId', '_version']), ).toEqual([ ['original title', null, 1], ['post title 0', null, 1], @@ -612,7 +612,7 @@ describe('DataStore sync engine', () => { await harness.expectGraphqlSettledWithEventCount(4); expect( - harness.subscriptionLogs(['title', 'blogId', '_version' ?? null]) + harness.subscriptionLogs(['title', 'blogId', '_version' ?? null]), ).toEqual([ ['original title', 'original blogId', 1], ['post title 0', 'original blogId', 1], @@ -650,7 +650,7 @@ describe('DataStore sync engine', () => { await harness.expectGraphqlSettledWithEventCount(4); expect( - harness.subscriptionLogs(['title', 'blogId', '_version']) + harness.subscriptionLogs(['title', 'blogId', '_version']), ).toEqual([ ['original title', null, 1], ['post title 0', null, 1], @@ -694,7 +694,7 @@ describe('DataStore sync engine', () => { await harness.expectGraphqlSettledWithEventCount(4); expect( - harness.subscriptionLogs(['title', 'blogId', '_version']) + harness.subscriptionLogs(['title', 'blogId', '_version']), ).toEqual([ ['original title', null, 1], ['post title 0', null, 1], @@ -793,7 +793,7 @@ describe('DataStore sync engine', () => { title: 'original title', blogId: 'blog id', }, - false + false, ); harness.latency = 'high'; @@ -824,7 +824,7 @@ describe('DataStore sync engine', () => { title: 'original title', blogId: 'blog id', }, - false + false, ); harness.userInputDelayed(); @@ -1119,7 +1119,7 @@ describe('DataStore sync engine', () => { }); expect( - harness.subscriptionLogs(['title', 'blogId', '_version']) + harness.subscriptionLogs(['title', 'blogId', '_version']), ).toEqual([ ['original title', null, 1], ['post title 0', null, 1], @@ -1170,7 +1170,7 @@ describe('DataStore sync engine', () => { }); expect( - harness.subscriptionLogs(['title', 'blogId', '_version']) + harness.subscriptionLogs(['title', 'blogId', '_version']), ).toEqual([ ['original title', null, 1], ['post title 0', null, 1], @@ -1218,7 +1218,7 @@ describe('DataStore sync engine', () => { }); expect( - harness.subscriptionLogs(['title', 'blogId', '_version']) + harness.subscriptionLogs(['title', 'blogId', '_version']), ).toEqual([ ['original title', null, 1], ['post title 0', null, 1], @@ -1270,7 +1270,7 @@ describe('DataStore sync engine', () => { }); expect( - harness.subscriptionLogs(['title', 'blogId', '_version' ?? null]) + harness.subscriptionLogs(['title', 'blogId', '_version' ?? null]), ).toEqual([ ['original title', 'original blogId', 1], ['post title 0', 'original blogId', 1], @@ -1310,7 +1310,7 @@ describe('DataStore sync engine', () => { await harness.expectGraphqlSettledWithEventCount(4); expect( - harness.subscriptionLogs(['title', 'blogId', '_version']) + harness.subscriptionLogs(['title', 'blogId', '_version']), ).toEqual([ ['original title', null, 1], ['post title 0', null, 1], @@ -1354,7 +1354,7 @@ describe('DataStore sync engine', () => { await harness.expectGraphqlSettledWithEventCount(4); expect( - harness.subscriptionLogs(['title', 'blogId', '_version']) + harness.subscriptionLogs(['title', 'blogId', '_version']), ).toEqual([ ['original title', null, 1], ['post title 0', null, 1], diff --git a/packages/datastore/__tests__/connectivityHandling.test.ts b/packages/datastore/__tests__/connectivityHandling.test.ts index 0852549906a..733393dc3e4 100644 --- a/packages/datastore/__tests__/connectivityHandling.test.ts +++ b/packages/datastore/__tests__/connectivityHandling.test.ts @@ -147,7 +147,7 @@ describe('DataStore sync engine', () => { const m = await DataStore.save( new BasicModel({ body: 'whatever and ever', - }) + }), ); await waitForEmptyOutbox(); @@ -167,7 +167,7 @@ describe('DataStore sync engine', () => { new Model({ field1: 'whatever and ever', dateCreated: new Date().toISOString(), - }) + }), ); const omitted_optional_fields = [ @@ -201,7 +201,7 @@ describe('DataStore sync engine', () => { field1: 'whatever and ever', dateCreated: new Date().toISOString(), metadata: null, - }) + }), ); await waitForEmptyOutbox(); @@ -224,14 +224,14 @@ describe('DataStore sync engine', () => { new Model({ field1: 'whatever and ever', dateCreated: new Date().toISOString(), - }) + }), ); await waitForEmptyOutbox(); const retrieved = (await DataStore.query(Model, saved.id))!; const updated = await DataStore.save( - Model.copyOf(retrieved, d => (d.optionalField1 = 'new value')) + Model.copyOf(retrieved, d => (d.optionalField1 = 'new value')), ); const omitted_fields = ['field1', 'emails', 'ips', 'logins', 'metadata']; @@ -259,14 +259,14 @@ describe('DataStore sync engine', () => { field1: 'whatever and ever', dateCreated: new Date().toISOString(), optionalField1: 'something', - }) + }), ); await waitForEmptyOutbox(); const retrieved = (await DataStore.query(Model, saved.id))!; await DataStore.save( - Model.copyOf(retrieved, d => (d.optionalField1 = null)) + Model.copyOf(retrieved, d => (d.optionalField1 = null)), ); await waitForEmptyOutbox(); @@ -286,7 +286,7 @@ describe('DataStore sync engine', () => { new ModelWithExplicitOwner({ title: 'very clever title', owner: null, - }) + }), ); await waitForEmptyOutboxOrError(graphqlService); @@ -303,7 +303,7 @@ describe('DataStore sync engine', () => { new ModelWithExplicitOwner({ title: 'very clever title', owner: undefined, - }) + }), ); await waitForEmptyOutboxOrError(graphqlService); @@ -320,7 +320,7 @@ describe('DataStore sync engine', () => { new ModelWithExplicitCustomOwner({ title: 'very clever title', customowner: null, - }) + }), ); await waitForEmptyOutboxOrError(graphqlService); @@ -337,7 +337,7 @@ describe('DataStore sync engine', () => { new ModelWithExplicitCustomOwner({ title: 'very clever title', customowner: undefined, - }) + }), ); await waitForEmptyOutboxOrError(graphqlService); @@ -355,7 +355,7 @@ describe('DataStore sync engine', () => { title: 'very clever title', customownerOne: undefined, customownerTwo: undefined, - }) + }), ); await waitForEmptyOutboxOrError(graphqlService); @@ -373,7 +373,7 @@ describe('DataStore sync engine', () => { title: 'very clever title', customownerOne: undefined, customownerTwo: 'bob', - }) + }), ); await waitForEmptyOutboxOrError(graphqlService); @@ -391,7 +391,7 @@ describe('DataStore sync engine', () => { title: 'very clever title', customownerOne: 'bob', customownerTwo: undefined, - }) + }), ); await waitForEmptyOutboxOrError(graphqlService); @@ -406,13 +406,13 @@ describe('DataStore sync engine', () => { test('includes timestamp fields in mutation events when NOT readonly', async () => { // make sure our test model still meets requirements to make this test valid. expect( - schema.models.BasicModelWritableTS.fields.createdAt.isReadOnly + schema.models.BasicModelWritableTS.fields.createdAt.isReadOnly, ).toBe(false); const m = await DataStore.save( new BasicModelWritableTS({ body: 'whatever else', - }) + }), ); await waitForEmptyOutbox(); @@ -444,7 +444,7 @@ describe('DataStore sync engine', () => { const updated = await DataStore.save( Post.copyOf(retrieved!, draft => { draft.title = 'updated title'; - }) + }), ); await waitForEmptyOutbox(); @@ -461,15 +461,15 @@ describe('DataStore sync engine', () => { field1: 'field 1 value', dateCreated: new Date().toISOString(), optionalField1: 'optional field value', - }) + }), ); await waitForEmptyOutbox(); const updated = await DataStore.save( Model.copyOf( (await DataStore.query(Model, original.id))!, - m => (m.optionalField1 = undefined) - ) + m => (m.optionalField1 = undefined), + ), ); const retrievedBeforeMutate = await DataStore.query(Model, original.id); await waitForEmptyOutbox(); @@ -507,7 +507,7 @@ describe('DataStore sync engine', () => { const retrieved = await DataStore.query(Post, post.id); const deleted = await DataStore.delete(retrieved!, p => - p.title.eq('post title') + p.title.eq('post title'), ); await waitForEmptyOutbox(); @@ -522,17 +522,17 @@ describe('DataStore sync engine', () => { [null, undefined].forEach(value => { test(`model field can be set to ${value} to remove connection hasOne parent`, async () => { const child = await DataStore.save( - new HasOneChild({ content: 'child content' }) + new HasOneChild({ content: 'child content' }), ); const parent = await DataStore.save( new HasOneParent({ child, - }) + }), ); await waitForEmptyOutboxOrError(graphqlService); const parentTable = graphqlService.tables.get('HasOneParent')!; const savedParentWithChild = parentTable.get( - JSON.stringify([parent.id]) + JSON.stringify([parent.id]), ) as any; expect(savedParentWithChild.hasOneParentChildId).toEqual(child.id); @@ -540,14 +540,14 @@ describe('DataStore sync engine', () => { (await DataStore.query(HasOneParent, parent.id))!, draft => { draft.child = value; - } + }, ); await DataStore.save(parentWithoutChild); await waitForEmptyOutboxOrError(graphqlService); const savedParentWithoutChild = parentTable.get( - JSON.stringify([parent.id]) + JSON.stringify([parent.id]), ) as any; expect(savedParentWithoutChild.hasOneParentChildId).toEqual(null); }); @@ -557,7 +557,7 @@ describe('DataStore sync engine', () => { new CompositePKParent({ customId: 'customId', content: 'content', - }) + }), ); const child = await DataStore.save( @@ -565,13 +565,13 @@ describe('DataStore sync engine', () => { childId: 'childId', content: 'content', parent, - }) + }), ); await waitForEmptyOutboxOrError(graphqlService); const childTable = graphqlService.tables.get('CompositePKChild')!; const savedChildWithParent = childTable.get( - JSON.stringify([child.childId, child.content]) + JSON.stringify([child.childId, child.content]), ) as any; expect(savedChildWithParent.parentId).toEqual(parent.customId); expect(savedChildWithParent.parentTitle).toEqual(parent.content); @@ -583,14 +583,14 @@ describe('DataStore sync engine', () => { }))!, draft => { draft.parent = value; - } + }, ); await DataStore.save(childWithoutParent); await waitForEmptyOutboxOrError(graphqlService); const savedChildWithoutParent = childTable.get( - JSON.stringify([child.childId, child.content]) + JSON.stringify([child.childId, child.content]), ) as any; expect(savedChildWithoutParent.parentId).toEqual(null); expect(savedChildWithoutParent.parentTitle).toEqual(null); @@ -611,7 +611,7 @@ describe('DataStore sync engine', () => { const post = await DataStore.save( new Post({ title: 'a title', - }) + }), ); await waitForEmptyOutbox(); @@ -622,7 +622,7 @@ describe('DataStore sync engine', () => { const anotherPost = await DataStore.save( new Post({ title: 'another title', - }) + }), ); await waitForEmptyOutbox(); @@ -634,7 +634,7 @@ describe('DataStore sync engine', () => { expect(cloudPost.title).toEqual('a title'); const cloudAnotherPost = table.get( - JSON.stringify([anotherPost.id]) + JSON.stringify([anotherPost.id]), ) as any; expect(cloudAnotherPost.title).toEqual('another title'); }); @@ -643,7 +643,7 @@ describe('DataStore sync engine', () => { const post = await DataStore.save( new Post({ title: 'a title', - }) + }), ); await waitForEmptyOutbox(); @@ -653,7 +653,7 @@ describe('DataStore sync engine', () => { const anotherPost = await DataStore.save( new Post({ title: 'another title', - }) + }), ); // In this scenario, we want to test the case where the offline @@ -670,7 +670,7 @@ describe('DataStore sync engine', () => { expect(cloudPost.title).toEqual('a title'); const cloudAnotherPost = table.get( - JSON.stringify([anotherPost.id]) + JSON.stringify([anotherPost.id]), ) as any; expect(cloudAnotherPost.title).toEqual('another title'); }); @@ -679,7 +679,7 @@ describe('DataStore sync engine', () => { const post = await DataStore.save( new Post({ title: 'a title', - }) + }), ); await waitForEmptyOutbox(); @@ -690,7 +690,7 @@ describe('DataStore sync engine', () => { const anotherPost = await DataStore.save( new Post({ title: 'another title', - }) + }), ); // NO PAUSE: Simulate reconnect IMMEDIATELY, causing a race @@ -706,7 +706,7 @@ describe('DataStore sync engine', () => { expect(cloudPost.title).toEqual('a title'); const cloudAnotherPost = table.get( - JSON.stringify([anotherPost.id]) + JSON.stringify([anotherPost.id]), ) as any; expect(cloudAnotherPost.title).toEqual('another title'); }); @@ -715,7 +715,7 @@ describe('DataStore sync engine', () => { const post = await DataStore.save( new Post({ title: 'a title', - }) + }), ); await waitForEmptyOutbox(); @@ -725,7 +725,7 @@ describe('DataStore sync engine', () => { const retrieved = await DataStore.query(Post, post.id); await DataStore.save( - Post.copyOf(retrieved!, updated => (updated.title = 'new title')) + Post.copyOf(retrieved!, updated => (updated.title = 'new title')), ); // NO PAUSE: Simulate reconnect IMMEDIATELY, causing a race @@ -745,7 +745,7 @@ describe('DataStore sync engine', () => { const post = await DataStore.save( new Post({ title: 'a title', - }) + }), ); await waitForEmptyOutbox(); @@ -774,7 +774,7 @@ describe('DataStore sync engine', () => { const post = await DataStore.save( new Post({ title: 'a title', - }) + }), ); await waitForEmptyOutbox(); @@ -819,13 +819,13 @@ describe('DataStore sync engine', () => { expect((await DataStore.query(Post)).length).toEqual(2); expect((await DataStore.query(Post, post.id))!.title).toEqual('a title'); expect((await DataStore.query(Post, secondPostId))!.title).toEqual( - 'a title 2' + 'a title 2', ); const thirdPost = await DataStore.save( new Post({ title: 'a title 3', - }) + }), ); expect((await DataStore.query(Post)).length).toEqual(3); @@ -849,7 +849,7 @@ describe('DataStore sync engine', () => { const postPromise = DataStore.save( new Post({ title: 'a title', - }) + }), ); const errorLog = jest.spyOn(console, 'error'); await simulateDisruption(); @@ -862,7 +862,7 @@ describe('DataStore sync engine', () => { expect(table.size).toEqual(1); const cloudPost = table.get( - JSON.stringify([(await postPromise).id]) + JSON.stringify([(await postPromise).id]), ) as any; expect(cloudPost.title).toEqual('a title'); @@ -891,7 +891,7 @@ describe('DataStore sync engine', () => { await DataStore.save( new Post({ title, - }) + }), ); } }; @@ -964,7 +964,7 @@ describe('DataStore sync engine', () => { await resyncWith([ syncExpression( Post, - async () => post => post.title.contains('cleaning') + async () => post => post.title.contains('cleaning'), ), ]); @@ -988,9 +988,8 @@ describe('DataStore sync engine', () => { }; await resyncWith([ - syncExpression( - LegacyJSONPost, - p => p?.title.eq("whatever, it doesn't matter.") + syncExpression(LegacyJSONPost, p => + p?.title.eq("whatever, it doesn't matter."), ), ]); @@ -1011,7 +1010,7 @@ describe('DataStore sync engine', () => { await resyncWith([ syncExpression( Post, - async () => post => post.title.contains('cleaning') + async () => post => post.title.contains('cleaning'), ), ]); @@ -1052,7 +1051,7 @@ describe('DataStore sync engine', () => { ]), and.emails.ne('-'), ]), - ]) + ]), ), ]); @@ -1175,7 +1174,7 @@ describe('DataStore sync engine', () => { DataStore.save( new LegacyJSONComment({ content: 'test content', - }) + }), ); const error: any = await waitForNextMessage(errorHandler); diff --git a/packages/datastore/__tests__/custom-pk-typings/identifier-fields.test.tsx b/packages/datastore/__tests__/custom-pk-typings/identifier-fields.test.tsx index d51cda45aa6..f38f4474b51 100644 --- a/packages/datastore/__tests__/custom-pk-typings/identifier-fields.test.tsx +++ b/packages/datastore/__tests__/custom-pk-typings/identifier-fields.test.tsx @@ -20,28 +20,28 @@ describe('IdentifierFields', () => { undefined! as IdentifierFields< ManagedCustomRO, ManagedCustomRO[typeof __modelMeta__] - > + >, ); expectType<'id'>( undefined! as IdentifierFields< OptionallyManagedCustomRO, OptionallyManagedCustomRO[typeof __modelMeta__] - > + >, ); expectType<'myId'>( undefined! as IdentifierFields< CustomIdentifierCustomRO, CustomIdentifierCustomRO[typeof __modelMeta__] - > + >, ); expectType<'tenant' | 'dob'>( undefined! as IdentifierFields< CompositeCustomRO, CompositeCustomRO[typeof __modelMeta__] - > + >, ); }); }); diff --git a/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/composite-identifier.test.tsx b/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/composite-identifier.test.tsx index 7135a440555..4dc8cebd91e 100644 --- a/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/composite-identifier.test.tsx +++ b/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/composite-identifier.test.tsx @@ -68,24 +68,24 @@ describe('Composite Identifier', () => { // await DataStore.query(CompositeDefaultRO, { id: 'someid' }); expectType( - await DataStore.query(CompositeDefaultRO, { tenant: '', dob: '' }) + await DataStore.query(CompositeDefaultRO, { tenant: '', dob: '' }), ); expectType(await DataStore.query(CompositeDefaultRO)); expectType( - await DataStore.query(CompositeDefaultRO, Predicates.ALL) + await DataStore.query(CompositeDefaultRO, Predicates.ALL), ); expectType( - await DataStore.query(CompositeDefaultRO, c => c.createdAt.ge('2019')) + await DataStore.query(CompositeDefaultRO, c => c.createdAt.ge('2019')), ); // Save expectType( - await DataStore.save(dummyInstance()) + await DataStore.save(dummyInstance()), ); expectType( await DataStore.save(dummyInstance(), c => - c.createdAt.ge('2019') - ) + c.createdAt.ge('2019'), + ), ); // Delete @@ -94,21 +94,21 @@ describe('Composite Identifier', () => { // await DataStore.delete(CompositeDefaultRO, '') expectType( - await DataStore.delete(CompositeDefaultRO, { tenant: '', dob: '' }) + await DataStore.delete(CompositeDefaultRO, { tenant: '', dob: '' }), ); expectType( - await DataStore.delete(dummyInstance()) + await DataStore.delete(dummyInstance()), ); expectType( await DataStore.delete(dummyInstance(), c => - c.description.contains('something') - ) + c.description.contains('something'), + ), ); expectType( - await DataStore.delete(CompositeDefaultRO, Predicates.ALL) + await DataStore.delete(CompositeDefaultRO, Predicates.ALL), ); expectType( - await DataStore.delete(CompositeDefaultRO, c => c.createdAt.le('2019')) + await DataStore.delete(CompositeDefaultRO, c => c.createdAt.le('2019')), ); // Observe @@ -117,7 +117,7 @@ describe('Composite Identifier', () => { expectType(element); }); DataStore.observe(CompositeDefaultRO, c => - c.description.beginsWith('something') + c.description.beginsWith('something'), ).subscribe(({ model, element }) => { expectType>(model); expectType(element); @@ -128,14 +128,14 @@ describe('Composite Identifier', () => { expectType(items); }); DataStore.observeQuery(CompositeDefaultRO, c => - c.description.notContains('something') + c.description.notContains('something'), ).subscribe(({ items }) => { expectType(items); }); DataStore.observeQuery( CompositeDefaultRO, c => c.description.notContains('something'), - { sort: c => c.createdAt('ASCENDING') } + { sort: c => c.createdAt('ASCENDING') }, ).subscribe(({ items }) => { expectType(items); }); diff --git a/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/legacy-backwards-compatibility.test.tsx b/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/legacy-backwards-compatibility.test.tsx index 95bc7c9f5b2..493c2b2bded 100644 --- a/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/legacy-backwards-compatibility.test.tsx +++ b/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/legacy-backwards-compatibility.test.tsx @@ -55,46 +55,46 @@ describe('Legacy - backwards compatibility', () => { // Query expectType( - await DataStore.query(LegacyNoMetadata, 'someid') + await DataStore.query(LegacyNoMetadata, 'someid'), ); expectType( - await DataStore.query(LegacyNoMetadata, { id: 'someid' }) + await DataStore.query(LegacyNoMetadata, { id: 'someid' }), ); expectType(await DataStore.query(LegacyNoMetadata)); expectType( - await DataStore.query(LegacyNoMetadata, Predicates.ALL) + await DataStore.query(LegacyNoMetadata, Predicates.ALL), ); expectType( - await DataStore.query(LegacyNoMetadata, c => c.createdAt.ge('2019')) + await DataStore.query(LegacyNoMetadata, c => c.createdAt.ge('2019')), ); // Save expectType( - await DataStore.save(dummyInstance()) + await DataStore.save(dummyInstance()), ); expectType( await DataStore.save(dummyInstance(), c => - c.createdAt.ge('2019') - ) + c.createdAt.ge('2019'), + ), ); // Delete expectType( - await DataStore.delete(LegacyNoMetadata, '') + await DataStore.delete(LegacyNoMetadata, ''), ); expectType( - await DataStore.delete(dummyInstance()) + await DataStore.delete(dummyInstance()), ); expectType( await DataStore.delete(dummyInstance(), c => - c.description.contains('something') - ) + c.description.contains('something'), + ), ); expectType( - await DataStore.delete(LegacyNoMetadata, Predicates.ALL) + await DataStore.delete(LegacyNoMetadata, Predicates.ALL), ); expectType( - await DataStore.delete(LegacyNoMetadata, c => c.createdAt.le('2019')) + await DataStore.delete(LegacyNoMetadata, c => c.createdAt.le('2019')), ); // Observe @@ -103,7 +103,7 @@ describe('Legacy - backwards compatibility', () => { expectType(element); }); DataStore.observe(LegacyNoMetadata, c => - c.description.beginsWith('something') + c.description.beginsWith('something'), ).subscribe(({ model, element }) => { expectType>(model); expectType(element); @@ -116,7 +116,7 @@ describe('Legacy - backwards compatibility', () => { }); expectType>(model); expectType(element); - } + }, ); // Observe query @@ -124,14 +124,14 @@ describe('Legacy - backwards compatibility', () => { expectType(items); }); DataStore.observeQuery(LegacyNoMetadata, c => - c.description.notContains('something') + c.description.notContains('something'), ).subscribe(({ items }) => { expectType(items); }); DataStore.observeQuery( LegacyNoMetadata, c => c.description.notContains('something'), - { sort: c => c.createdAt('ASCENDING') } + { sort: c => c.createdAt('ASCENDING') }, ).subscribe(({ items }) => { expectType(items); }); @@ -171,41 +171,41 @@ describe('Legacy - backwards compatibility', () => { // Query expectType( - (await DataStore.query(LegacyDefaultRO, 'someid'))! + (await DataStore.query(LegacyDefaultRO, 'someid'))!, ); expectType(await DataStore.query(LegacyDefaultRO)); expectType( - await DataStore.query(LegacyDefaultRO, Predicates.ALL) + await DataStore.query(LegacyDefaultRO, Predicates.ALL), ); expectType( - await DataStore.query(LegacyDefaultRO, c => c.createdAt.ge('2019')) + await DataStore.query(LegacyDefaultRO, c => c.createdAt.ge('2019')), ); // Save expectType( - await DataStore.save(dummyInstance()) + await DataStore.save(dummyInstance()), ); expectType( await DataStore.save(dummyInstance(), c => - c.createdAt.ge('2019') - ) + c.createdAt.ge('2019'), + ), ); // Delete expectType(await DataStore.delete(LegacyDefaultRO, '')); expectType( - await DataStore.delete(dummyInstance()) + await DataStore.delete(dummyInstance()), ); expectType( await DataStore.delete(dummyInstance(), c => - c.description.contains('something') - ) + c.description.contains('something'), + ), ); expectType( - await DataStore.delete(LegacyDefaultRO, Predicates.ALL) + await DataStore.delete(LegacyDefaultRO, Predicates.ALL), ); expectType( - await DataStore.delete(LegacyDefaultRO, c => c.createdAt.le('2019')) + await DataStore.delete(LegacyDefaultRO, c => c.createdAt.le('2019')), ); // Observe @@ -214,7 +214,7 @@ describe('Legacy - backwards compatibility', () => { expectType(element); }); DataStore.observe(LegacyDefaultRO, c => - c.description.beginsWith('something') + c.description.beginsWith('something'), ).subscribe(({ model, element }) => { expectType>(model); expectType(element); @@ -223,7 +223,7 @@ describe('Legacy - backwards compatibility', () => { ({ model, element }) => { expectType>(model); expectType(element); - } + }, ); // Observe query @@ -231,14 +231,14 @@ describe('Legacy - backwards compatibility', () => { expectType(items); }); DataStore.observeQuery(LegacyDefaultRO, c => - c.description.notContains('something') + c.description.notContains('something'), ).subscribe(({ items }) => { expectType(items); }); DataStore.observeQuery( LegacyDefaultRO, c => c.description.notContains('something'), - { sort: c => c.createdAt('ASCENDING') } + { sort: c => c.createdAt('ASCENDING') }, ).subscribe(({ items }) => { expectType(items); }); @@ -291,41 +291,41 @@ describe('Legacy - backwards compatibility', () => { // Query expectType( - (await DataStore.query(LegacyCustomRO, 'someid'))! + (await DataStore.query(LegacyCustomRO, 'someid'))!, ); expectType(await DataStore.query(LegacyCustomRO)); expectType( - await DataStore.query(LegacyCustomRO, Predicates.ALL) + await DataStore.query(LegacyCustomRO, Predicates.ALL), ); expectType( - await DataStore.query(LegacyCustomRO, c => c.createdOn.ge('2019')) + await DataStore.query(LegacyCustomRO, c => c.createdOn.ge('2019')), ); // Save expectType( - await DataStore.save(dummyInstance()) + await DataStore.save(dummyInstance()), ); expectType( await DataStore.save(dummyInstance(), c => - c.createdOn.ge('2019') - ) + c.createdOn.ge('2019'), + ), ); // Delete expectType(await DataStore.delete(LegacyCustomRO, '')); expectType( - await DataStore.delete(dummyInstance()) + await DataStore.delete(dummyInstance()), ); expectType( await DataStore.delete(dummyInstance(), c => - c.description.contains('something') - ) + c.description.contains('something'), + ), ); expectType( - await DataStore.delete(LegacyCustomRO, Predicates.ALL) + await DataStore.delete(LegacyCustomRO, Predicates.ALL), ); expectType( - await DataStore.delete(LegacyCustomRO, c => c.createdOn.le('2019')) + await DataStore.delete(LegacyCustomRO, c => c.createdOn.le('2019')), ); // Observe @@ -334,7 +334,7 @@ describe('Legacy - backwards compatibility', () => { expectType(element); }); DataStore.observe(LegacyCustomRO, c => - c.description.beginsWith('something') + c.description.beginsWith('something'), ).subscribe(({ model, element }) => { expectType>(model); expectType(element); @@ -343,7 +343,7 @@ describe('Legacy - backwards compatibility', () => { ({ model, element }) => { expectType>(model); expectType(element); - } + }, ); // Observe query @@ -351,14 +351,14 @@ describe('Legacy - backwards compatibility', () => { expectType(items); }); DataStore.observeQuery(LegacyCustomRO, c => - c.description.notContains('something') + c.description.notContains('something'), ).subscribe(({ items }) => { expectType(items); }); DataStore.observeQuery( LegacyCustomRO, c => c.description.notContains('something'), - { sort: c => c.createdOn('ASCENDING') } + { sort: c => c.createdOn('ASCENDING') }, ).subscribe(({ items }) => { expectType(items); }); @@ -410,48 +410,48 @@ describe('Legacy - backwards compatibility', () => { // Query expectType( - (await DataStore.query(CustomIdentifierNoRO, 'someid'))! + (await DataStore.query(CustomIdentifierNoRO, 'someid'))!, ); expectType( - (await DataStore.query(CustomIdentifierNoRO, { myId: 'someid' }))! + (await DataStore.query(CustomIdentifierNoRO, { myId: 'someid' }))!, ); expectType( - await DataStore.query(CustomIdentifierNoRO) + await DataStore.query(CustomIdentifierNoRO), ); expectType( - await DataStore.query(CustomIdentifierNoRO, Predicates.ALL) + await DataStore.query(CustomIdentifierNoRO, Predicates.ALL), ); expectType( - await DataStore.query(CustomIdentifierNoRO, c => c.createdAt.ge('2019')) + await DataStore.query(CustomIdentifierNoRO, c => c.createdAt.ge('2019')), ); // Save expectType( - await DataStore.save(dummyInstance()) + await DataStore.save(dummyInstance()), ); expectType( await DataStore.save(dummyInstance(), c => - c.createdAt.ge('2019') - ) + c.createdAt.ge('2019'), + ), ); // Delete expectType( - await DataStore.delete(CustomIdentifierNoRO, '') + await DataStore.delete(CustomIdentifierNoRO, ''), ); expectType( - await DataStore.delete(dummyInstance()) + await DataStore.delete(dummyInstance()), ); expectType( await DataStore.delete(dummyInstance(), c => - c.description.contains('something') - ) + c.description.contains('something'), + ), ); expectType( - await DataStore.delete(CustomIdentifierNoRO, Predicates.ALL) + await DataStore.delete(CustomIdentifierNoRO, Predicates.ALL), ); expectType( - await DataStore.delete(CustomIdentifierNoRO, c => c.createdAt.le('2019')) + await DataStore.delete(CustomIdentifierNoRO, c => c.createdAt.le('2019')), ); // Observe @@ -460,7 +460,7 @@ describe('Legacy - backwards compatibility', () => { expectType(element); }); DataStore.observe(CustomIdentifierNoRO, c => - c.description.beginsWith('something') + c.description.beginsWith('something'), ).subscribe(({ model, element }) => { expectType>(model); expectType(element); @@ -469,7 +469,7 @@ describe('Legacy - backwards compatibility', () => { ({ model, element }) => { expectType>(model); expectType(element); - } + }, ); // Observe query @@ -477,14 +477,14 @@ describe('Legacy - backwards compatibility', () => { expectType(items); }); DataStore.observeQuery(CustomIdentifierNoRO, c => - c.description.notContains('something') + c.description.notContains('something'), ).subscribe(({ items }) => { expectType(items); }); DataStore.observeQuery( CustomIdentifierNoRO, c => c.description.notContains('something'), - { sort: c => c.createdAt('ASCENDING') } + { sort: c => c.createdAt('ASCENDING') }, ).subscribe(({ items }) => { expectType(items); }); diff --git a/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/managed-identifier.test.tsx b/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/managed-identifier.test.tsx index 2e847e6caf6..97acff9d0cb 100644 --- a/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/managed-identifier.test.tsx +++ b/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/managed-identifier.test.tsx @@ -54,46 +54,46 @@ describe('Managed Identifier', () => { // Query expectType( - await DataStore.query(ManagedDefaultRO, 'someid') + await DataStore.query(ManagedDefaultRO, 'someid'), ); expectType( - await DataStore.query(ManagedDefaultRO, { id: 'someid' }) + await DataStore.query(ManagedDefaultRO, { id: 'someid' }), ); expectType(await DataStore.query(ManagedDefaultRO)); expectType( - await DataStore.query(ManagedDefaultRO, Predicates.ALL) + await DataStore.query(ManagedDefaultRO, Predicates.ALL), ); expectType( - await DataStore.query(ManagedDefaultRO, c => c.createdAt.ge('2019')) + await DataStore.query(ManagedDefaultRO, c => c.createdAt.ge('2019')), ); // Save expectType( - await DataStore.save(dummyInstance()) + await DataStore.save(dummyInstance()), ); expectType( await DataStore.save(dummyInstance(), c => - c.createdAt.ge('2019') - ) + c.createdAt.ge('2019'), + ), ); // Delete expectType( - await DataStore.delete(ManagedDefaultRO, '') + await DataStore.delete(ManagedDefaultRO, ''), ); expectType( - await DataStore.delete(dummyInstance()) + await DataStore.delete(dummyInstance()), ); expectType( await DataStore.delete(dummyInstance(), c => - c.description.contains('something') - ) + c.description.contains('something'), + ), ); expectType( - await DataStore.delete(ManagedDefaultRO, Predicates.ALL) + await DataStore.delete(ManagedDefaultRO, Predicates.ALL), ); expectType( - await DataStore.delete(ManagedDefaultRO, c => c.createdAt.le('2019')) + await DataStore.delete(ManagedDefaultRO, c => c.createdAt.le('2019')), ); // Observe @@ -102,7 +102,7 @@ describe('Managed Identifier', () => { expectType(element); }); DataStore.observe(ManagedDefaultRO, c => - c.description.beginsWith('something') + c.description.beginsWith('something'), ).subscribe(({ model, element }) => { expectType>(model); expectType(element); @@ -111,7 +111,7 @@ describe('Managed Identifier', () => { ({ model, element }) => { expectType>(model); expectType(element); - } + }, ); // Observe query @@ -119,14 +119,14 @@ describe('Managed Identifier', () => { expectType(items); }); DataStore.observeQuery(ManagedDefaultRO, c => - c.description.notContains('something') + c.description.notContains('something'), ).subscribe(({ items }) => { expectType(items); }); DataStore.observeQuery( ManagedDefaultRO, c => c.description.notContains('something'), - { sort: c => c.createdAt('ASCENDING') } + { sort: c => c.createdAt('ASCENDING') }, ).subscribe(({ items }) => { expectType(items); }); @@ -173,41 +173,41 @@ describe('Managed Identifier', () => { // Query expectType( - await DataStore.query(ManagedCustomRO, 'someid') + await DataStore.query(ManagedCustomRO, 'someid'), ); expectType(await DataStore.query(ManagedCustomRO)); expectType( - await DataStore.query(ManagedCustomRO, Predicates.ALL) + await DataStore.query(ManagedCustomRO, Predicates.ALL), ); expectType( - await DataStore.query(ManagedCustomRO, c => c.createdOn.ge('2019')) + await DataStore.query(ManagedCustomRO, c => c.createdOn.ge('2019')), ); // Save expectType( - await DataStore.save(dummyInstance()) + await DataStore.save(dummyInstance()), ); expectType( await DataStore.save(dummyInstance(), c => - c.createdOn.ge('2019') - ) + c.createdOn.ge('2019'), + ), ); // Delete expectType(await DataStore.delete(ManagedCustomRO, '')); expectType( - await DataStore.delete(dummyInstance()) + await DataStore.delete(dummyInstance()), ); expectType( await DataStore.delete(dummyInstance(), c => - c.description.contains('something') - ) + c.description.contains('something'), + ), ); expectType( - await DataStore.delete(ManagedCustomRO, Predicates.ALL) + await DataStore.delete(ManagedCustomRO, Predicates.ALL), ); expectType( - await DataStore.delete(ManagedCustomRO, c => c.createdOn.le('2019')) + await DataStore.delete(ManagedCustomRO, c => c.createdOn.le('2019')), ); // Observe @@ -216,7 +216,7 @@ describe('Managed Identifier', () => { expectType(element); }); DataStore.observe(ManagedCustomRO, c => - c.description.beginsWith('something') + c.description.beginsWith('something'), ).subscribe(({ model, element }) => { expectType>(model); expectType(element); @@ -225,7 +225,7 @@ describe('Managed Identifier', () => { ({ model, element }) => { expectType>(model); expectType(element); - } + }, ); // Observe query @@ -233,14 +233,14 @@ describe('Managed Identifier', () => { expectType(items); }); DataStore.observeQuery(ManagedCustomRO, c => - c.description.notContains('something') + c.description.notContains('something'), ).subscribe(({ items }) => { expectType(items); }); DataStore.observeQuery( ManagedCustomRO, c => c.description.notContains('something'), - { sort: c => c.createdOn('ASCENDING') } + { sort: c => c.createdOn('ASCENDING') }, ).subscribe(({ items }) => { expectType(items); }); diff --git a/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/optionally-managed-identifier.test.tsx b/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/optionally-managed-identifier.test.tsx index 5c7e1192b34..00dd4a9c9e1 100644 --- a/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/optionally-managed-identifier.test.tsx +++ b/packages/datastore/__tests__/custom-pk-typings/model-init-mutable-model-typings/optionally-managed-identifier.test.tsx @@ -69,65 +69,65 @@ describe('Optionally Managed Identifier', () => { // Query expectType( - await DataStore.query(OptionallyManagedDefaultRO, 'someid') + await DataStore.query(OptionallyManagedDefaultRO, 'someid'), ); expectType( - await DataStore.query(OptionallyManagedDefaultRO, { id: 'someid' }) + await DataStore.query(OptionallyManagedDefaultRO, { id: 'someid' }), ); expectType( - await DataStore.query(OptionallyManagedDefaultRO) + await DataStore.query(OptionallyManagedDefaultRO), ); expectType( - await DataStore.query(OptionallyManagedDefaultRO, Predicates.ALL) + await DataStore.query(OptionallyManagedDefaultRO, Predicates.ALL), ); expectType( await DataStore.query(OptionallyManagedDefaultRO, c => - c.createdAt.ge('2019') - ) + c.createdAt.ge('2019'), + ), ); // Save expectType( - await DataStore.save(dummyInstance()) + await DataStore.save(dummyInstance()), ); expectType( await DataStore.save(dummyInstance(), c => - c.createdAt.ge('2019') - ) + c.createdAt.ge('2019'), + ), ); // Delete expectType( - await DataStore.delete(OptionallyManagedDefaultRO, '') + await DataStore.delete(OptionallyManagedDefaultRO, ''), ); expectType( - await DataStore.delete(dummyInstance()) + await DataStore.delete(dummyInstance()), ); expectType( await DataStore.delete(dummyInstance(), c => - c.description.contains('something') - ) + c.description.contains('something'), + ), ); expectType( - await DataStore.delete(OptionallyManagedDefaultRO, Predicates.ALL) + await DataStore.delete(OptionallyManagedDefaultRO, Predicates.ALL), ); expectType( await DataStore.delete(OptionallyManagedDefaultRO, c => - c.createdAt.le('2019') - ) + c.createdAt.le('2019'), + ), ); // Observe DataStore.observe(OptionallyManagedDefaultRO).subscribe( ({ model, element }) => { expectType>( - model + model, ); expectType(element); - } + }, ); DataStore.observe(OptionallyManagedDefaultRO, c => - c.description.beginsWith('something') + c.description.beginsWith('something'), ).subscribe(({ model, element }) => { expectType>(model); expectType(element); @@ -135,27 +135,27 @@ describe('Optionally Managed Identifier', () => { DataStore.observe(dummyInstance()).subscribe( ({ model, element }) => { expectType>( - model + model, ); expectType(element); - } + }, ); // Observe query DataStore.observeQuery(OptionallyManagedDefaultRO).subscribe( ({ items }) => { expectType(items); - } + }, ); DataStore.observeQuery(OptionallyManagedDefaultRO, c => - c.description.notContains('something') + c.description.notContains('something'), ).subscribe(({ items }) => { expectType(items); }); DataStore.observeQuery( OptionallyManagedDefaultRO, c => c.description.notContains('something'), - { sort: c => c.createdAt('ASCENDING') } + { sort: c => c.createdAt('ASCENDING') }, ).subscribe(({ items }) => { expectType(items); }); @@ -221,65 +221,65 @@ describe('Optionally Managed Identifier', () => { // Query expectType( - await DataStore.query(OptionallyManagedCustomRO, 'someid') + await DataStore.query(OptionallyManagedCustomRO, 'someid'), ); expectType( - await DataStore.query(OptionallyManagedCustomRO, { id: 'someid' }) + await DataStore.query(OptionallyManagedCustomRO, { id: 'someid' }), ); expectType( - await DataStore.query(OptionallyManagedCustomRO) + await DataStore.query(OptionallyManagedCustomRO), ); expectType( - await DataStore.query(OptionallyManagedCustomRO, Predicates.ALL) + await DataStore.query(OptionallyManagedCustomRO, Predicates.ALL), ); expectType( await DataStore.query(OptionallyManagedCustomRO, c => - c.createdOn.ge('2019') - ) + c.createdOn.ge('2019'), + ), ); // Save expectType( - await DataStore.save(dummyInstance()) + await DataStore.save(dummyInstance()), ); expectType( await DataStore.save(dummyInstance(), c => - c.createdOn.ge('2019') - ) + c.createdOn.ge('2019'), + ), ); // Delete expectType( - await DataStore.delete(OptionallyManagedCustomRO, '') + await DataStore.delete(OptionallyManagedCustomRO, ''), ); expectType( - await DataStore.delete(dummyInstance()) + await DataStore.delete(dummyInstance()), ); expectType( await DataStore.delete(dummyInstance(), c => - c.description.contains('something') - ) + c.description.contains('something'), + ), ); expectType( - await DataStore.delete(OptionallyManagedCustomRO, Predicates.ALL) + await DataStore.delete(OptionallyManagedCustomRO, Predicates.ALL), ); expectType( await DataStore.delete(OptionallyManagedCustomRO, c => - c.createdOn.le('2019') - ) + c.createdOn.le('2019'), + ), ); // Observe DataStore.observe(OptionallyManagedCustomRO).subscribe( ({ model, element }) => { expectType>( - model + model, ); expectType(element); - } + }, ); DataStore.observe(OptionallyManagedCustomRO, c => - c.description.beginsWith('something') + c.description.beginsWith('something'), ).subscribe(({ model, element }) => { expectType>(model); expectType(element); @@ -287,10 +287,10 @@ describe('Optionally Managed Identifier', () => { DataStore.observe(dummyInstance()).subscribe( ({ model, element }) => { expectType>( - model + model, ); expectType(element); - } + }, ); // Observe query @@ -298,14 +298,14 @@ describe('Optionally Managed Identifier', () => { expectType(items); }); DataStore.observeQuery(OptionallyManagedCustomRO, c => - c.description.notContains('something') + c.description.notContains('something'), ).subscribe(({ items }) => { expectType(items); }); DataStore.observeQuery( OptionallyManagedCustomRO, c => c.description.notContains('something'), - { sort: c => c.createdOn('ASCENDING') } + { sort: c => c.createdOn('ASCENDING') }, ).subscribe(({ items }) => { expectType(items); }); diff --git a/packages/datastore/__tests__/graphql.test.ts b/packages/datastore/__tests__/graphql.test.ts index db2e16d0d2b..262d370ca34 100644 --- a/packages/datastore/__tests__/graphql.test.ts +++ b/packages/datastore/__tests__/graphql.test.ts @@ -133,14 +133,14 @@ describe('DataStore GraphQL generation', () => { const [[, , query]] = buildGraphQLOperation( namespace, postModelDefinition, - graphQLOpType + graphQLOpType, ); // why does it think `expectedGraphQL` is `string[] | undefined`? expect(print(parse(query))).toStrictEqual( - print(parse(expectedGraphQL as any)) + print(parse(expectedGraphQL as any)), ); - } + }, ); test.each([ @@ -188,11 +188,11 @@ describe('DataStore GraphQL generation', () => { postModelDefinition, transformerMutationType, false, - '' + '', ); expect(print(parse(query))).toStrictEqual(print(parse(expectedGraphQL))); - } + }, ); }); diff --git a/packages/datastore/__tests__/helpers/UpdateSequenceHarness.ts b/packages/datastore/__tests__/helpers/UpdateSequenceHarness.ts index 6903653ded5..e836016522e 100644 --- a/packages/datastore/__tests__/helpers/UpdateSequenceHarness.ts +++ b/packages/datastore/__tests__/helpers/UpdateSequenceHarness.ts @@ -166,7 +166,7 @@ export class UpdateSequenceHarness { subscriptionLogs(attributes: string[] = ['title', '_version']) { return this.subscriptionLog.map(post => - attributes.map(attribute => post[attribute]) + attributes.map(attribute => post[attribute]), ); } @@ -207,7 +207,7 @@ export class UpdateSequenceHarness { }); this.subscriptionLogSubscription = this.datastoreFake.DataStore.observe( - this.datastoreFake.Post + this.datastoreFake.Post, ).subscribe(({ opType, element }) => { if (opType === 'UPDATE') { this.subscriptionLog.push(element); @@ -254,7 +254,7 @@ export class UpdateSequenceHarness { update: number; updateSubscriptionMessage: number; updateError?: number; - } + }, ) { let updateCount: number; let updateSubscriptionMessageCount: number; @@ -290,10 +290,10 @@ export class UpdateSequenceHarness { */ async createPostHarness( args: ConstructorParameters[0], - settleOutbox: boolean = true + settleOutbox: boolean = true, ) { const original = await this.datastoreFake.DataStore.save( - new this.datastoreFake.Post(args) + new this.datastoreFake.Post(args), ); // We set this to `false` when we want to test updating a record that is still in the outbox. if (settleOutbox) { @@ -343,7 +343,7 @@ export class UpdateSequenceHarness { authToken: undefined, }, // For now we always ignore latency for external mutations. This could be a param if needed. - true + true, ); } @@ -358,13 +358,13 @@ export class UpdateSequenceHarness { } const retrieved = await this.datastoreFake.DataStore.query( this.datastoreFake.Post, - postId + postId, ); if (retrieved) { await this.datastoreFake.DataStore.save( this.datastoreFake.Post.copyOf(retrieved, updated => { updated.title = updatedTitle; - }) + }), ); } if (this.isSettledAfterRevisions) { diff --git a/packages/datastore/__tests__/helpers/datastoreFactory.ts b/packages/datastore/__tests__/helpers/datastoreFactory.ts index b4992d508b2..871d27d060f 100644 --- a/packages/datastore/__tests__/helpers/datastoreFactory.ts +++ b/packages/datastore/__tests__/helpers/datastoreFactory.ts @@ -144,7 +144,7 @@ export function getDataStore({ connectionState: ConnectionState.ConnectionDisrupted, }, }, - 'PubSub' + 'PubSub', ); if (log) console.log('done simulated disruption.'); @@ -173,7 +173,7 @@ export function getDataStore({ connectionState: ConnectionState.Connecting, }, }, - 'PubSub' + 'PubSub', ); Hub.dispatch( 'api', @@ -183,7 +183,7 @@ export function getDataStore({ connectionState: ConnectionState.Connected, }, }, - 'PubSub' + 'PubSub', ); if (log) console.log('done simulated disruption end.'); } diff --git a/packages/datastore/__tests__/helpers/fakes/graphqlService.ts b/packages/datastore/__tests__/helpers/fakes/graphqlService.ts index 1852d24849a..72d20c17872 100644 --- a/packages/datastore/__tests__/helpers/fakes/graphqlService.ts +++ b/packages/datastore/__tests__/helpers/fakes/graphqlService.ts @@ -101,7 +101,7 @@ export class FakeGraphQLService { */ public intercept: (request: GraphQLRequest, next: () => any) => any = ( request, - next + next, ) => next(); /** @@ -116,7 +116,7 @@ export class FakeGraphQLService { constructor( public schema: Schema, - mergeStrategy: MergeStrategy = 'Automerge' + mergeStrategy: MergeStrategy = 'Automerge', ) { for (const model of Object.values(schema.models)) { this.tables.set(model.name, new Map()); @@ -163,7 +163,7 @@ export class FakeGraphQLService { * "Materialized" jitter from -jitter to +jitter. */ const jitter = Math.floor( - Math.random() * this.latencies.jitter * 2 - this.latencies.jitter + Math.random() * this.latencies.jitter * 2 - this.latencies.jitter, ); const jitteredMs = Math.max(ms + jitter, 0); return pause(jitteredMs); @@ -176,7 +176,7 @@ export class FakeGraphQLService { */ private findSingularName(pluralName: string): string { const model = Object.values(this.schema.models).find( - m => m.pluralName === pluralName + m => m.pluralName === pluralName, ); if (!model) throw new Error(`No model found for plural name ${pluralName}`); return model.name; @@ -192,7 +192,7 @@ export class FakeGraphQLService { const selections = q.selectionSet.selections[0]; const selection = selections.name.value; const type = selection.match( - /^(create|update|delete|sync|get|list|onCreate|onUpdate|onDelete)(\w+)$/ + /^(create|update|delete|sync|get|list|onCreate|onUpdate|onDelete)(\w+)$/, )[1]; let table; @@ -200,20 +200,20 @@ export class FakeGraphQLService { if (type === 'sync' || type === 'list') { // e.g. `Models` const pluralName = selection.match( - /^(create|sync|get|list)([A-Za-z]+)$/ + /^(create|sync|get|list)([A-Za-z]+)$/, )[2]; table = this.findSingularName(pluralName); } else { table = selection.match( - /^(create|update|delete|sync|get|list|onCreate|onUpdate|onDelete)(\w+)$/ + /^(create|update|delete|sync|get|list|onCreate|onUpdate|onDelete)(\w+)$/, )[2]; } const items = operation === 'query' ? selections?.selectionSet?.selections[0]?.selectionSet?.selections?.map( - i => i.name.value - ) + i => i.name.value, + ) : selections?.selectionSet?.selections?.map(i => i.name.value); return { operation, name, selection, type, table, items }; @@ -229,7 +229,7 @@ export class FakeGraphQLService { if (!condition) { this.log( 'checking satisfiesCondition', - 'matches all for `null` conditions' + 'matches all for `null` conditions', ); return true; } @@ -237,7 +237,7 @@ export class FakeGraphQLService { const modelDefinition = this.schema.models[tableName]; const predicate = ModelPredicateCreator.createFromAST( modelDefinition, - condition + condition, ); const isMatch = validatePredicate(item, 'and', [ ModelPredicateCreator.getPredicates(predicate)!, @@ -245,7 +245,7 @@ export class FakeGraphQLService { this.log('satisfiesCondition result', { effectivePredicate: JSON.stringify( - ModelPredicateCreator.getPredicates(predicate) + ModelPredicateCreator.getPredicates(predicate), ), isMatch, }); @@ -346,7 +346,7 @@ export class FakeGraphQLService { private makeExtraFieldInputError(tableName, operation, fields) { const properOperationName = `${operation[0].toUpperCase()}${operation.substring( - 1 + 1, )}`; const inputName = `${properOperationName}${tableName}Input`; return { @@ -401,7 +401,7 @@ export class FakeGraphQLService { private writeableFields(tableName) { const def = this.tableDefinitions.get(tableName)!; return Object.keys(def.fields).filter( - field => !def.fields[field]?.isReadOnly + field => !def.fields[field]?.isReadOnly, ); } @@ -428,13 +428,13 @@ export class FakeGraphQLService { case 'update': const unexpectedFields = this.identifyExtraValues( [...writeableFields, '_version'], - Object.keys(record) + Object.keys(record), ); if (unexpectedFields.length > 0) { error = this.makeExtraFieldInputError( tableName, operation, - unexpectedFields + unexpectedFields, ); } for (const ownerField of this.ownerFields(tableName)) { @@ -464,7 +464,7 @@ export class FakeGraphQLService { private populatedFields(record) { return Object.fromEntries( - Object.entries(record).filter(([key, value]) => value !== undefined) + Object.entries(record).filter(([key, value]) => value !== undefined), ); } @@ -547,7 +547,7 @@ export class FakeGraphQLService { type, data, selection, - ignoreLatency = false + ignoreLatency = false, ) { const deliveryPromise = new Promise(async resolve => { !ignoreLatency && (await this.jitteredPause(this.latencies.subscriber)); @@ -600,7 +600,7 @@ export class FakeGraphQLService { public request( { query, variables, authMode, authToken }, - ignoreLatency = false + ignoreLatency = false, ) { this.log('API Request', { query, @@ -655,7 +655,7 @@ export class FakeGraphQLService { data = { [selection]: { items: [...table.values()].filter(item => - this.satisfiesCondition(tableName, item, variables.filter) + this.satisfiesCondition(tableName, item, variables.filter), ), nextToken: null, startedAt: new Date().getTime(), @@ -782,7 +782,7 @@ export class FakeGraphQLService { type, data, selection, - ignoreLatency + ignoreLatency, ); } else { if (!Array.isArray(this.errors.get(type))) { diff --git a/packages/datastore/__tests__/helpers/schemas/default.ts b/packages/datastore/__tests__/helpers/schemas/default.ts index f54f9fa53c1..92b87262c3b 100644 --- a/packages/datastore/__tests__/helpers/schemas/default.ts +++ b/packages/datastore/__tests__/helpers/schemas/default.ts @@ -25,7 +25,7 @@ export declare class Model { static copyOf( src: Model, - mutator: (draft: MutableModel) => void | Model + mutator: (draft: MutableModel) => void | Model, ): Model; } @@ -54,7 +54,7 @@ export declare class Blog { static copyOf( src: Blog, - mutator: (draft: MutableModel) => void | Blog + mutator: (draft: MutableModel) => void | Blog, ): Blog; } @@ -70,7 +70,7 @@ export declare class Post { static copyOf( src: Post, - mutator: (draft: MutableModel) => void | Post + mutator: (draft: MutableModel) => void | Post, ): Post; } @@ -84,7 +84,7 @@ export declare class Comment { static copyOf( src: Comment, - mutator: (draft: MutableModel) => void | Comment + mutator: (draft: MutableModel) => void | Comment, ): Comment; } export declare class PostUni { @@ -98,7 +98,7 @@ export declare class PostUni { static copyOf( src: Post, - mutator: (draft: MutableModel) => void | Post + mutator: (draft: MutableModel) => void | Post, ): Post; } @@ -111,7 +111,7 @@ export declare class CommentUni { static copyOf( src: Comment, - mutator: (draft: MutableModel) => void | Comment + mutator: (draft: MutableModel) => void | Comment, ): Comment; } @@ -125,7 +125,7 @@ export declare class User { static copyOf( src: User, - mutator: (draft: MutableModel) => void | User + mutator: (draft: MutableModel) => void | User, ): User; } export declare class Profile { @@ -137,7 +137,7 @@ export declare class Profile { static copyOf( src: Profile, - mutator: (draft: MutableModel) => void | Profile + mutator: (draft: MutableModel) => void | Profile, ): Profile; } @@ -152,7 +152,7 @@ export declare class PostComposite { static copyOf( src: PostComposite, - mutator: (draft: MutableModel) => void | PostComposite + mutator: (draft: MutableModel) => void | PostComposite, ): PostComposite; } @@ -173,7 +173,7 @@ export declare class PostCustomPK { static copyOf( src: PostCustomPK, - mutator: (draft: MutableModel) => void | PostCustomPK + mutator: (draft: MutableModel) => void | PostCustomPK, ): PostCustomPK; } @@ -190,7 +190,7 @@ export declare class PostCustomPKSort { static copyOf( src: PostCustomPKSort, - mutator: (draft: MutableModel) => void | PostCustomPKSort + mutator: (draft: MutableModel) => void | PostCustomPKSort, ): PostCustomPKSort; } @@ -209,8 +209,8 @@ export declare class PostCustomPKComposite { static copyOf( src: PostCustomPKComposite, mutator: ( - draft: MutableModel - ) => void | PostCustomPKComposite + draft: MutableModel, + ) => void | PostCustomPKComposite, ): PostCustomPKComposite; } @@ -227,8 +227,8 @@ export declare class BasicModel { static copyOf( source: BasicModel, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): BasicModel; } @@ -245,8 +245,8 @@ export declare class BasicModelWritableTS { static copyOf( source: BasicModelWritableTS, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): BasicModelWritableTS; } @@ -263,8 +263,8 @@ export declare class BasicModelRequiredTS { static copyOf( source: BasicModelRequiredTS, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): BasicModelRequiredTS; } @@ -282,8 +282,8 @@ export declare class HasOneParent { static copyOf( source: HasOneParent, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): HasOneParent; } @@ -300,8 +300,8 @@ export declare class HasOneChild { static copyOf( source: HasOneChild, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): HasOneChild; } @@ -319,7 +319,7 @@ export declare class MtmLeft { constructor(init: ModelInit); static copyOf( source: MtmLeft, - mutator: (draft: MutableModel) => MutableModel | void + mutator: (draft: MutableModel) => MutableModel | void, ): MtmLeft; } @@ -337,7 +337,7 @@ export declare class MtmRight { constructor(init: ModelInit); static copyOf( source: MtmRight, - mutator: (draft: MutableModel) => MutableModel | void + mutator: (draft: MutableModel) => MutableModel | void, ): MtmRight; } @@ -357,7 +357,7 @@ export declare class MtmJoin { constructor(init: ModelInit); static copyOf( source: MtmJoin, - mutator: (draft: MutableModel) => MutableModel | void + mutator: (draft: MutableModel) => MutableModel | void, ): MtmJoin; } @@ -375,8 +375,8 @@ export declare class DefaultPKParent { static copyOf( source: DefaultPKParent, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): DefaultPKParent; } @@ -395,8 +395,8 @@ export declare class DefaultPKChild { static copyOf( source: DefaultPKChild, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): DefaultPKChild; } @@ -410,8 +410,8 @@ export declare class DefaultPKHasOneParent { static copyOf( source: DefaultPKHasOneParent, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): DefaultPKHasOneParent; } @@ -425,8 +425,8 @@ export declare class DefaultPKHasOneChild { static copyOf( source: DefaultPKHasOneChild, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): DefaultPKHasOneChild; } @@ -450,8 +450,8 @@ export declare class CompositePKParent { static copyOf( source: CompositePKParent, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): CompositePKParent; } @@ -471,8 +471,8 @@ export declare class CompositePKChild { static copyOf( source: CompositePKChild, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): CompositePKChild; } @@ -492,8 +492,8 @@ export declare class ImplicitChild { static copyOf( source: ImplicitChild, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): ImplicitChild; } @@ -516,8 +516,8 @@ export declare class StrangeExplicitChild { static copyOf( source: StrangeExplicitChild, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): StrangeExplicitChild; } @@ -536,8 +536,8 @@ export declare class ChildSansBelongsTo { static copyOf( source: ChildSansBelongsTo, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): ChildSansBelongsTo; } @@ -563,8 +563,8 @@ export declare class LegacyJSONBlog { static copyOf( source: LegacyJSONBlog, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): LegacyJSONBlog; } @@ -579,8 +579,8 @@ export declare class LegacyJSONPost { static copyOf( source: LegacyJSONPost, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): LegacyJSONPost; } @@ -594,8 +594,8 @@ export declare class LegacyJSONComment { static copyOf( source: LegacyJSONComment, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): LegacyJSONComment; } @@ -609,7 +609,7 @@ export declare class ModelWithBoolean { static copyOf( src: ModelWithBoolean, - mutator: (draft: MutableModel) => void | ModelWithBoolean + mutator: (draft: MutableModel) => void | ModelWithBoolean, ): ModelWithBoolean; } @@ -627,8 +627,8 @@ export declare class ModelWithExplicitOwner { static copyOf( source: ModelWithExplicitOwner, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): ModelWithExplicitOwner; } @@ -646,8 +646,8 @@ export declare class ModelWithExplicitCustomOwner { static copyOf( source: ModelWithExplicitCustomOwner, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): ModelWithExplicitCustomOwner; } @@ -666,8 +666,8 @@ export declare class ModelWithMultipleCustomOwner { static copyOf( source: ModelWithMultipleCustomOwner, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): ModelWithMultipleCustomOwner; } @@ -683,7 +683,7 @@ export declare class ModelWithIndexes { static copyOf( src: ModelWithIndexes, - mutator: (draft: MutableModel) => void | ModelWithIndexes + mutator: (draft: MutableModel) => void | ModelWithIndexes, ): ModelWithIndexes; } diff --git a/packages/datastore/__tests__/helpers/schemas/typeOnlyModels.ts b/packages/datastore/__tests__/helpers/schemas/typeOnlyModels.ts index f310a98bcd3..13cf177f00a 100644 --- a/packages/datastore/__tests__/helpers/schemas/typeOnlyModels.ts +++ b/packages/datastore/__tests__/helpers/schemas/typeOnlyModels.ts @@ -49,8 +49,8 @@ export class LegacyCustomRO { static copyOf( source: LegacyCustomRO, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): LegacyCustomRO { return (undefined); } @@ -70,8 +70,8 @@ export class LegacyDefaultRO { static copyOf( source: LegacyDefaultRO, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): LegacyDefaultRO { return (undefined); } @@ -87,8 +87,8 @@ export class LegacyNoMetadata { static copyOf( source: LegacyNoMetadata, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): LegacyNoMetadata { return (undefined); } @@ -112,8 +112,8 @@ export class ManagedCustomRO { static copyOf( source: ManagedCustomRO, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): ManagedCustomRO { return (undefined); } @@ -133,8 +133,8 @@ export class ManagedDefaultRO { static copyOf( source: ManagedDefaultRO, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): ManagedDefaultRO { return (undefined); } @@ -158,8 +158,8 @@ export class OptionallyManagedCustomRO { static copyOf( source: OptionallyManagedCustomRO, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): OptionallyManagedCustomRO { return (undefined); } @@ -179,8 +179,8 @@ export class OptionallyManagedDefaultRO { static copyOf( source: OptionallyManagedDefaultRO, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): OptionallyManagedDefaultRO { return (undefined); } @@ -205,8 +205,8 @@ export class CompositeCustomRO { static copyOf( source: CompositeCustomRO, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): CompositeCustomRO { return (undefined); } @@ -227,8 +227,8 @@ export class CompositeDefaultRO { static copyOf( source: CompositeDefaultRO, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): CompositeDefaultRO { return (undefined); } @@ -252,8 +252,8 @@ export class CustomIdentifierCustomRO { static copyOf( source: CustomIdentifierCustomRO, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): CustomIdentifierCustomRO { return (undefined); } @@ -273,8 +273,8 @@ export class CustomIdentifierDefaultRO { static copyOf( source: CustomIdentifierDefaultRO, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): CustomIdentifierDefaultRO { return (undefined); } @@ -293,8 +293,8 @@ export class CustomIdentifierNoRO { static copyOf( source: CustomIdentifierNoRO, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): CustomIdentifierDefaultRO { return undefined!; } diff --git a/packages/datastore/__tests__/helpers/util.ts b/packages/datastore/__tests__/helpers/util.ts index 7ad45e67b48..ac34b9da84d 100644 --- a/packages/datastore/__tests__/helpers/util.ts +++ b/packages/datastore/__tests__/helpers/util.ts @@ -47,7 +47,7 @@ export function expectMutation(mutation, values) { ]; if (errors.length > 0) { throw new Error( - `Bad mutation: ${JSON.stringify(data, null, 2)}\n${errors.join('\n')}` + `Bad mutation: ${JSON.stringify(data, null, 2)}\n${errors.join('\n')}`, ); } } @@ -68,7 +68,7 @@ export function dummyInstance(): T { */ export function errorsFrom( data: T, - matchers: Record + matchers: Record, ) { return Object.entries(matchers).reduce((errors, [property, matcher]) => { const value = data[property]; @@ -82,7 +82,7 @@ export function errorsFrom( ) ) { errors.push( - `Property '${property}' value "${value}" does not match "${matcher}"` as never + `Property '${property}' value "${value}" does not match "${matcher}"` as never, ); } return errors; @@ -310,7 +310,7 @@ export async function expectIsolation( cycle: number; }) => Promise, cycles = 5, - focusedLogging = false + focusedLogging = false, ) { try { warpTime(); @@ -351,20 +351,20 @@ export async function expectIsolation( // act try { log( - `start cycle: "${expect.getState().currentTestName}" cycle ${cycle}` + `start cycle: "${expect.getState().currentTestName}" cycle ${cycle}`, ); await script({ DataStore, Post, cycle }); log( - `end cycle: "${expect.getState().currentTestName}" cycle ${cycle}` + `end cycle: "${expect.getState().currentTestName}" cycle ${cycle}`, ); } finally { // clean up log( - `before clear: "${expect.getState().currentTestName}" cycle ${cycle}` + `before clear: "${expect.getState().currentTestName}" cycle ${cycle}`, ); await DataStore.clear(); log( - `after clear: "${expect.getState().currentTestName}" cycle ${cycle}` + `after clear: "${expect.getState().currentTestName}" cycle ${cycle}`, ); } @@ -506,7 +506,7 @@ export async function waitForExpectModelUpdateGraphqlEventCount({ ({ operation, type, tableName }) => operation === 'mutation' && type === 'update' && - tableName === modelName + tableName === modelName, ).length; // Ensure the service has received all expected requests: @@ -522,7 +522,7 @@ export async function waitForExpectModelUpdateGraphqlEventCount({ graphqlService.subscriptionMessagesSent.filter( ([observerMessageName, message]) => { return observerMessageName === `onUpdate${modelName}`; - } + }, ).length; const allSubscriptionsSent = lastObservedSubscriptionCount === @@ -547,14 +547,14 @@ export async function waitForExpectModelUpdateGraphqlEventCount({ return true; } else { throw new Error( - 'Fake GraphQL Service did not receive and/or process all updates and/or subscriptions' + 'Fake GraphQL Service did not receive and/or process all updates and/or subscriptions', ); } }, [null], // Only retry up to 5 seconds 5_000, - undefined + undefined, ); } catch { // If the expected call count isn't observed after 5 seconds, raise an error describing the discrepency @@ -565,7 +565,7 @@ export async function waitForExpectModelUpdateGraphqlEventCount({ lastObservedSubscriptionCount ?? 'unknown' }. Expected ${expectedUpdateErrorCount} update errors for ${modelName}, but received ${ lastObservedUpdateErrorCount ?? 'unknown' - }` + }`, ); } } diff --git a/packages/datastore/__tests__/indexeddb.test.ts b/packages/datastore/__tests__/indexeddb.test.ts index f56740420cd..be333a5809f 100644 --- a/packages/datastore/__tests__/indexeddb.test.ts +++ b/packages/datastore/__tests__/indexeddb.test.ts @@ -49,19 +49,19 @@ describe('Indexed db storage test', () => { new Blog({ name: 'Avatar: Last Airbender', owner, - }) + }), ); blog2 = await DataStore.save( new Blog({ name: 'blog2', owner: owner2, - }) + }), ); blog3 = await DataStore.save( new Blog({ name: 'Avatar 101', owner: await DataStore.save(new BlogOwner({ name: 'owner 3' })), - }) + }), ); }); @@ -97,10 +97,10 @@ describe('Indexed db storage test', () => { // TODO: better way to get this const commentStore = (db)._rawDatabase.rawObjectStores.get( - `${USER}_Comment` + `${USER}_Comment`, ); const postAuthorStore = (db)._rawDatabase.rawObjectStores.get( - `${USER}_PostAuthorJoin` + `${USER}_PostAuthorJoin`, ); expect(commentStore.rawIndexes.has('byPk')).toBe(true); // checks byPkIndex @@ -123,7 +123,7 @@ describe('Indexed db storage test', () => { expect(get1).toBeDefined(); expect([...Object.keys(blog).sort(), 'blogOwnerId']).toEqual( - expect.arrayContaining(Object.keys(get1).sort()) + expect.arrayContaining(Object.keys(get1).sort()), ); expect(get1['blogOwnerId']).toBe(owner.id); @@ -135,7 +135,7 @@ describe('Indexed db storage test', () => { .get([owner.id]); expect([...Object.keys(owner)].sort()).toEqual( - expect.arrayContaining(Object.keys(get2).sort()) + expect.arrayContaining(Object.keys(get2).sort()), ); await DataStore.save(blog2); @@ -146,7 +146,7 @@ describe('Indexed db storage test', () => { .get([blog2.id]); expect([...Object.keys(blog2).sort(), 'blogOwnerId']).toEqual( - expect.arrayContaining(Object.keys(get3).sort()) + expect.arrayContaining(Object.keys(get3).sort()), ); }); @@ -186,7 +186,7 @@ describe('Indexed db storage test', () => { new Post({ title: 'Avatar', blog, - }) + }), ); const c1 = new Comment({ content: 'comment 1', post: p }); await DataStore.save(c1); @@ -197,7 +197,7 @@ describe('Indexed db storage test', () => { .get([c1.id]); expect([...Object.keys(c1), 'commentPostId'].sort()).toEqual( - expect.arrayContaining(Object.keys(getComment).sort()) + expect.arrayContaining(Object.keys(getComment).sort()), ); const checkIndex = await db @@ -214,7 +214,7 @@ describe('Indexed db storage test', () => { new Post({ title: 'Avatar', blog, - }) + }), ); const getPost = await db @@ -356,28 +356,28 @@ describe('Indexed db storage test', () => { const post = await DataStore.save( new Post({ title: 'some title', - }) + }), ); const comment1 = await DataStore.save( new Comment({ content: 'some really impressive comment', post, - }) + }), ); const comment2 = await DataStore.save( new Comment({ content: 'a less impressive comment', post, - }) + }), ); const comment3 = await DataStore.save( new Comment({ content: 'just a regular comment', post, - }) + }), ); const queriedPost = await DataStore.query(Post, post.id); @@ -400,19 +400,19 @@ describe('Indexed db storage test', () => { new ForumEditorJoin({ forum: f1 as any, editor: e1 as any, - }) + }), ); const f1e2 = await DataStore.save( new ForumEditorJoin({ forum: f1 as any, editor: e2 as any, - }) + }), ); const f2e2 = await DataStore.save( new ForumEditorJoin({ forum: f2 as any, editor: e2 as any, - }) + }), ); const q1 = (await DataStore.query(Forum, f1.id))!; @@ -468,10 +468,10 @@ describe('Indexed db storage test', () => { await DataStore.save(album1); await DataStore.save( - new Song({ name: 'Put you on Game', songID: album1.id }) + new Song({ name: 'Put you on Game', songID: album1.id }), ); await DataStore.save( - new Song({ name: 'Streets on Fire', songID: album1.id }) + new Song({ name: 'Streets on Fire', songID: album1.id }), ); await DataStore.save(new Song({ name: 'Superstar', songID: album1.id })); @@ -518,7 +518,7 @@ describe('Indexed db storage test', () => { editor: f2 as any, }); }).toThrow( - 'Value passed to ForumEditorJoin.editor is not an instance of Editor' + 'Value passed to ForumEditorJoin.editor is not an instance of Editor', ); }); @@ -597,7 +597,7 @@ describe('Indexed db storage test', () => { .firstName(SortDirection.ASCENDING) .lastName(SortDirection.ASCENDING) .username(SortDirection.ASCENDING), - } + }, ); expect(sortedPersons[0].username).toEqual('johnsnow'); @@ -612,22 +612,22 @@ describe('Indexed db storage test', () => { const owner = await DataStore.save( new BlogOwner({ name: "yep. doesn't matter", - }) + }), ); const blog = await DataStore.save( - new Blog({ name: 'Avatar, the last whatever', owner }) + new Blog({ name: 'Avatar, the last whatever', owner }), ); const decoyOwner = await DataStore.save( - new BlogOwner({ name: 'another one' }) + new BlogOwner({ name: 'another one' }), ); const decoyBlog = await DataStore.save( new Blog({ name: 'this one should still exist later', owner: decoyOwner, - }) + }), ); await DataStore.delete(Blog, blog.id); @@ -856,7 +856,7 @@ describe('DB versions migration', () => { // PostMetadata, // Nested, ].map(model => `${USER}_${model.name}`), - ].sort() + ].sort(), ); for (const storeName of db.objectStoreNames) { diff --git a/packages/datastore/__tests__/indexeddb.upgrade.test.ts b/packages/datastore/__tests__/indexeddb.upgrade.test.ts index 8f1827f9d77..a6a434ca37c 100644 --- a/packages/datastore/__tests__/indexeddb.upgrade.test.ts +++ b/packages/datastore/__tests__/indexeddb.upgrade.test.ts @@ -61,7 +61,7 @@ declare class BlogModel { constructor(init: ModelInit); static copyOf( source: BlogModel, - mutator: (draft: MutableModel) => MutableModel | void + mutator: (draft: MutableModel) => MutableModel | void, ): BlogModel; } @@ -92,7 +92,7 @@ describe('DB versions migration with destructive schema change', () => { const blogRes = await DataStore.query(Blog); const expectedCount = v1Data.data.tables.find( - t => t.name === 'user_Blog' + t => t.name === 'user_Blog', ).rowCount; expect(blogRes.length).toEqual(expectedCount); diff --git a/packages/datastore/__tests__/model.ts b/packages/datastore/__tests__/model.ts index d91a7149bd8..9d868357fc1 100644 --- a/packages/datastore/__tests__/model.ts +++ b/packages/datastore/__tests__/model.ts @@ -16,7 +16,7 @@ declare class BlogModel { constructor(init: ModelInit); static copyOf( source: BlogModel, - mutator: (draft: MutableModel) => MutableModel | void + mutator: (draft: MutableModel) => MutableModel | void, ): BlogModel; } @@ -31,7 +31,7 @@ declare class PostModel { constructor(init: ModelInit); static copyOf( source: PostModel, - mutator: (draft: MutableModel) => MutableModel | void + mutator: (draft: MutableModel) => MutableModel | void, ): PostModel; } @@ -44,8 +44,8 @@ declare class ProjectModel { static copyOf( source: ProjectModel, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): ProjectModel; } @@ -55,7 +55,7 @@ declare class TeamModel { constructor(init: ModelInit); static copyOf( source: TeamModel, - mutator: (draft: MutableModel) => MutableModel | void + mutator: (draft: MutableModel) => MutableModel | void, ): TeamModel; } @@ -79,8 +79,8 @@ declare class CommentModel { static copyOf( source: CommentModel, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): CommentModel; } @@ -92,8 +92,8 @@ declare class PostAuthorJoinModel { static copyOf( source: PostAuthorJoinModel, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): PostAuthorJoinModel; } @@ -105,8 +105,8 @@ declare class ForumModel { static copyOf( source: ForumModel, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): ForumModel; } @@ -118,8 +118,8 @@ declare class ForumEditorJoinModel { static copyOf( source: ForumEditorJoinModel, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): ForumEditorJoinModel; } @@ -131,8 +131,8 @@ declare class EditorModel { static copyOf( source: EditorModel, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): EditorModel; } @@ -164,8 +164,8 @@ declare class AuthorModel { static copyOf( source: AuthorModel, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): AuthorModel; } @@ -177,8 +177,8 @@ declare class BlogOwnerModel { static copyOf( source: BlogOwnerModel, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): BlogOwnerModel; } @@ -192,8 +192,8 @@ declare class PersonModel { static copyOf( source: PersonModel, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): PersonModel; } @@ -206,7 +206,7 @@ declare class SongModel { constructor(init: ModelInit); static copyOf( source: SongModel, - mutator: (draft: MutableModel) => MutableModel | void + mutator: (draft: MutableModel) => MutableModel | void, ): SongModel; } @@ -220,8 +220,8 @@ declare class AlbumModel { static copyOf( source: AlbumModel, mutator: ( - draft: MutableModel - ) => MutableModel | void + draft: MutableModel, + ) => MutableModel | void, ): AlbumModel; } diff --git a/packages/datastore/__tests__/mutation.test.ts b/packages/datastore/__tests__/mutation.test.ts index 47e72b78927..8130fd382e0 100644 --- a/packages/datastore/__tests__/mutation.test.ts +++ b/packages/datastore/__tests__/mutation.test.ts @@ -66,7 +66,7 @@ describe('Jittered backoff', () => { const COUNT = 13; const backoffs = [...Array(COUNT)].map((v, i) => - safeJitteredBackoff(i) + safeJitteredBackoff(i), ) as (number | boolean)[]; const isExpectedValue = (value, attempt) => { @@ -75,7 +75,7 @@ describe('Jittered backoff', () => { if (lowerLimit < 2 ** 12 * 100) { console.log( - `attempt ${attempt} (${value}) should be between ${lowerLimit} and ${upperLimit} inclusively.` + `attempt ${attempt} (${value}) should be between ${lowerLimit} and ${upperLimit} inclusively.`, ); return value >= lowerLimit && value <= upperLimit; } else { @@ -98,7 +98,7 @@ describe('Jittered backoff', () => { const COUNT = 1000; const backoffs = [...Array(COUNT)].map((v, i) => - safeJitteredBackoff(i, [], new Error('Network Error')) + safeJitteredBackoff(i, [], new Error('Network Error')), ) as (number | boolean)[]; backoffs.forEach(v => { @@ -138,14 +138,14 @@ describe('MutationProcessor', () => { expect(mockRetry.mock.results).toHaveLength(1); await expect(mockRetry.mock.results[0].value).rejects.toEqual( - new Error('Network Error') + new Error('Network Error'), ); expect(mutationProcessorSpy).toHaveBeenCalled(); // MutationProcessor.resume exited successfully, i.e., did not throw await expect(mutationProcessorSpy.mock.results[0].value).resolves.toEqual( - undefined + undefined, ); }); }); @@ -165,7 +165,7 @@ describe('MutationProcessor', () => { 'PostCustomPK', 'Delete', data, - '{}' + '{}', ); expect(input.postId).toEqual('100'); @@ -187,7 +187,7 @@ describe('MutationProcessor', () => { 'PostCustomPKSort', 'Delete', data, - '{}' + '{}', ); expect(input.id).toEqual('abcdef'); @@ -205,18 +205,18 @@ describe('MutationProcessor', () => { }), expect.objectContaining({ url: new URL( - 'https://xxxxxxxxxxxxxxxxxxxxxx.appsync-api.us-west-2.amazonaws.com/graphql' + 'https://xxxxxxxxxxxxxxxxxxxxxx.appsync-api.us-west-2.amazonaws.com/graphql', ), options: expect.objectContaining({ headers: expect.objectContaining({ 'x-amz-user-agent': getAmplifyUserAgent( - datastoreUserAgentDetails + datastoreUserAgentDetails, ), }), signingServiceInfo: undefined, withCredentials: undefined, }), - }) + }), ); }); }); @@ -258,7 +258,7 @@ describe('error handler', () => { operation: 'Create', process: 'mutate', errorType: 'BadRecord', - }) + }), ); }); @@ -275,7 +275,7 @@ describe('error handler', () => { operation: 'Create', process: 'mutate', errorType: 'Transient', - }) + }), ); }); @@ -293,7 +293,7 @@ describe('error handler', () => { operation: 'Create', process: 'mutate', errorType: 'Transient', - }) + }), ); }); @@ -312,7 +312,7 @@ describe('error handler', () => { operation: 'Create', process: 'mutate', errorType: 'Unauthorized', - }) + }), ); }); }); @@ -387,7 +387,7 @@ async function instantiateMutationProcessor({ () => null, errorHandler, () => null as any, - {} as any + {} as any, ); (mutationProcessor as any).observer = true; @@ -412,7 +412,7 @@ async function createMutationEvent(model, opType): Promise { model, {}, MutationEventConstructor, - modelInstanceCreator + modelInstanceCreator, ); } diff --git a/packages/datastore/__tests__/outbox.test.ts b/packages/datastore/__tests__/outbox.test.ts index 5237bd8e4b3..20cf7a46efc 100644 --- a/packages/datastore/__tests__/outbox.test.ts +++ b/packages/datastore/__tests__/outbox.test.ts @@ -33,7 +33,7 @@ let Model: PersistentModelConstructor; const schema: InternalSchema = internalTestSchema(); const getModelDefinition = ( - modelConstructor: PersistentModelConstructor + modelConstructor: PersistentModelConstructor, ): SchemaModel => { const modelDefinition = schema.namespaces[USER].models[modelConstructor.name]; return modelDefinition; @@ -82,7 +82,7 @@ describe('Outbox tests', () => { await processMutationResponse( s, response, - TransformerMutationType.CREATE + TransformerMutationType.CREATE, ); head = await outbox.peek(s); @@ -135,7 +135,7 @@ describe('Outbox tests', () => { const mutationsForModel = await outbox.getForModel( s, last, - modelDefinition + modelDefinition, ); expect(mutationsForModel.length).toEqual(1); }); @@ -162,7 +162,7 @@ describe('Outbox tests', () => { const mutationsForModel = await outbox.getForModel( Storage, last, - modelDefinition + modelDefinition, ); expect(mutationsForModel.length).toEqual(2); @@ -188,7 +188,7 @@ describe('Outbox tests', () => { await processMutationResponse( s, response, - TransformerMutationType.UPDATE + TransformerMutationType.UPDATE, ); const inProgress = await outbox.peek(s); @@ -211,7 +211,7 @@ describe('Outbox tests', () => { await processMutationResponse( s, response2, - TransformerMutationType.UPDATE + TransformerMutationType.UPDATE, ); const head = await outbox.peek(s); @@ -247,7 +247,7 @@ describe('Outbox tests', () => { const mutationsForModel = await outbox.getForModel( s, last, - modelDefinition + modelDefinition, ); expect(mutationsForModel.length).toEqual(1); }); @@ -265,7 +265,7 @@ describe('Outbox tests', () => { const mutationsForModel = await outbox.getForModel( Storage, last, - modelDefinition + modelDefinition, ); expect(mutationsForModel.length).toEqual(2); @@ -290,7 +290,7 @@ describe('Outbox tests', () => { await processMutationResponse( s, response, - TransformerMutationType.UPDATE + TransformerMutationType.UPDATE, ); const inProgress = await outbox.peek(s); @@ -307,7 +307,7 @@ describe('Outbox tests', () => { await processMutationResponse( s, response, - TransformerMutationType.UPDATE + TransformerMutationType.UPDATE, ); const head = await outbox.peek(s); @@ -379,7 +379,7 @@ async function instantiateOutbox(): Promise { schema, MutationEvent, modelInstanceCreator, - ownSymbol + ownSymbol, ); merger = new ModelMerger(outbox, ownSymbol); } @@ -402,14 +402,14 @@ async function createMutationEvent(model): Promise { originalElement, {}, MutationEventConstructor, - modelInstanceCreator + modelInstanceCreator, ); } async function processMutationResponse( storage, record, - recordOp + recordOp, ): Promise { await outbox.dequeue(storage, record, recordOp); diff --git a/packages/datastore/__tests__/storage.test.ts b/packages/datastore/__tests__/storage.test.ts index 6d13d46e299..7eba35b6434 100644 --- a/packages/datastore/__tests__/storage.test.ts +++ b/packages/datastore/__tests__/storage.test.ts @@ -113,13 +113,13 @@ describe('Storage tests', () => { new Model({ field1: 'Some value', dateCreated, - }) + }), ); await DataStore.save( Model.copyOf(model, draft => { draft.field1 = 'edited'; - }) + }), ); const [modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -141,13 +141,13 @@ describe('Storage tests', () => { new Model({ field1: 'Some value', dateCreated, - }) + }), ); await DataStore.save( Model.copyOf(model, draft => { draft.field1 = 'Some value'; - }) + }), ); const [_modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -165,13 +165,13 @@ describe('Storage tests', () => { field1: 'Some value', optionalField1: 'Some optional value', dateCreated: new Date().toISOString(), - }) + }), ); await DataStore.save( Model.copyOf(model, draft => { draft.optionalField1 = null!; - }) + }), ); const [_modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -186,13 +186,13 @@ describe('Storage tests', () => { field1: 'Some value', optionalField1: 'Some optional value', dateCreated: new Date().toISOString(), - }) + }), ); await DataStore.save( Model.copyOf(model, draft => { draft.optionalField1 = undefined; - }) + }), ); const [_modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -208,13 +208,13 @@ describe('Storage tests', () => { field1: 'Some value', dateCreated: new Date().toISOString(), emails: ['john@doe.com', 'jane@doe.com'], - }) + }), ); await DataStore.save( Model.copyOf(model, draft => { draft.emails = [...draft.emails!, 'joe@doe.com']; - }) + }), ); const [_modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -238,13 +238,13 @@ describe('Storage tests', () => { field1: 'Some value', dateCreated: new Date().toISOString(), emails: ['john@doe.com', 'jane@doe.com'], - }) + }), ); await DataStore.save( Model.copyOf(model, draft => { draft.emails!.push('joe@doe.com'); - }) + }), ); const [_modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -268,7 +268,7 @@ describe('Storage tests', () => { field1: 'Some value', dateCreated: new Date().toISOString(), emails: ['john@doe.com', 'jane@doe.com'], - }) + }), ); await DataStore.save( @@ -276,7 +276,7 @@ describe('Storage tests', () => { draft.field1 = 'Updated value'; // same as above. should not be included in mutation input draft.emails = ['john@doe.com', 'jane@doe.com']; - }) + }), ); const [_modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -295,14 +295,14 @@ describe('Storage tests', () => { field1: 'Some value', dateCreated: new Date().toISOString(), emails: ['john@doe.com', 'jane@doe.com'], - }) + }), ); await DataStore.save( Model.copyOf(model, draft => { // same as above. should not result in mutation event draft.emails = ['john@doe.com', 'jane@doe.com']; - }) + }), ); const [_modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -318,13 +318,13 @@ describe('Storage tests', () => { field1: 'Some value', dateCreated: new Date().toISOString(), emails: ['john@doe.com', 'jane@doe.com'], - }) + }), ); await DataStore.save( Model.copyOf(model, draft => { draft.emails = null!; - }) + }), ); const [_modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -345,7 +345,7 @@ describe('Storage tests', () => { penNames: [], nominations: [], }, - }) + }), ); await DataStore.save( @@ -354,7 +354,7 @@ describe('Storage tests', () => { ...draft.metadata, penNames: ['bob'], } as any; - }) + }), ); const [_modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -369,7 +369,7 @@ describe('Storage tests', () => { expect(modelUpdate.element.dateCreated).toBeUndefined(); expect(modelUpdate.element.field1).toBeUndefined(); expect(modelUpdate.element.metadata).toMatchObject( - expectedValueMetadata + expectedValueMetadata, ); }); @@ -386,13 +386,13 @@ describe('Storage tests', () => { penNames: [], nominations: [], }, - }) + }), ); await DataStore.save( Model.copyOf(model, draft => { draft.metadata!.penNames = ['bob']; - }) + }), ); const [_modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -406,7 +406,7 @@ describe('Storage tests', () => { expect(modelUpdate.element.dateCreated).toBeUndefined(); expect(modelUpdate.element.field1).toBeUndefined(); expect(modelUpdate.element.metadata).toMatchObject( - expectedValueMetadata + expectedValueMetadata, ); }); @@ -416,32 +416,32 @@ describe('Storage tests', () => { const originalPost = await DataStore.save( new Post({ title: 'my best post ever', - }) + }), ); const newPost = await DataStore.save( new Post({ title: 'oops. i mean this is my best post', - }) + }), ); const comment = await DataStore.save( new Comment({ content: 'your post is not that great, actually ....', post: originalPost, - }) + }), ); await DataStore.save( Comment.copyOf(comment, draft => { draft.post = newPost; - }) + }), ); const updatedComment = await DataStore.query(Comment, comment.id); expect((await updatedComment!.post).title).toEqual( - 'oops. i mean this is my best post' + 'oops. i mean this is my best post', ); }); @@ -453,14 +453,14 @@ describe('Storage tests', () => { const post = await DataStore.save( new Post({ title: 'my best post ever', - }) + }), ); const comment = await DataStore.save( new Comment({ content: 'comment 1', post, - }) + }), ); new Comment({ @@ -476,7 +476,7 @@ describe('Storage tests', () => { content: 'comment 2', } as any), ]; - }) + }), ); const test = await DataStore.query(Post, post.id); @@ -501,7 +501,7 @@ describe('Storage tests', () => { penNames: [], nominations: [], }, - }) + }), ); await DataStore.save( @@ -513,7 +513,7 @@ describe('Storage tests', () => { penNames: [], nominations: [], }; - }) + }), ); const [_modelSave, modelUpdate] = processZenPushCalls(zenNext); @@ -529,26 +529,26 @@ describe('Storage tests', () => { const post = await DataStore.save( new Post({ title: 'New Post', - }) + }), ); const comment = await DataStore.save( new Comment({ content: 'Hello world', post, - }) + }), ); const anotherPost = await DataStore.save( new Post({ title: 'Another Post', - }) + }), ); await DataStore.save( Comment.copyOf(comment, updated => { updated.post = anotherPost; - }) + }), ); const [_postSave, commentSave, _anotherPostSave, commentUpdate] = @@ -577,7 +577,7 @@ describe('Storage tests', () => { description: 'Desc', created: createdTimestamp, sort: 100, - }) + }), ); // `sort` is part of the key's composite sort key. @@ -585,21 +585,21 @@ describe('Storage tests', () => { const updated1 = await DataStore.save( PostComposite.copyOf(post, updated => { updated.sort = 101; - }) + }), ); // `title` is the HK, so `sort` and `created` should NOT be included in the input const updated2 = await DataStore.save( PostComposite.copyOf(updated1, updated => { updated.title = 'Updated Title'; - }) + }), ); // `description` does not belong to a key. No other fields should be included await DataStore.save( PostComposite.copyOf(updated2, updated => { updated.description = 'Updated Desc'; - }) + }), ); const [_postSave, postUpdate1, postUpdate2, postUpdate3] = @@ -632,13 +632,13 @@ describe('Storage tests', () => { title: 'New Post', description: 'Desc', dateCreated: new Date().toISOString(), - }) + }), ); await DataStore.save( PostCustomPK.copyOf(post, updated => { updated.title = 'Updated'; - }) + }), ); const [_postSave, postUpdate] = processZenPushCalls(zenNext); @@ -658,13 +658,13 @@ describe('Storage tests', () => { id: 'abcdef', postId: '100', title: 'New Post', - }) + }), ); await DataStore.save( PostCustomPKSort.copyOf(post, updated => { updated.title = 'Updated'; - }) + }), ); const [_postSave, postUpdate] = processZenPushCalls(zenNext); @@ -687,13 +687,13 @@ describe('Storage tests', () => { title: 'New Post', description: 'Desc', sort: 1, - }) + }), ); await DataStore.save( PostCustomPKComposite.copyOf(post, updated => { updated.title = 'Updated'; - }) + }), ); const [_postSave, postUpdate] = processZenPushCalls(zenNext); diff --git a/packages/datastore/__tests__/subscription.test.ts b/packages/datastore/__tests__/subscription.test.ts index 1f318f551bb..aa1e649b878 100644 --- a/packages/datastore/__tests__/subscription.test.ts +++ b/packages/datastore/__tests__/subscription.test.ts @@ -22,7 +22,7 @@ import { Category, DataStoreAction } from '@aws-amplify/core/internals/utils'; // mock graphql to return a mockable observable jest.mock('@aws-amplify/api/internals', () => { const actualInternalAPIModule = jest.requireActual( - '@aws-amplify/api/internals' + '@aws-amplify/api/internals', ); const actualInternalAPIInstance = actualInternalAPIModule.InternalAPI; @@ -62,8 +62,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'userPool', accessTokenPayload, - 'userPool' - ) + 'userPool', + ), ).toEqual(authInfo); }); test('owner authorization with only read operation', () => { @@ -92,8 +92,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'userPool', accessTokenPayload, - 'userPool' - ) + 'userPool', + ), ).toEqual(authInfo); }); test('owner authorization without read operation', () => { @@ -122,8 +122,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'userPool', accessTokenPayload, - 'userPool' - ) + 'userPool', + ), ).toEqual(authInfo); }); test('owner authorization with public subscription', () => { @@ -159,8 +159,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'userPool', accessTokenPayload, - 'userPool' - ) + 'userPool', + ), ).toEqual(authInfo); }); test('owner authorization with custom owner (explicit)', () => { @@ -198,8 +198,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'userPool', accessTokenPayload, - 'userPool' - ) + 'userPool', + ), ).toEqual(authInfo); }); test('owner authorization with auth different than default auth mode', () => { @@ -231,8 +231,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'userPool', // default auth mode accessTokenPayload, - 'iam' - ) + 'iam', + ), ).toEqual(authInfo); }); test('groups authorization', () => { @@ -260,8 +260,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'userPool', accessTokenPayload, - 'userPool' - ) + 'userPool', + ), ).toEqual(authInfo); }); test('groups authorization with groupClaim (array as string)', () => { @@ -294,8 +294,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'userPool', tokenPayload, - 'userPool' - ) + 'userPool', + ), ).toEqual(authInfo); }); test('groups authorization with groupClaim (string)', () => { @@ -328,8 +328,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'userPool', tokenPayload, - 'userPool' - ) + 'userPool', + ), ).toEqual(authInfo); }); test('groups authorization with groupClaim (plain string)', () => { @@ -362,8 +362,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'userPool', tokenPayload, - 'userPool' - ) + 'userPool', + ), ).toEqual(authInfo); }); test('public iam authorization for unauth user', () => { @@ -388,8 +388,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.unauth, 'iam', undefined, // No Cognito token - 'iam' - ) + 'iam', + ), ).toEqual(authInfo); }); test('private iam authorization for unauth user', () => { @@ -414,8 +414,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.unauth, 'iam', undefined, // No Cognito token - 'iam' - ) + 'iam', + ), ).toEqual(null); }); test('private iam authorization for auth user', () => { @@ -440,8 +440,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'iam', undefined, - 'iam' // No Cognito token - ) + 'iam', // No Cognito token + ), ).toEqual(authInfo); }); test('public apiKey authorization without credentials', () => { @@ -466,8 +466,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.none, 'apiKey', undefined, - 'apiKey' // No Cognito token - ) + 'apiKey', // No Cognito token + ), ).toEqual(authInfo); }); test('OIDC owner authorization', () => { @@ -509,8 +509,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'oidc', oidcTokenPayload, // No Cognito token, - 'oidc' - ) + 'oidc', + ), ).toEqual(authInfo); }); test('User Pools & OIDC owner authorization with Cognito token', () => { @@ -546,8 +546,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.auth, 'userPool', accessTokenPayload, - 'userPool' - ) + 'userPool', + ), ).toEqual(authInfo); }); @@ -573,8 +573,8 @@ describe('sync engine subscription module', () => { USER_CREDENTIALS.none, 'lambda', undefined, - 'lambda' // No Cognito token - ) + 'lambda', // No Cognito token + ), ).toEqual(authInfo); }); }); @@ -621,23 +621,23 @@ describe('error handler', () => { message, model: 'Model', operation, - }) + }), ); // expect logger.debug to be called 6 times for auth mode (2 for each operation) // can't use toHaveBeenCalledTimes because it is called elsewhere unrelated to the test expect(debugLog).toHaveBeenCalledWith( expect.stringMatching( new RegExp( - `[DEBUG].*${operation} subscription failed with authMode: apiKey` - ) - ) + `[DEBUG].*${operation} subscription failed with authMode: apiKey`, + ), + ), ); expect(debugLog).toHaveBeenCalledWith( expect.stringMatching( new RegExp( - `[DEBUG].*${operation} subscription failed with authMode: userPool` - ) - ) + `[DEBUG].*${operation} subscription failed with authMode: userPool`, + ), + ), ); expect(mockGraphQL).toHaveBeenCalledWith( @@ -646,7 +646,7 @@ describe('error handler', () => { { category: Category.DataStore, action: DataStoreAction.Subscribe, - } + }, ); }); @@ -687,7 +687,7 @@ describe('error handler', () => { aws_appsync_apiKey: 'da2-xxxxxxxxxxxxxxxxxxxxxx', }, () => ['apiKey', 'userPool'], - errorHandler + errorHandler, ); return subscriptionProcessor; @@ -713,7 +713,7 @@ const accessTokenPayload = { export function generateModelWithAuth( authRules, - modelProperties = {} + modelProperties = {}, ): SchemaModel { return { syncable: true, diff --git a/packages/datastore/__tests__/sync.test.ts b/packages/datastore/__tests__/sync.test.ts index e3a657c84a1..6bc74724df0 100644 --- a/packages/datastore/__tests__/sync.test.ts +++ b/packages/datastore/__tests__/sync.test.ts @@ -356,7 +356,7 @@ describe('Sync', () => { operation: 'syncPosts', process: 'sync', errorType: 'BadRecord', - }) + }), ); }); @@ -385,7 +385,7 @@ describe('Sync', () => { operation: 'syncPosts', process: 'sync', errorType: 'Transient', - }) + }), ); }); @@ -418,7 +418,7 @@ describe('Sync', () => { operation: 'syncPosts', process: 'sync', errorType: 'Transient', - }) + }), ); }); }); @@ -443,12 +443,12 @@ function jitteredRetrySyncProcessorSetup({ } else if (rejectResponse) { rej(rejectResponse); } - }) + }), ); // mock graphql to return a mockable observable jest.mock('@aws-amplify/api/internals', () => { const actualInternalAPIModule = jest.requireActual( - '@aws-amplify/api/internals' + '@aws-amplify/api/internals', ); const actualInternalAPIInstance = actualInternalAPIModule.InternalAPI; @@ -487,7 +487,7 @@ function jitteredRetrySyncProcessorSetup({ { aws_appsync_authenticationType: 'userPools' }, defaultAuthStrategy, errorHandler, - {} + {}, ); return SyncProcessor; diff --git a/packages/datastore/__tests__/util.test.ts b/packages/datastore/__tests__/util.test.ts index f89bab5b056..29dcf2ff9b5 100644 --- a/packages/datastore/__tests__/util.test.ts +++ b/packages/datastore/__tests__/util.test.ts @@ -27,36 +27,36 @@ import { testSchema } from './helpers'; describe('datastore util', () => { test('validatePredicateField', () => { expect(validatePredicateField(undefined, 'contains', 'test')).toEqual( - false + false, ); expect(validatePredicateField(null, 'contains', 'test')).toEqual(false); expect(validatePredicateField('some test', 'contains', 'test')).toEqual( - true + true, ); expect(validatePredicateField(undefined, 'beginsWith', 'test')).toEqual( - false + false, ); expect(validatePredicateField(null, 'beginsWith', 'test')).toEqual(false); expect(validatePredicateField('some test', 'beginsWith', 'test')).toEqual( - false + false, ); expect(validatePredicateField('testing', 'beginsWith', 'test')).toEqual( - true + true, ); expect(validatePredicateField(undefined, 'notContains', 'test')).toEqual( - true + true, ); expect(validatePredicateField(null, 'notContains', 'test')).toEqual(true); expect(validatePredicateField('abcdef', 'notContains', 'test')).toEqual( - true + true, ); expect(validatePredicateField('test', 'notContains', 'test')).toEqual( - false + false, ); expect(validatePredicateField('testing', 'notContains', 'test')).toEqual( - false + false, ); }); @@ -69,14 +69,14 @@ describe('datastore util', () => { expect(valuesEqual({ a: 1 }, { a: 1 })).toEqual(true); expect(valuesEqual({ a: 1 }, { a: 2 })).toEqual(false); expect( - valuesEqual({ a: [{ b: 2 }, { c: 3 }] }, { a: [{ b: 2 }, { c: 3 }] }) + valuesEqual({ a: [{ b: 2 }, { c: 3 }] }, { a: [{ b: 2 }, { c: 3 }] }), ).toEqual(true); expect( - valuesEqual({ a: [{ b: 2 }, { c: 3 }] }, { a: [{ b: 2 }, { c: 4 }] }) + valuesEqual({ a: [{ b: 2 }, { c: 3 }] }, { a: [{ b: 2 }, { c: 4 }] }), ).toEqual(false); expect(valuesEqual(new Set([1, 2, 3]), new Set([1, 2, 3]))).toEqual(true); expect(valuesEqual(new Set([1, 2, 3]), new Set([1, 2, 3, 4]))).toEqual( - false + false, ); const map1 = new Map(); @@ -94,7 +94,7 @@ describe('datastore util', () => { expect(valuesEqual({ a: 1 }, { a: 1, b: null }, true)).toEqual(true); expect(valuesEqual({ a: 1 }, { a: 1, b: 2 }, true)).toEqual(false); expect( - valuesEqual({ a: 1, b: null }, { a: 1, b: undefined }, true) + valuesEqual({ a: 1, b: null }, { a: 1, b: undefined }, true), ).toEqual(true); expect(valuesEqual({ a: 1, b: false }, { a: 1 }, true)).toEqual(false); @@ -114,7 +114,7 @@ describe('datastore util', () => { expect(valuesEqual([null], [undefined], true)).toEqual(true); expect(valuesEqual([undefined], [null], true)).toEqual(true); expect(valuesEqual(new Set([null]), new Set([undefined]), true)).toEqual( - true + true, ); // empty list [] should not equal [null] @@ -125,7 +125,7 @@ describe('datastore util', () => { expect(valuesEqual([null], [undefined], false)).toEqual(false); expect(valuesEqual(new Set([null]), new Set([]), false)).toEqual(false); expect(valuesEqual(new Set([null]), new Set([undefined]), false)).toEqual( - false + false, ); // primitive types @@ -620,7 +620,7 @@ describe('datastore util', () => { }, patches => { patchesAB = patches; - } + }, ); const modelC = produce( modelB, @@ -629,7 +629,7 @@ describe('datastore util', () => { }, patches => { patchesBC = patches; - } + }, ); const mergedPatches = mergePatches(modelA, patchesAB, patchesBC); @@ -661,7 +661,7 @@ describe('datastore util', () => { }, patches => { patchesAB = patches; - } + }, ); const modelC = produce( modelB, @@ -670,7 +670,7 @@ describe('datastore util', () => { }, patches => { patchesBC = patches; - } + }, ); const mergedPatches = mergePatches(modelA, patchesAB, patchesBC); @@ -700,7 +700,7 @@ describe('datastore util', () => { }, patches => { patchesAB = patches; - } + }, ); const modelC = produce( modelB, @@ -709,7 +709,7 @@ describe('datastore util', () => { }, patches => { patchesBC = patches; - } + }, ); const mergedPatches = mergePatches(modelA, patchesAB, patchesBC); @@ -738,7 +738,7 @@ describe('datastore util', () => { }); test('model definition with custom pk + sk', () => { const result = extractKeyIfExists( - testUserSchema.models.PostCustomPKSort + testUserSchema.models.PostCustomPKSort, )!; expect(result.properties!.fields.length).toBe(2); expect(result.properties!.fields[0]).toBe('id'); @@ -754,14 +754,14 @@ describe('datastore util', () => { const testUserSchema = testSchema(); test('model definition with custom pk', () => { const result = extractPrimaryKeyFieldNames( - testUserSchema.models.PostCustomPK + testUserSchema.models.PostCustomPK, ); expect(result.length).toBe(1); expect(result[0]).toBe('postId'); }); test('model definition with custom pk + sk', () => { const result = extractPrimaryKeyFieldNames( - testUserSchema.models.PostCustomPKSort + testUserSchema.models.PostCustomPKSort, ); expect(result.length).toBe(2); expect(result[0]).toBe('id'); @@ -783,7 +783,7 @@ describe('datastore util', () => { description: 'Desc', sort: 1, }, - ['id', 'postId', 'sort'] + ['id', 'postId', 'sort'], ); expect(result).toEqual(['abcdef', '100', 1]); }); @@ -804,7 +804,7 @@ describe('datastore util', () => { test('should return `false` for model with custom primary key', () => { const testUserSchema = testSchema(); const result = isIdOptionallyManaged( - testUserSchema.models.PostCustomPK + testUserSchema.models.PostCustomPK, ); expect(result).toBeFalsy(); }); diff --git a/packages/datastore/__tests__/utils.test.ts b/packages/datastore/__tests__/utils.test.ts index c8e7aa4528e..ebed797c5ca 100644 --- a/packages/datastore/__tests__/utils.test.ts +++ b/packages/datastore/__tests__/utils.test.ts @@ -123,7 +123,7 @@ _lastChangedAt _deleted`; expect(generateSelectionSet(namespace, modelDefinition)).toEqual( - selectionSet + selectionSet, ); }); test('explicit owner', () => { @@ -245,7 +245,7 @@ _lastChangedAt _deleted`; expect(generateSelectionSet(namespace, modelDefinition)).toEqual( - selectionSet + selectionSet, ); }); test('explicit custom owner', () => { @@ -367,7 +367,7 @@ _lastChangedAt _deleted`; expect(generateSelectionSet(namespace, modelDefinition)).toEqual( - selectionSet + selectionSet, ); }); }); diff --git a/packages/datastore/src/authModeStrategies/multiAuthStrategy.ts b/packages/datastore/src/authModeStrategies/multiAuthStrategy.ts index d5b1c1ebef0..14ac0a1dbc3 100644 --- a/packages/datastore/src/authModeStrategies/multiAuthStrategy.ts +++ b/packages/datastore/src/authModeStrategies/multiAuthStrategy.ts @@ -11,7 +11,7 @@ import { import { GraphQLAuthMode } from '@aws-amplify/core/internals/utils'; function getProviderFromRule( - rule: ModelAttributeAuthProperty + rule: ModelAttributeAuthProperty, ): ModelAttributeAuthProvider { // private with no provider means userPools if (rule.allow === 'private' && !rule.provider) { @@ -51,7 +51,7 @@ function sortAuthRulesWithPriority(rules: ModelAttributeAuthProperty[]) { return ( allowSortPriority.indexOf(a.allow) - allowSortPriority.indexOf(b.allow) ); - } + }, ); } @@ -136,7 +136,7 @@ function getAuthRules({ * @returns A sorted array of auth modes to attempt. */ export const multiAuthStrategy: ( - amplifyContext: AmplifyContext + amplifyContext: AmplifyContext, ) => AuthModeStrategy = (amplifyContext: AmplifyContext) => async ({ schema, modelName }) => { @@ -158,7 +158,7 @@ export const multiAuthStrategy: ( if (authAttribute?.properties?.rules) { const sortedRules = sortAuthRulesWithPriority( - authAttribute.properties.rules + authAttribute.properties.rules, ); return getAuthRules({ currentUser, rules: sortedRules }); diff --git a/packages/datastore/src/datastore/datastore.ts b/packages/datastore/src/datastore/datastore.ts index ac591009db0..8e77e85b2e7 100644 --- a/packages/datastore/src/datastore/datastore.ts +++ b/packages/datastore/src/datastore/datastore.ts @@ -122,7 +122,7 @@ declare class Setting { constructor(init: ModelInit); static copyOf( src: Setting, - mutator: (draft: MutableModel) => void | Setting + mutator: (draft: MutableModel) => void | Setting, ): Setting; public readonly id: string; public readonly key: string; @@ -149,7 +149,7 @@ const modelPatchesMap = new WeakMap< >(); const getModelDefinition = ( - modelConstructor: PersistentModelConstructor + modelConstructor: PersistentModelConstructor, ) => { const namespace = modelNamespaceMap.get(modelConstructor)!; const definition = namespace @@ -166,7 +166,7 @@ const getModelDefinition = ( * @param obj The object to test. */ const isValidModelConstructor = ( - obj: any + obj: any, ): obj is PersistentModelConstructor => { return isModelConstructor(obj) && modelNamespaceMap.has(obj); }; @@ -175,7 +175,7 @@ const namespaceResolver: NamespaceResolver = modelConstructor => { const resolver = modelNamespaceMap.get(modelConstructor); if (!resolver) { throw new Error( - `Namespace Resolver for '${modelConstructor.name}' not found! This is probably a bug in '@amplify-js/datastore'.` + `Namespace Resolver for '${modelConstructor.name}' not found! This is probably a bug in '@amplify-js/datastore'.`, ); } return resolver; @@ -201,12 +201,12 @@ const namespaceResolver: NamespaceResolver = modelConstructor => { * @param modelConstructor The model the predicate will query. */ const buildSeedPredicate = ( - modelConstructor: PersistentModelConstructor + modelConstructor: PersistentModelConstructor, ) => { if (!modelConstructor) throw new Error('Missing modelConstructor'); const modelSchema = getModelDefinition( - modelConstructor as PersistentModelConstructor + modelConstructor as PersistentModelConstructor, ); if (!modelSchema) throw new Error('Missing modelSchema'); @@ -275,7 +275,7 @@ const attachedModelInstances = new WeakMap(); */ export function attached( result: T, - attachment: ModelAttachment + attachment: ModelAttachment, ): T { if (Array.isArray(result)) { result.map(record => attached(record, attachment)) as T; @@ -339,7 +339,7 @@ const initSchema = (userSchema: Schema) => { Object.keys(schema.namespaces).forEach(namespace => { const [relations, keys] = establishRelationAndKeys( - schema.namespaces[namespace] + schema.namespaces[namespace], ); schema.namespaces[namespace].relationships = relations; @@ -355,10 +355,10 @@ const initSchema = (userSchema: Schema) => { field => field.association && field.association.connectionType === 'BELONGS_TO' && - (field.type).model !== model.name + (field.type).model !== model.name, ) .forEach(field => - connectedModels.push((field.type).model) + connectedModels.push((field.type).model), ); modelAssociations.set(model.name, connectedModels); @@ -374,7 +374,7 @@ const initSchema = (userSchema: Schema) => { const relatedModelDefinition = getModelDefinition(relatedModel); if (!relatedModelDefinition) throw new Error( - `Could not find model definition for ${relatedModel.name}` + `Could not find model definition for ${relatedModel.name}`, ); return { builder: relatedModel, @@ -409,7 +409,7 @@ const initSchema = (userSchema: Schema) => { type: 'ID', isArray: false, }, - ]) + ]), ), ...model.fields, }; @@ -425,7 +425,7 @@ const initSchema = (userSchema: Schema) => { count--; if (count === 0) { throw new Error( - 'Models are not topologically sortable. Please verify your schema.' + 'Models are not topologically sortable. Please verify your schema.', ); } @@ -506,7 +506,7 @@ const checkSchemaCodegenVersion = (codegenVersion: string) => { }; const createTypeClasses: ( - namespace: SchemaNamespace + namespace: SchemaNamespace, ) => TypeConstructorMap = namespace => { const classes: TypeConstructorMap = {}; @@ -521,7 +521,7 @@ const createTypeClasses: ( ([typeName, typeDefinition]) => { const clazz = createNonModelClass(typeDefinition); classes[typeName] = clazz; - } + }, ); return classes; @@ -547,7 +547,7 @@ const instancesMetadata = new WeakSet>(); function modelInstanceCreator( modelConstructor: PersistentModelConstructor, - init: Partial + init: Partial, ): T { instancesMetadata.add(init); @@ -612,14 +612,14 @@ const validateModelFields = if (!Array.isArray(v) && !isArrayNullable) { throw new Error( - `Field ${name} should be of type [${errorTypeText}], ${typeof v} received. ${v}` + `Field ${name} should be of type [${errorTypeText}], ${typeof v} received. ${v}`, ); } if ( !isNullOrUndefined(v) && (<[]>v).some(e => - isNullOrUndefined(e) ? isRequired : typeof e !== jsType + isNullOrUndefined(e) ? isRequired : typeof e !== jsType, ) ) { const elemTypes = (<[]>v) @@ -627,7 +627,7 @@ const validateModelFields = .join(','); throw new Error( - `All elements in the ${name} array should be of type ${errorTypeText}, [${elemTypes}] received. ${v}` + `All elements in the ${name} array should be of type ${errorTypeText}, [${elemTypes}] received. ${v}`, ); } @@ -644,7 +644,7 @@ const validateModelFields = if (!validationStatus.every(s => s)) { throw new Error( - `All elements in the ${name} array should be of type ${type}, validation failed for one or more elements. ${v}` + `All elements in the ${name} array should be of type ${type}, validation failed for one or more elements. ${v}`, ); } } @@ -652,7 +652,7 @@ const validateModelFields = return; } else if (typeof v !== jsType && v !== null) { throw new Error( - `Field ${name} should be of type ${jsType}, ${typeof v} received. ${v}` + `Field ${name} should be of type ${jsType}, ${typeof v} received. ${v}`, ); } else if ( !isNullOrUndefined(v) && @@ -660,7 +660,7 @@ const validateModelFields = !validateScalar(v as never) // TODO: why never, TS ... why ... ) { throw new Error( - `Field ${name} should be of type ${type}, validation failed. ${v}` + `Field ${name} should be of type ${type}, validation failed. ${v}`, ); } } else if (isNonModelFieldType(type)) { @@ -677,7 +677,7 @@ const validateModelFields = } if (!Array.isArray(v)) { throw new Error( - `Field ${name} should be of type [${errorTypeText}], ${typeof v} received. ${v}` + `Field ${name} should be of type [${errorTypeText}], ${typeof v} received. ${v}`, ); } @@ -689,7 +689,7 @@ const validateModelFields = throw new Error( `All elements in the ${name} array should be of type ${ type.nonModel - }, [${typeof item}] received. ${item}` + }, [${typeof item}] received. ${item}`, ); } @@ -704,7 +704,7 @@ const validateModelFields = throw new Error( `Field ${name} should be of type ${ type.nonModel - }, ${typeof v} recieved. ${v}` + }, ${typeof v} recieved. ${v}`, ); } @@ -720,7 +720,7 @@ const validateModelFields = const castInstanceType = ( modelDefinition: SchemaModel | SchemaNonModel, k: string, - v: any + v: any, ) => { const { isArray, type } = modelDefinition.fields[k] || {}; // attempt to parse stringified JSON @@ -764,7 +764,7 @@ const initPatches = new WeakMap(); const initializeInstance = ( init: ModelInit, modelDefinition: SchemaModel | SchemaNonModel, - draft: Draft + draft: Draft, ) => { const modelValidator = validateModelFields(modelDefinition); Object.entries(init).forEach(([k, v]) => { @@ -796,7 +796,7 @@ const initializeInstance = ( */ const normalize = ( modelDefinition: SchemaModel | SchemaNonModel, - draft: Draft + draft: Draft, ) => { for (const k of Object.keys(modelDefinition.fields)) { if (draft[k] === undefined) (draft)[k] = null; @@ -804,7 +804,7 @@ const normalize = ( }; const createModelClass = ( - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ) => { const clazz = >(class Model { constructor(init: ModelInit) { @@ -836,8 +836,8 @@ const createModelClass = ( const id = isInternalModel ? _id : modelDefinition.syncable - ? amplifyUuid() - : ulid(); + ? amplifyUuid() + : ulid(); ((draft)).id = id; } else if (isIdOptionallyManaged(modelDefinition)) { @@ -858,7 +858,7 @@ const createModelClass = ( draft._deleted = _deleted; } }, - p => (patches = p) + p => (patches = p), ); // now that we have a list of patches that encapsulate the explicit, customer-provided @@ -869,7 +869,7 @@ const createModelClass = ( const normalized = produce( baseInstance, (draft: Draft) => - normalize(modelDefinition, draft) + normalize(modelDefinition, draft), ); initPatches.set(normalized, patches); @@ -897,7 +897,7 @@ const createModelClass = ( if (draft[key] !== source[key]) { logger.warn( `copyOf() does not update PK fields. The '${key}' update is being ignored.`, - { source } + { source }, ); } (draft as Object)[key] = source[key]; @@ -912,7 +912,7 @@ const createModelClass = ( normalize(modelDefinition, draft); }, - p => (patches = p) + p => (patches = p), ); const hasExistingPatches = modelPatchesMap.has(source); @@ -924,7 +924,7 @@ const createModelClass = ( const mergedPatches = mergePatches( existingSource, existingPatches, - patches + patches, ); modelPatchesMap.set(model, [mergedPatches, existingSource]); checkReadOnlyPropertyOnUpdate(mergedPatches, modelDefinition); @@ -1050,10 +1050,10 @@ const createModelClass = ( return relationship.remoteJoinFields.map((field, index) => { // TODO: anything we can use instead of `any` here? return (q[field] as T[typeof field]).eq( - this[relationship.localJoinFields[index]] + this[relationship.localJoinFields[index]], ); }); - }) + }), ); // results in hand, how we return them to the caller depends on the relationship type. @@ -1175,7 +1175,7 @@ export class AsyncCollection implements AsyncIterable { const checkReadOnlyPropertyOnCreate = ( draft: T, - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ) => { const modelKeys = Object.keys(draft); const { fields } = modelDefinition; @@ -1189,7 +1189,7 @@ const checkReadOnlyPropertyOnCreate = ( const checkReadOnlyPropertyOnUpdate = ( patches: Patch[], - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ) => { const patchArray = patches.map(p => [p.path[0], p.value]); const { fields } = modelDefinition; @@ -1204,7 +1204,7 @@ const checkReadOnlyPropertyOnUpdate = ( }; const createNonModelClass = ( - typeDefinition: SchemaNonModel + typeDefinition: SchemaNonModel, ) => { const clazz = >(class Model { constructor(init: ModelInit) { @@ -1212,7 +1212,7 @@ const createNonModelClass = ( this, (draft: Draft) => { initializeInstance(init, typeDefinition, draft); - } + }, ); return instance; @@ -1244,7 +1244,7 @@ function defaultErrorHandler(error: SyncError): void { function getModelConstructorByModelName( namespaceName: NAMESPACES, - modelName: string + modelName: string, ): PersistentModelConstructor { let result: PersistentModelConstructor | NonModelTypeConstructor; @@ -1289,7 +1289,7 @@ function getModelConstructorByModelName( */ async function checkSchemaVersion( storage: Storage, - version: string + version: string, ): Promise { const Setting = dataStoreClasses.Setting as PersistentModelConstructor; @@ -1302,7 +1302,7 @@ async function checkSchemaVersion( ModelPredicateCreator.createFromAST(modelDefinition, { and: { key: { eq: SETTING_SCHEMA_VERSION } }, }), - { page: 0, limit: 1 } + { page: 0, limit: 1 }, ); if ( @@ -1319,7 +1319,7 @@ async function checkSchemaVersion( modelInstanceCreator(Setting, { key: SETTING_SCHEMA_VERSION, value: JSON.stringify(version), - }) + }), ); } }); @@ -1478,7 +1478,7 @@ class DataStore { `This can only be done while DataStore is "Started" or "Stopped". To remedy:`, 'Ensure all calls to `stop()` and `clear()` have completed first.', 'If this is not possible, retry the operation until it succeeds.', - ].join('\n') + ].join('\n'), ); } else { throw err; @@ -1516,7 +1516,7 @@ class DataStore { getModelConstructorByModelName, modelInstanceCreator, this.storageAdapter, - this.sessionId + this.sessionId, ); await this.storage.init(); @@ -1528,7 +1528,7 @@ class DataStore { if (aws_appsync_graphqlEndpoint) { logger.debug( 'GraphQL endpoint available', - aws_appsync_graphqlEndpoint + aws_appsync_graphqlEndpoint, ); this.syncPredicates = await this.processSyncExpressions(); @@ -1545,7 +1545,7 @@ class DataStore { this.amplifyConfig, this.authModeStrategy, this.amplifyContext, - this.connectivityMonitor + this.connectivityMonitor, ); const fullSyncIntervalInMilliseconds = @@ -1582,7 +1582,7 @@ class DataStore { "Data won't be synchronized. No GraphQL endpoint configured. Did you forget `Amplify.configure(awsconfig)`?", { config: this.amplifyConfig, - } + }, ); this.initResolve(); @@ -1600,7 +1600,7 @@ class DataStore { identifier: IdentifierFieldOrIdentifierObject< T, PersistentModelMetaData - > + >, ): Promise; ( modelConstructor: PersistentModelConstructor, @@ -1608,7 +1608,7 @@ class DataStore { | RecursiveModelPredicateExtender | typeof PredicateAll | null, - paginationProducer?: ProducerPaginationInput + paginationProducer?: ProducerPaginationInput, ): Promise; } = async ( modelConstructor: PersistentModelConstructor, @@ -1617,7 +1617,7 @@ class DataStore { | RecursiveModelPredicateExtender | typeof PredicateAll | null, - paginationProducer?: ProducerPaginationInput + paginationProducer?: ProducerPaginationInput, ): Promise => { return this.runningProcesses .add(async () => { @@ -1650,7 +1650,7 @@ class DataStore { const pagination = this.processPagination( modelDefinition, - paginationProducer + paginationProducer, ); const keyFields = extractPrimaryKeyFieldNames(modelDefinition); @@ -1665,25 +1665,25 @@ class DataStore { const predicate = ModelPredicateCreator.createFromFlatEqualities( modelDefinition, - { [keyFields[0]]: identifierOrCriteria } + { [keyFields[0]]: identifierOrCriteria }, ); result = await this.storage.query( modelConstructor, predicate, - pagination + pagination, ); } else { // Object is being queried using object literal syntax if (isIdentifierObject(identifierOrCriteria, modelDefinition)) { const predicate = ModelPredicateCreator.createForPk( modelDefinition, - identifierOrCriteria + identifierOrCriteria, ); result = await this.storage.query( modelConstructor, predicate, - pagination + pagination, ); } else if ( !identifierOrCriteria || @@ -1692,7 +1692,7 @@ class DataStore { result = await this.storage?.query( modelConstructor, undefined, - pagination + pagination, ); } else { const seedPredicate = recursivePredicateFor({ @@ -1702,8 +1702,8 @@ class DataStore { }); const predicate = internals( (identifierOrCriteria as RecursiveModelPredicateExtender)( - seedPredicate - ) + seedPredicate, + ), ); result = (await predicate.fetch(this.storage)) as T[]; result = inMemoryPagination(result, pagination); @@ -1718,7 +1718,7 @@ class DataStore { return attached( returnOne ? result[0] : result, - ModelAttachment.DataStore + ModelAttachment.DataStore, ); }, 'datastore query') .catch(this.handleAddProcError('DataStore.query()')); @@ -1726,7 +1726,7 @@ class DataStore { save = async ( model: T, - condition?: ModelPredicateExtender + condition?: ModelPredicateExtender, ): Promise => { return this.runningProcesses .add(async () => { @@ -1746,7 +1746,7 @@ class DataStore { ? ([initPatches.get(model)!, {}] as [ Patch[], Readonly>, - ]) + ]) : undefined; // favor update patches over init/create patches, because init patches @@ -1781,7 +1781,7 @@ class DataStore { // no enforcement for HAS_MANY on save, because the ~related~ entities // hold the FK in that case. const nonHasManyRelationships = ModelRelationship.allFrom( - modelMeta + modelMeta, ).filter(r => r.type === 'BELONGS_TO'); for (const relationship of nonHasManyRelationships) { const queryObject = relationship.createRemoteQueryObject(model); @@ -1790,8 +1790,8 @@ class DataStore { relationship.remoteModelConstructor, ModelPredicateCreator.createFromFlatEqualities( relationship.remoteDefinition!, - queryObject - ) + queryObject, + ), ); if (related.length === 0) { throw new Error( @@ -1802,7 +1802,7 @@ class DataStore { `but the instance assigned to the "${relationship.field}" property`, `does not exist in the local database. If you're trying to create the related`, `"${relationship.remoteDefinition?.name}", you must save it independently first.`, - ].join(' ') + ].join(' '), ); } } @@ -1811,8 +1811,8 @@ class DataStore { const producedCondition = condition ? internals( - condition(predicateFor(modelMeta)) - ).toStoragePredicate() + condition(predicateFor(modelMeta)), + ).toStoragePredicate() : undefined; const [savedModel] = await this.storage.runExclusive(async s => { @@ -1820,11 +1820,11 @@ class DataStore { model, producedCondition, undefined, - patchesTuple + patchesTuple, ); return s.query( modelConstructor, - ModelPredicateCreator.createForPk(modelDefinition, model) + ModelPredicateCreator.createForPk(modelDefinition, model), ); }); @@ -1871,22 +1871,22 @@ class DataStore { identifier: IdentifierFieldOrIdentifierObject< T, PersistentModelMetaData - > + >, ): Promise; ( modelConstructor: PersistentModelConstructor, - condition: ModelPredicateExtender | typeof PredicateAll + condition: ModelPredicateExtender | typeof PredicateAll, ): Promise; ( model: T, - condition?: ModelPredicateExtender + condition?: ModelPredicateExtender, ): Promise; } = async ( modelOrConstructor: T | PersistentModelConstructor, identifierOrCriteria?: | IdentifierFieldOrIdentifierObject> | ModelPredicateExtender - | typeof PredicateAll + | typeof PredicateAll, ): Promise => { return this.runningProcesses .add(async () => { @@ -1920,7 +1920,7 @@ class DataStore { if (!modelDefinition) { throw new Error( - 'Could not find model definition for modelConstructor.' + 'Could not find model definition for modelConstructor.', ); } @@ -1936,13 +1936,13 @@ class DataStore { condition = ModelPredicateCreator.createFromFlatEqualities( modelDefinition, - { [keyFields[0]]: identifierOrCriteria } + { [keyFields[0]]: identifierOrCriteria }, ); } else { if (isIdentifierObject(identifierOrCriteria, modelDefinition)) { condition = ModelPredicateCreator.createForPk( modelDefinition, - identifierOrCriteria + identifierOrCriteria, ); } else { condition = internals( @@ -1951,8 +1951,8 @@ class DataStore { builder: modelConstructor as PersistentModelConstructor, schema: modelDefinition, pkField: extractPrimaryKeyFieldNames(modelDefinition), - }) - ) + }), + ), ).toStoragePredicate(); } @@ -1970,7 +1970,7 @@ class DataStore { const [deleted] = await this.storage.delete( modelConstructor, - condition + condition, ); return attached(deleted, ModelAttachment.DataStore); @@ -1990,13 +1990,13 @@ class DataStore { if (!modelDefinition) { throw new Error( - 'Could not find model definition for modelConstructor.' + 'Could not find model definition for modelConstructor.', ); } const pkPredicate = ModelPredicateCreator.createForPk( modelDefinition, - model + model, ); if (identifierOrCriteria) { @@ -2013,8 +2013,8 @@ class DataStore { builder: modelConstructor as PersistentModelConstructor, schema: modelDefinition, pkField: extractPrimaryKeyFieldNames(modelDefinition), - }) - ) + }), + ), ).toStoragePredicate(); } else { condition = pkPredicate; @@ -2033,12 +2033,12 @@ class DataStore { ( modelConstructor: PersistentModelConstructor, - identifier: string + identifier: string, ): Observable>; ( modelConstructor: PersistentModelConstructor, - criteria?: RecursiveModelPredicateExtender | typeof PredicateAll + criteria?: RecursiveModelPredicateExtender | typeof PredicateAll, ): Observable>; (model: T): Observable>; @@ -2047,7 +2047,7 @@ class DataStore { identifierOrCriteria?: | string | RecursiveModelPredicateExtender - | typeof PredicateAll + | typeof PredicateAll, ): Observable> => { let executivePredicate: GroupCondition; @@ -2085,7 +2085,7 @@ class DataStore { modelConstructor && isIdentifierObject( identifierOrCriteria, - getModelDefinition(modelConstructor!)! + getModelDefinition(modelConstructor!)!, ) ) { const msg = errorMessages.observeWithObjectLiteral; @@ -2110,13 +2110,13 @@ class DataStore { if (modelConstructor && typeof identifierOrCriteria === 'string') { const buildIdPredicate = seed => seed.id.eq(identifierOrCriteria); executivePredicate = internals( - buildIdPredicate(buildSeedPredicate(modelConstructor)) + buildIdPredicate(buildSeedPredicate(modelConstructor)), ); } else if (modelConstructor && typeof identifierOrCriteria === 'function') { executivePredicate = internals( (identifierOrCriteria as RecursiveModelPredicateExtender)( - buildSeedPredicate(modelConstructor) - ) + buildSeedPredicate(modelConstructor), + ), ); } @@ -2146,15 +2146,15 @@ class DataStore { if (item.opType !== 'DELETE') { const modelDefinition = getModelDefinition(item.model); const keyFields = extractPrimaryKeyFieldNames( - modelDefinition! + modelDefinition!, ); const primaryKeysAndValues = extractPrimaryKeysAndValues( item.element, - keyFields + keyFields, ); const freshElement = await this.query( item.model, - primaryKeysAndValues + primaryKeysAndValues, ); message = { ...message, @@ -2193,12 +2193,12 @@ class DataStore { ( modelConstructor: PersistentModelConstructor, criteria?: RecursiveModelPredicateExtender | typeof PredicateAll, - paginationProducer?: ObserveQueryOptions + paginationProducer?: ObserveQueryOptions, ): Observable>; } = ( model: PersistentModelConstructor, criteria?: RecursiveModelPredicateExtender | typeof PredicateAll, - options?: ObserveQueryOptions + options?: ObserveQueryOptions, ): Observable> => { return new Observable>(observer => { const items = new Map(); @@ -2242,8 +2242,8 @@ class DataStore { if (model && typeof criteria === 'function') { executivePredicate = internals( (criteria as RecursiveModelPredicateExtender)( - buildSeedPredicate(model) - ) + buildSeedPredicate(model), + ), ); } else if (isPredicatesAll(criteria)) { executivePredicate = undefined; @@ -2270,7 +2270,7 @@ class DataStore { const itemModelDefinition = getModelDefinition(model)!; const idOrPk = getIdentifierValue( itemModelDefinition, - element + element, ); if ( executivePredicate && @@ -2314,7 +2314,7 @@ class DataStore { // kicks off every subsequent race as results sync down limitTimerRace.start(); - }, 'handle observeQuery observed event') + }, 'handle observeQuery observed event'), ); // returns a set of initial/locally-available results @@ -2395,7 +2395,7 @@ class DataStore { const pagination = this.processPagination(modelDefinition!, options); const sortPredicates = ModelSortPredicateCreator.getPredicates( - pagination!.sort! + pagination!.sort!, ); if (sortPredicates.length) { @@ -2546,7 +2546,7 @@ class DataStore { getModelConstructorByModelName, modelInstanceCreator, this.storageAdapter, - this.sessionId + this.sessionId, ); await this.storage.init(); } @@ -2604,7 +2604,7 @@ class DataStore { */ private processPagination( modelDefinition: SchemaModel, - paginationProducer?: ProducerPaginationInput + paginationProducer?: ProducerPaginationInput, ): PaginationInput | undefined { let sortPredicate: SortPredicate | undefined; const { limit, page, sort } = paginationProducer || {}; @@ -2640,7 +2640,7 @@ class DataStore { if (sort) { sortPredicate = ModelSortPredicateCreator.createFromExisting( modelDefinition, - sort + sort, ); } @@ -2665,7 +2665,7 @@ class DataStore { const syncPredicates = await Promise.all( this.syncExpressions.map( async ( - syncExpression: SyncExpression + syncExpression: SyncExpression, ): Promise<[SchemaModel, ModelPredicate | null]> => { const { modelConstructor, conditionProducer } = await syncExpression; const modelDefinition = getModelDefinition(modelConstructor)!; @@ -2683,20 +2683,20 @@ class DataStore { builder: modelConstructor, schema: modelDefinition, pkField: extractPrimaryKeyFieldNames(modelDefinition), - }) - ) + }), + ), ).toStoragePredicate(); return [modelDefinition, predicate]; - } - ) + }, + ), ); return this.weakMapFromEntries(syncPredicates); } private async unwrapPromise( - conditionProducer + conditionProducer, ): Promise> { try { const condition = await conditionProducer(); @@ -2710,14 +2710,14 @@ class DataStore { } private weakMapFromEntries( - entries: [SchemaModel, ModelPredicate | null][] + entries: [SchemaModel, ModelPredicate | null][], ): WeakMap> { return entries.reduce((map, [modelDefinition, predicate]) => { if (map.has(modelDefinition)) { const { name } = modelDefinition; logger.warn( `You can only utilize one Sync Expression per model. - Subsequent sync expressions for the ${name} model will be ignored.` + Subsequent sync expressions for the ${name} model will be ignored.`, ); return map; } diff --git a/packages/datastore/src/predicates/index.ts b/packages/datastore/src/predicates/index.ts index 19dddd5d546..db85998f027 100644 --- a/packages/datastore/src/predicates/index.ts +++ b/packages/datastore/src/predicates/index.ts @@ -14,7 +14,7 @@ export { ModelSortPredicateCreator } from './sort'; const predicatesAllSet = new WeakSet>(); export function isPredicatesAll( - predicate: any + predicate: any, ): predicate is typeof PredicateAll { return predicatesAllSet.has(predicate); } @@ -122,7 +122,7 @@ export class ModelPredicateCreator { * @param predicate The storage predicate (lookup key) to test. */ static isValidPredicate( - predicate: any + predicate: any, ): predicate is ModelPredicate { return ModelPredicateCreator.predicateGroupsMap.has(predicate); } @@ -140,7 +140,7 @@ export class ModelPredicateCreator { */ static getPredicates( predicate: ModelPredicate, - throwOnInvalid: boolean = true + throwOnInvalid: boolean = true, ) { if (throwOnInvalid && !ModelPredicateCreator.isValidPredicate(predicate)) { throw new Error('The predicate is not valid'); @@ -159,7 +159,7 @@ export class ModelPredicateCreator { */ static createForPk( modelDefinition: SchemaModel, - model: T + model: T, ) { const keyFields = extractPrimaryKeyFieldNames(modelDefinition); const keyValues = extractPrimaryKeyValues(model, keyFields); @@ -185,7 +185,7 @@ export class ModelPredicateCreator { */ static createFromFlatEqualities( modelDefinition: SchemaModel, - flatEqualities: Record + flatEqualities: Record, ) { const ast = { and: Object.entries(flatEqualities).map(([k, v]) => ({ [k]: { eq: v } })), @@ -217,7 +217,7 @@ export class ModelPredicateCreator { static transformGraphQLFilterNodeToPredicateAST(gql: any) { if (!isValid(gql)) { throw new Error( - 'Invalid GraphQL Condition or subtree: ' + JSON.stringify(gql) + 'Invalid GraphQL Condition or subtree: ' + JSON.stringify(gql), ); } @@ -229,7 +229,7 @@ export class ModelPredicateCreator { } else if (isGroup(gql)) { const groupkey = Object.keys(gql)[0]; const children = this.transformGraphQLFilterNodeToPredicateAST( - gql[groupkey] + gql[groupkey], ); return { type: groupkey, @@ -278,13 +278,13 @@ export class ModelPredicateCreator { */ static createFromAST( modelDefinition: SchemaModel, - ast: any + ast: any, ): ModelPredicate { const key = {} as ModelPredicate; ModelPredicateCreator.predicateGroupsMap.set( key, - this.transformGraphQLFilterNodeToPredicateAST(ast) + this.transformGraphQLFilterNodeToPredicateAST(ast), ); return key; diff --git a/packages/datastore/src/predicates/next.ts b/packages/datastore/src/predicates/next.ts index b4acf3642ea..08362dc9df6 100644 --- a/packages/datastore/src/predicates/next.ts +++ b/packages/datastore/src/predicates/next.ts @@ -29,7 +29,7 @@ type UntypedCondition = { fetch: (storage: StorageAdapter) => Promise[]>; matches: (item: Record) => Promise; copy( - extract?: GroupCondition + extract?: GroupCondition, ): [UntypedCondition, GroupCondition | undefined]; toAST(): any; }; @@ -69,7 +69,7 @@ const registerPredicateInternals = (condition: GroupCondition, key?: any) => { export const internals = (key: any) => { if (!predicateInternalsMap.has(key)) { throw new Error( - "Invalid predicate. Terminate your predicate with a valid condition (e.g., `p => p.field.eq('value')`) or pass `Predicates.ALL`." + "Invalid predicate. Terminate your predicate with a valid condition (e.g., `p => p.field.eq('value')`) or pass `Predicates.ALL`.", ); } return predicateInternalsMap.get(key)!; @@ -103,7 +103,7 @@ export class FieldCondition { constructor( public field: string, public operator: string, - public operands: string[] + public operands: string[], ) { this.validate(); } @@ -180,7 +180,7 @@ export class FieldCondition { return new FieldCondition( this.field, negations[this.operator], - this.operands + this.operands, ); } } @@ -345,7 +345,7 @@ export class GroupCondition { * This is used to guard against infinitely fetch -> optimize -> fetch * recursion. */ - public isOptimized: boolean = false + public isOptimized: boolean = false, ) {} /** @@ -360,7 +360,7 @@ export class GroupCondition { this.field, this.relationshipType, this.operator, - [] + [], ); let extractedCopy: GroupCondition | undefined = @@ -397,8 +397,8 @@ export class GroupCondition { this.operands .filter(o => o instanceof FieldCondition) .map(o => - negateChildren ? (o as FieldCondition).negated(this.model) : o - ) + negateChildren ? (o as FieldCondition).negated(this.model) : o, + ), ); } @@ -440,7 +440,7 @@ export class GroupCondition { */ optimized(preserveNode = true): UntypedCondition { const operands = this.operands.map(o => - o instanceof GroupCondition ? o.optimized(this.operator === 'not') : o + o instanceof GroupCondition ? o.optimized(this.operator === 'not') : o, ); // we're only collapsing and/or groups that contains a single child for now, @@ -474,7 +474,7 @@ export class GroupCondition { this.relationshipType, this.operator, operands, - true + true, ); } @@ -489,7 +489,7 @@ export class GroupCondition { async fetch( storage: StorageAdapter, breadcrumb: string[] = [], - negate = false + negate = false, ): Promise[]> { if (!this.isOptimized) { return this.optimized().fetch(storage); @@ -512,21 +512,21 @@ export class GroupCondition { * candidate results are selected to match those. */ const groups = this.operands.filter( - op => op instanceof GroupCondition + op => op instanceof GroupCondition, ) as GroupCondition[]; /** * Simple conditions that must match the target model of `this`. */ const conditions = this.operands.filter( - op => op instanceof FieldCondition + op => op instanceof FieldCondition, ) as FieldCondition[]; for (const g of groups) { const relatives = await g.fetch( storage, [...breadcrumb, this.groupId], - negateChildren + negateChildren, ); // no relatives -> no need to attempt to perform a "join" query for @@ -583,7 +583,7 @@ export class GroupCondition { this.model.schema, { or: allJoinConditions, - } + }, ); resultGroups.push(await storage.query(this.model.builder, predicate)); @@ -627,7 +627,7 @@ export class GroupCondition { resultIndex = new Map(group.map(item => [getPKValue(item), item])); } else { const intersectWith = new Map>( - group.map(item => [getPKValue(item), item]) + group.map(item => [getPKValue(item), item]), ); for (const k of resultIndex.keys()) { if (!intersectWith.has(k)) { @@ -665,7 +665,7 @@ export class GroupCondition { */ async matches( item: Record, - ignoreFieldName: boolean = false + ignoreFieldName: boolean = false, ): Promise { const itemToCheck = this.field && !ignoreFieldName ? await item[this.field] : item; @@ -696,7 +696,7 @@ export class GroupCondition { } else if (this.operator === 'not') { if (this.operands.length !== 1) { throw new Error( - 'Invalid arguments! `not()` accepts exactly one predicate expression.' + 'Invalid arguments! `not()` accepts exactly one predicate expression.', ); } return !(await this.operands[0].matches(itemToCheck)); @@ -725,7 +725,7 @@ export class GroupCondition { toStoragePredicate(): StoragePredicate { return FlatModelPredicateCreator.createFromAST( this.model.schema, - this.toAST() + this.toAST(), ) as StoragePredicate; } @@ -772,7 +772,7 @@ export function recursivePredicateFor( allowRecursion: boolean = true, field?: string, query?: GroupCondition, - tail?: GroupCondition + tail?: GroupCondition, ): RecursiveModelPredicate & PredicateInternalsKey { // to be used if we don't have a base query or tail to build onto const starter = new GroupCondition(ModelType, field, undefined, 'and', []); @@ -794,7 +794,7 @@ export function recursivePredicateFor( allowRecursion, undefined, query, - newTail + newTail, ); return { query, newTail, newLink }; }; @@ -808,11 +808,11 @@ export function recursivePredicateFor( const { query, newTail } = copyLink(); const childConditions = builder( - recursivePredicateFor(ModelType, allowRecursion) + recursivePredicateFor(ModelType, allowRecursion), ); if (!Array.isArray(childConditions)) { throw new Error( - `Invalid predicate. \`${op}\` groups must return an array of child conditions.` + `Invalid predicate. \`${op}\` groups must return an array of child conditions.`, ); } @@ -824,8 +824,8 @@ export function recursivePredicateFor( field, undefined, op as 'and' | 'or', - childConditions.map(c => internals(c)) - ) + childConditions.map(c => internals(c)), + ), ); // FinalPredicate @@ -835,7 +835,7 @@ export function recursivePredicateFor( // TODO: If revisiting this code, consider proxy. link.not = ( - builder: RecursiveModelPredicateExtender + builder: RecursiveModelPredicateExtender, ): PredicateInternalsKey => { // not() will return a copy of the original link // to head off mutability concerns. @@ -847,7 +847,7 @@ export function recursivePredicateFor( newTail?.operands.push( new GroupCondition(ModelType, field, undefined, 'not', [ internals(builder(recursivePredicateFor(ModelType, allowRecursion))), - ]) + ]), ); // A `FinalModelPredicate`. @@ -886,13 +886,13 @@ export function recursivePredicateFor( // normalize operands. if any of the values are `undefiend`, use // `null` instead, because that's what will be stored cross-platform. const normalizedOperands = operands.map(o => - o === undefined ? null : o + o === undefined ? null : o, ); // add the given condition to the link's TAIL node. // remember: the base link might go N nodes deep! e.g., newTail?.operands.push( - new FieldCondition(fieldName, operator, normalizedOperands) + new FieldCondition(fieldName, operator, normalizedOperands), ); // A `FinalModelPredicate`. @@ -905,7 +905,7 @@ export function recursivePredicateFor( } else { if (!allowRecursion) { throw new Error( - 'Predication on releated models is not supported in this context.' + 'Predication on releated models is not supported in this context.', ); } else if ( def.association.connectionType === 'BELONGS_TO' || @@ -918,7 +918,7 @@ export function recursivePredicateFor( const relatedMeta = (def.type as ModelFieldType).modelConstructor; if (!relatedMeta) { throw new Error( - 'Related model metadata is missing. This is a bug! Please report it.' + 'Related model metadata is missing. This is a bug! Please report it.', ); } @@ -931,7 +931,7 @@ export function recursivePredicateFor( fieldName, def.association.connectionType, 'and', - [] + [], ); // `oldtail` here refers to the *copy* of the old tail. @@ -943,12 +943,12 @@ export function recursivePredicateFor( allowRecursion, undefined, newquery, - newtail + newtail, ); return newlink; } else { throw new Error( - "Related model definition doesn't have a typedef. This is a bug! Please report it." + "Related model definition doesn't have a typedef. This is a bug! Please report it.", ); } } @@ -960,7 +960,7 @@ export function recursivePredicateFor( } export function predicateFor( - ModelType: ModelMeta + ModelType: ModelMeta, ): ModelPredicate & PredicateInternalsKey { // the cast here is just a cheap way to reduce the surface area from // the recursive type. diff --git a/packages/datastore/src/predicates/sort.ts b/packages/datastore/src/predicates/sort.ts index 7a5ab34d1ff..99f0e47b077 100644 --- a/packages/datastore/src/predicates/sort.ts +++ b/packages/datastore/src/predicates/sort.ts @@ -16,7 +16,7 @@ export class ModelSortPredicateCreator { >(); private static createPredicateBuilder( - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ) { const { name: modelName } = modelDefinition; const fieldNames = new Set(Object.keys(modelDefinition.fields)); @@ -31,8 +31,8 @@ export class ModelSortPredicateCreator { if (!fieldNames.has(field)) { throw new Error( `Invalid field for model. field: ${String( - field - )}, model: ${modelName}` + field, + )}, model: ${modelName}`, ); } @@ -45,7 +45,7 @@ export class ModelSortPredicateCreator { }; return result; }, - }) + }), ); ModelSortPredicateCreator.sortPredicateGroupsMap.set(predicate, []); @@ -54,14 +54,14 @@ export class ModelSortPredicateCreator { } static isValidPredicate( - predicate: any + predicate: any, ): predicate is SortPredicate { return ModelSortPredicateCreator.sortPredicateGroupsMap.has(predicate); } static getPredicates( predicate: SortPredicate, - throwOnInvalid: boolean = true + throwOnInvalid: boolean = true, ): SortPredicatesGroup { if ( throwOnInvalid && @@ -82,14 +82,14 @@ export class ModelSortPredicateCreator { // transforms cb-style predicate into Proxy static createFromExisting( modelDefinition: SchemaModel, - existing: ProducerSortPredicate + existing: ProducerSortPredicate, ) { if (!existing || !modelDefinition) { return undefined; } return existing( - ModelSortPredicateCreator.createPredicateBuilder(modelDefinition) + ModelSortPredicateCreator.createPredicateBuilder(modelDefinition), ); } } diff --git a/packages/datastore/src/storage/adapter/AsyncStorageAdapter.ts b/packages/datastore/src/storage/adapter/AsyncStorageAdapter.ts index 07d535aed70..9be4d353755 100644 --- a/packages/datastore/src/storage/adapter/AsyncStorageAdapter.ts +++ b/packages/datastore/src/storage/adapter/AsyncStorageAdapter.ts @@ -52,7 +52,7 @@ export class AsyncStorageAdapter extends StorageAdapterBase { async batchSave( modelConstructor: PersistentModelConstructor, - items: ModelInstanceMetadata[] + items: ModelInstanceMetadata[], ): Promise<[T, OpType][]> { if (items.length === 0) { return []; @@ -72,7 +72,7 @@ export class AsyncStorageAdapter extends StorageAdapterBase { model, this.schema.namespaces[namespaceName], this.modelInstanceCreator, - this.getModelConstructorByModelName + this.getModelConstructorByModelName, ); const keyValuesPath = this.getIndexKeyValuesPath(model); @@ -90,7 +90,7 @@ export class AsyncStorageAdapter extends StorageAdapterBase { protected async _get(storeName: string, keyArr: string[]): Promise { const itemKeyValuesPath: string = keyArr.join( - DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR + DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR, ); return await this.db.get(itemKeyValuesPath, storeName); @@ -98,7 +98,7 @@ export class AsyncStorageAdapter extends StorageAdapterBase { async save( model: T, - condition?: ModelPredicate + condition?: ModelPredicate, ): Promise<[T, OpType.INSERT | OpType.UPDATE][]> { const { storeName, connectionStoreNames, modelKeyValues } = this.saveMetadata(model); @@ -124,7 +124,7 @@ export class AsyncStorageAdapter extends StorageAdapterBase { item, storeName, keys, - itemKeyValues.join(DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR) + itemKeyValues.join(DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR), ); result.push([instance, opType]); @@ -136,7 +136,7 @@ export class AsyncStorageAdapter extends StorageAdapterBase { async query( modelConstructor: PersistentModelConstructor, predicate?: ModelPredicate, - pagination?: PaginationInput + pagination?: PaginationInput, ): Promise { const { storeName, @@ -172,20 +172,20 @@ export class AsyncStorageAdapter extends StorageAdapterBase { private async getByKey( storeName: string, - keyValuePath: string + keyValuePath: string, ): Promise { return await this.db.get(keyValuePath, storeName); } private async getAll( - storeName: string + storeName: string, ): Promise { return await this.db.getAll(storeName); } private async filterOnPredicate( storeName: string, - predicates: PredicatesGroup + predicates: PredicatesGroup, ) { const { predicates: predicateObjs, type } = predicates; @@ -200,14 +200,14 @@ export class AsyncStorageAdapter extends StorageAdapterBase { private inMemoryPagination( records: T[], - pagination?: PaginationInput + pagination?: PaginationInput, ): T[] { return inMemoryPagination(records, pagination); } async queryOne( modelConstructor: PersistentModelConstructor, - firstOrLast: QueryOne = QueryOne.FIRST + firstOrLast: QueryOne = QueryOne.FIRST, ): Promise { const storeName = this.getStorenameForModel(modelConstructor); const result = await this.db.getOne(firstOrLast, storeName); @@ -216,7 +216,7 @@ export class AsyncStorageAdapter extends StorageAdapterBase { } protected async deleteItem( - deleteQueue?: { storeName: string; items: T[] | IDBValidKey[] }[] + deleteQueue?: { storeName: string; items: T[] | IDBValidKey[] }[], ) { for await (const deleteItem of deleteQueue!) { const { storeName, items } = deleteItem; @@ -242,7 +242,7 @@ export class AsyncStorageAdapter extends StorageAdapterBase { */ private getIndexKeyValuesPath(model: T): string { return this.getIndexKeyValuesFromModel(model).join( - DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR + DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR, ); } diff --git a/packages/datastore/src/storage/adapter/AsyncStorageDatabase.ts b/packages/datastore/src/storage/adapter/AsyncStorageDatabase.ts index 99fc190c4e1..b78c81c3658 100644 --- a/packages/datastore/src/storage/adapter/AsyncStorageDatabase.ts +++ b/packages/datastore/src/storage/adapter/AsyncStorageDatabase.ts @@ -105,7 +105,7 @@ class AsyncStorageDatabase { item: T, storeName: string, keys: string[], - keyValuesPath: string + keyValuesPath: string, ) { const idxName = indexNameFromKeys(keys); @@ -126,7 +126,7 @@ class AsyncStorageDatabase { async batchSave( storeName: string, items: ModelInstanceMetadata[], - keys: string[] + keys: string[], ): Promise<[T, OpType][]> { if (items.length === 0) { return []; @@ -157,7 +157,7 @@ class AsyncStorageDatabase { const key = this.getKeyForItem( storeName, keyValues.join(DEFAULT_PRIMARY_KEY_VALUE_SEPARATOR), - ulid + ulid, ); allItemsKeys.push(key); @@ -252,7 +252,7 @@ class AsyncStorageDatabase { async get( keyValuePath: string, - storeName: string + storeName: string, ): Promise { const ulid = this.getCollectionIndex(storeName)!.get(keyValuePath)!; const itemKey = this.getKeyForItem(storeName, keyValuePath, ulid); @@ -270,12 +270,12 @@ class AsyncStorageDatabase { let id: string, ulid: string; for ([id, ulid] of collection) break; // Get first element of the set return [id!, ulid!]; - })() + })() : (() => { let id: string, ulid: string; for ([id, ulid] of collection); // Get last element of the set return [id!, ulid!]; - })(); + })(); const itemKey = this.getKeyForItem(storeName, itemId, ulid); const itemString = itemKey && (await this.storage.getItem(itemKey)); @@ -291,7 +291,7 @@ class AsyncStorageDatabase { */ async getAll( storeName: string, - pagination?: PaginationInput + pagination?: PaginationInput, ): Promise { const collection = this.getCollectionIndex(storeName)!; diff --git a/packages/datastore/src/storage/adapter/InMemoryStore.ts b/packages/datastore/src/storage/adapter/InMemoryStore.ts index 0a7c463c2c2..0ea858f59dc 100644 --- a/packages/datastore/src/storage/adapter/InMemoryStore.ts +++ b/packages/datastore/src/storage/adapter/InMemoryStore.ts @@ -10,7 +10,7 @@ export class InMemoryStore { multiGet = async (keys: string[]) => { return keys.reduce( (res, k) => (res.push([k, this.db.get(k)!]), res), - [] as [string, string][] + [] as [string, string][], ); }; diff --git a/packages/datastore/src/storage/adapter/IndexedDBAdapter.ts b/packages/datastore/src/storage/adapter/IndexedDBAdapter.ts index 0efe2964331..d059dd996d8 100644 --- a/packages/datastore/src/storage/adapter/IndexedDBAdapter.ts +++ b/packages/datastore/src/storage/adapter/IndexedDBAdapter.ts @@ -90,7 +90,7 @@ class IndexedDBAdapter extends StorageAdapterBase { db, namespaceName, storeName, - modelName + modelName, ); }); }); @@ -124,7 +124,7 @@ class IndexedDBAdapter extends StorageAdapterBase { db, namespaceName, storeName, - modelName + modelName, ); let cursor = await origStore.openCursor(); @@ -162,7 +162,7 @@ class IndexedDBAdapter extends StorageAdapterBase { db, namespaceName, storeName, - modelName + modelName, ); }); }); @@ -180,7 +180,7 @@ class IndexedDBAdapter extends StorageAdapterBase { protected async _get( storeOrStoreName: idb.IDBPObjectStore | string, - keyArr: string[] + keyArr: string[], ): Promise { let index: idb.IDBPIndex; @@ -209,7 +209,7 @@ class IndexedDBAdapter extends StorageAdapterBase { async save( model: T, - condition?: ModelPredicate + condition?: ModelPredicate, ): Promise<[T, OpType.INSERT | OpType.UPDATE][]> { await this.checkPrivate(); @@ -218,7 +218,7 @@ class IndexedDBAdapter extends StorageAdapterBase { const tx = this.db.transaction( [storeName, ...Array.from(set.values())], - 'readwrite' + 'readwrite', ); const store = tx.objectStore(storeName); @@ -255,7 +255,7 @@ class IndexedDBAdapter extends StorageAdapterBase { async query( modelConstructor: PersistentModelConstructor, predicate?: ModelPredicate, - pagination?: PaginationInput + pagination?: PaginationInput, ): Promise { await this.checkPrivate(); const { @@ -306,7 +306,7 @@ class IndexedDBAdapter extends StorageAdapterBase { async queryOne( modelConstructor: PersistentModelConstructor, - firstOrLast: QueryOne = QueryOne.FIRST + firstOrLast: QueryOne = QueryOne.FIRST, ): Promise { await this.checkPrivate(); const storeName = this.getStorenameForModel(modelConstructor); @@ -323,7 +323,7 @@ class IndexedDBAdapter extends StorageAdapterBase { async batchSave( modelConstructor: PersistentModelConstructor, - items: ModelInstanceMetadata[] + items: ModelInstanceMetadata[], ): Promise<[T, OpType][]> { await this.checkPrivate(); @@ -347,7 +347,7 @@ class IndexedDBAdapter extends StorageAdapterBase { model, this.schema.namespaces[namespaceName], this.modelInstanceCreator, - this.getModelConstructorByModelName! + this.getModelConstructorByModelName!, ); const keyValues = this.getIndexKeyValuesFromModel(model); @@ -386,7 +386,7 @@ class IndexedDBAdapter extends StorageAdapterBase { deleteQueue: { storeName: string; items: T[] | IDBValidKey[]; - }[] + }[], ) { const connectionStoreNames = deleteQueue!.map(({ storeName }) => { return storeName; @@ -428,7 +428,7 @@ class IndexedDBAdapter extends StorageAdapterBase { if (isPrivate) { logger.error("IndexedDB not supported in this browser's private mode"); return Promise.reject( - "IndexedDB not supported in this browser's private mode" + "IndexedDB not supported in this browser's private mode", ); } else { return Promise.resolve(); @@ -465,7 +465,7 @@ class IndexedDBAdapter extends StorageAdapterBase { db: idb.IDBPDatabase, namespaceName: string, storeName: string, - modelName: string + modelName: string, ): idb.IDBPObjectStore { const store = db.createObjectStore(storeName, { autoIncrement: true, @@ -483,13 +483,13 @@ class IndexedDBAdapter extends StorageAdapterBase { private async getByKey( storeName: string, - keyValue: string[] + keyValue: string[], ): Promise { return await this._get(storeName, keyValue); } private async getAll( - storeName: string + storeName: string, ): Promise { return await this.db.getAll(storeName); } @@ -506,7 +506,7 @@ class IndexedDBAdapter extends StorageAdapterBase { private matchingIndexQueries( storeName: string, predicates: PredicateObject[], - transaction: idb.IDBPTransaction + transaction: idb.IDBPTransaction, ) { // could be expanded later to include `exec()` and a `cardinality` estimate? const queries: (() => Promise)[] = []; @@ -541,7 +541,7 @@ class IndexedDBAdapter extends StorageAdapterBase { .transaction(storeName) .objectStore(storeName) .index(name) - .getAll(this.canonicalKeyPath(matchingPredicateValues)) + .getAll(this.canonicalKeyPath(matchingPredicateValues)), ); } } @@ -552,7 +552,7 @@ class IndexedDBAdapter extends StorageAdapterBase { private async baseQueryIndex( storeName: string, predicates: PredicatesGroup, - transaction?: idb.IDBPTransaction | undefined + transaction?: idb.IDBPTransaction | undefined, ) { let { predicates: predicateObjs, type } = predicates; @@ -570,7 +570,7 @@ class IndexedDBAdapter extends StorageAdapterBase { } const fieldPredicates = predicateObjs.filter( - p => isPredicateObj(p) && p.operator === 'eq' + p => isPredicateObj(p) && p.operator === 'eq', ) as PredicateObject[]; // several sub-queries could occur here. explicitly start a txn here to avoid @@ -596,12 +596,12 @@ class IndexedDBAdapter extends StorageAdapterBase { predicateObjs .filter(o => isPredicateGroup(o) && o.type === 'and') .map(o => - this.baseQueryIndex(storeName, o as PredicatesGroup, txn) - ) + this.baseQueryIndex(storeName, o as PredicatesGroup, txn), + ), ).then(queries => queries .filter(q => q.indexedQueries.length === 1) - .map(i => i.indexedQueries) + .map(i => i.indexedQueries), ); /** @@ -610,7 +610,7 @@ class IndexedDBAdapter extends StorageAdapterBase { const objectQueries = predicateObjs .filter(o => isPredicateObj(o)) .map(o => - this.matchingIndexQueries(storeName, [o as PredicateObject], txn) + this.matchingIndexQueries(storeName, [o as PredicateObject], txn), ); const indexedQueries = [...groupQueries, ...objectQueries] @@ -639,7 +639,7 @@ class IndexedDBAdapter extends StorageAdapterBase { indexedQueries: this.matchingIndexQueries( storeName, fieldPredicates, - txn + txn, ), }; } else { @@ -660,13 +660,13 @@ class IndexedDBAdapter extends StorageAdapterBase { private async filterOnPredicate( storeName: string, - predicates: PredicatesGroup + predicates: PredicatesGroup, ) { const { predicates: predicateObjs, type } = predicates; const { groupType, indexedQueries } = await this.baseQueryIndex( storeName, - predicates + predicates, ); // where we'll accumulate candidate results, which will be filtered at the end. @@ -714,14 +714,14 @@ class IndexedDBAdapter extends StorageAdapterBase { private inMemoryPagination( records: T[], - pagination?: PaginationInput + pagination?: PaginationInput, ): T[] { return inMemoryPagination(records, pagination); } private async enginePagination( storeName: string, - pagination?: PaginationInput + pagination?: PaginationInput, ): Promise { let result: T[]; diff --git a/packages/datastore/src/storage/adapter/StorageAdapterBase.ts b/packages/datastore/src/storage/adapter/StorageAdapterBase.ts index 119eaf530c3..8936979f79f 100644 --- a/packages/datastore/src/storage/adapter/StorageAdapterBase.ts +++ b/packages/datastore/src/storage/adapter/StorageAdapterBase.ts @@ -44,7 +44,7 @@ export abstract class StorageAdapterBase implements Adapter { protected modelInstanceCreator!: ModelInstanceCreator; protected getModelConstructorByModelName!: ( namsespaceName: NAMESPACES, - modelName: string + modelName: string, ) => PersistentModelConstructor; protected initPromise!: Promise; protected resolve!: (value?: any) => void; @@ -71,9 +71,9 @@ export abstract class StorageAdapterBase implements Adapter { modelInstanceCreator: ModelInstanceCreator, getModelConstructorByModelName: ( namsespaceName: NAMESPACES, - modelName: string + modelName: string, ) => PersistentModelConstructor, - sessionId?: string + sessionId?: string, ): Promise { await this.preSetUpChecks(); @@ -113,23 +113,23 @@ export abstract class StorageAdapterBase implements Adapter { public abstract save( model: T, - condition?: ModelPredicate + condition?: ModelPredicate, ); public abstract query( modelConstructor: PersistentModelConstructor, predicate?: ModelPredicate, - pagination?: PaginationInput + pagination?: PaginationInput, ): Promise; public abstract queryOne( modelConstructor: PersistentModelConstructor, - firstOrLast: QueryOne + firstOrLast: QueryOne, ): Promise; public abstract batchSave( modelConstructor: PersistentModelConstructor, - items: ModelInstanceMetadata[] + items: ModelInstanceMetadata[], ): Promise<[T, OpType][]>; /** @@ -137,7 +137,7 @@ export abstract class StorageAdapterBase implements Adapter { * @returns local DB table name */ protected getStorenameForModel( - modelConstructor: PersistentModelConstructor + modelConstructor: PersistentModelConstructor, ): string { const namespace = this.namespaceResolver(modelConstructor); const { name: modelName } = modelConstructor; @@ -151,7 +151,7 @@ export abstract class StorageAdapterBase implements Adapter { * @returns the record's primary key values */ protected getIndexKeyValuesFromModel( - model: T + model: T, ): string[] { const modelConstructor = Object.getPrototypeOf(model) .constructor as PersistentModelConstructor; @@ -159,7 +159,7 @@ export abstract class StorageAdapterBase implements Adapter { const keys = getIndexKeys( this.schema.namespaces[namespaceName], - modelConstructor.name + modelConstructor.name, ); return extractPrimaryKeyValues(model, keys); @@ -172,7 +172,7 @@ export abstract class StorageAdapterBase implements Adapter { * @param model */ protected saveMetadata( - model: T + model: T, ): { storeName: string; set: Set; @@ -189,7 +189,7 @@ export abstract class StorageAdapterBase implements Adapter { model, this.schema.namespaces[namespaceName], this.modelInstanceCreator, - this.getModelConstructorByModelName! + this.getModelConstructorByModelName!, ); const set = new Set(); @@ -199,10 +199,10 @@ export abstract class StorageAdapterBase implements Adapter { set.add(storeName); const keys = getIndexKeys( this.schema.namespaces[namespaceName], - modelName + modelName, ); return { storeName, item, instance, keys }; - } + }, ); const modelKeyValues = this.getIndexKeyValuesFromModel(model); @@ -218,7 +218,7 @@ export abstract class StorageAdapterBase implements Adapter { */ protected validateSaveCondition( condition?: ModelPredicate, - fromDB?: unknown + fromDB?: unknown, ): void { if (!(condition && fromDB)) { return; @@ -239,7 +239,7 @@ export abstract class StorageAdapterBase implements Adapter { protected abstract _get( storeOrStoreName: IDBPObjectStore | string, - keyArr: string[] + keyArr: string[], ): Promise; /** @@ -253,7 +253,7 @@ export abstract class StorageAdapterBase implements Adapter { protected async load( namespaceName: NAMESPACES, srcModelName: string, - records: T[] + records: T[], ): Promise { const namespace = this.schema.namespaces[namespaceName]; const relations = namespace.relationships![srcModelName].relationTypes; @@ -262,17 +262,17 @@ export abstract class StorageAdapterBase implements Adapter { }); const modelConstructor = this.getModelConstructorByModelName!( namespaceName, - srcModelName + srcModelName, ); if (connectionStoreNames.length === 0) { return records.map(record => - this.modelInstanceCreator(modelConstructor, record) + this.modelInstanceCreator(modelConstructor, record), ); } return records.map(record => - this.modelInstanceCreator(modelConstructor, record) + this.modelInstanceCreator(modelConstructor, record), ); } @@ -295,7 +295,7 @@ export abstract class StorageAdapterBase implements Adapter { */ private keyValueFromPredicate( predicates: PredicatesGroup, - keyPath: string[] + keyPath: string[], ): string[] | undefined { const { predicates: predicateObjs } = predicates; @@ -314,7 +314,7 @@ export abstract class StorageAdapterBase implements Adapter { p.field === key && p.operator === 'eq' && p.operand !== null && - p.operand !== undefined + p.operand !== undefined, ) as PredicateObject; predicateObj && keyValues.push(predicateObj.operand); @@ -334,18 +334,18 @@ export abstract class StorageAdapterBase implements Adapter { protected queryMetadata( modelConstructor: PersistentModelConstructor, predicate?: ModelPredicate, - pagination?: PaginationInput + pagination?: PaginationInput, ) { const storeName = this.getStorenameForModel(modelConstructor); const namespaceName = this.namespaceResolver( - modelConstructor + modelConstructor, ) as NAMESPACES; const predicates = predicate && ModelPredicateCreator.getPredicates(predicate); const keyPath = getIndexKeys( this.schema.namespaces[namespaceName], - modelConstructor.name + modelConstructor.name, ); const queryByKey = predicates && this.keyValueFromPredicate(predicates, keyPath); @@ -373,7 +373,7 @@ export abstract class StorageAdapterBase implements Adapter { */ public async delete( modelOrModelConstructor: T | PersistentModelConstructor, - condition?: ModelPredicate + condition?: ModelPredicate, ): Promise<[T[], T[]]> { await this.preOpCheck(); @@ -390,14 +390,14 @@ export abstract class StorageAdapterBase implements Adapter { models, modelConstructor, namespace, - deleteQueue + deleteQueue, ); await this.deleteItem(deleteQueue); const deletedModels = deleteQueue.reduce( (acc, { items }) => acc.concat(items), - [] + [], ); return [models, deletedModels]; @@ -406,14 +406,14 @@ export abstract class StorageAdapterBase implements Adapter { models, modelConstructor, namespace, - deleteQueue + deleteQueue, ); await this.deleteItem(deleteQueue); const deletedModels = deleteQueue.reduce( (acc, { items }) => acc.concat(items), - [] + [], ); return [models, deletedModels]; @@ -425,7 +425,7 @@ export abstract class StorageAdapterBase implements Adapter { .constructor as PersistentModelConstructor; const namespaceName = this.namespaceResolver( - modelConstructor + modelConstructor, ) as NAMESPACES; const storeName = this.getStorenameForModel(modelConstructor); @@ -457,21 +457,21 @@ export abstract class StorageAdapterBase implements Adapter { [model], modelConstructor, namespaceName, - deleteQueue + deleteQueue, ); } else { await this.deleteTraverse( [model], modelConstructor, namespaceName, - deleteQueue + deleteQueue, ); } await this.deleteItem(deleteQueue); const deletedModels = deleteQueue.reduce( (acc, { items }) => acc.concat(items), - [] + [], ); return [[model], deletedModels]; @@ -482,7 +482,7 @@ export abstract class StorageAdapterBase implements Adapter { deleteQueue?: { storeName: string; items: T[] | IDBValidKey[]; - }[] + }[], ); /** @@ -500,7 +500,7 @@ export abstract class StorageAdapterBase implements Adapter { models: T[], modelConstructor: PersistentModelConstructor, namespace: NAMESPACES, - deleteQueue: { storeName: string; items: T[] }[] + deleteQueue: { storeName: string; items: T[] }[], ): Promise { const cascadingRelationTypes = ['HAS_ONE', 'HAS_MANY']; @@ -515,7 +515,7 @@ export abstract class StorageAdapterBase implements Adapter { }; const relationships = ModelRelationship.allFrom(modelMeta).filter(r => - cascadingRelationTypes.includes(r.type) + cascadingRelationTypes.includes(r.type), ); for await (const r of relationships) { @@ -525,15 +525,15 @@ export abstract class StorageAdapterBase implements Adapter { r.remoteModelConstructor, ModelPredicateCreator.createFromFlatEqualities( r.remoteDefinition!, - queryObject - ) + queryObject, + ), ); await this.deleteTraverse( relatedRecords, r.remoteModelConstructor, namespace, - deleteQueue + deleteQueue, ); } } diff --git a/packages/datastore/src/storage/adapter/index.ts b/packages/datastore/src/storage/adapter/index.ts index 8150a2f4a6f..84b47c3baf2 100644 --- a/packages/datastore/src/storage/adapter/index.ts +++ b/packages/datastore/src/storage/adapter/index.ts @@ -15,23 +15,23 @@ export interface Adapter extends SystemComponent { clear(): Promise; save( model: T, - condition?: ModelPredicate + condition?: ModelPredicate, ): Promise<[T, OpType.INSERT | OpType.UPDATE][]>; delete: ( modelOrModelConstructor: T | PersistentModelConstructor, - condition?: ModelPredicate + condition?: ModelPredicate, ) => Promise<[T[], T[]]>; query( modelConstructor: PersistentModelConstructor, predicate?: ModelPredicate, - pagination?: PaginationInput + pagination?: PaginationInput, ): Promise; queryOne( modelConstructor: PersistentModelConstructor, - firstOrLast: QueryOne + firstOrLast: QueryOne, ): Promise; batchSave( modelConstructor: PersistentModelConstructor, - items: ModelInstanceMetadata[] + items: ModelInstanceMetadata[], ): Promise<[T, OpType][]>; } diff --git a/packages/datastore/src/storage/storage.ts b/packages/datastore/src/storage/storage.ts index e9cd3f275fd..6912df89751 100644 --- a/packages/datastore/src/storage/storage.ts +++ b/packages/datastore/src/storage/storage.ts @@ -53,11 +53,11 @@ class StorageClass implements StorageFacade { private readonly namespaceResolver: NamespaceResolver, private readonly getModelConstructorByModelName: ( namsespaceName: NAMESPACES, - modelName: string + modelName: string, ) => PersistentModelConstructor, private readonly modelInstanceCreator: ModelInstanceCreator, private readonly adapter?: Adapter, - private readonly sessionId?: string + private readonly sessionId?: string, ) { this.adapter = this.adapter || getDefaultAdapter(); this.pushStream = new Subject(); @@ -95,7 +95,7 @@ class StorageClass implements StorageFacade { this.namespaceResolver, this.modelInstanceCreator, this.getModelConstructorByModelName, - this.sessionId + this.sessionId, ).then(resolve!, reject!); await this.initialized; @@ -105,7 +105,7 @@ class StorageClass implements StorageFacade { model: T, condition?: ModelPredicate, mutator?: Symbol, - patchesTuple?: [Patch[], PersistentModel] + patchesTuple?: [Patch[], PersistentModel], ): Promise<[T, OpType.INSERT | OpType.UPDATE][]> { await this.init(); if (!this.adapter) { @@ -142,7 +142,7 @@ class StorageClass implements StorageFacade { updateMutationInput = this.getChangedFieldsInput( model, savedElement, - patchesTuple + patchesTuple, ); // // an update without changed user fields // => don't create mutationEvent @@ -175,17 +175,17 @@ class StorageClass implements StorageFacade { delete( model: T, condition?: ModelPredicate, - mutator?: Symbol + mutator?: Symbol, ): Promise<[T[], T[]]>; delete( modelConstructor: PersistentModelConstructor, condition?: ModelPredicate, - mutator?: Symbol + mutator?: Symbol, ): Promise<[T[], T[]]>; async delete( modelOrModelConstructor: T | PersistentModelConstructor, condition?: ModelPredicate, - mutator?: Symbol + mutator?: Symbol, ): Promise<[T[], T[]]> { await this.init(); if (!this.adapter) { @@ -197,7 +197,7 @@ class StorageClass implements StorageFacade { [models, deleted] = await this.adapter.delete( modelOrModelConstructor, - condition + condition, ); const modelConstructor = isModelConstructor(modelOrModelConstructor) @@ -213,7 +213,7 @@ class StorageClass implements StorageFacade { models.map(model => { const modelId = getIdentifierValue(modelDefinition, model); return modelId; - }) + }), ); if ( @@ -251,7 +251,7 @@ class StorageClass implements StorageFacade { async query( modelConstructor: PersistentModelConstructor, predicate?: ModelPredicate, - pagination?: PaginationInput + pagination?: PaginationInput, ): Promise { await this.init(); if (!this.adapter) { @@ -263,7 +263,7 @@ class StorageClass implements StorageFacade { async queryOne( modelConstructor: PersistentModelConstructor, - firstOrLast: QueryOne = QueryOne.FIRST + firstOrLast: QueryOne = QueryOne.FIRST, ): Promise { await this.init(); if (!this.adapter) { @@ -276,7 +276,7 @@ class StorageClass implements StorageFacade { observe( modelConstructor?: PersistentModelConstructor | null, predicate?: ModelPredicate | null, - skipOwn?: Symbol + skipOwn?: Symbol, ): Observable> { const listenToAll = !modelConstructor; const { predicates, type } = @@ -287,13 +287,13 @@ class StorageClass implements StorageFacade { .pipe( filter(({ mutator }) => { return !skipOwn || mutator !== skipOwn; - }) + }), ) .pipe( map( ({ mutator: _mutator, ...message }) => - message as SubscriptionMessage - ) + message as SubscriptionMessage, + ), ); if (!listenToAll) { @@ -308,7 +308,7 @@ class StorageClass implements StorageFacade { } return true; - }) + }), ); } @@ -331,7 +331,7 @@ class StorageClass implements StorageFacade { async batchSave( modelConstructor: PersistentModelConstructor, items: ModelInstanceMetadata[], - mutator?: Symbol + mutator?: Symbol, ): Promise<[T, OpType][]> { await this.init(); if (!this.adapter) { @@ -357,7 +357,7 @@ class StorageClass implements StorageFacade { private getChangedFieldsInput( model: T, originalElement: T, - patchesTuple?: [Patch[], PersistentModel] + patchesTuple?: [Patch[], PersistentModel], ): PersistentModel | null { const containsPatches = patchesTuple && patchesTuple.length; if (!containsPatches) { @@ -383,7 +383,7 @@ class StorageClass implements StorageFacade { // set original values for these fields updatedFields.forEach((field: string) => { const targetNames: any = isTargetNameAssociation( - fields[field]?.association + fields[field]?.association, ); if (Array.isArray(targetNames)) { @@ -470,11 +470,11 @@ class ExclusiveStorage implements StorageFacade { namespaceResolver: NamespaceResolver, getModelConstructorByModelName: ( namsespaceName: NAMESPACES, - modelName: string + modelName: string, ) => PersistentModelConstructor, modelInstanceCreator: ModelInstanceCreator, adapter?: Adapter, - sessionId?: string + sessionId?: string, ) { this.storage = new StorageClass( schema, @@ -482,7 +482,7 @@ class ExclusiveStorage implements StorageFacade { getModelConstructorByModelName, modelInstanceCreator, adapter, - sessionId + sessionId, ); } @@ -494,27 +494,27 @@ class ExclusiveStorage implements StorageFacade { model: T, condition?: ModelPredicate, mutator?: Symbol, - patchesTuple?: [Patch[], PersistentModel] + patchesTuple?: [Patch[], PersistentModel], ): Promise<[T, OpType.INSERT | OpType.UPDATE][]> { return this.runExclusive<[T, OpType.INSERT | OpType.UPDATE][]>(storage => - storage.save(model, condition, mutator, patchesTuple) + storage.save(model, condition, mutator, patchesTuple), ); } async delete( model: T, condition?: ModelPredicate, - mutator?: Symbol + mutator?: Symbol, ): Promise<[T[], T[]]>; async delete( modelConstructor: PersistentModelConstructor, condition?: ModelPredicate, - mutator?: Symbol + mutator?: Symbol, ): Promise<[T[], T[]]>; async delete( modelOrModelConstructor: T | PersistentModelConstructor, condition?: ModelPredicate, - mutator?: Symbol + mutator?: Symbol, ): Promise<[T[], T[]]> { return this.runExclusive<[T[], T[]]>(storage => { if (isModelConstructor(modelOrModelConstructor)) { @@ -532,19 +532,19 @@ class ExclusiveStorage implements StorageFacade { async query( modelConstructor: PersistentModelConstructor, predicate?: ModelPredicate, - pagination?: PaginationInput + pagination?: PaginationInput, ): Promise { return this.runExclusive(storage => - storage.query(modelConstructor, predicate, pagination) + storage.query(modelConstructor, predicate, pagination), ); } async queryOne( modelConstructor: PersistentModelConstructor, - firstOrLast: QueryOne = QueryOne.FIRST + firstOrLast: QueryOne = QueryOne.FIRST, ): Promise { return this.runExclusive(storage => - storage.queryOne(modelConstructor, firstOrLast) + storage.queryOne(modelConstructor, firstOrLast), ); } @@ -555,7 +555,7 @@ class ExclusiveStorage implements StorageFacade { observe( modelConstructor?: PersistentModelConstructor | null, predicate?: ModelPredicate | null, - skipOwn?: Symbol + skipOwn?: Symbol, ): Observable> { return this.storage.observe(modelConstructor, predicate, skipOwn); } @@ -566,7 +566,7 @@ class ExclusiveStorage implements StorageFacade { batchSave( modelConstructor: PersistentModelConstructor, - items: ModelInstanceMetadata[] + items: ModelInstanceMetadata[], ): Promise<[T, OpType][]> { return this.storage.batchSave(modelConstructor, items); } diff --git a/packages/datastore/src/sync/datastoreReachability/index.native.ts b/packages/datastore/src/sync/datastoreReachability/index.native.ts index d2993665f4b..8137ab74521 100644 --- a/packages/datastore/src/sync/datastoreReachability/index.native.ts +++ b/packages/datastore/src/sync/datastoreReachability/index.native.ts @@ -4,5 +4,5 @@ import { Reachability } from '@aws-amplify/core/internals/utils'; import { loadNetInfo } from '@aws-amplify/react-native'; export const ReachabilityMonitor = new Reachability().networkMonitor( - loadNetInfo() + loadNetInfo(), ); diff --git a/packages/datastore/src/sync/index.ts b/packages/datastore/src/sync/index.ts index e3b72b8cc1d..bcf1e9c72c3 100644 --- a/packages/datastore/src/sync/index.ts +++ b/packages/datastore/src/sync/index.ts @@ -72,7 +72,7 @@ export declare class MutationEvent { constructor(init: ModelInit); static copyOf( src: MutationEvent, - mutator: (draft: MutableModel) => void | MutationEvent + mutator: (draft: MutableModel) => void | MutationEvent, ): MutationEvent; } @@ -90,7 +90,7 @@ export declare class ModelMetadata { constructor(init: ModelInit); static copyOf( src: ModelMetadata, - mutator: (draft: MutableModel) => void | ModelMetadata + mutator: (draft: MutableModel) => void | ModelMetadata, ): ModelMetadata; } @@ -123,7 +123,7 @@ export class SyncEngine { private unsleepSyncQueriesObservable: (() => void) | null; private waitForSleepState: Promise; private syncQueriesObservableStartSleeping: ( - value?: void | PromiseLike + value?: void | PromiseLike, ) => void; private stopDisruptionListener: () => void; private connectionDisrupted = false; @@ -131,7 +131,7 @@ export class SyncEngine { private runningProcesses: BackgroundProcessManager; public getModelSyncedStatus( - modelConstructor: PersistentModelConstructor + modelConstructor: PersistentModelConstructor, ): boolean { return this.modelSyncedStatus.get(modelConstructor)!; } @@ -152,7 +152,7 @@ export class SyncEngine { private readonly amplifyConfig: Record = {}, private readonly authModeStrategy: AuthModeStrategy, private readonly amplifyContext: AmplifyContext, - private readonly connectivityMonitor?: DataStoreConnectivity + private readonly connectivityMonitor?: DataStoreConnectivity, ) { this.runningProcesses = new BackgroundProcessManager(); this.waitForSleepState = new Promise(resolve => { @@ -167,7 +167,7 @@ export class SyncEngine { this.schema, MutationEvent, modelInstanceCreator, - ownSymbol + ownSymbol, ); this.modelMerger = new ModelMerger(this.outbox, ownSymbol); @@ -178,7 +178,7 @@ export class SyncEngine { this.amplifyConfig, this.authModeStrategy, errorHandler, - this.amplifyContext + this.amplifyContext, ); this.subscriptionsProcessor = new SubscriptionProcessor( @@ -187,7 +187,7 @@ export class SyncEngine { this.amplifyConfig, this.authModeStrategy, errorHandler, - this.amplifyContext + this.amplifyContext, ); this.mutationsProcessor = new MutationProcessor( @@ -201,7 +201,7 @@ export class SyncEngine { this.authModeStrategy, errorHandler, conflictHandler, - this.amplifyContext + this.amplifyContext, ); this.datastoreConnectivity = @@ -268,7 +268,7 @@ export class SyncEngine { this.disconnectionHandler(); handleDisconnect(err); }, - } + }, ); subscriptions.push(ctlSubsSubscription); @@ -336,15 +336,15 @@ export class SyncEngine { const model = this.modelInstanceCreator( modelConstructor, - item + item, ); await this.storage.runExclusive(storage => this.modelMerger.merge( storage, model, - modelDefinition - ) + modelDefinition, + ), ); observer.next({ @@ -361,8 +361,8 @@ export class SyncEngine { isEmpty: !hasMore, }, }); - }, 'mutation processor event') - ) + }, 'mutation processor event'), + ), ); //#endregion @@ -377,18 +377,18 @@ export class SyncEngine { const model = this.modelInstanceCreator( modelConstructor, - item + item, ); await this.storage.runExclusive(storage => this.modelMerger.merge( storage, model, - modelDefinition - ) + modelDefinition, + ), ); - }, 'subscription dataSubsObservable event') - ) + }, 'subscription dataSubsObservable event'), + ), ); //#endregion } else if (!online) { @@ -406,9 +406,9 @@ export class SyncEngine { } doneStarting(); - }, 'datastore connectivity event') + }, 'datastore connectivity event'), ); - } + }, ); this.storage @@ -417,7 +417,7 @@ export class SyncEngine { filter(({ model }) => { const modelDefinition = this.getModelDefinition(model); return modelDefinition.syncable === true; - }) + }), ) .subscribe({ next: async ({ opType, model, element, condition }) => @@ -430,7 +430,7 @@ export class SyncEngine { const modelDefinition = this.getModelDefinition(model); const graphQLCondition = predicateToGraphQLCondition( condition!, - modelDefinition + modelDefinition, ); const mutationEvent = createMutationInstanceFromModelOperation( namespace.relationships!, @@ -440,7 +440,7 @@ export class SyncEngine { element, graphQLCondition, MutationEventConstructor, - this.modelInstanceCreator + this.modelInstanceCreator, ); await this.outbox.enqueue(this.storage, mutationEvent); @@ -492,13 +492,13 @@ export class SyncEngine { } private async getModelsMetadataWithNextFullSync( - currentTimeStamp: number + currentTimeStamp: number, ): Promise> { const modelLastSync: Map = new Map( ( await this.runningProcesses.add( () => this.getModelsMetadata(), - 'sync/index getModelsMetadataWithNextFullSync' + 'sync/index getModelsMetadataWithNextFullSync', ) ).map( ({ @@ -519,8 +519,8 @@ export class SyncEngine { this.schema.namespaces[namespace].models[model], [namespace, syncFrom!], ]; - } - ) + }, + ), ); return modelLastSync; @@ -551,7 +551,7 @@ export class SyncEngine { > = new WeakMap(); const modelLastSync = await this.getModelsMetadataWithNextFullSync( - Date.now() + Date.now(), ); const paginatingModels = new Set(modelLastSync.keys()); @@ -605,7 +605,7 @@ export class SyncEngine { const page = items.filter(item => { const itemId = getIdentifierValue( modelDefinition, - item + item, ); if (!idsInOutbox.has(itemId)) { @@ -622,7 +622,7 @@ export class SyncEngine { const opType = await this.modelMerger.merge( storage, item, - modelDefinition + modelDefinition, ); if (opType !== undefined) { @@ -635,8 +635,8 @@ export class SyncEngine { storage, modelConstructor, page, - modelDefinition - )) + modelDefinition, + )), ); const counts = count.get(modelConstructor)!; @@ -664,7 +664,7 @@ export class SyncEngine { //#region update last sync for type let modelMetadata = await this.getModelMetadata( namespace, - modelName + modelName, ); const { lastFullSync, fullSyncInterval } = modelMetadata; @@ -676,8 +676,8 @@ export class SyncEngine { ? lastFullSync! : Math.max( lastFullSyncStartedAt, - isFullSync ? startedAt : lastFullSync! - ); + isFullSync ? startedAt : lastFullSync!, + ); modelMetadata = ( this.modelClasses @@ -692,7 +692,7 @@ export class SyncEngine { await this.storage.save( modelMetadata, undefined, - ownSymbol + ownSymbol, ); //#endregion @@ -751,8 +751,8 @@ export class SyncEngine { logger.debug( `Next fullSync in ${msNextFullSync / 1000} seconds. (${new Date( - Date.now() + msNextFullSync - )})` + Date.now() + msNextFullSync, + )})`, ); // TODO: create `BackgroundProcessManager.sleep()` ... but, need to put @@ -874,7 +874,7 @@ export class SyncEngine { const modelMetadata = await this.getModelMetadata(namespace, model.name); const syncPredicate = ModelPredicateCreator.getPredicates( this.syncPredicates.get(model)!, - false + false, ); const lastSyncPredicate = syncPredicate ? JSON.stringify(syncPredicate) @@ -891,7 +891,7 @@ export class SyncEngine { lastSyncPredicate, }), undefined, - ownSymbol + ownSymbol, ); } else { const prevSyncPredicate = modelMetadata.lastSyncPredicate @@ -909,7 +909,7 @@ export class SyncEngine { draft.lastFullSync = null!; (draft.lastSyncPredicate as any) = lastSyncPredicate; } - }) + }), ); } @@ -937,14 +937,14 @@ export class SyncEngine { private async getModelMetadata( namespace: string, - model: string + model: string, ): Promise { const ModelMetadata = this.modelClasses .ModelMetadata as PersistentModelConstructor; const predicate = ModelPredicateCreator.createFromAST( this.schema.namespaces[SYNC].models[ModelMetadata.name], - { and: [{ namespace: { eq: namespace } }, { model: { eq: model } }] } + { and: [{ namespace: { eq: namespace } }, { model: { eq: model } }] }, ); const [modelMetadata] = await this.storage.query(ModelMetadata, predicate, { @@ -956,7 +956,7 @@ export class SyncEngine { } private getModelDefinition( - modelConstructor: PersistentModelConstructor + modelConstructor: PersistentModelConstructor, ): SchemaModel { const namespaceName = this.namespaceResolver(modelConstructor); @@ -1122,7 +1122,7 @@ export class SyncEngine { this.waitForSleepState.then(() => { // unsleepSyncQueriesObservable will be set if waitForSleepState has resolved this.unsleepSyncQueriesObservable!(); - }) + }), ) ); } diff --git a/packages/datastore/src/sync/merger.ts b/packages/datastore/src/sync/merger.ts index db947dfb07b..eaf9d3ecab9 100644 --- a/packages/datastore/src/sync/merger.ts +++ b/packages/datastore/src/sync/merger.ts @@ -14,7 +14,7 @@ import { getIdentifierValue } from './utils'; class ModelMerger { constructor( private readonly outbox: MutationEventOutbox, - private readonly ownSymbol: Symbol + private readonly ownSymbol: Symbol, ) {} /** @@ -26,13 +26,13 @@ class ModelMerger { public async merge( storage: Storage, model: T, - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ): Promise { let result: OpType; const mutationsForModel = await this.outbox.getForModel( storage, model, - modelDefinition + modelDefinition, ); const isDelete = model._deleted; @@ -53,7 +53,7 @@ class ModelMerger { storage: Storage, modelConstructor: PersistentModelConstructor, items: ModelInstanceMetadata[], - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ): Promise<[ModelInstanceMetadata, OpType][]> { const itemsMap: Map = new Map(); diff --git a/packages/datastore/src/sync/outbox.ts b/packages/datastore/src/sync/outbox.ts index 459dff3683d..d693e79c3f0 100644 --- a/packages/datastore/src/sync/outbox.ts +++ b/packages/datastore/src/sync/outbox.ts @@ -27,12 +27,12 @@ class MutationEventOutbox { private readonly schema: InternalSchema, private readonly MutationEvent: PersistentModelConstructor, private readonly modelInstanceCreator: ModelInstanceCreator, - private readonly ownSymbol: Symbol + private readonly ownSymbol: Symbol, ) {} public async enqueue( storage: Storage, - mutationEvent: MutationEvent + mutationEvent: MutationEvent, ): Promise { await storage.runExclusive(async s => { const mutationEventModelDefinition = @@ -47,7 +47,7 @@ class MutationEventOutbox { { modelId: { eq: mutationEvent.modelId } }, { id: { ne: this.inProgressMutationEventId } }, ], - } + }, ); // Check if there are any other records with same id @@ -76,7 +76,7 @@ class MutationEventOutbox { draft.data = merged.data; }), undefined, - this.ownSymbol + this.ownSymbol, ); } } else { @@ -103,7 +103,7 @@ class MutationEventOutbox { public async dequeue( storage: StorageClass, record?: PersistentModel, - recordOp?: TransformerMutationType + recordOp?: TransformerMutationType, ): Promise { const head = await this.peek(storage); @@ -135,7 +135,7 @@ class MutationEventOutbox { public async getForModel( storage: StorageFacade, model: T, - userModelDefinition: SchemaModel + userModelDefinition: SchemaModel, ): Promise { const mutationEventModelDefinition = this.schema.namespaces[SYNC].models.MutationEvent; @@ -146,7 +146,7 @@ class MutationEventOutbox { this.MutationEvent, ModelPredicateCreator.createFromAST(mutationEventModelDefinition, { and: { modelId: { eq: modelId } }, - }) + }), ); return mutationEvents; @@ -169,7 +169,7 @@ class MutationEventOutbox { storage: StorageClass, record: PersistentModel, head: PersistentModel, - recordOp: string + recordOp: string, ): Promise { if (head?.operation !== recordOp) { return; @@ -219,12 +219,12 @@ class MutationEventOutbox { { modelId: { eq: recordId } }, { id: { ne: this.inProgressMutationEventId } }, ], - } + }, ); const outdatedMutations = await storage.query( this.MutationEvent, - predicate + predicate, ); if (!outdatedMutations.length) { @@ -245,17 +245,17 @@ class MutationEventOutbox { await Promise.all( reconciledMutations.map( - async m => await storage.save(m, undefined, this.ownSymbol) - ) + async m => await storage.save(m, undefined, this.ownSymbol), + ), ); } private mergeUserFields( previous: MutationEvent, - current: MutationEvent + current: MutationEvent, ): MutationEvent { const { _version, _lastChangedAt, _deleted, ...previousData } = JSON.parse( - previous.data + previous.data, ); const { @@ -298,7 +298,7 @@ class MutationEventOutbox { */ private removeTimestampFields( model: string, - record: PersistentModel + record: PersistentModel, ): PersistentModel { const CREATED_AT_DEFAULT_KEY = 'createdAt'; const UPDATED_AT_DEFAULT_KEY = 'updatedAt'; diff --git a/packages/datastore/src/sync/processors/mutation.ts b/packages/datastore/src/sync/processors/mutation.ts index 6dba06d13c6..18619d5f251 100644 --- a/packages/datastore/src/sync/processors/mutation.ts +++ b/packages/datastore/src/sync/processors/mutation.ts @@ -88,7 +88,7 @@ class MutationProcessor { private readonly authModeStrategy: AuthModeStrategy, private readonly errorHandler: ErrorHandler, private readonly conflictHandler: ConflictHandler, - private readonly amplifyContext: AmplifyContext + private readonly amplifyContext: AmplifyContext, ) { this.amplifyContext.InternalAPI = this.amplifyContext.InternalAPI || InternalAPI; @@ -103,17 +103,17 @@ class MutationProcessor { const [createMutation] = buildGraphQLOperation( namespace, model, - 'CREATE' + 'CREATE', ); const [updateMutation] = buildGraphQLOperation( namespace, model, - 'UPDATE' + 'UPDATE', ); const [deleteMutation] = buildGraphQLOperation( namespace, model, - 'DELETE' + 'DELETE', ); this.typeQuery.set(model, [ @@ -207,7 +207,7 @@ class MutationProcessor { const authModeRetry = async () => { try { logger.debug( - `Attempting mutation with authMode: ${operationAuthModes[authModeAttempts]}` + `Attempting mutation with authMode: ${operationAuthModes[authModeAttempts]}`, ); const response = await this.jitteredRetry( namespaceName, @@ -219,11 +219,11 @@ class MutationProcessor { this.MutationEvent, head, operationAuthModes[authModeAttempts], - onTerminate + onTerminate, ); logger.debug( - `Mutation sent successfully with authMode: ${operationAuthModes[authModeAttempts]}` + `Mutation sent successfully with authMode: ${operationAuthModes[authModeAttempts]}`, ); return response; @@ -233,7 +233,7 @@ class MutationProcessor { logger.debug( `Mutation failed with authMode: ${ operationAuthModes[authModeAttempts - 1] - }` + }`, ); try { await this.errorHandler({ @@ -258,7 +258,7 @@ class MutationProcessor { operationAuthModes[authModeAttempts - 1] }. Retrying with authMode: ${ operationAuthModes[authModeAttempts] - }` + }`, ); return await authModeRetry(); } @@ -316,7 +316,7 @@ class MutationProcessor { MutationEvent: PersistentModelConstructor, mutationEvent: MutationEvent, authMode: GraphQLAuthMode, - onTerminate: Promise + onTerminate: Promise, ): Promise< [GraphQLResult>, string, SchemaModel] > { @@ -328,7 +328,7 @@ class MutationProcessor { condition: string, modelConstructor: PersistentModelConstructor, MutationEvent: PersistentModelConstructor, - mutationEvent: MutationEvent + mutationEvent: MutationEvent, ) => { const [query, variables, graphQLCondition, opName, modelDefinition] = this.createQueryVariables( @@ -336,12 +336,12 @@ class MutationProcessor { model, operation, data, - condition + condition, ); const authToken = await getTokenForCustomAuth( authMode, - this.amplifyConfig + this.amplifyConfig, ); const tryWith = { @@ -365,7 +365,7 @@ class MutationProcessor { await this.amplifyContext.InternalAPI.graphql( tryWith, undefined, - customUserAgentDetails + customUserAgentDetails, ) ); @@ -405,11 +405,11 @@ class MutationProcessor { modelConstructor, localModel: this.modelInstanceCreator( modelConstructor, - variables.input + variables.input, ), remoteModel: this.modelInstanceCreator( modelConstructor, - error.data + error.data, ), operation: opType, attempts: attempt, @@ -426,12 +426,12 @@ class MutationProcessor { const [[, opName, query]] = buildGraphQLOperation( this.schema.namespaces[namespaceName], modelDefinition, - 'GET' + 'GET', ); const authToken = await getTokenForCustomAuth( authMode, - this.amplifyConfig + this.amplifyConfig, ); const serverData = < @@ -444,7 +444,7 @@ class MutationProcessor { authToken, }, undefined, - customUserAgentDetails + customUserAgentDetails, ); // onTerminate cancel graphql() @@ -465,7 +465,7 @@ class MutationProcessor { graphQLCondition, MutationEvent, this.modelInstanceCreator, - mutationEvent.id + mutationEvent.id, ); await this.storage.save(updatedMutation); @@ -496,7 +496,7 @@ class MutationProcessor { { data: { [opName]: error.data } }, opName, modelDefinition, - ] + ] : []; } } @@ -518,7 +518,7 @@ class MutationProcessor { mutationEvent, ], safeJitteredBackoff, - onTerminate + onTerminate, ); } @@ -527,7 +527,7 @@ class MutationProcessor { model: string, operation: TransformerMutationType, data: string, - condition: string + condition: string, ): [string, Record, GraphQLCondition, string, SchemaModel] { const modelDefinition = this.schema.namespaces[namespaceName].models[model]; const { primaryKey } = this.schema.namespaces[namespaceName].keys![model]; @@ -540,7 +540,7 @@ class MutationProcessor { const queriesTuples = this.typeQuery.get(modelDefinition); const [, opName, query] = queriesTuples!.find( - ([transformerMutationType]) => transformerMutationType === operation + ([transformerMutationType]) => transformerMutationType === operation, )!; const { _version, ...parsedData } = JSON.parse(data); @@ -626,13 +626,13 @@ class MutationProcessor { Object.keys(graphQLCondition).length > 0 ? graphQLCondition : null, - }), + }), }; return [query, variables, graphQLCondition, opName, modelDefinition]; } private opTypeFromTransformerOperation( - operation: TransformerMutationType + operation: TransformerMutationType, ): OpType { switch (operation) { case TransformerMutationType.CREATE: @@ -677,7 +677,7 @@ const originalJitteredBackoff = jitteredBackoff(MAX_RETRY_DELAY_MS); export const safeJitteredBackoff: typeof originalJitteredBackoff = ( attempt, _args, - error + error, ) => { const attemptResult = originalJitteredBackoff(attempt); diff --git a/packages/datastore/src/sync/processors/subscription.ts b/packages/datastore/src/sync/processors/subscription.ts index 6561d178717..6e90ed7de32 100644 --- a/packages/datastore/src/sync/processors/subscription.ts +++ b/packages/datastore/src/sync/processors/subscription.ts @@ -92,7 +92,7 @@ class SubscriptionProcessor { private readonly errorHandler: ErrorHandler, private readonly amplifyContext: AmplifyContext = { InternalAPI, - } + }, ) {} private buildSubscription( @@ -102,7 +102,7 @@ class SubscriptionProcessor { userCredentials: USER_CREDENTIALS, oidcTokenPayload: JwtPayload | undefined, authMode: GraphQLAuthMode, - filterArg: boolean = false + filterArg: boolean = false, ): { opType: TransformerMutationType; opName: string; @@ -119,7 +119,7 @@ class SubscriptionProcessor { userCredentials, aws_appsync_authenticationType, oidcTokenPayload, - authMode + authMode, ) || {}; const [opType, opName, query] = buildSubscriptionGraphQLOperation( @@ -128,7 +128,7 @@ class SubscriptionProcessor { transformerMutationType, isOwner, ownerField!, - filterArg + filterArg, ); return { authMode, opType, opName, query, isOwner, ownerField, ownerValue }; } @@ -138,14 +138,14 @@ class SubscriptionProcessor { userCredentials: USER_CREDENTIALS, defaultAuthType: GraphQLAuthMode, oidcTokenPayload: JwtPayload | undefined, - authMode: GraphQLAuthMode + authMode: GraphQLAuthMode, ): AuthorizationInfo { const rules = getAuthorizationRules(model); // Return null if user doesn't have proper credentials for private API with IAM auth const iamPrivateAuth = authMode === 'iam' && rules.find( - rule => rule.authStrategy === 'private' && rule.provider === 'iam' + rule => rule.authStrategy === 'private' && rule.provider === 'iam', ); if (iamPrivateAuth && userCredentials === USER_CREDENTIALS.unauth) { @@ -159,7 +159,7 @@ class SubscriptionProcessor { const groupAuthRules = rules.filter( rule => rule.authStrategy === 'groups' && - ['userPools', 'oidc'].includes(rule.provider) + ['userPools', 'oidc'].includes(rule.provider), ); const validGroup = @@ -169,7 +169,7 @@ class SubscriptionProcessor { if (oidcTokenPayload) { const oidcUserGroups = getUserGroupsFromToken( oidcTokenPayload, - groupAuthRule + groupAuthRule, ); return [...oidcUserGroups].find(userGroup => { @@ -200,8 +200,8 @@ class SubscriptionProcessor { ? rules.filter( rule => rule.authStrategy === 'owner' && - (rule.provider === 'oidc' || rule.provider === 'userPools') - ) + (rule.provider === 'oidc' || rule.provider === 'userPools'), + ) : []; oidcOwnerAuthRules.forEach(ownerAuthRule => { @@ -234,7 +234,7 @@ class SubscriptionProcessor { private hubQueryCompletionListener( completed: Function, - capsule: HubCapsule<'datastore', { event: string }> + capsule: HubCapsule<'datastore', { event: string }>, ) { const { payload: { event }, @@ -326,7 +326,7 @@ class SubscriptionProcessor { const predicatesGroup = ModelPredicateCreator.getPredicates( this.syncPredicates.get(modelDefinition)!, - false + false, ); const addFilterArg = predicatesGroup !== undefined; @@ -336,7 +336,7 @@ class SubscriptionProcessor { // 2. RTF error - retry without sending filter arg. (filtering will fall back to clientside) const subscriptionRetry = async ( operation, - addFilter = addFilterArg + addFilter = addFilterArg, ) => { const { opType: transformerMutationType, @@ -353,12 +353,12 @@ class SubscriptionProcessor { userCredentials, oidcTokenPayload, readAuthModes[operationAuthModeAttempts[operation]], - addFilter + addFilter, ); const authToken = await getTokenForCustomAuth( authMode, - this.amplifyConfig + this.amplifyConfig, ); const variables = {}; @@ -376,7 +376,7 @@ class SubscriptionProcessor { if (isOwner) { if (!ownerValue) { observer.error( - 'Owner field required, sign in is needed in order to perform this operation' + 'Owner field required, sign in is needed in order to perform this operation', ); return; } @@ -387,7 +387,7 @@ class SubscriptionProcessor { logger.debug( `Attempting ${operation} subscription with authMode: ${ readAuthModes[operationAuthModeAttempts[operation]] - }` + }`, ); const queryObservable = < @@ -400,7 +400,7 @@ class SubscriptionProcessor { authToken, }, undefined, - customUserAgentDetails + customUserAgentDetails, )); let subscriptionReadyCallback: (param?: unknown) => void; @@ -422,8 +422,8 @@ class SubscriptionProcessor { logger.warn( `Skipping incoming subscription. Messages: ${messages.join( - '\n' - )}` + '\n', + )}`, ); this.drainBuffer(); @@ -433,7 +433,7 @@ class SubscriptionProcessor { const predicatesGroup = ModelPredicateCreator.getPredicates( this.syncPredicates.get(modelDefinition)!, - false + false, ); // @ts-ignore @@ -446,13 +446,13 @@ class SubscriptionProcessor { if ( this.passesPredicateValidation( record, - predicatesGroup! + predicatesGroup!, ) ) { this.pushToBuffer( transformerMutationType, modelDefinition, - record + record, ); } this.drainBuffer(); @@ -470,7 +470,7 @@ class SubscriptionProcessor { this.catchRTFError( message, modelDefinition, - predicatesGroup + predicatesGroup, ); // Catch RTF errors @@ -479,7 +479,7 @@ class SubscriptionProcessor { subscriptions[modelDefinition.name][ transformerMutationType ].forEach(subscription => - subscription.unsubscribe() + subscription.unsubscribe(), ); subscriptions[modelDefinition.name][ @@ -493,17 +493,17 @@ class SubscriptionProcessor { if ( message.includes( - PUBSUB_CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR + PUBSUB_CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR, ) || message.includes( - PUBSUB_CONTROL_MSG.CONNECTION_FAILED + PUBSUB_CONTROL_MSG.CONNECTION_FAILED, ) ) { // Unsubscribe and clear subscription array for model/operation subscriptions[modelDefinition.name][ transformerMutationType ].forEach(subscription => - subscription.unsubscribe() + subscription.unsubscribe(), ); subscriptions[modelDefinition.name][ transformerMutationType @@ -520,7 +520,7 @@ class SubscriptionProcessor { readAuthModes[ operationAuthModeAttempts[operation] - 1 ] - }` + }`, ); } else { // retry with different auth mode. Do not trigger @@ -534,7 +534,7 @@ class SubscriptionProcessor { readAuthModes[ operationAuthModeAttempts[operation] ] - }` + }`, ); subscriptionRetry(operation); return; @@ -560,7 +560,7 @@ class SubscriptionProcessor { } catch (e) { logger.error( 'Subscription error handler failed with:', - e + e, ); } @@ -576,7 +576,7 @@ class SubscriptionProcessor { } observer.error(message); }, - }) + }), ); promises.push( @@ -587,20 +587,20 @@ class SubscriptionProcessor { subscriptionReadyCallback = res; boundFunction = this.hubQueryCompletionListener.bind( this, - res + res, ); removeBoundFunctionListener = Hub.listen( 'api', - boundFunction + boundFunction, ); }); removeBoundFunctionListener(); - })() + })(), ); }; operations.forEach(op => subscriptionRetry(op)); - }) + }), ); }); @@ -608,20 +608,20 @@ class SubscriptionProcessor { this.runningProcesses.add(() => Promise.all(promises).then(() => { observer.next(CONTROL_MSG.CONNECTED); - }) + }), ); }, 'subscription processor new subscriber'); return this.runningProcesses.addCleaner(async () => { Object.keys(subscriptions).forEach(modelName => { subscriptions[modelName][TransformerMutationType.CREATE].forEach( - subscription => subscription.unsubscribe() + subscription => subscription.unsubscribe(), ); subscriptions[modelName][TransformerMutationType.UPDATE].forEach( - subscription => subscription.unsubscribe() + subscription => subscription.unsubscribe(), ); subscriptions[modelName][TransformerMutationType.DELETE].forEach( - subscription => subscription.unsubscribe() + subscription => subscription.unsubscribe(), ); }); }); @@ -648,7 +648,7 @@ class SubscriptionProcessor { private passesPredicateValidation( record: PersistentModel, - predicatesGroup: PredicatesGroup + predicatesGroup: PredicatesGroup, ): boolean { if (!predicatesGroup) { return true; @@ -662,7 +662,7 @@ class SubscriptionProcessor { private pushToBuffer( transformerMutationType: TransformerMutationType, modelDefinition: SchemaModel, - data: PersistentModel + data: PersistentModel, ) { this.buffer.push([transformerMutationType, modelDefinition, data]); } @@ -682,7 +682,7 @@ class SubscriptionProcessor { private catchRTFError( message: string, modelDefinition: SchemaModel, - predicatesGroup: PredicatesGroup | undefined + predicatesGroup: PredicatesGroup | undefined, ): boolean { const header = 'Backend subscriptions filtering error.\n' + @@ -700,14 +700,14 @@ class SubscriptionProcessor { const [_errorMsg, errorType] = Object.entries(messageErrorTypeMap).find(([errorMsg]) => - message.includes(errorMsg) + message.includes(errorMsg), ) || []; if (errorType !== undefined) { const remediationMessage = generateRTFRemediation( errorType, modelDefinition, - predicatesGroup + predicatesGroup, ); logger.warn(`${header}\n${message}\n${remediationMessage}`); diff --git a/packages/datastore/src/sync/processors/sync.ts b/packages/datastore/src/sync/processors/sync.ts index 40d07913e8f..d11ca8d4b82 100644 --- a/packages/datastore/src/sync/processors/sync.ts +++ b/packages/datastore/src/sync/processors/sync.ts @@ -60,7 +60,7 @@ class SyncProcessor { private readonly amplifyConfig: Record = {}, private readonly authModeStrategy: AuthModeStrategy, private readonly errorHandler: ErrorHandler, - private readonly amplifyContext: AmplifyContext + private readonly amplifyContext: AmplifyContext, ) { amplifyContext.InternalAPI = amplifyContext.InternalAPI || InternalAPI; this.generateQueries(); @@ -74,7 +74,7 @@ class SyncProcessor { const [[, ...opNameQuery]] = buildGraphQLOperation( namespace, model, - 'LIST' + 'LIST', ); this.typeQuery.set(model, opNameQuery); @@ -89,7 +89,7 @@ class SyncProcessor { const predicatesGroup: PredicatesGroup = ModelPredicateCreator.getPredicates( this.syncPredicates.get(model)!, - false + false, )!; if (!predicatesGroup) { @@ -105,7 +105,7 @@ class SyncProcessor { nextToken: string, limit: number = null!, filter: GraphQLFilter, - onTerminate: Promise + onTerminate: Promise, ): Promise<{ nextToken: string; startedAt: number; items: T[] }> { const [opName, query] = this.typeQuery.get(modelDefinition)!; @@ -130,13 +130,13 @@ class SyncProcessor { const authModeRetry = async () => { if (!this.runningProcesses.isOpen) { throw new Error( - 'sync.retreievePage termination was requested. Exiting.' + 'sync.retreievePage termination was requested. Exiting.', ); } try { logger.debug( - `Attempting sync with authMode: ${readAuthModes[authModeAttempts]}` + `Attempting sync with authMode: ${readAuthModes[authModeAttempts]}`, ); const response = await this.jitteredRetry({ query, @@ -147,7 +147,7 @@ class SyncProcessor { onTerminate, }); logger.debug( - `Sync successful with authMode: ${readAuthModes[authModeAttempts]}` + `Sync successful with authMode: ${readAuthModes[authModeAttempts]}`, ); return response; } catch (error) { @@ -158,7 +158,7 @@ class SyncProcessor { if (getClientSideAuthError(error) || getForbiddenError(error)) { // return empty list of data so DataStore will continue to sync other models logger.warn( - `User is unauthorized to query ${opName} with auth mode ${authMode}. No data could be returned.` + `User is unauthorized to query ${opName} with auth mode ${authMode}. No data could be returned.`, ); return { @@ -172,7 +172,7 @@ class SyncProcessor { logger.debug( `Sync failed with authMode: ${ readAuthModes[authModeAttempts - 1] - }. Retrying with authMode: ${readAuthModes[authModeAttempts]}` + }. Retrying with authMode: ${readAuthModes[authModeAttempts]}`, ); return await authModeRetry(); } @@ -219,7 +219,7 @@ class SyncProcessor { try { const authToken = await getTokenForCustomAuth( authMode, - this.amplifyConfig + this.amplifyConfig, ); const customUserAgentDetails: CustomUserAgentDetails = { @@ -235,7 +235,7 @@ class SyncProcessor { authToken, }, undefined, - customUserAgentDetails + customUserAgentDetails, ); // TODO: onTerminate.then(() => API.cancel(...)) @@ -254,20 +254,20 @@ class SyncProcessor { const unauthorized = error?.errors && (error.errors as [any]).some( - err => err.errorType === 'Unauthorized' + err => err.errorType === 'Unauthorized', ); const otherErrors = error?.errors && (error.errors as [any]).filter( - err => err.errorType !== 'Unauthorized' + err => err.errorType !== 'Unauthorized', ); const result = error; if (hasItems) { result.data[opName].items = result.data[opName].items.filter( - item => item !== null + item => item !== null, ); } @@ -290,7 +290,7 @@ class SyncProcessor { } catch (e) { logger.error('Sync error handler failed with:', e); } - }) + }), ); Hub.dispatch('datastore', { event: 'nonApplicableDataReceived', @@ -350,12 +350,12 @@ class SyncProcessor { }, [query, variables], undefined, - onTerminate + onTerminate, ); } start( - typesLastSync: Map + typesLastSync: Map, ): Observable { const { maxRecordsToSync, syncPageSize } = this.amplifyConfig; const parentPromises = new Map>(); @@ -363,14 +363,14 @@ class SyncProcessor { const sortedTypesLastSyncs = Object.values(this.schema.namespaces).reduce( (map, namespace) => { for (const modelName of Array.from( - namespace.modelTopologicalOrdering!.keys() + namespace.modelTopologicalOrdering!.keys(), )) { const typeLastSync = typesLastSync.get(namespace.models[modelName]); map.set(namespace.models[modelName], typeLastSync!); } return map; }, - new Map() + new Map(), ); const allModelsReady = Array.from(sortedTypesLastSyncs.entries()) @@ -391,7 +391,7 @@ class SyncProcessor { namespace ].modelTopologicalOrdering!.get(modelDefinition.name); const promises = parents!.map(parent => - parentPromises.get(`${namespace}_${parent}`) + parentPromises.get(`${namespace}_${parent}`), ); const promise = new Promise(async res => { @@ -405,14 +405,14 @@ class SyncProcessor { */ if (!this.runningProcesses.isOpen) { logger.debug( - `Sync processor has been stopped, terminating sync for ${modelDefinition.name}` + `Sync processor has been stopped, terminating sync for ${modelDefinition.name}`, ); return res(); } const limit = Math.min( maxRecordsToSync - recordsReceived, - syncPageSize + syncPageSize, ); /** @@ -427,7 +427,7 @@ class SyncProcessor { nextToken, limit, filter, - onTerminate + onTerminate, )); } catch (error) { try { @@ -477,11 +477,11 @@ class SyncProcessor { parentPromises.set( `${namespace}_${modelDefinition.name}`, - promise + promise, ); await promise; - }, `adding model ${modelDefinition.name}`) + }, `adding model ${modelDefinition.name}`), ); Promise.all(allModelsReady as Promise[]).then(() => { diff --git a/packages/datastore/src/sync/utils.ts b/packages/datastore/src/sync/utils.ts index bc1c42f99ea..ec6c4adf751 100644 --- a/packages/datastore/src/sync/utils.ts +++ b/packages/datastore/src/sync/utils.ts @@ -73,13 +73,13 @@ export function getMetadataFields(): ReadonlyArray { export function generateSelectionSet( namespace: SchemaNamespace, - modelDefinition: SchemaModel | SchemaNonModel + modelDefinition: SchemaModel | SchemaNonModel, ): string { const scalarFields = getScalarFields(modelDefinition); const nonModelFields = getNonModelFields(namespace, modelDefinition); const implicitOwnerField = getImplicitOwnerField( modelDefinition, - scalarFields + scalarFields, ); let scalarAndMetadataFields = Object.values(scalarFields) @@ -100,7 +100,7 @@ export function generateSelectionSet( function getImplicitOwnerField( modelDefinition: SchemaModel | SchemaNonModel, - scalarFields: ModelFields + scalarFields: ModelFields, ) { const ownerFields = getOwnerFields(modelDefinition); @@ -111,7 +111,7 @@ function getImplicitOwnerField( } function getOwnerFields( - modelDefinition: SchemaModel | SchemaNonModel + modelDefinition: SchemaModel | SchemaNonModel, ): string[] { const ownerFields: string[] = []; if (isSchemaModelWithAttributes(modelDefinition)) { @@ -128,7 +128,7 @@ function getOwnerFields( } function getScalarFields( - modelDefinition: SchemaModel | SchemaNonModel + modelDefinition: SchemaModel | SchemaNonModel, ): ModelFields { const { fields } = modelDefinition; @@ -152,7 +152,7 @@ function getScalarFields( // Used for generating the selection set for queries and mutations function getConnectionFields( modelDefinition: SchemaModel, - namespace: SchemaNamespace + namespace: SchemaNamespace, ): string[] { const result: string[] = []; @@ -177,7 +177,7 @@ function getConnectionFields( modelDefinition.fields[name].type['model']; const byPkIndex = relations[connectedModelName].indexes.find( - ([name]) => name === 'byPk' + ([name]) => name === 'byPk', ); const keyFields = byPkIndex && byPkIndex[1]; const keyFieldSelectionSet = keyFields?.join(' '); @@ -200,7 +200,7 @@ function getConnectionFields( function getNonModelFields( namespace: SchemaNamespace, - modelDefinition: SchemaModel | SchemaNonModel + modelDefinition: SchemaModel | SchemaNonModel, ): string[] { const result: string[] = []; @@ -208,7 +208,7 @@ function getNonModelFields( if (isNonModelFieldType(type)) { const typeDefinition = namespace.nonModels![type.nonModel]; const scalarFields = Object.values(getScalarFields(typeDefinition)).map( - ({ name }) => name + ({ name }) => name, ); const nested: string[] = []; @@ -218,7 +218,7 @@ function getNonModelFields( if (isNonModelFieldType(type)) { const typeDefinition = namespace.nonModels![type.nonModel]; nested.push( - `${name} { ${generateSelectionSet(namespace, typeDefinition)} }` + `${name} { ${generateSelectionSet(namespace, typeDefinition)} }`, ); } }); @@ -231,7 +231,7 @@ function getNonModelFields( } export function getAuthorizationRules( - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ): AuthorizationRule[] { // Searching for owner authorization on attributes const authConfig = ([] as ModelAttributes) @@ -308,7 +308,7 @@ export function buildSubscriptionGraphQLOperation( transformerMutationType: TransformerMutationType, isOwnerAuthorization: boolean, ownerField: string, - filterArg: boolean = false + filterArg: boolean = false, ): [TransformerMutationType, string, string] { const selectionSet = generateSelectionSet(namespace, modelDefinition); @@ -346,7 +346,7 @@ export function buildSubscriptionGraphQLOperation( export function buildGraphQLOperation( namespace: SchemaNamespace, modelDefinition: SchemaModel, - graphQLOpType: keyof typeof GraphQLOperationType + graphQLOpType: keyof typeof GraphQLOperationType, ): [TransformerMutationType, string, string][] { let selectionSet = generateSelectionSet(namespace, modelDefinition); @@ -421,7 +421,7 @@ export function createMutationInstanceFromModelOperation< condition: GraphQLCondition, MutationEventConstructor: PersistentModelConstructor, modelInstanceCreator: ModelInstanceCreator, - id?: string + id?: string, ): MutationEvent { let operation: TransformerMutationType; @@ -473,7 +473,7 @@ export function createMutationInstanceFromModelOperation< export function predicateToGraphQLCondition( predicate: PredicatesGroup, - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ): GraphQLCondition { const result = {}; @@ -511,7 +511,7 @@ export function predicateToGraphQLCondition( export function predicateToGraphQLFilter( predicatesGroup: PredicatesGroup, fieldsToOmit: string[] = [], - root = true + root = true, ): GraphQLFilter { const result: GraphQLFilter = {}; @@ -674,7 +674,7 @@ export function countFilterCombinations(group?: PredicatesGroup): number { * ``` */ export function repeatedFieldInGroup( - group?: PredicatesGroup + group?: PredicatesGroup, ): string | null { if (!group || !Array.isArray(group.predicates)) return null; @@ -708,12 +708,12 @@ export function repeatedFieldInGroup( // field value will be single object const predicateObjects = values.filter( - v => !Array.isArray(Object.values(v)[0]) + v => !Array.isArray(Object.values(v)[0]), ); // group value will be an array const predicateGroups = values.filter(v => - Array.isArray(Object.values(v)[0]) + Array.isArray(Object.values(v)[0]), ); if (key === 'and') { @@ -741,7 +741,7 @@ export enum RTFError { export function generateRTFRemediation( errorType: RTFError, modelDefinition: SchemaModel, - predicatesGroup: PredicatesGroup | undefined + predicatesGroup: PredicatesGroup | undefined, ): string { const selSyncFields = filterFields(predicatesGroup); const selSyncFieldStr = [...selSyncFields].join(', '); @@ -797,7 +797,7 @@ export function generateRTFRemediation( export function getUserGroupsFromToken( token: { [field: string]: any }, - rule: AuthorizationRule + rule: AuthorizationRule, ): string[] { // validate token against groupClaim let userGroups: string[] | string = token[rule.groupClaim] || []; @@ -856,7 +856,7 @@ export async function getModelAuthModes({ // Use default auth mode if nothing is returned from authModeStrategy modelAuthModes[operation] = [defaultAuthMode]; } - }) + }), ); } catch (error) { logger.debug(`Error getting auth modes for model: ${modelName}`, error); @@ -869,7 +869,7 @@ export function getForbiddenError(error) { let forbiddenError; if (error && error.errors) { forbiddenError = (error.errors as [any]).find(err => - forbiddenErrorCodes.includes(resolveServiceErrorStatusCode(err)) + forbiddenErrorCodes.includes(resolveServiceErrorStatusCode(err)), ); } else if (error && error.message) { forbiddenError = error; @@ -879,7 +879,7 @@ export function getForbiddenError(error) { return ( forbiddenError.message ?? `Request failed with status code ${resolveServiceErrorStatusCode( - forbiddenError + forbiddenError, )}` ); } @@ -891,7 +891,7 @@ export function resolveServiceErrorStatusCode(error: unknown): number | null { return Number(error?.['$metadata']?.['httpStatusCode']); } else if ((error as GraphQLError)?.originalError) { return resolveServiceErrorStatusCode( - (error as GraphQLError)?.originalError + (error as GraphQLError)?.originalError, ); } else { return null; @@ -904,14 +904,14 @@ export function getClientSideAuthError(error) { error && error.message && clientSideAuthErrors.find(clientError => - error.message.includes(clientError) + error.message.includes(clientError), ); return clientSideError || null; } export async function getTokenForCustomAuth( authMode: GraphQLAuthMode, - amplifyConfig: Record = {} + amplifyConfig: Record = {}, ): Promise { if (authMode === 'lambda') { const { @@ -923,13 +923,13 @@ export async function getTokenForCustomAuth( return token; } catch (error) { throw new Error( - `Error retrieving token from \`functionAuthProvider\`: ${error}` + `Error retrieving token from \`functionAuthProvider\`: ${error}`, ); } } else { // TODO: add docs link once available throw new Error( - 'You must provide a `functionAuthProvider` function to `DataStore.configure` when using lambda' + 'You must provide a `functionAuthProvider` function to `DataStore.configure` when using lambda', ); } } @@ -938,7 +938,7 @@ export async function getTokenForCustomAuth( // Util that takes a modelDefinition and model and returns either the id value(s) or the custom primary key value(s) export function getIdentifierValue( modelDefinition: SchemaModel, - model: ModelInstanceMetadata | PersistentModel + model: ModelInstanceMetadata | PersistentModel, ): string { const pkFieldNames = extractPrimaryKeyFieldNames(modelDefinition); diff --git a/packages/datastore/src/types.ts b/packages/datastore/src/types.ts index a39c83864de..37d98d1c2a5 100644 --- a/packages/datastore/src/types.ts +++ b/packages/datastore/src/types.ts @@ -67,7 +67,7 @@ export function isSchemaModel(obj: any): obj is SchemaModel { } export function isSchemaModelWithAttributes( - m: SchemaModel | SchemaNonModel + m: SchemaModel | SchemaNonModel, ): m is SchemaModel { return isSchemaModel(m) && (m as SchemaModel).attributes !== undefined; } @@ -106,7 +106,7 @@ type TargetNameAssociation = { }; export function isTargetNameAssociation( - obj: any + obj: any, ): obj is TargetNameAssociation { return obj?.targetName || obj?.targetNames; } @@ -116,7 +116,7 @@ type FieldAssociation = { }; export function isFieldAssociation( obj: any, - fieldName: string + fieldName: string, ): obj is FieldAssociation { return obj?.fields[fieldName]?.association?.connectionType; } @@ -143,7 +143,7 @@ export type ModelAttributeAuth = { }; export function isModelAttributeAuth( - attr: ModelAttribute + attr: ModelAttribute, ): attr is ModelAttributeAuth { return ( attr.type === 'auth' && @@ -178,7 +178,7 @@ type ModelAttributeCompositeKey = { }; export function isModelAttributeKey( - attr: ModelAttribute + attr: ModelAttribute, ): attr is ModelAttributeKey { return ( attr.type === 'key' && @@ -189,13 +189,13 @@ export function isModelAttributeKey( } export function isModelAttributePrimaryKey( - attr: ModelAttribute + attr: ModelAttribute, ): attr is ModelAttributePrimaryKey { return isModelAttributeKey(attr) && attr.properties.name === undefined; } export function isModelAttributeCompositeKey( - attr: ModelAttribute + attr: ModelAttribute, ): attr is ModelAttributeCompositeKey { return ( isModelAttributeKey(attr) && @@ -253,7 +253,7 @@ export namespace GraphQLScalarType { scalar: keyof Omit< typeof GraphQLScalarType, 'getJSType' | 'getValidationFunction' - > + >, ) { switch (scalar) { case 'Boolean': @@ -283,7 +283,7 @@ export namespace GraphQLScalarType { scalar: keyof Omit< typeof GraphQLScalarType, 'getJSType' | 'getValidationFunction' - > + >, ): ((val: string) => boolean) | ((val: number) => boolean) | undefined { switch (scalar) { case 'AWSDate': @@ -322,7 +322,7 @@ export type AuthorizationRule = { }; export function isGraphQLScalarType( - obj: any + obj: any, ): obj is keyof Omit< typeof GraphQLScalarType, 'getJSType' | 'getValidationFunction' @@ -335,7 +335,7 @@ export type ModelFieldType = { modelConstructor?: ModelMeta; }; export function isModelFieldType( - obj: any + obj: any, ): obj is ModelFieldType { const modelField: keyof ModelFieldType = 'model'; if (obj && obj[modelField]) return true; @@ -388,7 +388,7 @@ export type PersistentModelConstructor = { new (init: ModelInit>): T; copyOf( src: T, - mutator: (draft: MutableModel>) => void + mutator: (draft: MutableModel>) => void, ): T; }; @@ -462,9 +462,9 @@ export type IdentifierFields< : MetadataOrDefault['identifier'] extends CompositeIdentifier< T, infer B - > - ? B[number] // B[number] - : MetadataOrDefault['identifier']['field']) & + > + ? B[number] // B[number] + : MetadataOrDefault['identifier']['field']) & string; export type IdentifierFieldsForInit< @@ -477,11 +477,11 @@ export type IdentifierFieldsForInit< : MetadataOrDefault['identifier'] extends OptionallyManagedIdentifier< T, any - > - ? IdentifierFields - : MetadataOrDefault['identifier'] extends CompositeIdentifier - ? IdentifierFields - : never; + > + ? IdentifierFields + : MetadataOrDefault['identifier'] extends CompositeIdentifier + ? IdentifierFields + : never; // Instance of model export declare const __modelMeta__: unique symbol; @@ -495,23 +495,24 @@ export interface AsyncCollection extends AsyncIterable { toArray(options?: { max?: number }): Promise; } -export type SettableFieldType = T extends Promise - ? undefined extends InnerPromiseType - ? InnerPromiseType | null - : InnerPromiseType - : T extends AsyncCollection - ? InnerCollectionType[] | undefined - : undefined extends T - ? T | null - : T; +export type SettableFieldType = + T extends Promise + ? undefined extends InnerPromiseType + ? InnerPromiseType | null + : InnerPromiseType + : T extends AsyncCollection + ? InnerCollectionType[] | undefined + : undefined extends T + ? T | null + : T; export type PredicateFieldType = NonNullable< Scalar< T extends Promise ? InnerPromiseType : T extends AsyncCollection - ? InnerCollectionType - : T + ? InnerCollectionType + : T > >; @@ -598,12 +599,12 @@ type DeepWritable = { -readonly [P in keyof T]: T[P] extends TypeName ? T[P] : T[P] extends Promise - ? undefined extends InnerPromiseType + ? undefined extends InnerPromiseType ? InnerPromiseType | null : InnerPromiseType - : T[P] extends AsyncCollection - ? InnerCollectionType[] | undefined | null - : DeepWritable; + : T[P] extends AsyncCollection + ? InnerCollectionType[] | undefined | null + : DeepWritable; }; export type MutableModel< @@ -625,11 +626,12 @@ export type ModelInstanceMetadata = { export type IdentifierFieldValue< T extends PersistentModel, M extends PersistentModelMetaData, -> = MetadataOrDefault['identifier'] extends CompositeIdentifier - ? MetadataOrDefault['identifier']['fields'] extends [any] - ? T[MetadataOrDefault['identifier']['fields'][0]] - : never - : T[MetadataOrDefault['identifier']['field']]; +> = + MetadataOrDefault['identifier'] extends CompositeIdentifier + ? MetadataOrDefault['identifier']['fields'] extends [any] + ? T[MetadataOrDefault['identifier']['fields'][0]] + : never + : T[MetadataOrDefault['identifier']['field']]; export type IdentifierFieldOrIdentifierObject< T extends PersistentModel, @@ -638,7 +640,7 @@ export type IdentifierFieldOrIdentifierObject< export function isIdentifierObject( obj: any, - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ): obj is IdentifierFields { const keys = extractPrimaryKeyFieldNames(modelDefinition); @@ -676,16 +678,14 @@ export type DataStoreSnapshot = { //#region Predicates -export type PredicateExpression< - M extends PersistentModel, - FT, -> = TypeName extends keyof MapTypeToOperands - ? ( - operator: keyof MapTypeToOperands[TypeName], - // make the operand type match the type they're trying to filter on - operand: MapTypeToOperands[TypeName][keyof MapTypeToOperands[TypeName]] - ) => ModelPredicate - : never; +export type PredicateExpression = + TypeName extends keyof MapTypeToOperands + ? ( + operator: keyof MapTypeToOperands[TypeName], + // make the operand type match the type they're trying to filter on + operand: MapTypeToOperands[TypeName][keyof MapTypeToOperands[TypeName]], + ) => ModelPredicate + : never; type EqualityOperators = { ne: T; @@ -726,26 +726,26 @@ type MapTypeToOperands = { type TypeName = T extends string ? 'string' : T extends number - ? 'number' - : T extends boolean - ? 'boolean' - : T extends string[] - ? 'string[]' - : T extends number[] - ? 'number[]' - : T extends boolean[] - ? 'boolean[]' - : never; + ? 'number' + : T extends boolean + ? 'boolean' + : T extends string[] + ? 'string[]' + : T extends number[] + ? 'number[]' + : T extends boolean[] + ? 'boolean[]' + : never; export type PredicateGroups = { and: ( - predicate: (predicate: ModelPredicate) => ModelPredicate + predicate: (predicate: ModelPredicate) => ModelPredicate, ) => ModelPredicate; or: ( - predicate: (predicate: ModelPredicate) => ModelPredicate + predicate: (predicate: ModelPredicate) => ModelPredicate, ) => ModelPredicate; not: ( - predicate: (predicate: ModelPredicate) => ModelPredicate + predicate: (predicate: ModelPredicate) => ModelPredicate, ) => ModelPredicate; }; @@ -754,7 +754,7 @@ export type ModelPredicate = { } & PredicateGroups; export type ProducerModelPredicate = ( - condition: ModelPredicate + condition: ModelPredicate, ) => ModelPredicate; export type PredicatesGroup = { @@ -763,13 +763,13 @@ export type PredicatesGroup = { }; export function isPredicateObj( - obj: any + obj: any, ): obj is PredicateObject { return obj && (>obj).field !== undefined; } export function isPredicateGroup( - obj: any + obj: any, ): obj is PredicatesGroup { return obj && (>obj).type !== undefined; } @@ -834,19 +834,17 @@ export type PaginationInput = { }; export type ProducerSortPredicate = ( - condition: SortPredicate + condition: SortPredicate, ) => SortPredicate; export type SortPredicate = { [K in keyof T]-?: SortPredicateExpression>; }; -export type SortPredicateExpression< - M extends PersistentModel, - FT, -> = TypeName extends keyof MapTypeToOperands - ? (sortDirection: keyof typeof SortDirection) => SortPredicate - : never; +export type SortPredicateExpression = + TypeName extends keyof MapTypeToOperands + ? (sortDirection: keyof typeof SortDirection) => SortPredicate + : never; export enum SortDirection { ASCENDING = 'ASCENDING', @@ -872,14 +870,14 @@ export type SystemComponent = { modelInstanceCreator: ModelInstanceCreator, getModelConstructorByModelName: ( namsespaceName: NAMESPACES, - modelName: string + modelName: string, ) => PersistentModelConstructor, - appId?: string + appId?: string, ): Promise; }; export type NamespaceResolver = ( - modelConstructor: PersistentModelConstructor + modelConstructor: PersistentModelConstructor, ) => string; export type ControlMessageType = { @@ -972,7 +970,7 @@ export type AuthModeStrategyParams = { }; export type AuthModeStrategy = ( - authModeStrategyParams: AuthModeStrategyParams + authModeStrategyParams: AuthModeStrategyParams, ) => AuthModeStrategyReturn | Promise; export enum ModelOperation { @@ -1031,7 +1029,7 @@ export async function syncExpression< A extends Option, >( modelConstructor: PersistentModelConstructor, - conditionProducer: ConditionProducer + conditionProducer: ConditionProducer, ): Promise<{ modelConstructor: PersistentModelConstructor; conditionProducer: ConditionProducer; @@ -1080,7 +1078,7 @@ export enum ProcessName { export const DISCARD = Symbol('DISCARD'); export type ConflictHandler = ( - conflict: SyncConflict + conflict: SyncConflict, ) => | Promise | PersistentModel @@ -1145,7 +1143,7 @@ export type WithoutNevers = Pick>; * ``` */ export type RecursiveModelPredicateExtender = ( - lambda: RecursiveModelPredicate + lambda: RecursiveModelPredicate, ) => PredicateInternalsKey; export type RecursiveModelPredicateAggregateExtender< @@ -1153,11 +1151,11 @@ export type RecursiveModelPredicateAggregateExtender< > = (lambda: RecursiveModelPredicate) => PredicateInternalsKey[]; export type RecursiveModelPredicateOperator = ( - predicates: RecursiveModelPredicateAggregateExtender + predicates: RecursiveModelPredicateAggregateExtender, ) => PredicateInternalsKey; export type RecursiveModelPredicateNegation = ( - predicate: RecursiveModelPredicateExtender + predicate: RecursiveModelPredicateExtender, ) => PredicateInternalsKey; export type RecursiveModelPredicate = { @@ -1192,11 +1190,11 @@ export type RecursiveModelPredicate = { * ``` */ export type ModelPredicateExtender = ( - lambda: V5ModelPredicate + lambda: V5ModelPredicate, ) => PredicateInternalsKey; export type ModelPredicateAggregateExtender = ( - lambda: V5ModelPredicate + lambda: V5ModelPredicate, ) => PredicateInternalsKey[]; export type ValuePredicate< @@ -1206,8 +1204,8 @@ export type ValuePredicate< [K in AllFieldOperators]: K extends 'between' ? ( inclusiveLowerBound: Scalar, - inclusiveUpperBound: Scalar - ) => PredicateInternalsKey + inclusiveUpperBound: Scalar, + ) => PredicateInternalsKey : (operand: Scalar) => PredicateInternalsKey; }; @@ -1222,11 +1220,11 @@ export type V5ModelPredicate = WithoutNevers<{ } & PredicateInternalsKey; export type ModelPredicateOperator = ( - predicates: ModelPredicateAggregateExtender + predicates: ModelPredicateAggregateExtender, ) => PredicateInternalsKey; export type ModelPredicateNegation = ( - predicate: ModelPredicateExtender + predicate: ModelPredicateExtender, ) => PredicateInternalsKey; /** diff --git a/packages/datastore/src/util.ts b/packages/datastore/src/util.ts index a09ab8a0d8f..684bda822c1 100644 --- a/packages/datastore/src/util.ts +++ b/packages/datastore/src/util.ts @@ -93,7 +93,7 @@ export const isNullOrUndefined = (val: any): boolean => { export const validatePredicate = ( model: T, groupType: keyof PredicateGroups, - predicatesOrGroups: (PredicateObject | PredicatesGroup)[] + predicatesOrGroups: (PredicateObject | PredicatesGroup)[], ) => { let filterType: keyof Pick; let isNegation = false; @@ -139,7 +139,7 @@ export const validatePredicate = ( export const validatePredicateField = ( value: T, operator: keyof AllOperators, - operand: T | [T, T] + operand: T | [T, T], ) => { switch (operator) { case 'ne': @@ -178,7 +178,7 @@ export const validatePredicateField = ( }; export const isModelConstructor = ( - obj: any + obj: any, ): obj is PersistentModelConstructor => { return ( obj && typeof (>obj).copyOf === 'function' @@ -192,7 +192,7 @@ export function registerNonModelClass(clazz: NonModelTypeConstructor) { } export const isNonModelConstructor = ( - obj: any + obj: any, ): obj is NonModelTypeConstructor => { return nonModelClasses.has(obj); }; @@ -206,12 +206,12 @@ export const traverseModel = ( modelInstanceCreator: ModelInstanceCreator, getModelConstructorByModelName: ( namsespaceName: NAMESPACES, - modelName: string - ) => PersistentModelConstructor + modelName: string, + ) => PersistentModelConstructor, ) => { const modelConstructor = getModelConstructorByModelName( namespace.name as NAMESPACES, - srcModelName + srcModelName, ); const result: { @@ -231,7 +231,7 @@ export const traverseModel = ( if (!topologicallySortedModels.has(namespace)) { topologicallySortedModels.set( namespace, - Array.from(namespace.modelTopologicalOrdering!.keys()) + Array.from(namespace.modelTopologicalOrdering!.keys()), ); } @@ -400,7 +400,7 @@ const getBytesFromHex = (encoded: string): Uint8Array => { out[i / 2] = HEX_TO_SHORT[encodedByte]; } else { throw new Error( - `Cannot decode unrecognized sequence ${encodedByte} as hexadecimal` + `Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`, ); } } @@ -449,7 +449,7 @@ export function getNow() { } export function sortCompareFunction( - sortPredicates: SortPredicatesGroup + sortPredicates: SortPredicatesGroup, ) { return function compareFunction(a, b) { // enable multi-field sort by iterating over predicates until @@ -486,7 +486,7 @@ export function sortCompareFunction( export function directedValueEquality( fromObject: object, againstObject: object, - nullish: boolean = false + nullish: boolean = false, ) { const aKeys = Object.keys(fromObject); @@ -510,7 +510,7 @@ export function directedValueEquality( export function valuesEqual( valA: any, valB: any, - nullish: boolean = false + nullish: boolean = false, ): boolean { let a = valA; let b = valB; @@ -590,12 +590,12 @@ export function valuesEqual( */ export function inMemoryPagination( records: T[], - pagination?: PaginationInput + pagination?: PaginationInput, ): T[] { if (pagination && records.length > 1) { if (pagination.sort) { const sortPredicates = ModelSortPredicateCreator.getPredicates( - pagination.sort + pagination.sort, ); if (sortPredicates.length) { @@ -622,7 +622,7 @@ export function inMemoryPagination( */ export async function asyncSome( items: Record[], - matches: (item: Record) => Promise + matches: (item: Record) => Promise, ): Promise { for (const item of items) { if (await matches(item)) { @@ -641,7 +641,7 @@ export async function asyncSome( */ export async function asyncEvery( items: Record[], - matches: (item: Record) => Promise + matches: (item: Record) => Promise, ): Promise { for (const item of items) { if (!(await matches(item))) { @@ -661,7 +661,7 @@ export async function asyncEvery( */ export async function asyncFilter( items: T[], - matches: (item: T) => Promise + matches: (item: T) => Promise, ): Promise { const results: T[] = []; for (const item of items) { @@ -678,13 +678,13 @@ export const isAWSDate = (val: string): boolean => { export const isAWSTime = (val: string): boolean => { return !!/^\d{2}:\d{2}(:\d{2}(.\d+)?)?(Z|[+-]\d{2}:\d{2}($|:\d{2}))?$/.exec( - val + val, ); }; export const isAWSDateTime = (val: string): boolean => { return !!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(.\d+)?)?(Z|[+-]\d{2}:\d{2}($|:\d{2}))?$/.exec( - val + val, ); }; @@ -694,7 +694,7 @@ export const isAWSTimestamp = (val: number): boolean => { export const isAWSEmail = (val: string): boolean => { return !!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.exec( - val + val, ); }; @@ -721,7 +721,7 @@ export const isAWSPhone = (val: string): boolean => { export const isAWSIPAddress = (val: string): boolean => { return !!/((^((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))$)|(^((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?$))$/.exec( - val + val, ); }; @@ -735,7 +735,7 @@ export class DeferredPromise { (resolve: (value: string | PromiseLike) => void, reject) => { self.resolve = resolve; self.reject = reject; - } + }, ); } } @@ -749,7 +749,7 @@ export class DeferredCallbackResolver { private callback = () => {}; private errorHandler: (error: string) => void; private defaultErrorHandler = ( - msg = 'DeferredCallbackResolver error' + msg = 'DeferredCallbackResolver error', ): void => { throw new Error(msg); }; @@ -823,7 +823,7 @@ export class DeferredCallbackResolver { export function mergePatches( originalSource: T, oldPatches: Patch[], - newPatches: Patch[] + newPatches: Patch[], ): Patch[] { const patchesToMerge = oldPatches.concat(newPatches); let patches: Patch[]; @@ -834,7 +834,7 @@ export function mergePatches( }, p => { patches = p; - } + }, ); return patches!; } @@ -880,7 +880,7 @@ export const getStorename = (namespace: string, modelName: string) => { See 'processCompositeKeys' test in util.test.ts for more examples */ export const processCompositeKeys = ( - attributes: ModelAttributes + attributes: ModelAttributes, ): Set[] => { const extractCompositeSortKey = ({ properties: { @@ -935,7 +935,7 @@ export const processCompositeKeys = ( }; export const extractKeyIfExists = ( - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ): ModelAttribute | undefined => { const keyAttribute = modelDefinition?.attributes?.find(isModelAttributeKey); @@ -943,7 +943,7 @@ export const extractKeyIfExists = ( }; export const extractPrimaryKeyFieldNames = ( - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ): string[] => { const keyAttribute = extractKeyIfExists(modelDefinition); if (keyAttribute && isModelAttributePrimaryKey(keyAttribute)) { @@ -955,14 +955,14 @@ export const extractPrimaryKeyFieldNames = ( export const extractPrimaryKeyValues = ( model: T, - keyFields: string[] + keyFields: string[], ): string[] => { return keyFields.map(key => model[key]); }; export const extractPrimaryKeysAndValues = ( model: T, - keyFields: string[] + keyFields: string[], ): any => { const primaryKeysAndValues = {}; keyFields.forEach(key => (primaryKeysAndValues[key] = model[key])); @@ -984,7 +984,7 @@ export const isIdManaged = (modelDefinition: SchemaModel): boolean => { // IdentifierFields // @primaryKey with explicit `id` in the PK. Single key or composite export const isIdOptionallyManaged = ( - modelDefinition: SchemaModel + modelDefinition: SchemaModel, ): boolean => { const keyAttribute = extractKeyIfExists(modelDefinition); @@ -996,7 +996,7 @@ export const isIdOptionallyManaged = ( }; export const establishRelationAndKeys = ( - namespace: SchemaNamespace + namespace: SchemaNamespace, ): [RelationshipType, ModelKeys] => { const relationship: RelationshipType = {}; const keys: ModelKeys = {}; @@ -1024,13 +1024,13 @@ export const establishRelationAndKeys = ( if (connectionType === 'BELONGS_TO') { const targetNames = extractTargetNamesFromSrc( - fieldAttribute.association + fieldAttribute.association, ); if (targetNames) { const idxName = indexNameFromKeys(targetNames); const idxExists = relationship[mKey].indexes.find( - ([index]) => index === idxName + ([index]) => index === idxName, ); if (!idxExists) { @@ -1059,7 +1059,7 @@ export const establishRelationAndKeys = ( // create indexes for all other keys const idxName = indexNameFromKeys(fields); const idxExists = relationship[mKey].indexes.find( - ([index]) => index === idxName + ([index]) => index === idxName, ); if (!idxExists) { @@ -1086,7 +1086,7 @@ export const establishRelationAndKeys = ( export const getIndex = ( rel: RelationType[], - src: string + src: string, ): string | undefined => { let indexName; rel.some((relItem: RelationType) => { @@ -1101,7 +1101,7 @@ export const getIndex = ( export const getIndexFromAssociation = ( indexes: IndexesType, - src: string | string[] + src: string | string[], ): string | undefined => { let indexName: string; @@ -1123,7 +1123,7 @@ the single field `targetName` has been replaced with an array of `targetNames`. * @returns array of targetNames, or `undefined` */ export const extractTargetNamesFromSrc = ( - src: RelationType | ModelAssociation | undefined + src: RelationType | ModelAssociation | undefined, ): string[] | undefined => { const targetName = src?.targetName; const targetNames = src?.targetNames; @@ -1159,7 +1159,7 @@ export const keysEqual = (keysA, keysB): boolean => { // Returns primary keys for a model export const getIndexKeys = ( namespace: SchemaNamespace, - modelName: string + modelName: string, ): string[] => { const keyPath = namespace?.keys?.[modelName]?.primaryKey; @@ -1185,10 +1185,10 @@ export const getIndexKeys = ( * @returns An object mapping `createdAt` and `updatedAt` to their field names. */ export const getTimestampFields = ( - definition: SchemaModel + definition: SchemaModel, ): { createdAt: string; updatedAt: string } => { const modelAttributes = definition.attributes?.find( - attr => attr.type === 'model' + attr => attr.type === 'model', ); const timestampFieldsMap = modelAttributes?.properties?.timestamps; diff --git a/packages/geo/__tests__/Geo.test.ts b/packages/geo/__tests__/Geo.test.ts index 6a65c407eb7..1f331aff552 100644 --- a/packages/geo/__tests__/Geo.test.ts +++ b/packages/geo/__tests__/Geo.test.ts @@ -111,7 +111,7 @@ describe('Geo', () => { geo.addPluggable(provider); expect(geo.getPluggable(provider.getProviderName())).toBeInstanceOf( - AmazonLocationServiceProvider + AmazonLocationServiceProvider, ); }); @@ -123,7 +123,7 @@ describe('Geo', () => { geo.removePluggable(provider.getProviderName()); expect(() => geo.getPluggable(provider.getProviderName())).toThrow( - 'No plugin found in Geo for the provider' + 'No plugin found in Geo for the provider', ); }); }); @@ -133,7 +133,7 @@ describe('Geo', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const geo = new GeoClass(); expect(geo.getPluggable('AmazonLocationService')).toBeInstanceOf( - AmazonLocationServiceProvider + AmazonLocationServiceProvider, ); }); }); @@ -149,10 +149,10 @@ describe('Geo', () => { geo.removePluggable('AmazonLocationService'); expect(() => geo.getAvailableMaps()).toThrow( - 'No plugin found in Geo for the provider' + 'No plugin found in Geo for the provider', ); expect(() => geo.getDefaultMap()).toThrow( - 'No plugin found in Geo for the provider' + 'No plugin found in Geo for the provider', ); }); @@ -163,7 +163,7 @@ describe('Geo', () => { const geo = new GeoClass(); expect(() => geo.getAvailableMaps()).toThrow( - "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" + "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after", ); }); @@ -188,7 +188,7 @@ describe('Geo', () => { const geo = new GeoClass(); expect(() => geo.getDefaultMap()).toThrow( - "No Geo configuration found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" + "No Geo configuration found in amplify config, run 'amplify add geo' to create one and run `amplify push` after", ); }); @@ -199,7 +199,7 @@ describe('Geo', () => { const geo = new GeoClass(); expect(() => geo.getDefaultMap()).toThrow( - "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" + "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after", ); }); @@ -214,7 +214,7 @@ describe('Geo', () => { const geo = new GeoClass(); expect(() => geo.getDefaultMap()).toThrow( - "No default map resource found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" + "No default map resource found in amplify config, run 'amplify add geo' to create one and run `amplify push` after", ); }); @@ -330,7 +330,7 @@ describe('Geo', () => { }; await expect(geo.searchByText(testString, searchOptions)).rejects.toThrow( - 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object' + 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object', ); }); @@ -344,7 +344,7 @@ describe('Geo', () => { geo.removePluggable('AmazonLocationService'); await expect(geo.searchByText(testString)).rejects.toThrow( - 'No plugin found in Geo for the provider' + 'No plugin found in Geo for the provider', ); }); }); @@ -382,7 +382,7 @@ describe('Geo', () => { geo.removePluggable('AmazonLocationService'); await expect(geo.searchByPlaceId(testPlaceId)).rejects.toThrow( - 'No plugin found in Geo for the provider' + 'No plugin found in Geo for the provider', ); }); }); @@ -491,9 +491,9 @@ describe('Geo', () => { }; await expect( - geo.searchForSuggestions(testString, searchOptions) + geo.searchForSuggestions(testString, searchOptions), ).rejects.toThrow( - 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object' + 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object', ); }); @@ -507,7 +507,7 @@ describe('Geo', () => { geo.removePluggable('AmazonLocationService'); await expect(geo.searchForSuggestions(testString)).rejects.toThrow( - 'No plugin found in Geo for the provider' + 'No plugin found in Geo for the provider', ); }); }); @@ -548,7 +548,7 @@ describe('Geo', () => { }; const results = await geo.searchByCoordinates( testCoordinates, - searchOptions + searchOptions, ); expect(results).toEqual(testPlaceCamelCase); @@ -571,7 +571,7 @@ describe('Geo', () => { geo.removePluggable('AmazonLocationService'); await expect(geo.searchByCoordinates(testCoordinates)).rejects.toThrow( - 'No plugin found in Geo for the provider' + 'No plugin found in Geo for the provider', ); }); }); @@ -629,7 +629,7 @@ describe('Geo', () => { // Expect that the API was called the right amount of times const expectedNumberOfCalls = Math.floor(validGeofences.length / 10) + 1; expect(LocationClient.prototype.send).toHaveBeenCalledTimes( - expectedNumberOfCalls + expectedNumberOfCalls, ); }); @@ -643,7 +643,7 @@ describe('Geo', () => { geo.removePluggable('AmazonLocationService'); await expect(geo.saveGeofences(validGeofence1)).rejects.toThrow( - 'No plugin found in Geo for the provider' + 'No plugin found in Geo for the provider', ); }); }); @@ -723,10 +723,10 @@ describe('Geo', () => { expect(second100Geofences.entries.length).toEqual(100); expect(second100Geofences.entries[0].geofenceId).toEqual( - 'validGeofenceId100' + 'validGeofenceId100', ); expect(second100Geofences.entries[99].geofenceId).toEqual( - 'validGeofenceId199' + 'validGeofenceId199', ); }); }); diff --git a/packages/geo/__tests__/Providers/AmazonLocationServiceProvider.test.ts b/packages/geo/__tests__/Providers/AmazonLocationServiceProvider.test.ts index c44e391b21a..e52aebf7ad3 100644 --- a/packages/geo/__tests__/Providers/AmazonLocationServiceProvider.test.ts +++ b/packages/geo/__tests__/Providers/AmazonLocationServiceProvider.test.ts @@ -117,7 +117,7 @@ describe('AmazonLocationServiceProvider', () => { }); const provider = new AmazonLocationServiceProvider(); expect(() => provider.getAvailableMaps()).toThrow( - "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" + "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after", ); }); @@ -142,7 +142,7 @@ describe('AmazonLocationServiceProvider', () => { const provider = new AmazonLocationServiceProvider(); expect(() => provider.getDefaultMap()).toThrow( - "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" + "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after", ); }); @@ -156,11 +156,11 @@ describe('AmazonLocationServiceProvider', () => { }; (Amplify.getConfig as jest.Mock).mockReturnValue(noDefaultMapConfig); const provider = new AmazonLocationServiceProvider( - noDefaultMapConfig as any + noDefaultMapConfig as any, ); expect(() => provider.getDefaultMap()).toThrow( - "No default map resource found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" + "No default map resource found in amplify config, run 'amplify add geo' to create one and run `amplify push` after", ); }); @@ -189,7 +189,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const results = await locationProvider.searchByText(testString); @@ -210,7 +210,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const searchOptions: SearchByTextOptions = { @@ -222,7 +222,7 @@ describe('AmazonLocationServiceProvider', () => { const results = await locationProvider.searchByText( testString, - searchOptions + searchOptions, ); expect(results).toEqual([testPlaceCamelCase]); @@ -245,7 +245,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const searchOptions: SearchByTextOptions = { @@ -257,7 +257,7 @@ describe('AmazonLocationServiceProvider', () => { const resultsWithConstraints = await locationProvider.searchByText( testString, - searchOptions + searchOptions, ); expect(resultsWithConstraints).toEqual([testPlaceCamelCase]); @@ -279,7 +279,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const searchOptions: SearchByTextOptions = { @@ -291,9 +291,9 @@ describe('AmazonLocationServiceProvider', () => { }; await expect( - locationProvider.searchByText(testString, searchOptions) + locationProvider.searchByText(testString, searchOptions), ).rejects.toThrow( - 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object' + 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object', ); }); @@ -305,7 +305,7 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect(locationProvider.searchByText(testString)).rejects.toThrow( - 'No credentials' + 'No credentials', ); }); @@ -317,7 +317,7 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect(locationProvider.searchByText(testString)).rejects.toThrow( - 'No credentials' + 'No credentials', ); }); @@ -332,7 +332,7 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); expect(locationProvider.searchByText(testString)).rejects.toThrow( - 'No Search Index found in amplify config, please run `amplify add geo` to create one and run `amplify push` after.' + 'No Search Index found in amplify config, please run `amplify add geo` to create one and run `amplify push` after.', ); }); }); @@ -356,7 +356,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const results = await locationProvider.searchForSuggestions(testString); @@ -378,7 +378,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const searchOptions: SearchByTextOptions = { @@ -390,7 +390,7 @@ describe('AmazonLocationServiceProvider', () => { const results = await locationProvider.searchForSuggestions( testString, - searchOptions + searchOptions, ); expect(results).toEqual(testResults); @@ -413,7 +413,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const searchOptions: SearchByTextOptions = { @@ -445,7 +445,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const searchOptions: SearchByTextOptions = { @@ -457,9 +457,9 @@ describe('AmazonLocationServiceProvider', () => { }; await expect( - locationProvider.searchForSuggestions(testString, searchOptions) + locationProvider.searchForSuggestions(testString, searchOptions), ).rejects.toThrow( - 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object' + 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object', ); }); @@ -471,7 +471,7 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect( - locationProvider.searchForSuggestions(testString) + locationProvider.searchForSuggestions(testString), ).rejects.toThrow('No credentials'); }); @@ -483,7 +483,7 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect( - locationProvider.searchForSuggestions(testString) + locationProvider.searchForSuggestions(testString), ).rejects.toThrow('No credentials'); }); @@ -498,9 +498,9 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect( - locationProvider.searchForSuggestions(testString) + locationProvider.searchForSuggestions(testString), ).rejects.toThrow( - 'No Search Index found in amplify config, please run `amplify add geo` to create one and run `amplify push` after.' + 'No Search Index found in amplify config, please run `amplify add geo` to create one and run `amplify push` after.', ); }); }); @@ -516,7 +516,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const results = await locationProvider.searchByPlaceId(testPlaceId); @@ -538,11 +538,11 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); await expect(locationProvider.searchByPlaceId('')).rejects.toThrow( - 'PlaceId cannot be an empty string.' + 'PlaceId cannot be an empty string.', ); }); @@ -554,7 +554,7 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect( - locationProvider.searchByPlaceId(testPlaceId) + locationProvider.searchByPlaceId(testPlaceId), ).rejects.toThrow('No credentials'); }); @@ -566,7 +566,7 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect( - locationProvider.searchByPlaceId(testPlaceId) + locationProvider.searchByPlaceId(testPlaceId), ).rejects.toThrow('No credentials'); }); @@ -581,9 +581,9 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect( - locationProvider.searchByPlaceId(testPlaceId) + locationProvider.searchByPlaceId(testPlaceId), ).rejects.toThrow( - 'No Search Index found in amplify config, please run `amplify add geo` to create one and run `amplify push` after.' + 'No Search Index found in amplify config, please run `amplify add geo` to create one and run `amplify push` after.', ); }); }); @@ -598,7 +598,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const results = @@ -620,7 +620,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const searchOptions: SearchByCoordinatesOptions = { @@ -629,7 +629,7 @@ describe('AmazonLocationServiceProvider', () => { }; const results = await locationProvider.searchByCoordinates( testCoordinates, - searchOptions + searchOptions, ); expect(results).toEqual(testPlaceCamelCase); @@ -650,7 +650,7 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect( - locationProvider.searchByCoordinates(testCoordinates) + locationProvider.searchByCoordinates(testCoordinates), ).rejects.toThrow('No credentials'); }); @@ -662,7 +662,7 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect( - locationProvider.searchByCoordinates(testCoordinates) + locationProvider.searchByCoordinates(testCoordinates), ).rejects.toThrow('No credentials'); }); @@ -677,9 +677,9 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect( - locationProvider.searchByCoordinates(testCoordinates) + locationProvider.searchByCoordinates(testCoordinates), ).rejects.toThrow( - 'No Search Index found in amplify config, please run `amplify add geo` to create one and run `amplify push` after.' + 'No Search Index found in amplify config, please run `amplify add geo` to create one and run `amplify push` after.', ); }); }); @@ -696,7 +696,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const results = await locationProvider.saveGeofences(validGeofences); @@ -711,7 +711,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const numberOfGeofences = 44; @@ -739,7 +739,7 @@ describe('AmazonLocationServiceProvider', () => { const spyClientInput = spyonClient.mock.calls; expect(spyClientInput.length).toEqual( - Math.ceil(spyProviderInput.length / 10) + Math.ceil(spyProviderInput.length / 10), ); }); @@ -750,7 +750,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const input = createGeofenceInputArray(44); @@ -812,13 +812,13 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); await expect( - locationProvider.saveGeofences([clockwiseGeofence]) + locationProvider.saveGeofences([clockwiseGeofence]), ).rejects.toThrow( - 'geofenceWithClockwiseGeofence: LinearRing coordinates must be wound counterclockwise' + 'geofenceWithClockwiseGeofence: LinearRing coordinates must be wound counterclockwise', ); }); @@ -833,11 +833,11 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); await expect(locationProvider.saveGeofences([])).rejects.toThrow( - 'Geofence input array is empty' + 'Geofence input array is empty', ); }); @@ -852,9 +852,9 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect( - locationProvider.saveGeofences(validGeofences) + locationProvider.saveGeofences(validGeofences), ).rejects.toThrow( - 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.' + 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.', ); }); }); @@ -871,7 +871,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const results: AmazonLocationServiceGeofence = @@ -899,12 +899,12 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const badGeofenceId = 't|-|!$ !$ N()T V@|_!D'; await expect(locationProvider.getGeofence(badGeofenceId)).rejects.toThrow( - `Invalid geofenceId: '${badGeofenceId}' - IDs can only contain alphanumeric characters, hyphens, underscores and periods.` + `Invalid geofenceId: '${badGeofenceId}' - IDs can only contain alphanumeric characters, hyphens, underscores and periods.`, ); }); @@ -919,7 +919,7 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect(locationProvider.getGeofence('geofenceId')).rejects.toThrow( - 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.' + 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.', ); }); }); @@ -936,7 +936,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const geofences = await locationProvider.listGeofences(); @@ -955,7 +955,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const first100Geofences = await locationProvider.listGeofences(); @@ -966,10 +966,10 @@ describe('AmazonLocationServiceProvider', () => { expect(second100Geofences.entries.length).toEqual(100); expect(second100Geofences.entries[0].geofenceId).toEqual( - 'validGeofenceId100' + 'validGeofenceId100', ); expect(second100Geofences.entries[99].geofenceId).toEqual( - 'validGeofenceId199' + 'validGeofenceId199', ); }); @@ -984,7 +984,7 @@ describe('AmazonLocationServiceProvider', () => { const locationProvider = new AmazonLocationServiceProvider(); await expect(locationProvider.listGeofences()).rejects.toThrow( - 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.' + 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.', ); }); }); @@ -1001,7 +1001,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const geofenceIds = validGeofences.map(({ geofenceId }) => geofenceId); @@ -1023,7 +1023,7 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const geofenceIds = validGeofences.map(({ geofenceId }) => geofenceId); @@ -1045,7 +1045,7 @@ describe('AmazonLocationServiceProvider', () => { const spyClientInput = spyonClient.mock.calls; expect(spyClientInput.length).toEqual( - Math.ceil(spyProviderInput.length / 10) + Math.ceil(spyProviderInput.length / 10), ); }); @@ -1056,11 +1056,11 @@ describe('AmazonLocationServiceProvider', () => { (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); const input = createGeofenceInputArray(44).map( - ({ geofenceId }) => geofenceId + ({ geofenceId }) => geofenceId, ); input[22] = 'badId'; const validEntries = [...input.slice(0, 20), ...input.slice(30, 44)]; @@ -1110,16 +1110,16 @@ describe('AmazonLocationServiceProvider', () => { }); (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); await expect( locationProvider.deleteGeofences([ 'thisIsAGoodId', 't|-|!$ !$ N()T V@|_!D', '#2 t|-|!$ !$ N()T V@|_!D', - ]) + ]), ).rejects.toThrow( - `Invalid geofence ids: t|-|!$ !$ N()T V@|_!D, #2 t|-|!$ !$ N()T V@|_!D` + `Invalid geofence ids: t|-|!$ !$ N()T V@|_!D, #2 t|-|!$ !$ N()T V@|_!D`, ); }); @@ -1129,10 +1129,10 @@ describe('AmazonLocationServiceProvider', () => { }); (Amplify.getConfig as jest.Mock).mockReturnValue(awsConfigGeoV4); const locationProvider = new AmazonLocationServiceProvider( - awsConfigGeoV4 + awsConfigGeoV4, ); await expect(locationProvider.deleteGeofences([])).rejects.toThrow( - `GeofenceId input array is empty` + `GeofenceId input array is empty`, ); }); @@ -1149,9 +1149,9 @@ describe('AmazonLocationServiceProvider', () => { const geofenceIds = validGeofences.map(({ geofenceId }) => geofenceId); await expect( - locationProvider.deleteGeofences(geofenceIds) + locationProvider.deleteGeofences(geofenceIds), ).rejects.toThrow( - 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.' + 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.', ); }); }); diff --git a/packages/geo/__tests__/util.test.ts b/packages/geo/__tests__/util.test.ts index c02d46d8b7b..3ec7f10854f 100644 --- a/packages/geo/__tests__/util.test.ts +++ b/packages/geo/__tests__/util.test.ts @@ -42,7 +42,7 @@ describe('Geo utility functions', () => { test('should error with message for bad longitude', () => { invalidLngCoordinates.forEach(([lng, lat]) => { expect(() => validateCoordinates(lng, lat)).toThrow( - 'Longitude must be between -180 and 180 degrees inclusive.' + 'Longitude must be between -180 and 180 degrees inclusive.', ); }); }); @@ -50,7 +50,7 @@ describe('Geo utility functions', () => { test('should error with message for bad latitude', () => { invalidLatCoordinates.forEach(([lng, lat]) => { expect(() => validateCoordinates(lng, lat)).toThrow( - 'Latitude must be between -90 and 90 degrees inclusive.' + 'Latitude must be between -90 and 90 degrees inclusive.', ); }); }); @@ -58,7 +58,7 @@ describe('Geo utility functions', () => { test('should error with message for coordinates with infinity', () => { infiniteCoordinates.forEach(([lng, lat]) => { expect(() => validateCoordinates(lng, lat)).toThrow( - `Invalid coordinates: [${lng},${lat}]` + `Invalid coordinates: [${lng},${lat}]`, ); }); }); @@ -71,30 +71,33 @@ describe('Geo utility functions', () => { }); test('should error if first and last coordinates do not match', () => { expect(() => - validateLinearRing(linearRingIncomplete, 'linearRingIncomplete') + validateLinearRing(linearRingIncomplete, 'linearRingIncomplete'), ).toThrow( - `linearRingIncomplete: LinearRing's first and last coordinates are not the same` + `linearRingIncomplete: LinearRing's first and last coordinates are not the same`, ); }); test('should error if LinearRing has less than 4 elements', () => { expect(() => - validateLinearRing(linearRingTooSmall, 'linearRingTooSmall') + validateLinearRing(linearRingTooSmall, 'linearRingTooSmall'), ).toThrow( - 'linearRingTooSmall: LinearRing must contain 4 or more coordinates.' + 'linearRingTooSmall: LinearRing must contain 4 or more coordinates.', ); }); test('should error if any coordinates are not valid', () => { expect(() => - validateLinearRing(linearRingBadCoordinates, 'linearRingBadCoordinates') + validateLinearRing( + linearRingBadCoordinates, + 'linearRingBadCoordinates', + ), ).toThrow( - 'linearRingBadCoordinates: One or more of the coordinates in the Polygon LinearRing are not valid: [{"coordinates":[181,0],"error":"Longitude must be between -180 and 180 degrees inclusive."},{"coordinates":[0,-91],"error":"Latitude must be between -90 and 90 degrees inclusive."}]' + 'linearRingBadCoordinates: One or more of the coordinates in the Polygon LinearRing are not valid: [{"coordinates":[181,0],"error":"Longitude must be between -180 and 180 degrees inclusive."},{"coordinates":[0,-91],"error":"Latitude must be between -90 and 90 degrees inclusive."}]', ); }); test('should error if the coordinates are not in counterclockwise order', () => { expect(() => - validateLinearRing(clockwiseLinearRing, 'clockwiseLinearRing') + validateLinearRing(clockwiseLinearRing, 'clockwiseLinearRing'), ).toThrow( - 'clockwiseLinearRing: LinearRing coordinates must be wound counterclockwise' + 'clockwiseLinearRing: LinearRing coordinates must be wound counterclockwise', ); }); }); @@ -105,17 +108,17 @@ describe('Geo utility functions', () => { }); test('should error if polygon is not a length of 1', () => { expect(() => validatePolygon(polygonTooBig, 'polygonTooBig')).toThrow( - `polygonTooBig: Polygon must have a single LinearRing array. Note: We do not currently support polygons with holes, multipolygons, polygons that are wound clockwise, or that cross the antimeridian.` + `polygonTooBig: Polygon must have a single LinearRing array. Note: We do not currently support polygons with holes, multipolygons, polygons that are wound clockwise, or that cross the antimeridian.`, ); expect(() => validatePolygon([], 'emptyPolygon')).toThrow( - `emptyPolygon: Polygon must have a single LinearRing array.` + `emptyPolygon: Polygon must have a single LinearRing array.`, ); }); test('should error if polygon has more than 1000 vertices', () => { expect(() => - validatePolygon(polygonTooManyVertices, 'polygonTooManyVertices') + validatePolygon(polygonTooManyVertices, 'polygonTooManyVertices'), ).toThrow( - 'polygonTooManyVertices: Polygon has more than the maximum 1000 vertices.' + 'polygonTooManyVertices: Polygon has more than the maximum 1000 vertices.', ); }); }); @@ -161,18 +164,18 @@ describe('Geo utility functions', () => { }); test('should error if a geofenceId is not unique', () => { expect(() => validateGeofencesInput(geofencesWithDuplicate)).toThrow( - `Duplicate geofenceId: validGeofenceId1` + `Duplicate geofenceId: validGeofenceId1`, ); }); test('should error if a geofenceId is not valid', () => { expect(() => validateGeofencesInput(geofencesWithInvalidId)).toThrow( - `Invalid geofenceId: 't|-|!$ !$ N()T V@|_!D' - IDs can only contain alphanumeric characters, hyphens, underscores and periods.` + `Invalid geofenceId: 't|-|!$ !$ N()T V@|_!D' - IDs can only contain alphanumeric characters, hyphens, underscores and periods.`, ); }); }); test('should error if polygon has more than 1000 vertices', () => { expect(() => validateGeofencesInput([geofenceWithTooManyVertices])).toThrow( - `Geofence 'geofenceWithTooManyVertices' has more than the maximum of 1000 vertices` + `Geofence 'geofenceWithTooManyVertices' has more than the maximum of 1000 vertices`, ); }); @@ -193,7 +196,7 @@ describe('Geo utility functions', () => { }; const result = mapSearchOptions( searchOptionsWithBiasPosition, - locationServiceInput + locationServiceInput, ); expect(result).toEqual(modifiedSearchOptionsMappedToInput); }); @@ -210,7 +213,7 @@ describe('Geo utility functions', () => { }; const result = mapSearchOptions( searchOptionsWithSearchAreaConstraints, - locationServiceInput + locationServiceInput, ); expect(result).toEqual(modifiedSearchOptionsMappedToInput); }); @@ -222,7 +225,7 @@ describe('Geo utility functions', () => { searchAreaConstraints: [123, 456, 789, 321], }; expect(() => mapSearchOptions(searchOptionsExtended, {})).toThrow( - `BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object` + `BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object`, ); }); }); diff --git a/packages/geo/src/Geo.ts b/packages/geo/src/Geo.ts index 504973bdbb7..ea98d997320 100644 --- a/packages/geo/src/Geo.ts +++ b/packages/geo/src/Geo.ts @@ -43,7 +43,7 @@ export class GeoClass { this._config = Object.assign({}, this._config, amplifyConfig.Geo); const locationProvider = new AmazonLocationServiceProvider( - amplifyConfig.Geo + amplifyConfig.Geo, ); this._pluggables.push(locationProvider); @@ -74,7 +74,7 @@ export class GeoClass { */ public getPluggable(providerName: string) { const pluggable = this._pluggables.find( - pluggable => pluggable.getProviderName() === providerName + pluggable => pluggable.getProviderName() === providerName, ); if (pluggable === undefined) { logger.debug('No plugin found with providerName', providerName); @@ -88,7 +88,7 @@ export class GeoClass { */ public removePluggable(providerName: string) { this._pluggables = this._pluggables.filter( - pluggable => pluggable.getProviderName() !== providerName + pluggable => pluggable.getProviderName() !== providerName, ); return; } @@ -123,7 +123,7 @@ export class GeoClass { */ public async searchByText( text: string, - options?: SearchByTextOptions + options?: SearchByTextOptions, ): Promise { const { providerName = DEFAULT_PROVIDER } = options || {}; const prov = this.getPluggable(providerName); @@ -144,7 +144,7 @@ export class GeoClass { */ public async searchForSuggestions( text: string, - options?: SearchByTextOptions + options?: SearchByTextOptions, ) { const { providerName = DEFAULT_PROVIDER } = options || {}; const prov = this.getPluggable(providerName); @@ -165,7 +165,7 @@ export class GeoClass { */ public async searchByPlaceId( placeId: string, - options?: searchByPlaceIdOptions + options?: searchByPlaceIdOptions, ) { const providerName = DEFAULT_PROVIDER; const prov = this.getPluggable(providerName); @@ -186,7 +186,7 @@ export class GeoClass { */ public async searchByCoordinates( coordinates: Coordinates, - options?: SearchByCoordinatesOptions + options?: SearchByCoordinatesOptions, ): Promise { const { providerName = DEFAULT_PROVIDER } = options || {}; const prov = this.getPluggable(providerName); @@ -211,7 +211,7 @@ export class GeoClass { */ public async saveGeofences( geofences: GeofenceInput | GeofenceInput[], - options?: GeofenceOptions + options?: GeofenceOptions, ): Promise { const { providerName = DEFAULT_PROVIDER } = options || {}; const prov = this.getPluggable(providerName); @@ -240,7 +240,7 @@ export class GeoClass { */ public async getGeofence( geofenceId: GeofenceId, - options?: GeofenceOptions + options?: GeofenceOptions, ): Promise { const { providerName = DEFAULT_PROVIDER } = options || {}; const prov = this.getPluggable(providerName); @@ -261,7 +261,7 @@ export class GeoClass { * nextToken: token for next page of geofences */ public async listGeofences( - options?: ListGeofenceOptions + options?: ListGeofenceOptions, ): Promise { const { providerName = DEFAULT_PROVIDER } = options || {}; const prov = this.getPluggable(providerName); @@ -284,7 +284,7 @@ export class GeoClass { */ public async deleteGeofences( geofenceIds: string | string[], - options?: GeofenceOptions + options?: GeofenceOptions, ): Promise { const { providerName = DEFAULT_PROVIDER } = options || {}; const prov = this.getPluggable(providerName); diff --git a/packages/geo/src/providers/location-service/AmazonLocationServiceProvider.ts b/packages/geo/src/providers/location-service/AmazonLocationServiceProvider.ts index 79488643d50..85957e43ab4 100644 --- a/packages/geo/src/providers/location-service/AmazonLocationServiceProvider.ts +++ b/packages/geo/src/providers/location-service/AmazonLocationServiceProvider.ts @@ -139,7 +139,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { */ public async searchByText( text: string, - options?: SearchByTextOptions + options?: SearchByTextOptions, ): Promise { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { @@ -187,7 +187,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { * Here we want to flatten that to an array of results and change them to camelCase */ const PascalResults: PlaceResult[] = response.Results.map( - result => result.Place + result => result.Place, ); const results: Place[] = camelcaseKeys(PascalResults, { deep: true, @@ -205,7 +205,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { public async searchForSuggestions( text: string, - options?: SearchByTextOptions + options?: SearchByTextOptions, ): Promise { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { @@ -238,7 +238,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { customUserAgent: getGeoUserAgent(GeoAction.SearchForSuggestions), }); const command = new SearchPlaceIndexForSuggestionsCommand( - locationServiceInput + locationServiceInput, ); let response; @@ -270,7 +270,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { public async searchByPlaceId( placeId: string, - options?: searchByPlaceIdOptions + options?: searchByPlaceIdOptions, ): Promise { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { @@ -317,7 +317,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { */ public async searchByCoordinates( coordinates: Coordinates, - options?: SearchByCoordinatesOptions + options?: SearchByCoordinatesOptions, ): Promise { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { @@ -344,7 +344,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { customUserAgent: getGeoUserAgent(GeoAction.SearchByCoordinates), }); const command = new SearchPlaceIndexForPositionCommand( - locationServiceInput + locationServiceInput, ); let response; @@ -378,7 +378,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { */ public async saveGeofences( geofences: GeofenceInput[], - options?: AmazonLocationServiceGeofenceOptions + options?: AmazonLocationServiceGeofenceOptions, ): Promise { if (geofences.length < 1) { throw new Error('Geofence input array is empty'); @@ -408,7 +408,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { Polygon: polygon, }, }; - } + }, ); const results: SaveGeofencesResults = { successes: [], @@ -430,7 +430,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { try { response = await this._AmazonLocationServiceBatchPutGeofenceCall( batch, - options?.collectionName || this._config.geofenceCollections.default + options?.collectionName || this._config.geofenceCollections.default, ); } catch (error) { // If the API call fails, add the geofences to the errors array and move to next batch @@ -468,7 +468,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { geofenceId: GeofenceId!, }); }); - }) + }), ); return results; @@ -482,7 +482,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { */ public async getGeofence( geofenceId: GeofenceId, - options?: AmazonLocationServiceGeofenceOptions + options?: AmazonLocationServiceGeofenceOptions, ): Promise { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { @@ -546,7 +546,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { * nextToken: token for next page of geofences */ public async listGeofences( - options?: AmazonLocationServiceListGeofenceOptions + options?: AmazonLocationServiceListGeofenceOptions, ): Promise { const credentialsOK = await this._ensureCredentials(); if (!credentialsOK) { @@ -577,7 +577,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { // Create Amazon Location Service command const command: ListGeofencesCommand = new ListGeofencesCommand( - listGeofencesInput + listGeofencesInput, ); // Make API call @@ -604,7 +604,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { polygon: Geometry!.Polygon as GeofencePolygon, }, }; - } + }, ), nextToken: NextToken, }; @@ -622,7 +622,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { */ public async deleteGeofences( geofenceIds: string[], - options?: AmazonLocationServiceGeofenceOptions + options?: AmazonLocationServiceGeofenceOptions, ): Promise { if (geofenceIds.length < 1) { throw new Error('GeofenceId input array is empty'); @@ -665,7 +665,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { try { response = await this._AmazonLocationServiceBatchDeleteGeofenceCall( batch, - options?.collectionName || this._config.geofenceCollections.default + options?.collectionName || this._config.geofenceCollections.default, ); } catch (error) { // If the API call fails, add the geofences to the errors array and move to next batch @@ -685,12 +685,12 @@ export class AmazonLocationServiceProvider implements GeoProvider { } const badGeofenceIds = response.Errors.map( - ({ geofenceId }) => geofenceId + ({ geofenceId }) => geofenceId, ); results.successes.push( - ...batch.filter(Id => !badGeofenceIds.includes(Id)) + ...batch.filter(Id => !badGeofenceIds.includes(Id)), ); - }) + }), ); return results; } @@ -704,7 +704,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { if (!credentials) return false; logger.debug( 'Set credentials for storage. Credentials are:', - credentials + credentials, ); this._credentials = credentials; return true; @@ -769,7 +769,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { private async _AmazonLocationServiceBatchPutGeofenceCall( PascalGeofences: BatchPutGeofenceRequestEntry[], - collectionName?: string + collectionName?: string, ) { // Create the BatchPutGeofence input const geofenceInput: BatchPutGeofenceCommandInput = { @@ -796,7 +796,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { private async _AmazonLocationServiceBatchDeleteGeofenceCall( geofenceIds: string[], - collectionName?: string + collectionName?: string, ): Promise { // Create the BatchDeleteGeofence input const deleteGeofencesInput: BatchDeleteGeofenceCommandInput = { diff --git a/packages/geo/src/types/Provider.ts b/packages/geo/src/types/Provider.ts index bd9f169b810..1ef696fcfb7 100644 --- a/packages/geo/src/types/Provider.ts +++ b/packages/geo/src/types/Provider.ts @@ -37,29 +37,29 @@ export interface GeoProvider { // search by coordinates and return a matching place searchByCoordinates( coordinates: Coordinates, - options?: SearchByCoordinatesOptions + options?: SearchByCoordinatesOptions, ): Promise; searchForSuggestions( text: string, - options?: SearchByTextOptions + options?: SearchByTextOptions, ): Promise; searchByPlaceId( placeId: string, - options?: searchByPlaceIdOptions + options?: searchByPlaceIdOptions, ): Promise; // create geofences saveGeofences( geofences: GeofenceInput[], - options?: GeofenceOptions + options?: GeofenceOptions, ): Promise; // get a single geofence getGeofence( geofenceId: GeofenceId, - options?: ListGeofenceOptions + options?: ListGeofenceOptions, ): Promise; // list all geofences @@ -68,6 +68,6 @@ export interface GeoProvider { // Delete geofences deleteGeofences( geofenceIds: string[], - options?: GeofenceOptions + options?: GeofenceOptions, ): Promise; } diff --git a/packages/geo/src/util.ts b/packages/geo/src/util.ts index 0889ab22e7a..c83d1f2de01 100644 --- a/packages/geo/src/util.ts +++ b/packages/geo/src/util.ts @@ -26,7 +26,7 @@ export function validateCoordinates(lng: Longitude, lat: Latitude): void { throw new Error('Latitude must be between -90 and 90 degrees inclusive.'); } else if (lng < -180 || 180 < lng) { throw new Error( - 'Longitude must be between -180 and 180 degrees inclusive.' + 'Longitude must be between -180 and 180 degrees inclusive.', ); } } @@ -37,20 +37,20 @@ export function validateGeofenceId(geofenceId: GeofenceId): void { // Check if geofenceId is valid if (!geofenceIdRegex.test(geofenceId)) { throw new Error( - `Invalid geofenceId: '${geofenceId}' - IDs can only contain alphanumeric characters, hyphens, underscores and periods.` + `Invalid geofenceId: '${geofenceId}' - IDs can only contain alphanumeric characters, hyphens, underscores and periods.`, ); } } export function validateLinearRing( linearRing: LinearRing, - geofenceId?: GeofenceId + geofenceId?: GeofenceId, ): void { const errorPrefix = geofenceId ? `${geofenceId}: ` : ''; // Validate LinearRing size, must be at least 4 points if (linearRing.length < 4) { throw new Error( - `${errorPrefix}LinearRing must contain 4 or more coordinates.` + `${errorPrefix}LinearRing must contain 4 or more coordinates.`, ); } @@ -66,8 +66,8 @@ export function validateLinearRing( if (badCoordinates.length > 0) { throw new Error( `${errorPrefix}One or more of the coordinates in the Polygon LinearRing are not valid: ${JSON.stringify( - badCoordinates - )}` + badCoordinates, + )}`, ); } @@ -77,45 +77,45 @@ export function validateLinearRing( if (lngA !== lngB || latA !== latB) { throw new Error( - `${errorPrefix}LinearRing's first and last coordinates are not the same` + `${errorPrefix}LinearRing's first and last coordinates are not the same`, ); } if (booleanClockwise(linearRing)) { throw new Error( - `${errorPrefix}LinearRing coordinates must be wound counterclockwise` + `${errorPrefix}LinearRing coordinates must be wound counterclockwise`, ); } } export function validatePolygon( polygon: GeofencePolygon, - geofenceId?: GeofenceId + geofenceId?: GeofenceId, ): void { const errorPrefix = geofenceId ? `${geofenceId}: ` : ''; if (!Array.isArray(polygon)) { throw new Error( - `${errorPrefix}Polygon is of incorrect structure. It should be an array of LinearRings` + `${errorPrefix}Polygon is of incorrect structure. It should be an array of LinearRings`, ); } if (polygon.length < 1) { throw new Error( - `${errorPrefix}Polygon must have a single LinearRing array.` + `${errorPrefix}Polygon must have a single LinearRing array.`, ); } if (polygon.length > 1) { throw new Error( - `${errorPrefix}Polygon must have a single LinearRing array. Note: We do not currently support polygons with holes, multipolygons, polygons that are wound clockwise, or that cross the antimeridian.` + `${errorPrefix}Polygon must have a single LinearRing array. Note: We do not currently support polygons with holes, multipolygons, polygons that are wound clockwise, or that cross the antimeridian.`, ); } const verticesCount = polygon.reduce( (prev, linearRing) => prev + linearRing.length, - 0 + 0, ); if (verticesCount > 1000) { throw new Error( - `${errorPrefix}Polygon has more than the maximum 1000 vertices.` + `${errorPrefix}Polygon has more than the maximum 1000 vertices.`, ); } polygon.forEach(linearRing => { @@ -161,11 +161,11 @@ export function validateGeofencesInput(geofences: GeofenceInput[]) { } catch (error) { if ( (error as Error).message.includes( - 'Polygon has more than the maximum 1000 vertices.' + 'Polygon has more than the maximum 1000 vertices.', ) ) { throw new Error( - `Geofence '${geofenceId}' has more than the maximum of 1000 vertices` + `Geofence '${geofenceId}' has more than the maximum of 1000 vertices`, ); } } @@ -188,7 +188,7 @@ export function mapSearchOptions(options, locationServiceInput) { if (options['biasPosition'] && options['searchAreaConstraints']) { throw new Error( - 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object' + 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object', ); } if (options['biasPosition']) { diff --git a/packages/interactions/__tests__/lex-v1/AWSLexProvider.test.ts b/packages/interactions/__tests__/lex-v1/AWSLexProvider.test.ts index 051c2aa8029..1cd11351a83 100644 --- a/packages/interactions/__tests__/lex-v1/AWSLexProvider.test.ts +++ b/packages/interactions/__tests__/lex-v1/AWSLexProvider.test.ts @@ -255,7 +255,7 @@ describe('Interactions', () => { mockFetchAuthSession.mockReturnValue(Promise.reject(new Error())); await expect( - provider.sendMessage(botConfig.BookTrip, 'hi') + provider.sendMessage(botConfig.BookTrip, 'hi'), ).rejects.toEqual('No credentials'); expect.assertions(1); }); @@ -268,7 +268,7 @@ describe('Interactions', () => { options: { messageType: 'text', }, - }) + }), ).rejects.toEqual('invalid content type'); // obj voice in wrong format @@ -278,7 +278,7 @@ describe('Interactions', () => { options: { messageType: 'voice', }, - }) + }), ).rejects.toEqual('invalid content type'); }); }); @@ -299,7 +299,7 @@ describe('Interactions', () => { test('Configure onComplete callback for a configured bot successfully', () => { expect(() => - provider.onComplete(botConfig.BookTrip, callback) + provider.onComplete(botConfig.BookTrip, callback), ).not.toThrow(); expect.assertions(1); }); @@ -324,7 +324,7 @@ describe('Interactions', () => { // mock callbacks inProgressCallback = jest.fn((err, confirmation) => - fail(`callback shouldn't be called`) + fail(`callback shouldn't be called`), ); completeSuccessCallback = jest.fn((err, confirmation) => { @@ -340,23 +340,23 @@ describe('Interactions', () => { }); completeFailCallback = jest.fn((err, confirmation) => - expect(err).toEqual(new Error('Bot conversation failed')) + expect(err).toEqual(new Error('Bot conversation failed')), ); // mock responses inProgressResp = (await provider.sendMessage( botConfig.BookTrip, - 'hi' + 'hi', )) as PostTextCommandOutput; completeSuccessResp = (await provider.sendMessage( botConfig.BookTrip, - 'done' + 'done', )) as PostTextCommandOutput; completeFailResp = (await provider.sendMessage( botConfig.BookTrip, - 'error' + 'error', )) as PostTextCommandOutput; }); diff --git a/packages/interactions/__tests__/lex-v1/apis/onComplete.test.ts b/packages/interactions/__tests__/lex-v1/apis/onComplete.test.ts index 76d40ae7d10..29f3ac6cd99 100644 --- a/packages/interactions/__tests__/lex-v1/apis/onComplete.test.ts +++ b/packages/interactions/__tests__/lex-v1/apis/onComplete.test.ts @@ -37,7 +37,7 @@ describe('Interactions LexV1 API: onComplete', () => { it('rejects when bot config does not exist', async () => { mockResolveBotConfig.mockReturnValue(undefined); expect(() => - onComplete({ botName: v1BotConfig.name, callback: jest.fn }) + onComplete({ botName: v1BotConfig.name, callback: jest.fn }), ).toThrow(InteractionsError); }); }); diff --git a/packages/interactions/__tests__/lex-v1/apis/send.test.ts b/packages/interactions/__tests__/lex-v1/apis/send.test.ts index 63f3393f45d..7e05d0538aa 100644 --- a/packages/interactions/__tests__/lex-v1/apis/send.test.ts +++ b/packages/interactions/__tests__/lex-v1/apis/send.test.ts @@ -36,7 +36,7 @@ describe('Interactions LexV1 API: send', () => { it('rejects when bot config does not exist', async () => { mockResolveBotConfig.mockReturnValue(undefined); await expect( - send({ botName: v1BotConfig.name, message: uuid() }) + send({ botName: v1BotConfig.name, message: uuid() }), ).rejects.toBeInstanceOf(InteractionsError); }); }); diff --git a/packages/interactions/__tests__/lex-v2/AWSLexV2Provider.test.ts b/packages/interactions/__tests__/lex-v2/AWSLexV2Provider.test.ts index 4f5c526edd7..0239afb08e1 100644 --- a/packages/interactions/__tests__/lex-v2/AWSLexV2Provider.test.ts +++ b/packages/interactions/__tests__/lex-v2/AWSLexV2Provider.test.ts @@ -342,7 +342,7 @@ describe('Interactions', () => { mockFetchAuthSession.mockReturnValue(Promise.reject(new Error())); await expect( - provider.sendMessage(botConfig.BookTrip, 'hi') + provider.sendMessage(botConfig.BookTrip, 'hi'), ).rejects.toEqual('No credentials'); expect.assertions(1); }); @@ -355,7 +355,7 @@ describe('Interactions', () => { options: { messageType: 'text', }, - }) + }), ).rejects.toEqual('invalid content type'); // obj voice in wrong format @@ -365,7 +365,7 @@ describe('Interactions', () => { options: { messageType: 'voice', }, - }) + }), ).rejects.toEqual('invalid content type'); }); }); @@ -384,7 +384,7 @@ describe('Interactions', () => { test('Configure onComplete callback for a configured bot successfully', () => { expect(() => - provider.onComplete(botConfig.BookTrip, callback) + provider.onComplete(botConfig.BookTrip, callback), ).not.toThrow(); expect.assertions(1); }); @@ -410,7 +410,7 @@ describe('Interactions', () => { switch (actionType) { case ACTION_TYPE.IN_PROGRESS: return jest.fn((err, confirmation) => - fail(`callback shouldn't be called`) + fail(`callback shouldn't be called`), ); case ACTION_TYPE.COMPLETE: @@ -428,24 +428,24 @@ describe('Interactions', () => { }); case ACTION_TYPE.ERROR: return jest.fn((err, confirmation) => - expect(err).toEqual(new Error('Bot conversation failed')) + expect(err).toEqual(new Error('Bot conversation failed')), ); } }; const inProgressResp = (await provider.sendMessage( botConfig.BookTrip, - 'in progress. callback isnt fired' + 'in progress. callback isnt fired', )) as RecognizeTextCommandOutput; const completeSuccessResp = (await provider.sendMessage( botConfig.BookTrip, - 'done' + 'done', )) as RecognizeTextCommandOutput; const completeFailResp = (await provider.sendMessage( botConfig.BookTrip, - 'error' + 'error', )) as RecognizeTextCommandOutput; mockResponseProvider = actionType => { @@ -469,13 +469,13 @@ describe('Interactions', () => { // callback is only called once conversation is completed let config = { ...botConfig.BookTrip, name: uuid() }; const inProgressCallback = mockCallbackProvider( - ACTION_TYPE.IN_PROGRESS + ACTION_TYPE.IN_PROGRESS, ); provider.onComplete(config, inProgressCallback); provider._reportBotStatus( mockResponseProvider(ACTION_TYPE.IN_PROGRESS), - config + config, ); jest.runAllTimers(); @@ -486,13 +486,13 @@ describe('Interactions', () => { test(`task complete; callback with success resp`, async () => { let config = { ...botConfig.BookTrip, name: uuid() }; const completeSuccessCallback = mockCallbackProvider( - ACTION_TYPE.COMPLETE + ACTION_TYPE.COMPLETE, ); provider.onComplete(config, completeSuccessCallback); provider._reportBotStatus( mockResponseProvider(ACTION_TYPE.COMPLETE), - config + config, ); jest.runAllTimers(); @@ -508,7 +508,7 @@ describe('Interactions', () => { provider._reportBotStatus( mockResponseProvider(ACTION_TYPE.ERROR), - config + config, ); jest.runAllTimers(); diff --git a/packages/interactions/__tests__/lex-v2/apis/onComplete.test.ts b/packages/interactions/__tests__/lex-v2/apis/onComplete.test.ts index c81b120693c..dc0b77186d6 100644 --- a/packages/interactions/__tests__/lex-v2/apis/onComplete.test.ts +++ b/packages/interactions/__tests__/lex-v2/apis/onComplete.test.ts @@ -37,7 +37,7 @@ describe('Interactions LexV2 API: onComplete', () => { it('rejects when bot config does not exist', async () => { mockResolveBotConfig.mockReturnValue(undefined); expect(() => - onComplete({ botName: v2BotConfig.name, callback: jest.fn }) + onComplete({ botName: v2BotConfig.name, callback: jest.fn }), ).toThrow(InteractionsError); }); }); diff --git a/packages/interactions/__tests__/lex-v2/apis/send.test.ts b/packages/interactions/__tests__/lex-v2/apis/send.test.ts index 6d6ec998127..b1984822db0 100644 --- a/packages/interactions/__tests__/lex-v2/apis/send.test.ts +++ b/packages/interactions/__tests__/lex-v2/apis/send.test.ts @@ -36,7 +36,7 @@ describe('Interactions LexV2 API: send', () => { it('rejects when bot config does not exist', async () => { mockResolveBotConfig.mockReturnValue(undefined); await expect( - send({ botName: v2BotConfig.name, message: uuid() }) + send({ botName: v2BotConfig.name, message: uuid() }), ).rejects.toBeInstanceOf(InteractionsError); }); }); diff --git a/packages/interactions/src/errors/assertValidationError.ts b/packages/interactions/src/errors/assertValidationError.ts index 6870363498c..74b05eb8056 100644 --- a/packages/interactions/src/errors/assertValidationError.ts +++ b/packages/interactions/src/errors/assertValidationError.ts @@ -10,7 +10,7 @@ import { InteractionsError } from './InteractionsError'; export function assertValidationError( assertion: boolean, name: InteractionsValidationErrorCode, - message?: string + message?: string, ): asserts assertion { if (!assertion) { const { message: defaultMessage, recoverySuggestion } = diff --git a/packages/interactions/src/lex-v1/AWSLexProvider.ts b/packages/interactions/src/lex-v1/AWSLexProvider.ts index ba876c5477c..deb2dba436e 100644 --- a/packages/interactions/src/lex-v1/AWSLexProvider.ts +++ b/packages/interactions/src/lex-v1/AWSLexProvider.ts @@ -44,7 +44,7 @@ class AWSLexProvider { */ reportBotStatus( data: AWSLexProviderSendResponse, - { name }: AWSLexProviderOption + { name }: AWSLexProviderOption, ) { const callback = this._botsCompleteCallback[name]; if (!callback) { @@ -68,7 +68,7 @@ class AWSLexProvider { async sendMessage( botConfig: AWSLexProviderOption, - message: string | InteractionsMessage + message: string | InteractionsMessage, ): Promise { // check if credentials are present let session; @@ -158,7 +158,7 @@ class AWSLexProvider { onComplete( { name }: AWSLexProviderOption, - callback: InteractionsOnCompleteCallback + callback: InteractionsOnCompleteCallback, ) { this._botsCompleteCallback[name] = callback; } diff --git a/packages/interactions/src/lex-v1/apis/onComplete.ts b/packages/interactions/src/lex-v1/apis/onComplete.ts index bee86a26850..e1d34ad25b9 100644 --- a/packages/interactions/src/lex-v1/apis/onComplete.ts +++ b/packages/interactions/src/lex-v1/apis/onComplete.ts @@ -15,7 +15,7 @@ export const onComplete = (input: OnCompleteInput): void => { assertValidationError( !!botConfig, InteractionsValidationErrorCode.NoBotConfig, - `Bot ${botName} does not exist.` + `Bot ${botName} does not exist.`, ); lexProvider.onComplete(botConfig, callback); }; diff --git a/packages/interactions/src/lex-v1/apis/send.ts b/packages/interactions/src/lex-v1/apis/send.ts index 720bb04b040..2dc4e46e265 100644 --- a/packages/interactions/src/lex-v1/apis/send.ts +++ b/packages/interactions/src/lex-v1/apis/send.ts @@ -15,7 +15,7 @@ export const send = async (input: SendInput): Promise => { assertValidationError( !!botConfig, InteractionsValidationErrorCode.NoBotConfig, - `Bot ${botName} does not exist.` + `Bot ${botName} does not exist.`, ); return lexProvider.sendMessage(botConfig, message); }; diff --git a/packages/interactions/src/lex-v1/utils/resolveBotConfig.ts b/packages/interactions/src/lex-v1/utils/resolveBotConfig.ts index 2a60b3d4309..88b243dbc8a 100644 --- a/packages/interactions/src/lex-v1/utils/resolveBotConfig.ts +++ b/packages/interactions/src/lex-v1/utils/resolveBotConfig.ts @@ -5,7 +5,7 @@ import { AWSLexProviderOption } from '../types'; import { Amplify } from '@aws-amplify/core'; export const resolveBotConfig = ( - botName: string + botName: string, ): AWSLexProviderOption | undefined => { const { [botName]: botConfig = undefined } = Amplify.getConfig().Interactions?.LexV1 ?? {}; diff --git a/packages/interactions/src/lex-v2/AWSLexV2Provider.ts b/packages/interactions/src/lex-v2/AWSLexV2Provider.ts index 9f8fab1c2bf..177fb40bc26 100644 --- a/packages/interactions/src/lex-v2/AWSLexV2Provider.ts +++ b/packages/interactions/src/lex-v2/AWSLexV2Provider.ts @@ -66,7 +66,7 @@ class AWSLexV2Provider { */ public async sendMessage( botConfig: AWSLexV2ProviderOption, - message: string | InteractionsMessage + message: string | InteractionsMessage, ): Promise { // check if credentials are present let session; @@ -98,14 +98,14 @@ class AWSLexV2Provider { botConfig, message, reqBaseParams, - client + client, ); } else { response = await this._handleRecognizeUtteranceCommand( botConfig, message, reqBaseParams, - client + client, ); } return response; @@ -119,7 +119,7 @@ class AWSLexV2Provider { */ public onComplete( { name }: AWSLexV2ProviderOption, - callback: InteractionsOnCompleteCallback + callback: InteractionsOnCompleteCallback, ) { this._botsCompleteCallback[name] = callback; } @@ -129,7 +129,7 @@ class AWSLexV2Provider { */ _reportBotStatus( data: AWSLexV2ProviderSendResponse, - { name }: AWSLexV2ProviderOption + { name }: AWSLexV2ProviderOption, ) { const sessionState = data?.sessionState; @@ -159,7 +159,7 @@ class AWSLexV2Provider { * update audioStream format */ private async _formatUtteranceCommandOutput( - data: RecognizeUtteranceCommandOutput + data: RecognizeUtteranceCommandOutput, ): Promise { return { ...data, @@ -182,7 +182,7 @@ class AWSLexV2Provider { botConfig: AWSLexV2ProviderOption, data: string, baseParams: lexV2BaseReqParams, - client: LexRuntimeV2Client + client: LexRuntimeV2Client, ) { logger.debug('postText to lex2', data); @@ -210,7 +210,7 @@ class AWSLexV2Provider { botConfig: AWSLexV2ProviderOption, data: InteractionsMessage, baseParams: lexV2BaseReqParams, - client: LexRuntimeV2Client + client: LexRuntimeV2Client, ) { const { content, diff --git a/packages/interactions/src/lex-v2/apis/onComplete.ts b/packages/interactions/src/lex-v2/apis/onComplete.ts index 9a972ba5fa2..1ac0cae524b 100644 --- a/packages/interactions/src/lex-v2/apis/onComplete.ts +++ b/packages/interactions/src/lex-v2/apis/onComplete.ts @@ -15,7 +15,7 @@ export const onComplete = (input: OnCompleteInput): void => { assertValidationError( !!botConfig, InteractionsValidationErrorCode.NoBotConfig, - `Bot ${botName} does not exist.` + `Bot ${botName} does not exist.`, ); lexProvider.onComplete(botConfig, callback); }; diff --git a/packages/interactions/src/lex-v2/apis/send.ts b/packages/interactions/src/lex-v2/apis/send.ts index c04211a4ebd..c185c4595fa 100644 --- a/packages/interactions/src/lex-v2/apis/send.ts +++ b/packages/interactions/src/lex-v2/apis/send.ts @@ -15,7 +15,7 @@ export const send = async (input: SendInput): Promise => { assertValidationError( !!botConfig, InteractionsValidationErrorCode.NoBotConfig, - `Bot ${botName} does not exist.` + `Bot ${botName} does not exist.`, ); return lexProvider.sendMessage(botConfig, message); }; diff --git a/packages/interactions/src/lex-v2/utils/resolveBotConfig.ts b/packages/interactions/src/lex-v2/utils/resolveBotConfig.ts index a99133e62a0..3759a39810b 100644 --- a/packages/interactions/src/lex-v2/utils/resolveBotConfig.ts +++ b/packages/interactions/src/lex-v2/utils/resolveBotConfig.ts @@ -5,7 +5,7 @@ import { AWSLexV2ProviderOption } from '../types'; import { Amplify } from '@aws-amplify/core'; export const resolveBotConfig = ( - botName: string + botName: string, ): AWSLexV2ProviderOption | undefined => { const { [botName]: botConfig = undefined } = Amplify.getConfig().Interactions?.LexV2 ?? {}; diff --git a/packages/interactions/src/types/Interactions.ts b/packages/interactions/src/types/Interactions.ts index 59da66dc0cc..0f76a1da857 100644 --- a/packages/interactions/src/types/Interactions.ts +++ b/packages/interactions/src/types/Interactions.ts @@ -21,7 +21,7 @@ export type InteractionsMessage = export type InteractionsOnCompleteCallback = ( error?: Error, - completion?: InteractionsResponse + completion?: InteractionsResponse, ) => void; export type InteractionsResponse = { diff --git a/packages/interactions/src/utils/utils.native.ts b/packages/interactions/src/utils/utils.native.ts index f37d8947a17..cc4fcb02c48 100644 --- a/packages/interactions/src/utils/utils.native.ts +++ b/packages/interactions/src/utils/utils.native.ts @@ -33,7 +33,7 @@ export const base64ToArrayBuffer = (base64: string): Uint8Array => { }; export const gzipDecompressToString = async ( - data: Uint8Array + data: Uint8Array, ): Promise => { return new Promise((resolve, reject) => { try { diff --git a/packages/interactions/src/utils/utils.ts b/packages/interactions/src/utils/utils.ts index 607e4c30e27..6c3b50f3a9a 100644 --- a/packages/interactions/src/utils/utils.ts +++ b/packages/interactions/src/utils/utils.ts @@ -18,7 +18,7 @@ export const base64ToArrayBuffer = (base64: string): Uint8Array => { }; export const gzipDecompressToString = async ( - data: Uint8Array + data: Uint8Array, ): Promise => { return await new Promise((resolve, reject) => { gunzip(data, (err, resp) => { diff --git a/packages/notifications/__tests__/eventListeners/eventListeners.test.ts b/packages/notifications/__tests__/eventListeners/eventListeners.test.ts index 9ac105ea41e..dc8d7d27ff8 100644 --- a/packages/notifications/__tests__/eventListeners/eventListeners.test.ts +++ b/packages/notifications/__tests__/eventListeners/eventListeners.test.ts @@ -55,7 +55,7 @@ describe('Event listeners', () => { addEventListener(eventType, mockHandler); await expect( - notifyEventListenersAndAwaitHandlers(eventType, params) + notifyEventListenersAndAwaitHandlers(eventType, params), ).rejects.toThrow(); expect(mockHandler).toHaveBeenCalledWith(params); }); @@ -104,7 +104,7 @@ describe('Event listeners', () => { const unknownType = 'unknown'; expect(notifyEventListeners(unknownType, {})).toBeUndefined(); expect( - await notifyEventListenersAndAwaitHandlers(unknownType, {}) + await notifyEventListenersAndAwaitHandlers(unknownType, {}), ).toStrictEqual([]); }); }); diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/clearMessages.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/clearMessages.test.ts index faffa251ee5..42070f9f34f 100644 --- a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/clearMessages.test.ts +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/clearMessages.test.ts @@ -26,7 +26,7 @@ describe('clearMessages', () => { }); it('Rejects if there is a validation error', async () => { await expect(clearMessages()).rejects.toStrictEqual( - expect.any(InAppMessagingError) + expect.any(InAppMessagingError), ); expect(mockDefaultStorage.removeItem).not.toHaveBeenCalled(); }); @@ -37,10 +37,10 @@ describe('clearMessages', () => { new InAppMessagingError({ name: 'ItemCorrupted', message: 'Item corrupted', - }) + }), ); await expect(clearMessages()).rejects.toStrictEqual( - expect.any(InAppMessagingError) + expect.any(InAppMessagingError), ); }); @@ -48,7 +48,7 @@ describe('clearMessages', () => { initializeInAppMessaging(); await clearMessages(); expect(mockDefaultStorage.removeItem).toHaveBeenCalledWith( - `${PINPOINT_KEY_PREFIX}${STORAGE_KEY_SUFFIX}` + `${PINPOINT_KEY_PREFIX}${STORAGE_KEY_SUFFIX}`, ); }); }); diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/dispatchEvent.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/dispatchEvent.test.ts index 1cdadd7a343..5de2bdfb5cc 100644 --- a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/dispatchEvent.test.ts +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/dispatchEvent.test.ts @@ -34,40 +34,40 @@ describe('dispatchEvent', () => { it('gets in-app messages from store and notifies listeners', async () => { const [message] = inAppMessages; mockDefaultStorage.getItem.mockResolvedValueOnce( - JSON.stringify(simpleInAppMessages) + JSON.stringify(simpleInAppMessages), ); mockProcessInAppMessages.mockReturnValueOnce([message]); await dispatchEvent(simpleInAppMessagingEvent); expect(mockProcessInAppMessages).toHaveBeenCalledWith( simpleInAppMessages, - simpleInAppMessagingEvent + simpleInAppMessagingEvent, ); expect(mockNotifyEventListeners).toHaveBeenCalledWith( 'messageReceived', - message + message, ); }); it('handles conflicts through default conflict handler', async () => { mockDefaultStorage.getItem.mockResolvedValueOnce( - JSON.stringify(simpleInAppMessages) + JSON.stringify(simpleInAppMessages), ); mockProcessInAppMessages.mockReturnValueOnce(inAppMessages); await dispatchEvent(simpleInAppMessagingEvent); expect(mockProcessInAppMessages).toHaveBeenCalledWith( simpleInAppMessages, - simpleInAppMessagingEvent + simpleInAppMessagingEvent, ); expect(mockNotifyEventListeners).toHaveBeenCalledWith( 'messageReceived', - inAppMessages[4] + inAppMessages[4], ); }); it('does not notify listeners if no messages are returned', async () => { mockProcessInAppMessages.mockReturnValueOnce([]); mockDefaultStorage.getItem.mockResolvedValueOnce( - JSON.stringify(simpleInAppMessages) + JSON.stringify(simpleInAppMessages), ); await dispatchEvent(simpleInAppMessagingEvent); @@ -78,7 +78,7 @@ describe('dispatchEvent', () => { it('logs error if storage retrieval fails', async () => { mockDefaultStorage.getItem.mockRejectedValueOnce(Error); await expect( - dispatchEvent(simpleInAppMessagingEvent) + dispatchEvent(simpleInAppMessagingEvent), ).rejects.toStrictEqual(expect.any(InAppMessagingError)); }); }); diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/initializeInAppMessaging.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/initializeInAppMessaging.test.ts index 621280a13cf..0edfd5c0885 100644 --- a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/initializeInAppMessaging.test.ts +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/initializeInAppMessaging.test.ts @@ -27,17 +27,17 @@ describe('initializeInAppMessaging', () => { expect(mockAddEventListener).toHaveBeenNthCalledWith( 1, 'messageDisplayed', - expect.any(Function) + expect.any(Function), ); expect(mockAddEventListener).toHaveBeenNthCalledWith( 2, 'messageDismissed', - expect.any(Function) + expect.any(Function), ); expect(mockAddEventListener).toHaveBeenNthCalledWith( 3, 'messageActionTaken', - expect.any(Function) + expect.any(Function), ); expect(Hub.listen).toHaveBeenCalledWith('analytics', expect.any(Function)); }); diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/interactionEvents.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/interactionEvents.test.ts index 23862aaf31d..325d9118dee 100644 --- a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/interactionEvents.test.ts +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/interactionEvents.test.ts @@ -30,7 +30,7 @@ describe('Interaction events', () => { expect(mockAddEventListener).toHaveBeenCalledWith( 'messageReceived', - handler + handler, ); }); @@ -39,7 +39,7 @@ describe('Interaction events', () => { expect(mockAddEventListener).toHaveBeenCalledWith( 'messageDisplayed', - handler + handler, ); }); @@ -48,7 +48,7 @@ describe('Interaction events', () => { expect(mockAddEventListener).toHaveBeenCalledWith( 'messageDismissed', - handler + handler, ); }); @@ -57,7 +57,7 @@ describe('Interaction events', () => { expect(mockAddEventListener).toHaveBeenCalledWith( 'messageActionTaken', - handler + handler, ); }); it('can be notified by notifyMessageInteraction', () => { @@ -70,7 +70,7 @@ describe('Interaction events', () => { expect(mockNotifyEventListeners).toHaveBeenCalledWith( 'messageReceived', - message + message, ); }); }); diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/setConflictHandler.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/setConflictHandler.test.ts index e62915c8110..4c58f87bafa 100644 --- a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/setConflictHandler.test.ts +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/setConflictHandler.test.ts @@ -43,7 +43,7 @@ describe('setConflictHandler', () => { expect(mockNotifyEventListeners).toHaveBeenCalledWith( 'messageReceived', - customHandledMessage + customHandledMessage, ); }); }); diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/syncMessages.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/syncMessages.test.ts index db1e7cab106..32a26a71ff3 100644 --- a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/syncMessages.test.ts +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/apis/syncMessages.test.ts @@ -77,7 +77,7 @@ describe('syncMessages', () => { expect(mockDefaultStorage.setItem).toHaveBeenCalledWith( expect.stringContaining(STORAGE_KEY_SUFFIX), - JSON.stringify(simpleInAppMessages) + JSON.stringify(simpleInAppMessages), ); }); @@ -93,7 +93,7 @@ describe('syncMessages', () => { throw new Error(); }); await expect(syncMessages()).rejects.toStrictEqual( - expect.any(InAppMessagingError) + expect.any(InAppMessagingError), ); expect(mockDefaultStorage.setItem).not.toHaveBeenCalled(); @@ -102,7 +102,7 @@ describe('syncMessages', () => { it('Rejects if there is a failure getting messages', async () => { mockGetInAppMessages.mockRejectedValueOnce(Error); await expect(syncMessages()).rejects.toStrictEqual( - expect.any(InAppMessagingError) + expect.any(InAppMessagingError), ); expect(mockDefaultStorage.setItem).not.toHaveBeenCalled(); @@ -111,7 +111,7 @@ describe('syncMessages', () => { it('Rejects if there is a failure storing messages', async () => { mockDefaultStorage.setItem.mockRejectedValueOnce(Error); await expect(syncMessages()).rejects.toStrictEqual( - expect.any(InAppMessagingError) + expect.any(InAppMessagingError), ); }); }); diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/helpers.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/helpers.test.ts index 33b7bfd1b6d..62013e6cf5f 100644 --- a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/helpers.test.ts +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/helpers.test.ts @@ -250,7 +250,7 @@ describe('InAppMessaging Provider Utils', () => { // Set the end date to 24 hours from now message!.Schedule!.EndDate = new Date( - new Date().getTime() + HOUR_IN_MS * 24 + new Date().getTime() + HOUR_IN_MS * 24, ).toISOString(); expect(isBeforeEndDate(message)).toBe(true); diff --git a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveConfig.test.ts b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveConfig.test.ts index 6eb572e2888..4ea208a69a9 100644 --- a/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveConfig.test.ts +++ b/packages/notifications/__tests__/inAppMessaging/providers/pinpoint/utils/resolveConfig.test.ts @@ -15,7 +15,7 @@ describe('resolveConfig', () => { it('should return the configured appId and region', () => { Amplify.configure(validConfig); expect(resolveConfig()).toStrictEqual( - validConfig.Notifications!.InAppMessaging!.Pinpoint + validConfig.Notifications!.InAppMessaging!.Pinpoint, ); }); }); diff --git a/packages/notifications/__tests__/inAppMessaging/utils/processInAppMessages.test.ts b/packages/notifications/__tests__/inAppMessaging/utils/processInAppMessages.test.ts index ef764ec2d77..40dd21bea12 100644 --- a/packages/notifications/__tests__/inAppMessaging/utils/processInAppMessages.test.ts +++ b/packages/notifications/__tests__/inAppMessaging/utils/processInAppMessages.test.ts @@ -60,7 +60,7 @@ describe('processInAppMessages', () => { mockMatchesMetrics.mockReturnValueOnce(false); const [result] = await processInAppMessages( messages, - simpleInAppMessagingEvent + simpleInAppMessagingEvent, ); expect(result.id).toBe('uuid-4'); }); @@ -68,7 +68,7 @@ describe('processInAppMessages', () => { it('filters in-app messages from Pinpoint by priority', async () => { const [result] = await processInAppMessages( messages, - simpleInAppMessagingEvent + simpleInAppMessagingEvent, ); expect(result.id).toBe('uuid-3'); }); @@ -81,7 +81,7 @@ describe('processInAppMessages', () => { const [result] = await processInAppMessages( messages, - simpleInAppMessagingEvent + simpleInAppMessagingEvent, ); expect(result.id).toBe('uuid-4'); }); diff --git a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/identifyUser.native.test.ts b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/identifyUser.native.test.ts index 7d33fc9f19d..8ff028d026e 100644 --- a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/identifyUser.native.test.ts +++ b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/identifyUser.native.test.ts @@ -55,7 +55,7 @@ describe('identifyUser (native)', () => { throw new Error(); }); await expect( - identifyUser({ userId: 'user-id', userProfile: {} }) + identifyUser({ userId: 'user-id', userProfile: {} }), ).rejects.toThrow(); }); diff --git a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/identifyUser.test.ts b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/identifyUser.test.ts index 4a8b650b3ac..9e3b56a6f07 100644 --- a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/identifyUser.test.ts +++ b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/identifyUser.test.ts @@ -7,7 +7,7 @@ import { expectNotSupportedAsync } from '../../../../testUtils/expectNotSupporte describe('identifyUser', () => { it('is only supported on React Native', async () => { await expectNotSupportedAsync( - identifyUser({ userId: 'user-id', userProfile: {} }) + identifyUser({ userId: 'user-id', userProfile: {} }), ); }); }); diff --git a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/initializePushNotifications.native.test.ts b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/initializePushNotifications.native.test.ts index 9e4d69a8ec0..a2cc8508df7 100644 --- a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/initializePushNotifications.native.test.ts +++ b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/initializePushNotifications.native.test.ts @@ -67,13 +67,13 @@ describe('initializePushNotifications (native)', () => { toBeAdded: () => { expect(mockAddMessageEventListener).toHaveBeenCalledWith( event, - expect.any(Function) + expect.any(Function), ); }, notToBeAdded: () => { expect(mockAddMessageEventListener).not.toHaveBeenCalledWith( event, - expect.any(Function) + expect.any(Function), ); }, }); @@ -126,10 +126,10 @@ describe('initializePushNotifications (native)', () => { it('registers a headless task if able', () => { initializePushNotifications(); expect(mockRegisterHeadlessTask).toHaveBeenCalledWith( - expect.any(Function) + expect.any(Function), ); expectListenerForEvent( - NativeEvent.BACKGROUND_MESSAGE_RECEIVED + NativeEvent.BACKGROUND_MESSAGE_RECEIVED, ).notToBeAdded(); }); @@ -140,7 +140,7 @@ describe('initializePushNotifications (native)', () => { initializePushNotifications(); expect(mockNotifyEventListenersAndAwaitHandlers).toHaveBeenCalledWith( 'backgroundMessageReceived', - simplePushMessage + simplePushMessage, ); }); @@ -149,12 +149,12 @@ describe('initializePushNotifications (native)', () => { mockGetConstants.mockReturnValue({ NativeEvent }); initializePushNotifications(); expectListenerForEvent( - NativeEvent.BACKGROUND_MESSAGE_RECEIVED + NativeEvent.BACKGROUND_MESSAGE_RECEIVED, ).toBeAdded(); expect(mockRegisterHeadlessTask).not.toHaveBeenCalled(); expect(mockNotifyEventListenersAndAwaitHandlers).toHaveBeenCalledWith( 'backgroundMessageReceived', - simplePushMessage + simplePushMessage, ); }); @@ -171,12 +171,12 @@ describe('initializePushNotifications (native)', () => { mockGetConstants.mockReturnValue({ NativeEvent }); initializePushNotifications(); expectListenerForEvent( - NativeEvent.BACKGROUND_MESSAGE_RECEIVED + NativeEvent.BACKGROUND_MESSAGE_RECEIVED, ).toBeAdded(); expect(mockRegisterHeadlessTask).not.toHaveBeenCalled(); expect(mockNotifyEventListenersAndAwaitHandlers).toHaveBeenCalledWith( 'backgroundMessageReceived', - simplePushMessage + simplePushMessage, ); }); }); @@ -187,11 +187,11 @@ describe('initializePushNotifications (native)', () => { initializePushNotifications(); expectListenerForEvent( - NativeEvent.LAUNCH_NOTIFICATION_OPENED + NativeEvent.LAUNCH_NOTIFICATION_OPENED, ).toBeAdded(); expect(mockNotifyEventListeners).toHaveBeenCalledWith( 'launchNotificationOpened', - simplePushMessage + simplePushMessage, ); }); @@ -206,7 +206,7 @@ describe('initializePushNotifications (native)', () => { initializePushNotifications(); expectListenerForEvent( - NativeEvent.LAUNCH_NOTIFICATION_OPENED + NativeEvent.LAUNCH_NOTIFICATION_OPENED, ).notToBeAdded(); expect(mockNotifyEventListeners).not.toHaveBeenCalled(); }); @@ -219,7 +219,7 @@ describe('initializePushNotifications (native)', () => { expectListenerForEvent(NativeEvent.FOREGROUND_MESSAGE_RECEIVED).toBeAdded(); expect(mockNotifyEventListeners).toHaveBeenCalledWith( 'foregroundMessageReceived', - simplePushMessage + simplePushMessage, ); }); @@ -230,7 +230,7 @@ describe('initializePushNotifications (native)', () => { expectListenerForEvent(NativeEvent.NOTIFICATION_OPENED).toBeAdded(); expect(mockNotifyEventListeners).toHaveBeenCalledWith( 'notificationOpened', - simplePushMessage + simplePushMessage, ); }); @@ -242,7 +242,7 @@ describe('initializePushNotifications (native)', () => { if (heardEvent === NativeEvent.TOKEN_RECEIVED) { await handler(pushToken); } - } + }, ); mockUpdateEndpoint.mockImplementation(() => { expect(mockUpdateEndpoint).toHaveBeenCalled(); @@ -252,12 +252,12 @@ describe('initializePushNotifications (native)', () => { expect(mockAddTokenEventListener).toHaveBeenCalledWith( NativeEvent.TOKEN_RECEIVED, - expect.any(Function) + expect.any(Function), ); expect(mockSetToken).toHaveBeenCalledWith(pushToken); expect(mockNotifyEventListeners).toHaveBeenCalledWith( 'tokenReceived', - pushToken + pushToken, ); }); @@ -301,7 +301,7 @@ describe('initializePushNotifications (native)', () => { await expect(handler(pushToken)).rejects.toThrow(); done(); } - } + }, ); initializePushNotifications(); }); diff --git a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationOpened.native.test.ts b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationOpened.native.test.ts index 3e4a692c151..5de86a0ac9e 100644 --- a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationOpened.native.test.ts +++ b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationOpened.native.test.ts @@ -31,7 +31,7 @@ describe('onNotificationOpened (native)', () => { onNotificationOpened(mockHandler); expect(mockAddEventListener).toHaveBeenCalledWith( 'notificationOpened', - mockHandler + mockHandler, ); }); }); diff --git a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.native.test.ts b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.native.test.ts index 298e611178e..4ec43e58348 100644 --- a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.native.test.ts +++ b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.native.test.ts @@ -31,7 +31,7 @@ describe('onNotificationReceivedInBackground (native)', () => { onNotificationReceivedInBackground(mockHandler); expect(mockAddEventListener).toHaveBeenCalledWith( 'backgroundMessageReceived', - mockHandler + mockHandler, ); }); }); diff --git a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.native.test.ts b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.native.test.ts index 9a4a657d967..909c2c83bdd 100644 --- a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.native.test.ts +++ b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.native.test.ts @@ -31,7 +31,7 @@ describe('onNotificationReceivedInForeground (native)', () => { onNotificationReceivedInForeground(mockHandler); expect(mockAddEventListener).toHaveBeenCalledWith( 'foregroundMessageReceived', - mockHandler + mockHandler, ); }); }); diff --git a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onTokenReceived.native.test.ts b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onTokenReceived.native.test.ts index 5dd96673fa5..1e4c8fe722b 100644 --- a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onTokenReceived.native.test.ts +++ b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/apis/onTokenReceived.native.test.ts @@ -31,7 +31,7 @@ describe('onTokenReceived (native)', () => { onTokenReceived(mockHandler); expect(mockAddEventListener).toHaveBeenCalledWith( 'tokenReceived', - mockHandler + mockHandler, ); }); }); diff --git a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.test.ts b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.test.ts index fa073358b28..bc42e38f8d7 100644 --- a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.test.ts +++ b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.test.ts @@ -21,13 +21,13 @@ jest.mock('@aws-amplify/react-native', () => ({ getOperatingSystem: jest.fn(), })); jest.mock( - '../../../../../src/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent' + '../../../../../src/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent', ); jest.mock( - '../../../../../src/pushNotifications/providers/pinpoint/utils/getChannelType' + '../../../../../src/pushNotifications/providers/pinpoint/utils/getChannelType', ); jest.mock( - '../../../../../src/pushNotifications/providers/pinpoint/utils/resolveConfig' + '../../../../../src/pushNotifications/providers/pinpoint/utils/resolveConfig', ); jest.mock('../../../../../src/pushNotifications/utils'); @@ -52,7 +52,7 @@ describe('createMessageEventRecorder', () => { it('returns message event recorder', () => { expect(createMessageEventRecorder('received_background')).toStrictEqual( - expect.any(Function) + expect.any(Function), ); }); @@ -64,7 +64,7 @@ describe('createMessageEventRecorder', () => { }); const recorder = createMessageEventRecorder( 'received_background', - callback + callback, ); recorder(simplePushMessage); }); @@ -73,7 +73,7 @@ describe('createMessageEventRecorder', () => { it('records a message event', done => { mockRecord.mockImplementation(() => { expect(mockRecord).toHaveBeenCalledWith( - expect.objectContaining({ event: analyticsEvent }) + expect.objectContaining({ event: analyticsEvent }), ); done(); }); diff --git a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.test.ts b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.test.ts index 7f15cbcd894..570ebd1ae5a 100644 --- a/packages/notifications/__tests__/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.test.ts +++ b/packages/notifications/__tests__/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.test.ts @@ -16,7 +16,7 @@ describe('getAnalyticsEvent', () => { it('returns an android campaign analytics event', () => { // Also tests campaign / notification received in background combination expect( - getAnalyticsEvent({ data: androidCampaignData }, 'received_background') + getAnalyticsEvent({ data: androidCampaignData }, 'received_background'), ).toMatchObject({ attributes: { campaign_activity_id: pinpointCampaign.campaign_activity_id, @@ -30,7 +30,7 @@ describe('getAnalyticsEvent', () => { it('returns an android journey analytics event', () => { // Also tests journey / notification received in background combination expect( - getAnalyticsEvent({ data: androidJourneyData }, 'received_background') + getAnalyticsEvent({ data: androidJourneyData }, 'received_background'), ).toMatchObject({ attributes: pinpointJourney, name: '_journey.received_background', @@ -40,7 +40,7 @@ describe('getAnalyticsEvent', () => { it('returns an ios campaign analytics event', () => { // Also tests campaign / notification received in foreground combination expect( - getAnalyticsEvent({ data: iosCampaignData }, 'received_foreground') + getAnalyticsEvent({ data: iosCampaignData }, 'received_foreground'), ).toMatchObject({ attributes: pinpointCampaign, name: '_campaign.received_foreground', @@ -50,7 +50,7 @@ describe('getAnalyticsEvent', () => { it('returns an ios journey analytics event', () => { // Also tests journey / notification received in foreground combination expect( - getAnalyticsEvent({ data: iosJourneyData }, 'received_foreground') + getAnalyticsEvent({ data: iosJourneyData }, 'received_foreground'), ).toMatchObject({ attributes: pinpointJourney, name: '_journey.received_foreground', @@ -59,12 +59,12 @@ describe('getAnalyticsEvent', () => { it('returns the correct event type for notifications opened', () => { expect( - getAnalyticsEvent({ data: androidJourneyData }, 'opened_notification') + getAnalyticsEvent({ data: androidJourneyData }, 'opened_notification'), ).toMatchObject({ name: '_journey.opened_notification', }); expect( - getAnalyticsEvent({ data: iosCampaignData }, 'opened_notification') + getAnalyticsEvent({ data: iosCampaignData }, 'opened_notification'), ).toMatchObject({ name: '_campaign.opened_notification', }); @@ -72,7 +72,7 @@ describe('getAnalyticsEvent', () => { it('returns null if there is no data', () => { expect( - getAnalyticsEvent({ data: undefined }, 'received_background') + getAnalyticsEvent({ data: undefined }, 'received_background'), ).toBeNull(); }); diff --git a/packages/notifications/__tests__/pushNotifications/utils/getPushNotificationUserAgentString.test.ts b/packages/notifications/__tests__/pushNotifications/utils/getPushNotificationUserAgentString.test.ts index 44d9eb0114a..7ee3c7dee41 100644 --- a/packages/notifications/__tests__/pushNotifications/utils/getPushNotificationUserAgentString.test.ts +++ b/packages/notifications/__tests__/pushNotifications/utils/getPushNotificationUserAgentString.test.ts @@ -21,7 +21,7 @@ describe('getPushNotificationUserAgentString', () => { it('gets an Amplify user agent', () => { mockGetAmplifyUserAgent.mockReturnValue(userAgentValue); expect( - getPushNotificationUserAgentString(PushNotificationAction.IdentifyUser) + getPushNotificationUserAgentString(PushNotificationAction.IdentifyUser), ).toBe(userAgentValue); expect(mockGetAmplifyUserAgent).toHaveBeenCalledWith({ category: Category.PushNotification, diff --git a/packages/notifications/src/eventListeners/eventListeners.ts b/packages/notifications/src/eventListeners/eventListeners.ts index 5d255f064c7..97dd2bfd088 100644 --- a/packages/notifications/src/eventListeners/eventListeners.ts +++ b/packages/notifications/src/eventListeners/eventListeners.ts @@ -22,12 +22,12 @@ export const notifyEventListenersAndAwaitHandlers = ( } catch (err) { throw err; } - }) + }), ); export const addEventListener = ( type: EventType, - handler: EventHandler + handler: EventHandler, ): EventListenerRemover => { // If there is no listener set for the event type, just create it if (!eventListeners[type]) { diff --git a/packages/notifications/src/inAppMessaging/errors/assertServiceError.ts b/packages/notifications/src/inAppMessaging/errors/assertServiceError.ts index 9665304dd01..ffd965d68a1 100644 --- a/packages/notifications/src/inAppMessaging/errors/assertServiceError.ts +++ b/packages/notifications/src/inAppMessaging/errors/assertServiceError.ts @@ -8,7 +8,7 @@ import { import { InAppMessagingError } from './InAppMessagingError'; export function assertServiceError( - error: unknown + error: unknown, ): asserts error is ServiceError { if ( !error || diff --git a/packages/notifications/src/inAppMessaging/errors/assertValidationError.ts b/packages/notifications/src/inAppMessaging/errors/assertValidationError.ts index b9eb9b304d4..d279970e63b 100644 --- a/packages/notifications/src/inAppMessaging/errors/assertValidationError.ts +++ b/packages/notifications/src/inAppMessaging/errors/assertValidationError.ts @@ -12,7 +12,7 @@ import { */ export function assertValidationError( assertion: boolean, - name: InAppMessagingValidationErrorCode + name: InAppMessagingValidationErrorCode, ): asserts assertion { const { message, recoverySuggestion } = validationErrorMap[name]; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts index a371217c767..c89fda70591 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts @@ -47,13 +47,13 @@ export async function dispatchEvent(input: DispatchEventInput): Promise { const cachedMessages = await defaultStorage.getItem(key); const messages: InAppMessage[] = await processInAppMessages( cachedMessages ? JSON.parse(cachedMessages) : [], - input + input, ); const flattenedMessages = flatten(messages); if (flattenedMessages.length > 0) { notifyEventListeners( 'messageReceived', - conflictHandler(flattenedMessages) + conflictHandler(flattenedMessages), ); } } catch (error) { diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/identifyUser.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/identifyUser.ts index 25d59ba0f7b..4db6f8b7302 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/identifyUser.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/identifyUser.ts @@ -88,7 +88,7 @@ export const identifyUser = async ({ userId, userProfile, userAgentValue: getInAppMessagingUserAgentString( - InAppMessagingAction.IdentifyUser + InAppMessagingAction.IdentifyUser, ), }); }; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageActionTaken.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageActionTaken.ts index f7e3969cb6d..d6bbc4cd3ca 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageActionTaken.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageActionTaken.ts @@ -22,7 +22,7 @@ import { OnMessageActionTakenOutput } from '../types/outputs'; * ``` */ export function onMessageActionTaken( - input: OnMessageActionTakenInput + input: OnMessageActionTakenInput, ): OnMessageActionTakenOutput { assertIsInitialized(); return addEventListener('messageActionTaken', input); diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDismissed.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDismissed.ts index 6ac6dc4ef83..629c06917b7 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDismissed.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDismissed.ts @@ -22,7 +22,7 @@ import { assertIsInitialized } from '../../../utils'; * ``` */ export function onMessageDismissed( - input: OnMessageDismissedInput + input: OnMessageDismissedInput, ): OnMessageDismissedOutput { assertIsInitialized(); return addEventListener('messageDismissed', input); diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDisplayed.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDisplayed.ts index ee672f1a900..fedda241df1 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDisplayed.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDisplayed.ts @@ -22,7 +22,7 @@ import { assertIsInitialized } from '../../../utils'; * ``` */ export function onMessageDisplayed( - input: OnMessageDisplayedInput + input: OnMessageDisplayedInput, ): OnMessageDisplayedOutput { assertIsInitialized(); return addEventListener('messageDisplayed', input); diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageReceived.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageReceived.ts index a80e42af6e5..36acbcfadf0 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageReceived.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageReceived.ts @@ -22,7 +22,7 @@ import { OnMessageReceivedOutput } from '../types/outputs'; * ``` */ export function onMessageReceived( - input: OnMessageReceivedInput + input: OnMessageReceivedInput, ): OnMessageReceivedOutput { assertIsInitialized(); return addEventListener('messageReceived', input); diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/syncMessages.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/syncMessages.ts index 58e6def29e6..c3da2d0dc95 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/syncMessages.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/syncMessages.ts @@ -66,7 +66,7 @@ async function fetchInAppMessages() { identityId, region, userAgentValue: getInAppMessagingUserAgentString( - InAppMessagingAction.SyncMessages + InAppMessagingAction.SyncMessages, ), }); @@ -76,7 +76,7 @@ async function fetchInAppMessages() { }; const response: GetInAppMessagesOutput = await getInAppMessages( { credentials, region }, - input + input, ); const { InAppMessageCampaigns: messages } = response.InAppMessagesResponse ?? {}; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/types/types.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/types/types.ts index 89185f8fb87..71d0092f645 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/types/types.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/types/types.ts @@ -18,7 +18,7 @@ export type InAppMessageCounts = { export type MetricsComparator = ( metricsVal: number, - eventVal: number + eventVal: number, ) => boolean; export enum PinpointMessageEvent { @@ -28,7 +28,7 @@ export enum PinpointMessageEvent { } export type InAppMessageConflictHandler = ( - messages: InAppMessage[] + messages: InAppMessage[], ) => InAppMessage; export type OnMessageInteractionEventHandler = (message: InAppMessage) => void; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts index be0a1bb5b24..64f86d8511a 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts @@ -30,7 +30,7 @@ export const logger = new ConsoleLogger('InAppMessaging.Pinpoint.Utils'); export const recordAnalyticsEvent = ( event: PinpointMessageEvent, - message: InAppMessage + message: InAppMessage, ) => { const { appId, region } = resolveConfig(); @@ -53,7 +53,7 @@ export const recordAnalyticsEvent = ( identityId, region, userAgentValue: getInAppMessagingUserAgentString( - InAppMessagingAction.NotifyMessageInteraction + InAppMessagingAction.NotifyMessageInteraction, ), }); }) @@ -71,7 +71,7 @@ export const getStartOfDay = (): string => { export const matchesEventType = ( { CampaignId, Schedule }: PinpointInAppMessage, - { name: eventType }: InAppMessagingEvent + { name: eventType }: InAppMessagingEvent, ) => { const { EventType } = Schedule?.EventFilter?.Dimensions ?? {}; const memoKey = `${CampaignId}:${eventType}`; @@ -83,7 +83,7 @@ export const matchesEventType = ( export const matchesAttributes = ( { CampaignId, Schedule }: PinpointInAppMessage, - { attributes = {} }: InAppMessagingEvent + { attributes = {} }: InAppMessagingEvent, ): boolean => { const { Attributes } = Schedule?.EventFilter?.Dimensions ?? {}; if (isEmpty(Attributes)) { @@ -98,8 +98,8 @@ export const matchesAttributes = ( if (!eventAttributesMemo.hasOwnProperty(memoKey)) { eventAttributesMemo[memoKey] = !Attributes || - Object.entries(Attributes).every( - ([key, { Values }]) => Values?.includes(attributes[key]) + Object.entries(Attributes).every(([key, { Values }]) => + Values?.includes(attributes[key]), ); } return eventAttributesMemo[memoKey]; @@ -107,7 +107,7 @@ export const matchesAttributes = ( export const matchesMetrics = ( { CampaignId, Schedule }: PinpointInAppMessage, - { metrics = {} }: InAppMessagingEvent + { metrics = {} }: InAppMessagingEvent, ): boolean => { const { Metrics } = Schedule?.EventFilter?.Dimensions ?? {}; if (isEmpty(Metrics)) { @@ -132,7 +132,7 @@ export const matchesMetrics = ( }; export const getComparator = ( - operator?: string + operator?: string, ): MetricsComparator | undefined => { switch (operator) { case 'EQUAL': @@ -187,13 +187,13 @@ export const isQuietTime = (message: PinpointInAppMessage): boolean => { Number.parseInt(startHours, 10), Number.parseInt(startMinutes, 10), 0, - 0 + 0, ); end.setHours( Number.parseInt(endHours, 10), Number.parseInt(endMinutes, 10), 0, - 0 + 0, ); // if quiet time includes midnight, bump the end time to the next day @@ -225,7 +225,7 @@ export const clearMemo = () => { // - 2. Amplify correctly handles the legacy layout values from Pinpoint after they are updated export const interpretLayout = ( - layout: NonNullable['Layout'] + layout: NonNullable['Layout'], ): InAppMessageLayout => { if (layout === 'MOBILE_FEED') { return 'MODAL'; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/messageProcessingHelpers.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/messageProcessingHelpers.ts index fe22b139b87..abcedb39448 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/messageProcessingHelpers.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/messageProcessingHelpers.ts @@ -28,7 +28,7 @@ let sessionMessageCountMap: InAppMessageCountMap = {}; export async function processInAppMessages( messages: PinpointInAppMessage[], - event: InAppMessagingEvent + event: InAppMessagingEvent, ): Promise { let highestPrioritySeen: number | undefined; let acc: PinpointInAppMessage[] = []; @@ -116,7 +116,7 @@ async function isBelowCap({ } async function getMessageCounts( - messageId?: string + messageId?: string, ): Promise { let messageCounts = { sessionCount: 0, diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveCredentials.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveCredentials.ts index 90104cb57a7..22da7a3757b 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveCredentials.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveCredentials.ts @@ -14,7 +14,7 @@ export const resolveCredentials = async () => { const { credentials, identityId } = await fetchAuthSession(); assertValidationError( !!credentials, - InAppMessagingValidationErrorCode.NoCredentials + InAppMessagingValidationErrorCode.NoCredentials, ); return { credentials, identityId }; }; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/userAgent.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/userAgent.ts index 00f1433dda7..b8d4fec1633 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/userAgent.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/userAgent.ts @@ -9,7 +9,7 @@ import { import { UserAgent } from '@aws-sdk/types'; export function getInAppMessagingUserAgent( - action: InAppMessagingAction + action: InAppMessagingAction, ): UserAgent { return getAmplifyUserAgentObject({ category: Category.InAppMessaging, diff --git a/packages/notifications/src/inAppMessaging/utils/statusHelpers.ts b/packages/notifications/src/inAppMessaging/utils/statusHelpers.ts index 8f44c11dec6..62d61a41073 100644 --- a/packages/notifications/src/inAppMessaging/utils/statusHelpers.ts +++ b/packages/notifications/src/inAppMessaging/utils/statusHelpers.ts @@ -27,6 +27,6 @@ export const isInitialized = () => initialized; export function assertIsInitialized() { assertValidationError( isInitialized(), - InAppMessagingValidationErrorCode.NotInitialized + InAppMessagingValidationErrorCode.NotInitialized, ); } diff --git a/packages/notifications/src/pushNotifications/errors/errorHelpers.ts b/packages/notifications/src/pushNotifications/errors/errorHelpers.ts index 20e54209095..5081f19d398 100644 --- a/packages/notifications/src/pushNotifications/errors/errorHelpers.ts +++ b/packages/notifications/src/pushNotifications/errors/errorHelpers.ts @@ -37,7 +37,7 @@ const pushNotificationValidationErrorMap: AmplifyErrorMap = createAssertionFunction( pushNotificationValidationErrorMap, - PushNotificationError + PushNotificationError, ); export const assertIsInitialized = () => { diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/identifyUser.native.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/identifyUser.native.ts index 79d862ae750..ee1810f8018 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/identifyUser.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/identifyUser.native.ts @@ -33,7 +33,7 @@ export const identifyUser: IdentifyUser = async ({ userId, userProfile, userAgentValue: getPushNotificationUserAgentString( - PushNotificationAction.IdentifyUser + PushNotificationAction.IdentifyUser, ), }); }; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/initializePushNotifications.native.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/initializePushNotifications.native.ts index fda560f8069..61cd0eb30ce 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/initializePushNotifications.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/initializePushNotifications.native.ts @@ -66,7 +66,7 @@ const addNativeListeners = (): void => { // keep headless task running until handlers have completed their work await notifyEventListenersAndAwaitHandlers( 'backgroundMessageReceived', - message + message, ); }); } else if (BACKGROUND_MESSAGE_RECEIVED) { @@ -80,7 +80,7 @@ const addNativeListeners = (): void => { await Promise.race([ notifyEventListenersAndAwaitHandlers( 'backgroundMessageReceived', - message + message, ), // background tasks will get suspended and all future tasks be deprioritized by the OS if they run for // more than 30 seconds so we reject with a error in a shorter amount of time to prevent this from @@ -89,9 +89,9 @@ const addNativeListeners = (): void => { setTimeout( () => reject( - `onNotificationReceivedInBackground handlers should complete their work within ${BACKGROUND_TASK_TIMEOUT} seconds, but they did not.` + `onNotificationReceivedInBackground handlers should complete their work within ${BACKGROUND_TASK_TIMEOUT} seconds, but they did not.`, ), - BACKGROUND_TASK_TIMEOUT * 1000 + BACKGROUND_TASK_TIMEOUT * 1000, ); }), ]); @@ -103,7 +103,7 @@ const addNativeListeners = (): void => { completeNotification(completionHandlerId); } } - } + }, ); } @@ -112,7 +112,7 @@ const addNativeListeners = (): void => { FOREGROUND_MESSAGE_RECEIVED, message => { notifyEventListeners('foregroundMessageReceived', message); - } + }, ); launchNotificationOpenedListener = LAUNCH_NOTIFICATION_OPENED @@ -125,8 +125,8 @@ const addNativeListeners = (): void => { notifyEventListeners('launchNotificationOpened', message); // once we are done with it we can remove the listener launchNotificationOpenedListener?.remove(); - } - ) + }, + ) : null; addMessageEventListener( @@ -137,7 +137,7 @@ const addNativeListeners = (): void => { notifyEventListeners('notificationOpened', message); // if we are in this state, we no longer need the listener as the app was launched via some other means launchNotificationOpenedListener?.remove(); - } + }, ); addTokenEventListener( @@ -157,7 +157,7 @@ const addNativeListeners = (): void => { logger.error('Failed to register device for push notifications', err); throw err; } - } + }, ); }; @@ -167,27 +167,27 @@ const addAnalyticsListeners = (): void => { // wire up default Pinpoint message event handling addEventListener( 'backgroundMessageReceived', - createMessageEventRecorder('received_background') + createMessageEventRecorder('received_background'), ); addEventListener( 'foregroundMessageReceived', - createMessageEventRecorder('received_foreground') + createMessageEventRecorder('received_foreground'), ); launchNotificationOpenedListenerRemover = addEventListener( 'launchNotificationOpened', createMessageEventRecorder( 'opened_notification', // once we are done with it we can remove the listener - launchNotificationOpenedListenerRemover?.remove - ) + launchNotificationOpenedListenerRemover?.remove, + ), ); addEventListener( 'notificationOpened', createMessageEventRecorder( 'opened_notification', // if we are in this state, we no longer need the listener as the app was launched via some other means - launchNotificationOpenedListenerRemover?.remove - ) + launchNotificationOpenedListenerRemover?.remove, + ), ); }; @@ -203,7 +203,7 @@ const registerDevice = async (address: string): Promise => { channelType: getChannelType(), identityId, userAgentValue: getPushNotificationUserAgentString( - PushNotificationAction.InitializePushNotifications + PushNotificationAction.InitializePushNotifications, ), }); }; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/types/apis.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/types/apis.ts index 84aef6e4fb2..caeb6022b3a 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/types/apis.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/types/apis.ts @@ -32,23 +32,23 @@ export type IdentifyUser = (input: IdentifyUserInput) => Promise; export type InitializePushNotifications = () => void; export type RequestPermissions = ( - input?: RequestPermissionsInput + input?: RequestPermissionsInput, ) => Promise; export type SetBadgeCount = (input: SetBadgeCountInput) => void; export type OnNotificationOpened = ( - input: OnNotificationOpenedInput + input: OnNotificationOpenedInput, ) => OnNotificationOpenedOutput; export type OnNotificationReceivedInBackground = ( - input: OnNotificationReceivedInBackgroundInput + input: OnNotificationReceivedInBackgroundInput, ) => OnNotificationReceivedInBackgroundOutput; export type OnNotificationReceivedInForeground = ( - input: OnNotificationReceivedInForegroundInput + input: OnNotificationReceivedInForegroundInput, ) => OnNotificationReceivedInForegroundOutput; export type OnTokenReceived = ( - input: OnTokenReceivedInput + input: OnTokenReceivedInput, ) => OnTokenReceivedOutput; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.ts index e1d7b242644..38ae1173609 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.ts @@ -22,7 +22,7 @@ const logger = new ConsoleLogger('PushNotification.recordMessageEvent'); export const createMessageEventRecorder = ( event: PinpointMessageEvent, - callback?: Function + callback?: Function, ): OnPushNotificationMessageHandler => async message => { const { credentials } = await resolveCredentials(); diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.ts index 86c1e5c8d8a..d0f69de6582 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.ts @@ -15,7 +15,7 @@ const ANDROID_CAMPAIGN_TREATMENT_ID_KEY = 'pinpoint.campaign.treatment_id'; */ export const getAnalyticsEvent = ( { data }: PushNotificationMessage, - event: PinpointMessageEvent + event: PinpointMessageEvent, ): PinpointAnalyticsEvent | null => { if (!data) { return null; @@ -32,7 +32,7 @@ export const getAnalyticsEvent = ( }; const getAnalyticsEventAttributes = ( - data: PushNotificationMessage['data'] + data: PushNotificationMessage['data'], ): AnalyticsEventAttributes | undefined => { if (!data) { return; diff --git a/packages/notifications/src/pushNotifications/types/pushNotifications.ts b/packages/notifications/src/pushNotifications/types/pushNotifications.ts index bdae4a038f8..56b48ae7fc0 100644 --- a/packages/notifications/src/pushNotifications/types/pushNotifications.ts +++ b/packages/notifications/src/pushNotifications/types/pushNotifications.ts @@ -6,7 +6,7 @@ import { PushNotificationMessage } from './module'; export type OnTokenReceivedHandler = (token: string) => void; export type OnPushNotificationMessageHandler = ( - message: PushNotificationMessage + message: PushNotificationMessage, ) => void; export type PushNotificationEvent = diff --git a/packages/notifications/src/pushNotifications/utils/getPushNotificationUserAgentString.ts b/packages/notifications/src/pushNotifications/utils/getPushNotificationUserAgentString.ts index c374698a9ed..e89ecfc1c33 100644 --- a/packages/notifications/src/pushNotifications/utils/getPushNotificationUserAgentString.ts +++ b/packages/notifications/src/pushNotifications/utils/getPushNotificationUserAgentString.ts @@ -7,7 +7,7 @@ import { } from '@aws-amplify/core/internals/utils'; export const getPushNotificationUserAgentString = ( - action: PushNotificationAction + action: PushNotificationAction, ) => getAmplifyUserAgent({ category: Category.PushNotification, diff --git a/packages/predictions/__tests__/providers/AWSAIConvertPredictionsProvider.test.ts b/packages/predictions/__tests__/providers/AWSAIConvertPredictionsProvider.test.ts index b0e662a8f5e..5678c1b079c 100644 --- a/packages/predictions/__tests__/providers/AWSAIConvertPredictionsProvider.test.ts +++ b/packages/predictions/__tests__/providers/AWSAIConvertPredictionsProvider.test.ts @@ -173,7 +173,7 @@ describe('Predictions convert provider test', () => { }); const predictionsProvider = new AmazonAIConvertPredictionsProvider(); expect( - predictionsProvider.convert(validTranslateTextInput) + predictionsProvider.convert(validTranslateTextInput), ).resolves.toMatchObject({ language: 'es', text: 'translatedText' }); }); test('error case credentials do not exist', () => { @@ -186,11 +186,11 @@ describe('Predictions convert provider test', () => { const predictionsProvider = new AmazonAIConvertPredictionsProvider(); expect( - predictionsProvider.convert(validTranslateTextInput) + predictionsProvider.convert(validTranslateTextInput), ).rejects.toThrow( expect.objectContaining( - validationErrorMap[PredictionsValidationErrorCode.NoCredentials] - ) + validationErrorMap[PredictionsValidationErrorCode.NoCredentials], + ), ); }); test('error case credentials exist but service fails', () => { @@ -208,7 +208,7 @@ describe('Predictions convert provider test', () => { return Promise.reject('error'); }); expect( - predictionsProvider.convert(validTranslateTextInput) + predictionsProvider.convert(validTranslateTextInput), ).rejects.toMatch('error'); }); }); @@ -233,7 +233,7 @@ describe('Predictions convert provider test', () => { return 'dummyURL'; }); expect( - predictionsProvider.convert(validTextToSpeechInput) + predictionsProvider.convert(validTextToSpeechInput), ).resolves.toMatchObject({ speech: { url: 'dummyURL', @@ -251,11 +251,11 @@ describe('Predictions convert provider test', () => { }); const predictionsProvider = new AmazonAIConvertPredictionsProvider(); expect( - predictionsProvider.convert(validTextToSpeechInput) + predictionsProvider.convert(validTextToSpeechInput), ).rejects.toThrow( expect.objectContaining( - validationErrorMap[PredictionsValidationErrorCode.NoCredentials] - ) + validationErrorMap[PredictionsValidationErrorCode.NoCredentials], + ), ); }); test('error case credentials exist but service fails', () => { @@ -273,7 +273,7 @@ describe('Predictions convert provider test', () => { return Promise.reject('error'); }); expect( - predictionsProvider.convert(validTextToSpeechInput) + predictionsProvider.convert(validTextToSpeechInput), ).rejects.toMatch('error'); }); }); @@ -302,17 +302,17 @@ describe('Predictions convert provider test', () => { AmazonAIConvertPredictionsProvider.serializeDataFromTranscribe = jest.fn( () => { return 'Hello how are you'; - } + }, ); const predictionsProvider = new AmazonAIConvertPredictionsProvider(); return expect( - predictionsProvider.convert(validSpeechToTextInput) + predictionsProvider.convert(validSpeechToTextInput), ).rejects.toThrow( expect.objectContaining( - validationErrorMap[PredictionsValidationErrorCode.NoRegion] - ) + validationErrorMap[PredictionsValidationErrorCode.NoRegion], + ), ); }); test('Error languageCode not configured ', () => { @@ -333,17 +333,17 @@ describe('Predictions convert provider test', () => { AmazonAIConvertPredictionsProvider.serializeDataFromTranscribe = jest.fn( () => { return 'Hello how are you'; - } + }, ); const predictionsProvider = new AmazonAIConvertPredictionsProvider(); expect( - predictionsProvider.convert(validSpeechToTextInput) + predictionsProvider.convert(validSpeechToTextInput), ).rejects.toThrow( expect.objectContaining( - validationErrorMap[PredictionsValidationErrorCode.NoLanguage] - ) + validationErrorMap[PredictionsValidationErrorCode.NoLanguage], + ), ); }); test('Happy case ', () => { @@ -359,13 +359,13 @@ describe('Predictions convert provider test', () => { AmazonAIConvertPredictionsProvider.serializeDataFromTranscribe = jest.fn( () => { return 'Hello, how are you?'; - } + }, ); const predictionsProvider = new AmazonAIConvertPredictionsProvider(); expect( - predictionsProvider.convert(validSpeechToTextInput) + predictionsProvider.convert(validSpeechToTextInput), ).resolves.toMatchObject({ transcription: { fullText: 'Hello, how are you?', @@ -393,18 +393,18 @@ describe('Predictions convert provider test', () => { AmazonAIConvertPredictionsProvider.serializeDataFromTranscribe = jest.fn( () => { return 'Bonjour, comment vas tu?'; - } + }, ); const downsampleBufferSpyon = jest.spyOn( AmazonAIConvertPredictionsProvider.prototype as any, - 'downsampleBuffer' + 'downsampleBuffer', ); const predictionsProvider = new AmazonAIConvertPredictionsProvider(); await predictionsProvider.convert(validSpeechToTextInput); expect(downsampleBufferSpyon).toHaveBeenCalledWith( - expect.objectContaining({ outputSampleRate: 8000 }) + expect.objectContaining({ outputSampleRate: 8000 }), ); downsampleBufferSpyon.mockClear(); }); @@ -435,12 +435,12 @@ describe('Predictions convert provider test', () => { // pollyClient is a private property // Used this strategy to easily check that the customUserAgent is set correctly on the client expect( - (predictionsProvider as any).pollyClient.config.customUserAgent + (predictionsProvider as any).pollyClient.config.customUserAgent, ).toEqual( getAmplifyUserAgentObject({ category: Category.Predictions, action: PredictionsAction.Convert, - }) + }), ); }); test('convert translate text initializes a client with the correct custom user agent', async () => { @@ -459,12 +459,12 @@ describe('Predictions convert provider test', () => { // translateClient is a private property // Used this strategy to easily check that the customUserAgent is set correctly on the client expect( - (predictionsProvider as any).translateClient.config.customUserAgent + (predictionsProvider as any).translateClient.config.customUserAgent, ).toEqual( getAmplifyUserAgentObject({ category: Category.Predictions, action: PredictionsAction.Convert, - }) + }), ); }); }); diff --git a/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts b/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts index 5aa2140502f..4280ea132d5 100644 --- a/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts +++ b/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts @@ -287,13 +287,13 @@ mockGetUrl.mockImplementation(({ key, options }) => { let url: URL; if (level === 'guest') { url = new URL( - `https://bucket-name.s3.us-west-2.amazonaws.com/public/${key}?X-Amz-Algorithm=AWS4-HMAC-SHA256` + `https://bucket-name.s3.us-west-2.amazonaws.com/public/${key}?X-Amz-Algorithm=AWS4-HMAC-SHA256`, ); } else { const identityId = options?.targetIdentityId || 'identityId'; // tslint:disable-next-line: max-line-length url = new URL( - `https://bucket-name.s3.us-west-2.amazonaws.com/${level}/${identityId}/key.png?X-Amz-Algorithm=AWS4-HMAC-SHA256` + `https://bucket-name.s3.us-west-2.amazonaws.com/${level}/${identityId}/key.png?X-Amz-Algorithm=AWS4-HMAC-SHA256`, ); } return Promise.resolve({ url }); @@ -320,7 +320,7 @@ describe('Predictions identify provider test', () => { }, }; expect( - predictionsProvider.identify(detectTextInput) + predictionsProvider.identify(detectTextInput), ).resolves.toMatchObject(expected); }); @@ -329,8 +329,8 @@ describe('Predictions identify provider test', () => { expect(predictionsProvider.identify(detectTextInput)).rejects.toThrow( expect.objectContaining( - validationErrorMap[PredictionsValidationErrorCode.NoCredentials] - ) + validationErrorMap[PredictionsValidationErrorCode.NoCredentials], + ), ); }); @@ -387,7 +387,7 @@ describe('Predictions identify provider test', () => { }, }; expect( - predictionsProvider.identify(detectTextInput) + predictionsProvider.identify(detectTextInput), ).resolves.toMatchObject(expected); }); }); @@ -408,7 +408,7 @@ describe('Predictions identify provider test', () => { ], }; expect( - predictionsProvider.identify(detectLabelInput) + predictionsProvider.identify(detectLabelInput), ).resolves.toMatchObject(expected); }); test('error case credentials do not exist', () => { @@ -416,8 +416,8 @@ describe('Predictions identify provider test', () => { expect(predictionsProvider.identify(detectLabelInput)).rejects.toThrow( expect.objectContaining( - validationErrorMap[PredictionsValidationErrorCode.NoCredentials] - ) + validationErrorMap[PredictionsValidationErrorCode.NoCredentials], + ), ); }); test('error case credentials exist but service fails', () => { @@ -427,7 +427,7 @@ describe('Predictions identify provider test', () => { return Promise.reject('error'); }); expect(predictionsProvider.identify(detectLabelInput)).rejects.toMatch( - 'error' + 'error', ); }); }); @@ -440,7 +440,7 @@ describe('Predictions identify provider test', () => { test('happy case credentials exist, unsafe image', () => { const expected: IdentifyLabelsOutput = { unsafe: 'YES' }; expect( - predictionsProvider.identify(detectModerationInput) + predictionsProvider.identify(detectModerationInput), ).resolves.toMatchObject(expected); }); @@ -451,7 +451,7 @@ describe('Predictions identify provider test', () => { return Promise.reject('error'); }); expect( - predictionsProvider.identify(detectModerationInput) + predictionsProvider.identify(detectModerationInput), ).rejects.toMatch('error'); }); }); @@ -472,7 +472,7 @@ describe('Predictions identify provider test', () => { unsafe: 'YES', }; expect( - predictionsProvider.identify(detectModerationInput) + predictionsProvider.identify(detectModerationInput), ).resolves.toMatchObject(expected); }); @@ -483,7 +483,7 @@ describe('Predictions identify provider test', () => { return Promise.reject('error'); }); expect( - predictionsProvider.identify(detectModerationInput) + predictionsProvider.identify(detectModerationInput), ).rejects.toMatch('error'); }); }); @@ -514,7 +514,7 @@ describe('Predictions identify provider test', () => { ], }; expect( - predictionsProvider.identify(detectFacesInput) + predictionsProvider.identify(detectFacesInput), ).resolves.toMatchObject(expected); }); @@ -523,8 +523,8 @@ describe('Predictions identify provider test', () => { expect(predictionsProvider.identify(detectFacesInput)).rejects.toThrow( expect.objectContaining( - validationErrorMap[PredictionsValidationErrorCode.NoCredentials] - ) + validationErrorMap[PredictionsValidationErrorCode.NoCredentials], + ), ); }); @@ -535,7 +535,7 @@ describe('Predictions identify provider test', () => { return Promise.reject('error'); }); expect(predictionsProvider.identify(detectFacesInput)).rejects.toMatch( - 'error' + 'error', ); }); }); @@ -553,7 +553,7 @@ describe('Predictions identify provider test', () => { entities: [{ boundingBox: { left: 0, top: 0, height: 0, width: 0 } }], }; expect( - predictionsProvider.identify(recognizeCelebritiesInput) + predictionsProvider.identify(recognizeCelebritiesInput), ).resolves.toMatchObject(expected); }); @@ -564,7 +564,7 @@ describe('Predictions identify provider test', () => { return Promise.reject('error'); }); expect( - predictionsProvider.identify(recognizeCelebritiesInput) + predictionsProvider.identify(recognizeCelebritiesInput), ).rejects.toMatch('error'); }); }); @@ -584,7 +584,7 @@ describe('Predictions identify provider test', () => { entities: [{ boundingBox: { left: 0, top: 0, height: 0, width: 0 } }], }; expect( - predictionsProvider.identify(searchByFacesInput) + predictionsProvider.identify(searchByFacesInput), ).resolves.toMatchObject(expected); }); @@ -595,7 +595,7 @@ describe('Predictions identify provider test', () => { return Promise.reject('error'); }); expect( - predictionsProvider.identify(searchByFacesInput) + predictionsProvider.identify(searchByFacesInput), ).rejects.toMatch('error'); }); }); @@ -622,7 +622,7 @@ describe('Predictions identify provider test', () => { .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(command => { expect( - (command as DetectLabelsCommand).input.Image?.S3Object?.Name + (command as DetectLabelsCommand).input.Image?.S3Object?.Name, ).toMatch('public/key'); return Promise.resolve(detectlabelsResponse); }); @@ -637,7 +637,7 @@ describe('Predictions identify provider test', () => { .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(command => { expect( - (command as DetectLabelsCommand).input.Image?.S3Object?.Name + (command as DetectLabelsCommand).input.Image?.S3Object?.Name, ).toMatch('private/identityId/key'); return {}; }); @@ -659,7 +659,7 @@ describe('Predictions identify provider test', () => { .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(command => { expect( - (command as DetectLabelsCommand).input.Image?.S3Object?.Name + (command as DetectLabelsCommand).input.Image?.S3Object?.Name, ).toMatch('protected/identityId/key'); return Promise.resolve(detectlabelsResponse); }); @@ -674,7 +674,7 @@ describe('Predictions identify provider test', () => { .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(command => { expect((command as DetectLabelsCommand).input.Image?.Bytes).toMatch( - 'bytes' + 'bytes', ); return Promise.resolve(detectlabelsResponse); }); @@ -690,7 +690,7 @@ describe('Predictions identify provider test', () => { .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(command => { expect( - (command as DetectLabelsCommand).input.Image?.Bytes + (command as DetectLabelsCommand).input.Image?.Bytes, ).toStrictEqual(fileInput); return {}; }); @@ -707,7 +707,7 @@ describe('Predictions identify provider test', () => { .spyOn(RekognitionClient.prototype, 'send') .mockImplementationOnce(command => { expect( - (command as DetectLabelsCommand).input.Image?.Bytes + (command as DetectLabelsCommand).input.Image?.Bytes, ).toMatchObject(fileInput); return {}; }); @@ -719,7 +719,7 @@ describe('Predictions identify provider test', () => { labels: { source: null, type: 'LABELS' }, }; expect(predictionsProvider.identify(detectLabelInput)).rejects.toMatch( - 'not configured correctly' + 'not configured correctly', ); }); }); @@ -736,12 +736,12 @@ describe('Predictions identify provider test', () => { await predictionsProvider.identify(detectLabelInput); expect( - predictionsProvider.rekognitionClient.config.customUserAgent + predictionsProvider.rekognitionClient.config.customUserAgent, ).toEqual( getAmplifyUserAgentObject({ category: Category.Predictions, action: PredictionsAction.Identify, - }) + }), ); }); test('identify for entities initializes a client with the correct custom user agent', async () => { @@ -759,12 +759,12 @@ describe('Predictions identify provider test', () => { await predictionsProvider.identify(detectFacesInput); expect( - predictionsProvider.rekognitionClient.config.customUserAgent + predictionsProvider.rekognitionClient.config.customUserAgent, ).toEqual( getAmplifyUserAgentObject({ category: Category.Predictions, action: PredictionsAction.Identify, - }) + }), ); }); test('identify for text initializes a client with the correct custom user agent', async () => { @@ -777,19 +777,19 @@ describe('Predictions identify provider test', () => { await predictionsProvider.identify(detectTextInput); expect( - predictionsProvider.rekognitionClient.config.customUserAgent + predictionsProvider.rekognitionClient.config.customUserAgent, ).toEqual( getAmplifyUserAgentObject({ category: Category.Predictions, action: PredictionsAction.Identify, - }) + }), ); expect(predictionsProvider.textractClient.config.customUserAgent).toEqual( getAmplifyUserAgentObject({ category: Category.Predictions, action: PredictionsAction.Identify, - }) + }), ); }); }); diff --git a/packages/predictions/__tests__/providers/AWSAIInterpretPredictionsProvider.test.ts b/packages/predictions/__tests__/providers/AWSAIInterpretPredictionsProvider.test.ts index 77e14e2907e..60bc46c4c2e 100644 --- a/packages/predictions/__tests__/providers/AWSAIInterpretPredictionsProvider.test.ts +++ b/packages/predictions/__tests__/providers/AWSAIInterpretPredictionsProvider.test.ts @@ -245,7 +245,7 @@ describe('Predictions interpret provider test', () => { }, type: 'entities', }, - }) + }), ).resolves.toMatchObject({ textInterpretation: { textEntities: [{ text: 'William', type: 'PERSON' }], @@ -264,7 +264,7 @@ describe('Predictions interpret provider test', () => { const predictionsProvider = new AmazonAIInterpretPredictionsProvider(); const dominantLanguageSpy = jest.spyOn( ComprehendClient.prototype, - 'send' + 'send', ); expect.assertions(2); @@ -277,7 +277,7 @@ describe('Predictions interpret provider test', () => { }, type: 'language', }, - }) + }), ).resolves.toMatchObject({ textInterpretation: { language: 'en-US', @@ -306,7 +306,7 @@ describe('Predictions interpret provider test', () => { }, type: 'sentiment', }, - }) + }), ).resolves.toMatchObject({ textInterpretation: { sentiment: { @@ -342,7 +342,7 @@ describe('Predictions interpret provider test', () => { }, type: 'syntax', }, - }) + }), ).resolves.toMatchObject({ textInterpretation: { syntax: [ @@ -388,7 +388,7 @@ describe('Predictions interpret provider test', () => { }, type: 'keyPhrases', }, - }) + }), ).resolves.toMatchObject({ textInterpretation: { keyPhrases: [ @@ -417,7 +417,7 @@ describe('Predictions interpret provider test', () => { }, type: 'all', }, - }) + }), ).resolves.toMatchObject({ textInterpretation: { keyPhrases: [ @@ -459,7 +459,7 @@ describe('Predictions interpret provider test', () => { const sentimentSpy = jest.spyOn(ComprehendClient.prototype, 'send'); const dominantLanguageSpy = jest.spyOn( ComprehendClient.prototype, - 'send' + 'send', ); const detectEntitiesSpy = jest.spyOn(ComprehendClient.prototype, 'send'); @@ -496,12 +496,12 @@ describe('Predictions interpret provider test', () => { // comprehendClient is a private property // Used this strategy to easily check that the customUserAgent is set correctly on the client expect( - (predictionsProvider as any).comprehendClient.config.customUserAgent + (predictionsProvider as any).comprehendClient.config.customUserAgent, ).toEqual( getAmplifyUserAgentObject({ category: Category.Predictions, action: PredictionsAction.Interpret, - }) + }), ); }); }); diff --git a/packages/predictions/src/Predictions.ts b/packages/predictions/src/Predictions.ts index 97d699abb14..f491798134b 100644 --- a/packages/predictions/src/Predictions.ts +++ b/packages/predictions/src/Predictions.ts @@ -42,7 +42,7 @@ export class PredictionsClass { public convert(input: TextToSpeechInput): Promise; public convert(input: SpeechToTextInput): Promise; public convert( - input: TranslateTextInput | TextToSpeechInput | SpeechToTextInput + input: TranslateTextInput | TextToSpeechInput | SpeechToTextInput, ): Promise { return this.convertProvider.convert(input); } @@ -50,10 +50,10 @@ export class PredictionsClass { public identify(input: IdentifyTextInput): Promise; public identify(input: IdentifyLabelsInput): Promise; public identify( - input: IdentifyEntitiesInput + input: IdentifyEntitiesInput, ): Promise; public identify( - input: IdentifyTextInput | IdentifyLabelsInput | IdentifyEntitiesInput + input: IdentifyTextInput | IdentifyLabelsInput | IdentifyEntitiesInput, ): Promise< IdentifyTextOutput | IdentifyLabelsOutput | IdentifyEntitiesOutput > { diff --git a/packages/predictions/src/errors/utils/assertValidationError.ts b/packages/predictions/src/errors/utils/assertValidationError.ts index 16e70aa3740..f712c8880e1 100644 --- a/packages/predictions/src/errors/utils/assertValidationError.ts +++ b/packages/predictions/src/errors/utils/assertValidationError.ts @@ -9,7 +9,7 @@ import { export function assertValidationError( assertion: boolean, - name: PredictionsValidationErrorCode + name: PredictionsValidationErrorCode, ): asserts assertion { if (!assertion) { const { message, recoverySuggestion } = validationErrorMap[name]; diff --git a/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts b/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts index 77beadfd21d..a38dba2f3a4 100644 --- a/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts +++ b/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts @@ -50,11 +50,11 @@ export class AmazonAIConvertPredictionsProvider { } convert( - input: TranslateTextInput | TextToSpeechInput | SpeechToTextInput + input: TranslateTextInput | TextToSpeechInput | SpeechToTextInput, ): Promise { assertValidationError( isValidConvertInput(input), - PredictionsValidationErrorCode.InvalidInput + PredictionsValidationErrorCode.InvalidInput, ); if (isTranslateTextInput(input)) { @@ -70,7 +70,7 @@ export class AmazonAIConvertPredictionsProvider { } protected async translateText( - input: TranslateTextInput + input: TranslateTextInput, ): Promise { logger.debug('Starting translation'); @@ -78,14 +78,14 @@ export class AmazonAIConvertPredictionsProvider { Amplify.getConfig().Predictions?.convert ?? {}; assertValidationError( !!translateText.region, - PredictionsValidationErrorCode.NoRegion + PredictionsValidationErrorCode.NoRegion, ); const { defaults = {}, region } = translateText; const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, - PredictionsValidationErrorCode.NoCredentials + PredictionsValidationErrorCode.NoCredentials, ); const { sourceLanguage, targetLanguage } = defaults; @@ -95,11 +95,11 @@ export class AmazonAIConvertPredictionsProvider { input.translateText?.targetLanguage ?? targetLanguage; assertValidationError( !!sourceLanguageCode, - PredictionsValidationErrorCode.NoSourceLanguage + PredictionsValidationErrorCode.NoSourceLanguage, ); assertValidationError( !!targetLanguageCode, - PredictionsValidationErrorCode.NoTargetLanguage + PredictionsValidationErrorCode.NoTargetLanguage, ); this.translateClient = new TranslateClient({ @@ -123,22 +123,22 @@ export class AmazonAIConvertPredictionsProvider { } protected async convertTextToSpeech( - input: TextToSpeechInput + input: TextToSpeechInput, ): Promise { const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, - PredictionsValidationErrorCode.NoCredentials + PredictionsValidationErrorCode.NoCredentials, ); assertValidationError( !!input.textToSpeech?.source, - PredictionsValidationErrorCode.NoSource + PredictionsValidationErrorCode.NoSource, ); const { speechGenerator } = Amplify.getConfig().Predictions?.convert ?? {}; assertValidationError( !!speechGenerator?.region, - PredictionsValidationErrorCode.NoRegion + PredictionsValidationErrorCode.NoRegion, ); const { defaults = {}, region } = speechGenerator; @@ -178,19 +178,19 @@ export class AmazonAIConvertPredictionsProvider { } protected async convertSpeechToText( - input: SpeechToTextInput + input: SpeechToTextInput, ): Promise { logger.debug('starting transcription..'); const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, - PredictionsValidationErrorCode.NoCredentials + PredictionsValidationErrorCode.NoCredentials, ); const { transcription } = Amplify.getConfig().Predictions?.convert ?? {}; assertValidationError( !!transcription?.region, - PredictionsValidationErrorCode.NoRegion + PredictionsValidationErrorCode.NoRegion, ); const { defaults, region } = transcription; @@ -198,13 +198,13 @@ export class AmazonAIConvertPredictionsProvider { assertValidationError( !!language, - PredictionsValidationErrorCode.NoLanguage + PredictionsValidationErrorCode.NoLanguage, ); const source = input.transcription?.source; assertValidationError( isConvertBytesSource(source), - PredictionsValidationErrorCode.InvalidSource + PredictionsValidationErrorCode.InvalidSource, ); const connection = await this.openConnectionWithTranscribe({ @@ -232,7 +232,7 @@ export class AmazonAIConvertPredictionsProvider { if (transcribeMessage.headers[':message-type'].value === 'exception') { logger.debug( 'exception', - JSON.stringify(transcribeMessageJson.Message, null, 2) + JSON.stringify(transcribeMessageJson.Message, null, 2), ); throw new Error(transcribeMessageJson.Message); } else if (transcribeMessage.headers[':message-type'].value === 'event') { @@ -275,7 +275,7 @@ export class AmazonAIConvertPredictionsProvider { try { const decodedMessage = AmazonAIConvertPredictionsProvider.serializeDataFromTranscribe( - message + message, ); if (decodedMessage) { fullText += decodedMessage + ' '; @@ -318,7 +318,7 @@ export class AmazonAIConvertPredictionsProvider { private sendEncodedDataToTranscribe( connection: WebSocket, data: ConvertBytes | any[], - languageCode: string + languageCode: string, ) { const downsampledBuffer = this.downsampleBuffer({ buffer: data, @@ -329,7 +329,7 @@ export class AmazonAIConvertPredictionsProvider { const pcmEncodedBuffer = this.pcmEncode(downsampledBuffer); const audioEventMessage = this.getAudioEventMessage( - Buffer.from(pcmEncodedBuffer) + Buffer.from(pcmEncodedBuffer), ); const binary = eventBuilder.encode(audioEventMessage); connection.send(binary); @@ -467,7 +467,7 @@ export class AmazonAIConvertPredictionsProvider { url, credentials, { region, service: 'transcribe' }, - 300 + 300, ); return signedUrl; diff --git a/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts b/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts index 5c749eb465d..ce2567131eb 100644 --- a/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts +++ b/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts @@ -73,13 +73,13 @@ export class AmazonAIIdentifyPredictionsProvider { } identify( - input: IdentifyTextInput | IdentifyLabelsInput | IdentifyEntitiesInput + input: IdentifyTextInput | IdentifyLabelsInput | IdentifyEntitiesInput, ): Promise< IdentifyTextOutput | IdentifyLabelsOutput | IdentifyEntitiesOutput > { assertValidationError( isValidIdentifyInput(input), - PredictionsValidationErrorCode.InvalidInput + PredictionsValidationErrorCode.InvalidInput, ); if (isIdentifyTextInput(input)) { @@ -156,12 +156,12 @@ export class AmazonAIIdentifyPredictionsProvider { * @return {Promise} - Promise resolving to object containing identified texts. */ protected async identifyText( - input: IdentifyTextInput + input: IdentifyTextInput, ): Promise { const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, - PredictionsValidationErrorCode.NoCredentials + PredictionsValidationErrorCode.NoCredentials, ); const { identifyText = {} } = @@ -207,7 +207,7 @@ export class AmazonAIIdentifyPredictionsProvider { await this.rekognitionClient.send(detectTextCommand); const rekognitionResponse = categorizeRekognitionBlocks( - rekognitionData.TextDetections as TextDetectionList + rekognitionData.TextDetections as TextDetectionList, ); if (rekognitionResponse.text.words.length < 50) { // did not hit the word limit, return the data @@ -215,11 +215,11 @@ export class AmazonAIIdentifyPredictionsProvider { } const detectDocumentTextCommand = new DetectDocumentTextCommand( - textractParam + textractParam, ); const { Blocks } = await this.textractClient.send( - detectDocumentTextCommand + detectDocumentTextCommand, ); if ( @@ -247,12 +247,12 @@ export class AmazonAIIdentifyPredictionsProvider { * @return {Promise} - Promise resolving to an array of identified entities. */ protected async identifyLabels( - input: IdentifyLabelsInput + input: IdentifyLabelsInput, ): Promise { const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, - PredictionsValidationErrorCode.NoCredentials + PredictionsValidationErrorCode.NoCredentials, ); const { identifyLabels = {} } = @@ -295,7 +295,7 @@ export class AmazonAIIdentifyPredictionsProvider { * @return {Promise} - Promise resolving to organized detectLabels response. */ private async detectLabels( - param: DetectLabelsCommandInput + param: DetectLabelsCommandInput, ): Promise { const detectLabelsCommand = new DetectLabelsCommand(param); const data = await this.rekognitionClient!.send(detectLabelsCommand); @@ -304,7 +304,7 @@ export class AmazonAIIdentifyPredictionsProvider { const boxes = label.Instances?.map( instance => - makeCamelCase(instance.BoundingBox) as BoundingBox | undefined + makeCamelCase(instance.BoundingBox) as BoundingBox | undefined, ) || []; return { name: label.Name, @@ -324,13 +324,13 @@ export class AmazonAIIdentifyPredictionsProvider { * @return {Promise} - Promise resolving to organized detectModerationLabels response. */ private async detectModerationLabels( - param: DetectModerationLabelsCommandInput + param: DetectModerationLabelsCommandInput, ): Promise { const detectModerationLabelsCommand = new DetectModerationLabelsCommand( - param + param, ); const data = await this.rekognitionClient!.send( - detectModerationLabelsCommand + detectModerationLabelsCommand, ); if (data.ModerationLabels?.length !== 0) { return { unsafe: 'YES' }; @@ -346,12 +346,12 @@ export class AmazonAIIdentifyPredictionsProvider { * @return {Promise} Promise resolving to identify results. */ protected async identifyEntities( - input: IdentifyEntitiesInput + input: IdentifyEntitiesInput, ): Promise { const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, - PredictionsValidationErrorCode.NoCredentials + PredictionsValidationErrorCode.NoCredentials, ); const { identifyEntities = {} } = @@ -381,13 +381,13 @@ export class AmazonAIIdentifyPredictionsProvider { ) { assertValidationError( celebrityDetectionEnabled, - PredictionsValidationErrorCode.CelebrityDetectionNotEnabled + PredictionsValidationErrorCode.CelebrityDetectionNotEnabled, ); const recognizeCelebritiesCommand = new RecognizeCelebritiesCommand( - param + param, ); const data = await this.rekognitionClient.send( - recognizeCelebritiesCommand + recognizeCelebritiesCommand, ); const faces = data.CelebrityFaces?.map( @@ -399,7 +399,7 @@ export class AmazonAIIdentifyPredictionsProvider { ...makeCamelCase(celebrity, ['Id', 'Name', 'Urls']), pose: makeCamelCase(celebrity.Face?.Pose), }, - }) as IdentifyEntity + }) as IdentifyEntity, ) ?? []; return { entities: faces }; } else if ( @@ -417,7 +417,7 @@ export class AmazonAIIdentifyPredictionsProvider { MaxFaces: maxFaces, }; const searchFacesByImageCommand = new SearchFacesByImageCommand( - updatedParam + updatedParam, ); const data = await this.rekognitionClient.send(searchFacesByImageCommand); const faces = @@ -452,11 +452,11 @@ export class AmazonAIIdentifyPredictionsProvider { ]; const faceAttributes = makeCamelCase( detail, - attributeKeys + attributeKeys, ) as FaceAttributes; faceAttributes.emotions = detail.Emotions?.map( - emotion => emotion.Type + emotion => emotion.Type, ); return { boundingBox: makeCamelCase(detail.BoundingBox), diff --git a/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts b/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts index 39093783449..48b5c1cdab1 100644 --- a/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts +++ b/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts @@ -42,7 +42,7 @@ export class AmazonAIInterpretPredictionsProvider { interpret(input: InterpretTextInput): Promise { assertValidationError( isValidInterpretInput(input), - PredictionsValidationErrorCode.InvalidInput + PredictionsValidationErrorCode.InvalidInput, ); return this.interpretText(input); @@ -52,7 +52,7 @@ export class AmazonAIInterpretPredictionsProvider { const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, - PredictionsValidationErrorCode.NoCredentials + PredictionsValidationErrorCode.NoCredentials, ); const { interpretText = {} } = @@ -91,7 +91,7 @@ export class AmazonAIInterpretPredictionsProvider { if (doAll || type === 'entities') { assertValidationError( !!languageCode, - PredictionsValidationErrorCode.NoLanguage + PredictionsValidationErrorCode.NoLanguage, ); const entitiesDetectionParams = { Text: text, @@ -104,7 +104,7 @@ export class AmazonAIInterpretPredictionsProvider { if (doAll || type === 'sentiment') { assertValidationError( !!languageCode, - PredictionsValidationErrorCode.NoLanguage + PredictionsValidationErrorCode.NoLanguage, ); const sentimentParams = { Text: text, @@ -117,7 +117,7 @@ export class AmazonAIInterpretPredictionsProvider { if (doAll || type === 'syntax') { assertValidationError( !!languageCode, - PredictionsValidationErrorCode.NoLanguage + PredictionsValidationErrorCode.NoLanguage, ); const syntaxParams = { Text: text, @@ -130,7 +130,7 @@ export class AmazonAIInterpretPredictionsProvider { if (doAll || type === 'keyPhrases') { assertValidationError( !!languageCode, - PredictionsValidationErrorCode.NoLanguage + PredictionsValidationErrorCode.NoLanguage, ); const keyPhrasesParams = { @@ -168,7 +168,7 @@ export class AmazonAIInterpretPredictionsProvider { if (err.code === 'AccessDeniedException') { throw new Error( 'Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' + - 'amplify predictions add' + 'amplify predictions add', ); } else { throw err; @@ -186,7 +186,7 @@ export class AmazonAIInterpretPredictionsProvider { if (err.code === 'AccessDeniedException') { throw new Error( 'Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' + - 'amplify predictions add' + 'amplify predictions add', ); } else { throw err; @@ -195,14 +195,14 @@ export class AmazonAIInterpretPredictionsProvider { } private serializeSyntaxFromComprehend( - tokens: SyntaxToken[] + tokens: SyntaxToken[], ): Array { let response: TextSyntax[] = []; if (tokens && Array.isArray(tokens)) { response = tokens.map( ({ Text: text = '', PartOfSpeech: { Tag: syntax = '' } = {} }) => { return { text, syntax }; - } + }, ); } return response; @@ -226,7 +226,7 @@ export class AmazonAIInterpretPredictionsProvider { if (err.code === 'AccessDeniedException') { throw new Error( 'Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' + - 'amplify predictions add' + 'amplify predictions add', ); } else { throw err; @@ -235,7 +235,7 @@ export class AmazonAIInterpretPredictionsProvider { } private async detectEntities( - params: DetectParams + params: DetectParams, ): Promise> { try { const detectEntitiesCommand = new DetectEntitiesCommand(params); @@ -246,7 +246,7 @@ export class AmazonAIInterpretPredictionsProvider { if (err.code === 'AccessDeniedException') { throw new Error( 'Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' + - 'amplify predictions add' + 'amplify predictions add', ); } else { throw err; @@ -267,15 +267,15 @@ export class AmazonAIInterpretPredictionsProvider { private async detectLanguage(params: { Text: string }): Promise { try { const detectDominantLanguageCommand = new DetectDominantLanguageCommand( - params + params, ); const data = await this.comprehendClient!.send( - detectDominantLanguageCommand + detectDominantLanguageCommand, ); const { Languages: [{ LanguageCode }] = [{}] } = ({} = data || {}); assertValidationError( !!LanguageCode, - PredictionsValidationErrorCode.NoLanguage + PredictionsValidationErrorCode.NoLanguage, ); return LanguageCode; @@ -283,7 +283,7 @@ export class AmazonAIInterpretPredictionsProvider { if (err.code === 'AccessDeniedException') { throw new Error( 'Not authorized, did you enable Interpret Text on predictions category Amplify CLI? try: ' + - 'amplify predictions add' + 'amplify predictions add', ); } else { throw err; diff --git a/packages/predictions/src/providers/IdentifyTextUtils.ts b/packages/predictions/src/providers/IdentifyTextUtils.ts index 047d987e802..7a71a581c39 100644 --- a/packages/predictions/src/providers/IdentifyTextUtils.ts +++ b/packages/predictions/src/providers/IdentifyTextUtils.ts @@ -29,7 +29,7 @@ function getPolygon(geometry?: Geometry): Polygon | undefined { * @return {IdentifyTextOutput} - Object that categorizes each block and its information. */ export function categorizeRekognitionBlocks( - blocks: TextDetectionList + blocks: TextDetectionList, ): IdentifyTextOutput { // Skeleton IdentifyText API response. We will populate it as we iterate through blocks. const response: IdentifyTextOutput = { @@ -67,7 +67,7 @@ export function categorizeRekognitionBlocks( // remove trailing space of fullText response.text.fullText = response.text.fullText.substr( 0, - response.text.fullText.length - 1 + response.text.fullText.length - 1, ); return response; } @@ -79,7 +79,7 @@ export function categorizeRekognitionBlocks( * @return {IdentifyTextOutput} - Object that categorizes each block and its information. */ export function categorizeTextractBlocks( - blocks: BlockList + blocks: BlockList, ): IdentifyTextOutput { // Skeleton IdentifyText API response. We will populate it as we iterate through blocks. const response: IdentifyTextOutput = { @@ -161,7 +161,7 @@ export function categorizeTextractBlocks( // remove trailing space in fullText response.text.fullText = response.text.fullText.substr( 0, - response.text.fullText.length - 1 + response.text.fullText.length - 1, ); // Post-process complex structures if they exist. @@ -195,7 +195,7 @@ export function categorizeTextractBlocks( */ function constructTable( table: Block, - blockMap: { [key: string]: Block } + blockMap: { [key: string]: Block }, ): Table { let tableMatrix: TableCell[][]; tableMatrix = []; @@ -241,7 +241,7 @@ function constructTable( */ function constructKeyValue( keyBlock: Block, - blockMap: { [key: string]: Block } + blockMap: { [key: string]: Block }, ): KeyValue { let keyText: string = ''; let valueText: string = ''; @@ -276,7 +276,7 @@ function constructKeyValue( */ function extractContentsFromBlock( block: Block, - blockMap: { [id: string]: Block } + blockMap: { [id: string]: Block }, ): Content { let words: string = ''; let isSelected: boolean = false; diff --git a/packages/predictions/src/types/Predictions.ts b/packages/predictions/src/types/Predictions.ts index cc502c4e34b..289c791e244 100644 --- a/packages/predictions/src/types/Predictions.ts +++ b/packages/predictions/src/types/Predictions.ts @@ -338,7 +338,7 @@ export function isValidInterpretInput(obj: any) { } export function isIdentifyFromCollection( - obj: any + obj: any, ): obj is IdentifyFromCollection { const key: keyof IdentifyFromCollection = 'collection'; const keyId: keyof IdentifyFromCollection = 'collectionId'; @@ -376,14 +376,14 @@ export function isFileSource(obj: any): obj is FileSource { } export function isConvertBytesSource( - obj: any + obj: any, ): obj is BytesSource { const key: keyof BytesSource = 'bytes'; return obj && obj.hasOwnProperty(key); } export function isIdentifyBytesSource( - obj: any + obj: any, ): obj is BytesSource { const key: keyof BytesSource = 'bytes'; return obj && obj.hasOwnProperty(key); @@ -400,7 +400,7 @@ export function isIdentifyLabelsInput(obj: any): obj is IdentifyLabelsInput { } export function isIdentifyEntitiesInput( - obj: any + obj: any, ): obj is IdentifyEntitiesInput { const key: keyof IdentifyEntitiesInput = 'entities'; return obj && obj.hasOwnProperty(key); @@ -412,7 +412,7 @@ export function isInterpretTextInput(obj: any): obj is InterpretTextInput { } export function isInterpretTextOthers( - text: InterpretTextInput['text'] + text: InterpretTextInput['text'], ): text is InterpretTextOthers { return (text as InterpretTextOthers).source.language !== undefined; } diff --git a/packages/pubsub/__tests__/PubSub.test.ts b/packages/pubsub/__tests__/PubSub.test.ts index 44b600c1a33..b4b1885b6e8 100644 --- a/packages/pubsub/__tests__/PubSub.test.ts +++ b/packages/pubsub/__tests__/PubSub.test.ts @@ -71,7 +71,7 @@ const testPubSubAsync = ( topic, message, options?, - hubConnectionListener? + hubConnectionListener?, ) => new Promise(async (resolve, reject) => { if (hubConnectionListener === undefined) { @@ -224,7 +224,7 @@ describe('PubSub', () => { expect( testPubSubAsync(pubsub, 'topicA', 'my message AWSIoTProvider', { provider: 'AWSIoTProvider', - }) + }), ).rejects.toMatchObject({ error: new Error('Failed to connect to the network'), }); @@ -300,7 +300,7 @@ describe('PubSub', () => { // @ts-ignore new Observable(observer => { reachabilityObserver = observer; - }) + }), ) // Twice because we subscribe to get the initial state then again to monitor reachability .mockImplementationOnce( @@ -308,7 +308,7 @@ describe('PubSub', () => { // @ts-ignore new Observable(observer => { reachabilityObserver = observer; - }) + }), ); reachabilityObserver?.next?.({ online: true }); }); @@ -456,7 +456,7 @@ describe('PubSub', () => { { provider: 'AWSIoTProvider', }, - hubConnectionListener + hubConnectionListener, ); await testPubSubAsync( @@ -466,7 +466,7 @@ describe('PubSub', () => { { provider: 'MqttOverWSProvider', }, - hubConnectionListener + hubConnectionListener, ); }); @@ -489,7 +489,7 @@ describe('PubSub', () => { iotClient.publish({ topics: 'topicA', message: { msg: 'my message AWSIoTProvider' }, - }) + }), ).rejects.toMatch('Failed to publish'); }); @@ -566,7 +566,7 @@ describe('PubSub', () => { subscription2.unsubscribe(); expect(spyDisconnect).not.toHaveBeenCalled(); spyDisconnect.mockClear(); - } + }, ); }); }); diff --git a/packages/pubsub/__tests__/helpers.ts b/packages/pubsub/__tests__/helpers.ts index e9c4e4dc3e7..5fb25cea201 100644 --- a/packages/pubsub/__tests__/helpers.ts +++ b/packages/pubsub/__tests__/helpers.ts @@ -196,7 +196,7 @@ export class FakeWebSocketInterface { type: constants.MESSAGE_TYPES.GQL_CONNECTION_ACK, payload: payload, }), - }) + }), ); } @@ -210,7 +210,7 @@ export class FakeWebSocketInterface { type: constants.MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE, payload: payload, }), - }) + }), ); } @@ -222,7 +222,7 @@ export class FakeWebSocketInterface { payload: payload, id: this.webSocket.subscriptionId, }), - }) + }), ); } @@ -236,7 +236,7 @@ export class FakeWebSocketInterface { ...data, id: this.webSocket.subscriptionId, }), - }) + }), ); } @@ -283,7 +283,7 @@ export class FakeWebSocketInterface { */ async waitUntilConnectionStateIn(connectionStates: CS[]) { return this.hubConnectionListener.waitUntilConnectionStateIn( - connectionStates + connectionStates, ); } } @@ -317,12 +317,12 @@ class FakeWebSocket implements WebSocket { addEventListener( type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, - options?: boolean | AddEventListenerOptions + options?: boolean | AddEventListenerOptions, ): void; addEventListener( type: string, listener: EventListenerOrEventListenerObject, - options?: boolean | AddEventListenerOptions + options?: boolean | AddEventListenerOptions, ): void; addEventListener(type: unknown, listener: unknown, options?: unknown): void { throw new Error('Method not implemented addEventListener.'); @@ -330,17 +330,17 @@ class FakeWebSocket implements WebSocket { removeEventListener( type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, - options?: boolean | EventListenerOptions + options?: boolean | EventListenerOptions, ): void; removeEventListener( type: string, listener: EventListenerOrEventListenerObject, - options?: boolean | EventListenerOptions + options?: boolean | EventListenerOptions, ): void; removeEventListener( type: unknown, listener: unknown, - options?: unknown + options?: unknown, ): void { throw new Error('Method not implemented removeEventListener.'); } @@ -356,7 +356,7 @@ class FakeWebSocket implements WebSocket { export async function replaceConstant( name: string, replacementValue: any, - testFn: () => Promise + testFn: () => Promise, ) { const initialValue = constants[name]; Object.defineProperty(constants, name, { diff --git a/packages/pubsub/src/Providers/AWSIot.ts b/packages/pubsub/src/Providers/AWSIot.ts index 6e62283623e..b517c516f06 100644 --- a/packages/pubsub/src/Providers/AWSIot.ts +++ b/packages/pubsub/src/Providers/AWSIot.ts @@ -42,7 +42,7 @@ export class AWSIoT extends MqttOverWS { const result = Signer.signUrl( endpoint, { access_key, secret_key, session_token }, - serviceInfo + serviceInfo, ); return result; diff --git a/packages/pubsub/src/Providers/MqttOverWS.ts b/packages/pubsub/src/Providers/MqttOverWS.ts index ea943b88bbb..c3eb89c4c8d 100644 --- a/packages/pubsub/src/Providers/MqttOverWS.ts +++ b/packages/pubsub/src/Providers/MqttOverWS.ts @@ -69,7 +69,7 @@ class ClientsQueue { async get( clientId: string, - clientFactory?: (input: string) => Promise + clientFactory?: (input: string) => Promise, ) { const cachedPromise = this.promises.get(clientId); if (cachedPromise) return cachedPromise; @@ -129,7 +129,7 @@ export class MqttOverWS extends AbstractPubSub { // Trigger connected to halt reconnection attempts this.reconnectionMonitor.record(ReconnectEvent.HALT_RECONNECT); } - } + }, ); } @@ -214,7 +214,7 @@ export class MqttOverWS extends AbstractPubSub { if (connected) { this.connectionStateMonitor.record( - CONNECTION_CHANGE.CONNECTION_ESTABLISHED + CONNECTION_CHANGE.CONNECTION_ESTABLISHED, ); } @@ -223,7 +223,7 @@ export class MqttOverWS extends AbstractPubSub { protected async connect( clientId: string, - options: MqttOptions = {} + options: MqttOptions = {}, ): Promise { return await this.clientsQueue.get(clientId, async clientId => { const client = await this.newClient({ ...options, clientId }); @@ -233,7 +233,7 @@ export class MqttOverWS extends AbstractPubSub { this._topicObservers.forEach( (_value: Set, key: string) => { client.subscribe(key); - } + }, ); } return client; @@ -263,7 +263,7 @@ export class MqttOverWS extends AbstractPubSub { logger.debug( 'Publishing to topic(s) failed', targetTopics.join(','), - message + message, ); } } @@ -368,7 +368,7 @@ export class MqttOverWS extends AbstractPubSub { if (this._clientIdObservers.get(clientId)?.size === 0) { this.disconnect(clientId); this.connectionStateMonitor.record( - CONNECTION_CHANGE.CLOSING_CONNECTION + CONNECTION_CHANGE.CLOSING_CONNECTION, ); this._clientIdObservers.delete(clientId); } diff --git a/packages/pubsub/src/utils/ConnectionStateMonitor.ts b/packages/pubsub/src/utils/ConnectionStateMonitor.ts index daada3eed40..f0e7c38c3ba 100644 --- a/packages/pubsub/src/utils/ConnectionStateMonitor.ts +++ b/packages/pubsub/src/utils/ConnectionStateMonitor.ts @@ -67,10 +67,10 @@ export class ConnectionStateMonitor { this._initialNetworkStateSubscription = ReachabilityMonitor().subscribe( ({ online }) => { this.record( - online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE + online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE, ); this._initialNetworkStateSubscription?.unsubscribe(); - } + }, ); this._linkedConnectionStateObservable = @@ -92,9 +92,9 @@ export class ConnectionStateMonitor { this._networkMonitoringSubscription = ReachabilityMonitor().subscribe( ({ online }) => { this.record( - online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE + online ? CONNECTION_CHANGE.ONLINE : CONNECTION_CHANGE.OFFLINE, ); - } + }, ); } } @@ -124,14 +124,14 @@ export class ConnectionStateMonitor { .pipe( map(value => { return this.connectionStatesTranslator(value); - }) + }), ) .pipe( filter(current => { const toInclude = current !== previous; previous = current; return toInclude; - }) + }), ); } diff --git a/packages/pubsub/src/vendor/paho-mqtt.js b/packages/pubsub/src/vendor/paho-mqtt.js index d5899c55c01..ae69a665096 100644 --- a/packages/pubsub/src/vendor/paho-mqtt.js +++ b/packages/pubsub/src/vendor/paho-mqtt.js @@ -169,7 +169,7 @@ function onMessageArrived(message) { if (keys.hasOwnProperty(key)) { if (typeof obj[key] !== keys[key]) throw new Error( - format(ERROR.INVALID_TYPE, [typeof obj[key], key]) + format(ERROR.INVALID_TYPE, [typeof obj[key], key]), ); } else { var errorStr = @@ -403,7 +403,7 @@ function onMessageArrived(message) { first = first |= this.payloadMessage.qos << 1; if (this.payloadMessage.retained) first |= 0x01; destinationNameLength = UTF8Length( - this.payloadMessage.destinationName + this.payloadMessage.destinationName, ); remLength += destinationNameLength + 2; var payloadBytes = this.payloadMessage.payloadBytes; @@ -438,7 +438,7 @@ function onMessageArrived(message) { this.payloadMessage.destinationName, destinationNameLength, byteStream, - pos + pos, ); // If this is a CONNECT then the variable header contains the protocol name/version, flags and keepalive time else if (this.type == MESSAGE_TYPE.CONNECT) { @@ -477,19 +477,19 @@ function onMessageArrived(message) { this.clientId, UTF8Length(this.clientId), byteStream, - pos + pos, ); if (this.willMessage !== undefined) { pos = writeString( this.willMessage.destinationName, UTF8Length(this.willMessage.destinationName), byteStream, - pos + pos, ); pos = writeUint16( willMessagePayloadBytes.byteLength, byteStream, - pos + pos, ); byteStream.set(willMessagePayloadBytes, pos); pos += willMessagePayloadBytes.byteLength; @@ -499,14 +499,14 @@ function onMessageArrived(message) { this.userName, UTF8Length(this.userName), byteStream, - pos + pos, ); if (this.password !== undefined) pos = writeString( this.password, UTF8Length(this.password), byteStream, - pos + pos, ); break; @@ -528,7 +528,7 @@ function onMessageArrived(message) { this.topics[i], topicStrLength[i], byteStream, - pos + pos, ); byteStream[pos++] = this.requestedQos[i]; } @@ -541,7 +541,7 @@ function onMessageArrived(message) { this.topics[i], topicStrLength[i], byteStream, - pos + pos, ); break; @@ -699,7 +699,7 @@ function onMessageArrived(message) { var lowCharCode = input.charCodeAt(++i); if (isNaN(lowCharCode)) { throw new Error( - format(ERROR.MALFORMED_UNICODE, [charCode, lowCharCode]) + format(ERROR.MALFORMED_UNICODE, [charCode, lowCharCode]), ); } charCode = @@ -741,7 +741,7 @@ function onMessageArrived(message) { byte1.toString(16), byte2.toString(16), '', - ]) + ]), ); if (byte1 < 0xe0) // 2 byte character @@ -754,7 +754,7 @@ function onMessageArrived(message) { byte1.toString(16), byte2.toString(16), byte3.toString(16), - ]) + ]), ); if (byte1 < 0xf0) // 3 byte character @@ -768,7 +768,7 @@ function onMessageArrived(message) { byte2.toString(16), byte3.toString(16), byte4.toString(16), - ]) + ]), ); if (byte1 < 0xf8) // 4 byte character @@ -782,7 +782,7 @@ function onMessageArrived(message) { byte2.toString(16), byte3.toString(16), byte4.toString(16), - ]) + ]), ); } } @@ -822,7 +822,7 @@ function onMessageArrived(message) { this._client._trace('Pinger.doPing', 'Timed out'); this._client._disconnected( ERROR.PING_TIMEOUT.code, - format(ERROR.PING_TIMEOUT) + format(ERROR.PING_TIMEOUT), ); } else { this.isReset = false; @@ -858,7 +858,7 @@ function onMessageArrived(message) { }; this.timeout = setTimeout( doTimeout(action, client, args), - timeoutSeconds * 1000 + timeoutSeconds * 1000, ); this.cancel = function () { @@ -983,7 +983,7 @@ function onMessageArrived(message) { 'Client.connect', connectOptionsMasked, this.socket, - this.connected + this.connected, ); if (this.connected) @@ -1053,7 +1053,7 @@ function onMessageArrived(message) { errorCode: ERROR.SUBSCRIBE_TIMEOUT.code, errorMessage: format(ERROR.SUBSCRIBE_TIMEOUT), }, - ] + ], ); } @@ -1090,7 +1090,7 @@ function onMessageArrived(message) { errorCode: ERROR.UNSUBSCRIBE_TIMEOUT.code, errorMessage: format(ERROR.UNSUBSCRIBE_TIMEOUT), }, - ] + ], ); } @@ -1113,7 +1113,7 @@ function onMessageArrived(message) { this._requires_ack(wireMessage); } else if (this.onMessageDelivered) { this._notify_msg_sent[wireMessage] = this.onMessageDelivered( - wireMessage.payloadMessage + wireMessage.payloadMessage, ); } this._schedule_message(wireMessage); @@ -1127,7 +1127,7 @@ function onMessageArrived(message) { this._buffered_msg_queue.length; if (messageCount > this.disconnectedBufferSize) { throw new Error( - format(ERROR.BUFFER_FULL, [this.disconnectedBufferSize]) + format(ERROR.BUFFER_FULL, [this.disconnectedBufferSize]), ); } else { if (message.qos > 0) { @@ -1158,7 +1158,7 @@ function onMessageArrived(message) { if (!this.socket) throw new Error( - format(ERROR.INVALID_STATE, ['not connecting or connected']) + format(ERROR.INVALID_STATE, ['not connecting or connected']), ); var wireMessage = new WireMessage(MESSAGE_TYPE.DISCONNECT); @@ -1176,7 +1176,7 @@ function onMessageArrived(message) { this._trace('Client.getTraceLog', new Date()); this._trace( 'Client.getTraceLog in flight messages', - this._sentMessages.length + this._sentMessages.length, ); for (var key in this._sentMessages) this._trace('_sentMessages ', key, this._sentMessages[key]); @@ -1222,7 +1222,7 @@ function onMessageArrived(message) { this.sendPinger = new Pinger(this, this.connectOptions.keepAliveInterval); this.receivePinger = new Pinger( this, - this.connectOptions.keepAliveInterval + this.connectOptions.keepAliveInterval, ); if (this._connectTimeout) { this._connectTimeout.cancel(); @@ -1232,7 +1232,7 @@ function onMessageArrived(message) { this, this.connectOptions.timeout, this._disconnected, - [ERROR.CONNECT_TIMEOUT.code, format(ERROR.CONNECT_TIMEOUT)] + [ERROR.CONNECT_TIMEOUT.code, format(ERROR.CONNECT_TIMEOUT)], ); }; @@ -1293,12 +1293,12 @@ function onMessageArrived(message) { format(ERROR.INVALID_STORED_DATA, [ prefix + this._localKey + wireMessage.messageIdentifier, storedMessage, - ]) + ]), ); } localStorage.setItem( prefix + this._localKey + wireMessage.messageIdentifier, - JSON.stringify(storedMessage) + JSON.stringify(storedMessage), ); }; @@ -1390,7 +1390,7 @@ function onMessageArrived(message) { // Create the CONNECT message object. var wireMessage = new WireMessage( MESSAGE_TYPE.CONNECT, - this.connectOptions + this.connectOptions, ); wireMessage.clientId = this.clientId; this._socket_send(wireMessage); @@ -1413,7 +1413,7 @@ function onMessageArrived(message) { var messages = []; if (this.receiveBuffer) { var newData = new Uint8Array( - this.receiveBuffer.length + byteArray.length + this.receiveBuffer.length + byteArray.length, ); newData.set(this.receiveBuffer); newData.set(byteArray, this.receiveBuffer.length); @@ -1442,7 +1442,7 @@ function onMessageArrived(message) { : 'No Error Stack Available'; this._disconnected( ERROR.INTERNAL_ERROR.code, - format(ERROR.INTERNAL_ERROR, [error.message, errorStack]) + format(ERROR.INTERNAL_ERROR, [error.message, errorStack]), ); return; } @@ -1463,7 +1463,7 @@ function onMessageArrived(message) { for (var key in this._sentMessages) { var sentMessage = this._sentMessages[key]; localStorage.removeItem( - 'Sent:' + this._localKey + sentMessage.messageIdentifier + 'Sent:' + this._localKey + sentMessage.messageIdentifier, ); } this._sentMessages = {}; @@ -1473,7 +1473,7 @@ function onMessageArrived(message) { localStorage.removeItem( 'Received:' + this._localKey + - receivedMessage.messageIdentifier + receivedMessage.messageIdentifier, ); } this._receivedMessages = {}; @@ -1491,7 +1491,7 @@ function onMessageArrived(message) { format(ERROR.CONNACK_RETURNCODE, [ wireMessage.returnCode, CONNACK_RC[wireMessage.returnCode], - ]) + ]), ); break; } @@ -1510,7 +1510,7 @@ function onMessageArrived(message) { sequencedMessages.push(msg); if (this.onMessageDelivered) this._notify_msg_sent[msg] = this.onMessageDelivered( - msg.payloadMessage + msg.payloadMessage, ); } } @@ -1567,7 +1567,7 @@ function onMessageArrived(message) { if (sentMessage) { delete this._sentMessages[wireMessage.messageIdentifier]; localStorage.removeItem( - 'Sent:' + this._localKey + wireMessage.messageIdentifier + 'Sent:' + this._localKey + wireMessage.messageIdentifier, ); if (this.onMessageDelivered) this.onMessageDelivered(sentMessage.payloadMessage); @@ -1591,7 +1591,7 @@ function onMessageArrived(message) { var receivedMessage = this._receivedMessages[wireMessage.messageIdentifier]; localStorage.removeItem( - 'Received:' + this._localKey + wireMessage.messageIdentifier + 'Received:' + this._localKey + wireMessage.messageIdentifier, ); // If this is a re flow of a PUBREL after we have restarted receivedMessage will not exist. if (receivedMessage) { @@ -1610,7 +1610,7 @@ function onMessageArrived(message) { var sentMessage = this._sentMessages[wireMessage.messageIdentifier]; delete this._sentMessages[wireMessage.messageIdentifier]; localStorage.removeItem( - 'Sent:' + this._localKey + wireMessage.messageIdentifier + 'Sent:' + this._localKey + wireMessage.messageIdentifier, ); if (this.onMessageDelivered) this.onMessageDelivered(sentMessage.payloadMessage); @@ -1653,14 +1653,14 @@ function onMessageArrived(message) { // Clients do not expect to receive disconnect packets. this._disconnected( ERROR.INVALID_MQTT_MESSAGE_TYPE.code, - format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type]) + format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type]), ); break; default: this._disconnected( ERROR.INVALID_MQTT_MESSAGE_TYPE.code, - format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type]) + format(ERROR.INVALID_MQTT_MESSAGE_TYPE, [wireMessage.type]), ); } } catch (error) { @@ -1670,7 +1670,7 @@ function onMessageArrived(message) { : 'No Error Stack Available'; this._disconnected( ERROR.INTERNAL_ERROR.code, - format(ERROR.INTERNAL_ERROR, [error.message, errorStack]) + format(ERROR.INTERNAL_ERROR, [error.message, errorStack]), ); return; } @@ -1681,7 +1681,7 @@ function onMessageArrived(message) { if (!this._reconnecting) { this._disconnected( ERROR.SOCKET_ERROR.code, - format(ERROR.SOCKET_ERROR, [error.data]) + format(ERROR.SOCKET_ERROR, [error.data]), ); } }; @@ -1790,7 +1790,7 @@ function onMessageArrived(message) { this._reconnectTimeout = new Timeout( this, this._reconnectInterval, - this._reconnect + this._reconnect, ); return; } @@ -1997,7 +1997,7 @@ function onMessageArrived(message) { clientId = port; uri = host; var match = uri.match( - /^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/ + /^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/, ); if (match) { host = match[4] || match[2]; @@ -2095,7 +2095,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_TYPE, [ typeof newOnConnected, 'onConnected', - ]) + ]), ); }, }, @@ -2127,7 +2127,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_TYPE, [ typeof newOnConnectionLost, 'onConnectionLost', - ]) + ]), ); }, }, @@ -2143,7 +2143,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_TYPE, [ typeof newOnMessageDelivered, 'onMessageDelivered', - ]) + ]), ); }, }, @@ -2159,7 +2159,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_TYPE, [ typeof newOnMessageArrived, 'onMessageArrived', - ]) + ]), ); }, }, @@ -2172,7 +2172,7 @@ function onMessageArrived(message) { client.traceFunction = trace; } else { throw new Error( - format(ERROR.INVALID_TYPE, [typeof trace, 'onTrace']) + format(ERROR.INVALID_TYPE, [typeof trace, 'onTrace']), ); } }, @@ -2271,7 +2271,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_ARGUMENT, [ connectOptions.mqttVersion, 'connectOptions.mqttVersion', - ]) + ]), ); } @@ -2291,7 +2291,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_ARGUMENT, [ connectOptions.password, 'connectOptions.password', - ]) + ]), ); if (connectOptions.willMessage) { @@ -2300,7 +2300,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_TYPE, [ connectOptions.willMessage, 'connectOptions.willMessage', - ]) + ]), ); // The will message must have a payload that can be represented as a string. // Cause the willMessage to throw an exception if this is not the case. @@ -2311,7 +2311,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_TYPE, [ typeof connectOptions.willMessage.destinationName, 'connectOptions.willMessage.destinationName', - ]) + ]), ); } if (typeof connectOptions.cleanSession === 'undefined') @@ -2322,14 +2322,14 @@ function onMessageArrived(message) { format(ERROR.INVALID_ARGUMENT, [ connectOptions.hosts, 'connectOptions.hosts', - ]) + ]), ); if (connectOptions.hosts.length < 1) throw new Error( format(ERROR.INVALID_ARGUMENT, [ connectOptions.hosts, 'connectOptions.hosts', - ]) + ]), ); var usingURIs = false; @@ -2339,11 +2339,11 @@ function onMessageArrived(message) { format(ERROR.INVALID_TYPE, [ typeof connectOptions.hosts[i], 'connectOptions.hosts[' + i + ']', - ]) + ]), ); if ( /^(wss?):\/\/((\[(.+)\])|([^\/]+?))(:(\d+))?(\/.*)$/.test( - connectOptions.hosts[i] + connectOptions.hosts[i], ) ) { if (i === 0) { @@ -2353,7 +2353,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_ARGUMENT, [ connectOptions.hosts[i], 'connectOptions.hosts[' + i + ']', - ]) + ]), ); } } else if (usingURIs) { @@ -2361,7 +2361,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_ARGUMENT, [ connectOptions.hosts[i], 'connectOptions.hosts[' + i + ']', - ]) + ]), ); } } @@ -2372,21 +2372,21 @@ function onMessageArrived(message) { format(ERROR.INVALID_ARGUMENT, [ connectOptions.ports, 'connectOptions.ports', - ]) + ]), ); if (!(connectOptions.ports instanceof Array)) throw new Error( format(ERROR.INVALID_ARGUMENT, [ connectOptions.ports, 'connectOptions.ports', - ]) + ]), ); if (connectOptions.hosts.length !== connectOptions.ports.length) throw new Error( format(ERROR.INVALID_ARGUMENT, [ connectOptions.ports, 'connectOptions.ports', - ]) + ]), ); connectOptions.uris = []; @@ -2400,7 +2400,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_TYPE, [ typeof connectOptions.ports[i], 'connectOptions.ports[' + i + ']', - ]) + ]), ); var host = connectOptions.hosts[i]; var port = connectOptions.ports[i]; @@ -2463,7 +2463,7 @@ function onMessageArrived(message) { }); if (subscribeOptions.timeout && !subscribeOptions.onFailure) throw new Error( - 'subscribeOptions.timeout specified with no onFailure callback.' + 'subscribeOptions.timeout specified with no onFailure callback.', ); if ( typeof subscribeOptions.qos !== 'undefined' && @@ -2477,7 +2477,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_ARGUMENT, [ subscribeOptions.qos, 'subscribeOptions.qos', - ]) + ]), ); client.subscribe(filter, subscribeOptions); }; @@ -2522,7 +2522,7 @@ function onMessageArrived(message) { }); if (unsubscribeOptions.timeout && !unsubscribeOptions.onFailure) throw new Error( - 'unsubscribeOptions.timeout specified with no onFailure callback.' + 'unsubscribeOptions.timeout specified with no onFailure callback.', ); client.unsubscribe(filter, unsubscribeOptions); }; @@ -2564,7 +2564,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_ARGUMENT, [ message.destinationName, 'Message.destinationName', - ]) + ]), ); client.send(message); } else { @@ -2615,7 +2615,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_ARGUMENT, [ message.destinationName, 'Message.destinationName', - ]) + ]), ); client.send(message); } else { @@ -2761,7 +2761,7 @@ function onMessageArrived(message) { format(ERROR.INVALID_ARGUMENT, [ newDestinationName, 'newDestinationName', - ]) + ]), ); }, }, @@ -2784,7 +2784,7 @@ function onMessageArrived(message) { if (typeof newRetained === 'boolean') retained = newRetained; else throw new Error( - format(ERROR.INVALID_ARGUMENT, [newRetained, 'newRetained']) + format(ERROR.INVALID_ARGUMENT, [newRetained, 'newRetained']), ); }, }, @@ -2819,10 +2819,10 @@ function onMessageArrived(message) { typeof global !== 'undefined' ? global : typeof self !== 'undefined' - ? self - : typeof window !== 'undefined' - ? window - : {} + ? self + : typeof window !== 'undefined' + ? window + : {}, ); return PahoMQTT; }); diff --git a/packages/react-native/example/metro.config.js b/packages/react-native/example/metro.config.js index c83f38d55f2..67cc9487d10 100644 --- a/packages/react-native/example/metro.config.js +++ b/packages/react-native/example/metro.config.js @@ -17,8 +17,8 @@ const config = { resolver: { blacklistRE: exclusionList( modules.map( - m => new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`) - ) + m => new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`), + ), ), extraNodeModules: modules.reduce((acc, name) => { acc[name] = path.join(__dirname, 'node_modules', name); diff --git a/packages/react-native/src/moduleLoaders/loadAmplifyPushNotification.ts b/packages/react-native/src/moduleLoaders/loadAmplifyPushNotification.ts index 0b23cc1900e..a86697e4e8c 100644 --- a/packages/react-native/src/moduleLoaders/loadAmplifyPushNotification.ts +++ b/packages/react-native/src/moduleLoaders/loadAmplifyPushNotification.ts @@ -13,7 +13,7 @@ export const loadAmplifyPushNotification = () => { } throw new Error( - 'Ensure `@aws-amplify/rtn-push-notification` is installed and linked.' + 'Ensure `@aws-amplify/rtn-push-notification` is installed and linked.', ); } catch (e) { // The error parsing logic cannot be extracted with metro as the `require` @@ -21,7 +21,7 @@ export const loadAmplifyPushNotification = () => { // another module and that causes an error const message = (e as Error).message.replace( /undefined/g, - '@aws-amplify/rtn-push-notification' + '@aws-amplify/rtn-push-notification', ); throw new Error(message); } diff --git a/packages/react-native/src/moduleLoaders/loadAmplifyWebBrowser.ts b/packages/react-native/src/moduleLoaders/loadAmplifyWebBrowser.ts index 29611beae02..2c98a39f8f6 100644 --- a/packages/react-native/src/moduleLoaders/loadAmplifyWebBrowser.ts +++ b/packages/react-native/src/moduleLoaders/loadAmplifyWebBrowser.ts @@ -13,7 +13,7 @@ export const loadAmplifyWebBrowser = () => { } throw new Error( - 'Ensure `@aws-amplify/rtn-web-browser` is installed and linked.' + 'Ensure `@aws-amplify/rtn-web-browser` is installed and linked.', ); } catch (e) { // The error parsing logic cannot be extracted with metro as the `require` @@ -21,7 +21,7 @@ export const loadAmplifyWebBrowser = () => { // another module and that causes an error const message = (e as Error).message.replace( /undefined/g, - '@aws-amplify/rtn-web-browser' + '@aws-amplify/rtn-web-browser', ); throw new Error(message); } diff --git a/packages/react-native/src/moduleLoaders/loadAsyncStorage.ts b/packages/react-native/src/moduleLoaders/loadAsyncStorage.ts index 2c3cf052a2f..ae5de3ec2bd 100644 --- a/packages/react-native/src/moduleLoaders/loadAsyncStorage.ts +++ b/packages/react-native/src/moduleLoaders/loadAsyncStorage.ts @@ -14,7 +14,7 @@ export const loadAsyncStorage = (): AsyncStorageStatic => { } throw new Error( - 'Ensure `@react-native-async-storage/async-storage` is installed and linked.' + 'Ensure `@react-native-async-storage/async-storage` is installed and linked.', ); } catch (e) { // The error parsing logic cannot be extracted with metro as the `require` @@ -22,7 +22,7 @@ export const loadAsyncStorage = (): AsyncStorageStatic => { // another module and that causes an error const message = (e as Error).message.replace( /undefined/g, - '@react-native-async-storage/async-storage' + '@react-native-async-storage/async-storage', ); throw new Error(message); } diff --git a/packages/react-native/src/moduleLoaders/loadGetRandomValues.ts b/packages/react-native/src/moduleLoaders/loadGetRandomValues.ts index ca315df3340..53d3320b99b 100644 --- a/packages/react-native/src/moduleLoaders/loadGetRandomValues.ts +++ b/packages/react-native/src/moduleLoaders/loadGetRandomValues.ts @@ -12,7 +12,7 @@ export const loadGetRandomValues = () => { // another module and that causes error const message = (e as Error).message.replace( /undefined/g, - 'react-native-get-random-values' + 'react-native-get-random-values', ); throw new Error(message); } diff --git a/packages/react-native/src/moduleLoaders/loadNetInfo.ts b/packages/react-native/src/moduleLoaders/loadNetInfo.ts index 9601026b602..def2c04c602 100644 --- a/packages/react-native/src/moduleLoaders/loadNetInfo.ts +++ b/packages/react-native/src/moduleLoaders/loadNetInfo.ts @@ -16,7 +16,7 @@ export const loadNetInfo = (): NetInfoModule => { } throw new Error( - 'Ensure `@react-native-community/netinfo` is installed and linked.' + 'Ensure `@react-native-community/netinfo` is installed and linked.', ); } catch (e) { // The error parsing logic cannot be extract as with metro the `require` @@ -24,7 +24,7 @@ export const loadNetInfo = (): NetInfoModule => { // another module and that causes error const message = (e as Error).message.replace( /undefined/g, - '@react-native-community/netinfo' + '@react-native-community/netinfo', ); throw new Error(message); } diff --git a/packages/react-native/src/moduleLoaders/loadUrlPolyfill.ts b/packages/react-native/src/moduleLoaders/loadUrlPolyfill.ts index 3c64c33a220..39393732d06 100644 --- a/packages/react-native/src/moduleLoaders/loadUrlPolyfill.ts +++ b/packages/react-native/src/moduleLoaders/loadUrlPolyfill.ts @@ -12,7 +12,7 @@ export const loadUrlPolyfill = () => { // another module and that causes error const message = (e as Error).message.replace( /undefined/g, - 'react-native-url-polyfill' + 'react-native-url-polyfill', ); throw new Error(message); } diff --git a/packages/react-native/src/nativeModule.ts b/packages/react-native/src/nativeModule.ts index 062c73d9c3a..75ec171c590 100644 --- a/packages/react-native/src/nativeModule.ts +++ b/packages/react-native/src/nativeModule.ts @@ -18,5 +18,5 @@ export const nativeModule: RTNCore = NativeModules.AmplifyRTNCore get() { throw new Error(LINKING_ERROR); }, - } - ); + }, + ); diff --git a/packages/rtn-push-notification/__tests__/apis/addMessageEventListener.test.ts b/packages/rtn-push-notification/__tests__/apis/addMessageEventListener.test.ts index 407b808cfce..6f7f6d5df0a 100644 --- a/packages/rtn-push-notification/__tests__/apis/addMessageEventListener.test.ts +++ b/packages/rtn-push-notification/__tests__/apis/addMessageEventListener.test.ts @@ -29,7 +29,7 @@ describe('addMessageEventListener', () => { expect(mockAddListenerNative).toHaveBeenCalledWith( event, - expect.any(Function) + expect.any(Function), ); }); @@ -48,7 +48,7 @@ describe('addMessageEventListener', () => { expect.objectContaining({ body: `normalized-${nativeMessage.body}`, }), - undefined + undefined, ); }); @@ -69,7 +69,7 @@ describe('addMessageEventListener', () => { expect.objectContaining({ body: `normalized-${nativeMessage.body}`, }), - completionHandlerId + completionHandlerId, ); }); }); diff --git a/packages/rtn-push-notification/__tests__/apis/addTokenEventListener.test.ts b/packages/rtn-push-notification/__tests__/apis/addTokenEventListener.test.ts index 96c22e416b4..bcd1d1eb0a9 100644 --- a/packages/rtn-push-notification/__tests__/apis/addTokenEventListener.test.ts +++ b/packages/rtn-push-notification/__tests__/apis/addTokenEventListener.test.ts @@ -25,7 +25,7 @@ describe('addTokenEventListener', () => { expect(mockAddListenerNative).toHaveBeenCalledWith( eventType, - expect.any(Function) + expect.any(Function), ); }); diff --git a/packages/rtn-push-notification/__tests__/apis/completeNotification.test.ts b/packages/rtn-push-notification/__tests__/apis/completeNotification.test.ts index 53c5157a4e4..334e9962be3 100644 --- a/packages/rtn-push-notification/__tests__/apis/completeNotification.test.ts +++ b/packages/rtn-push-notification/__tests__/apis/completeNotification.test.ts @@ -28,7 +28,7 @@ describe('completeNotification', () => { completeNotification(completionHandlerId); expect(mockCompleteNotificationNative).toHaveBeenCalledWith( - completionHandlerId + completionHandlerId, ); }); }); diff --git a/packages/rtn-push-notification/__tests__/apis/getLaunchNotification.test.ts b/packages/rtn-push-notification/__tests__/apis/getLaunchNotification.test.ts index d628c43f2b6..7fadf9eca66 100644 --- a/packages/rtn-push-notification/__tests__/apis/getLaunchNotification.test.ts +++ b/packages/rtn-push-notification/__tests__/apis/getLaunchNotification.test.ts @@ -34,7 +34,7 @@ describe('getLaunchNotification', () => { expect(await getLaunchNotification()).toStrictEqual( expect.objectContaining({ body: `normalized-${nativeMessage.body}`, - }) + }), ); expect(mockGetLaunchNotificationNative).toHaveBeenCalled(); expect(mockNormalizeNativeMessage).toHaveBeenCalledWith(nativeMessage); diff --git a/packages/rtn-push-notification/__tests__/apis/getPermissionStatus.test.ts b/packages/rtn-push-notification/__tests__/apis/getPermissionStatus.test.ts index 1588e665216..d58cc630a7d 100644 --- a/packages/rtn-push-notification/__tests__/apis/getPermissionStatus.test.ts +++ b/packages/rtn-push-notification/__tests__/apis/getPermissionStatus.test.ts @@ -23,7 +23,7 @@ describe('getPermissionStatus', () => { beforeAll(() => { mockGetPermissionStatusNative.mockResolvedValue(status); mockNormalizeNativePermissionStatus.mockImplementation( - status => `normalized-${status}` + status => `normalized-${status}`, ); }); diff --git a/packages/rtn-push-notification/__tests__/apis/registerHeadlessTask.test.ts b/packages/rtn-push-notification/__tests__/apis/registerHeadlessTask.test.ts index ed47bf17c07..8a4c5492544 100644 --- a/packages/rtn-push-notification/__tests__/apis/registerHeadlessTask.test.ts +++ b/packages/rtn-push-notification/__tests__/apis/registerHeadlessTask.test.ts @@ -44,7 +44,7 @@ describe('registerHeadlessTask', () => { expect(mockReactNativeRegisterHeadlessTask).toHaveBeenCalledWith( nativeHeadlessTaskKey, - expect.any(Function) + expect.any(Function), ); }); @@ -63,7 +63,7 @@ describe('registerHeadlessTask', () => { expect(listener).toHaveBeenCalledWith( expect.objectContaining({ body: `normalized-${nativeMessage.body}`, - }) + }), ); }); diff --git a/packages/rtn-push-notification/__tests__/apis/requestPermissions.test.ts b/packages/rtn-push-notification/__tests__/apis/requestPermissions.test.ts index 37a955ec1c9..1dd7bf4e167 100644 --- a/packages/rtn-push-notification/__tests__/apis/requestPermissions.test.ts +++ b/packages/rtn-push-notification/__tests__/apis/requestPermissions.test.ts @@ -37,7 +37,7 @@ describe('requestPermissions', () => { await requestPermissions({ badge: false, sound: false, - }) + }), ).toBe(true); expect(mockRequestPermissionsNative).toHaveBeenCalledWith({ alert: true, diff --git a/packages/rtn-push-notification/__tests__/utils/normalizeNativeMessage.test.ts b/packages/rtn-push-notification/__tests__/utils/normalizeNativeMessage.test.ts index 833621719bf..01e05c327e0 100644 --- a/packages/rtn-push-notification/__tests__/utils/normalizeNativeMessage.test.ts +++ b/packages/rtn-push-notification/__tests__/utils/normalizeNativeMessage.test.ts @@ -37,7 +37,7 @@ describe('normalizeNativeMessage', () => { const payload = { aps: { alert: { body, title } } }; expect(normalizeNativeMessage(payload)).toStrictEqual( - expect.objectContaining({ body, title }) + expect.objectContaining({ body, title }), ); }); @@ -50,7 +50,7 @@ describe('normalizeNativeMessage', () => { expect(normalizeNativeMessage(payload)).toStrictEqual( expect.objectContaining({ data: pushNotificationAdhocData, - }) + }), ); }); @@ -92,7 +92,7 @@ describe('normalizeNativeMessage', () => { expect(normalizeNativeMessage(payload)).toStrictEqual( expect.objectContaining({ data: pushNotificationAdhocData, - }) + }), ); }); diff --git a/packages/rtn-push-notification/__tests__/utils/normalizeNativePermissionStatus.test.ts b/packages/rtn-push-notification/__tests__/utils/normalizeNativePermissionStatus.test.ts index 85eeaca1f73..5e713593949 100644 --- a/packages/rtn-push-notification/__tests__/utils/normalizeNativePermissionStatus.test.ts +++ b/packages/rtn-push-notification/__tests__/utils/normalizeNativePermissionStatus.test.ts @@ -6,10 +6,10 @@ import { normalizeNativePermissionStatus } from '../../src/utils'; describe('normalizeNativePermissionStatus', () => { it('normalizes android statuses', () => { expect(normalizeNativePermissionStatus('ShouldRequest')).toBe( - 'shouldRequest' + 'shouldRequest', ); expect(normalizeNativePermissionStatus('ShouldExplainThenRequest')).toBe( - 'shouldExplainThenRequest' + 'shouldExplainThenRequest', ); expect(normalizeNativePermissionStatus('Granted')).toBe('granted'); expect(normalizeNativePermissionStatus('Denied')).toBe('denied'); @@ -17,7 +17,7 @@ describe('normalizeNativePermissionStatus', () => { it('normalizes ios statuses', () => { expect(normalizeNativePermissionStatus('NotDetermined')).toBe( - 'shouldExplainThenRequest' + 'shouldExplainThenRequest', ); expect(normalizeNativePermissionStatus('Authorized')).toBe('granted'); expect(normalizeNativePermissionStatus('Denied')).toBe('denied'); diff --git a/packages/rtn-push-notification/src/apis/addMessageEventListener.ts b/packages/rtn-push-notification/src/apis/addMessageEventListener.ts index 586c7f68a0b..50367252c7b 100644 --- a/packages/rtn-push-notification/src/apis/addMessageEventListener.ts +++ b/packages/rtn-push-notification/src/apis/addMessageEventListener.ts @@ -10,12 +10,12 @@ export const addMessageEventListener = ( event: string, listener: ( message: PushNotificationMessage | null, - completionHandlerId?: string - ) => void + completionHandlerId?: string, + ) => void, ): EmitterSubscription => nativeEventEmitter.addListener(event, (nativeMessage: NativeMessage) => { listener( normalizeNativeMessage(nativeMessage), - nativeMessage.completionHandlerId + nativeMessage.completionHandlerId, ); }); diff --git a/packages/rtn-push-notification/src/apis/addTokenEventListener.ts b/packages/rtn-push-notification/src/apis/addTokenEventListener.ts index afabac89266..e049f22f1f0 100644 --- a/packages/rtn-push-notification/src/apis/addTokenEventListener.ts +++ b/packages/rtn-push-notification/src/apis/addTokenEventListener.ts @@ -7,7 +7,7 @@ import { TokenPayload } from '../types'; export const addTokenEventListener = ( event: string, - listener: (token: string) => void + listener: (token: string) => void, ): EmitterSubscription => nativeEventEmitter.addListener(event, ({ token }: TokenPayload) => { listener(token); diff --git a/packages/rtn-push-notification/src/apis/getLaunchNotification.ts b/packages/rtn-push-notification/src/apis/getLaunchNotification.ts index 47d5993e0af..ec9accf131c 100644 --- a/packages/rtn-push-notification/src/apis/getLaunchNotification.ts +++ b/packages/rtn-push-notification/src/apis/getLaunchNotification.ts @@ -8,5 +8,5 @@ import { normalizeNativeMessage } from '../utils'; export const getLaunchNotification = async (): Promise => normalizeNativeMessage( - (await nativeModule.getLaunchNotification()) ?? undefined + (await nativeModule.getLaunchNotification()) ?? undefined, ); diff --git a/packages/rtn-push-notification/src/apis/registerHeadlessTask.ts b/packages/rtn-push-notification/src/apis/registerHeadlessTask.ts index 02924f11ef2..895a2b0fc5c 100644 --- a/packages/rtn-push-notification/src/apis/registerHeadlessTask.ts +++ b/packages/rtn-push-notification/src/apis/registerHeadlessTask.ts @@ -7,7 +7,7 @@ import { NativeMessage, PushNotificationMessage } from '../types'; import { normalizeNativeMessage } from '../utils'; export const registerHeadlessTask = ( - task: (message: PushNotificationMessage | null) => Promise + task: (message: PushNotificationMessage | null) => Promise, ): void => { const { NativeHeadlessTaskKey } = getConstants(); if (NativeHeadlessTaskKey) { @@ -15,7 +15,7 @@ export const registerHeadlessTask = ( NativeHeadlessTaskKey, () => async (nativeMessage: NativeMessage) => { await task(normalizeNativeMessage(nativeMessage)); - } + }, ); } }; diff --git a/packages/rtn-push-notification/src/apis/requestPermissions.ts b/packages/rtn-push-notification/src/apis/requestPermissions.ts index c3bd599013b..40541c663c0 100644 --- a/packages/rtn-push-notification/src/apis/requestPermissions.ts +++ b/packages/rtn-push-notification/src/apis/requestPermissions.ts @@ -9,7 +9,7 @@ export const requestPermissions = async ( alert: true, badge: true, sound: true, - } + }, ): Promise => nativeModule.requestPermissions({ alert, diff --git a/packages/rtn-push-notification/src/nativeModule.ts b/packages/rtn-push-notification/src/nativeModule.ts index ae4ab42b5ea..c7c4f6374df 100644 --- a/packages/rtn-push-notification/src/nativeModule.ts +++ b/packages/rtn-push-notification/src/nativeModule.ts @@ -14,7 +14,7 @@ export const nativeModule: PushNotificationNativeModule = get() { throw new Error(LINKING_ERROR); }, - } - ); + }, + ); export const nativeEventEmitter = new NativeEventEmitter(nativeModule); diff --git a/packages/rtn-push-notification/src/types/native.ts b/packages/rtn-push-notification/src/types/native.ts index 942c3683b4d..6791bfc09e7 100644 --- a/packages/rtn-push-notification/src/types/native.ts +++ b/packages/rtn-push-notification/src/types/native.ts @@ -21,7 +21,7 @@ export interface PushNotificationNativeModule extends NativeModule { setBadgeCount?: (count: number) => void; getPermissionStatus: () => Promise; requestPermissions: ( - permissions: PushNotificationPermissions + permissions: PushNotificationPermissions, ) => Promise; } diff --git a/packages/rtn-push-notification/src/utils/normalizeNativeMessage.ts b/packages/rtn-push-notification/src/utils/normalizeNativeMessage.ts index 93d52f4886b..d3bbaf68017 100644 --- a/packages/rtn-push-notification/src/utils/normalizeNativeMessage.ts +++ b/packages/rtn-push-notification/src/utils/normalizeNativeMessage.ts @@ -15,7 +15,7 @@ import { * @internal */ export const normalizeNativeMessage = ( - nativeMessage?: NativeMessage + nativeMessage?: NativeMessage, ): PushNotificationMessage | null => { let normalized: NormalizedValues; if (isApnsMessage(nativeMessage)) { @@ -53,7 +53,7 @@ const normalizeFcmMessage = (fcmMessage: FcmMessage): NormalizedValues => { }; const getApnsAction = ( - action?: NativeAction + action?: NativeAction, ): Pick | undefined => { if (action?.deeplink) { return { deeplinkUrl: action.deeplink }; @@ -61,7 +61,7 @@ const getApnsAction = ( }; const getFcmAction = ( - action?: NativeAction + action?: NativeAction, ): Pick | undefined => { if (action?.url) { return { goToUrl: action.url }; @@ -95,9 +95,9 @@ const getFcmOptions = ({ }; const isApnsMessage = ( - nativeMessage?: NativeMessage + nativeMessage?: NativeMessage, ): nativeMessage is ApnsMessage => !!nativeMessage?.aps; const isFcmMessage = ( - nativeMessage?: NativeMessage + nativeMessage?: NativeMessage, ): nativeMessage is FcmMessage => !!nativeMessage?.rawData; diff --git a/packages/rtn-push-notification/src/utils/normalizeNativePermissionStatus.ts b/packages/rtn-push-notification/src/utils/normalizeNativePermissionStatus.ts index eaf6f7c2f0e..d7ba583c8c8 100644 --- a/packages/rtn-push-notification/src/utils/normalizeNativePermissionStatus.ts +++ b/packages/rtn-push-notification/src/utils/normalizeNativePermissionStatus.ts @@ -10,7 +10,7 @@ import { * @internal */ export const normalizeNativePermissionStatus = ( - nativeStatus: NativePermissionStatus + nativeStatus: NativePermissionStatus, ): PushNotificationPermissionStatus => { switch (nativeStatus) { case 'ShouldRequest': diff --git a/packages/rtn-web-browser/src/apis/openAuthSessionAsync.ts b/packages/rtn-web-browser/src/apis/openAuthSessionAsync.ts index 37f5a287839..55344564fc3 100644 --- a/packages/rtn-web-browser/src/apis/openAuthSessionAsync.ts +++ b/packages/rtn-web-browser/src/apis/openAuthSessionAsync.ts @@ -15,7 +15,7 @@ let redirectListener: NativeEventSubscription | undefined; export const openAuthSessionAsync = async ( url: string, redirectUrls: string[], - prefersEphemeralSession?: boolean + prefersEphemeralSession?: boolean, ) => { // enforce HTTPS const httpsUrl = url.replace('http://', 'https://'); @@ -31,16 +31,16 @@ export const openAuthSessionAsync = async ( const openAuthSessionIOS = async ( url: string, redirectUrls: string[], - prefersEphemeralSession: boolean = false + prefersEphemeralSession: boolean = false, ) => { const redirectUrl = redirectUrls.find( // take the first non-web url as the deeplink - item => !item.startsWith('https://') && !item.startsWith('http://') + item => !item.startsWith('https://') && !item.startsWith('http://'), ); return nativeModule.openAuthSessionAsync( url, redirectUrl, - prefersEphemeralSession + prefersEphemeralSession, ); }; diff --git a/packages/rtn-web-browser/src/nativeModule.ts b/packages/rtn-web-browser/src/nativeModule.ts index 9ec0ce26227..bc534235bde 100644 --- a/packages/rtn-web-browser/src/nativeModule.ts +++ b/packages/rtn-web-browser/src/nativeModule.ts @@ -14,5 +14,5 @@ export const nativeModule: WebBrowserNativeModule = get() { throw new Error(LINKING_ERROR); }, - } - ); + }, + ); diff --git a/packages/rtn-web-browser/src/types/native.ts b/packages/rtn-web-browser/src/types/native.ts index 3ddc1a6d952..b3172af60e0 100644 --- a/packages/rtn-web-browser/src/types/native.ts +++ b/packages/rtn-web-browser/src/types/native.ts @@ -7,6 +7,6 @@ export interface WebBrowserNativeModule extends NativeModule { openAuthSessionAsync: ( url: string, redirectUrl?: string, - prefersEphemeralSession?: boolean + prefersEphemeralSession?: boolean, ) => Promise; } diff --git a/packages/storage/__tests__/providers/s3/apis/copy.test.ts b/packages/storage/__tests__/providers/s3/apis/copy.test.ts index ec7dcbd1b16..e7c61ef8a3a 100644 --- a/packages/storage/__tests__/providers/s3/apis/copy.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/copy.test.ts @@ -164,7 +164,7 @@ describe('copy API', () => { ...(destination as CopyDestinationOptions), key: destinationKey, }, - }) + }), ).toEqual(copyResult); expect(copyObject).toHaveBeenCalledTimes(1); expect(copyObject).toHaveBeenCalledWith(copyObjectClientConfig, { @@ -173,7 +173,7 @@ describe('copy API', () => { Key: expectedDestinationKey, }); }); - } + }, ); }); @@ -186,7 +186,7 @@ describe('copy API', () => { Object.assign(new Error(), { $metadata: { httpStatusCode: 404 }, name: 'NotFound', - }) + }), ); expect.assertions(3); const sourceKey = 'SourceKeyNotFound'; diff --git a/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts b/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts index 9d894b45ddf..62f1704398b 100644 --- a/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/downloadData.test.ts @@ -114,7 +114,7 @@ describe('downloadData', () => { { Bucket: bucket, Key: expectedKey, - } + }, ); }); }); @@ -173,7 +173,7 @@ describe('downloadData', () => { expect.anything(), expect.objectContaining({ Range: `bytes=${start}-${end}`, - }) + }), ); }); }); diff --git a/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts b/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts index b10050156d9..6ee31b031ed 100644 --- a/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/getProperties.test.ts @@ -112,7 +112,7 @@ describe('getProperties api', () => { await getProperties({ key, options: options as GetPropertiesOptions, - }) + }), ).toEqual(expected); expect(headObject).toHaveBeenCalledTimes(1); expect(headObject).toHaveBeenCalledWith(config, headObjectOptions); @@ -129,7 +129,7 @@ describe('getProperties api', () => { Object.assign(new Error(), { $metadata: { httpStatusCode: 404 }, name: 'NotFound', - }) + }), ); expect.assertions(3); try { @@ -145,7 +145,7 @@ describe('getProperties api', () => { { Bucket: 'bucket', Key: 'public/keyed', - } + }, ); expect(error.$metadata.httpStatusCode).toBe(404); } diff --git a/packages/storage/__tests__/providers/s3/apis/list.test.ts b/packages/storage/__tests__/providers/s3/apis/list.test.ts index 6a615a7cd8e..681b4ff1af9 100644 --- a/packages/storage/__tests__/providers/s3/apis/list.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/list.test.ts @@ -252,7 +252,7 @@ describe('list API', () => { Prefix: expectedPath, MaxKeys: 1000, ContinuationToken: undefined, - } + }, ); // last input recieves TEST_TOKEN as the Continuation Token expect(listObjectsV2).toHaveBeenNthCalledWith( @@ -263,7 +263,7 @@ describe('list API', () => { Prefix: expectedPath, MaxKeys: 1000, ContinuationToken: nextToken, - } + }, ); }); }); @@ -278,7 +278,7 @@ describe('list API', () => { Object.assign(new Error(), { $metadata: { httpStatusCode: 404 }, name: 'NotFound', - }) + }), ); expect.assertions(3); try { diff --git a/packages/storage/__tests__/providers/s3/apis/remove.test.ts b/packages/storage/__tests__/providers/s3/apis/remove.test.ts index ccfba1e1a19..0f2e1a65b17 100644 --- a/packages/storage/__tests__/providers/s3/apis/remove.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/remove.test.ts @@ -86,7 +86,7 @@ describe('remove API', () => { it(`should remove object with ${accessLevel} accessLevel`, async () => { expect.assertions(3); expect( - await remove({ key, options: options as StorageOptions }) + await remove({ key, options: options as StorageOptions }), ).toEqual(removeResult); expect(deleteObject).toHaveBeenCalledTimes(1); expect(deleteObject).toHaveBeenCalledWith(deleteObjectClientConfig, { @@ -106,7 +106,7 @@ describe('remove API', () => { Object.assign(new Error(), { $metadata: { httpStatusCode: 404 }, name: 'NotFound', - }) + }), ); expect.assertions(3); const key = 'wrongKey'; diff --git a/packages/storage/__tests__/providers/s3/apis/uploadData/index.test.ts b/packages/storage/__tests__/providers/s3/apis/uploadData/index.test.ts index 95a59ac92e9..22569bf6671 100644 --- a/packages/storage/__tests__/providers/s3/apis/uploadData/index.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/uploadData/index.test.ts @@ -37,11 +37,11 @@ describe('uploadData', () => { uploadData({ key: 'key', data: { size: MAX_OBJECT_SIZE + 1 } as any, - }) + }), ).toThrow( expect.objectContaining( - validationErrorMap[StorageValidationErrorCode.ObjectIsTooLarge] - ) + validationErrorMap[StorageValidationErrorCode.ObjectIsTooLarge], + ), ); }); @@ -78,7 +78,7 @@ describe('uploadData', () => { job: 'putObjectJob', onCancel: expect.any(Function), isMultipartUpload: false, - }) + }), ); }); }); @@ -108,7 +108,7 @@ describe('uploadData', () => { onResume: expect.any(Function), onPause: expect.any(Function), isMultipartUpload: true, - }) + }), ); }); diff --git a/packages/storage/__tests__/providers/s3/apis/uploadData/multipartHandlers.test.ts b/packages/storage/__tests__/providers/s3/apis/uploadData/multipartHandlers.test.ts index d02dc5534e5..65b4dd473a6 100644 --- a/packages/storage/__tests__/providers/s3/apis/uploadData/multipartHandlers.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/uploadData/multipartHandlers.test.ts @@ -84,7 +84,7 @@ const mockMultipartUploadSuccess = (disableAssertion?: boolean) => { }; const mockMultipartUploadCancellation = ( - beforeUploadPartResponseCallback?: () => void + beforeUploadPartResponseCallback?: () => void, ) => { mockCreateMultipartUpload.mockImplementation(async ({ abortSignal }) => ({ UploadId: 'uploadId', @@ -143,7 +143,7 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, data: { size: 5 * 1024 * 1024 } as any, }, - 5 * 1024 * 1024 + 5 * 1024 * 1024, ); expect(multipartUploadHandlers).toEqual({ multipartUploadJob: expect.any(Function), @@ -199,15 +199,15 @@ describe('getMultipartUploadHandlers', () => { Bucket: bucket, Key: expectedKey, ContentType: defaultContentType, - }) + }), ); expect(result).toEqual( - expect.objectContaining({ key: defaultKey, eTag: 'etag' }) + expect.objectContaining({ key: defaultKey, eTag: 'etag' }), ); expect(mockCreateMultipartUpload).toHaveBeenCalledTimes(1); expect(mockUploadPart).toHaveBeenCalledTimes(2); expect(mockCompleteMultipartUpload).toHaveBeenCalledTimes(1); - } + }, ); }); @@ -219,8 +219,8 @@ describe('getMultipartUploadHandlers', () => { }); await expect(multipartUploadJob()).rejects.toThrow( expect.objectContaining( - validationErrorMap[StorageValidationErrorCode.InvalidUploadSource] - ) + validationErrorMap[StorageValidationErrorCode.InvalidUploadSource], + ), ); }); @@ -245,7 +245,7 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, data: file, }, - file.size + file.size, ); await multipartUploadJob(); expect(file.slice).toHaveBeenCalledTimes(10_000); // S3 limit of parts count @@ -268,14 +268,14 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, data: new ArrayBuffer(8 * MB), }, - 8 * MB + 8 * MB, ); try { await multipartUploadJob(); fail('should throw error'); } catch (e: any) { expect(e.message).toEqual( - `Upload failed. Expected object size ${8 * MB}, but got 1.` + `Upload failed. Expected object size ${8 * MB}, but got 1.`, ); } }); @@ -343,7 +343,7 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, data: new ArrayBuffer(size), }, - size + size, ); await multipartUploadJob(); // 1 for caching upload task; 1 for remove cache after upload is completed @@ -361,7 +361,7 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, lastTouched: Date.now() - 2 * 60 * 60 * 1000, // 2 hours ago }, - }) + }), ); mockMultipartUploadSuccess(); mockListParts.mockResolvedValueOnce({ Parts: [] }); @@ -371,7 +371,7 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, data: new ArrayBuffer(size), }, - size + size, ); await multipartUploadJob(); expect(mockCreateMultipartUpload).toHaveBeenCalledTimes(1); @@ -389,18 +389,18 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, data: new File([new ArrayBuffer(size)], 'someName'), }, - size + size, ); await multipartUploadJob(); // 1 for caching upload task; 1 for remove cache after upload is completed expect(mockDefaultStorage.setItem).toHaveBeenCalledTimes(2); const cacheValue = JSON.parse( - mockDefaultStorage.setItem.mock.calls[0][1] + mockDefaultStorage.setItem.mock.calls[0][1], ); expect(Object.keys(cacheValue)).toEqual([ expect.stringMatching( // \d{13} is the file lastModified property of a file - /someName_\d{13}_8388608_application\/octet-stream_bucket_public_key/ + /someName_\d{13}_8388608_application\/octet-stream_bucket_public_key/, ), ]); }); @@ -414,7 +414,7 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, lastModified: Date.now(), }, - }) + }), ); mockMultipartUploadSuccess(); mockListParts.mockResolvedValueOnce({ Parts: [] }); @@ -424,7 +424,7 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, data: new ArrayBuffer(size), }, - size + size, ); await multipartUploadJob(); expect(mockCreateMultipartUpload).not.toHaveBeenCalled(); @@ -442,20 +442,20 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, data: new ArrayBuffer(size), }, - size + size, ); await multipartUploadJob(); // 1 for caching upload task; 1 for remove cache after upload is completed expect(mockDefaultStorage.setItem).toHaveBeenCalledTimes(2); expect(mockDefaultStorage.setItem.mock.calls[0][0]).toEqual( - UPLOADS_STORAGE_KEY + UPLOADS_STORAGE_KEY, ); const cacheValue = JSON.parse( - mockDefaultStorage.setItem.mock.calls[0][1] + mockDefaultStorage.setItem.mock.calls[0][1], ); expect(Object.keys(cacheValue)).toEqual([ expect.stringMatching( - /8388608_application\/octet-stream_bucket_public_key/ + /8388608_application\/octet-stream_bucket_public_key/, ), ]); }); @@ -469,7 +469,7 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, data: new ArrayBuffer(size), }, - size + size, ); await multipartUploadJob(); // 1 for caching upload task; 1 for remove cache after upload is completed @@ -477,7 +477,7 @@ describe('getMultipartUploadHandlers', () => { expect(mockDefaultStorage.setItem).toHaveBeenNthCalledWith( 2, UPLOADS_STORAGE_KEY, - JSON.stringify({}) + JSON.stringify({}), ); }); @@ -491,7 +491,7 @@ describe('getMultipartUploadHandlers', () => { key: defaultKey, data: new ArrayBuffer(size), }, - size + size, ); const uploadJobPromise = multipartUploadJob(); await uploadJobPromise; @@ -500,7 +500,7 @@ describe('getMultipartUploadHandlers', () => { expect(mockDefaultStorage.setItem).toHaveBeenNthCalledWith( 2, UPLOADS_STORAGE_KEY, - JSON.stringify({}) + JSON.stringify({}), ); }); }); @@ -567,7 +567,7 @@ describe('getMultipartUploadHandlers', () => { onProgress, }, }, - 8 * MB + 8 * MB, ); await multipartUploadJob(); expect(onProgress).toHaveBeenCalledTimes(4); // 2 simulated onProgress events per uploadPart call are all tracked @@ -602,7 +602,7 @@ describe('getMultipartUploadHandlers', () => { bucket, key: defaultKey, }, - }) + }), ); mockListParts.mockResolvedValue({ Parts: [{ PartNumber: 1 }], @@ -617,7 +617,7 @@ describe('getMultipartUploadHandlers', () => { onProgress, }, }, - 8 * MB + 8 * MB, ); await multipartUploadJob(); expect(onProgress).toHaveBeenCalledTimes(3); diff --git a/packages/storage/__tests__/providers/s3/apis/uploadData/putObjectJob.test.ts b/packages/storage/__tests__/providers/s3/apis/uploadData/putObjectJob.test.ts index 93679f794b1..cc61a4e2bd6 100644 --- a/packages/storage/__tests__/providers/s3/apis/uploadData/putObjectJob.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/uploadData/putObjectJob.test.ts @@ -78,7 +78,7 @@ describe('putObjectJob', () => { useAccelerateEndpoint, }, }, - abortController.signal + abortController.signal, ); const result = await job(); expect(result).toEqual({ @@ -107,7 +107,7 @@ describe('putObjectJob', () => { ContentEncoding: contentEncoding, Metadata: metadata, ContentMD5: undefined, - } + }, ); }); @@ -124,7 +124,7 @@ describe('putObjectJob', () => { key: 'key', data: 'data', }, - new AbortController().signal + new AbortController().signal, ); await job(); expect(calculateContentMd5).toHaveBeenCalledWith('data'); diff --git a/packages/storage/__tests__/providers/s3/apis/utils/downloadTask.test.ts b/packages/storage/__tests__/providers/s3/apis/utils/downloadTask.test.ts index 771817cbb0a..4220759724f 100644 --- a/packages/storage/__tests__/providers/s3/apis/utils/downloadTask.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/utils/downloadTask.test.ts @@ -72,6 +72,6 @@ describe('createDownloadTask', () => { task.cancel(); expect(onCancel).not.toHaveBeenCalled(); expect(task.state).toBe(state); - } + }, ); }); diff --git a/packages/storage/__tests__/providers/s3/apis/utils/resolvePrefix.test.ts b/packages/storage/__tests__/providers/s3/apis/utils/resolvePrefix.test.ts index a97ade3bc86..0d728e4e4d2 100644 --- a/packages/storage/__tests__/providers/s3/apis/utils/resolvePrefix.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/utils/resolvePrefix.test.ts @@ -38,7 +38,7 @@ describe('resolvePrefix', () => { }); } catch (error) { expect(error).toMatchObject( - validationErrorMap[StorageValidationErrorCode.NoIdentityId] + validationErrorMap[StorageValidationErrorCode.NoIdentityId], ); } }); @@ -50,7 +50,7 @@ describe('resolvePrefix', () => { }); } catch (error) { expect(error).toMatchObject( - validationErrorMap[StorageValidationErrorCode.NoIdentityId] + validationErrorMap[StorageValidationErrorCode.NoIdentityId], ); } }); diff --git a/packages/storage/__tests__/providers/s3/apis/utils/resolveS3ConfigAndInput.test.ts b/packages/storage/__tests__/providers/s3/apis/utils/resolveS3ConfigAndInput.test.ts index 9a15b06e141..5db56bed1ed 100644 --- a/packages/storage/__tests__/providers/s3/apis/utils/resolveS3ConfigAndInput.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/utils/resolveS3ConfigAndInput.test.ts @@ -65,7 +65,7 @@ describe('resolveS3ConfigAndInput', () => { identityId: targetIdentityId, }); await expect(resolveS3ConfigAndInput(Amplify, {})).rejects.toMatchObject( - validationErrorMap[StorageValidationErrorCode.NoCredentials] + validationErrorMap[StorageValidationErrorCode.NoCredentials], ); }); @@ -74,14 +74,14 @@ describe('resolveS3ConfigAndInput', () => { credentials, }); await expect(resolveS3ConfigAndInput(Amplify, {})).rejects.toMatchObject( - validationErrorMap[StorageValidationErrorCode.NoIdentityId] + validationErrorMap[StorageValidationErrorCode.NoIdentityId], ); }); it('should resolve bucket from S3 config', async () => { const { bucket: resolvedBucket } = await resolveS3ConfigAndInput( Amplify, - {} + {}, ); expect(resolvedBucket).toEqual(bucket); expect(mockGetConfig).toHaveBeenCalled(); @@ -96,7 +96,7 @@ describe('resolveS3ConfigAndInput', () => { }, }); await expect(resolveS3ConfigAndInput(Amplify, {})).rejects.toMatchObject( - validationErrorMap[StorageValidationErrorCode.NoBucket] + validationErrorMap[StorageValidationErrorCode.NoBucket], ); }); @@ -115,7 +115,7 @@ describe('resolveS3ConfigAndInput', () => { }, }); await expect(resolveS3ConfigAndInput(Amplify, {})).rejects.toMatchObject( - validationErrorMap[StorageValidationErrorCode.NoRegion] + validationErrorMap[StorageValidationErrorCode.NoRegion], ); }); diff --git a/packages/storage/__tests__/providers/s3/apis/utils/uploadTask.test.ts b/packages/storage/__tests__/providers/s3/apis/utils/uploadTask.test.ts index 99d92c82a0b..1eeacb61f85 100644 --- a/packages/storage/__tests__/providers/s3/apis/utils/uploadTask.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/utils/uploadTask.test.ts @@ -73,7 +73,7 @@ describe('createUploadTask', () => { task.cancel(); expect(onCancel).not.toHaveBeenCalled(); expect(task.state).toBe(state); - } + }, ); it('should call the onPause callback if the task is in status of IN_PROGRESS', () => { @@ -106,7 +106,7 @@ describe('createUploadTask', () => { task.pause(); expect(onPause).not.toHaveBeenCalled(); expect(task.state).toBe(state); - } + }, ); it('should call the onResume callback if the task is in status of PAUSED', () => { @@ -140,6 +140,6 @@ describe('createUploadTask', () => { task.resume(); expect(onResume).not.toHaveBeenCalled(); expect(task.state).toBe(state); - } + }, ); }); diff --git a/packages/storage/__tests__/providers/s3/utils/client/S3/cases/getObject.ts b/packages/storage/__tests__/providers/s3/utils/client/S3/cases/getObject.ts index 0506b02d876..7893c045924 100644 --- a/packages/storage/__tests__/providers/s3/utils/client/S3/cases/getObject.ts +++ b/packages/storage/__tests__/providers/s3/utils/client/S3/cases/getObject.ts @@ -127,7 +127,7 @@ const getObjectHappyCase: ApiFunctionalTestCase = [ TagCount: Number(getObjectResponseHeaders['x-amz-tagging-count']), ObjectLockMode: getObjectResponseHeaders['x-amz-object-lock-mode'], ObjectLockRetainUntilDate: new Date( - getObjectResponseHeaders['x-amz-object-lock-retain-until-date'] + getObjectResponseHeaders['x-amz-object-lock-retain-until-date'], ), ObjectLockLegalHoldStatus: getObjectResponseHeaders['x-amz-object-lock-legal-hold'], diff --git a/packages/storage/__tests__/providers/s3/utils/client/S3/functional-apis.test.ts b/packages/storage/__tests__/providers/s3/utils/client/S3/functional-apis.test.ts index 0bcbab879ba..d625218a6fc 100644 --- a/packages/storage/__tests__/providers/s3/utils/client/S3/functional-apis.test.ts +++ b/packages/storage/__tests__/providers/s3/utils/client/S3/functional-apis.test.ts @@ -8,7 +8,7 @@ import cases from './cases'; import { StorageError } from '../../../../../../src/errors/StorageError'; jest.mock( - '../../../../../../src/providers/s3/utils/client/runtime/s3TransferHandler/fetch' + '../../../../../../src/providers/s3/utils/client/runtime/s3TransferHandler/fetch', ); const mockS3TransferHandler = s3TransferHandler as jest.Mock; @@ -24,7 +24,7 @@ const mockBinaryResponse = ({ const responseBody = { json: async (): Promise => { throw new Error( - 'Parsing response to JSON is not implemented. Please use response.text() instead.' + 'Parsing response to JSON is not implemented. Please use response.text() instead.', ); }, blob: async () => new Blob([body], { type: 'plain/text' }), @@ -51,11 +51,11 @@ describe('S3 APIs functional test', () => { input, expectedRequest, response, - outputOrError + outputOrError, ) => { expect.assertions(2); mockS3TransferHandler.mockResolvedValue( - mockBinaryResponse(response as any) + mockBinaryResponse(response as any), ); try { const output = await handler(config, input as any); @@ -63,7 +63,7 @@ describe('S3 APIs functional test', () => { expect(output).toEqual(outputOrError); expect(mockS3TransferHandler).toHaveBeenCalledWith( expectedRequest, - expect.anything() + expect.anything(), ); } else { fail(`${name} ${caseType} should fail`); @@ -76,6 +76,6 @@ describe('S3 APIs functional test', () => { expect(e).toEqual(expect.objectContaining(outputOrError)); } } - } + }, ); }); diff --git a/packages/storage/__tests__/providers/s3/utils/client/S3/getPresignedGetObjectUrl.test.ts b/packages/storage/__tests__/providers/s3/utils/client/S3/getPresignedGetObjectUrl.test.ts index 71c50663fc1..0108bd37084 100644 --- a/packages/storage/__tests__/providers/s3/utils/client/S3/getPresignedGetObjectUrl.test.ts +++ b/packages/storage/__tests__/providers/s3/utils/client/S3/getPresignedGetObjectUrl.test.ts @@ -7,7 +7,7 @@ import { defaultConfig } from './cases/shared'; jest.mock('@aws-amplify/core/internals/aws-client-utils', () => { const original = jest.requireActual( - '@aws-amplify/core/internals/aws-client-utils' + '@aws-amplify/core/internals/aws-client-utils', ); const presignUrl = original.presignUrl; @@ -32,16 +32,16 @@ describe('serializeGetObjectRequest', () => { { Bucket: 'bucket', Key: 'key', - } + }, ); const actualUrl = actual; expect(actualUrl.hostname).toEqual( - `bucket.s3.${defaultConfig.region}.amazonaws.com` + `bucket.s3.${defaultConfig.region}.amazonaws.com`, ); expect(actualUrl.pathname).toEqual('/key'); expect(actualUrl.searchParams.get('X-Amz-Expires')).toEqual('900'); expect(actualUrl.searchParams.get('x-amz-content-sha256')).toEqual( - expect.any(String) + expect.any(String), ); expect(actualUrl.searchParams.get('x-amz-user-agent')).toEqual('UA'); }); @@ -58,14 +58,14 @@ describe('serializeGetObjectRequest', () => { { Bucket: 'bucket', Key: 'key', - } + }, ); expect(mockPresignUrl).toHaveBeenCalledWith( expect.anything(), expect.objectContaining({ uriEscapePath: false, - }) + }), ); }); }); diff --git a/packages/storage/__tests__/providers/s3/utils/client/testUtils/mocks.ts b/packages/storage/__tests__/providers/s3/utils/client/testUtils/mocks.ts index baf139f67a5..cec66b98cce 100644 --- a/packages/storage/__tests__/providers/s3/utils/client/testUtils/mocks.ts +++ b/packages/storage/__tests__/providers/s3/utils/client/testUtils/mocks.ts @@ -48,7 +48,7 @@ export const mockXhrResponse = ( // XHR's raw header string. @see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders#return_value headerString: string; body: Blob | string; - } + }, ) => { mockXhr.readyState = XMLHttpRequest.DONE; mockXhr.status = response.status; @@ -58,14 +58,14 @@ export const mockXhrResponse = ( return response.body as string; } throw new Error( - `Cannot read responseText when responseType is ${mockXhr.responseType}` + `Cannot read responseText when responseType is ${mockXhr.responseType}`, ); }, configurable: true, }); mockXhr.response = response.body; (mockXhr.getAllResponseHeaders as jest.Mock).mockReturnValue( - response.headerString + response.headerString, ); mockXhr.listeners.readystatechange?.forEach(cb => { cb({} as any); diff --git a/packages/storage/__tests__/providers/s3/utils/client/xhrTransferHandler-util.test.ts b/packages/storage/__tests__/providers/s3/utils/client/xhrTransferHandler-util.test.ts index 58d45fbd2c2..ab28eae4a5b 100644 --- a/packages/storage/__tests__/providers/s3/utils/client/xhrTransferHandler-util.test.ts +++ b/packages/storage/__tests__/providers/s3/utils/client/xhrTransferHandler-util.test.ts @@ -41,7 +41,7 @@ describe('xhrTransferHandler', () => { jest.fn().mockImplementation(() => { return new originalFileReaderCtor(); }), - { ...originalFileReaderCtor } + { ...originalFileReaderCtor }, ); }); @@ -60,7 +60,7 @@ describe('xhrTransferHandler', () => { await requestPromise; expect(mockXhr.open).toHaveBeenCalledWith( defaultRequest.method, - defaultRequest.url.toString() + defaultRequest.url.toString(), ); }); @@ -76,7 +76,7 @@ describe('xhrTransferHandler', () => { }, { responseType: 'text', - } + }, ); mockXhrResponse(mockXhr, mock200Response); await requestPromise; @@ -110,7 +110,7 @@ describe('xhrTransferHandler', () => { }, { responseType: 'text', - } + }, ); mockXhrResponse(mockXhr, mock200Response); await requestPromise; @@ -127,8 +127,8 @@ describe('xhrTransferHandler', () => { }, { responseType: 'text', - } - ) + }, + ), ).rejects.toThrow('ReadableStream request payload is not supported.'); }); @@ -141,7 +141,7 @@ describe('xhrTransferHandler', () => { }, { responseType: 'text', - } + }, ); mockXhrResponse(mockXhr, mock200Response); await requestPromise; @@ -197,7 +197,7 @@ describe('xhrTransferHandler', () => { expect.objectContaining({ message: 'Network Error', name: 'ECONNABORTED', - }) + }), ); }); @@ -211,7 +211,7 @@ describe('xhrTransferHandler', () => { expect.objectContaining({ message: 'Network Error', name: 'ECONNABORTED', - }) + }), ); // Should be no-op if the xhr is already cleared mockXhrResponse(mockXhr, mock200Response); @@ -264,7 +264,7 @@ describe('xhrTransferHandler', () => { expect.objectContaining({ message: 'Request aborted', name: 'ERR_ABORTED', - }) + }), ); }); @@ -278,7 +278,7 @@ describe('xhrTransferHandler', () => { expect.objectContaining({ message: 'Request aborted', name: 'ERR_ABORTED', - }) + }), ); // Should be no-op if the xhr is already cleared mockXhrResponse(mockXhr, mock200Response); @@ -336,9 +336,9 @@ describe('xhrTransferHandler', () => { await expect(body!.json()).rejects.toThrow( expect.objectContaining({ message: expect.stringContaining( - 'Parsing response to JSON is not implemented.' + 'Parsing response to JSON is not implemented.', ), - }) + }), ); }); diff --git a/packages/storage/src/errors/utils/assertValidationError.ts b/packages/storage/src/errors/utils/assertValidationError.ts index aab418634a2..97d6265a16b 100644 --- a/packages/storage/src/errors/utils/assertValidationError.ts +++ b/packages/storage/src/errors/utils/assertValidationError.ts @@ -9,7 +9,7 @@ import { StorageError } from '../StorageError'; export function assertValidationError( assertion: boolean, - name: StorageValidationErrorCode + name: StorageValidationErrorCode, ): asserts assertion { const { message, recoverySuggestion } = validationErrorMap[name]; diff --git a/packages/storage/src/providers/s3/apis/downloadData.ts b/packages/storage/src/providers/s3/apis/downloadData.ts index 281f73a7456..2af97220d24 100644 --- a/packages/storage/src/providers/s3/apis/downloadData.ts +++ b/packages/storage/src/providers/s3/apis/downloadData.ts @@ -57,12 +57,12 @@ export const downloadData = (input: DownloadDataInput): DownloadDataOutput => { const downloadDataJob = ( { options: downloadDataOptions, key }: DownloadDataInput, - abortSignal: AbortSignal + abortSignal: AbortSignal, ) => async () => { const { bucket, keyPrefix, s3Config } = await resolveS3ConfigAndInput( Amplify, - downloadDataOptions + downloadDataOptions, ); const finalKey = keyPrefix + key; @@ -89,7 +89,7 @@ const downloadDataJob = ...(downloadDataOptions?.bytesRange && { Range: `bytes=${downloadDataOptions.bytesRange.start}-${downloadDataOptions.bytesRange.end}`, }), - } + }, ); return { key, diff --git a/packages/storage/src/providers/s3/apis/getProperties.ts b/packages/storage/src/providers/s3/apis/getProperties.ts index 7f012d3f2be..7d3f9765e37 100644 --- a/packages/storage/src/providers/s3/apis/getProperties.ts +++ b/packages/storage/src/providers/s3/apis/getProperties.ts @@ -15,7 +15,7 @@ import { getProperties as getPropertiesInternal } from './internal/getProperties * @throws A {@link StorageValidationErrorCode} when API call parameters are invalid. */ export const getProperties = ( - input: GetPropertiesInput + input: GetPropertiesInput, ): Promise => { return getPropertiesInternal(Amplify, input); }; diff --git a/packages/storage/src/providers/s3/apis/internal/copy.ts b/packages/storage/src/providers/s3/apis/internal/copy.ts index 47afbc9107e..a5c0f3b159d 100644 --- a/packages/storage/src/providers/s3/apis/internal/copy.ts +++ b/packages/storage/src/providers/s3/apis/internal/copy.ts @@ -13,7 +13,7 @@ import { logger } from '../../../../utils'; export const copy = async ( amplify: AmplifyClassV6, - input: CopyInput + input: CopyInput, ): Promise => { const { source: { key: sourceKey }, @@ -23,7 +23,7 @@ export const copy = async ( assertValidationError(!!sourceKey, StorageValidationErrorCode.NoSourceKey); assertValidationError( !!destinationKey, - StorageValidationErrorCode.NoDestinationKey + StorageValidationErrorCode.NoDestinationKey, ); const { @@ -33,7 +33,7 @@ export const copy = async ( } = await resolveS3ConfigAndInput(amplify, input.source); const { keyPrefix: destinationKeyPrefix } = await resolveS3ConfigAndInput( amplify, - input.destination + input.destination, ); // resolveS3ConfigAndInput does not make extra API calls or storage access if called repeatedly. // TODO(ashwinkumar6) V6-logger: warn `You may copy files from another user if the source level is "protected", currently it's ${srcLevel}` @@ -50,7 +50,7 @@ export const copy = async ( CopySource: finalCopySource, Key: finalCopyDestination, MetadataDirective: 'COPY', // Copies over metadata like contentType as well - } + }, ); return { diff --git a/packages/storage/src/providers/s3/apis/internal/getProperties.ts b/packages/storage/src/providers/s3/apis/internal/getProperties.ts index cd75852b38f..b0343e1ff64 100644 --- a/packages/storage/src/providers/s3/apis/internal/getProperties.ts +++ b/packages/storage/src/providers/s3/apis/internal/getProperties.ts @@ -12,12 +12,12 @@ import { logger } from '../../../../utils'; export const getProperties = async function ( amplify: AmplifyClassV6, input: GetPropertiesInput, - action?: StorageAction + action?: StorageAction, ): Promise { const { key, options } = input; const { s3Config, bucket, keyPrefix } = await resolveS3ConfigAndInput( amplify, - options + options, ); const finalKey = `${keyPrefix}${key}`; @@ -26,13 +26,13 @@ export const getProperties = async function ( { ...s3Config, userAgentValue: getStorageUserAgentValue( - action ?? StorageAction.GetProperties + action ?? StorageAction.GetProperties, ), }, { Bucket: bucket, Key: finalKey, - } + }, ); return { key, diff --git a/packages/storage/src/providers/s3/apis/internal/getUrl.ts b/packages/storage/src/providers/s3/apis/internal/getUrl.ts index 5f6fb0ed81d..24cd799983a 100644 --- a/packages/storage/src/providers/s3/apis/internal/getUrl.ts +++ b/packages/storage/src/providers/s3/apis/internal/getUrl.ts @@ -16,7 +16,7 @@ import { StorageAction } from '@aws-amplify/core/internals/utils'; export const getUrl = async function ( amplify: AmplifyClassV6, - input: GetUrlInput + input: GetUrlInput, ): Promise { const { key, options } = input; @@ -26,21 +26,21 @@ export const getUrl = async function ( const { s3Config, keyPrefix, bucket } = await resolveS3ConfigAndInput( amplify, - options + options, ); let urlExpirationInSec = options?.expiresIn ?? DEFAULT_PRESIGN_EXPIRATION; const awsCredExpiration = s3Config.credentials?.expiration; if (awsCredExpiration) { const awsCredExpirationInSec = Math.floor( - (awsCredExpiration.getTime() - Date.now()) / 1000 + (awsCredExpiration.getTime() - Date.now()) / 1000, ); urlExpirationInSec = Math.min(awsCredExpirationInSec, urlExpirationInSec); } const maxUrlExpirationInSec = MAX_URL_EXPIRATION / 1000; assertValidationError( urlExpirationInSec <= maxUrlExpirationInSec, - StorageValidationErrorCode.UrlExpirationMaxLimitExceed + StorageValidationErrorCode.UrlExpirationMaxLimitExceed, ); // expiresAt is the minimum of credential expiration and url expiration @@ -53,7 +53,7 @@ export const getUrl = async function ( { Bucket: bucket, Key: `${keyPrefix}${key}`, - } + }, ), expiresAt: new Date(Date.now() + urlExpirationInSec * 1000), }; diff --git a/packages/storage/src/providers/s3/apis/internal/list.ts b/packages/storage/src/providers/s3/apis/internal/list.ts index 1e90565e6a9..15b6ed43cab 100644 --- a/packages/storage/src/providers/s3/apis/internal/list.ts +++ b/packages/storage/src/providers/s3/apis/internal/list.ts @@ -30,7 +30,7 @@ type ListInputArgs = { export const list = async ( amplify: AmplifyClassV6, - input?: ListAllInput | ListPaginateInput + input?: ListAllInput | ListPaginateInput, ): Promise => { const { options = {}, prefix: path = '' } = input ?? {}; const { @@ -44,7 +44,7 @@ export const list = async ( logger.debug( `listAll is set to true, ignoring ${ anyOptions?.pageSize ? `pageSize: ${anyOptions?.pageSize}` : '' - } ${anyOptions?.nextToken ? `nextToken: ${anyOptions?.nextToken}` : ''}.` + } ${anyOptions?.nextToken ? `nextToken: ${anyOptions?.nextToken}` : ''}.`, ); } const listParams = { @@ -101,7 +101,7 @@ const _list = async ({ ...s3Config, userAgentValue: getStorageUserAgentValue(StorageAction.List), }, - listParamsClone + listParamsClone, ); if (!response?.Contents) { diff --git a/packages/storage/src/providers/s3/apis/internal/remove.ts b/packages/storage/src/providers/s3/apis/internal/remove.ts index f942f1a180a..f1283df9c29 100644 --- a/packages/storage/src/providers/s3/apis/internal/remove.ts +++ b/packages/storage/src/providers/s3/apis/internal/remove.ts @@ -11,12 +11,12 @@ import { logger } from '../../../../utils'; export const remove = async ( amplify: AmplifyClassV6, - input: RemoveInput + input: RemoveInput, ): Promise => { const { key, options = {} } = input; const { s3Config, keyPrefix, bucket } = await resolveS3ConfigAndInput( amplify, - options + options, ); const finalKey = `${keyPrefix}${key}`; @@ -29,7 +29,7 @@ export const remove = async ( { Bucket: bucket, Key: finalKey, - } + }, ); return { key, diff --git a/packages/storage/src/providers/s3/apis/list.ts b/packages/storage/src/providers/s3/apis/list.ts index a1a7f3e5458..24c0e751f05 100644 --- a/packages/storage/src/providers/s3/apis/list.ts +++ b/packages/storage/src/providers/s3/apis/list.ts @@ -31,7 +31,7 @@ type ListApi = { }; export const list: ListApi = ( - input?: ListAllInput | ListPaginateInput + input?: ListAllInput | ListPaginateInput, ): Promise => { return listInternal(Amplify, input ?? {}); }; diff --git a/packages/storage/src/providers/s3/apis/server/copy.ts b/packages/storage/src/providers/s3/apis/server/copy.ts index ea8e9de90f8..b17e5ab7a52 100644 --- a/packages/storage/src/providers/s3/apis/server/copy.ts +++ b/packages/storage/src/providers/s3/apis/server/copy.ts @@ -10,7 +10,7 @@ import { copy as copyInternal } from '../internal/copy'; export const copy = async ( contextSpec: AmplifyServer.ContextSpec, - input: CopyInput + input: CopyInput, ): Promise => { return copyInternal(getAmplifyServerContext(contextSpec).amplify, input); }; diff --git a/packages/storage/src/providers/s3/apis/server/getProperties.ts b/packages/storage/src/providers/s3/apis/server/getProperties.ts index c26bf24f502..e54536b4e54 100644 --- a/packages/storage/src/providers/s3/apis/server/getProperties.ts +++ b/packages/storage/src/providers/s3/apis/server/getProperties.ts @@ -10,10 +10,10 @@ import { getProperties as getPropertiesInternal } from '../internal/getPropertie export const getProperties = ( contextSpec: AmplifyServer.ContextSpec, - input: GetPropertiesInput + input: GetPropertiesInput, ): Promise => { return getPropertiesInternal( getAmplifyServerContext(contextSpec).amplify, - input + input, ); }; diff --git a/packages/storage/src/providers/s3/apis/server/getUrl.ts b/packages/storage/src/providers/s3/apis/server/getUrl.ts index 7b6cc802cbe..b1913de0bdb 100644 --- a/packages/storage/src/providers/s3/apis/server/getUrl.ts +++ b/packages/storage/src/providers/s3/apis/server/getUrl.ts @@ -10,7 +10,7 @@ import { getUrl as getUrlInternal } from '../internal/getUrl'; export const getUrl = async ( contextSpec: AmplifyServer.ContextSpec, - input: GetUrlInput + input: GetUrlInput, ): Promise => { return getUrlInternal(getAmplifyServerContext(contextSpec).amplify, input); }; diff --git a/packages/storage/src/providers/s3/apis/server/list.ts b/packages/storage/src/providers/s3/apis/server/list.ts index 970301c1622..0bf46b11ca0 100644 --- a/packages/storage/src/providers/s3/apis/server/list.ts +++ b/packages/storage/src/providers/s3/apis/server/list.ts @@ -24,7 +24,7 @@ type ListApi = { */ ( contextSpec: AmplifyServer.ContextSpec, - input?: ListPaginateInput + input?: ListPaginateInput, ): Promise; /** * Lists all bucket objects. @@ -35,16 +35,16 @@ type ListApi = { */ ( contextSpec: AmplifyServer.ContextSpec, - input?: ListAllInput + input?: ListAllInput, ): Promise; }; export const list: ListApi = ( contextSpec: AmplifyServer.ContextSpec, - input?: ListAllInput | ListPaginateInput + input?: ListAllInput | ListPaginateInput, ): Promise => { return listInternal( getAmplifyServerContext(contextSpec).amplify, - input ?? {} + input ?? {}, ); }; diff --git a/packages/storage/src/providers/s3/apis/server/remove.ts b/packages/storage/src/providers/s3/apis/server/remove.ts index d54d0687333..f6a1fcca364 100644 --- a/packages/storage/src/providers/s3/apis/server/remove.ts +++ b/packages/storage/src/providers/s3/apis/server/remove.ts @@ -10,7 +10,7 @@ import { remove as removeInternal } from '../internal/remove'; export const remove = ( contextSpec: AmplifyServer.ContextSpec, - input: RemoveInput + input: RemoveInput, ): Promise => { return removeInternal(getAmplifyServerContext(contextSpec).amplify, input); }; diff --git a/packages/storage/src/providers/s3/apis/uploadData/index.ts b/packages/storage/src/providers/s3/apis/uploadData/index.ts index ad43972d46b..c2096366ea0 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/index.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/index.ts @@ -64,7 +64,7 @@ export const uploadData = (input: UploadDataInput): UploadDataOutput => { const dataByteLength = byteLength(data); assertValidationError( dataByteLength === undefined || dataByteLength <= MAX_OBJECT_SIZE, - StorageValidationErrorCode.ObjectIsTooLarge + StorageValidationErrorCode.ObjectIsTooLarge, ); if (dataByteLength && dataByteLength <= DEFAULT_PART_SIZE) { diff --git a/packages/storage/src/providers/s3/apis/uploadData/multipart/getDataChunker.ts b/packages/storage/src/providers/s3/apis/uploadData/multipart/getDataChunker.ts index 4289152bb91..72fc9cf7e54 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/multipart/getDataChunker.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/multipart/getDataChunker.ts @@ -17,7 +17,7 @@ export type PartToUpload = { export const getDataChunker = ( data: StorageUploadDataPayload, - totalSize?: number + totalSize?: number, ): Generator => { const partSize = calculatePartSize(totalSize); @@ -42,7 +42,7 @@ const helper = function* ( buffer: ArrayBuffer | Blob, byteOffset: number, byteLength: number, - partSize: number + partSize: number, ): Generator { let partNumber = 1; let startByte = byteOffset; diff --git a/packages/storage/src/providers/s3/apis/uploadData/multipart/initialUpload.ts b/packages/storage/src/providers/s3/apis/uploadData/multipart/initialUpload.ts index c7b8f64dfc6..a0f432a87a0 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/multipart/initialUpload.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/multipart/initialUpload.ts @@ -103,7 +103,7 @@ export const loadOrCreateMultipartUpload = async ({ ContentDisposition: contentDisposition, ContentEncoding: contentEncoding, Metadata: metadata, - } + }, ); if (size === undefined) { logger.debug('uploaded data size cannot be determined, skipping cache.'); diff --git a/packages/storage/src/providers/s3/apis/uploadData/multipart/progressTracker.ts b/packages/storage/src/providers/s3/apis/uploadData/multipart/progressTracker.ts index 58e19c439b7..bf73adbec7b 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/multipart/progressTracker.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/multipart/progressTracker.ts @@ -22,7 +22,7 @@ export const getConcurrentUploadsProgressTracker = ({ const getTransferredBytes = () => transferredBytesPerListener.reduce( (acc, transferredBytes) => acc + transferredBytes, - 0 + 0, ); return { diff --git a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadCache.ts b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadCache.ts index 251b5a1bf60..6f6eb050e6e 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadCache.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadCache.ts @@ -47,7 +47,7 @@ export const findCachedUploadParts = async ({ await defaultStorage.setItem( UPLOADS_STORAGE_KEY, - JSON.stringify(cachedUploads) + JSON.stringify(cachedUploads), ); try { @@ -77,7 +77,7 @@ type FileMetadata = { }; const listCachedUploadTasks = async ( - kvStorage: KeyValueStorageInterface + kvStorage: KeyValueStorageInterface, ): Promise> => { try { return JSON.parse((await kvStorage.getItem(UPLOADS_STORAGE_KEY)) ?? '{}'); @@ -122,7 +122,7 @@ export const getUploadsCacheKey = ({ export const cacheMultipartUpload = async ( cacheKey: string, - fileMetadata: Omit + fileMetadata: Omit, ): Promise => { const cachedUploads = await listCachedUploadTasks(defaultStorage); cachedUploads[cacheKey] = { @@ -131,7 +131,7 @@ export const cacheMultipartUpload = async ( }; await defaultStorage.setItem( UPLOADS_STORAGE_KEY, - JSON.stringify(cachedUploads) + JSON.stringify(cachedUploads), ); }; @@ -140,6 +140,6 @@ export const removeCachedUpload = async (cacheKey: string): Promise => { delete cachedUploads[cacheKey]; await defaultStorage.setItem( UPLOADS_STORAGE_KEY, - JSON.stringify(cachedUploads) + JSON.stringify(cachedUploads), ); }; diff --git a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadHandlers.ts b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadHandlers.ts index bd560fc0406..3d53ceadae1 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadHandlers.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadHandlers.ts @@ -36,7 +36,7 @@ import { logger } from '../../../../../utils'; */ export const getMultipartUploadHandlers = ( { options: uploadDataOptions, key, data }: UploadDataInput, - size?: number + size?: number, ) => { let resolveCallback: ((value: S3Item) => void) | undefined; let rejectCallback: ((reason?: any) => void) | undefined; @@ -59,7 +59,7 @@ export const getMultipartUploadHandlers = ( const startUpload = async (): Promise => { const resolvedS3Options = await resolveS3ConfigAndInput( Amplify, - uploadDataOptions + uploadDataOptions, ); s3Config = resolvedS3Options.s3Config; bucket = resolvedS3Options.bucket; @@ -107,12 +107,12 @@ export const getMultipartUploadHandlers = ( bucket: bucket!, size, key, - }) + }) : undefined; const dataChunker = getDataChunker(data, size); const completedPartNumberSet = new Set( - inProgressUpload.completedParts.map(({ PartNumber }) => PartNumber!) + inProgressUpload.completedParts.map(({ PartNumber }) => PartNumber!), ); const onPartUploadCompletion = (partNumber: number, eTag: string) => { inProgressUpload?.completedParts.push({ @@ -140,7 +140,7 @@ export const getMultipartUploadHandlers = ( onPartUploadCompletion, onProgress: concurrentUploadsProgressTracker.getOnProgressListener(), isObjectLockEnabled: resolvedS3Options.isObjectLockEnabled, - }) + }), ); } @@ -158,10 +158,10 @@ export const getMultipartUploadHandlers = ( UploadId: inProgressUpload.uploadId, MultipartUpload: { Parts: inProgressUpload.completedParts.sort( - (partA, partB) => partA.PartNumber! - partB.PartNumber! + (partA, partB) => partA.PartNumber! - partB.PartNumber!, ), }, - } + }, ); if (size) { @@ -238,7 +238,7 @@ export const getMultipartUploadHandlers = ( rejectCallback!( // Internal error that should not be exposed to the users. They should use isCancelError() to check if // the error is caused by cancel(). - new CanceledError(message ? { message } : undefined) + new CanceledError(message ? { message } : undefined), ); }; return { diff --git a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadPartExecutor.ts b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadPartExecutor.ts index b8c2b7f43c1..71801fe1a23 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadPartExecutor.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/multipart/uploadPartExecutor.ts @@ -68,7 +68,7 @@ export const uploadPartExecutor = async ({ ContentMD5: isObjectLockEnabled ? await calculateContentMd5(data) : undefined, - } + }, ); transferredBytes += size; // eTag will always be set even the S3 model interface marks it as optional. diff --git a/packages/storage/src/providers/s3/apis/uploadData/putObjectJob.ts b/packages/storage/src/providers/s3/apis/uploadData/putObjectJob.ts index 0842197acf8..5d1a40786ad 100644 --- a/packages/storage/src/providers/s3/apis/uploadData/putObjectJob.ts +++ b/packages/storage/src/providers/s3/apis/uploadData/putObjectJob.ts @@ -19,7 +19,7 @@ export const putObjectJob = ( { options: uploadDataOptions, key, data }: UploadDataInput, abortSignal: AbortSignal, - totalLength?: number + totalLength?: number, ) => async (): Promise => { const { bucket, keyPrefix, s3Config, isObjectLockEnabled } = @@ -52,7 +52,7 @@ export const putObjectJob = ContentMD5: isObjectLockEnabled ? await calculateContentMd5(data) : undefined, - } + }, ); return { diff --git a/packages/storage/src/providers/s3/utils/client/abortMultipartUpload.ts b/packages/storage/src/providers/s3/utils/client/abortMultipartUpload.ts index 301092613ac..72463961c96 100644 --- a/packages/storage/src/providers/s3/utils/client/abortMultipartUpload.ts +++ b/packages/storage/src/providers/s3/utils/client/abortMultipartUpload.ts @@ -33,7 +33,7 @@ export type AbortMultipartUploadOutput = MetadataBearer; const abortMultipartUploadSerializer = ( input: AbortMultipartUploadInput, - endpoint: Endpoint + endpoint: Endpoint, ): HttpRequest => { const url = new AmplifyUrl(endpoint.url.toString()); validateS3RequiredParameter(!!input.Key, 'Key'); @@ -50,7 +50,7 @@ const abortMultipartUploadSerializer = ( }; const abortMultipartUploadDeserializer = async ( - response: HttpResponse + response: HttpResponse, ): Promise => { if (response.statusCode >= 300) { const error = (await parseXmlError(response)) as Error; @@ -66,5 +66,5 @@ export const abortMultipartUpload = composeServiceApi( s3TransferHandler, abortMultipartUploadSerializer, abortMultipartUploadDeserializer, - { ...defaultConfig, responseType: 'text' } + { ...defaultConfig, responseType: 'text' }, ); diff --git a/packages/storage/src/providers/s3/utils/client/base.ts b/packages/storage/src/providers/s3/utils/client/base.ts index 5638402d351..f5697134f08 100644 --- a/packages/storage/src/providers/s3/utils/client/base.ts +++ b/packages/storage/src/providers/s3/utils/client/base.ts @@ -52,7 +52,7 @@ export type S3EndpointResolverOptions = EndpointResolverOptions & { */ const endpointResolver = ( options: S3EndpointResolverOptions, - apiInput?: { Bucket?: string } + apiInput?: { Bucket?: string }, ) => { const { region, useAccelerateEndpoint, customEndpoint, forcePathStyle } = options; @@ -63,7 +63,7 @@ const endpointResolver = ( } else if (useAccelerateEndpoint) { if (forcePathStyle) { throw new Error( - 'Path style URLs are not supported with S3 Transfer Acceleration.' + 'Path style URLs are not supported with S3 Transfer Acceleration.', ); } endpoint = new AmplifyUrl(`https://s3-accelerate.${getDnsSuffix(region)}`); diff --git a/packages/storage/src/providers/s3/utils/client/completeMultipartUpload.ts b/packages/storage/src/providers/s3/utils/client/completeMultipartUpload.ts index 55e52fbcb7d..cc5ad37ebe0 100644 --- a/packages/storage/src/providers/s3/utils/client/completeMultipartUpload.ts +++ b/packages/storage/src/providers/s3/utils/client/completeMultipartUpload.ts @@ -44,7 +44,7 @@ export type CompleteMultipartUploadOutput = Pick< const completeMultipartUploadSerializer = async ( input: CompleteMultipartUploadInput, - endpoint: Endpoint + endpoint: Endpoint, ): Promise => { const headers = { 'content-type': 'application/xml', @@ -68,13 +68,13 @@ const completeMultipartUploadSerializer = async ( }; const serializeCompletedMultipartUpload = ( - input: CompletedMultipartUpload + input: CompletedMultipartUpload, ): string => { if (!input.Parts?.length) { throw new Error(`${INVALID_PARAMETER_ERROR_MSG}: ${input}`); } return `${input.Parts.map( - serializeCompletedPartList + serializeCompletedPartList, ).join('')}`; }; @@ -104,7 +104,7 @@ const parseXmlBodyOrThrow = async (response: HttpResponse): Promise => { }; const completeMultipartUploadDeserializer = async ( - response: HttpResponse + response: HttpResponse, ): Promise => { if (response.statusCode >= 300) { const error = (await parseXmlError(response)) as Error; @@ -128,7 +128,7 @@ const completeMultipartUploadDeserializer = async ( // Ref: https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html#API_CompleteMultipartUpload_Example_4 const retryWhenErrorWith200StatusCode = async ( response?: HttpResponse, - error?: unknown + error?: unknown, ): Promise => { if (!response) { return false; @@ -156,5 +156,5 @@ export const completeMultipartUpload = composeServiceApi( ...defaultConfig, responseType: 'text', retryDecider: retryWhenErrorWith200StatusCode, - } + }, ); diff --git a/packages/storage/src/providers/s3/utils/client/copyObject.ts b/packages/storage/src/providers/s3/utils/client/copyObject.ts index 6a79bfb6d9f..1259fc3f8cf 100644 --- a/packages/storage/src/providers/s3/utils/client/copyObject.ts +++ b/packages/storage/src/providers/s3/utils/client/copyObject.ts @@ -42,7 +42,7 @@ export type CopyObjectOutput = CopyObjectCommandOutput; const copyObjectSerializer = async ( input: CopyObjectInput, - endpoint: Endpoint + endpoint: Endpoint, ): Promise => { const headers = { ...(await serializeObjectConfigsToHeaders(input)), @@ -62,7 +62,7 @@ const copyObjectSerializer = async ( }; const copyObjectDeserializer = async ( - response: HttpResponse + response: HttpResponse, ): Promise => { if (response.statusCode >= 300) { const error = (await parseXmlError(response)) as Error; @@ -79,5 +79,5 @@ export const copyObject = composeServiceApi( s3TransferHandler, copyObjectSerializer, copyObjectDeserializer, - { ...defaultConfig, responseType: 'text' } + { ...defaultConfig, responseType: 'text' }, ); diff --git a/packages/storage/src/providers/s3/utils/client/createMultipartUpload.ts b/packages/storage/src/providers/s3/utils/client/createMultipartUpload.ts index 62c72d6e94c..0010721f464 100644 --- a/packages/storage/src/providers/s3/utils/client/createMultipartUpload.ts +++ b/packages/storage/src/providers/s3/utils/client/createMultipartUpload.ts @@ -39,7 +39,7 @@ export type CreateMultipartUploadOutput = Pick< const createMultipartUploadSerializer = async ( input: CreateMultipartUploadInput, - endpoint: Endpoint + endpoint: Endpoint, ): Promise => { const headers = await serializeObjectConfigsToHeaders(input); const url = new AmplifyUrl(endpoint.url.toString()); @@ -54,7 +54,7 @@ const createMultipartUploadSerializer = async ( }; const createMultipartUploadDeserializer = async ( - response: HttpResponse + response: HttpResponse, ): Promise => { if (response.statusCode >= 300) { const error = (await parseXmlError(response)) as Error; @@ -75,5 +75,5 @@ export const createMultipartUpload = composeServiceApi( s3TransferHandler, createMultipartUploadSerializer, createMultipartUploadDeserializer, - { ...defaultConfig, responseType: 'text' } + { ...defaultConfig, responseType: 'text' }, ); diff --git a/packages/storage/src/providers/s3/utils/client/deleteObject.ts b/packages/storage/src/providers/s3/utils/client/deleteObject.ts index 8ba2ea864d7..28cfc2ee797 100644 --- a/packages/storage/src/providers/s3/utils/client/deleteObject.ts +++ b/packages/storage/src/providers/s3/utils/client/deleteObject.ts @@ -35,7 +35,7 @@ export type DeleteObjectOutput = DeleteObjectCommandOutput; const deleteObjectSerializer = ( input: DeleteObjectInput, - endpoint: Endpoint + endpoint: Endpoint, ): HttpRequest => { const url = new AmplifyUrl(endpoint.url.toString()); validateS3RequiredParameter(!!input.Key, 'Key'); @@ -48,7 +48,7 @@ const deleteObjectSerializer = ( }; const deleteObjectDeserializer = async ( - response: HttpResponse + response: HttpResponse, ): Promise => { if (response.statusCode >= 300) { // error is always set when statusCode >= 300 @@ -71,5 +71,5 @@ export const deleteObject = composeServiceApi( s3TransferHandler, deleteObjectSerializer, deleteObjectDeserializer, - { ...defaultConfig, responseType: 'text' } + { ...defaultConfig, responseType: 'text' }, ); diff --git a/packages/storage/src/providers/s3/utils/client/getObject.ts b/packages/storage/src/providers/s3/utils/client/getObject.ts index 17278aaa67e..a85c75bd248 100644 --- a/packages/storage/src/providers/s3/utils/client/getObject.ts +++ b/packages/storage/src/providers/s3/utils/client/getObject.ts @@ -45,7 +45,7 @@ export type GetObjectOutput = GetObjectCommandOutput; const getObjectSerializer = async ( input: GetObjectInput, - endpoint: Endpoint + endpoint: Endpoint, ): Promise => { const url = new AmplifyUrl(endpoint.url.toString()); validateS3RequiredParameter(!!input.Key, 'Key'); @@ -60,7 +60,7 @@ const getObjectSerializer = async ( }; const getObjectDeserializer = async ( - response: HttpResponse + response: HttpResponse, ): Promise => { if (response.statusCode >= 300) { const error = (await parseXmlError(response)) as Error; @@ -122,7 +122,7 @@ export const getObject = composeServiceApi( s3TransferHandler, getObjectSerializer, getObjectDeserializer, - { ...defaultConfig, responseType: 'blob' } + { ...defaultConfig, responseType: 'blob' }, ); type S3GetObjectPresignedUrlConfig = Omit< @@ -140,7 +140,7 @@ type S3GetObjectPresignedUrlConfig = Omit< */ export const getPresignedGetObjectUrl = async ( config: S3GetObjectPresignedUrlConfig, - input: GetObjectInput + input: GetObjectInput, ): Promise => { const endpoint = defaultConfig.endpointResolver(config, input); const { url, headers, method } = await getObjectSerializer(input, endpoint); @@ -152,12 +152,12 @@ export const getPresignedGetObjectUrl = async ( if (config.userAgentValue) { url.searchParams.append( config.userAgentHeader ?? USER_AGENT_HEADER, - config.userAgentValue + config.userAgentValue, ); } for (const [headerName, value] of Object.entries(headers).sort( - ([key1], [key2]) => key1.localeCompare(key2) + ([key1], [key2]) => key1.localeCompare(key2), )) { url.searchParams.append(headerName, value); } @@ -168,6 +168,6 @@ export const getPresignedGetObjectUrl = async ( signingRegion: config.region, ...defaultConfig, ...config, - } + }, ); }; diff --git a/packages/storage/src/providers/s3/utils/client/headObject.ts b/packages/storage/src/providers/s3/utils/client/headObject.ts index 580162edff7..65feae805bc 100644 --- a/packages/storage/src/providers/s3/utils/client/headObject.ts +++ b/packages/storage/src/providers/s3/utils/client/headObject.ts @@ -40,7 +40,7 @@ export type HeadObjectOutput = Pick< const headObjectSerializer = async ( input: HeadObjectInput, - endpoint: Endpoint + endpoint: Endpoint, ): Promise => { const url = new AmplifyUrl(endpoint.url.toString()); validateS3RequiredParameter(!!input.Key, 'Key'); @@ -53,7 +53,7 @@ const headObjectSerializer = async ( }; const headObjectDeserializer = async ( - response: HttpResponse + response: HttpResponse, ): Promise => { if (response.statusCode >= 300) { // error is always set when statusCode >= 300 @@ -81,5 +81,5 @@ export const headObject = composeServiceApi( s3TransferHandler, headObjectSerializer, headObjectDeserializer, - { ...defaultConfig, responseType: 'text' } + { ...defaultConfig, responseType: 'text' }, ); diff --git a/packages/storage/src/providers/s3/utils/client/listObjectsV2.ts b/packages/storage/src/providers/s3/utils/client/listObjectsV2.ts index ab2e5d2ebf6..931977a5007 100644 --- a/packages/storage/src/providers/s3/utils/client/listObjectsV2.ts +++ b/packages/storage/src/providers/s3/utils/client/listObjectsV2.ts @@ -36,7 +36,7 @@ export type ListObjectsV2Output = ListObjectsV2CommandOutput; const listObjectsV2Serializer = ( input: ListObjectsV2Input, - endpoint: Endpoint + endpoint: Endpoint, ): HttpRequest => { const headers = assignStringVariables({ 'x-amz-request-payer': input.RequestPayer, @@ -62,7 +62,7 @@ const listObjectsV2Serializer = ( }; const listObjectsV2Deserializer = async ( - response: HttpResponse + response: HttpResponse, ): Promise => { if (response.statusCode >= 300) { // error is always set when statusCode >= 300 @@ -131,5 +131,5 @@ export const listObjectsV2 = composeServiceApi( s3TransferHandler, listObjectsV2Serializer, listObjectsV2Deserializer, - { ...defaultConfig, responseType: 'text' } + { ...defaultConfig, responseType: 'text' }, ); diff --git a/packages/storage/src/providers/s3/utils/client/listParts.ts b/packages/storage/src/providers/s3/utils/client/listParts.ts index ca369f8f0c6..ba12b4a97ff 100644 --- a/packages/storage/src/providers/s3/utils/client/listParts.ts +++ b/packages/storage/src/providers/s3/utils/client/listParts.ts @@ -42,7 +42,7 @@ export type ListPartsOutput = Pick< const listPartsSerializer = async ( input: ListPartsInput, - endpoint: Endpoint + endpoint: Endpoint, ): Promise => { const headers = {}; const url = new AmplifyUrl(endpoint.url.toString()); @@ -60,7 +60,7 @@ const listPartsSerializer = async ( }; const listPartsDeserializer = async ( - response: HttpResponse + response: HttpResponse, ): Promise => { if (response.statusCode >= 300) { const error = (await parseXmlError(response)) as Error; @@ -87,12 +87,12 @@ const deserializeCompletedPartList = (input: any[]): CompletedPart[] => PartNumber: ['PartNumber', deserializeNumber], ETag: 'ETag', Size: ['Size', deserializeNumber], - }) + }), ); export const listParts = composeServiceApi( s3TransferHandler, listPartsSerializer, listPartsDeserializer, - { ...defaultConfig, responseType: 'text' } + { ...defaultConfig, responseType: 'text' }, ); diff --git a/packages/storage/src/providers/s3/utils/client/putObject.ts b/packages/storage/src/providers/s3/utils/client/putObject.ts index f7d5a1b6218..ac8509270a6 100644 --- a/packages/storage/src/providers/s3/utils/client/putObject.ts +++ b/packages/storage/src/providers/s3/utils/client/putObject.ts @@ -48,7 +48,7 @@ export type PutObjectOutput = Pick< const putObjectSerializer = async ( input: PutObjectInput, - endpoint: Endpoint + endpoint: Endpoint, ): Promise => { const headers = { ...(await serializeObjectConfigsToHeaders({ @@ -69,7 +69,7 @@ const putObjectSerializer = async ( }; const putObjectDeserializer = async ( - response: HttpResponse + response: HttpResponse, ): Promise => { if (response.statusCode >= 300) { const error = (await parseXmlError(response)) as Error; @@ -89,5 +89,5 @@ export const putObject = composeServiceApi( s3TransferHandler, putObjectSerializer, putObjectDeserializer, - { ...defaultConfig, responseType: 'text' } + { ...defaultConfig, responseType: 'text' }, ); diff --git a/packages/storage/src/providers/s3/utils/client/runtime/base64/index.browser.ts b/packages/storage/src/providers/s3/utils/client/runtime/base64/index.browser.ts index 8190395051e..325b19a66f3 100644 --- a/packages/storage/src/providers/s3/utils/client/runtime/base64/index.browser.ts +++ b/packages/storage/src/providers/s3/utils/client/runtime/base64/index.browser.ts @@ -16,6 +16,6 @@ export function toBase64(input: string | ArrayBufferView): string { } return bytesToBase64( - new Uint8Array(input.buffer, input.byteOffset, input.byteLength) + new Uint8Array(input.buffer, input.byteOffset, input.byteLength), ); } diff --git a/packages/storage/src/providers/s3/utils/client/runtime/xhrTransferHandler.ts b/packages/storage/src/providers/s3/utils/client/runtime/xhrTransferHandler.ts index 74c71a0d4e7..c323342fb1d 100644 --- a/packages/storage/src/providers/s3/utils/client/runtime/xhrTransferHandler.ts +++ b/packages/storage/src/providers/s3/utils/client/runtime/xhrTransferHandler.ts @@ -80,7 +80,7 @@ export const xhrTransferHandler: TransferHandler< xhr.addEventListener('error', () => { const networkError = buildHandlerError( NETWORK_ERROR_MESSAGE, - NETWORK_ERROR_CODE + NETWORK_ERROR_CODE, ); logger.error(NETWORK_ERROR_MESSAGE); reject(networkError); @@ -111,7 +111,7 @@ export const xhrTransferHandler: TransferHandler< // The load event is triggered after the error/abort/load event. So we need to check if the xhr is null. if (!xhr) return; const responseHeaders = convertResponseHeaders( - xhr.getAllResponseHeaders() + xhr.getAllResponseHeaders(), ); const responseType = xhr.responseType; const responseBlob = xhr.response as Blob; @@ -121,14 +121,14 @@ export const xhrTransferHandler: TransferHandler< text: withMemoization(() => responseType === 'blob' ? readBlobAsText(responseBlob) - : Promise.resolve(responseText) + : Promise.resolve(responseText), ), json: () => Promise.reject( // S3 does not support JSON response. So fail-fast here with nicer error message. new Error( - 'Parsing response to JSON is not implemented. Please use response.text() instead.' - ) + 'Parsing response to JSON is not implemented. Please use response.text() instead.', + ), ), }; const response: HttpResponse = { @@ -184,7 +184,7 @@ export const xhrTransferHandler: TransferHandler< }; const convertToTransferProgressEvent = ( - event: ProgressEvent + event: ProgressEvent, ): TransferProgressEvent => ({ transferredBytes: event.loaded, totalBytes: event.lengthComputable ? event.total : undefined, diff --git a/packages/storage/src/providers/s3/utils/client/uploadPart.ts b/packages/storage/src/providers/s3/utils/client/uploadPart.ts index e02ba2c57a4..a5b9c22bb42 100644 --- a/packages/storage/src/providers/s3/utils/client/uploadPart.ts +++ b/packages/storage/src/providers/s3/utils/client/uploadPart.ts @@ -39,7 +39,7 @@ export type UploadPartOutput = Pick< const uploadPartSerializer = async ( input: UploadPartInput, - endpoint: Endpoint + endpoint: Endpoint, ): Promise => { const headers = { ...assignStringVariables({ 'content-md5': input.ContentMD5 }), @@ -63,7 +63,7 @@ const uploadPartSerializer = async ( }; const uploadPartDeserializer = async ( - response: HttpResponse + response: HttpResponse, ): Promise => { if (response.statusCode >= 300) { const error = (await parseXmlError(response)) as Error; @@ -82,5 +82,5 @@ export const uploadPart = composeServiceApi( s3TransferHandler, uploadPartSerializer, uploadPartDeserializer, - { ...defaultConfig, responseType: 'text' } + { ...defaultConfig, responseType: 'text' }, ); diff --git a/packages/storage/src/providers/s3/utils/client/utils/deserializeHelpers.ts b/packages/storage/src/providers/s3/utils/client/utils/deserializeHelpers.ts index 50e8de17e41..78d88a714b9 100644 --- a/packages/storage/src/providers/s3/utils/client/utils/deserializeHelpers.ts +++ b/packages/storage/src/providers/s3/utils/client/utils/deserializeHelpers.ts @@ -50,7 +50,7 @@ type InferInstructionResultType> = */ export const map = }>( obj: Record, - instructions: Instructions + instructions: Instructions, ): { [K in keyof Instructions]: InferInstructionResultType; } => { @@ -110,13 +110,13 @@ export const deserializeTimestamp = (value: string): Date | undefined => { */ export const emptyArrayGuard = >( value: any, - deserializer: (value: any[]) => T + deserializer: (value: any[]) => T, ): T => { if (value === '') { return [] as any as T; } const valueArray = (Array.isArray(value) ? value : [value]).filter( - e => e != null + e => e != null, ); return deserializer(valueArray); }; @@ -125,7 +125,7 @@ export const emptyArrayGuard = >( * @internal */ export const deserializeMetadata = ( - headers: Headers + headers: Headers, ): Record => { const objectMetadataHeaderPrefix = 'x-amz-meta-'; const deserialized = Object.keys(headers) @@ -144,7 +144,7 @@ export const deserializeMetadata = ( */ export const buildStorageServiceError = ( error: Error, - statusCode: number + statusCode: number, ): ServiceError => { const storageError = new StorageError({ name: error.name, diff --git a/packages/storage/src/providers/s3/utils/client/utils/parsePayload.ts b/packages/storage/src/providers/s3/utils/client/utils/parsePayload.ts index 7ac7029a8d1..a905a864c86 100644 --- a/packages/storage/src/providers/s3/utils/client/utils/parsePayload.ts +++ b/packages/storage/src/providers/s3/utils/client/utils/parsePayload.ts @@ -18,8 +18,8 @@ export const parseXmlError: ErrorParser = async (response?: HttpResponse) => { const code = body?.['Code'] ? (body.Code as string) : statusCode === 404 - ? 'NotFound' - : statusCode.toString(); + ? 'NotFound' + : statusCode.toString(); const message = body?.['message'] ?? body?.['Message'] ?? code; const error = new Error(message); return Object.assign(error, { diff --git a/packages/storage/src/providers/s3/utils/client/utils/serializeHelpers.ts b/packages/storage/src/providers/s3/utils/client/utils/serializeHelpers.ts index 1fd41bc916e..b563f6070cf 100644 --- a/packages/storage/src/providers/s3/utils/client/utils/serializeHelpers.ts +++ b/packages/storage/src/providers/s3/utils/client/utils/serializeHelpers.ts @@ -8,7 +8,7 @@ import { StorageError } from '../../../../../errors/StorageError'; * @internal */ export const assignStringVariables = ( - values: Record string } | undefined> + values: Record string } | undefined>, ): Record => { const queryParams: Record = {}; for (const [key, value] of Object.entries(values)) { @@ -39,7 +39,7 @@ interface ObjectConfigs { * @internal */ export const serializeObjectConfigsToHeaders = async ( - input: ObjectConfigs + input: ObjectConfigs, ) => ({ ...assignStringVariables({ 'x-amz-acl': input.ACL, @@ -55,7 +55,7 @@ export const serializeObjectConfigsToHeaders = async ( }); const serializeMetadata = ( - metadata: Record = {} + metadata: Record = {}, ): Record => Object.keys(metadata).reduce((acc: any, suffix: string) => { acc[`x-amz-meta-${suffix.toLowerCase()}`] = metadata[suffix]; @@ -77,14 +77,14 @@ export const serializePathnameObjectKey = (url: URL, key: string) => { export function validateS3RequiredParameter( assertion: boolean, - paramName: string + paramName: string, ): asserts assertion { if (!assertion) { throw new StorageError({ name: AmplifyErrorCode.Unknown, message: 'An unknown error has occurred.', underlyingError: new TypeError( - `Expected a non-null value for S3 parameter ${paramName}` + `Expected a non-null value for S3 parameter ${paramName}`, ), recoverySuggestion: 'This is likely to be a bug. Please reach out to library authors.', diff --git a/packages/storage/src/providers/s3/utils/md5.native.ts b/packages/storage/src/providers/s3/utils/md5.native.ts index cdb6f63e210..65479c67c84 100644 --- a/packages/storage/src/providers/s3/utils/md5.native.ts +++ b/packages/storage/src/providers/s3/utils/md5.native.ts @@ -5,7 +5,7 @@ import { Md5 } from '@smithy/md5-js'; import { toBase64 } from './client/utils'; export const calculateContentMd5 = async ( - content: Blob | string | ArrayBuffer | ArrayBufferView + content: Blob | string | ArrayBuffer | ArrayBufferView, ): Promise => { const hasher = new Md5(); if (typeof content === 'string') { diff --git a/packages/storage/src/providers/s3/utils/md5.ts b/packages/storage/src/providers/s3/utils/md5.ts index 430784f23c7..cce01e71723 100644 --- a/packages/storage/src/providers/s3/utils/md5.ts +++ b/packages/storage/src/providers/s3/utils/md5.ts @@ -5,7 +5,7 @@ import { Md5 } from '@smithy/md5-js'; import { toBase64, utf8Encode } from './client/utils'; export const calculateContentMd5 = async ( - content: Blob | string | ArrayBuffer | ArrayBufferView + content: Blob | string | ArrayBuffer | ArrayBufferView, ): Promise => { const hasher = new Md5(); if (typeof content === 'string') { diff --git a/packages/storage/src/providers/s3/utils/resolveS3ConfigAndInput.ts b/packages/storage/src/providers/s3/utils/resolveS3ConfigAndInput.ts index cf32138b86e..04054e8474f 100644 --- a/packages/storage/src/providers/s3/utils/resolveS3ConfigAndInput.ts +++ b/packages/storage/src/providers/s3/utils/resolveS3ConfigAndInput.ts @@ -35,7 +35,7 @@ type ResolvedS3ConfigAndInput = { */ export const resolveS3ConfigAndInput = async ( amplify: AmplifyClassV6, - apiOptions?: S3ApiOptions + apiOptions?: S3ApiOptions, ): Promise => { // identityId is always cached in memory if forceRefresh is not set. So we can safely make calls here. const { credentials, identityId } = await amplify.Auth.fetchAuthSession({ @@ -43,7 +43,7 @@ export const resolveS3ConfigAndInput = async ( }); assertValidationError( !!credentials, - StorageValidationErrorCode.NoCredentials + StorageValidationErrorCode.NoCredentials, ); assertValidationError(!!identityId, StorageValidationErrorCode.NoIdentityId); @@ -77,7 +77,7 @@ export const resolveS3ConfigAndInput = async ( ? { customEndpoint: LOCAL_TESTING_S3_ENDPOINT, forcePathStyle: true, - } + } : {}), }, bucket, diff --git a/packages/storage/src/utils/resolvePrefix.ts b/packages/storage/src/utils/resolvePrefix.ts index cba1973179d..8d33f59bd69 100644 --- a/packages/storage/src/utils/resolvePrefix.ts +++ b/packages/storage/src/utils/resolvePrefix.ts @@ -17,13 +17,13 @@ export const resolvePrefix = ({ if (accessLevel === 'private') { assertValidationError( !!targetIdentityId, - StorageValidationErrorCode.NoIdentityId + StorageValidationErrorCode.NoIdentityId, ); return `private/${targetIdentityId}/`; } else if (accessLevel === 'protected') { assertValidationError( !!targetIdentityId, - StorageValidationErrorCode.NoIdentityId + StorageValidationErrorCode.NoIdentityId, ); return `protected/${targetIdentityId}/`; } else { diff --git a/rollup/utils.mjs b/rollup/utils.mjs index d9b7d1875b0..131c1872d4e 100644 --- a/rollup/utils.mjs +++ b/rollup/utils.mjs @@ -21,10 +21,10 @@ export const getInputForGlob = (matcher, { ignore } = {}) => // file, so e.g. src/nested/foo.js becomes nested/foo path.relative( 'src', - file.slice(0, file.length - path.extname(file).length) + file.slice(0, file.length - path.extname(file).length), ), // This expands the relative paths to absolute paths, so e.g. // src/nested/foo becomes //packages/src/nested/foo.js path.resolve(path.resolve('.'), file), - ]) + ]), ); diff --git a/scripts/dts-bundler/dts-bundler.config.js b/scripts/dts-bundler/dts-bundler.config.js index 5d741bfb877..77671630aeb 100644 --- a/scripts/dts-bundler/dts-bundler.config.js +++ b/scripts/dts-bundler/dts-bundler.config.js @@ -14,7 +14,7 @@ const baseTsConfigPath = join( '..', '..', 'packages', - 'tsconfig.base.json' + 'tsconfig.base.json', ); const corePackageSrcClientsPath = join( __dirname, @@ -23,7 +23,7 @@ const corePackageSrcClientsPath = join( 'packages', 'core', 'src', - 'awsClients' + 'awsClients', ); const storagePackageSrcClientsPath = join( @@ -35,7 +35,7 @@ const storagePackageSrcClientsPath = join( 'src', 'providers', 's3', - 'utils' + 'utils', ); const authPackageSrcClientsPath = join( __dirname, @@ -47,7 +47,7 @@ const authPackageSrcClientsPath = join( 'providers', 'cognito', 'utils', - 'clients' + 'clients', ); /** @type import('dts-bundle-generator/config-schema').BundlerConfig */ @@ -85,7 +85,7 @@ const config = { outFile: join( authPackageSrcClientsPath, 'CognitoIdentityProvider', - 'types.ts' + 'types.ts', ), libraries: { inlinedLibraries: ['@aws-sdk/client-cognito-identity-provider'], diff --git a/scripts/test-github-actions.js b/scripts/test-github-actions.js index e369c837ebb..8b6bbea9400 100755 --- a/scripts/test-github-actions.js +++ b/scripts/test-github-actions.js @@ -62,7 +62,7 @@ for (const file of [...workflowYmlFiles, ...actionYmlFiles]) { continue; } console.log( - `In ${file} the uses reference ${val} must either be local to the project or fully reference a specific action commit on an external project` + `In ${file} the uses reference ${val} must either be local to the project or fully reference a specific action commit on an external project`, ); exitCode = 1; } diff --git a/yarn.lock b/yarn.lock index 6026009115a..128d63906ac 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12730,10 +12730,10 @@ prettier-linter-helpers@^1.0.0: dependencies: fast-diff "^1.1.2" -prettier@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.1.0.tgz#c6d16474a5f764ea1a4a373c593b779697744d5e" - integrity sha512-TQLvXjq5IAibjh8EpBIkNKxO749UEWABoiIZehEPiY4GNpVdhaFKqSTu+QrlU6D2dPAfubRmtJTi4K4YkQ5eXw== +prettier@^3.2.5: + version "3.2.5" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.2.5.tgz#e52bc3090586e824964a8813b09aba6233b28368" + integrity sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A== pretty-format@29.4.3: version "29.4.3"