char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Aleksander Grygierui: Stores consolidation refactor (#27238)fdf4c6460

char/aliceai-t5-moe
2.6 KiB86 linesraw
1import { browser } from '$app/environment';
2import { BUILD_VERSION_LOCALSTORAGE_KEY, SW_CONFIG } from '$lib/constants';
3import { versionStore } from '$lib/stores';
4import { useRegisterSW } from 'virtual:pwa-register/svelte';
5
6/**
7 * Hook for PWA service worker registration, update polling, and build version mismatch detection.
8 *
9 * Combines two concerns that always belong together:
10 * 1. SW registration with periodic polling for updates
11 * 2. localStorage-based version tracking for non-PWA users
12 */
13export function usePwa() {
14	let swCheckInterval: ReturnType<typeof setInterval> | null = null;
15	let needRefreshByStorage = $state(false);
16
17	const {
18		// offlineReady, // to do - add installation banners for iOS
19		needRefresh: pwaNeedRefresh,
20		updateServiceWorker
21	} = useRegisterSW({
22		onRegisteredSW(swUrl: string, r: ServiceWorkerRegistration | undefined) {
23			if (swCheckInterval) {
24				clearInterval(swCheckInterval);
25			}
26
27			swCheckInterval = setInterval(async () => {
28				if (!r || r.installing || !navigator?.onLine) return;
29
30				try {
31					const resp = await fetch(swUrl, {
32						cache: SW_CONFIG.UPDATE_FETCH_OPTIONS.CACHE,
33						headers: {
34							cache: SW_CONFIG.UPDATE_FETCH_OPTIONS.HEADERS.CACHE,
35							'cache-control': SW_CONFIG.UPDATE_FETCH_OPTIONS.HEADERS.CACHE_CONTROL
36						}
37					});
38
39					if (resp?.status === 200) {
40						await r.update();
41					}
42				} catch (e) {
43					console.error(e);
44				}
45			}, SW_CONFIG.CHECK_INTERVAL_MS);
46		},
47		onRegisterError(error: unknown) {
48			console.error('[PWA] SW registration error:', error);
49		}
50	});
51
52	// Detect version mismatch via localStorage.
53	// _app/version.json is SvelteKit's native version file for PWA cache invalidation.
54	// This comparison detects server upgrades for non-PWA users.
55	$effect(() => {
56		if (!browser) return;
57
58		// PWA pages update via the service worker path; the storage check is the non-PWA fallback only
59		if (navigator.serviceWorker?.controller) return;
60
61		const currentVersion = versionStore.frontend;
62
63		if (!currentVersion) return;
64
65		try {
66			const storedVersion = localStorage.getItem(BUILD_VERSION_LOCALSTORAGE_KEY);
67
68			needRefreshByStorage = !!storedVersion && storedVersion !== currentVersion;
69			localStorage.setItem(BUILD_VERSION_LOCALSTORAGE_KEY, currentVersion);
70		} catch {
71			needRefreshByStorage = false;
72		}
73	});
74
75	return {
76		/** Writable that is true when a PWA service worker update is available */
77		get needRefresh() {
78			return pwaNeedRefresh;
79		},
80		/** Version mismatch detected via localStorage (non-PWA users) */
81		get needRefreshByStorage() {
82			return needRefreshByStorage;
83		},
84		updateServiceWorker
85	};
86}