93 lines
2.8 KiB
JavaScript
93 lines
2.8 KiB
JavaScript
const CACHE_NAME = 'camila-ai-v7';
|
|
const urlsToCache = [
|
|
'/',
|
|
'/index.html',
|
|
'/style.css',
|
|
'/app.js',
|
|
'/manifest.json',
|
|
'/icon-192.png',
|
|
'/icon-512.png'
|
|
];
|
|
|
|
// Instalação - abre cache e armazena os arquivos iniciais
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME)
|
|
.then((cache) => {
|
|
console.log('Camila AI SW: Armazenando cache inicial');
|
|
return cache.addAll(urlsToCache);
|
|
})
|
|
.then(() => self.skipWaiting())
|
|
);
|
|
});
|
|
|
|
// Ativação - limpa caches antigos
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((cacheNames) => {
|
|
return Promise.all(
|
|
cacheNames.map((cacheName) => {
|
|
if (cacheName !== CACHE_NAME) {
|
|
console.log('Camila AI SW: Removendo cache antigo:', cacheName);
|
|
return caches.delete(cacheName);
|
|
}
|
|
})
|
|
);
|
|
}).then(() => self.clients.claim())
|
|
);
|
|
});
|
|
|
|
// Interceptador de requisições: Network-First para arquivos de código, Cache-First para mídias/assets
|
|
self.addEventListener('fetch', (event) => {
|
|
if (event.request.method !== 'GET') return;
|
|
|
|
const url = new URL(event.request.url);
|
|
|
|
// Ignora requisições de API e chamadas externas (não as intercepta)
|
|
if (url.pathname.startsWith('/api') || !url.origin.startsWith(self.location.origin)) {
|
|
return;
|
|
}
|
|
|
|
const isAsset = url.pathname.endsWith('.png') ||
|
|
url.pathname.endsWith('.jpg') ||
|
|
url.pathname.endsWith('.jpeg') ||
|
|
url.pathname.endsWith('.gif') ||
|
|
url.pathname.endsWith('.ico') ||
|
|
url.pathname.endsWith('.svg') ||
|
|
url.pathname.includes('/assets/');
|
|
|
|
if (isAsset) {
|
|
// Cache-First para imagens, ícones e mídias estáticas
|
|
event.respondWith(
|
|
caches.match(event.request).then((cachedResponse) => {
|
|
if (cachedResponse) return cachedResponse;
|
|
|
|
return fetch(event.request).then((networkResponse) => {
|
|
if (networkResponse && networkResponse.status === 200) {
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
cache.put(event.request, networkResponse.clone());
|
|
});
|
|
}
|
|
return networkResponse;
|
|
});
|
|
})
|
|
);
|
|
} else {
|
|
// Network-First para HTML, CSS, JS e manifest (garante código sempre atualizado pós-deploy)
|
|
event.respondWith(
|
|
fetch(event.request)
|
|
.then((networkResponse) => {
|
|
if (networkResponse && networkResponse.status === 200) {
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
cache.put(event.request, networkResponse.clone());
|
|
});
|
|
}
|
|
return networkResponse;
|
|
})
|
|
.catch(() => {
|
|
// Se estiver offline, serve do cache
|
|
return caches.match(event.request);
|
|
})
|
|
);
|
|
}
|
|
}); |