Files
EchoionWeb/frontend/public/sw.js
T
faumaray e80dbc2fda Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-15 19:50:44 +03:00

83 lines
2.3 KiB
JavaScript

// Minimal, dependency-free service worker: makes the panel installable and
// keeps the app shell available offline. It deliberately does NOT touch the
// live surfaces — /rpc (WebSockets aren't interceptable anyway),
// /config.json, /api/* and /avatar/* all fall through to the network so the
// UI never shows stale identity/config.
// Bump when the player shell changes materially so installed/PWA clients do
// not retain an index that references a removed hashed bundle.
const CACHE = 'echoion-shell-v4';
const SHELL = ['/', '/manifest.webmanifest', '/icon.svg', '/icon-maskable.svg'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
)
.then(() => self.clients.claim())
);
});
// Only same-origin GETs are cacheable; everything else passes through.
function isStaticAsset(url) {
return (
url.pathname.startsWith('/assets/') ||
url.pathname === '/manifest.webmanifest' ||
url.pathname.startsWith('/icon') ||
url.pathname.startsWith('/fonts') ||
url.pathname.endsWith('.css') ||
url.pathname.endsWith('.woff2') ||
url.pathname.endsWith('.svg')
);
}
self.addEventListener('fetch', (event) => {
const req = event.request;
if (req.method !== 'GET') return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
// Never intercept the live control/config/media surfaces.
if (
url.pathname === '/config.json' ||
url.pathname.startsWith('/api/') ||
url.pathname.startsWith('/rpc') ||
url.pathname.startsWith('/avatar')
) {
return;
}
// SPA navigations: network-first, fall back to the cached shell offline.
if (req.mode === 'navigate') {
event.respondWith(
fetch(req).catch(() => caches.match('/').then((r) => r || fetch(req)))
);
return;
}
// Hashed static assets: cache-first, populate on first hit.
if (isStaticAsset(url)) {
event.respondWith(
caches.match(req).then(
(hit) =>
hit ||
fetch(req).then((resp) => {
if (resp.ok) {
const copy = resp.clone();
caches.open(CACHE).then((c) => c.put(req, copy));
}
return resp;
})
)
);
}
});