const CONFIG = []; const CACHE_PREFIX = 'mandano-pwa-'; const CACHE_NAME = CACHE_PREFIX + (CONFIG.cacheVersion || '1'); const PRECACHE_NAME = CACHE_NAME + '-precache'; const BASE_PATH = (CONFIG.basePath || '').replace(/\/$/, ''); function relativePath(pathname) { if (BASE_PATH && pathname.indexOf(BASE_PATH) === 0) { pathname = pathname.slice(BASE_PATH.length) || '/'; } return pathname || '/'; } function isExcluded(pathname) { const path = relativePath(pathname); return (CONFIG.excludedPaths || []).some(function (excluded) { return path === excluded || path.indexOf(excluded + '/') === 0; }); } function resolveUrl(value) { const raw = String(value || CONFIG.startUrl || '/'); if (/^https?:\/\//i.test(raw)) return raw; const base = new URL(CONFIG.startUrl || self.registration.scope, self.location.origin); const path = base.pathname.replace(/\/$/, '') + '/' + raw.replace(/^\//, ''); return new URL(path, base.origin).href; } function isCacheable(response) { if (!response || response.status !== 200 || response.type !== 'basic') { return false; } const control = (response.headers.get('cache-control') || '').toLowerCase(); return !/no-store|private/.test(control) && !response.headers.has('set-cookie'); } function trimCache(name, limit) { return caches.open(name).then(function (cache) { return cache.keys().then(function (keys) { if (keys.length <= limit) return; return Promise.all(keys.slice(0, keys.length - limit).map(function (request) { return cache.delete(request); })); }); }); } async function networkFirst(request, event) { const cache = await caches.open(CACHE_NAME); try { const response = await fetch(request); if (CONFIG.cachePages && isCacheable(response)) { // Keep the cache write inside the respondWith promise. Calling // event.waitUntil() after an await is not reliable in Safari. try { await cache.put(request, response.clone()); } catch (error) { // A successful navigation must still render when the cache // rejects a response (for example Vary: * or quota limits). } } return response; } catch (error) { const cached = await cache.match(request); if (cached) return cached; const offline = CONFIG.offline ? await caches.match(CONFIG.offlineUrl) : null; return offline || new Response( '
Reconnect to continue shopping.
', {headers: {'Content-Type': 'text/html; charset=utf-8'}} ); } } function staleWhileRevalidate(request, event) { const cachePromise = caches.open(CACHE_NAME); const network = cachePromise.then(function (cache) { return fetch(request).then(function (response) { if (!CONFIG.cacheAssets || !isCacheable(response)) return response; return cache.put(request, response.clone()) .then(function () { return trimCache(CACHE_NAME, 90); }) .catch(function () {}) .then(function () { return response; }); }); }).catch(function () { return null; }); // Start extending the event while this function is still synchronous; // this matters on iOS where the worker can be stopped quickly. event.waitUntil(network); return cachePromise.then(function (cache) { return cache.match(request); }).then(function (cached) { if (cached) return cached; return network.then(function (response) { return response || new Response('', {status: 503, statusText: 'Offline'}); }); }).catch(function () { return new Response('', {status: 503, statusText: 'Offline'}); }); } self.addEventListener('install', function (event) { event.waitUntil( caches.open(PRECACHE_NAME).then(function (cache) { return Promise.all((CONFIG.precache || []).map(function (url) { return cache.add(url).catch(function () { // One optional asset (for example a custom icon) must not // stop the service worker from installing. }); })); }).then(function () { return self.skipWaiting(); }) ); }); self.addEventListener('activate', function (event) { event.waitUntil( caches.keys().then(function (keys) { return Promise.all(keys.filter(function (key) { return key.indexOf(CACHE_PREFIX) === 0 && key !== CACHE_NAME && key !== PRECACHE_NAME; }).map(function (key) { return caches.delete(key); })); }).then(function () { return self.clients.claim(); }) ); }); self.addEventListener('fetch', function (event) { const request = event.request; if (request.method !== 'GET') return; const url = new URL(request.url); if (url.origin !== self.location.origin) return; if (request.headers.get('range')) return; if (request.mode === 'navigate') { if (isExcluded(url.pathname)) { event.respondWith(fetch(request).catch(async function () { const offline = CONFIG.offline ? await caches.match(CONFIG.offlineUrl) : null; return offline || new Response('', {status: 503, statusText: 'Offline'}); })); return; } event.respondWith(networkFirst(request, event)); return; } if (isExcluded(url.pathname)) { event.respondWith(fetch(request).catch(function () { const offline = CONFIG.offline ? caches.match(CONFIG.offlineUrl) : null; return offline || new Response('', {status: 503, statusText: 'Offline'}); })); return; } if (['style', 'script', 'image', 'font', 'manifest'].indexOf(request.destination) !== -1 || url.pathname.indexOf('/assets/') !== -1) { event.respondWith(staleWhileRevalidate(request, event)); } }); self.addEventListener('push', function (event) { let data = {}; if (event.data) { try { data = event.data.json(); } catch (error) { data = {body: event.data.text()}; } } const title = data.title || CONFIG.appName || 'Store update'; const options = { body: data.body || '', icon: data.icon || CONFIG.icon, badge: data.badge || CONFIG.badge || CONFIG.icon, tag: data.tag || 'mandano-pwa', renotify: true, data: { url: data.url || CONFIG.startUrl || '/', }, actions: [{action: 'open', title: CONFIG.openLabel || 'Open'}], }; event.waitUntil(self.registration.showNotification(title, options)); }); self.addEventListener('notificationclick', function (event) { event.notification.close(); const target = resolveUrl(event.notification.data && event.notification.data.url); event.waitUntil( self.clients.matchAll({type: 'window', includeUncontrolled: true}).then(function (clients) { for (const client of clients) { if ('focus' in client) { if (client.url === target) return client.focus(); } } for (const client of clients) { if ('navigate' in client && client.url.indexOf(self.location.origin) === 0) { return client.navigate(target).then(function () { return client.focus(); }); } } if (self.clients.openWindow) return self.clients.openWindow(target); }) ); }); self.addEventListener('message', function (event) { if (event.data === 'SKIP_WAITING') self.skipWaiting(); if (event.data === 'CLEAR_CACHE') { event.waitUntil( caches.keys().then(function (keys) { return Promise.all(keys.filter(function (key) { return key.indexOf(CACHE_PREFIX) === 0; }).map(function (key) { return caches.delete(key); })); }) ); } });