@wovvmap/search-core 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,10 @@
1
- # Temporary Holding Version
1
+ # @wovvmap/search-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Generic, framework-independent search indexing, text matching, and sorting engine for WovVMap.
4
+
5
+ ## Responsibilities
6
+
7
+ - Prepares reusable normalized/tokenized search indexes and canonical paid-promotion entries once per document revision (`SearchIndex`, `createSearchIndex`).
8
+ - Evaluates exact, prefix, substring, and configurable fuzzy/typo matches across weighted fields and paid-promotion keywords for English and Unicode/Hindi text.
9
+ - Supports deterministic sorting (`relevance`, `asc`, `desc`, `floor_proximity`, `paid_promotion_asc`, `paid_promotion_desc`, `paid_promotion_weight`, `paid_promotion_floor`) and bounded pagination with lightweight, JSON-serializable result records (`SearchResultItem`, `SearchPageResult`).
10
+ - Does **not** depend on `NodePoint`, Three.js, React, WebView, network APIs, or global singleton state.
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @file index.ts
3
+ * @description Public root facade for `@wovvmap/search-core`.
4
+ * Hinglish: `@wovvmap/search-core` package ka public root export facade.
5
+ */
6
+ export { createSearchIndex, DEFAULT_FLOOR_SECONDARY_SORT_BY, DEFAULT_MIN_MATCH_RATIO, DEFAULT_MIN_QUERY_LENGTH, DEFAULT_MIN_SCORE, DEFAULT_MIN_SUBSTRING_LENGTH, DEFAULT_RETURN_ALL_ON_EMPTY, DEFAULT_SEARCH_LIMIT, DEFAULT_SEARCH_LOCALE, DEFAULT_SORT_BY, DEFAULT_TYPO_TOLERANCE, SearchIndex, } from './searchIndex.js';
7
+ export { levenshteinDistance, normalizeSearchText, smartLevenshteinDistance, tokenizeSearchText, } from './matching.js';
8
+ export { SearchCoreError } from './types.js';
9
+ export type { FloorSecondarySortMode, PaidPromotionMatchGroup, SearchAllResult, SearchCoreErrorCode, SearchDocumentInput, SearchFieldConfig, SearchIndexConfig, SearchMatchKind, SearchPageResult, SearchQueryOptions, SearchResultItem, SearchSortMode, } from './types.js';
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACL,iBAAiB,EACjB,+BAA+B,EAC/B,uBAAuB,EACvB,wBAAwB,EACxB,iBAAiB,EACjB,4BAA4B,EAC5B,2BAA2B,EAC3B,oBAAoB,EACpB,qBAAqB,EACrB,eAAe,EACf,sBAAsB,EACtB,WAAW,GACZ,MAAM,eAAe,CAAA;AAEtB,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,wBAAwB,EACxB,kBAAkB,GACnB,MAAM,YAAY,CAAA;AAEnB,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AACzC,YAAY,EACV,sBAAsB,EACtB,uBAAuB,EACvB,eAAe,EACf,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,GACf,MAAM,SAAS,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @file index.ts
3
+ * @description Public root facade for `@wovvmap/search-core`.
4
+ * Hinglish: `@wovvmap/search-core` package ka public root export facade.
5
+ */
6
+ export { createSearchIndex, DEFAULT_FLOOR_SECONDARY_SORT_BY, DEFAULT_MIN_MATCH_RATIO, DEFAULT_MIN_QUERY_LENGTH, DEFAULT_MIN_SCORE, DEFAULT_MIN_SUBSTRING_LENGTH, DEFAULT_RETURN_ALL_ON_EMPTY, DEFAULT_SEARCH_LIMIT, DEFAULT_SEARCH_LOCALE, DEFAULT_SORT_BY, DEFAULT_TYPO_TOLERANCE, SearchIndex, } from './searchIndex.js';
7
+ export { levenshteinDistance, normalizeSearchText, smartLevenshteinDistance, tokenizeSearchText, } from './matching.js';
8
+ export { SearchCoreError } from './types.js';
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @file matching.ts
3
+ * @description Unicode/Hindi-aware text normalization, tokenization, edit-distance calculation, and weighted field matching.
4
+ * Hinglish: English aur Hindi/Unicode text ke liye normalization, tokenization, fuzzy edit distance aur exact/prefix/substring/fuzzy scoring logic.
5
+ */
6
+ import type { PreparedSearchDocument, ScoredSearchCandidate, SearchMatchKind } from './types.js';
7
+ /**
8
+ * Scoring multipliers enforcing the strict per-field match hierarchy:
9
+ * `exact (10,000) > prefix (3,000..3,050) > substring (1,500..1,550) > fuzzy (< 600)`.
10
+ *
11
+ * Hinglish: Per-field match hierarchy (`exact > prefix > substring > fuzzy`) ko enforce karne wale multipliers.
12
+ */
13
+ export declare const EXACT_TOKEN_MULTIPLIER = 10000;
14
+ export declare const EXACT_PHRASE_BONUS_MULTIPLIER = 2000;
15
+ export declare const PREFIX_TOKEN_MULTIPLIER = 3000;
16
+ export declare const SUBSTRING_TOKEN_MULTIPLIER = 1500;
17
+ export declare const FUZZY_FULL_TOKEN_MAX_MULTIPLIER = 600;
18
+ export declare const FUZZY_PREFIX_TOKEN_MAX_MULTIPLIER = 450;
19
+ /**
20
+ * Normalizes a text string for indexing and query evaluation:
21
+ * 1. Decomposes to NFD and strips Latin combining diacritical marks (`U+0300..U+036F`) so `"Café"` -> `"cafe"`.
22
+ * 2. Re-composes to canonical NFC so Indic/Devanagari vowel matras, nukta, and anusvara stay intact.
23
+ * 3. Lowercases, collapses internal whitespace runs to a single space, and trims.
24
+ *
25
+ * Hinglish: Search aur indexing ke liye text normalize karta hai: Latin accents (`Café` -> `cafe`) hatata hai
26
+ * aur NFC normalization ke zariye Hindi/Unicode matras ko preserve rakhta hai.
27
+ */
28
+ export declare function normalizeSearchText(text: string | null | undefined): string;
29
+ /**
30
+ * Splits a normalized text string into searchable word tokens across English, Hindi/Devanagari, and Unicode scripts.
31
+ * Preserves Unicode letters (`\p{L}`), combining/spacing marks (`\p{M}`), and digits (`\p{N}`), while discarding
32
+ * punctuation, symbols, and standalone combining marks without a base letter/digit.
33
+ *
34
+ * Hinglish: Normalized text ko English, Hindi aur sabhi Unicode scripts ke word tokens me todta hai;
35
+ * punctuation/symbols aur bina base letter wale marks ko filter out karta hai.
36
+ */
37
+ export declare function tokenizeSearchText(normalizedText: string): string[];
38
+ /**
39
+ * Deduplicates query tokens while preserving their first-seen order.
40
+ *
41
+ * Hinglish: Query tokens ka first-seen order banaye rakhte hue duplicate tokens hatata hai.
42
+ */
43
+ export declare function dedupeQueryTokens(tokens: readonly string[]): string[];
44
+ /**
45
+ * Standard integer Levenshtein edit distance between two strings.
46
+ *
47
+ * Hinglish: Do strings ke beech standard integer Levenshtein edit distance calculate karta hai.
48
+ */
49
+ export declare function levenshteinDistance(a: string, b: string): number;
50
+ /**
51
+ * Phonetic/vowel-aware edit distance for fuzzy matching.
52
+ * - For ASCII Latin letters, vowel-to-vowel substitutions and vowel insertions/deletions cost `0.5`,
53
+ * vowel-to-consonant costs `1.0`, and consonant-to-consonant costs `1.5` (preserving legacy phonetic typo behavior such as `"feson"` -> `"fashion"`).
54
+ * - For non-ASCII Unicode characters (such as Hindi/Devanagari), uses a uniform edit cost of `1.0`.
55
+ *
56
+ * Hinglish: Fuzzy matching ke liye smart edit distance: English vowels ke phonetic typos (`feson` -> `fashion`)
57
+ * par `0.5` cost aur Hindi/Unicode characters par uniform `1.0` edit cost lagata hai.
58
+ */
59
+ export declare function smartLevenshteinDistance(a: string, b: string): number;
60
+ /**
61
+ * Parameters controlling single-token and multi-token matching.
62
+ *
63
+ * Hinglish: Single-token aur document-level matching ke parameters.
64
+ */
65
+ export interface TokenMatchParameters {
66
+ readonly typoTolerance: number;
67
+ readonly minSubstringLength: number;
68
+ readonly minMatchRatio: number;
69
+ readonly minScore: number;
70
+ readonly includePaidPromotions?: boolean;
71
+ }
72
+ /**
73
+ * Result of comparing a single normalized query token against a single normalized document token.
74
+ *
75
+ * Hinglish: Ek query token aur document token ke comparison ka result (`kind` aur `multiplier`).
76
+ */
77
+ export interface TokenMatchScore {
78
+ readonly kind: SearchMatchKind;
79
+ readonly multiplier: number;
80
+ }
81
+ /**
82
+ * Evaluates a single normalized query token (`qToken`) against a normalized document token (`vToken`).
83
+ * Returns `null` when no match occurs, or a `{ kind, multiplier }` respecting:
84
+ * `exact (10,000) > prefix (3,000..3,050) > substring (1,500..1,550) > fuzzy (< 600)`.
85
+ *
86
+ * Hinglish: Query token (`qToken`) ko document token (`vToken`) se match karke `exact > prefix > substring > fuzzy`
87
+ * hierarchy ke mutabik multiplier deta hai.
88
+ */
89
+ export declare function scoreTokenMatch(qToken: string, vToken: string, params: Pick<TokenMatchParameters, 'typoTolerance' | 'minSubstringLength'>): TokenMatchScore | null;
90
+ /**
91
+ * Evaluates a prepared document against the normalized query and its deduplicated query tokens.
92
+ * Returns a `ScoredSearchCandidate` when the document meets `minMatchRatio` and `minScore`, or `null` otherwise.
93
+ *
94
+ * Hinglish: Prepared document ko query tokens ke khilaf evaluate karke score, `matchedTerms` aur `matchedFields`
95
+ * calculate karta hai; `minMatchRatio` ya `minScore` pura na hone par `null` deta hai.
96
+ */
97
+ export declare function evaluateDocumentMatch(doc: PreparedSearchDocument, queryTokens: readonly string[], normalizedQuery: string, params: TokenMatchParameters): ScoredSearchCandidate | null;
98
+ //# sourceMappingURL=matching.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matching.d.ts","sourceRoot":"","sources":["../src/matching.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAEV,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EAChB,MAAM,SAAS,CAAA;AAEhB;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,QAAS,CAAA;AAC5C,eAAO,MAAM,6BAA6B,OAAQ,CAAA;AAClD,eAAO,MAAM,uBAAuB,OAAQ,CAAA;AAC5C,eAAO,MAAM,0BAA0B,OAAQ,CAAA;AAC/C,eAAO,MAAM,+BAA+B,MAAM,CAAA;AAClD,eAAO,MAAM,iCAAiC,MAAM,CAAA;AAgCpD;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAS3E;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,EAAE,CAWnE;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAYrE;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CA2ChE;AAED;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CA8DrE;AAED;;;;GAIG;AACH,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;IAC9B,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAA;IACnC,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;IAC9B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,qBAAqB,CAAC,EAAE,OAAO,CAAA;CACzC;AAED;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAA;IAC9B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;CAC5B;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,eAAe,GAAG,oBAAoB,CAAC,GACzE,eAAe,GAAG,IAAI,CAsFxB;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,sBAAsB,EAC3B,WAAW,EAAE,SAAS,MAAM,EAAE,EAC9B,eAAe,EAAE,MAAM,EACvB,MAAM,EAAE,oBAAoB,GAC3B,qBAAqB,GAAG,IAAI,CAoK9B"}
@@ -0,0 +1,460 @@
1
+ /**
2
+ * @file matching.ts
3
+ * @description Unicode/Hindi-aware text normalization, tokenization, edit-distance calculation, and weighted field matching.
4
+ * Hinglish: English aur Hindi/Unicode text ke liye normalization, tokenization, fuzzy edit distance aur exact/prefix/substring/fuzzy scoring logic.
5
+ */
6
+ /**
7
+ * Scoring multipliers enforcing the strict per-field match hierarchy:
8
+ * `exact (10,000) > prefix (3,000..3,050) > substring (1,500..1,550) > fuzzy (< 600)`.
9
+ *
10
+ * Hinglish: Per-field match hierarchy (`exact > prefix > substring > fuzzy`) ko enforce karne wale multipliers.
11
+ */
12
+ export const EXACT_TOKEN_MULTIPLIER = 10_000;
13
+ export const EXACT_PHRASE_BONUS_MULTIPLIER = 2_000;
14
+ export const PREFIX_TOKEN_MULTIPLIER = 3_000;
15
+ export const SUBSTRING_TOKEN_MULTIPLIER = 1_500;
16
+ export const FUZZY_FULL_TOKEN_MAX_MULTIPLIER = 600;
17
+ export const FUZZY_PREFIX_TOKEN_MAX_MULTIPLIER = 450;
18
+ const LATIN_COMBINING_MARKS_REGEX = /[\u0300-\u036f]+/g;
19
+ const WHITESPACE_COLLAPSE_REGEX = /\s+/g;
20
+ const NON_WORD_SPLIT_REGEX = /[^\p{L}\p{M}\p{N}]+/u;
21
+ const HAS_LETTER_OR_DIGIT_REGEX = /[\p{L}\p{N}]/u;
22
+ const MAX_REUSABLE_BUFFER_LEN = 128;
23
+ let sharedPrevRow = new Float64Array(MAX_REUSABLE_BUFFER_LEN + 1);
24
+ let sharedCurrRow = new Float64Array(MAX_REUSABLE_BUFFER_LEN + 1);
25
+ function isLatinVowelCode(code) {
26
+ // 'a'=97, 'e'=101, 'i'=105, 'o'=111, 'u'=117, 'y'=121
27
+ return code === 97 || code === 101 || code === 105 || code === 111 || code === 117 || code === 121;
28
+ }
29
+ function isAsciiLowerLetterCode(code) {
30
+ return code >= 97 && code <= 122;
31
+ }
32
+ function characterEditCost(code) {
33
+ return isAsciiLowerLetterCode(code) && isLatinVowelCode(code) ? 0.5 : 1.0;
34
+ }
35
+ function sumStringEditCost(text) {
36
+ let total = 0;
37
+ for (let i = 0; i < text.length; i++) {
38
+ total += characterEditCost(text.charCodeAt(i));
39
+ }
40
+ return total;
41
+ }
42
+ /**
43
+ * Normalizes a text string for indexing and query evaluation:
44
+ * 1. Decomposes to NFD and strips Latin combining diacritical marks (`U+0300..U+036F`) so `"Café"` -> `"cafe"`.
45
+ * 2. Re-composes to canonical NFC so Indic/Devanagari vowel matras, nukta, and anusvara stay intact.
46
+ * 3. Lowercases, collapses internal whitespace runs to a single space, and trims.
47
+ *
48
+ * Hinglish: Search aur indexing ke liye text normalize karta hai: Latin accents (`Café` -> `cafe`) hatata hai
49
+ * aur NFC normalization ke zariye Hindi/Unicode matras ko preserve rakhta hai.
50
+ */
51
+ export function normalizeSearchText(text) {
52
+ if (!text)
53
+ return '';
54
+ return String(text)
55
+ .normalize('NFD')
56
+ .replace(LATIN_COMBINING_MARKS_REGEX, '')
57
+ .normalize('NFC')
58
+ .toLowerCase()
59
+ .replace(WHITESPACE_COLLAPSE_REGEX, ' ')
60
+ .trim();
61
+ }
62
+ /**
63
+ * Splits a normalized text string into searchable word tokens across English, Hindi/Devanagari, and Unicode scripts.
64
+ * Preserves Unicode letters (`\p{L}`), combining/spacing marks (`\p{M}`), and digits (`\p{N}`), while discarding
65
+ * punctuation, symbols, and standalone combining marks without a base letter/digit.
66
+ *
67
+ * Hinglish: Normalized text ko English, Hindi aur sabhi Unicode scripts ke word tokens me todta hai;
68
+ * punctuation/symbols aur bina base letter wale marks ko filter out karta hai.
69
+ */
70
+ export function tokenizeSearchText(normalizedText) {
71
+ if (!normalizedText)
72
+ return [];
73
+ const parts = normalizedText.split(NON_WORD_SPLIT_REGEX);
74
+ const tokens = [];
75
+ for (let i = 0; i < parts.length; i++) {
76
+ const part = parts[i];
77
+ if (part.length > 0 && HAS_LETTER_OR_DIGIT_REGEX.test(part)) {
78
+ tokens.push(part);
79
+ }
80
+ }
81
+ return tokens;
82
+ }
83
+ /**
84
+ * Deduplicates query tokens while preserving their first-seen order.
85
+ *
86
+ * Hinglish: Query tokens ka first-seen order banaye rakhte hue duplicate tokens hatata hai.
87
+ */
88
+ export function dedupeQueryTokens(tokens) {
89
+ if (tokens.length <= 1)
90
+ return tokens.slice();
91
+ const seen = new Set();
92
+ const unique = [];
93
+ for (let i = 0; i < tokens.length; i++) {
94
+ const token = tokens[i];
95
+ if (!seen.has(token)) {
96
+ seen.add(token);
97
+ unique.push(token);
98
+ }
99
+ }
100
+ return unique;
101
+ }
102
+ /**
103
+ * Standard integer Levenshtein edit distance between two strings.
104
+ *
105
+ * Hinglish: Do strings ke beech standard integer Levenshtein edit distance calculate karta hai.
106
+ */
107
+ export function levenshteinDistance(a, b) {
108
+ if (a === b)
109
+ return 0;
110
+ if (a.length === 0)
111
+ return b.length;
112
+ if (b.length === 0)
113
+ return a.length;
114
+ let left = a;
115
+ let right = b;
116
+ if (left.length > right.length) {
117
+ left = b;
118
+ right = a;
119
+ }
120
+ const m = left.length;
121
+ const n = right.length;
122
+ const useShared = n <= MAX_REUSABLE_BUFFER_LEN;
123
+ let prev = useShared ? sharedPrevRow : new Float64Array(n + 1);
124
+ let curr = useShared ? sharedCurrRow : new Float64Array(n + 1);
125
+ for (let j = 0; j <= n; j++) {
126
+ prev[j] = j;
127
+ }
128
+ for (let i = 1; i <= m; i++) {
129
+ curr[0] = i;
130
+ const charLeft = left.charCodeAt(i - 1);
131
+ for (let j = 1; j <= n; j++) {
132
+ const cost = charLeft === right.charCodeAt(j - 1) ? 0 : 1;
133
+ const deletion = prev[j] + 1;
134
+ const insertion = curr[j - 1] + 1;
135
+ const substitution = prev[j - 1] + cost;
136
+ curr[j] = Math.min(deletion, insertion, substitution);
137
+ }
138
+ const temp = prev;
139
+ prev = curr;
140
+ curr = temp;
141
+ }
142
+ const result = prev[n];
143
+ if (useShared) {
144
+ sharedPrevRow = prev;
145
+ sharedCurrRow = curr;
146
+ }
147
+ return result;
148
+ }
149
+ /**
150
+ * Phonetic/vowel-aware edit distance for fuzzy matching.
151
+ * - For ASCII Latin letters, vowel-to-vowel substitutions and vowel insertions/deletions cost `0.5`,
152
+ * vowel-to-consonant costs `1.0`, and consonant-to-consonant costs `1.5` (preserving legacy phonetic typo behavior such as `"feson"` -> `"fashion"`).
153
+ * - For non-ASCII Unicode characters (such as Hindi/Devanagari), uses a uniform edit cost of `1.0`.
154
+ *
155
+ * Hinglish: Fuzzy matching ke liye smart edit distance: English vowels ke phonetic typos (`feson` -> `fashion`)
156
+ * par `0.5` cost aur Hindi/Unicode characters par uniform `1.0` edit cost lagata hai.
157
+ */
158
+ export function smartLevenshteinDistance(a, b) {
159
+ if (a === b)
160
+ return 0;
161
+ if (a.length === 0)
162
+ return sumStringEditCost(b);
163
+ if (b.length === 0)
164
+ return sumStringEditCost(a);
165
+ const m = a.length;
166
+ const n = b.length;
167
+ const useShared = n <= MAX_REUSABLE_BUFFER_LEN;
168
+ let prev = useShared ? sharedPrevRow : new Float64Array(n + 1);
169
+ let curr = useShared ? sharedCurrRow : new Float64Array(n + 1);
170
+ prev[0] = 0;
171
+ for (let j = 1; j <= n; j++) {
172
+ prev[j] = prev[j - 1] + characterEditCost(b.charCodeAt(j - 1));
173
+ }
174
+ for (let i = 1; i <= m; i++) {
175
+ const codeA = a.charCodeAt(i - 1);
176
+ const isAsciiA = isAsciiLowerLetterCode(codeA);
177
+ const isVowelA = isAsciiA && isLatinVowelCode(codeA);
178
+ const deleteCost = isVowelA ? 0.5 : 1.0;
179
+ curr[0] = prev[0] + deleteCost;
180
+ for (let j = 1; j <= n; j++) {
181
+ const codeB = b.charCodeAt(j - 1);
182
+ let subCost = 0;
183
+ if (codeA !== codeB) {
184
+ const isAsciiB = isAsciiLowerLetterCode(codeB);
185
+ if (isAsciiA && isAsciiB) {
186
+ const isVowelB = isLatinVowelCode(codeB);
187
+ if (isVowelA && isVowelB) {
188
+ subCost = 0.5;
189
+ }
190
+ else if (isVowelA || isVowelB) {
191
+ subCost = 1.0;
192
+ }
193
+ else {
194
+ subCost = 1.5;
195
+ }
196
+ }
197
+ else {
198
+ subCost = 1.0;
199
+ }
200
+ }
201
+ const isVowelB = isAsciiLowerLetterCode(codeB) && isLatinVowelCode(codeB);
202
+ const insertCost = isVowelB ? 0.5 : 1.0;
203
+ const above = prev[j] + deleteCost;
204
+ const left = curr[j - 1] + insertCost;
205
+ const diag = prev[j - 1] + subCost;
206
+ curr[j] = Math.min(above, left, diag);
207
+ }
208
+ const temp = prev;
209
+ prev = curr;
210
+ curr = temp;
211
+ }
212
+ const result = prev[n];
213
+ if (useShared) {
214
+ sharedPrevRow = prev;
215
+ sharedCurrRow = curr;
216
+ }
217
+ return result;
218
+ }
219
+ /**
220
+ * Evaluates a single normalized query token (`qToken`) against a normalized document token (`vToken`).
221
+ * Returns `null` when no match occurs, or a `{ kind, multiplier }` respecting:
222
+ * `exact (10,000) > prefix (3,000..3,050) > substring (1,500..1,550) > fuzzy (< 600)`.
223
+ *
224
+ * Hinglish: Query token (`qToken`) ko document token (`vToken`) se match karke `exact > prefix > substring > fuzzy`
225
+ * hierarchy ke mutabik multiplier deta hai.
226
+ */
227
+ export function scoreTokenMatch(qToken, vToken, params) {
228
+ if (!qToken || !vToken)
229
+ return null;
230
+ // 1. Exact token match
231
+ if (vToken === qToken) {
232
+ return {
233
+ kind: 'exact',
234
+ multiplier: EXACT_TOKEN_MULTIPLIER,
235
+ };
236
+ }
237
+ // 2. Prefix match (vToken starts with qToken)
238
+ if (vToken.startsWith(qToken)) {
239
+ const closenessBonus = 50 * (qToken.length / vToken.length);
240
+ return {
241
+ kind: 'prefix',
242
+ multiplier: PREFIX_TOKEN_MULTIPLIER + closenessBonus,
243
+ };
244
+ }
245
+ // 3. Substring (contains) match when qToken meets minimum substring length
246
+ if (qToken.length >= params.minSubstringLength && vToken.includes(qToken)) {
247
+ const closenessBonus = 50 * (qToken.length / vToken.length);
248
+ return {
249
+ kind: 'substring',
250
+ multiplier: SUBSTRING_TOKEN_MULTIPLIER + closenessBonus,
251
+ };
252
+ }
253
+ // 4. Configurable fuzzy / typo match (only when typoTolerance > 0, qToken has >= 3 chars, and first character matches)
254
+ const maxAllowedDistance = params.typoTolerance;
255
+ if (maxAllowedDistance > 0 &&
256
+ qToken.length >= 3 &&
257
+ vToken.length >= 2 &&
258
+ qToken.charCodeAt(0) === vToken.charCodeAt(0)) {
259
+ const dynamicMaxDistance = Math.min(maxAllowedDistance, Math.max(1, Math.ceil(qToken.length / 3)));
260
+ // 4a. Full-token fuzzy match
261
+ if (Math.abs(qToken.length - vToken.length) <= dynamicMaxDistance * 2) {
262
+ const dist = smartLevenshteinDistance(qToken, vToken);
263
+ if (dist <= dynamicMaxDistance) {
264
+ const maxLength = Math.max(qToken.length, vToken.length);
265
+ const accuracy = Math.max(0, 1 - dist / Math.max(3, maxLength));
266
+ if (accuracy >= 0.7) {
267
+ return {
268
+ kind: 'fuzzy',
269
+ multiplier: FUZZY_FULL_TOKEN_MAX_MULTIPLIER * Math.pow(accuracy, 3),
270
+ };
271
+ }
272
+ }
273
+ }
274
+ // 4b. Prefix fuzzy match (when document token is longer than query token)
275
+ if (vToken.length > qToken.length && qToken.length >= 4) {
276
+ const vPrefix = vToken.slice(0, qToken.length);
277
+ const prefixDist = smartLevenshteinDistance(qToken, vPrefix);
278
+ if (prefixDist <= dynamicMaxDistance) {
279
+ const accuracy = Math.max(0, 1 - prefixDist / Math.max(3, qToken.length));
280
+ if (accuracy >= 0.8) {
281
+ return {
282
+ kind: 'fuzzy',
283
+ multiplier: FUZZY_PREFIX_TOKEN_MAX_MULTIPLIER * Math.pow(accuracy, 3),
284
+ };
285
+ }
286
+ }
287
+ else if (vToken.length > qToken.length + 1) {
288
+ const vPrefixLong = vToken.slice(0, qToken.length + 1);
289
+ const prefixLongDist = smartLevenshteinDistance(qToken, vPrefixLong);
290
+ if (prefixLongDist <= dynamicMaxDistance) {
291
+ const accuracy = Math.max(0, 1 - prefixLongDist / Math.max(3, qToken.length));
292
+ if (accuracy >= 0.8) {
293
+ return {
294
+ kind: 'fuzzy',
295
+ multiplier: (FUZZY_PREFIX_TOKEN_MAX_MULTIPLIER - 50) * Math.pow(accuracy, 3),
296
+ };
297
+ }
298
+ }
299
+ }
300
+ }
301
+ }
302
+ return null;
303
+ }
304
+ /**
305
+ * Evaluates a prepared document against the normalized query and its deduplicated query tokens.
306
+ * Returns a `ScoredSearchCandidate` when the document meets `minMatchRatio` and `minScore`, or `null` otherwise.
307
+ *
308
+ * Hinglish: Prepared document ko query tokens ke khilaf evaluate karke score, `matchedTerms` aur `matchedFields`
309
+ * calculate karta hai; `minMatchRatio` ya `minScore` pura na hone par `null` deta hai.
310
+ */
311
+ export function evaluateDocumentMatch(doc, queryTokens, normalizedQuery, params) {
312
+ const includePaidPromotions = params.includePaidPromotions === true;
313
+ if (queryTokens.length === 0) {
314
+ return null;
315
+ }
316
+ if (!includePaidPromotions && doc.fields.length === 0) {
317
+ return null;
318
+ }
319
+ if (includePaidPromotions && doc.fields.length === 0 && doc.promotions.length === 0) {
320
+ return null;
321
+ }
322
+ let rawItemScore = 0;
323
+ let matchedQueryTokenCount = 0;
324
+ let bestMatchedPromotionWeight = 0;
325
+ const matchedTermsSet = new Set();
326
+ const matchedFieldsSet = new Set();
327
+ for (let qIdx = 0; qIdx < queryTokens.length; qIdx++) {
328
+ const qToken = queryTokens[qIdx];
329
+ let bestFieldTokenScore = 0;
330
+ let bestFieldMatchedTerm = '';
331
+ let bestFieldMatchedName = '';
332
+ for (let fIdx = 0; fIdx < doc.fields.length; fIdx++) {
333
+ const field = doc.fields[fIdx];
334
+ const fieldWeight = field.weight;
335
+ if (bestFieldTokenScore >= EXACT_TOKEN_MULTIPLIER * fieldWeight) {
336
+ continue;
337
+ }
338
+ const tokens = field.tokens;
339
+ for (let tIdx = 0; tIdx < tokens.length; tIdx++) {
340
+ const vToken = tokens[tIdx];
341
+ const match = scoreTokenMatch(qToken, vToken, params);
342
+ if (match !== null) {
343
+ const tokenScore = match.multiplier * fieldWeight;
344
+ if (tokenScore > bestFieldTokenScore) {
345
+ bestFieldTokenScore = tokenScore;
346
+ bestFieldMatchedTerm = vToken;
347
+ bestFieldMatchedName = field.name;
348
+ }
349
+ if (match.kind === 'exact') {
350
+ break;
351
+ }
352
+ }
353
+ }
354
+ }
355
+ let bestPromoTokenScore = 0;
356
+ let bestPromoMatchedTerm = '';
357
+ if (includePaidPromotions && doc.promotions.length > 0) {
358
+ for (let pIdx = 0; pIdx < doc.promotions.length; pIdx++) {
359
+ const promo = doc.promotions[pIdx];
360
+ const promoWeight = promo.weight;
361
+ if (bestMatchedPromotionWeight >= promoWeight &&
362
+ bestPromoTokenScore >= EXACT_TOKEN_MULTIPLIER * promoWeight) {
363
+ continue;
364
+ }
365
+ const tokens = promo.tokens;
366
+ for (let tIdx = 0; tIdx < tokens.length; tIdx++) {
367
+ const vToken = tokens[tIdx];
368
+ const match = scoreTokenMatch(qToken, vToken, params);
369
+ if (match !== null) {
370
+ if (promoWeight > bestMatchedPromotionWeight) {
371
+ bestMatchedPromotionWeight = promoWeight;
372
+ }
373
+ const tokenScore = match.multiplier * promoWeight;
374
+ if (tokenScore > bestPromoTokenScore) {
375
+ bestPromoTokenScore = tokenScore;
376
+ bestPromoMatchedTerm = vToken;
377
+ }
378
+ if (match.kind === 'exact') {
379
+ break;
380
+ }
381
+ }
382
+ }
383
+ }
384
+ }
385
+ const combinedTokenScore = bestFieldTokenScore + bestPromoTokenScore;
386
+ if (combinedTokenScore > 0) {
387
+ rawItemScore += combinedTokenScore;
388
+ matchedQueryTokenCount++;
389
+ if (bestFieldMatchedTerm) {
390
+ matchedTermsSet.add(bestFieldMatchedTerm);
391
+ }
392
+ if (bestFieldMatchedName) {
393
+ matchedFieldsSet.add(bestFieldMatchedName);
394
+ }
395
+ if (bestPromoMatchedTerm) {
396
+ matchedTermsSet.add(bestPromoMatchedTerm);
397
+ matchedFieldsSet.add('paidPromotion');
398
+ }
399
+ }
400
+ }
401
+ const matchRatio = matchedQueryTokenCount / queryTokens.length;
402
+ if (matchRatio < params.minMatchRatio) {
403
+ return null;
404
+ }
405
+ // Exact full-field phrase bonus when a multi-token query matches an entire normalized field string verbatim
406
+ if (queryTokens.length > 1 && matchRatio === 1) {
407
+ for (let fIdx = 0; fIdx < doc.fields.length; fIdx++) {
408
+ const field = doc.fields[fIdx];
409
+ for (let vIdx = 0; vIdx < field.normalizedValues.length; vIdx++) {
410
+ if (field.normalizedValues[vIdx] === normalizedQuery) {
411
+ rawItemScore += EXACT_PHRASE_BONUS_MULTIPLIER * field.weight;
412
+ matchedFieldsSet.add(field.name);
413
+ break;
414
+ }
415
+ }
416
+ }
417
+ if (includePaidPromotions && doc.promotions.length > 0) {
418
+ for (let pIdx = 0; pIdx < doc.promotions.length; pIdx++) {
419
+ const promo = doc.promotions[pIdx];
420
+ if (promo.keyword === normalizedQuery) {
421
+ rawItemScore += EXACT_PHRASE_BONUS_MULTIPLIER * promo.weight;
422
+ if (promo.weight > bestMatchedPromotionWeight) {
423
+ bestMatchedPromotionWeight = promo.weight;
424
+ }
425
+ break;
426
+ }
427
+ }
428
+ }
429
+ }
430
+ const finalScore = Math.round((matchRatio === 1 ? rawItemScore * 1.5 : rawItemScore * matchRatio) * 100) / 100;
431
+ if (finalScore <= params.minScore) {
432
+ return null;
433
+ }
434
+ if (includePaidPromotions) {
435
+ let paidPromotionGroup = 3;
436
+ let paidPromotionWeight = 0;
437
+ if (bestMatchedPromotionWeight > 0) {
438
+ paidPromotionGroup = 1;
439
+ paidPromotionWeight = bestMatchedPromotionWeight;
440
+ }
441
+ else if (doc.totalPromotionWeight > 0) {
442
+ paidPromotionGroup = 2;
443
+ paidPromotionWeight = doc.totalPromotionWeight;
444
+ }
445
+ return {
446
+ doc,
447
+ score: finalScore,
448
+ matchedTerms: Array.from(matchedTermsSet),
449
+ matchedFields: Array.from(matchedFieldsSet),
450
+ paidPromotionGroup,
451
+ paidPromotionWeight,
452
+ };
453
+ }
454
+ return {
455
+ doc,
456
+ score: finalScore,
457
+ matchedTerms: Array.from(matchedTermsSet),
458
+ matchedFields: Array.from(matchedFieldsSet),
459
+ };
460
+ }