dracosh 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +42 -20
  2. package/assets/sounds/badge-1.wav +0 -0
  3. package/assets/sounds/badge-2.wav +0 -0
  4. package/assets/sounds/badge-3.wav +0 -0
  5. package/assets/sounds/badge-4.wav +0 -0
  6. package/data/tips.json +31 -1361
  7. package/package.json +1 -1
  8. package/src/alerts.js +4 -3
  9. package/src/backup.js +95 -0
  10. package/src/cli.js +97 -16
  11. package/src/commands.js +7 -7
  12. package/src/judge.js +33 -12
  13. package/src/library.js +127 -0
  14. package/src/lock.js +63 -0
  15. package/src/manage.js +75 -0
  16. package/src/pause.js +23 -0
  17. package/src/progress.js +145 -53
  18. package/src/quiet.js +1 -1
  19. package/src/scheduler.js +38 -26
  20. package/src/session.js +128 -30
  21. package/src/settings.js +4 -9
  22. package/src/starter.js +38 -0
  23. package/src/store.js +55 -16
  24. package/src/tips.js +7 -24
  25. package/src/ui/AddCard.js +172 -0
  26. package/src/ui/AnswerInput.js +8 -5
  27. package/src/ui/App.js +211 -71
  28. package/src/ui/BadgeUnlock.js +50 -0
  29. package/src/ui/Badges.js +75 -17
  30. package/src/ui/Choice.js +33 -0
  31. package/src/ui/Companion.js +20 -35
  32. package/src/ui/Decks.js +49 -0
  33. package/src/ui/DieRoll.js +104 -0
  34. package/src/ui/Evolution.js +6 -5
  35. package/src/ui/Hatch.js +5 -4
  36. package/src/ui/Header.js +7 -6
  37. package/src/ui/Help.js +68 -0
  38. package/src/ui/Mascot.js +88 -38
  39. package/src/ui/Missed.js +6 -5
  40. package/src/ui/Preview.js +92 -17
  41. package/src/ui/Reset.js +72 -0
  42. package/src/ui/Settings.js +15 -11
  43. package/src/ui/Stats.js +10 -7
  44. package/src/ui/Summary.js +12 -5
  45. package/src/ui/TheOne.js +121 -0
  46. package/src/ui/icons.js +156 -24
  47. package/src/ui/kit.js +58 -1
  48. package/src/vacation.js +7 -2
  49. package/src/words.js +21 -14
  50. package/assets/sounds/badge.wav +0 -0
  51. package/src/ui/Tip.js +0 -25
package/src/session.js CHANGED
@@ -1,41 +1,95 @@
1
- import { directionsFor } from "./settings.js";
2
1
  import { closestCandidate, judge } from "./judge.js";
3
- import { addVacation, applyAnswer, applyOverrule, calendarMonth, cancelVacations, ensureProgress, missedOn, recordMiss, snapshot, undoMiss, vacationInfo } from "./progress.js";
4
- import { describeDue, grade, itemKey, pickNext } from "./scheduler.js";
2
+ import { addVacation, applyAnswer, applyCaughtUp, applyOverrule, calendarMonth, cancelVacations, ensureProgress, markBadgesSeen, missedOn, recordMiss, snapshot, undoMiss, unseenBadges, vacationInfo } from "./progress.js";
3
+ import { describeDue, grade, itemKey, nextDueAt, pickNext, startOfTomorrow } from "./scheduler.js";
5
4
  import { recordAnswer, saveState } from "./store.js";
6
5
  import { createTipDeck } from "./tips.js";
7
6
  import { dayKey } from "./dates.js";
8
- import { formatRange, parseVacation } from "./vacation.js";
7
+ import { PAUSE_HELP, parsePause } from "./pause.js";
8
+ import { formatRange } from "./vacation.js";
9
9
 
10
10
  const LABELS = { "en-pl": "EN → PL", "pl-en": "PL → EN" };
11
+
12
+ // the tag on the card's border: the language pair for a language deck, the deck's name otherwise
13
+ function labelOf(deck, direction) {
14
+ if (!deck) return LABELS[direction];
15
+ if (!deck.languages) return deck.name;
16
+ const { front, back } = deck.languages;
17
+ const [from, to] = direction === "en-pl" ? [front, back] : [back, front];
18
+ return `${from.toUpperCase()} → ${to.toUpperCase()}`;
19
+ }
11
20
  const COMBO_CHEER_EVERY = 5;
