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.
@@ -0,0 +1,238 @@
1
+ import { Fragment, useRef, useState } from "react";
2
+ import { Box, useInput } from "ink";
3
+ import { language, t } from "../i18n.js";
4
+ import { forgetKey, maskKey, saveKey } from "../ai.js";
5
+ import { ELEVENLABS, findVoiceKey, listVoices, speech, voiceLabel } from "../voice.js";
6
+ import { fold } from "../judge.js";
7
+ import { AnswerInput } from "./AnswerInput.js";
8
+ import { Choice, choiceHints } from "./Choice.js";
9
+ import { cutToWidth, html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
10
+
11
+ const SHOWN = 8; // voices listed at a time
12
+ const look = (text) => fold(text.toLowerCase());
13
+ const SHORT = ["noKey", "badKey", "noCredit", "noVoice"];
14
+
15
+ // /settings → Voice: the system's voices (free, built in) or a natural one from ElevenLabs with your own
16
+ // key. For ElevenLabs: the key, the voice, then a short sample read in it; only then is anything saved.
17
+ // `current`: settings.voice. onSave(voice | null) keeps the choice. `play(file)`: plays the sample.
18
+ // `speakOn`: Read aloud is on already (picking a voice turns it on). Esc goes back a step, from the
19
+ // first one it leaves.
20
+ export function VoiceSetup({ current, onSave, onClose, play = () => {}, speakOn = true }) {
21
+ const panel = usePanelWidth();
22
+ const [step, setStep] = useState("provider");
23
+ const [selected, setSelected] = useState(current ? 1 : 0);
24
+ const [key, setKey] = useState(null); // { key, from: "env" | "saved" | "typed", env? }
25
+ const [voices, setVoices] = useState(null);
26
+ const [voice, setVoice] = useState(null);
27
+ const [query, setQuery] = useState("");
28
+ const [error, setError] = useState("");
29
+ const [message, setMessage] = useState("");
30
+ const history = useRef([]);
31
+ const job = useRef(0); // a newer step makes an older request's answer stale
32
+ const request = useRef(null); // the request in flight, cancelled when it goes stale (a sample is billed)
33
+
34
+ const go = (next, pick = 0) => {
35
+ const at = history.current.indexOf(next);
36
+ if (at >= 0) history.current = history.current.slice(0, at);
37
+ else if (step !== next && step !== "checking" && step !== "failed") history.current.push(step);
38
+ setError("");
39
+ setMessage("");
40
+ setSelected(pick);
41
+ setStep(next);
42
+ };
43
+ const back = () => {
44
+ job.current += 1;
45
+ request.current?.abort();
46
+ setError("");
47
+ setMessage("");
48
+ const last = history.current.pop();
49
+ if (!last) return onClose();
50
+ setSelected(last === "provider" ? 1 : 0);
51
+ setStep(last);
52
+ };
53
+ const stillOn = () => {
54
+ const mine = ++job.current;
55
+ request.current?.abort();
56
+ request.current = new AbortController();
57
+ return () => mine === job.current;
58
+ };
59
+ // here the message says what's wrong, not where to fix it (this is the place)
60
+ const said = (err) => (SHORT.includes(err.code) ? t(`voice.short.${err.code}`, { env: ELEVENLABS.keyEnv }) : err.message);
61
+
62
+ async function pickProvider(index) {
63
+ if (index === 0) {
64
+ if (current) onSave(null);
65
+ return onClose(current ? t("voice.systemSet") : undefined);
66
+ }
67
+ const fresh = stillOn();
68
+ const found = await findVoiceKey();
69
+ if (!fresh()) return;
70
+ setKey(found);
71
+ if (found?.from === "env") return loadVoices(found);
72
+ go(found ? "keep-key" : "key");
73
+ }
74
+
75
+ async function loadVoices(withKey = key) {
76
+ go("voices");
77
+ const fresh = stillOn();
78
+ setVoices(null);
79
+ setQuery("");
80
+ try {
81
+ const list = await listVoices({ key: withKey?.key ?? null, url: current?.url, signal: request.current.signal });
82
+ if (!fresh()) return;
83
+ setVoices(list);
84
+ setSelected(Math.max(0, list.findIndex((item) => item.id === current?.id)));
85
+ } catch (err) {
86
+ if (!fresh()) return;
87
+ setVoices([]);
88
+ if (["badKey", "noKey"].includes(err.code) && withKey?.from !== "env") {
89
+ const at = history.current.indexOf("key");
90
+ if (at >= 0) history.current = history.current.slice(0, at);
91
+ setSelected(0);
92
+ setStep("key");
93
+ }
94
+ setError(said(err));
95
+ }
96
+ }
97
+
98
+ async function check(picked) {
99
+ const chosen = { provider: "elevenlabs", id: picked.id, name: picked.name, ...(current?.url ? { url: current.url } : {}) };
100
+ setVoice(chosen);
101
+ go("checking");
102
+ const fresh = stillOn();
103
+ try {
104
+ const file = await speech(chosen, t("voice.sample"), language(), { key: key?.key ?? null, signal: request.current.signal });
105
+ if (!fresh()) return;
106
+ play(file);
107
+ if (key?.from === "typed") await saveKey("elevenlabs", key.key);
108
+ onSave(chosen);
109
+ onClose(t(speakOn ? "voice.ready" : "voice.readyOn", { label: voiceLabel(chosen) }));
110
+ } catch (err) {
111
+ if (!fresh()) return;
112
+ setError(said(err));
113
+ setStep("failed");
114
+ setSelected(0);
115
+ }
116
+ }
117
+
118
+ const found = (voices ?? []).filter((item) => !query || look(`${item.name} ${item.note}`).includes(look(query)));
119
+
120
+ useInput((input, k) => {
121
+ if ((step === "checking" || (step === "voices" && voices === null)) && k.escape) return back();
122
+ if (step !== "voices" || voices === null) return;
123
+ if (k.escape) return query ? (setQuery(""), setSelected(0)) : back();
124
+ if (k.upArrow) return setSelected((i) => Math.max(0, i - 1));
125
+ if (k.downArrow) return setSelected((i) => Math.min(found.length - 1, i + 1));
126
+ if (k.return) return found[selected] && check(found[selected]);
127
+ if (k.backspace || k.delete) return query && (setQuery((q) => q.slice(0, -1)), setSelected(0));
128
+ const text = input.replace(/[\u0000-\u001f\u007f]/g, "");
129
+ if (text && !k.ctrl && !k.meta) {
130
+ setQuery((q) => q + text);
131
+ setSelected(0);
132
+ }
133
+ });
134
+
135
+ const problem = error && html`<${Box} marginTop=${1}><${Text} color=${theme.bad}>${error}<//><//>`;
136
+ const frame = (title, body, hints, { errorAbove = false } = {}) => html`
137
+ <${Fragment}>
138
+ <${Box} flexDirection="column" borderStyle="round" borderColor=${theme.accent} paddingX=${2} width=${panel}>
139
+ <${Text} bold color=${theme.accent}>${title}<//>
140
+ ${errorAbove && problem}
141
+ ${body}
142
+ ${message && html`<${Box} marginTop=${1}><${Text} color=${theme.good}>${message}<//><//>`}
143
+ ${!errorAbove && problem}
144
+ <//>
145
+ <${Box} paddingX=${1}><${KeyHints} text=${hints} /><//>
146
+ <//>
147
+ `;
148
+
149
+ if (step === "provider") {
150
+ const options = [{ label: t("voice.system"), note: t("voice.systemNote") }, { label: "ElevenLabs", note: t("voice.elevenNote") }];
151
+ return frame(
152
+ t("voice.title"),
153
+ html`
154
+ <${Box} flexDirection="column">
155
+ <${Text} dimColor>${t("voice.note")}<//>
156
+ <${Box} marginTop=${1}><${Text} dimColor>${t("voice.now", { label: voiceLabel(current) })}<//><//>
157
+ <${Box} marginTop=${1}><${Choice} options=${options} selected=${selected} onMove=${setSelected} onPick=${(i) => pickProvider(i).catch((err) => setError(err.message))} onCancel=${() => onClose()} /><//>
158
+ <//>
159
+ `,
160
+ choiceHints("back")
161
+ );
162
+ }
163
+
164
+ if (step === "keep-key") {
165
+ const options = [{ label: t("ai.keepKey"), note: maskKey(key.key) }, { label: t("ai.newKey") }, { label: t("ai.forgetKey"), danger: true }];
166
+ return frame(
167
+ t("voice.keyTitle"),
168
+ html`<${Box} marginTop=${1}><${Choice} options=${options} selected=${selected} onMove=${setSelected} onPick=${(i) => {
169
+ if (i === 0) return loadVoices();
170
+ if (i === 1) return go("key");
171
+ forgetKey("elevenlabs").then(() => {
172
+ setKey(null);
173
+ go("key");
174
+ setMessage(t("ai.keyForgotten", { provider: "ElevenLabs" }));
175
+ }, (err) => setError(err.message));
176
+ }} onCancel=${back} /><//>`,
177
+ choiceHints("back")
178
+ );
179
+ }
180
+
181
+ if (step === "key")
182
+ return frame(
183
+ t("voice.keyTitle"),
184
+ html`
185
+ <${Box} flexDirection="column">
186
+ <${Text} dimColor>${t("voice.keyNote", { env: ELEVENLABS.keyEnv, site: ELEVENLABS.site })}<//>
187
+ <${Box} marginTop=${1}><${AnswerInput} key="voice-key" plain secret escLeaves onChange=${() => (setError(""), setMessage(""))} onExit=${back} onSubmit=${(text) => {
188
+ const typed = text.trim();
189
+ if (!typed) return setError(t("ai.needKey"));
190
+ const next = { key: typed, from: "typed" };
191
+ setKey(next);
192
+ loadVoices(next);
193
+ }} /><//>
194
+ <//>
195
+ `,
196
+ t("keyHints.importName")
197
+ );
198
+
199
+ if (step === "voices") {
200
+ const top = Math.max(0, Math.min(selected - Math.floor(SHOWN / 2), found.length - SHOWN));
201
+ return frame(
202
+ t("voice.pickTitle"),
203
+ html`
204
+ <${Box} flexDirection="column">
205
+ <${Text} dimColor>${[key?.from === "env" && t("ai.keyFromEnv", { env: key.env }), t("voice.pickNote")].filter(Boolean).join(" ")}<//>
206
+ ${voices?.length === 0 && !error && html`<${Box} marginTop=${1}><${Text}>${t("voice.noVoices")}<//><//>`}
207
+ ${voices === null
208
+ ? html`<${Box} marginTop=${1}><${Text} dimColor>${t("voice.loading")}<//><//>`
209
+ : voices.length > 0 && html`
210
+ <${Box} flexDirection="column" marginTop=${1}>
211
+ ${(voices.length > SHOWN || query) && html`<${Box}><${Box} flexShrink=${0}><${Text} dimColor>${t("languages.search")} <//><//><${Text} wrap="truncate-start">${query}<//><${Box} flexShrink=${0}><${Text} inverse> <//><//><//>`}
212
+ <${Text} dimColor>${top > 0 ? " ↑" : " "}<//>
213
+ ${found.slice(top, top + SHOWN).map((item, i) => {
214
+ const on = top + i === selected;
215
+ const extra = item.id === current?.id ? t("voice.current") : item.note;
216
+ return html`<${Text} key=${item.id} color=${on ? theme.accent : undefined} bold=${on} wrap="truncate-end">${on ? "❯" : " "} ${cutToWidth(item.name, panel - 12)} ${extra ? html`<${Text} dimColor>· ${extra}<//>` : ""}<//>`;
217
+ })}
218
+ <${Text} dimColor>${top + SHOWN < found.length ? " ↓" : " "}<//>
219
+ <//>
220
+ `}
221
+ <//>
222
+ `,
223
+ voices && voices.length > SHOWN ? t("keyHints.modelPick") : choiceHints("back")
224
+ );
225
+ }
226
+
227
+ if (step === "checking")
228
+ return frame(t("voice.pickTitle"), html`<${Box} marginTop=${1}><${Text} dimColor>${t("voice.checking", { label: voiceLabel(voice) })}<//><//>`, t("keyHints.back"));
229
+
230
+ // failed: what now (a key from the environment is changed there, not here)
231
+ const options = [{ label: t("ai.tryAgain") }, { label: t("voice.otherVoice") }, ...(key?.from === "env" ? [] : [{ label: t("ai.otherKey") }])];
232
+ return frame(
233
+ t("voice.failedTitle", { label: voiceLabel(voice) }),
234
+ html`<${Box} marginTop=${1}><${Choice} options=${options} selected=${selected} onMove=${setSelected} onPick=${(i) => (i === 0 ? check(voice) : i === 1 ? loadVoices() : go("key"))} onCancel=${back} /><//>`,
235
+ choiceHints("back"),
236
+ { errorAbove: true }
237
+ );
238
+ }
package/src/ui/Welcome.js CHANGED
@@ -8,13 +8,13 @@ import { html, KeyHints, Text, theme, usePanelWidth } from "./kit.js";
8
8
  import { LanguageSearch } from "./Languages.js";
