|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useEffect } from 'react'; |
| 4 | + |
| 5 | +const SW_PATH = '/sw.js'; |
| 6 | + |
| 7 | +/** Must match shared-lib Interceptor (Bearer token). */ |
| 8 | +const TOKEN_STORAGE_KEY = 'token'; |
| 9 | +const TENANT_STORAGE_KEY = 'tenantId'; |
| 10 | +/** Must match learner tracking queue key convention in IndexedDB (SW filters by this substring). */ |
| 11 | +const USER_ID_STORAGE_KEY = 'userId'; |
| 12 | + |
| 13 | +/** Must match `LS_IN_PROGRESS_KEY` in public/sw.js (page mirror of SW lock). */ |
| 14 | +export const TRACKING_API_SYNC_LS_KEY = 'trackingApiSyncInProgress'; |
| 15 | + |
| 16 | +function buildTrackingSyncPayload() { |
| 17 | + let temp_base = process.env.NEXT_PUBLIC_MIDDLEWARE_URL || ''; |
| 18 | + const base = temp_base.replace(/\/$/, ''); |
| 19 | + |
| 20 | + const contentCreateUrl = `${base}/tracking/content/create`; |
| 21 | + const courseStatusUrl = `${base}/tracking/content/course/status`; |
| 22 | + const userCertificateStatusUpdateUrl = `${base}/tracking/user_certificate/status/update`; |
| 23 | + const authUrl = `${base}/user/auth`; |
| 24 | + const userCertificateStatusGetUrl = `${base}/tracking/user_certificate/status/get`; |
| 25 | + const courseHierarchyUrl = `${base}/api/course/v1/hierarchy/`; |
| 26 | + const issueCertificateUrl = `${base}/tracking/certificate/issue`; |
| 27 | + const assessmentStatusUrl = `${base}/tracking/assessment/search/status`; |
| 28 | + return { |
| 29 | + type: 'SET_TRACKING_SYNC_CONFIG' as const, |
| 30 | + contentCreateUrl, |
| 31 | + courseStatusUrl, |
| 32 | + userCertificateStatusUpdateUrl, |
| 33 | + authUrl, |
| 34 | + userCertificateStatusGetUrl, |
| 35 | + courseHierarchyUrl, |
| 36 | + issueCertificateUrl, |
| 37 | + assessmentStatusUrl, |
| 38 | + token: localStorage.getItem(TOKEN_STORAGE_KEY) || '', |
| 39 | + tenantId: localStorage.getItem(TENANT_STORAGE_KEY) || '', |
| 40 | + userId: localStorage.getItem(USER_ID_STORAGE_KEY) || '', |
| 41 | + }; |
| 42 | +} |
| 43 | + |
| 44 | +function pushTrackingConfig(registration: ServiceWorkerRegistration) { |
| 45 | + if (!registration.active) return; |
| 46 | + registration.active.postMessage(buildTrackingSyncPayload()); |
| 47 | +} |
| 48 | + |
| 49 | +function requestIdbReadFromSw(registration: ServiceWorkerRegistration) { |
| 50 | + const key = process.env.NEXT_PUBLIC_SW_IDB_PROBE_KEY; |
| 51 | + if (!key || !registration.active) return; |
| 52 | + registration.active.postMessage({ type: 'IDB_GET', key }); |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * Registers the origin-scoped service worker, pushes auth + tracking API URL to the SW |
| 57 | + * (SW cannot read localStorage), and mirrors SW sync lock to localStorage. |
| 58 | + */ |
| 59 | +export default function ServiceWorkerRegister() { |
| 60 | + useEffect(() => { |
| 61 | + if (typeof window === 'undefined') return; |
| 62 | + if (!('serviceWorker' in navigator)) return; |
| 63 | + |
| 64 | + const onMessage = (event: MessageEvent) => { |
| 65 | + const d = event.data; |
| 66 | + if (!d || typeof d !== 'object') return; |
| 67 | + if (d.type === 'LEARNER_SW_STATUS') { |
| 68 | + console.log( |
| 69 | + '[learner-sw → page]', |
| 70 | + d.reason, |
| 71 | + 'online=', |
| 72 | + d.online, |
| 73 | + d.time |
| 74 | + ); |
| 75 | + } |
| 76 | + if (d.type === 'LEARNER_SW_IDB_RESULT') { |
| 77 | + console.log('[learner-sw → page] IDB', d.key, d.value, d.time); |
| 78 | + } |
| 79 | + if (d.type === 'LEARNER_SW_IDB_ERROR') { |
| 80 | + console.error( |
| 81 | + '[learner-sw → page] IDB error', |
| 82 | + d.key, |
| 83 | + d.error, |
| 84 | + d.time |
| 85 | + ); |
| 86 | + } |
| 87 | + if (d.type === 'TRACKING_SYNC_LOCK') { |
| 88 | + const lsKey = |
| 89 | + typeof d.localStorageKey === 'string' |
| 90 | + ? d.localStorageKey |
| 91 | + : TRACKING_API_SYNC_LS_KEY; |
| 92 | + if (d.inProgress) { |
| 93 | + localStorage.setItem(lsKey, 'true'); |
| 94 | + } else { |
| 95 | + localStorage.removeItem(lsKey); |
| 96 | + } |
| 97 | + } |
| 98 | + }; |
| 99 | + |
| 100 | + navigator.serviceWorker.addEventListener('message', onMessage); |
| 101 | + |
| 102 | + const onStorage = (e: StorageEvent) => { |
| 103 | + if ( |
| 104 | + e.key === TOKEN_STORAGE_KEY || |
| 105 | + e.key === TENANT_STORAGE_KEY || |
| 106 | + e.key === USER_ID_STORAGE_KEY |
| 107 | + ) { |
| 108 | + void navigator.serviceWorker.ready.then(pushTrackingConfig); |
| 109 | + } |
| 110 | + }; |
| 111 | + window.addEventListener('storage', onStorage); |
| 112 | + |
| 113 | + const onFocus = () => { |
| 114 | + void navigator.serviceWorker.ready.then(pushTrackingConfig); |
| 115 | + }; |
| 116 | + window.addEventListener('focus', onFocus); |
| 117 | + |
| 118 | + let cancelled = false; |
| 119 | + let configIntervalId: ReturnType<typeof setInterval> | undefined; |
| 120 | + |
| 121 | + void navigator.serviceWorker |
| 122 | + .register(SW_PATH) |
| 123 | + .then(() => navigator.serviceWorker.ready) |
| 124 | + .then((registration) => { |
| 125 | + if (cancelled) return; |
| 126 | + pushTrackingConfig(registration); |
| 127 | + requestIdbReadFromSw(registration); |
| 128 | + configIntervalId = setInterval(() => { |
| 129 | + pushTrackingConfig(registration); |
| 130 | + }, 60000); |
| 131 | + }) |
| 132 | + .catch((err) => { |
| 133 | + console.error('[learner-sw] registration failed', err); |
| 134 | + }); |
| 135 | + |
| 136 | + return () => { |
| 137 | + cancelled = true; |
| 138 | + if (configIntervalId) clearInterval(configIntervalId); |
| 139 | + navigator.serviceWorker.removeEventListener('message', onMessage); |
| 140 | + window.removeEventListener('storage', onStorage); |
| 141 | + window.removeEventListener('focus', onFocus); |
| 142 | + }; |
| 143 | + }, []); |
| 144 | + |
| 145 | + return null; |
| 146 | +} |
0 commit comments