12
21
 
13
22
  // Quiz logic without any I/O of its own: words, settings and persistence are injected, the UI only renders what this returns.
14
- export function createSession({ loadWords, state, getSettings, save = saveState, now = Date.now, tipDeck = createTipDeck({ state }) }) {
23
+ // `loadAllWords` → [{ words, deck }] for every deck of yours: "all done for today" means the whole library.
24
+ export function createSession({ loadWords, loadAllWords, state, getSettings, save = saveState, now = Date.now, tipDeck = createTipDeck({ state }) }) {
15
25
  const rules = () => ({ skipWeekends: getSettings().skipWeekends });
16
26
  const totals = { asked: 0, correct: 0, combo: 0 };
17
27
  let lastNoteId = null;
28
+ let inTour = false; // the tour teaches one thing per card; tips on top of that are too much
18
29
  let lastWrong = null; // the latest wrong answer, until the next question: /correct can still overrule it
30
+ let current = { words: [], deck: null }; // the deck the last question came from
31
+
32
+ // When nothing is waiting in any of your decks before tomorrow, the day is done → { done, cheers }
33
+ async function settleDay() {
34
+ const decks = loadAllWords ? await loadAllWords() : [current].filter((d) => !d.deck?.tour);
35
+ const t = now();
36
+ for (const { words, deck } of decks) {
37
+ const directions = directionsOf(deck);
38
+ if (pickNext({ words, state, now: t, directions })) return { done: false, cheers: [] };
39
+ const due = nextDueAt({ words, state, now: t, directions });
40
+ if (due !== null && due < startOfTomorrow(t)) return { done: false, cheers: [] };
41
+ }
42
+ const { cheers } = applyCaughtUp(state, { goal: getSettings().dailyGoal, rules: rules(), now: t });
43
+ await save(state);
44
+ return { done: true, cheers };
45
+ }
46
+
47
+ // when the deck's next card is due, if nothing is waiting in it right now (null: something is)
48
+ function upNext() {
49
+ const { words, deck } = current;
50
+ if (deck?.tour || pickNext({ words, state, now: now(), directions: directionsOf(deck) })) return null;
51
+ return nextDueAt({ words, state, now: now(), directions: directionsOf(deck) });
52
+ }
19
53
 
20
54
  async function next() {
21
- const { words, cached } = await loadWords();
22
- const item = pickNext({ words, state, now: now(), lastNoteId, directions: directionsFor(getSettings().directions) });
23
- if (!item) throw new Error("No words to ask about.");
55
+ const { words, deck } = await loadWords();
56
+ current = { words, deck };
57
+ inTour = Boolean(deck?.tour);
58
+ const item = pickNext({ words, state, now: now(), lastNoteId, directions: directionsOf(deck), tour: deck?.tour });
59
+ // nothing to ask is a normal state, not an error: the UI shows a way on (a finished tour, a new
60
+ // deck) or when the next card is due. Done with everything for today counts as the daily goal.
61
+ if (!item) {
62
+ const empty = { empty: true, tour: Boolean(deck?.tour), count: words.length, nextDue: null, cheers: [], dayDone: false };
63
+ if (!deck?.tour && words.length) {
64
+ empty.nextDue = nextDueAt({ words, state, now: now(), directions: directionsOf(deck) });
65
+ const day = await settleDay();
66
+ empty.cheers = day.cheers;
67
+ empty.dayDone = day.done; // false: this deck is done, but another one still has cards today
68
+ }
69
+ const message = deck?.tour ? "You've finished the tour." : words.length ? "Nothing to practise right now." : `The deck "${deck?.name}" has no cards yet.`;
70
+ throw Object.assign(new Error(message), empty);
71
+ }
24
72
  lastNoteId = item.word.noteId;
25
73
  lastWrong = null;
26
74
 
27
- const toPolish = item.direction === "en-pl";
75
+ const forward = item.direction === "en-pl";
28
76
  return {
29
77
  word: item.word,
30
78
  direction: item.direction,
31
- label: LABELS[item.direction],
32
- prompt: toPolish ? item.word.word : item.word.translations.join(", "),
33
- expected: toPolish ? item.word.translations : [item.word.word],
79
+ label: labelOf(deck, item.direction),
80
+ prompt: forward ? item.word.word : item.word.translations.join(", "),
81
+ expected: forward ? item.word.translations : [item.word.word],
34
82
  wordCount: words.length,
35
- cached
83
+ tour: Boolean(deck?.tour) // the tour marks what to type with `backticks`
36
84
  };
37
85
  }
38
86
 
87
+ // Each deck decides which way it's asked (set when it's made): both ways, or one way only
88
+ // ("2 + 2" → "4"). The front-to-back direction is keyed "en-pl" internally, whatever the languages.
89
+ function directionsOf(deck) {
90
+ return deck?.directions === "forward" ? ["en-pl"] : ["en-pl", "pl-en"];
91
+ }
92
+
39
93
  async function answer(question, text, { hinted = false } = {}) {
40
94
  const key = itemKey(question.word.noteId, question.direction);
41
95
  // answers you once declared right (/correct) count for this card from now on
@@ -45,28 +99,31 @@ export function createSession({ loadWords, state, getSettings, save = saveState,
45
99
  const before = state.items[key];
46
100
  const comboBefore = totals.combo;
47
101
  const entry = grade(before, correct, t, { hinted });
48
- recordAnswer(state, question.word.noteId, question.direction, entry, t);
102
+ recordAnswer(state, question.word.noteId, question.direction, entry, t, { countNew: !question.tour });
49
103
 
50
104
  totals.asked += 1;
51
105
  totals.correct += correct ? 1 : 0;
52
106
  totals.combo = correct ? totals.combo + 1 : 0;
53
107
  lastWrong = correct ? null : { question, text, key, before, comboBefore, hinted, at: t };
54
- if (!correct) recordMiss(state, { key, label: question.label, prompt: question.prompt, expected: question.expected, answer: text, at: t }, t);
108
+ // a blank answer on a tour card just shows it: the tour isn't something to have "missed"
109
+ if (!correct && !(question.tour && !text.trim())) recordMiss(state, { key, label: question.label, prompt: question.prompt, expected: question.expected, answer: text, at: t }, t);
55
110
 
56
111
  const reward = applyAnswer(state, { result, goal: getSettings().dailyGoal, rules: rules(), combo: totals.combo, now: t });
57
112
  const cheers = [...reward.cheers];
58
113
  if (correct && totals.combo % COMBO_CHEER_EVERY === 0) cheers.push({ kind: "combo", text: `Combo ×${totals.combo}` });
59
114
 
60
115
  await save(state);
116
+ // the last card of the day settles it right away, so quitting now doesn't lose the goal
117
+ if (!question.tour) cheers.push(...(await settleDay()).cheers);
61
118
  // given/closest feed the per-letter diff the UI shows after a miss or a forgiven typo
62
119
  const closest = result === "exact" ? null : closestCandidate(text, [...question.expected, ...(state.accepted?.[key] ?? [])]);
63
- return { result, hinted: hinted && correct, dueIn: describeDue(entry, t), combo: totals.combo, cheers, given: text, closest };
120
+ return { result, hinted: hinted && correct, dueIn: describeDue(entry, t), combo: totals.combo, cheers, given: text, closest, nextDue: upNext() };
64
121
  }
65
122
 
66
123
  // Re-grade the last wrong answer as correct and remember the answer for this card.
67
124
  async function overrule() {
68
125
  if (!lastWrong) throw new Error("There is no wrong answer to correct.");
69
- const { text, key, before, comboBefore, hinted, at } = lastWrong;
126
+ const { question, text, key, before, comboBefore, hinted, at } = lastWrong;
70
127
  lastWrong = null;
71
128
 
72
129
  const entry = grade(before, true, at, { hinted });
@@ -80,34 +137,40 @@ export function createSession({ loadWords, state, getSettings, save = saveState,
80
137
  const { cheers } = applyOverrule(state, { goal: getSettings().dailyGoal, rules: rules(), combo: totals.combo, now: at });
81
138
 
82
139
  await save(state);
83
- return { result: "exact", overruled: true, accepted: text, dueIn: describeDue(entry, now()), combo: totals.combo, cheers };
140
+ if (!question.tour) cheers.push(...(await settleDay()).cheers);
141
+ return { result: "exact", overruled: true, accepted: text, dueIn: describeDue(entry, now()), combo: totals.combo, cheers, nextDue: upNext() };
84
142
  }
85
143
 
86
- const canOverrule = () => lastWrong !== null;
144
+ const canOverrule = () => lastWrong !== null && lastWrong.text.trim() !== ""; // nothing typed, nothing to accept
87
145
 
88
146
  const stats = () => snapshot(state, { goal: getSettings().dailyGoal, rules: rules(), now: now() });
89
147
 
90
148
  const month = (offset) => calendarMonth(state, { offset, rules: rules(), now: now() });
91
149
  const missed = (offset) => missedOn(state, { offset, now: now() });
92
150
 
93
- // /vacation: plan, list or cancel rest days that keep the streak alive → a message for the user
94
- async function vacation(args) {
151
+ // /pause: a break today (the UI holds it, this returns its length) or days off that keep the
152
+ // streak (saved here). → { snooze?: ms | "off", list?: true, message? }
153
+ async function pause(args) {
95
154
  const today = dayKey(now());
96
- const parsed = parseVacation(args, today);
97
- if (!parsed) throw new Error("Try /vacation 7, /vacation 24.12 2.01 or /vacation off");
98
-
99
- if (parsed.action === "add") {
100
- addVacation(state, parsed.from, parsed.to, now());
155
+ const parsed = parsePause(args, today);
156
+ if (!parsed) throw new Error(PAUSE_HELP);
157
+ if (parsed.action === "snooze") return { snooze: parsed.ms };
158
+ if (parsed.action === "days") {
159
+ // days off start today at the earliest: missed days can't be turned into days off afterwards
160
+ const from = parsed.from < today ? today : parsed.from;
161
+ if (parsed.to < today) throw new Error("Those days are already over. Days off can only start today or later.");
162
+ addVacation(state, from, parsed.to, now());
101
163
  await save(state);
102
- return `Vacation ${formatRange(parsed.from, parsed.to)}: your streak is safe until then`;
164
+ const what = from === parsed.to ? `Day off on ${formatRange(from, from)}` : `Days off ${formatRange(from, parsed.to)}`;
165
+ return { message: `${what}: your streak is safe.` };
103
166
  }
104
167
  if (parsed.action === "off") {
105
168
  cancelVacations(state, now());
106
169
  await save(state);
107
- return "Vacation cancelled";
170
+ return { snooze: "off", message: "Pause off: questions are back, and no days off are planned" };
108
171
  }
109
172
  const { upcoming } = vacationInfo(ensureProgress(state, now()), today);
110
- return upcoming.length ? `Vacations: ${upcoming.map((v) => formatRange(v.from, v.to)).join(", ")}` : "No vacation planned. Try /vacation 7 or /vacation 24.12 2.01";
173
+ return { list: true, message: upcoming.length ? `Days off: ${upcoming.map((v) => formatRange(v.from, v.to)).join(", ")}` : `No days off planned. ${PAUSE_HELP}` };
111
174
  }
112
175
 
113
176
  // a tip for the wait between questions; remembering which ones were shown is best-effort
@@ -117,6 +180,31 @@ export function createSession({ loadWords, state, getSettings, save = saveState,
117
180
  return tip;
118
181
  }
119
182
 
183
+ // progress of cards that are gone (a removed deck) is dropped with them
184
+ async function forget(cardIds) {
185
+ const ids = new Set(cardIds);
186
+ const gone = (key) => ids.has(key.slice(0, key.lastIndexOf(":")));
187
+ for (const key of Object.keys(state.items)) if (gone(key)) delete state.items[key];
188
+ for (const key of Object.keys(state.accepted ?? {})) if (gone(key)) delete state.accepted[key];
189
+ await save(state);
190
+ }
191
+
192
+ // Reset from /settings (the caller makes a backup first). "progress" starts the game over: badges,
193
+ // streak, stats and the dragon's form and element; your cards and their boxes stay. "everything"
194
+ // empties the state as on a fresh install, so the egg hatches again.
195
+ async function reset(scope) {
196
+ if (scope === "everything") {
197
+ for (const key of Object.keys(state)) delete state[key];
198
+ Object.assign(state, { version: 1, items: {}, newToday: { date: "", count: 0 } });
199
+ } else {
200
+ delete state.progress;
201
+ delete state.tips;
202
+ }
203
+ totals.combo = 0;
204
+ lastWrong = null;
205
+ await save(state);
206
+ }
207
+
120
208
  // the hatching intro plays once ever: on a brand-new state that has never answered anything
121
209
  const isFirstRun = () => !state.hatched && Object.keys(state.items).length === 0;
122
210
 
@@ -125,5 +213,15 @@ export function createSession({ loadWords, state, getSettings, save = saveState,
125
213
  await save(state);
126
214
  }
127
215
 
128
- return { totals, next, answer, overrule, canOverrule, stats, month, missed, nextTip, vacation, isFirstRun, markHatched };
216
+ // /badges: the ones won since it was last opened, which light up one by one; opening it marks them seen
217
+ async function openBadges() {
218
+ const fresh = unseenBadges(state, now());
219
+ if (fresh.length) {
220
+ markBadgesSeen(state, now());
221
+ await save(state);
222
+ }
223
+ return fresh;
224
+ }
225
+
226
+ return { totals, next, answer, overrule, canOverrule, stats, month, missed, nextTip, pause, isFirstRun, markHatched, openBadges, forget, reset, inTour: () => inTour };
129
227
  }
package/src/settings.js CHANGED
@@ -1,4 +1,4 @@
1
- export const DEFAULTS = { everyMs: 600_000, sound: true, volume: 0.5, dailyGoal: 20, directions: "both", tips: "always", quiet: null, skipWeekends: true };
1
+ export const DEFAULTS = { everyMs: 600_000, sound: true, volume: 0.5, dailyGoal: 20, tips: "always", quiet: null, skipWeekends: true, deck: null };
2
2
 
3
3
  export const INTERVALS = [60_000, 120_000, 300_000, 600_000, 900_000, 1_200_000, 1_800_000, 2_700_000, 3_600_000];
4
4
  export const GOALS = [5, 10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200];
@@ -7,9 +7,6 @@ export const TIP_MODES = ["always", "sometimes", "off"];
7
7
  export const TIP_LABELS = { always: "always", sometimes: "sometimes (1 in 3 waits)", off: "off" };
8
8
  // presets for /settings; any { from, to } in settings.json works too
9
9
  export const QUIET_PRESETS = [null, { from: 21, to: 7 }, { from: 22, to: 8 }, { from: 23, to: 7 }, { from: 0, to: 8 }];
10
- export const DIRECTION_OPTIONS = ["both", "en-pl", "pl-en"];
11
-
12
- export const DIRECTION_LABELS = { both: "EN ⇄ PL", "en-pl": "EN → PL only", "pl-en": "PL → EN only" };
13
10
 
14
11
  export function formatInterval(ms) {
15
12
  if (ms < 60_000) return `${Math.round(ms / 1000)} s`;
@@ -26,18 +23,16 @@ const isNumber = (v) => typeof v === "number" && Number.isFinite(v);
26
23
 
27
24
  // settings.json is hand-editable, so anything invalid falls back to the default instead of crashing
28
25
  export function normalizeSettings(raw = {}) {
26
+ raw = raw && typeof raw === "object" ? raw : {};
29
27
  return {
30
28
  everyMs: isNumber(raw.everyMs) && raw.everyMs >= 1000 ? raw.everyMs : DEFAULTS.everyMs,
31
29
  sound: typeof raw.sound === "boolean" ? raw.sound : DEFAULTS.sound,
32
30
  volume: isNumber(raw.volume) && raw.volume >= 0 && raw.volume <= 1 ? raw.volume : DEFAULTS.volume,
33
31
  dailyGoal: isNumber(raw.dailyGoal) && raw.dailyGoal >= 1 ? Math.round(raw.dailyGoal) : DEFAULTS.dailyGoal,
34
- directions: DIRECTION_OPTIONS.includes(raw.directions) ? raw.directions : DEFAULTS.directions,
35
32
  tips: normalizeTips(raw.tips),
36
33
  skipWeekends: typeof raw.skipWeekends === "boolean" ? raw.skipWeekends : DEFAULTS.skipWeekends,
37
- quiet: raw.quiet && isHour(raw.quiet.from) && isHour(raw.quiet.to) ? { from: raw.quiet.from, to: raw.quiet.to } : null
34
+ quiet: raw.quiet && isHour(raw.quiet.from) && isHour(raw.quiet.to) ? { from: raw.quiet.from, to: raw.quiet.to } : null,
35
+ deck: typeof raw.deck === "string" && raw.deck.trim() ? raw.deck : null // picked in /decks; null = your first deck
38
36
  };
39
37
  }
40
38
 
41
- export function directionsFor(setting) {
42
- return setting === "en-pl" ? ["en-pl"] : setting === "pl-en" ? ["pl-en"] : ["en-pl", "pl-en"];
43
- }
package/src/starter.js ADDED
@@ -0,0 +1,38 @@
1
+ import { addCard, createDeck } from "./library.js";
2
+
3
+ // The deck a fresh install starts with: a short tour that teaches Dracosh by doing. Every card says
4
+ // exactly what to type, and the line shown after the answer explains the next thing. It's a `tour`
5
+ // deck: every card is asked once, in this order, and never comes back as a review. `Backticks` mark
6
+ // what to type (or a command); the quiz shows them highlighted, in the tour only. Answers never start with "/", because "/" opens the commands.
7
+ export const STARTER_DECK = "Getting started";
8
+ // bump it when the cards below change: an older copy of the tour in someone's library gets replaced
9
+ const STARTER_VERSION = 7;
10
+
11
+ const STARTER_CARDS = [
12
+ { front: "Welcome! Every few minutes a card asks you something. Type the answer and press Enter. Try it and type `hello`", back: ["hello"], example: "Press `Enter` now for the next card, or wait and it will come by itself." },
13
+ { front: "Small typos still count. Type `dragon`, but miss a letter on purpose (like `dragn`)", back: ["dragon"], example: "A typo counts as right, and Dracosh shows you the correct spelling." },
14
+ { front: "A card can accept more than one answer. What is 2 + 2? (`4` and `four` both work)", back: ["4", "four"], example: "Every right answer moves a card to a later box, so you see it less and less often." },
15
+ { front: "Stuck? Type `/hint` and press Enter, and the answer shows up letter by letter. Try it, then type `apple`", back: ["apple"], example: "A hinted answer still counts, but the card stays in its box for now." },
16
+ { front: "What is your dragon's secret name? Nobody knows, so get this one wrong on purpose and type `dog`", back: ["Asogaras"], example: "In your own decks a missed card comes back sooner. If you were marked wrong by mistake, type `/correct` now." },
17
+ { front: "Type `/` at any time to see all commands. Try `/badges` after this card. For now, type `ok`", back: ["ok", "okay"], example: "`/stats` shows your calendar, `/companion` your dragon, `/settings` how often cards come." },
18
+ { front: "Reach your daily goal every day to keep your streak. Your dragon grows with it. Type `every day`", back: ["every day", "everyday", "daily"], example: "Miss a day and a freeze saves your streak, if you have one left." },
19
+ { front: "Need a break? `/pause 1h` holds the cards for an hour, `/pause 3d` gives you days off. For now, type `later`", back: ["later"], example: "Leave Dracosh alone for a few minutes and the dragon dozes off. Any key wakes it." },
20
+ { front: "That's the tour! Type `done`", back: ["done"], example: "Now make it yours and type `/add` to start your own deck. The tour makes room for it." }
21
+ ];
22
+
23
+ // the tour as an earlier version created it (the first one had no version number yet)
24
+ const isStarter = (deck) => deck.starter !== undefined || (deck.name === STARTER_DECK && deck.type === "qa" && !deck.languages);
25
+
26
+ // Adds the tour to an empty library, or brings an older copy of it up to date (its progress is
27
+ // dropped with the old cards). Returns true when the library changed and needs saving.
28
+ export function seedLibrary(library, now = Date.now()) {
29
+ let deck = library.decks.find(isStarter);
30
+ if (library.decks.length && !deck) return false;
31
+ if (deck && (deck.starter ?? 1) >= STARTER_VERSION) return false;
32
+
33
+ if (deck) library.cards = library.cards.filter((card) => card.deckId !== deck.id);
34
+ else deck = createDeck(library, { name: STARTER_DECK, type: "qa", answerMode: "typed", languages: null, directions: "forward", tour: true, now });
35
+ Object.assign(deck, { tour: true, starter: STARTER_VERSION });
36
+ for (const card of STARTER_CARDS) addCard(library, deck.id, { ...card, now });
37
+ return true;
38
+ }
package/src/store.js CHANGED
@@ -1,21 +1,31 @@
1
1
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
- import { join } from "node:path";
3
+ import { dirname, join } from "node:path";
4
4
  import { dayKey } from "./dates.js";
5
+ import { upgradeLibrary } from "./library.js";
5
6
  import { itemKey, newToday } from "./scheduler.js";
6
7
 
7
8
  export const HOME = process.env.DRACOSH_HOME || join(homedir(), ".dracosh");
9
+ const LIBRARY_FILE = join(HOME, "library.json");
8
10
  const STATE_FILE = join(HOME, "state.json");
9
- const WORDS_FILE = join(HOME, "words.json");
10
11
  const SETTINGS_FILE = join(HOME, "settings.json");
12
+ // everything a backup holds, by name
13
+ export const DATA_FILES = { library: LIBRARY_FILE, state: STATE_FILE, settings: SETTINGS_FILE };
11
14
 
12
- const emptyState = () => ({ version: 1, items: {}, newToday: { date: "", count: 0 } });
15
+ export const STATE_VERSION = 1;
16
+ const emptyState = () => ({ version: STATE_VERSION, items: {}, newToday: { date: "", count: 0 } });
13
17
 
14
- async function readJson(file, fallback) {
18
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
19
+
20
+ // what to say when a data file can't be used as it is
21
+ export const damaged = (file, why) => new Error(`${file} looks damaged (${why}). Run "dracosh restore" to bring back a backup.`);
22
+
23
+ export async function readJson(file, fallback) {
15
24
  try {
16
25
  return JSON.parse(await readFile(file, "utf8"));
17
26
  } catch (err) {
18
27
  if (err.code === "ENOENT") return fallback;
28
+ if (err instanceof SyntaxError) throw damaged(file, err.message);
19
29
  throw new Error(`Can't read ${file}: ${err.message}`);
20
30
  }
21
31
  }
@@ -24,11 +34,11 @@ async function readJson(file, fallback) {
24
34
  // and two saves in quick succession (an answer and a shown tip, say) can't trip over each other's temp file.
25
35
  let writes = Promise.resolve();
26
36
 
27
- function writeJson(file, data) {
37
+ export function writeJson(file, data) {
28
38
  const json = JSON.stringify(data, null, 2); // snapshot now: the state object keeps changing
29
39
  const job = writes.then(async () => {
30
- await mkdir(HOME, { recursive: true });
31
- const tmp = `${file}.tmp`;
40
+ await mkdir(dirname(file), { recursive: true });
41
+ const tmp = `${file}.${process.pid}.tmp`; // another Dracosh process never shares it
32
42
  await writeFile(tmp, json);
33
43
  await rename(tmp, file);
34
44
  });
@@ -36,26 +46,55 @@ function writeJson(file, data) {
36
46
  return job;
37
47
  }
38
48
 
39
- export const loadState = () => readJson(STATE_FILE, emptyState());
40
- export const saveState = (state) => writeJson(STATE_FILE, state);
49
+ export async function loadLibrary() {
50
+ try {
51
+ return upgradeLibrary(await readJson(LIBRARY_FILE, undefined));
52
+ } catch (err) {
53
+ throw err.damaged ? damaged(LIBRARY_FILE, err.message) : err;
54
+ }
55
+ }
56
+ export const saveLibrary = (library) => writeJson(LIBRARY_FILE, library);
41
57
 
42
- // last successful read from Anki, so the quiz still works while Anki is closed
43
- export const loadWordsCache = () => readJson(WORDS_FILE, null);
44
- export const saveWordsCache = (deck, words) => writeJson(WORDS_FILE, { deck, words });
58
+ // Progress, checked for the shape the quiz relies on; a file from a newer Dracosh is never overwritten
59
+ export async function loadState() {
60
+ const state = await readJson(STATE_FILE, undefined);
61
+ if (state === undefined) return emptyState();
62
+ if (!isObject(state) || !isObject(state.items)) throw damaged(STATE_FILE, "no progress in it");
63
+ if (!Object.values(state.items).every((entry) => isObject(entry) && Number.isFinite(entry.box) && Number.isFinite(entry.due))) throw damaged(STATE_FILE, "a card without its box or date");
64
+ const { progress } = state;
65
+ const validProgress =
66
+ isObject(progress) &&
67
+ isObject(progress.days) &&
68
+ Object.values(progress.days).every(isObject) &&
69
+ isObject(progress.streak) &&
70
+ ["count", "best", "freezes"].every((key) => Number.isFinite(progress.streak[key])) &&
71
+ isObject(progress.badges) &&
72
+ (progress.vacations === undefined || Array.isArray(progress.vacations));
73
+ if (progress !== undefined && !validProgress) throw damaged(STATE_FILE, "the streak and badges are unreadable");
74
+ if (state.version > STATE_VERSION) throw new Error(`${STATE_FILE} was saved by a newer version of Dracosh. Please update Dracosh.`);
75
+ if (!isObject(state.newToday)) state.newToday = { date: "", count: 0 };
76
+ return state;
77
+ }
78
+ export const saveState = (state) => writeJson(STATE_FILE, state);
45
79
 
46
- export function recordAnswer(state, noteId, direction, entry, now = Date.now()) {
80
+ // `countNew: false` keeps a card out of the daily cap on new cards (the tour's don't use it up)
81
+ export function recordAnswer(state, noteId, direction, entry, now = Date.now(), { countNew = true } = {}) {
47
82
  const key = itemKey(noteId, direction);
48
- const isNew = !state.items[key];
83
+ const isNew = countNew && !state.items[key];
49
84
  const date = dayKey(now);
50
85
  state.items[key] = entry;
51
86
  if (isNew) state.newToday = { date, count: newToday(state, now) + 1 };
52
87
  return state;
53
88
  }
54
89
 
55
- export const loadSettingsRaw = () => readJson(SETTINGS_FILE, {});
90
+ // hand-edited into something odd, even broken JSON: the defaults take over (nothing worth a restore)
91
+ export const loadSettingsRaw = async () => {
92
+ const raw = await readJson(SETTINGS_FILE, {}).catch((err) => (err.message.includes("looks damaged") ? {} : Promise.reject(err)));
93
+ return isObject(raw) ? raw : {};
94
+ };
56
95
 
57
96
  // merges into what's on disk, so a one-off CLI flag never gets persisted by accident
58
97
  export async function patchSettings(patch) {
59
- const current = await readJson(SETTINGS_FILE, {});
98
+ const current = await loadSettingsRaw();
60
99
  await writeJson(SETTINGS_FILE, { ...current, ...patch });
61
100
  }
package/src/tips.js CHANGED
@@ -1,38 +1,21 @@
1
1
  import { readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { HOME } from "./store.js";
4
2
 
5
- const BUNDLED = JSON.parse(readFileSync(new URL("../data/tips.json", import.meta.url), "utf8"));
6
- const USER_FILE = join(HOME, "tips.json");
3
+ // Short tips about Dracosh itself, shown now and then while you wait for the next card.
4
+ export const TIPS = JSON.parse(readFileSync(new URL("../data/tips.json", import.meta.url), "utf8"));
7
5
  const SOMETIMES_CHANCE = 1 / 3;
8
6
 
9
- // Your own tips: ~/.dracosh/tips.json, an array of { "cat": "...", "text": "..." } (the id is optional).
10
- // A broken or missing file just means no extra tips.
11
- export function loadUserTips(file = USER_FILE) {
12
- let raw;
13
- try {
14
- raw = JSON.parse(readFileSync(file, "utf8"));
15
- } catch {
16
- return [];
17
- }
18
- if (!Array.isArray(raw)) return [];
19
- return raw
20
- .filter((tip) => tip && typeof tip.text === "string" && tip.text.trim())
21
- .map((tip, i) => ({ id: `u-${tip.id ?? i + 1}`, cat: typeof tip.cat === "string" && tip.cat ? tip.cat : "My tips", text: tip.text.trim() }));
22
- }
23
-
24
- export const allTips = () => [...BUNDLED, ...loadUserTips()];
25
-
26
7
  // "always" shows a tip on every wait, "sometimes" on about one in three
27
8
  export function shouldShowTip(mode, random = Math.random) {
28
9
  return mode === "always" || (mode === "sometimes" && random() < SOMETIMES_CHANCE);
29
10
  }
30
11
 
31
- // Shows every tip once before any repeats; what has been shown is remembered in state.tips.seen.
32
- export function createTipDeck({ state, tips = allTips(), random = Math.random }) {
12
+ // Shows every tip once before any repeats; what has been shown is remembered in state.tips.seen
13
+ // (ids of tips that no longer exist are dropped from it).
14
+ export function createTipDeck({ state, tips = TIPS, random = Math.random }) {
15
+ const known = new Set(tips.map((tip) => tip.id));
33
16
  return {
34
17
  next() {
35
- const seen = new Set(state.tips?.seen ?? []);
18
+ const seen = new Set((state.tips?.seen ?? []).filter((id) => known.has(id)));
36
19
  let fresh = tips.filter((tip) => !seen.has(tip.id));
37
20
  if (!fresh.length) {
38
21
  seen.clear();