Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
fix(pwa): rename the static cache when a script or stylesheet changes
Miguel Ribeiro1d37f898d458
diff --git a/service-worker.php b/service-worker.phpindex 898c7bd..8ae45fc 100644--- a/service-worker.php+++ b/service-worker.php@@ -1,359 +1,368 @@-<?php-require_once __DIR__ . '/includes/version.php';-if (!headers_sent()) {- header('Content-Type: text/javascript; charset=utf-8');- header('Cache-Control: no-cache');-}-?>-// STATIC_CACHE is tied to the app version (rather than a hand-bumped literal)-// so every release invalidates stale precached assets automatically - a release-// that changed JS/CSS without remembering to bump a hardcoded cache version-// used to leave already-visited browsers stuck on old cached files indefinitely.-const STATIC_CACHE = 'static-cache-<?= $version ?>';-const PAGES_CACHE = 'pages-cache-v1';-const LOGOS_CACHE = 'logos-cache-v2';--// manifest.php is intentionally not precached here: it's per-user (theme-// cookie dependent), so it falls through to the network-first handler below-// instead of being served stale from a cache-first bucket forever.-const staticAssets = [- 'styles/styles.css',- 'styles/theme.css',- 'styles/dark-theme.css',- 'styles/login.css',- 'styles/login-dark-theme.css',- 'styles/font-awesome.min.css',- 'styles/brands.css',- 'styles/barlow.css',- 'styles/themes/red.css',- 'styles/themes/green.css',- 'styles/themes/yellow.css',- 'styles/themes/purple.css',- 'webfonts/fa-solid-900.woff2',- 'webfonts/fa-solid-900.ttf',- 'webfonts/fa-brands-400.woff2',- 'webfonts/fa-brands-400.ttf',- 'webfonts/fa-regular-400.woff2',- 'webfonts/fa-regular-400.ttf',- 'scripts/all.js',- 'scripts/common.js',- 'scripts/dashboard.js',- 'scripts/subscriptions.js',- 'scripts/subscription-details.js',- 'scripts/password-toggle.js',- 'scripts/stats.js',- 'scripts/settings.js',- 'scripts/profile.js',- 'scripts/theme.js',- 'scripts/auth-theme.js',- 'scripts/notifications.js',- 'scripts/registration.js',- 'scripts/login.js',- 'scripts/admin.js',- 'scripts/calendar.js',- 'scripts/i18n/ar.js',- 'scripts/i18n/az.js',- 'scripts/i18n/ca.js',- 'scripts/i18n/cs.js',- 'scripts/i18n/da.js',- 'scripts/i18n/de.js',- 'scripts/i18n/el.js',- 'scripts/i18n/en.js',- 'scripts/i18n/es.js',- 'scripts/i18n/fr.js',- 'scripts/i18n/hu.js',- 'scripts/i18n/id.js',- 'scripts/i18n/it.js',- 'scripts/i18n/ja.js',- 'scripts/i18n/ko.js',- 'scripts/i18n/nl.js',- 'scripts/i18n/pl.js',- 'scripts/i18n/pt.js',- 'scripts/i18n/pt_br.js',- 'scripts/i18n/ro.js',- 'scripts/i18n/ru.js',- 'scripts/i18n/sl.js',- 'scripts/i18n/sr_lat.js',- 'scripts/i18n/sr.js',- 'scripts/i18n/tr.js',- 'scripts/i18n/uk.js',- 'scripts/i18n/vi.js',- 'scripts/i18n/zh_cn.js',- 'scripts/i18n/zh_tw.js',- 'scripts/i18n/getlang.js',- 'scripts/libs/apexcharts.min.js',- 'scripts/libs/sortable.min.js',- 'scripts/libs/qrcode.min.js',- 'images/icon/favicon.ico',- 'images/icon/favicon-16x16.png',- 'images/icon/favicon-32x32.png',- 'images/icon/android-chrome-192x192.png',- 'images/icon/android-chrome-512x512.png',- 'images/icon/maskable_icon_x192.png',- 'images/icon/maskable_icon_x512.png',- 'images/icon/apple-touch-icon-180.png',- 'images/icon/apple-touch-icon-152.png',- 'images/icon/apple-touch-icon.png',- 'images/screenshots/desktop.png',- 'images/siteicons/wallos.png',- 'images/siteicons/walloswhite.png',- 'images/siteimages/empty.png',- 'images/siteimages/mobilenav.png',- 'images/siteimages/mobilenavdark.png',- 'images/avatars/1.svg',- 'images/avatars/2.svg',- 'images/avatars/3.svg',- 'images/avatars/4.svg',- 'images/avatars/5.svg',- 'images/avatars/6.svg',- 'images/avatars/7.svg',- 'images/avatars/8.svg',- 'images/avatars/9.svg',- 'images/siteicons/svg/logo.php',- 'images/siteicons/svg/automatic.php',- 'images/siteicons/svg/manual.php',- 'images/siteicons/svg/export_ical.php',- 'images/siteicons/svg/check.php',- 'images/siteicons/svg/mobile-menu/calendar.php',- 'images/siteicons/svg/mobile-menu/home.php',- 'images/siteicons/svg/mobile-menu/profile.php',- 'images/siteicons/svg/mobile-menu/settings.php',- 'images/siteicons/svg/mobile-menu/statistics.php',- 'images/siteicons/svg/mobile-menu/subscriptions.php',- 'images/siteicons/svg/mobile-menu/about.php',- 'images/siteicons/svg/mobile-menu/admin.php',- 'images/siteicons/svg/mobile-menu/logout.php',- 'images/siteicons/svg/mobile-menu/clone.php',- 'images/siteicons/svg/mobile-menu/delete.php',- 'images/siteicons/svg/mobile-menu/edit.php',- 'images/siteicons/svg/mobile-menu/renew.php',- 'images/siteicons/pwa/stats.png',- 'images/siteicons/pwa/settings.png',- 'images/siteicons/pwa/about.png',- 'images/siteicons/pwa/calendar.png',- 'images/siteicons/pwa/subscriptions.png',- 'images/siteicons/pwa/dashboard.png',- 'images/uploads/icons/paypal.png',- 'images/uploads/icons/creditcard.png',- 'images/uploads/icons/banktransfer.png',- 'images/uploads/icons/directdebit.png',- 'images/uploads/icons/money.png',- 'images/uploads/icons/googlepay.png',- 'images/uploads/icons/samsungpay.png',- 'images/uploads/icons/applepay.png',- 'images/uploads/icons/crypto.png',- 'images/uploads/icons/klarna.png',- 'images/uploads/icons/amazonpay.png',- 'images/uploads/icons/sepa.png',- 'images/uploads/icons/skrill.png',- 'images/uploads/icons/sofort.png',- 'images/uploads/icons/stripe.png',- 'images/uploads/icons/affirm.png',- 'images/uploads/icons/alipay.png',- 'images/uploads/icons/elo.png',- 'images/uploads/icons/facebookpay.png',- 'images/uploads/icons/giropay.png',- 'images/uploads/icons/ideal.png',- 'images/uploads/icons/unionpay.png',- 'images/uploads/icons/interac.png',- 'images/uploads/icons/wechat.png',- 'images/uploads/icons/paysafe.png',- 'images/uploads/icons/poli.png',- 'images/uploads/icons/qiwi.png',- 'images/uploads/icons/shoppay.png',- 'images/uploads/icons/venmo.png',- 'images/uploads/icons/verifone.png',- 'images/uploads/icons/webmoney.png',-];--const pagesToPrefetch = [- 'index.php',- 'subscriptions.php',- 'profile.php',- 'calendar.php',- 'settings.php',- 'stats.php',- 'about.php',- 'login.php',- 'admin.php',-];--// Install: cache static assets in small batches. Firing all ~150 fetches at-// once starves large files (apexcharts is 600KB) of connections on HTTP/1.1-// origins, and a dropped one is silently skipped - see the static-asset-// fetch handler, which backfills anything that slips through here.-self.addEventListener('install', function (event) {- event.waitUntil(- caches.open(STATIC_CACHE).then(async function (cache) {- const BATCH_SIZE = 12;- for (let i = 0; i < staticAssets.length; i += BATCH_SIZE) {- await Promise.allSettled(- staticAssets.slice(i, i + BATCH_SIZE).map(url =>- fetch(url, { cache: 'reload' }).then(response => {- if (response.ok) return cache.put(url, response);- }).catch(() => {}) // silently skip missing files- )- );- }- })- );- self.skipWaiting();-});--// Activate: clean up old caches-self.addEventListener('activate', function (event) {- const validCaches = [STATIC_CACHE, PAGES_CACHE, LOGOS_CACHE];- event.waitUntil(- caches.keys().then(keys =>- Promise.all(- keys.filter(key => !validCaches.includes(key))- .map(key => caches.delete(key))- )- )- );- self.clients.claim();-});--// Message: prefetch pages after login-self.addEventListener('message', function (event) {- if (event.data && event.data.type === 'PREFETCH_PAGES') {- caches.open(PAGES_CACHE).then(cache => {- pagesToPrefetch.forEach(url => {- fetch(url).then(response => {- // Only cache if user is actually logged in (no redirect)- if (response.ok && !response.redirected) {- cache.put(url, response);- }- }).catch(() => {});- });- });- }-});--// Fetch: single handler for all requests-self.addEventListener('fetch', function (event) {- const request = event.request;- const url = new URL(request.url);-- // Never intercept non-GET requests (POST, etc.)- if (request.method !== 'GET') return;-- // Search endpoints must always return their current JSON response. Falling- // back to a cached PHP page (especially with ignoreSearch) makes the client- // try to parse HTML or another query's data as JSON.- if (url.pathname.includes('/endpoints/logos/')) {- event.respondWith(fetch(request));- return;- }-- // Logo images: use cache-first, but cache only successful image responses.- // This prevents temporary 404/HTML responses from becoming permanent- // broken images. Bumping LOGOS_CACHE removes previously poisoned entries.- if (url.pathname.includes('images/uploads/logos')) {- event.respondWith(- caches.match(request).then(response => {- return response || fetch(request).then(networkResponse => {- const contentType = networkResponse.headers.get('content-type') || '';- if (networkResponse.ok && contentType.startsWith('image/')) {- return caches.open(LOGOS_CACHE).then(cache => {- cache.put(request, networkResponse.clone());- return networkResponse;- });- }- return networkResponse;- });- })- );- return;- }-- // Static assets: cache-first (they only change on deploy). ignoreSearch- // because the pages request these with a "?<version>" cache-buster, while- // they're precached under the bare path - without it every asset misses- // the cache and the page renders unstyled offline.- //- // On a miss, fetch AND store the result: the install step fires ~150- // parallel fetches and any that fail (a large file like apexcharts, a- // dropped connection) are silently skipped, so without this backfill a- // once-missed asset would never get cached and its feature (e.g. the- // stats charts) would stay broken offline forever.- if (staticAssets.some(asset => url.pathname.endsWith(asset))) {- event.respondWith(- caches.match(request, { ignoreSearch: true }).then(cached => {- if (cached) return cached;- return fetch(request).then(networkResponse => {- if (networkResponse.ok) {- const clone = networkResponse.clone();- caches.open(STATIC_CACHE).then(cache => cache.put(request, clone));- }- return networkResponse;- });- })- );- return;- }-- // PHP pages and everything else: network-first, cache as fallback- // Also update the pages cache on every successful load- event.respondWith(- fetch(request).then(response => {- if (response.ok && !response.redirected) {- const responseClone = response.clone(); // clone before any async operation- caches.open(PAGES_CACHE).then(cache => {- cache.put(request, responseClone);- });- }- return response;- }).catch(() => {- return caches.match(request, { ignoreSearch: true });- })- );-});--// Web Push (RFC 8291/8292): the payload includes/webpush_helper.php sends is-// {"title": ..., "body": ...} JSON, decrypted by the browser itself before-// this handler ever sees it - nothing here has to know that aes128gcm-// happened at all.-self.addEventListener('push', function (event) {- let data = {};-- if (event.data) {- try {- data = event.data.json();- } catch (e) {- data = { title: 'Wallos', body: event.data.text() };- }- }-- const title = data.title || 'Wallos';- const options = {- body: data.body || '',- icon: 'images/icon/android-chrome-192x192.png',- badge: 'images/icon/android-chrome-192x192.png',- data: { url: data.url || './' },- };-- event.waitUntil(self.registration.showNotification(title, options));-});--self.addEventListener('notificationclick', function (event) {- event.notification.close();-- const targetUrl = (event.notification.data && event.notification.data.url) || './';-- event.waitUntil(- clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (windowClients) {- // Focus a tab that already has the app open, rather than piling- // up a new one every time a notification is tapped.- for (const client of windowClients) {- if (client.url.includes(self.registration.scope) && 'focus' in client) {- return client.focus();- }- }-- if (clients.openWindow) {- return clients.openWindow(targetUrl);- }- })- );-});+<?php+require_once __DIR__ . '/includes/version.php';+$assetsStamp = 0;+foreach (array_merge(glob(__DIR__ . '/scripts/*.js') ?: [], glob(__DIR__ . '/scripts/i18n/*.js') ?: [], glob(__DIR__ . '/styles/*.css') ?: [], glob(__DIR__ . '/styles/themes/*.css') ?: []) as $assetFile) {+ $assetsStamp = max($assetsStamp, (int) filemtime($assetFile));+}+if (!headers_sent()) {+ header('Content-Type: text/javascript; charset=utf-8');+ header('Cache-Control: no-cache');+}+?>+// STATIC_CACHE is tied to the app version (rather than a hand-bumped literal)+// so every release invalidates stale precached assets automatically - a release+// that changed JS/CSS without remembering to bump a hardcoded cache version+// used to leave already-visited browsers stuck on old cached files indefinitely.+//+// The version alone only changes at a release, so the newest modification time+// of the precached scripts and styles is part of the name as well: a changed+// file changes this worker, the browser installs it and drops the old cache,+// instead of serving the previous copy until the version is bumped.+const STATIC_CACHE = 'static-cache-<?= $version ?>-<?= $assetsStamp ?>';+const PAGES_CACHE = 'pages-cache-v1';+const LOGOS_CACHE = 'logos-cache-v2';++// manifest.php is intentionally not precached here: it's per-user (theme+// cookie dependent), so it falls through to the network-first handler below+// instead of being served stale from a cache-first bucket forever.+const staticAssets = [+ 'styles/styles.css',+ 'styles/theme.css',+ 'styles/dark-theme.css',+ 'styles/login.css',+ 'styles/login-dark-theme.css',+ 'styles/font-awesome.min.css',+ 'styles/brands.css',+ 'styles/barlow.css',+ 'styles/themes/red.css',+ 'styles/themes/green.css',+ 'styles/themes/yellow.css',+ 'styles/themes/purple.css',+ 'webfonts/fa-solid-900.woff2',+ 'webfonts/fa-solid-900.ttf',+ 'webfonts/fa-brands-400.woff2',+ 'webfonts/fa-brands-400.ttf',+ 'webfonts/fa-regular-400.woff2',+ 'webfonts/fa-regular-400.ttf',+ 'scripts/all.js',+ 'scripts/common.js',+ 'scripts/dashboard.js',+ 'scripts/subscriptions.js',+ 'scripts/subscription-details.js',+ 'scripts/password-toggle.js',+ 'scripts/stats.js',+ 'scripts/settings.js',+ 'scripts/profile.js',+ 'scripts/theme.js',+ 'scripts/auth-theme.js',+ 'scripts/notifications.js',+ 'scripts/registration.js',+ 'scripts/login.js',+ 'scripts/admin.js',+ 'scripts/calendar.js',+ 'scripts/i18n/ar.js',+ 'scripts/i18n/az.js',+ 'scripts/i18n/ca.js',+ 'scripts/i18n/cs.js',+ 'scripts/i18n/da.js',+ 'scripts/i18n/de.js',+ 'scripts/i18n/el.js',+ 'scripts/i18n/en.js',+ 'scripts/i18n/es.js',+ 'scripts/i18n/fr.js',+ 'scripts/i18n/hu.js',+ 'scripts/i18n/id.js',+ 'scripts/i18n/it.js',+ 'scripts/i18n/ja.js',+ 'scripts/i18n/ko.js',+ 'scripts/i18n/nl.js',+ 'scripts/i18n/pl.js',+ 'scripts/i18n/pt.js',+ 'scripts/i18n/pt_br.js',+ 'scripts/i18n/ro.js',+ 'scripts/i18n/ru.js',+ 'scripts/i18n/sl.js',+ 'scripts/i18n/sr_lat.js',+ 'scripts/i18n/sr.js',+ 'scripts/i18n/tr.js',+ 'scripts/i18n/uk.js',+ 'scripts/i18n/vi.js',+ 'scripts/i18n/zh_cn.js',+ 'scripts/i18n/zh_tw.js',+ 'scripts/i18n/getlang.js',+ 'scripts/libs/apexcharts.min.js',+ 'scripts/libs/sortable.min.js',+ 'scripts/libs/qrcode.min.js',+ 'images/icon/favicon.ico',+ 'images/icon/favicon-16x16.png',+ 'images/icon/favicon-32x32.png',+ 'images/icon/android-chrome-192x192.png',+ 'images/icon/android-chrome-512x512.png',+ 'images/icon/maskable_icon_x192.png',+ 'images/icon/maskable_icon_x512.png',+ 'images/icon/apple-touch-icon-180.png',+ 'images/icon/apple-touch-icon-152.png',+ 'images/icon/apple-touch-icon.png',+ 'images/screenshots/desktop.png',+ 'images/siteicons/wallos.png',+ 'images/siteicons/walloswhite.png',+ 'images/siteimages/empty.png',+ 'images/siteimages/mobilenav.png',+ 'images/siteimages/mobilenavdark.png',+ 'images/avatars/1.svg',+ 'images/avatars/2.svg',+ 'images/avatars/3.svg',+ 'images/avatars/4.svg',+ 'images/avatars/5.svg',+ 'images/avatars/6.svg',+ 'images/avatars/7.svg',+ 'images/avatars/8.svg',+ 'images/avatars/9.svg',+ 'images/siteicons/svg/logo.php',+ 'images/siteicons/svg/automatic.php',+ 'images/siteicons/svg/manual.php',+ 'images/siteicons/svg/export_ical.php',+ 'images/siteicons/svg/check.php',+ 'images/siteicons/svg/mobile-menu/calendar.php',+ 'images/siteicons/svg/mobile-menu/home.php',+ 'images/siteicons/svg/mobile-menu/profile.php',+ 'images/siteicons/svg/mobile-menu/settings.php',+ 'images/siteicons/svg/mobile-menu/statistics.php',+ 'images/siteicons/svg/mobile-menu/subscriptions.php',+ 'images/siteicons/svg/mobile-menu/about.php',+ 'images/siteicons/svg/mobile-menu/admin.php',+ 'images/siteicons/svg/mobile-menu/logout.php',+ 'images/siteicons/svg/mobile-menu/clone.php',+ 'images/siteicons/svg/mobile-menu/delete.php',+ 'images/siteicons/svg/mobile-menu/edit.php',+ 'images/siteicons/svg/mobile-menu/renew.php',+ 'images/siteicons/pwa/stats.png',+ 'images/siteicons/pwa/settings.png',+ 'images/siteicons/pwa/about.png',+ 'images/siteicons/pwa/calendar.png',+ 'images/siteicons/pwa/subscriptions.png',+ 'images/siteicons/pwa/dashboard.png',+ 'images/uploads/icons/paypal.png',+ 'images/uploads/icons/creditcard.png',+ 'images/uploads/icons/banktransfer.png',+ 'images/uploads/icons/directdebit.png',+ 'images/uploads/icons/money.png',+ 'images/uploads/icons/googlepay.png',+ 'images/uploads/icons/samsungpay.png',+ 'images/uploads/icons/applepay.png',+ 'images/uploads/icons/crypto.png',+ 'images/uploads/icons/klarna.png',+ 'images/uploads/icons/amazonpay.png',+ 'images/uploads/icons/sepa.png',+ 'images/uploads/icons/skrill.png',+ 'images/uploads/icons/sofort.png',+ 'images/uploads/icons/stripe.png',+ 'images/uploads/icons/affirm.png',+ 'images/uploads/icons/alipay.png',+ 'images/uploads/icons/elo.png',+ 'images/uploads/icons/facebookpay.png',+ 'images/uploads/icons/giropay.png',+ 'images/uploads/icons/ideal.png',+ 'images/uploads/icons/unionpay.png',+ 'images/uploads/icons/interac.png',+ 'images/uploads/icons/wechat.png',+ 'images/uploads/icons/paysafe.png',+ 'images/uploads/icons/poli.png',+ 'images/uploads/icons/qiwi.png',+ 'images/uploads/icons/shoppay.png',+ 'images/uploads/icons/venmo.png',+ 'images/uploads/icons/verifone.png',+ 'images/uploads/icons/webmoney.png',+];++const pagesToPrefetch = [+ 'index.php',+ 'subscriptions.php',+ 'profile.php',+ 'calendar.php',+ 'settings.php',+ 'stats.php',+ 'about.php',+ 'login.php',+ 'admin.php',+];++// Install: cache static assets in small batches. Firing all ~150 fetches at+// once starves large files (apexcharts is 600KB) of connections on HTTP/1.1+// origins, and a dropped one is silently skipped - see the static-asset+// fetch handler, which backfills anything that slips through here.+self.addEventListener('install', function (event) {+ event.waitUntil(+ caches.open(STATIC_CACHE).then(async function (cache) {+ const BATCH_SIZE = 12;+ for (let i = 0; i < staticAssets.length; i += BATCH_SIZE) {+ await Promise.allSettled(+ staticAssets.slice(i, i + BATCH_SIZE).map(url =>+ fetch(url, { cache: 'reload' }).then(response => {+ if (response.ok) return cache.put(url, response);+ }).catch(() => {}) // silently skip missing files+ )+ );+ }+ })+ );+ self.skipWaiting();+});++// Activate: clean up old caches+self.addEventListener('activate', function (event) {+ const validCaches = [STATIC_CACHE, PAGES_CACHE, LOGOS_CACHE];+ event.waitUntil(+ caches.keys().then(keys =>+ Promise.all(+ keys.filter(key => !validCaches.includes(key))+ .map(key => caches.delete(key))+ )+ )+ );+ self.clients.claim();+});++// Message: prefetch pages after login+self.addEventListener('message', function (event) {+ if (event.data && event.data.type === 'PREFETCH_PAGES') {+ caches.open(PAGES_CACHE).then(cache => {+ pagesToPrefetch.forEach(url => {+ fetch(url).then(response => {+ // Only cache if user is actually logged in (no redirect)+ if (response.ok && !response.redirected) {+ cache.put(url, response);+ }+ }).catch(() => {});+ });+ });+ }+});++// Fetch: single handler for all requests+self.addEventListener('fetch', function (event) {+ const request = event.request;+ const url = new URL(request.url);++ // Never intercept non-GET requests (POST, etc.)+ if (request.method !== 'GET') return;++ // Search endpoints must always return their current JSON response. Falling+ // back to a cached PHP page (especially with ignoreSearch) makes the client+ // try to parse HTML or another query's data as JSON.+ if (url.pathname.includes('/endpoints/logos/')) {+ event.respondWith(fetch(request));+ return;+ }++ // Logo images: use cache-first, but cache only successful image responses.+ // This prevents temporary 404/HTML responses from becoming permanent+ // broken images. Bumping LOGOS_CACHE removes previously poisoned entries.+ if (url.pathname.includes('images/uploads/logos')) {+ event.respondWith(+ caches.match(request).then(response => {+ return response || fetch(request).then(networkResponse => {+ const contentType = networkResponse.headers.get('content-type') || '';+ if (networkResponse.ok && contentType.startsWith('image/')) {+ return caches.open(LOGOS_CACHE).then(cache => {+ cache.put(request, networkResponse.clone());+ return networkResponse;+ });+ }+ return networkResponse;+ });+ })+ );+ return;+ }++ // Static assets: cache-first (they only change on deploy). ignoreSearch+ // because the pages request these with a "?<version>" cache-buster, while+ // they're precached under the bare path - without it every asset misses+ // the cache and the page renders unstyled offline.+ //+ // On a miss, fetch AND store the result: the install step fires ~150+ // parallel fetches and any that fail (a large file like apexcharts, a+ // dropped connection) are silently skipped, so without this backfill a+ // once-missed asset would never get cached and its feature (e.g. the+ // stats charts) would stay broken offline forever.+ if (staticAssets.some(asset => url.pathname.endsWith(asset))) {+ event.respondWith(+ caches.match(request, { ignoreSearch: true }).then(cached => {+ if (cached) return cached;+ return fetch(request).then(networkResponse => {+ if (networkResponse.ok) {+ const clone = networkResponse.clone();+ caches.open(STATIC_CACHE).then(cache => cache.put(request, clone));+ }+ return networkResponse;+ });+ })+ );+ return;+ }++ // PHP pages and everything else: network-first, cache as fallback+ // Also update the pages cache on every successful load+ event.respondWith(+ fetch(request).then(response => {+ if (response.ok && !response.redirected) {+ const responseClone = response.clone(); // clone before any async operation+ caches.open(PAGES_CACHE).then(cache => {+ cache.put(request, responseClone);+ });+ }+ return response;+ }).catch(() => {+ return caches.match(request, { ignoreSearch: true });+ })+ );+});++// Web Push (RFC 8291/8292): the payload includes/webpush_helper.php sends is+// {"title": ..., "body": ...} JSON, decrypted by the browser itself before+// this handler ever sees it - nothing here has to know that aes128gcm+// happened at all.+self.addEventListener('push', function (event) {+ let data = {};++ if (event.data) {+ try {+ data = event.data.json();+ } catch (e) {+ data = { title: 'Wallos', body: event.data.text() };+ }+ }++ const title = data.title || 'Wallos';+ const options = {+ body: data.body || '',+ icon: 'images/icon/android-chrome-192x192.png',+ badge: 'images/icon/android-chrome-192x192.png',+ data: { url: data.url || './' },+ };++ event.waitUntil(self.registration.showNotification(title, options));+});++self.addEventListener('notificationclick', function (event) {+ event.notification.close();++ const targetUrl = (event.notification.data && event.notification.data.url) || './';++ event.waitUntil(+ clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (windowClients) {+ // Focus a tab that already has the app open, rather than piling+ // up a new one every time a notification is tapped.+ for (const client of windowClients) {+ if (client.url.includes(self.registration.scope) && 'focus' in client) {+ return client.focus();+ }+ }++ if (clients.openWindow) {+ return clients.openWindow(targetUrl);+ }+ })+ );+});diff --git a/tests/cases/pwa_manifest_test.php b/tests/cases/pwa_manifest_test.phpindex fcc775b..164e2c3 100644--- a/tests/cases/pwa_manifest_test.php+++ b/tests/cases/pwa_manifest_test.php@@ -136,8 +136,10 @@ wallos_test('the legacy service-worker.js stub hands existing registrations overwallos_test('the service worker cache name is tied to the app version', function () {$source = file_get_contents(WALLOS_ROOT . '/service-worker.php');- assert_contains("'static-cache-<?= \$version ?>'", $source,+ assert_contains("'static-cache-<?= \$version ?>-<?= \$assetsStamp ?>'", $source,'every release gets a fresh static cache, and activate deletes the old one');+ assert_contains('filemtime(', $source,+ 'a changed script or stylesheet changes the cache name too, not only a version bump');assert_contains("cache: 'reload'", $source,'precaching bypasses the HTTP cache so stale files are not stored under the new cache name');});