import { EMPTY_MODEL, type LearnerModel, type Trace, modelFrom } from "../practice/model.ts"; import type { History } from "../practice/history.ts"; import type { Memory } from "../practice/memory.ts"; import { EMPTY_STREAK, PAST_WEEKS, type PastWeek, type Streak } from "./streak.ts"; import { courseById, DEFAULT_COURSE, type Course } from "../../course/registry.ts"; /** * Progress on more than one device — how the pieces combine. * * THE RULE THAT MAKES IT CORRECT: a device only ever stores what IT observed. * The server keeps each device's contribution separately, and a page shows * this device's own record combined with the others'. Nothing fetched is ever * written back into the local record, so however often two devices sync, * nothing is counted twice — the failure a "merge everything into everything" * sync produces on its second round. * * Each kind of record combines the way its meaning demands: * * model SUM. A trace is counts of questions asked and missed; two * devices answered different questions, so their counts add. * history UNION. The questions seen recently, to avoid repeats. * memory NEWEST PER QUESTION. When each question is due again; the device * that answered it last knows where it stands (`combineMemories`). * streak The record with the latest practice day, and the best of all. * A streak stores no list of dates (on purpose — see streak.ts), * so two devices practising on alternate days cannot be stitched * into one run; the newest record is the honest answer. * saved NOT combined here. The word list is edited in place — a removal * must stay removed — so the newest list is adopted as this * device's own (`newestSaved`), rather than unioned into a list * that would bring deleted words back. * focus NOT combined either: «Meine Situationen» is a choice, not a * count. A device that has not chosen adopts the newest choice * from another; a device that has chosen keeps its own, so a * second phone never asks again and never overrides the first. * bridge The same rule as `focus`, for the same reason: how good the * difficulty learner's German is and how hard they want practice are * answers, not counts. Adopted where nothing is answered here. * profile Why they are learning, and whether the setup is done. An * answer too, but one that carries when it was given, so the * NEWER record is adopted (`newerProfile`): a reason changed on * the phone reaches the laptop, and the setup finished on one is * not offered again on the other. */ export type SyncKey = "model" | "history" | "memory" | "streak" | "saved" | "focus" | "profile" | "bridge" | "difficulty"; export const SYNC_KEYS: readonly SyncKey[] = ["model", "history", "memory", "streak", "saved", "focus", "profile", "bridge", "difficulty"]; /** * The records that are about the PERSON rather than a course: practising any * course on a day keeps the same streak going. Every other key is one * course's record and is only ever combined with the same course's. */ export const LEARNER_KEYS: readonly SyncKey[] = ["streak"]; /** * The request header that names the course a device is syncing. * * A header beside `x-heidi-device`, and optional: a tab opened before courses * existed sends none and is syncing the default course, which is the only * one it could have been practising. */ export const COURSE_HEADER = "x-heidi-course"; /** The course a sync request is about, or null when it names one this build does not have. */ export function courseOfRequest(request: Request): Course | null { const named = request.headers.get(COURSE_HEADER); return named === null ? DEFAULT_COURSE : (courseById(named) ?? null); } function addTraces(a: Record, b: Record): Record { const out: Record = { ...a }; for (const [k, t] of Object.entries(b)) { const cur = out[k]; out[k] = cur ? { asked: cur.asked + t.asked, missed: cur.missed + t.missed } : t; } return out; } export function sumModels(models: readonly LearnerModel[]): LearnerModel { return models.reduce( (acc, m) => modelFrom((name) => addTraces(acc[name], m[name])), EMPTY_MODEL, ); } export function unionHistory(histories: readonly History[]): History { return [...new Set(histories.flat())]; } export function combineStreaks(streaks: readonly Streak[]): Streak { if (streaks.length === 0) return EMPTY_STREAK; const newest = [...streaks].sort( (a, b) => (b.lastDay ?? "").localeCompare(a.lastDay ?? "") || b.current - a.current, )[0]; return { ...newest, best: Math.max(...streaks.map((s) => s.best), newest.current), past: combinePast(streaks, newest.week) }; } /** * The finished weeks of every device, one entry per week. Two devices that * each practised part of a week cannot be added (the days may be the same * days), so the fuller count stands: a lower bound, never an invention. */ function combinePast(streaks: readonly Streak[], currentWeek: string | null): PastWeek[] { const byWeek = new Map(); const consider = (p: PastWeek) => { if (currentWeek !== null && p.week >= currentWeek) return; const have = byWeek.get(p.week); if (!have || p.days > have.days) byWeek.set(p.week, p); }; for (const s of streaks) { s.past.forEach(consider); // A device last used in an earlier week still holds that week as its current one. if (s.week !== null && s.weekDays > 0) consider({ week: s.week, days: s.weekDays, goal: s.weekGoal }); } return [...byWeek.values()].sort((a, b) => b.week.localeCompare(a.week)).slice(0, PAST_WEEKS); } /** One device's pushed record of one key, as the server returns it. */ export type Snapshot = { value: T; updatedAt: string }; /** * The saved list to keep: another device's, if it changed after this one last * did; otherwise this device's own. Returns null when nothing should change. */ export function newestSaved(ownChangedAt: string | null, others: readonly Snapshot[]): T | null { const newest = [...others].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0]; if (!newest) return null; return ownChangedAt === null || newest.updatedAt > ownChangedAt ? newest.value : null; } /** * A record from another device that is newer than this device's own, or null * when this device's is the newest (or nothing came). Used for the profile. */ export function newerRecord(own: T | null, others: readonly T[]): T | null { const newest = [...others].sort((a, b) => b.at.localeCompare(a.at))[0]; if (!newest) return null; return own === null || newest.at > own.at ? newest : null; } // --------------------------------------------------------------------------- // What the browser keeps about syncing // --------------------------------------------------------------------------- /** * Whether this browser syncs, and as which device. * * WITH AN ACCOUNT, PROGRESS FOLLOWS THE ACCOUNT (the default since * 2026-11-26). It was off until switched on in the settings, and a person who * made an account to have their progress on their phone and their laptop had * an account that did not do that, with nothing saying so. Now: * * - The sign-in and sign-up screens say, in one line, what is stored with * the account, and note in this record that the line was shown * (`informed`). Nothing is sent by that. * - Once that browser is signed in, sync switches on (`by: "default"`), and * the personal page repeats the line with one tap to keep everything on * this device only. Either answer removes the notice. * - A learner who was ALREADY signed in when the default changed never saw * the line: they have no record here and are asked once, exactly as * before. Nobody is switched silently. * - Signed out, nothing is ever sent, whatever this record says. * * `device` is random and names nothing but "this browser"; `savedChangedAt` * is when the saved list last changed HERE, so a newer list from elsewhere * can be told from an older one. */ export type SyncSetting = { on: boolean; device: string; savedChangedAt: string | null; /** The sign-in screen showed what is stored with an account; no choice has been made yet. */ informed?: boolean; /** On because that is the default, not because of a tap: the page still owes the notice. */ by?: "default"; }; const DEVICE = /^[A-Za-z0-9_-]{16,64}$/; export function decodeSyncSetting(raw: string): SyncSetting | null { try { const o = JSON.parse(raw) as Record; if (!o || typeof o !== "object" || typeof o.device !== "string" || !DEVICE.test(o.device)) return null; const on = o.on === true; return { on, device: o.device, savedChangedAt: typeof o.savedChangedAt === "string" ? o.savedChangedAt : null, ...(o.informed === true && !on ? { informed: true } : {}), ...(o.by === "default" && on ? { by: "default" as const } : {}), }; } catch { return null; } } /** * Where this browser stands on syncing, for a signed-in learner. * * ask never chose and never saw the line: ask once * pending saw the line at sign-in: switch on now, by default * told on by default: show the line and the one tap back * on, off their own choice */ export type SyncStance = "ask" | "pending" | "told" | "on" | "off"; export function syncStance(setting: SyncSetting | null): SyncStance { if (!setting) return "ask"; if (setting.on) return setting.by === "default" ? "told" : "on"; return setting.informed ? "pending" : "off"; } export function isDeviceId(value: unknown): value is string { return typeof value === "string" && DEVICE.test(value); } /** * The other devices' records, as last fetched — a cache, so a page shows the * combined view without waiting for the network, and a reload offline still * shows everything. Never merged into this device's own records. */ export type OtherDevices = { model: LearnerModel[]; history: History[]; memory: Memory[]; streak: Streak[] }; export const NO_OTHERS: OtherDevices = { model: [], history: [], memory: [], streak: [] }; export function decodeOthers( raw: string, decode: { model(raw: string): LearnerModel; history(raw: string): History | null; memory(raw: string): Memory | null; streak(raw: string): Streak | null; }, ): OtherDevices | null { try { const o = JSON.parse(raw) as Record; if (!o || typeof o !== "object") return null; const each = (v: unknown, d: (raw: string) => T | null): T[] => Array.isArray(v) ? v.map((x) => d(JSON.stringify(x))).filter((x): x is T => x !== null) : []; return { model: each(o.model, decode.model), history: each(o.history, decode.history), memory: each(o.memory, decode.memory), streak: each(o.streak, decode.streak), }; } catch { return null; } }