UNPKG

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 2.5 kB
import{join}from"node:path";import{encodeError}from"error-message-utils";import{isArrayValid,isObjectValid,isStringValid,generateRandomString}from"web-utils-kit";import{isDirectory,readJSONFile,getPathElement,readDirectory}from"fs-utils-sync";import{ERRORS}from"../shared/errors.js";const CACHE_NAME_CHARACTERS="abcdefghijklmnopqrstuvwxyz0123456789",CACHE_NAME_LENGTH=10,OUTPUT_NAME="sw.js",__validateConfigFile=e=>{if(!isObjectValid(e))throw console.log(e),new Error(encodeError("The extracted configuration is not a valid object.",ERRORS.INVALID_CONFIG_VALUE));if(!isStringValid(e.outDir,1)||!isDirectory(e.outDir))throw new Error(encodeError(`The outDir '${e.outDir}' is not a directory or doesn't exist.`,ERRORS.INVALID_CONFIG_VALUE));if(!isStringValid(e.template,1))throw new Error(encodeError(`The template '${e.template}' is not a valid template name.`,ERRORS.INVALID_CONFIG_VALUE));if(!isArrayValid(e.includeToPrecache,!0))throw console.log(e.includeToPrecache),new Error(encodeError(`The includeToPrecache '${e.includeToPrecache}' list is invalid.`,ERRORS.INVALID_CONFIG_VALUE));if(!isArrayValid(e.excludeFilesFromPrecache,!0))throw console.log(e.excludeFilesFromPrecache),new Error(encodeError(`The excludeFilesFromPrecache '${e.excludeFilesFromPrecache}' list is invalid.`,ERRORS.INVALID_CONFIG_VALUE));if(!isArrayValid(e.excludeMIMETypesFromCache,!0))throw console.log(e.excludeMIMETypesFromCache),new Error(encodeError(`The excludeMIMETypesFromCache '${e.excludeMIMETypesFromCache}' list is invalid.`,ERRORS.INVALID_CONFIG_VALUE))},__getPathElement=e=>{const r=getPathElement(e);if(null===r||!r.isDirectory&&!r.isFile)throw new Error(encodeError(`The asset '${e}' is not a path element.`,ERRORS.NOT_A_PATH_ELEMENT));return r},__extractCacheableFilesFromDirectory=(e,r,i)=>{let t=readDirectory(r,!0);return t=t.filter((e=>{const r=__getPathElement(e);return r.isFile&&!i.includes(r.baseName)})),t.map((r=>r.replace(e,"")))},readConfigFile=e=>{const r=readJSONFile(e);return __validateConfigFile(r),r},generateCacheName=()=>generateRandomString(10,CACHE_NAME_CHARACTERS),buildPrecacheAssetPaths=(e,r,i)=>{if(0===r.length)return[];const t=["/"];return r.forEach((r=>{if("/"!==r){const o=__getPathElement(join(e,r));o.isFile&&!i.includes(o.baseName)?t.push(r):t.push(...__extractCacheableFilesFromDirectory(e,o.path,i))}})),t},buildOutputPath=e=>join(e,"sw.js");export{CACHE_NAME_CHARACTERS,CACHE_NAME_LENGTH,OUTPUT_NAME,readConfigFile,generateCacheName,buildPrecacheAssetPaths,buildOutputPath};