dracosh 0.4.0 → 0.5.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));
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.
@@ -88,10 +88,12 @@ export function createDeck(library, { name, type = "translation", languages = nu
88
88
  }
89
89
 
90
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) {
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/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);
package/src/store.js CHANGED
@@ -61,8 +61,15 @@ export const saveLibrary = (library) => writeJson(LIBRARY_FILE, library);
61
61
  export async function loadState() {
62
62
  const state = await readJson(STATE_FILE, undefined);
63
63
  if (state === undefined) return emptyState();
64
- if (!isObject(state) || !isObject(state.items)) throw damaged(STATE_FILE, t("errors.why.noProgress"));
65
- if (!Object.values(state.items).every((entry) => isObject(entry) && Number.isFinite(entry.box) && Number.isFinite(entry.due))) throw damaged(STATE_FILE, t("errors.why.progressEntry"));
64
+ checkState(state, STATE_FILE);
65
+ if (!isObject(state.newToday)) state.newToday = { date: "", count: 0 };
66
+ return state;
67
+ }
68
+
69
+ // throws when `state` (read from `file`) isn't progress the quiz can use
70
+ export function checkState(state, file = STATE_FILE) {
71
+ if (!isObject(state) || !isObject(state.items)) throw damaged(file, t("errors.why.noProgress"));
72
+ if (!Object.values(state.items).every((entry) => isObject(entry) && Number.isFinite(entry.box) && Number.isFinite(entry.due))) throw damaged(file, t("errors.why.progressEntry"));
66
73
  const { progress } = state;
67
74
  const validProgress =
68
75
  isObject(progress) &&
@@ -72,10 +79,8 @@ export async function loadState() {
72
79
  ["count", "best", "freezes"].every((key) => Number.isFinite(progress.streak[key])) &&
73
80
  isObject(progress.badges) &&
74
81
  (progress.vacations === undefined || Array.isArray(progress.vacations));
75
- if (progress !== undefined && !validProgress) throw damaged(STATE_FILE, t("errors.why.streak"));
76
- if (state.version > STATE_VERSION) throw new Error(t("errors.newerState", { file: STATE_FILE }));
77
- if (!isObject(state.newToday)) state.newToday = { date: "", count: 0 };
78
- return state;
82
+ if (progress !== undefined && !validProgress) throw damaged(file, t("errors.why.streak"));
83
+ if (state.version > STATE_VERSION) throw new Error(t("errors.newerState", { file }));
79
84
  }
80
85
  export const saveState = (state) => writeJson(STATE_FILE, state);
81
86