2023-05-30 17:38:24 +00:00
|
|
|
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
|
|
import type { Buffer } from 'node:buffer'
|
|
|
|
import { dirname } from 'node:path'
|
|
|
|
import { fileURLToPath } from 'node:url'
|
2023-02-16 09:23:26 +00:00
|
|
|
import { addPlugin, createResolver, defineNuxtModule } from '@nuxt/kit'
|
2023-01-06 12:48:43 +00:00
|
|
|
import type { VitePluginPWAAPI } from 'vite-plugin-pwa'
|
2022-12-17 23:29:16 +00:00
|
|
|
import { VitePWA } from 'vite-plugin-pwa'
|
|
|
|
import type { Plugin } from 'vite'
|
2023-05-30 17:38:24 +00:00
|
|
|
import { join, resolve } from 'pathe'
|
2022-12-17 23:29:16 +00:00
|
|
|
import type { VitePWANuxtOptions } from './types'
|
|
|
|
import { configurePWAOptions } from './config'
|
2023-01-06 12:48:43 +00:00
|
|
|
import { type LocalizedWebManifest, createI18n, pwaLocales } from './i18n'
|
2022-12-17 23:29:16 +00:00
|
|
|
|
|
|
|
export * from './types'
|
2023-05-30 17:38:24 +00:00
|
|
|
|
|
|
|
interface PwaDevIcon {
|
|
|
|
src: string
|
|
|
|
type: string
|
|
|
|
}
|
|
|
|
|
|
|
|
interface ResolvedPwaDevIcon extends PwaDevIcon {
|
|
|
|
data: Promise<Buffer>
|
|
|
|
}
|
|
|
|
|
2022-12-17 23:29:16 +00:00
|
|
|
export default defineNuxtModule<VitePWANuxtOptions>({
|
|
|
|
meta: {
|
2023-04-03 13:34:19 +00:00
|
|
|
name: 'elk-pwa',
|
2022-12-17 23:29:16 +00:00
|
|
|
configKey: 'pwa',
|
|
|
|
},
|
|
|
|
defaults: nuxt => ({
|
|
|
|
base: nuxt.options.app.baseURL,
|
|
|
|
scope: nuxt.options.app.baseURL,
|
|
|
|
}),
|
|
|
|
async setup(options, nuxt) {
|
2023-02-16 09:23:26 +00:00
|
|
|
const resolver = createResolver(import.meta.url)
|
|
|
|
|
2022-12-17 23:29:16 +00:00
|
|
|
let vitePwaClientPlugin: Plugin | undefined
|
|
|
|
const resolveVitePluginPWAAPI = (): VitePluginPWAAPI | undefined => {
|
|
|
|
return vitePwaClientPlugin?.api
|
|
|
|
}
|
2023-01-06 12:48:43 +00:00
|
|
|
let webmanifests: LocalizedWebManifest | undefined
|
2022-12-17 23:29:16 +00:00
|
|
|
|
2023-01-29 14:18:27 +00:00
|
|
|
nuxt.options.appConfig = nuxt.options.appConfig || {}
|
|
|
|
nuxt.options.appConfig.pwaEnabled = !options.disable
|
|
|
|
|
2023-02-12 14:48:56 +00:00
|
|
|
nuxt.options.nitro.publicAssets = nuxt.options.nitro.publicAssets || []
|
|
|
|
const manifestDir = join(nuxt.options.buildDir, 'manifests')
|
|
|
|
nuxt.options.nitro.publicAssets.push({
|
|
|
|
dir: manifestDir,
|
|
|
|
baseURL: '/',
|
|
|
|
maxAge: 0,
|
|
|
|
})
|
2023-12-09 16:04:41 +00:00
|
|
|
|
|
|
|
// Register PWA types
|
|
|
|
nuxt.hook('prepare:types', ({ references }) => {
|
|
|
|
// TODO: remove this once JetBrains fixes the issue with types: remove also the dts file
|
|
|
|
references.push({ path: resolver.resolve('runtime/types') })
|
|
|
|
references.push({ types: 'vite-plugin-pwa/info' })
|
|
|
|
references.push({ types: 'vite-plugin-pwa/vue' })
|
|
|
|
})
|
|
|
|
if (!options.disable) {
|
2023-02-16 09:23:26 +00:00
|
|
|
// Inject $pwa helper throughout app
|
|
|
|
addPlugin({ src: resolver.resolve('./runtime/pwa-plugin.client') })
|
|
|
|
}
|
|
|
|
|
2022-12-17 23:29:16 +00:00
|
|
|
// TODO: combine with configurePWAOptions?
|
|
|
|
nuxt.hook('nitro:init', (nitro) => {
|
|
|
|
options.outDir = nitro.options.output.publicDir
|
|
|
|
options.injectManifest = options.injectManifest || {}
|
|
|
|
options.injectManifest.globDirectory = nitro.options.output.publicDir
|
|
|
|
})
|
|
|
|
nuxt.hook('vite:extend', ({ config }) => {
|
|
|
|
const plugin = config.plugins?.find(p => p && typeof p === 'object' && 'name' in p && p.name === 'vite-plugin-pwa')
|
|
|
|
if (plugin)
|
|
|
|
throw new Error('Remove vite-plugin-pwa plugin from Vite Plugins entry in Nuxt config file!')
|
|
|
|
})
|
2023-01-04 13:26:30 +00:00
|
|
|
nuxt.hook('vite:extendConfig', async (viteInlineConfig, { isClient }) => {
|
2022-12-17 23:29:16 +00:00
|
|
|
viteInlineConfig.plugins = viteInlineConfig.plugins || []
|
|
|
|
const plugin = viteInlineConfig.plugins.find(p => p && typeof p === 'object' && 'name' in p && p.name === 'vite-plugin-pwa')
|
|
|
|
if (plugin)
|
|
|
|
throw new Error('Remove vite-plugin-pwa plugin from Vite Plugins entry in Nuxt config file!')
|
2023-01-06 12:48:43 +00:00
|
|
|
|
|
|
|
webmanifests = await createI18n()
|
2023-01-10 20:35:34 +00:00
|
|
|
const generateManifest = (entry: string) => {
|
|
|
|
const manifest = webmanifests![entry]
|
2023-01-06 12:48:43 +00:00
|
|
|
if (!manifest)
|
2023-01-10 20:35:34 +00:00
|
|
|
throw new Error(`No webmanifest found for locale/theme ${entry}`)
|
2023-01-06 12:48:43 +00:00
|
|
|
return JSON.stringify(manifest)
|
2023-01-04 13:26:30 +00:00
|
|
|
}
|
2023-02-12 14:48:56 +00:00
|
|
|
if (isClient) {
|
|
|
|
viteInlineConfig.plugins.push({
|
|
|
|
name: 'elk:pwa:locales:build',
|
|
|
|
apply: 'build',
|
|
|
|
async writeBundle(_options, bundle) {
|
|
|
|
if (options.disable || !bundle)
|
|
|
|
return
|
|
|
|
await mkdir(manifestDir, { recursive: true })
|
|
|
|
for (const wm in webmanifests)
|
|
|
|
await writeFile(join(manifestDir, `manifest-${wm}.webmanifest`), generateManifest(wm))
|
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
2023-01-06 12:48:43 +00:00
|
|
|
viteInlineConfig.plugins.push({
|
2023-05-30 17:38:24 +00:00
|
|
|
name: 'elk:pwa:dev',
|
2023-01-06 12:48:43 +00:00
|
|
|
apply: 'serve',
|
|
|
|
configureServer(server) {
|
2023-05-30 17:38:24 +00:00
|
|
|
const icons: PwaDevIcon[] = webmanifests?.['en-US']?.icons as any
|
|
|
|
const mappedIcons: PwaDevIcon[] = [
|
|
|
|
...icons.map(({ src, type }) => ({ src, type })),
|
|
|
|
{ src: 'favicon.ico', type: 'image/x-icon' },
|
|
|
|
{ src: 'apple-touch-icon.png', type: 'image/png' },
|
|
|
|
{ src: 'logo.svg', type: 'image/svg+xml' },
|
|
|
|
]
|
|
|
|
|
|
|
|
const folder = dirname(fileURLToPath(import.meta.url))
|
|
|
|
const useIcons = mappedIcons.reduce((acc, icon) => {
|
|
|
|
icon.src = `${nuxt.options.app.baseURL}${icon.src}`
|
|
|
|
acc[icon.src] = {
|
|
|
|
...icon,
|
|
|
|
data: readFile(resolve(join(folder, '../../public-dev', icon.src))),
|
|
|
|
}
|
|
|
|
return acc
|
|
|
|
}, <Record<string, ResolvedPwaDevIcon>>{})
|
2023-01-06 12:48:43 +00:00
|
|
|
const localeMatcher = new RegExp(`^${nuxt.options.app.baseURL}manifest-(.*).webmanifest$`)
|
2023-05-30 17:38:24 +00:00
|
|
|
server.middlewares.use(async (req, res, next) => {
|
|
|
|
const url = req.url
|
|
|
|
if (!url)
|
|
|
|
return next()
|
|
|
|
|
|
|
|
const match = url.match(localeMatcher)
|
2023-01-06 12:48:43 +00:00
|
|
|
const entry = match && webmanifests![match[1]]
|
|
|
|
if (entry) {
|
|
|
|
res.statusCode = 200
|
|
|
|
res.setHeader('Content-Type', 'application/manifest+json')
|
2023-02-12 11:08:50 +00:00
|
|
|
res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate')
|
2023-01-06 12:48:43 +00:00
|
|
|
res.write(JSON.stringify(entry), 'utf-8')
|
|
|
|
res.end()
|
2023-05-30 17:38:24 +00:00
|
|
|
return
|
2023-01-06 12:48:43 +00:00
|
|
|
}
|
2023-05-30 17:38:24 +00:00
|
|
|
|
|
|
|
const icon = useIcons[url]
|
|
|
|
if (!icon)
|
|
|
|
return next()
|
|
|
|
|
|
|
|
res.statusCode = 200
|
|
|
|
res.setHeader('Content-Type', icon.type)
|
|
|
|
res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate')
|
|
|
|
res.write(await icon.data)
|
|
|
|
res.end()
|
2023-01-06 12:48:43 +00:00
|
|
|
})
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
configurePWAOptions(options, nuxt)
|
|
|
|
const plugins = VitePWA(options)
|
2022-12-17 23:29:16 +00:00
|
|
|
viteInlineConfig.plugins.push(plugins)
|
|
|
|
if (isClient)
|
|
|
|
vitePwaClientPlugin = plugins.find(p => p.name === 'vite-plugin-pwa') as Plugin
|
|
|
|
})
|
|
|
|
|
|
|
|
if (nuxt.options.dev) {
|
|
|
|
const webManifest = `${nuxt.options.app.baseURL}${options.devOptions?.webManifestUrl ?? options.manifestFilename ?? 'manifest.webmanifest'}`
|
|
|
|
const devSw = `${nuxt.options.app.baseURL}dev-sw.js?dev-sw`
|
|
|
|
const workbox = `${nuxt.options.app.baseURL}workbox-`
|
|
|
|
// @ts-expect-error just ignore
|
|
|
|
const emptyHandle = (_req, _res, next) => {
|
|
|
|
next()
|
|
|
|
}
|
|
|
|
nuxt.hook('vite:serverCreated', (viteServer, { isServer }) => {
|
|
|
|
if (isServer)
|
|
|
|
return
|
|
|
|
|
|
|
|
viteServer.middlewares.stack.push({ route: webManifest, handle: emptyHandle })
|
2023-01-06 12:48:43 +00:00
|
|
|
if (webmanifests) {
|
2023-01-10 20:35:34 +00:00
|
|
|
Object.keys(webmanifests).forEach((wm) => {
|
2023-01-06 12:48:43 +00:00
|
|
|
viteServer.middlewares.stack.push({
|
2023-01-10 20:35:34 +00:00
|
|
|
route: `${nuxt.options.app.baseURL}manifest-${wm}.webmanifest`,
|
2023-01-06 12:48:43 +00:00
|
|
|
handle: emptyHandle,
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
2022-12-17 23:29:16 +00:00
|
|
|
viteServer.middlewares.stack.push({ route: devSw, handle: emptyHandle })
|
|
|
|
})
|
2023-01-06 12:48:43 +00:00
|
|
|
|
2022-12-17 23:29:16 +00:00
|
|
|
if (!options.strategies || options.strategies === 'generateSW') {
|
|
|
|
nuxt.hook('vite:serverCreated', (viteServer, { isServer }) => {
|
|
|
|
if (isServer)
|
|
|
|
return
|
|
|
|
|
|
|
|
viteServer.middlewares.stack.push({ route: workbox, handle: emptyHandle })
|
|
|
|
})
|
|
|
|
nuxt.hook('close', async () => {
|
|
|
|
// todo: cleanup dev-dist folder
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
2023-01-06 12:48:43 +00:00
|
|
|
nuxt.hook('nitro:config', async (nitroConfig) => {
|
|
|
|
nitroConfig.routeRules = nitroConfig.routeRules || {}
|
2023-02-12 11:08:50 +00:00
|
|
|
nitroConfig.routeRules!['/sw.js'] = {
|
|
|
|
headers: {
|
|
|
|
'Cache-Control': 'public, max-age=0, must-revalidate',
|
|
|
|
},
|
|
|
|
}
|
2023-01-06 12:48:43 +00:00
|
|
|
for (const locale of pwaLocales) {
|
|
|
|
nitroConfig.routeRules![`/manifest-${locale.code}.webmanifest`] = {
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/manifest+json',
|
2023-02-12 11:08:50 +00:00
|
|
|
'Cache-Control': 'public, max-age=0, must-revalidate',
|
2023-01-06 12:48:43 +00:00
|
|
|
},
|
|
|
|
}
|
2023-01-10 20:35:34 +00:00
|
|
|
nitroConfig.routeRules![`/manifest-${locale.code}-dark.webmanifest`] = {
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/manifest+json',
|
2023-02-12 11:08:50 +00:00
|
|
|
'Cache-Control': 'public, max-age=0, must-revalidate',
|
2023-01-10 20:35:34 +00:00
|
|
|
},
|
|
|
|
}
|
2023-01-06 12:48:43 +00:00
|
|
|
}
|
|
|
|
})
|
2023-12-01 17:28:31 +00:00
|
|
|
nuxt.hook('nitro:build:public-assets', async () => {
|
|
|
|
await resolveVitePluginPWAAPI()?.generateSW()
|
2022-12-17 23:29:16 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
},
|
|
|
|
})
|