|
| 1 | +import {manualRegister} from '~/serviceWorkerRegistration'; |
| 2 | +import {newAddNotificationAction, NotificationType} from "~/store/notifications"; |
| 3 | +import {checkUpdates} from "~/services/updates"; |
| 4 | + |
| 5 | +import {Dispatcher} from "./utils"; |
| 6 | +import {DispatchFn} from "../helpers"; |
| 7 | + |
| 8 | +const truncateCachesAndRegister = async (registration: ServiceWorkerRegistration) => { |
| 9 | + console.log(`updater: unregistering service worker...`); |
| 10 | + await registration.unregister(); |
| 11 | + |
| 12 | + console.log('updater: truncating all caches'); |
| 13 | + const keys = await caches.keys(); |
| 14 | + await Promise.all(keys.map(key => caches.delete(key))); |
| 15 | + |
| 16 | + console.log('updater: re-registering service worker...'); |
| 17 | + manualRegister(); |
| 18 | +} |
| 19 | + |
| 20 | +const performSelfUpdate = async (dispatch: DispatchFn, newVersion: string)=> { |
| 21 | + if (!('serviceWorker' in navigator)) { |
| 22 | + console.warn('updater: no SW registrations found, skip'); |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + const registration = await navigator.serviceWorker.getRegistration(); |
| 27 | + if (!registration) { |
| 28 | + console.warn('updater: no SW registrations found, skip'); |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + await truncateCachesAndRegister(registration); |
| 33 | + dispatch(newAddNotificationAction({ |
| 34 | + id: 'UPDATE', |
| 35 | + type: NotificationType.Warning, |
| 36 | + title: `Update available - ${newVersion}`, |
| 37 | + description: 'Playground was updated. Please refresh page to apply changes.', |
| 38 | + canDismiss: false, |
| 39 | + actions: [ |
| 40 | + { |
| 41 | + key: 'refresh', |
| 42 | + label: 'Refresh', |
| 43 | + primary: true, |
| 44 | + onClick: () => { |
| 45 | + window.location.replace(""); |
| 46 | + } |
| 47 | + } |
| 48 | + ] |
| 49 | + })); |
| 50 | +} |
| 51 | + |
| 52 | +export const dispatchUpdateCheck: Dispatcher = async (dispatch: DispatchFn) => { |
| 53 | + try { |
| 54 | + const rsp = await checkUpdates(); |
| 55 | + if (!rsp) { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + try { |
| 60 | + await performSelfUpdate(dispatch, rsp.newVersion); |
| 61 | + } catch (err) { |
| 62 | + console.error('updater: error during update:', err); |
| 63 | + } |
| 64 | + } catch (err) { |
| 65 | + console.error('updater: failed to check for updates', err); |
| 66 | + } |
| 67 | +} |
0 commit comments