sw.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // Bambuddy Service Worker
  2. const CACHE_NAME = 'bambuddy-v27';
  3. const STATIC_CACHE = 'bambuddy-static-v26';
  4. // Static assets to cache on install
  5. const STATIC_ASSETS = [
  6. '/',
  7. '/manifest.json',
  8. '/img/favicon.png',
  9. '/img/favicon-16x16.png',
  10. '/img/favicon-32x32.png',
  11. '/img/android-chrome-192x192.png',
  12. '/img/android-chrome-512x512.png',
  13. '/img/apple-touch-icon.png',
  14. '/img/bambuddy_logo_dark.png',
  15. // Self-hosted Inter font (#1460) - cached so the UI renders offline.
  16. '/fonts/inter-latin.woff2',
  17. '/fonts/inter-latin-ext.woff2',
  18. ];
  19. // Install event - cache static assets
  20. self.addEventListener('install', (event) => {
  21. console.log('[SW] Installing service worker...');
  22. event.waitUntil(
  23. caches.open(STATIC_CACHE).then((cache) => {
  24. console.log('[SW] Caching static assets');
  25. return cache.addAll(STATIC_ASSETS);
  26. })
  27. );
  28. // Activate immediately
  29. self.skipWaiting();
  30. });
  31. // Activate event - clean up old caches
  32. self.addEventListener('activate', (event) => {
  33. console.log('[SW] Activating service worker...');
  34. event.waitUntil(
  35. caches.keys().then((cacheNames) => {
  36. return Promise.all(
  37. cacheNames
  38. .filter((name) => name !== CACHE_NAME && name !== STATIC_CACHE)
  39. .map((name) => {
  40. console.log('[SW] Deleting old cache:', name);
  41. return caches.delete(name);
  42. })
  43. );
  44. })
  45. );
  46. // Take control immediately
  47. self.clients.claim();
  48. });
  49. // Fetch event - network-first for API, cache-first for static
  50. self.addEventListener('fetch', (event) => {
  51. const { request } = event;
  52. const url = new URL(request.url);
  53. // Skip non-GET requests
  54. if (request.method !== 'GET') {
  55. return;
  56. }
  57. // Skip cross-origin requests - let the browser handle them directly.
  58. // Without this the catch-all HTML branch below would answer a failed
  59. // cross-origin request with our cached index.html, so e.g. a blocked
  60. // Google Fonts request came back as text/html (#1460).
  61. if (url.origin !== self.location.origin) {
  62. return;
  63. }
  64. // Skip WebSocket connections
  65. if (url.protocol === 'ws:' || url.protocol === 'wss:') {
  66. return;
  67. }
  68. // Skip camera stream/snapshot requests - Safari has issues with streaming through SW
  69. if (url.pathname.includes('/camera/stream') || url.pathname.includes('/camera/snapshot')) {
  70. return;
  71. }
  72. // API requests - network first, no cache (real-time data is critical)
  73. if (url.pathname.startsWith('/api/')) {
  74. event.respondWith(
  75. fetch(request).catch(() => {
  76. // Return offline response for API failures
  77. return new Response(
  78. JSON.stringify({ error: 'offline', message: 'You are currently offline' }),
  79. {
  80. status: 503,
  81. headers: { 'Content-Type': 'application/json' },
  82. }
  83. );
  84. })
  85. );
  86. return;
  87. }
  88. // Static assets - cache first, then network
  89. if (
  90. url.pathname.startsWith('/img/') ||
  91. url.pathname.startsWith('/icons/') ||
  92. url.pathname.startsWith('/fonts/') ||
  93. url.pathname.endsWith('.png') ||
  94. url.pathname.endsWith('.jpg') ||
  95. url.pathname.endsWith('.svg') ||
  96. url.pathname.endsWith('.ico') ||
  97. url.pathname.endsWith('.woff2')
  98. ) {
  99. event.respondWith(
  100. caches.match(request).then((cached) => {
  101. if (cached) {
  102. return cached;
  103. }
  104. return fetch(request).then((response) => {
  105. // Cache successful responses
  106. if (response.ok) {
  107. const clone = response.clone();
  108. caches.open(STATIC_CACHE).then((cache) => {
  109. cache.put(request, clone);
  110. });
  111. }
  112. return response;
  113. });
  114. })
  115. );
  116. return;
  117. }
  118. // JS/CSS assets - network first (Vite content-hashes filenames, so
  119. // cache-busting is built in; network-first ensures new builds load immediately)
  120. if (
  121. url.pathname.startsWith('/assets/') ||
  122. url.pathname.endsWith('.js') ||
  123. url.pathname.endsWith('.css')
  124. ) {
  125. event.respondWith(
  126. fetch(request)
  127. .then((response) => {
  128. if (response.ok) {
  129. const clone = response.clone();
  130. caches.open(CACHE_NAME).then((cache) => {
  131. cache.put(request, clone);
  132. });
  133. }
  134. return response;
  135. })
  136. .catch(() => {
  137. return caches.match(request);
  138. })
  139. );
  140. return;
  141. }
  142. // HTML pages - network first, fall back to cache
  143. event.respondWith(
  144. fetch(request)
  145. .then((response) => {
  146. if (response.ok) {
  147. const clone = response.clone();
  148. caches.open(CACHE_NAME).then((cache) => {
  149. cache.put(request, clone);
  150. });
  151. }
  152. return response;
  153. })
  154. .catch(() => {
  155. return caches.match(request).then((cached) => {
  156. if (cached) {
  157. return cached;
  158. }
  159. // Return cached index for SPA navigation
  160. return caches.match('/');
  161. });
  162. })
  163. );
  164. });
  165. // Handle push notifications (for future use)
  166. self.addEventListener('push', (event) => {
  167. if (!event.data) return;
  168. const data = event.data.json();
  169. const options = {
  170. body: data.body || 'New notification from Bambuddy',
  171. icon: '/img/android-chrome-192x192.png',
  172. badge: '/img/favicon-32x32.png',
  173. vibrate: [100, 50, 100],
  174. data: {
  175. url: data.url || '/',
  176. },
  177. };
  178. event.waitUntil(
  179. self.registration.showNotification(data.title || 'Bambuddy', options)
  180. );
  181. });
  182. // Handle notification clicks
  183. self.addEventListener('notificationclick', (event) => {
  184. event.notification.close();
  185. const url = event.notification.data?.url || '/';
  186. event.waitUntil(
  187. clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
  188. // Check if there's already a window open
  189. for (const client of windowClients) {
  190. if (client.url.includes(self.location.origin) && 'focus' in client) {
  191. client.navigate(url);
  192. return client.focus();
  193. }
  194. }
  195. // Open a new window if none exists
  196. if (clients.openWindow) {
  197. return clients.openWindow(url);
  198. }
  199. })
  200. );
  201. });