dracosh 0.7.0 → 0.9.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/src/cli.js CHANGED
@@ -4,6 +4,9 @@ import React from "react";
4
4
  import { parseArgs } from "node:util";
5
5
  import { createInterface } from "node:readline/promises";
6
6
  import { createAlerts } from "./alerts.js";
7
+ import { detectBackground } from "./background.js";
8
+ import { issueBody, issueUrl, openInBrowser } from "./bug.js";
9
+ import { checkAll, report } from "./doctor.js";
7
10
  import { existsSync } from "node:fs";
8
11
  import { language, setLanguage, t } from "./i18n.js";
9
12
  import { BACKUP_DIR, dailyBackup, listBackups, restoreBackup, saveUpgraded } from "./backup.js";
@@ -16,6 +19,7 @@ import { seedLibrary } from "./starter.js";
16
19
  import { DATA_FILES, HOME, loadLibrary, loadSettingsRaw, loadState, patchSettings, saveLibrary } from "./store.js";
17
20
  import { App } from "./ui/App.js";
18
21
  import { Preview } from "./ui/Preview.js";
22
+ import { setBackground } from "./ui/kit.js";
19
23
  import { ALREADY_RUNNING, acquireLock, runningPid } from "./lock.js";
20
24
  import * as manage from "./manage.js";
21
25
  import { findDeck } from "./library.js";
@@ -82,6 +86,19 @@ async function printData() {
82
86
  console.log(`\n${t("cli.data.footer")}`);
83
87
  }
84
88
 
89
+ async function doctor(settings) {
90
+ const checks = await checkAll(settings);
91
+ console.log(report(checks));
92
+ if (checks.some((check) => check.status === "fail")) process.exitCode = 1;
93
+ }
94
+
95
+ async function bug(settings) {
96
+ console.log(t("cli.bug.checking"));
97
+ const url = issueUrl(await issueBody(settings));
98
+ const opened = await openInBrowser(url);
99
+ console.log(`${t(opened ? "cli.bug.opened" : "cli.bug.notOpened")}\n\n${url}`);
100
+ }
101
+
85
102
  async function restore(choice, { yes }) {
86
103
  const backups = await listBackups();
87
104
  if (!backups.length) return console.log(t("cli.restore.none", { dir: BACKUP_DIR }));
@@ -138,6 +155,8 @@ async function main() {
138
155
  if (values.help) return console.log(help());
139
156
  const [command, ...args] = positionals;
140
157
  if (command === "restore") return restore(args[0], values);
158
+ if (command === "doctor") return doctor(early);
159
+ if (command === "bug") return bug(early);
141
160
  if ((command === "import" || command === "export") && args.length > 1) throw new Error(t("cli.oneFile", { command }));
142
161
  if (command === "import") return runImport(args[0], values);
143
162
  if (command === "export") return runExport(args[0], values);
@@ -154,8 +173,9 @@ async function main() {
154
173
 
155
174
  if (values.preview) {
156
175
  if (!process.stdin.isTTY) throw new Error(t("cli.needsTerminal"));
157
- const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak });
158
- return render(React.createElement(Preview, { alerts })).waitUntilExit();
176
+ const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak, voice: settings.voice });
177
+ if (settings.theme === "auto") setBackground(await detectBackground());
178
+ return render(React.createElement(Preview, { alerts, theme: settings.theme })).waitUntilExit();
159
179
  }
160
180
 
161
181
  const state = await loadState();
@@ -179,12 +199,15 @@ async function main() {
179
199
  let active = deck.name; // /add can switch to your first own deck
180
200
  let mix = values.deck ? null : settings.mix; // decks practised together (/decks); --deck is one deck
181
201
  const session = createSession({ loadWords: () => loadWords(mix ?? active), loadAllWords, state, getSettings: () => current });
182
- const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak });
202
+ const alerts = createAlerts({ sound: settings.sound, volume: settings.volume, speak: settings.speak, voice: settings.voice });
183
203
  const persistSettings = async (patch) => {
184
204
  current = { ...current, ...patch };
185
205
  await patchSettings(patch);
186
206
  };
187
207
 
208
+ // only for the auto theme: a picked one needs no question, and auto picked later in /settings is dark
209
+ if (settings.theme === "auto") setBackground(await detectBackground());
210
+
188
211
  // the session summary screen stays on screen after exit, so nothing more to print here
189
212
  const app = render(React.createElement(App, { session, deck: deck.name, initialSettings: settings, initialMix: mix, alerts, persistSettings, library: manage, onSwitchDeck: (name) => (active = name), onMix: (decks) => (mix = decks) }));
190
213
  await app.waitUntilExit();
