@metamask-previews/notification-services-controller 0.2.0-preview-c081c503 → 0.2.0-preview-1f29151
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.js +4 -3
- package/dist/NotificationServicesController/NotificationServicesController.mjs +3 -2
- package/dist/NotificationServicesController/index.js +11 -10
- package/dist/NotificationServicesController/index.mjs +10 -9
- package/dist/NotificationServicesController/services/onchain-notifications.js +3 -2
- package/dist/NotificationServicesController/services/onchain-notifications.mjs +2 -1
- package/dist/NotificationServicesController/types/feature-announcement/index.js +1 -1
- package/dist/NotificationServicesController/types/feature-announcement/index.mjs +1 -1
- package/dist/NotificationServicesController/types/index.js +3 -3
- package/dist/NotificationServicesController/types/index.mjs +3 -3
- package/dist/NotificationServicesPushController/NotificationServicesPushController.js +13 -12
- package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs +12 -11
- package/dist/NotificationServicesPushController/index.js +18 -17
- package/dist/NotificationServicesPushController/index.mjs +17 -16
- package/dist/NotificationServicesPushController/services/push/push-web.js +10 -9
- package/dist/NotificationServicesPushController/services/push/push-web.mjs +9 -8
- package/dist/NotificationServicesPushController/services/services.js +12 -11
- package/dist/NotificationServicesPushController/services/services.mjs +11 -10
- package/dist/NotificationServicesPushController/utils/get-notification-message.js +8 -7
- package/dist/NotificationServicesPushController/utils/get-notification-message.mjs +8 -7
- package/dist/NotificationServicesPushController/utils/index.js +8 -7
- package/dist/NotificationServicesPushController/utils/index.mjs +8 -7
- package/dist/{chunk-MT4VCZEE.js → chunk-2BCJRWFF.js} +6 -6
- package/dist/{chunk-CGQRVA4Q.js → chunk-323GXNRE.js} +53 -8
- package/dist/chunk-323GXNRE.js.map +1 -0
- package/dist/{chunk-GJHW5Z65.js → chunk-4HOEZMSV.js} +4 -4
- package/dist/{chunk-5TUHE2FM.js → chunk-6GXEFQ64.js} +11 -11
- package/dist/chunk-6GXEFQ64.js.map +1 -0
- package/dist/chunk-DINCLRZT.mjs +12 -0
- package/dist/chunk-DINCLRZT.mjs.map +1 -0
- package/dist/{chunk-W7PLAK7T.mjs → chunk-DQ4O52YU.mjs} +6 -6
- package/dist/chunk-DT6SLUWJ.js +12 -0
- package/dist/chunk-DT6SLUWJ.js.map +1 -0
- package/dist/{chunk-EZHMYHBX.mjs → chunk-FN6GVBCU.mjs} +9 -11
- package/dist/chunk-FN6GVBCU.mjs.map +1 -0
- package/dist/{chunk-72H2V4J5.js → chunk-GDKHOBJT.js} +7 -3
- package/dist/chunk-GDKHOBJT.js.map +1 -0
- package/dist/{chunk-DNVD3CHQ.js → chunk-H73GATCU.js} +9 -11
- package/dist/chunk-H73GATCU.js.map +1 -0
- package/dist/{chunk-R373BQEU.mjs → chunk-N4EKQQX7.mjs} +5 -5
- package/dist/{chunk-DSLFFOGF.mjs → chunk-OLYCBAVW.mjs} +48 -3
- package/dist/chunk-OLYCBAVW.mjs.map +1 -0
- package/dist/{chunk-ADYRLXWY.mjs → chunk-WGGW6VCR.mjs} +2 -2
- package/dist/{chunk-XVIUHFC3.mjs → chunk-X3ZU3HL7.mjs} +4 -4
- package/dist/{chunk-XVIUHFC3.mjs.map → chunk-X3ZU3HL7.mjs.map} +1 -1
- package/dist/{chunk-F2X3OS5R.js → chunk-X6BNWJOZ.js} +12 -12
- package/dist/{chunk-A5QFYBTR.mjs → chunk-YHVXD5WW.mjs} +7 -3
- package/dist/chunk-YHVXD5WW.mjs.map +1 -0
- package/dist/index.js +16 -15
- package/dist/index.mjs +15 -14
- package/dist/shared/to-raw-notification.js +8 -0
- package/dist/shared/to-raw-notification.js.map +1 -0
- package/dist/shared/to-raw-notification.mjs +8 -0
- package/dist/shared/to-raw-notification.mjs.map +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/NotificationServicesController/NotificationServicesController.d.ts +14 -5
- package/dist/types/NotificationServicesController/NotificationServicesController.d.ts.map +1 -1
- package/dist/types/NotificationServicesController/services/onchain-notifications.d.ts.map +1 -1
- package/dist/types/NotificationServicesController/types/on-chain-notification/on-chain-notification.d.ts +1 -0
- package/dist/types/NotificationServicesController/types/on-chain-notification/on-chain-notification.d.ts.map +1 -1
- package/dist/types/NotificationServicesPushController/services/push/push-web.d.ts.map +1 -1
- package/dist/types/shared/to-raw-notification.d.ts +11 -0
- package/dist/types/shared/to-raw-notification.d.ts.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-5TUHE2FM.js.map +0 -1
- package/dist/chunk-72H2V4J5.js.map +0 -1
- package/dist/chunk-A5QFYBTR.mjs.map +0 -1
- package/dist/chunk-CGQRVA4Q.js.map +0 -1
- package/dist/chunk-DNVD3CHQ.js.map +0 -1
- package/dist/chunk-DSLFFOGF.mjs.map +0 -1
- package/dist/chunk-EZHMYHBX.mjs.map +0 -1
- /package/dist/{chunk-MT4VCZEE.js.map → chunk-2BCJRWFF.js.map} +0 -0
- /package/dist/{chunk-GJHW5Z65.js.map → chunk-4HOEZMSV.js.map} +0 -0
- /package/dist/{chunk-W7PLAK7T.mjs.map → chunk-DQ4O52YU.mjs.map} +0 -0
- /package/dist/{chunk-R373BQEU.mjs.map → chunk-N4EKQQX7.mjs.map} +0 -0
- /package/dist/{chunk-ADYRLXWY.mjs.map → chunk-WGGW6VCR.mjs.map} +0 -0
- /package/dist/{chunk-F2X3OS5R.js.map → chunk-X6BNWJOZ.js.map} +0 -0
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunk4HOEZMSVjs = require('./chunk-4HOEZMSV.js');
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
var
|
|
10
|
+
var _chunkGDKHOBJTjs = require('./chunk-GDKHOBJT.js');
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
|
|
@@ -67,17 +67,17 @@ var NotificationServicesPushController = class extends _basecontroller.BaseContr
|
|
|
67
67
|
}
|
|
68
68
|
const bearerToken = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getAndAssertBearerToken, getAndAssertBearerToken_fn).call(this);
|
|
69
69
|
try {
|
|
70
|
-
const regToken = await
|
|
70
|
+
const regToken = await _chunk4HOEZMSVjs.activatePushNotifications.call(void 0, {
|
|
71
71
|
bearerToken,
|
|
72
72
|
triggers: UUIDs,
|
|
73
73
|
env: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _env),
|
|
74
|
-
createRegToken:
|
|
74
|
+
createRegToken: _chunkGDKHOBJTjs.createRegToken,
|
|
75
75
|
platform: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _config).platform
|
|
76
76
|
});
|
|
77
77
|
if (!regToken) {
|
|
78
78
|
return;
|
|
79
79
|
}
|
|
80
|
-
_chunkIGY2S5BCjs.__privateSet.call(void 0, this, _pushListenerUnsubscribe, await
|
|
80
|
+
_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _pushListenerUnsubscribe) ?? _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _pushListenerUnsubscribe, await _chunk4HOEZMSVjs.listenToPushNotifications.call(void 0, {
|
|
81
81
|
env: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _env),
|
|
82
82
|
listenToPushReceived: async (n) => {
|
|
83
83
|
this.messagingSystem.publish(
|
|
@@ -121,11 +121,11 @@ var NotificationServicesPushController = class extends _basecontroller.BaseContr
|
|
|
121
121
|
const bearerToken = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getAndAssertBearerToken, getAndAssertBearerToken_fn).call(this);
|
|
122
122
|
let isPushNotificationsDisabled;
|
|
123
123
|
try {
|
|
124
|
-
isPushNotificationsDisabled = await
|
|
124
|
+
isPushNotificationsDisabled = await _chunk4HOEZMSVjs.deactivatePushNotifications.call(void 0, {
|
|
125
125
|
bearerToken,
|
|
126
126
|
triggers: UUIDs,
|
|
127
127
|
env: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _env),
|
|
128
|
-
deleteRegToken:
|
|
128
|
+
deleteRegToken: _chunkGDKHOBJTjs.deleteRegToken,
|
|
129
129
|
regToken: this.state.fcmToken
|
|
130
130
|
});
|
|
131
131
|
} catch (error) {
|
|
@@ -156,12 +156,12 @@ var NotificationServicesPushController = class extends _basecontroller.BaseContr
|
|
|
156
156
|
}
|
|
157
157
|
const bearerToken = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getAndAssertBearerToken, getAndAssertBearerToken_fn).call(this);
|
|
158
158
|
try {
|
|
159
|
-
const { fcmToken } = await
|
|
159
|
+
const { fcmToken } = await _chunk4HOEZMSVjs.updateTriggerPushNotifications.call(void 0, {
|
|
160
160
|
bearerToken,
|
|
161
161
|
triggers: UUIDs,
|
|
162
162
|
env: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _env),
|
|
163
|
-
createRegToken:
|
|
164
|
-
deleteRegToken:
|
|
163
|
+
createRegToken: _chunkGDKHOBJTjs.createRegToken,
|
|
164
|
+
deleteRegToken: _chunkGDKHOBJTjs.deleteRegToken,
|
|
165
165
|
platform: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _config).platform,
|
|
166
166
|
regToken: this.state.fcmToken
|
|
167
167
|
});
|
|
@@ -213,4 +213,4 @@ getAndAssertBearerToken_fn = async function() {
|
|
|
213
213
|
|
|
214
214
|
|
|
215
215
|
exports.defaultState = defaultState; exports.NotificationServicesPushController = NotificationServicesPushController;
|
|
216
|
-
//# sourceMappingURL=chunk-
|
|
216
|
+
//# sourceMappingURL=chunk-6GXEFQ64.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/NotificationServicesPushController/NotificationServicesPushController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAIA,SAAS,sBAAsB;AAE/B,OAAO,SAAS;AAYhB,IAAM,iBAAiB;AAqDhB,IAAM,eAAwD;AAAA,EACnE,UAAU;AACZ;AACA,IAAM,WAAW;AAAA,EACf,UAAU;AAAA,IACR,SAAS;AAAA,IACT,WAA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H;AAAA,IACF,SAAS,OAAO;AACd,YAAM,eAAe,qDACnB,KACF;AACA,UAAI,MAAM,YAAY;AACtB,YAAM,IAAI,MAAM,YAAY;AAAA,IAC9B;AAAA,EACF;AACF;AAlNE;AAEA;AAEA;AA0BA;AAAA,6BAAwB,WAAS;AAC/B,OAAK,gBAAgB;AAAA,IACnB;AAAA,IACA,KAAK,wBAAwB,KAAK,IAAI;AAAA,EACxC;AACA,OAAK,gBAAgB;AAAA,IACnB;AAAA,IACA,KAAK,yBAAyB,KAAK,IAAI;AAAA,EACzC;AACA,OAAK,gBAAgB;AAAA,IACnB;AAAA,IACA,KAAK,+BAA+B,KAAK,IAAI;AAAA,EAC/C;AACF;AAEM;AAAA,6BAAwB,iBAAG;AAC/B,QAAM,cAAc,MAAM,KAAK,gBAAgB;AAAA,IAC7C;AAAA,EACF;AACA,MAAI,CAAC,aAAa;AAChB,QAAI;AAAA,MACF;AAAA,IACF;AACA,UAAM,IAAI,MAAM,8BAA8B;AAAA,EAChD;AAEA,SAAO;AACT","sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\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 type { Types } from '../NotificationServicesController';\nimport { createRegToken, deleteRegToken } from './services/push/push-web';\nimport {\n activatePushNotifications,\n deactivatePushNotifications,\n listenToPushNotifications,\n updateTriggerPushNotifications,\n} from './services/services';\nimport type { PushNotificationEnv } from './types';\n\nconst controllerName = 'NotificationServicesPushController';\n\nexport type NotificationServicesPushControllerState = {\n fcmToken: string;\n};\n\nexport type NotificationServicesPushControllerEnablePushNotificationsAction = {\n type: `${typeof controllerName}:enablePushNotifications`;\n handler: NotificationServicesPushController['enablePushNotifications'];\n};\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 };\n\nexport type Actions =\n | NotificationServicesPushControllerEnablePushNotificationsAction\n | NotificationServicesPushControllerDisablePushNotificationsAction\n | NotificationServicesPushControllerUpdateTriggerPushNotificationsAction\n | ControllerGetStateAction<'state', NotificationServicesPushControllerState>;\n\nexport type AllowedActions =\n AuthenticationController.AuthenticationControllerGetBearerToken;\n\nexport type NotificationServicesPushControllerOnNewNotificationEvent = {\n type: `${typeof controllerName}:onNewNotifications`;\n payload: [Types.INotification];\n};\n\nexport type NotificationServicesPushControllerPushNotificationClicked = {\n type: `${typeof controllerName}:pushNotificationClicked`;\n payload: [Types.INotification];\n};\n\nexport type AllowedEvents =\n | NotificationServicesPushControllerOnNewNotificationEvent\n | NotificationServicesPushControllerPushNotificationClicked;\n\nexport type NotificationServicesPushControllerMessenger =\n RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n >;\n\nexport const defaultState: NotificationServicesPushControllerState = {\n fcmToken: '',\n};\nconst metadata = {\n fcmToken: {\n persist: true,\n anonymous: true,\n },\n};\n\ntype ControllerConfig = {\n /**\n * Config to turn on/off push notifications.\n * This is currently linked to MV3 builds on extension.\n */\n isPushEnabled: boolean;\n\n /**\n * Must handle when a push notification is received.\n * You must call `registration.showNotification` or equivalent to show the notification on web/mobile\n */\n onPushNotificationReceived: (\n notification: Types.INotification,\n ) => void | Promise<void>;\n\n /**\n * Must handle when a push notification is clicked.\n * You must call `event.notification.close();` or equivalent for closing and opening notification in a new window.\n */\n onPushNotificationClicked: (\n event: NotificationEvent,\n notification?: Types.INotification,\n ) => void;\n\n /**\n * determine the config used for push notification services\n */\n platform: 'extension' | 'mobile';\n};\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 *\n * @augments {BaseController<typeof controllerName, NotificationServicesPushControllerState, NotificationServicesPushControllerMessenger>}\n */\nexport default class NotificationServicesPushController extends BaseController<\n typeof controllerName,\n NotificationServicesPushControllerState,\n NotificationServicesPushControllerMessenger\n> {\n #pushListenerUnsubscribe: (() => void) | undefined = undefined;\n\n #env: PushNotificationEnv;\n\n #config: ControllerConfig;\n\n constructor({\n messenger,\n state,\n env,\n config,\n }: {\n messenger: NotificationServicesPushControllerMessenger;\n state: NotificationServicesPushControllerState;\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;\n this.#config = config;\n\n this.#registerMessageHandlers();\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 }\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 /**\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 async enablePushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n const bearerToken = await this.#getAndAssertBearerToken();\n\n try {\n // Activate Push Notifications\n const regToken = await activatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n createRegToken,\n platform: this.#config.platform,\n });\n\n if (!regToken) {\n return;\n }\n\n this.#pushListenerUnsubscribe ??= await listenToPushNotifications({\n env: this.#env,\n listenToPushReceived: async (n) => {\n this.messagingSystem.publish(\n 'NotificationServicesPushController:onNewNotifications',\n n,\n );\n await this.#config.onPushNotificationReceived(n);\n },\n listenToPushClicked: (e, n) => {\n if (n) {\n this.messagingSystem.publish(\n 'NotificationServicesPushController:pushNotificationClicked',\n n,\n );\n }\n\n this.#config.onPushNotificationClicked(e);\n },\n });\n\n // Update state\n this.update((state) => {\n state.fcmToken = regToken;\n });\n } catch (error) {\n log.error('Failed to enable push notifications:', error);\n throw new Error('Failed to enable push notifications');\n }\n }\n\n /**\n * Disables push notifications for the application.\n * This method handles the process of disabling push notifications by:\n * 1. Unregistering the service worker to stop listening for messages.\n * 2. Sending a request to the server to unregister the device using the FCM token.\n * 3. Removing the FCM token from the state to complete the process.\n *\n * @param UUIDs - An array of UUIDs for which push notifications should be disabled.\n */\n async disablePushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n const bearerToken = await this.#getAndAssertBearerToken();\n let isPushNotificationsDisabled: boolean;\n\n try {\n // Send a request to the server to unregister the token/device\n isPushNotificationsDisabled = await deactivatePushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n 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 }\n\n // Remove the FCM token from the state\n if (!isPushNotificationsDisabled) {\n return;\n }\n\n // Unsubscribe from push notifications\n this.#pushListenerUnsubscribe?.();\n\n // Update State\n if (isPushNotificationsDisabled) {\n this.update((state) => {\n state.fcmToken = '';\n });\n }\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 async updateTriggerPushNotifications(UUIDs: string[]) {\n if (!this.#config.isPushEnabled) {\n return;\n }\n\n const bearerToken = await this.#getAndAssertBearerToken();\n\n try {\n const { fcmToken } = await updateTriggerPushNotifications({\n bearerToken,\n triggers: UUIDs,\n env: this.#env,\n createRegToken,\n deleteRegToken,\n platform: this.#config.platform,\n regToken: this.state.fcmToken,\n });\n\n // update the state with the new FCM token\n if (fcmToken) {\n this.update((state) => {\n state.fcmToken = fcmToken;\n });\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 }\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/shared/to-raw-notification.ts"],"sourcesContent":["import type {\n OnChainRawNotification,\n UnprocessedOnChainRawNotification,\n} from 'src/NotificationServicesController/types';\n\n/**\n * A true \"raw notification\" does not have some fields that exist on this type. E.g. the `type` field.\n * This is retro-actively added when we fetch notifications to be able to easily type-discriminate notifications.\n * We use this to ensure that the correct missing fields are added to the raw shapes\n *\n * @param data - raw onchain notification\n * @returns a complete raw onchain notification\n */\nexport function toRawOnChainNotification(\n data: UnprocessedOnChainRawNotification,\n): OnChainRawNotification {\n return {\n ...data,\n type: data?.data?.kind,\n } as OnChainRawNotification;\n}\n"],"mappings":";AAaO,SAAS,yBACd,MACwB;AACxB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,MAAM,MAAM,MAAM;AAAA,EACpB;AACF;","names":[]}
|
|
@@ -7,10 +7,13 @@ import {
|
|
|
7
7
|
import {
|
|
8
8
|
types_exports
|
|
9
9
|
} from "./chunk-B4ECJJ5C.mjs";
|
|
10
|
+
import {
|
|
11
|
+
constants_exports
|
|
12
|
+
} from "./chunk-ZHAD55AN.mjs";
|
|
10
13
|
import {
|
|
11
14
|
NotificationServicesController,
|
|
12
15
|
defaultState
|
|
13
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-OLYCBAVW.mjs";
|
|
14
17
|
import {
|
|
15
18
|
FEATURE_ANNOUNCEMENT_API
|
|
16
19
|
} from "./chunk-QFJZBLYQ.mjs";
|
|
@@ -18,13 +21,10 @@ import {
|
|
|
18
21
|
NOTIFICATION_API_LIST_ENDPOINT,
|
|
19
22
|
NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT,
|
|
20
23
|
TRIGGER_API_BATCH_ENDPOINT
|
|
21
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-FN6GVBCU.mjs";
|
|
22
25
|
import {
|
|
23
26
|
initializeUserStorage
|
|
24
27
|
} from "./chunk-ILPTPB4U.mjs";
|
|
25
|
-
import {
|
|
26
|
-
constants_exports
|
|
27
|
-
} from "./chunk-ZHAD55AN.mjs";
|
|
28
28
|
import {
|
|
29
29
|
USER_STORAGE_VERSION_KEY
|
|
30
30
|
} from "./chunk-6ZDVTRRT.mjs";
|
|
@@ -926,4 +926,4 @@ export {
|
|
|
926
926
|
fixtures_exports,
|
|
927
927
|
NotificationServicesController_exports
|
|
928
928
|
};
|
|
929
|
-
//# sourceMappingURL=chunk-
|
|
929
|
+
//# sourceMappingURL=chunk-DQ4O52YU.mjs.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/shared/to-raw-notification.ts
|
|
2
|
+
function toRawOnChainNotification(data) {
|
|
3
|
+
return {
|
|
4
|
+
...data,
|
|
5
|
+
type: data?.data?.kind
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
exports.toRawOnChainNotification = toRawOnChainNotification;
|
|
12
|
+
//# sourceMappingURL=chunk-DT6SLUWJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/shared/to-raw-notification.ts"],"names":[],"mappings":";AAaO,SAAS,yBACd,MACwB;AACxB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,MAAM,MAAM,MAAM;AAAA,EACpB;AACF","sourcesContent":["import type {\n OnChainRawNotification,\n UnprocessedOnChainRawNotification,\n} from 'src/NotificationServicesController/types';\n\n/**\n * A true \"raw notification\" does not have some fields that exist on this type. E.g. the `type` field.\n * This is retro-actively added when we fetch notifications to be able to easily type-discriminate notifications.\n * We use this to ensure that the correct missing fields are added to the raw shapes\n *\n * @param data - raw onchain notification\n * @returns a complete raw onchain notification\n */\nexport function toRawOnChainNotification(\n data: UnprocessedOnChainRawNotification,\n): OnChainRawNotification {\n return {\n ...data,\n type: data?.data?.kind,\n } as OnChainRawNotification;\n}\n"]}
|
|
@@ -3,6 +3,9 @@ import {
|
|
|
3
3
|
toggleUserStorageTriggerStatus,
|
|
4
4
|
traverseUserStorageTriggers
|
|
5
5
|
} from "./chunk-ILPTPB4U.mjs";
|
|
6
|
+
import {
|
|
7
|
+
toRawOnChainNotification
|
|
8
|
+
} from "./chunk-DINCLRZT.mjs";
|
|
6
9
|
|
|
7
10
|
// src/NotificationServicesController/services/onchain-notifications.ts
|
|
8
11
|
import { UserStorageController } from "@metamask/profile-sync-controller";
|
|
@@ -122,17 +125,12 @@ async function getOnChainNotifications(userStorage, bearerToken) {
|
|
|
122
125
|
{ trigger_ids: triggerIds }
|
|
123
126
|
);
|
|
124
127
|
const notifications = await response.json();
|
|
125
|
-
const transformedNotifications = notifications.map(
|
|
126
|
-
(n)
|
|
127
|
-
|
|
128
|
-
return void 0;
|
|
129
|
-
}
|
|
130
|
-
return {
|
|
131
|
-
...n,
|
|
132
|
-
type: n.data.kind
|
|
133
|
-
};
|
|
128
|
+
const transformedNotifications = notifications.map((n) => {
|
|
129
|
+
if (!n.data?.kind) {
|
|
130
|
+
return void 0;
|
|
134
131
|
}
|
|
135
|
-
|
|
132
|
+
return toRawOnChainNotification(n);
|
|
133
|
+
}).filter((n) => Boolean(n));
|
|
136
134
|
onChainNotifications.push(...transformedNotifications);
|
|
137
135
|
if (notifications.length < 100) {
|
|
138
136
|
page = PAGE_LIMIT + 1;
|
|
@@ -184,4 +182,4 @@ export {
|
|
|
184
182
|
getOnChainNotifications,
|
|
185
183
|
markNotificationsAsRead
|
|
186
184
|
};
|
|
187
|
-
//# sourceMappingURL=chunk-
|
|
185
|
+
//# sourceMappingURL=chunk-FN6GVBCU.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/NotificationServicesController/services/onchain-notifications.ts"],"sourcesContent":["import { UserStorageController } from '@metamask/profile-sync-controller';\nimport log from 'loglevel';\n\nimport { toRawOnChainNotification } from '../../shared/to-raw-notification';\nimport type {\n OnChainRawNotification,\n UnprocessedOnChainRawNotification,\n} from '../types/on-chain-notification/on-chain-notification';\nimport type { UserStorage } from '../types/user-storage/user-storage';\nimport {\n makeApiCall,\n toggleUserStorageTriggerStatus,\n traverseUserStorageTriggers,\n} from '../utils/utils';\n\nexport type NotificationTrigger = {\n id: string;\n chainId: string;\n kind: string;\n address: string;\n};\n\nexport const TRIGGER_API = 'https://trigger.api.cx.metamask.io';\nexport const NOTIFICATION_API = 'https://notification.api.cx.metamask.io';\nexport const TRIGGER_API_BATCH_ENDPOINT = `${TRIGGER_API}/api/v1/triggers/batch`;\nexport const NOTIFICATION_API_LIST_ENDPOINT = `${NOTIFICATION_API}/api/v1/notifications`;\nexport const NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY = (page: number) =>\n `${NOTIFICATION_API_LIST_ENDPOINT}?page=${page}&per_page=100`;\nexport const NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT = `${NOTIFICATION_API}/api/v1/notifications/mark-as-read`;\n\n/**\n * Creates on-chain triggers based on the provided notification triggers.\n * This method generates a unique token for each trigger using the trigger ID and storage key,\n * proving ownership of the trigger being updated. It then makes an API call to create these triggers.\n * Upon successful creation, it updates the userStorage to reflect the new trigger status.\n *\n * @param userStorage - The user's storage object where triggers and their statuses are stored.\n * @param storageKey - A key used along with the trigger ID to generate a unique token for each trigger.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param triggers - An array of notification triggers to be created. Each trigger includes an ID, chain ID, kind, and address.\n * @returns A promise that resolves to void. Throws an error if the API call fails or if there's an issue creating the triggers.\n */\nexport async function createOnChainTriggers(\n userStorage: UserStorage,\n storageKey: string,\n bearerToken: string,\n triggers: NotificationTrigger[],\n): Promise<void> {\n type RequestPayloadTrigger = {\n id: string;\n // this is the trigger token, generated by using the uuid + storage key. It proves you own the trigger you are updating\n token: string;\n config: {\n kind: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n chain_id: number;\n address: string;\n };\n };\n const triggersToCreate: RequestPayloadTrigger[] = triggers.map((t) => ({\n id: t.id,\n token: UserStorageController.createSHA256Hash(t.id + storageKey),\n config: {\n kind: t.kind,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n chain_id: Number(t.chainId),\n address: t.address,\n },\n }));\n\n if (triggersToCreate.length === 0) {\n return;\n }\n\n const response = await makeApiCall(\n bearerToken,\n TRIGGER_API_BATCH_ENDPOINT,\n 'POST',\n triggersToCreate,\n );\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => undefined);\n log.error('Error creating triggers:', errorData);\n throw new Error('OnChain Notifications - unable to create triggers');\n }\n\n // If the trigger creation was fine\n // then update the userStorage\n for (const trigger of triggersToCreate) {\n toggleUserStorageTriggerStatus(\n userStorage,\n trigger.config.address,\n String(trigger.config.chain_id),\n trigger.id,\n true,\n );\n }\n}\n\n/**\n * Deletes on-chain triggers based on the provided UUIDs.\n * This method generates a unique token for each trigger using the UUID and storage key,\n * proving ownership of the trigger being deleted. It then makes an API call to delete these triggers.\n * Upon successful deletion, it updates the userStorage to remove the deleted trigger statuses.\n *\n * @param userStorage - The user's storage object where triggers and their statuses are stored.\n * @param storageKey - A key used along with the UUID to generate a unique token for each trigger.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param uuids - An array of UUIDs representing the triggers to be deleted.\n * @returns A promise that resolves to the updated UserStorage object. Throws an error if the API call fails or if there's an issue deleting the triggers.\n */\nexport async function deleteOnChainTriggers(\n userStorage: UserStorage,\n storageKey: string,\n bearerToken: string,\n uuids: string[],\n): Promise<UserStorage> {\n const triggersToDelete = uuids.map((uuid) => ({\n id: uuid,\n token: UserStorageController.createSHA256Hash(uuid + storageKey),\n }));\n\n try {\n const response = await makeApiCall(\n bearerToken,\n TRIGGER_API_BATCH_ENDPOINT,\n 'DELETE',\n triggersToDelete,\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to delete on-chain notifications for uuids ${uuids.join(', ')}`,\n );\n }\n\n // Update the state of the deleted trigger to false\n for (const uuid of uuids) {\n for (const address in userStorage) {\n if (address in userStorage) {\n for (const chainId in userStorage[address]) {\n if (userStorage?.[address]?.[chainId]?.[uuid]) {\n delete userStorage[address][chainId][uuid];\n }\n }\n }\n }\n }\n\n // Follow-up cleanup, if an address had no triggers whatsoever, then we can delete the address\n const isEmpty = (obj = {}) => Object.keys(obj).length === 0;\n for (const address in userStorage) {\n if (address in userStorage) {\n for (const chainId in userStorage[address]) {\n // Chain isEmpty Check\n if (isEmpty(userStorage?.[address]?.[chainId])) {\n delete userStorage[address][chainId];\n }\n }\n\n // Address isEmpty Check\n if (isEmpty(userStorage?.[address])) {\n delete userStorage[address];\n }\n }\n }\n } catch (err) {\n log.error(\n `Error deleting on-chain notifications for uuids ${uuids.join(', ')}:`,\n err,\n );\n throw err;\n }\n\n return userStorage;\n}\n\n/**\n * Fetches on-chain notifications for the given user storage and BearerToken.\n * This method iterates through the userStorage to find enabled triggers and fetches notifications for those triggers.\n * It makes paginated API calls to the notifications service, transforming and aggregating the notifications into a single array.\n * The process stops either when all pages have been fetched or when a page has less than 100 notifications, indicating the end of the data.\n *\n * @param userStorage - The user's storage object containing trigger information.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @returns A promise that resolves to an array of OnChainRawNotification objects. If no triggers are enabled or an error occurs, it may return an empty array.\n */\nexport async function getOnChainNotifications(\n userStorage: UserStorage,\n bearerToken: string,\n): Promise<OnChainRawNotification[]> {\n const triggerIds = traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (!t.enabled) {\n return undefined;\n }\n return t.id;\n },\n });\n\n if (triggerIds.length === 0) {\n return [];\n }\n\n const onChainNotifications: OnChainRawNotification[] = [];\n const PAGE_LIMIT = 2;\n for (let page = 1; page <= PAGE_LIMIT; page++) {\n try {\n const response = await makeApiCall(\n bearerToken,\n NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY(page),\n 'POST',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n { trigger_ids: triggerIds },\n );\n\n const notifications =\n (await response.json()) as UnprocessedOnChainRawNotification[];\n\n // Transform and sort notifications\n const transformedNotifications = notifications\n .map((n): OnChainRawNotification | undefined => {\n if (!n.data?.kind) {\n return undefined;\n }\n\n return toRawOnChainNotification(n);\n })\n .filter((n): n is OnChainRawNotification => Boolean(n));\n\n onChainNotifications.push(...transformedNotifications);\n\n // if less than 100 notifications on page, then means we reached end\n if (notifications.length < 100) {\n page = PAGE_LIMIT + 1;\n break;\n }\n } catch (err) {\n log.error(\n `Error fetching on-chain notifications for trigger IDs ${triggerIds.join(\n ', ',\n )}:`,\n err,\n );\n // do nothing\n }\n }\n\n return onChainNotifications;\n}\n\n/**\n * Marks the specified notifications as read.\n * This method sends a POST request to the notifications service to mark the provided notification IDs as read.\n * If the operation is successful, it completes without error. If the operation fails, it throws an error with details.\n *\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param notificationIds - An array of notification IDs to be marked as read.\n * @returns A promise that resolves to void. The promise will reject if there's an error during the API call or if the response status is not 200.\n */\nexport async function markNotificationsAsRead(\n bearerToken: string,\n notificationIds: string[],\n): Promise<void> {\n if (notificationIds.length === 0) {\n return;\n }\n\n try {\n const response = await makeApiCall(\n bearerToken,\n NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT,\n 'POST',\n { ids: notificationIds },\n );\n\n if (response.status !== 200) {\n const errorData = await response.json().catch(() => undefined);\n throw new Error(\n `Error marking notifications as read: ${errorData?.message as string}`,\n );\n }\n } catch (err) {\n log.error('Error marking notifications as read:', err);\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,6BAA6B;AACtC,OAAO,SAAS;AAqBT,IAAM,cAAc;AACpB,IAAM,mBAAmB;AACzB,IAAM,6BAA6B,GAAG,WAAW;AACjD,IAAM,iCAAiC,GAAG,gBAAgB;AAC1D,IAAM,4CAA4C,CAAC,SACxD,GAAG,8BAA8B,SAAS,IAAI;AACzC,IAAM,6CAA6C,GAAG,gBAAgB;AAc7E,eAAsB,sBACpB,aACA,YACA,aACA,UACe;AAYf,QAAM,mBAA4C,SAAS,IAAI,CAAC,OAAO;AAAA,IACrE,IAAI,EAAE;AAAA,IACN,OAAO,sBAAsB,iBAAiB,EAAE,KAAK,UAAU;AAAA,IAC/D,QAAQ;AAAA,MACN,MAAM,EAAE;AAAA;AAAA,MAER,UAAU,OAAO,EAAE,OAAO;AAAA,MAC1B,SAAS,EAAE;AAAA,IACb;AAAA,EACF,EAAE;AAEF,MAAI,iBAAiB,WAAW,GAAG;AACjC;AAAA,EACF;AAEA,QAAM,WAAW,MAAM;AAAA,IACrB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,YAAY,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,MAAS;AAC7D,QAAI,MAAM,4BAA4B,SAAS;AAC/C,UAAM,IAAI,MAAM,mDAAmD;AAAA,EACrE;AAIA,aAAW,WAAW,kBAAkB;AACtC;AAAA,MACE;AAAA,MACA,QAAQ,OAAO;AAAA,MACf,OAA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S,KAAK,EAAE,MAAM,MAAM,MAAS;AAC7D,YAAM,IAAI;AAAA,QACR,wCAAwC,WAAW,OAAiB;AAAA,MACtE;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,QAAI,MAAM,wCAAwC,GAAG;AACrD,UAAM;AAAA,EACR;AACF;","names":[]}
|
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
var _chunkKWTSMLNDjs = require('./chunk-KWTSMLND.js');
|
|
4
4
|
|
|
5
|
+
|
|
6
|
+
var _chunkDT6SLUWJjs = require('./chunk-DT6SLUWJ.js');
|
|
7
|
+
|
|
5
8
|
// src/NotificationServicesPushController/services/push/push-web.ts
|
|
6
9
|
var _app = require('firebase/app');
|
|
7
10
|
var _messaging = require('firebase/messaging');
|
|
@@ -55,10 +58,11 @@ async function listenToPushNotificationsReceived(env, handler) {
|
|
|
55
58
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
56
59
|
async (payload) => {
|
|
57
60
|
try {
|
|
58
|
-
const
|
|
59
|
-
if (!
|
|
61
|
+
const data = payload?.data?.data ? JSON.parse(payload?.data?.data) : void 0;
|
|
62
|
+
if (!data) {
|
|
60
63
|
return;
|
|
61
64
|
}
|
|
65
|
+
const notificationData = _chunkDT6SLUWJjs.toRawOnChainNotification.call(void 0, data);
|
|
62
66
|
const notification = _chunkKWTSMLNDjs.processors_exports.processNotification(notificationData);
|
|
63
67
|
await handler(notification);
|
|
64
68
|
} catch (error) {
|
|
@@ -89,4 +93,4 @@ function listenToPushNotificationsClicked(handler) {
|
|
|
89
93
|
|
|
90
94
|
|
|
91
95
|
exports.createRegToken = createRegToken; exports.deleteRegToken = deleteRegToken; exports.listenToPushNotificationsReceived = listenToPushNotificationsReceived; exports.listenToPushNotificationsClicked = listenToPushNotificationsClicked;
|
|
92
|
-
//# sourceMappingURL=chunk-
|
|
96
|
+
//# sourceMappingURL=chunk-GDKHOBJT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/NotificationServicesPushController/services/push/push-web.ts"],"names":[],"mappings":";;;;;;;;AAIA,SAAS,QAAQ,qBAAqB;AACtC,SAAS,UAAU,mBAAmB;AACtC,SAAS,cAAc,2BAA2B;AAElD,OAAO,SAAS;AAShB,IAAM,oBAAoB,OACxB,QACyB;AACzB,MAAI;AACF,WAAO,OAAO;AAAA,EAChB,QAAQ;AACN,UAAM,iBAAiB;AAAA,MACrB,QAAQ,IAAI;AAAA,MACZ,YAAY,IAAI;AAAA,MAChB,eAAe,IAAI;AAAA,MACnB,WAAW,IAAI;AAAA,MACf,mBAAmB,IAAI;AAAA,MACvB,OAAO,IAAI;AAAA,MACX,eAAe,IAAI;AAAA,IACrB;AACA,WAAO,cAAc,cAAc;AAAA,EACrC;AACF;AAEA,IAAM,uBAAuB,OAC3B,QACuB;AACvB,QAAM,MAAM,MAAM,kBAAkB,GAAG;AACvC,SAAO,aAAa,GAAG;AACzB;AAQA,eAAsB,eACpB,KACwB;AACxB,MAAI;AACF,UAAM,YAAY,MAAM,qBAAqB,GAAG;AAChD,UAAM,QAAQ,MAAM,SAAS,WAAW;AAAA,MACtC,2BAA2B,KAAK;AAAA,MAChC,UAAU,IAAI;AAAA,IAChB,CAAC;AACD,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,eAAsB,eACpB,KACkB;AAClB,MAAI;AACF,UAAM,YAAY,MAAM,qBAAqB,GAAG;AAChD,UAAM,YAAY,SAAS;AAC3B,WAAO;AAAA,EACT,SAAS,OAAO;AACd,WAAO;AAAA,EACT;AACF;AAQA,eAAsB,kCACpB,KACA,SACA;AACA,QAAM,YAAY,MAAM,qBAAqB,GAAG;AAChD,QAAM,+BAA+B;AAAA,IACnC;AAAA;AAAA,IAEA,OAAO,YAA4B;AACjC,UAAI;AACF,cAAM,OACJ,SAAS,MAAM,OAAO,KAAK,MAAM,SAAS,MAAM,IAAI,IAAI;AAE1D,YAAI,CAAC,MAAM;AACT;AAAA,QACF;AAEA,cAAM,mBAAmB,yBAAyB,IAAI;AACtD,cAAM,eAAe,mBAAW,oBAAoB,gBAAgB;AACpE,cAAM,QAAQ,YAAY;AAAA,MAC5B,SAAS,OAAO;AAEd,YAAI,MAAM,qCAAqC;AAAA,UAC7C,cAAc,SAAS,MAAM;AAAA,UAC7B;AAAA,QACF,CAAC;AACD,cAAM,IAAI,MAAM,kCAAkC;AAAA,MACpD;AAAA,IACF;AAAA,EACF;AAEA,QAAM,cAAc,MAAM,6BAA6B;AACvD,SAAO;AACT;AAQO,SAAS,iCACd,SACA;AACA,QAAM,eAAe,CAAC,UAA6B;AAEjD,UAAM,OAA4B,OAAO,cAAc;AACvD,YAAQ,OAAO,IAAI;AAAA,EACrB;AAEA,OAAK,iBAAiB,qBAAqB,YAAY;AACvD,QAAM,cAAc,MAClB,KAAK,oBAAoB,qBAAqB,YAAY;AAC5D,SAAO;AACT","sourcesContent":["// We are defining that this file uses a webworker global scope.\n// eslint-disable-next-line spaced-comment\n/// <reference lib=\"webworker\" />\nimport type { FirebaseApp } from 'firebase/app';\nimport { getApp, initializeApp } from 'firebase/app';\nimport { getToken, deleteToken } from 'firebase/messaging';\nimport { getMessaging, onBackgroundMessage } from 'firebase/messaging/sw';\nimport type { Messaging, MessagePayload } from 'firebase/messaging/sw';\nimport log from 'loglevel';\n\nimport type { Types } from '../../../NotificationServicesController';\nimport { Processors } from '../../../NotificationServicesController';\nimport { toRawOnChainNotification } from '../../../shared/to-raw-notification';\nimport type { PushNotificationEnv } from '../../types/firebase';\n\ndeclare const self: ServiceWorkerGlobalScope;\n\nconst createFirebaseApp = async (\n env: PushNotificationEnv,\n): Promise<FirebaseApp> => {\n try {\n return getApp();\n } catch {\n const firebaseConfig = {\n apiKey: env.apiKey,\n authDomain: env.authDomain,\n storageBucket: env.storageBucket,\n projectId: env.projectId,\n messagingSenderId: env.messagingSenderId,\n appId: env.appId,\n measurementId: env.measurementId,\n };\n return initializeApp(firebaseConfig);\n }\n};\n\nconst getFirebaseMessaging = async (\n env: PushNotificationEnv,\n): Promise<Messaging> => {\n const app = await createFirebaseApp(env);\n return getMessaging(app);\n};\n\n/**\n * Creates a registration token for Firebase Cloud Messaging.\n *\n * @param env - env to configure push notifications\n * @returns A promise that resolves with the registration token or null if an error occurs.\n */\nexport async function createRegToken(\n env: PushNotificationEnv,\n): Promise<string | null> {\n try {\n const messaging = await getFirebaseMessaging(env);\n const token = await getToken(messaging, {\n serviceWorkerRegistration: self.registration,\n vapidKey: env.vapidKey,\n });\n return token;\n } catch {\n return null;\n }\n}\n\n/**\n * Deletes the Firebase Cloud Messaging registration token.\n *\n * @param env - env to configure push notifications\n * @returns A promise that resolves with true if the token was successfully deleted, false otherwise.\n */\nexport async function deleteRegToken(\n env: PushNotificationEnv,\n): Promise<boolean> {\n try {\n const messaging = await getFirebaseMessaging(env);\n await deleteToken(messaging);\n return true;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Service Worker Listener for when push notifications are received.\n * @param env - push notification environment\n * @param handler - handler to actually showing notification, MUST BE PROVEDED\n * @returns unsubscribe handler\n */\nexport async function listenToPushNotificationsReceived(\n env: PushNotificationEnv,\n handler: (notification: Types.INotification) => void | Promise<void>,\n) {\n const messaging = await getFirebaseMessaging(env);\n const unsubscribePushNotifications = onBackgroundMessage(\n messaging,\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (payload: MessagePayload) => {\n try {\n const data: Types.UnprocessedOnChainRawNotification | undefined =\n payload?.data?.data ? JSON.parse(payload?.data?.data) : undefined;\n\n if (!data) {\n return;\n }\n\n const notificationData = toRawOnChainNotification(data);\n const notification = Processors.processNotification(notificationData);\n await handler(notification);\n } catch (error) {\n // Do Nothing, cannot parse a bad notification\n log.error('Unable to send push notification:', {\n notification: payload?.data?.data,\n error,\n });\n throw new Error('Unable to send push notification');\n }\n },\n );\n\n const unsubscribe = () => unsubscribePushNotifications();\n return unsubscribe;\n}\n\n/**\n * Service Worker Listener for when a notification is clicked\n *\n * @param handler - listen to NotificationEvent from the service worker\n * @returns unsubscribe handler\n */\nexport function listenToPushNotificationsClicked(\n handler: (e: NotificationEvent, notification?: Types.INotification) => void,\n) {\n const clickHandler = (event: NotificationEvent) => {\n // Get Data\n const data: Types.INotification = event?.notification?.data;\n handler(event, data);\n };\n\n self.addEventListener('notificationclick', clickHandler);\n const unsubscribe = () =>\n self.removeEventListener('notificationclick', clickHandler);\n return unsubscribe;\n}\n"]}
|
|
@@ -4,6 +4,9 @@
|
|
|
4
4
|
|
|
5
5
|
var _chunkNOYP2T77js = require('./chunk-NOYP2T77.js');
|
|
6
6
|
|
|
7
|
+
|
|
8
|
+
var _chunkDT6SLUWJjs = require('./chunk-DT6SLUWJ.js');
|
|
9
|
+
|
|
7
10
|
// src/NotificationServicesController/services/onchain-notifications.ts
|
|
8
11
|
var _profilesynccontroller = require('@metamask/profile-sync-controller');
|
|
9
12
|
var _loglevel = require('loglevel'); var _loglevel2 = _interopRequireDefault(_loglevel);
|
|
@@ -122,17 +125,12 @@ async function getOnChainNotifications(userStorage, bearerToken) {
|
|
|
122
125
|
{ trigger_ids: triggerIds }
|
|
123
126
|
);
|
|
124
127
|
const notifications = await response.json();
|
|
125
|
-
const transformedNotifications = notifications.map(
|
|
126
|
-
(n)
|
|
127
|
-
|
|
128
|
-
return void 0;
|
|
129
|
-
}
|
|
130
|
-
return {
|
|
131
|
-
...n,
|
|
132
|
-
type: n.data.kind
|
|
133
|
-
};
|
|
128
|
+
const transformedNotifications = notifications.map((n) => {
|
|
129
|
+
if (!n.data?.kind) {
|
|
130
|
+
return void 0;
|
|
134
131
|
}
|
|
135
|
-
|
|
132
|
+
return _chunkDT6SLUWJjs.toRawOnChainNotification.call(void 0, n);
|
|
133
|
+
}).filter((n) => Boolean(n));
|
|
136
134
|
onChainNotifications.push(...transformedNotifications);
|
|
137
135
|
if (notifications.length < 100) {
|
|
138
136
|
page = PAGE_LIMIT + 1;
|
|
@@ -184,4 +182,4 @@ async function markNotificationsAsRead(bearerToken, notificationIds) {
|
|
|
184
182
|
|
|
185
183
|
|
|
186
184
|
exports.TRIGGER_API = TRIGGER_API; exports.NOTIFICATION_API = NOTIFICATION_API; exports.TRIGGER_API_BATCH_ENDPOINT = TRIGGER_API_BATCH_ENDPOINT; exports.NOTIFICATION_API_LIST_ENDPOINT = NOTIFICATION_API_LIST_ENDPOINT; exports.NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY = NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY; exports.NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT = NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT; exports.createOnChainTriggers = createOnChainTriggers; exports.deleteOnChainTriggers = deleteOnChainTriggers; exports.getOnChainNotifications = getOnChainNotifications; exports.markNotificationsAsRead = markNotificationsAsRead;
|
|
187
|
-
//# sourceMappingURL=chunk-
|
|
185
|
+
//# sourceMappingURL=chunk-H73GATCU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/NotificationServicesController/services/onchain-notifications.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,SAAS,6BAA6B;AACtC,OAAO,SAAS;AAqBT,IAAM,cAAc;AACpB,IAAM,mBAAmB;AACzB,IAAM,6BAA6B,GAAG,WAAW;AACjD,IAAM,iCAAiC,GAAG,gBAAgB;AAC1D,IAAM,4CAA4C,CAAC,SACxD,GAAG,8BAA8B,SAAS,IAAI;AACzC,IAAM,6CAA6C,GAAG,gBAAgB;AAc7E,eAAsB,sBACpB,aACA,YACA,aACA,UACe;AAYf,QAAM,mBAA4C,SAAS,IAAI,CAAC,OAAO;AAAA,IACrE,IAAI,EAAE;AAAA,IACN,OAAO,sBAAsB,iBAAiB,EAAE,KAAK,UAAU;AAAA,IAC/D,QAAQ;AAAA,MACN,MAAM,EAAE;AAAA;AAAA,MAER,UAAU,OAAO,EAAE,OAAO;AAAA,MAC1B,SAAS,EAAE;AAAA,IACb;AAAA,EACF,EAAE;AAEF,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,UAAI;AAAA,QACF,yDAAyD,WAAW;AAAA,UAClE;AAAA,QACF,CAAC;AAAA,QACD;AAAA,MACF;AAAA,IAEF;AAAA,EACF;AAEA,SAAO;AACT;AAWA,eAAsB,wBACpB,aACA,iBACe;AACf,MAAI,gBAAgB,WAAW,GAAG;AAChC;AAAA,EACF;AAEA,MAAI;AACF,UAAM,WAAW,MAAM;AAAA,MACrB;AAAA,MACA;AAAA,MACA;AAAA,MACA,EAAE,KAAK,gBAAgB;AAAA,IACzB;AAEA,QAAI,SAAS,WAAW,KAAK;AAC3B,YAAM,YAAY,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,MAAS;AAC7D,YAAM,IAAI;AAAA,QACR,wCAAwC,WAAW,OAAiB;AAAA,MACtE;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,QAAI,MAAM,wCAAwC,GAAG;AACrD,UAAM;AAAA,EACR;AACF","sourcesContent":["import { UserStorageController } from '@metamask/profile-sync-controller';\nimport log from 'loglevel';\n\nimport { toRawOnChainNotification } from '../../shared/to-raw-notification';\nimport type {\n OnChainRawNotification,\n UnprocessedOnChainRawNotification,\n} from '../types/on-chain-notification/on-chain-notification';\nimport type { UserStorage } from '../types/user-storage/user-storage';\nimport {\n makeApiCall,\n toggleUserStorageTriggerStatus,\n traverseUserStorageTriggers,\n} from '../utils/utils';\n\nexport type NotificationTrigger = {\n id: string;\n chainId: string;\n kind: string;\n address: string;\n};\n\nexport const TRIGGER_API = 'https://trigger.api.cx.metamask.io';\nexport const NOTIFICATION_API = 'https://notification.api.cx.metamask.io';\nexport const TRIGGER_API_BATCH_ENDPOINT = `${TRIGGER_API}/api/v1/triggers/batch`;\nexport const NOTIFICATION_API_LIST_ENDPOINT = `${NOTIFICATION_API}/api/v1/notifications`;\nexport const NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY = (page: number) =>\n `${NOTIFICATION_API_LIST_ENDPOINT}?page=${page}&per_page=100`;\nexport const NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT = `${NOTIFICATION_API}/api/v1/notifications/mark-as-read`;\n\n/**\n * Creates on-chain triggers based on the provided notification triggers.\n * This method generates a unique token for each trigger using the trigger ID and storage key,\n * proving ownership of the trigger being updated. It then makes an API call to create these triggers.\n * Upon successful creation, it updates the userStorage to reflect the new trigger status.\n *\n * @param userStorage - The user's storage object where triggers and their statuses are stored.\n * @param storageKey - A key used along with the trigger ID to generate a unique token for each trigger.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param triggers - An array of notification triggers to be created. Each trigger includes an ID, chain ID, kind, and address.\n * @returns A promise that resolves to void. Throws an error if the API call fails or if there's an issue creating the triggers.\n */\nexport async function createOnChainTriggers(\n userStorage: UserStorage,\n storageKey: string,\n bearerToken: string,\n triggers: NotificationTrigger[],\n): Promise<void> {\n type RequestPayloadTrigger = {\n id: string;\n // this is the trigger token, generated by using the uuid + storage key. It proves you own the trigger you are updating\n token: string;\n config: {\n kind: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n chain_id: number;\n address: string;\n };\n };\n const triggersToCreate: RequestPayloadTrigger[] = triggers.map((t) => ({\n id: t.id,\n token: UserStorageController.createSHA256Hash(t.id + storageKey),\n config: {\n kind: t.kind,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n chain_id: Number(t.chainId),\n address: t.address,\n },\n }));\n\n if (triggersToCreate.length === 0) {\n return;\n }\n\n const response = await makeApiCall(\n bearerToken,\n TRIGGER_API_BATCH_ENDPOINT,\n 'POST',\n triggersToCreate,\n );\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => undefined);\n log.error('Error creating triggers:', errorData);\n throw new Error('OnChain Notifications - unable to create triggers');\n }\n\n // If the trigger creation was fine\n // then update the userStorage\n for (const trigger of triggersToCreate) {\n toggleUserStorageTriggerStatus(\n userStorage,\n trigger.config.address,\n String(trigger.config.chain_id),\n trigger.id,\n true,\n );\n }\n}\n\n/**\n * Deletes on-chain triggers based on the provided UUIDs.\n * This method generates a unique token for each trigger using the UUID and storage key,\n * proving ownership of the trigger being deleted. It then makes an API call to delete these triggers.\n * Upon successful deletion, it updates the userStorage to remove the deleted trigger statuses.\n *\n * @param userStorage - The user's storage object where triggers and their statuses are stored.\n * @param storageKey - A key used along with the UUID to generate a unique token for each trigger.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param uuids - An array of UUIDs representing the triggers to be deleted.\n * @returns A promise that resolves to the updated UserStorage object. Throws an error if the API call fails or if there's an issue deleting the triggers.\n */\nexport async function deleteOnChainTriggers(\n userStorage: UserStorage,\n storageKey: string,\n bearerToken: string,\n uuids: string[],\n): Promise<UserStorage> {\n const triggersToDelete = uuids.map((uuid) => ({\n id: uuid,\n token: UserStorageController.createSHA256Hash(uuid + storageKey),\n }));\n\n try {\n const response = await makeApiCall(\n bearerToken,\n TRIGGER_API_BATCH_ENDPOINT,\n 'DELETE',\n triggersToDelete,\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to delete on-chain notifications for uuids ${uuids.join(', ')}`,\n );\n }\n\n // Update the state of the deleted trigger to false\n for (const uuid of uuids) {\n for (const address in userStorage) {\n if (address in userStorage) {\n for (const chainId in userStorage[address]) {\n if (userStorage?.[address]?.[chainId]?.[uuid]) {\n delete userStorage[address][chainId][uuid];\n }\n }\n }\n }\n }\n\n // Follow-up cleanup, if an address had no triggers whatsoever, then we can delete the address\n const isEmpty = (obj = {}) => Object.keys(obj).length === 0;\n for (const address in userStorage) {\n if (address in userStorage) {\n for (const chainId in userStorage[address]) {\n // Chain isEmpty Check\n if (isEmpty(userStorage?.[address]?.[chainId])) {\n delete userStorage[address][chainId];\n }\n }\n\n // Address isEmpty Check\n if (isEmpty(userStorage?.[address])) {\n delete userStorage[address];\n }\n }\n }\n } catch (err) {\n log.error(\n `Error deleting on-chain notifications for uuids ${uuids.join(', ')}:`,\n err,\n );\n throw err;\n }\n\n return userStorage;\n}\n\n/**\n * Fetches on-chain notifications for the given user storage and BearerToken.\n * This method iterates through the userStorage to find enabled triggers and fetches notifications for those triggers.\n * It makes paginated API calls to the notifications service, transforming and aggregating the notifications into a single array.\n * The process stops either when all pages have been fetched or when a page has less than 100 notifications, indicating the end of the data.\n *\n * @param userStorage - The user's storage object containing trigger information.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @returns A promise that resolves to an array of OnChainRawNotification objects. If no triggers are enabled or an error occurs, it may return an empty array.\n */\nexport async function getOnChainNotifications(\n userStorage: UserStorage,\n bearerToken: string,\n): Promise<OnChainRawNotification[]> {\n const triggerIds = traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (!t.enabled) {\n return undefined;\n }\n return t.id;\n },\n });\n\n if (triggerIds.length === 0) {\n return [];\n }\n\n const onChainNotifications: OnChainRawNotification[] = [];\n const PAGE_LIMIT = 2;\n for (let page = 1; page <= PAGE_LIMIT; page++) {\n try {\n const response = await makeApiCall(\n bearerToken,\n NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY(page),\n 'POST',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n { trigger_ids: triggerIds },\n );\n\n const notifications =\n (await response.json()) as UnprocessedOnChainRawNotification[];\n\n // Transform and sort notifications\n const transformedNotifications = notifications\n .map((n): OnChainRawNotification | undefined => {\n if (!n.data?.kind) {\n return undefined;\n }\n\n return toRawOnChainNotification(n);\n })\n .filter((n): n is OnChainRawNotification => Boolean(n));\n\n onChainNotifications.push(...transformedNotifications);\n\n // if less than 100 notifications on page, then means we reached end\n if (notifications.length < 100) {\n page = PAGE_LIMIT + 1;\n break;\n }\n } catch (err) {\n log.error(\n `Error fetching on-chain notifications for trigger IDs ${triggerIds.join(\n ', ',\n )}:`,\n err,\n );\n // do nothing\n }\n }\n\n return onChainNotifications;\n}\n\n/**\n * Marks the specified notifications as read.\n * This method sends a POST request to the notifications service to mark the provided notification IDs as read.\n * If the operation is successful, it completes without error. If the operation fails, it throws an error with details.\n *\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param notificationIds - An array of notification IDs to be marked as read.\n * @returns A promise that resolves to void. The promise will reject if there's an error during the API call or if the response status is not 200.\n */\nexport async function markNotificationsAsRead(\n bearerToken: string,\n notificationIds: string[],\n): Promise<void> {\n if (notificationIds.length === 0) {\n return;\n }\n\n try {\n const response = await makeApiCall(\n bearerToken,\n NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT,\n 'POST',\n { ids: notificationIds },\n );\n\n if (response.status !== 200) {\n const errorData = await response.json().catch(() => undefined);\n throw new Error(\n `Error marking notifications as read: ${errorData?.message as string}`,\n );\n }\n } catch (err) {\n log.error('Error marking notifications as read:', err);\n throw err;\n }\n}\n"]}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
utils_exports
|
|
3
|
-
} from "./chunk-DCADU5QI.mjs";
|
|
4
1
|
import {
|
|
5
2
|
types_exports
|
|
6
3
|
} from "./chunk-IOMDG67D.mjs";
|
|
4
|
+
import {
|
|
5
|
+
utils_exports
|
|
6
|
+
} from "./chunk-DCADU5QI.mjs";
|
|
7
7
|
import {
|
|
8
8
|
NotificationServicesPushController,
|
|
9
9
|
defaultState
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-X3ZU3HL7.mjs";
|
|
11
11
|
import {
|
|
12
12
|
REGISTRATION_TOKENS_ENDPOINT
|
|
13
13
|
} from "./chunk-IKWNHNJQ.mjs";
|
|
@@ -91,4 +91,4 @@ export {
|
|
|
91
91
|
fixtures_exports,
|
|
92
92
|
NotificationServicesPushController_exports
|
|
93
93
|
};
|
|
94
|
-
//# sourceMappingURL=chunk-
|
|
94
|
+
//# sourceMappingURL=chunk-N4EKQQX7.mjs.map
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
deleteOnChainTriggers,
|
|
10
10
|
getOnChainNotifications,
|
|
11
11
|
markNotificationsAsRead
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-FN6GVBCU.mjs";
|
|
13
13
|
import {
|
|
14
14
|
checkAccountsPresence,
|
|
15
15
|
getAllUUIDs,
|
|
@@ -87,7 +87,7 @@ var defaultState = {
|
|
|
87
87
|
isUpdatingMetamaskNotificationsAccount: [],
|
|
88
88
|
isCheckingAccountsPresence: false
|
|
89
89
|
};
|
|
90
|
-
var _isPushIntegrated, _auth, _storage, _pushNotifications, _accounts, _featureAnnouncementEnv, _registerMessageHandlers, registerMessageHandlers_fn, _clearLoadingStates, clearLoadingStates_fn, _assertAuthEnabled, assertAuthEnabled_fn, _getValidStorageKeyAndBearerToken, getValidStorageKeyAndBearerToken_fn, _performEnableProfileSyncing, _assertUserStorage, assertUserStorage_fn, _getUserStorage, getUserStorage_fn, _setIsUpdatingMetamaskNotifications, setIsUpdatingMetamaskNotifications_fn, _setIsFetchingMetamaskNotifications, setIsFetchingMetamaskNotifications_fn, _setIsCheckingAccountsPresence, setIsCheckingAccountsPresence_fn, _updateUpdatingAccountsState, updateUpdatingAccountsState_fn, _clearUpdatingAccountsState, clearUpdatingAccountsState_fn;
|
|
90
|
+
var _isPushIntegrated, _isPushNotificationsSetup, _isUnlocked, _keyringController, _auth, _storage, _pushNotifications, _accounts, _featureAnnouncementEnv, _registerMessageHandlers, registerMessageHandlers_fn, _clearLoadingStates, clearLoadingStates_fn, _assertAuthEnabled, assertAuthEnabled_fn, _getValidStorageKeyAndBearerToken, getValidStorageKeyAndBearerToken_fn, _performEnableProfileSyncing, _assertUserStorage, assertUserStorage_fn, _getUserStorage, getUserStorage_fn, _setIsUpdatingMetamaskNotifications, setIsUpdatingMetamaskNotifications_fn, _setIsFetchingMetamaskNotifications, setIsFetchingMetamaskNotifications_fn, _setIsCheckingAccountsPresence, setIsCheckingAccountsPresence_fn, _updateUpdatingAccountsState, updateUpdatingAccountsState_fn, _clearUpdatingAccountsState, clearUpdatingAccountsState_fn;
|
|
91
91
|
var NotificationServicesController = class extends BaseController {
|
|
92
92
|
/**
|
|
93
93
|
* Creates a NotificationServicesController instance.
|
|
@@ -170,6 +170,26 @@ var NotificationServicesController = class extends BaseController {
|
|
|
170
170
|
__privateAdd(this, _clearUpdatingAccountsState);
|
|
171
171
|
// Temporary boolean as push notifications are not yet enabled on mobile
|
|
172
172
|
__privateAdd(this, _isPushIntegrated, true);
|
|
173
|
+
// Flag to check is notifications have been setup when the browser/extension is initialized.
|
|
174
|
+
// We want to re-initialize push notifications when the browser/extension is refreshed
|
|
175
|
+
// To ensure we subscribe to the most up-to-date notifications
|
|
176
|
+
__privateAdd(this, _isPushNotificationsSetup, false);
|
|
177
|
+
__privateAdd(this, _isUnlocked, false);
|
|
178
|
+
__privateAdd(this, _keyringController, {
|
|
179
|
+
setupLockedStateSubscriptions: (onUnlock) => {
|
|
180
|
+
const { isUnlocked } = this.messagingSystem.call(
|
|
181
|
+
"KeyringController:getState"
|
|
182
|
+
);
|
|
183
|
+
__privateSet(this, _isUnlocked, isUnlocked);
|
|
184
|
+
this.messagingSystem.subscribe("KeyringController:unlock", () => {
|
|
185
|
+
__privateSet(this, _isUnlocked, true);
|
|
186
|
+
onUnlock();
|
|
187
|
+
});
|
|
188
|
+
this.messagingSystem.subscribe("KeyringController:lock", () => {
|
|
189
|
+
__privateSet(this, _isUnlocked, false);
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
});
|
|
173
193
|
__privateAdd(this, _auth, {
|
|
174
194
|
getBearerToken: async () => {
|
|
175
195
|
return await this.messagingSystem.call(
|
|
@@ -261,12 +281,19 @@ var NotificationServicesController = class extends BaseController {
|
|
|
261
281
|
if (!this.state.isNotificationServicesEnabled) {
|
|
262
282
|
return;
|
|
263
283
|
}
|
|
284
|
+
if (__privateGet(this, _isPushNotificationsSetup)) {
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (!__privateGet(this, _isUnlocked)) {
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
264
290
|
const storage = await __privateMethod(this, _getUserStorage, getUserStorage_fn).call(this);
|
|
265
291
|
if (!storage) {
|
|
266
292
|
return;
|
|
267
293
|
}
|
|
268
294
|
const uuids = getAllUUIDs(storage);
|
|
269
295
|
await __privateGet(this, _pushNotifications).enablePushNotifications(uuids);
|
|
296
|
+
__privateSet(this, _isPushNotificationsSetup, true);
|
|
270
297
|
}
|
|
271
298
|
});
|
|
272
299
|
__privateAdd(this, _accounts, {
|
|
@@ -349,6 +376,9 @@ var NotificationServicesController = class extends BaseController {
|
|
|
349
376
|
__privateSet(this, _featureAnnouncementEnv, env.featureAnnouncements);
|
|
350
377
|
__privateMethod(this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
|
|
351
378
|
__privateMethod(this, _clearLoadingStates, clearLoadingStates_fn).call(this);
|
|
379
|
+
__privateGet(this, _keyringController).setupLockedStateSubscriptions(
|
|
380
|
+
__privateGet(this, _pushNotifications).initializePushNotifications
|
|
381
|
+
);
|
|
352
382
|
__privateGet(this, _accounts).initialize();
|
|
353
383
|
__privateGet(this, _pushNotifications).initializePushNotifications();
|
|
354
384
|
__privateGet(this, _accounts).subscribe();
|
|
@@ -630,6 +660,10 @@ var NotificationServicesController = class extends BaseController {
|
|
|
630
660
|
this.update((state) => {
|
|
631
661
|
state.metamaskNotificationsList = metamaskNotifications;
|
|
632
662
|
});
|
|
663
|
+
this.messagingSystem.publish(
|
|
664
|
+
`${controllerName}:notificationsListUpdated`,
|
|
665
|
+
this.state.metamaskNotificationsList
|
|
666
|
+
);
|
|
633
667
|
__privateMethod(this, _setIsFetchingMetamaskNotifications, setIsFetchingMetamaskNotifications_fn).call(this, false);
|
|
634
668
|
return metamaskNotifications;
|
|
635
669
|
} catch (err) {
|
|
@@ -692,6 +726,10 @@ var NotificationServicesController = class extends BaseController {
|
|
|
692
726
|
}
|
|
693
727
|
);
|
|
694
728
|
});
|
|
729
|
+
this.messagingSystem.publish(
|
|
730
|
+
`${controllerName}:markNotificationsAsRead`,
|
|
731
|
+
this.state.metamaskNotificationsList
|
|
732
|
+
);
|
|
695
733
|
}
|
|
696
734
|
/**
|
|
697
735
|
* Updates the list of MetaMask notifications by adding a new notification at the beginning of the list.
|
|
@@ -715,12 +753,19 @@ var NotificationServicesController = class extends BaseController {
|
|
|
715
753
|
notification,
|
|
716
754
|
...state.metamaskNotificationsList
|
|
717
755
|
];
|
|
756
|
+
this.messagingSystem.publish(
|
|
757
|
+
`${controllerName}:notificationsListUpdated`,
|
|
758
|
+
state.metamaskNotificationsList
|
|
759
|
+
);
|
|
718
760
|
}
|
|
719
761
|
});
|
|
720
762
|
}
|
|
721
763
|
}
|
|
722
764
|
};
|
|
723
765
|
_isPushIntegrated = new WeakMap();
|
|
766
|
+
_isPushNotificationsSetup = new WeakMap();
|
|
767
|
+
_isUnlocked = new WeakMap();
|
|
768
|
+
_keyringController = new WeakMap();
|
|
724
769
|
_auth = new WeakMap();
|
|
725
770
|
_storage = new WeakMap();
|
|
726
771
|
_pushNotifications = new WeakMap();
|
|
@@ -831,4 +876,4 @@ export {
|
|
|
831
876
|
defaultState,
|
|
832
877
|
NotificationServicesController
|
|
833
878
|
};
|
|
834
|
-
//# sourceMappingURL=chunk-
|
|
879
|
+
//# sourceMappingURL=chunk-OLYCBAVW.mjs.map
|