dracosh 0.4.0 → 0.6.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.
@@ -0,0 +1,222 @@
1
+ import { t } from "./i18n.js";
2
+ import { gapsOf } from "./cardline.js";
3
+ import { readCardList } from "./cardlist.js";
4
+ import { frontKey } from "./judge.js";
5
+ import { addCard, cardsOf, createDeck, findDeck, frontIndex, MAX_DECK_NAME, removeDeck, typedSides, updateCard } from "./library.js";
6
+
7
+ // Importing a list of cards: reading the file, a plan of what it would change (shown before anything is
8
+ // saved), then that plan carried out. Pure apart from decodeText's input; the CLI does the asking.
9
+
10
+ // A file's text, read the way it was saved: UTF-8 (with or without a BOM), or UTF-16 (Excel's "Unicode
11
+ // text"). Anything else isn't guessed: → throws with the start of the file read as the usual legacy
12
+ // encodings, so the right --encoding can be picked.
13
+ export function decodeText(bytes, encoding = null) {
14
+ const buffer = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
15
+ if (encoding) {
16
+ let decoder;
17
+ try {
18
+ decoder = new TextDecoder(encoding);
19
+ } catch {
20
+ throw new Error(t("import.unknownEncoding", { encoding }));
21
+ }
22
+ return { text: decoder.decode(buffer), encoding: decoder.encoding };
23
+ }
24
+ const starts = (...prefix) => prefix.every((byte, i) => buffer[i] === byte);
25
+ if (starts(0xff, 0xfe)) return { text: new TextDecoder("utf-16le").decode(buffer), encoding: "utf-16le" };
26
+ if (starts(0xfe, 0xff)) return { text: new TextDecoder("utf-16be").decode(buffer), encoding: "utf-16be" };
27
+ // UTF-16 without a BOM: every other byte is zero in text that's mostly Latin
28
+ const sample = buffer.subarray(0, 4000);
29
+ const zeros = (offset) => sample.filter((byte, i) => i % 2 === offset && byte === 0).length;
30
+ if (sample.length >= 4 && zeros(1) > sample.length * 0.3) return { text: new TextDecoder("utf-16le").decode(buffer), encoding: "utf-16le" };
31
+ if (sample.length >= 4 && zeros(0) > sample.length * 0.3) return { text: new TextDecoder("utf-16be").decode(buffer), encoding: "utf-16be" };
32
+ try {
33
+ return { text: new TextDecoder("utf-8", { fatal: true }).decode(buffer), encoding: "utf-8" };
34
+ } catch {
35
+ const line = (label) => new TextDecoder(label).decode(buffer).split(/\r?\n/).find((l) => /[^\x00-\x7f]/.test(l)) ?? "";
36
+ const samples = ["windows-1250", "windows-1252"].map((label) => ({ encoding: label, line: line(label).slice(0, 60) }));
37
+ throw Object.assign(new Error(t("import.notUtf8")), { samples });
38
+ }
39
+ }
40
+
41
+ // the same answers, maybe in another order: a fixed accent or letter case is a change
42
+ const answersKey = (back) => back.map((answer) => answer.trim()).sort().join("\u0001");
43
+
44
+ // → { decks: [{ name, deck (existing or null), direction, items }], problems, read: { format, separator,
45
+ // columns, ignored, count } }, each item one of:
46
+ // { kind: "new", line, fields } added
47
+ // { kind: "same", line, fields, card } already in the deck as it is: left alone
48
+ // { kind: "changed", line, fields, card } in the deck with other answers or example: asked about
49
+ // problems: [{ line, issue, text, first? }]: issue is noFront, noBack, noSeparator (a Dracosh line
50
+ // without " = "), slash (an answer to type starts with "/"), twice (first: the line it was on before),
51
+ // noDeck, tooLong (a deck name), tour (a deck name taken by the tour), picture (an Anki note that
52
+ // is a picture, from a package).
53
+ // `deck`: every card goes into this deck (--deck); `deckName`: the deck for cards the file doesn't put
54
+ // in one (what was asked). `directions`: { deck name: direction } picked for new decks.
55
+ // `split`: in a table, one answer listing several ("cat, kitty", "cat / kitty") becomes several;
56
+ // read.splittable says how many there are, with an example. `list`: the cards already read (an Anki
57
+ // package, by apkg.js), instead of `text`.
58
+ export function planImport(library, text, { deck: only = null, deckName = null, separator = null, csv = false, directions = {}, split = false, list: given = null } = {}) {
59
+ const list = given ?? readCardList(text, { separator, csv });
60
+ const decks = new Map();
61
+ const problems = [];
62
+ const seen = new Map(); // deck name + front → the line it was first on
63
+ const fronts = new Map(); // deck id → its frontIndex
64
+ const splittable = [];
65
+
66
+ for (const { line, text: source } of list.unknown) problems.push({ line, issue: "badDirection", text: source });
67
+ const fittedFrom = new Map(); // a shortened deck name → the long one it came from
68
+ for (const item of list.items) {
69
+ const full = (only ?? item.deck ?? deckName ?? "").trim();
70
+ const name = fitName(full);
71
+ let { fields } = item;
72
+ const problem = (issue, extra = {}) => problems.push({ line: item.line, issue, text: item.source, ...extra });
73
+ if (item.skip) {
74
+ problem(item.skip);
75
+ continue;
76
+ }
77
+ if (!fields.front) {
78
+ problem("noFront");
79
+ continue;
80
+ }
81
+ if (!fields.cloze && !fields.back.length) {
82
+ problem(list.format === "lines" && !item.source.includes("=") ? "noSeparator" : "noBack");
83
+ continue;
84
+ }
85
+ // a phrase ("Hello, world") is translated by a phrase, not a list
86
+ const listed = (list.format === "table" || list.format === "apkg") && !fields.cloze && fields.back.length === 1 && !fields.front.includes(",") && listedAnswers(fields.back[0]);
87
+ if (listed) {
88
+ splittable.push(fields.back[0]);
89
+ if (split) fields = { ...fields, back: listed };
90
+ }
91
+ if (!name) {
92
+ problem("noDeck");
93
+ continue;
94
+ }
95
+ // two long names that shorten to the same one stay apart: the second one is named instead
96
+ const before = fittedFrom.get(name.toLowerCase()) ?? full;
97
+ fittedFrom.set(name.toLowerCase(), before);
98
+ if (Array.from(name).length > MAX_DECK_NAME || before !== full) {
99
+ problem("tooLong", { deck: full });
100
+ continue;
101
+ }
102
+ const key = `${name.toLowerCase()}\u0001${frontKey(fields.front)}`;
103
+ if (seen.has(key)) {
104
+ problem("twice", { first: seen.get(key) });
105
+ continue;
106
+ }
107
+ seen.set(key, item.line);
108
+
109
+ if (!decks.has(name.toLowerCase())) {
110
+ const deck = findDeck(library, name);
111
+ decks.set(name.toLowerCase(), { name: deck?.name ?? name, deck, direction: deck ? deck.directions : item.direction, items: [] });
112
+ }
113
+ const target = decks.get(name.toLowerCase());
114
+ if (target.deck?.tour) {
115
+ problem("tour", { deck: target.deck.name });
116
+ continue;
117
+ }
118
+ if (target.deck && !fronts.has(target.deck.id)) fronts.set(target.deck.id, frontIndex(library, target.deck.id));
119
+ const existing = target.deck ? (fronts.get(target.deck.id).get(frontKey(fields.front)) ?? null) : null;
120
+ const direction = target.deck?.directions ?? directions[target.name] ?? target.direction ?? "forward";
121
+ if (slashIn(fields, direction)) {
122
+ problem("slash");
123
+ continue;
124
+ }
125
+ if (!existing) target.items.push({ kind: "new", line: item.line, fields });
126
+ else {
127
+ // the same answers in another order, or an example left out of the file, change nothing
128
+ const sameBack = answersKey(existing.back) === answersKey(fields.back);
129
+ const sameExample = !fields.example || fields.example === existing.example;
130
+ const sameGaps = !(fields.cloze || existing.cloze) || fields.front === existing.front;
131
+ target.items.push({ kind: sameBack && sameExample && sameGaps ? "same" : "changed", line: item.line, fields, card: existing });
132
+ }
133
+ }
134
+ return {
135
+ decks: [...decks.values()].filter((deck) => deck.items.length),
136
+ problems,
137
+ read: { anki: list.anki, html: list.html, media: list.media ?? 0, format: list.format, separator: list.separator, columns: list.columns, ignored: list.ignored, count: list.items.length, splittable: splittable.length, splitExample: splittable[0] ?? null }
138
+ };
139
+ }
140
+
141
+ // Anki's nested decks ("Languages::Spanish::Verbs for travel") are long: one that doesn't fit keeps its
142
+ // last part, the deck the cards are really in
143
+ const fitName = (name) => {
144
+ if (Array.from(name).length <= MAX_DECK_NAME || !name.includes("::")) return name;
145
+ // as many of the last parts as fit: "Languages::Spanish for my trip::Verbs" → "Spanish for my trip::Verbs"
146
+ const parts = name.split("::").map((part) => part.trim());
147
+ let fitted = parts.at(-1);
148
+ for (let i = parts.length - 2; i >= 0 && Array.from(`${parts[i]}::${fitted}`).length <= MAX_DECK_NAME; i--) fitted = `${parts[i]}::${fitted}`;
149
+ return fitted;
150
+ };
151
+
152
+ // "cat, kitty" or "cat / kitty": answers listed the way Anki and Quizlet decks often do → ["cat", "kitty"];
153
+ // null for a sentence ("Yes, I do.") or a single answer
154
+ function listedAnswers(answer) {
155
+ if (/[.?!…]$/.test(answer.trim())) return null;
156
+ const parts = answer.split(/\s*,\s+|\s+\/\s+/).map((part) => part.trim()).filter(Boolean);
157
+ return parts.length > 1 && parts.every((part) => part.split(/\s+/).length <= 3) ? parts : null;
158
+ }
159
+
160
+ // in the quiz "/" opens the commands, so nothing to be typed may start with it
161
+ const slashIn = (fields, directions) => {
162
+ const slash = (text) => text.startsWith("/");
163
+ if (fields.cloze) return gapsOf(fields.front).some(slash);
164
+ return typedSides({ directions }).some((side) => [fields[side]].flat().some(slash));
165
+ };
166
+
167
+ // Carries out a plan. `update`: changed cards take the file's answers and example (their progress
168
+ // stays): true for all of them, or a Set of the card ids that were shown and agreed to; otherwise
169
+ // they're left as they are. `directions`: { deck name: direction } for new decks
170
+ // (forward when not given). → { added, updated, slash: [{ line, text }] (left out: an answer to type
171
+ // starts with "/"), decks: [{ name, isNew, added, updated }], removedTour: the tour's card ids (it goes
172
+ // once you have a deck of your own, as in /add; `keepTour` keeps it) }
173
+ // A card already in a deck that the import found among Anki's own notes is marked as from Anki too
174
+ // (as a new one is), so `export --anki` never sends Anki a second copy of it. → how many were marked
175
+ export function markFromAnki(library, plan) {
176
+ let marked = 0;
177
+ for (const item of plan.decks.flatMap((deck) => deck.items)) {
178
+ const card = item.card && item.fields.fromAnki && library.cards.find((each) => each.id === item.card.id);
179
+ if (card && !card.fromAnki) [card.fromAnki, marked] = [true, marked + 1];
180
+ }
181
+ return marked;
182
+ }
183
+
184
+ export function applyImport(library, plan, { update = false, directions = {}, keepTour = false, now = Date.now() } = {}) {
185
+ const result = { added: 0, updated: 0, slash: [], decks: [], removedTour: [] };
186
+ markFromAnki(library, plan);
187
+ for (const target of plan.decks) {
188
+ let deck = target.deck && library.decks.find((d) => d.id === target.deck.id);
189
+ const isNew = !deck;
190
+ if (isNew) deck = createDeck(library, { name: target.name, directions: directions[target.name] ?? target.direction ?? "forward", now });
191
+ const counts = { name: deck.name, isNew, added: 0, updated: 0 };
192
+ const index = frontIndex(library, deck.id);
193
+ for (const item of target.items) {
194
+ const updating = item.kind === "changed" && (update === true || update?.has?.(item.card.id));
195
+ if ((item.kind === "new" || updating) && slashIn(item.fields, deck.directions)) {
196
+ result.slash.push({ line: item.line, text: item.fields.front });
197
+ continue;
198
+ }
199
+ if (item.kind === "new") {
200
+ addCard(library, deck.id, { ...item.fields, now }, index);
201
+ counts.added++;
202
+ } else if (updating) {
203
+ updateCard(library, item.card.id, { front: item.fields.front, back: item.fields.back, cloze: item.fields.cloze, ...(item.fields.example && { example: item.fields.example }) }, now);
204
+ counts.updated++;
205
+ }
206
+ }
207
+ result.added += counts.added;
208
+ result.updated += counts.updated;
209
+ result.decks.push(counts);
210
+ }
211
+ // your first deck of your own replaces the tour, as in /add
212
+ const tour = library.decks.find((d) => d.tour);
213
+ if (tour && !keepTour && library.decks.some((d) => !d.tour && cardsOf(library, d.id).length)) result.removedTour = removeDeck(library, tour.id);
214
+ return result;
215
+ }
216
+
217
+ // the items of a plan that would be asked about, saved, or left: for the preview
218
+ export const planCounts = (plan) => {
219
+ const items = plan.decks.flatMap((deck) => deck.items);
220
+ const count = (kind) => items.filter((item) => item.kind === kind).length;
221
+ return { new: count("new"), same: count("same"), changed: count("changed"), problems: plan.problems.length };
222
+ };
package/src/judge.js CHANGED
@@ -45,6 +45,10 @@ export function fold(s) {
45
45
  .replace(/[\ue000-\ue002]/g, (ch) => OWN_BACK[ch]);
46
46
  }
