pi-reply-reader 0.0.0-stage → 0.2.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/CHANGELOG.md +200 -0
- package/LICENSE +21 -0
- package/README.md +710 -2
- package/dist/bin/reply-reader.js +49 -0
- package/dist/src/cli.js +329 -0
- package/dist/src/listener.js +532 -0
- package/dist/src/music.js +452 -0
- package/dist/src/outputs.js +86 -0
- package/dist/src/playback.js +369 -0
- package/dist/src/player.js +265 -0
- package/dist/src/project.js +50 -0
- package/dist/src/reading-lock.js +371 -0
- package/dist/src/settings.js +126 -0
- package/dist/src/speech-text.js +1028 -0
- package/dist/src/voice.js +173 -0
- package/examples/reply-reader-desktop-audio.service +57 -0
- package/examples/reply-reader-vps-audio.service +57 -0
- package/extensions/reply-reader.ts +1278 -0
- package/package.json +71 -4
- package/src/auto-queue.ts +123 -0
- package/src/cli.ts +346 -0
- package/src/listener.ts +522 -0
- package/src/music.ts +474 -0
- package/src/outputs.ts +105 -0
- package/src/pause-key.ts +105 -0
- package/src/playback.ts +423 -0
- package/src/player.ts +255 -0
- package/src/project.ts +46 -0
- package/src/prompts.ts +142 -0
- package/src/questions.ts +19 -0
- package/src/reader-events.ts +44 -0
- package/src/reading-lock.ts +465 -0
- package/src/replies.ts +64 -0
- package/src/sections.ts +47 -0
- package/src/settings.ts +125 -0
- package/src/sherpa-onnx-node.d.ts +29 -0
- package/src/speech-text.ts +1215 -0
- package/src/voice.ts +195 -0
|
@@ -0,0 +1,1028 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns a Markdown reply into text meant to be heard: the syntax a voice would read literally
|
|
3
|
+
* ("asterisco asterisco", "or col 1 or", "comilla simple") is removed and the words are kept.
|
|
4
|
+
* Deterministic and model-free, so the same reply always sounds the same.
|
|
5
|
+
*/
|
|
6
|
+
export function speechText(markdown, language) {
|
|
7
|
+
return speechReading(markdown, language).text;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The cleaned text plus the language its added words are in (S7). Pass `language` when `markdown` is part
|
|
11
|
+
* of a larger text (a section, the closing questions), so the part follows the language of the whole.
|
|
12
|
+
*/
|
|
13
|
+
export function speechReading(markdown, language = detectLanguage(markdown)) {
|
|
14
|
+
const { text } = speechNarration(markdown, language);
|
|
15
|
+
return { text, language };
|
|
16
|
+
}
|
|
17
|
+
/** (S12) `speechReading`, plus the fragments playback speaks and the tokens the cleanup could not classify. */
|
|
18
|
+
export function speechNarration(markdown, language = detectLanguage(markdown)) {
|
|
19
|
+
return renderNarration(narrationPlan(markdown), language);
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* (S18, T48) Several documents read one after another, each cleaned on its own, so no Markdown block of one (an
|
|
23
|
+
* unclosed code fence, a list) runs into the next. Empty parts say nothing.
|
|
24
|
+
*/
|
|
25
|
+
export function speechNarrationOfParts(parts, language) {
|
|
26
|
+
const narrations = parts.map((part) => speechNarration(part, language)).filter((narration) => narration.text);
|
|
27
|
+
return {
|
|
28
|
+
text: narrations.map((narration) => narration.text).join("\n\n"),
|
|
29
|
+
language,
|
|
30
|
+
fragments: narrations.flatMap((narration) => narration.fragments),
|
|
31
|
+
diagnostics: narrations.flatMap((narration) => narration.diagnostics),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* (S7) English or Spanish, from the text's own function words; code, URLs and paths do not count.
|
|
36
|
+
* Spanish wins ties, so a reply with no clear English majority reads as it always did.
|
|
37
|
+
*/
|
|
38
|
+
export function detectLanguage(markdown) {
|
|
39
|
+
return languageOfWords(markdown) ?? "es";
|
|
40
|
+
}
|
|
41
|
+
/** (S7, S18) `detectLanguage`, or undefined when the text has no function word of either language ("git", "OK?"). */
|
|
42
|
+
export function languageOfWords(markdown) {
|
|
43
|
+
const prose = markdown
|
|
44
|
+
.replace(/^\s{0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^\s{0,3}\1[^\n]*$|(?![\s\S]))/gm, " ")
|
|
45
|
+
// The closing heading every reply here uses is English even in a Spanish reply.
|
|
46
|
+
.replace(/^\s*(?:#{1,6}\s+|\*\*|__)?needs your decision:?(?:\*\*|__)?\s*$/gim, " ")
|
|
47
|
+
.replace(/(`+)[\s\S]+?\1/g, " ")
|
|
48
|
+
.replace(/\S*(?::\/\/|[/\\~])\S*/g, " ")
|
|
49
|
+
.toLowerCase();
|
|
50
|
+
let english = 0;
|
|
51
|
+
let spanish = 0;
|
|
52
|
+
for (const [word] of prose.matchAll(/\p{L}+/gu)) {
|
|
53
|
+
if (ENGLISH_WORDS.has(word))
|
|
54
|
+
english++;
|
|
55
|
+
else if (SPANISH_WORDS.has(word))
|
|
56
|
+
spanish++;
|
|
57
|
+
}
|
|
58
|
+
if (english === 0 && spanish === 0)
|
|
59
|
+
return undefined;
|
|
60
|
+
return english > spanish ? "en" : "es";
|
|
61
|
+
}
|
|
62
|
+
/** Common function words found in one language only ("a", "no" and "me" are in both and count for neither). */
|
|
63
|
+
const ENGLISH_WORDS = new Set("the and of to is are was were be been being it its this that these those with for from on at by an as or not but if then than when which what who how you your we our they their there here will would can could should does do did has have had into only also just about all any each more most such so".split(" "));
|
|
64
|
+
const SPANISH_WORDS = new Set("el la los las de del al que y en un una unos unas es son era fue ser está están estar por para con sin se lo le les su sus este esta esto estos estas ese esa eso como más pero si sí ya hay cuando también porque sobre muy entre hasta desde todo todos cada qué cómo donde dónde o ni".split(" "));
|
|
65
|
+
/** The phrasebook of the text being cleaned; `renderNarration` sets it around one synchronous run. */
|
|
66
|
+
let words;
|
|
67
|
+
/** Where `renderNarration` collects diagnostics during its run, and the source line of the block being rendered. */
|
|
68
|
+
let diagnosis;
|
|
69
|
+
/**
|
|
70
|
+
* (k5) The tags of the text being rendered, in the order the renderer meets them: a first run records them, and
|
|
71
|
+
* `paired` then says which opening and closing tags match, for the run that is kept.
|
|
72
|
+
*/
|
|
73
|
+
let tagging;
|
|
74
|
+
/** (S12) The blocks of `markdown`, language-free: fences, table rows and one block per other line. */
|
|
75
|
+
export function narrationPlan(markdown) {
|
|
76
|
+
const blocks = [];
|
|
77
|
+
const lines = markdown.replace(/\r\n?/g, "\n").split("\n");
|
|
78
|
+
let fence;
|
|
79
|
+
for (let i = 0; i < lines.length; i++) {
|
|
80
|
+
const raw = lines[i];
|
|
81
|
+
if (fence) {
|
|
82
|
+
const close = /^\s*(`{3,}|~{3,})\s*$/.exec(raw);
|
|
83
|
+
if (close && close[1][0] === fence.char && close[1].length >= fence.length)
|
|
84
|
+
fence = undefined;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const open = /^\s{0,3}(`{3,}|~{3,})/.exec(raw);
|
|
88
|
+
if (open) {
|
|
89
|
+
fence = { char: open[1][0], length: open[1].length };
|
|
90
|
+
blocks.push({ role: "codeBlock", line: i + 1 });
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (raw.includes("|") && TABLE_SEPARATOR.test(lines[i + 1] ?? "")) {
|
|
94
|
+
blocks.push({ role: "row", cells: tableCells(raw), line: i + 1 });
|
|
95
|
+
i++;
|
|
96
|
+
while (i + 1 < lines.length && lines[i + 1].includes("|") && lines[i + 1].trim() !== "") {
|
|
97
|
+
i++;
|
|
98
|
+
blocks.push({ role: "row", cells: tableCells(lines[i]), line: i + 1 });
|
|
99
|
+
}
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
blocks.push(lineBlock(raw, i + 1));
|
|
103
|
+
}
|
|
104
|
+
return { blocks };
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* (S12) The words of `plan` in `language`: one line per block (and a blank one after a heading, so playback pauses
|
|
108
|
+
* as at a blank line), split into fragments, with the tokens no reading class claimed.
|
|
109
|
+
*/
|
|
110
|
+
export function renderNarration(plan, language) {
|
|
111
|
+
const previous = { words, diagnosis, tagging };
|
|
112
|
+
words = PHRASEBOOKS[language];
|
|
113
|
+
try {
|
|
114
|
+
tagging = undefined;
|
|
115
|
+
// (k5) A closing tag anywhere means a pair may span blocks: a first run finds which tags match.
|
|
116
|
+
if (plan.blocks.some((block) => CLOSING_TAG.test("source" in block ? block.source : "cells" in block ? block.cells.join(" ") : ""))) {
|
|
117
|
+
tagging = { seen: [], next: 0 };
|
|
118
|
+
rendered(plan, language);
|
|
119
|
+
tagging = { seen: [], paired: pairedTags(tagging.seen), next: 0 };
|
|
120
|
+
}
|
|
121
|
+
return rendered(plan, language);
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
({ words, diagnosis, tagging } = previous);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const CLOSING_TAG = /<\/\p{L}[\p{L}\p{N}-]*>/u;
|
|
128
|
+
/** (k5) Which of `seen` belong to a pair: each closing tag matches the nearest open tag of the same name before it. */
|
|
129
|
+
function pairedTags(seen) {
|
|
130
|
+
const paired = seen.map(() => false);
|
|
131
|
+
const open = new Map();
|
|
132
|
+
seen.forEach(({ name, closing }, index) => {
|
|
133
|
+
const key = name.toLowerCase();
|
|
134
|
+
const stack = open.get(key) ?? [];
|
|
135
|
+
open.set(key, stack);
|
|
136
|
+
if (!closing)
|
|
137
|
+
stack.push(index);
|
|
138
|
+
else {
|
|
139
|
+
const start = stack.pop();
|
|
140
|
+
if (start !== undefined)
|
|
141
|
+
paired[start] = paired[index] = true;
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
return paired;
|
|
145
|
+
}
|
|
146
|
+
/** One run of the renderer over `plan`, with the current phrasebook. */
|
|
147
|
+
function rendered(plan, language) {
|
|
148
|
+
diagnosis = { diagnostics: [], line: 0 };
|
|
149
|
+
const lines = [];
|
|
150
|
+
for (const block of plan.blocks) {
|
|
151
|
+
diagnosis.line = block.line;
|
|
152
|
+
const role = block.role === "break" ? "paragraph" : block.role;
|
|
153
|
+
lines.push({ text: numbersInWords(finished(blockText(block))), role });
|
|
154
|
+
// A heading or bold-only line ends its section, so playback pauses as at a blank line; trim drops a last one.
|
|
155
|
+
if (block.role === "heading")
|
|
156
|
+
lines.push({ text: "", role });
|
|
157
|
+
}
|
|
158
|
+
const text = lines
|
|
159
|
+
.map((line) => line.text)
|
|
160
|
+
.join("\n")
|
|
161
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
162
|
+
.trim();
|
|
163
|
+
return { text, language, fragments: fragmentsOf(lines), diagnostics: diagnosis.diagnostics };
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* (S14) What a reading that waited in the line says first: "Respuesta P12.R2." / "Reply P12.R2." for a reply,
|
|
167
|
+
* "Archivo notas.md." / "File notes.md." for a file, cleaned like any text in `language`, with a section break after it.
|
|
168
|
+
*/
|
|
169
|
+
export function announcement(kind, name, language) {
|
|
170
|
+
// As inline code, so a name's own `_` or `*` is not read as emphasis.
|
|
171
|
+
const named = name.includes("`") ? name : `\`${name}\``;
|
|
172
|
+
const fragments = speechNarration(`${PHRASEBOOKS[language][kind]} ${named}.`, language).fragments;
|
|
173
|
+
const last = fragments.at(-1);
|
|
174
|
+
if (last)
|
|
175
|
+
last.after = "paragraph";
|
|
176
|
+
return fragments;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* (S19) What a reading of another project than the last one says first: the project's name, read like any text in
|
|
180
|
+
* `language` ("pi-reply-reader.", "p uno."), with a section break after it.
|
|
181
|
+
*/
|
|
182
|
+
export function projectAnnouncement(project, language) {
|
|
183
|
+
// As inline code, so a name's own `_` or `*` is not read as emphasis.
|
|
184
|
+
const named = project.includes("`") ? project : `\`${project}\``;
|
|
185
|
+
const fragments = speechNarration(`${named}.`, language).fragments;
|
|
186
|
+
const last = fragments.at(-1);
|
|
187
|
+
if (last)
|
|
188
|
+
last.after = "paragraph";
|
|
189
|
+
return fragments;
|
|
190
|
+
}
|
|
191
|
+
/** (S12) Text already meant for speech, split as playback speaks it: every fragment a paragraph's. */
|
|
192
|
+
export function spokenFragments(text) {
|
|
193
|
+
return fragmentsOf(text.split("\n").map((line) => ({ text: line, role: "paragraph" })));
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Sentences and lines, in order, each with the boundary after it; Supertonic only calls back once per
|
|
197
|
+
* 300 characters, so we split first. Never at ":" or ";", where a pause would sound like a full stop.
|
|
198
|
+
* A line with no sentence (blank, or emoji only) ends a paragraph.
|
|
199
|
+
*/
|
|
200
|
+
function fragmentsOf(lines) {
|
|
201
|
+
const result = [];
|
|
202
|
+
let blank = false;
|
|
203
|
+
for (const { text, role } of lines) {
|
|
204
|
+
const sentences = text
|
|
205
|
+
.split(/(?<=[.!?…])\s+/)
|
|
206
|
+
.map((sentence) => sentence.trim())
|
|
207
|
+
.filter((sentence) => sentence !== "");
|
|
208
|
+
if (sentences.length === 0) {
|
|
209
|
+
blank = true;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
const previous = result.at(-1);
|
|
213
|
+
if (previous)
|
|
214
|
+
previous.after = blank ? "paragraph" : "line";
|
|
215
|
+
blank = false;
|
|
216
|
+
for (const sentence of sentences)
|
|
217
|
+
result.push({ text: sentence, role, after: "sentence" });
|
|
218
|
+
}
|
|
219
|
+
return result;
|
|
220
|
+
}
|
|
221
|
+
/** The passes that once ran over the whole text; none of them crosses a line break, so they run per line. */
|
|
222
|
+
function finished(line) {
|
|
223
|
+
const spaced = line.replace(/[ \t]{2,}|\t/g, " ");
|
|
224
|
+
return (words.contracts ? contracted(spaced) : spaced)
|
|
225
|
+
// A numbered heading or bold line ("## 1. Estado", "## 5.2. Título") starts with "1." too; "1:" keeps playback
|
|
226
|
+
// from cutting there.
|
|
227
|
+
.replace(new RegExp(`^(\\d+(?: ${words.point} \\d+)*)\\. `), "$1: ");
|
|
228
|
+
}
|
|
229
|
+
/** Spanish: the readings add "el comando", "la rama", "un commit" next to "de" and "a". */
|
|
230
|
+
function contracted(text) {
|
|
231
|
+
return (text
|
|
232
|
+
// Spanish contracts "de el" and "a el" (but not "de él").
|
|
233
|
+
.replace(/(?<![\p{L}\p{N}])([dD]e|[aA]) el(?![\p{L}\p{N}])/gu, (_m, word) => (word.length === 1 ? `${word}l` : `${word[0]}el`))
|
|
234
|
+
// The reverse for a contraction already written before the token: "del el comando" → "del comando",
|
|
235
|
+
// "del la rama" → "de la rama", "al un commit" → "a un commit".
|
|
236
|
+
.replace(/(?<![\p{L}\p{N}])([dD]e|[aA])l (el|la|un) (comando|carpeta|rama|commit|etiqueta)(?![\p{L}\p{N}])/gu, (_m, word, article, noun) => (article === "el" ? `${word}l ${noun}` : `${word} ${article} ${noun}`)));
|
|
237
|
+
}
|
|
238
|
+
const SPANISH_UNITS = "cero uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciséis diecisiete dieciocho diecinueve veinte veintiuno veintidós veintitrés veinticuatro veinticinco veintiséis veintisiete veintiocho veintinueve".split(" ");
|
|
239
|
+
const SPANISH_TENS = " veinte treinta cuarenta cincuenta sesenta setenta ochenta noventa".split(" ");
|
|
240
|
+
const SPANISH_HUNDREDS = " ciento doscientos trescientos cuatrocientos quinientos seiscientos setecientos ochocientos novecientos".split(" ");
|
|
241
|
+
/** "veintiuno" → "veintiún", "treinta y uno" → "treinta y un": before "mil", "millones" or a noun. */
|
|
242
|
+
function apocope(text) {
|
|
243
|
+
return text.replace(/(veinti)?uno$/, (_m, twenty) => (twenty ? "veintiún" : "un"));
|
|
244
|
+
}
|
|
245
|
+
function spanishBelowThousand(n) {
|
|
246
|
+
if (n === 100)
|
|
247
|
+
return "cien";
|
|
248
|
+
const hundreds = SPANISH_HUNDREDS[Math.floor(n / 100)];
|
|
249
|
+
const rest = n % 100;
|
|
250
|
+
const tens = rest < 30 ? SPANISH_UNITS[rest] : `${SPANISH_TENS[Math.floor(rest / 10)]}${rest % 10 ? ` y ${SPANISH_UNITS[rest % 10]}` : ""}`;
|
|
251
|
+
return [hundreds, rest || !hundreds ? tens : ""].filter((part) => part !== "").join(" ");
|
|
252
|
+
}
|
|
253
|
+
function spanishCardinal(n) {
|
|
254
|
+
if (n >= 1_000_000) {
|
|
255
|
+
const millions = Math.floor(n / 1_000_000);
|
|
256
|
+
const rest = n % 1_000_000;
|
|
257
|
+
const head = millions === 1 ? "un millón" : `${apocope(spanishCardinal(millions))} millones`;
|
|
258
|
+
return rest ? `${head} ${spanishCardinal(rest)}` : head;
|
|
259
|
+
}
|
|
260
|
+
if (n >= 1000) {
|
|
261
|
+
const thousands = Math.floor(n / 1000);
|
|
262
|
+
const rest = n % 1000;
|
|
263
|
+
const head = thousands === 1 ? "mil" : `${apocope(spanishBelowThousand(thousands))} mil`;
|
|
264
|
+
return rest ? `${head} ${spanishBelowThousand(rest)}` : head;
|
|
265
|
+
}
|
|
266
|
+
return spanishBelowThousand(n);
|
|
267
|
+
}
|
|
268
|
+
const ENGLISH_UNITS = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split(" ");
|
|
269
|
+
const ENGLISH_TENS = " twenty thirty forty fifty sixty seventy eighty ninety".split(" ");
|
|
270
|
+
function englishCardinal(n) {
|
|
271
|
+
for (const [size, name] of [[1e9, "billion"], [1e6, "million"], [1e3, "thousand"], [100, "hundred"]]) {
|
|
272
|
+
if (n >= size) {
|
|
273
|
+
const rest = n % size;
|
|
274
|
+
const head = `${englishCardinal(Math.floor(n / size))} ${name}`;
|
|
275
|
+
return rest ? `${head} ${englishCardinal(rest)}` : head;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return n < 20 ? ENGLISH_UNITS[n] : `${ENGLISH_TENS[Math.floor(n / 10)]}${n % 10 ? ` ${ENGLISH_UNITS[n % 10]}` : ""}`;
|
|
279
|
+
}
|
|
280
|
+
/** (j1) Frequent feminine nouns, singular and plural: "una respuesta", "veintiuna líneas". Tunable. */
|
|
281
|
+
const FEMININE = new Set(("línea respuesta pregunta sesión tarea vez hora semana página carpeta rama prueba versión lectura voz opción regla palabra cosa parte persona máquina salida entrada imagen corrida fila " +
|
|
282
|
+
"líneas respuestas preguntas sesiones tareas veces horas semanas páginas carpetas ramas pruebas versiones lecturas voces opciones reglas palabras cosas partes personas máquinas salidas entradas imágenes corridas filas").split(" "));
|
|
283
|
+
/** (j1) Function words a number ending in 1 keeps "uno" before: "de 1 a 5", "1 de 3". */
|
|
284
|
+
const KEEPS_UNO = new Set("a de del al y e o u ni en por para con sin entre hasta desde sobre contra según que es son más menos coma punto no ya se lo la el los las le está era queda sigue fue".split(" "));
|
|
285
|
+
const SPANISH = {
|
|
286
|
+
codeBlock: "Bloque de código.",
|
|
287
|
+
reply: "Respuesta",
|
|
288
|
+
file: "Archivo",
|
|
289
|
+
needsYourDecision: "Decisiones pendientes",
|
|
290
|
+
contracts: true,
|
|
291
|
+
command: "el comando",
|
|
292
|
+
folder: "la carpeta",
|
|
293
|
+
branch: "la rama",
|
|
294
|
+
aCommit: "un commit",
|
|
295
|
+
in: "en",
|
|
296
|
+
line: "línea",
|
|
297
|
+
dot: "punto",
|
|
298
|
+
point: "punto",
|
|
299
|
+
or: "o",
|
|
300
|
+
number: "número",
|
|
301
|
+
plus: "más",
|
|
302
|
+
orLater: "o superior",
|
|
303
|
+
orMore: "o más",
|
|
304
|
+
approximately: "aproximadamente",
|
|
305
|
+
times: "por",
|
|
306
|
+
units: {
|
|
307
|
+
s: "segundos",
|
|
308
|
+
ms: "milisegundos",
|
|
309
|
+
min: "minutos",
|
|
310
|
+
KB: "kilobytes",
|
|
311
|
+
MB: "megabytes",
|
|
312
|
+
GB: "gigabytes",
|
|
313
|
+
"%": "por ciento",
|
|
314
|
+
dB: "decibeles",
|
|
315
|
+
dBFS: "decibeles",
|
|
316
|
+
},
|
|
317
|
+
unit: {
|
|
318
|
+
s: "segundo",
|
|
319
|
+
ms: "milisegundo",
|
|
320
|
+
min: "minuto",
|
|
321
|
+
KB: "kilobyte",
|
|
322
|
+
MB: "megabyte",
|
|
323
|
+
GB: "gigabyte",
|
|
324
|
+
"%": "por ciento",
|
|
325
|
+
dB: "decibel",
|
|
326
|
+
dBFS: "decibel",
|
|
327
|
+
},
|
|
328
|
+
punctuation: {
|
|
329
|
+
".": "punto",
|
|
330
|
+
",": "coma",
|
|
331
|
+
";": "punto y coma",
|
|
332
|
+
":": "dos puntos",
|
|
333
|
+
"!": "signo de exclamación",
|
|
334
|
+
"?": "signo de pregunta",
|
|
335
|
+
"~": "virgulilla",
|
|
336
|
+
"/": "barra",
|
|
337
|
+
"-": "guion",
|
|
338
|
+
_: "guion bajo",
|
|
339
|
+
"*": "asterisco",
|
|
340
|
+
"#": "numeral",
|
|
341
|
+
"|": "barra vertical",
|
|
342
|
+
},
|
|
343
|
+
symbols: [
|
|
344
|
+
[/[→⇒➜]/, "a"],
|
|
345
|
+
[/←/, "desde"],
|
|
346
|
+
[/≈/, "aproximadamente"],
|
|
347
|
+
[/≠/, "distinto de"],
|
|
348
|
+
[/≥/, "mayor o igual a"],
|
|
349
|
+
[/≤/, "menor o igual a"],
|
|
350
|
+
[/±/, "más o menos"],
|
|
351
|
+
[/&+/, "y"],
|
|
352
|
+
],
|
|
353
|
+
thousands: true,
|
|
354
|
+
commaThousands: false,
|
|
355
|
+
comma: "coma",
|
|
356
|
+
minus: "menos",
|
|
357
|
+
cardinal: spanishCardinal,
|
|
358
|
+
agreement: { feminine: FEMININE, keepsUno: KEEPS_UNO },
|
|
359
|
+
oClock: "en punto",
|
|
360
|
+
months: "enero febrero marzo abril mayo junio julio agosto septiembre octubre noviembre diciembre".split(" "),
|
|
361
|
+
date: (day, month, year) => `${day} de ${month} de ${year}`,
|
|
362
|
+
any: "cualquier",
|
|
363
|
+
everythingIn: "todo lo de",
|
|
364
|
+
something: "algo",
|
|
365
|
+
tag: (name) => `la etiqueta ${name}`,
|
|
366
|
+
};
|
|
367
|
+
const ENGLISH = {
|
|
368
|
+
codeBlock: "Code block.",
|
|
369
|
+
reply: "Reply",
|
|
370
|
+
file: "File",
|
|
371
|
+
contracts: false,
|
|
372
|
+
command: "the command",
|
|
373
|
+
folder: "the folder",
|
|
374
|
+
branch: "the branch",
|
|
375
|
+
aCommit: "a commit",
|
|
376
|
+
in: "in",
|
|
377
|
+
line: "line",
|
|
378
|
+
dot: "dot",
|
|
379
|
+
point: "point",
|
|
380
|
+
or: "or",
|
|
381
|
+
number: "number",
|
|
382
|
+
plus: "plus",
|
|
383
|
+
orLater: "or later",
|
|
384
|
+
orMore: "or more",
|
|
385
|
+
approximately: "approximately",
|
|
386
|
+
times: "times",
|
|
387
|
+
units: {
|
|
388
|
+
s: "seconds",
|
|
389
|
+
ms: "milliseconds",
|
|
390
|
+
min: "minutes",
|
|
391
|
+
KB: "kilobytes",
|
|
392
|
+
MB: "megabytes",
|
|
393
|
+
GB: "gigabytes",
|
|
394
|
+
"%": "percent",
|
|
395
|
+
dB: "decibels",
|
|
396
|
+
dBFS: "decibels",
|
|
397
|
+
},
|
|
398
|
+
unit: {
|
|
399
|
+
s: "second",
|
|
400
|
+
ms: "millisecond",
|
|
401
|
+
min: "minute",
|
|
402
|
+
KB: "kilobyte",
|
|
403
|
+
MB: "megabyte",
|
|
404
|
+
GB: "gigabyte",
|
|
405
|
+
"%": "percent",
|
|
406
|
+
dB: "decibel",
|
|
407
|
+
dBFS: "decibel",
|
|
408
|
+
},
|
|
409
|
+
punctuation: {
|
|
410
|
+
".": "period",
|
|
411
|
+
",": "comma",
|
|
412
|
+
";": "semicolon",
|
|
413
|
+
":": "colon",
|
|
414
|
+
"!": "exclamation mark",
|
|
415
|
+
"?": "question mark",
|
|
416
|
+
"~": "tilde",
|
|
417
|
+
"/": "slash",
|
|
418
|
+
"-": "hyphen",
|
|
419
|
+
_: "underscore",
|
|
420
|
+
"*": "asterisk",
|
|
421
|
+
"#": "hash",
|
|
422
|
+
"|": "pipe",
|
|
423
|
+
},
|
|
424
|
+
symbols: [
|
|
425
|
+
[/[→⇒➜]/, "to"],
|
|
426
|
+
[/←/, "from"],
|
|
427
|
+
[/≈/, "approximately"],
|
|
428
|
+
[/≠/, "not equal to"],
|
|
429
|
+
[/≥/, "greater than or equal to"],
|
|
430
|
+
[/≤/, "less than or equal to"],
|
|
431
|
+
[/±/, "plus or minus"],
|
|
432
|
+
[/&+/, "and"],
|
|
433
|
+
],
|
|
434
|
+
thousands: false,
|
|
435
|
+
commaThousands: true,
|
|
436
|
+
comma: "comma",
|
|
437
|
+
minus: "minus",
|
|
438
|
+
cardinal: englishCardinal,
|
|
439
|
+
oClock: "o'clock",
|
|
440
|
+
months: "January February March April May June July August September October November December".split(" "),
|
|
441
|
+
date: (day, month, year) => `${month} ${day}, ${year}`,
|
|
442
|
+
any: "any",
|
|
443
|
+
everythingIn: "everything in",
|
|
444
|
+
something: "something",
|
|
445
|
+
tag: (name) => `the ${name} tag`,
|
|
446
|
+
};
|
|
447
|
+
const PHRASEBOOKS = { es: SPANISH, en: ENGLISH };
|
|
448
|
+
words = SPANISH;
|
|
449
|
+
const TABLE_SEPARATOR = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
|
|
450
|
+
const WORD = String.raw `\p{L}\p{N}_`;
|
|
451
|
+
/** A line wrapped whole in one emphasis (`**Qué cambió**`, `*Nota*`, `__X__`), read like a heading. */
|
|
452
|
+
const EMPHASIS_LINE = /^(?:\*\*(?=\S)(?:(?!\*\*).)+(?<=\S)\*\*|__(?=\S)(?:(?!__).)+(?<=\S)__|\*(?=\S)[^*]+(?<=\S)\*|_(?=\S)[^_]+(?<=\S)_)$/;
|
|
453
|
+
/** One line outside fences and tables, as a block; `line` is its 1-based source line. */
|
|
454
|
+
function lineBlock(raw, line) {
|
|
455
|
+
let text = raw.trim();
|
|
456
|
+
while (/^>\s?/.test(text))
|
|
457
|
+
text = text.replace(/^>\s?/, "").trim();
|
|
458
|
+
if (text === "" || /^([-*_])(\s*\1){2,}$/.test(text) || /^\[[^\]]+\]:\s*\S+/.test(text))
|
|
459
|
+
return { role: "break", line };
|
|
460
|
+
const heading = /^#{1,6}\s+(.*?)(\s+#+)?$/.exec(text);
|
|
461
|
+
if (heading)
|
|
462
|
+
return { role: "heading", source: heading[1], line };
|
|
463
|
+
if (EMPHASIS_LINE.test(text))
|
|
464
|
+
return { role: "heading", source: text, line };
|
|
465
|
+
const bullet = /^[-*+]\s+(?:\[[ xX]\]\s+)?(.*)$/.exec(text);
|
|
466
|
+
if (bullet)
|
|
467
|
+
return { role: "item", source: bullet[1], line };
|
|
468
|
+
const numbered = /^(\d+)[.)]\s+(.*)$/.exec(text);
|
|
469
|
+
if (numbered)
|
|
470
|
+
return { role: "item", number: numbered[1], source: numbered[2], line };
|
|
471
|
+
return { role: "paragraph", source: text, line };
|
|
472
|
+
}
|
|
473
|
+
/** One block in the words of the current phrasebook, before the per-line passes. */
|
|
474
|
+
function blockText(block) {
|
|
475
|
+
switch (block.role) {
|
|
476
|
+
case "break":
|
|
477
|
+
return "";
|
|
478
|
+
case "codeBlock":
|
|
479
|
+
return words.codeBlock;
|
|
480
|
+
case "heading":
|
|
481
|
+
return closeSentence(spokenHeading(inline(block.source)));
|
|
482
|
+
case "item":
|
|
483
|
+
// "1:" rather than "1.", which playback would cut at, reading the number alone.
|
|
484
|
+
return closeSentence(block.number === undefined ? inline(block.source) : `${block.number}: ${inline(block.source)}`);
|
|
485
|
+
case "row":
|
|
486
|
+
return closeSentence(block.cells
|
|
487
|
+
.map((cell) => inline(cell))
|
|
488
|
+
.filter((cell) => cell !== "")
|
|
489
|
+
.join(", "));
|
|
490
|
+
case "paragraph":
|
|
491
|
+
return inline(block.source);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
/** Every reply here closes with the English heading "Needs your decision"; a Spanish voice would mangle it. */
|
|
495
|
+
function spokenHeading(text) {
|
|
496
|
+
return words.needsYourDecision !== undefined && /^needs your decision:?$/i.test(text) ? words.needsYourDecision : text;
|
|
497
|
+
}
|
|
498
|
+
/** A table row's cells, trimmed and still in Markdown; escaped pipes stay inside their cell. */
|
|
499
|
+
function tableCells(raw) {
|
|
500
|
+
return raw
|
|
501
|
+
.trim()
|
|
502
|
+
.replace(/^\|/, "")
|
|
503
|
+
.replace(/(?<!\\)\|$/, "")
|
|
504
|
+
.split(/(?<!\\)\|/)
|
|
505
|
+
.map((cell) => cell.trim());
|
|
506
|
+
}
|
|
507
|
+
function closeSentence(text) {
|
|
508
|
+
const bare = text.replace(KEPT_MARKS, "");
|
|
509
|
+
return bare === "" || /[.!?:;…,]$/.test(bare) ? text : `${text}.`;
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* (j1) Text whose digits stay as written (URL hosts, technical tokens no class claimed) is held between \uE00A and
|
|
513
|
+
* \uE00B from `speakable` until `numbersInWords` drops the marks.
|
|
514
|
+
*/
|
|
515
|
+
const KEPT_MARKS = /[\uE00A\uE00B]/g;
|
|
516
|
+
/** (j1) Kept text, or a run of digits, its groups joined by single dots or commas, with an optional leading minus. */
|
|
517
|
+
const DIGITS = /\uE00A[^\uE00B]*\uE00B|[-−]?\d+(?:[.,]\d+)*/gu;
|
|
518
|
+
/**
|
|
519
|
+
* (j1) The last pass of a line: every run of digits left becomes words in the current language, except in kept text.
|
|
520
|
+
* The text around it does not change, so units, numbering, IDs and the (h1) and (i4) readings keep their shape.
|
|
521
|
+
*/
|
|
522
|
+
function numbersInWords(line) {
|
|
523
|
+
return line.replace(DIGITS, (match, offset, whole) => {
|
|
524
|
+
if (match.startsWith("\uE00A")) {
|
|
525
|
+
// A later rule may have split a kept token into words (">=1 punto 2 punto 0"): only its technical parts stay.
|
|
526
|
+
const kept = match.slice(1, -1);
|
|
527
|
+
return /\s/.test(kept) ? kept.replace(/\S+/g, (part) => (UNCLASSIFIED.test(part) && !NUMERIC.test(part) ? part : numbersInWords(part))) : kept;
|
|
528
|
+
}
|
|
529
|
+
const before = whole.slice(0, offset);
|
|
530
|
+
const after = whole.slice(offset + match.length);
|
|
531
|
+
let sign = "";
|
|
532
|
+
let run = match;
|
|
533
|
+
if (/^[-−]/.test(run)) {
|
|
534
|
+
// A hyphen right after a word or a number ("2026-10-27", "a-1") is not a minus.
|
|
535
|
+
sign = /[\p{L}\p{N}_.,\-−]$/u.test(before) ? run[0] : `${words.minus} `;
|
|
536
|
+
run = run.slice(1);
|
|
537
|
+
}
|
|
538
|
+
// Digits glued to letters are spoken apart from them: "Q5" reads "Q cinco".
|
|
539
|
+
const space = (char) => (/\p{L}/u.test(char) ? " " : "");
|
|
540
|
+
// A decimal part ("2 punto 1 segundos") keeps "uno", as a decimal run does, and so does a name such as "T1".
|
|
541
|
+
const decimalPart = new RegExp(`(?:^|\\s)(?:${words.point}|${words.comma}) $`).test(before);
|
|
542
|
+
const glued = sign === "" && space(before.at(-1) ?? "") !== "";
|
|
543
|
+
const following = /^[ \t]+(\p{L}+)(?:[ \t]+(\p{L}+))?/u.exec(after);
|
|
544
|
+
const next = following?.[1];
|
|
545
|
+
// (k1) "200 mil líneas": the hundreds agree with the noun after "mil".
|
|
546
|
+
const noun = next?.toLowerCase() === "mil" ? following?.[2] : next;
|
|
547
|
+
const reading = digitRun(run, decimalPart || glued ? undefined : { next: next ?? "", noun });
|
|
548
|
+
return `${sign === "" ? space(before.at(-1) ?? "") : ""}${sign}${reading}${space(after[0] ?? "")}`;
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
/** One run of digit groups; `following` holds the words after it, which a whole number agrees with (Spanish). */
|
|
552
|
+
function digitRun(run, following) {
|
|
553
|
+
const thousands = words.thousands
|
|
554
|
+
? /^([1-9]\d{0,2}(?:\.\d{3})+)(?:,(\d+))?$/.exec(run)
|
|
555
|
+
: words.commaThousands
|
|
556
|
+
? /^([1-9]\d{0,2}(?:,\d{3})+)$/.exec(run)
|
|
557
|
+
: null;
|
|
558
|
+
if (thousands && !IP_ADDRESS.test(run)) {
|
|
559
|
+
const whole = words.cardinal(Number(thousands[1].replace(/[.,]/g, "")));
|
|
560
|
+
return thousands[2] === undefined ? agreed(whole, following) : `${whole} ${words.comma} ${digitGroup(thousands[2])}`;
|
|
561
|
+
}
|
|
562
|
+
if (/^\d+$/.test(run)) {
|
|
563
|
+
const reading = digitGroup(run);
|
|
564
|
+
return run.length > 1 && (run.startsWith("0") || run.length > 9) ? reading : agreed(reading, following);
|
|
565
|
+
}
|
|
566
|
+
return run
|
|
567
|
+
.split(/([.,])/)
|
|
568
|
+
.map((part) => (part === "." ? ` ${words.point} ` : part === "," ? ` ${words.comma} ` : digitGroup(part)))
|
|
569
|
+
.join("");
|
|
570
|
+
}
|
|
571
|
+
/** Four groups of 0-255: an IP address, read group by group even when it looks like a Spanish thousand. */
|
|
572
|
+
const IP_ADDRESS = /^(?:(?:25[0-5]|2[0-4]\d|1?\d{1,2})\.){3}(?:25[0-5]|2[0-4]\d|1?\d{1,2})$/;
|
|
573
|
+
/** A group of digits: a whole number, or digit by digit when it is longer than 9 digits or starts with 0. */
|
|
574
|
+
function digitGroup(digits) {
|
|
575
|
+
if (digits.length > 9 || (digits.length > 1 && digits.startsWith("0")))
|
|
576
|
+
return [...digits].map((digit) => words.cardinal(Number(digit))).join(" ");
|
|
577
|
+
return words.cardinal(Number(digits));
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* "uno" becomes "un" before a word, "una" before a listed feminine noun; it stays before a function word. (k1) Before
|
|
581
|
+
* a listed feminine noun, right after the number or after "mil", the hundreds below the millions are feminine too.
|
|
582
|
+
*/
|
|
583
|
+
function agreed(reading, following) {
|
|
584
|
+
const agreement = words.agreement;
|
|
585
|
+
if (!agreement || following === undefined || following.next === "")
|
|
586
|
+
return reading;
|
|
587
|
+
const feminine = following.noun !== undefined && agreement.feminine.has(following.noun.toLowerCase());
|
|
588
|
+
const agreeing = feminine ? feminineHundreds(reading) : reading;
|
|
589
|
+
if (!/uno$/.test(agreeing))
|
|
590
|
+
return agreeing;
|
|
591
|
+
const word = following.next.toLowerCase();
|
|
592
|
+
if (agreement.feminine.has(word))
|
|
593
|
+
return agreeing.replace(/uno$/, "una");
|
|
594
|
+
return agreement.keepsUno.has(word) ? agreeing : apocope(agreeing);
|
|
595
|
+
}
|
|
596
|
+
/** (k1) "doscientos mil" → "doscientas mil"; "millón" and "millones" are masculine, so hundreds before them stay. */
|
|
597
|
+
function feminineHundreds(reading) {
|
|
598
|
+
const parts = reading.split(/(?<=millón |millones )/);
|
|
599
|
+
const last = parts.pop() ?? "";
|
|
600
|
+
return `${parts.join("")}${last.replace(/ientos(?![\p{L}])/gu, "ientas")}`;
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Inline syntax: code spans are spoken verbatim (minus backticks), everything else is unwrapped.
|
|
604
|
+
* Code spans and escapes are parked behind private-use markers so emphasis around them still pairs up
|
|
605
|
+
* and their characters never count as Markdown.
|
|
606
|
+
*/
|
|
607
|
+
function inline(text) {
|
|
608
|
+
const spans = [];
|
|
609
|
+
const parked = text
|
|
610
|
+
.replace(/(`+)(.+?)(?<!`)\1(?!`)/g, (m, _ticks, code, offset) => `\uE002${spans.push(codeSpan(code, text.slice(0, offset), text.slice(offset + m.length))) - 1}\uE003`)
|
|
611
|
+
.replace(/\\([\\`*_{}[\]()#+\-.!|~<>])/g, (_m, ch) => `\uE000${ch.codePointAt(0)}\uE001`);
|
|
612
|
+
return prose(parked)
|
|
613
|
+
.replace(/\uE000(\d+)\uE001/g, (_m, code) => String.fromCodePoint(Number(code)))
|
|
614
|
+
.replace(/\uE002(\d+)\uE003/g, (_m, index) => spans[Number(index)])
|
|
615
|
+
.replace(/[ \t]*\uE008/g, "")
|
|
616
|
+
// (k5) The pauses around `<< text >>`, now that code spans are back in the line.
|
|
617
|
+
.replace(QUOTE_OPENING, (_m, offset, whole) => {
|
|
618
|
+
const before = whole.slice(0, offset).replace(KEPT_MARKS, "");
|
|
619
|
+
if (before === "" || /[([{"'“«¿¡]$/u.test(before))
|
|
620
|
+
return "";
|
|
621
|
+
return /[\p{L}\p{N}]$/u.test(before) ? ", " : " ";
|
|
622
|
+
})
|
|
623
|
+
.replace(QUOTE_CLOSING, (match, offset, whole) => {
|
|
624
|
+
const after = whole.slice(offset + match.length).replace(KEPT_MARKS, "");
|
|
625
|
+
if (after === "" || /^[)\]}.,;:!?…"'”»]/u.test(after))
|
|
626
|
+
return "";
|
|
627
|
+
return /[.,;:!?…]$/u.test(whole.slice(0, offset)) ? " " : ", ";
|
|
628
|
+
})
|
|
629
|
+
// (j1) A host keeps its digits: its marks become the kept-text marks `numbersInWords` drops.
|
|
630
|
+
.replace(/\uE006/g, "\uE00A")
|
|
631
|
+
.replace(/\uE007/g, "\uE00B");
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* `before` and `after` are the text around the span, so a branch or hash in it can tell what word precedes it,
|
|
635
|
+
* and in English what noun follows it ("the `/read` command").
|
|
636
|
+
*/
|
|
637
|
+
function codeSpan(code, before, after) {
|
|
638
|
+
// A code span holding one mark is spoken by name; a bare "." would also end a sentence in playback.
|
|
639
|
+
return Object.hasOwn(words.punctuation, code.trim()) ? words.punctuation[code.trim()] : speakable(code.trim(), before, after);
|
|
640
|
+
}
|
|
641
|
+
/** IDs, symbols, emoji and technical tokens a voice stumbles on, made speakable (prose and code spans alike). */
|
|
642
|
+
function speakable(text, before = "", after = "") {
|
|
643
|
+
const urls = [];
|
|
644
|
+
let out = text.replace(/\S*:\/\/\S*/g, (url) => `\uE004${urls.push(url) - 1}\uE005`);
|
|
645
|
+
out = tags(angleQuotes(out), before, after);
|
|
646
|
+
out = identifierSpaces(out.replace(/\S+/g, (token, offset, whole) => tokenReading(token, previousWord(before + whole.slice(0, offset)), nextWord(whole.slice(offset + token.length) + after))));
|
|
647
|
+
out = out
|
|
648
|
+
// "aproximadamente" has no gender, unlike "unos" ("las unos 400 líneas").
|
|
649
|
+
.replace(/(?<![\p{L}\p{N}])~(?=\d)/gu, `${words.approximately} `)
|
|
650
|
+
.replace(UNIT, (_m, number, unit) => `${number} ${(number === "1" ? words.unit : words.units)[unit]}`)
|
|
651
|
+
// After the units, so "2.1 s" is "2 punto 1 segundos" and not "2 punto 1 segundo".
|
|
652
|
+
.replace(DOTTED_NUMBER, dottedNumber);
|
|
653
|
+
out = out.replace(/(?<![\p{L}\p{N}.])P(\d+)\.R(\d+)(?:\.Q(\d+))?(?![\p{L}\p{N}]|\.[\p{L}\p{N}])/gu, (_m, p, r, q) => `P ${p}, R ${r}${q ? `, Q ${q}` : ""}`);
|
|
654
|
+
out = out.replace(/(\d)[ \t]*×[ \t]*(?=\d)/g, `$1 ${words.times} `);
|
|
655
|
+
for (const [symbol, word] of words.symbols)
|
|
656
|
+
out = spokenAs(out, symbol, word);
|
|
657
|
+
return spokenAs(out, EMOJI, "")
|
|
658
|
+
.replace(/\uE004(\d+)\uE005/g, (_m, index) => `\uE00A${identifierSpaces(urls[Number(index)])}\uE00B`)
|
|
659
|
+
.replace(/\uE009/g, ".");
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* (h1) Digit groups joined by single dots, standing alone: not inside a word, a version tag (`v2.0.1`,
|
|
663
|
+
* `x@2.0.1`), a file name (`2.0.1.tgz`), a host (marked by `prose`) or an address after `tcp:`. A dot between
|
|
664
|
+
* digits in a technical token's own reading is parked as \uE009, so paths and file names keep theirs.
|
|
665
|
+
*/
|
|
666
|
+
const DOTTED_NUMBER = /\uE006[^\uE007]*\uE007|(?<![\p{L}\p{N}_.@/:\\\uE009])(?<![\p{L}\p{N}_]-)\d+(?:\.\d+)+(?![\p{L}\p{N}_@/\\\uE009]|\.[\p{L}\p{N}])/gu;
|
|
667
|
+
/** Spanish thousands: "2.750", "1.500.000". */
|
|
668
|
+
const THOUSANDS = /^[1-9]\d{0,2}(?:\.\d{3})+$/;
|
|
669
|
+
/** "1.1" reads as "1 punto 1"; Spanish thousands, IP addresses and hosts stay as they are. */
|
|
670
|
+
function dottedNumber(match) {
|
|
671
|
+
if (match.startsWith("\uE006") || (words.thousands && THOUSANDS.test(match)))
|
|
672
|
+
return match;
|
|
673
|
+
const groups = match.split(".");
|
|
674
|
+
if (groups.length === 4 && groups.every((group) => group.length <= 3 && Number(group) <= 255))
|
|
675
|
+
return match;
|
|
676
|
+
return groups.join(` ${words.point} `);
|
|
677
|
+
}
|
|
678
|
+
/** A unit right after a number that letters or a version dot do not precede: "2,5 s", "80%", "-16 dB". */
|
|
679
|
+
const UNIT = /(?<![\p{L}\p{N}_.,])(\d+(?:[.,]\d+)*)[ \t]?(dBFS|dB|ms|min|s|KB|MB|GB|%)(?![\p{L}\p{N}])/gu;
|
|
680
|
+
const EMOJI = /(?:\p{Extended_Pictographic}|\p{Regional_Indicator}|[\u{1F3FB}-\u{1F3FF}\uFE0F\u200D\u20E3])+/u;
|
|
681
|
+
/** Replaces `symbol` with `word`, spaced from neighbouring words but not from punctuation. */
|
|
682
|
+
function spokenAs(text, symbol, word) {
|
|
683
|
+
const pattern = new RegExp(`[ \\t]*(?:${symbol.source})[ \\t]*`, "gu");
|
|
684
|
+
return text.replace(pattern, (match, offset, whole) => {
|
|
685
|
+
const before = offset > 0 && !/[([{\s]/u.test(whole[offset - 1]);
|
|
686
|
+
const next = whole[offset + match.length];
|
|
687
|
+
const after = next !== undefined && !/[)\]}.,;:!?\s]/u.test(next);
|
|
688
|
+
if (word === "")
|
|
689
|
+
return before && after ? " " : "";
|
|
690
|
+
return `${before ? " " : ""}${word}${after ? " " : ""}`;
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* One technical token, read by its class in the order of S2 (e2)-(e8); URLs never get here (e1).
|
|
695
|
+
* Leading and trailing punctuation stays outside, so "`README.md`." reads "README punto md.".
|
|
696
|
+
* A dropped token leaves a \uE008 marker that takes the space before it along when removed.
|
|
697
|
+
*/
|
|
698
|
+
function tokenReading(token, previous, next) {
|
|
699
|
+
const [, lead, core, trail] = /^([("'“«[]*)(.*?)([)"'”»\].,;:!?]*)$/u.exec(token) ?? [];
|
|
700
|
+
if (!core || /[\uE000-\uE008]/u.test(token) || !/[\p{L}\p{N}]/u.test(core))
|
|
701
|
+
return token;
|
|
702
|
+
// English puts the noun after the token ("the `/read` command"); punctuation in between ends the phrase.
|
|
703
|
+
const noun = words === ENGLISH && trail === "" ? next.toLowerCase() : "";
|
|
704
|
+
const reading = classified(core, previous.toLowerCase(), noun);
|
|
705
|
+
if (reading === undefined) {
|
|
706
|
+
if (!UNCLASSIFIED.test(core) || NUMERIC.test(core))
|
|
707
|
+
return token;
|
|
708
|
+
if (diagnosis)
|
|
709
|
+
diagnosis.diagnostics.push({ line: diagnosis.line, token: core });
|
|
710
|
+
// (j1) Read as written, digits included.
|
|
711
|
+
return `${lead}\uE00A${core}\uE00B${trail}`;
|
|
712
|
+
}
|
|
713
|
+
if (reading === "")
|
|
714
|
+
return `\uE008${trail}`;
|
|
715
|
+
// A dot between digits in a reading ("a punto ts, en 1.2") is the token's own; (h1) leaves it.
|
|
716
|
+
return `${lead}${reading.replace(/(?<=\d)\.(?=\d)/g, "\uE009")}${trail}`;
|
|
717
|
+
}
|
|
718
|
+
/** (S12) Characters a voice reads oddly in a token no class claimed; numbers such as `1/2` or `10:30` are fine. */
|
|
719
|
+
const UNCLASSIFIED = /[/\\=<>|*{}$^@#+]|\.\./;
|
|
720
|
+
const NUMERIC = /^~?[\d.,:/]+$/;
|
|
721
|
+
/** `noun` is the English noun right after the token, which the reading then leaves out ("the read command"). */
|
|
722
|
+
function classified(core, previous, noun) {
|
|
723
|
+
if (previous === "rama" || previous === "branch")
|
|
724
|
+
return nameWords(core);
|
|
725
|
+
const moment = clockTime(core) ?? calendarDate(core);
|
|
726
|
+
if (moment !== undefined)
|
|
727
|
+
return moment;
|
|
728
|
+
const line = /^(.+):(\d+)$/.exec(core);
|
|
729
|
+
const file = line && (pathReading(line[1], previous) ?? fileName(line[1]));
|
|
730
|
+
if (line && file)
|
|
731
|
+
return `${file}, ${words.line} ${line[2]}`;
|
|
732
|
+
if (BRANCH.test(core) && !/\.\p{L}+$/u.test(core))
|
|
733
|
+
return noun === "branch" ? nameWords(core) : `${words.branch} ${nameWords(core)}`;
|
|
734
|
+
if (noun === "folder") {
|
|
735
|
+
const folder = folderName(core);
|
|
736
|
+
if (folder !== undefined)
|
|
737
|
+
return folder;
|
|
738
|
+
}
|
|
739
|
+
return (issueNumber(core) ??
|
|
740
|
+
keyCombination(core) ??
|
|
741
|
+
minimumVersion(core) ??
|
|
742
|
+
alternatives(core) ??
|
|
743
|
+
pathReading(core, previous) ??
|
|
744
|
+
command(core, previous, noun) ??
|
|
745
|
+
fileName(core) ??
|
|
746
|
+
commitHash(core, previous) ??
|
|
747
|
+
emphasis(core) ??
|
|
748
|
+
glob(core) ??
|
|
749
|
+
slashWords(core));
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* (k2) A standalone `H:MM` or `HH:MM`, optionally `:SS`, reads like a digital clock, already in words: `21:02`
|
|
753
|
+
* "veintiuno cero dos", `07:30` "siete treinta", `07:00` "siete en punto". With seconds, minutes 00 read "cero cero".
|
|
754
|
+
*/
|
|
755
|
+
function clockTime(core) {
|
|
756
|
+
const time = /^([01]?\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/.exec(core);
|
|
757
|
+
if (!time)
|
|
758
|
+
return undefined;
|
|
759
|
+
const [, hour, minutes, seconds] = time;
|
|
760
|
+
const said = words.cardinal(Number(hour));
|
|
761
|
+
if (seconds === undefined && minutes === "00")
|
|
762
|
+
return `${said} ${words.oClock}`;
|
|
763
|
+
return [said, digitGroup(minutes), ...(seconds === undefined ? [] : [digitGroup(seconds)])].join(" ");
|
|
764
|
+
}
|
|
765
|
+
/** (k3) `2026-10-27` and day-first `27/10/2026`, valid only: "veintisiete de octubre de dos mil veintiséis". */
|
|
766
|
+
function calendarDate(core) {
|
|
767
|
+
const iso = /^(\d{4})-(\d{2})-(\d{2})$/.exec(core);
|
|
768
|
+
const dayFirst = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(core);
|
|
769
|
+
const [year, month, day] = iso ? [iso[1], iso[2], iso[3]] : dayFirst ? [dayFirst[3], dayFirst[2], dayFirst[1]] : [];
|
|
770
|
+
if (year === undefined || month === undefined || day === undefined)
|
|
771
|
+
return undefined;
|
|
772
|
+
const [y, m, d] = [Number(year), Number(month), Number(day)];
|
|
773
|
+
// Day 0 of the next month is the last day of this one.
|
|
774
|
+
if (m < 1 || m > 12 || d < 1 || d > new Date(Date.UTC(y, m, 0)).getUTCDate())
|
|
775
|
+
return undefined;
|
|
776
|
+
return words.date(words.cardinal(d), words.months[m - 1], words.cardinal(y));
|
|
777
|
+
}
|
|
778
|
+
/** (k5) Where the pauses around `<< text >>` go, placed by `inline` once code spans are back in the line. */
|
|
779
|
+
const QUOTE_OPEN = String.fromCharCode(0xe00c);
|
|
780
|
+
const QUOTE_CLOSE = String.fromCharCode(0xe00d);
|
|
781
|
+
const QUOTE_OPENING = new RegExp(`[ \\t]*${QUOTE_OPEN}[ \\t]*`, "g");
|
|
782
|
+
const QUOTE_CLOSING = new RegExp(`[ \\t]*${QUOTE_CLOSE}[ \\t]*`, "g");
|
|
783
|
+
/**
|
|
784
|
+
* (k5) `<< text >>`, a format models use, reads like quotes: the marks are silent and the text has a short pause
|
|
785
|
+
* around it. It needs a letter inside and a `>>` on the same line, so a shift such as `a << b` or `x << 2 >> 1`
|
|
786
|
+
* keeps its reading and swallows nothing.
|
|
787
|
+
*/
|
|
788
|
+
function angleQuotes(text) {
|
|
789
|
+
return text.replace(/(?<![^\s([{"'“«])<<(?!<)[ \t]*([^<>\n]*?\p{L}[^<>\n]*?)[ \t]*>>(?![>\p{L}\p{N}_])/gu, (_m, inside) => ` ${QUOTE_OPEN} ${inside} ${QUOTE_CLOSE} `);
|
|
790
|
+
}
|
|
791
|
+
/** (k5) A tag name: letters, digits and `-`, starting with a letter. */
|
|
792
|
+
const TAG = /<(\/?)(\p{L}[\p{L}\p{N}-]*)(\/?)>/gu;
|
|
793
|
+
/**
|
|
794
|
+
* A tag glued to a letter, digit or `_` (`a<b>c`, `List<String>`) is not one: markup or a generic type. So is one
|
|
795
|
+
* glued to a code span, URL or escape parked behind a private-use mark (`` `x`<br>`y` ``).
|
|
796
|
+
*/
|
|
797
|
+
const TAG_GLUE = /[\p{L}\p{N}_\uE000-\uE00F]/u;
|
|
798
|
+
/**
|
|
799
|
+
* (k5) Tags, HTML or not. A pair `<name>…</name>` of the same text reads "name: " and then the content, the closing
|
|
800
|
+
* tag silent; the opening tag may be glued to the content, the closing one to the content before it. A lone
|
|
801
|
+
* `<name>` reads its name (`<archivo>` "archivo"); a lone `</name>` or `<name/>` reads "la etiqueta name" ("the
|
|
802
|
+
* name tag"), only the name right after "etiqueta"/"tag". Lone tags glued to other text (`a<b>c`) are not tags.
|
|
803
|
+
*/
|
|
804
|
+
function tags(text, before, after) {
|
|
805
|
+
return text.replace(TAG, (match, closing, rawName, selfClosing, offset, whole) => {
|
|
806
|
+
if (closing !== "" && selfClosing !== "")
|
|
807
|
+
return match;
|
|
808
|
+
const prior = offset === 0 ? "" : whole[offset - 1];
|
|
809
|
+
const next = whole[offset + match.length] ?? "";
|
|
810
|
+
const apartBefore = prior === "" || !TAG_GLUE.test(prior);
|
|
811
|
+
const apartAfter = next === "" || !TAG_GLUE.test(next);
|
|
812
|
+
const name = rawName.replace(/-+/g, " ");
|
|
813
|
+
let paired = false;
|
|
814
|
+
// An opening tag may start a pair only where a word could start, a closing one end it only where a word could end.
|
|
815
|
+
if (selfClosing === "" && tagging && (closing === "" ? apartBefore : apartAfter)) {
|
|
816
|
+
const index = tagging.next++;
|
|
817
|
+
tagging.seen.push({ name: rawName, closing: closing !== "" });
|
|
818
|
+
paired = tagging.paired?.[index] ?? false;
|
|
819
|
+
}
|
|
820
|
+
if (paired)
|
|
821
|
+
return closing === "" ? `${name}:${next === "" || /\s/.test(next) ? "" : " "}` : "";
|
|
822
|
+
// Alone, a tag right after another tag's `>` (`height="450"></iframe>`) is still markup, and one between `/`
|
|
823
|
+
// (`/catalog/<id>`) is part of a path, whose reading gives the name.
|
|
824
|
+
if (!apartBefore || !apartAfter || prior === ">" || next === "<" || prior === "/" || next === "/")
|
|
825
|
+
return match;
|
|
826
|
+
if (closing === "" && selfClosing === "")
|
|
827
|
+
return name;
|
|
828
|
+
const said = previousWord(before + whole.slice(0, offset)).toLowerCase();
|
|
829
|
+
const noun = words === ENGLISH && /^\s/.test(next) ? nextWord(whole.slice(offset + match.length) + after).toLowerCase() : "";
|
|
830
|
+
return said === "etiqueta" || said === "tag" || noun === "tag" ? name : words.tag(name);
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
/** (k4, L128) Markdown emphasis written as code, `**negrita**` or `*nota*`, reads only its letters: "negrita". */
|
|
834
|
+
function emphasis(core) {
|
|
835
|
+
return /^(\*{1,2})(\p{L}+)\1$/u.exec(core)?.[2];
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* (k4) A glob with a letter: a leading `*` reads "cualquier" (`*.hs.lan` "cualquier hs punto lan"), a trailing `/*`
|
|
839
|
+
* "todo lo de" plus the folder (`bin/*` "todo lo de bin"), any other `*` "algo" (`lab-*` "lab algo").
|
|
840
|
+
*/
|
|
841
|
+
function glob(core) {
|
|
842
|
+
if (!core.includes("*") || !/^[\p{L}\p{N}._~/*-]+$/u.test(core) || !/\p{L}/u.test(core))
|
|
843
|
+
return undefined;
|
|
844
|
+
const folder = /^(.*[^/*])\/\*+$/.exec(core)?.[1];
|
|
845
|
+
if (folder !== undefined && !folder.includes("*"))
|
|
846
|
+
return `${words.everythingIn} ${pathReading(`${folder}/`, "carpeta") ?? nameWords(folder)}`;
|
|
847
|
+
if (!core.startsWith("*"))
|
|
848
|
+
return globWords(core);
|
|
849
|
+
const rest = globWords(core.replace(/^\*+/, ""));
|
|
850
|
+
return rest === "" ? undefined : `${words.any} ${rest}`;
|
|
851
|
+
}
|
|
852
|
+
/** A glob's parts as words, each `*` (or `**`) as "algo": `TEST_CKAN_*` "TEST CKAN algo". */
|
|
853
|
+
function globWords(text) {
|
|
854
|
+
return text
|
|
855
|
+
.split(/\*+/)
|
|
856
|
+
.map((part) => part
|
|
857
|
+
.replace(/^[._~/-]+|[._~/-]+$/g, "")
|
|
858
|
+
.replace(/(?<=[\p{L}\p{N}])\.(?=[\p{L}\p{N}])/gu, ` ${words.dot} `)
|
|
859
|
+
.replace(/[._~/-]+/g, " "))
|
|
860
|
+
.join(` ${words.something} `)
|
|
861
|
+
.replace(/\s+/g, " ")
|
|
862
|
+
.trim();
|
|
863
|
+
}
|
|
864
|
+
const BRANCH = /^(?:feat|fix|docs|chore|refactor|test|release|origin|upstream)\/[\p{L}\p{N}][\p{L}\p{N}._/-]*$/u;
|
|
865
|
+
const PATH = /^[\p{L}\p{N}._~/+-]+$/u;
|
|
866
|
+
/** A bare `name.<tld>` is a host, not a file. */
|
|
867
|
+
const HOST_ENDINGS = new Set(["com", "org", "net", "io", "dev", "lan", "app", "ai", "co"]);
|
|
868
|
+
/** (i2) `#43` reads as "número 43"; a heading's own `#` never gets here. */
|
|
869
|
+
function issueNumber(core) {
|
|
870
|
+
const digits = /^#(\d+)$/.exec(core)?.[1];
|
|
871
|
+
return digits === undefined ? undefined : `${words.number} ${digits}`;
|
|
872
|
+
}
|
|
873
|
+
const MODIFIER = /^(?:ctrl|control|alt|shift|cmd|command|super|meta|win|option|fn)$/i;
|
|
874
|
+
const KEY = /^(?:[\p{L}\p{N}]|enter|tab|esc|space|delete|backspace|up|down|left|right|home|end|f(?:[1-9]|1[0-2]))$/iu;
|
|
875
|
+
/** (i3) `Ctrl+Shift+P` reads as "Control más Shift más P": modifiers joined by `+` to one key. */
|
|
876
|
+
function keyCombination(core) {
|
|
877
|
+
const keys = core.split("+");
|
|
878
|
+
const key = keys.pop() ?? "";
|
|
879
|
+
if (keys.length === 0 || !keys.every((name) => MODIFIER.test(name)) || !KEY.test(key))
|
|
880
|
+
return undefined;
|
|
881
|
+
return [...keys.map((name) => (/^ctrl$/i.test(name) ? "Control" : name)), key].join(` ${words.plus} `);
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* (i4) `v2.0+` reads as "v2 punto 0 o superior". Without a `v`, a whole number (`100+`, or a Spanish thousand such
|
|
885
|
+
* as `6.000+`) is a count: "100 o más".
|
|
886
|
+
*/
|
|
887
|
+
function minimumVersion(core) {
|
|
888
|
+
const version = /^(v?)(\d+(?:\.\d+)*)\+$/.exec(core);
|
|
889
|
+
if (!version)
|
|
890
|
+
return undefined;
|
|
891
|
+
const [, v, number] = version;
|
|
892
|
+
if (v === "" && (!number.includes(".") || (words.thousands && THOUSANDS.test(number))))
|
|
893
|
+
return `${number} ${words.orMore}`;
|
|
894
|
+
return `${v}${dottedNumber(number)} ${words.orLater}`;
|
|
895
|
+
}
|
|
896
|
+
/** `feat/pending-central` reads as "feat pending central". */
|
|
897
|
+
function nameWords(core) {
|
|
898
|
+
return core.replace(/(?<=[\p{L}\p{N}])[-_/]+(?=[\p{L}\p{N}])/gu, " ");
|
|
899
|
+
}
|
|
900
|
+
/** `light/dark` reads as "light o dark"; short pairs such as `y/o` or `km/h` are kept. */
|
|
901
|
+
function alternatives(core) {
|
|
902
|
+
const pair = /^(\p{L}+)\/(\p{L}+)$/u.exec(core);
|
|
903
|
+
if (!pair)
|
|
904
|
+
return undefined;
|
|
905
|
+
return pair[1].length <= 3 && pair[2].length <= 3 ? core : `${pair[1]} ${words.or} ${pair[2]}`;
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* The last part plus its folder: `~/.gentle-shell/agent/AGENTS.md` reads as "AGENTS punto md, en agent"
|
|
909
|
+
* and `/tmp/x/wav/hs/` as "la carpeta hs, en wav" ("hs, en wav" right after "carpeta"). A single `/word` is
|
|
910
|
+
* left to `command`, `1/2` to the numbers. (i1) A relative `src/` is a folder too, and a last part starting with
|
|
911
|
+
* a dot (`ckan-docker/.prettierrc.json`) reads like any other; with no extension and a folder before it
|
|
912
|
+
* (`ckan-docker/.gitignore`) it is a file named without the dot: "gitignore, en ckan docker".
|
|
913
|
+
*/
|
|
914
|
+
function pathReading(core, previous) {
|
|
915
|
+
if (!PATH.test(core))
|
|
916
|
+
return undefined;
|
|
917
|
+
const root = /^(?:~|\.{1,2})?\//.exec(core)?.[0] ?? "";
|
|
918
|
+
const parts = core.slice(root.length).split("/").filter((part) => part !== "");
|
|
919
|
+
const isFolder = core.endsWith("/");
|
|
920
|
+
const bareFolder = root === "" && parts.length === 1 && isFolder && /\p{L}/u.test(parts[0]);
|
|
921
|
+
if (bareFolder)
|
|
922
|
+
return previous === "carpeta" || previous === "folder" ? partName(parts[0]) : `${words.folder} ${partName(parts[0])}`;
|
|
923
|
+
if (root === "/" ? parts.length < 2 && !isFolder : root === "" && parts.length < 2)
|
|
924
|
+
return undefined;
|
|
925
|
+
if (root === "" && !/\p{L}\/\.?[\p{L}\p{N}]|[\p{L}\p{N}]\/\.?\p{L}/u.test(core))
|
|
926
|
+
return undefined;
|
|
927
|
+
const name = partName(parts.at(-1) ?? "");
|
|
928
|
+
if (name === "")
|
|
929
|
+
return undefined;
|
|
930
|
+
const said = previous === "carpeta" || previous === "folder";
|
|
931
|
+
const last = parts.at(-1) ?? "";
|
|
932
|
+
const dotFile = !isFolder && parts.length > 1 && last.startsWith(".") ? name : undefined;
|
|
933
|
+
const reading = (!isFolder && fileReading(last)) || dotFile || (said ? name : `${words.folder} ${name}`);
|
|
934
|
+
const folder = parts.length > 1 ? partName(parts[parts.length - 2]) : "";
|
|
935
|
+
return folder === "" ? reading : `${reading}, ${words.in} ${folder}`;
|
|
936
|
+
}
|
|
937
|
+
/** A leading `.` is dropped and `-`/`_` become spaces: `.gentle-shell` reads as "gentle shell". */
|
|
938
|
+
function partName(part) {
|
|
939
|
+
return part.replace(/^\.+/, "").replace(/[-_]+/g, " ").trim();
|
|
940
|
+
}
|
|
941
|
+
/** `speech-text.ts` reads as "speech text punto ts"; a part without a letter-only extension is not a file. */
|
|
942
|
+
function fileReading(part) {
|
|
943
|
+
const file = /^(.*\p{L}.*)\.(\p{L}+)$/u.exec(part);
|
|
944
|
+
if (!file)
|
|
945
|
+
return undefined;
|
|
946
|
+
const name = partName(file[1]).replace(/(?<=[\p{L}\p{N}])\.(?=[\p{L}\p{N}])/gu, ` ${words.dot} `);
|
|
947
|
+
return name === "" ? undefined : `${name} ${words.dot} ${file[2]}`;
|
|
948
|
+
}
|
|
949
|
+
/** Top-level folders of a Unix system: `/tmp` is a place, not a command. */
|
|
950
|
+
const SYSTEM_FOLDERS = new Set(["bin", "boot", "dev", "etc", "home", "lib", "media", "mnt", "opt", "proc", "root", "run", "srv", "sys", "tmp", "usr", "var"]);
|
|
951
|
+
/** `/reload` reads as "el comando reload", or just "reload" right after "comando"; `/tmp` reads as "la carpeta tmp". */
|
|
952
|
+
function command(core, previous, noun) {
|
|
953
|
+
const name = /^\/(\p{L}[\p{L}\p{N}_:-]*)$/u.exec(core)?.[1]?.replace(/[-_:]+/g, " ");
|
|
954
|
+
if (!name)
|
|
955
|
+
return undefined;
|
|
956
|
+
if (SYSTEM_FOLDERS.has(name))
|
|
957
|
+
return previous === "carpeta" || previous === "folder" ? name : `${words.folder} ${name}`;
|
|
958
|
+
return previous === "comando" || previous === "command" || noun === "command" ? name : `${words.command} ${name}`;
|
|
959
|
+
}
|
|
960
|
+
/** "the `/tmp/a/b/` folder" and "the `src/` folder" read as "the b folder" and "the src folder"; files are not folders. */
|
|
961
|
+
function folderName(core) {
|
|
962
|
+
if (!PATH.test(core) || !core.includes("/"))
|
|
963
|
+
return undefined;
|
|
964
|
+
const last = core.split("/").filter((part) => part !== "").at(-1) ?? "";
|
|
965
|
+
if (!core.endsWith("/") && fileReading(last))
|
|
966
|
+
return undefined;
|
|
967
|
+
const name = partName(last);
|
|
968
|
+
return /\p{L}/u.test(name) ? name : undefined;
|
|
969
|
+
}
|
|
970
|
+
/** A bare `README.md`; versions, numbers, hosts, `a..b` ranges and abbreviations such as `e.g` are not file names. */
|
|
971
|
+
function fileName(core) {
|
|
972
|
+
if (!/^[\p{L}\p{N}_.-]+$/u.test(core) || /^(?:\p{L}\.)+\p{L}$/u.test(core) || core.includes(".."))
|
|
973
|
+
return undefined;
|
|
974
|
+
const ext = /\.(\p{L}+)$/u.exec(core)?.[1];
|
|
975
|
+
return ext && !HOST_ENDINGS.has(ext.toLowerCase()) ? fileReading(core) : undefined;
|
|
976
|
+
}
|
|
977
|
+
/** A hash is dropped right after "commit" and spoken as "un commit" elsewhere. */
|
|
978
|
+
function commitHash(core, previous) {
|
|
979
|
+
if (!/^(?=.*\d)(?=.*[a-f])[0-9a-f]{7,40}$/.test(core))
|
|
980
|
+
return undefined;
|
|
981
|
+
return previous === "commit" || previous === "commits" ? "" : words.aCommit;
|
|
982
|
+
}
|
|
983
|
+
/** Other paths, such as `@scope/pkg` or `/a/<id>/b`, keep (d)'s reading: their parts as words. */
|
|
984
|
+
function slashWords(core) {
|
|
985
|
+
if (!/^(?:~|\.{1,2})?\//.test(core) && !/\p{L}\/[\p{L}\p{N}]|[\p{L}\p{N}]\/\p{L}/u.test(core))
|
|
986
|
+
return undefined;
|
|
987
|
+
const parts = core.split("/").map((part) => part.replace(/^[~.]+/, "")).filter((part) => part !== "");
|
|
988
|
+
// (k5) A placeholder in a path reads by its name: `/catalog/download/<id>` "catalog download id".
|
|
989
|
+
return parts
|
|
990
|
+
.join(" ")
|
|
991
|
+
.replace(/<(\p{L}[\p{L}\p{N}-]*)>/gu, "$1")
|
|
992
|
+
.replace(/(?<=[\p{L}\p{N}])[-_]+(?=[\p{L}\p{N}])/gu, " ");
|
|
993
|
+
}
|
|
994
|
+
/** The word right before a token, across spaces, opening quotes and emphasis markers. */
|
|
995
|
+
function previousWord(text) {
|
|
996
|
+
return /(?<![\p{L}\p{N}])(\p{L}+)[ \t*_`"'“«(]*$/u.exec(text)?.[1] ?? "";
|
|
997
|
+
}
|
|
998
|
+
/** The word right after a token, across closing emphasis or quotes and spaces, but not across punctuation. */
|
|
999
|
+
function nextWord(text) {
|
|
1000
|
+
return /^[*_`"'”»]*[ \t]+[*_`"'“«]*(\p{L}+)(?![\p{L}\p{N}])/u.exec(text)?.[1] ?? "";
|
|
1001
|
+
}
|
|
1002
|
+
/** `auto_read` reads as "auto read", not "auto guion bajo read". */
|
|
1003
|
+
function identifierSpaces(text) {
|
|
1004
|
+
return text.replace(/(?<=[\p{L}\p{N}])_+(?=[\p{L}\p{N}])/gu, " ");
|
|
1005
|
+
}
|
|
1006
|
+
function prose(text) {
|
|
1007
|
+
const unwrapped = text
|
|
1008
|
+
.replace(/!?\[([^\]]*)\]\([^)\s]*(?:\s+"[^"]*")?\)/g, "$1")
|
|
1009
|
+
.replace(/\[([^\]]+)\]\[[^\]]*\]/g, "$1")
|
|
1010
|
+
// Hosts are marked so the file-name rule leaves `github.com` alone; `inline` drops the marks.
|
|
1011
|
+
.replace(/<(https?:\/\/[^>\s]+)>/g, (_m, url) => `\uE006${host(url)}\uE007`)
|
|
1012
|
+
.replace(/\bhttps?:\/\/[^\s<>()[\]*]+/g, (url) => {
|
|
1013
|
+
const trailing = /[.,;:!?]+$/.exec(url)?.[0] ?? "";
|
|
1014
|
+
return `\uE006${host(url.slice(0, url.length - trailing.length))}\uE007${trailing}`;
|
|
1015
|
+
})
|
|
1016
|
+
.replace(/\*\*(?=\S)(.+?)(?<=\S)\*\*/g, "$1")
|
|
1017
|
+
.replace(new RegExp(`(?<![${WORD}])__(?=\\S)(.+?)(?<=\\S)__(?![${WORD}])`, "gu"), "$1")
|
|
1018
|
+
.replace(/~~(?=\S)(.+?)(?<=\S)~~/g, "$1")
|
|
1019
|
+
.replace(new RegExp(`(?<![${WORD}*])\\*(?=\\S)([^*\\n]*?)(?<=\\S)\\*(?![${WORD}*])`, "gu"), "$1")
|
|
1020
|
+
.replace(new RegExp(`(?<![${WORD}])_(?=\\S)([^_\\n]*?)(?<=\\S)_(?![${WORD}])`, "gu"), "$1");
|
|
1021
|
+
return speakable(unwrapped);
|
|
1022
|
+
}
|
|
1023
|
+
function host(url) {
|
|
1024
|
+
return url
|
|
1025
|
+
.replace(/^https?:\/\//, "")
|
|
1026
|
+
.split(/[/?#]/)[0]
|
|
1027
|
+
.replace(/^www\./, "");
|
|
1028
|
+
}
|