diff --git a/Makefile b/Makefile index 03c8216..d6d9bc5 100644 --- a/Makefile +++ b/Makefile @@ -110,15 +110,13 @@ test-browser: $(PLAYWRIGHT) $(QR_READER) ## Parcours Playwright de l'app, captur @tmp="$$(mktemp -d)"; data="$$tmp/data"; site="$$tmp/build/site"; \ trap 'kill $$pid 2>/dev/null; rm -rf -- "$$tmp"' EXIT; \ $(MAKE) --no-print-directory site SITE_BUILD="$$tmp/build" >/dev/null || exit 1; \ - port="$$(node -e 'const s=require("node:net").createServer().listen(0,"127.0.0.1",()=>{console.log(s.address().port);s.close()})')"; \ - PORT="$$port" SITE_DIR="$$site" DATA_DIR="$$data" PUBLIC_URL="http://127.0.0.1:$$port" \ - node server/main.js >"$$tmp/server.log" 2>&1 & pid=$$!; \ - for _ in $$(seq 50); do curl -sf -o /dev/null "http://127.0.0.1:$$port/" && break; sleep 0.1; done; \ - curl -sf -o /dev/null "http://127.0.0.1:$$port/" || { echo "Le serveur ne démarre pas :"; cat "$$tmp/server.log"; exit 1; }; \ - docker run --rm --init --ipc=host --network host -u "$$(id -u):$$(id -g)" -e HOME=/tmp \ - -v "$(CURDIR)/$(APP_DIR):/app:ro" -v "$(CURDIR)/tests/browser:/tests:ro" -v "$$site:/site" \ + mkdir -p "$$data"; \ + docker run --rm --init --ipc=host --network bridge -u "$$(id -u):$$(id -g)" -e HOME=/tmp \ + -v "$(CURDIR)/$(APP_DIR):/repo/app:ro" -v "$(CURDIR)/server:/repo/server:ro" -v "$(CURDIR)/package.json:/repo/package.json:ro" \ + -v "$(CURDIR)/tests/browser:/tests:ro" \ + -v "$$site:/site" -v "$$data:/data" \ -v "$(CURDIR)/$(BROWSER_TOOLS):/tools:ro" -v "$(CURDIR)/build/shots:/shots" \ - $(PLAYWRIGHT_IMAGE) node /tests/parcours.cjs /app /shots "http://127.0.0.1:$$port/" + $(PLAYWRIGHT_IMAGE) sh /tests/run.sh test-site: ## Construit l'image de production en local et vérifie ce qu'elle sert (Docker) @tests/test_site.sh diff --git a/app/domain/wod-generator.js b/app/domain/wod-generator.js new file mode 100644 index 0000000..8ed064b --- /dev/null +++ b/app/domain/wod-generator.js @@ -0,0 +1,175 @@ +// Le générateur de « WOD du jour », hors ligne (lot 5c, ADR 0011) : un WOD composé +// par des règles, sans IA. Déterministe : le même jour, le même matériel et le même +// tirage donnent le même WOD (« Un autre » passe au tirage suivant). +// Règles de composition : +// - un format tiré parmi AMRAP, EMOM, For Time en tours, et 21-15-9 ; +// - deux ou trois mouvements, de modalités différentes autant que le matériel le +// permet : cardio (M), gymnastique (G), charges (W) ; +// - seulement ce que le matériel coché permet (sans matériel renseigné : poids du +// corps et course) ; +// - pas un mouvement fait dans les deux derniers jours, tant qu'il en reste d'autres ; +// - des répétitions à l'échelle du format (moins par intervalle d'EMOM, plus par tour +// d'un For Time court ; 12-9-6 plutôt que 21-15-9 pour un mouvement lourd) ; +// - pas de mouvement de gymnastique avancé (pompes en équilibre, muscle-up) : le profil +// ne dit pas encore le niveau. +// Glossaire : docs/glossaire/wod.md + +import { EXERCISES } from "./exercises.js"; +import { canDo } from "./kit.js"; +import { addDays } from "./dates.js"; + +/** @typedef {"M"|"G"|"W"} Modality */ +/** @typedef {import("./program.js").ProgramSession} ProgramSession */ + +/** + * Les mouvements du générateur : leur modalité, les répétitions d'un tour d'AMRAP + * (ou une distance, des calories), et la charge conseillée. + * @type {readonly {ref: string, m: Modality, reps: number, unit?: string, note?: string}[]} + */ +export const WOD_MOVES = Object.freeze([ + { ref: "run", m: "M", reps: 200, unit: "m" }, + { ref: "rowing-machine", m: "M", reps: 250, unit: "m" }, + { ref: "assault-bike", m: "M", reps: 12, unit: "cal" }, + { ref: "ski-erg", m: "M", reps: 12, unit: "cal" }, + { ref: "jump-rope", m: "M", reps: 50 }, + { ref: "double-under", m: "M", reps: 30 }, + { ref: "pull-up", m: "G", reps: 7 }, + { ref: "push-up", m: "G", reps: 10 }, + { ref: "burpee", m: "G", reps: 8 }, + { ref: "sit-up", m: "G", reps: 15 }, + { ref: "bodyweight-squat", m: "G", reps: 15 }, + { ref: "box-jump", m: "G", reps: 10, note: "Box de 60 / 50 cm" }, + { ref: "toes-to-bar", m: "G", reps: 8 }, + { ref: "forward-lunge", m: "G", reps: 12, note: "En alternant les jambes" }, + { ref: "mountain-climber", m: "G", reps: 20 }, + { ref: "ring-row", m: "G", reps: 10 }, + { ref: "ring-dip", m: "G", reps: 7 }, + { ref: "kettlebell-swing", m: "W", reps: 15, note: "Kettlebell 24 / 16 kg" }, + { ref: "wall-ball", m: "W", reps: 12, note: "Ballon de 9 / 6 kg" }, + { ref: "dumbbell-snatch", m: "W", reps: 10, note: "Haltère 22,5 / 15 kg, en alternant les bras" }, + { ref: "thruster", m: "W", reps: 10, note: "Haltères 2 × 15 / 10 kg" }, + { ref: "devil-press", m: "W", reps: 6, note: "Haltères 2 × 15 / 10 kg" }, + { ref: "goblet-squat", m: "W", reps: 12, note: "Haltère ou kettlebell 24 / 16 kg" }, + { ref: "ball-slam", m: "W", reps: 12, note: "Ballon de 9 / 6 kg" }, + { ref: "barbell-thruster", m: "W", reps: 9, note: "Barre légère : 43 / 29 kg" }, + { ref: "power-clean", m: "W", reps: 6, note: "Barre moyenne : 61 / 43 kg" }, + { ref: "deadlift", m: "W", reps: 9, note: "Barre moyenne : 84 / 57 kg" }, + { ref: "front-squat", m: "W", reps: 8, note: "Barre moyenne : 52 / 35 kg" }, + { ref: "push-press", m: "W", reps: 8, note: "Barre légère : 43 / 29 kg" }, + { ref: "sumo-deadlift-high-pull", m: "W", reps: 10, note: "Barre légère : 34 / 25 kg" }, +]); + +/** Les mouvements qui ne demandent rien : sans matériel renseigné, on reste là. */ +const NO_KIT = /** @type {string[]} */ ([]); + +/** + * Générateur pseudo-aléatoire à graine (mulberry32) : le même tirage pour la même graine. + * @param {number} seed + */ +function random(seed) { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +/** Une graine stable pour un texte (FNV-1a). @param {string} text */ +function hash(text) { + let h = 0x811c9dc5; + for (const c of text) h = Math.imul(h ^ c.charCodeAt(0), 0x01000193) >>> 0; + return h; +} + +/** @template T @param {() => number} rnd @param {readonly T[]} list @returns {T} */ +const pick = (rnd, list) => list[Math.floor(rnd() * list.length)]; + +/** + * @typedef {object} GeneratorInput + * @property {string} today AAAA-MM-JJ + * @property {number} [draw] tirage du jour, à partir de 1 + * @property {readonly string[]} [kit] matériel coché ; absent : poids du corps et course + * @property {{date: string, exercises: {id: string}[]}[]} [sessions] l'historique, pour éviter les mouvements récents + */ + +/** + * Le WOD du jour : une séance WOD ponctuelle, valide (validateProgram) et faisable + * avec le matériel. + * @param {GeneratorInput} input + * @returns {Omit} + */ +export function generateWod({ today, draw = 1, kit, sessions = [] }) { + const rnd = random(hash(`${today}|${draw}|${[...(kit ?? ["-"])].sort().join(",")}`)); + const since = addDays(today, -2); + // Les deux jours d'avant, pas aujourd'hui : faire le WOD du jour ne doit pas le changer. + const recent = new Set(sessions.filter((s) => s.date >= since && s.date < today).flatMap((s) => s.exercises.map((x) => x.id))); + const possible = WOD_MOVES.filter((x) => EXERCISES[x.ref] && canDo(x.ref, kit ?? NO_KIT)); + const fresh = possible.filter((x) => !recent.has(x.ref)); + const pool = fresh.length >= 3 ? fresh : possible; + + // Le format, puis le nombre de mouvements qu'il demande. + const kind = pick(rnd, /** @type {const} */ (["amrap", "amrap", "emom", "rounds", "couplet"])); + const count = kind === "couplet" ? 2 : kind === "emom" ? pick(rnd, [2, 3]) : 3; + + // Les modalités : toutes différentes tant qu'il y en a assez ; un couplet 21-15-9 + // préfère charges + gymnastique. + const byM = /** @type {Record} */ ({ M: [], G: [], W: [] }); + for (const x of pool) byM[x.m].push(x); + const order = /** @type {Modality[]} */ (kind === "couplet" ? ["W", "G", "M"] : shuffle(rnd, ["M", "G", "W"])); + /** @type {typeof pool} */ + const chosen = []; + for (const m of order) if (chosen.length < count && byM[m].length) chosen.push(pick(rnd, byM[m])); + // Pas assez de modalités (poids du corps seul) : on complète, sans doublon ni même muscle principal. + const rest = shuffle(rnd, pool.filter((x) => !chosen.includes(x))); + for (const x of rest) { + if (chosen.length >= count) break; + const first = EXERCISES[x.ref].primary[0]; + if (!chosen.some((c) => EXERCISES[c.ref].primary[0] === first)) chosen.push(x); + } + for (const x of rest) if (chosen.length < count && !chosen.includes(x)) chosen.push(x); + + const amount = (/** @type {(typeof pool)[number]} */ x, /** @type {number} */ factor) => { + const n = x.unit === "m" ? Math.max(100, Math.round((x.reps * factor) / 50) * 50) : Math.max(1, Math.round(x.reps * factor)); + return x.unit ? `${n} ${x.unit}` : String(n); + }; + /** @param {(typeof pool)[number]} x @param {string} reps */ + const move = (x, reps) => ({ ref: x.ref, sets: 1, reps, rest: 0, ...(x.note ? { note: x.note } : {}) }); + + const name = `WOD du jour · ${frenchDay(today)}${draw > 1 ? ` (${draw})` : ""}`; + if (kind === "amrap") { + const minutes = pick(rnd, [10, 12, 15, 20]); + return { name, oneOff: true, format: { type: "amrap", minutes }, exercises: chosen.map((x) => move(x, amount(x, 1))) }; + } + if (kind === "emom") { + const minutes = chosen.length * pick(rnd, [4, 5]); + return { name, oneOff: true, format: { type: "emom", minutes }, exercises: chosen.map((x) => move(x, amount(x, x.m === "M" ? 0.6 : 0.8))) }; + } + if (kind === "rounds") { + const rounds = pick(rnd, [3, 4, 5]); + const factor = rounds === 3 ? 1.5 : rounds === 4 ? 1.2 : 1; + return { name, oneOff: true, format: { type: "fortime", rounds, capMinutes: rounds * 4 }, exercises: chosen.map((x) => move(x, amount(x, factor))) }; + } + // 21-15-9 : un couplet court et intense ; 12-9-6 pour un mouvement lourd (peu de + // répétitions par tour d'AMRAP) ; un mouvement de cardio garde une distance. + return { + name, oneOff: true, format: { type: "fortime", capMinutes: 10 }, + exercises: chosen.map((x) => move(x, x.unit ? `${amount(x, 1)} par tour` : x.reps >= 9 ? "21-15-9" : "12-9-6")), + }; +} + +/** @template T @param {() => number} rnd @param {readonly T[]} list @returns {T[]} */ +function shuffle(rnd, list) { + const out = [...list]; + for (let i = out.length - 1; i > 0; i--) { + const j = Math.floor(rnd() * (i + 1)); + [out[i], out[j]] = [out[j], out[i]]; + } + return out; +} + +const MONTHS = ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."]; +/** « 23 nov. » @param {string} day */ +const frenchDay = (day) => `${Number(day.slice(8, 10))} ${MONTHS[Number(day.slice(5, 7)) - 1]}`; diff --git a/app/main.js b/app/main.js index a2f6ae6..db6cb5c 100644 --- a/app/main.js +++ b/app/main.js @@ -149,7 +149,7 @@ startRouter(root, (route, nav) => { case "sync": return syncScreen({ service: sync, store, nav }); case "pair": return pairScreen({ service: sync, store, nav, key: pairKey }); case "library": return libraryScreen({ store, nav, query: route.query }); - case "wods": return wodCatalogScreen({ store, nav }); + case "wods": return wodCatalogScreen({ store, nav, today, query: route.query }); case "wod": return wodItemScreen({ store, nav, today, id: route.id }); case "library-item": return libraryItemScreen({ store, nav, today, id: route.id }); case "connect-ai": return connectAiScreen({ service: sync, nav, hash: "?" + route.query }); diff --git a/app/styles/screens.css b/app/styles/screens.css index 0421b6e..abf881b 100644 --- a/app/styles/screens.css +++ b/app/styles/screens.css @@ -123,3 +123,6 @@ .lib-more > summary::-webkit-details-marker { display: none; } .lib-more > summary::before { content: "+"; font-family: var(--font-mark); } .lib-more[open] > summary::before { content: "−"; } + +/* WOD du jour (lot 5c), en tête du catalogue. */ +.wod-daily { margin-bottom: var(--space-5); display: grid; gap: var(--space-2); } diff --git a/app/ui/router.js b/app/ui/router.js index 2c676a9..23f5eed 100644 --- a/app/ui/router.js +++ b/app/ui/router.js @@ -32,7 +32,7 @@ * | {name: "connect-ai", query: string} * | {name: "library", query: string} * | {name: "library-item", id: string, query: string} - * | {name: "wods"} + * | {name: "wods", query: string} * | {name: "wod", id: string} * | {name: "reserved"} * | {name: "not-found"}} Route @@ -65,7 +65,7 @@ export function parseRoute(hash) { if (head === "connecter-ia" && parts.length === 1) return { name: "connect-ai", query }; if (head === "bibliotheque" && parts.length === 1) return { name: "library", query }; if (head === "bibliotheque" && parts.length === 2 && arg) return { name: "library-item", id: arg, query }; - if (head === "wod" && parts.length === 1) return { name: "wods" }; + if (head === "wod" && parts.length === 1) return { name: "wods", query }; if (head === "wod" && parts.length === 2 && arg) return { name: "wod", id: arg }; if (parts.length === 1 && WITH_QUERY[head]) return /** @type {Route} */ ({ name: WITH_QUERY[head], query }); if (parts.length === 1 && SIMPLE[head]) return /** @type {Route} */ ({ name: SIMPLE[head] }); @@ -120,7 +120,8 @@ export const href = { sync: () => "#/synchro", pair: () => "#/relier", library: (/** @type {string} */ query = "") => "#/bibliotheque" + (query ? "?" + query : ""), - wods: () => "#/wod", + /** Le catalogue, et le tirage du WOD du jour (1 omis). */ + wods: (/** @type {number} */ draw = 1) => withParams("#/wod", { tirage: draw > 1 ? draw : null }), wod: (/** @type {string} */ id) => "#/wod/" + enc(id), libraryItem: (/** @type {string} */ id, /** @type {string} */ query = "") => "#/bibliotheque/" + enc(id) + (query ? "?" + query : ""), }; diff --git a/app/ui/screens/wod-catalog.js b/app/ui/screens/wod-catalog.js index f9575a5..ae9893a 100644 --- a/app/ui/screens/wod-catalog.js +++ b/app/ui/screens/wod-catalog.js @@ -1,8 +1,10 @@ -// Le catalogue des WOD de référence (lot 4d) : la liste, et la fiche d'un WOD avec +// Le catalogue des WOD de référence (lot 4d), précédé du WOD du jour généré hors +// ligne (lot 5c, domain/wod-generator.js) : la liste, et la fiche d'un WOD avec // son record, « Faire aujourd'hui » (ajouté au programme comme WOD ponctuel) et // « Demander à mon IA de l'adapter ». Données : domain/benchmarks.js. -import { h } from "../dom.js"; +import { h, replace } from "../dom.js"; +import { generateWod } from "../../domain/wod-generator.js"; import { BENCHMARKS, BENCHMARK_FAMILIES, benchmark } from "../../domain/benchmarks.js"; import { formatHint, formatLabel, scoreLabel, wodKey } from "../../domain/wod.js"; import { wodRecords } from "../../domain/analysis.js"; @@ -23,14 +25,67 @@ import { toast } from "../feedback.js"; const recordOf = (state, b) => wodRecords(state).find((r) => r.key === wodKey(b.session.name, /** @type {any} */ (b.session.format))) ?? null; /** - * @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation}} ctx + * Le tirage du WOD du jour, lu dans l'adresse (#/wod?tirage=2) ; 1 par défaut. + * @param {string} query + */ +export function readDraw(query) { + const n = Number(new URLSearchParams(query).get("tirage")); + return Number.isInteger(n) && n >= 1 && n <= 99 ? n : 1; +} + +/** + * Le WOD du jour : généré par les règles de l'app, avec le matériel du profil. + * @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string, query: string}} ctx + */ +function dailyWod({ store, nav, today, query }) { + let draw = readDraw(query); + const box = h("section", { class: "block wod-daily", "aria-labelledby": "wod-daily" }); + const paint = () => { + const state = store.getState(); + const session = generateWod({ today: today(), draw, kit: state.profile.kit, sessions: state.sessions }); + const format = /** @type {import("../../domain/wod.js").WodFormat} */ (session.format); + const pending = pendingOneOffs(state.program, state.sessions).find((s) => s.format && wodKey(s.name, s.format) === wodKey(session.name, format)); + const doToday = () => { + if (pending) return nav.go(href.session(pending.key)); + const program = store.getState().program; + if (!program) return; + const { program: next, key } = withOneOff(program, session, store.getState().sessions); + store.dispatch("ProgramAdopted", { program: next, source: "app", reason: `WOD du jour ajouté : ${formatLabel(format)}.` }); + nav.go(href.session(key)); + }; + replace(box, + h("p", { class: "kicker" }, "Composé par l'app, hors ligne"), + h("h2", { class: "block__title", id: "wod-daily" }, "WOD du jour"), + h("p", { class: "wod-format__label" }, formatLabel(format)), + h("p", { class: "muted" }, formatHint(format)), + h("ol", { class: "wod-moves" }, session.exercises.map((x) => { + const r = resolveExercise(x); + return h("li", { class: "wod-move" }, + h("div", { class: "wod-move__main" }, h("span", { class: "wod-move__reps num" }, x.reps), h("a", { class: "wod-move__name", href: href.libraryItem(/** @type {string} */ (x.ref)) }, r.name)), + x.note && h("p", { class: "wod-move__note" }, x.note)); + })), + !state.profile.kit && h("p", { class: "coach-note coach-note--plain" }, "Sans matériel coché dans ton profil, le WOD reste au poids du corps et à la course. ", + h("a", { href: href.profile() }, "Cocher mon matériel")), + h("div", { class: "btn-stack" }, + state.program + ? h("button", { type: "button", class: "btn btn--primary btn--block", on: { click: doToday } }, pending ? "Reprendre ce WOD" : "Faire aujourd'hui") + : h("p", { class: "muted" }, "Crée d'abord ton programme : le WOD s'y ajoutera, hors rotation."), + !pending && h("button", { type: "button", class: "btn btn--ghost btn--block", on: { click: () => { draw = draw >= 99 ? 1 : draw + 1; nav.set(href.wods(draw)); paint(); } } }, "Un autre"))); + }; + paint(); + return box; +} + +/** + * @param {{store: import("../store.js").Store, nav: import("../router.js").Navigation, today: () => string, query: string}} ctx * @returns {import("../router.js").Screen} */ -export function wodCatalogScreen({ store, nav }) { +export function wodCatalogScreen({ store, nav, today, query }) { const state = store.getState(); const node = h("div", { class: "screen" }, - screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "WOD", title: "Références", - sub: "Les WOD que tout le monde connaît : fais-les, note ton score, et bats ton record la fois suivante." }), + screenHeader({ back: { label: "Accueil", onClick: () => nav.back(href.home()) }, kicker: "Cross-training", title: "WOD", + sub: "Le WOD du jour, composé par l'app, et les WOD que tout le monde connaît : fais-les, note ton score, bats ton record." }), + dailyWod({ store, nav, today, query }), Object.entries(BENCHMARK_FAMILIES).map(([family, label]) => { const list = BENCHMARKS.filter((b) => b.family === family); return [ @@ -44,7 +99,7 @@ export function wodCatalogScreen({ store, nav }) { h("span", { class: "chevron", "aria-hidden": "true" }))); }))]; })); - return { node, title: "WOD de référence" }; + return { node, title: "WOD" }; } /** @@ -53,7 +108,7 @@ export function wodCatalogScreen({ store, nav }) { */ export function wodItemScreen({ store, nav, today, id }) { const b = benchmark(id); - const back = { label: "Références", onClick: () => nav.back(href.wods()) }; + const back = { label: "WOD", onClick: () => nav.back(href.wods()) }; if (!b) return { title: "WOD introuvable", node: h("div", { class: "screen" }, screenHeader({ back, title: "Introuvable", sub: "Ce WOD n'est pas dans le catalogue." })) }; const state = store.getState(); const format = /** @type {import("../../domain/wod.js").WodFormat} */ (b.session.format); diff --git a/docs/feuille-de-route.md b/docs/feuille-de-route.md index 68251dc..b095ba3 100644 --- a/docs/feuille-de-route.md +++ b/docs/feuille-de-route.md @@ -66,7 +66,7 @@ briques, dans cet ordre, après R2, 1i et l'extension du format WOD (Chelsea, Ba | --- | --- | --- | | 5a | Matériel structuré dans le profil (cases à cocher), filtre « ce que je peux faire » dans la bibliothèque | ✅ | | 5b | Vérification des propositions : équilibre, volume par muscle, récupération, matériel, variété d'un WOD ; alertes dans l'aperçu et dans la réponse MCP, adoption libre (ADR 0011) | ✅ | -| 5c | Générateur de « WOD du jour » hors ligne : format, durée, modalités variées, matériel, historique | ⏳ | +| 5c | Générateur de « WOD du jour » hors ligne : format, durée, modalités variées, matériel, historique ; tirage dans l'adresse | ✅ | | 5d | Progression et décharge : semaine de décharge proposée, règle pour la charge par série | ⏳ | ## Retours d'usage du 2026-11-22 diff --git a/docs/glossaire/wod.md b/docs/glossaire/wod.md index e7b7c58..f8bc1ef 100644 --- a/docs/glossaire/wod.md +++ b/docs/glossaire/wod.md @@ -22,4 +22,8 @@ suivi par son nom et son format, d'une séance à l'autre. En séance, l'app affiche un chrono adapté qui bipe aux changements de phase, puis fait noter le score. Voir l'ADR 0010. +Le **WOD du jour** est composé par l'app, hors ligne (`generateWod`) : un format tiré au sort, deux ou trois +mouvements de modalités différentes (cardio, gymnastique, charges), faisables avec le matériel coché et pas +faits les deux jours d'avant. Le même jour donne le même WOD ; « Un autre » passe au tirage suivant (`#/wod?tirage=2`). + Voir aussi : [Score](score.md), [Séance](seance.md) diff --git a/server/static.js b/server/static.js index 8a4ff34..d2b6d50 100644 --- a/server/static.js +++ b/server/static.js @@ -34,12 +34,17 @@ const COMPRESSIBLE = /^(text\/|application\/json|application\/manifest\+json|ima /** Comme Caddy : en dessous, la compression ne fait rien gagner. */ const MIN_COMPRESS = 512; +/** zstd n'existe dans Node qu'à partir de 22.15 (l'image de production a Node 24). */ +export const HAS_ZSTD = typeof (/** @type {any} */ (zlib)).zstdCompressSync === "function"; + /** - * Encodage choisi d'après Accept-Encoding : zstd, sinon gzip, sinon aucun. + * Encodage choisi d'après Accept-Encoding : zstd (si ce Node le sait), sinon gzip, + * sinon aucun. * @param {string|undefined} header + * @param {boolean} [zstd] ce Node sait compresser en zstd * @returns {"zstd"|"gzip"|null} */ -export function pickEncoding(header) { +export function pickEncoding(header, zstd = HAS_ZSTD) { /** @type {Map} */ const accepted = new Map(); for (const part of (header ?? "").split(",")) { @@ -49,7 +54,7 @@ export function pickEncoding(header) { accepted.set(name, q ? Number(q[1]) : 1); } const ok = (/** @type {string} */ name) => (accepted.get(name) ?? accepted.get("*") ?? 0) > 0; - if (ok("zstd")) return "zstd"; + if (zstd && ok("zstd")) return "zstd"; if (ok("gzip")) return "gzip"; return null; } diff --git a/tests/browser/parcours.cjs b/tests/browser/parcours.cjs index 541451c..1d82aa9 100644 --- a/tests/browser/parcours.cjs +++ b/tests/browser/parcours.cjs @@ -42,6 +42,8 @@ const server = http.createServer((req, res) => { }); let failures = 0; +/** Les derniers messages de la page (console, erreurs), pour le diagnostic d'un arrêt. */ +const pageLog = []; /** Page en cours, pour une capture si le parcours s'interrompt. */ let lastPage = null; /** @param {string} scheme @param {boolean} cond @param {string} msg */ @@ -69,7 +71,8 @@ function check(scheme, cond, msg) { const page = await ctx.newPage(); lastPage = page; const errors = []; - page.on("pageerror", (e) => errors.push(String(e))); + page.on("pageerror", (e) => { errors.push(String(e)); pageLog.push("pageerror: " + String(e)); }); + page.on("console", (m) => pageLog.push(`${m.type()}: ${m.text()}`.slice(0, 300))); page.on("console", (m) => { if (m.type() === "error") errors.push(m.text()); }); const ok = (cond, msg) => check(scheme, cond, msg); const shot = (name, full = false) => page.screenshot({ path: `${outDir}/${scheme}-${name}.png`, fullPage: full }); @@ -576,7 +579,19 @@ function check(scheme, cond, msg) { await go("#/"); await page.getByRole("link", { name: /^WOD/ }).click(); await settle(); - ok(await page.locator("h1").textContent() === "Références" && await page.getByRole("link", { name: /Fran · For Time/ }).isVisible(), "catalogue des WOD de référence"); + ok(await page.locator("h1").textContent() === "WOD" && await page.getByRole("link", { name: /Fran · For Time/ }).isVisible(), "catalogue des WOD de référence"); + // WOD du jour (lot 5c) : composé par l'app, un autre tirage dans l'adresse, le même en rouvrant. + const daily = page.locator(".wod-daily"); + ok(await daily.getByRole("heading", { name: "WOD du jour" }).isVisible() && await daily.locator(".wod-move").count() >= 2, "WOD du jour composé par l'app"); + const firstDraw = await daily.locator(".wod-moves").innerText(); + await daily.getByRole("button", { name: "Un autre" }).click(); + ok(page.url().endsWith("#/wod?tirage=2"), "un autre tirage, dans l'adresse : " + page.url().split("#")[1]); + const secondDraw = await daily.locator(".wod-moves").innerText(); + await shot("24a-wod-du-jour"); + await go("#/wod?tirage=2"); + ok(await page.locator(".wod-daily .wod-moves").innerText() === secondDraw, "même tirage, même WOD"); + await go("#/wod"); + ok(await page.locator(".wod-daily .wod-moves").innerText() === firstDraw, "tirage 1 retrouvé"); await page.getByRole("link", { name: /Cindy · AMRAP 20 min/ }).click(); await settle(); ok(page.url().endsWith("#/wod/cindy") && await page.getByText("Scaled : ").isVisible(), "fiche de Cindy, avec sa variante scaled"); @@ -631,7 +646,17 @@ function check(scheme, cond, msg) { process.exit(failures ? 1 : 0); })().catch(async (e) => { console.error(e); - if (lastPage) await lastPage.screenshot({ path: `${outDir}/erreur.png`, fullPage: true }).catch(() => {}); + if (lastPage) { + await lastPage.screenshot({ path: `${outDir}/erreur.png`, fullPage: true }).catch(() => {}); + // De quoi comprendre une page restée vide : état du document, scripts chargés, erreurs. + const diag = await lastPage.evaluate(() => ({ + url: location.href, readyState: document.readyState, bodyChildren: document.body?.children.length ?? null, + scripts: performance.getEntriesByType("resource").filter((r) => /\.js$/.test(r.name)).length, + slowest: performance.getEntriesByType("resource").sort((a, b) => b.duration - a.duration).slice(0, 3).map((r) => `${r.name.split("/").pop()} ${Math.round(r.duration)} ms`), + })).catch((err) => ({ evaluate: String(err) })); + console.error("Diagnostic :", JSON.stringify(diag)); + console.error("Messages de la page :", JSON.stringify(pageLog.slice(-15))); + } process.exit(1); }); diff --git a/tests/browser/run.sh b/tests/browser/run.sh new file mode 100644 index 0000000..144ef65 --- /dev/null +++ b/tests/browser/run.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# Lancé par make test-browser dans le conteneur Playwright, sur son propre réseau +# (--network bridge) : il a ses interfaces à lui. Avant, le conteneur partageait le réseau de la machine +# (--network host) : quand d'autres conteneurs démarraient ou s'arrêtaient, Chromium +# voyait les interfaces changer et abandonnait ses chargements +# (net::ERR_NETWORK_CHANGED, page restée vide après un rechargement). Sans réseau du +# tout (--network none), Chromium se croit hors ligne et la synchro ne part pas. +# Le vrai serveur (synchro, MCP, site assemblé) tourne donc ici, à côté du navigateur. +set -eu +port=8787 +PORT="$port" SITE_DIR=/site DATA_DIR=/data PUBLIC_URL="http://127.0.0.1:$port" \ + node /repo/server/main.js >/data/server.log 2>&1 & +pid=$! +trap 'kill $pid 2>/dev/null || true' EXIT +# Attendre que le serveur réponde (pas de curl dans l'image : node suffit). +node -e ' + const url = process.argv[1]; + const until = Date.now() + 10000; + (async function wait() { + try { if ((await fetch(url)).ok) process.exit(0); } catch {} + if (Date.now() > until) process.exit(1); + setTimeout(wait, 100); + })();' "http://127.0.0.1:$port/" || { echo "Le serveur ne démarre pas :"; cat /data/server.log; exit 1; } +node /tests/parcours.cjs /repo/app /shots "http://127.0.0.1:$port/" diff --git a/tests/domain/wod-generator.test.js b/tests/domain/wod-generator.test.js new file mode 100644 index 0000000..3c572b0 --- /dev/null +++ b/tests/domain/wod-generator.test.js @@ -0,0 +1,61 @@ +// Le générateur de WOD du jour (lot 5c) : déterministe, valide, faisable avec le +// matériel, varié, sans répéter les mouvements récents. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { generateWod, WOD_MOVES } from "../../app/domain/wod-generator.js"; +import { EXERCISES } from "../../app/domain/exercises.js"; +import { KIT, canDo } from "../../app/domain/kit.js"; +import { validateProgram } from "../../app/domain/program.js"; +import { checkProgram } from "../../app/domain/checks.js"; +import { DEFAULT_PROFILE } from "../../app/domain/profile.js"; + +const KITS = [undefined, [], Object.keys(KIT), ["dumbbells", "pullup-bar"], ["barbell", "rower"], ["kettlebell", "jump-rope", "box"]]; +const DAYS = ["2026-11-23", "2026-11-24", "2026-12-01", "2027-03-15"]; +const modality = (/** @type {string} */ ref) => WOD_MOVES.find((x) => x.ref === ref)?.m; + +test("chaque mouvement du générateur est dans la bibliothèque", () => { + for (const x of WOD_MOVES) assert.ok(EXERCISES[x.ref], x.ref); +}); + +test("le même jour, le même matériel et le même tirage donnent le même WOD ; un autre tirage, un autre", () => { + const a = generateWod({ today: "2026-11-23", kit: Object.keys(KIT) }); + assert.deepEqual(generateWod({ today: "2026-11-23", kit: Object.keys(KIT) }), a); + const others = [2, 3, 4, 5].map((draw) => JSON.stringify(generateWod({ today: "2026-11-23", draw, kit: Object.keys(KIT) }).exercises)); + assert.ok(others.some((x) => x !== JSON.stringify(a.exercises))); + assert.equal(a.name, "WOD du jour · 23 nov."); + assert.equal(generateWod({ today: "2026-11-23", draw: 2 }).name, "WOD du jour · 23 nov. (2)"); +}); + +test("toujours valide, ponctuel, faisable avec le matériel, sans alerte des règles de l'app", () => { + for (const kit of KITS) for (const today of DAYS) for (let draw = 1; draw <= 8; draw++) { + const session = generateWod({ today, draw, kit }); + const program = { name: "P", sessions: [{ key: "J1", ...session }] }; + const where = `${JSON.stringify(kit)} ${today} #${draw}`; + assert.deepEqual(validateProgram(program), [], where); + assert.equal(session.oneOff, true); + assert.ok(session.exercises.length >= 2 && session.exercises.length <= 3, where); + assert.equal(new Set(session.exercises.map((x) => x.ref)).size, session.exercises.length, where + " : doublon"); + for (const x of session.exercises) assert.ok(canDo(/** @type {string} */ (x.ref), kit ?? []), `${where} : ${x.ref}`); + assert.deepEqual(checkProgram(program, { ...DEFAULT_PROFILE, kit: /** @type {any} */ (kit) }), [], where); + } +}); + +test("des modalités différentes quand le matériel le permet", () => { + let mixed = 0, total = 0; + for (const today of DAYS) for (let draw = 1; draw <= 10; draw++) { + const s = generateWod({ today, draw, kit: Object.keys(KIT) }); + total++; + if (new Set(s.exercises.map((x) => modality(/** @type {string} */ (x.ref)))).size === s.exercises.length) mixed++; + } + assert.equal(mixed, total, "salle complète : jamais deux mouvements de la même modalité"); +}); + +test("pas un mouvement des deux derniers jours, tant qu'il en reste d'autres ; aujourd'hui ne compte pas", () => { + const kit = Object.keys(KIT); + const first = generateWod({ today: "2026-11-23", kit }); + const done = (/** @type {string} */ date) => [{ date, exercises: first.exercises.map((x) => ({ id: /** @type {string} */ (x.ref) })) }]; + const next = generateWod({ today: "2026-11-23", kit, sessions: done("2026-11-22") }); + for (const x of next.exercises) assert.ok(!first.exercises.some((y) => y.ref === x.ref), `${x.ref} refait`); + assert.deepEqual(generateWod({ today: "2026-11-23", kit, sessions: done("2026-11-23") }), first, "faire le WOD du jour ne le change pas"); + assert.deepEqual(generateWod({ today: "2026-11-23", kit, sessions: done("2026-11-19") }), first, "il y a quatre jours : sans effet"); +}); diff --git a/tests/server/static.test.js b/tests/server/static.test.js index 35e3e6c..5ebbaa2 100644 --- a/tests/server/static.test.js +++ b/tests/server/static.test.js @@ -50,7 +50,10 @@ test("site : compression zstd ou gzip des textes, pas des polices", async () => const f = /** @type {any} */ (await get("/police.woff2", "gzip")); assert.equal(f.headers["content-encoding"], undefined); assert.equal(pickEncoding("gzip;q=0, zstd;q=0"), null); - assert.equal(pickEncoding("*"), "zstd"); + assert.equal(pickEncoding("*", true), "zstd"); + // Un Node sans zstd (avant 22.15) : gzip, plutôt qu'une erreur 500. + assert.equal(pickEncoding("zstd, gzip", false), "gzip"); + assert.equal(pickEncoding("zstd", false), null); assert.equal(pickEncoding(undefined), null); } finally { await s.close();