sw.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. // Bambuddy Service Worker
  2. const CACHE_NAME = 'bambuddy-v24';
  3. const STATIC_CACHE = 'bambuddy-static-v24';
  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 - stale-while-revalidate
  107. if (
  108. url.pathname.startsWith('/assets/') ||
  109. url.pathname.endsWith('.js') ||
  110. url.pathname.endsWith('.css')
  111. ) {
  112. event.respondWith(
  113. caches.match(request).then((cached) => {
  114. const fetchPromise = fetch(request).then((response) => {
  115. if (response.ok) {
  116. const clone = response.clone();
  117. caches.open(CACHE_NAME).then((cache) => {
  118. cache.put(request, clone);
  119. });
  120. }
  121. return response;
  122. });
  123. return cached || fetchPromise;
  124. })
  125. );
  126. return;
  127. }
  128. // HTML pages - network first, fall back to cache
  129. event.respondWith(
  130. fetch(request)
  131. .then((response) => {
  132. if (response.ok) {
  133. const clone = response.clone();
  134. caches.open(CACHE_NAME).then((cache) => {
  135. cache.put(request, clone);
  136. });
  137. }
  138. return response;
  139. })
  140. .catch(() => {
  141. return caches.match(request).then((cached) => {
  142. if (cached) {
  143. return cached;
  144. }
  145. // Return cached index for SPA navigation
  146. return caches.match('/');
  147. });
  148. })
  149. );
  150. });
  151. // Handle push notifications (for future use)
  152. self.addEventListener('push', (event) => {
  153. if (!event.data) return;
  154. const data = event.data.json();
  155. const options = {
  156. body: data.body || 'New notification from Bambuddy',
  157. icon: '/img/android-chrome-192x192.png',
  158. badge: '/img/favicon-32x32.png',
  159. vibrate: [100, 50, 100],
  160. data: {
  161. url: data.url || '/',
  162. },
  163. };
  164. event.waitUntil(
  165. self.registration.showNotification(data.title || 'Bambuddy', options)
  166. );
  167. });
  168. // Handle notification clicks
  169. self.addEventListener('notificationclick', (event) => {
  170. event.notification.close();
  171. const url = event.notification.data?.url || '/';
  172. event.waitUntil(
  173. clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
  174. // Check if there's already a window open
  175. for (const client of windowClients) {
  176. if (client.url.includes(self.location.origin) && 'focus' in client) {
  177. client.navigate(url);
  178. return client.focus();
  179. }
  180. }
  181. // Open a new window if none exists
  182. if (clients.openWindow) {
  183. return clients.openWindow(url);
  184. }
  185. })
  186. );
  187. });