{"version":3,"sources":["../src/NotificationServicesPushController/services/push/push-web.ts"],"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 type { PushNotificationEnv } from '../../types/firebase';\n\nconst sw = self as unknown as 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: sw.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 notificationData: Types.NotificationUnion = payload?.data?.data\n          ? JSON.parse(payload?.data?.data)\n          : undefined;\n\n        if (!notificationData) {\n          return;\n        }\n\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  sw.addEventListener('notificationclick', clickHandler);\n  const unsubscribe = () =>\n    sw.removeEventListener('notificationclick', clickHandler);\n  return unsubscribe;\n}\n"],"mappings":";;;;;AAIA,SAAS,QAAQ,qBAAqB;AACtC,SAAS,UAAU,mBAAmB;AACtC,SAAS,cAAc,2BAA2B;AAElD,OAAO,SAAS;AAMhB,IAAM,KAAK;AAEX,IAAM,oBAAoB,OACxB,QACyB;AACzB,MAAI;AACF,WAAO,OAAO;AAAA,EAChB,QAAQ;AACN,UAA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