tinyfix-tr 0.0.0-stage → 0.1.1

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 +139 -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 +53 -0
  6. package/dist/pkg/src/data.js +498 -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,599 @@
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 { areNearKeys, lowerTr } from "../turkish.js";
16
+ import { PA_CANNOT_TERMINATE, computeNextPhoneticAttrs, generateSurface, surfaceCacheKey, } from "./phonetics.js";
17
+ const MAX_WORD_LEN = 48;
18
+ const MAX_FUZZY_CACHE = 4096;
19
+ const INF_DIST = 99;
20
+ const VOWELS = new Set(["a", "e", "ı", "i", "o", "ö", "u", "ü"]);
21
+ const VOICING_PAIRS = new Set(["dt", "td", "bp", "pb", "cç", "çc", "gk", "kg", "gğ", "ğg"]);
22
+ const MARK_RESTORE_PAIRS = new Set(["cç", "gğ", "iı", "oö", "sş", "uü"]);
23
+ const MARK_STRIP_PAIRS = new Set(["çc", "ğg", "ıi", "öo", "şs", "üu"]);
24
+ const TURKISH_MARKS = new Set(["ç", "ğ", "ı", "ö", "ş", "ü"]);
25
+ /** Maps lowercase Turkish characters (and circumflexes) to ASCII codes 0..25 (26 = other). */
26
+ const FOLD_CODE = new Uint8Array(65536).fill(26);
27
+ for (let c = 97; c <= 122; c++)
28
+ FOLD_CODE[c] = c - 97; // a..z
29
+ FOLD_CODE["ç".charCodeAt(0)] = "c".charCodeAt(0) - 97;
30
+ FOLD_CODE["ğ".charCodeAt(0)] = "g".charCodeAt(0) - 97;
31
+ FOLD_CODE["ı".charCodeAt(0)] = "i".charCodeAt(0) - 97;
32
+ FOLD_CODE["ö".charCodeAt(0)] = "o".charCodeAt(0) - 97;
33
+ FOLD_CODE["ş".charCodeAt(0)] = "s".charCodeAt(0) - 97;
34
+ FOLD_CODE["ü".charCodeAt(0)] = "u".charCodeAt(0) - 97;
35
+ FOLD_CODE["â".charCodeAt(0)] = "a".charCodeAt(0) - 97;
36
+ FOLD_CODE["î".charCodeAt(0)] = "i".charCodeAt(0) - 97;
37
+ FOLD_CODE["û".charCodeAt(0)] = "u".charCodeAt(0) - 97;
38
+ function charSubCost(typedCh, candCh, typedIndex) {
39
+ if (typedCh === candCh)
40
+ return 0;
41
+ const pair = typedCh + candCh;
42
+ if (MARK_RESTORE_PAIRS.has(pair) || (typedIndex === 0 && typedCh === "ı" && candCh === "i")) {
43
+ return 0.35;
44
+ }
45
+ if (MARK_STRIP_PAIRS.has(pair)) {
46
+ return 1.25;
47
+ }
48
+ const lead = typedIndex === 0 ? 0.45 : 0;
49
+ if (areNearKeys(typedCh, candCh))
50
+ return 0.8 + lead;
51
+ if (VOWELS.has(typedCh) && VOWELS.has(candCh))
52
+ return 1.1 + lead;
53
+ if (VOICING_PAIRS.has(pair))
54
+ return 1.25 + lead;
55
+ return 1.8 + lead;
56
+ }
57
+ /**
58
+ * Exact Turkish Q-keyboard + mark-loss + transposition edit cost between `typed` and `cand`.
59
+ * 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.
60
+ */
61
+ export function turkishEditCost(typed, cand) {
62
+ const m = typed.length;
63
+ const n = cand.length;
64
+ if (m === 0)
65
+ return n;
66
+ if (n === 0)
67
+ return m;
68
+ if (typed === cand)
69
+ return 0;
70
+ const stride = n + 1;
71
+ const dp = new Float64Array((m + 1) * stride);
72
+ for (let i = 1; i <= m; i++) {
73
+ const ch = typed[i - 1];
74
+ const prev = i > 1 ? typed[i - 2] : undefined;
75
+ const next = i < m ? typed[i] : undefined;
76
+ const isDup = ch === prev || ch === next;
77
+ const isNear = (prev !== undefined && areNearKeys(ch, prev)) || (next !== undefined && areNearKeys(ch, next));
78
+ const delCost = isDup ? 0.65 : isNear ? 0.85 : TURKISH_MARKS.has(ch) ? 2.4 : 1.9;
79
+ dp[i * stride] = dp[(i - 1) * stride] + delCost + (i === 1 ? 0.45 : 0);
80
+ }
81
+ for (let j = 1; j <= n; j++) {
82
+ const ch = cand[j - 1];
83
+ const isDup = j > 1 && ch === cand[j - 2];
84
+ const insCost = isDup ? 0.65 : 0.95;
85
+ dp[j] = dp[j - 1] + insCost + (j === 1 ? 0.45 : 0);
86
+ }
87
+ for (let i = 1; i <= m; i++) {
88
+ const tc = typed[i - 1];
89
+ const tPrev = i > 1 ? typed[i - 2] : undefined;
90
+ const tNext = i < m ? typed[i] : undefined;
91
+ const isDupDel = tc === tPrev || tc === tNext;
92
+ const isNearDel = (tPrev !== undefined && areNearKeys(tc, tPrev)) || (tNext !== undefined && areNearKeys(tc, tNext));
93
+ const delCost = (isDupDel ? 0.65 : isNearDel ? 0.85 : TURKISH_MARKS.has(tc) ? 2.4 : 1.9) + (i === 1 ? 0.45 : 0);
94
+ const rowOff = i * stride;
95
+ const prevOff = (i - 1) * stride;
96
+ for (let j = 1; j <= n; j++) {
97
+ const cc = cand[j - 1];
98
+ const sub = dp[prevOff + j - 1] + charSubCost(tc, cc, i - 1);
99
+ const del = dp[prevOff + j] + delCost;
100
+ // Insertion of cc into typed between typed[i-1] and typed[i] (missing letter in typed).
101
+ const betweenConsonants = tNext !== undefined && !VOWELS.has(tc) && !VOWELS.has(tNext);
102
+ const isDupIns = cc === tc || cc === tNext;
103
+ const insBase = betweenConsonants && VOWELS.has(cc) ? 0.6 : isDupIns ? 0.65 : 0.95;
104
+ const ins = dp[rowOff + j - 1] + insBase;
105
+ let best = sub < del ? (sub < ins ? sub : ins) : del < ins ? del : ins;
106
+ // Adjacent transposition (also allowing mark restoration on the swapped letters).
107
+ if (i >= 2 && j >= 2) {
108
+ const tcPrev = typed[i - 2];
109
+ const ccPrev = cand[j - 2];
110
+ const c1 = charSubCost(tcPrev, cc, i - 2);
111
+ const c2 = charSubCost(tc, ccPrev, i - 1);
112
+ if (c1 <= 0.35 && c2 <= 0.35) {
113
+ const trans = dp[(i - 2) * stride + j - 2] + 0.7 + c1 + c2 + (i === 2 ? 0.35 : 0);
114
+ if (trans < best)
115
+ best = trans;
116
+ }
117
+ }
118
+ dp[rowOff + j] = best;
119
+ }
120
+ }
121
+ return dp[m * stride + n];
122
+ }
123
+ function resolveSurfaceAndNextPhonetic(tr, phonetic) {
124
+ const key = surfaceCacheKey(phonetic);
125
+ let surface = tr.surfaceCache[key];
126
+ if (surface === undefined) {
127
+ const generated = generateSurface(tr.tokens, phonetic);
128
+ tr.surfaceCache[key] = generated;
129
+ if (generated !== null) {
130
+ tr.nextPhoneticCache[key] = computeNextPhoneticAttrs(generated, phonetic, tr.lastToken);
131
+ }
132
+ surface = generated;
133
+ }
134
+ if (surface === null)
135
+ return null;
136
+ return { surface, nextPhonetic: tr.nextPhoneticCache[key] ?? 0 };
137
+ }
138
+ function exceedsLocalRepeat(node, stateId) {
139
+ let count = 0;
140
+ let cur = node;
141
+ while (cur !== null) {
142
+ if (cur.state.id === stateId) {
143
+ count++;
144
+ if (count >= 2)
145
+ return true;
146
+ }
147
+ cur = cur.prev;
148
+ }
149
+ return false;
150
+ }
151
+ export class FuzzyMorphSearch {
152
+ analyzer;
153
+ prior;
154
+ root;
155
+ dpSlab;
156
+ wordCodes = new Uint8Array(MAX_WORD_LEN);
157
+ cache = new Map();
158
+ constructor(stemIndex, analyzer, prior) {
159
+ this.analyzer = analyzer;
160
+ this.prior = prior;
161
+ this.dpSlab = new Uint8Array((MAX_WORD_LEN + 6) * (MAX_WORD_LEN + 2));
162
+ // Build compact mark-folded stem trie once (~10 ms).
163
+ const root = { keys: [], children: [], stems: null };
164
+ for (const [surface, entry] of stemIndex.stems) {
165
+ if (surface.length === 0 || surface.length > MAX_WORD_LEN)
166
+ continue;
167
+ let node = root;
168
+ let ok = true;
169
+ for (let i = 0; i < surface.length; i++) {
170
+ const code = FOLD_CODE[surface.charCodeAt(i)];
171
+ if (code >= 26) {
172
+ ok = false;
173
+ break;
174
+ }
175
+ const keys = node.keys;
176
+ let idx = -1;
177
+ for (let k = 0; k < keys.length; k++) {
178
+ if (keys[k] === code) {
179
+ idx = k;
180
+ break;
181
+ }
182
+ }
183
+ if (idx === -1) {
184
+ const next = { keys: [], children: [], stems: null };
185
+ keys.push(code);
186
+ node.children.push(next);
187
+ node = next;
188
+ }
189
+ else {
190
+ node = node.children[idx];
191
+ }
192
+ }
193
+ if (!ok)
194
+ continue;
195
+ if (node.stems === null)
196
+ node.stems = [];
197
+ if (Array.isArray(entry)) {
198
+ for (let i = 0; i < entry.length; i++)
199
+ node.stems.push(entry[i]);
200
+ }
201
+ else {
202
+ node.stems.push(entry);
203
+ }
204
+ }
205
+ this.root = root;
206
+ }
207
+ /**
208
+ * Finds valid Turkish words within `maxEdits` (1 or 2) mark-folded Damerau-Levenshtein edits of `form`.
209
+ * Results are verified via `analyzer.isWord()` and sorted by `editCost` ascending.
210
+ */
211
+ search(form, maxEdits = 1, maxResults = 40) {
212
+ const word = lowerTr(form);
213
+ const L = word.length;
214
+ if (L < 3 || L > MAX_WORD_LEN - 4)
215
+ return [];
216
+ const cacheKey = `${maxEdits}:${word}`;
217
+ const cached = this.cache.get(cacheKey);
218
+ if (cached !== undefined)
219
+ return cached.length <= maxResults ? cached : cached.slice(0, maxResults);
220
+ const wCodes = this.wordCodes;
221
+ for (let i = 0; i < L; i++) {
222
+ const code = FOLD_CODE[word.charCodeAt(i)];
223
+ wCodes[i] = code;
224
+ }
225
+ const stride = L + 1;
226
+ const slab = this.dpSlab;
227
+ // Row 0: [0, 1, 2, ..., L]
228
+ for (let j = 0; j <= L; j++)
229
+ slab[j] = j;
230
+ const stemHits = [];
231
+ const maxStemDepth = Math.min(L + maxEdits, MAX_WORD_LEN);
232
+ const dfsTrie = (node, depth, lastCode) => {
233
+ const rowOff = depth * stride;
234
+ if (node.stems !== null && depth >= 1) {
235
+ const loJ = depth > maxEdits ? depth - maxEdits : 0;
236
+ const hiJ = depth + maxEdits < L ? depth + maxEdits : L;
237
+ let best = maxEdits + 1;
238
+ for (let j = loJ; j <= hiJ; j++) {
239
+ const v = slab[rowOff + j];
240
+ if (v < best)
241
+ best = v;
242
+ }
243
+ if (best <= maxEdits && (depth >= 2 || slab[rowOff + 1] === 0)) {
244
+ const rowCopy = slab.slice(rowOff, rowOff + stride);
245
+ const prevCopy = depth > 0 ? slab.slice((depth - 1) * stride, depth * stride) : null;
246
+ const stems = node.stems;
247
+ for (let i = 0; i < stems.length; i++) {
248
+ const st = stems[i];
249
+ const lemmaScore = this.prior ? this.prior.stemTotal(st.item.root) : 0;
250
+ stemHits.push({
251
+ st,
252
+ row: rowCopy,
253
+ prevRow: prevCopy,
254
+ lastCode,
255
+ bestDist: best,
256
+ lemmaScore,
257
+ });
258
+ }
259
+ }
260
+ }
261
+ if (depth >= maxStemDepth)
262
+ return;
263
+ const nextDepth = depth + 1;
264
+ const nextOff = nextDepth * stride;
265
+ const prevOff = (depth - 1) * stride;
266
+ const loJ = nextDepth > maxEdits + 1 ? nextDepth - maxEdits - 1 : 1;
267
+ const hiJ = nextDepth + maxEdits + 1 < L ? nextDepth + maxEdits + 1 : L;
268
+ const keys = node.keys;
269
+ const children = node.children;
270
+ for (let k = 0; k < keys.length; k++) {
271
+ const code = keys[k];
272
+ // Initialize entire row to INF_DIST so out-of-band entries (especially row[L] on short stems)
273
+ // never read stale zeros from earlier searches or unvisited cells.
274
+ slab.fill(INF_DIST, nextOff, nextOff + stride);
275
+ if (loJ === 1)
276
+ slab[nextOff] = nextDepth;
277
+ let minVal = nextDepth;
278
+ for (let j = loJ; j <= hiJ; j++) {
279
+ const sub = slab[rowOff + j - 1] + (wCodes[j - 1] === code ? 0 : 1);
280
+ const del = slab[rowOff + j] + 1;
281
+ const ins = slab[nextOff + j - 1] + 1;
282
+ let v = sub < del ? (sub < ins ? sub : ins) : del < ins ? del : ins;
283
+ if (depth >= 1 && j >= 2 && wCodes[j - 1] === lastCode && wCodes[j - 2] === code) {
284
+ const trans = slab[prevOff + j - 2] + 1;
285
+ if (trans < v)
286
+ v = trans;
287
+ }
288
+ slab[nextOff + j] = v;
289
+ if (v < minVal)
290
+ minVal = v;
291
+ }
292
+ if (minVal <= maxEdits) {
293
+ dfsTrie(children[k], nextDepth, code);
294
+ }
295
+ }
296
+ };
297
+ dfsTrie(this.root, 0, 26);
298
+ // Explore smallest edit distance first, then longest stems first (prevents short 2-3 letter stems from starving real roots),
299
+ // breaking ties by lemma frequency.
300
+ stemHits.sort((a, b) => a.bestDist - b.bestDist ||
301
+ b.st.surface.length - a.st.surface.length ||
302
+ b.lemmaScore - a.lemmaScore);
303
+ const found = new Map();
304
+ const maxFstSteps = maxEdits <= 1 ? 1500 : 3500;
305
+ const maxStepsPerStem = maxEdits <= 1 ? 160 : 220;
306
+ const virtualInputLen = L + maxEdits + 1;
307
+ let fstSteps = 0;
308
+ // Fast exact mark-folded suffix expansion when remaining edit budget is 0.
309
+ const expandExactFolded = (st, startPosInW, usedEdits, stemLimit) => {
310
+ const stack = [
311
+ {
312
+ prev: null,
313
+ stemTransition: st,
314
+ state: st.to,
315
+ surface: st.surface,
316
+ pos: startPosInW,
317
+ inputLength: L,
318
+ phonetic: st.phonetic,
319
+ depth: 0,
320
+ hasSurface: false,
321
+ hasDerivation: false,
322
+ currentGroupHasSurface: false,
323
+ lastDerivation: null,
324
+ word: st.surface,
325
+ derivCount: 0,
326
+ },
327
+ ];
328
+ while (stack.length > 0 && fstSteps < stemLimit) {
329
+ const node = stack.pop();
330
+ fstSteps++;
331
+ if (node.pos === L && node.state.terminal && (node.phonetic & PA_CANNOT_TERMINATE) === 0) {
332
+ const prev = found.get(node.word);
333
+ if (prev === undefined || usedEdits < prev)
334
+ found.set(node.word, usedEdits);
335
+ }
336
+ if (node.depth >= 14)
337
+ continue;
338
+ const remaining = L - node.pos;
339
+ const outgoing = node.state.outgoing;
340
+ const phonetic = node.phonetic;
341
+ for (let i = 0; i < outgoing.length; i++) {
342
+ const tr = outgoing[i];
343
+ const isDeriv = tr.to.derivative;
344
+ if (isDeriv && node.derivCount >= 2)
345
+ continue;
346
+ if (!tr.hasSurface) {
347
+ if (tr.condition !== null && !tr.condition(node))
348
+ continue;
349
+ if (node.depth > 4 && exceedsLocalRepeat(node, tr.to.id))
350
+ continue;
351
+ stack.push({
352
+ prev: node,
353
+ stemTransition: node.stemTransition,
354
+ state: tr.to,
355
+ surface: "",
356
+ pos: node.pos,
357
+ inputLength: L,
358
+ phonetic,
359
+ depth: node.depth + 1,
360
+ hasSurface: node.hasSurface,
361
+ hasDerivation: node.hasDerivation || isDeriv,
362
+ currentGroupHasSurface: isDeriv ? false : node.currentGroupHasSurface,
363
+ lastDerivation: isDeriv ? tr.to : node.lastDerivation,
364
+ word: node.word,
365
+ derivCount: node.derivCount + (isDeriv ? 1 : 0),
366
+ });
367
+ continue;
368
+ }
369
+ if (remaining === 0 || (phonetic & tr.forbiddenPhonetic) !== 0)
370
+ continue;
371
+ const resolved = resolveSurfaceAndNextPhonetic(tr, phonetic);
372
+ if (resolved === null)
373
+ continue;
374
+ const { surface, nextPhonetic } = resolved;
375
+ const sLen = surface.length;
376
+ if (sLen > remaining)
377
+ continue;
378
+ let matched = true;
379
+ for (let k = 0; k < sLen; k++) {
380
+ if (FOLD_CODE[surface.charCodeAt(k)] !== wCodes[node.pos + k]) {
381
+ matched = false;
382
+ break;
383
+ }
384
+ }
385
+ if (!matched)
386
+ continue;
387
+ if (tr.condition !== null && !tr.condition(node))
388
+ continue;
389
+ if (node.depth > 4 && exceedsLocalRepeat(node, tr.to.id))
390
+ continue;
391
+ stack.push({
392
+ prev: node,
393
+ stemTransition: node.stemTransition,
394
+ state: tr.to,
395
+ surface,
396
+ pos: node.pos + sLen,
397
+ inputLength: L,
398
+ phonetic: nextPhonetic,
399
+ depth: node.depth + 1,
400
+ hasSurface: true,
401
+ hasDerivation: node.hasDerivation || isDeriv,
402
+ currentGroupHasSurface: isDeriv ? false : true,
403
+ lastDerivation: isDeriv ? tr.to : node.lastDerivation,
404
+ word: node.word + surface,
405
+ derivCount: node.derivCount + (isDeriv ? 1 : 0),
406
+ });
407
+ }
408
+ }
409
+ };
410
+ const advanceOneCode = (prevRow, prevPrevRow, code, prevCode, candLen) => {
411
+ const loJ = candLen > maxEdits + 1 ? candLen - maxEdits - 1 : 1;
412
+ const hiJ = candLen + maxEdits + 1 < L ? candLen + maxEdits + 1 : L;
413
+ // Fast pre-check before allocating: compute into scratch row first, copy only if minVal <= maxEdits.
414
+ const scratch = slab;
415
+ const scratchOff = (maxStemDepth + 2) * stride;
416
+ scratch.fill(INF_DIST, scratchOff, scratchOff + stride);
417
+ if (loJ === 1)
418
+ scratch[scratchOff] = candLen;
419
+ let minVal = candLen <= maxEdits ? candLen : INF_DIST;
420
+ for (let j = loJ; j <= hiJ; j++) {
421
+ const sub = prevRow[j - 1] + (wCodes[j - 1] === code ? 0 : 1);
422
+ const del = prevRow[j] + 1;
423
+ const ins = scratch[scratchOff + j - 1] + 1;
424
+ let v = sub < del ? (sub < ins ? sub : ins) : del < ins ? del : ins;
425
+ if (prevPrevRow !== null && j >= 2 && prevCode < 26 && wCodes[j - 1] === prevCode && wCodes[j - 2] === code) {
426
+ const trans = prevPrevRow[j - 2] + 1;
427
+ if (trans < v)
428
+ v = trans;
429
+ }
430
+ scratch[scratchOff + j] = v;
431
+ if (v < minVal)
432
+ minVal = v;
433
+ }
434
+ return minVal <= maxEdits ? scratch.slice(scratchOff, scratchOff + stride) : null;
435
+ };
436
+ for (let h = 0; h < stemHits.length && fstSteps < maxFstSteps; h++) {
437
+ const hit = stemHits[h];
438
+ const st = hit.st;
439
+ const stemLimit = Math.min(maxFstSteps, fstSteps + maxStepsPerStem);
440
+ // Zero remaining edits: use ultra-fast exact mark-folded suffix expansion UNLESS a cross-boundary
441
+ // transposition (stem's last char == next typed char, e.g. "kalem|lerimi" vs "kalel|merimi") is possible.
442
+ if (hit.bestDist === maxEdits) {
443
+ const sLen = st.surface.length;
444
+ const loJ = sLen > maxEdits ? sLen - maxEdits : 0;
445
+ const hiJ = sLen + maxEdits < L ? sLen + maxEdits : L;
446
+ let canBoundarySwap = false;
447
+ if (hit.prevRow !== null && hit.lastCode < 26) {
448
+ for (let j = Math.max(1, loJ); j <= hiJ && j < L; j++) {
449
+ if (hit.prevRow[j - 1] < maxEdits && wCodes[j] === hit.lastCode) {
450
+ canBoundarySwap = true;
451
+ break;
452
+ }
453
+ }
454
+ }
455
+ if (!canBoundarySwap) {
456
+ for (let j = loJ; j <= hiJ && fstSteps < stemLimit; j++) {
457
+ if (hit.row[j] === maxEdits) {
458
+ expandExactFolded(st, j, maxEdits, stemLimit);
459
+ }
460
+ }
461
+ continue;
462
+ }
463
+ }
464
+ // Remaining edit budget >= 1 (or cross-boundary transposition): run banded fuzzy FST DFS.
465
+ const stack = [
466
+ {
467
+ prev: null,
468
+ stemTransition: st,
469
+ state: st.to,
470
+ surface: st.surface,
471
+ pos: st.surface.length,
472
+ inputLength: virtualInputLen,
473
+ phonetic: st.phonetic,
474
+ depth: 0,
475
+ hasSurface: false,
476
+ hasDerivation: false,
477
+ currentGroupHasSurface: false,
478
+ lastDerivation: null,
479
+ word: st.surface,
480
+ row: hit.row,
481
+ prevRow: hit.prevRow,
482
+ lastCode: hit.lastCode,
483
+ derivCount: 0,
484
+ },
485
+ ];
486
+ while (stack.length > 0 && fstSteps < stemLimit) {
487
+ const node = stack.pop();
488
+ fstSteps++;
489
+ const endDist = node.row[L];
490
+ if (endDist <= maxEdits && node.state.terminal && (node.phonetic & PA_CANNOT_TERMINATE) === 0) {
491
+ const prev = found.get(node.word);
492
+ if (prev === undefined || endDist < prev)
493
+ found.set(node.word, endDist);
494
+ }
495
+ if (node.depth >= 12)
496
+ continue;
497
+ const outgoing = node.state.outgoing;
498
+ const phonetic = node.phonetic;
499
+ for (let i = 0; i < outgoing.length; i++) {
500
+ const tr = outgoing[i];
501
+ const isDeriv = tr.to.derivative;
502
+ if (isDeriv && node.derivCount >= 2)
503
+ continue;
504
+ if (!tr.hasSurface) {
505
+ if (tr.condition !== null && !tr.condition(node))
506
+ continue;
507
+ if (node.depth > 4 && exceedsLocalRepeat(node, tr.to.id))
508
+ continue;
509
+ stack.push({
510
+ prev: node,
511
+ stemTransition: node.stemTransition,
512
+ state: tr.to,
513
+ surface: "",
514
+ pos: node.pos,
515
+ inputLength: virtualInputLen,
516
+ phonetic,
517
+ depth: node.depth + 1,
518
+ hasSurface: node.hasSurface,
519
+ hasDerivation: node.hasDerivation || isDeriv,
520
+ currentGroupHasSurface: isDeriv ? false : node.currentGroupHasSurface,
521
+ lastDerivation: isDeriv ? tr.to : node.lastDerivation,
522
+ word: node.word,
523
+ row: node.row,
524
+ prevRow: node.prevRow,
525
+ lastCode: node.lastCode,
526
+ derivCount: node.derivCount + (isDeriv ? 1 : 0),
527
+ });
528
+ continue;
529
+ }
530
+ if ((phonetic & tr.forbiddenPhonetic) !== 0)
531
+ continue;
532
+ const resolved = resolveSurfaceAndNextPhonetic(tr, phonetic);
533
+ if (resolved === null)
534
+ continue;
535
+ const { surface, nextPhonetic } = resolved;
536
+ const newLen = node.word.length + surface.length;
537
+ if (newLen > L + maxEdits)
538
+ continue;
539
+ let curRow = node.row;
540
+ let curPrev = node.prevRow;
541
+ let curCode = node.lastCode;
542
+ let curLen = node.word.length;
543
+ let ok = true;
544
+ for (let k = 0; k < surface.length; k++) {
545
+ const code = FOLD_CODE[surface.charCodeAt(k)];
546
+ curLen++;
547
+ const nextRow = advanceOneCode(curRow, curPrev, code, curCode, curLen);
548
+ if (nextRow === null) {
549
+ ok = false;
550
+ break;
551
+ }
552
+ curPrev = curRow;
553
+ curRow = nextRow;
554
+ curCode = code;
555
+ }
556
+ if (!ok)
557
+ continue;
558
+ if (tr.condition !== null && !tr.condition(node))
559
+ continue;
560
+ if (node.depth > 4 && exceedsLocalRepeat(node, tr.to.id))
561
+ continue;
562
+ stack.push({
563
+ prev: node,
564
+ stemTransition: node.stemTransition,
565
+ state: tr.to,
566
+ surface,
567
+ pos: newLen,
568
+ inputLength: virtualInputLen,
569
+ phonetic: nextPhonetic,
570
+ depth: node.depth + 1,
571
+ hasSurface: true,
572
+ hasDerivation: node.hasDerivation || isDeriv,
573
+ currentGroupHasSurface: isDeriv ? false : true,
574
+ lastDerivation: isDeriv ? tr.to : node.lastDerivation,
575
+ word: node.word + surface,
576
+ row: curRow,
577
+ prevRow: curPrev,
578
+ lastCode: curCode,
579
+ derivCount: node.derivCount + (isDeriv ? 1 : 0),
580
+ });
581
+ }
582
+ }
583
+ }
584
+ // Verify every emitted candidate with exact analyzer.isWord() and compute rich Turkish edit cost.
585
+ const verified = [];
586
+ for (const [cand, foldedEdits] of found) {
587
+ if (cand === word || Math.abs(cand.length - L) > maxEdits)
588
+ continue;
589
+ if (!this.analyzer.isWord(cand))
590
+ continue;
591
+ verified.push({ word: cand, foldedEdits, editCost: turkishEditCost(word, cand) });
592
+ }
593
+ verified.sort((a, b) => a.editCost - b.editCost || a.foldedEdits - b.foldedEdits);
594
+ if (this.cache.size >= MAX_FUZZY_CACHE)
595
+ this.cache.clear();
596
+ this.cache.set(cacheKey, verified);
597
+ return verified.length <= maxResults ? verified : verified.slice(0, maxResults);
598
+ }
599
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Public entry point for the Turkish morphology module.
3
+ * Checks whether a lowercased Turkish word form is valid according to Turkish phonology
4
+ * and morphotactics, exposes full morphological analyses, generative prior counts, and
5
+ * error-tolerant fuzzy morphological candidate generation.
6
+ */
7
+ import { turkishEditCost, type FuzzyMorphCandidate } from "./fuzzy.ts";
8
+ import { MorphPrior } from "./prior.ts";
9
+ import type { MorphAnalysis } from "./types.ts";
10
+ export type { FuzzyMorphCandidate, MorphAnalysis };
11
+ export { MorphPrior, turkishEditCost };
12
+ export declare class TurkishMorphology {
13
+ private readonly analyzer;
14
+ private readonly prior?;
15
+ private readonly priorCache;
16
+ private fuzzyEngine;
17
+ private constructor();
18
+ /** Sözlük metinlerinden kurar (Zemberek .dict dosyalarının içeriği) ve isteğe bağlı öncül ekler. */
19
+ static fromDictionaries(texts: readonly string[], prior?: MorphPrior): TurkishMorphology;
20
+ /** Sıkıştırılmış ikili sözlükten (AMR1/AMR2 `morph.bin`) kurar. */
21
+ static fromBinary(bytes: Uint8Array): TurkishMorphology;
22
+ /** Küçük harfli Türkçe biçim (lowerTr ile) Türkçe ek kurallarına göre geçerli bir kelime mi? */
23
+ isWord(form: string): boolean;
24
+ /** İnceleme ve test için: bulunan çözümlemeler (kök, tür, ek dizisi). */
25
+ analyze(form: string): MorphAnalysis[];
26
+ /** Biçimbilimsel üretici öncül (kök sıklığı × ek dizisi olasılığı) yüklü mü? */
27
+ get hasPrior(): boolean;
28
+ /**
29
+ * Geçerli bir Türkçe biçim için kök sıklığı ve ek dizisi olasılığından beklenen derlem sıklığı.
30
+ * Öncül yüklü değilse veya kelime geçersizse 0 döndürür.
31
+ */
32
+ priorCount(form: string): number;
33
+ /** Belirli bir kök+tür çiftinin derlem toplam sıklığı. */
34
+ lemmaCount(stem: string, pos: string): number;
35
+ /**
36
+ * Hata toleranslı biçimbilim araması: Türkçe işaret kaybı + `maxEdits` (1 veya 2) düzenleme
37
+ * uzaklığındaki geçerli Türkçe biçimleri (derlemde hiç görülmemiş olanlar dahil) bulur.
38
+ */
39
+ fuzzySearch(form: string, maxEdits?: number, maxResults?: number): readonly FuzzyMorphCandidate[];
40
+ }