diff --git a/index.js b/index.js index 738a975..b47adc5 100644 --- a/index.js +++ b/index.js @@ -69,15 +69,36 @@ export default function serviceWorker(config) { registerSW();` let output = 'static'; + const __dirname = path.resolve(path.dirname('.')); return { 'name': 'astro-sw', 'hooks': { - 'astro:config:setup': ({ injectScript, config, command }) => { + 'astro:config:setup': async ({ injectScript, config, command, logger }) => { output = config.output; if (command === 'build') { injectScript('page', registrationScript); } + + const injectedTypeDefinitions = ` +/*** + * @ayco/astro-sw injected variables + */ +declare const __assets: string; +declare const __version: string; +declare const __prefix: string; + ` + + const envTs = path.join(__dirname, 'src/env.d.ts'); + try { + await writeFile( + envTs, + injectedTypeDefinitions, + { flag: 'a+' } + ); + } catch (err) { + logger.error(err.toString()) + } }, 'astro:build:ssr': ({ manifest }) => { const files = manifest.routes.map(route => route.file.replaceAll('/', '')); @@ -89,7 +110,6 @@ export default function serviceWorker(config) { }, 'astro:build:done': async ({ dir, routes, pages, logger }) => { const outfile = fileURLToPath(new URL('./sw.js', dir)); - const __dirname = path.resolve(path.dirname('.')); const swPath = path.join(__dirname, serviceWorkerPath ?? ''); let originalScript; diff --git a/src/example_sw.ts b/src/example_sw.ts index 744d419..70fe866 100644 --- a/src/example_sw.ts +++ b/src/example_sw.ts @@ -1,11 +1,11 @@ import { log } from "./utils"; /** - * Note: @ayco/astro-sw integration injects variables `__astro_sw_cache_prefix__`, `__astro_sw_version__`, & `__astro_sw_assets__` + * Note: @ayco/astro-sw integration injects variables `__prefix`, `__version`, & `__assets` * -- find usage in package readme; `astro.config.mjs` integrations * @see https://ayco.io/n/@ayco/astro-sw */ -const cacheName = `${__astro_sw_cache_prefix__ ?? 'app'}-v${__astro_sw_version__ ?? '000'}` +const cacheName = `${__prefix ?? 'app'}-v${__version ?? '000'}` const addResourcesToCache = async (resources) => { const cache = await caches.open(cacheName); console.log('adding resources to cache...', resources) @@ -80,7 +80,7 @@ self.addEventListener('install', (event) => { event.waitUntil( addResourcesToCache([ './', - ...(__astro_sw_assets__ ?? []) + ...(__assets ?? []) ]) ); });