Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,16 @@ Formato basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/).
(`tests/data.test.mjs`: JSON válido, ids únicos, recetas sin ingredientes
inexistentes, categorías con tope, `visualStyle` conocido) (#3).

### Cambiado
- Service worker: *network-first* (con timeout de 4 s) para todo lo del
propio sitio en vez de servir primero la caché, así los cambios en `/data`
y en el código se ven en la siguiente carga sin tocar `CACHE_NAME`. Sin red
o con red lenta, arranca desde caché (#5).

### Corregido
- El service worker ya no guarda en caché respuestas de error (404/500), y
la app vuelve a arrancar sin conexión. El precache avisa en consola de qué
fichero falló en vez de silenciarlo (#5).
- La ronda 2 ya no se queda en "Cargando…" si falla la carga del tipo de
cena elegido: muestra el error con el fichero que falló y permite
reintentar (sin perder la ronda 1) o volver al inicio (#19).
Expand Down
13 changes: 13 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,19 @@ Ver `README.md` sección "Añadir un tipo de cena nuevo" — resumen: crea
`admin.html`) y añade la entrada en `data/dish-types.json`. No hace falta
tocar `service-worker.js` ni el código JS.

## Service worker y caché
`service-worker.js` sirve todo lo del propio sitio con *network-first*
(con conexión siempre llega lo último publicado; la caché es solo para
offline o red lenta) y nunca cachea respuestas de error. Por eso:
- **Cambiar `/data` o el código no requiere tocar el service worker.**
- **Sube `CACHE_NAME`** (`dinner-match-v4` → `v5`...) solo si quieres purgar
la caché de todos los clientes: al renombrar o borrar ficheros del shell,
o si cambias la estrategia de caché.
- Si añades un fichero al shell (un HTML, CSS o módulo de `js/` nuevo),
añádelo a `ASSETS` para que funcione offline desde la primera visita.
`tests/sw.test.mjs` falla si falta alguno o si una ruta de `ASSETS` no
existe.

## Añadir una tarea al backlog
Añádela a `backlog/issues.json` (con `title`, `body`, `labels`, `milestone`)
y luego créala en GitHub con:
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,18 @@ Cualquier hosting estático con HTTPS sirve, por ejemplo:
Una vez desplegado, entra desde el móvil y usa "Añadir a pantalla de inicio"
(o el banner de instalación que aparece solo en Chrome/Edge Android).

### Publicar cambios de contenido o de código

No hay que hacer nada especial: haz commit de los JSON de `/data` (o del
código) y despliega. El service worker usa *network-first* para todo lo del
propio sitio, así que quien abra la app con conexión ve la versión nueva en
esa misma carga, también con la PWA instalada. Sin conexión (o si la red
tarda más de 4 s) se usa la última versión guardada en el móvil, y se
actualiza sola la próxima vez que haya red.

No hace falta cambiar `CACHE_NAME` en `service-worker.js` para publicar
cambios; ver `CONTRIBUTING.md` para los casos en que sí.

## Estructura

```
Expand Down
119 changes: 95 additions & 24 deletions service-worker.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,27 @@
const CACHE_NAME = "dinner-match-v3";
// Precache solo el "shell" de la app y el catálogo de tipos: los datos de
// cada tipo (data/types/<id>/*.json) se cachean en runtime la primera vez
// que se piden (ver el handler de "fetch" más abajo), así añadir un tipo
// nuevo en /data no requiere tocar este fichero.
// Estrategia de caché:
// - Mismo origen (HTML, JS, CSS, iconos y /data): network-first. Con
// conexión siempre se sirve lo último publicado (contenido de /data y
// código siempre coherentes entre sí); la caché solo se usa sin red o si
// la red tarda más de NETWORK_TIMEOUT_MS. Por eso publicar cambios en /data
// o en el código NO requiere tocar este fichero.
// - Otros orígenes (Google Fonts): cache-first, no cambian.
// - Solo se guardan respuestas válidas: un 404/500 nunca se cachea.
//
// CACHE_NAME solo hay que cambiarlo si se quiere purgar la caché de todos
// los clientes (p. ej. al renombrar o borrar ficheros del shell). Ver
// CONTRIBUTING.md.
const CACHE_NAME = "dinner-match-v4";
const NETWORK_TIMEOUT_MS = 4000;
// Tras un timeout, durante este tiempo se sirve directamente de caché (sin
// esperar otra vez a la red) para que la cadena HTML → JS → JSON no sume un
// timeout por nivel. La red se sigue consultando en segundo plano.
const SLOW_NETWORK_GRACE_MS = 15000;
let slowNetworkUntil = 0;

// Shell precacheado para que la app arranque offline desde la primera
// visita. Los datos de cada tipo (data/types/<id>/*.json) se cachean en
// runtime la primera vez que se piden. tests/sw.test.mjs comprueba que
// todas estas rutas existen.
const ASSETS = [
"./",
"./index.html",
Expand All @@ -21,30 +40,82 @@ const ASSETS = [
];

self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(ASSETS)).catch(() => {})
);
event.waitUntil((async () => {
const cache = await caches.open(CACHE_NAME);
// Uno a uno en vez de addAll: si falla un fichero se avisa de cuál y el
// resto sí queda precacheado (addAll es todo o nada).
const results = await Promise.allSettled(ASSETS.map((url) => cache.add(new Request(url, { cache: "reload" }))));
results.forEach((r, i) => {
if (r.status === "rejected") console.warn(`[sw] No se pudo precachear ${ASSETS[i]}:`, r.reason);
});
})());
self.skipWaiting();
});

self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((keys) => Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k))))
);
self.clients.claim();
event.waitUntil((async () => {
const keys = await caches.keys();
await Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)));
await self.clients.claim();
})());
});

self.addEventListener("fetch", (event) => {
if (event.request.method !== "GET") return;
event.respondWith(
caches.match(event.request).then((cached) => {
const fetchPromise = fetch(event.request)
.then((networkResponse) => {
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, networkResponse.clone()));
return networkResponse;
})
.catch(() => cached);
return cached || fetchPromise;
})
);
const { request } = event;
if (request.method !== "GET") return;
const url = new URL(request.url);
if (url.protocol !== "http:" && url.protocol !== "https:") return;
event.respondWith(url.origin === self.location.origin ? networkFirst(event) : cacheFirst(event));
});

function cacheable(response) {
// Las respuestas opacas (CSS/fuentes de Google cargadas sin CORS) no
// exponen su status; se aceptan solo para otros orígenes.
return response && (response.ok || response.type === "opaque");
}

function store(event, response) {
if (!cacheable(response)) return;
const copy = response.clone();
event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.put(event.request, copy)));
}

async function networkFirst(event) {
const { request } = event;
const network = fetch(request).then((response) => {
if (response.ok) store(event, response);
return response;
});
// Evita un unhandled rejection si gana el timeout y luego falla la red.
network.catch(() => {});

const cached = await caches.match(request);
if (!cached) return network; // sin copia local: lo que diga la red, errores incluidos
if (Date.now() < slowNetworkUntil) return cached;

let timer;
const timeout = new Promise((resolve) => {
timer = setTimeout(() => {
slowNetworkUntil = Date.now() + SLOW_NETWORK_GRACE_MS;
resolve(cached);
}, NETWORK_TIMEOUT_MS);
});
try {
const response = await Promise.race([network, timeout]);
// Si el servidor responde con error pero hay copia válida, mejor la copia
// que romper la app (p. ej. un 5xx puntual del hosting).
return response.ok || response === cached ? response : cached;
} catch {
return cached; // sin red
} finally {
clearTimeout(timer);
}
}

async function cacheFirst(event) {
const cached = await caches.match(event.request);
if (cached) return cached;
const response = await fetch(event.request);
store(event, response);
return response;
}
40 changes: 40 additions & 0 deletions tests/sw.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Coherencia entre service-worker.js y los ficheros del repo: si una ruta del
// precache no existe, ese fichero no estará disponible offline; si un módulo
// de js/ no está precacheado, la app no arranca offline en la primera visita.

import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync, readdirSync, existsSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";

const ROOT = fileURLToPath(new URL("..", import.meta.url));
const sw = readFileSync(join(ROOT, "service-worker.js"), "utf8");
const block = sw.match(/const ASSETS = \[([\s\S]*?)\];/);
const assets = block ? [...block[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]) : [];

test("service-worker.js declara ASSETS", () => {
assert.ok(assets.length > 0, "no se encontró const ASSETS = [...] en service-worker.js");
});

test("todas las rutas precacheadas existen", () => {
const missing = assets
.filter((a) => a !== "./")
.filter((a) => !existsSync(join(ROOT, a)));
assert.deepEqual(missing, []);
});

test("el shell completo está precacheado (HTML, CSS, módulos JS, manifest, datos globales)", () => {
const required = [
"./index.html", "./admin.html", "./manifest.json", "./css/style.css",
"./data/dish-types.json", "./data/game-config.json",
...readdirSync(join(ROOT, "js")).filter((f) => f.endsWith(".js")).map((f) => `./js/${f}`),
];
assert.deepEqual(required.filter((r) => !assets.includes(r)), []);
});

test("los iconos del manifest están precacheados", () => {
const manifest = JSON.parse(readFileSync(join(ROOT, "manifest.json"), "utf8"));
const icons = manifest.icons.map((i) => `./${i.src.replace(/^\.\//, "")}`);
assert.deepEqual(icons.filter((i) => !assets.includes(i)), []);
});
Loading