// part of file sw.ts -> transpiles into /sw.js
const VERSION = "<WHATEVER>";
const CACHE_KEY = 'pacemjs-v' + VERSION;
const OFFLINE_PAGE = '/offline.html';
//Prefetched items.
const PREFETCHED = [
    '/bundle.js',
    OFFLINE_PAGE,
];
//List of items excluded.
const EXCLUDED = [
    '/manifest.json'
];
async function _tryCache(request, response) {
    // Only GET requests are allowed to be `put` into the cache.
    if (request.method.toLowerCase() != 'get')
        return;
    const url = request.url;
    // check if the requested url must not be included in the cache
    for (var excluded of EXCLUDED) {
        if (url.endsWith(excluded)) {
            return;
        }
    }
    // if caching is allowed for this request, then...
    const cache = await caches.open(CACHE_KEY);
    cache.put(request, 
    // responses might be allowed to be used only once, thus cloning 
    response.clone());
}
const _networkFirst = (evt) => {
    // Network first (refreshes the cache), falling back to cache if offline.
    evt.respondWith(caches.match(evt.request)
        .then(async (cachedResponse) => {
        const url = evt.request.url;
        try {
            const r = await fetch(evt.request);
            // might respond `200 ok` even if offline, depending on the browser HTTP cache.
            console.log('fresh response for ' + url);
            await _tryCache(evt.request, r);
            return r;
        }
        catch (_) {
            console.warn(_);
            if (cachedResponse) {
                console.log('cached response for ' + url);
                return cachedResponse;
            }
            else
                return caches.match(OFFLINE_PAGE);
        }
    }));
};
self.addEventListener('fetch', _networkFirst);
self.addEventListener('activate', function (event) {
    console.log('Service Worker v' + VERSION + ' activated.');
    // In order to clear the cache, then update the {VERSION} above:
    // former cache version, if any, will be cleared.
    // Delete all caches that aren't named {CACHE_KEY}    
    event.waitUntil(caches.keys().then(function (cacheNames) {
        return Promise.all(cacheNames.map(function (cacheName) {
            if (cacheName !== CACHE_KEY) {
                console.info('Removing outdated cache:', cacheName);
                return caches.delete(cacheName);
            }
        }));
    }));
});
