tinyfix-tr 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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +138 -2
  3. package/dist/pkg/src/context.d.ts +13 -0
  4. package/dist/pkg/src/context.js +80 -0
  5. package/dist/pkg/src/data.d.ts +50 -0
  6. package/dist/pkg/src/data.js +495 -0
  7. package/dist/pkg/src/engine.d.ts +39 -0
  8. package/dist/pkg/src/engine.js +357 -0
  9. package/dist/pkg/src/index.d.ts +30 -0
  10. package/dist/pkg/src/index.js +85 -0
  11. package/dist/pkg/src/protocol.d.ts +64 -0
  12. package/dist/pkg/src/protocol.js +1 -0
  13. package/dist/pkg/src/types.d.ts +184 -0
  14. package/dist/pkg/src/types.js +16 -0
  15. package/dist/pkg/src/worker.d.ts +11 -0
  16. package/dist/pkg/src/worker.js +111 -0
  17. package/dist/pkg/src/workerClient.d.ts +3 -0
  18. package/dist/pkg/src/workerClient.js +202 -0
  19. package/dist/src/context-vocab.d.ts +1 -0
  20. package/dist/src/context-vocab.js +2 -0
  21. package/dist/src/context.d.ts +92 -0
  22. package/dist/src/context.js +390 -0
  23. package/dist/src/corrector.d.ts +338 -0
  24. package/dist/src/corrector.js +2684 -0
  25. package/dist/src/known.d.ts +88 -0
  26. package/dist/src/known.js +286 -0
  27. package/dist/src/lexicon-binary.d.ts +85 -0
  28. package/dist/src/lexicon-binary.js +805 -0
  29. package/dist/src/lexicon.d.ts +24 -0
  30. package/dist/src/lexicon.js +79 -0
  31. package/dist/src/morphology/analyzer.d.ts +30 -0
  32. package/dist/src/morphology/analyzer.js +311 -0
  33. package/dist/src/morphology/binary.d.ts +22 -0
  34. package/dist/src/morphology/binary.js +372 -0
  35. package/dist/src/morphology/dictionary.d.ts +21 -0
  36. package/dist/src/morphology/dictionary.js +559 -0
  37. package/dist/src/morphology/fuzzy.d.ts +44 -0
  38. package/dist/src/morphology/fuzzy.js +599 -0
  39. package/dist/src/morphology/index.d.ts +40 -0
  40. package/dist/src/morphology/index.js +81 -0
  41. package/dist/src/morphology/morphotactics.d.ts +148 -0
  42. package/dist/src/morphology/morphotactics.js +1871 -0
  43. package/dist/src/morphology/phonetics.d.ts +71 -0
  44. package/dist/src/morphology/phonetics.js +309 -0
  45. package/dist/src/morphology/prior.d.ts +61 -0
  46. package/dist/src/morphology/prior.js +457 -0
  47. package/dist/src/morphology/types.d.ts +110 -0
  48. package/dist/src/morphology/types.js +32 -0
  49. package/dist/src/rules/proper-names.d.ts +145 -0
  50. package/dist/src/rules/proper-names.js +1217 -0
  51. package/dist/src/rules/turkish-rules.d.ts +126 -0
  52. package/dist/src/rules/turkish-rules.js +365 -0
  53. package/dist/src/sentence.d.ts +83 -0
  54. package/dist/src/sentence.js +2408 -0
  55. package/dist/src/turkish.d.ts +20 -0
  56. package/dist/src/turkish.js +94 -0
  57. package/package.json +60 -4
