44class ServiceWorkerManager {
55 private registration : ServiceWorkerRegistration | null = null ;
66 private pendingToken : string | null = null ;
7+ private pendingCacheClear = false ;
78
89 async register ( ) : Promise < void > {
910 if ( ! ( 'serviceWorker' in navigator ) ) {
@@ -12,11 +13,13 @@ class ServiceWorkerManager {
1213 }
1314
1415 try {
15- this . registration = await navigator . serviceWorker . register ( '/sw.js' , {
16- scope : '/'
16+ const baseUrl = import . meta. env . BASE_URL || '/' ;
17+ const swUrl = new URL ( 'sw.js' , window . location . origin + baseUrl ) . href ;
18+ this . registration = await navigator . serviceWorker . register ( swUrl , {
19+ scope : baseUrl
1720 } ) ;
1821
19- console . log ( 'Service Worker registered successfully' ) ;
22+ console . log ( 'Service Worker registered successfully at' , swUrl , 'scope' , baseUrl ) ;
2023
2124 // Wait for the service worker to be ready
2225 await navigator . serviceWorker . ready ;
@@ -30,9 +33,20 @@ class ServiceWorkerManager {
3033 this . pendingToken = null ;
3134 }
3235
36+ // Send any queued cache clear request once the worker is active
37+ if ( this . pendingCacheClear && this . registration ?. active ) {
38+ this . sendCacheClear ( ) ;
39+ this . pendingCacheClear = false ;
40+ }
41+
3342 // Set up message handling
3443 navigator . serviceWorker . addEventListener ( 'message' , this . handleMessage . bind ( this ) ) ;
3544
45+ // Expose manual cache clear command in console
46+ window . clearGitHubApiCache = async ( ) => {
47+ await this . clearCache ( ) ;
48+ } ;
49+
3650 } catch ( error ) {
3751 console . error ( 'Service Worker registration failed:' , error ) ;
3852 }
@@ -80,7 +94,35 @@ class ServiceWorkerManager {
8094 }
8195 }
8296
97+ async clearCache ( ) : Promise < void > {
98+ if ( ! this . registration ?. active ) {
99+ this . pendingCacheClear = true ;
100+ return ;
101+ }
102+
103+ this . sendCacheClear ( ) ;
104+ }
105+
106+ private sendCacheClear ( ) : void {
107+ if ( ! this . registration ?. active ) {
108+ console . warn ( 'Service worker not active, cannot clear cache' ) ;
109+ return ;
110+ }
111+
112+ try {
113+ this . registration . active . postMessage ( {
114+ type : 'CLEAR_CACHE'
115+ } ) ;
116+ } catch ( error ) {
117+ console . error ( 'Failed to send cache clear command to service worker:' , error ) ;
118+ }
119+ }
120+
83121 private handleMessage ( event : MessageEvent ) : void {
122+ if ( event . data ?. type === 'CACHE_CLEARED' ) {
123+ console . log ( 'Service worker cache cleared' ) ;
124+ return ;
125+ }
84126 // Handle messages from service worker if needed
85127 if ( event . data ?. type === 'TOKEN_STORED' ) {
86128 console . log ( 'Token successfully stored in service worker' ) ;
0 commit comments