/* * [ Caution ] * Since this module is being used by a service worker, be very careful about adding imports or using functions for browsers. */ import { storeOnce, type NoticeStore } from './store-once' export type PushWorker = { registration: { showNotification(title: string, options?: any): Promise } channel: { postMessage(message: any): void } /* only kept here - the open screen keeps each tab of the inbox to its own limit (notification client/inbox.ts) */ store: NoticeStore /* the title of a push that brings none */ tagline?: string } /** * Shows a web push, keeps it in the worker's store and tells the open screens. The work is handed to * `event.waitUntil` before anything is awaited - otherwise the browser may stop the worker first, and a mobile * browser drops the notice or revokes the subscription of a site that received a push and showed nothing. */ export function handlePush(event: { data?: any; waitUntil(work: Promise): void }, worker: PushWorker) { if (!event.data) { return } try { var { notification, data } = event.data.json() } catch (e) { notification = { body: event.data.text() } } const title = notification.title || worker.tagline const options = { icon: '/assets/manifest/icon-128x128.png', badge: '/assets/manifest/badge-128x128.png', ...notification, data } event.waitUntil( (async () => { /* the screen may have kept this notice from its subscription already - one moment, as a number, for both */ await storeOnce(worker.store, { ...notification, ...data, timestamp: Number(data?.timestamp) || Date.now() }) worker.channel.postMessage({ type: 'notification', notification, data }) /* https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification */ await worker.registration.showNotification(title, options) })() ) }