@@ -0,0 +1,559 @@
1
+ /**
2
+ * Zemberek .dict parser, Turkish root attribute inference, and stem transition generator.
3
+ * Adapted from Zemberek's TextDictionaryLoader and StemTransitionsBase (Apache 2.0).
4
+ */
5
+ import { lowerTr } from "../turkish.js";
6
+ import { PA_CANNOT_TERMINATE, PA_EXPECTS_CONSONANT, PA_EXPECTS_VOWEL, PA_LAST_LETTER_DROPPED, PA_LAST_VOICED, PA_LAST_VOICELESS, PA_LAST_VOICELESS_STOP, PA_MODIFIED_PRONOUN, PA_UNMODIFIED_PRONOUN, PA_VOWEL_BACK, PA_VOWEL_FRONT, computePhoneticAttributes, containsVowel, countVowels, isVowel, isVoicelessStop, normalizeCircumflex, voiceChar, } from "./phonetics.js";
7
+ import { RA_AORIST_A, RA_AORIST_I, RA_CAUSATIVE_T, RA_COMPOUND_P3SG, RA_COMPOUND_P3SG_ROOT, RA_DOUBLING, RA_DUMMY, RA_EXT, RA_FAMILY_MEMBER, RA_IMPLICIT_DATIVE, RA_IMPLICIT_P1SG, RA_IMPLICIT_P2SG, RA_IMPLICIT_PLURAL, RA_INFORMAL, RA_INVERSE_HARMONY, RA_LAST_VOWEL_DROP, RA_NONE, RA_NON_RECIPROCAL, RA_NOUN_CONS_INSERT_N, RA_NO_SUFFIX, RA_NO_VOICING, RA_PASSIVE_IN, RA_PROGRESSIVE_VOWEL_DROP, RA_RECIPROCAL, RA_REFLEXIVE, RA_VOICING, RA_VOICING_OPT, } from "./types.js";
8
+ const PRIMARY_POS_MAP = {
9
+ Noun: "Noun",
10
+ Adj: "Adj",
11
+ Adjective: "Adj",
12
+ Verb: "Verb",
13
+ Pron: "Pron",
14
+ Pronoun: "Pron",
15
+ Adv: "Adv",
16
+ Adverb: "Adv",
17
+ Conj: "Conj",
18
+ Conjunction: "Conj",
19
+ Ques: "Ques",
20
+ Question: "Ques",
21
+ Postp: "Postp",
22
+ PostPositive: "Postp",
23
+ Det: "Det",
24
+ Determiner: "Det",
25
+ Num: "Num",
26
+ Numeral: "Num",
27
+ Dup: "Dup",
28
+ Duplicator: "Dup",
29
+ Interj: "Interj",
30
+ Interjection: "Interj",
31
+ Punc: "Punc",
32
+ Punctuation: "Punc",
33
+ };
34
+ const SECONDARY_POS_MAP = {
35
+ Prop: "ProperNoun",
36
+ ProperNoun: "ProperNoun",
37
+ Abbrv: "Abbreviation",
38
+ Abbreviation: "Abbreviation",
39
+ Time: "Time",
40
+ Pers: "PersonalPron",
41
+ PersonalPron: "PersonalPron",
42
+ Demons: "DemonstrativePron",
43
+ DemonstrativePron: "DemonstrativePron",
44
+ Quant: "QuantitivePron",
45
+ QuantitivePron: "QuantitivePron",
46
+ Ques: "QuestionPron",
47
+ QuestionPron: "QuestionPron",
48
+ Reflex: "ReflexivePron",
49
+ ReflexivePron: "ReflexivePron",
50
+ Card: "Card",
51
+ Ord: "Ord",
52
+ Dist: "Dist",
53
+ PCDat: "PCDat",
54
+ PCAbl: "PCAbl",
55
+ PCNom: "PCNom",
56
+ PCGen: "PCGen",
57
+ PCIns: "PCIns",
58
+ PCAcc: "PCAcc",
59
+ };
60
+ const ROOT_ATTR_MAP = {
61
+ Voicing: RA_VOICING,
62
+ NoVoicing: RA_NO_VOICING,
63
+ VoicingOpt: RA_VOICING_OPT,
64
+ InverseHarmony: RA_INVERSE_HARMONY,
65
+ Doubling: RA_DOUBLING,
66
+ LastVowelDrop: RA_LAST_VOWEL_DROP,
67
+ CompoundP3sg: RA_COMPOUND_P3SG,
68
+ CompoundP3sgRoot: RA_COMPOUND_P3SG_ROOT,
69
+ NoSuffix: RA_NO_SUFFIX,
70
+ ProgressiveVowelDrop: RA_PROGRESSIVE_VOWEL_DROP,
71
+ Aorist_I: RA_AORIST_I,
72
+ Aorist_A: RA_AORIST_A,
73
+ Passive_In: RA_PASSIVE_IN,
74
+ Causative_t: RA_CAUSATIVE_T,
75
+ ImplicitPlural: RA_IMPLICIT_PLURAL,
76
+ ImplicitDative: RA_IMPLICIT_DATIVE,
77
+ ImplicitP1sg: RA_IMPLICIT_P1SG,
78
+ ImplicitP2sg: RA_IMPLICIT_P2SG,
79
+ FamilyMember: RA_FAMILY_MEMBER,
80
+ Reciprocal: RA_RECIPROCAL,
81
+ NonReciprocal: RA_NON_RECIPROCAL,
82
+ Reflexive: RA_REFLEXIVE,
83
+ Dummy: RA_DUMMY,
84
+ NounConsInsert_n: RA_NOUN_CONS_INSERT_N,
85
+ Ext: RA_EXT,
86
+ Informal: RA_INFORMAL,
87
+ };
88
+ /**
89
+ * Known non-TDK entries and typos present inside Zemberek's master-dictionary.dict
90
+ * (mostly from manually appended adverb/interjection blocks at the end of the file).
91
+ * Excluded so the autocorrector does not treat common joined/colloquial misspellings as valid.
92
+ */
93
+ const EXCLUDED_NON_TDK_LEMMAS = new Set([
94
+ "afedersin",
95
+ "afedersinin",
96
+ "ardarda",
97
+ "birara",
98
+ "birarada",
99
+ "çöğunlukla",
100
+ "elele",
101
+ "herbiri",
102
+ "herzaman",
103
+ "ilerde",
104
+ "keşki",
105
+ "kolkola",
106
+ "yanısıra",
107
+ ]);
108
+ function makeKey(rootLemma, primaryPos, secondaryPos) {
109
+ return secondaryPos === "None" ? `${rootLemma}_${primaryPos}` : `${rootLemma}_${primaryPos}_${secondaryPos}`;
110
+ }
111
+ function inferAttributes(root, primaryPos, secondaryPos, attrs) {
112
+ let out = attrs;
113
+ const len = root.length;
114
+ if (len === 0)
115
+ return out;
116
+ const last = root[len - 1] ?? "";
117
+ const prev = len > 1 ? (root[len - 2] ?? "") : "";
118
+ const vowels = countVowels(root);
119
+ if (primaryPos === "Verb") {
120
+ // Special verbs handled separately in StemTransitions / Morphotactics.
121
+ if (root === "de" || root === "ye" || root === "i" || root === "değil") {
122
+ return out;
123
+ }
124
+ // Progressive vowel drop: verb stems ending in a vowel (ara -> ar-ıyor, bekle -> bekl-iyor).
125
+ if (isVowel(last)) {
126
+ out |= RA_PROGRESSIVE_VOWEL_DROP;
127
+ }
128
+ // Aorist: default single-syllable -> -Ar, multi-syllable -> -Ir (unless explicitly tagged).
129
+ if ((out & (RA_AORIST_A | RA_AORIST_I)) === 0) {
130
+ if (vowels <= 1 && !isVowel(last)) {
131
+ out |= RA_AORIST_A;
132
+ }
133
+ else {
134
+ out |= RA_AORIST_I;
135
+ }
136
+ }
137
+ // Passive: vowel-final or l-final stems take -In/-InIl; others take +nIl.
138
+ if (isVowel(last) || last === "l") {
139
+ out |= RA_PASSIVE_IN;
140
+ }
141
+ // Causative -t: vowel-final stems, or multi-syllable stems ending in r or l.
142
+ if (isVowel(last) || (vowels > 1 && (last === "r" || last === "l"))) {
143
+ out |= RA_CAUSATIVE_T;
144
+ }
145
+ return out;
146
+ }
147
+ // Non-verb automatic consonant voicing (kitap -> kitab, ağaç -> ağac, renk -> reng, psikolog -> psikoloğ).
148
+ // Proper nouns and abbreviations do not soften in standard Turkish orthography unless explicitly tagged.
149
+ if ((primaryPos === "Noun" || primaryPos === "Adj" || primaryPos === "Num" || primaryPos === "Pron") &&
150
+ secondaryPos !== "ProperNoun" &&
151
+ secondaryPos !== "Abbreviation" &&
152
+ (out & (RA_VOICING | RA_NO_VOICING | RA_VOICING_OPT | RA_DOUBLING | RA_INVERSE_HARMONY | RA_NO_SUFFIX | RA_COMPOUND_P3SG)) === 0) {
153
+ const endsWithNk = len >= 2 && prev === "n" && last === "k";
154
+ const endsWithVowelG = len >= 2 && isVowel(prev) && last === "g";
155
+ if (endsWithNk) {
156
+ out |= RA_VOICING;
157
+ }
158
+ else if (vowels > 1 && (isVoicelessStop(last) || endsWithVowelG)) {
159
+ out |= RA_VOICING;
160
+ }
161
+ }
162
+ return out;
163
+ }
164
+ /**
165
+ * Parses one or more Zemberek `.dict` text payloads into DictionaryItems.
166
+ * Entries marked `A:Informal` or `A:Ext` (non-TDK noisy/colloquial spellings) and
167
+ * `P:Punc` entries are skipped to preserve high spellchecking precision.
168
+ */
169
+ export function parseDictionaries(texts) {
170
+ const items = [];
171
+ const byKey = new Map();
172
+ const pendingRefs = [];
173
+ for (const text of texts) {
174
+ let start = 0;
175
+ const n = text.length;
176
+ while (start <= n) {
177
+ let end = text.indexOf("\n", start);
178
+ if (end === -1)
179
+ end = n;
180
+ let lineEnd = end;
181
+ if (lineEnd > start && text.charCodeAt(lineEnd - 1) === 13) {
182
+ lineEnd--;
183
+ }
184
+ const rawLine = text.slice(start, lineEnd).trim();
185
+ start = end + 1;
186
+ if (rawLine.length === 0 || rawLine.charCodeAt(0) === 35 /* '#' */) {
187
+ continue;
188
+ }
189
+ const bracketIdx = rawLine.indexOf("[");
190
+ const rawLemma = (bracketIdx === -1 ? rawLine : rawLine.slice(0, bracketIdx)).trim();
191
+ if (rawLemma.length === 0)
192
+ continue;
193
+ let primaryPos = null;
194
+ let secondaryPos = "None";
195
+ let attrs = RA_NONE;
196
+ let rawPron = "";
197
+ let rawRoots = "";
198
+ let refSpec = "";
199
+ let index = 0;
200
+ if (bracketIdx !== -1) {
201
+ const closeIdx = rawLine.lastIndexOf("]");
202
+ const meta = closeIdx > bracketIdx ? rawLine.slice(bracketIdx + 1, closeIdx) : rawLine.slice(bracketIdx + 1);
203
+ let segStart = 0;
204
+ while (segStart <= meta.length) {
205
+ let segEnd = meta.indexOf(";", segStart);
206
+ if (segEnd === -1)
207
+ segEnd = meta.length;
208
+ const seg = meta.slice(segStart, segEnd).trim();
209
+ segStart = segEnd + 1;
210
+ if (seg.length === 0)
211
+ continue;
212
+ const colon = seg.indexOf(":");
213
+ if (colon === -1)
214
+ continue;
215
+ const tag = seg.slice(0, colon).trim();
216
+ const val = seg.slice(colon + 1).trim();
217
+ if (tag === "P") {
218
+ const comma = val.indexOf(",");
219
+ if (comma === -1) {
220
+ const p = PRIMARY_POS_MAP[val];
221
+ if (p !== undefined)
222
+ primaryPos = p;
223
+ }
224
+ else {
225
+ const p1 = val.slice(0, comma).trim();
226
+ const p2 = val.slice(comma + 1).trim();
227
+ const mapped1 = PRIMARY_POS_MAP[p1];
228
+ if (mapped1 !== undefined)
229
+ primaryPos = mapped1;
230
+ const mapped2 = SECONDARY_POS_MAP[p2];
231
+ if (mapped2 !== undefined)
232
+ secondaryPos = mapped2;
233
+ }
234
+ }
235
+ else if (tag === "A") {
236
+ let aStart = 0;
237
+ while (aStart <= val.length) {
238
+ let aEnd = val.indexOf(",", aStart);
239
+ if (aEnd === -1)
240
+ aEnd = val.length;
241
+ const attrName = val.slice(aStart, aEnd).trim();
242
+ aStart = aEnd + 1;
243
+ if (attrName.length === 0)
244
+ continue;
245
+ const bit = ROOT_ATTR_MAP[attrName];
246
+ if (bit !== undefined)
247
+ attrs |= bit;
248
+ }
249
+ }
250
+ else if (tag === "Pr" || tag === "pr") {
251
+ rawPron = val;
252
+ }
253
+ else if (tag === "Roots") {
254
+ rawRoots = val;
255
+ }
256
+ else if (tag === "Index") {
257
+ const parsed = Number.parseInt(val, 10);
258
+ if (!Number.isNaN(parsed))
259
+ index = parsed;
260
+ }
261
+ else if (tag === "Ref") {
262
+ refSpec = val;
263
+ }
264
+ }
265
+ }
266
+ // Skip punctuation, informal spellings, and non-TDK [A:Ext] entries.
267
+ if (primaryPos === "Punc" || (attrs & (RA_INFORMAL | RA_EXT)) !== 0) {
268
+ continue;
269
+ }
270
+ const lowerLemma = lowerTr(rawLemma);
271
+ const normLemma = normalizeCircumflex(lowerLemma);
272
+ if (EXCLUDED_NON_TDK_LEMMAS.has(normLemma)) {
273
+ continue;
274
+ }
275
+ // Default POS inference.
276
+ if (primaryPos === null) {
277
+ if (normLemma.length > 3 && (normLemma.endsWith("mak") || normLemma.endsWith("mek"))) {
278
+ primaryPos = "Verb";
279
+ }
280
+ else {
281
+ primaryPos = "Noun";
282
+ const firstRaw = rawLemma[0] ?? "";
283
+ if (firstRaw !== lowerTr(firstRaw)) {
284
+ secondaryPos = "ProperNoun";
285
+ }
286
+ }
287
+ }
288
+ const root = primaryPos === "Verb" && normLemma.length > 3 && (normLemma.endsWith("mak") || normLemma.endsWith("mek"))
289
+ ? normLemma.slice(0, -3)
290
+ : normLemma;
291
+ const pronunciation = rawPron.length > 0 ? normalizeCircumflex(lowerTr(rawPron)) : root;
292
+ const inferredAttrs = inferAttributes(root, primaryPos, secondaryPos, attrs);
293
+ const key = makeKey(normLemma, primaryPos, secondaryPos);
294
+ const item = {
295
+ key,
296
+ lemma: lowerLemma,
297
+ root,
298
+ pronunciation,
299
+ primaryPos,
300
+ secondaryPos,
301
+ attributes: inferredAttrs,
302
+ index,
303
+ referenceItem: null,
304
+ };
305
+ items.push(item);
306
+ const lowerKey = lowerTr(key);
307
+ if (index === 0 && !byKey.has(lowerKey)) {
308
+ byKey.set(lowerKey, item);
309
+ }
310
+ if (refSpec.length > 0) {
311
+ pendingRefs.push({ item, refKey: normalizeCircumflex(lowerTr(refSpec)) });
312
+ }
313
+ // Generate dummy CompoundP3sgRoot stem for compound nouns with Roots:r1-r2
314
+ // (e.g. zeytinyağı [A:CompoundP3sg; Roots:zeytin-yağ] -> dummy root "zeytinyağ").
315
+ if ((inferredAttrs & RA_COMPOUND_P3SG) !== 0 && rawRoots.length > 0 && primaryPos === "Noun") {
316
+ const dashIdx = rawRoots.indexOf("-");
317
+ if (dashIdx > 0 && dashIdx < rawRoots.length - 1) {
318
+ const compoundRoot = normalizeCircumflex(lowerTr(rawRoots.slice(0, dashIdx) + rawRoots.slice(dashIdx + 1)));
319
+ if (compoundRoot.length > 0 && compoundRoot !== root) {
320
+ const dummyItem = {
321
+ key: `${compoundRoot}_Noun_CompoundRoot`,
322
+ lemma: lowerLemma,
323
+ root: compoundRoot,
324
+ pronunciation: compoundRoot,
325
+ primaryPos: "Noun",
326
+ secondaryPos: "None",
327
+ attributes: RA_COMPOUND_P3SG_ROOT | RA_DUMMY | (inferredAttrs & RA_INVERSE_HARMONY),
328
+ index: 0,
329
+ referenceItem: item,
330
+ };
331
+ items.push(dummyItem);
332
+ }
333
+ }
334
+ }
335
+ }
336
+ }
337
+ // Resolve Ref: links (e.g. non-dropped LastVowelDrop variants or circumflex variants).
338
+ for (const { item, refKey } of pendingRefs) {
339
+ const direct = byKey.get(refKey);
340
+ if (direct !== undefined) {
341
+ item.referenceItem = direct;
342
+ }
343
+ else {
344
+ const posFallback = byKey.get(`${refKey}_${lowerTr(item.primaryPos)}`);
345
+ if (posFallback !== undefined) {
346
+ item.referenceItem = posFallback;
347
+ }
348
+ }
349
+ }
350
+ return items;
351
+ }
352
+ const MODIFIER_ATTR_MASK = RA_DOUBLING |
353
+ RA_LAST_VOWEL_DROP |
354
+ RA_PROGRESSIVE_VOWEL_DROP |
355
+ RA_INVERSE_HARMONY |
356
+ RA_VOICING |
357
+ RA_COMPOUND_P3SG |
358
+ RA_COMPOUND_P3SG_ROOT;
359
+ const SPECIAL_ROOT_KEYS = new Set([
360
+ "ben_Pron_PersonalPron",
361
+ "sen_Pron_PersonalPron",
362
+ "demek_Verb",
363
+ "yemek_Verb",
364
+ "imek_Verb",
365
+ "birbiri_Pron_QuantitivePron",
366
+ "çoğu_Pron_QuantitivePron",
367
+ "öbürü_Pron_QuantitivePron",
368
+ "birçoğu_Pron_QuantitivePron",
369
+ ]);
370
+ function isNonDroppedLastVowelDropVariant(item) {
371
+ const ref = item.referenceItem;
372
+ return (ref !== null &&
373
+ (ref.attributes & RA_LAST_VOWEL_DROP) !== 0 &&
374
+ (item.attributes & RA_LAST_VOWEL_DROP) === 0 &&
375
+ item.root === ref.root);
376
+ }
377
+ function generateSpecialRootTransitions(item, graph) {
378
+ const origAttrs = computePhoneticAttributes(item.pronunciation);
379
+ const unmodifiedState = graph.getRootState(item, origAttrs);
380
+ switch (item.key) {
381
+ case "ben_Pron_PersonalPron":
382
+ case "sen_Pron_PersonalPron": {
383
+ const modSurface = item.root === "ben" ? "ban" : "san";
384
+ const orig = {
385
+ surface: item.root,
386
+ item,
387
+ phonetic: origAttrs | PA_UNMODIFIED_PRONOUN,
388
+ to: unmodifiedState,
389
+ };
390
+ const mod = {
391
+ surface: modSurface,
392
+ item,
393
+ phonetic: computePhoneticAttributes(modSurface) | PA_MODIFIED_PRONOUN,
394
+ to: graph.pronPers_Mod_S,
395
+ };
396
+ return [orig, mod];
397
+ }
398
+ case "demek_Verb":
399
+ case "yemek_Verb": {
400
+ const modSurface = item.root === "de" ? "di" : "yi";
401
+ return [
402
+ { surface: item.root, item, phonetic: origAttrs, to: graph.vDeYeRoot_S },
403
+ { surface: modSurface, item, phonetic: computePhoneticAttributes(modSurface), to: graph.vDeYeRoot_S },
404
+ ];
405
+ }
406
+ case "imek_Verb":
407
+ return [{ surface: item.root, item, phonetic: origAttrs, to: graph.imekRoot_S }];
408
+ case "birbiri_Pron_QuantitivePron":
409
+ case "çoğu_Pron_QuantitivePron":
410
+ case "öbürü_Pron_QuantitivePron":
411
+ case "birçoğu_Pron_QuantitivePron": {
412
+ let modSurface;
413
+ if (item.root === "birbiri")
414
+ modSurface = "birbir";
415
+ else if (item.root === "çoğu")
416
+ modSurface = "çok";
417
+ else if (item.root === "öbürü")
418
+ modSurface = "öbür";
419
+ else
420
+ modSurface = "birçok";
421
+ return [
422
+ {
423
+ surface: item.root,
424
+ item,
425
+ phonetic: origAttrs | PA_UNMODIFIED_PRONOUN,
426
+ to: graph.pronQuant_S,
427
+ },
428
+ {
429
+ surface: modSurface,
430
+ item,
431
+ phonetic: computePhoneticAttributes(modSurface) | PA_MODIFIED_PRONOUN,
432
+ to: graph.pronQuantModified_S,
433
+ },
434
+ ];
435
+ }
436
+ default:
437
+ return [{ surface: item.root, item, phonetic: origAttrs, to: unmodifiedState }];
438
+ }
439
+ }
440
+ function generateStemTransitions(item, graph) {
441
+ if (SPECIAL_ROOT_KEYS.has(item.key)) {
442
+ return generateSpecialRootTransitions(item, graph);
443
+ }
444
+ if ((item.attributes & MODIFIER_ATTR_MASK) === 0) {
445
+ let phonetic = computePhoneticAttributes(item.pronunciation);
446
+ if (isNonDroppedLastVowelDropVariant(item)) {
447
+ phonetic |= PA_EXPECTS_VOWEL | PA_CANNOT_TERMINATE;
448
+ }
449
+ return [
450
+ {
451
+ surface: item.root,
452
+ item,
453
+ phonetic,
454
+ to: graph.getRootState(item, phonetic),
455
+ },
456
+ ];
457
+ }
458
+ let modifiedSeq = item.root;
459
+ let originalAttrs = computePhoneticAttributes(item.pronunciation);
460
+ let modifiedAttrs = originalAttrs;
461
+ let unmodifiedRootState = null;
462
+ let modifiedRootState = null;
463
+ // Apply Voicing BEFORE Doubling (ret -> red -> redd, tıp -> tıb -> tıbb, zıt -> zıd -> zıdd).
464
+ if ((item.attributes & RA_VOICING) !== 0 && modifiedSeq.length > 0) {
465
+ const last = modifiedSeq[modifiedSeq.length - 1] ?? "";
466
+ const voiced = modifiedSeq.endsWith("nk") ? "g" : voiceChar(last);
467
+ if (voiced !== last) {
468
+ modifiedSeq = modifiedSeq.slice(0, -1) + voiced;
469
+ modifiedAttrs &= ~(PA_LAST_VOICELESS_STOP | PA_LAST_VOICELESS);
470
+ modifiedAttrs |= PA_LAST_VOICED | PA_EXPECTS_VOWEL | PA_CANNOT_TERMINATE;
471
+ originalAttrs |= PA_EXPECTS_CONSONANT;
472
+ }
473
+ }
474
+ if ((item.attributes & RA_DOUBLING) !== 0 && modifiedSeq.length > 0) {
475
+ const last = modifiedSeq[modifiedSeq.length - 1] ?? "";
476
+ modifiedSeq = modifiedSeq + last;
477
+ originalAttrs |= PA_EXPECTS_CONSONANT;
478
+ modifiedAttrs |= PA_EXPECTS_VOWEL | PA_CANNOT_TERMINATE;
479
+ }
480
+ if ((item.attributes & RA_LAST_VOWEL_DROP) !== 0 && modifiedSeq.length >= 2) {
481
+ const last = modifiedSeq[modifiedSeq.length - 1] ?? "";
482
+ if (!isVowel(last)) {
483
+ modifiedSeq = modifiedSeq.slice(0, -2) + last;
484
+ if (item.primaryPos !== "Verb") {
485
+ originalAttrs |= PA_EXPECTS_CONSONANT;
486
+ }
487
+ else {
488
+ unmodifiedRootState = graph.verbLastVowelDropUnmodRoot_S;
489
+ modifiedRootState = graph.verbLastVowelDropModRoot_S;
490
+ }
491
+ modifiedAttrs |= PA_EXPECTS_VOWEL | PA_CANNOT_TERMINATE;
492
+ }
493
+ }
494
+ if ((item.attributes & RA_INVERSE_HARMONY) !== 0) {
495
+ originalAttrs = (originalAttrs & ~PA_VOWEL_BACK) | PA_VOWEL_FRONT;
496
+ modifiedAttrs = (modifiedAttrs & ~PA_VOWEL_BACK) | PA_VOWEL_FRONT;
497
+ }
498
+ if ((item.attributes & RA_PROGRESSIVE_VOWEL_DROP) !== 0 && modifiedSeq.length > 1) {
499
+ modifiedSeq = modifiedSeq.slice(0, -1);
500
+ if (containsVowel(modifiedSeq)) {
501
+ modifiedAttrs = computePhoneticAttributes(modifiedSeq);
502
+ }
503
+ modifiedAttrs |= PA_LAST_LETTER_DROPPED;
504
+ }
505
+ const unmodState = unmodifiedRootState ?? graph.getRootState(item, originalAttrs);
506
+ const modState = modifiedRootState ?? graph.getRootState(item, modifiedAttrs);
507
+ const original = {
508
+ surface: item.root,
509
+ item,
510
+ phonetic: originalAttrs,
511
+ to: unmodState,
512
+ };
513
+ const modified = {
514
+ surface: modifiedSeq,
515
+ item,
516
+ phonetic: modifiedAttrs,
517
+ to: modState,
518
+ };
519
+ if (original.surface === modified.surface && original.phonetic === modified.phonetic && original.to === modified.to) {
520
+ return [original];
521
+ }
522
+ if (isNonDroppedLastVowelDropVariant(item) && (item.attributes & RA_VOICING) !== 0) {
523
+ return [modified];
524
+ }
525
+ return [original, modified];
526
+ }
527
+ /**
528
+ * Generates all surface stem transitions for the parsed dictionary items and indexes
529
+ * them in a compact Map (single transitions stored directly without wrapper arrays).
530
+ */
531
+ export function buildStemIndex(items, graph) {
532
+ const stems = new Map();
533
+ let maxStemLength = 0;
534
+ for (let i = 0; i < items.length; i++) {
535
+ const item = items[i];
536
+ if (item === undefined || item.root.length === 0)
537
+ continue;
538
+ const transitions = generateStemTransitions(item, graph);
539
+ for (let j = 0; j < transitions.length; j++) {
540
+ const tr = transitions[j];
541
+ if (tr === undefined || tr.surface.length === 0)
542
+ continue;
543
+ if (tr.surface.length > maxStemLength) {
544
+ maxStemLength = tr.surface.length;
545
+ }
546
+ const existing = stems.get(tr.surface);
547
+ if (existing === undefined) {
548
+ stems.set(tr.surface, tr);
549
+ }
550
+ else if (Array.isArray(existing)) {
551
+ existing.push(tr);
552
+ }
553
+ else {
554
+ stems.set(tr.surface, [existing, tr]);
555
+ }
556
+ }
557
+ }
558
+ return { stems, maxStemLength };
559
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Fast, error-tolerant morphological search over Zemberek's StemIndex + Morphotactics FST.
3
+ *
4
+ * Finds morphologically valid Turkish words within 1 or 2 Damerau-Levenshtein edits (plus
5
+ * arbitrary Turkish diacritic restoration) — including completely unseen inflected forms
6
+ * like "düzenlemiyor" from "duzenblemiyor" or "duzenlemniyor", and double omissions like
7
+ * "grkli" -> "gerekli" or "beketiyruz" -> "bekletiyoruz".
8
+ *
9
+ * Key performance techniques:
10
+ * - Lazy compact mark-folded stem trie built in RAM from StemIndex (~10 ms, 0 bytes on disk).
11
+ * - Banded Damerau-Levenshtein DP on a preallocated flat Uint8Array slab (zero heap allocations).
12
+ * - Zero-remaining-edits exact mark-folded suffix fast path inside the FST.
13
+ * - Lemma-frequency-prioritized stem ordering and bounded FST expansion + LRU result cache.
14
+ */
15
+ import type { MorphologicalAnalyzer } from "./analyzer.ts";
16
+ import type { StemIndex } from "./dictionary.ts";
17
+ import type { MorphPrior } from "./prior.ts";
18
+ export interface FuzzyMorphCandidate {
19
+ /** Morphologically valid lowercase Turkish word. */
20
+ readonly word: string;
21
+ /** Mark-folded Damerau-Levenshtein edit distance (0 = mark restoration only, 1 or 2 = edits). */
22
+ readonly foldedEdits: number;
23
+ /** Rich Turkish Q-keyboard + mark-loss edit cost. */
24
+ readonly editCost: number;
25
+ }
26
+ /**
27
+ * Exact Turkish Q-keyboard + mark-loss + transposition edit cost between `typed` and `cand`.
28
+ * Lower is closer; ~0.35 for a missing Turkish mark, ~0.6-0.95 for a single typo, ~1.2-1.8 for two errors.
29
+ */
30
+ export declare function turkishEditCost(typed: string, cand: string): number;
31
+ export declare class FuzzyMorphSearch {
32
+ private readonly analyzer;
33
+ private readonly prior?;
34
+ private readonly root;
35
+ private readonly dpSlab;
36
+ private readonly wordCodes;
37
+ private readonly cache;
38
+ constructor(stemIndex: StemIndex, analyzer: MorphologicalAnalyzer, prior?: MorphPrior);
39
+ /**
40
+ * Finds valid Turkish words within `maxEdits` (1 or 2) mark-folded Damerau-Levenshtein edits of `form`.
41
+ * Results are verified via `analyzer.isWord()` and sorted by `editCost` ascending.
42
+ */
43
+ search(form: string, maxEdits?: number, maxResults?: number): readonly FuzzyMorphCandidate[];
44
+ }