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.
- package/README.md +71 -5
- package/locales/de.json +230 -3
- package/locales/en.json +230 -3
- package/locales/fr.json +252 -3
- package/locales/pl.json +274 -3
- package/locales/uk.json +274 -3
- package/package.json +2 -2
- package/src/ankiconnect.js +106 -0
- package/src/apkg.js +472 -0
- package/src/backup.js +12 -1
- package/src/cardline.js +11 -3
- package/src/cardlist.js +381 -0
- package/src/cli.js +11 -0
- package/src/entities.js +40 -0
- package/src/exporter.js +71 -0
- package/src/importer.js +222 -0
- package/src/judge.js +4 -0
- package/src/language.js +6 -0
- package/src/library.js +19 -10
- package/src/sqlite.js +28 -0
- package/src/store.js +11 -6
- package/src/transfer.js +557 -0
- package/src/ui/AddCard.js +18 -25
- package/src/ui/AnswerInput.js +3 -3
- package/src/zip.js +157 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dracosh",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "A gamified language or definitions trainer for your terminal. Your personal pixel dragon grows with your progress.",
|
|
5
5
|
"author": "Tomasz Przyborowski (https://github.com/lynthius)",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"NOTICE"
|
|
35
35
|
],
|
|
36
36
|
"engines": {
|
|
37
|
-
"node": ">=22"
|
|
37
|
+
"node": ">=22.15"
|
|
38
38
|
},
|
|
39
39
|
"scripts": {
|
|
40
40
|
"start": "node src/cli.js",
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { request } from "node:http";
|
|
2
|
+
|
|
3
|
+
// Talking to a running Anki through the AnkiConnect add-on (code 2055492159): JSON over HTTP on
|
|
4
|
+
// 127.0.0.1:8765, API version 6. Cards move as Anki's own packages, made and read by Anki itself
|
|
5
|
+
// (exportPackage, importPackage), so they go the same tested way as an .apkg file.
|
|
6
|
+
// DRACOSH_ANKI_URL points elsewhere; DRACOSH_ANKI_KEY is the key, when AnkiConnect is set to ask one.
|
|
7
|
+
// const anki = connect(); await anki("deckNames") → ["Default", "Spanish", …]
|
|
8
|
+
|
|
9
|
+
const API_VERSION = 6;
|
|
10
|
+
// AnkiConnect answers from Anki's main thread: a busy Anki (syncing, checking its database) or one
|
|
11
|
+
// macOS has put to sleep in the background (App Nap) takes the call and says nothing. A question
|
|
12
|
+
// waits this long; writing or reading a whole package (media too) may take minutes.
|
|
13
|
+
const QUICK = 15_000;
|
|
14
|
+
const SLOW = 10 * 60_000;
|
|
15
|
+
const SLOW_ACTIONS = new Set(["exportPackage", "importPackage"]);
|
|
16
|
+
|
|
17
|
+
// → an error with a code: NO_ANKI (nothing answers), ANKI_BUSY (it took the call, no answer),
|
|
18
|
+
// BAD_URL, OLD_ANKICONNECT, ANKI_KEY, NO_DECK, NOT_IMPORTED, or ANKI_ERROR (Anki said no; its words
|
|
19
|
+
// in `detail`)
|
|
20
|
+
const failure = (code, detail = "") => Object.assign(new Error(`AnkiConnect: ${code} ${detail}`.trim()), { code, detail });
|
|
21
|
+
// a reply of API version 6, { result, error } → its result, or the failure it says
|
|
22
|
+
const resultOf = (reply) => {
|
|
23
|
+
if (reply === null || typeof reply !== "object" || !("result" in reply)) throw failure("OLD_ANKICONNECT");
|
|
24
|
+
if (reply.error) throw /api key/i.test(reply.error) ? failure("ANKI_KEY") : failure("ANKI_ERROR", String(reply.error));
|
|
25
|
+
return reply.result;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export function connect({ url = process.env.DRACOSH_ANKI_URL || "http://127.0.0.1:8765", key = process.env.DRACOSH_ANKI_KEY || null } = {}) {
|
|
29
|
+
let target = null;
|
|
30
|
+
try {
|
|
31
|
+
target = new URL(url);
|
|
32
|
+
} catch {}
|
|
33
|
+
if (target?.protocol !== "http:") target = null;
|
|
34
|
+
const call = (action, params = {}) =>
|
|
35
|
+
new Promise((resolve, reject) => {
|
|
36
|
+
if (!target) return reject(failure("BAD_URL", url));
|
|
37
|
+
const body = JSON.stringify({ action, version: API_VERSION, params, ...(key && { key }) });
|
|
38
|
+
// node:http sends no Origin header, which AnkiConnect lets through without asking; a
|
|
39
|
+
// connection of its own each time (agent: false) is closed when answered, so nothing left
|
|
40
|
+
// open keeps Dracosh from exiting
|
|
41
|
+
const timeout = SLOW_ACTIONS.has(action) ? SLOW : QUICK;
|
|
42
|
+
const req = request(target, { method: "POST", agent: false, headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) }, timeout }, (res) => {
|
|
43
|
+
const chunks = [];
|
|
44
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
45
|
+
res.on("end", () => {
|
|
46
|
+
try {
|
|
47
|
+
resolve(resultOf(JSON.parse(Buffer.concat(chunks).toString("utf8"))));
|
|
48
|
+
} catch (err) {
|
|
49
|
+
reject(err.code ? err : failure("NO_ANKI", "the answer isn't AnkiConnect's"));
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
req.on("timeout", () => req.destroy(failure("ANKI_BUSY")));
|
|
54
|
+
req.on("error", (err) => reject(err.code === "ANKI_BUSY" ? err : failure("NO_ANKI", err.code ?? err.message)));
|
|
55
|
+
req.end(body);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
let checked = null;
|
|
59
|
+
// the first call checks that it's an AnkiConnect new enough for API version 6
|
|
60
|
+
const anki = async (action, params) => {
|
|
61
|
+
checked ??= call("version").then((version) => {
|
|
62
|
+
if (!(Number(version) >= API_VERSION)) throw failure("OLD_ANKICONNECT");
|
|
63
|
+
});
|
|
64
|
+
await checked;
|
|
65
|
+
return call(action, params);
|
|
66
|
+
};
|
|
67
|
+
// the actions in a "multi" are each checked like a request of their own: version and key too
|
|
68
|
+
anki.action = (action, params) => ({ action, version: API_VERSION, params, ...(key && { key }) });
|
|
69
|
+
return anki;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// "Spanish" before "Spanish Extra", with "Spanish::Verbs" right under its parent
|
|
73
|
+
const byName = (a, b) => {
|
|
74
|
+
const [left, right] = [a.split("::"), b.split("::")];
|
|
75
|
+
for (let i = 0; i < Math.min(left.length, right.length); i++) if (left[i] !== right[i]) return left[i].localeCompare(right[i]);
|
|
76
|
+
return left.length - right.length;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// Anki's decks → [{ name, notes, filtered }]: `notes` counts its subdecks' too, and those with cards
|
|
80
|
+
// lent to a filtered deck for now (one Anki note is one Dracosh card); a `filtered` deck only borrows
|
|
81
|
+
// cards (its config says "dyn")
|
|
82
|
+
export async function ankiDecks(anki) {
|
|
83
|
+
const names = (await anki("deckNames")).sort(byName);
|
|
84
|
+
// in Anki's search "*" and "_" are wildcards: escaped, they're the name's own characters
|
|
85
|
+
const query = (name) => `deck:"${name.replace(/(["\\*_])/g, "\\$1")}"`;
|
|
86
|
+
const replies = await anki("multi", { actions: names.flatMap((name) => [anki.action("findNotes", { query: query(name) }), anki.action("getDeckConfig", { deck: name })]) });
|
|
87
|
+
return names.map((name, i) => ({ name, notes: resultOf(replies[2 * i])?.length ?? 0, filtered: Boolean(resultOf(replies[2 * i + 1])?.dyn) }));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// a deck as an .apkg written by Anki at `path` (AnkiConnect's exportPackage, subdecks included).
|
|
91
|
+
// With scheduling, so a card lent to a filtered deck still says which deck is its own.
|
|
92
|
+
export async function exportDeck(anki, deck, path) {
|
|
93
|
+
if (!(await anki("exportPackage", { deck, path, includeSched: true }))) throw failure("NO_DECK", deck);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// the name and fields of the note type with that id in Anki, or null when there's none
|
|
97
|
+
export async function noteType(anki, id) {
|
|
98
|
+
const name = Object.entries(await anki("modelNamesAndIds")).find(([, each]) => Number(each) === id)?.[0];
|
|
99
|
+
return name === undefined ? null : { name, fields: await anki("modelFieldNames", { modelName: name }) };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// an .apkg at `path` imported by Anki, as File → Import does (notes it has already, newer here,
|
|
103
|
+
// are updated)
|
|
104
|
+
export async function importIntoAnki(anki, path) {
|
|
105
|
+
if (!(await anki("importPackage", { path }))) throw failure("NOT_IMPORTED");
|
|
106
|
+
}
|
package/src/apkg.js
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { columnRole, htmlLines, noteFields } from "./cardlist.js";
|
|
6
|
+
import { GAP } from "./cardline.js";
|
|
7
|
+
import { escapeHtml } from "./exporter.js";
|
|
8
|
+
import { cardsOf } from "./library.js";
|
|
9
|
+
import { loadSqlite, unzstd } from "./sqlite.js";
|
|
10
|
+
import { readZip, writeZip } from "./zip.js";
|
|
11
|
+
|
|
12
|
+
// An Anki deck package (.apkg): a zip with the collection as an SQLite file, in the schema Anki
|
|
13
|
+
// writes with "Support older Anki versions" (schema 11, as genanki writes it), so every Anki
|
|
14
|
+
// since 2.1 opens it, and AnkiDroid and AnkiMobile too.
|
|
15
|
+
//
|
|
16
|
+
// The package brings its own two note types, so it opens the same in an Anki set up in any language
|
|
17
|
+
// (a text file can only name a note type, and Anki names its own in its language):
|
|
18
|
+
// Dracosh Front, Back (one answer a line), Example, Forward, Backward: a card is made for
|
|
19
|
+
// each way the deck asks ("y" in Forward and/or Backward), as Anki's own "optional
|
|
20
|
+
// reversed card" does
|
|
21
|
+
// Dracosh Cloze Text ({{c1::…}} for each gap), Hint (shown with the gap), Example
|
|
22
|
+
// Their ids are fixed and they only change with NOTE_TYPES_VERSION, so a second export reuses the
|
|
23
|
+
// note types already in Anki. Each note's guid comes from the card's id, so it updates the notes
|
|
24
|
+
// already there instead of adding them again (Anki updates a note when it's newer: changing how a
|
|
25
|
+
// deck asks makes its notes newer too). Progress isn't written: the cards arrive as new.
|
|
26
|
+
|
|
27
|
+
const BASIC_ID = 1760358162311;
|
|
28
|
+
const CLOZE_ID = 1760358162312;
|
|
29
|
+
const NOTE_TYPES_VERSION = 1760358162; // a template or field changed → a new timestamp here
|
|
30
|
+
const DEFAULT_DECK = 1;
|
|
31
|
+
|
|
32
|
+
const CSS = `.card {
|
|
33
|
+
font-family: arial;
|
|
34
|
+
font-size: 20px;
|
|
35
|
+
line-height: 1.5;
|
|
36
|
+
text-align: center;
|
|
37
|
+
color: black;
|
|
38
|
+
background-color: white;
|
|
39
|
+
}
|
|
40
|
+
.example, .hint {
|
|
41
|
+
margin-top: 0.8em;
|
|
42
|
+
font-size: 0.8em;
|
|
43
|
+
color: #555;
|
|
44
|
+
}
|
|
45
|
+
.example { font-style: italic; }
|
|
46
|
+
.nightMode .example, .nightMode .hint { color: #aaa; }
|
|
47
|
+
.cloze { font-weight: bold; color: blue; }
|
|
48
|
+
.nightMode .cloze { color: lightblue; }
|
|
49
|
+
`;
|
|
50
|
+
|
|
51
|
+
const EXAMPLE = '{{#Example}}<div class="example">{{Example}}</div>{{/Example}}';
|
|
52
|
+
const HINT = '{{#Hint}}<div class="hint">{{Hint}}</div>{{/Hint}}';
|
|
53
|
+
const ANSWER = "\n\n<hr id=answer>\n\n";
|
|
54
|
+
|
|
55
|
+
const field = (name, ord, description = "") => ({ name, ord, sticky: false, rtl: false, font: "Arial", size: 20, description, plainText: false, collapsed: false, excludeFromSearch: false });
|
|
56
|
+
const template = (name, ord, qfmt, afmt) => ({ name, ord, qfmt, afmt, bqfmt: "", bafmt: "", did: null, bfont: "", bsize: 0 });
|
|
57
|
+
const noteType = (fields) => ({ mod: NOTE_TYPES_VERSION, usn: -1, sortf: 0, did: null, tags: [], vers: [], css: CSS, latexPre: LATEX_PRE, latexPost: "\\end{document}", latexsvg: false, ...fields });
|
|
58
|
+
const LATEX_PRE = "\\documentclass[12pt]{article}\n\\special{papersize=3in,5in}\n\\usepackage[utf8]{inputenc}\n\\usepackage{amssymb,amsmath}\n\\pagestyle{empty}\n\\setlength{\\parindent}{0in}\n\\begin{document}\n";
|
|
59
|
+
|
|
60
|
+
const NOTE_TYPES = {
|
|
61
|
+
[BASIC_ID]: noteType({
|
|
62
|
+
id: BASIC_ID,
|
|
63
|
+
name: "Dracosh",
|
|
64
|
+
type: 0,
|
|
65
|
+
flds: [field("Front", 0), field("Back", 1), field("Example", 2), field("Forward", 3, "y: ask front → back"), field("Backward", 4, "y: ask back → front")],
|
|
66
|
+
tmpls: [
|
|
67
|
+
template("Forward", 0, "{{#Forward}}{{Front}}{{/Forward}}", `{{FrontSide}}${ANSWER}{{Back}}${EXAMPLE}`),
|
|
68
|
+
template("Backward", 1, "{{#Backward}}{{Back}}{{/Backward}}", `{{FrontSide}}${ANSWER}{{Front}}${EXAMPLE}`)
|
|
69
|
+
],
|
|
70
|
+
req: [
|
|
71
|
+
[0, "all", [0, 3]],
|
|
72
|
+
[1, "all", [1, 4]]
|
|
73
|
+
]
|
|
74
|
+
}),
|
|
75
|
+
[CLOZE_ID]: noteType({
|
|
76
|
+
id: CLOZE_ID,
|
|
77
|
+
name: "Dracosh Cloze",
|
|
78
|
+
type: 1,
|
|
79
|
+
flds: [field("Text", 0), field("Hint", 1), field("Example", 2)],
|
|
80
|
+
tmpls: [template("Cloze", 0, `{{cloze:Text}}${HINT}`, `{{cloze:Text}}${HINT}${EXAMPLE}`)],
|
|
81
|
+
req: [[0, "any", [0]]]
|
|
82
|
+
})
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
// Dracosh's note types → [{ id, name, fields }], to see whether the ones in Anki are still as written
|
|
86
|
+
// here (Anki knows them by id; a name can be changed there)
|
|
87
|
+
export const NOTE_TYPE_FIELDS = Object.values(NOTE_TYPES).map((type) => ({ id: type.id, name: type.name, fields: type.flds.map((field) => field.name) }));
|
|
88
|
+
|
|
89
|
+
const deckEntry = (id, name, mod) => ({
|
|
90
|
+
id,
|
|
91
|
+
mod,
|
|
92
|
+
name,
|
|
93
|
+
usn: -1,
|
|
94
|
+
lrnToday: [0, 0],
|
|
95
|
+
revToday: [0, 0],
|
|
96
|
+
newToday: [0, 0],
|
|
97
|
+
timeToday: [0, 0],
|
|
98
|
+
collapsed: false,
|
|
99
|
+
browserCollapsed: false,
|
|
100
|
+
desc: "",
|
|
101
|
+
dyn: 0,
|
|
102
|
+
conf: 1,
|
|
103
|
+
extendNew: 0,
|
|
104
|
+
extendRev: 0
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
const DECK_CONFIG = {
|
|
108
|
+
1: {
|
|
109
|
+
id: 1,
|
|
110
|
+
mod: 0,
|
|
111
|
+
name: "Default",
|
|
112
|
+
usn: 0,
|
|
113
|
+
maxTaken: 60,
|
|
114
|
+
autoplay: true,
|
|
115
|
+
timer: 0,
|
|
116
|
+
replayq: true,
|
|
117
|
+
dyn: false,
|
|
118
|
+
new: { bury: false, delays: [1, 10], initialFactor: 2500, ints: [1, 4, 0], order: 1, perDay: 20 },
|
|
119
|
+
rev: { bury: false, ease4: 1.3, ivlFct: 1, maxIvl: 36500, perDay: 200, hardFactor: 1.2 },
|
|
120
|
+
lapse: { delays: [10], leechAction: 1, leechFails: 8, minInt: 1, mult: 0 }
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const SCHEMA = `
|
|
125
|
+
CREATE TABLE col (id integer PRIMARY KEY, crt integer NOT NULL, mod integer NOT NULL, scm integer NOT NULL, ver integer NOT NULL, dty integer NOT NULL, usn integer NOT NULL, ls integer NOT NULL, conf text NOT NULL, models text NOT NULL, decks text NOT NULL, dconf text NOT NULL, tags text NOT NULL);
|
|
126
|
+
CREATE TABLE notes (id integer PRIMARY KEY, guid text NOT NULL, mid integer NOT NULL, mod integer NOT NULL, usn integer NOT NULL, tags text NOT NULL, flds text NOT NULL, sfld integer NOT NULL, csum integer NOT NULL, flags integer NOT NULL, data text NOT NULL);
|
|
127
|
+
CREATE TABLE cards (id integer PRIMARY KEY, nid integer NOT NULL, did integer NOT NULL, ord integer NOT NULL, mod integer NOT NULL, usn integer NOT NULL, type integer NOT NULL, queue integer NOT NULL, due integer NOT NULL, ivl integer NOT NULL, factor integer NOT NULL, reps integer NOT NULL, lapses integer NOT NULL, left integer NOT NULL, odue integer NOT NULL, odid integer NOT NULL, flags integer NOT NULL, data text NOT NULL);
|
|
128
|
+
CREATE TABLE revlog (id integer PRIMARY KEY, cid integer NOT NULL, usn integer NOT NULL, ease integer NOT NULL, ivl integer NOT NULL, lastIvl integer NOT NULL, factor integer NOT NULL, time integer NOT NULL, type integer NOT NULL);
|
|
129
|
+
CREATE TABLE graves (usn integer NOT NULL, oid integer NOT NULL, type integer NOT NULL);
|
|
130
|
+
CREATE INDEX ix_notes_usn ON notes (usn);
|
|
131
|
+
CREATE INDEX ix_cards_usn ON cards (usn);
|
|
132
|
+
CREATE INDEX ix_revlog_usn ON revlog (usn);
|
|
133
|
+
CREATE INDEX ix_cards_nid ON cards (nid);
|
|
134
|
+
CREATE INDEX ix_cards_sched ON cards (did, queue, due);
|
|
135
|
+
CREATE INDEX ix_revlog_cid ON revlog (cid);
|
|
136
|
+
CREATE INDEX ix_notes_csum ON notes (csum);
|
|
137
|
+
`;
|
|
138
|
+
|
|
139
|
+
const sha1 = (text) => createHash("sha1").update(text).digest();
|
|
140
|
+
// the same Dracosh card always gets the same guid; Anki matches notes by it
|
|
141
|
+
const guidOf = (cardId) => sha1(`dracosh card ${cardId}`).toString("base64url").slice(0, 10);
|
|
142
|
+
// a deck id that stays the same between exports (Anki's own are millisecond timestamps)
|
|
143
|
+
const deckIdOf = (deckId) => 1_000_000_000_000 + (sha1(`dracosh deck ${deckId}`).readUInt32BE(0) % 1_000_000_000) * 1000;
|
|
144
|
+
// Anki's sort field and checksum: the first field without HTML, its sha1's first 8 hex digits
|
|
145
|
+
const unhtml = (html) => html.replace(/<[^>]*>/g, "").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
|
146
|
+
const checksum = (html) => sha1(unhtml(html)).readUInt32BE(0);
|
|
147
|
+
const tagsOf = (tags = []) => (tags.length ? ` ${tags.map((tag) => tag.replace(/\s+/g, "_")).join(" ")} ` : "");
|
|
148
|
+
|
|
149
|
+
// a card → the note's fields and the templates to make cards from ("ord")
|
|
150
|
+
function noteOf(card, deck) {
|
|
151
|
+
const example = card.example ? escapeHtml(card.example) : "";
|
|
152
|
+
if (card.cloze) {
|
|
153
|
+
let gap = 0;
|
|
154
|
+
// Braces kept as text ("\{{") go to Anki as "{{", which it shows as "{{" but never reads as a
|
|
155
|
+
// gap; in a gap, "::" would start Anki's hint, so it goes as "::" for the same reason
|
|
156
|
+
const text = card.front
|
|
157
|
+
.split(GAP)
|
|
158
|
+
.map((part, i) => (i % 2 ? `{{c${++gap}::${escapeHtml(part).replace(/::/g, "::")}}}` : escapeHtml(part.replace(/\\\{\{/g, "{{")).replace(/\{\{/g, "{{")))
|
|
159
|
+
.join("");
|
|
160
|
+
return { mid: CLOZE_ID, fields: [text, escapeHtml(card.back.join("; ")), example], ords: [...Array(gap).keys()] };
|
|
161
|
+
}
|
|
162
|
+
const forward = deck.directions !== "backward";
|
|
163
|
+
const backward = deck.directions !== "forward";
|
|
164
|
+
const fields = [escapeHtml(card.front), card.back.map(escapeHtml).join("<br>"), example, forward ? "y" : "", backward ? "y" : ""];
|
|
165
|
+
return { mid: BASIC_ID, fields, ords: [...(forward ? [0] : []), ...(backward ? [1] : [])] };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// The decks' cards as an .apkg file → Buffer. SQLite is loaded only here, for this. `skip`: cards
|
|
169
|
+
// to leave out (what Anki has already, for `export --anki`).
|
|
170
|
+
export async function toApkg(library, decks, { now = Date.now(), skip = () => false } = {}) {
|
|
171
|
+
const { DatabaseSync } = await loadSqlite();
|
|
172
|
+
const folder = mkdtempSync(join(tmpdir(), "dracosh-apkg-"));
|
|
173
|
+
try {
|
|
174
|
+
const path = join(folder, "collection.anki2");
|
|
175
|
+
const db = new DatabaseSync(path);
|
|
176
|
+
try {
|
|
177
|
+
writeCollection(db, library, decks, now, skip);
|
|
178
|
+
} finally {
|
|
179
|
+
db.close();
|
|
180
|
+
}
|
|
181
|
+
return writeZip(
|
|
182
|
+
[
|
|
183
|
+
{ name: "collection.anki2", data: readFileSync(path) },
|
|
184
|
+
{ name: "media", data: Buffer.from("{}") }
|
|
185
|
+
],
|
|
186
|
+
{ date: new Date(now) }
|
|
187
|
+
);
|
|
188
|
+
} finally {
|
|
189
|
+
rmSync(folder, { recursive: true, force: true });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function writeCollection(db, library, decks, now, skip) {
|
|
194
|
+
db.exec(SCHEMA);
|
|
195
|
+
const seconds = Math.floor(now / 1000);
|
|
196
|
+
// a package always has Anki's Default deck (id 1); a Dracosh deck called that is that deck, or Anki
|
|
197
|
+
// would see two of the same name
|
|
198
|
+
const isDefault = (deck) => deck.name.trim().toLowerCase() === "default";
|
|
199
|
+
const deckIds = new Map(decks.map((deck) => [deck.id, isDefault(deck) ? DEFAULT_DECK : deckIdOf(deck.id)]));
|
|
200
|
+
const ankiDecks = { [DEFAULT_DECK]: deckEntry(DEFAULT_DECK, "Default", seconds) };
|
|
201
|
+
for (const deck of decks) ankiDecks[deckIds.get(deck.id)] = deckEntry(deckIds.get(deck.id), deck.name, seconds);
|
|
202
|
+
const conf = { activeDecks: [DEFAULT_DECK], curDeck: DEFAULT_DECK, curModel: BASIC_ID, nextPos: 1, sortType: "noteFld", sortBackwards: false, addToCur: true, newSpread: 0, collapseTime: 1200, timeLim: 0, estTimes: true, dueCounts: true, schedVer: 2 };
|
|
203
|
+
db.prepare("INSERT INTO col VALUES (1, ?, ?, ?, 11, 0, 0, 0, ?, ?, ?, ?, '{}')").run(
|
|
204
|
+
Math.floor(new Date(now).setHours(4, 0, 0, 0) / 1000),
|
|
205
|
+
now,
|
|
206
|
+
now,
|
|
207
|
+
JSON.stringify(conf),
|
|
208
|
+
JSON.stringify(NOTE_TYPES),
|
|
209
|
+
JSON.stringify(ankiDecks),
|
|
210
|
+
JSON.stringify(DECK_CONFIG)
|
|
211
|
+
);
|
|
212
|
+
|
|
213
|
+
const addNote = db.prepare("INSERT INTO notes VALUES (?, ?, ?, ?, -1, ?, ?, ?, ?, 0, '')");
|
|
214
|
+
const addCard = db.prepare("INSERT INTO cards VALUES (?, ?, ?, ?, ?, -1, 0, 0, ?, 0, 0, 0, 0, 0, 0, 0, 0, '')");
|
|
215
|
+
let id = now; // note and card ids: unique within the package; Anki gives new ones where they clash
|
|
216
|
+
let position = 0;
|
|
217
|
+
// a guid is one note: a second card with the same one (the same note imported twice) gets its own
|
|
218
|
+
const guids = new Set();
|
|
219
|
+
const guidFor = (card) => {
|
|
220
|
+
let guid = card.guid && !guids.has(card.guid) ? card.guid : guidOf(card.id);
|
|
221
|
+
for (let n = 1; guids.has(guid); n++) guid = guidOf(`${card.id} ${n}`);
|
|
222
|
+
guids.add(guid);
|
|
223
|
+
return guid;
|
|
224
|
+
};
|
|
225
|
+
db.exec("BEGIN");
|
|
226
|
+
for (const deck of decks) {
|
|
227
|
+
for (const card of cardsOf(library, deck.id)) {
|
|
228
|
+
if (skip(card)) continue;
|
|
229
|
+
const { mid, fields, ords } = noteOf(card, deck);
|
|
230
|
+
const noteId = id++;
|
|
231
|
+
const mod = Math.floor(Math.max(card.updated ?? card.created ?? now, deck.updated ?? 0) / 1000);
|
|
232
|
+
addNote.run(noteId, guidFor(card), mid, mod, tagsOf(card.tags), fields.join("\x1f"), unhtml(fields[0]), checksum(fields[0]));
|
|
233
|
+
position++;
|
|
234
|
+
for (const ord of ords) addCard.run(id++, noteId, deckIds.get(deck.id), ord, seconds, position);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
db.exec("COMMIT");
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ── Reading ──
|
|
241
|
+
//
|
|
242
|
+
// A package from Anki (.apkg, decks; .colpkg, a whole collection) → a card list in the shape
|
|
243
|
+
// readCardList gives (format "apkg"), so an import goes on as from a text file: the same preview,
|
|
244
|
+
// duplicates and backup. Anki has written three kinds of collection over the years, newest first:
|
|
245
|
+
// collection.anki21b zstd-compressed, schema 18: note types, fields and decks in tables of their own
|
|
246
|
+
// collection.anki21 schema 11 (Anki 2.1, and "Support older Anki versions")
|
|
247
|
+
// collection.anki2 schema 11 (Anki 2.0, genanki and Dracosh); next to a newer one, only a stub
|
|
248
|
+
// A note's deck is the one its cards are in (for a card in a filtered deck, the one it came from).
|
|
249
|
+
// How to read a note comes from its note type, never its name, which Anki gives in its own language:
|
|
250
|
+
// a cloze type's text is the field its template puts {{cloze:…}} on, and the next field Anki's
|
|
251
|
+
// Extra, shown after the answer (an example). Any other type's front is the field its first template
|
|
252
|
+
// asks; its answer the field named so (Meaning, Translation, or after a language: "English"), else the
|
|
253
|
+
// next one its answer side shows; an example the field named so (Sentence, Example). Dracosh's own
|
|
254
|
+
// note types come back exactly, with how each deck asks. A deck with reverse cards asks both ways.
|
|
255
|
+
// Pictures and sounds stay out; image occlusion notes (masks over a picture) and notes that are only a
|
|
256
|
+
// picture or a sound are listed as left out. Progress in Anki isn't brought over; tags are.
|
|
257
|
+
|
|
258
|
+
const COLLECTIONS = ["collection.anki21b", "collection.anki21", "collection.anki2"];
|
|
259
|
+
const notAnki = (why) => Object.assign(new Error(why), { code: "NOT_ANKI" });
|
|
260
|
+
|
|
261
|
+
export async function readApkg(file) {
|
|
262
|
+
const { DatabaseSync } = await loadSqlite();
|
|
263
|
+
let files;
|
|
264
|
+
try {
|
|
265
|
+
files = await readZip(file, COLLECTIONS, { first: true });
|
|
266
|
+
} catch (err) {
|
|
267
|
+
throw ["NOT_ZIP", "DAMAGED_ZIP", "Z_DATA_ERROR", "Z_BUF_ERROR"].includes(err.code) ? notAnki(err.message) : err;
|
|
268
|
+
}
|
|
269
|
+
const [name, packed] = [...files][0] ?? [];
|
|
270
|
+
if (!name) throw notAnki("No collection in the package");
|
|
271
|
+
const folder = mkdtempSync(join(tmpdir(), "dracosh-apkg-"));
|
|
272
|
+
try {
|
|
273
|
+
const path = join(folder, "collection.db");
|
|
274
|
+
let db;
|
|
275
|
+
try {
|
|
276
|
+
writeFileSync(path, name.endsWith("b") ? unzstd(packed) : packed);
|
|
277
|
+
dropUnicase(DatabaseSync, path);
|
|
278
|
+
db = new DatabaseSync(path, { readOnly: true, defensive: true });
|
|
279
|
+
return readCollection(db);
|
|
280
|
+
} catch (err) {
|
|
281
|
+
// not a database, not zstd, or not what Anki keeps in one
|
|
282
|
+
throw err.code === "ERR_SQLITE_ERROR" || String(err.code).startsWith("ZSTD_") || err instanceof SyntaxError ? notAnki(err.message) : err;
|
|
283
|
+
} finally {
|
|
284
|
+
db?.close();
|
|
285
|
+
}
|
|
286
|
+
} finally {
|
|
287
|
+
rmSync(folder, { recursive: true, force: true });
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Anki compares names with a collation of its own ("unicase", schema 15 and later) that plain SQLite
|
|
292
|
+
// doesn't have, and won't read those tables without it. This copy is a throwaway one, so the
|
|
293
|
+
// collation is taken out of its schema: names are only read here, never sorted or looked up.
|
|
294
|
+
function dropUnicase(DatabaseSync, path) {
|
|
295
|
+
const db = new DatabaseSync(path, { defensive: false });
|
|
296
|
+
try {
|
|
297
|
+
const rows = db.prepare("SELECT type, name, sql FROM sqlite_master WHERE sql LIKE '%unicase%'").all();
|
|
298
|
+
if (!rows.length) return;
|
|
299
|
+
db.exec("PRAGMA writable_schema = ON");
|
|
300
|
+
const update = db.prepare("UPDATE sqlite_master SET sql = ? WHERE type = ? AND name = ?");
|
|
301
|
+
for (const { type, name, sql } of rows) update.run(sql.replace(/\s+COLLATE\s+unicase\b/gi, ""), type, name);
|
|
302
|
+
db.exec("PRAGMA writable_schema = OFF");
|
|
303
|
+
} finally {
|
|
304
|
+
db.close();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// a protobuf message's fields (schema 18 keeps note type and template settings so) → Map number →
|
|
309
|
+
// value: a number, or the bytes of a string or message
|
|
310
|
+
function protobuf(bytes) {
|
|
311
|
+
const fields = new Map();
|
|
312
|
+
let at = 0;
|
|
313
|
+
const varint = () => {
|
|
314
|
+
let value = 0;
|
|
315
|
+
for (let shift = 0; at < bytes.length; shift += 7) {
|
|
316
|
+
const byte = bytes[at++];
|
|
317
|
+
value += (byte & 0x7f) * 2 ** shift;
|
|
318
|
+
if (byte < 0x80) break;
|
|
319
|
+
}
|
|
320
|
+
return value;
|
|
321
|
+
};
|
|
322
|
+
while (at < bytes.length) {
|
|
323
|
+
const key = varint();
|
|
324
|
+
const [number, wire] = [Math.floor(key / 8), key % 8];
|
|
325
|
+
let value;
|
|
326
|
+
if (wire === 0) value = varint();
|
|
327
|
+
else if (wire === 2) {
|
|
328
|
+
const length = varint();
|
|
329
|
+
value = bytes.subarray(at, at + length);
|
|
330
|
+
at += length;
|
|
331
|
+
} else if (wire === 1 || wire === 5) at += wire === 1 ? 8 : 4;
|
|
332
|
+
else break;
|
|
333
|
+
if (value !== undefined && !fields.has(number)) fields.set(number, value);
|
|
334
|
+
}
|
|
335
|
+
return fields;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const CLOZE_KIND = 1;
|
|
339
|
+
const text = (bytes) => (bytes ? Buffer.from(bytes).toString("utf8") : "");
|
|
340
|
+
|
|
341
|
+
// → { types: Map id → { name, cloze, fields: [names], question, answer }, decks: Map id → name }:
|
|
342
|
+
// `question` and `answer`: the first template's two sides, to see which fields they show
|
|
343
|
+
function schema18(db) {
|
|
344
|
+
const types = new Map(db.prepare("SELECT id, name, config FROM notetypes").all().map(({ id, name, config }) => [id, { name, cloze: protobuf(config).get(1) === CLOZE_KIND, fields: [], question: "", answer: "" }]));
|
|
345
|
+
for (const { ntid, ord, name } of db.prepare("SELECT ntid, ord, name FROM fields").all()) if (types.has(ntid)) types.get(ntid).fields[ord] = name;
|
|
346
|
+
for (const { ntid, ord, config } of db.prepare("SELECT ntid, ord, config FROM templates").all()) {
|
|
347
|
+
if (ord !== 0 || !types.has(ntid)) continue;
|
|
348
|
+
const settings = protobuf(config);
|
|
349
|
+
Object.assign(types.get(ntid), { question: text(settings.get(1)), answer: text(settings.get(2)) });
|
|
350
|
+
}
|
|
351
|
+
const decks = new Map(db.prepare("SELECT id, name FROM decks").all().map(({ id, name }) => [id, name.replaceAll("\x1f", "::")]));
|
|
352
|
+
return { types, decks };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function schema11(db) {
|
|
356
|
+
const col = db.prepare("SELECT models, decks FROM col").get();
|
|
357
|
+
const [models, decks] = [JSON.parse(col?.models ?? "null"), JSON.parse(col?.decks ?? "null")];
|
|
358
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
359
|
+
if (!isObject(models) || !isObject(decks) || !Object.values(models).every((type) => isObject(type) && Array.isArray(type.flds) && Array.isArray(type.tmpls))) throw notAnki("Not an Anki collection");
|
|
360
|
+
const first = (type) => type.tmpls.find((template) => template?.ord === 0) ?? type.tmpls[0] ?? {};
|
|
361
|
+
return {
|
|
362
|
+
types: new Map(
|
|
363
|
+
Object.values(models).map((type) => [
|
|
364
|
+
Number(type.id),
|
|
365
|
+
{ name: String(type.name ?? ""), cloze: type.type === CLOZE_KIND, fields: [...type.flds].sort((a, b) => a.ord - b.ord).map((field) => String(field?.name ?? "")), question: String(first(type).qfmt ?? ""), answer: String(first(type).afmt ?? "") }
|
|
366
|
+
])
|
|
367
|
+
),
|
|
368
|
+
decks: new Map(Object.values(decks).map((deck) => [Number(deck?.id), String(deck?.name ?? "")]))
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// the fields a template side shows, in order: "{{Front}}", "{{type:Back}}", "{{furigana:Reading}}"
|
|
373
|
+
const shownFields = (format) =>
|
|
374
|
+
[...format.matchAll(/\{\{([^{}#^/][^{}]*)\}\}/g)]
|
|
375
|
+
.map((match) => match[1].split(":").pop().trim())
|
|
376
|
+
.filter((name) => name !== "FrontSide");
|
|
377
|
+
// a field named after what it holds, or after a language ("English", "Vocabulary-English")
|
|
378
|
+
const LANGUAGE_NAMED = /\b(english|polish|german|french|ukrainian|spanish|italian|portuguese|russian|japanese|chinese|korean|dutch|swedish|meaning|translation|definition)\b/i;
|
|
379
|
+
|
|
380
|
+
// which field holds the front, the answer and an example → { front, back, example } indexes
|
|
381
|
+
function rolesOf(type) {
|
|
382
|
+
const index = (name) => type.fields.indexOf(name);
|
|
383
|
+
const named = (role) => type.fields.findIndex((name, i) => i !== front && columnRole(name) === role);
|
|
384
|
+
const asked = shownFields(type.question).map(index).find((i) => i >= 0);
|
|
385
|
+
const front = asked ?? Math.max(0, type.fields.findIndex((name) => columnRole(name) === "front"));
|
|
386
|
+
const found = (i) => (i >= 0 && i !== front ? i : undefined);
|
|
387
|
+
const back =
|
|
388
|
+
found(named("back")) ??
|
|
389
|
+
found(type.fields.findIndex((name, i) => i !== front && LANGUAGE_NAMED.test(name.replace(/[-_]/g, " ")))) ??
|
|
390
|
+
shownFields(type.answer).map(index).find((i) => found(i) !== undefined) ??
|
|
391
|
+
type.fields.findIndex((_, i) => i !== front);
|
|
392
|
+
const example = [named("example")].find((i) => i >= 0 && i !== back) ?? null;
|
|
393
|
+
return { front, back, example };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const MEDIA = /<img\b|\[sound:/i;
|
|
397
|
+
const IMAGE_OCCLUSION = /\{\{c\d+::image-occlusion:/;
|
|
398
|
+
const textOf = (html) => htmlLines(html).join(" ");
|
|
399
|
+
|
|
400
|
+
function readCollection(db) {
|
|
401
|
+
const tables = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
|
|
402
|
+
if (!tables.has("notes") || !tables.has("cards") || !tables.has("col")) throw notAnki("Not an Anki collection");
|
|
403
|
+
const { types, decks } = tables.has("notetypes") ? schema18(db) : schema11(db);
|
|
404
|
+
const cardsOfNote = new Map();
|
|
405
|
+
for (const { nid, did, odid, ord } of db.prepare("SELECT nid, did, odid, ord FROM cards ORDER BY ord").all()) {
|
|
406
|
+
if (!cardsOfNote.has(nid)) cardsOfNote.set(nid, []);
|
|
407
|
+
cardsOfNote.get(nid).push({ deck: odid || did, ord });
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const items = [];
|
|
411
|
+
const asks = new Map(); // deck name → how its notes ask: { forward, backward, both } counts
|
|
412
|
+
let media = 0;
|
|
413
|
+
db.prepare("SELECT id, guid, mid, flds, tags FROM notes ORDER BY id")
|
|
414
|
+
.all()
|
|
415
|
+
.forEach((note, i) => {
|
|
416
|
+
const type = types.get(note.mid) ?? { name: "", cloze: false, fields: [], question: "", answer: "" };
|
|
417
|
+
const values = String(note.flds).split("\x1f");
|
|
418
|
+
const value = (at) => (at === null || at === undefined || at < 0 ? "" : (values[at] ?? ""));
|
|
419
|
+
const byName = (name) => value(type.fields.indexOf(name));
|
|
420
|
+
const cards = cardsOfNote.get(note.id) ?? [];
|
|
421
|
+
const deck = decks.get(cards[0]?.deck) ?? null;
|
|
422
|
+
const tags = String(note.tags ?? "").trim().split(/\s+/).filter(Boolean);
|
|
423
|
+
const item = { line: i + 1, deck, direction: null, source: values.slice(0, 2).map(textOf).filter(Boolean).join(" = ") };
|
|
424
|
+
// a picture card is named by its header, or its picture's file
|
|
425
|
+
const picture = () => values.slice(1).map(textOf).find(Boolean) ?? values.join(" ").match(/<img[^>]*src="([^"]+)"/i)?.[1] ?? "";
|
|
426
|
+
if (type.cloze && IMAGE_OCCLUSION.test(values[0])) return items.push({ ...item, source: picture(), skip: "picture", fields: noteFields({}) });
|
|
427
|
+
|
|
428
|
+
let fields;
|
|
429
|
+
let ask = null;
|
|
430
|
+
let front = values[0];
|
|
431
|
+
if (note.mid === BASIC_ID || (type.name === "Dracosh" && type.fields.includes("Forward"))) {
|
|
432
|
+
front = byName("Front");
|
|
433
|
+
fields = noteFields({ front, back: byName("Back"), example: byName("Example"), perLine: true });
|
|
434
|
+
const [forward, backward] = [byName("Forward"), byName("Backward")].map((flag) => Boolean(textOf(flag)));
|
|
435
|
+
ask = forward && backward ? "both" : backward ? "backward" : "forward";
|
|
436
|
+
} else if (note.mid === CLOZE_ID || (type.name === "Dracosh Cloze" && type.fields.includes("Hint"))) {
|
|
437
|
+
front = byName("Text");
|
|
438
|
+
fields = noteFields({ front, back: byName("Hint"), example: byName("Example"), cloze: true, hint: true });
|
|
439
|
+
} else if (type.cloze) {
|
|
440
|
+
const clozeName = type.question.match(/\{\{(?:[^{}:]*:)*cloze:([^{}]+)\}\}/)?.[1]?.trim();
|
|
441
|
+
const at = Math.max(0, type.fields.indexOf(clozeName));
|
|
442
|
+
const extra = shownFields(type.answer).map((name) => type.fields.indexOf(name)).find((j) => j >= 0 && j !== at) ?? (at === 0 ? 1 : 0);
|
|
443
|
+
front = value(at);
|
|
444
|
+
fields = noteFields({ front, back: value(extra), cloze: true });
|
|
445
|
+
} else {
|
|
446
|
+
const roles = rolesOf(type);
|
|
447
|
+
front = value(roles.front);
|
|
448
|
+
fields = noteFields({ front, back: value(roles.back), example: value(roles.example) });
|
|
449
|
+
ask = cards.some((card) => card.ord === 0) && cards.some((card) => card.ord > 0) ? "both" : "forward";
|
|
450
|
+
}
|
|
451
|
+
// a front that is only a picture or a sound has nothing to ask in text
|
|
452
|
+
if (!fields.front && MEDIA.test(front)) return items.push({ ...item, source: item.source || picture(), skip: "mediaOnly", fields });
|
|
453
|
+
if (values.some((field) => MEDIA.test(field))) media++;
|
|
454
|
+
if (ask && deck) {
|
|
455
|
+
const counts = asks.get(deck) ?? { forward: 0, backward: 0, both: 0 };
|
|
456
|
+
counts[ask]++;
|
|
457
|
+
asks.set(deck, counts);
|
|
458
|
+
}
|
|
459
|
+
// A note of Dracosh's own keeps its guid: sent back to Anki, the card updates that note. Anki's
|
|
460
|
+
// own notes never go back under their guid: the importer AnkiConnect uses would turn them into
|
|
461
|
+
// Dracosh notes, dropping fields Dracosh doesn't have. They're marked instead (fromAnki).
|
|
462
|
+
const own = note.mid === BASIC_ID || note.mid === CLOZE_ID;
|
|
463
|
+
const origin = own ? note.guid && { guid: String(note.guid) } : { fromAnki: true };
|
|
464
|
+
items.push({ ...item, fields: { ...fields, ...(tags.length && { tags }), ...origin } });
|
|
465
|
+
});
|
|
466
|
+
// a deck asks the way most of its notes do
|
|
467
|
+
for (const item of items) {
|
|
468
|
+
const counts = asks.get(item.deck);
|
|
469
|
+
if (counts) item.direction = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
|
|
470
|
+
}
|
|
471
|
+
return { format: "apkg", separator: null, header: {}, items, columns: null, ignored: [], unknown: [], anki: true, html: true, media };
|
|
472
|
+
}
|
package/src/backup.js
CHANGED
|
@@ -6,7 +6,7 @@ import { DATA_FILES, HOME, readJson, writeJson } from "./store.js";
|
|
|
6
6
|
|
|
7
7
|
// A backup is one JSON file in ~/.dracosh/backups holding the library, progress and settings as they
|
|
8
8
|
// were. One is taken on the first start of each day, and right before anything that changes a lot at
|
|
9
|
-
// once (a restore
|
|
9
|
+
// once (a restore, an import, a deletion or a reset).
|
|
10
10
|
export const BACKUP_DIR = join(HOME, "backups");
|
|
11
11
|
const BACKUP_FORMAT = 1;
|
|
12
12
|
export const KEEP = 7; // per kind: the last 7 daily ones, and the last 7 taken before an operation
|
|
@@ -14,6 +14,17 @@ export const KEEP = 7; // per kind: the last 7 daily ones, and the last 7 taken
|
|
|
14
14
|
// "2026-10-09T21:15:03.120Z" → "2026-10-09_21-15-03", so file names sort by time
|
|
15
15
|
const stamp = (now) => new Date(now).toISOString().slice(0, 19).replace("T", "_").replaceAll(":", "-");
|
|
16
16
|
|
|
17
|
+
// What a backup holds, as an object: the library, progress and settings now. `dracosh export x.json`
|
|
18
|
+
// writes it, and `dracosh import x.json` (or a restore) brings it back. A damaged file is left out.
|
|
19
|
+
export async function backupData(reason, now = Date.now()) {
|
|
20
|
+
const files = {};
|
|
21
|
+
for (const [name, file] of Object.entries(DATA_FILES)) {
|
|
22
|
+
const data = await readJson(file, null).catch(() => null);
|
|
23
|
+
if (data) files[name] = data;
|
|
24
|
+
}
|
|
25
|
+
return { format: BACKUP_FORMAT, created: now, reason, files };
|
|
26
|
+
}
|
|
27
|
+
|
|
17
28
|
// → the file it wrote, or null when there is nothing to back up (or, with `skipDamaged`, when a data file
|
|
18
29
|
// is too damaged to read: a backup missing the library would push the good ones out). Otherwise a damaged
|
|
19
30
|
// file is set aside as it is (library.json.damaged-<day>, one a day) and the backup goes on, so a
|
package/src/cardline.js
CHANGED
|
@@ -40,6 +40,9 @@ export function parseLine(line, { separator = " = " } = {}) {
|
|
|
40
40
|
let hidden = hide(String(line ?? "").trim());
|
|
41
41
|
// "kot =" is a front still waiting for its back
|
|
42
42
|
if (separator === " = " && !hidden.includes(separator) && hidden.endsWith(" =")) hidden = hidden.slice(0, -2).trimEnd();
|
|
43
|
+
// without a back, " // " still starts the example: "Ella {{come}} pan. // She eats bread."
|
|
44
|
+
const lone = separator === " = " && !hidden.includes(separator) ? hidden.indexOf(" // ") : -1;
|
|
45
|
+
if (lone !== -1) hidden = `${hidden.slice(0, lone)} = ${hidden.slice(lone + 1)}`;
|
|
43
46
|
const at = hidden.indexOf(separator);
|
|
44
47
|
const frontPart = at === -1 ? hidden : hidden.slice(0, at);
|
|
45
48
|
const rest = at === -1 ? "" : ` ${hidden.slice(at + separator.length)}`; // the space lets the back start with "// "
|
|
@@ -49,7 +52,9 @@ export function parseLine(line, { separator = " = " } = {}) {
|
|
|
49
52
|
// braces escaped with \{{ are plain text, so only the visible ones make gaps
|
|
50
53
|
const cloze = hasGap(frontPart.replace(/\u0004/g, ""));
|
|
51
54
|
const front = show(frontPart, cloze ? { "\u0004": "\\{{" } : {}).trim();
|
|
52
|
-
|
|
55
|
+
// a cloze card's back is a hint, not answers: its ";" is part of it
|
|
56
|
+
const back = cloze ? [show(backPart).trim()].filter(Boolean) : splitAnswers(backPart);
|
|
57
|
+
return { front, back, example, cloze, hasBack: at !== -1 && lone === -1 };
|
|
53
58
|
}
|
|
54
59
|
|
|
55
60
|
// What goes into a second step's field: the back of a card, maybe with its example ("cat; kitty // …")
|
|
@@ -62,10 +67,13 @@ export function parseBack(text) {
|
|
|
62
67
|
// otherwise read as an escape (before = ; // {{ \ or at the end of a piece).
|
|
63
68
|
const backslashes = (text, { cloze = false } = {}) => text.replace(cloze ? /\\(?=[=;\\]|\/\/|$)/g : /\\(?=[=;\\]|\/\/|\{\{|$)/g, "\\\\");
|
|
64
69
|
export function formatLine({ front, back = [], example = "", cloze = false }) {
|
|
65
|
-
|
|
70
|
+
// " //" in the front is escaped too: without a back it would start the example
|
|
71
|
+
let line = backslashes(front, { cloze }).replace(/ =/g, " \\=").replace(/(^|\s)\/\//g, "$1\\//");
|
|
66
72
|
if (!cloze) line = line.replace(/\{\{/g, "\\{{");
|
|
67
73
|
const backText = back.map((answer) => backslashes(answer).replace(/;/g, "\\;").replace(/(^|\s)\/\//g, "$1\\//")).join("; ");
|
|
68
|
-
|
|
74
|
+
// a cloze card needs no back, so its example can follow right after the front (unless an "=" in it
|
|
75
|
+
// could read as the separator)
|
|
76
|
+
if (backText || (example && (!cloze || example.includes("=")))) line += ` = ${backText}`;
|
|
69
77
|
if (example) line += ` // ${backslashes(example)}`;
|
|
70
78
|
return line;
|
|
71
79
|
}
|