47
47
 
48
+ // One card's front, as duplicates are found: letter case and punctuation don't count, accents do
49
+ // ("el" and "él", "kat" and "kąt" are different words)
50
+ export const frontKey = (s) => plain(String(s ?? ""));
51
+
48
52
  // plain(), and diacritics folded too
49
53
  export function normalize(s) {
50
54
  return fold(plain(s));
@@ -120,7 +124,7 @@ function spelledAnyWay(answer, candidate, lang) {
120
124
  }
121
125
 
122
126
  // German umlauts and articles are what a learner has to get right: an answer without them still counts,
123
- // but as "almost" (the card doesn't move up)
127
+ // but as "almost" (the card comes back sooner)
124
128
  const NO_GENDER = new Set(["to", "att", "at", "å"]); // infinitive markers
125
129
  // elided or plural articles that don't show the gender, per language
126
130
  const NO_GENDER_SHOWN = { fr: new Set(["l'", "les", "des", "de l'"]), it: new Set(["l'"]), ca: new Set(["l'"]) };
package/src/language.js CHANGED
@@ -351,5 +351,11 @@ function guessDeck(deck, cards, ui) {
351
351
  // your own language, where the cards show some sign of it
352
352
  else if (ui !== taken && fits(ui, side) && pointsFor(sides[side], ui) > 0) found[side] = ui;
353
353
  }
354
+ // both sides read as one language, while the name says another: the name wins on the side it fits
355
+ // ("Spanish verbs": "hablar", "comer" look like plain English letters, but the deck says Spanish)
356
+ if (found.front && found.front === found.back) {
357
+ const side = ["front", "back"].find((side) => named.some((lang) => lang !== found[side] && fits(lang, side)));
358
+ if (side) found[side] = named.find((lang) => lang !== found[side] && fits(lang, side));
359
+ }
354
360
  return { front: found.front ?? UNKNOWN, back: found.back ?? UNKNOWN, guessed: true };
355
361
  }
