vanillajs-deck/pwa.js

234 lines
7.4 KiB
JavaScript
Raw Normal View History

2019-12-03 19:17:35 +00:00
// @ts-check
2019-12-03 00:18:40 +00:00
/**
2019-12-03 19:17:35 +00:00
* @typedef {function} AddEventListener
* @param {string} eventName Name of event to add
* @param {EventListener} callback Callback when event is fired
* @returns {void}
2019-12-03 00:18:40 +00:00
*/
/**
2019-12-03 19:17:35 +00:00
* @typedef {object} ServiceWorkerGlobalScope
* @property {function} skipWaiting skip the waiting
* @property {AddEventListener} addEventListener Add event listener
* @property {any} clients Service worker clients
2019-12-03 00:18:40 +00:00
*/
/**
2019-12-03 19:17:35 +00:00
* Service worker for Progressive Web App
* */
class Pwa {
/**
* Create a new instance
* @param {ServiceWorkerGlobalScope} self
*/
constructor(self) {
/**
* Global scope
* @type {ServiceWorkerGlobalScope}
*/
this.scope = self;
2019-12-03 00:18:40 +00:00
2019-12-03 19:17:35 +00:00
/**
* Cache version
* @type {number}
*/
2020-01-28 21:41:29 +00:00
this.CACHE_VERSION = 1.3;
2019-12-03 19:17:35 +00:00
/**
* Pre-emptive files to cache
* @type {string[]}
*/
this.BASE_CACHE_FILES = [
'/index.html',
'/pwa/404.html',
'/pwa/offline.html',
'/css/style.css',
'/css/animations.css',
'/manifest.json',
'/images/logo.png',
'/js/app.js',
];
/**
* Page to redirect to when offline
* @type {string}
*/
this.OFFLINE_PAGE = '/pwa/offline.html';
/**
* Page to show when not found (404)
* @type {string}
*/
this.NOT_FOUND_PAGE = '/pwa/404.html';
/**
2019-12-03 23:28:57 +00:00
* Versioned cache
* @type {string}
2019-12-03 19:17:35 +00:00
*/
2019-12-03 23:28:57 +00:00
this.CACHE_NAME = `content-v${this.CACHE_VERSION}`;
2019-12-03 19:17:35 +00:00
/**
* The time to live in cache
* @type {object}
*/
2019-12-03 23:28:57 +00:00
this.MAX_TTL = 86400;
2019-12-03 00:18:40 +00:00
2019-12-03 19:17:35 +00:00
/**
2019-12-03 23:28:57 +00:00
* Extensions with no expiration in the cache
2019-12-03 19:17:35 +00:00
* @type {string[]}
*/
2019-12-03 23:28:57 +00:00
this.TTL_EXCEPTIONS = ["jpg", "jpeg", "png", "gif", "mp4"];
2019-12-03 19:17:35 +00:00
}
2019-12-03 00:18:40 +00:00
2019-12-03 19:17:35 +00:00
/**
* Get the extension of a file from URL
* @param {string} url
2019-12-03 23:28:57 +00:00
* @returns {string} The extension
2019-12-03 19:17:35 +00:00
*/
getFileExtension(url) {
2019-12-03 23:28:57 +00:00
const extension = url.split('.').reverse()[0].split('?')[0];
2019-12-03 19:17:35 +00:00
return (extension.endsWith('/')) ? '/' : extension;
}
2019-12-03 00:18:40 +00:00
2019-12-03 19:17:35 +00:00
/**
* Get time to live for cache by extension
* @param {string} url
* @returns {number} Time to live in seconds
*/
getTTL(url) {
if (typeof url === 'string') {
const extension = this.getFileExtension(url);
2019-12-03 23:28:57 +00:00
return ~this.TTL_EXCEPTIONS.indexOf(extension) ?
2019-12-05 18:51:21 +00:00
null : this.MAX_TTL;
2019-12-03 19:17:35 +00:00
}
2019-12-03 23:28:57 +00:00
return null;
2019-12-03 19:17:35 +00:00
}
2019-12-03 00:18:40 +00:00
2019-12-03 19:17:35 +00:00
async installServiceWorker() {
try {
2019-12-03 23:28:57 +00:00
await caches.open(this.CACHE_NAME).then((cache) => {
return cache.addAll(this.BASE_CACHE_FILES);
}, err => console.error(`Error with ${this.CACHE_NAME}`, err));
2019-12-03 19:17:35 +00:00
return this.scope.skipWaiting();
}
2019-12-03 23:28:57 +00:00
catch (err) {
return console.error("Error with installation: ", err);
2019-12-03 19:17:35 +00:00
}
}
2019-12-03 00:18:40 +00:00
2019-12-03 19:17:35 +00:00
/**
* Removes prior cache version
* @returns {Promise}
*/
cleanupLegacyCache() {
2019-12-03 00:18:40 +00:00
2019-12-03 23:28:57 +00:00
const currentCaches = [this.CACHE_NAME];
2019-12-03 00:18:40 +00:00
2019-12-03 19:17:35 +00:00
return new Promise(
(resolve, reject) => {
2019-12-03 23:28:57 +00:00
caches.keys()
.then((keys) => keys.filter((key) => !~currentCaches.indexOf(key)))
.then((legacy) => {
if (legacy.length) {
Promise.all(legacy.map((legacyKey) => caches.delete(legacyKey))
).then(() => resolve()).catch((err) => {
console.error("Error in legacy cleanup: ", err);
reject(err);
});
} else {
2019-12-03 19:17:35 +00:00
resolve();
2019-12-03 23:28:57 +00:00
}
}).catch((err) => {
console.error("Error in legacy cleanup: ", err);
reject(err);
});
2019-12-03 19:17:35 +00:00
});
}
/**
* Pre-fetches URL to store to cache
* @param {string} url
*/
2019-12-03 23:28:57 +00:00
async preCacheUrl(url) {
const cache = await caches.open(this.CACHE_NAME);
const response = await cache.match(url);
if (!response) {
return fetch(url).then(resp => cache.put(url, resp.clone()));
}
return null;
2019-12-03 19:17:35 +00:00
}
/**
* Registers the various service worker functions
* @returns {void}
*/
register() {
this.scope.addEventListener('install', event => {
event.waitUntil(
Promise.all([
this.installServiceWorker(),
this.scope.skipWaiting(),
]));
});
// The activate handler takes care of cleaning up old caches.
this.scope.addEventListener('activate', event => {
event.waitUntil(Promise.all(
[this.cleanupLegacyCache(),
this.scope.clients.claim(),
this.scope.skipWaiting()]).catch((err) => {
console.error("Activation error: ", err);
event.skipWaiting();
}));
});
this.scope.addEventListener('fetch', event => {
event.respondWith(
2019-12-03 23:28:57 +00:00
caches.open(this.CACHE_NAME).then(async cache => {
2020-01-28 21:41:29 +00:00
if (event.request.url.startsWith("http://localhost")) {
return fetch(event.request.clone());
}
const response = await cache.match(event.request);
if (response) {
// found it, see if expired
const headers = response.headers.entries();
let date = null;
for (let pair of headers) {
if (pair[0] === 'date') {
date = new Date(pair[1]);
break;
2019-12-03 00:18:40 +00:00
}
2019-12-03 23:28:57 +00:00
}
2020-01-28 21:41:29 +00:00
if (!date) {
return response;
}
const age = parseInt(((new Date().getTime() - date.getTime()) / 1000).toString());
const ttl = this.getTTL(event.request.url);
if (ttl === null || (ttl && age < ttl)) {
return response;
}
2019-12-03 23:28:57 +00:00
}
// not found or expired, fresh request
return fetch(event.request.clone()).then(resp => {
if (resp.status < 400) {
// good to go
cache.put(event.request, resp.clone());
return resp;
}
else {
// not found
return cache.match(this.NOT_FOUND_PAGE);
}
}).catch(err => {
// offline
console.error("Error resulting in offline", err);
return cache.match(this.OFFLINE_PAGE);
2019-12-03 19:17:35 +00:00
})
2019-12-03 23:28:57 +00:00
}));
2019-12-03 19:17:35 +00:00
});
2019-12-03 00:18:40 +00:00
}
2019-12-03 19:17:35 +00:00
}
/**
* Sadly this is a pathetic hack to workaround JsDoc limitations
2019-12-05 18:51:21 +00:00
* Casting what the IDE thinks is Window to service worker scope
2019-12-03 19:17:35 +00:00
* @type {any} */
const _self = self;
var pwa = new Pwa(/**@type {ServiceWorkerGlobalScope}*/(_self));
pwa.register();