sw.js 5.5 KB

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