Skip to content

Commit

Permalink
make it worse
Browse files Browse the repository at this point in the history
  • Loading branch information
KaelWD committed Oct 14, 2024
1 parent 983bb66 commit b9a70b3
Show file tree
Hide file tree
Showing 8 changed files with 45 additions and 100 deletions.
8 changes: 8 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
services:
docs:
image: nginx:alpine
ports:
- ${PORT:-8095}:80
volumes:
- ./packages/docs/dist:/usr/share/nginx/html
- ./packages/docs/build/nginx.conf:/etc/nginx/nginx.conf
4 changes: 0 additions & 4 deletions packages/docs/auto-imports.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,6 @@ declare module 'vue' {
readonly copyElementContent: UnwrapRef<typeof import('./src/utils/helpers')['copyElementContent']>
readonly createAdProps: UnwrapRef<typeof import('./src/composables/ad')['createAdProps']>
readonly createApp: UnwrapRef<typeof import('vue')['createApp']>
readonly createCacheKey: UnwrapRef<typeof import('./src/utils/pwa')['createCacheKey']>
readonly createOne: UnwrapRef<typeof import('@vuetify/one')['createOne']>
readonly createPinia: UnwrapRef<typeof import('pinia')['createPinia']>
readonly customRef: UnwrapRef<typeof import('vue')['customRef']>
Expand All @@ -196,7 +195,6 @@ declare module 'vue' {
readonly generatedRoutes: UnwrapRef<typeof import('./src/utils/routes')['generatedRoutes']>
readonly getActivePinia: UnwrapRef<typeof import('pinia')['getActivePinia']>
readonly getBranch: UnwrapRef<typeof import('./src/utils/helpers')['getBranch']>
readonly getCacheKeyForUrl: UnwrapRef<typeof import('./src/utils/pwa')['getCacheKeyForUrl']>
readonly getCurrentInstance: UnwrapRef<typeof import('vue')['getCurrentInstance']>
readonly getCurrentScope: UnwrapRef<typeof import('vue')['getCurrentScope']>
readonly getDistance: UnwrapRef<typeof import('./src/utils/helpers')['getDistance']>
Expand Down Expand Up @@ -328,7 +326,6 @@ declare module '@vue/runtime-core' {
readonly copyElementContent: UnwrapRef<typeof import('./src/utils/helpers')['copyElementContent']>
readonly createAdProps: UnwrapRef<typeof import('./src/composables/ad')['createAdProps']>
readonly createApp: UnwrapRef<typeof import('vue')['createApp']>
readonly createCacheKey: UnwrapRef<typeof import('./src/utils/pwa')['createCacheKey']>
readonly createOne: UnwrapRef<typeof import('@vuetify/one')['createOne']>
readonly createPinia: UnwrapRef<typeof import('pinia')['createPinia']>
readonly customRef: UnwrapRef<typeof import('vue')['customRef']>
Expand All @@ -344,7 +341,6 @@ declare module '@vue/runtime-core' {
readonly generatedRoutes: UnwrapRef<typeof import('./src/utils/routes')['generatedRoutes']>
readonly getActivePinia: UnwrapRef<typeof import('pinia')['getActivePinia']>
readonly getBranch: UnwrapRef<typeof import('./src/utils/helpers')['getBranch']>
readonly getCacheKeyForUrl: UnwrapRef<typeof import('./src/utils/pwa')['getCacheKeyForUrl']>
readonly getCurrentInstance: UnwrapRef<typeof import('vue')['getCurrentInstance']>
readonly getCurrentScope: UnwrapRef<typeof import('vue')['getCurrentScope']>
readonly getDistance: UnwrapRef<typeof import('./src/utils/helpers')['getDistance']>
Expand Down
2 changes: 1 addition & 1 deletion packages/docs/src/components/app/settings/Drawer.vue
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
g<template>
<template>
<v-navigation-drawer
id="settings-drawer"
v-model="app.settings"
Expand Down
2 changes: 1 addition & 1 deletion packages/docs/src/plugins/pwa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export async function installPwa (router: Router) {

router.beforeEach(async (to, from) => {
if (to.path !== from.path) {
if (store.pendingUpdate) {
if (store.pendingUpdate && !store.isUpdating) {
console.log('Reloading page to update service worker')
window.location.pathname = to.fullPath
}
Expand Down
69 changes: 19 additions & 50 deletions packages/docs/src/service-worker.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
ensureCacheableResponse,
getCacheKeyForUrl,
openCache,
} from '@/utils/pwa'
import { ensureCacheableResponse, openCache } from '@/utils/pwa'

const MANIFEST = self.__WB_MANIFEST

Expand All @@ -25,38 +21,31 @@ self.addEventListener('install', () => {
self.skipWaiting()
})

let hasModernCache = false
self.addEventListener('activate', event => {
console.log('[SW] Activated')
event.waitUntil((async () => {
hasModernCache = await caches.has(`precache-${location.origin}`)
if (hasModernCache) {
await removeWorkboxCaches()
await self.clients.claim()
}
await removeWorkboxCaches()
await self.clients.claim()
})())
})

self.addEventListener('fetch', event => {
const url = new URL(event.request.url, location.href)
console.log(event.request.url)
const url = new URL(event.request.url)

if (!['http:', 'https:'].includes(url.protocol)) return

if (event.request.method !== 'GET') return

if (
event.request.mode === 'navigate' &&
event.request.destination === 'document' &&
url.origin === self.location.origin
) {
return event.respondWith(getFallbackDocument())
}

if (['https://tag.researchnow.com', 'https://srv.carbonads.net', 'https://pixel.adsafeprotected.com', 'https://cdn4.buysellads.net', 'https://ad.doubleclick.net'].includes(url.origin)) {
return
}

if (getCacheKeyForUrl(url.href)) {
if (url.origin === self.location.origin) {
if (event.request.mode === 'navigate' &&
event.request.destination === 'document') {
return event.respondWith(matchPrecache('/_fallback.html'))
}
return event.respondWith(matchPrecache(event.request))
}

Expand All @@ -67,20 +56,17 @@ self.addEventListener('fetch', event => {

async function matchPrecache (request) {
const precache = await openCache('precache')
const matched = await precache.match(getCacheKeyForUrl(request.url))
const matched = await precache.match(request)
if (matched) return matched
const response = fetch(request)
const cacheKey = getCacheKeyForUrl(request.url)
if (cacheKey) {
response.then(response => {
response = ensureCacheableResponse(response)
if (response.status === 200) {
precache.put(cacheKey, response.clone())
} else {
console.error(`[SW] Failed to fetch missing precached asset ${request.url}`)
}
})
}
response.then(response => {
response = ensureCacheableResponse(response)
if (response.status === 200) {
precache.put(response.url, response.clone())
} else {
console.error(`[SW] Failed to fetch missing precached asset ${request.url}`)
}
})
return response
}

Expand Down Expand Up @@ -113,23 +99,6 @@ async function networkFirst (request) {
}
}

async function getFallbackDocument () {
const precache = await openCache('precache')

const response = await fetch('/_fallback.html')
.then(ensureCacheableResponse)
.catch(() => {
console.warn('[SW] Failed to fetch fallback document')
})

if (response?.status === 200) {
await precache.put('/_fallback.html', response.clone())
return response
}

return precache.match('/_fallback.html')
}

function removeWorkboxCaches () {
return caches.keys().then(keys => {
keys = keys.filter(key => key.startsWith('workbox-') || key.endsWith(self.registration.scope))
Expand Down
9 changes: 8 additions & 1 deletion packages/docs/src/stores/pwa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,20 @@ export const usePwaStore = defineStore('pwa', () => {
const prev = registration.active
prevManifest.value = prev && await messageSW(prev, { type: 'GET_MANIFEST' })
console.log({ prevManifest: prevManifest.value })
if (localStorage.getItem('vuetify:cacheReady') !== 'true') {
await updateCache()
}
}

async function removeWorker () {
const registration = await navigator.serviceWorker.getRegistration()
registration?.unregister()
if (await registration?.unregister()) {
window.location.reload()
}
}

async function updateCache () {
localStorage.setItem('vuetify:cacheReady', 'false')
isUpdating.value = true
const next = nextManifest.value ?? prevManifest.value
const prev = nextManifest.value ? prevManifest.value : undefined
Expand All @@ -57,6 +63,7 @@ export const usePwaStore = defineStore('pwa', () => {
progressTotal.value = total
})
isUpdating.value = false
localStorage.setItem('vuetify:cacheReady', 'true')
}

return {
Expand Down
49 changes: 7 additions & 42 deletions packages/docs/src/utils/pwa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,6 @@ import eachLimit from 'async-es/eachLimit'
type ManifestEntry = { url: string, revision?: string }
type Manifest = ManifestEntry[]

const urlsToCacheKeys = new Map<string, string>()
export function getCacheKeyForUrl (url: string) {
url = createCacheKey(url).url

return urlsToCacheKeys.get(url)
}

export async function openCache (name: string) {
return caches.open(`${name}-${location.origin}`)
}
Expand All @@ -19,23 +12,21 @@ export async function cacheManifestEntries (
previousManifest: Manifest,
progress?: (value: number, total: number) => void
) {
for (const entry of manifest) {
const cacheKey = createCacheKey(entry)
urlsToCacheKeys.set(cacheKey.url, cacheKey.cacheKey)
}
const cache = await openCache('precache')
let count = 0
const total = urlsToCacheKeys.size
await eachLimit(urlsToCacheKeys, 4, async ([url, cacheKey]: [string, string]) => {
const total = manifest.length
await eachLimit(manifest, 8, async ({ url, revision }: ManifestEntry) => {
let response
try {
response = ensureCacheableResponse(await fetch(url))
response = ensureCacheableResponse(await fetch(url, {
cache: revision ? 'no-cache' : 'default',
}))
} catch (err: any) {
console.warn(`[SW] Failed to cache ${url}`, err.message)
return
}
if (response.status === 200) {
await cache.put(cacheKey, response)
await cache.put(url, response)
} else {
console.warn(`[SW] Failed to cache ${url}`, response.status, response.statusText)
}
Expand All @@ -44,15 +35,6 @@ export async function cacheManifestEntries (
console.log('[SW] Precached', total, 'files')
if (previousManifest) {
await cleanCache(previousManifest)
let count = 0
for (const entry of previousManifest) {
const cacheKey = createCacheKey(entry)
if (!urlsToCacheKeys.has(cacheKey.url)) {
count++
urlsToCacheKeys.set(cacheKey.url, cacheKey.cacheKey)
}
}
console.log('[SW] Reused', count, 'of', previousManifest.length, 'files')
}
}

Expand All @@ -62,7 +44,7 @@ async function cleanCache (previousManifest: Manifest) {
const precache = await openCache('precache')

const responses = await Promise.all(
previousManifest.map(entry => precache.match(createCacheKey(entry).cacheKey))
previousManifest.map(entry => precache.match(entry.url))
)

// Date of earliest entry in the old manifest
Expand Down Expand Up @@ -105,20 +87,3 @@ export function ensureCacheableResponse (response: Response) {
statusText: cloned.statusText,
})
}

export function createCacheKey (entry: string | ManifestEntry) {
const { revision = null, url } = typeof entry === 'string'
? { url: entry }
: entry

const cacheKeyUrl = new URL(url, location.origin)

if (revision) {
cacheKeyUrl.searchParams.set('__WB_REVISION__', revision)
}

return {
cacheKey: cacheKeyUrl.href,
url: new URL(url, location.origin).href,
}
}
2 changes: 1 addition & 1 deletion packages/docs/vite.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ export default defineConfig(({ command, mode, isSsrBuild }) => {
additionalManifestEntries: [
{ url: '/_fallback.html', revision: Date.now().toString(16) },
],
dontCacheBustURLsMatching: /^\/assets\//,
dontCacheBustURLsMatching: /^\/?assets\//,
maximumFileSizeToCacheInBytes: 24 * 1024 ** 2,
},
manifest: {
Expand Down

0 comments on commit b9a70b3

Please sign in to comment.