9
9
 
10
10
  export const WELCOME_STEPS = ["language", "home", "learning", "start"];
11
- const FIRST_WORDS_COUNT = 30;
11
+ export const FIRST_WORDS_COUNT = 30;
12
12
 
13
13
  // After the hatching, before the first question: the app's language, the one you speak, the one you're
14
14
  // learning, and a way to start. Every answer is kept as it's given (onStep), so a welcome left halfway
15
15
  // goes on from that step. `onPreviewLanguage` shows the texts in a language while it's only selected;
16
- // onStart(how): "words" (the first words of the pair), "tour", "import" (cards you have, /import) or
17
- // "own" (a deck of your own, in /add).
16
+ // onStart(how): "words" (the first words of the pair), "ai" (a list from AI help, set up first if it
17
+ // isn't), "tour", "import" (cards you have, /import) or "own" (a deck of your own, in /add).
18
18
  // `tour`: whether there's still a tour to show (a deck of your own may have taken its place).
19
19
  export function Welcome({ step, settings, tour = true, onPreviewLanguage, onStep, onStart }) {
20
20
  const panel = usePanelWidth();
@@ -40,6 +40,7 @@ export function Welcome({ step, settings, tour = true, onPreviewLanguage, onStep
40
40
  const words = learning && hasFirstWords(home, learning);
41
41
  const options = [
42
42
  words && { id: "words", label: t("welcome.start.words", { count: FIRST_WORDS_COUNT }), note: t("welcome.start.wordsNote", { language: languageName(learning), home: languageName(home) }) },
43
+ learning && { id: "ai", label: t("welcome.start.ai"), note: t("welcome.start.aiNote") },
43
44
  tour && { id: "tour", label: t("welcome.start.tour"), note: t("welcome.start.tourNote", { count: entry("tour.cards").length }) },
44
45
  { id: "import", label: t("welcome.start.import"), note: t("welcome.start.importNote") },
45
46
  { id: "own", label: t("welcome.start.own"), note: t("welcome.start.ownNote") }
package/src/ui/icons.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { BADGES } from "../progress.js";
2
- import { html, Text } from "./kit.js";
2
+ import { html, Text, theme } from "./kit.js";
3
3
  import { PixelGrid } from "./Mascot.js";
4
4
 
5
5
  // 8×8 pixel icons for the badge groups, drawn with the same half-block technique as the mascot.
@@ -237,8 +237,6 @@ const ICON_FOR = {
237
237
  "dragons-die": "die"
238
238
  };
239
239
 
240
- const LOCKED_COLOR = "#4a5058";
241
-
242
240
  // Rank colors for the badge groups that climb (more answers, longer streaks…): the higher, the rarer.
243
241
  const TIERS = [
244
242
  { name: "bronze", main: "#d08a4e", shade: "#8a4f1c", light: "#f3c9a0" },
@@ -326,7 +324,7 @@ export function BadgeIcon({ id, locked = false, flash = false, secret = false })
326
324
  if (secret) return html`<${PixelGrid} grid=${ICONS.secret.grid.map((row) => [...row])} palette=${ICONS.secret.palette} />`;
327
325
  const icon = ICONS[ICON_FOR[id]] ?? ICONS.star;
328
326
  const flat = (color) => Object.fromEntries(Object.keys(icon.palette).map((k) => [k, color]));
329
- const palette = flash ? flat("#ffffff") : locked ? flat(LOCKED_COLOR) : paletteFor(id, icon);
327
+ const palette = flash ? flat(theme.flash) : locked ? flat(theme.locked) : paletteFor(id, icon);
330
328
  // a locked ring is drawn filled in, so its silhouette doesn't give away what it is
331
329
  const own = OWN_GRIDS[id] ?? icon.grid;
332
330
  const grid = locked && !flash && id === "one-ring" ? own.map(fillIn) : own;
package/src/ui/kit.js CHANGED
@@ -28,17 +28,94 @@ export function Text(props) {
28
28
  return React.createElement(InsideText.Provider, { value: true }, React.createElement(Transform, { transform: unspill }, text));
29
29
  }
30
30
 
31
- // Dracosh palette: soft violet accents and a green dragon on dark, gold for fire and glory
32
- export const theme = {
33
- accent: "#9d7cd8",
34
- good: "#4ade80",
35
- bad: "#f87171",
36
- warn: "#fbbf24",
37
- text: "#c9ccd3",
38
- hint: "#8b919c", // the words in key hints: quieter than text, easier to read than dim
39
- track: "#3a3f47"
31
+ // Dracosh palettes: soft violet accents and gold for fire and glory. Dark is the original look; light
32
+ // keeps the same hues, darkened until text reads at 4.5:1 or more on white, in 24-bit color and after
33
+ // the step down to 256 colors (Terminal.app). The dragon and the badge art keep their colors in both.
34
+ export const PALETTES = {
35
+ dark: {
36
+ accent: "#9d7cd8",
37
+ good: "#4ade80",
38
+ bad: "#f87171",
39
+ warn: "#fbbf24",
40
+ text: "#c9ccd3",
41
+ hint: "#8b919c", // the words in key hints: quieter than text, easier to read than dim
42
+ track: "#3a3f47",
43
+ separator: "#5a606b", // the dots between key hints
44
+ mark: "#2a2440", // behind `something to type`
45
+ countdown: "#6b5e8a", // the bar until the next card
46
+ locked: "#4a5058", // a badge not won yet
47
+ flash: "#ffffff", // a badge lighting up
48
+ sky: "#7dd3fc",
49
+ pink: "#f0abfc",
50
+ dayHalfway: "#3f9d5e",
51
+ daySome: "#2f6b45",
52
+ dayNone: "#3a3f47",
53
+ dayRest: "#2a2e35",
54
+ dayFuture: "#1c1f25",
55
+ dieFace: "#f4f4f5",
56
+ dieEdge: "#c7c9d1",
57
+ diePips: "#2a2440"
58
+ },
59
+ light: {
60
+ accent: "#7b4cca",
61
+ good: "#117f3a",
62
+ bad: "#b01212",
63
+ warn: "#9c4a00",
64
+ text: "#303030",
65
+ hint: "#626262",
66
+ track: "#dadada",
67
+ separator: "#a8a8a8",
68
+ mark: "#ece4fa",
69
+ countdown: "#a08ad6",
70
+ locked: "#c6c6c6",
71
+ flash: "#000000",
72
+ sky: "#027fbf",
73
+ pink: "#b0179e",
74
+ dayHalfway: "#5fbf7f",
75
+ daySome: "#a6dcaa",
76
+ dayNone: "#dadada",
77
+ dayRest: "#e8e8e8",
78
+ dayFuture: "#f4f4f4",
79
+ dieFace: "#e4e4e4",
80
+ dieEdge: "#a8a8b0",
81
+ diePips: "#2a2440"
82
+ }
40
83
  };
41
84
 
85
+ // The colors in use. Screens read them while they render, so switching the theme repaints everything.
86
+ export const theme = { ...PALETTES.dark };
87
+
88
+ // what the terminal said its background is ("light" or "dark"), for the auto theme; unknown: dark
89
+ let background = null;
90
+ export function setBackground(value) {
91
+ background = value === "light" || value === "dark" ? value : null;
92
+ }
93
+ export const themeName = (choice) => (choice === "light" || choice === "dark" ? choice : background ?? "dark");
94
+ let applied = "dark";
95
+ export function applyTheme(choice) {
96
+ applied = themeName(choice);
97
+ Object.assign(theme, PALETTES[applied]);
98
+ return applied;
99
+ }
100
+
101
+ // A sprite's own color (a badge's rank, the dragon's element) used for words: as it is on dark; on
102
+ // light, darkened in steps until it reads at 4.5:1 on white, in 24-bit color and in 256 (chalk's pick).
103
+ const channels = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
104
+ const luminance = (rgb) => rgb.map((v) => v / 255).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)).reduce((sum, c, i) => sum + c * [0.2126, 0.7152, 0.0722][i], 0);
105
+ const onWhite = (rgb) => 1.05 / (luminance(rgb) + 0.05);
106
+ const STEPS = [0, 95, 135, 175, 215, 255];
107
+ const in256 = ([r, g, b]) => (r === g && g === b ? [r, g, b].map(() => (r < 8 ? 0 : r > 248 ? 255 : 8 + Math.round(((r - 8) / 247) * 24) * 10)) : [r, g, b].map((v) => STEPS[Math.round((v / 255) * 5)]));
108
+ const darkened = new Map();
109
+ export function readable(color) {
110
+ if (!color || applied !== "light") return color;
111
+ if (!darkened.has(color)) {
112
+ let rgb = channels(color);
113
+ for (let scale = 1; scale > 0 && (onWhite(rgb) < 4.5 || onWhite(in256(rgb)) < 4.5); scale -= 0.02) rgb = channels(color).map((v) => Math.round(v * scale));
114
+ darkened.set(color, `#${rgb.map((v) => v.toString(16).padStart(2, "0")).join("")}`);
115
+ }
116
+ return darkened.get(color);
117
+ }
118
+
42
119
  // Text where `backticks` mark something to type: shown in the accent color on a faint violet
43
120
  // background, like code in docs. Used for the tour's cards; `plain` shows the text as it is.
44
121
  export function Marked({ text, plain = false, ...props }) {
@@ -47,7 +124,7 @@ export function Marked({ text, plain = false, ...props }) {
47
124
  return React.createElement(
48
125
  Text,
49
126
  props,
50
- ...parts.map((part, i) => (i % 2 ? React.createElement(Text, { key: i, color: theme.accent, backgroundColor: "#2a2440", bold: true }, part) : part))
127
+ ...parts.map((part, i) => (i % 2 ? React.createElement(Text, { key: i, color: theme.accent, backgroundColor: theme.mark, bold: true }, part) : part))
51
128
  );
52
129
  }
53
130
 
@@ -69,7 +146,7 @@ export function KeyHints({ text }) {
69
146
  const key = KEY.exec(part)?.[0];
70
147
  const rest = key ? part.slice(key.length) : part;
71
148
  return [
72
- i > 0 && React.createElement(Text, { key: `s${i}`, color: "#5a606b" }, " · "),
149
+ i > 0 && React.createElement(Text, { key: `s${i}`, color: theme.separator }, " · "),
73
150
  key && React.createElement(Text, { key: `k${i}`, color: theme.text }, key),
74
151
  React.createElement(Text, { key: `r${i}`, color: theme.hint }, rest)
75
152
  ].filter(Boolean);
package/src/voice.js ADDED
@@ -0,0 +1,129 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { cleanUrl, findKey } from "./ai.js";
5
+ import { t } from "./i18n.js";
6
+ import { HOME } from "./store.js";
7
+
8
+ // Natural voices from ElevenLabs, with the user's own key (/settings → Voice). Optional: without one,
9
+ // words are read by the system's voices. Each word is generated once and kept in ~/.dracosh/audio,
10
+ // so a card costs once, not on every review.
11
+ export const ELEVENLABS = { url: "https://api.elevenlabs.io", keyEnv: "ELEVENLABS_API_KEY", site: "elevenlabs.io/app/settings/api-keys" };
12
+ // Flash v2.5: the cheapest per character, fast, and takes the word's language as a hint
13
+ export const MODEL = "eleven_flash_v2_5";
14
+ const LANGUAGES = new Set(["en", "ja", "zh", "de", "hi", "fr", "ko", "pt", "it", "es", "id", "nl", "tr", "fil", "pl", "sv", "bg", "ro", "ar", "cs", "el", "fi", "hr", "ms", "sk", "da", "ta", "uk", "ru", "hu", "no", "vi"]);
15
+ const CODE = { nb: "no", nn: "no", tl: "fil" };
16
+ const codeOf = (lang) => CODE[lang] ?? lang;
17
+ // a language the voice can read; the others stay with the system's voices
18
+ export const speaksLanguage = (lang) => LANGUAGES.has(codeOf(lang));
19
+
20
+ export const AUDIO_DIR = join(HOME, "audio");
21
+ const TIMEOUT_MS = 20_000;
22
+
23
+ // settings.voice, as saved: { provider: "elevenlabs", id, name, url? } (url: another of its servers, the
24
+ // EU one say), or null for the system's voices. The key goes to the address, so only ElevenLabs' own.
25
+ const isElevenLabs = (text) => typeof text === "string" && /^https:\/\/([a-z0-9-]+\.)*elevenlabs\.io\/?$/i.test(text.trim());
26
+ export function normalizeVoice(raw) {
27
+ if (!raw || typeof raw !== "object" || raw.provider !== "elevenlabs") return null;
28
+ if (typeof raw.id !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(raw.id)) return null;
29
+ const name = typeof raw.name === "string" && raw.name.trim() ? raw.name.trim().slice(0, 60) : raw.id;
30
+ return { provider: "elevenlabs", id: raw.id, name, ...(isElevenLabs(raw.url) ? { url: cleanUrl(raw.url) } : {}) };
31
+ }
32
+
33
+ export const voiceLabel = (voice) => (voice ? `ElevenLabs · ${voice.name}` : t("voice.system"));
34
+ const urlOf = (voice) => voice?.url ?? ELEVENLABS.url;
35
+
36
+ // What went wrong, said as what to do: `code` is noKey, badKey, noCredit, noVoice, rateLimit, offline,
37
+ // timeout, server or failed. The key is never part of the message.
38
+ export class VoiceError extends Error {
39
+ constructor(code, vars = {}) {
40
+ super(t(`voice.errors.${code}`, { env: ELEVENLABS.keyEnv, ...vars }));
41
+ this.code = code;
42
+ }
43
+ }
44
+
45
+ export const findVoiceKey = () => findKey("elevenlabs");
46
+
47
+ async function call(voice, key, path, { body, signal, timeoutMs = TIMEOUT_MS } = {}) {
48
+ if (!key) throw new VoiceError("noKey");
49
+ const timeout = AbortSignal.timeout(timeoutMs);
50
+ let response;
51
+ try {
52
+ response = await fetch(`${urlOf(voice)}${path}`, {
53
+ method: body ? "POST" : "GET",
54
+ headers: { "xi-api-key": key, ...(body ? { "content-type": "application/json", accept: "audio/mpeg" } : {}) },
55
+ body: body && JSON.stringify(body),
56
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout
57
+ });
58
+ } catch (err) {
59
+ if (signal?.aborted) throw err;
60
+ throw new VoiceError(timeout.aborted ? "timeout" : "offline");
61
+ }
62
+ if (response.ok) return response;
63
+ let detail = {};
64
+ try {
65
+ const data = JSON.parse(await response.text());
66
+ detail = typeof data?.detail === "object" && data.detail ? data.detail : { message: data?.detail };
67
+ } catch {}
68
+ const code = detail.code ?? detail.status ?? "";
69
+ const said = String(detail.message ?? response.statusText ?? "").split(key).join("…").slice(0, 200);
70
+ if (response.status === 402 || /insufficient_credits|quota_exceeded/.test(code)) throw new VoiceError("noCredit");
71
+ if (response.status === 401 || response.status === 403) throw new VoiceError("badKey");
72
+ if (response.status === 404) throw new VoiceError("noVoice");
73
+ if (response.status === 429) throw new VoiceError("rateLimit");
74
+ if (response.status >= 500) throw new VoiceError("server", { status: response.status });
75
+ throw new VoiceError("failed", { status: response.status, detail: said });
76
+ }
77
+
78
+ // the voices the account can use, premade ones included, by name. → [{ id, name, note }]
79
+ export async function listVoices({ key, url, signal } = {}) {
80
+ const voices = [];
81
+ let token = null;
82
+ for (let page = 0; page < 5; page++) {
83
+ const query = new URLSearchParams({ page_size: "100", ...(token ? { next_page_token: token } : {}) });
84
+ const data = await (await call({ url }, key, `/v2/voices?${query}`, { signal })).json().catch(() => ({}));
85
+ for (const voice of Array.isArray(data.voices) ? data.voices : []) {
86
+ if (typeof voice?.voice_id !== "string" || !voice.voice_id) continue;
87
+ const labels = voice.labels && typeof voice.labels === "object" ? voice.labels : {};
88
+ const note = [labels.gender, labels.accent, labels.age].filter((v) => typeof v === "string" && v).join(", ");
89
+ voices.push({ id: voice.voice_id, name: typeof voice.name === "string" && voice.name.trim() ? voice.name.trim() : voice.voice_id, note });
90
+ }
91
+ if (!data.has_more || !data.next_page_token) break;
92
+ token = data.next_page_token;
93
+ }
94
+ const seen = new Set();
95
+ return voices.filter((voice) => !seen.has(voice.id) && seen.add(voice.id)).sort((a, b) => a.name.localeCompare(b.name));
96
+ }
97
+
98
+ // where a word's audio is kept: one file per voice, model, language and text
99
+ export const audioPath = (voice, text, lang) => join(AUDIO_DIR, `${createHash("sha256").update(JSON.stringify([voice.id, MODEL, codeOf(lang), text])).digest("hex").slice(0, 32)}.mp3`);
100
+
101
+ // The word as an mp3 file: the kept one, or a new one from ElevenLabs. → the file's path. `key`: null
102
+ // for only a kept one; left out, the saved one (or the environment's)
103
+ export async function speech(voice, text, lang, { key, signal, timeoutMs } = {}) {
104
+ const file = audioPath(voice, text, lang);
105
+ try {
106
+ if ((await stat(file)).size > 0) return file;
107
+ } catch {}
108
+ if (key === undefined) key = (await findVoiceKey())?.key ?? null;
109
+ const query = new URLSearchParams({ output_format: "mp3_44100_64" });
110
+ const response = await call(voice, key, `/v1/text-to-speech/${encodeURIComponent(voice.id)}?${query}`, { signal, timeoutMs, body: { text, model_id: MODEL, language_code: codeOf(lang) } });
111
+ let audio;
112
+ try {
113
+ audio = Buffer.from(await response.arrayBuffer());
114
+ } catch (err) {
115
+ if (signal?.aborted) throw err;
116
+ throw new VoiceError("offline");
117
+ }
118
+ if (!audio.length) throw new VoiceError("failed", { status: response.status, detail: t("voice.errors.empty") });
119
+ await mkdir(AUDIO_DIR, { recursive: true });
120
+ const tmp = `${file}.${randomUUID()}.tmp`; // the same word asked twice at once writes two files
121
+ try {
122
+ await writeFile(tmp, audio);
123
+ await rename(tmp, file);
124
+ } catch (err) {
125
+ await rm(tmp, { force: true }).catch(() => {});
126
+ throw err;
127
+ }
128
+ return file;
129
+ }