package/src/doctor.js ADDED
@@ -0,0 +1,123 @@
1
+ import { constants } from "node:fs";
2
+ import { access } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import { aiLabel, listModels } from "./ai.js";
5
+ import { t } from "./i18n.js";
6
+ import { findNotifier } from "./notify.js";
7
+ import { findPlayers } from "./player.js";
8
+ import { findSpeech } from "./speech.js";
9
+ import { DATA_FILES, HOME, loadLibrary, loadState, readJson } from "./store.js";
10
+ import { findVoiceKey, listVoices, voiceLabel } from "./voice.js";
11
+
12
+ // `dracosh doctor`: what works on this computer and what to do about what doesn't. Each check is
13
+ // { status, label, detail, safe }: ok, warn (works, could be better), fail (needs fixing) or off (not
14
+ // set up); `safe` is the detail with nothing personal in it (no paths, addresses, names or what a
15
+ // server said), for a bug report.
16
+ // Online checks only list models or voices: free, and they prove the key and the address.
17
+
18
+ const NEEDED = [22, 15];
19
+ const newEnough = (version) => {
20
+ const [major, minor] = version.split(".").map(Number);
21
+ return major > NEEDED[0] || (major === NEEDED[0] && minor >= NEEDED[1]);
22
+ };
23
+
24
+ const exists = (path) => access(path).then(() => true, () => false);
25
+ const writable = (path) => access(path, constants.W_OK).then(() => true, () => false);
26
+
27
+ // the first folder on the way up that's there: where a data folder not made yet would go
28
+ async function nearest(path) {
29
+ while (!(await exists(path)) && dirname(path) !== path) path = dirname(path);
30
+ return path;
31
+ }
32
+
33
+ // platform, has (what's on PATH), env, node, home and online (listModels, listVoices, findVoiceKey):
34
+ // given by tests
35
+ export async function checkAll(settings, { platform = process.platform, has, env = process.env, node = process.versions.node, home = HOME, online = {} } = {}) {
36
+ const found = { platform, env, ...(has && { has }) };
37
+ const models = online.listModels ?? listModels;
38
+ const voices = online.listVoices ?? listVoices;
39
+ const voiceKey = online.findVoiceKey ?? findVoiceKey;
40
+ const checks = [];
41
+ const add = (status, label, detail, safe = detail) => checks.push({ status, label, detail, safe });
42
+
43
+ add(newEnough(node) ? "ok" : "fail", "Node", newEnough(node) ? node : t("cli.doctor.nodeOld", { version: node, needed: NEEDED.join(".") }));
44
+
45
+ const data = t("cli.doctor.data");
46
+ if (!(await exists(home))) {
47
+ const canMake = await writable(await nearest(home));
48
+ add(canMake ? "ok" : "fail", data, t(canMake ? "cli.doctor.dataNew" : "cli.doctor.dataReadOnly", { home }), canMake ? "not created yet" : "can't be written to");
49
+ } else if (!(await writable(home))) add("fail", data, t("cli.doctor.dataReadOnly", { home }), "can't be written to");
50
+ else {
51
+ try {
52
+ // settings read as they are: the app quietly falls back to the defaults when they're damaged
53
+ await Promise.all([loadLibrary(), loadState(), readJson(DATA_FILES.settings, {})]);
54
+ add("ok", data, home, "readable");
55
+ } catch (err) {
56
+ add("fail", data, err.message, err.damaged ? "a file is damaged" : "a file can't be read");
57
+ }
58
+ }
59
+
60
+ const sound = t("settings.rows.sound.label");
61
+ const players = findPlayers(found);
62
+ if (platform === "win32") add("off", sound, t("cli.doctor.noSoundWindows"));
63
+ else if (players.length) add(settings.sound ? "ok" : "off", sound, settings.sound ? players.join(", ") : t("settings.off"));
64
+ else add(settings.sound ? "fail" : "off", sound, t("cli.doctor.noPlayer"));
65
+
66
+ const notifier = findNotifier(found);
67
+ const overSsh = Boolean(env.SSH_CONNECTION || env.SSH_TTY); // the bell is the right thing there
68
+ const bellOnly = notifier === "bell" && platform !== "win32" && platform !== "darwin" && !overSsh;
69
+ add(bellOnly ? "warn" : "ok", t("cli.doctor.notifications"), t(`cli.doctor.notifier.${bellOnly ? "bellLinux" : notifier}`));
70
+
71
+ if (platform !== "win32") {
72
+ const speak = t("settings.rows.speak.label");
73
+ const speech = findSpeech(found);
74
+ if (!settings.speak) add("off", speak, t("settings.off"));
75
+ else if (speech) add("ok", speak, speech);
76
+ else add(settings.voice ? "warn" : "fail", speak, t("cli.doctor.noSpeech"));
77
+
78
+ if (settings.speak && settings.voice) {
79
+ const label = t("settings.rows.voice.label");
80
+ const name = voiceLabel(settings.voice);
81
+ if (!findPlayers({ ...found, mp3: true }).length) add("fail", label, t("cli.doctor.noMp3Player", { voice: name }), "ElevenLabs: no player for mp3");
82
+ else {
83
+ try {
84
+ const key = (await voiceKey())?.key ?? null;
85
+ const list = await voices({ key, url: settings.voice.url });
86
+ // a voice's name is often the person it was cloned from: never in a report
87
+ if (list.some((voice) => voice.id === settings.voice.id)) add("ok", label, name, "ElevenLabs");
88
+ else add("fail", label, t("voice.errors.noVoice"), "ElevenLabs: noVoice");
89
+ } catch (err) {
90
+ add("fail", label, err.message, `ElevenLabs: ${err.code ?? "failed"}`);
91
+ }
92
+ }
93
+ }
94
+ }
95
+
96
+ const aiRow = t("settings.rows.ai.label");
97
+ if (!settings.ai) add("off", aiRow, t("settings.off"));
98
+ else {
99
+ try {
100
+ const names = await models(settings.ai);
101
+ // a server that lists nothing (some don't) isn't held against the model; a short name stands for
102
+ // its dated versions ("claude-x" for "claude-x-20260101")
103
+ const { model } = settings.ai;
104
+ // the provider only: a model's name can carry an account's ("ft:…:acme:…"), a message its address
105
+ const provider = settings.ai.provider;
106
+ if (!names.length || names.some((name) => name === model || name.startsWith(`${model}-`))) add("ok", aiRow, aiLabel(settings.ai), provider);
107
+ else add("warn", aiRow, t("cli.doctor.aiNoModel", { label: aiLabel(settings.ai), model: settings.ai.model }), `${provider}: model not listed`);
108
+ } catch (err) {
109
+ add("fail", aiRow, err.message, `${settings.ai.provider}: ${err.code ?? "failed"}`);
110
+ }
111
+ }
112
+ return checks;
113
+ }
114
+
115
+ const MARKS = { ok: "✓", warn: "!", fail: "✗", off: "–" };
116
+
117
+ // safe: each line's detail with nothing personal in it (for `dracosh bug`)
118
+ export function report(checks, { safe = false } = {}) {
119
+ const width = Math.max(...checks.map((check) => check.label.length));
120
+ const lines = checks.map((check) => ` ${MARKS[check.status]} ${check.label.padEnd(width)} ${safe ? (check.safe ?? check.detail) : check.detail}`);
121
+ const problems = checks.filter((check) => check.status === "fail").length;
122
+ return [t("cli.doctor.title"), "", ...lines, "", problems ? t("cli.doctor.problems", { count: problems }) : t("cli.doctor.allGood")].join("\n");
123
+ }
package/src/library.js CHANGED
@@ -260,7 +260,7 @@ export const frontIndex = (library, deckId) => new Map(cardsOf(library, deckId).
260
260
  // `index`: the deck's frontIndex, kept up to date here (see findDuplicate)
261
261
  // `guid`: the note in a Dracosh package it came from, so going back to Anki it's that note again;
262
262
  // `fromAnki`: it came from a note of Anki's own (see apkg.js), which Anki still has
263
- export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, guid, fromAnki = false, now = Date.now() }, index = null) {
263
+ export function addCard(library, deckId, { front, back, example = "", tags = [], cloze = false, id, guid, fromAnki = false, ai = false, now = Date.now() }, index = null) {
264
264
  if (!library.decks.some((deck) => deck.id === deckId)) throw new Error("That deck doesn't exist.");
265
265
  const cleanFront = String(front ?? "").trim();
266
266
  const cleanBack = cleanList(back);
@@ -271,7 +271,7 @@ export function addCard(library, deckId, { front, back, example = "", tags = [],
271
271
  const duplicate = findDuplicate(library, deckId, cleanFront, index);
272
272
  if (duplicate) return { card: null, duplicate };
273
273
 
274
- 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 };
274
+ 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 }), ...(ai && { ai: true }), created: now, updated: now };
275
275
  if (id && library.cards.some((c) => c.id === card.id)) throw new Error(`A card with id ${card.id} already exists.`);
