From 1a6d358ba2f0ee2ffeed972f89abdd018aecd1a1 Mon Sep 17 00:00:00 2001 From: Hui Zhao <10602282+HuiSF@users.noreply.github.com> Date: Wed, 20 Mar 2024 16:33:37 -0700 Subject: [PATCH] chore(notifications): enable eslint and remove telint (#13091) * chore(notifications): enable eslint and remove telint * chore(notifications): run yarn lint:fix * chore(notifications): manual fix of linter reported errors * apply suggestions * fix lint regressions caused by rebasing --- .eslintrc.js | 2 +- ...initializePushNotifications.native.test.ts | 2 +- packages/notifications/jest.config.js | 2 +- packages/notifications/package.json | 3 +- .../src/eventListeners/eventListeners.ts | 25 ++++++---- .../notifications/src/eventListeners/types.ts | 12 +++-- .../errors/assertServiceError.ts | 1 + .../providers/pinpoint/apis/clearMessages.ts | 5 +- .../providers/pinpoint/apis/dispatchEvent.ts | 6 ++- .../providers/pinpoint/apis/identifyUser.ts | 12 ++--- .../pinpoint/apis/initializeInAppMessaging.ts | 8 +-- .../pinpoint/apis/notifyMessageInteraction.ts | 1 + .../pinpoint/apis/onMessageActionTaken.ts | 2 + .../pinpoint/apis/onMessageDismissed.ts | 2 + .../pinpoint/apis/onMessageDisplayed.ts | 4 +- .../pinpoint/apis/onMessageReceived.ts | 2 + .../pinpoint/apis/setConflictHandler.ts | 1 + .../providers/pinpoint/apis/syncMessages.ts | 22 ++++---- .../providers/pinpoint/types/inputs.ts | 15 +++--- .../providers/pinpoint/types/types.ts | 8 +-- .../pinpoint/utils/conflictHandlerManager.ts | 2 + .../providers/pinpoint/utils/helpers.ts | 28 +++++++---- .../utils/messageProcessingHelpers.ts | 30 +++++++---- .../providers/pinpoint/utils/resolveConfig.ts | 2 + .../pinpoint/utils/resolveCredentials.ts | 2 + .../providers/pinpoint/utils/userAgent.ts | 4 +- .../src/inAppMessaging/types/event.ts | 4 +- .../src/inAppMessaging/types/inputs.ts | 7 +-- .../pushNotifications/errors/errorHelpers.ts | 2 + .../pinpoint/apis/getBadgeCount.native.ts | 2 + .../providers/pinpoint/apis/getBadgeCount.ts | 1 + .../apis/getLaunchNotification.native.ts | 2 + .../pinpoint/apis/getLaunchNotification.ts | 1 + .../apis/getPermissionStatus.native.ts | 2 + .../pinpoint/apis/getPermissionStatus.ts | 1 + .../pinpoint/apis/identifyUser.native.ts | 1 + .../providers/pinpoint/apis/identifyUser.ts | 1 + .../initializePushNotifications.native.ts | 33 +++++++----- .../apis/initializePushNotifications.ts | 1 + .../apis/onNotificationOpened.native.ts | 1 + .../pinpoint/apis/onNotificationOpened.ts | 1 + ...NotificationReceivedInBackground.native.ts | 1 + .../onNotificationReceivedInBackground.ts | 1 + ...NotificationReceivedInForeground.native.ts | 1 + .../onNotificationReceivedInForeground.ts | 1 + .../pinpoint/apis/onTokenReceived.native.ts | 1 + .../pinpoint/apis/onTokenReceived.ts | 1 + .../apis/requestPermissions.native.ts | 2 + .../pinpoint/apis/requestPermissions.ts | 1 + .../pinpoint/apis/setBadgeCount.native.ts | 1 + .../providers/pinpoint/apis/setBadgeCount.ts | 1 + .../providers/pinpoint/types/analytics.ts | 4 +- .../providers/pinpoint/types/inputs.ts | 7 +-- .../utils/createMessageEventRecorder.ts | 6 ++- .../pinpoint/utils/getAnalyticsEvent.ts | 4 +- .../pinpoint/utils/getChannelType.ts | 1 + .../providers/pinpoint/utils/resolveConfig.ts | 4 +- .../src/pushNotifications/types/inputs.ts | 7 +-- .../getPushNotificationUserAgentString.ts | 2 +- .../utils/resolveCredentials.ts | 4 +- packages/notifications/tslint.json | 50 ------------------- 61 files changed, 208 insertions(+), 155 deletions(-) delete mode 100644 packages/notifications/tslint.json diff --git a/.eslintrc.js b/.eslintrc.js index b8e593373d4..eb968e3fb61 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -50,7 +50,7 @@ module.exports = { 'packages/datastore-storage-adapter', // 'packages/geo', // 'packages/interactions', - 'packages/notifications', + // 'packages/notifications', // 'packages/predictions', // 'packages/pubsub', // 'packages/react-native', 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 a2cc8508df7..42011ab0893 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 @@ -47,7 +47,7 @@ const mockGetConstants = jest.fn(); const mockRegisterHeadlessTask = jest.fn(); describe('initializePushNotifications (native)', () => { - let initializePushNotifications; + let initializePushNotifications: () => void; const { NativeEvent } = pushModuleConstants; // create mocks const mockEventListenerRemover = { remove: jest.fn() }; diff --git a/packages/notifications/jest.config.js b/packages/notifications/jest.config.js index 76f3094c2cf..da5232b6dbf 100644 --- a/packages/notifications/jest.config.js +++ b/packages/notifications/jest.config.js @@ -3,7 +3,7 @@ module.exports = { coverageThreshold: { global: { branches: 73, - functions: 90, + functions: 89, lines: 91, statements: 92, }, diff --git a/packages/notifications/package.json b/packages/notifications/package.json index fc9490c3ecf..d614f240ec8 100644 --- a/packages/notifications/package.json +++ b/packages/notifications/package.json @@ -21,7 +21,8 @@ "clean": "npm run clean:size && rimraf dist lib lib-esm", "clean:size": "rimraf dual-publish-tmp tmp*", "format": "echo \"Not implemented\"", - "lint": "tslint 'src/**/*.ts' && npm run ts-coverage", + "lint": "eslint '**/*.{ts,tsx}' && npm run ts-coverage", + "lint:fix": "eslint '**/*.{ts,tsx}' --fix", "ts-coverage": "typescript-coverage-report -p ./tsconfig.build.json -t 88.21" }, "typesVersions": { diff --git a/packages/notifications/src/eventListeners/eventListeners.ts b/packages/notifications/src/eventListeners/eventListeners.ts index 97dd2bfd088..aa71f809acc 100644 --- a/packages/notifications/src/eventListeners/eventListeners.ts +++ b/packages/notifications/src/eventListeners/eventListeners.ts @@ -1,9 +1,17 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { EventListener, EventListenerRemover, EventType } from './types'; +import { + EventListener, + EventListenerHandler, + EventListenerRemover, + EventType, +} from './types'; -const eventListeners: Record>> = {}; +const eventListeners: Record< + string, + Set> +> = {}; export const notifyEventListeners = (type: EventType, ...args: any[]): void => { eventListeners[type]?.forEach(listener => { @@ -17,15 +25,11 @@ export const notifyEventListenersAndAwaitHandlers = ( ): Promise => Promise.all( Array.from(eventListeners[type] ?? []).map(async listener => { - try { - await listener.handleEvent(...args); - } catch (err) { - throw err; - } + await listener.handleEvent(...args); }), ); -export const addEventListener = ( +export const addEventListener = ( type: EventType, handler: EventHandler, ): EventListenerRemover => { @@ -40,7 +44,10 @@ export const addEventListener = ( }, }; eventListeners[type].add(listener); + return { - remove: () => listener.remove(), + remove: () => { + listener.remove(); + }, }; }; diff --git a/packages/notifications/src/eventListeners/types.ts b/packages/notifications/src/eventListeners/types.ts index 7c44d928eda..1217da57aa1 100644 --- a/packages/notifications/src/eventListeners/types.ts +++ b/packages/notifications/src/eventListeners/types.ts @@ -4,13 +4,15 @@ import { InAppMessageInteractionEvent } from '../inAppMessaging/types'; import { PushNotificationEvent } from '../pushNotifications/types'; -export interface EventListener { +export type EventListenerHandler = (...args: any[]) => unknown; + +export interface EventListener { handleEvent: EventHandler; - remove: () => void; + remove(): void; } export type EventType = InAppMessageInteractionEvent | PushNotificationEvent; -export type EventListenerRemover = { - remove: () => void; -}; +export interface EventListenerRemover { + remove(): void; +} diff --git a/packages/notifications/src/inAppMessaging/errors/assertServiceError.ts b/packages/notifications/src/inAppMessaging/errors/assertServiceError.ts index ffd965d68a1..19fe0bc4c37 100644 --- a/packages/notifications/src/inAppMessaging/errors/assertServiceError.ts +++ b/packages/notifications/src/inAppMessaging/errors/assertServiceError.ts @@ -5,6 +5,7 @@ import { AmplifyErrorCode, ServiceError, } from '@aws-amplify/core/internals/utils'; + import { InAppMessagingError } from './InAppMessagingError'; export function assertServiceError( diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/clearMessages.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/clearMessages.ts index ad60bc84e0f..52e02809076 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/clearMessages.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/clearMessages.ts @@ -2,8 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import { defaultStorage } from '@aws-amplify/core'; -import { STORAGE_KEY_SUFFIX, PINPOINT_KEY_PREFIX } from '../utils'; +import { PINPOINT_KEY_PREFIX, STORAGE_KEY_SUFFIX } from '../utils'; import { InAppMessagingValidationErrorCode } from '../../../errors'; import { assertIsInitialized } from '../../../utils'; @@ -22,5 +22,6 @@ import { assertIsInitialized } from '../../../utils'; export async function clearMessages(): Promise { assertIsInitialized(); const key = `${PINPOINT_KEY_PREFIX}${STORAGE_KEY_SUFFIX}`; - return await defaultStorage.removeItem(key); + + await defaultStorage.removeItem(key); } diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts index 83523db023f..119d86840d0 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/dispatchEvent.ts @@ -5,7 +5,10 @@ import flatten from 'lodash/flatten.js'; import { defaultStorage } from '@aws-amplify/core'; import { notifyEventListeners } from '../../../../eventListeners'; -import { assertServiceError } from '../../../errors'; +import { + InAppMessagingValidationErrorCode, + assertServiceError, +} from '../../../errors'; import { InAppMessage } from '../../../types'; import { assertIsInitialized } from '../../../utils'; import { DispatchEventInput } from '../types'; @@ -15,6 +18,7 @@ import { getConflictHandler, processInAppMessages, } from '../utils'; + import { syncMessages } from './syncMessages'; import { setConflictHandler } from './setConflictHandler'; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/identifyUser.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/identifyUser.ts index 4db6f8b7302..a147fdec7c2 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/identifyUser.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/identifyUser.ts @@ -3,9 +3,10 @@ import { InAppMessagingAction } from '@aws-amplify/core/internals/utils'; import { - updateEndpoint, UpdateEndpointException, + updateEndpoint, } from '@aws-amplify/core/internals/providers/pinpoint'; + import { InAppMessagingValidationErrorCode } from '../../../errors'; import { CATEGORY, @@ -22,7 +23,7 @@ import { assertIsInitialized } from '../../../utils'; * profile and activities or actions in your application. Activity can be tracked across devices & platforms by using * the same `userId`. * - * @param {IdentifyUserParameters} params The input object used to construct requests sent to Pinpoint's UpdateEndpoint + * @param input The input object that conforms to {@link IdentifyUserInput} used to construct requests sent to Pinpoint's UpdateEndpoint * API. * @throws service: {@link UpdateEndpointException} - Thrown when the underlying Pinpoint service returns an error. * @throws validation: {@link InAppMessagingValidationErrorCode} - Thrown when the provided parameters or library @@ -66,11 +67,8 @@ import { assertIsInitialized } from '../../../utils'; * }, * }); */ -export const identifyUser = async ({ - userId, - userProfile, - options, -}: IdentifyUserInput): Promise => { +export const identifyUser = async (input: IdentifyUserInput): Promise => { + const { userId, userProfile, options } = input; assertIsInitialized(); const { credentials, identityId } = await resolveCredentials(); const { appId, region } = resolveConfig(); diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/initializeInAppMessaging.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/initializeInAppMessaging.ts index 3329623ea3e..de4f2ebe27d 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/initializeInAppMessaging.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/initializeInAppMessaging.ts @@ -2,14 +2,16 @@ // SPDX-License-Identifier: Apache-2.0 import { sessionListener } from '@aws-amplify/core/internals/utils'; +import { Hub, HubCapsule } from '@aws-amplify/core'; + import { InAppMessage, InAppMessagingEvent } from '../../../types'; import { addEventListener } from '../../../../eventListeners'; import { recordAnalyticsEvent } from '../utils/helpers'; import { PinpointMessageEvent } from '../types'; -import { Hub, HubCapsule } from '@aws-amplify/core'; -import { dispatchEvent } from './dispatchEvent'; import { incrementMessageCounts, sessionStateChangeHandler } from '../utils'; -import { isInitialized, initialize } from '../../../utils'; +import { initialize, isInitialized } from '../../../utils'; + +import { dispatchEvent } from './dispatchEvent'; /** * Initialize and set up in-app messaging category. This API needs to be called to enable other InAppMessaging APIs. diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/notifyMessageInteraction.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/notifyMessageInteraction.ts index fb7da9a1fff..e011e0b91b3 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/notifyMessageInteraction.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/notifyMessageInteraction.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { notifyEventListeners } from '../../../../eventListeners'; +import { InAppMessagingValidationErrorCode } from '../../../errors'; import { assertIsInitialized } from '../../../utils'; import { NotifyMessageInteractionInput } from '../types/inputs'; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageActionTaken.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageActionTaken.ts index d6bbc4cd3ca..978165aedb2 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageActionTaken.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageActionTaken.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { addEventListener } from '../../../../eventListeners'; +import { InAppMessagingValidationErrorCode } from '../../../errors'; import { assertIsInitialized } from '../../../utils'; import { OnMessageActionTakenInput } from '../types/inputs'; import { OnMessageActionTakenOutput } from '../types/outputs'; @@ -25,5 +26,6 @@ export function onMessageActionTaken( 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 629c06917b7..38c8cbc8244 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDismissed.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDismissed.ts @@ -5,6 +5,7 @@ import { addEventListener } from '../../../../eventListeners'; import { OnMessageDismissedOutput } from '../types/outputs'; import { OnMessageDismissedInput } from '../types/inputs'; import { assertIsInitialized } from '../../../utils'; +import { InAppMessagingValidationErrorCode } from '../../../errors'; /** * Registers a callback that will be invoked on `messageDismissed` events. @@ -25,5 +26,6 @@ export function onMessageDismissed( 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 fedda241df1..635c77a5272 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDisplayed.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageDisplayed.ts @@ -5,6 +5,7 @@ import { addEventListener } from '../../../../eventListeners'; import { OnMessageDisplayedOutput } from '../types/outputs'; import { OnMessageDisplayedInput } from '../types/inputs'; import { assertIsInitialized } from '../../../utils'; +import { InAppMessagingValidationErrorCode } from '../../../errors'; /** * Registers a callback that will be invoked on `messageDisplayed` events. @@ -12,7 +13,7 @@ import { assertIsInitialized } from '../../../utils'; * @param {OnMessageDisplayedInput} input - The input object that holds the callback handler. * @throws validation: {@link InAppMessagingValidationErrorCode} - Thrown when the provided parameters or library * configuration is incorrect, or if In App messaging hasn't been initialized. - * @returns {OnMessageDismissedOutput} - An object that holds a remove method to stop listening to events. + * @returns {OnMessageDisplayedOutput} - An object that holds a remove method to stop listening to events. * @example * ```ts * onMessageDisplayed((message) => { @@ -25,5 +26,6 @@ export function onMessageDisplayed( 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 36acbcfadf0..14af2f0d4a2 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageReceived.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/onMessageReceived.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { addEventListener } from '../../../../eventListeners'; +import { InAppMessagingValidationErrorCode } from '../../../errors'; import { assertIsInitialized } from '../../../utils'; import { OnMessageReceivedInput } from '../types/inputs'; import { OnMessageReceivedOutput } from '../types/outputs'; @@ -25,5 +26,6 @@ export function onMessageReceived( input: OnMessageReceivedInput, ): OnMessageReceivedOutput { assertIsInitialized(); + return addEventListener('messageReceived', input); } diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/setConflictHandler.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/setConflictHandler.ts index 5efdb62f734..053f0eb26d4 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/setConflictHandler.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/setConflictHandler.ts @@ -1,6 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { InAppMessagingValidationErrorCode } from '../../../errors'; import { assertIsInitialized } from '../../../utils'; import { SetConflictHandlerInput } from '../types'; import { setConflictHandler as setConflictHandlerInteral } from '../utils'; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/syncMessages.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/syncMessages.ts index c3da2d0dc95..70c92fd6997 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/syncMessages.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/apis/syncMessages.ts @@ -5,19 +5,20 @@ import { InAppMessagingAction } from '@aws-amplify/core/internals/utils'; import { resolveEndpointId } from '@aws-amplify/core/internals/providers/pinpoint'; import { defaultStorage } from '@aws-amplify/core'; import { - resolveConfig, - resolveCredentials, - getInAppMessagingUserAgentString, - STORAGE_KEY_SUFFIX, - PINPOINT_KEY_PREFIX, - CATEGORY, - CHANNEL_TYPE, -} from '../utils'; -import { - getInAppMessages, GetInAppMessagesInput, GetInAppMessagesOutput, + getInAppMessages, } from '@aws-amplify/core/internals/aws-clients/pinpoint'; + +import { + CATEGORY, + CHANNEL_TYPE, + PINPOINT_KEY_PREFIX, + STORAGE_KEY_SUFFIX, + getInAppMessagingUserAgentString, + resolveConfig, + resolveCredentials, +} from '../utils'; import { InAppMessagingValidationErrorCode, assertServiceError, @@ -80,6 +81,7 @@ async function fetchInAppMessages() { ); const { InAppMessageCampaigns: messages } = response.InAppMessagesResponse ?? {}; + return messages; } catch (error) { assertServiceError(error); diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/types/inputs.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/types/inputs.ts index 092bdd88b91..df9b292f7a5 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/types/inputs.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/types/inputs.ts @@ -1,11 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { IdentifyUserOptions } from './options'; -import { - InAppMessageConflictHandler, - OnMessageInteractionEventHandler, -} from './types'; import { InAppMessage, InAppMessageInteractionEvent, @@ -13,6 +8,12 @@ import { InAppMessagingIdentifyUserInput, } from '../../../types'; +import { IdentifyUserOptions } from './options'; +import { + InAppMessageConflictHandler, + OnMessageInteractionEventHandler, +} from './types'; + /** * Input type for Pinpoint identifyUser API. */ @@ -52,7 +53,7 @@ export type OnMessageActionTakenInput = OnMessageInteractionEventHandler; /** * Input type for NotifyMessageInteraction API. */ -export type NotifyMessageInteractionInput = { +export interface NotifyMessageInteractionInput { message: InAppMessage; type: InAppMessageInteractionEvent; -}; +} diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/types/types.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/types/types.ts index 71d0092f645..4b6df1f34ef 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/types/types.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/types/types.ts @@ -5,16 +5,16 @@ import { InAppMessage } from '../../../types'; export type InAppMessageCountMap = Record; -export type DailyInAppMessageCounter = { +export interface DailyInAppMessageCounter { count: number; lastCountTimestamp: string; -}; +} -export type InAppMessageCounts = { +export interface InAppMessageCounts { sessionCount: number; dailyCount: number; totalCount: number; -}; +} export type MetricsComparator = ( metricsVal: number, diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/conflictHandlerManager.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/conflictHandlerManager.ts index e6f27849b1e..68ee739d0c9 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/conflictHandlerManager.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/conflictHandlerManager.ts @@ -27,9 +27,11 @@ let conflictHandler: InAppMessageConflictHandler = ( if (!endDateA && endDateB) { return 1; } + // otherwise, compare them return new Date(endDateA) < new Date(endDateB) ? -1 : 1; }); + // always return the top sorted return sorted[0]; }; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts index 64f86d8511a..dcd5c0adf23 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/helpers.ts @@ -5,6 +5,8 @@ import { ConsoleLogger } from '@aws-amplify/core'; import { InAppMessagingAction } from '@aws-amplify/core/internals/utils'; import type { InAppMessageCampaign as PinpointInAppMessage } from '@aws-amplify/core/internals/aws-clients/pinpoint'; import isEmpty from 'lodash/isEmpty.js'; +import { record as recordCore } from '@aws-amplify/core/internals/providers/pinpoint'; + import { InAppMessage, InAppMessageAction, @@ -14,7 +16,7 @@ import { InAppMessagingEvent, } from '../../../types'; import { MetricsComparator, PinpointMessageEvent } from '../types'; -import { record as recordCore } from '@aws-amplify/core/internals/providers/pinpoint'; + import { resolveConfig } from './resolveConfig'; import { resolveCredentials } from './resolveCredentials'; import { CATEGORY } from './constants'; @@ -66,6 +68,7 @@ export const recordAnalyticsEvent = ( export const getStartOfDay = (): string => { const now = new Date(); now.setHours(0, 0, 0, 0); + return now.toISOString(); }; @@ -75,9 +78,10 @@ export const matchesEventType = ( ) => { const { EventType } = Schedule?.EventFilter?.Dimensions ?? {}; const memoKey = `${CampaignId}:${eventType}`; - if (!eventNameMemo.hasOwnProperty(memoKey)) { + if (!Object.prototype.hasOwnProperty.call(eventNameMemo, memoKey)) { eventNameMemo[memoKey] = !!EventType?.Values?.includes(eventType); } + return eventNameMemo[memoKey]; }; @@ -95,13 +99,14 @@ export const matchesAttributes = ( return false; } const memoKey = `${CampaignId}:${JSON.stringify(attributes)}`; - if (!eventAttributesMemo.hasOwnProperty(memoKey)) { + if (!Object.prototype.hasOwnProperty.call(eventAttributesMemo, memoKey)) { eventAttributesMemo[memoKey] = !Attributes || Object.entries(Attributes).every(([key, { Values }]) => Values?.includes(attributes[key]), ); } + return eventAttributesMemo[memoKey]; }; @@ -119,15 +124,17 @@ export const matchesMetrics = ( return false; } const memoKey = `${CampaignId}:${JSON.stringify(metrics)}`; - if (!eventMetricsMemo.hasOwnProperty(memoKey)) { + if (!Object.prototype.hasOwnProperty.call(eventMetricsMemo, memoKey)) { eventMetricsMemo[memoKey] = !Metrics || Object.entries(Metrics).every(([key, { ComparisonOperator, Value }]) => { const compare = getComparator(ComparisonOperator); + // if there is some unknown comparison operator, treat as a comparison failure return compare && !!Value ? compare(Value, metrics[key]) : false; }); } + return eventMetricsMemo[memoKey]; }; @@ -156,6 +163,7 @@ export const isBeforeEndDate = ({ if (!Schedule?.EndDate) { return true; } + return new Date() < new Date(Schedule.EndDate); }; @@ -201,11 +209,12 @@ export const isQuietTime = (message: PinpointInAppMessage): boolean => { end.setDate(end.getDate() + 1); } - const isQuietTime = now >= start && now <= end; - if (isQuietTime) { + const isDuringQuietTime = now >= start && now <= end; + if (isDuringQuietTime) { logger.debug('message filtered due to quiet time', message); } - return isQuietTime; + + return isDuringQuietTime; }; export const clearMemo = () => { @@ -315,18 +324,19 @@ export const extractContent = ({ }, }; } + return extractedContent; }) ?? [] ); }; export const extractMetadata = ({ - InAppMessage, + InAppMessage: inAppMessage, Priority, Schedule, TreatmentId, }: PinpointInAppMessage): InAppMessage['metadata'] => ({ - customData: InAppMessage?.CustomConfig, + customData: inAppMessage?.CustomConfig, endDate: Schedule?.EndDate, priority: Priority, treatmentId: TreatmentId, diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/messageProcessingHelpers.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/messageProcessingHelpers.ts index abcedb39448..29f18f8176c 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/messageProcessingHelpers.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/messageProcessingHelpers.ts @@ -1,12 +1,17 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import type { InAppMessageCampaign as PinpointInAppMessage } from '@aws-amplify/core/internals/aws-clients/pinpoint'; +import { ConsoleLogger, defaultStorage } from '@aws-amplify/core'; +import { SessionState } from '@aws-amplify/core/internals/utils'; + import { InAppMessage, InAppMessagingEvent } from '../../../types'; import { - InAppMessageCounts, - InAppMessageCountMap, DailyInAppMessageCounter, + InAppMessageCountMap, + InAppMessageCounts, } from '../types'; + import { extractContent, extractMetadata, @@ -16,9 +21,6 @@ import { matchesEventType, matchesMetrics, } from './helpers'; -import type { InAppMessageCampaign as PinpointInAppMessage } from '@aws-amplify/core/internals/aws-clients/pinpoint'; -import { defaultStorage, ConsoleLogger } from '@aws-amplify/core'; -import { SessionState } from '@aws-amplify/core/internals/utils'; const MESSAGE_DAILY_COUNT_KEY = 'pinpointProvider_inAppMessages_dailyCount'; const MESSAGE_TOTAL_COUNT_KEY = 'pinpointProvider_inAppMessages_totalCount'; @@ -32,8 +34,7 @@ export async function processInAppMessages( ): Promise { let highestPrioritySeen: number | undefined; let acc: PinpointInAppMessage[] = []; - for (let index = 0; index < messages.length; index++) { - const message = messages[index]; + for (const message of messages) { const messageQualifies = matchesEventType(message, event) && matchesAttributes(message, event) && @@ -65,6 +66,7 @@ export async function processInAppMessages( } } } + return normalizeMessages(acc); } @@ -85,14 +87,15 @@ export async function incrementMessageCounts(messageId: string): Promise { function normalizeMessages(messages: PinpointInAppMessage[]): InAppMessage[] { return messages.map(message => { - const { CampaignId, InAppMessage } = message; + const { CampaignId, InAppMessage: pinpointInAppMessage } = message; + return { // Default to empty string in rare cases we don't have a campaignId id: CampaignId ?? '', content: extractContent(message), // Default to TOP_BANNER layout in rare cases we don't have a Layout - layout: InAppMessage?.Layout - ? interpretLayout(InAppMessage.Layout) + layout: pinpointInAppMessage?.Layout + ? interpretLayout(pinpointInAppMessage.Layout) : 'TOP_BANNER', metadata: extractMetadata(message), }; @@ -104,7 +107,7 @@ async function isBelowCap({ SessionCap, DailyCap, TotalCap, -}: PinpointInAppMessage): Promise { +}: PinpointInAppMessage): Promise { const { sessionCount, dailyCount, totalCount } = await getMessageCounts(CampaignId); @@ -131,6 +134,7 @@ async function getMessageCounts( dailyCount: await getDailyCount(), totalCount: await getTotalCount(messageId), }; + return messageCounts; } catch (err) { logger.error('Failed to get message counts from storage', err); @@ -185,18 +189,21 @@ async function getDailyCount(): Promise { const counter: DailyInAppMessageCounter = item ? JSON.parse(item) : { count: 0, lastCountTimestamp: today }; + // If the stored counter timestamp is today, use it as the count, otherwise reset to 0 return counter.lastCountTimestamp === today ? counter.count : 0; } async function getTotalCountMap(): Promise { const item = await defaultStorage.getItem(MESSAGE_TOTAL_COUNT_KEY); + // Parse stored count map or initialize as empty return item ? JSON.parse(item) : {}; } async function getTotalCount(messageId: string): Promise { const countMap = await getTotalCountMap(); + // Return stored count or initialize as empty count return countMap[messageId] || 0; } @@ -204,5 +211,6 @@ async function getTotalCount(messageId: string): Promise { const getStartOfDay = (): string => { const now = new Date(); now.setHours(0, 0, 0, 0); + return now.toISOString(); }; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveConfig.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveConfig.ts index 6406f8289eb..4161066d0f8 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveConfig.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveConfig.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from '@aws-amplify/core'; + import { InAppMessagingValidationErrorCode, assertValidationError, @@ -15,5 +16,6 @@ export const resolveConfig = () => { Amplify.getConfig().Notifications?.InAppMessaging?.Pinpoint ?? {}; assertValidationError(!!appId, InAppMessagingValidationErrorCode.NoAppId); assertValidationError(!!region, InAppMessagingValidationErrorCode.NoRegion); + return { appId, region }; }; diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveCredentials.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveCredentials.ts index 22da7a3757b..79d067fb828 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveCredentials.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveCredentials.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { fetchAuthSession } from '@aws-amplify/core'; + import { InAppMessagingValidationErrorCode, assertValidationError, @@ -16,5 +17,6 @@ export const resolveCredentials = async () => { !!credentials, 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 b8d4fec1633..bc00a697ea0 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/userAgent.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/userAgent.ts @@ -2,9 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 import { Category, - getAmplifyUserAgentObject, - getAmplifyUserAgent, InAppMessagingAction, + getAmplifyUserAgent, + getAmplifyUserAgentObject, } from '@aws-amplify/core/internals/utils'; import { UserAgent } from '@aws-sdk/types'; diff --git a/packages/notifications/src/inAppMessaging/types/event.ts b/packages/notifications/src/inAppMessaging/types/event.ts index 2b5d0255c4e..f0107f11d92 100644 --- a/packages/notifications/src/inAppMessaging/types/event.ts +++ b/packages/notifications/src/inAppMessaging/types/event.ts @@ -7,8 +7,8 @@ export type InAppMessageInteractionEvent = | 'messageDismissed' | 'messageActionTaken'; -export type InAppMessagingEvent = { +export interface InAppMessagingEvent { name: string; attributes?: Record; metrics?: Record; -}; +} diff --git a/packages/notifications/src/inAppMessaging/types/inputs.ts b/packages/notifications/src/inAppMessaging/types/inputs.ts index 0df082ea000..14d5b0f04b4 100644 --- a/packages/notifications/src/inAppMessaging/types/inputs.ts +++ b/packages/notifications/src/inAppMessaging/types/inputs.ts @@ -2,15 +2,16 @@ // SPDX-License-Identifier: Apache-2.0 import { UserProfile } from '@aws-amplify/core'; + import { InAppMessagingServiceOptions } from './options'; /** * Input type for `identifyUser`. */ -export type InAppMessagingIdentifyUserInput< +export interface InAppMessagingIdentifyUserInput< ServiceOptions extends InAppMessagingServiceOptions = InAppMessagingServiceOptions, -> = { +> { /** * A User ID associated to the current device. */ @@ -25,4 +26,4 @@ export type InAppMessagingIdentifyUserInput< * Options to be passed to the API. */ options?: ServiceOptions; -}; +} diff --git a/packages/notifications/src/pushNotifications/errors/errorHelpers.ts b/packages/notifications/src/pushNotifications/errors/errorHelpers.ts index 5081f19d398..cb94a01e362 100644 --- a/packages/notifications/src/pushNotifications/errors/errorHelpers.ts +++ b/packages/notifications/src/pushNotifications/errors/errorHelpers.ts @@ -6,7 +6,9 @@ import { AssertionFunction, createAssertionFunction, } from '@aws-amplify/core/internals/utils'; + import { isInitialized } from '../utils/initializationManager'; + import { PushNotificationError } from './PushNotificationError'; export enum PushNotificationValidationErrorCode { diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getBadgeCount.native.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getBadgeCount.native.ts index e2feeb46137..e7eb90c3615 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getBadgeCount.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getBadgeCount.native.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { loadAmplifyPushNotification } from '@aws-amplify/react-native'; + import { assertIsInitialized } from '../../../errors/errorHelpers'; import { GetBadgeCount } from '../types'; @@ -9,5 +10,6 @@ const { getBadgeCount: getBadgeCountNative } = loadAmplifyPushNotification(); export const getBadgeCount: GetBadgeCount = async () => { assertIsInitialized(); + return getBadgeCountNative(); }; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getBadgeCount.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getBadgeCount.ts index 86834063c1b..d6830251152 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getBadgeCount.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getBadgeCount.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; + import { GetBadgeCount } from '../types'; /** diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getLaunchNotification.native.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getLaunchNotification.native.ts index ffecd7ce60e..689154a2887 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getLaunchNotification.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getLaunchNotification.native.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { loadAmplifyPushNotification } from '@aws-amplify/react-native'; + import { assertIsInitialized } from '../../../errors/errorHelpers'; import { GetLaunchNotification } from '../types'; @@ -10,5 +11,6 @@ const { getLaunchNotification: getLaunchNotificationNative } = export const getLaunchNotification: GetLaunchNotification = async () => { assertIsInitialized(); + return getLaunchNotificationNative(); }; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getLaunchNotification.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getLaunchNotification.ts index fd85039bc2f..60d72444520 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getLaunchNotification.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getLaunchNotification.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; + import { PushNotificationMessage } from '../../../types'; import { GetLaunchNotification, GetLaunchNotificationOutput } from '../types'; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getPermissionStatus.native.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getPermissionStatus.native.ts index 2f11ad58ec2..1d9d09f8fbf 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getPermissionStatus.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getPermissionStatus.native.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { loadAmplifyPushNotification } from '@aws-amplify/react-native'; + import { assertIsInitialized } from '../../../errors/errorHelpers'; import { GetPermissionStatus } from '../types'; @@ -10,5 +11,6 @@ const { getPermissionStatus: getPermissionStatusNative } = export const getPermissionStatus: GetPermissionStatus = async () => { assertIsInitialized(); + return getPermissionStatusNative(); }; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getPermissionStatus.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getPermissionStatus.ts index 04c5f5ee758..a776273817b 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getPermissionStatus.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/getPermissionStatus.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; + import { GetPermissionStatus, GetPermissionStatusOutput } from '../types'; /** 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 ee1810f8018..880d3dc8a43 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/identifyUser.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/identifyUser.native.ts @@ -3,6 +3,7 @@ import { PushNotificationAction } from '@aws-amplify/core/internals/utils'; import { updateEndpoint } from '@aws-amplify/core/internals/providers/pinpoint'; + import { assertIsInitialized } from '../../../errors/errorHelpers'; import { getPushNotificationUserAgentString, diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/identifyUser.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/identifyUser.ts index 6659a1be7b8..054a3be0033 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/identifyUser.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/identifyUser.ts @@ -3,6 +3,7 @@ import { UpdateEndpointException } from '@aws-amplify/core/internals/providers/pinpoint'; import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; + import { PushNotificationValidationErrorCode } from '../../../errors'; import { IdentifyUser, IdentifyUserInput } from '../types'; 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 61cd0eb30ce..0e6de6f4212 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/initializePushNotifications.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/initializePushNotifications.native.ts @@ -5,6 +5,7 @@ import { ConsoleLogger } from '@aws-amplify/core'; import { PushNotificationAction } from '@aws-amplify/core/internals/utils'; import { updateEndpoint } from '@aws-amplify/core/internals/providers/pinpoint'; import { loadAmplifyPushNotification } from '@aws-amplify/react-native'; + import { EventListenerRemover, addEventListener, @@ -40,6 +41,7 @@ const BACKGROUND_TASK_TIMEOUT = 25; // seconds export const initializePushNotifications = (): void => { if (isInitialized()) { logger.info('Push notifications have already been enabled'); + return; } addNativeListeners(); @@ -48,9 +50,9 @@ export const initializePushNotifications = (): void => { }; const addNativeListeners = (): void => { - let launchNotificationOpenedListener: ReturnType< - typeof addMessageEventListener - > | null; + let launchNotificationOpenedListener: + | ReturnType + | undefined; const { NativeEvent, NativeHeadlessTaskKey } = getConstants(); const { BACKGROUND_MESSAGE_RECEIVED, @@ -85,14 +87,14 @@ const addNativeListeners = (): void => { // 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 // happening - new Promise((_, reject) => { - setTimeout( - () => - reject( + new Promise((_resolve, reject) => { + setTimeout(() => { + reject( + new Error( `onNotificationReceivedInBackground handlers should complete their work within ${BACKGROUND_TASK_TIMEOUT} seconds, but they did not.`, ), - BACKGROUND_TASK_TIMEOUT * 1000, - ); + ); + }, BACKGROUND_TASK_TIMEOUT * 1000); }), ]); } catch (err) { @@ -125,9 +127,10 @@ const addNativeListeners = (): void => { notifyEventListeners('launchNotificationOpened', message); // once we are done with it we can remove the listener launchNotificationOpenedListener?.remove(); + launchNotificationOpenedListener = undefined; }, ) - : null; + : undefined; addMessageEventListener( // listen for native notification opened (user tapped on notification, opening the app from background - @@ -178,7 +181,10 @@ const addAnalyticsListeners = (): void => { createMessageEventRecorder( 'opened_notification', // once we are done with it we can remove the listener - launchNotificationOpenedListenerRemover?.remove, + () => { + launchNotificationOpenedListenerRemover?.remove(); + launchNotificationOpenedListenerRemover = undefined; + }, ), ); addEventListener( @@ -186,7 +192,10 @@ const addAnalyticsListeners = (): void => { 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(); + launchNotificationOpenedListenerRemover = undefined; + }, ), ); }; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/initializePushNotifications.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/initializePushNotifications.ts index 009342a2df9..f1480687c1c 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/initializePushNotifications.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/initializePushNotifications.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; + import { InitializePushNotifications } from '../types'; /** diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationOpened.native.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationOpened.native.ts index a2694b0a02a..4458ae60198 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationOpened.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationOpened.native.ts @@ -7,5 +7,6 @@ import { OnNotificationOpened } from '../types'; export const onNotificationOpened: OnNotificationOpened = input => { assertIsInitialized(); + return addEventListener('notificationOpened', input); }; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationOpened.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationOpened.ts index 90570d0a484..217637e00b1 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationOpened.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationOpened.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; + import { PushNotificationMessage } from '../../../types'; import { OnNotificationOpened, diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.native.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.native.ts index b43f561ef0e..a97cc1a804d 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.native.ts @@ -8,5 +8,6 @@ import { OnNotificationReceivedInBackground } from '../types'; export const onNotificationReceivedInBackground: OnNotificationReceivedInBackground = input => { assertIsInitialized(); + return addEventListener('backgroundMessageReceived', input); }; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.ts index b47c03eaa36..87d63a72194 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInBackground.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; + import { PushNotificationMessage } from '../../../types'; import { OnNotificationReceivedInBackground, diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.native.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.native.ts index 6afd65e51bd..be0e4731181 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.native.ts @@ -8,5 +8,6 @@ import { OnNotificationReceivedInForeground } from '../types'; export const onNotificationReceivedInForeground: OnNotificationReceivedInForeground = input => { assertIsInitialized(); + return addEventListener('foregroundMessageReceived', input); }; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.ts index 1fed662673a..9d032712c8d 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onNotificationReceivedInForeground.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; + import { PushNotificationMessage } from '../../../types'; import { OnNotificationReceivedInForeground, diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onTokenReceived.native.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onTokenReceived.native.ts index 2d688a438df..29464da44de 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onTokenReceived.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onTokenReceived.native.ts @@ -7,5 +7,6 @@ import { OnTokenReceived } from '../types'; export const onTokenReceived: OnTokenReceived = input => { assertIsInitialized(); + return addEventListener('tokenReceived', input); }; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onTokenReceived.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onTokenReceived.ts index ab28b35392a..cf0fd2910ea 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onTokenReceived.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/onTokenReceived.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; + import { OnTokenReceived, OnTokenReceivedInput, diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/requestPermissions.native.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/requestPermissions.native.ts index f4a83901562..252d10cb47e 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/requestPermissions.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/requestPermissions.native.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { loadAmplifyPushNotification } from '@aws-amplify/react-native'; + import { assertIsInitialized } from '../../../errors/errorHelpers'; import { RequestPermissions } from '../types'; @@ -10,5 +11,6 @@ const { requestPermissions: requestPermissionsNative } = export const requestPermissions: RequestPermissions = async input => { assertIsInitialized(); + return requestPermissionsNative(input); }; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/requestPermissions.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/requestPermissions.ts index ef9e01d43b3..fc6b1579a2b 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/requestPermissions.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/requestPermissions.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; + import { RequestPermissions } from '../types'; /** diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/setBadgeCount.native.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/setBadgeCount.native.ts index dd8e3738d20..6b2e750615d 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/setBadgeCount.native.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/setBadgeCount.native.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { loadAmplifyPushNotification } from '@aws-amplify/react-native'; + import { assertIsInitialized } from '../../../errors/errorHelpers'; import { SetBadgeCount } from '../types'; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/setBadgeCount.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/setBadgeCount.ts index 6e0e767c18a..9f58eb8b010 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/apis/setBadgeCount.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/apis/setBadgeCount.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; + import { SetBadgeCount } from '../types'; /** diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/types/analytics.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/types/analytics.ts index 26a9617ca80..8ce79f54c96 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/types/analytics.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/types/analytics.ts @@ -8,7 +8,7 @@ export type PinpointMessageEvent = export type PinpointMessageEventSource = '_campaign' | '_journey'; -export type AnalyticsEventAttributes = { +export interface AnalyticsEventAttributes { source: PinpointMessageEventSource; attributes: Record; -}; +} diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/types/inputs.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/types/inputs.ts index 12128c68837..fc508f6285e 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/types/inputs.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/types/inputs.ts @@ -1,17 +1,18 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { IdentifyUserOptions } from './options'; import { PushNotificationIdentifyUserInput, - PushNotificationRequestPermissionsInput, - PushNotificationSetBadgeCountInput, PushNotificationOnNotificationOpenedInput, PushNotificationOnNotificationReceivedInBackgroundInput, PushNotificationOnNotificationReceivedInForegroundInput, PushNotificationOnTokenReceivedInput, + PushNotificationRequestPermissionsInput, + PushNotificationSetBadgeCountInput, } from '../../../types'; +import { IdentifyUserOptions } from './options'; + export type IdentifyUserInput = PushNotificationIdentifyUserInput; diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.ts index 38ae1173609..c02baee6f2a 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/createMessageEventRecorder.ts @@ -4,12 +4,14 @@ import { record } from '@aws-amplify/core/internals/providers/pinpoint'; import { ConsoleLogger } from '@aws-amplify/core'; import { AWSCredentials } from '@aws-amplify/core/internals/utils'; + import { PinpointMessageEvent } from '../types'; import { OnPushNotificationMessageHandler, PushNotificationMessage, } from '../../../types'; import { resolveCredentials } from '../../../utils'; + import { getAnalyticsEvent } from './getAnalyticsEvent'; import { getChannelType } from './getChannelType'; import { resolveConfig } from './resolveConfig'; @@ -22,7 +24,7 @@ const logger = new ConsoleLogger('PushNotification.recordMessageEvent'); export const createMessageEventRecorder = ( event: PinpointMessageEvent, - callback?: Function, + callback?: () => void, ): OnPushNotificationMessageHandler => async message => { const { credentials } = await resolveCredentials(); @@ -53,8 +55,10 @@ const recordMessageEvent = async ({ const analyticsEvent = getAnalyticsEvent(message, event); if (!analyticsEvent) { logger.debug('A notification missing event information was not recorded'); + return; } + return record({ appId, category: 'PushNotification', diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.ts index d0f69de6582..d55f1318581 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getAnalyticsEvent.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { PinpointAnalyticsEvent } from '@aws-amplify/core/internals/providers/pinpoint'; + import { AnalyticsEventAttributes, PinpointMessageEvent } from '../types'; import { PushNotificationMessage } from '../../../types'; @@ -25,6 +26,7 @@ export const getAnalyticsEvent = ( return null; } const { source, attributes } = eventAttributes; + return { attributes, name: `${source}.${event}`, @@ -37,7 +39,7 @@ const getAnalyticsEventAttributes = ( if (!data) { return; } - if (data.hasOwnProperty(ANDROID_CAMPAIGN_ID_KEY)) { + if (Object.prototype.hasOwnProperty.call(data, ANDROID_CAMPAIGN_ID_KEY)) { return { source: '_campaign', attributes: { diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getChannelType.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getChannelType.ts index 728f873c2b6..86368d4b21a 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getChannelType.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/getChannelType.ts @@ -3,6 +3,7 @@ import { PlatformNotSupportedError } from '@aws-amplify/core/internals/utils'; import { getOperatingSystem } from '@aws-amplify/react-native'; + import { ChannelType } from '../types'; const operatingSystem = getOperatingSystem(); diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/resolveConfig.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/resolveConfig.ts index a6a92beb454..65e08c82006 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/resolveConfig.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/resolveConfig.ts @@ -2,7 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import { Amplify } from '@aws-amplify/core'; -import { assert, PushNotificationValidationErrorCode } from '../../../errors'; + +import { PushNotificationValidationErrorCode, assert } from '../../../errors'; /** * @internal @@ -12,5 +13,6 @@ export const resolveConfig = () => { Amplify.getConfig().Notifications?.PushNotification?.Pinpoint ?? {}; assert(!!appId, PushNotificationValidationErrorCode.NoAppId); assert(!!region, PushNotificationValidationErrorCode.NoRegion); + return { appId, region }; }; diff --git a/packages/notifications/src/pushNotifications/types/inputs.ts b/packages/notifications/src/pushNotifications/types/inputs.ts index 994c345e658..48e43b39827 100644 --- a/packages/notifications/src/pushNotifications/types/inputs.ts +++ b/packages/notifications/src/pushNotifications/types/inputs.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { UserProfile } from '@aws-amplify/core'; + import { PushNotificationServiceOptions } from './options'; import { PushNotificationPermissions } from './module'; import { @@ -9,10 +10,10 @@ import { OnTokenReceivedHandler, } from './pushNotifications'; -export type PushNotificationIdentifyUserInput< +export interface PushNotificationIdentifyUserInput< ServiceOptions extends PushNotificationServiceOptions = PushNotificationServiceOptions, -> = { +> { /** * A User ID associated to the current device. */ @@ -27,7 +28,7 @@ export type PushNotificationIdentifyUserInput< * Options to be passed to the API. */ options?: ServiceOptions; -}; +} export type PushNotificationRequestPermissionsInput = PushNotificationPermissions; diff --git a/packages/notifications/src/pushNotifications/utils/getPushNotificationUserAgentString.ts b/packages/notifications/src/pushNotifications/utils/getPushNotificationUserAgentString.ts index e89ecfc1c33..766a1d4f475 100644 --- a/packages/notifications/src/pushNotifications/utils/getPushNotificationUserAgentString.ts +++ b/packages/notifications/src/pushNotifications/utils/getPushNotificationUserAgentString.ts @@ -1,8 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { - PushNotificationAction, Category, + PushNotificationAction, getAmplifyUserAgent, } from '@aws-amplify/core/internals/utils'; diff --git a/packages/notifications/src/pushNotifications/utils/resolveCredentials.ts b/packages/notifications/src/pushNotifications/utils/resolveCredentials.ts index 9067f56b1b8..3f0e37eecad 100644 --- a/packages/notifications/src/pushNotifications/utils/resolveCredentials.ts +++ b/packages/notifications/src/pushNotifications/utils/resolveCredentials.ts @@ -2,9 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { fetchAuthSession } from '@aws-amplify/core'; + import { - assert, PushNotificationValidationErrorCode, + assert, } from '../errors/errorHelpers'; /** @@ -13,5 +14,6 @@ import { export const resolveCredentials = async () => { const { credentials, identityId } = await fetchAuthSession(); assert(!!credentials, PushNotificationValidationErrorCode.NoCredentials); + return { credentials, identityId }; }; diff --git a/packages/notifications/tslint.json b/packages/notifications/tslint.json deleted file mode 100644 index 8eafab1d2b4..00000000000 --- a/packages/notifications/tslint.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "defaultSeverity": "error", - "plugins": ["prettier"], - "extends": [], - "jsRules": {}, - "rules": { - "prefer-const": true, - "max-line-length": [true, 120], - "no-empty-interface": true, - "no-var-keyword": true, - "object-literal-shorthand": true, - "no-eval": true, - "space-before-function-paren": [ - true, - { - "anonymous": "never", - "named": "never" - } - ], - "no-parameter-reassignment": true, - "align": [true, "parameters"], - "no-duplicate-imports": true, - "one-variable-per-declaration": [false, "ignore-for-loop"], - "triple-equals": [true, "allow-null-check"], - "comment-format": [true, "check-space"], - "indent": [false], - "whitespace": [ - false, - "check-branch", - "check-decl", - "check-operator", - "check-preblock" - ], - "eofline": true, - "variable-name": [ - true, - "check-format", - "allow-pascal-case", - "allow-snake-case", - "allow-leading-underscore" - ], - "semicolon": [ - true, - "always", - "ignore-interfaces", - "ignore-bound-class-methods" - ] - }, - "rulesDirectory": [] -}