diff --git a/astro.config.mjs b/astro.config.mjs index d4a8723..a74a221 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -11,6 +11,10 @@ export default defineConfig({ serviceWorker({ path: "./example_sw.js", assetCachePrefix: 'cozy-reader', + // onInstalled: () => console.log('Installed...'), + // onInstalling: () => console.log('Installing...'), + // onActive: () => console.log('Active!'), + // onError: (error) => console.error(`Registration failed on ${error}`) }) ] }); diff --git a/index.js b/index.js index 4c590a8..5559cf3 100644 --- a/index.js +++ b/index.js @@ -5,16 +5,20 @@ import { randomUUID } from "node:crypto"; /** * @typedef {{ + * path: string, * assetCachePrefix?: string, * assetCacheVersionID?: string, - * path: string, + * onInstalling?: Function, + * onInstalled?: Function, + * onActive?: Function, + * onError?: Function * }} ServiceWorkerConfig * @typedef {import('astro').AstroIntegration} AstroIntegration */ /** * Accepts configuration options with service worker path - * and injects needed variables such as `assets` generated by Astro + * and injects needed variables such as `__assets` generated by Astro * @param {ServiceWorkerConfig} config * @returns {AstroIntegration} */ @@ -22,7 +26,15 @@ export default function serviceWorker(config) { let { assetCachePrefix, assetCacheVersionID = randomUUID(), - path: serviceWorkerPath + path: serviceWorkerPath, + /** + * TODO: use registration hooks callbacks + */ + // onInstalling, + // onInstalled, + // onActive, + // onError, + // onUnsupported, } = config; /** @@ -30,9 +42,40 @@ export default function serviceWorker(config) { */ let assets = []; + const registrationScript = `const registerSW = async () => { + if ("serviceWorker" in navigator) { + try { + const registration = await navigator.serviceWorker.register("/sw.js", { + scope: "/", + }); + if (registration.installing) { + // installingFn(); + console.log('[astro-sw] Installing...') + } else if (registration.waiting) { + // installedFn(); + console.log('[astro-sw] Installed...') + } else if (registration.active) { + // activeFn(); + console.log('[astro-sw] Active...') + } + } catch (error) { + // onError(error); + console.error('[astro-sw] ERR', error) + } + } else { + // onUnsupported(); + console.log('[astro-sw] Browser does not support Service Worker') + } + } + + registerSW();` + return { 'name': 'astro-sw', 'hooks': { + 'astro:config:setup': ({injectScript}) => { + injectScript('page', registrationScript); + }, 'astro:build:ssr': ({ manifest }) => { assets = manifest.assets.filter(ass => !ass.includes('sw.js')) }, diff --git a/src/index.astro b/src/index.astro deleted file mode 100644 index fbcbb08..0000000 --- a/src/index.astro +++ /dev/null @@ -1,4 +0,0 @@ ---- ---- - -hello diff --git a/src/pages/index.astro b/src/pages/index.astro new file mode 100644 index 0000000..b20feff --- /dev/null +++ b/src/pages/index.astro @@ -0,0 +1,14 @@ +--- +--- + + + + + + Hello + + + Hello + + + \ No newline at end of file