276
276
  library.cards.push(card);
277
277
  index?.set(frontKey(cleanFront), card);
@@ -293,10 +293,21 @@ export function updateCard(library, cardId, patch, now = Date.now()) {
293
293
  else delete card.cloze;
294
294
  if (patch.example !== undefined) card.example = String(patch.example).trim();
295
295
  if (patch.tags !== undefined) card.tags = cleanList(patch.tags);
296
+ // a card written by AI help stays marked (`ai`) until it's changed or checked
297
+ if (patch.ai) card.ai = true;
298
+ else delete card.ai;
296
299
  card.updated = now;
297
300
  return card;
298
301
  }
299
302
 
303
+ // a card written by AI help, looked over and found right: its mark goes
304
+ export function confirmCard(library, cardId) {
305
+ const card = library.cards.find((c) => c.id === cardId);
306
+ if (!card) throw new Error("That card doesn't exist.");
307
+ delete card.ai;
308
+ return card;
309
+ }
310
+
300
311
  // The quiz's word shape, so the scheduler and session keep working unchanged. A cloze card is asked one
301
312
  // gap at a time ("c1", "c2"…), whatever the deck's direction.
302
313
  export const toWords = (cards) =>
@@ -305,5 +316,6 @@ export const toWords = (cards) =>
305
316
  word: card.front,
