@metamask-previews/notification-services-controller 1.0.0-preview-5dad659d → 1.0.0-preview-5b37150f
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/NotificationServicesController/NotificationServicesController.cjs +5 -2
- package/dist/NotificationServicesController/NotificationServicesController.cjs.map +1 -1
- package/dist/NotificationServicesController/NotificationServicesController.d.cts.map +1 -1
- package/dist/NotificationServicesController/NotificationServicesController.d.mts.map +1 -1
- package/dist/NotificationServicesController/NotificationServicesController.mjs +5 -2
- package/dist/NotificationServicesController/NotificationServicesController.mjs.map +1 -1
- package/dist/NotificationServicesPushController/NotificationServicesPushController.cjs +2 -0
- package/dist/NotificationServicesPushController/NotificationServicesPushController.cjs.map +1 -1
- package/dist/NotificationServicesPushController/NotificationServicesPushController.d.cts +4 -0
- package/dist/NotificationServicesPushController/NotificationServicesPushController.d.cts.map +1 -1
- package/dist/NotificationServicesPushController/NotificationServicesPushController.d.mts +4 -0
- package/dist/NotificationServicesPushController/NotificationServicesPushController.d.mts.map +1 -1
- package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs +2 -0
- package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs.map +1 -1
- package/dist/NotificationServicesPushController/mocks/mockResponse.cjs +2 -2
- package/dist/NotificationServicesPushController/mocks/mockResponse.cjs.map +1 -1
- package/dist/NotificationServicesPushController/mocks/mockResponse.mjs +2 -2
- package/dist/NotificationServicesPushController/mocks/mockResponse.mjs.map +1 -1
- package/dist/NotificationServicesPushController/services/services.cjs +6 -4
- package/dist/NotificationServicesPushController/services/services.cjs.map +1 -1
- package/dist/NotificationServicesPushController/services/services.d.cts +3 -0
- package/dist/NotificationServicesPushController/services/services.d.cts.map +1 -1
- package/dist/NotificationServicesPushController/services/services.d.mts +3 -0
- package/dist/NotificationServicesPushController/services/services.d.mts.map +1 -1
- package/dist/NotificationServicesPushController/services/services.mjs +6 -4
- package/dist/NotificationServicesPushController/services/services.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NotificationServicesPushController.mjs","sourceRoot":"","sources":["../../src/NotificationServicesPushController/NotificationServicesPushController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,IAAG,iBAAiB;;AAE3B,OAAO,EACL,yBAAyB,EACzB,2BAA2B,EAC3B,8BAA8B,EAC/B,gCAA4B;AAK7B,MAAM,cAAc,GAAG,oCAAoC,CAAC;AAyE5D,MAAM,CAAC,MAAM,YAAY,GAA4C;IACnE,aAAa,EAAE,IAAI;IACnB,QAAQ,EAAE,EAAE;IACZ,kBAAkB,EAAE,KAAK;CAC1B,CAAC;AACF,MAAM,QAAQ,GAA2D;IACvE,aAAa,EAAE;QACb,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IACD,QAAQ,EAAE;QACR,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IACD,kBAAkB,EAAE;QAClB,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,IAAI;KAChB;CACF,CAAC;AAEF,MAAM,cAAc,GAAwB;IAC1C,MAAM,EAAE,EAAE;IACV,UAAU,EAAE,EAAE;IACd,aAAa,EAAE,EAAE;IACjB,SAAS,EAAE,EAAE;IACb,iBAAiB,EAAE,EAAE;IACrB,KAAK,EAAE,EAAE;IACT,aAAa,EAAE,EAAE;IACjB,QAAQ,EAAE,EAAE;CACb,CAAC;AA4BF;;;;;;GAMG;AACH,MAAqB,kCAAmC,SAAQ,cAI/D;IAOC,YAAY,EACV,SAAS,EACT,KAAK,EACL,GAAG,EACH,MAAM,GAOP;QACC,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ;YACR,IAAI,EAAE,cAAc;YACpB,KAAK,EAAE,EAAE,GAAG,YAAY,EAAE,GAAG,KAAK,EAAE;SACrC,CAAC,CAAC;;QAvBL,sEAAqD,SA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,CAAC;AACrB,CAAC,qHAEgB,OAAqB;IACpC,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;QAC7B,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,aAAa,GAAG,IAAI,CAAC;YAC3B,KAAK,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;YAClC,KAAK,CAAC,kBAAkB,GAAG,KAAK,CAAC;QACnC,CAAC,CAAC,CAAC;KACJ;IAED,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE;QAC9B,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,aAAa,GAAG,KAAK,CAAC;YAC5B,KAAK,CAAC,QAAQ,GAAG,EAAE,CAAC;YACpB,KAAK,CAAC,kBAAkB,GAAG,KAAK,CAAC;QACnC,CAAC,CAAC,CAAC;KACJ;IAED,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;QAC7B,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,aAAa,GAAG,IAAI,CAAC;YAC3B,KAAK,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;YAClC,KAAK,CAAC,kBAAkB,GAAG,KAAK,CAAC;QACnC,CAAC,CAAC,CAAC;KACJ;AACH,CAAC;eApGkB,kCAAkC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport log from 'loglevel';\n\nimport {\n activatePushNotifications,\n deactivatePushNotifications,\n updateTriggerPushNotifications,\n} from './services/services';\nimport type { PushNotificationEnv } from './types';\nimport type { PushService } from './types/push-service-interface';\nimport type { Types } from '../NotificationServicesController';\n\nconst controllerName = 'NotificationServicesPushController';\n\nexport type NotificationServicesPushControllerState = {\n isPushEnabled: boolean;\n fcmToken: string;\n isUpdatingFCMToken: boolean;\n};\n\nexport type NotificationServicesPushControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerEnablePushNotificationsAction = {\n type: `${typeof controllerName}:enablePushNotifications`;\n handler: NotificationServicesPushController['enablePushNotifications'];\n};\nexport type NotificationServicesPushControllerDisablePushNotificationsAction = {\n type: `${typeof controllerName}:disablePushNotifications`;\n handler: NotificationServicesPushController['disablePushNotifications'];\n};\nexport type NotificationServicesPushControllerUpdateTriggerPushNotificationsAction =\n {\n type: `${typeof controllerName}:updateTriggerPushNotifications`;\n handler: NotificationServicesPushController['updateTriggerPushNotifications'];\n };\nexport type NotificationServicesPushControllerSubscribeToNotificationsAction = {\n type: `${typeof controllerName}:subscribeToPushNotifications`;\n handler: NotificationServicesPushController['subscribeToPushNotifications'];\n};\n\nexport type Actions =\n | NotificationServicesPushControllerGetStateAction\n | NotificationServicesPushControllerEnablePushNotificationsAction\n | NotificationServicesPushControllerDisablePushNotificationsAction\n | NotificationServicesPushControllerUpdateTriggerPushNotificationsAction\n | NotificationServicesPushControllerSubscribeToNotificationsAction;\n\nexport type AllowedActions =\n AuthenticationController.AuthenticationControllerGetBearerToken;\n\nexport type NotificationServicesPushControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerOnNewNotificationEvent = {\n type: `${typeof controllerName}:onNewNotifications`;\n payload: [Types.INotification];\n};\n\nexport type NotificationServicesPushControllerPushNotificationClickedEvent = {\n type: `${typeof controllerName}:pushNotificationClicked`;\n payload: [Types.INotification];\n};\n\nexport type Events =\n | NotificationServicesPushControllerStateChangeEvent\n | NotificationServicesPushControllerOnNewNotificationEvent\n | NotificationServicesPushControllerPushNotificationClickedEvent;\n\nexport type AllowedEvents = never;\n\nexport type NotificationServicesPushControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport const defaultState: NotificationServicesPushControllerState = {\n isPushEnabled: true,\n fcmToken: '',\n isUpdatingFCMToken: false,\n};\nconst metadata: StateMetadata<NotificationServicesPushControllerState> = {\n isPushEnabled: {\n persist: true,\n anonymous: true,\n },\n fcmToken: {\n persist: true,\n anonymous: true,\n },\n isUpdatingFCMToken: {\n persist: false,\n anonymous: true,\n },\n};\n\nconst defaultPushEnv: PushNotificationEnv = {\n apiKey: '',\n authDomain: '',\n storageBucket: '',\n projectId: '',\n messagingSenderId: '',\n appId: '',\n measurementId: '',\n vapidKey: '',\n};\n\nexport type ControllerConfig = {\n /**\n * Global switch to determine to use push notifications\n * Allows us to control Builds on extension (MV2 vs MV3)\n */\n isPushFeatureEnabled?: boolean;\n\n /**\n * determine the config used for push notification services\n */\n platform: 'extension' | 'mobile';\n\n /**\n * Push Service Interface\n * - create reg token\n * - delete reg token\n * - subscribe to push notifications\n */\n pushService: PushService;\n};\n\ntype StateCommand =\n | { type: 'enable'; fcmToken: string }\n | { type: 'disable' }\n | { type: 'update'; fcmToken: string };\n\n/**\n * Manages push notifications for the application, including enabling, disabling, and updating triggers for push notifications.\n * This controller integrates with Firebase Cloud Messaging (FCM) to handle the registration and management of push notifications.\n * It is responsible for registering and unregistering the service worker that listens for push notifications,\n * managing the FCM token, and communicating with the server to register or unregister the device for push notifications.\n * Additionally, it provides functionality to update the server with new UUIDs that should trigger push notifications.\n */\nexport default class NotificationServicesPushController extends BaseController<\n typeof controllerName,\n NotificationServicesPushControllerState,\n NotificationServicesPushControllerMessenger\n> {\n #pushListenerUnsubscribe: (() => void) | undefined = undefined;\n\n readonly #env: PushNotificationEnv;\n\n readonly #config: ControllerConfig;\n\n constructor({\n messenger,\n state,\n env,\n config,\n }: {\n messenger: NotificationServicesPushControllerMessenger;\n state: NotificationServicesPushControllerState;\n /** Push Environment is only required for extension */\n env?: PushNotificationEnv;\n config: ControllerConfig;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#env = env ?? defaultPushEnv;\n this.#config = config;\n\n this.#registerMessageHandlers();\n this.#clearLoadingStates();\n }\n\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:enablePushNotifications',\n this.enablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:disablePushNotifications',\n this.disablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:updateTriggerPushNotifications',\n this.updateTriggerPushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n this.subscribeToPushNotifications.bind(this),\n );\n }\n\n #clearLoadingStates(): void {\n this.update((state) => {\n state.isUpdatingFCMToken = false;\n });\n }\n\n async #getAndAssertBearerToken() {\n const bearerToken = await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n if (!bearerToken) {\n log.error(\n 'Failed to enable push notifications: BearerToken token is missing.',\n );\n throw new Error('BearerToken token is missing');\n }\n\n return bearerToken;\n }\n\n #updatePushState(command: StateCommand) {\n if (command.type === 'enable') {\n this.update((state) => {\n state.isPushEnabled = true;\n state.fcmToken = command.fcmToken;\n state.isUpdatingFCMToken = false;\n });\n }\n\n if (command.type === 'disable') {\n this.update((state) => {\n state.isPushEnabled = false;\n state.fcmToken = '';\n state.isUpdatingFCMToken = false;\n });\n }\n\n if (command.type === 'update') {\n this.update((state) => {\n state.isPushEnabled = true;\n state.fcmToken = command.fcmToken;\n state.isUpdatingFCMToken = false;\n });\n }\n }\n\n public async subscribeToPushNotifications() {\n if (!this.#config.isPushFeatureEnabled) {\n return;\n }\n\n if (this.#pushListenerUnsubscribe) {\n this.#pushListenerUnsubscribe();\n this.#pushListenerUnsubscribe = undefined;\n }\n\n try {\n this.#pushListenerUnsubscribe =\n (await this.#config.pushService.subscribeToPushNotifications(\n this.#env,\n )) ?? undefined;\n } catch {\n // Do nothing, we are silently failing if push notification registration fails\n }\n }\n\n /**\n * Enables push notifications for the application.\n *\n * This method sets up the necessary infrastructure for handling push notifications by:\n * 1. Registering the service worker to listen for messages.\n * 2. Fetching the Firebase Cloud Messaging (FCM) token from Firebase.\n * 3. Sending the FCM token to the server responsible for sending notifications, to register the device.\n *\n * @param UUIDs - An array of UUIDs to enable push notifications for.\n */\n public async enablePushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushFeatureEnabled) {\n return;\n }\n\n this.update((state) => {\n state.isUpdatingFCMToken = true;\n });\n\n // Handle creating new reg token (if available)\n try {\n const bearerToken = await this.#getAndAssertBearerToken().catch(\n () => null,\n );\n\n // If there is a bearer token, lets try to refresh/create new reg token\n if (bearerToken) {\n // Activate Push Notifications\n const fcmToken = await activatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n createRegToken: this.#config.pushService.createRegToken,\n platform: this.#config.platform,\n }).catch(() => null);\n\n if (fcmToken) {\n this.#updatePushState({ type: 'enable', fcmToken });\n }\n }\n } catch {\n // Do nothing, we are silently failing\n }\n\n // New token created, (re)subscribe to push notifications\n try {\n await this.subscribeToPushNotifications();\n } catch {\n // Do nothing we are silently failing\n }\n\n this.update((state) => {\n state.isUpdatingFCMToken = false;\n });\n }\n\n /**\n * Disables push notifications for the application.\n * This removes the registration token on this device, and ensures we unsubscribe from any listeners\n */\n public async disablePushNotifications() {\n if (!this.#config.isPushFeatureEnabled) {\n return;\n }\n\n this.update((state) => {\n state.isUpdatingFCMToken = true;\n });\n\n try {\n // Send a request to the server to unregister the token/device\n await deactivatePushNotifications({\n env: this.#env,\n deleteRegToken: this.#config.pushService.deleteRegToken,\n regToken: this.state.fcmToken,\n });\n } catch (error) {\n const errorMessage = `Failed to disable push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n } finally {\n this.update((state) => {\n state.isUpdatingFCMToken = false;\n });\n }\n\n // Unsubscribe from push notifications\n this.#pushListenerUnsubscribe?.();\n\n // Update State\n this.#updatePushState({ type: 'disable' });\n }\n\n /**\n * Updates the triggers for push notifications.\n * This method is responsible for updating the server with the new set of UUIDs that should trigger push notifications.\n * It uses the current FCM token and a BearerToken for authentication.\n *\n * @param UUIDs - An array of UUIDs that should trigger push notifications.\n */\n public async updateTriggerPushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushFeatureEnabled) {\n return;\n }\n\n this.update((state) => {\n state.isUpdatingFCMToken = true;\n });\n\n try {\n const bearerToken = await this.#getAndAssertBearerToken();\n const { fcmToken } = await updateTriggerPushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n createRegToken: this.#config.pushService.createRegToken,\n deleteRegToken: this.#config.pushService.deleteRegToken,\n platform: this.#config.platform,\n });\n\n // update the state with the new FCM token\n if (fcmToken) {\n this.#updatePushState({ type: 'update', fcmToken });\n }\n } catch (error) {\n const errorMessage = `Failed to update triggers for push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n } finally {\n this.update((state) => {\n state.isUpdatingFCMToken = false;\n });\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"NotificationServicesPushController.mjs","sourceRoot":"","sources":["../../src/NotificationServicesPushController/NotificationServicesPushController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAMA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,IAAG,iBAAiB;;AAE3B,OAAO,EACL,yBAAyB,EACzB,2BAA2B,EAC3B,8BAA8B,EAC/B,gCAA4B;AAK7B,MAAM,cAAc,GAAG,oCAAoC,CAAC;AAyE5D,MAAM,CAAC,MAAM,YAAY,GAA4C;IACnE,aAAa,EAAE,IAAI;IACnB,QAAQ,EAAE,EAAE;IACZ,kBAAkB,EAAE,KAAK;CAC1B,CAAC;AACF,MAAM,QAAQ,GAA2D;IACvE,aAAa,EAAE;QACb,O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AAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,aAAa,GAAG,KAAK,CAAC;YAC5B,KAAK,CAAC,QAAQ,GAAG,EAAE,CAAC;YACpB,KAAK,CAAC,kBAAkB,GAAG,KAAK,CAAC;QACnC,CAAC,CAAC,CAAC;KACJ;IAED,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;QAC7B,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,aAAa,GAAG,IAAI,CAAC;YAC3B,KAAK,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;YAClC,KAAK,CAAC,kBAAkB,GAAG,KAAK,CAAC;QACnC,CAAC,CAAC,CAAC;KACJ;AACH,CAAC;eApGkB,kCAAkC","sourcesContent":["import type {\n RestrictedMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { AuthenticationController } from '@metamask/profile-sync-controller';\nimport log from 'loglevel';\n\nimport {\n activatePushNotifications,\n deactivatePushNotifications,\n updateTriggerPushNotifications,\n} from './services/services';\nimport type { PushNotificationEnv } from './types';\nimport type { PushService } from './types/push-service-interface';\nimport type { Types } from '../NotificationServicesController';\n\nconst controllerName = 'NotificationServicesPushController';\n\nexport type NotificationServicesPushControllerState = {\n isPushEnabled: boolean;\n fcmToken: string;\n isUpdatingFCMToken: boolean;\n};\n\nexport type NotificationServicesPushControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerEnablePushNotificationsAction = {\n type: `${typeof controllerName}:enablePushNotifications`;\n handler: NotificationServicesPushController['enablePushNotifications'];\n};\nexport type NotificationServicesPushControllerDisablePushNotificationsAction = {\n type: `${typeof controllerName}:disablePushNotifications`;\n handler: NotificationServicesPushController['disablePushNotifications'];\n};\nexport type NotificationServicesPushControllerUpdateTriggerPushNotificationsAction =\n {\n type: `${typeof controllerName}:updateTriggerPushNotifications`;\n handler: NotificationServicesPushController['updateTriggerPushNotifications'];\n };\nexport type NotificationServicesPushControllerSubscribeToNotificationsAction = {\n type: `${typeof controllerName}:subscribeToPushNotifications`;\n handler: NotificationServicesPushController['subscribeToPushNotifications'];\n};\n\nexport type Actions =\n | NotificationServicesPushControllerGetStateAction\n | NotificationServicesPushControllerEnablePushNotificationsAction\n | NotificationServicesPushControllerDisablePushNotificationsAction\n | NotificationServicesPushControllerUpdateTriggerPushNotificationsAction\n | NotificationServicesPushControllerSubscribeToNotificationsAction;\n\nexport type AllowedActions =\n AuthenticationController.AuthenticationControllerGetBearerToken;\n\nexport type NotificationServicesPushControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n NotificationServicesPushControllerState\n >;\n\nexport type NotificationServicesPushControllerOnNewNotificationEvent = {\n type: `${typeof controllerName}:onNewNotifications`;\n payload: [Types.INotification];\n};\n\nexport type NotificationServicesPushControllerPushNotificationClickedEvent = {\n type: `${typeof controllerName}:pushNotificationClicked`;\n payload: [Types.INotification];\n};\n\nexport type Events =\n | NotificationServicesPushControllerStateChangeEvent\n | NotificationServicesPushControllerOnNewNotificationEvent\n | NotificationServicesPushControllerPushNotificationClickedEvent;\n\nexport type AllowedEvents = never;\n\nexport type NotificationServicesPushControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport const defaultState: NotificationServicesPushControllerState = {\n isPushEnabled: true,\n fcmToken: '',\n isUpdatingFCMToken: false,\n};\nconst metadata: StateMetadata<NotificationServicesPushControllerState> = {\n isPushEnabled: {\n persist: true,\n anonymous: true,\n },\n fcmToken: {\n persist: true,\n anonymous: true,\n },\n isUpdatingFCMToken: {\n persist: false,\n anonymous: true,\n },\n};\n\nconst defaultPushEnv: PushNotificationEnv = {\n apiKey: '',\n authDomain: '',\n storageBucket: '',\n projectId: '',\n messagingSenderId: '',\n appId: '',\n measurementId: '',\n vapidKey: '',\n};\n\nexport type ControllerConfig = {\n /**\n * User locale for server push notifications\n */\n getLocale?: () => string;\n\n /**\n * Global switch to determine to use push notifications\n * Allows us to control Builds on extension (MV2 vs MV3)\n */\n isPushFeatureEnabled?: boolean;\n\n /**\n * determine the config used for push notification services\n */\n platform: 'extension' | 'mobile';\n\n /**\n * Push Service Interface\n * - create reg token\n * - delete reg token\n * - subscribe to push notifications\n */\n pushService: PushService;\n};\n\ntype StateCommand =\n | { type: 'enable'; fcmToken: string }\n | { type: 'disable' }\n | { type: 'update'; fcmToken: string };\n\n/**\n * Manages push notifications for the application, including enabling, disabling, and updating triggers for push notifications.\n * This controller integrates with Firebase Cloud Messaging (FCM) to handle the registration and management of push notifications.\n * It is responsible for registering and unregistering the service worker that listens for push notifications,\n * managing the FCM token, and communicating with the server to register or unregister the device for push notifications.\n * Additionally, it provides functionality to update the server with new UUIDs that should trigger push notifications.\n */\nexport default class NotificationServicesPushController extends BaseController<\n typeof controllerName,\n NotificationServicesPushControllerState,\n NotificationServicesPushControllerMessenger\n> {\n #pushListenerUnsubscribe: (() => void) | undefined = undefined;\n\n readonly #env: PushNotificationEnv;\n\n readonly #config: ControllerConfig;\n\n constructor({\n messenger,\n state,\n env,\n config,\n }: {\n messenger: NotificationServicesPushControllerMessenger;\n state: NotificationServicesPushControllerState;\n /** Push Environment is only required for extension */\n env?: PushNotificationEnv;\n config: ControllerConfig;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#env = env ?? defaultPushEnv;\n this.#config = config;\n\n this.#registerMessageHandlers();\n this.#clearLoadingStates();\n }\n\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:enablePushNotifications',\n this.enablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:disablePushNotifications',\n this.disablePushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:updateTriggerPushNotifications',\n this.updateTriggerPushNotifications.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n 'NotificationServicesPushController:subscribeToPushNotifications',\n this.subscribeToPushNotifications.bind(this),\n );\n }\n\n #clearLoadingStates(): void {\n this.update((state) => {\n state.isUpdatingFCMToken = false;\n });\n }\n\n async #getAndAssertBearerToken() {\n const bearerToken = await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n if (!bearerToken) {\n log.error(\n 'Failed to enable push notifications: BearerToken token is missing.',\n );\n throw new Error('BearerToken token is missing');\n }\n\n return bearerToken;\n }\n\n #updatePushState(command: StateCommand) {\n if (command.type === 'enable') {\n this.update((state) => {\n state.isPushEnabled = true;\n state.fcmToken = command.fcmToken;\n state.isUpdatingFCMToken = false;\n });\n }\n\n if (command.type === 'disable') {\n this.update((state) => {\n state.isPushEnabled = false;\n state.fcmToken = '';\n state.isUpdatingFCMToken = false;\n });\n }\n\n if (command.type === 'update') {\n this.update((state) => {\n state.isPushEnabled = true;\n state.fcmToken = command.fcmToken;\n state.isUpdatingFCMToken = false;\n });\n }\n }\n\n public async subscribeToPushNotifications() {\n if (!this.#config.isPushFeatureEnabled) {\n return;\n }\n\n if (this.#pushListenerUnsubscribe) {\n this.#pushListenerUnsubscribe();\n this.#pushListenerUnsubscribe = undefined;\n }\n\n try {\n this.#pushListenerUnsubscribe =\n (await this.#config.pushService.subscribeToPushNotifications(\n this.#env,\n )) ?? undefined;\n } catch {\n // Do nothing, we are silently failing if push notification registration fails\n }\n }\n\n /**\n * Enables push notifications for the application.\n *\n * This method sets up the necessary infrastructure for handling push notifications by:\n * 1. Registering the service worker to listen for messages.\n * 2. Fetching the Firebase Cloud Messaging (FCM) token from Firebase.\n * 3. Sending the FCM token to the server responsible for sending notifications, to register the device.\n *\n * @param UUIDs - An array of UUIDs to enable push notifications for.\n */\n public async enablePushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushFeatureEnabled) {\n return;\n }\n\n this.update((state) => {\n state.isUpdatingFCMToken = true;\n });\n\n // Handle creating new reg token (if available)\n try {\n const bearerToken = await this.#getAndAssertBearerToken().catch(\n () => null,\n );\n\n // If there is a bearer token, lets try to refresh/create new reg token\n if (bearerToken) {\n // Activate Push Notifications\n const fcmToken = await activatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n createRegToken: this.#config.pushService.createRegToken,\n platform: this.#config.platform,\n locale: this.#config.getLocale?.() ?? 'en',\n }).catch(() => null);\n\n if (fcmToken) {\n this.#updatePushState({ type: 'enable', fcmToken });\n }\n }\n } catch {\n // Do nothing, we are silently failing\n }\n\n // New token created, (re)subscribe to push notifications\n try {\n await this.subscribeToPushNotifications();\n } catch {\n // Do nothing we are silently failing\n }\n\n this.update((state) => {\n state.isUpdatingFCMToken = false;\n });\n }\n\n /**\n * Disables push notifications for the application.\n * This removes the registration token on this device, and ensures we unsubscribe from any listeners\n */\n public async disablePushNotifications() {\n if (!this.#config.isPushFeatureEnabled) {\n return;\n }\n\n this.update((state) => {\n state.isUpdatingFCMToken = true;\n });\n\n try {\n // Send a request to the server to unregister the token/device\n await deactivatePushNotifications({\n env: this.#env,\n deleteRegToken: this.#config.pushService.deleteRegToken,\n regToken: this.state.fcmToken,\n });\n } catch (error) {\n const errorMessage = `Failed to disable push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n } finally {\n this.update((state) => {\n state.isUpdatingFCMToken = false;\n });\n }\n\n // Unsubscribe from push notifications\n this.#pushListenerUnsubscribe?.();\n\n // Update State\n this.#updatePushState({ type: 'disable' });\n }\n\n /**\n * Updates the triggers for push notifications.\n * This method is responsible for updating the server with the new set of UUIDs that should trigger push notifications.\n * It uses the current FCM token and a BearerToken for authentication.\n *\n * @param UUIDs - An array of UUIDs that should trigger push notifications.\n */\n public async updateTriggerPushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushFeatureEnabled) {\n return;\n }\n\n this.update((state) => {\n state.isUpdatingFCMToken = true;\n });\n\n try {\n const bearerToken = await this.#getAndAssertBearerToken();\n const { fcmToken } = await updateTriggerPushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n createRegToken: this.#config.pushService.createRegToken,\n deleteRegToken: this.#config.pushService.deleteRegToken,\n platform: this.#config.platform,\n locale: this.#config.getLocale?.() ?? 'en',\n });\n\n // update the state with the new FCM token\n if (fcmToken) {\n this.#updatePushState({ type: 'update', fcmToken });\n }\n } catch (error) {\n const errorMessage = `Failed to update triggers for push notifications: ${\n error as string\n }`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n } finally {\n this.update((state) => {\n state.isUpdatingFCMToken = false;\n });\n }\n }\n}\n"]}
|
|
@@ -6,8 +6,8 @@ exports.MOCK_REG_TOKEN = 'REG_TOKEN';
|
|
|
6
6
|
exports.MOCK_LINKS_RESPONSE = {
|
|
7
7
|
trigger_ids: ['1', '2', '3'],
|
|
8
8
|
registration_tokens: [
|
|
9
|
-
{ token: 'reg_token_1', platform: 'portfolio' },
|
|
10
|
-
{ token: 'reg_token_2', platform: 'extension' },
|
|
9
|
+
{ token: 'reg_token_1', platform: 'portfolio', locale: 'en' },
|
|
10
|
+
{ token: 'reg_token_2', platform: 'extension', locale: 'en' },
|
|
11
11
|
],
|
|
12
12
|
};
|
|
13
13
|
const getMockRetrievePushNotificationLinksResponse = () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockResponse.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/mocks/mockResponse.ts"],"names":[],"mappings":";;;AAAA,yDAAqE;AASxD,QAAA,cAAc,GAAG,WAAW,CAAC;AAC7B,QAAA,mBAAmB,GAAgB;IAC9C,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC;IAC5B,mBAAmB,EAAE;QACnB,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE;
|
|
1
|
+
{"version":3,"file":"mockResponse.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/mocks/mockResponse.ts"],"names":[],"mappings":";;;AAAA,yDAAqE;AASxD,QAAA,cAAc,GAAG,WAAW,CAAC;AAC7B,QAAA,mBAAmB,GAAgB;IAC9C,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC;IAC5B,mBAAmB,EAAE;QACnB,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE;QAC7D,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE;KAC9D;CACF,CAAC;AAEK,MAAM,4CAA4C,GAAG,GAAG,EAAE;IAC/D,OAAO;QACL,GAAG,EAAE,wCAA4B;QACjC,aAAa,EAAE,KAAK;QACpB,QAAQ,EAAE,2BAAmB;KACP,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,4CAA4C,gDAMvD;AAEK,MAAM,0CAA0C,GAAG,GAAG,EAAE;IAC7D,OAAO;QACL,GAAG,EAAE,wCAA4B;QACjC,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,IAAI;KACQ,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,0CAA0C,8CAMrD;AAEW,QAAA,iBAAiB,GAAG;IAC/B,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,WAAW;IAClB,GAAG,EAAE;QACH,QAAQ,EAAE,EAAE;QACZ,MAAM,EAAE,EAAE;QACV,IAAI,EAAE,EAAE;QACR,iBAAiB,EAAE,EAAE;KACtB;CACF,CAAC;AAEK,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,yBAAiB;KACL,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,yCAAyC,6CAMpD;AAEK,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,EAAE;KACU,CAAC;AAC3B,CAAC,CAAC;AANW,QAAA,yCAAyC,6CAMpD","sourcesContent":["import { REGISTRATION_TOKENS_ENDPOINT } from '../services/endpoints';\nimport type { LinksResult } from '../services/services';\n\ntype MockResponse = {\n url: string | RegExp;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const MOCK_REG_TOKEN = 'REG_TOKEN';\nexport const MOCK_LINKS_RESPONSE: LinksResult = {\n trigger_ids: ['1', '2', '3'],\n registration_tokens: [\n { token: 'reg_token_1', platform: 'portfolio', locale: 'en' },\n { token: 'reg_token_2', platform: 'extension', locale: 'en' },\n ],\n};\n\nexport const getMockRetrievePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_LINKS_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockUpdatePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'POST',\n response: null,\n } satisfies MockResponse;\n};\n\nexport const MOCK_FCM_RESPONSE = {\n name: '',\n token: 'fcm-token',\n web: {\n endpoint: '',\n p256dh: '',\n auth: '',\n applicationPubKey: '',\n },\n};\n\nexport const getMockCreateFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: MOCK_FCM_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockDeleteFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: {},\n } satisfies MockResponse;\n};\n"]}
|
|
@@ -3,8 +3,8 @@ export const MOCK_REG_TOKEN = 'REG_TOKEN';
|
|
|
3
3
|
export const MOCK_LINKS_RESPONSE = {
|
|
4
4
|
trigger_ids: ['1', '2', '3'],
|
|
5
5
|
registration_tokens: [
|
|
6
|
-
{ token: 'reg_token_1', platform: 'portfolio' },
|
|
7
|
-
{ token: 'reg_token_2', platform: 'extension' },
|
|
6
|
+
{ token: 'reg_token_1', platform: 'portfolio', locale: 'en' },
|
|
7
|
+
{ token: 'reg_token_2', platform: 'extension', locale: 'en' },
|
|
8
8
|
],
|
|
9
9
|
};
|
|
10
10
|
export const getMockRetrievePushNotificationLinksResponse = () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockResponse.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/mocks/mockResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,kCAA8B;AASrE,MAAM,CAAC,MAAM,cAAc,GAAG,WAAW,CAAC;AAC1C,MAAM,CAAC,MAAM,mBAAmB,GAAgB;IAC9C,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC;IAC5B,mBAAmB,EAAE;QACnB,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE;
|
|
1
|
+
{"version":3,"file":"mockResponse.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/mocks/mockResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,kCAA8B;AASrE,MAAM,CAAC,MAAM,cAAc,GAAG,WAAW,CAAC;AAC1C,MAAM,CAAC,MAAM,mBAAmB,GAAgB;IAC9C,WAAW,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC;IAC5B,mBAAmB,EAAE;QACnB,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE;QAC7D,EAAE,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE;KAC9D;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,4CAA4C,GAAG,GAAG,EAAE;IAC/D,OAAO;QACL,GAAG,EAAE,4BAA4B;QACjC,aAAa,EAAE,KAAK;QACpB,QAAQ,EAAE,mBAAmB;KACP,CAAC;AAC3B,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,0CAA0C,GAAG,GAAG,EAAE;IAC7D,OAAO;QACL,GAAG,EAAE,4BAA4B;QACjC,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,IAAI;KACQ,CAAC;AAC3B,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,WAAW;IAClB,GAAG,EAAE;QACH,QAAQ,EAAE,EAAE;QACZ,MAAM,EAAE,EAAE;QACV,IAAI,EAAE,EAAE;QACR,iBAAiB,EAAE,EAAE;KACtB;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,iBAAiB;KACL,CAAC;AAC3B,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,yCAAyC,GAAG,GAAG,EAAE;IAC5D,OAAO;QACL,GAAG,EAAE,kEAAkE;QACvE,aAAa,EAAE,MAAM;QACrB,QAAQ,EAAE,EAAE;KACU,CAAC;AAC3B,CAAC,CAAC","sourcesContent":["import { REGISTRATION_TOKENS_ENDPOINT } from '../services/endpoints';\nimport type { LinksResult } from '../services/services';\n\ntype MockResponse = {\n url: string | RegExp;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const MOCK_REG_TOKEN = 'REG_TOKEN';\nexport const MOCK_LINKS_RESPONSE: LinksResult = {\n trigger_ids: ['1', '2', '3'],\n registration_tokens: [\n { token: 'reg_token_1', platform: 'portfolio', locale: 'en' },\n { token: 'reg_token_2', platform: 'extension', locale: 'en' },\n ],\n};\n\nexport const getMockRetrievePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_LINKS_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockUpdatePushNotificationLinksResponse = () => {\n return {\n url: REGISTRATION_TOKENS_ENDPOINT,\n requestMethod: 'POST',\n response: null,\n } satisfies MockResponse;\n};\n\nexport const MOCK_FCM_RESPONSE = {\n name: '',\n token: 'fcm-token',\n web: {\n endpoint: '',\n p256dh: '',\n auth: '',\n applicationPubKey: '',\n },\n};\n\nexport const getMockCreateFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: MOCK_FCM_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockDeleteFCMRegistrationTokenResponse = () => {\n return {\n url: /^https:\\/\\/fcmregistrations\\.googleapis\\.com\\/v1\\/projects\\/.*$/u,\n requestMethod: 'POST',\n response: {},\n } satisfies MockResponse;\n};\n"]}
|
|
@@ -61,12 +61,14 @@ exports.updateLinksAPI = updateLinksAPI;
|
|
|
61
61
|
* @returns A promise that resolves with an object containing the success status and the BearerToken token.
|
|
62
62
|
*/
|
|
63
63
|
async function activatePushNotifications(params) {
|
|
64
|
-
const { bearerToken, triggers, env, createRegToken, platform } = params;
|
|
64
|
+
const { bearerToken, triggers, env, createRegToken, platform, locale } = params;
|
|
65
65
|
const regToken = await createRegToken(env).catch(() => null);
|
|
66
66
|
if (!regToken) {
|
|
67
67
|
return null;
|
|
68
68
|
}
|
|
69
|
-
await updateLinksAPI(bearerToken, triggers, [
|
|
69
|
+
await updateLinksAPI(bearerToken, triggers, [
|
|
70
|
+
{ token: regToken, platform, locale },
|
|
71
|
+
]);
|
|
70
72
|
return regToken;
|
|
71
73
|
}
|
|
72
74
|
exports.activatePushNotifications = activatePushNotifications;
|
|
@@ -101,14 +103,14 @@ exports.deactivatePushNotifications = deactivatePushNotifications;
|
|
|
101
103
|
* - fcmToken: the new or existing Firebase Cloud Messaging token used for the update, if applicable.
|
|
102
104
|
*/
|
|
103
105
|
async function updateTriggerPushNotifications(params) {
|
|
104
|
-
const { bearerToken, triggers, createRegToken, platform, deleteRegToken, env, } = params;
|
|
106
|
+
const { bearerToken, triggers, createRegToken, platform, locale, deleteRegToken, env, } = params;
|
|
105
107
|
await deleteRegToken(env);
|
|
106
108
|
const newRegToken = await createRegToken(env);
|
|
107
109
|
if (!newRegToken) {
|
|
108
110
|
throw new Error('Failed to create a new registration token');
|
|
109
111
|
}
|
|
110
112
|
const linksNotUpdated = await updateLinksAPI(bearerToken, triggers, [
|
|
111
|
-
{ token: newRegToken, platform },
|
|
113
|
+
{ token: newRegToken, platform, locale },
|
|
112
114
|
]);
|
|
113
115
|
if (!linksNotUpdated) {
|
|
114
116
|
throw new Error('Failed to create links to new reg token');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2DAAyC;
|
|
1
|
+
{"version":3,"file":"services.cjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2DAAyC;AAqBzC;;;;;;;GAOG;AACI,KAAK,UAAU,cAAc,CAClC,WAAmB,EACnB,QAAkB,EAClB,SAAqB;IAErB,IAAI;QACF,MAAM,IAAI,GAAgB;YACxB,WAAW,EAAE,QAAQ;YACrB,mBAAmB,EAAE,SAAS;SAC/B,CAAC;QACF,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,4BAA4B,EAAE;YACnE,MAAM,EAAE,MAAM;YACd,OAAO,EAAE;gBACP,aAAa,EAAE,UAAU,WAAW,EAAE;gBACtC,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Q,EACR,MAAM,EACN,cAAc,EACd,GAAG,GACJ,GAAG,MAAM,CAAC;IAEX,MAAM,cAAc,CAAC,GAAG,CAAC,CAAC;IAC1B,MAAM,WAAW,GAAG,MAAM,cAAc,CAAC,GAAG,CAAC,CAAC;IAC9C,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;KAC9D;IAED,MAAM,eAAe,GAAG,MAAM,cAAc,CAAC,WAAW,EAAE,QAAQ,EAAE;QAClE,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,EAAE;KACzC,CAAC,CAAC;IACH,IAAI,CAAC,eAAe,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;KAC5D;IAED,OAAO;QACL,QAAQ,EAAE,WAAW;KACtB,CAAC;AACJ,CAAC;AA/BD,wEA+BC","sourcesContent":["import * as endpoints from './endpoints';\nimport type { PushNotificationEnv } from '../types';\nimport type {\n CreateRegToken,\n DeleteRegToken,\n} from '../types/push-service-interface';\n\nexport type RegToken = {\n token: string;\n platform: 'extension' | 'mobile' | 'portfolio';\n locale: string;\n};\n\n/**\n * Links API Response Shape\n */\nexport type LinksResult = {\n trigger_ids: string[];\n registration_tokens: RegToken[];\n};\n\n/**\n * Updates the push notification links on a remote API.\n *\n * @param bearerToken - The JSON Web Token used for authorization.\n * @param triggers - An array of trigger identifiers.\n * @param regTokens - An array of registration tokens.\n * @returns A promise that resolves with true if the update was successful, false otherwise.\n */\nexport async function updateLinksAPI(\n bearerToken: string,\n triggers: string[],\n regTokens: RegToken[],\n): Promise<boolean> {\n try {\n const body: LinksResult = {\n trigger_ids: triggers,\n registration_tokens: regTokens,\n };\n const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${bearerToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n return response.status === 200;\n } catch {\n return false;\n }\n}\n\ntype ActivatePushNotificationsParams = {\n // Push Links\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n locale: string;\n};\n\n/**\n * Enables push notifications by registering the device and linking triggers.\n *\n * @param params - Activate Push Params\n * @returns A promise that resolves with an object containing the success status and the BearerToken token.\n */\nexport async function activatePushNotifications(\n params: ActivatePushNotificationsParams,\n): Promise<string | null> {\n const { bearerToken, triggers, env, createRegToken, platform, locale } =\n params;\n\n const regToken = await createRegToken(env).catch(() => null);\n if (!regToken) {\n return null;\n }\n\n await updateLinksAPI(bearerToken, triggers, [\n { token: regToken, platform, locale },\n ]);\n return regToken;\n}\n\ntype DeactivatePushNotificationsParams = {\n // Push Links\n regToken: string;\n\n // Push Un-registration\n env: PushNotificationEnv;\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Disables push notifications by removing the registration token\n * We do not need to unlink triggers, and remove old reg tokens (this is cleaned up in the back-end)\n *\n * @param params - Deactivate Push Params\n * @returns A promise that resolves with true if push notifications were successfully disabled, false otherwise.\n */\nexport async function deactivatePushNotifications(\n params: DeactivatePushNotificationsParams,\n): Promise<boolean> {\n const { regToken, env, deleteRegToken } = params;\n\n // if we don't have a reg token, then we can early return\n if (!regToken) {\n return true;\n }\n\n const isTokenRemovedFromFCM = await deleteRegToken(env);\n if (!isTokenRemovedFromFCM) {\n return false;\n }\n\n return true;\n}\n\ntype UpdateTriggerPushNotificationsParams = {\n // Push Links\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n locale: string;\n\n // Push Un-registration\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Updates the triggers linked to push notifications for a given registration token.\n * If the provided registration token does not exist or is not in the current set of registration tokens,\n * a new registration token is created and used for the update.\n *\n * @param params - Update Push Params\n * @returns A promise that resolves with an object containing:\n * - isTriggersLinkedToPushNotifications: boolean indicating if the triggers were successfully updated.\n * - fcmToken: the new or existing Firebase Cloud Messaging token used for the update, if applicable.\n */\nexport async function updateTriggerPushNotifications(\n params: UpdateTriggerPushNotificationsParams,\n): Promise<{\n fcmToken: string;\n}> {\n const {\n bearerToken,\n triggers,\n createRegToken,\n platform,\n locale,\n deleteRegToken,\n env,\n } = params;\n\n await deleteRegToken(env);\n const newRegToken = await createRegToken(env);\n if (!newRegToken) {\n throw new Error('Failed to create a new registration token');\n }\n\n const linksNotUpdated = await updateLinksAPI(bearerToken, triggers, [\n { token: newRegToken, platform, locale },\n ]);\n if (!linksNotUpdated) {\n throw new Error('Failed to create links to new reg token');\n }\n\n return {\n fcmToken: newRegToken,\n };\n}\n"]}
|
|
@@ -3,6 +3,7 @@ import type { CreateRegToken, DeleteRegToken } from "../types/push-service-inter
|
|
|
3
3
|
export type RegToken = {
|
|
4
4
|
token: string;
|
|
5
5
|
platform: 'extension' | 'mobile' | 'portfolio';
|
|
6
|
+
locale: string;
|
|
6
7
|
};
|
|
7
8
|
/**
|
|
8
9
|
* Links API Response Shape
|
|
@@ -26,6 +27,7 @@ type ActivatePushNotificationsParams = {
|
|
|
26
27
|
env: PushNotificationEnv;
|
|
27
28
|
createRegToken: CreateRegToken;
|
|
28
29
|
platform: 'extension' | 'mobile' | 'portfolio';
|
|
30
|
+
locale: string;
|
|
29
31
|
};
|
|
30
32
|
/**
|
|
31
33
|
* Enables push notifications by registering the device and linking triggers.
|
|
@@ -53,6 +55,7 @@ type UpdateTriggerPushNotificationsParams = {
|
|
|
53
55
|
env: PushNotificationEnv;
|
|
54
56
|
createRegToken: CreateRegToken;
|
|
55
57
|
platform: 'extension' | 'mobile' | 'portfolio';
|
|
58
|
+
locale: string;
|
|
56
59
|
deleteRegToken: DeleteRegToken;
|
|
57
60
|
};
|
|
58
61
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.d.cts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAAiB;AACpD,OAAO,KAAK,EACV,cAAc,EACd,cAAc,EACf,4CAAwC;AAEzC,MAAM,MAAM,QAAQ,GAAG;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"services.d.cts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAAiB;AACpD,OAAO,KAAK,EACV,cAAc,EACd,cAAc,EACf,4CAAwC;AAEzC,MAAM,MAAM,QAAQ,GAAG;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;IAC/C,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,mBAAmB,EAAE,QAAQ,EAAE,CAAC;CACjC,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAAE,EAClB,SAAS,EAAE,QAAQ,EAAE,GACpB,OAAO,CAAC,OAAO,CAAC,CAkBlB;AAED,KAAK,+BAA+B,GAAG;IAErC,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,EAAE,CAAC;IAGnB,GAAG,EAAE,mBAAmB,CAAC;IACzB,cAAc,EAAE,cAAc,CAAC;IAC/B,QAAQ,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;IAC/C,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,+BAA+B,GACtC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAaxB;AAED,KAAK,iCAAiC,GAAG;IAEvC,QAAQ,EAAE,MAAM,CAAC;IAGjB,GAAG,EAAE,mBAAmB,CAAC;IACzB,cAAc,EAAE,cAAc,CAAC;CAChC,CAAC;AAEF;;;;;;GAMG;AACH,wBAAsB,2BAA2B,CAC/C,MAAM,EAAE,iCAAiC,GACxC,OAAO,CAAC,OAAO,CAAC,CAclB;AAED,KAAK,oCAAoC,GAAG;IAE1C,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,EAAE,CAAC;IAGnB,GAAG,EAAE,mBAAmB,CAAC;IACzB,cAAc,EAAE,cAAc,CAAC;IAC/B,QAAQ,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;IAC/C,MAAM,EAAE,MAAM,CAAC;IAGf,cAAc,EAAE,cAAc,CAAC;CAChC,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,8BAA8B,CAClD,MAAM,EAAE,oCAAoC,GAC3C,OAAO,CAAC;IACT,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC,CA2BD"}
|
|
@@ -3,6 +3,7 @@ import type { CreateRegToken, DeleteRegToken } from "../types/push-service-inter
|
|
|
3
3
|
export type RegToken = {
|
|
4
4
|
token: string;
|
|
5
5
|
platform: 'extension' | 'mobile' | 'portfolio';
|
|
6
|
+
locale: string;
|
|
6
7
|
};
|
|
7
8
|
/**
|
|
8
9
|
* Links API Response Shape
|
|
@@ -26,6 +27,7 @@ type ActivatePushNotificationsParams = {
|
|
|
26
27
|
env: PushNotificationEnv;
|
|
27
28
|
createRegToken: CreateRegToken;
|
|
28
29
|
platform: 'extension' | 'mobile' | 'portfolio';
|
|
30
|
+
locale: string;
|
|
29
31
|
};
|
|
30
32
|
/**
|
|
31
33
|
* Enables push notifications by registering the device and linking triggers.
|
|
@@ -53,6 +55,7 @@ type UpdateTriggerPushNotificationsParams = {
|
|
|
53
55
|
env: PushNotificationEnv;
|
|
54
56
|
createRegToken: CreateRegToken;
|
|
55
57
|
platform: 'extension' | 'mobile' | 'portfolio';
|
|
58
|
+
locale: string;
|
|
56
59
|
deleteRegToken: DeleteRegToken;
|
|
57
60
|
};
|
|
58
61
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.d.mts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAAiB;AACpD,OAAO,KAAK,EACV,cAAc,EACd,cAAc,EACf,4CAAwC;AAEzC,MAAM,MAAM,QAAQ,GAAG;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"services.d.mts","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAAiB;AACpD,OAAO,KAAK,EACV,cAAc,EACd,cAAc,EACf,4CAAwC;AAEzC,MAAM,MAAM,QAAQ,GAAG;IACrB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;IAC/C,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,mBAAmB,EAAE,QAAQ,EAAE,CAAC;CACjC,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,cAAc,CAClC,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,EAAE,EAClB,SAAS,EAAE,QAAQ,EAAE,GACpB,OAAO,CAAC,OAAO,CAAC,CAkBlB;AAED,KAAK,+BAA+B,GAAG;IAErC,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,EAAE,CAAC;IAGnB,GAAG,EAAE,mBAAmB,CAAC;IACzB,cAAc,EAAE,cAAc,CAAC;IAC/B,QAAQ,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;IAC/C,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,+BAA+B,GACtC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAaxB;AAED,KAAK,iCAAiC,GAAG;IAEvC,QAAQ,EAAE,MAAM,CAAC;IAGjB,GAAG,EAAE,mBAAmB,CAAC;IACzB,cAAc,EAAE,cAAc,CAAC;CAChC,CAAC;AAEF;;;;;;GAMG;AACH,wBAAsB,2BAA2B,CAC/C,MAAM,EAAE,iCAAiC,GACxC,OAAO,CAAC,OAAO,CAAC,CAclB;AAED,KAAK,oCAAoC,GAAG;IAE1C,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,EAAE,CAAC;IAGnB,GAAG,EAAE,mBAAmB,CAAC;IACzB,cAAc,EAAE,cAAc,CAAC;IAC/B,QAAQ,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;IAC/C,MAAM,EAAE,MAAM,CAAC;IAGf,cAAc,EAAE,cAAc,CAAC;CAChC,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,8BAA8B,CAClD,MAAM,EAAE,oCAAoC,GAC3C,OAAO,CAAC;IACT,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC,CA2BD"}
|
|
@@ -34,12 +34,14 @@ export async function updateLinksAPI(bearerToken, triggers, regTokens) {
|
|
|
34
34
|
* @returns A promise that resolves with an object containing the success status and the BearerToken token.
|
|
35
35
|
*/
|
|
36
36
|
export async function activatePushNotifications(params) {
|
|
37
|
-
const { bearerToken, triggers, env, createRegToken, platform } = params;
|
|
37
|
+
const { bearerToken, triggers, env, createRegToken, platform, locale } = params;
|
|
38
38
|
const regToken = await createRegToken(env).catch(() => null);
|
|
39
39
|
if (!regToken) {
|
|
40
40
|
return null;
|
|
41
41
|
}
|
|
42
|
-
await updateLinksAPI(bearerToken, triggers, [
|
|
42
|
+
await updateLinksAPI(bearerToken, triggers, [
|
|
43
|
+
{ token: regToken, platform, locale },
|
|
44
|
+
]);
|
|
43
45
|
return regToken;
|
|
44
46
|
}
|
|
45
47
|
/**
|
|
@@ -72,14 +74,14 @@ export async function deactivatePushNotifications(params) {
|
|
|
72
74
|
* - fcmToken: the new or existing Firebase Cloud Messaging token used for the update, if applicable.
|
|
73
75
|
*/
|
|
74
76
|
export async function updateTriggerPushNotifications(params) {
|
|
75
|
-
const { bearerToken, triggers, createRegToken, platform, deleteRegToken, env, } = params;
|
|
77
|
+
const { bearerToken, triggers, createRegToken, platform, locale, deleteRegToken, env, } = params;
|
|
76
78
|
await deleteRegToken(env);
|
|
77
79
|
const newRegToken = await createRegToken(env);
|
|
78
80
|
if (!newRegToken) {
|
|
79
81
|
throw new Error('Failed to create a new registration token');
|
|
80
82
|
}
|
|
81
83
|
const linksNotUpdated = await updateLinksAPI(bearerToken, triggers, [
|
|
82
|
-
{ token: newRegToken, platform },
|
|
84
|
+
{ token: newRegToken, platform, locale },
|
|
83
85
|
]);
|
|
84
86
|
if (!linksNotUpdated) {
|
|
85
87
|
throw new Error('Failed to create links to new reg token');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,wBAAoB;
|
|
1
|
+
{"version":3,"file":"services.mjs","sourceRoot":"","sources":["../../../src/NotificationServicesPushController/services/services.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,wBAAoB;AAqBzC;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,WAAmB,EACnB,QAAkB,EAClB,SAAqB;IAErB,IAAI;QACF,MAAM,IAAI,GAAgB;YACxB,WAAW,EAAE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QAC1B,OAAO,KAAK,CAAC;KACd;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAiBD;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,MAA4C;IAI5C,MAAM,EACJ,WAAW,EACX,QAAQ,EACR,cAAc,EACd,QAAQ,EACR,MAAM,EACN,cAAc,EACd,GAAG,GACJ,GAAG,MAAM,CAAC;IAEX,MAAM,cAAc,CAAC,GAAG,CAAC,CAAC;IAC1B,MAAM,WAAW,GAAG,MAAM,cAAc,CAAC,GAAG,CAAC,CAAC;IAC9C,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;KAC9D;IAED,MAAM,eAAe,GAAG,MAAM,cAAc,CAAC,WAAW,EAAE,QAAQ,EAAE;QAClE,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,EAAE;KACzC,CAAC,CAAC;IACH,IAAI,CAAC,eAAe,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;KAC5D;IAED,OAAO;QACL,QAAQ,EAAE,WAAW;KACtB,CAAC;AACJ,CAAC","sourcesContent":["import * as endpoints from './endpoints';\nimport type { PushNotificationEnv } from '../types';\nimport type {\n CreateRegToken,\n DeleteRegToken,\n} from '../types/push-service-interface';\n\nexport type RegToken = {\n token: string;\n platform: 'extension' | 'mobile' | 'portfolio';\n locale: string;\n};\n\n/**\n * Links API Response Shape\n */\nexport type LinksResult = {\n trigger_ids: string[];\n registration_tokens: RegToken[];\n};\n\n/**\n * Updates the push notification links on a remote API.\n *\n * @param bearerToken - The JSON Web Token used for authorization.\n * @param triggers - An array of trigger identifiers.\n * @param regTokens - An array of registration tokens.\n * @returns A promise that resolves with true if the update was successful, false otherwise.\n */\nexport async function updateLinksAPI(\n bearerToken: string,\n triggers: string[],\n regTokens: RegToken[],\n): Promise<boolean> {\n try {\n const body: LinksResult = {\n trigger_ids: triggers,\n registration_tokens: regTokens,\n };\n const response = await fetch(endpoints.REGISTRATION_TOKENS_ENDPOINT, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${bearerToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n return response.status === 200;\n } catch {\n return false;\n }\n}\n\ntype ActivatePushNotificationsParams = {\n // Push Links\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n locale: string;\n};\n\n/**\n * Enables push notifications by registering the device and linking triggers.\n *\n * @param params - Activate Push Params\n * @returns A promise that resolves with an object containing the success status and the BearerToken token.\n */\nexport async function activatePushNotifications(\n params: ActivatePushNotificationsParams,\n): Promise<string | null> {\n const { bearerToken, triggers, env, createRegToken, platform, locale } =\n params;\n\n const regToken = await createRegToken(env).catch(() => null);\n if (!regToken) {\n return null;\n }\n\n await updateLinksAPI(bearerToken, triggers, [\n { token: regToken, platform, locale },\n ]);\n return regToken;\n}\n\ntype DeactivatePushNotificationsParams = {\n // Push Links\n regToken: string;\n\n // Push Un-registration\n env: PushNotificationEnv;\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Disables push notifications by removing the registration token\n * We do not need to unlink triggers, and remove old reg tokens (this is cleaned up in the back-end)\n *\n * @param params - Deactivate Push Params\n * @returns A promise that resolves with true if push notifications were successfully disabled, false otherwise.\n */\nexport async function deactivatePushNotifications(\n params: DeactivatePushNotificationsParams,\n): Promise<boolean> {\n const { regToken, env, deleteRegToken } = params;\n\n // if we don't have a reg token, then we can early return\n if (!regToken) {\n return true;\n }\n\n const isTokenRemovedFromFCM = await deleteRegToken(env);\n if (!isTokenRemovedFromFCM) {\n return false;\n }\n\n return true;\n}\n\ntype UpdateTriggerPushNotificationsParams = {\n // Push Links\n bearerToken: string;\n triggers: string[];\n\n // Push Registration\n env: PushNotificationEnv;\n createRegToken: CreateRegToken;\n platform: 'extension' | 'mobile' | 'portfolio';\n locale: string;\n\n // Push Un-registration\n deleteRegToken: DeleteRegToken;\n};\n\n/**\n * Updates the triggers linked to push notifications for a given registration token.\n * If the provided registration token does not exist or is not in the current set of registration tokens,\n * a new registration token is created and used for the update.\n *\n * @param params - Update Push Params\n * @returns A promise that resolves with an object containing:\n * - isTriggersLinkedToPushNotifications: boolean indicating if the triggers were successfully updated.\n * - fcmToken: the new or existing Firebase Cloud Messaging token used for the update, if applicable.\n */\nexport async function updateTriggerPushNotifications(\n params: UpdateTriggerPushNotificationsParams,\n): Promise<{\n fcmToken: string;\n}> {\n const {\n bearerToken,\n triggers,\n createRegToken,\n platform,\n locale,\n deleteRegToken,\n env,\n } = params;\n\n await deleteRegToken(env);\n const newRegToken = await createRegToken(env);\n if (!newRegToken) {\n throw new Error('Failed to create a new registration token');\n }\n\n const linksNotUpdated = await updateLinksAPI(bearerToken, triggers, [\n { token: newRegToken, platform, locale },\n ]);\n if (!linksNotUpdated) {\n throw new Error('Failed to create links to new reg token');\n }\n\n return {\n fcmToken: newRegToken,\n };\n}\n"]}
|
package/package.json
CHANGED