Skip to content

armgit / dashy

Public Imported from GitHub
0

πŸš€ A self-hostable personal dashboard built for you. Includes status-checking, widgets, themes, icon packs, a UI editor and tons more!

βž– Removes register-service-worker dep, does manually

Alicia Sykes0ac634ed03e1
diff --git a/package.json b/package.json
index cfe30dc8..ff154d2a 100644
--- a/package.json
+++ b/package.json
@@ -45,7 +45,6 @@
"js-yaml": "^4.1.0",
"keycloak-js": "^20.0.3",
"oidc-client-ts": "^3.0.1",
- "register-service-worker": "^1.7.2",
"rsup-progress": "^3.2.0",
"simple-icons": "^16.6.0",
"vue": "^3.5.0",
diff --git a/src/assets/locales/en.json b/src/assets/locales/en.json
index 389fce89..ef6b2a88 100644
--- a/src/assets/locales/en.json
+++ b/src/assets/locales/en.json
@@ -146,7 +146,9 @@
"up-to-date": "Up-to-Date",
"out-of-date": "Update Available",
"unsupported-version-l1": "You are using an unsupported version of Dashy",
- "unsupported-version-l2": "For the best experience, and recent security patches, please update to"
+ "unsupported-version-l2": "For the best experience, and recent security patches, please update to",
+ "sw-update-available": "A new version of Dashy is available.",
+ "sw-update-action": "Refresh"
},
"language-switcher": {
"title": "Change Application Language",
diff --git a/src/utils/InitServiceWorker.js b/src/utils/InitServiceWorker.js
index 72c31e3c..9302d3d4 100644
--- a/src/utils/InitServiceWorker.js
+++ b/src/utils/InitServiceWorker.js
@@ -1,100 +1,70 @@
import yaml from 'js-yaml';
-import { register } from 'register-service-worker';
import request from '@/utils/request';
-import { sessionStorageKeys } from '@/utils/config/defaults';
+import i18n from '@/utils/i18n';
import { statusMsg, statusErrorMsg } from '@/utils/logging/CoolConsole';
+import { toast } from '@/utils/Toast';
-/* Sets a local storage item with the state from the SW lifecycle */
-const setSwStatus = (swStateToSet) => {
- const initialSwState = {
- ready: false,
- registered: false,
- cached: false,
- updateFound: false,
- updated: false,
- offline: false,
- error: false,
- devMode: false,
- disabledByUser: false,
- };
- const sessionData = sessionStorage[sessionStorageKeys.SW_STATUS];
- const currentSwState = sessionData ? JSON.parse(sessionData) : initialSwState;
+const SW_LABEL = 'Service Worker Status';
+const UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000; // hourly
+
+/* Loads conf.yml and returns the parsed object, or null on failure */
+const loadAppConfig = async () => {
try {
- const newSwState = { ...currentSwState, ...swStateToSet };
- sessionStorage.setItem(sessionStorageKeys.SW_STATUS, JSON.stringify(newSwState));
+ const { data } = await request.get('/conf.yml');
+ return yaml.load(data) || null;
} catch (e) {
- statusErrorMsg('Service Worker Status', 'Error Updating SW Status', e);
+ statusErrorMsg(SW_LABEL, 'Failed to load config for SW check', e);
+ return null;
}
};
-/**
- * Checks if service workers should be enabled
- * Disable if not running in production
- * Or disable if user specified to disable
- */
-const shouldEnableServiceWorker = async () => {
+/* Best-effort cleanup of any prior service worker (used when user opts out) */
+const unregisterAll = async () => {
try {
- const response = await request.get('/conf.yml');
- const conf = yaml.load(response.data);
- if (conf && conf.appConfig && conf.appConfig.enableServiceWorker) {
- setSwStatus({ disabledByUser: false });
- return true;
- }
- } catch (e) {
- statusErrorMsg('Service Worker Status', 'Failed to load config for SW check', e);
- }
- if (import.meta.env.DEV) {
- setSwStatus({ devMode: true });
- return false;
- }
- setSwStatus({ disabledByUser: true });
- return false;
+ const regs = await navigator.serviceWorker.getRegistrations();
+ if (!regs.length) return;
+ await Promise.all(regs.map(r => r.unregister().catch(() => {})));
+ statusMsg(SW_LABEL, 'Service worker unregistered (opt-out).');
+ } catch (e) { /* no-op */ }
};
-/* Calls to the print status function */
-const printSwStatus = (msg) => {
- statusMsg('Service Worker Status', msg);
+/* Sticky toast with a Refresh action that swaps in the new SW and reloads */
+const promptForUpdate = (updateSW) => {
+ const t = i18n.global.t;
+ toast(t('updates.sw-update-available'), {
+ type: 'info',
+ duration: 0,
+ dismissible: true,
+ action: { text: t('updates.sw-update-action'), onClick: () => updateSW(true) },
+ });
};
-const swUrl = `${import.meta.env.BASE_URL || '/'}service-worker.js`;
+const initServiceWorker = async () => {
+ if (import.meta.env.DEV) return;
+ if (!('serviceWorker' in navigator)) return;
-/* If service worker enabled, then register it, and print message when status changes */
-const registerServiceWorker = async () => {
- if (await shouldEnableServiceWorker()) {
- register(swUrl, {
- ready() {
- setSwStatus({ ready: true });
- printSwStatus(
- 'Dashy is being served from cache by a service worker.\n'
- + 'For more details, visit https://goo.gl/AFskqB',
- );
- },
- registered() {
- setSwStatus({ registered: true });
- printSwStatus('Service worker has been registered.');
- },
- cached() {
- setSwStatus({ cached: true });
- printSwStatus('App has been cached for offline use.');
- },
- updatefound() {
- setSwStatus({ updateFound: true });
- printSwStatus('New content is downloading...');
- },
- updated() {
- setSwStatus({ updated: true });
- printSwStatus('New content is available; please refresh the page.');
- },
- offline() {
- setSwStatus({ offline: true });
- printSwStatus('No internet connection found. Dashy is running in offline mode.');
- },
- error(error) {
- setSwStatus({ error: true });
- statusErrorMsg('Service Worker Status', 'Error during SW registration', error);
+ const conf = await loadAppConfig();
+ if (!conf) return; // network/parse failed β€” leave any existing SW alone
+
+ if (!conf.appConfig?.enableServiceWorker) {
+ await unregisterAll();
+ return;
+ }
+
+ try {
+ const { registerSW } = await import('virtual:pwa-register');
+ const updateSW = registerSW({
+ onRegisteredSW(swUrl, reg) {
+ statusMsg(SW_LABEL, `Service worker registered (${swUrl}).`);
+ if (reg) setInterval(() => reg.update().catch(() => {}), UPDATE_CHECK_INTERVAL_MS);
},
+ onNeedRefresh: () => promptForUpdate(updateSW),
+ onOfflineReady: () => statusMsg(SW_LABEL, 'App is ready for offline use.'),
+ onRegisterError: (e) => statusErrorMsg(SW_LABEL, 'Error during SW registration', e),
});
+ } catch (e) {
+ statusErrorMsg(SW_LABEL, 'Error setting up service worker', e);
}
};
-export default registerServiceWorker;
+export default initServiceWorker;
diff --git a/src/utils/config/defaults.js b/src/utils/config/defaults.js
index 58473bd2..8adcdec5 100644
--- a/src/utils/config/defaults.js
+++ b/src/utils/config/defaults.js
@@ -155,7 +155,6 @@ const defaults = {
},
/* Key names for session storage identifiers */
sessionStorageKeys: {
- SW_STATUS: 'serviceWorkerStatus',
ERROR_LOG: 'errorLog',
},
/* Unique IDs of modals within the app */
diff --git a/vite.config.mjs b/vite.config.mjs
index a95d77d5..3ea60d50 100644
--- a/vite.config.mjs
+++ b/vite.config.mjs
@@ -67,23 +67,37 @@ export default defineConfig({
],
},
workbox: {
+ cleanupOutdatedCaches: true,
+ clientsClaim: true,
+ skipWaiting: false,
+ navigateFallback: '/index.html',
+ navigateFallbackDenylist: [
+ /^\/(status-check|system-info|cors-proxy|get-user|config-manager)\b/,
+ ],
maximumFileSizeToCacheInBytes: 10 * 1024 * 1024,
globIgnores: [
'**/*.map',
'**/manifest*.js',
'**/.nojekyll',
'**/.gitignore',
- '**/conf.yml',
+ '**/*.yml',
+ '**/*.yaml',
],
runtimeCaching: [
{
- urlPattern: /conf\.yml$/,
+ urlPattern: /\.ya?ml(\?.*)?$/i,
handler: 'NetworkFirst',
options: {
- cacheName: 'config-cache',
+ cacheName: 'dashy-config',
networkTimeoutSeconds: 3,
+ expiration: { maxEntries: 20, maxAgeSeconds: 60 * 60 * 24 },
+ cacheableResponse: { statuses: [200] },
},
},
+ {
+ urlPattern: /\/(status-check|system-info|cors-proxy|get-user|config-manager)\b/,
+ handler: 'NetworkOnly',
+ },
],
},
}),
diff --git a/yarn.lock b/yarn.lock
index fd0be5b7..49f3c4a7 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4361,11 +4361,6 @@ regexpu-core@^6.3.1:
unicode-match-property-ecmascript "^2.0.0"
unicode-match-property-value-ecmascript "^2.2.1"
-register-service-worker@^1.7.2:
- version "1.7.2"
- resolved "https://registry.yarnpkg.com/register-service-worker/-/register-service-worker-1.7.2.tgz#6516983e1ef790a98c4225af1216bc80941a4bd2"
- integrity sha512-CiD3ZSanZqcMPRhtfct5K9f7i3OLCcBBWsJjLh1gW9RO/nS94sVzY59iS+fgYBOBqaBpf4EzfqUF3j9IG+xo8A==
-
regjsgen@^0.8.0:
version "0.8.0"
resolved "https://registry.yarnpkg.com/regjsgen/-/regjsgen-0.8.0.tgz#df23ff26e0c5b300a6470cad160a9d090c3a37ab"