mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Add progress export/import (JSON file) with strict import validation and change events
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -287,6 +287,26 @@ pre {
|
|||||||
accent-color: var(--accent);
|
accent-color: var(--accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.setting-group {
|
||||||
|
margin: 1rem 0;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setting-group legend {
|
||||||
|
padding: 0 0.25rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setting-group .hint {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setting-group .btn {
|
||||||
|
margin: 0.25rem 0.5rem 0.25rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
.author-link {
|
.author-link {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -4,6 +4,13 @@
|
|||||||
|
|
||||||
const STORAGE_KEY = 'progress';
|
const STORAGE_KEY = 'progress';
|
||||||
const SCHEMA_VERSION = 1;
|
const SCHEMA_VERSION = 1;
|
||||||
|
const ID_PATTERN = /^(?!__proto__$)[A-Za-z0-9_-]{1,64}$/;
|
||||||
|
const MAX_ENTRIES = 500;
|
||||||
|
const MAX_LEVEL_XP = 100000;
|
||||||
|
|
||||||
|
function isPlainObject(value) {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
|
||||||
// Badges de progression : règle déclarative évaluée sur l'état complet.
|
// Badges de progression : règle déclarative évaluée sur l'état complet.
|
||||||
const BADGES = [
|
const BADGES = [
|
||||||
@@ -14,12 +21,13 @@ const BADGES = [
|
|||||||
{ id: 'streak_7', test: (state) => state.streak.best >= 7 },
|
{ id: 'streak_7', test: (state) => state.streak.best >= 7 },
|
||||||
];
|
];
|
||||||
|
|
||||||
export class ProgressStore {
|
export class ProgressStore extends EventTarget {
|
||||||
#store;
|
#store;
|
||||||
#state = null;
|
#state = null;
|
||||||
|
|
||||||
/** @param {{get: (key: string) => Promise<any>, set: (key: string, value: any) => Promise<void>}} store */
|
/** @param {{get: (key: string) => Promise<any>, set: (key: string, value: any) => Promise<void>}} store */
|
||||||
constructor(store) {
|
constructor(store) {
|
||||||
|
super();
|
||||||
this.#store = store;
|
this.#store = store;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,20 +111,24 @@ export class ProgressStore {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Importe une progression exportée. Fusion par défaut (union, jamais de perte) : pratique
|
* Importe une progression exportée. Fusion par défaut (union, jamais de perte) : pratique
|
||||||
* pour réunir deux appareils. `replace` écrase tout.
|
* pour réunir deux appareils. `replace` écrase tout. Lève une erreur si le contenu est invalide.
|
||||||
*/
|
*/
|
||||||
async import(json, { mode = 'merge' } = {}) {
|
async import(json, { mode = 'merge' } = {}) {
|
||||||
const incoming = this.#parseImport(json);
|
const incoming = this.#parseImport(json);
|
||||||
const state = this.#requireState();
|
const state = this.#requireState();
|
||||||
|
const before = Object.keys(state.completedLevels).length;
|
||||||
if (mode === 'replace') {
|
if (mode === 'replace') {
|
||||||
this.#state = incoming;
|
this.#state = incoming;
|
||||||
} else {
|
} else {
|
||||||
this.#merge(state, incoming);
|
this.#merge(state, incoming);
|
||||||
}
|
}
|
||||||
await this.#save();
|
await this.#save();
|
||||||
return this.snapshot();
|
// `addedLevels` : niveaux nouveaux pour cet appareil (pour informer l'apprenant).
|
||||||
|
const after = Object.keys(this.#requireState().completedLevels).length;
|
||||||
|
return { ...this.snapshot(), addedLevels: Math.max(0, after - before) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Valide strictement un fichier venant de l'extérieur (jamais fiable : fichier édité, jeton volé…). */
|
||||||
#parseImport(json) {
|
#parseImport(json) {
|
||||||
let data;
|
let data;
|
||||||
try {
|
try {
|
||||||
@@ -124,15 +136,34 @@ export class ProgressStore {
|
|||||||
} catch {
|
} catch {
|
||||||
throw new Error('Invalid progress file: not JSON');
|
throw new Error('Invalid progress file: not JSON');
|
||||||
}
|
}
|
||||||
|
if (!isPlainObject(data) || data.version !== SCHEMA_VERSION) {
|
||||||
|
throw new Error('Invalid progress file: unsupported format');
|
||||||
|
}
|
||||||
|
const { completedLevels, badges, streak } = data;
|
||||||
const valid =
|
const valid =
|
||||||
data?.version === SCHEMA_VERSION &&
|
isPlainObject(completedLevels) &&
|
||||||
typeof data.completedLevels === 'object' &&
|
Object.entries(completedLevels).length <= MAX_ENTRIES &&
|
||||||
typeof data.badges === 'object' &&
|
Object.entries(completedLevels).every(
|
||||||
typeof data.streak === 'object';
|
([id, level]) =>
|
||||||
|
ID_PATTERN.test(id) &&
|
||||||
|
isPlainObject(level) &&
|
||||||
|
Number.isFinite(level.xp) &&
|
||||||
|
level.xp >= 0 &&
|
||||||
|
level.xp <= MAX_LEVEL_XP &&
|
||||||
|
typeof level.completedAt === 'string',
|
||||||
|
) &&
|
||||||
|
isPlainObject(badges) &&
|
||||||
|
Object.entries(badges).length <= MAX_ENTRIES &&
|
||||||
|
Object.entries(badges).every(([id, at]) => ID_PATTERN.test(id) && typeof at === 'string') &&
|
||||||
|
isPlainObject(streak) &&
|
||||||
|
Number.isInteger(streak.current) &&
|
||||||
|
Number.isInteger(streak.best) &&
|
||||||
|
(streak.lastDay === null || typeof streak.lastDay === 'string');
|
||||||
if (!valid) {
|
if (!valid) {
|
||||||
throw new Error('Invalid progress file: unsupported format');
|
throw new Error('Invalid progress file: unsupported format');
|
||||||
}
|
}
|
||||||
return data;
|
// On ne reprend que les champs connus.
|
||||||
|
return { version: SCHEMA_VERSION, completedLevels, badges, streak: { current: streak.current, best: streak.best, lastDay: streak.lastDay } };
|
||||||
}
|
}
|
||||||
|
|
||||||
#merge(state, incoming) {
|
#merge(state, incoming) {
|
||||||
@@ -182,6 +213,7 @@ export class ProgressStore {
|
|||||||
|
|
||||||
async #save() {
|
async #save() {
|
||||||
await this.#store.set(STORAGE_KEY, this.#state);
|
await this.#store.set(STORAGE_KEY, this.#state);
|
||||||
|
this.dispatchEvent(new Event('change'));
|
||||||
}
|
}
|
||||||
|
|
||||||
#requireState() {
|
#requireState() {
|
||||||
|
|||||||
+8
-1
@@ -86,5 +86,12 @@
|
|||||||
"settings.testSound": "Test the sound",
|
"settings.testSound": "Test the sound",
|
||||||
"settings.testVoice": "Test the voice",
|
"settings.testVoice": "Test the voice",
|
||||||
"settings.voiceOffNotice": "Turn the voice on in the settings first.",
|
"settings.voiceOffNotice": "Turn the voice on in the settings first.",
|
||||||
"settings.voiceRate": "Voice speed"
|
"settings.voiceRate": "Voice speed",
|
||||||
|
"backup.title": "Progress backup",
|
||||||
|
"backup.help": "A file to keep or copy to another device. Nothing is sent over the Internet.",
|
||||||
|
"backup.export": "Export my progress",
|
||||||
|
"backup.import": "Import progress",
|
||||||
|
"backup.imported": "Progress imported: {n} new level(s).",
|
||||||
|
"backup.importFailed": "This file is not a valid PyQuest progress file.",
|
||||||
|
"backup.exported": "Progress exported."
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-1
@@ -86,5 +86,12 @@
|
|||||||
"settings.testSound": "Tester le son",
|
"settings.testSound": "Tester le son",
|
||||||
"settings.testVoice": "Tester la voix",
|
"settings.testVoice": "Tester la voix",
|
||||||
"settings.voiceOffNotice": "Active d'abord la voix dans les réglages.",
|
"settings.voiceOffNotice": "Active d'abord la voix dans les réglages.",
|
||||||
"settings.voiceRate": "Vitesse de la voix"
|
"settings.voiceRate": "Vitesse de la voix",
|
||||||
|
"backup.title": "Sauvegarde de la progression",
|
||||||
|
"backup.help": "Un fichier à garder ou à copier sur un autre appareil. Rien n'est envoyé sur Internet.",
|
||||||
|
"backup.export": "Exporter ma progression",
|
||||||
|
"backup.import": "Importer une progression",
|
||||||
|
"backup.imported": "Progression importée : {n} nouveau(x) niveau(x).",
|
||||||
|
"backup.importFailed": "Ce fichier n'est pas une progression PyQuest valide.",
|
||||||
|
"backup.exported": "Progression exportée."
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -122,6 +122,8 @@ class App {
|
|||||||
this.#panel = new SettingsPanel(this.#i18n);
|
this.#panel = new SettingsPanel(this.#i18n);
|
||||||
this.#panel.addEventListener('change', (event) => this.#onSettingChange(event.detail));
|
this.#panel.addEventListener('change', (event) => this.#onSettingChange(event.detail));
|
||||||
this.#panel.addEventListener('test', (event) => this.#onTest(event.detail.kind));
|
this.#panel.addEventListener('test', (event) => this.#onTest(event.detail.kind));
|
||||||
|
this.#panel.addEventListener('export', () => this.#exportProgress());
|
||||||
|
this.#panel.addEventListener('import', (event) => this.#importProgress(event.detail.file));
|
||||||
|
|
||||||
document.getElementById('notebook-region').append(notebook.element);
|
document.getElementById('notebook-region').append(notebook.element);
|
||||||
document.getElementById('toast-region').append(toast.element);
|
document.getElementById('toast-region').append(toast.element);
|
||||||
@@ -267,6 +269,29 @@ class App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Télécharge la progression en JSON (Blob + lien temporaire : API standard, sans serveur). */
|
||||||
|
#exportProgress() {
|
||||||
|
const blob = new Blob([this.#progress.export()], { type: 'application/json' });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const link = el('a', { href: url, download: `pyquest-progress-${ProgressStore.dayKey(new Date())}.json` });
|
||||||
|
document.body.append(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
this.#toast.show(this.#i18n.t('backup.exported'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fusionne un fichier de progression (union : on ne perd jamais rien). */
|
||||||
|
async #importProgress(file) {
|
||||||
|
try {
|
||||||
|
const result = await this.#progress.import(await file.text());
|
||||||
|
await this.#renderMap();
|
||||||
|
this.#toast.show(this.#i18n.t('backup.imported', { n: result.addedLevels }));
|
||||||
|
} catch {
|
||||||
|
this.#toast.show(this.#i18n.t('backup.importFailed'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Échantillons des réglages : le clic est le geste utilisateur qui débloque le son. */
|
/** Échantillons des réglages : le clic est le geste utilisateur qui débloque le son. */
|
||||||
async #onTest(kind) {
|
async #onTest(kind) {
|
||||||
if (kind === 'sound') {
|
if (kind === 'sound') {
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ export class SettingsPanel extends EventTarget {
|
|||||||
this.#testButton('settings.testVoice', 'voice'),
|
this.#testButton('settings.testVoice', 'voice'),
|
||||||
this.#field('settings.voiceRate', 'range', { value: settings.voiceRate, min: 0.5, max: 2, step: 0.1, key: 'voiceRate', number: true }),
|
this.#field('settings.voiceRate', 'range', { value: settings.voiceRate, min: 0.5, max: 2, step: 0.1, key: 'voiceRate', number: true }),
|
||||||
this.#field('settings.author', 'checkbox', { value: settings.authorMode, key: 'authorMode' }),
|
this.#field('settings.author', 'checkbox', { value: settings.authorMode, key: 'authorMode' }),
|
||||||
|
this.#backupSection(),
|
||||||
settings.authorMode ? el('a', { class: 'btn author-link', href: 'author.html', text: t('settings.authorOpen') }) : null,
|
settings.authorMode ? el('a', { class: 'btn author-link', href: 'author.html', text: t('settings.authorOpen') }) : null,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -51,6 +52,34 @@ export class SettingsPanel extends EventTarget {
|
|||||||
this.#root.querySelector(`[data-setting="${key}"]`)?.focus();
|
this.#root.querySelector(`[data-setting="${key}"]`)?.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Sauvegarde manuelle de la progression : fichier JSON, sans serveur. */
|
||||||
|
#backupSection() {
|
||||||
|
const t = (key) => this.#i18n.t(key);
|
||||||
|
const fileId = uniqueId('import');
|
||||||
|
const input = el('input', {
|
||||||
|
id: fileId,
|
||||||
|
type: 'file',
|
||||||
|
accept: 'application/json,.json',
|
||||||
|
hidden: true,
|
||||||
|
onchange: (event) => {
|
||||||
|
const [file] = event.target.files;
|
||||||
|
event.target.value = '';
|
||||||
|
if (file) {
|
||||||
|
this.dispatchEvent(new CustomEvent('import', { detail: { file } }));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return el(
|
||||||
|
'fieldset',
|
||||||
|
{ class: 'setting-group' },
|
||||||
|
el('legend', { text: t('backup.title') }),
|
||||||
|
el('p', { class: 'hint', text: t('backup.help') }),
|
||||||
|
el('button', { type: 'button', class: 'btn', text: t('backup.export'), onclick: () => this.dispatchEvent(new Event('export')) }),
|
||||||
|
el('button', { type: 'button', class: 'btn', text: t('backup.import'), onclick: () => input.click() }),
|
||||||
|
input,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#testButton(labelKey, kind) {
|
#testButton(labelKey, kind) {
|
||||||
const button = el('button', {
|
const button = el('button', {
|
||||||
type: 'button',
|
type: 'button',
|
||||||
|
|||||||
@@ -417,6 +417,42 @@ test('carte de progression et badges : états en texte, badge obtenu à la fin d
|
|||||||
assert.deepEqual(errors, []);
|
assert.deepEqual(errors, []);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('sauvegarde : exporter la progression sur un appareil, l\'importer sur un autre', { skip, timeout: 120000 }, async () => {
|
||||||
|
const errors = [];
|
||||||
|
const open = async () => {
|
||||||
|
const page = await (await browser.newContext({ acceptDownloads: true })).newPage();
|
||||||
|
page.on('pageerror', (error) => errors.push(error.message));
|
||||||
|
await page.goto(base);
|
||||||
|
await page.waitForSelector('.explain', { timeout: 60000 });
|
||||||
|
return page;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Appareil A : termine le niveau 00 puis exporte.
|
||||||
|
const a = await open();
|
||||||
|
for (let i = 0; i < 5; i++) await a.locator('.notebook-action button').last().click();
|
||||||
|
await a.waitForSelector('.toast');
|
||||||
|
await a.locator('#settings-toggle').click();
|
||||||
|
const [download] = await Promise.all([a.waitForEvent('download'), a.getByRole('button', { name: 'Exporter ma progression' }).click()]);
|
||||||
|
assert.match(download.suggestedFilename(), /^pyquest-progress-\d{4}-\d{2}-\d{2}\.json$/);
|
||||||
|
const path = await download.path();
|
||||||
|
const content = readFileSync(path, 'utf8');
|
||||||
|
assert.ok('00-intro' in JSON.parse(content).completedLevels);
|
||||||
|
|
||||||
|
// Appareil B (profil vierge) : un fichier invalide est refusé, le bon est fusionné.
|
||||||
|
const b = await open();
|
||||||
|
await b.locator('#settings-toggle').click();
|
||||||
|
const input = b.locator('.settings input[type=file]');
|
||||||
|
await input.setInputFiles({ name: 'mauvais.json', mimeType: 'application/json', buffer: Buffer.from('{"version":1,"completedLevels":{"x":{"xp":"beaucoup"}}}') });
|
||||||
|
await b.waitForFunction(() => /pas une progression PyQuest valide/.test(document.querySelector('.toast-region')?.textContent ?? ''));
|
||||||
|
await input.setInputFiles({ name: 'progression.json', mimeType: 'application/json', buffer: Buffer.from(content) });
|
||||||
|
await b.waitForFunction(() => /1 nouveau\(x\) niveau/.test(document.querySelector('.toast-region')?.textContent ?? ''));
|
||||||
|
await b.keyboard.press('Escape');
|
||||||
|
await b.locator('#levels-toggle').click();
|
||||||
|
assert.match(await b.locator('.level-button.is-done').first().textContent(), /Terminé/);
|
||||||
|
assert.match(await b.textContent('.badge-count'), /1 badge\(s\) obtenu\(s\)/);
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
});
|
||||||
|
|
||||||
test('éditeur de niveaux (mode auteur) : écrire un niveau, le vérifier, l\'essayer, l\'exporter', { skip, timeout: 240000 }, async () => {
|
test('éditeur de niveaux (mode auteur) : écrire un niveau, le vérifier, l\'essayer, l\'exporter', { skip, timeout: 240000 }, async () => {
|
||||||
const { spawnSync } = await import('node:child_process');
|
const { spawnSync } = await import('node:child_process');
|
||||||
const { mkdtempSync, writeFileSync } = await import('node:fs');
|
const { mkdtempSync, writeFileSync } = await import('node:fs');
|
||||||
|
|||||||
@@ -22,4 +22,29 @@ assert.equal(merged.xp, 140); assert.equal(Object.keys(merged.completedLevels).l
|
|||||||
assert.equal(merged.streak.lastDay, '2026-10-20');
|
assert.equal(merged.streak.lastDay, '2026-10-20');
|
||||||
await assert.rejects(p2.import('{"version":99}'));
|
await assert.rejects(p2.import('{"version":99}'));
|
||||||
await assert.rejects(new ProgressStore(kv).completeLevel('x', 1));
|
await assert.rejects(new ProgressStore(kv).completeLevel('x', 1));
|
||||||
|
assert.equal(merged.addedLevels, 1);
|
||||||
|
// Fichier hostile ou corrompu : rejeté sans toucher à l'état
|
||||||
|
const good = JSON.parse(other.export());
|
||||||
|
const bad = [
|
||||||
|
{ ...good, completedLevels: { x: { xp: 'beaucoup', completedAt: 'a' } } },
|
||||||
|
{ ...good, completedLevels: { x: { xp: -5, completedAt: 'a' } } },
|
||||||
|
{ ...good, completedLevels: { x: { xp: 1e12, completedAt: 'a' } } },
|
||||||
|
{ ...good, completedLevels: JSON.parse('{"__proto__": {"xp": 1, "completedAt": "a"}}') },
|
||||||
|
{ ...good, completedLevels: { '../etc': { xp: 1, completedAt: 'a' } } },
|
||||||
|
{ ...good, badges: [] },
|
||||||
|
{ ...good, streak: { current: 'x', best: 1, lastDay: null } },
|
||||||
|
[],
|
||||||
|
null,
|
||||||
|
];
|
||||||
|
const xpBefore = p2.snapshot().xp;
|
||||||
|
for (const candidate of bad) {
|
||||||
|
await assert.rejects(p2.import(JSON.stringify(candidate)));
|
||||||
|
}
|
||||||
|
assert.equal(p2.snapshot().xp, xpBefore);
|
||||||
|
assert.equal(({}).xp, undefined);
|
||||||
|
// Un changement persisté est signalé (utilisé par la synchronisation)
|
||||||
|
let changes = 0;
|
||||||
|
p2.addEventListener('change', () => (changes += 1));
|
||||||
|
await p2.recordActivity(d('2026-10-21'));
|
||||||
|
assert.equal(changes, 1);
|
||||||
console.log('progress ok');
|
console.log('progress ok');
|
||||||
|
|||||||
Reference in New Issue
Block a user