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,381 @@
1
+ import { decodeEntities } from "./entities.js";
2
+ import { gapsOf, parseLine } from "./cardline.js";
3
+ import { normalize } from "./judge.js";
4
+
5
+ // A list of cards read from text: a file being imported, or a list pasted into /add. It's either
6
+ // Dracosh lines (the /add format, "el gato = the cat; kitty // example"), a table (Anki's and
7
+ // Quizlet's tab-separated exports, a spreadsheet's CSV, rows copied from Sheets or Excel), or a plain
8
+ // list written with dashes ("apple - jabłko"). Nothing is guessed silently: what was taken how is
9
+ // returned (`format`, `columns`, `ignored`), so it can be shown before anything is saved.
10
+ //
11
+ // A file can start with "#key:value" lines. Anki's are read (#separator, #html, #columns, #deck,
12
+ // and the #… column ones), and two of Dracosh's own: #deck can come again further down to start the
13
+ // next deck, and #direction says how a new deck is asked (forward, backward or both). Any other line
14
+ // starting with "#" is a comment.
15
+
16
+ const NAMED_SEPARATORS = { tab: "\t", comma: ",", semicolon: ";", pipe: "|", colon: ":", space: " " };
17
+ const TABLE_SEPARATORS = ["\t", ",", ";", "|"];
18
+ const DASHES = [" - ", " – ", " — "];
19
+ export const DIRECTION_HEADERS = { forward: "forward", backward: "backward", both: "both" };
20
+
21
+ // "#separator:Tab" → "\t"; a single character stands for itself
22
+ export function separatorNamed(value) {
23
+ if (value === null || value === undefined) return null;
24
+ const text = String(value);
25
+ const named = NAMED_SEPARATORS[text.trim().toLowerCase()];
26
+ if (named) return named;
27
+ return Array.from(text).length === 1 ? text : null;
28
+ }
29
+
30
+ const looksLikeHtml = (text) => /<\/?(br|div|p|span|b|i|u|strong|em|font|ul|ol|li|img|sup|sub|a)\b[^>]*>|&(nbsp|amp|lt|gt|quot);/i.test(text);
31
+
32
+ // a field from Anki, maybe HTML: its lines, without tags (sounds and images are left out, and so
33
+ // are styles, scripts and a ruby's reading: <ruby>漢字<rt>かんじ</rt></ruby> is 漢字)
34
+ export function htmlLines(html) {
35
+ return decodeEntities(
36
+ String(html)
37
+ .replace(/\[sound:[^\]]*\]/g, "")
38
+ .replace(/<(style|script|rt|rp)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, "")
39
+ .replace(/<br\s*\/?>|<\/?(div|p|li|tr)\b[^>]*>/gi, "\n")
40
+ .replace(/<\/(td|th)\s*>/gi, " ")
41
+ .replace(/<[^>]*>/g, "")
42
+ )
43
+ .split("\n")
44
+ .map((line) => line.replace(/\s+/g, " ").trim())
45
+ .filter(Boolean);
46
+ }
47
+
48
+ // Anki's cloze "{{c1::look forward::hint}}" is a Dracosh gap "{{look forward}}"; other braces in an
49
+ // Anki cloze note are plain text there, so they stay text ("\{{")
50
+ const ANKI_GAP = /\{\{c\d+::(.*?)(?:::[^{}]*?)?\}\}/g;
51
+ const INNERMOST_GAP = /\{\{c\d+::([^{}]*?)(?:::[^{}]*?)?\}\}/g;
52
+ const [OPEN, CLOSE, LITERAL] = ["\u000e", "\u000f", "\u0010"];
53
+ // `anki`: the text comes from an Anki file, where only "{{c1::…}}" is a gap. Anki nests gaps
54
+ // ("{{c1::a {{c2::b}} c}}") and Dracosh doesn't: the outer gap stays, the inner ones are its text.
55
+ const fromAnkiCloze = (text, anki = false) => {
56
+ if (!new RegExp(ANKI_GAP.source).test(text)) return anki ? text.replace(/(?<!\\)\{\{/g, "\\{{") : text;
57
+ let marked = text.replace(/\{\{(?!c\d+::)/g, LITERAL);
58
+ for (let before = ""; before !== marked; ) [before, marked] = [marked, marked.replace(INNERMOST_GAP, `${OPEN}$1${CLOSE}`)];
59
+ let depth = 0;
60
+ let result = "";
61
+ for (const char of marked) {
62
+ if (char === OPEN) result += depth++ ? "" : "{{";
63
+ else if (char === CLOSE) result += --depth ? "" : "}}";
64
+ else result += char;
65
+ }
66
+ return result.replaceAll(LITERAL, "\\{{");
67
+ };
68
+ // "{{c1::come::verb}}": Anki's hints, shown in place of the gap. Dracosh has one hint per card
69
+ const gapHints = (text) => [...new Set([...text.matchAll(/\{\{c\d+::[^{}]*?::([^{}]*?)\}\}/g)].map((match) => match[1].trim()).filter(Boolean))].join(", ");
70
+ // A package from Dracosh writes braces that aren't a gap as "&#123;{" and "::" in a gap as ":&#58;":
71
+ // the same to see in Anki, never read as cloze. They're kept apart until the gaps are found.
72
+ const [BRACE, COLON] = ["\u0011", "\u0012"];
73
+ const hideEntities = (html) => String(html).replace(/&#123;|&#x7b;|&lbrace;/gi, BRACE).replace(/&#58;|&#x3a;|&colon;/gi, COLON);
74
+ const showEntities = (text) => text.replace(new RegExp(`${BRACE}\\{`, "g"), "\\{{").replaceAll(BRACE, "{").replaceAll(COLON, ":");
75
+
76
+ // One Anki note (from a package) → card fields, from its fields' HTML by role. `cloze`: the note
77
+ // type is a cloze one (only then is "{{c1::…}}" a gap; elsewhere braces are text). A cloze note's
78
+ // second field is Anki's Extra, shown after the answer, so it's an example; `hint: true` (Dracosh
79
+ // Cloze) says it's a hint shown with the gap instead. `perLine: true` (Dracosh): one answer a line.
80
+ export function noteFields({ front = "", back = "", example = "", cloze = false, hint = false, perLine = false }) {
81
+ const written = htmlLines(front).join(" ");
82
+ const backLines = htmlLines(back);
83
+ const extra = htmlLines(example);
84
+ const text = cloze ? showEntities(fromAnkiCloze(htmlLines(hideEntities(front)).join(" "), true)) : written;
85
+ if (cloze && gapsOf(text).length) {
86
+ const hintText = hint ? backLines.join(" ") : gapHints(written);
87
+ return { front: text, back: [hintText].filter(Boolean), example: [...(hint ? [] : backLines), ...extra].join(" "), cloze: true, hasBack: true };
88
+ }
89
+ if (perLine) return { front: written, back: backLines, example: extra.join(" "), cloze: false, hasBack: backLines.length > 0 };
90
+ const [answers = "", ...more] = backLines;
91
+ return { front: written, back: splitAnswers(answers), example: [...more, ...extra].join(" "), cloze: false, hasBack: Boolean(answers) };
92
+ }
93
+
94
+ // The header lines at the top ("#key:value"); the rest is the body, its line numbers kept
95
+ function readHeader(lines) {
96
+ const header = {};
97
+ let at = 0;
98
+ for (; at < lines.length; at++) {
99
+ const match = /^#([a-z ]+):(.*)$/i.exec(lines[at]);
100
+ if (!match) break;
101
+ header[match[1].trim().toLowerCase()] = match[2].trim();
102
+ }
103
+ return { header, body: at };
104
+ }
105
+
106
+ // A cell opening with a quote is a quoted one only when its closing quote ends the cell: '"to be" or
107
+ // not' and an unmatched '"Quote me' are plain text that happens to start with a quote
108
+ function closesCell(text, open, separator) {
109
+ for (let i = open + 1; i < text.length; i++) {
110
+ if (text[i] !== '"') continue;
111
+ if (text[i + 1] === '"') {
112
+ i++;
113
+ continue;
114
+ }
115
+ const next = text.slice(i + 1).match(/^[ ]*(.|\n|$)/)[1];
116
+ return next === separator || next === "\n" || next === "";
117
+ }
118
+ return false;
119
+ }
120
+
121
+ // Rows split on a one-character separator, the way spreadsheets write them: a cell in double quotes
122
+ // can hold the separator and line breaks, and "" inside it is one quote. → [{ line, cells, comment }]:
123
+ // `line` is the 1-based line the row starts on; `comment`: the row starts with "#" (with `comments`:
124
+ // then it's the whole line, quotes and all). Empty rows are left out.
125
+ export function splitRows(lines, separator, firstLine = 1, { comments = true } = {}) {
126
+ const text = lines.join("\n");
127
+ const rows = [];
128
+ let cells = [];
129
+ let cell = "";
130
+ let quoted = false;
131
+ let line = firstLine;
132
+ let rowLine = firstLine;
133
+ let cellStart = true;
134
+ let comment = false;
135
+ const endRow = () => {
136
+ cells.push(cell);
137
+ if (cells.some((c) => c.trim())) rows.push({ line: rowLine, cells, comment });
138
+ cells = [];
139
+ cell = "";
140
+ cellStart = true;
141
+ };
142
+ for (let i = 0; i < text.length; i++) {
143
+ const ch = text[i];
144
+ if (quoted) {
145
+ if (ch === '"') {
146
+ if (text[i + 1] === '"') {
147
+ cell += '"';
148
+ i++;
149
+ } else quoted = false;
150
+ } else {
151
+ if (ch === "\n") line++;
152
+ cell += ch;
153
+ }
154
+ continue;
155
+ }
156
+ if (cells.length === 0 && cell === "") {
157
+ comment = comments && ch === "#";
158
+ if (comment) {
159
+ const end = text.indexOf("\n", i);
160
+ cell = text.slice(i, end === -1 ? text.length : end);
161
+ i = (end === -1 ? text.length : end) - 1;
162
+ continue;
163
+ }
164
+ }
165
+ if (ch === '"' && cellStart && cell.trim() === "" && closesCell(text, i, separator)) {
166
+ quoted = true;
167
+ cell = "";
168
+ cellStart = false;
169
+ } else if (ch === separator) {
170
+ cells.push(cell);
171
+ cell = "";
172
+ cellStart = true;
173
+ } else if (ch === "\n") {
174
+ endRow();
175
+ line++;
176
+ rowLine = line;
177
+ } else {
178
+ cell += ch;
179
+ if (ch !== " ") cellStart = false;
180
+ }
181
+ }
182
+ if (cell !== "" || cells.length) endRow();
183
+ return rows;
184
+ }
185
+
186
+ // How well a separator splits these lines into a table: the share of rows with the most common
187
+ // number of cells, when that number is 2 or more (0 otherwise)
188
+ function tableScore(lines, separator) {
189
+ const rows = splitRows(lines.slice(0, 200), separator, 1, { comments: false });
190
+ if (rows.length === 0) return { score: 0, columns: 0 };
191
+ const counts = new Map();
192
+ for (const row of rows) {
193
+ const filled = trimEmpty(row.cells).length;
194
+ counts.set(filled, (counts.get(filled) ?? 0) + 1);
195
+ }
196
+ const [columns, often] = [...counts].sort((a, b) => b[1] - a[1] || b[0] - a[0])[0];
197
+ return { score: columns >= 2 ? often / rows.length : 0, columns };
198
+ }
199
+
200
+ // trailing empty cells don't count: spreadsheets often write a few
201
+ function trimEmpty(cells) {
202
+ let end = cells.length;
203
+ while (end > 0 && !cells[end - 1].trim()) end--;
204
+ return cells.slice(0, end);
205
+ }
206
+
207
+ // A header row names its columns ("front,back,example", "term;definition"); it isn't a card
208
+ const COLUMN_NAMES = {
209
+ front: ["front", "term", "word", "question", "prompt", "expression", "vocabulary", "text", "przód", "termin", "słowo", "pytanie", "vorderseite", "begriff", "wort", "frage", "recto", "terme", "mot", "лицьова", "термін", "слово"],
210
+ back: ["back", "definition", "translation", "answer", "meaning", "tył", "definicja", "tłumaczenie", "odpowiedź", "znaczenie", "rückseite", "definition", "übersetzung", "antwort", "bedeutung", "verso", "traduction", "réponse", "sens", "зворотна", "визначення", "переклад", "відповідь", "значення"],
211
+ example: ["example", "sentence", "context", "notes", "note", "przykład", "zdanie", "notatka", "beispiel", "satz", "exemple", "phrase", "приклад", "речення"],
212
+ deck: ["deck", "talia", "stapel", "paquet", "колода"],
213
+ skip: ["tags", "tag", "guid", "id", "notetype", "note type", "tagi", "schlagwörter", "étiquettes", "теги"]
214
+ };
215
+ export const columnRole = (name) => {
216
+ const key = normalize(name);
217
+ return Object.entries(COLUMN_NAMES).find(([, names]) => names.some((n) => normalize(n) === key))?.[0] ?? null;
218
+ };
219
+ // it names both a front and a back column: "Wort,word" is a card, "Wort,Übersetzung" a header
220
+ const isHeaderRow = (cells) => {
221
+ const roles = cells.map((cell) => columnRole(cell.replace(/^"|"$/g, "")));
222
+ return roles.includes("front") && roles.includes("back");
223
+ };
224
+
225
+ // → { front, back, example, deck, skip: Set } column indexes, from a header row or Anki's headers;
226
+ // without names: front, back, example in that order
227
+ function columnsFrom(names, header = {}) {
228
+ const roles = { front: null, back: null, example: null, deck: null, notetype: null, skip: new Set() };
229
+ const at = (value) => (/^\d+$/.test(String(value ?? "").trim()) ? Number(value) - 1 : null);
230
+ for (const key of ["guid column", "notetype column", "tags column"]) if (at(header[key]) !== null) roles.skip.add(at(header[key]));
231
+ roles.notetype = at(header["notetype column"]);
232
+ if (at(header["deck column"]) !== null) roles.deck = at(header["deck column"]);
233
+ if (names) {
234
+ names.forEach((name, i) => {
235
+ const role = columnRole(name);
236
+ if (role === "skip") roles.skip.add(i);
237
+ else if (role && roles[role] === null && !roles.skip.has(i)) roles[role] = i;
238
+ });
239
+ }
240
+ // the fields left over, in order: front, back, then an example
241
+ let next = 0;
242
+ const free = () => {
243
+ while (next === roles.deck || roles.skip.has(next) || [roles.front, roles.back, roles.example].includes(next)) next++;
244
+ return next++;
245
+ };
246
+ if (roles.front === null) roles.front = free();
247
+ if (roles.back === null) roles.back = free();
248
+ if (roles.example === null && !names) roles.example = free();
249
+ return roles;
250
+ }
251
+
252
+ // "\;" keeps a semicolon inside an answer, as in /add
253
+ const splitAnswers = (text) => text.split(/(?<!\\);/).map((part) => part.replace(/\\;/g, ";").trim()).filter(Boolean);
254
+
255
+ // One table row → card fields. A line break in the back starts the example (Anki notes are often
256
+ // "answer<br>example sentence"); answers are separated by ";" as in /add.
257
+ function rowFields(cells, roles, html, anki = false) {
258
+ const cell = (i) => (i === null || i === undefined ? "" : cells[i] ?? "");
259
+ const lines = (text) => (html || looksLikeHtml(text) ? htmlLines(text) : text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
260
+ const written = lines(cell(roles.front)).join(" ");
261
+ // in an Anki note without "{{c1::…}}" braces are plain text. The note type's name can't tell: Anki
262
+ // names it in its own language ("Cloze" is "Luka", "Lückentext"…)
263
+ const plainNote = roles.notetype !== null && roles.notetype !== undefined && !new RegExp(ANKI_GAP.source).test(written);
264
+ const front = plainNote ? written.replace(/(?<!\\)\{\{/g, "\\{{") : fromAnkiCloze(written, anki);
265
+ const cloze = gapsOf(front).length > 0;
266
+ let [answers = "", ...more] = lines(cell(roles.back));
267
+ // a cloze note's Extra field is shown after the answer, so on its own it's an example, not a hint
268
+ if (anki && cloze && !more.length && !cell(roles.example)) [answers, more] = ["", [answers].filter(Boolean)];
269
+ const example = [...more, ...lines(cell(roles.example))].join(" ");
270
+ // a cloze card's back is one hint, as in /add
271
+ const back = cloze ? [answers.replace(/\\;/g, ";").trim() || (anki ? gapHints(written) : "")].filter(Boolean) : splitAnswers(answers);
272
+ // a card without gaps keeps its braces as they are ("\{{x}}" was only there to say they're text)
273
+ return { front: cloze ? front : front.replace(/\\\{\{/g, "{{"), back, example, cloze, hasBack: Boolean(answers) || cloze };
274
+ }
275
+
276
+ // A dash list's line splits on its first dash; a tab still splits a line that has one
277
+ const dashOf = (line) => DASHES.map((dash) => [dash, line.indexOf(dash)]).filter(([, at]) => at >= 0).sort((a, b) => a[1] - b[1])[0]?.[0];
278
+
279
+ // What kind of list this is, when the header doesn't say: a table when one separator splits nearly
280
+ // every row the same way (a ".csv" file is always one), Dracosh lines when they use " = ", a dash
281
+ // list when most lines have a dash
282
+ function detectFormat(lines, { csv = false, comments = true } = {}) {
283
+ const content = lines.filter((line) => line.trim() && !(comments && line.startsWith("#")));
284
+ const share = (test) => (content.length ? content.filter(test).length / content.length : 0);
285
+ const equals = share((line) => line.includes(" = "));
286
+ // a header row ("front,back", "term\tdefinition") says which separator it is
287
+ const named = TABLE_SEPARATORS.find((separator) => {
288
+ const cells = trimEmpty(content[0]?.split(separator) ?? []);
289
+ return cells.length >= 2 && isHeaderRow(cells);
290
+ });
291
+ if (named) return { format: "table", separator: named };
292
+ if (share((line) => line.includes("\t")) >= Math.max(0.8, equals)) return { format: "table", separator: "\t" };
293
+ if (!csv && equals >= 0.5) return { format: "lines" };
294
+ if (!csv && share((line) => dashOf(line)) >= 0.5) return { format: "dashes" };
295
+ // commas and semicolons in sentences ("Yes, I do") come with a space after them; a spreadsheet's don't
296
+ const prose = (separator) => share((line) => line.includes(`${separator} `)) >= 0.5;
297
+ const best = TABLE_SEPARATORS.filter((separator) => csv || !prose(separator))
298
+ .map((separator) => ({ separator, ...tableScore(content, separator) }))
299
+ .sort((a, b) => b.score - a.score)[0];
300
+ if (best && best.score >= (csv ? 0.5 : 0.9) && content.length >= (csv ? 1 : 2)) return { format: "table", separator: best.separator };
301
+ return csv ? { format: "table", separator: "," } : { format: "lines" };
302
+ }
303
+
304
+ // → { format, separator, header, items: [{ line, deck, direction, source, fields }], columns, ignored,
305
+ // unknown, anki, html }: `unknown` lists "#direction:" lines that name no direction, `anki` says the
306
+ // file has Anki's header lines, `html` that its fields are HTML
307
+ // `line`: where the card starts in the text (1-based); `source`: its text as written (for a fix);
308
+ // `deck` and `direction`: from the "#deck:" and "#direction:" lines above it, if any;
309
+ // `ignored`: the lines with text in a column that isn't read (shown, never dropped silently).
310
+ // `separator` (a name or a character) and `csv` (the file is a .csv) are hints from the caller.
311
+ // `comments: false` (a list pasted into /add) reads every line as a card: no header, no "#" lines.
312
+ export function readCardList(text, { separator: forced = null, csv = false, comments = true } = {}) {
313
+ const all = String(text ?? "").replace(/^\uFEFF/, "").split(/\r\n|\r|\n/);
314
+ const { header, body } = comments ? readHeader(all) : { header: {}, body: 0 };
315
+ // a bulleted list ("- dom - house", "• dom = house") loses its bullets
316
+ const BULLET = /^\s*(?:[-*•]|\d+[.)])\s+/;
317
+ const filled = all.slice(body).filter((line) => line.trim());
318
+ const bulleted = filled.length > 0 && filled.filter((line) => BULLET.test(line)).length * 2 >= filled.length;
319
+ const lines = all.slice(body).map((line) => (bulleted ? line.replace(BULLET, "") : line));
320
+ const html = /^true$/i.test(header.html ?? "");
321
+ const anki = ["separator", "html", "notetype", "notetype column", "guid column"].some((key) => key in header);
322
+ const fromHeader = separatorNamed(forced ?? header.separator);
323
+ const detected = fromHeader ? { format: "table", separator: fromHeader } : detectFormat(lines, { csv, comments });
324
+ const direction = (value) => DIRECTION_HEADERS[String(value ?? "").trim().toLowerCase()] ?? null;
325
+ let deck = header.deck || null;
326
+ // a "#direction:" that isn't one is said, not ignored
327
+ const unknown = [];
328
+ const readDirection = (value, line) => {
329
+ const read = direction(value);
330
+ if (!read && String(value).trim()) unknown.push({ line, text: `#direction:${String(value).trim()}` });
331
+ return read;
332
+ };
333
+ let deckDirection = header.direction === undefined ? null : readDirection(header.direction, body);
334
+ const items = [];
335
+ const ignored = []; // the lines with text in a column that isn't read
336
+ let columns = null;
337
+
338
+ if (detected.format === "table") {
339
+ // "#deck:" and "#direction:" rows switch the deck; other "#" rows are comments
340
+ const rows = [];
341
+ for (const row of splitRows(lines, detected.separator, body + 1, { comments })) {
342
+ if (!row.comment) rows.push(row);
343
+ else rows.push({ ...row, marker: lines[row.line - body - 1].trim() });
344
+ }
345
+ const named = header.columns ? header.columns.split(detected.separator === "\t" ? "\t" : detected.separator).map((name) => name.trim()) : null;
346
+ const first = rows.find((row) => !row.marker) && trimEmpty(rows.find((row) => !row.marker).cells);
347
+ const headerRow = !named && first && first.length >= 2 && isHeaderRow(first);
348
+ const roles = columnsFrom(named ?? (headerRow ? first : null), header);
349
+ // only the columns there are: a two-column list has no example column
350
+ const width = Math.max(0, ...rows.filter((row) => !row.marker).map((row) => trimEmpty(row.cells).length));
351
+ columns = Object.fromEntries(["deck", "front", "back", "example"].map((role) => [role, roles[role] !== null && roles[role] < width ? roles[role] : null]));
352
+ const firstCard = headerRow ? rows.find((row) => !row.marker) : null;
353
+ for (const row of rows) {
354
+ if (row === firstCard) continue;
355
+ if (row.marker) {
356
+ if (/^#deck:/i.test(row.marker)) [deck, deckDirection] = [row.marker.slice(6).trim() || null, null];
357
+ else if (/^#direction:/i.test(row.marker)) deckDirection = readDirection(row.marker.slice(11), row.line);
358
+ continue;
359
+ }
360
+ const used = new Set([roles.front, roles.back, roles.example, roles.deck, ...roles.skip]);
361
+ if (row.cells.some((cell, i) => !used.has(i) && cell.trim())) ignored.push(row.line);
362
+ // a row without the separator: maybe a Dracosh line among the rows
363
+ const fields = row.cells.length === 1 && row.cells[0].includes(" = ") ? parseLine(row.cells[0]) : rowFields(row.cells, roles, html, anki);
364
+ const rowDeck = roles.deck !== null && row.cells[roles.deck]?.trim() ? row.cells[roles.deck].trim() : deck;
365
+ items.push({ line: row.line, deck: rowDeck, direction: deckDirection, source: row.cells.join(detected.separator === "\t" ? "\t" : detected.separator), fields });
366
+ }
367
+ } else {
368
+ lines.forEach((raw, i) => {
369
+ const line = raw.trim();
370
+ if (!line) return;
371
+ if (comments && /^#deck:/i.test(line)) return void ([deck, deckDirection] = [line.slice(6).trim() || null, null]);
372
+ if (comments && /^#direction:/i.test(line)) return void (deckDirection = readDirection(line.slice(11), body + i + 1));
373
+ if (comments && line.startsWith("#")) return; // a comment ("\#" starts a card with "#")
374
+ // a line with a tab is a row copied from a table: front, back, example
375
+ const card = comments && line.startsWith("\\#") ? line.slice(1) : line;
376
+ const fields = card.includes("\t") ? rowFields(card.split("\t"), { front: 0, back: 1, example: 2 }, false) : parseLine(card, { separator: detected.format === "dashes" ? (dashOf(card) ?? " = ") : " = " });
377
+ items.push({ line: body + i + 1, deck, direction: deckDirection, source: line, fields });
378
+ });
379
+ }
380
+ return { format: detected.format, separator: detected.separator ?? null, header, items, columns, ignored, unknown, anki, html };
381
+ }
package/src/cli.js CHANGED
@@ -19,6 +19,7 @@ import { ALREADY_RUNNING, acquireLock, runningPid } from "./lock.js";
19
19
  import * as manage from "./manage.js";
20
20
  import { findDeck } from "./library.js";
21
21
  import { loadAllWords, loadWords, missingDeck } from "./words.js";
22
+ import { runExport, runImport } from "./transfer.js";
22
23
 
23
24
  const help = () => t("cli.help", { interval: formatInterval(DEFAULTS.everyMs), volume: DEFAULTS.volume });
24
25
 
@@ -114,6 +115,11 @@ async function main() {
114
115
  allowPositionals: true,
115
116
  options: {
116
117
  deck: { type: "string" },
118
+ separator: { type: "string" },
119
+ encoding: { type: "string" },
120
+ update: { type: "boolean", default: false },
121
+ anki: { type: "boolean", default: false },
122
+ split: { type: "boolean", default: false },
117
123
  every: { type: "string" },
118
124
  volume: { type: "string" },
119
125
  "no-sound": { type: "boolean", default: false },
@@ -127,6 +133,9 @@ async function main() {
127
133
  if (values.help) return console.log(help());
128
134
  const [command, ...args] = positionals;
129
135
  if (command === "restore") return restore(args[0], values);
136
+ if ((command === "import" || command === "export") && args.length > 1) throw new Error(t("cli.oneFile", { command }));
137
+ if (command === "import") return runImport(args[0], values);
138
+ if (command === "export") return runExport(args[0], values);
130
139
  if (command) throw new Error(t("cli.unknownCommand", { command }));
131
140
  if (values.data) return printData();
132
141
 
@@ -175,6 +184,8 @@ async function main() {
175
184
  }
176
185
 
177
186
  main().catch((err) => {
187
+ // an option Dracosh doesn't have, said in the app's language
188
+ if (err.code === "ERR_PARSE_ARGS_UNKNOWN_OPTION") err.message = t("cli.unknownOption", { option: /'([^']+)'/.exec(err.message)?.[1] ?? "" });
178
189
  if (["EACCES", "EPERM", "ENOTDIR", "EEXIST"].includes(err.code)) {
179
190
  console.error(t("cli.cantUseFolder", { home: HOME, code: err.code }));
180
191
  process.exit(1);
@@ -0,0 +1,40 @@
1
+ // HTML's named characters (the 252 of HTML 4, which is what editors write: Anki's, Quizlet's,
2
+ // spreadsheets'), so "&eacute;t&eacute;" reads "été" and its ";" never splits an answer.
3
+ // decodeEntities("caf&eacute; &mdash; &#233;") → "café — é"
4
+
5
+ const LATIN1 = "nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml";
6
+ const GREEK = "Alpha Beta Gamma Delta Epsilon Zeta Eta Theta Iota Kappa Lambda Mu Nu Xi Omicron Pi Rho";
7
+ const GREEK_END = "Sigma Tau Upsilon Phi Chi Psi Omega";
8
+ const OTHERS = {
9
+ quot: 34, amp: 38, apos: 39, lt: 60, gt: 62, OElig: 338, oelig: 339, Scaron: 352, scaron: 353, Yuml: 376, fnof: 402, circ: 710, tilde: 732,
10
+ sigmaf: 962, thetasym: 977, upsih: 978, piv: 982, ensp: 8194, emsp: 8195, thinsp: 8201, zwnj: 8204, zwj: 8205, lrm: 8206, rlm: 8207,
11
+ ndash: 8211, mdash: 8212, lsquo: 8216, rsquo: 8217, sbquo: 8218, ldquo: 8220, rdquo: 8221, bdquo: 8222, dagger: 8224, Dagger: 8225,
12
+ bull: 8226, hellip: 8230, permil: 8240, prime: 8242, Prime: 8243, lsaquo: 8249, rsaquo: 8250, oline: 8254, frasl: 8260, euro: 8364,
13
+ image: 8465, weierp: 8472, real: 8476, trade: 8482, alefsym: 8501, larr: 8592, uarr: 8593, rarr: 8594, darr: 8595, harr: 8596,
14
+ crarr: 8629, lArr: 8656, uArr: 8657, rArr: 8658, dArr: 8659, hArr: 8660, forall: 8704, part: 8706, exist: 8707, empty: 8709,
15
+ nabla: 8711, isin: 8712, notin: 8713, ni: 8715, prod: 8719, sum: 8721, minus: 8722, lowast: 8727, radic: 8730, prop: 8733,
16
+ infin: 8734, ang: 8736, and: 8743, or: 8744, cap: 8745, cup: 8746, int: 8747, there4: 8756, sim: 8764, cong: 8773, asymp: 8776,
17
+ ne: 8800, equiv: 8801, le: 8804, ge: 8805, sub: 8834, sup: 8835, nsub: 8836, sube: 8838, supe: 8839, oplus: 8853, otimes: 8855,
18
+ perp: 8869, sdot: 8901, lceil: 8968, rceil: 8969, lfloor: 8970, rfloor: 8971, lang: 9001, rang: 9002, loz: 9674, spades: 9824,
19
+ clubs: 9827, hearts: 9829, diams: 9830
20
+ };
21
+
22
+ const NAMED = new Map(Object.entries(OTHERS).map(([name, code]) => [name, String.fromCodePoint(code)]));
23
+ const run = (names, from) => names.split(" ").forEach((name, i) => NAMED.set(name, String.fromCodePoint(from + i)));
24
+ run(LATIN1, 160);
25
+ run(GREEK, 913);
26
+ run(GREEK_END, 931);
27
+ run(GREEK.toLowerCase(), 945);
28
+ run(GREEK_END.toLowerCase(), 963);
29
+ NAMED.set("nbsp", " "); // a space to type, as the answer is typed
30
+ NAMED.set("shy", ""); // a hyphen only where a line breaks
31
+
32
+ // names are case-sensitive ("&Eacute;" isn't "&eacute;"), but "&NBSP;" and "&AMP;" are common enough
33
+ export const decodeEntities = (text) =>
34
+ text.replace(/&(#\d+|#x[0-9a-f]+|[a-z][a-z0-9]*);/gi, (match, name) => {
35
+ if (name.startsWith("#")) {
36
+ const code = /^#x/i.test(name) ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
37
+ return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : match;
38
+ }
39
+ return NAMED.get(name) ?? NAMED.get(name.toLowerCase()) ?? match;
40
+ });
@@ -0,0 +1,71 @@
1
+ import { t } from "./i18n.js";
2
+ import { formatLine, GAP } from "./cardline.js";
3
+ import { cardsOf } from "./library.js";
4
+
5
+ // Decks written out as text, picked by the file's extension:
6
+ // .txt Dracosh lines, as /add takes them, with "#deck:" and "#direction:" above each deck: easy to
7
+ // read and edit (by you or an AI assistant), and `dracosh import` reads it back unchanged
8
+ // .apkg for Anki: a deck package with its own note types (apkg.js)
9
+ // .tsv Anki's plain text: File → Import takes it as it is (tab-separated, with Anki's header lines)
10
+ // .csv for spreadsheets: front, back, example (and deck, when there are several)
11
+ // A full backup (.json) is backup.js's job. Each function takes the decks to write and the library.
12
+
13
+ export const EXPORT_FORMATS = ["txt", "apkg", "tsv", "csv", "json"];
14
+
15
+ // a line starting with "#" would read as a comment: "\#" keeps it a card (and "\\#" a "\#" front)
16
+ const keepHash = (line) => (/^\\*#/.test(line) ? `\\${line}` : line);
17
+
18
+ export function toDracoshText(library, decks, { now = Date.now() } = {}) {
19
+ const parts = [`# ${t("export.fileHeader", { date: new Date(now).toISOString().slice(0, 10) })}`, `# ${t("export.fileHowTo")}`];
20
+ for (const deck of decks) {
21
+ parts.push("", `#deck:${deck.name}`, `#direction:${deck.directions}`);
22
+ for (const card of cardsOf(library, deck.id)) parts.push(keepHash(formatLine(card)));
23
+ }
24
+ return `${parts.join("\n")}\n`;
25
+ }
26
+
27
+ // RFC 4180: a cell with the separator, a quote, a line break or a leading "#" goes in quotes
28
+ const cell = (value, separator) => {
29
+ const text = String(value ?? "");
30
+ return text.includes(separator) || /["\r\n]/.test(text) || text.startsWith("#") || text !== text.trim() ? `"${text.replace(/"/g, '""')}"` : text;
31
+ };
32
+ const row = (cells, separator) => cells.map((value) => cell(value, separator)).join(separator);
33
+
34
+ export function toCsv(library, decks) {
35
+ const several = decks.length > 1;
36
+ const lines = [row([...(several ? ["deck"] : []), "front", "back", "example"], ",")];
37
+ for (const deck of decks) {
38
+ for (const card of cardsOf(library, deck.id)) lines.push(row([...(several ? [deck.name] : []), textFront(card), joinAnswers(card.back), card.example ?? ""], ","));
39
+ }
40
+ return `${lines.join("\r\n")}\r\n`;
41
+ }
42
+
43
+ // braces in a card without gaps are text: "\{{" keeps them from reading as a gap again
44
+ const textFront = (card) => (card.cloze ? card.front : card.front.replace(/\{\{/g, "\\{{"));
45
+
46
+ // answers joined by ";" as in /add: one holding a ";" keeps it as "\;"
47
+ export const joinAnswers = (back) => back.map((answer) => answer.replace(/;/g, "\\;")).join("; ");
48
+
49
+ export const escapeHtml = (text) => String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
50
+
51
+ // For Anki, one kind of card per file (`cloze`: the cloze cards, otherwise the others). Anki names its
52
+ // note types in the language it was set up in ("Basic" is "Podstawowy", "Einfach"…) and finds them by
53
+ // name, so a file mixing both kinds would import nothing there; one kind per file lets Anki fall back
54
+ // to the note type picked in its import dialog. Anki's "Basic" note has two fields, so the example
55
+ // goes under the answers, on a line of its own; a cloze card becomes a "Cloze" note ("{{c1::…}}"),
56
+ // its back the "Back Extra" field.
57
+ export function toAnki(library, decks, { cloze = false } = {}) {
58
+ const cards = decks.flatMap((deck) => cardsOf(library, deck.id).filter((card) => Boolean(card.cloze) === cloze).map((card) => ({ deck, card })));
59
+ const several = new Set(cards.map(({ deck }) => deck.id)).size > 1;
60
+ const header = ["#separator:tab", "#html:true", `#notetype:${cloze ? "Cloze" : "Basic"}`];
61
+ if (several) header.push("#deck column:1");
62
+ else header.push(`#deck:${cards[0]?.deck.name ?? decks[0]?.name ?? ""}`);
63
+ const lines = cards.map(({ deck, card }) => {
64
+ let gap = 0;
65
+ // the same gaps as the quiz asks (GAP); braces kept as text ("\{{") are plain text in Anki too
66
+ const front = card.cloze ? escapeHtml(card.front.replace(GAP, (_, text) => `{{c${++gap}::${text}}}`).replace(/\\\{\{/g, "{{")) : escapeHtml(card.front);
67
+ const back = [escapeHtml(joinAnswers(card.back)), card.example ? escapeHtml(card.example) : ""].filter(Boolean).join("<br>");
68
+ return row([...(several ? [deck.name] : []), front, back], "\t");
69
+ });
70
+ return `${[...header, ...lines].join("\n")}\n`;
71
+ }