@uyghurcommunity/spell 0.0.0-stage → 0.1.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/suggest.js ADDED
@@ -0,0 +1,278 @@
1
+ /**
2
+ * The correction engine.
3
+ *
4
+ * Produces suggestions; it never rewrites text. Every issue it reports carries
5
+ * the exact span it refers to and a ranked list of candidates, and the caller
6
+ * decides what, if anything, to apply.
7
+ *
8
+ * That restraint is deliberate and load-bearing. The bundled lexicon is a small
9
+ * unreviewed seed (see `data/roots.js`), so a word being absent from it is weak
10
+ * evidence of anything. An engine that silently "fixed" text on that basis
11
+ * would inject errors into work the user believes it improved — strictly worse
12
+ * than doing nothing.
13
+ */
14
+
15
+ import { describeNormalization, findAmbiguousCharacters, normalize } from './normalize.js';
16
+ import { getLexicon, lookalikeSwaps } from './lexicon.js';
17
+ import { explainDifference } from './confusions.js';
18
+ import { editDistance, similarity } from './distance.js';
19
+ import { reattach, segment } from './morphology.js';
20
+ import { applyEdits, isArabicScript, isNumeric, tokenize } from './tokenize.js';
21
+
22
+ /**
23
+ * Minimum similarity for a candidate to be offered at all.
24
+ *
25
+ * Below roughly this, the "correction" is usually a different word that happens
26
+ * to be nearby in edit space, and offering it does more harm than good.
27
+ */
28
+ const MIN_SIMILARITY = 0.6;
29
+
30
+ /** Letters Tesseract reads for a word-initial ئ, and what that slip costs. */
31
+ const INITIAL_HAMZA_MISREADS = new Set(['گ', 'ك', 'ق']);
32
+ const INITIAL_HAMZA_COST = 0.3;
33
+
34
+ /**
35
+ * Ranking handicap for forms found only by swapping a letter and recognised
36
+ * only through their suffixes: a fallback for when no attested word is close.
37
+ */
38
+ const SWAP_PENALTY = 0.05;
39
+
40
+ /**
41
+ * Ranking bonus for words in the user's personal dictionary. Small enough that
42
+ * a clearly closer seed word still wins; large enough to break the frequent
43
+ * near-ties between single-substitution candidates.
44
+ */
45
+ const PREFERRED_BONUS = 0.05;
46
+
47
+ /**
48
+ * Ranking bonus for common words, scaled by `Lexicon#commonness` (0..1). Kept
49
+ * below PREFERRED_BONUS so a word the user confirmed still beats a merely
50
+ * frequent one, and well below the similarity gap of one extra edit.
51
+ */
52
+ const FREQUENCY_BONUS = 0.03;
53
+
54
+ /** Words shorter than this produce too many equally-plausible neighbours. */
55
+ const MIN_WORD_LENGTH = 3;
56
+
57
+ /**
58
+ * @typedef {object} Suggestion
59
+ * @property {string} text the proposed replacement, in the original inflected form
60
+ * @property {number} similarity 0..1
61
+ * @property {string} [reason] why the two were likely confused, when it is a single substitution
62
+ *
63
+ * @typedef {object} Issue
64
+ * @property {'unknown-word'|'ambiguous-character'} type
65
+ * @property {number} start
66
+ * @property {number} end
67
+ * @property {string} original
68
+ * @property {Suggestion[]} suggestions
69
+ * @property {string} [note]
70
+ *
71
+ * @typedef {object} Analysis
72
+ * @property {string} text the text that was analysed
73
+ * @property {string} normalized the text with safe normalisations applied
74
+ * @property {Array<object>} normalizations what `normalize` would change
75
+ * @property {Issue[]} issues
76
+ * @property {{words: number, known: number, unknown: number}} stats
77
+ */
78
+
79
+ /**
80
+ * Analyse text and report what could be improved.
81
+ *
82
+ * @param {string} text
83
+ * @param {{lexicon?: import('./lexicon').Lexicon, maxIssues?: number}} [options]
84
+ * @returns {Analysis}
85
+ */
86
+ export function analyze(text, { lexicon = getLexicon(), maxIssues = 200 } = {}) {
87
+ const empty = {
88
+ text: text ?? '',
89
+ normalized: '',
90
+ normalizations: [],
91
+ issues: [],
92
+ stats: { words: 0, known: 0, unknown: 0 },
93
+ };
94
+ if (typeof text !== 'string' || !text.trim()) return empty;
95
+
96
+ const normalizations = describeNormalization(text);
97
+ const normalized = normalize(text);
98
+
99
+ // Analysis runs on the ORIGINAL text so that reported offsets address what
100
+ // the user is actually looking at. Normalisation is offered separately.
101
+ const issues = [];
102
+ const stats = { words: 0, known: 0, unknown: 0 };
103
+
104
+ for (const { char, index, candidates, note } of findAmbiguousCharacters(text)) {
105
+ issues.push({
106
+ type: 'ambiguous-character',
107
+ start: index,
108
+ end: index + char.length,
109
+ original: char,
110
+ note,
111
+ suggestions: candidates.map((candidate) => ({ text: candidate, similarity: 1 })),
112
+ });
113
+ }
114
+
115
+ for (const token of tokenize(text)) {
116
+ if (!token.isWord) continue;
117
+ if (!isArabicScript(token.text) || isNumeric(token.text)) continue;
118
+
119
+ stats.words++;
120
+
121
+ // Compare against the normalised form: the lexicon holds standard spellings,
122
+ // and an encoding variant is not a spelling error.
123
+ const candidate = normalize(token.text, { collapseWhitespace: false });
124
+ const { known } = lexicon.analyze(candidate);
125
+
126
+ if (known) {
127
+ stats.known++;
128
+ continue;
129
+ }
130
+
131
+ stats.unknown++;
132
+ if (candidate.length < MIN_WORD_LENGTH) continue;
133
+ if (issues.length >= maxIssues) continue;
134
+
135
+ const suggestions = suggestFor(candidate, lexicon);
136
+ // An unknown word with no near neighbour is far more likely to be a word
137
+ // missing from the seed lexicon than a misspelling, so it is not reported.
138
+ if (!suggestions.length) continue;
139
+
140
+ issues.push({
141
+ type: 'unknown-word',
142
+ start: token.start,
143
+ end: token.end,
144
+ original: token.text,
145
+ suggestions,
146
+ });
147
+ }
148
+
149
+ issues.sort((a, b) => a.start - b.start);
150
+
151
+ return { text, normalized, normalizations, issues, stats };
152
+ }
153
+
154
+ /**
155
+ * Ranked replacements for one unknown word.
156
+ *
157
+ * Tries the whole word first, then each stem the morphology module can reach —
158
+ * a correction found at the stem is reattached to the original suffixes so the
159
+ * word keeps its grammar.
160
+ *
161
+ * @param {string} word
162
+ * @param {import('./lexicon').Lexicon} lexicon
163
+ * @returns {Suggestion[]}
164
+ */
165
+ export function suggestFor(word, lexicon = getLexicon()) {
166
+ /** @type {Map<string, Suggestion>} */
167
+ const found = new Map();
168
+
169
+ const consider = (text, similarityScore, original) => {
170
+ if (text === word) return;
171
+ if (similarityScore < MIN_SIMILARITY) return;
172
+ const existing = found.get(text);
173
+ if (existing && existing.similarity >= similarityScore) return;
174
+ const explanation = explainDifference(original, text);
175
+ found.set(text, {
176
+ text,
177
+ similarity: similarityScore,
178
+ ...(explanation ? { reason: explanation.reason } : {}),
179
+ });
180
+ };
181
+
182
+ for (const neighbour of lexicon.neighbours(word)) {
183
+ consider(neighbour.word, neighbour.similarity, word);
184
+ }
185
+
186
+ // Tesseract reads a word-initial ئ as گ، ك or ق (گۇنىڭ for ئۇنىڭ). The
187
+ // general distance prices that as a full substitution, so search from the
188
+ // repaired spelling as well, charging the slip as a cheap one.
189
+ if (INITIAL_HAMZA_MISREADS.has(word[0])) {
190
+ const repaired = 'ئ' + word.slice(1);
191
+ for (const neighbour of lexicon.neighbours(repaired, { limit: 3 })) {
192
+ const distance = neighbour.distance + INITIAL_HAMZA_COST;
193
+ consider(neighbour.word, similarity(word, neighbour.word, distance), word);
194
+ }
195
+ }
196
+
197
+ // Correcting the stem of an inflected word: كىتاپلىرىم → كىتابلىرىم, by
198
+ // finding كىتاب near كىتاپ and putting the suffixes back.
199
+ for (const segmentation of segment(word)) {
200
+ if (!segmentation.suffixes.length) continue;
201
+ for (const neighbour of lexicon.neighbours(segmentation.stem, { limit: 3 })) {
202
+ if (neighbour.word === segmentation.stem) continue;
203
+ const candidate = reattach(neighbour.word, segmentation.suffixes);
204
+ // The rebuilt form must itself be recognised: a corrected stem can clash
205
+ // with the original suffixes' harmony (گۇرۇھش، ئورۇنلاشتۇرۇشڭ).
206
+ if (!knows(lexicon, candidate)) continue;
207
+ consider(candidate, neighbour.similarity, segmentation.stem);
208
+ }
209
+ }
210
+
211
+ // Inflected forms the lexicon never saw whole (ئورۇنلاشتۇرۇڭ) are out of
212
+ // reach of the neighbour search; try the word with one look-alike letter
213
+ // swapped and keep the spellings the morphology recognises.
214
+ if (lexicon.analyze && lookalikeSwaps) {
215
+ for (const candidate of lookalikeSwaps(word)) {
216
+ if (found.has(candidate) || !knows(lexicon, candidate)) continue;
217
+ consider(candidate, similarity(word, candidate, editDistance(word, candidate)) - SWAP_PENALTY, word);
218
+ }
219
+ }
220
+
221
+ // A word the user has confirmed before is the better guess for their
222
+ // documents; it wins ties and near-ties against seed words.
223
+ const rank = (suggestion) => suggestion.similarity
224
+ + (suggestion.preferred ? PREFERRED_BONUS : 0)
225
+ + FREQUENCY_BONUS * (lexicon.commonness?.(stemOf(suggestion.text, lexicon)) ?? 0);
226
+ for (const suggestion of found.values()) {
227
+ if (lexicon.isPreferred?.(suggestion.text) || lexicon.isPreferred?.(stemOf(suggestion.text, lexicon))) {
228
+ suggestion.preferred = true;
229
+ }
230
+ }
231
+
232
+ return [...found.values()]
233
+ .sort((a, b) => rank(b) - rank(a) || a.text.localeCompare(b.text))
234
+ .slice(0, 5);
235
+ }
236
+
237
+ /** Whether the lexicon recognises a form, through its suffixes if need be. */
238
+ function knows(lexicon, text) {
239
+ return lexicon.analyze ? lexicon.analyze(text).known : lexicon.has(text);
240
+ }
241
+
242
+ /** The stem a known surface form was recognised through, if any. */
243
+ function stemOf(word, lexicon) {
244
+ return lexicon.analyze?.(word)?.stem ?? word;
245
+ }
246
+
247
+ /**
248
+ * Apply a chosen set of corrections to the text.
249
+ *
250
+ * @param {string} text
251
+ * @param {Array<{start: number, end: number, replacement: string}>} accepted
252
+ * @returns {string}
253
+ */
254
+ export function applyCorrections(text, accepted) {
255
+ return applyEdits(text, accepted);
256
+ }
257
+
258
+ /**
259
+ * Convenience for the common UI action: accept the top suggestion for every
260
+ * issue of the given types.
261
+ *
262
+ * Defaults to ambiguous characters only. Those are cases where the source
263
+ * character is definitely not Uyghur, so replacing it is a real fix; unknown
264
+ * words rest on the seed lexicon and should stay a per-word decision.
265
+ *
266
+ * @param {Analysis} analysis
267
+ * @param {{types?: string[], minSimilarity?: number}} [options]
268
+ * @returns {string}
269
+ */
270
+ export function applyTopSuggestions(analysis, { types = ['ambiguous-character'], minSimilarity = 0.8 } = {}) {
271
+ const edits = analysis.issues
272
+ .filter((issue) => types.includes(issue.type))
273
+ .map((issue) => ({ issue, best: issue.suggestions[0] }))
274
+ .filter(({ best }) => best && best.similarity >= minSimilarity)
275
+ .map(({ issue, best }) => ({ start: issue.start, end: issue.end, replacement: best.text }));
276
+
277
+ return applyEdits(analysis.text, edits);
278
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Word tokenisation with source offsets.
3
+ *
4
+ * Offsets are the point of this module. The correction UI has to highlight a
5
+ * suspect word in the user's own text and replace exactly that span when a
6
+ * suggestion is accepted, so every token carries where it came from. Splitting
7
+ * on whitespace and losing the positions would make non-destructive editing
8
+ * impossible.
9
+ */
10
+
11
+ /**
12
+ * Characters that make up a word in Uyghur Arabic script, plus Latin letters
13
+ * and digits so that mixed-script text tokenises sensibly.
14
+ *
15
+ * Covers Arabic (U+0600-U+06FF), Arabic Supplement (U+0750-U+077F) and Arabic
16
+ * Extended-A (U+08A0-U+08FF), which is where every Uyghur letter lives.
17
+ */
18
+ const WORD_CHAR = /[ؠ-يٮ-ۓەۥۦۮۯۺ-ۿݐ-ݿࢠ-ࣿA-Za-zÀ-ɏ0-9]/;
19
+
20
+ /**
21
+ * Marks that attach to a word rather than separating it: combining diacritics,
22
+ * and the ASCII/Arabic apostrophes used in transliteration.
23
+ */
24
+ const WORD_JOINER = /[ً-ْٰٕٔ'’]/;
25
+
26
+ /**
27
+ * @typedef {object} Token
28
+ * @property {string} text
29
+ * @property {number} start index into the source string
30
+ * @property {number} end exclusive
31
+ * @property {boolean} isWord false for whitespace and punctuation runs
32
+ */
33
+
34
+ /**
35
+ * Split text into word and non-word tokens, preserving offsets.
36
+ *
37
+ * Every character of the input appears in exactly one token, so joining the
38
+ * token texts reproduces the input exactly. That property is what lets the UI
39
+ * rebuild the text after an edit without drift.
40
+ *
41
+ * @param {string} text
42
+ * @returns {Token[]}
43
+ */
44
+ export function tokenize(text) {
45
+ if (typeof text !== 'string' || !text) return [];
46
+
47
+ const tokens = [];
48
+ let index = 0;
49
+
50
+ while (index < text.length) {
51
+ const start = index;
52
+ const isWordStart = WORD_CHAR.test(text[index]);
53
+
54
+ if (isWordStart) {
55
+ while (index < text.length && (WORD_CHAR.test(text[index]) || WORD_JOINER.test(text[index]))) {
56
+ index++;
57
+ }
58
+ } else {
59
+ while (index < text.length && !WORD_CHAR.test(text[index])) {
60
+ index++;
61
+ }
62
+ }
63
+
64
+ // Defensive: a character matching neither branch would loop forever.
65
+ if (index === start) index++;
66
+
67
+ tokens.push({ text: text.slice(start, index), start, end: index, isWord: isWordStart });
68
+ }
69
+
70
+ return tokens;
71
+ }
72
+
73
+ /**
74
+ * Just the word tokens.
75
+ * @param {string} text
76
+ * @returns {Token[]}
77
+ */
78
+ export function words(text) {
79
+ return tokenize(text).filter((token) => token.isWord);
80
+ }
81
+
82
+ /**
83
+ * Whether a token is Uyghur Arabic script, as opposed to Latin or digits.
84
+ * Used to skip tokens the Uyghur lexicon has no opinion about.
85
+ *
86
+ * @param {string} text
87
+ * @returns {boolean}
88
+ */
89
+ export function isArabicScript(text) {
90
+ return /[ؠ-ۿݐ-ݿࢠ-ࣿ]/.test(text);
91
+ }
92
+
93
+ /**
94
+ * Whether a token is purely numeric (in either digit set).
95
+ * @param {string} text
96
+ * @returns {boolean}
97
+ */
98
+ export function isNumeric(text) {
99
+ return /^[0-9٠-٩۰-۹]+$/.test(text);
100
+ }
101
+
102
+ /**
103
+ * Apply replacements to text by offset, without disturbing anything else.
104
+ *
105
+ * Applied right-to-left so that each replacement's offsets stay valid — editing
106
+ * left-to-right would shift every subsequent span.
107
+ *
108
+ * @param {string} text
109
+ * @param {Array<{start: number, end: number, replacement: string}>} edits
110
+ * @returns {string}
111
+ */
112
+ export function applyEdits(text, edits) {
113
+ if (!edits.length) return text;
114
+
115
+ const ordered = [...edits].sort((a, b) => b.start - a.start);
116
+ let out = text;
117
+
118
+ let previousStart = Infinity;
119
+ for (const edit of ordered) {
120
+ // Overlapping edits would corrupt the result; skip rather than mangle.
121
+ if (edit.end > previousStart) continue;
122
+ out = out.slice(0, edit.start) + edit.replacement + out.slice(edit.end);
123
+ previousStart = edit.start;
124
+ }
125
+
126
+ return out;
127
+ }
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Personal dictionary: words the user has confirmed.
3
+ *
4
+ * The bundled lexicon is a small seed (see `data/roots.js`), so on real text
5
+ * most "unknown word" flags are words that are simply missing from it. Every
6
+ * time the user accepts a suggestion, corrects a word in the box editor, or
7
+ * says "this word is fine", they are telling us something the seed does not
8
+ * know. Keeping that makes the engine better the more it is used:
9
+ *
10
+ * - learned words are no longer flagged as unknown;
11
+ * - they become candidates for correcting nearby misspellings;
12
+ * - they rank ahead of seed words at equal similarity, because a word this
13
+ * user actually writes is the better guess for this user's documents.
14
+ *
15
+ * Privacy: only individual words are stored — never sentences — and only where
16
+ * the caller says. By default the dictionary lives in memory; pass
17
+ * `storage: localStorage` (or any object with getItem/setItem/removeItem) to
18
+ * keep it between visits. `clear()` removes all of it, and `export()` shows
19
+ * exactly what is held.
20
+ *
21
+ * Nothing happens on import: create a dictionary and attach it to a lexicon
22
+ * with `dictionary.apply(lexicon)`, or pass it to `createSpellChecker`.
23
+ */
24
+
25
+ import { getLexicon } from './lexicon.js';
26
+ import { normalize } from './normalize.js';
27
+ import { isArabicScript, isNumeric } from './tokenize.js';
28
+
29
+ const DEFAULT_STORAGE_KEY = 'uyghur-spell:user-dictionary';
30
+
31
+ /** Bound on retained words, so the list cannot grow without limit. */
32
+ const MAX_WORDS = 20000;
33
+
34
+ /** Shortest word worth learning; shorter ones are mostly particles and noise. */
35
+ const MIN_LENGTH = 2;
36
+
37
+ /**
38
+ * Per lexicon, the words this dictionary added — as opposed to words the
39
+ * lexicon already knew — so forgetting a word never removes a seed entry.
40
+ * @type {WeakMap<import('./lexicon').Lexicon, Set<string>>}
41
+ */
42
+ const addedTo = new WeakMap();
43
+
44
+ export class UserDictionary {
45
+ /**
46
+ * @param {{storage?: Pick<Storage, 'getItem'|'setItem'|'removeItem'> | null, storageKey?: string}} [options]
47
+ */
48
+ constructor({ storage = null, storageKey = DEFAULT_STORAGE_KEY } = {}) {
49
+ this.storage = storage;
50
+ this.storageKey = storageKey;
51
+ /** Lexicons this dictionary has been applied to; kept in sync on every change. */
52
+ this.attached = new Set();
53
+ /** @type {Map<string, number>} word → times confirmed */
54
+ this.words = new Map(this.read());
55
+ this.listeners = new Set();
56
+ }
57
+
58
+ get size() {
59
+ return this.words.size;
60
+ }
61
+
62
+ has(word) {
63
+ return this.words.has(clean(word));
64
+ }
65
+
66
+ /** Every learned word, most-confirmed first. */
67
+ list() {
68
+ return [...this.words.entries()]
69
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
70
+ .map(([word]) => word);
71
+ }
72
+
73
+ /**
74
+ * Record that the user confirmed these words. Non-Uyghur tokens (Latin,
75
+ * numbers) are ignored — the lexicon only concerns Arabic-script Uyghur.
76
+ *
77
+ * @param {string | string[]} input a word, a list, or a phrase
78
+ * @returns {number} how many words were new
79
+ */
80
+ learn(input) {
81
+ const tokens = (Array.isArray(input) ? input : [input])
82
+ .flatMap((item) => String(item ?? '').split(/\s+/))
83
+ .map(clean)
84
+ .filter((word) => word.length >= MIN_LENGTH && isArabicScript(word) && !isNumeric(word));
85
+
86
+ let added = 0;
87
+ for (const word of tokens) {
88
+ if (!this.words.has(word)) added++;
89
+ this.words.set(word, (this.words.get(word) ?? 0) + 1);
90
+ }
91
+ if (!tokens.length) return 0;
92
+
93
+ this.trim();
94
+ this.write();
95
+ this.applyAll();
96
+ this.emit();
97
+ return added;
98
+ }
99
+
100
+ /** Remove one word. */
101
+ forget(word) {
102
+ const cleaned = clean(word);
103
+ if (!this.words.delete(cleaned)) return false;
104
+ this.unapplyAll([cleaned]);
105
+ this.write();
106
+ this.emit();
107
+ return true;
108
+ }
109
+
110
+ /** Remove everything. */
111
+ clear() {
112
+ this.unapplyAll([...this.words.keys()]);
113
+ this.words.clear();
114
+ try {
115
+ this.storage?.removeItem(this.storageKey);
116
+ } catch {
117
+ // Nothing further to try.
118
+ }
119
+ this.emit();
120
+ }
121
+
122
+ /** One word per line, for the user to inspect or reuse. */
123
+ export() {
124
+ return this.list().join('\n');
125
+ }
126
+
127
+ /**
128
+ * Add the learned words to the active lexicon and mark them preferred.
129
+ * Idempotent; called after every change and once at startup.
130
+ *
131
+ * @param {import('./lexicon').Lexicon} [lexicon]
132
+ */
133
+ apply(lexicon = getLexicon()) {
134
+ this.attached.add(lexicon);
135
+ const added = addedTo.get(lexicon) ?? new Set();
136
+ addedTo.set(lexicon, added);
137
+ for (const word of this.words.keys()) {
138
+ if (!lexicon.has(word)) {
139
+ lexicon.add(word);
140
+ added.add(word);
141
+ }
142
+ lexicon.prefer(word);
143
+ }
144
+ return lexicon;
145
+ }
146
+
147
+ /** @private — re-apply to every attached lexicon (the default one if none yet). */
148
+ applyAll() {
149
+ if (!this.attached.size) return this.apply();
150
+ for (const lexicon of this.attached) this.apply(lexicon);
151
+ }
152
+
153
+ /** @private — undo `apply` for the given words on every attached lexicon. */
154
+ unapplyAll(words) {
155
+ if (!this.attached.size) return this.unapply(words);
156
+ for (const lexicon of this.attached) this.unapply(words, lexicon);
157
+ }
158
+
159
+ /** @private — undo `apply` for the given words. */
160
+ unapply(words, lexicon = getLexicon()) {
161
+ const added = addedTo.get(lexicon);
162
+ for (const word of words) {
163
+ if (added?.has(word)) {
164
+ lexicon.remove(word);
165
+ added.delete(word);
166
+ } else {
167
+ lexicon.preferred?.delete(word);
168
+ }
169
+ }
170
+ }
171
+
172
+ /** @param {() => void} listener @returns {() => void} unsubscribe */
173
+ subscribe(listener) {
174
+ this.listeners.add(listener);
175
+ return () => this.listeners.delete(listener);
176
+ }
177
+
178
+ /** @private */
179
+ emit() {
180
+ for (const listener of this.listeners) listener();
181
+ }
182
+
183
+ /** @private — keep the most-confirmed words when over the cap. */
184
+ trim() {
185
+ if (this.words.size <= MAX_WORDS) return;
186
+ const keep = [...this.words.entries()].sort((a, b) => b[1] - a[1]).slice(0, MAX_WORDS);
187
+ this.words = new Map(keep);
188
+ }
189
+
190
+ /** @private */
191
+ read() {
192
+ try {
193
+ const raw = this.storage?.getItem(this.storageKey);
194
+ if (!raw) return [];
195
+ const parsed = JSON.parse(raw);
196
+ return Array.isArray(parsed)
197
+ ? parsed.filter((entry) => Array.isArray(entry) && typeof entry[0] === 'string')
198
+ : [];
199
+ } catch {
200
+ return [];
201
+ }
202
+ }
203
+
204
+ /** @private */
205
+ write() {
206
+ try {
207
+ this.storage?.setItem(this.storageKey, JSON.stringify([...this.words.entries()]));
208
+ } catch {
209
+ // Quota exhaustion must not break correction; the list is a nicety.
210
+ }
211
+ }
212
+ }
213
+
214
+ function clean(word) {
215
+ // Strip surrounding punctuation, then apply the same safe normalisation the
216
+ // analyser uses, so a learned word matches what it will be compared against.
217
+ const stripped = String(word ?? '').replace(/^[^\p{L}]+|[^\p{L}]+$/gu, '');
218
+ return normalize(stripped, { collapseWhitespace: false });
219
+ }