306
317
  translations: card.back,
307
318
  example: card.example,
319
+ ...(card.ai && { ai: true }),
308
320
  ...(card.cloze && { cloze: gapsOf(card.front), directions: gapsOf(card.front).map((_, i) => `c${i + 1}`) })
309
321
  }));
package/src/lock.js CHANGED
@@ -59,6 +59,6 @@ export function acquireLock() {
59
59
  };
60
60
  process.on("exit", release);
61
61
  // with the lock held no other window writes here: temp files left by a crash can go
62
- for (const name of readdirSync(HOME)) if (/^(library|state|settings)\.json\.\d+\.tmp$/.test(name)) rmSync(join(HOME, name), { force: true });
62
+ for (const name of readdirSync(HOME)) if (/^(library|state|settings|keys)\.json\.\d+\.tmp$/.test(name)) rmSync(join(HOME, name), { force: true });
63
63
  return release;
64
64
  }
package/src/manage.js CHANGED
@@ -2,7 +2,7 @@ import { language as uiLanguage, t } from "./i18n.js";
2
2
  import { backupNow } from "./backup.js";
3
3
  import { seedLibrary } from "./starter.js";
4
4
  import { gapsOf } from "./cardline.js";
5
- import { addCard, cardsOf, createDeck, emptyLibrary, emptyOldTrash, findDeck, findDuplicate, moveCards as moveLibraryCards, removeDeck, renameDeck as renameLibraryDeck, restoreDeck, trashCards, setDirections as setLibraryDirections, setLanguages as setLibraryLanguages, trashDeck, trashedUntil, typedSides, updateCard } from "./library.js";
5
+ import { addCard, cardsOf, confirmCard, createDeck, emptyLibrary, emptyOldTrash, findDeck, findDuplicate, moveCards as moveLibraryCards, removeDeck, renameDeck as renameLibraryDeck, restoreDeck, trashCards, setDirections as setLibraryDirections, setLanguages as setLibraryLanguages, trashDeck, trashedUntil, typedSides, updateCard } from "./library.js";
6
6
  import { firstWords } from "./firstwords.js";
7
7
  import { applyImport, planImport } from "./importer.js";
8
8
  import { deckLanguages, homeLanguages, languageName, learningSide } from "./language.js";
@@ -194,8 +194,19 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
194
194
  return { added, duplicates };
195
195
  },
196
196
 
197
+ // a card written by AI help, checked: it loses its ✦
198
+ async confirmCardIn(deckName, cardId) {
199
+ const library = await load();
200
+ const deck = await deckNamed(library, deckName);
201
+ if (!cardsOf(library, deck.id).some((card) => card.id === cardId)) throw new Error("That card doesn't exist.");
202
+ const card = confirmCard(library, cardId);
203
+ await save(library);
204
+ return card;
205
+ },
206
+
197
207
  // A card fixed right after adding it (↑ in /add) → { card, staleKeys }: the progress keys it no
198
208
  // longer has (a gap removed, a cloze card turned plain or the other way round), for the session to drop
