- COMPLETAMENTO PASSAGGIO A VITE - versione 1.2.2:
- Sistemato RefreshToken - Integrato modifiche di PiuCheBuono - Aggiornato a Node 22 - Aggiornato Server a Mongodb 8.0.
This commit is contained in:
@@ -2,6 +2,22 @@
|
||||
/* global idbKeyval */
|
||||
/* global workbox */
|
||||
/* global cfgenv */
|
||||
|
||||
importScripts('/workbox/workbox-sw.js'); // 7.3.0
|
||||
|
||||
if (workbox) {
|
||||
console.log('Workbox ESISTE ✅ ');
|
||||
|
||||
// Imposta configurazione prima di tutto
|
||||
const debug = process.env.NODE_ENV !== 'production';
|
||||
workbox.setConfig({ debug });
|
||||
|
||||
workbox.precaching.precacheAndRoute([]);
|
||||
} else {
|
||||
console.error('Workbox NON CARICATO ! ❌');
|
||||
}
|
||||
|
||||
|
||||
import { precacheAndRoute } from 'workbox-precaching';
|
||||
import { registerRoute } from 'workbox-routing';
|
||||
import { setCacheNameDetails } from 'workbox-core';
|
||||
@@ -14,30 +30,54 @@ import {
|
||||
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
|
||||
import { ExpirationPlugin } from 'workbox-expiration';
|
||||
|
||||
importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.5.4/workbox-sw.js');
|
||||
|
||||
|
||||
|
||||
|
||||
setCacheNameDetails({
|
||||
prefix: self.location.hostname,
|
||||
suffix: 'v1',
|
||||
precache: 'precache',
|
||||
runtime: 'runtime',
|
||||
});
|
||||
|
||||
const precacheList = (self.__WB_MANIFEST || []).filter(entry => {
|
||||
// Esclude tutto ciò che si trova nella cartella 'upload'
|
||||
if (entry.url.includes('/upload/')) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
// Precache solo i file filtrati
|
||||
precacheAndRoute(precacheList);
|
||||
|
||||
// importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.5.4/workbox-sw.js');
|
||||
|
||||
|
||||
|
||||
self.addEventListener('install', () => {
|
||||
console.log('Service Worker: Skip...');
|
||||
self.skipWaiting()
|
||||
});
|
||||
self.addEventListener('activate', (event) => {
|
||||
console.log('Service Worker: Activated');
|
||||
// console.log('CLAIM');
|
||||
//event.waitUntil(self.clients.claim())
|
||||
|
||||
event.waitUntil(async () => {
|
||||
// Check for a new service worker version
|
||||
const registration = await navigator.serviceWorker.getRegistration();
|
||||
if (registration && registration.waiting) {
|
||||
// A new service worker is waiting, trigger a page reload
|
||||
await registration.waiting.postMessage({ type: 'SKIP_WAITING' });
|
||||
self.skipWaiting();
|
||||
}
|
||||
});
|
||||
clientsClaim();
|
||||
event.waitUntil(
|
||||
(async () => {
|
||||
const cacheNames = await caches.keys();
|
||||
await Promise.all(
|
||||
cacheNames.map(cacheName => {
|
||||
if (!cacheName.startsWith(`${self.location.hostname}-v1`)) {
|
||||
return caches.delete(cacheName);
|
||||
}
|
||||
})
|
||||
);
|
||||
})()
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
const VITE_APP_VERSION = "1.1.23";
|
||||
const VITE_APP_VERSION = "1.2.2";
|
||||
|
||||
console.log(' [ VER-' + VITE_APP_VERSION + ' ] _---------________------ PAO: this is my custom service worker');
|
||||
|
||||
@@ -45,13 +85,13 @@ try {
|
||||
importScripts('/js/idb.js', '/js/storage.js');
|
||||
console.log('Local scripts imported successfully.');
|
||||
} catch (error) {
|
||||
console.error('Failed to import local scripts:', error);
|
||||
console.error('Failed to import local scripts ❌:', error);
|
||||
}
|
||||
|
||||
let port = self.location.hostname.startsWith('test') ? 3001 : 3000;
|
||||
let ISTEST = self.location.hostname.startsWith('test');
|
||||
let ISLOCALE = self.location.hostname.startsWith('localhost');
|
||||
console.log('SW- app ver ' + VITE_APP_VERSION + ' on port ' + port);
|
||||
console.log('SW- app ver ' + VITE_APP_VERSION);
|
||||
|
||||
|
||||
// Function helpers
|
||||
@@ -73,26 +113,8 @@ async function deleteItemFromData(table, id) {
|
||||
}
|
||||
|
||||
if (workbox) {
|
||||
const debug = false;
|
||||
workbox.setConfig({ debug });
|
||||
|
||||
const precacheList = (self.__WB_MANIFEST || []).filter(entry => {
|
||||
// Esclude tutto ciò che si trova nella cartella 'upload'
|
||||
if (entry.url.includes('/upload/')) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
setCacheNameDetails({
|
||||
prefix: self.location.hostname,
|
||||
suffix: 'v1',
|
||||
precache: 'precache',
|
||||
runtime: 'runtime',
|
||||
});
|
||||
|
||||
// Precache solo i file filtrati
|
||||
precacheAndRoute(precacheList);
|
||||
|
||||
// Cache strategy registrations
|
||||
registerRoute(
|
||||
@@ -128,8 +150,8 @@ if (workbox) {
|
||||
})
|
||||
);
|
||||
|
||||
registerRoute(
|
||||
new RegExp(/.*\/(?:icons).*$/),
|
||||
/*registerRoute(
|
||||
new RegExp('^/myicons/.*$'), // Corrisponde a percorsi come "/icons/miaicona.ico"
|
||||
new CacheFirst({
|
||||
cacheName: `icon-cache-${VITE_APP_VERSION}`,
|
||||
plugins: [
|
||||
@@ -137,7 +159,7 @@ if (workbox) {
|
||||
new ExpirationPlugin({ maxAgeSeconds: 30 * 24 * 60 * 60 }), // 30 Days
|
||||
],
|
||||
})
|
||||
);
|
||||
);*/
|
||||
|
||||
registerRoute(
|
||||
new RegExp(/\.(?:js|css|font)$/),
|
||||
@@ -189,18 +211,6 @@ if (workbox) {
|
||||
console.log(event.data);
|
||||
});
|
||||
|
||||
// Costanti di configurazione
|
||||
const DYNAMIC_CACHE = 'dynamic-cache-v1';
|
||||
const ENABLE_DYNAMIC_CACHING = true;
|
||||
const baseUrl = self.location.origin;
|
||||
console.log('baseUrl', baseUrl);
|
||||
const APP_DOMAIN = extractDomain(baseUrl);
|
||||
let API_DOMAIN = '';
|
||||
if (ISTEST) {
|
||||
API_DOMAIN = 'testapi.' + removeTestPrefix(APP_DOMAIN);
|
||||
} else {
|
||||
API_DOMAIN = 'api.' + APP_DOMAIN;
|
||||
}
|
||||
|
||||
function removeTestPrefix(str) {
|
||||
return str.startsWith('test.') ? str.slice(5) : str;
|
||||
@@ -217,11 +227,26 @@ if (workbox) {
|
||||
const baseUrl = self.location.origin;
|
||||
return requestUrl.origin !== baseUrl;
|
||||
} catch (e) {
|
||||
console.error('Error parsing URL:', e);
|
||||
console.error('Error parsing URL: ❌', e);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Costanti di configurazione
|
||||
const DYNAMIC_CACHE = 'dynamic-cache-v1';
|
||||
const ENABLE_DYNAMIC_CACHING = true;
|
||||
const baseUrl = self.location.origin;
|
||||
console.log('baseUrl', baseUrl);
|
||||
const APP_DOMAIN = extractDomain(baseUrl);
|
||||
let API_DOMAIN = '';
|
||||
if (ISTEST) {
|
||||
API_DOMAIN = 'testapi.' + removeTestPrefix(APP_DOMAIN);
|
||||
} else {
|
||||
API_DOMAIN = 'api.' + APP_DOMAIN;
|
||||
}
|
||||
|
||||
console.log('API_DOMAIN', API_DOMAIN);
|
||||
|
||||
// Funzione per gestire specificamente le richieste API
|
||||
async function handleApiRequest(request) {
|
||||
const modifiedRequest = new Request(request.url, {
|
||||
@@ -255,7 +280,7 @@ if (workbox) {
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error('[Service Worker] API request error:', error);
|
||||
console.error('[Service Worker] API request error ❌:', error);
|
||||
return new Response(JSON.stringify({
|
||||
error: 'Network error',
|
||||
message: 'Unable to fetch from API'
|
||||
@@ -304,13 +329,13 @@ if (workbox) {
|
||||
const cache = await caches.open(DYNAMIC_CACHE);
|
||||
cache.put(request, response.clone());
|
||||
} catch (cacheError) {
|
||||
console.error('[Service Worker] Cache error:', cacheError);
|
||||
console.error('[Service Worker] Cache error ❌:', cacheError);
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error('[Service Worker] Fetch error:', error, request);
|
||||
console.error('[Service Worker] Fetch error: ❌', error, request);
|
||||
|
||||
// Personalizza la risposta di errore in base al tipo di richiesta
|
||||
if (request.headers.get('Accept')?.includes('application/json')) {
|
||||
@@ -328,49 +353,40 @@ if (workbox) {
|
||||
|
||||
return new Response('Network error', {
|
||||
status: 503,
|
||||
statusText: 'Service Unavailable'
|
||||
statusText: 'Internet non disponibile (503)'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Event listener per il fetch
|
||||
self.addEventListener('fetch', event => {
|
||||
// Gestione delle richieste OPTIONS per CORS
|
||||
if (event.request.method === 'OPTIONS') {
|
||||
event.respondWith(
|
||||
new Response(null, {
|
||||
status: 204,
|
||||
headers: {
|
||||
'Access-Control-Allow-Origin': `https://${APP_DOMAIN}`,
|
||||
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type',
|
||||
'Access-Control-Max-Age': '86400'
|
||||
}
|
||||
})
|
||||
);
|
||||
self.addEventListener('fetch', (event) => {
|
||||
// Ignora richieste non gestibili
|
||||
if (event.request.method !== 'GET' ||
|
||||
event.request.url.startsWith('chrome-extension://')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ignora le richieste non-GET che non sono OPTIONS
|
||||
if (event.request.method !== 'GET') return;
|
||||
|
||||
// Gestisci il caso 'only-if-cached'
|
||||
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
|
||||
// Gestione richieste API
|
||||
const url = new URL(event.request.url);
|
||||
if (url.origin === API_DOMAIN) {
|
||||
event.respondWith(handleApiRequest(event.request));
|
||||
return;
|
||||
}
|
||||
|
||||
// Default handler per altre richieste
|
||||
event.respondWith(handleFetch(event.request));
|
||||
});
|
||||
|
||||
|
||||
// Gestione degli errori non catturati
|
||||
self.addEventListener('unhandledrejection', event => {
|
||||
console.error('[Service Worker] Unhandled rejection:', event.reason);
|
||||
console.error('[Service Worker] Unhandled rejection ❌:', event.reason);
|
||||
});
|
||||
|
||||
// Gestione degli errori globali
|
||||
self.addEventListener('error', event => {
|
||||
console.error('[Service Worker] Global error:', event.error);
|
||||
console.error('[Service Worker] Global error ❌:', event.error);
|
||||
});
|
||||
|
||||
// Funzione di utilità per il logging (decommentare se necessario)
|
||||
// function logFetchDetails(request) {
|
||||
// console.log('[Service Worker] Fetching:', request.url);
|
||||
|
||||
Reference in New Issue
Block a user