perf: arranque ultrarapido pwa con gzip compression stale-while-revalidate y renderizado optimista

This commit is contained in:
unknown
2026-10-08 22:09:49 -06:00
parent da5dbd24f8
commit 06beb22c1f
6 changed files with 192 additions and 61 deletions
+79
View File
@@ -10,6 +10,7 @@
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"better-sqlite3": "^13.0.3", "better-sqlite3": "^13.0.3",
"compression": "^1.8.2",
"cors": "^2.8.6", "cors": "^2.8.6",
"express": "^5.2.1", "express": "^5.2.1",
"imap-simple": "^5.1.0", "imap-simple": "^5.1.0",
@@ -493,6 +494,65 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/compressible": {
"version": "2.0.18",
"resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz",
"integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==",
"license": "MIT",
"dependencies": {
"mime-db": ">= 1.43.0 < 2"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/compression": {
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/compression/-/compression-1.8.2.tgz",
"integrity": "sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==",
"license": "MIT",
"dependencies": {
"bytes": "3.1.2",
"compressible": "~2.0.18",
"debug": "2.6.9",
"destroy": "1.2.0",
"negotiator": "~0.6.4",
"on-headers": "~1.1.0",
"safe-buffer": "5.2.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.8.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/compression/node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
"license": "MIT",
"dependencies": {
"ms": "2.0.0"
}
},
"node_modules/compression/node_modules/ms": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT"
},
"node_modules/compression/node_modules/negotiator": {
"version": "0.6.4",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.4.tgz",
"integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-disposition": { "node_modules/content-disposition": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
@@ -622,6 +682,16 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/destroy": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
"license": "MIT",
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/devtools-protocol": { "node_modules/devtools-protocol": {
"version": "0.0.1687809", "version": "0.0.1687809",
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1687809.tgz", "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1687809.tgz",
@@ -1512,6 +1582,15 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/on-headers": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz",
"integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/once": { "node_modules/once": {
"version": "1.4.0", "version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+1
View File
@@ -22,6 +22,7 @@
"homepage": "https://github.com/pampo32-hub/recreopay#readme", "homepage": "https://github.com/pampo32-hub/recreopay#readme",
"dependencies": { "dependencies": {
"better-sqlite3": "^13.0.3", "better-sqlite3": "^13.0.3",
"compression": "^1.8.2",
"cors": "^2.8.6", "cors": "^2.8.6",
"express": "^5.2.1", "express": "^5.2.1",
"imap-simple": "^5.1.0", "imap-simple": "^5.1.0",
+6 -5
View File
@@ -11,7 +11,8 @@
<meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="SiboPay"> <meta name="apple-mobile-web-app-title" content="SiboPay">
<meta name="mobile-web-app-capable" content="yes"> <link rel="preload" href="/css/styles.css?v=14.0" as="style">
<link rel="preload" href="/js/app.js?v=14.0" as="script">
<link rel="stylesheet" href="/css/styles.css?v=14.0"> <link rel="stylesheet" href="/css/styles.css?v=14.0">
<link rel="stylesheet" href="/css/desktop.css?v=2.2"> <link rel="stylesheet" href="/css/desktop.css?v=2.2">
<style> <style>
@@ -3896,9 +3897,9 @@
</nav> </nav>
<script src="/js/dialogs.js?v=13.8"></script> <script src="/js/dialogs.js?v=13.8"></script>
<script src="/js/sounds.js?v=13.8"></script> <script src="/js/sounds.js?v=13.8" defer></script>
<script src="/js/jsQR.js"></script> <script src="/js/jsQR.js" defer></script>
<script src="/js/food-icons.js?v=1.1"></script> <script src="/js/food-icons.js?v=1.1" defer></script>
<script src="/js/app.js?v=14.0"></script> <script src="/js/app.js?v=15.0"></script>
</body> </body>
</html> </html>
+49 -18
View File
@@ -68,7 +68,7 @@ document.addEventListener('DOMContentLoaded', async () => {
// Registrar Service Worker para PWA // Registrar Service Worker para PWA
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js?v=15.0').then(reg => { navigator.serviceWorker.register('/sw.js?v=16.0').then(reg => {
reg.update().catch(() => {}); reg.update().catch(() => {});
if ('Notification' in window && Notification.permission === 'granted') { if ('Notification' in window && Notification.permission === 'granted') {
subscribeDeviceToWebPush().catch(() => {}); subscribeDeviceToWebPush().catch(() => {});
@@ -546,12 +546,38 @@ async function applyUserRoleSession() {
const btnPadres = document.getElementById('btnModePadres'); const btnPadres = document.getElementById('btnModePadres');
if (btnPadres) btnPadres.style.display = 'none'; if (btnPadres) btnPadres.style.display = 'none';
await loadInitialData(); // 🚀 RENDERIZADO OPTIMISTA INSTANTÁNEO (0 ms):
// El estudiante ve su carné, saldo y botón de QR de inmediato con sus datos guardados localmente
if (currentUser.estudiante) { if (currentUser.estudiante) {
await selectStudent(currentUser.estudiante.id); currentStudent = currentUser.estudiante;
currentAppMode = 'teens';
updateStudentUI();
}
// En segundo plano y en paralelo: sincronizar datos frescos sin congelar la pantalla
const studentTasks = [loadInitialData(true)];
if (currentUser.estudiante) {
studentTasks.push(
fetch(`/api/estudiantes/${currentUser.estudiante.id}`)
.then(r => r.json())
.then(freshStudent => {
if (freshStudent && freshStudent.id) {
currentStudent = freshStudent;
currentUser.estudiante = freshStudent;
try {
localStorage.setItem('sibopay_user', JSON.stringify(currentUser));
} catch (_) {}
updateStudentUI();
}
})
.catch(e => console.warn('Error sincronizando estudiante:', e))
);
} else if (students.length > 0) { } else if (students.length > 0) {
selectStudent(students[0].id); selectStudent(students[0].id);
} }
await Promise.allSettled(studentTasks);
} }
} }
@@ -678,21 +704,24 @@ function pwaNavigateTo(target) {
} }
} }
async function loadInitialData() { async function loadInitialData(isStudent = false) {
try { try {
// 1. Cargar estudiantes
const resEst = await fetch('/api/estudiantes');
students = await resEst.json();
populateStudentSelector();
// 2. Cargar productos y categorías de la escuela activa
const escId = (currentUser && currentUser.escuela_id) || (currentStudent && currentStudent.escuela_id) || 1; const escId = (currentUser && currentUser.escuela_id) || (currentStudent && currentStudent.escuela_id) || 1;
const resProd = await fetch(`/api/productos?escuela_id=${escId}`);
const dataProd = await resProd.json();
categories = dataProd.categorias || [];
// Deduplicar productos para garantizar que nunca se repita ninguno // 🚀 Ejecución paralela ultra rápida con Promise.all
const promises = [
fetch(`/api/productos?escuela_id=${escId}`).then(r => r.json()).catch(() => ({ categorias: [], productos: [] })),
loadCardDesigns()
];
if (!isStudent) {
promises.push(fetch('/api/estudiantes').then(r => r.json()).catch(() => []));
}
const [dataProd, _, resEst] = await Promise.all(promises);
if (dataProd) {
categories = dataProd.categorias || [];
const seenNames = new Set(); const seenNames = new Set();
products = (dataProd.productos || []).filter(p => { products = (dataProd.productos || []).filter(p => {
const key = String(p.nombre).trim().toLowerCase(); const key = String(p.nombre).trim().toLowerCase();
@@ -700,12 +729,14 @@ async function loadInitialData() {
seenNames.add(key); seenNames.add(key);
return true; return true;
}); });
renderCategories(); renderCategories();
renderProducts(); renderProducts();
}
// 3. Cargar catálogo de diseños de tarjetas if (!isStudent && Array.isArray(resEst)) {
await loadCardDesigns(); students = resEst;
populateStudentSelector();
}
} catch (error) { } catch (error) {
console.error('Error cargando datos iniciales:', error); console.error('Error cargando datos iniciales:', error);
} }
+22 -13
View File
@@ -1,5 +1,5 @@
// SiboPay PWA Service Worker v15.0 - Dashboard Ejecutivo de Padres & Persistencia Sesión F5 // SiboPay PWA Service Worker v16.0 - Ultra Fast Startup & Stale-While-Revalidate
const CACHE_NAME = 'sibopay-v15.0'; const CACHE_NAME = 'sibopay-v16.0';
const STATIC_ASSETS = [ const STATIC_ASSETS = [
'/', '/',
'/index.html', '/index.html',
@@ -7,13 +7,13 @@ const STATIC_ASSETS = [
'/pistola.html', '/pistola.html',
'/carnet.html', '/carnet.html',
'/manifest.json', '/manifest.json',
'/css/styles.css', '/css/styles.css?v=14.0',
'/css/desktop.css', '/css/desktop.css?v=2.2',
'/js/dialogs.js', '/js/dialogs.js?v=13.8',
'/js/app.js', '/js/app.js?v=14.0',
'/js/pos.js', '/js/pos.js',
'/js/sounds.js', '/js/sounds.js?v=13.8',
'/js/food-icons.js', '/js/food-icons.js?v=1.1',
'/icons/icon-192.png', '/icons/icon-192.png',
'/icons/icon-512.png', '/icons/icon-512.png',
'/img/sibopay-emblem.png', '/img/sibopay-emblem.png',
@@ -46,11 +46,11 @@ self.addEventListener('activate', (event) => {
); );
}); });
// Network-First con fallback a caché para navegación y recursos estáticos // Estrategia Stale-While-Revalidate para apertura instantánea (0ms) en móviles
self.addEventListener('fetch', (event) => { self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url); const url = new URL(event.request.url);
// APIs y Server-Sent Events (SSE): Directo a red sin caché // APIs y Server-Sent Events (SSE): Directo a red en tiempo real sin caché
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/events')) { if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/events')) {
return; return;
} }
@@ -61,7 +61,9 @@ self.addEventListener('fetch', (event) => {
} }
event.respondWith( event.respondWith(
fetch(event.request) caches.match(event.request).then((cachedResponse) => {
// Lanzar actualización en segundo plano (revalidate) sin bloquear la pantalla
const fetchPromise = fetch(event.request)
.then((networkResponse) => { .then((networkResponse) => {
if (networkResponse && networkResponse.status === 200) { if (networkResponse && networkResponse.status === 200) {
const responseClone = networkResponse.clone(); const responseClone = networkResponse.clone();
@@ -72,12 +74,19 @@ self.addEventListener('fetch', (event) => {
return networkResponse; return networkResponse;
}) })
.catch(() => { .catch(() => {
return caches.match(event.request).then((cachedResponse) => { // Si no hay red y era navegación, retornar index.html en caché
if (cachedResponse) return cachedResponse;
if (event.request.mode === 'navigate') { if (event.request.mode === 'navigate') {
return caches.match('/index.html'); return caches.match('/index.html');
} }
}); });
// Si ya está en la memoria del teléfono, entregar INMEDIATAMENTE (<15ms)
if (cachedResponse) {
return cachedResponse;
}
// Si es la primera vez que se descarga, esperar la respuesta de red
return fetchPromise;
}) })
); );
}); });
+14 -4
View File
@@ -89,9 +89,13 @@ async function sendWebPushNotification({ escuelaId = null, payload, roles = ['ad
} }
} }
const compression = require('compression');
const app = express(); const app = express();
const PORT = process.env.PORT || 3030; const PORT = process.env.PORT || 3030;
// Compresión Gzip de alto rendimiento para HTML, JS, CSS y JSON
app.use(compression());
// Initialize DB schema & seed data // Initialize DB schema & seed data
initDatabase(); initDatabase();
@@ -114,12 +118,18 @@ app.get('/desktop-preview.html', (req, res) => {
res.redirect(301, '/'); res.redirect(301, '/');
}); });
// Servir archivos estáticos con compresión y caché optimizado para PWA
app.use(express.static(path.join(__dirname, '../public'), { app.use(express.static(path.join(__dirname, '../public'), {
etag: false, etag: true,
maxAge: '1d',
setHeaders: (res, filePath) => { setHeaders: (res, filePath) => {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); // Para HTML y Service Worker: siempre revalidar para garantizar actualizaciones inmediatas
res.setHeader('Pragma', 'no-cache'); if (filePath.endsWith('.html') || filePath.endsWith('sw.js') || filePath.endsWith('manifest.json')) {
res.setHeader('Expires', '0'); res.setHeader('Cache-Control', 'no-cache, must-revalidate');
} else {
// Para CSS, JS, imágenes y fuentes: permitir caché con stale-while-revalidate para arranque instantáneo
res.setHeader('Cache-Control', 'public, max-age=86400, stale-while-revalidate=604800');
}
} }
})); }));