@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.
@@ -0,0 +1,386 @@
1
+ /**
2
+ * Uyghur suffix segmentation.
3
+ *
4
+ * Uyghur is agglutinative: a noun stem takes plural, then possessive, then case
5
+ * suffixes, and a single stem can surface in dozens of inflected forms. A flat
6
+ * word list is therefore close to useless on its own — كىتاب (book) also appears
7
+ * as كىتابلار, كىتابىم, كىتابلىرىمىزدىن and many more, none of which a list of
8
+ * roots would contain.
9
+ *
10
+ * Stripping suffixes before lexicon lookup is what makes a modest root list
11
+ * cover real text. This module does not attempt full morphological analysis; it
12
+ * peels recognised suffixes off the end of a word in the documented order and
13
+ * reports the candidate stems that remain.
14
+ *
15
+ * Suffix order (stem → plural → possessive → case) and the harmony variants are
16
+ * from the Uyghur grammar references listed in `docs/uyghur-references.md`.
17
+ *
18
+ * Vowel harmony means most suffixes have a back and a front form, and several
19
+ * also have voiced/voiceless variants after a voiceless consonant. Both are
20
+ * listed explicitly rather than derived, because deriving them correctly needs
21
+ * the stem's vowel inventory, and listing them is auditable by a reader who
22
+ * speaks the language.
23
+ */
24
+
25
+ /**
26
+ * Case suffixes, outermost in the noun.
27
+ * @type {Array<{suffixes: string[], label: string}>}
28
+ */
29
+ export const CASE_SUFFIXES = [
30
+ { suffixes: ['نىڭ', 'نڭ'], label: 'genitive' },
31
+ { suffixes: ['نى'], label: 'accusative' },
32
+ { suffixes: ['غا', 'قا', 'گە', 'كە', 'ا', 'ە'], label: 'dative' },
33
+ { suffixes: ['دا', 'تا', 'دە', 'تە'], label: 'locative' },
34
+ { suffixes: ['دىن', 'تىن'], label: 'ablative' },
35
+ { suffixes: ['دەك', 'تەك'], label: 'similitude' },
36
+ { suffixes: ['چە'], label: 'equative' },
37
+ ];
38
+
39
+ /**
40
+ * Possessive suffixes, between plural and case.
41
+ * @type {Array<{suffixes: string[], label: string}>}
42
+ */
43
+ export const POSSESSIVE_SUFFIXES = [
44
+ { suffixes: ['ىمىز', 'ىمىز', 'مىز', 'ۇمىز', 'ۈمىز'], label: '1pl' },
45
+ { suffixes: ['ىڭلار', 'ىڭلەر', 'ڭلار', 'ڭلەر'], label: '2pl' },
46
+ { suffixes: ['ىڭىز', 'ڭىز', 'ۇڭىز', 'ۈڭىز'], label: '2sg-formal' },
47
+ { suffixes: ['ىم', 'م', 'ۇم', 'ۈم'], label: '1sg' },
48
+ { suffixes: ['ىڭ', 'ڭ', 'ۇڭ', 'ۈڭ'], label: '2sg' },
49
+ { suffixes: ['لىرى', 'سى', 'ى', 'ئى'], label: '3rd' },
50
+ ];
51
+
52
+ /**
53
+ * Plural suffixes, innermost of the three.
54
+ * @type {Array<{suffixes: string[], label: string}>}
55
+ */
56
+ export const PLURAL_SUFFIXES = [
57
+ { suffixes: ['لار', 'لەر', 'لىر'], label: 'plural' },
58
+ ];
59
+
60
+ /**
61
+ * A small set of highly productive derivational suffixes. Kept separate from
62
+ * inflection because they build new stems rather than inflecting one, so a
63
+ * result that needs them is a weaker match.
64
+ * @type {Array<{suffixes: string[], label: string}>}
65
+ */
66
+ export const DERIVATIONAL_SUFFIXES = [
67
+ { suffixes: ['چى', 'چى'], label: 'agent' },
68
+ { suffixes: ['لىق', 'لىك', 'لۇق', 'لۈك'], label: 'adjectival' },
69
+ { suffixes: ['سىز', 'سىز'], label: 'privative' },
70
+ { suffixes: ['داش', 'تاش'], label: 'associative' },
71
+ { suffixes: ['گەن', 'قان', 'كەن', 'غان'], label: 'participle' },
72
+ { suffixes: ['ىش', 'ش'], label: 'verbal-noun' },
73
+ { suffixes: ['ماق', 'مەك'], label: 'infinitive' },
74
+ ];
75
+
76
+ /** The inflectional layers, outermost first — the order suffixes are peeled. */
77
+ const LAYERS = [
78
+ { name: 'case', groups: CASE_SUFFIXES },
79
+ { name: 'possessive', groups: POSSESSIVE_SUFFIXES },
80
+ { name: 'plural', groups: PLURAL_SUFFIXES },
81
+ ];
82
+
83
+ /** Stems shorter than this are not plausible Uyghur roots. */
84
+ const MIN_STEM_LENGTH = 2;
85
+
86
+ /**
87
+ * @typedef {object} Segmentation
88
+ * @property {string} stem the candidate root
89
+ * @property {Array<{suffix: string, label: string, layer: string}>} suffixes
90
+ * peeled outermost-first
91
+ * @property {number} depth how many suffixes were removed
92
+ */
93
+
94
+ /**
95
+ * Produce every plausible stem for a word by peeling inflectional suffixes.
96
+ *
97
+ * The full word is always the first candidate, since an uninflected word is the
98
+ * commonest case and should be checked before any analysis is attempted.
99
+ *
100
+ * @param {string} word
101
+ * @param {{includeDerivational?: boolean, maxDepth?: number}} [options]
102
+ * @returns {Segmentation[]} ordered by increasing depth (shallowest first)
103
+ */
104
+ export function segment(word, { includeDerivational = true, maxDepth = 4 } = {}) {
105
+ if (typeof word !== 'string' || word.length < MIN_STEM_LENGTH) {
106
+ return word ? [{ stem: word, suffixes: [], depth: 0 }] : [];
107
+ }
108
+
109
+ /** @type {Map<string, Segmentation>} */
110
+ const seen = new Map();
111
+ const results = [];
112
+
113
+ const record = (segmentation) => {
114
+ // The same stem can be reached by more than one path; keep the shallowest,
115
+ // which is the analysis a reader would give.
116
+ const key = segmentation.stem;
117
+ const existing = seen.get(key);
118
+ if (existing && existing.depth <= segmentation.depth) return;
119
+ if (existing) {
120
+ results.splice(results.indexOf(existing), 1);
121
+ }
122
+ seen.set(key, segmentation);
123
+ results.push(segmentation);
124
+ };
125
+
126
+ record({ stem: word, suffixes: [], depth: 0 });
127
+
128
+ /**
129
+ * Peel from `layerIndex` outward. Each layer may be skipped, because a word
130
+ * need not carry every layer.
131
+ */
132
+ const walk = (current, layerIndex, suffixes) => {
133
+ if (suffixes.length >= maxDepth) return;
134
+
135
+ for (let i = layerIndex; i < LAYERS.length; i++) {
136
+ const layer = LAYERS[i];
137
+ for (const group of layer.groups) {
138
+ for (const suffix of group.suffixes) {
139
+ if (!current.endsWith(suffix)) continue;
140
+ const stem = current.slice(0, current.length - suffix.length);
141
+ if (stem.length < MIN_STEM_LENGTH) continue;
142
+
143
+ const next = [...suffixes, { suffix, label: group.label, layer: layer.name }];
144
+ record({ stem, suffixes: next, depth: next.length });
145
+ // Continue with the next layer inward, never the same one again.
146
+ walk(stem, i + 1, next);
147
+ }
148
+ }
149
+ }
150
+
151
+ if (includeDerivational) {
152
+ for (const group of DERIVATIONAL_SUFFIXES) {
153
+ for (const suffix of group.suffixes) {
154
+ if (!current.endsWith(suffix)) continue;
155
+ const stem = current.slice(0, current.length - suffix.length);
156
+ if (stem.length < MIN_STEM_LENGTH) continue;
157
+ const next = [...suffixes, { suffix, label: group.label, layer: 'derivational' }];
158
+ record({ stem, suffixes: next, depth: next.length });
159
+ }
160
+ }
161
+ }
162
+ };
163
+
164
+ walk(word, 0, []);
165
+
166
+ return results.sort((a, b) => a.depth - b.depth);
167
+ }
168
+
169
+ /**
170
+ * The stems a word could reduce to, shallowest first.
171
+ * @param {string} word
172
+ * @returns {string[]}
173
+ */
174
+ export function candidateStems(word) {
175
+ return segment(word).map((s) => s.stem);
176
+ }
177
+
178
+ /**
179
+ * Rebuild a surface form from a stem and the suffixes that were peeled.
180
+ * Used to render a suggestion in the same inflected form as the original, so a
181
+ * correction to a stem does not silently strip the grammar off the word.
182
+ *
183
+ * @param {string} stem
184
+ * @param {Array<{suffix: string}>} suffixes as returned by `segment` (outermost first)
185
+ * @returns {string}
186
+ */
187
+ export function reattach(stem, suffixes) {
188
+ // `segment` peels outermost-first, so reattaching runs in reverse.
189
+ return [...suffixes].reverse().reduce((word, { suffix }) => word + suffix, stem);
190
+ }
191
+
192
+ const BACK_VOWELS = new Set(['ا', 'و', 'ۇ']);
193
+ const FRONT_VOWELS = new Set(['ە', 'ۆ', 'ۈ']);
194
+ const BACK_SUFFIX_LETTERS = new Set(['ا', 'و', 'ۇ', 'ق', 'غ']);
195
+ const FRONT_SUFFIX_LETTERS = new Set(['ە', 'ۆ', 'ۈ', 'ك', 'گ']);
196
+
197
+ /**
198
+ * Suffixes with a single form whatever the stem (ئادەمدەك، بالىدەك، ئۇيغۇرچە).
199
+ * كەن is also the evidential particle (ياخشىكەن), and a lone ا or ە is also
200
+ * the vocative (ھەسرەتا, "alas"), so neither is checked.
201
+ */
202
+ const INVARIANT_SUFFIXES = new Set(['دەك', 'تەك', 'چە', 'كەن', 'ا', 'ە']);
203
+
204
+ /** Endings after which suffixes take the front form, whatever came before. */
205
+ const FRONT_ENDINGS = ['كى', 'لىك'];
206
+
207
+ /**
208
+ * The harmony class of a stem: 'back', 'front', or null when it cannot be told.
209
+ *
210
+ * The last non-neutral vowel decides (ى and ې are neutral). A stem with only
211
+ * neutral vowels is back if it has ق، غ or خ, front if it has ك or گ, and
212
+ * undecided otherwise — those take either form often enough in real text
213
+ * that rejecting one would cost more than it saves. A stem ending in -كى or
214
+ * -لىك is front (ئېقىمىدىكىلەر، مۇمكىنچىلىكلەر).
215
+ *
216
+ * @param {string} stem
217
+ * @returns {'back'|'front'|null}
218
+ */
219
+ export function stemHarmony(stem) {
220
+ if (FRONT_ENDINGS.some((e) => stem.endsWith(e))) return 'front';
221
+ for (let i = stem.length - 1; i >= 0; i--) {
222
+ if (BACK_VOWELS.has(stem[i])) return 'back';
223
+ if (FRONT_VOWELS.has(stem[i])) return 'front';
224
+ }
225
+ if (/[قغخ]/.test(stem)) return 'back';
226
+ if (/[كگ]/.test(stem)) return 'front';
227
+ return null;
228
+ }
229
+
230
+ /**
231
+ * The harmony class a suffix form belongs to, or null for neutral and
232
+ * invariant suffixes (نىڭ، نى، لىرى، دەك…).
233
+ *
234
+ * @param {string} suffix
235
+ * @returns {'back'|'front'|null}
236
+ */
237
+ export function suffixHarmony(suffix) {
238
+ if (INVARIANT_SUFFIXES.has(suffix)) return null;
239
+ let back = false;
240
+ let front = false;
241
+ for (const ch of suffix) {
242
+ if (BACK_SUFFIX_LETTERS.has(ch)) back = true;
243
+ if (FRONT_SUFFIX_LETTERS.has(ch)) front = true;
244
+ }
245
+ if (back === front) return null;
246
+ return back ? 'back' : 'front';
247
+ }
248
+
249
+ /**
250
+ * Whether every peeled suffix agrees with the stem's vowel harmony. Catches
251
+ * OCR's rounded-vowel slips that would otherwise segment cleanly: دوستۈم
252
+ * (front ۈم on a back stem) is not a form of دوست, while دوستۇم is.
253
+ *
254
+ * @param {string} stem
255
+ * @param {Array<{suffix: string}>} suffixes
256
+ * @returns {boolean}
257
+ */
258
+ export function harmonizes(stem, suffixes) {
259
+ const cls = stemHarmony(stem);
260
+ if (!cls) return true;
261
+ return suffixes.every(({ suffix }) => {
262
+ const s = suffixHarmony(suffix);
263
+ return s === null || s === cls;
264
+ });
265
+ }
266
+
267
+ /**
268
+ * Verb endings that Wikipedia prose rarely contains — second person, first
269
+ * person, imperative, conditional, evidential — so their forms are missing
270
+ * from a frequency list even when the verb is common. Each is stripped to the
271
+ * verb root, and the root is accepted if the lexicon has one of its everyday
272
+ * forms (ROOT_FORMS): ئىزدەيسىز is known because ئىزدەيدۇ or ئىزدەش is.
273
+ * @type {Array<{suffixes: string[], label: string, invariant?: boolean, raisedOnly?: boolean}>}
274
+ */
275
+ export const VERB_ENDINGS = [
276
+ { suffixes: ['يسىز', 'ىسىز', 'يسىلەر', 'ىسىلەر'], label: '2sg-formal' },
277
+ { suffixes: ['يمەن', 'ىمەن', 'يمىز', 'ىمىز', 'يسەن', 'ىسەن'], label: 'present' },
278
+ // Invariant: يارىمايدىكەن, not *يارىمايدىكان.
279
+ { suffixes: ['يدىكەن', 'ىدىكەن', 'دىكەن', 'غانىكەن', 'گەنىكەن'], label: 'evidential', invariant: true },
280
+ { suffixes: ['سىڭىز', 'ساڭ', 'سەڭ', 'سام', 'سەم', 'ساق', 'سەك'], label: 'conditional' },
281
+ { suffixes: ['دىڭىز', 'تىڭىز', 'دىم', 'تىم', 'دىڭ', 'تىڭ', 'دۇق', 'تۇق'], label: 'past' },
282
+ // The plain past is common in prose, so it is only needed where the root's
283
+ // last vowel was raised (قەدىرلىدى ← قەدىرلە-); a bare root would let
284
+ // OCR slips like يۈرتى (يۈر + تى) through.
285
+ { suffixes: ['دى', 'تى'], label: 'past', raisedOnly: true },
286
+ { suffixes: ['غىلى', 'قىلى', 'گىلى', 'كىلى'], label: 'purpose' },
287
+ { suffixes: ['ىڭ', 'ۇڭ', 'ۈڭ', 'ڭ', 'ىڭلار', 'ىڭلەر', 'ڭلار', 'ڭلەر', 'سۇن', 'سۈن', 'ايلى', 'ەيلى', 'يلى'], label: 'imperative' },
288
+ { suffixes: ['ىۋاتىدۇ', 'ۋاتىدۇ', 'ىۋاتقان', 'ۋاتقان', 'ىۋېتىپ', 'ۋېتىپ'], label: 'progressive' },
289
+ ];
290
+
291
+ /** Everyday forms of a verb root, any one of which shows the root is real. */
292
+ export const ROOT_FORMS = [
293
+ 'ىدۇ', 'يدۇ', 'ىش', 'ش', 'ۇش', 'ۈش', 'دى', 'تى', 'ىپ', 'پ', 'ۇپ', 'ۈپ',
294
+ 'غان', 'قان', 'گەن', 'كەن', 'ماق', 'مەك', 'سا', 'سە', 'مايدۇ', 'مەيدۇ',
295
+ ];
296
+
297
+ /** Clitic particles that attach to any word: ئىشىنىپلا، سەنمۇ. */
298
+ export const PARTICLES = ['لا', 'مۇ', 'چۇ', 'غۇ'];
299
+
300
+ /**
301
+ * Verb roots a word could have under VERB_ENDINGS, with the forms to look up
302
+ * for each. Roots whose harmony clashes with the ending are skipped.
303
+ *
304
+ * @param {string} word
305
+ * @returns {Array<{root: string, suffix: string, label: string, forms: string[]}>}
306
+ */
307
+ export function verbRoots(word) {
308
+ const out = [];
309
+ for (const group of VERB_ENDINGS) {
310
+ for (const suffix of new Set(group.suffixes)) {
311
+ if (!word.endsWith(suffix)) continue;
312
+ const root = word.slice(0, word.length - suffix.length);
313
+ if (root.length < MIN_STEM_LENGTH) continue;
314
+ if (!group.invariant && !harmonizes(root, [{ suffix }])) continue;
315
+ const forms = group.raisedOnly ? [] : ROOT_FORMS.map((f) => root + f);
316
+ // ئىشلىدىڭىز: the root ئىشلە- was raised before the ending.
317
+ for (const r of unraise(root)) forms.push(r, ...ROOT_FORMS.map((f) => r + f));
318
+ if (!forms.length) continue;
319
+ out.push({ root, suffix, label: group.label, forms });
320
+ }
321
+ }
322
+ return out;
323
+ }
324
+
325
+ /**
326
+ * The word with a clitic particle removed, in each spelling the host may have:
327
+ * a final ا or ە raises to ى before the particle (قىلغاندىلا ← قىلغاندا).
328
+ *
329
+ * @param {string} word
330
+ * @returns {Array<{host: string, particle: string}>}
331
+ */
332
+ export function particleHosts(word) {
333
+ const out = [];
334
+ for (const particle of PARTICLES) {
335
+ if (!word.endsWith(particle)) continue;
336
+ const host = word.slice(0, word.length - particle.length);
337
+ if (host.length < MIN_STEM_LENGTH) continue;
338
+ out.push({ host, particle });
339
+ if (host.endsWith('ى')) {
340
+ for (const v of ['ا', 'ە']) out.push({ host: host.slice(0, -1) + v, particle });
341
+ }
342
+ }
343
+ return out;
344
+ }
345
+
346
+ const VOWELS = new Set(['ا', 'ە', 'و', 'ۇ', 'ۆ', 'ۈ', 'ې', 'ى']);
347
+
348
+ /**
349
+ * Undo vowel raising: a stem's last ا or ە becomes ى when a suffix follows
350
+ * (مەسىلە → مەسىلىسى، ئىشلە → ئىشلىدى، قەپەس → قەپىسى). Given the raised stem
351
+ * as it appears before the suffix, returns the dictionary spellings it could
352
+ * come from. Only an ى in the stem's last syllable can be a raised vowel.
353
+ *
354
+ * @param {string} stem
355
+ * @returns {string[]}
356
+ */
357
+ export function unraise(stem) {
358
+ // Short stems give too many accidental matches (سىي → ساي).
359
+ if (stem.length < 4) return [];
360
+ const i = stem.lastIndexOf('ى');
361
+ if (i < 1) return [];
362
+ for (let j = i + 1; j < stem.length; j++) if (VOWELS.has(stem[j])) return [];
363
+ return ['ا', 'ە'].map((v) => stem.slice(0, i) + v + stem.slice(i + 1));
364
+ }
365
+
366
+ /** Possessive forms that attach only after a vowel, or only after a consonant. */
367
+ const AFTER_VOWEL = new Set(['م', 'ڭ', 'مىز', 'ڭىز', 'ڭلار', 'ڭلەر', 'سى']);
368
+ const AFTER_CONSONANT = new Set(['ىم', 'ۇم', 'ۈم', 'ىڭ', 'ۇڭ', 'ۈڭ', 'ىمىز', 'ۇمىز', 'ۈمىز', 'ىڭىز', 'ۇڭىز', 'ۈڭىز', 'ىڭلار', 'ىڭلەر', 'ى']);
369
+
370
+ /**
371
+ * Whether the suffix next to the stem has the right shape for how the stem
372
+ * ends: كىتابىم but ئانام, never *كىتابم or *ئانائىم. OCR that drops or adds
373
+ * an ى can otherwise produce a form that segments cleanly.
374
+ *
375
+ * @param {string} stem
376
+ * @param {Array<{suffix: string}>} suffixes outermost first, as from `segment`
377
+ * @returns {boolean}
378
+ */
379
+ export function attachesCleanly(stem, suffixes) {
380
+ if (!suffixes.length) return true;
381
+ const inner = suffixes[suffixes.length - 1].suffix;
382
+ const endsInVowel = VOWELS.has(stem[stem.length - 1]);
383
+ if (AFTER_VOWEL.has(inner)) return endsInVowel;
384
+ if (AFTER_CONSONANT.has(inner)) return !endsInVowel;
385
+ return true;
386
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Unicode normalisation for Uyghur Arabic-script text.
3
+ *
4
+ * Split deliberately into two tiers, because they carry very different risk:
5
+ *
6
+ * SAFE Transformations that cannot change which letter was meant. These
7
+ * are encoding-level fixes — a presentation form and its base letter
8
+ * ARE the same letter, and U+06A9 and U+0643 ARE the same letter.
9
+ * Applying them automatically loses nothing.
10
+ *
11
+ * AMBIGUOUS Characters that are wrong in Uyghur but whose correct
12
+ * replacement depends on the word. ه could be intended as ھ (the
13
+ * consonant h) or as ە (the vowel e); ی could be ى (the vowel i) or
14
+ * ي (the consonant y). Guessing silently would corrupt text while
15
+ * appearing to fix it, so these are surfaced as suggestions and
16
+ * resolved against the lexicon instead.
17
+ *
18
+ * That division is the whole point of this file: `normalize()` is safe to run
19
+ * on every result, and nothing else is.
20
+ */
21
+
22
+ /**
23
+ * Characters that are always encoding variants of a Uyghur letter, never a
24
+ * different letter. Mapping them is lossless.
25
+ *
26
+ * @type {Record<string, string>}
27
+ */
28
+ export const SAFE_REPLACEMENTS = {
29
+ // Arabic/Persian keyboards produce U+06A9; the Uyghur standard is U+0643.
30
+ // Same letter, same shape, different code point.
31
+ 'ک': 'ك', // ک → ك
32
+ // Arabic kaf variants seen in older documents.
33
+ 'ـ': '', // ـ tatweel/kashida — decorative elongation, carries no meaning
34
+ // Arabic-Indic and extended Arabic-Indic digits → ASCII, so that numbers in
35
+ // recognised text are usable as numbers.
36
+ '٠': '0', '١': '1', '٢': '2', '٣': '3', '٤': '4',
37
+ '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9',
38
+ '۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4',
39
+ '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9',
40
+ };
41
+
42
+ /**
43
+ * Characters that are not Uyghur letters, each with the candidates a Uyghur
44
+ * reader would consider. Order is by prior likelihood, but the lexicon decides.
45
+ *
46
+ * @type {Record<string, {candidates: string[], note: string}>}
47
+ */
48
+ export const AMBIGUOUS_REPLACEMENTS = {
49
+ 'ه': { // ه ARABIC LETTER HEH
50
+ candidates: ['ھ', 'ە'], // ھ (h) or ە (e)
51
+ note: 'ه is not a Uyghur letter; it is either ھ (the consonant h) or ە (the vowel e).',
52
+ },
53
+ 'ی': { // ی FARSI YEH
54
+ candidates: ['ى', 'ي'], // ى (i) or ي (y)
55
+ note: 'ی is not a Uyghur letter; it is either ى (the vowel i) or ي (the consonant y).',
56
+ },
57
+ 'ئ': { // yeh + hamza above, seen instead of the composed ئ
58
+ candidates: ['ئ'],
59
+ note: 'Decomposed hamza should be the composed carrier ئ.',
60
+ },
61
+ '›': { // U+203A — Tesseract's uig model reads the Arabic comma ، as this
62
+ candidates: ['،'],
63
+ note: '› is not used in Uyghur text; OCR commonly produces it for the Arabic comma ،.',
64
+ },
65
+ 'ة': { // ة TEH MARBUTA — Arabic loanword ending
66
+ candidates: ['ە', 'ت'], // ە or ت
67
+ note: 'ة is Arabic; in Uyghur the ending is written ە or ت.',
68
+ },
69
+ };
70
+
71
+ /**
72
+ * Zero-width and directional characters that survive OCR and PDF extraction.
73
+ *
74
+ * Written as escapes rather than literals so the set is auditable — these are
75
+ * invisible in an editor, and a stray one in a character class is impossible to
76
+ * spot by eye.
77
+ *
78
+ * U+200B zero-width space U+200C zero-width non-joiner
79
+ * U+200D zero-width joiner U+200E left-to-right mark
80
+ * U+200F right-to-left mark U+2060 word joiner
81
+ * U+FEFF byte-order mark
82
+ *
83
+ * The directional marks go too: the app renders with `dir="auto"`, which infers
84
+ * direction from the text itself, so embedded marks only cause the kind of
85
+ * bidi artefacts that make copied text behave strangely elsewhere.
86
+ */
87
+ // Alternation rather than a character class: a class containing the joiners can
88
+ // silently match a joined grapheme sequence, which is not what we want here —
89
+ // each of these is removed on its own.
90
+ const ZERO_WIDTH = /\u200B|\u200C|\u200D|\u200E|\u200F|\u2060|\uFEFF/g;
91
+
92
+ /**
93
+ * Apply only the lossless normalisations.
94
+ *
95
+ * @param {string} text
96
+ * @param {{collapseWhitespace?: boolean}} [options]
97
+ * @returns {string}
98
+ */
99
+ export function normalize(text, { collapseWhitespace = true } = {}) {
100
+ if (typeof text !== 'string' || !text) return '';
101
+
102
+ // NFKC folds the Arabic Presentation Forms (U+FB50-FDFF, U+FE70-FEFF) that
103
+ // appear in text extracted from older PDFs back to their base letters. Those
104
+ // forms are positional glyphs, not distinct letters, and every downstream
105
+ // step — lexicon lookup, edit distance, the script converter — expects base
106
+ // letters.
107
+ let out = text.normalize('NFKC');
108
+
109
+ out = out.replace(ZERO_WIDTH, '');
110
+
111
+ for (const [from, to] of Object.entries(SAFE_REPLACEMENTS)) {
112
+ if (out.includes(from)) out = out.split(from).join(to);
113
+ }
114
+
115
+ if (collapseWhitespace) {
116
+ // OCR routinely emits runs of spaces where the layout had none, and space
117
+ // before punctuation where the glyph spacing confused it.
118
+ out = out
119
+ .replace(/[^\S\n]+/g, ' ')
120
+ .replace(/ +([،؛؟!.:؍])/g, '$1')
121
+ .replace(/\n{3,}/g, '\n\n')
122
+ .split('\n')
123
+ .map((line) => line.trim())
124
+ .join('\n');
125
+ }
126
+
127
+ return out;
128
+ }
129
+
130
+ /**
131
+ * Report which safe normalisations a piece of text would undergo, so the change
132
+ * can be shown rather than merely applied.
133
+ *
134
+ * @param {string} text
135
+ * @returns {Array<{type: string, from: string, to: string, count: number, note: string}>}
136
+ */
137
+ export function describeNormalization(text) {
138
+ if (typeof text !== 'string' || !text) return [];
139
+ const changes = [];
140
+
141
+ const nfkc = text.normalize('NFKC');
142
+ if (nfkc !== text) {
143
+ // Count the characters that actually moved rather than reporting a bare
144
+ // "something changed".
145
+ let moved = 0;
146
+ for (const ch of text) if (ch.normalize('NFKC') !== ch) moved++;
147
+ changes.push({
148
+ type: 'presentation-forms',
149
+ from: '',
150
+ to: '',
151
+ count: moved,
152
+ note: 'Arabic presentation forms folded to base letters.',
153
+ });
154
+ }
155
+
156
+ const zeroWidth = (text.match(ZERO_WIDTH) ?? []).length;
157
+ if (zeroWidth) {
158
+ changes.push({ type: 'zero-width', from: '', to: '', count: zeroWidth, note: 'Zero-width characters removed.' });
159
+ }
160
+
161
+ for (const [from, to] of Object.entries(SAFE_REPLACEMENTS)) {
162
+ const count = countOccurrences(nfkc, from);
163
+ if (count > 0) {
164
+ changes.push({
165
+ type: 'encoding-variant',
166
+ from,
167
+ to,
168
+ count,
169
+ note: to
170
+ ? `${from} replaced with the Uyghur standard ${to}.`
171
+ : `${from} removed.`,
172
+ });
173
+ }
174
+ }
175
+
176
+ return changes;
177
+ }
178
+
179
+ /**
180
+ * Find characters that are not Uyghur letters and cannot be resolved without
181
+ * knowing the word. These become suggestions, never automatic edits.
182
+ *
183
+ * @param {string} text
184
+ * @returns {Array<{index: number, char: string, candidates: string[], note: string}>}
185
+ */
186
+ export function findAmbiguousCharacters(text) {
187
+ if (typeof text !== 'string' || !text) return [];
188
+ const found = [];
189
+
190
+ for (const [char, spec] of Object.entries(AMBIGUOUS_REPLACEMENTS)) {
191
+ let index = text.indexOf(char);
192
+ while (index !== -1) {
193
+ found.push({ index, char, candidates: spec.candidates, note: spec.note });
194
+ index = text.indexOf(char, index + char.length);
195
+ }
196
+ }
197
+
198
+ return found.sort((a, b) => a.index - b.index);
199
+ }
200
+
201
+ function countOccurrences(haystack, needle) {
202
+ if (!needle) return 0;
203
+ return haystack.split(needle).length - 1;
204
+ }