package/src/library.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t } from "./i18n.js";
2
2
  import { randomBytes } from "node:crypto";
3
- import { normalize } from "./judge.js";
3
+ import { frontKey } from "./judge.js";
4
4
  import { gapsOf } from "./cardline.js";
5
5
 
6
6
  // The card library: decks and their cards. Pure functions over a plain object; saving is the caller's job.
@@ -87,11 +87,13 @@ export function createDeck(library, { name, type = "translation", languages = nu
87
87
  return deck;
88
88
  }
89
89
 
90
- // Progress is kept per direction, so turning one off only stops asking it: its boxes stay for later.
91
- export function setDirections(library, deckId, directions) {
90
+ // Progress is kept per direction, so turning one off only stops asking it: its progress stays for later.
91
+ // `updated` says when: an Anki package written later makes its notes ask the new way too
92
+ export function setDirections(library, deckId, directions, now = Date.now()) {
92
93
  if (!DIRECTIONS.includes(directions)) throw new Error(`Unknown direction "${directions}".`);
93
94
  const deck = library.decks.find((d) => d.id === deckId);
94
95
  if (!deck) throw new Error("That deck doesn't exist.");
96
+ if (deck.directions !== directions) deck.updated = now;
95
97
  deck.directions = directions;
96
98
  return deck;
97
99
  }
@@ -124,15 +126,21 @@ export function removeDeck(library, deckId) {
124
126
 
125
127
  export const cardsOf = (library, deckId) => library.cards.filter((card) => card.deckId === deckId);
126
128
 
127
- // a card with the same front (ignoring case, accents and punctuation) in the same deck
128
- export const findDuplicate = (library, deckId, front) => {
129
- const key = normalize(front);
130
- return library.cards.find((card) => card.deckId === deckId && normalize(card.front) === key) ?? null;
129
+ // a card with the same front (ignoring case and punctuation: see frontKey) in the same deck. `index`,
130
+ // a Map of frontKey → card for the deck, saves reading every card again (an import adds thousands)
131
+ export const findDuplicate = (library, deckId, front, index = null) => {
132
+ const key = frontKey(front);
133
+ if (index) return index.get(key) ?? null;
134
+ return library.cards.find((card) => card.deckId === deckId && frontKey(card.front) === key) ?? null;
131
135
  };
136
+ export const frontIndex = (library, deckId) => new Map(cardsOf(library, deckId).map((card) => [frontKey(card.front), card]));
132
137
 
133
138
  // → { card, duplicate }: `duplicate` is the existing card when the front is already in the deck (nothing is added then)
134
139
  // `cloze`: the front has {{gaps}}, each asked as a card of its own; the back is then only a hint
135
- export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, now = Date.now() }) {
140
+ // `index`: the deck's frontIndex, kept up to date here (see findDuplicate)
141
+ // `guid`: the note in a Dracosh package it came from, so going back to Anki it's that note again;
142
+ // `fromAnki`: it came from a note of Anki's own (see apkg.js), which Anki still has
143
+ export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, guid, fromAnki = false, now = Date.now() }, index = null) {
136
144
  if (!library.decks.some((deck) => deck.id === deckId)) throw new Error("That deck doesn't exist.");
137
145
  const cleanFront = String(front ?? "").trim();
138
146
  const cleanBack = cleanList(back);
@@ -140,12 +148,13 @@ export function addCard(library, deckId, { front, back, example = "", tags = [],
140
148
  if (!cleanFront) throw new Error(t("errors.cardNeedsFront"));
141
149
  if (!cleanBack.length && !isCloze) throw new Error(t("errors.cardNeedsBack"));
142
150
 
143
- const duplicate = findDuplicate(library, deckId, cleanFront);
151
+ const duplicate = findDuplicate(library, deckId, cleanFront, index);
144
152
  if (duplicate) return { card: null, duplicate };
145
153
 
146
- const card = { id: id ? String(id) : newId("c"), deckId, front: cleanFront, back: cleanBack, example: String(example).trim(), tags: cleanList(tags), ...(isCloze && { cloze: true }), created: now, updated: now };
147
- if (library.cards.some((c) => c.id === card.id)) throw new Error(`A card with id ${card.id} already exists.`);
154
+ const card = { id: id ? String(id) : newId("c"), deckId, front: cleanFront, back: cleanBack, example: String(example).trim(), tags: cleanList(tags), ...(isCloze && { cloze: true }), ...(guid && { guid: String(guid) }), ...(fromAnki && { fromAnki: true }), created: now, updated: now };
155
+ if (id && library.cards.some((c) => c.id === card.id)) throw new Error(`A card with id ${card.id} already exists.`);
148
156
  library.cards.push(card);
157
+ index?.set(frontKey(cleanFront), card);
149
158
  return { card, duplicate: null };
150
159
  }
151
160
 
package/src/progress.js CHANGED
@@ -1,9 +1,8 @@
1
1
  import { dateLocale, t } from "./i18n.js";
2
2
  import { addDays, dayKey, daysBetween, weekStart } from "./dates.js";
3
- import { BOX_INTERVALS_DAYS } from "./scheduler.js";
3
+ import { isMastered } from "./scheduler.js";
4
4
 
5
5
  export const MAX_FREEZES = 2;
6
- const MAX_BOX = BOX_INTERVALS_DAYS.length;
7
6
  const AT_RISK_HOUR = 19;
8
7
  const COMEBACK_AFTER_DAYS = 5;
9
8
  const MISSED_KEEP_DAYS = 14;
@@ -260,13 +259,14 @@ for (const badge of BADGES) {
260
259
  // progress is kept per card and direction ("id:en-pl"); badges count cards
261
260
  const cardOf = (key) => key.slice(0, key.lastIndexOf(":"));
262
261
 
263
- // a card is mastered once every direction it's asked in has reached the last box; a direction its deck
262
+ // a card is mastered once every direction it's asked in waits a month or more between reviews (see
263
+ // isMastered); a direction its deck
264
264
  // no longer asks (`dormant`, kept for when it's turned back on) doesn't hold it back
265
265
  function masteredCards(items, dormant = []) {
266
266
  const resting = new Set(dormant);
267
267
  items = items.filter(([key]) => !resting.has(key));
268
268
  const byCard = new Map();
269
- for (const [key, entry] of items) byCard.set(cardOf(key), (byCard.get(cardOf(key)) ?? true) && entry.box === MAX_BOX);
269
+ for (const [key, entry] of items) byCard.set(cardOf(key), (byCard.get(cardOf(key)) ?? true) && isMastered(entry));
270
270
  return [...byCard.values()].filter(Boolean).length;
271
271
  }
272
272
 
package/src/scheduler.js CHANGED
@@ -1,12 +1,19 @@
1
+ import { createEmptyCard, fsrs, Rating } from "ts-fsrs";
1
2
  import { dayKey } from "./dates.js";
2
3
 
3
4
  const MINUTE = 60_000;
4
5
  const DAY = 24 * 60 * MINUTE;
5
6
 
6
- // Leitner boxes: a correct answer moves the card one box up; a miss sends it back to box 1
7
- export const BOX_INTERVALS_DAYS = [1, 3, 7, 14, 30];
7
+ // Each card's next review comes from FSRS (the open-source scheduler Anki offers too): it keeps an estimate of how
8
+ // well you know the card (stability, in days, and difficulty, 1 to 10) and asks it again when
9
+ // you're about to forget it, at 90% recall. A miss brings the card back in 10 minutes, and a new card
10
+ // answered right waits a couple of days.
11
+ const scheduler = fsrs({ request_retention: 0.9, learning_steps: ["10m"], relearning_steps: ["10m"], enable_fuzz: true });
8
12
  export const RELEARN_DELAY = 10 * MINUTE;
9
13
  export const NEW_PER_DAY = 20;
14
+ // a card waiting a month or more between reviews is one you know
15
+ export const MASTERED_DAYS = 30;
16
+ export { Rating };
10
17
 
11
18
  export const DIRECTIONS = ["en-pl", "pl-en"];
12
19
  export const itemKey = (noteId, direction) => `${noteId}:${direction}`;
@@ -17,10 +24,11 @@ export function newToday(state, now) {
17
24
 
18
25
  // A review is waiting for the whole day it falls due, from midnight: a card answered at 17:00 yesterday
19
26
  // can be done this morning. But never sooner than half a day after it was answered, so a sitting across
20
- // midnight doesn't ask it again minutes later. A card just missed (streak 0) comes back at its minute.
27
+ // midnight doesn't ask it again minutes later. A card still being learned (just missed, or new) comes
28
+ // back at its minute.
21
29
  const MIN_GAP = 12 * 60 * MINUTE;
22
30
  export function readyAt(entry) {
23
- if (!entry.streak) return entry.due;
31
+ if (entry.phase !== "review") return entry.due;
24
32
  const day = new Date(entry.due);
25
33
  day.setHours(0, 0, 0, 0);
26
34
  return Math.min(entry.due, Math.max(day.getTime(), (entry.last ?? 0) + MIN_GAP));
@@ -51,8 +59,8 @@ function pickDue(due, now, random) {
51
59
  }
52
60
 
53
61
  // What to ask next: a due review or a new card (up to the daily cap), mixed at random; null when there
54
- // is nothing to do right now. Cards are never asked before they're due: answering early would move them
55
- // up the boxes without the spacing that makes them stick. Never the same note twice in a row while
62
+ // is nothing to do right now. Cards are never asked before they're due: answering early would count
63
+ // as knowing them without the spacing that makes them stick. Never the same note twice in a row while
56
64
  // anything else is waiting. A `tour` deck is different: each card is asked once, in deck order, and
57
65
  // never comes back as a review. A word's own `directions` (a cloze card's gaps) replace the deck's.
58
66
  export function pickNext({ words, state, now = Date.now(), lastNoteId = null, directions = DIRECTIONS, tour = false, random = Math.random }) {
@@ -92,15 +100,99 @@ export function startOfTomorrow(now) {
92
100
  return date.getTime();
93
101
  }
94
102
 
95
- export function grade(entry, correct, now = Date.now(), { hinted = false } = {}) {
96
- const prev = entry ?? { box: 0, seen: 0, correct: 0, wrong: 0, streak: 0 };
97
- if (correct) {
98
- // right after a miss the card starts over at box 1 (back tomorrow) instead of skipping ahead
99
- const relearning = prev.seen > 0 && prev.streak === 0;
100
- const box = hinted || relearning ? Math.max(prev.box, 1) : Math.min(prev.box + 1, BOX_INTERVALS_DAYS.length);
101
- return { ...prev, box, due: daysLater(now, BOX_INTERVALS_DAYS[box - 1]), seen: prev.seen + 1, correct: prev.correct + 1, streak: prev.streak + 1, last: now };
102
- }
103
- return { ...prev, box: 1, due: now + RELEARN_DELAY, seen: prev.seen + 1, wrong: prev.wrong + 1, streak: 0, last: now };
103
+ // How an answer rates for FSRS: a miss or "didn't know" is Again; right, but with a hint, a typo or
104
+ // "almost" (an article, an umlaut), is Hard; right is Good. Easy isn't used: typing it is the test.
105
+ export const ratingFor = ({ correct, hinted = false, almost = false }) => (!correct ? Rating.Again : hinted || almost ? Rating.Hard : Rating.Good);
106
+
107
+ // a card's progress, as kept in state.json: the answers so far (seen, correct, wrong, streak), when it
108
+ // was last answered and is next due, and FSRS's memory of it
109
+ const PHASES = ["new", "learning", "review", "relearning"]; // FSRS's State, by number
110
+ const round = (value) => Math.round(value * 10_000) / 10_000;
111
+
112
+ function toCard(entry, now) {
113
+ if (!entry) return createEmptyCard(new Date(now));
114
+ return {
115
+ due: new Date(entry.due),
116
+ stability: entry.stability,
117
+ difficulty: entry.difficulty,
118
+ elapsed_days: 0,
119
+ scheduled_days: intervalDays(entry),
120
+ learning_steps: entry.step ?? 0,
121
+ reps: entry.seen,
122
+ lapses: entry.lapses ?? 0,
123
+ state: PHASES.indexOf(entry.phase),
124
+ last_review: new Date(entry.last)
125
+ };
126
+ }
127
+
128
+ // → the card's progress after an answer rated `rating` (see ratingFor) at `now`
129
+ export function grade(entry, rating, now = Date.now()) {
130
+ const prev = entry ?? { seen: 0, correct: 0, wrong: 0, streak: 0 };
131
+ // While a card is being learned, Hard repeats the step instead of moving on. Anki leaves that to
132
+ // you, but here a typo or a hint every time would keep the card at 15 minutes all day: the second
133
+ // right answer in a row (streak > 0 while still learning) moves it on, as Good does.
134
+ if (rating === Rating.Hard && entry && entry.phase !== "review" && entry.streak > 0) rating = Rating.Good;
135
+ // a clock set back since the last answer: FSRS can't answer before that, so it's taken as then
136
+ now = Math.max(now, entry?.last ?? now);
137
+ const { card } = scheduler.next(toCard(entry, now), new Date(now), rating);
138
+ const correct = rating !== Rating.Again;
139
+ const phase = PHASES[card.state];
140
+ // a review lands at the same time of day, so a day with a clock change is still one day
141
+ const due = phase === "review" ? daysLater(now, card.scheduled_days) : card.due.getTime();
142
+ return {
143
+ due,
144
+ last: now,
145
+ seen: prev.seen + 1,
146
+ correct: prev.correct + (correct ? 1 : 0),
147
+ wrong: prev.wrong + (correct ? 0 : 1),
148
+ streak: correct ? prev.streak + 1 : 0,
149
+ phase,
150
+ step: card.learning_steps,
151
+ stability: round(card.stability),
152
+ difficulty: round(card.difficulty),
153
+ lapses: card.lapses,
154
+ box: boxFor(phase === "review" ? card.scheduled_days : 0)
155
+ };
156
+ }
157
+
158
+ // Dracosh 0.5 and older read a Leitner `box` on every card before they look at the file's version, so
159
+ // one is kept, close to the interval: an older Dracosh then says the file is from a newer version
160
+ // instead of calling it damaged. Nothing here reads it.
161
+ const boxFor = (days) => Math.max(1, BOX_DAYS.filter((each) => each <= days).length);
162
+
163
+ // the days between the last answer and the next review (0 while it's still being learned)
164
+ export const intervalDays = (entry) => (entry.phase === "review" ? Math.max(0, Math.round((entry.due - entry.last) / DAY)) : 0);
165
+ export const isMastered = (entry) => intervalDays(entry) >= MASTERED_DAYS;
166
+
167
+ // Progress from Dracosh 0.5 and older, kept in Leitner boxes (1 to 5: 1, 3, 7, 14 and 30 days), as
168
+ // FSRS's memory of it. A box's interval is what the card was last trusted with, so it becomes the
169
+ // stability; the share of misses sets the difficulty, between FSRS's first guess after "Good" and
170
+ // after "Again". A card just missed (streak 0) is still relearning. Its due date stays.
171
+ const BOX_DAYS = [1, 3, 7, 14, 30];
172
+ export function fromBox(entry) {
173
+ const level = Math.min(Math.max(Math.round(entry.box) || 1, 1), BOX_DAYS.length);
174
+ const days = BOX_DAYS[level - 1];
175
+ // a count that isn't a number (a hand-edited file) is taken as none
176
+ const count = (value) => (Number.isFinite(value) && value > 0 ? Math.floor(value) : 0);
177
+ const [seen, correct, wrong, streak] = [count(entry.seen), count(entry.correct), count(entry.wrong), count(entry.streak)];
178
+ const missed = Math.min(wrong / Math.max(seen, 1), 1);
179
+ const [easy, hard] = [scheduler.init_difficulty(Rating.Good), scheduler.init_difficulty(Rating.Again)];
180
+ // never answered after it's due: FSRS counts the days between the two
181
+ const last = Number.isFinite(entry.last) ? Math.min(entry.last, entry.due) : entry.due - days * DAY;
182
+ return {
183
+ ...entry,
184
+ seen,
185
+ correct,
186
+ wrong,
187
+ streak,
188
+ last,
189
+ phase: !streak && seen > 0 ? "relearning" : "review",
190
+ step: 0,
191
+ stability: days,
192
+ difficulty: round(easy + (hard - easy) * missed),
193
+ lapses: wrong,
194
+ box: level
195
+ };
104
196
  }
105
197
 
106
198
  export function describeDue(entry, now = Date.now()) {
package/src/session.js CHANGED
@@ -2,8 +2,8 @@ import { t as say } from "./i18n.js"; // `t` and `text` are taken here (the cloc
2
2
  import { blankGap, plainFront } from "./cardline.js";
3
3
  import { ALMOST, closestCandidate, judge } from "./judge.js";
4
4
  import { addVacation, applyAnswer, applyCaughtUp, markWorkWaiting, applyOverrule, calendarMonth, cancelVacations, ensureProgress, markBadgesSeen, missedOn, recordMiss, snapshot, undoMiss, unseenBadges, vacationInfo } from "./progress.js";
5
- import { BOX_INTERVALS_DAYS, describeDue, grade, itemKey, nextDueAt, pickNext, startOfTomorrow } from "./scheduler.js";
6
- import { recordAnswer, saveState } from "./store.js";
5
+ import { describeDue, grade, intervalDays, itemKey, nextDueAt, pickNext, Rating, ratingFor, startOfTomorrow } from "./scheduler.js";
6
+ import { recordAnswer, saveState, STATE_VERSION } from "./store.js";
7
7
  import { createTipDeck } from "./tips.js";
8
8
  import { dayKey } from "./dates.js";
9
9
  import { parsePause } from "./pause.js";
@@ -32,6 +32,14 @@ export function toSpeak(question, answer = null) {
32
32
 
33
33
  // Quiz logic without any I/O of its own: words, settings and persistence are injected, the UI only renders what this returns.
34
34
  // `loadAllWords` → [{ words, deck }] for every deck of yours: "all done for today" means the whole library.
35
+ // the days until a card comes back (0: minutes away, still being learned), and the days a clean answer
36
+ // would have given it; null when the difference isn't worth a line (a day or two, or under a quarter)
37
+ function heldBack(entry, would) {
38
+ const [days, wouldDays] = [intervalDays(entry), intervalDays(would)];
39
+ const worth = days === 0 ? wouldDays > 0 : wouldDays - days >= 2 && wouldDays >= days * 1.25;
40
+ return worth ? { days, would: wouldDays } : null;
41
+ }
42
+
35
43
  export function createSession({ loadWords, loadAllWords, state, getSettings, save = saveState, now = Date.now, tipDeck = createTipDeck({ state }) }) {
36
44
  const rules = () => ({ skipWeekends: getSettings().skipWeekends });
37
45
  const totals = { asked: 0, correct: 0, combo: 0 };
@@ -134,7 +142,7 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
134
142
  // An empty Enter shows the answer and nothing is written yet: you say whether you knew it (selfGrade).
135
143
  const reveal = (question) => ({ expected: question.expected, example: question.word.example });
136
144
 
137
- // After a reveal. "Knew it" counts exactly like a typed right answer: boxes, goal, streak, combo and
145
+ // After a reveal. "Knew it" counts exactly like a typed right answer: scheduling, goal, streak, combo and
138
146
  // badges. Long answers can't be typed word for word, and they must be able to earn everything too.
139
147
  async function selfGrade(question, knew, { hinted = false } = {}) {
140
148
  return { ...(await record(question, { result: knew ? "exact" : "wrong", text: "", hinted })), self: true };
@@ -146,11 +154,13 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
146
154
  const t = now();
147
155
  const before = state.items[key];
148
156
  const comboBefore = totals.combo;
149
- // almost right (an article left out, an umlaut left plain) counts, but the card doesn't move up, like with a hint
150
- const almost = ALMOST.includes(result);
151
- const entry = grade(before, correct, t, { hinted: hinted || almost });
152
- const would = almost ? grade(before, true, t, { hinted }) : entry; // a hint alone would have held it too
153
- const held = would.box > entry.box ? { days: BOX_INTERVALS_DAYS[entry.box - 1], would: BOX_INTERVALS_DAYS[would.box - 1] } : null;
157
+ // almost right (an article left out, an umlaut left plain) or a typo counts, but like with a hint
158
+ // the card comes back sooner than after a clean answer: `held` says when, and when it would have
159
+ const almost = ALMOST.includes(result) || result === "typo";
160
+ const rating = ratingFor({ correct, hinted, almost });
161
+ const entry = grade(before, rating, t);
162
+ // a tour card never comes back, so there's nothing to say about when
163
+ const held = rating === Rating.Hard && !question.tour ? heldBack(entry, grade(before, Rating.Good, t)) : null;
154
164
  recordAnswer(state, question.word.noteId, question.direction, entry, t, { countNew: !question.tour });
155
165
 
156
166
  totals.asked += 1;
@@ -179,7 +189,7 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
179
189
  const { question, text, key, before, comboBefore, hinted, at } = lastWrong;
180
190
  lastWrong = null;
181
191
 
182
- const entry = grade(before, true, at, { hinted });
192
+ const entry = grade(before, ratingFor({ correct: true, hinted }), at);
183
193
  state.items[key] = entry;
184
194
  undoMiss(state, key, at);
185
195
  state.accepted ??= {};
@@ -264,12 +274,12 @@ export function createSession({ loadWords, loadAllWords, state, getSettings, sav
264
274
  }
265
275
 
266
276
  // Reset from /settings (the caller makes a backup first). "progress" starts the game over: badges,
267
- // streak, stats and the dragon's form and element; your cards and their boxes stay. "everything"
277
+ // streak, stats and the dragon's form and element; your cards and how well you know them stay. "everything"
268
278
  // empties the state as on a fresh install, so the egg hatches again.
269
279
  async function reset(scope) {
270
280
  if (scope === "everything") {
271
281
  for (const key of Object.keys(state)) delete state[key];
272
- Object.assign(state, { version: 1, items: {}, newToday: { date: "", count: 0 } });
282
+ Object.assign(state, { version: STATE_VERSION, items: {}, newToday: { date: "", count: 0 } });
273
283
  } else {
274
284
  delete state.progress;
275
285
  delete state.tips;
package/src/sqlite.js ADDED
@@ -0,0 +1,28 @@
1
+ import * as zlib from "node:zlib";
2
+
3
+ // What Anki packages need from Node: its built-in SQLite (node:sqlite, there without a flag since
4
+ // 22.13) and zstd (22.15), which newer Anki packages are compressed with. Node 22 and 24 still print
5
+ // "SQLite is an experimental feature" when it loads, which tells someone moving a deck nothing, so
6
+ // that one warning is left out. Any other warning still shows.
7
+ export const ANKI_NODE = "22.15";
8
+
9
+ const needsNode = () => Object.assign(new Error(`Anki packages need Node ${ANKI_NODE}`), { code: "NEEDS_NODE", version: ANKI_NODE });
10
+
11
+ export async function loadSqlite() {
12
+ if (typeof zlib.zstdDecompressSync !== "function") throw needsNode();
13
+ const emitWarning = process.emitWarning;
14
+ process.emitWarning = function (warning, ...rest) {
15
+ const type = typeof rest[0] === "string" ? rest[0] : rest[0]?.type;
16
+ if (type === "ExperimentalWarning" && String(warning?.message ?? warning).includes("SQLite")) return;
17
+ return emitWarning.call(this, warning, ...rest);
18
+ };
19
+ try {
20
+ return await import("node:sqlite");
21
+ } catch (err) {
22
+ throw err.code === "ERR_UNKNOWN_BUILTIN_MODULE" ? needsNode() : err;
23
+ } finally {
24
+ process.emitWarning = emitWarning;
25
+ }
26
+ }
27
+
28
+ export const unzstd = (buffer) => zlib.zstdDecompressSync(buffer);