sw.jsā¢3.02 kB
// Service Worker for MCP Markdown Manager PWA
const CACHE_NAME = 'mcp-markdown-manager-v1';
const STATIC_CACHE = 'mcp-markdown-manager-static-v1';
const DYNAMIC_CACHE = 'mcp-markdown-manager-dynamic-v1';
// Static assets to cache on install
const STATIC_ASSETS = [
'/',
'/manifest.json',
'/icon-192.png',
'/icon-512.png'
];
// Install event - cache static assets
self.addEventListener('install', (event) => {
console.log('[SW] Installing service worker...');
event.waitUntil(
caches.open(STATIC_CACHE)
.then((cache) => {
console.log('[SW] Caching static assets');
return cache.addAll(STATIC_ASSETS);
})
.then(() => self.skipWaiting())
);
});
// Activate event - clean up old caches
self.addEventListener('activate', (event) => {
console.log('[SW] Activating service worker...');
event.waitUntil(
caches.keys()
.then((cacheNames) => {
return Promise.all(
cacheNames
.filter((name) => name !== STATIC_CACHE && name !== DYNAMIC_CACHE)
.map((name) => {
console.log('[SW] Deleting old cache:', name);
return caches.delete(name);
})
);
})
.then(() => self.clients.claim())
);
});
// Fetch event - network first, fallback to cache for API calls, cache first for static assets
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
// Skip non-GET requests
if (request.method !== 'GET') {
return;
}
// API requests - network first, fallback to cache
if (url.pathname.startsWith('/api/') || url.pathname === '/health') {
event.respondWith(
fetch(request)
.then((response) => {
// Clone response and cache it
const responseClone = response.clone();
caches.open(DYNAMIC_CACHE).then((cache) => {
cache.put(request, responseClone);
});
return response;
})
.catch(() => {
// Fallback to cache if network fails
return caches.match(request);
})
);
return;
}
// Static assets - cache first, fallback to network
event.respondWith(
caches.match(request)
.then((cachedResponse) => {
if (cachedResponse) {
return cachedResponse;
}
return fetch(request)
.then((response) => {
// Don't cache non-successful responses
if (!response || response.status !== 200 || response.type === 'error') {
return response;
}
// Clone and cache the response
const responseClone = response.clone();
caches.open(DYNAMIC_CACHE).then((cache) => {
cache.put(request, responseClone);
});
return response;
});
})
);
});
// Handle messages from clients
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});