209
+
199
210
  async updateCardIn(deckName, cardId, fields) {
200
211
  const library = await load();
201
212
  const deck = await deckNamed(library, deckName);
@@ -263,7 +274,7 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
263
274
  // /cards: a deck's cards as they are now, in the order they were added
264
275
  async cardsIn(deckName) {
265
276
  const library = await load();
266
- return cardsOf(library, (await deckNamed(library, deckName)).id).map(({ id, front, back, example, cloze }) => ({ id, front, back, example: example ?? "", cloze: Boolean(cloze) }));
277
+ return cardsOf(library, (await deckNamed(library, deckName)).id).map(({ id, front, back, example, cloze, ai }) => ({ id, front, back, example: example ?? "", cloze: Boolean(cloze), ai: Boolean(ai) }));
267
278
  },
268
279
 
269
280
  // /cards → Delete: into the trash with their progress (`progressOf`, from the session); the deck stays,
@@ -352,4 +363,4 @@ export function libraryActions({ load = loadLibrary, save = saveLibrary, backup
352
363
 
353
364
  // the app's own: reads and writes ~/.dracosh
354
365
  const actions = libraryActions();
355
- export const { allDecks, ownDecks, startDeck, startFirstWords, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, updateCardIn, previewImport, importCards, renameDeck, deleteDeck, trash, restoreFromTrash, cardsIn, deleteCards, moveCards, mergeDecks, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
366
+ export const { allDecks, ownDecks, startDeck, startFirstWords, setDirections, languagesOf, setLanguages, setLearning, existingDeck, existingCard, addCardTo, addCardsTo, confirmCardIn, updateCardIn, previewImport, importCards, renameDeck, deleteDeck, trash, restoreFromTrash, cardsIn, deleteCards, moveCards, mergeDecks, matchTourLanguage, backupBeforeReset, resetLibrary } = actions;
package/src/notify.js ADDED
@@ -0,0 +1,44 @@
1
+ import { execFile } from "node:child_process";
2
+ import { onPath } from "./player.js";
3
+
4
+ // A new card while you're in another window: a Notification Center banner on macOS, a desktop
5
+ // notification through notify-send on Linux, the terminal's bell elsewhere and wherever the native way
6
+ // doesn't work. Over SSH a desktop notification would show on the remote screen: the bell instead.
7
+
8
+ export function findNotifier({ platform = process.platform, has = onPath, env = process.env } = {}) {
9
+ if (env.SSH_CONNECTION || env.SSH_TTY) return "bell";
10
+ if (platform === "darwin") return "osascript";
11
+ if (platform !== "win32" && has("notify-send")) return "notify-send";
12
+ return "bell";
13
+ }
14
+
15
+ const COMMANDS = {
16
+ // the text goes to AppleScript as an argument, never into the script itself
17
+ osascript: (text) => ["-e", "on run argv", "-e", 'display notification (item 1 of argv) with title "Dracosh"', "-e", "end run", text],
18
+ "notify-send": (text) => ["--app-name=Dracosh", "--", "Dracosh", text]
19
+ };
20
+ const TIMEOUT_MS = 5_000; // notify-send can wait on a session bus with no notification daemon behind it
21
+
22
+ // BEL is zero-width, so it doesn't upset Ink's drawing; piped output doesn't get it
23
+ const ringBell = () => {
24
+ if (process.stdout.isTTY) process.stdout.write("\x07");
25
+ };
26
+
27
+ // notify(text, { bell }). The bell rings only when asked: Windows Terminal plays the system's sound for
28
+ // it by default, which would sound on top of the app's own chime. A native notification that fails (no
29
+ // notification daemon) gives way to the bell for the rest of the run.
30
+ export function createNotifier({ kind = findNotifier(), run = execFile, bell = ringBell } = {}) {
31
+ let use = kind;
32
+ return {
33
+ notify(text, { bell: ring = true } = {}) {
34
+ if (use === "bell") return void (ring && bell());
35
+ const tried = use;
36
+ const child = run(tried, COMMANDS[tried](text), { windowsHide: true, timeout: TIMEOUT_MS }, (err) => {
37
+ if (!err || use !== tried) return;
38
+ use = "bell";
39
+ if (ring) bell();
40
+ });
41
+ child?.unref?.(); // quitting doesn't wait for it
42
+ }
43
+ };
44
+ }
package/src/player.js ADDED
@@ -0,0 +1,117 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+
7
+ // The program that plays a .wav on this system: afplay on macOS, paplay, aplay or ffplay on Linux.
8
+ // Windows has none: PowerShell, its only built-in way, takes a third of a second to start for each
9
+ // sound, so the chime would come late after every answer. With none that works, sounds stay silent.
10
+
11
+ export const onPath = (name, env = process.env) =>
12
+ (env.PATH ?? "").split(path.delimiter).some((dir) => {
13
+ if (!dir) return false;
14
+ try {
15
+ accessSync(path.join(dir, name), constants.X_OK);
16
+ return true;
17
+ } catch {
18
+ return false;
19
+ }
20
+ });
21
+
22
+ // volume: whether the player takes a level; one that doesn't gets a quieter copy of the sound
23
+ const PLAYERS = {
24
+ afplay: { volume: true, args: (file, volume) => ["-v", String(volume), file] },
25
+ // PulseAudio's volume is cubic: the cube root gives the same loudness as afplay's linear level
26
+ paplay: { volume: true, args: (file, volume) => [`--volume=${Math.round(Math.cbrt(volume) * 65536)}`, file] },
27
+ aplay: { volume: false, args: (file) => ["-q", file] },
28
+ ffplay: { volume: true, args: (file, volume) => ["-nodisp", "-autoexit", "-loglevel", "quiet", "-volume", String(Math.round(volume * 100)), file] }
29
+ };
30
+ const LINUX = ["paplay", "aplay", "ffplay"];
31
+ const LINUX_MP3 = ["paplay", "ffplay"]; // aplay reads .wav only; paplay reads .mp3 with libsndfile 1.1+
32
+
33
+ // whether this system plays sounds at all (Settings leaves Sound, Volume and Read aloud out where it doesn't)
34
+ export const PLAYS_SOUNDS = process.platform !== "win32";
35
+
36
+ // The players on PATH to try, best first. mp3: only those that can play one (a natural voice's file).
37
+ export function findPlayers({ platform = process.platform, has = onPath, mp3 = false } = {}) {
38
+ if (platform === "win32") return [];
39
+ return (platform === "darwin" ? ["afplay"] : mp3 ? LINUX_MP3 : LINUX).filter((name) => has(name));
40
+ }
41
+
42
+ // How to run a player for a file at a volume: { command, args }
43
+ export function playCommand(name, file, volume, dir) {
44
+ const player = PLAYERS[name];
45
+ return { command: name, args: player.args(player.volume ? file : scaledWav(file, volume, dir), volume) };
46
+ }
47
+
48
+ // play(file, volume, done): plays, then calls done() whether it played or not; returns { kill } to cut
49
+ // it off. silent: no player left that works. A player that fails (paplay with no sound server, aplay
50
+ // with no sound card) is dropped for the rest of the run and the sound goes to the next one.
51
+ // dir: where quieter copies go.
52
+ export function createPlayer({ players = findPlayers(), run = execFile, dir } = {}) {
53
+ const left = [...players];
54
+ const play = (file, volume, done = () => {}) => {
55
+ let child = null;
56
+ let stopped = false;
57
+ const start = () => {
58
+ const name = left[0];
59
+ if (!name || stopped) return void done();
60
+ const { command, args } = playCommand(name, file, volume, dir);
61
+ child = run(command, args, (err) => {
62
+ if (!err || stopped || err.killed || err.signal) return void done();
63
+ if (left[0] === name) left.shift();
64
+ start();
65
+ });
66
+ };
67
+ start();
68
+ return {
69
+ kill() {
70
+ stopped = true;
71
+ child?.kill?.();
72
+ }
73
+ };
74
+ };
75
+ return {
76
+ play,
77
+ get silent() {
78
+ return left.length === 0;
79
+ }
80
+ };
81
+ }
82
+
83
+ // A 16-bit PCM .wav (what scripts/make-sounds.js writes) at a lower volume, made once per level in the
84
+ // system's temp folder and kept there for the next run, under a name that changes with the sound.
85
+ // Written under another name first, so a second Dracosh never plays half a file; made again if the
86
+ // system cleans the temp folder meanwhile.
87
+ const HEADER = 44;
88
+ const sources = new Map(); // file → its contents and a short hash of them, read once a run
89
+ export function scaledWav(file, volume, dir = path.join(tmpdir(), "dracosh-sounds")) {
90
+ if (volume >= 1) return file;
91
+ const level = Math.round(volume * 100);
92
+ let part = null;
93
+ try {
94
+ if (!sources.has(file)) {
95
+ const data = readFileSync(file);
96
+ sources.set(file, { data, hash: createHash("sha256").update(data).digest("hex").slice(0, 8) });
97
+ }
98
+ const { data: original, hash } = sources.get(file);
99
+ const out = path.join(dir, String(level), `${path.basename(file, ".wav")}-${hash}.wav`);
100
+ if (existsSync(out)) return out;
101
+ const data = Buffer.from(original);
102
+ for (let at = HEADER; at + 1 < data.length; at += 2) data.writeInt16LE(Math.round((data.readInt16LE(at) * level) / 100), at);
103
+ mkdirSync(path.dirname(out), { recursive: true });
104
+ part = `${out}.${process.pid}.part`;
105
+ writeFileSync(part, data);
106
+ try {
107
+ renameSync(part, out);
108
+ } catch (err) {
109
+ rmSync(part, { force: true });
110
+ if (!existsSync(out)) throw err; // another Dracosh made it first (Windows won't replace a file in use)
111
+ }
112
+ return out;
113
+ } catch {
114
+ if (part) rmSync(part, { force: true });
115
+ return file; // no temp folder to write to: the sound at full volume beats no sound
116
+ }
117
+ }
package/src/settings.js CHANGED
@@ -1,11 +1,15 @@
1
+ import { normalizeAi } from "./ai.js";
2
+ import { normalizeVoice } from "./voice.js";
1
3
  import { LANGUAGES, systemLanguage, t } from "./i18n.js";
2
4
 
3
- export const DEFAULTS = { everyMs: 600_000, rhythm: "minutes", sound: true, speak: false, volume: 0.5, dailyGoal: 20, tips: "sometimes", quiet: null, skipWeekends: true, deck: null, mix: null, homeLanguage: null, learningLanguage: null };
5
+ export const DEFAULTS = { everyMs: 600_000, rhythm: "minutes", sound: true, speak: false, volume: 0.5, dailyGoal: 20, tips: "sometimes", quiet: null, skipWeekends: true, deck: null, mix: null, homeLanguage: null, learningLanguage: null, ai: null, voice: null, theme: "auto" };
4
6
 
5
7
  export const INTERVALS = [60_000, 120_000, 300_000, 600_000, 900_000, 1_200_000, 1_800_000, 2_700_000, 3_600_000];
6
8
  export const GOALS = [5, 10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200];
7
9
  export const VOLUMES = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1];
8
10
  export const TIP_MODES = ["always", "sometimes", "off"];
11
+ // auto follows the terminal's background; dark and light are the palettes in src/ui/kit.js
12
+ export const THEMES = ["auto", "dark", "light"];
9
13
  // how cards come: one every few minutes (everyMs), or a session where Enter asks the next one right
10
14
  // away, endless or for a set number of cards, after which the minutes take over again
11
15
  export const RHYTHMS = ["minutes", "session", "session-10", "session-20"];
@@ -38,6 +42,7 @@ export function normalizeSettings(raw = {}) {
38
42
  volume: isNumber(raw.volume) && raw.volume >= 0 && raw.volume <= 1 ? raw.volume : DEFAULTS.volume,
39
43
  dailyGoal: isNumber(raw.dailyGoal) && raw.dailyGoal >= 1 ? Math.round(raw.dailyGoal) : DEFAULTS.dailyGoal,
40
44
  tips: normalizeTips(raw.tips),
45
+ theme: THEMES.includes(raw.theme) ? raw.theme : DEFAULTS.theme,
41
46
  skipWeekends: typeof raw.skipWeekends === "boolean" ? raw.skipWeekends : DEFAULTS.skipWeekends,
42
47
  quiet: raw.quiet && isHour(raw.quiet.from) && isHour(raw.quiet.to) ? { from: raw.quiet.from, to: raw.quiet.to } : null,
43
48
  deck: typeof raw.deck === "string" && raw.deck.trim() ? raw.deck : null, // picked in /decks; null = your first deck
@@ -46,6 +51,8 @@ export function normalizeSettings(raw = {}) {
46
51
  // the language you speak and the one you're learning, from the welcome (codes; null: not said)
47
52
  homeLanguage: isLanguage(raw.homeLanguage) ? raw.homeLanguage : null,
48
53
  learningLanguage: isLanguage(raw.learningLanguage) ? raw.learningLanguage : null,
54
+ ai: normalizeAi(raw.ai), // AI help (/settings): provider, model and address; the key is kept apart
55
+ voice: normalizeVoice(raw.voice), // natural voice (/settings → Voice); null: the system's voices
49
56
  language: typeof raw.language === "string" && Object.hasOwn(LANGUAGES, raw.language) ? raw.language : systemLanguage() // until picked in /settings, the system's
50
57
  };
51
58
  }
package/src/speech.js ADDED
@@ -0,0 +1,82 @@
1
+ import { execFile } from "node:child_process";
2
+ import { onPath } from "./player.js";
3
+
4
+ // The system's own voices: `say` on macOS, `espeak-ng` on Linux; none on Windows. Each one writes the
5
+ // word to an audio file, which the app then plays like its sounds, so it follows the volume and can be
6
+ // cut off. voiceFor(lang): the best voice for a language, or null; render(voice, words, file, volume,
7
+ // done): the running process, so it can be stopped. Voices are read once, when the first word is spoken.
8
+
9
+ // the region most learners mean (English from the US or Britain, not India; Chinese from the mainland)
10
+ const REGIONS = { en: ["US", "GB"], zh: ["CN", "TW"], pt: ["PT", "BR"], es: ["ES", "MX"], fr: ["FR"], de: ["DE"], nl: ["NL"] };
11
+ const NORWEGIAN = { no: "nb", nn: "nb" }; // both systems read Norwegian as Bokmål
12
+
13
+ const listOnce = (command, args, parse, run) => {
14
+ let voices = null;
15
+ return () =>
16
+ (voices ??= new Promise((resolve) => run(command, args, (err, out) => resolve(err ? [] : parse(String(out))))));
17
+ };
18
+
19
+ // macOS: `say -v ?` lists "Name pl_PL # sample"; the novelty voices are left out, and a premium or
20
+ // enhanced voice comes before a plain named one
21
+ const NOVELTY = new Set(["Albert", "Bad News", "Bahh", "Bells", "Boing", "Bubbles", "Cellos", "Good News", "Jester", "Organ", "Superstar", "Trinoids", "Whisper", "Wobble", "Zarvox", "Fred", "Junior", "Kathy", "Ralph", "Grandma", "Grandpa", "Rocko"]);
22
+ export const parseSay = (out) =>
23
+ out.split("\n").map((line) => line.match(/^(.+?)\s+([a-z]{2,3})_([A-Za-z0-9]+)\s+#/)).filter(Boolean).map(([, name, lang, region]) => ({ name: name.trim(), lang, region }));
24
+ const sayRank = (voice) => {
25
+ const regions = REGIONS[voice.lang] ?? [];
26
+ const region = regions.includes(voice.region) ? regions.indexOf(voice.region) : regions.length;
27
+ const quality = /\((Premium|Enhanced)\)/.test(voice.name) ? 0 : /\(/.test(voice.name) ? 2 : 1;
28
+ return region * 10 + quality;
29
+ };
30
+
31
+ // Linux: `espeak-ng --voices` lists " 5 en-us --/M English_(America) gmw/en-US ..."; the
32
+ // language column is what -v takes. Chinese is "cmn" there, and a plain code beats an odd variant.
33
+ const ESPEAK_CODE = { ...NORWEGIAN, zh: "cmn" };
34
+ export const parseEspeak = (out) =>
35
+ out.split("\n").slice(1).map((line) => line.trim().split(/\s+/)[1]).filter(Boolean).map((code) => {
36
+ const [lang, region = ""] = code.split("-");
37
+ return { name: code, lang, region: region.toUpperCase(), plain: !code.includes("-") || /^[a-z]+-[a-z]{2,3}$/.test(code) };
38
+ });
39
+ const espeakRank = (voice) => {
40
+ const regions = REGIONS[voice.lang === "cmn" ? "zh" : voice.lang] ?? [];
41
+ // a voice with no region is the language's main one ("pt" is Portugal's, "es" Spain's)
42
+ const region = !voice.region ? 0 : regions.includes(voice.region) ? regions.indexOf(voice.region) : regions.length;
43
+ return region * 10 + (voice.plain ? 0 : 1);
44
+ };
45
+
46
+ const SYSTEMS = {
47
+ say: {
48
+ ext: "aiff",
49
+ list: (run) => listOnce("say", ["-v", "?"], parseSay, run),
50
+ pick: (voices, lang) => voices.filter((voice) => voice.lang === (NORWEGIAN[lang] ?? lang) && !NOVELTY.has(voice.name)).sort((a, b) => sayRank(a) - sayRank(b))[0]?.name ?? null,
51
+ // say's own volume is ignored by today's voices: the player sets it
52
+ render: (run, voice, words, file, done) => run("say", ["-v", voice, "-o", file, "--", words], done),
53
+ playVolume: (volume) => volume
54
+ },
55
+ "espeak-ng": {
56
+ ext: "wav",
57
+ list: (run) => listOnce("espeak-ng", ["--voices"], parseEspeak, run),
58
+ pick: (voices, lang) => voices.filter((voice) => voice.lang === (ESPEAK_CODE[lang] ?? lang)).sort((a, b) => espeakRank(a) - espeakRank(b))[0]?.name ?? null,
59
+ // the volume goes into the file (-a, 100 is normal), so any player can play it as it is
60
+ render: (run, voice, words, file, done, volume) => run("espeak-ng", ["-v", voice, "-a", String(Math.round(volume * 100)), "-w", file, "--", words], done),
61
+ playVolume: () => 1
62
+ }
63
+ };
64
+
65
+ export function findSpeech({ platform = process.platform, has = onPath } = {}) {
66
+ if (platform === "win32") return null;
67
+ const name = platform === "darwin" ? "say" : "espeak-ng";
68
+ return has(name) ? name : null;
69
+ }
70
+
71
+ // null where the system has no voices
72
+ export function createSpeech({ name = findSpeech(), run = execFile } = {}) {
73
+ const system = SYSTEMS[name];
74
+ if (!system) return null;
75
+ const voices = system.list(run);
76
+ return {
77
+ ext: system.ext,
78
+ voiceFor: async (lang) => system.pick(await voices(), lang),
79
+ render: (voice, words, file, volume, done) => system.render(run, voice, words, file, done, volume),
80
+ playVolume: system.playVolume
81
+ };
82
+ }