-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathservice-worker.js
More file actions
230 lines (208 loc) · 7.43 KB
/
service-worker.js
File metadata and controls
230 lines (208 loc) · 7.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// ===================================
// ENHANCED SERVICE WORKER v3.1.2
// Offline Support & Caching Strategy
// Fixed: Using local icon files
// ===================================
const CACHE_VERSION = 'gh-bot-v3.1.2';
const STATIC_CACHE = `${CACHE_VERSION}-static`;
const DYNAMIC_CACHE = `${CACHE_VERSION}-dynamic`;
const MAX_DYNAMIC_CACHE_SIZE = 50;
// ✅ FIXED: Now includes actual local icon files
const STATIC_ASSETS = [
'/',
'/index.html',
'/app.js',
'/guide.html',
'/manifest.json',
'/favicon.ico',
'/icon.png',
'/icon-512.png',
'https://cdn.tailwindcss.com',
'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap',
'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css',
'https://d3js.org/d3.v7.min.js'
];
// Cache size limiter
const limitCacheSize = async (cacheName, maxSize) => {
const cache = await caches.open(cacheName);
const keys = await cache.keys();
if (keys.length > maxSize) {
await cache.delete(keys[0]);
limitCacheSize(cacheName, maxSize);
}
};
// Helper: Check if URL should be cached
function shouldCache(url) {
try {
// Don't cache chrome extensions, browser extensions, or data URLs
if (url.protocol === 'chrome-extension:' ||
url.protocol === 'moz-extension:' ||
url.protocol === 'safari-extension:' ||
url.protocol === 'data:' ||
url.protocol === 'blob:') {
return false;
}
// Don't cache API calls
if (url.hostname === 'api.github.com' ||
url.hostname.includes('generativelanguage.googleapis.com')) {
return false;
}
return true;
} catch (e) {
return false;
}
}
// Install event - cache static assets
self.addEventListener('install', event => {
console.log('[SW] Installing Service Worker v3.1.2...');
event.waitUntil(
caches.open(STATIC_CACHE)
.then(cache => {
console.log('[SW] Caching static assets including local icons');
// Filter valid URLs before caching
const validAssets = STATIC_ASSETS.filter(url => {
try {
const parsed = new URL(url, self.location.origin);
return shouldCache(parsed);
} catch (e) {
console.warn('[SW] Invalid URL:', url);
return false;
}
});
// Cache assets one by one to avoid 404 errors blocking installation
return Promise.allSettled(
validAssets.map(url =>
cache.add(url).catch(err => {
console.warn(`[SW] Failed to cache ${url}:`, err.message);
return null;
})
)
);
})
.then(() => {
console.log('[SW] Installation complete with local icons');
return self.skipWaiting();
})
.catch(err => console.error('[SW] Install failed:', err))
);
});
// Activate event - clean up old caches
self.addEventListener('activate', event => {
console.log('[SW] Activating Service Worker v3.1.2...');
event.waitUntil(
caches.keys()
.then(keys => {
return Promise.all(
keys
.filter(key => key !== STATIC_CACHE && key !== DYNAMIC_CACHE)
.map(key => {
console.log('[SW] Removing old cache:', key);
return caches.delete(key);
})
);
})
.then(() => self.clients.claim())
);
});
// Fetch event - network first, fallback to cache
self.addEventListener('fetch', event => {
const { request } = event;
// Parse URL safely
let url;
try {
url = new URL(request.url);
} catch (e) {
console.warn('[SW] Invalid request URL:', request.url);
return;
}
// Skip non-GET requests
if (request.method !== 'GET') return;
// Skip extension URLs, blob URLs, and data URLs
if (!shouldCache(url)) {
return;
}
// Cache strategy: Network first, fallback to cache
event.respondWith(
fetch(request)
.then(async response => {
// Only cache successful responses from valid URLs
if (response.status === 200 && shouldCache(url)) {
try {
const responseClone = response.clone();
const cache = await caches.open(DYNAMIC_CACHE);
await cache.put(request, responseClone);
limitCacheSize(DYNAMIC_CACHE, MAX_DYNAMIC_CACHE_SIZE);
} catch (err) {
console.warn('[SW] Cache put failed:', err.message);
}
}
return response;
})
.catch(async () => {
// Network failed, try cache
const cachedResponse = await caches.match(request);
if (cachedResponse) {
console.log('[SW] Serving from cache:', request.url);
return cachedResponse;
}
// Return offline page for navigation requests
if (request.mode === 'navigate') {
const indexCache = await caches.match('/index.html');
if (indexCache) return indexCache;
}
// Return error response
return new Response('Offline - resource not available', {
status: 503,
statusText: 'Service Unavailable',
headers: new Headers({
'Content-Type': 'text/plain'
})
});
})
);
});
// Message event - handle commands from app
self.addEventListener('message', event => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
if (event.data && event.data.type === 'CLEAR_CACHE') {
event.waitUntil(
caches.keys().then(keys => {
return Promise.all(
keys.map(key => caches.delete(key))
);
})
);
}
});
// Push notification support (future enhancement)
self.addEventListener('push', event => {
if (!event.data) return;
try {
const data = event.data.json();
const options = {
body: data.body || 'New notification',
icon: '/icon.png',
badge: '/icon.png',
vibrate: [200, 100, 200],
data: {
dateOfArrival: Date.now(),
primaryKey: data.primaryKey || 1
},
actions: [
{
action: 'view',
title: 'View'
},
{
action: 'close',
title: 'Close'
}
]
};
event.waitUntil(
self.registration.showNotification(data.title || 'GitHub Bot', options)
);
} catch (err) {
console.error('[SW] Push notification error:', err);