sw-builder
Version:
The sw-builder package automates the creation of your Application's Service Worker, which pre-caches your build. This leads to a better overall performance and enables users to access your PWA without an Internet connection.
1 lines • 5.3 kB
JavaScript
const BASE_TEMPLATE="/* ************************************************************************************************\n* CONSTANTS *\n************************************************************************************************ */\n\n// the current version of the cache\nconst CACHE_NAME = '';\n\n// assets that will be cached once the service worker is installed\nconst PRECACHE_ASSETS = [];\n\n// the list of MIME Types that won't be cached when the app sends HTTP GET requests\nconst EXCLUDE_MIME_TYPES = [];\n\n\n\n\n\n/* ************************************************************************************************\n* MAIN CACHE ACTIONS *\n************************************************************************************************ */\n\n/**\n * Invoked when the Service Worker has been installed. It takes care of adding the base resources\n * to the cache (if any).\n* @returns Promise<void>\n*/\nconst precacheResources = async () => {\n if (PRECACHE_ASSETS.length > 0) {\n const cache = await caches.open(CACHE_NAME);\n await cache.addAll(PRECACHE_ASSETS);\n }\n};\n\n/**\n * Verifies if the value of the 'Accept' or 'Content-Type' header is cacheable.\n * @param {*} contentTypeHeader\n * @returns boolean\n */\nconst isMIMETypeCacheable = (contentTypeHeader) => (\n contentTypeHeader === null\n || !EXCLUDE_MIME_TYPES.some((type) => contentTypeHeader.includes(type))\n);\n\n/**\n* All requests should be cached except for:\n* - Non-GET requests\n* - Requests with MIME Types that are not included in EXCLUDE_MIME_TYPES\n* @param {*} request\n* @param {*} response\n* @returns boolean\n*/\nconst canRequestBeCached = (request, response) => (\n request.ok\n && request.method === 'GET'\n && response.type !== 'opaque'\n && isMIMETypeCacheable(request.headers.get('accept'))\n && isMIMETypeCacheable(response.headers.get('content-type'))\n);\n\n/**\n* Adds the request and its response to the cache.\n* @param {*} request\n* @param {*} response\n* @returns Promise<void>\n*/\nconst putInCache = async (request, response) => {\n if (canRequestBeCached(request, response)) {\n const cache = await caches.open(CACHE_NAME);\n await cache.put(request, response);\n }\n};\n\n/**\n* Intercepts the fetch requests and attempts to fill them with data from the cache. If not present,\n* it will perform the request and store the data in cache.\n* Note: the Response stored in cache is a clone as it can only be read once.\n* @param {*} request\n* @returns Promise<Response>\n*/\nconst cacheFirst = async (request) => {\n // first, try to get the resource from the cache\n const responseFromCache = await caches.match(request);\n if (responseFromCache) {\n return responseFromCache;\n }\n\n // next, try to get the resource from the network\n try {\n const responseFromNetwork = await fetch(request);\n putInCache(request, responseFromNetwork.clone());\n return responseFromNetwork;\n } catch (error) {\n return new Response('Network error happened', {\n status: 408,\n headers: { 'Content-Type': 'text/plain' },\n });\n }\n};\n\n\n\n\n\n/* ************************************************************************************************\n* CACHE CLEAN UP ACTIONS *\n************************************************************************************************ */\n\n/**\n* Deletes everything stored in cache that doesn't match the current version.\n* @returns Promise<void>\n*/\nconst deleteOldCaches = async () => {\n const keyList = await caches.keys();\n const cachesToDelete = keyList.filter((key) => key !== CACHE_NAME);\n if (cachesToDelete.length) {\n await Promise.all(cachesToDelete.map((key) => caches.delete(key)));\n }\n};\n\n\n\n\n\n/* ************************************************************************************************\n* EVENTS *\n************************************************************************************************ */\n\n/**\n* Triggers when the Service Worker has been fetched and registered.\n* It takes care of clearing and adding the new base resources to the cache.\n*/\nself.addEventListener('install', (event) => {\n event.waitUntil(deleteOldCaches().then(() => precacheResources()));\n});\n\n/**\n* Triggers after the Service Worker is installed and it has taken control of the app.\n* It takes care of enabling navigation preload (if supported) and it also takes control of any\n* pages that were controlled by the previous version of the worker (if any).\n*/\nself.addEventListener('activate', (event) => {\n event.waitUntil(self.clients.claim().then(() => deleteOldCaches()));\n});\n\n/**\n* Triggers when the app thread makes a network request.\n* It intercepts the request and checks if it can be filled with data from cache. Otherwise, it\n* resumes the network request and then stores it cache for future requests.\n*/\nself.addEventListener('fetch', (event) => {\n event.respondWith(cacheFirst(event.request));\n});\n";export{BASE_TEMPLATE};