From bd3a1fe84c0bf22115daa68f8d1f1a96c6b4b80b Mon Sep 17 00:00:00 2001 From: ayoayco Date: Sat, 17 Aug 2024 11:33:39 +0200 Subject: [PATCH] feat: better logs & helpful messages --- index.js | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/index.js b/index.js index 0a4e99f..497b3e4 100644 --- a/index.js +++ b/index.js @@ -22,19 +22,19 @@ const ASTROSW = 'astro-sw'; /** * Accepts configuration options with service worker path * and injects needed variables such as `__assets` generated by Astro - * @param {ServiceWorkerConfig} config + * @param {ServiceWorkerConfig} options * @returns {AstroIntegration} */ -export default function serviceWorker(config) { +export default function serviceWorker(options) { let { assetCachePrefix = ASTROSW, assetCacheVersionID = randomUUID(), - path: serviceWorkerPath, + path: serviceWorkerPath = undefined, customRoutes = [], excludeRoutes = [], logAssets = false, esbuild = {} - } = config; + } = options || {}; /** * @type {Array} @@ -75,8 +75,15 @@ export default function serviceWorker(config) { return { 'name': ASTROSW, 'hooks': { - 'astro:config:setup': async ({ injectScript, config, command, logger }) => { - output = config.output; + 'astro:config:setup': async ({ injectScript, config: _config, command, logger }) => { + + if (!serviceWorkerPath || serviceWorkerPath === '') { + // REQUIRED OPTION IS MISSING + logger.error('Missing required path to service worker script'); + } + + + output = _config.output; if (command === 'build') { injectScript('page', registrationScript); } @@ -98,7 +105,9 @@ declare const __prefix: string;` }, 'astro:build:done': async ({ dir, routes, pages, logger }) => { const outfile = fileURLToPath(new URL('./sw.js', dir)); - const swPath = path.join(__dirname, serviceWorkerPath ?? ''); + const swPath = (serviceWorkerPath && serviceWorkerPath !== '') + ? path.join(__dirname, serviceWorkerPath) + : undefined; let originalScript; const _publicFiles = (await readdir(dir, { withFileTypes: true }) ?? []) @@ -147,17 +156,26 @@ declare const __prefix: string;` && !_excludeRoutes.includes(asset) ); - logger.info(`${assets.length} assets for caching.`); if (logAssets) { - logger.info('Assets: ' + assets.toString().replaceAll(',', ', ')); + logger.info(`\n\n[${ASTROSW}] ${assets.length} assets for caching: \n ▶ ${assets.toString().replaceAll(',', ',\n ▶ ')}\n`); + } else { + logger.info(`${assets.length} assets for caching.`); } try { - logger.info(`Using service worker: ${swPath}`); + logger.info(`Using service worker in path: ${swPath}`); originalScript = await readFile(swPath); } catch { logger.error(`Service worker script not found! ${swPath}`) + if (!swPath) { + + logger.error(` + +[${ASTROSW}] ERR: The 'path' option is required! +[${ASTROSW}] INFO: Please see service worker options in https://ayco.io/gh/astro-sw#readme +`); + } } const assetsDeclaration = `const __assets = ${JSON.stringify(assets)};\n`;