import { pinyin, match as pinyinMatch } from "pinyin-pro"; import type { CorpConfig } from "../config/types.js"; export interface FuzzyMatchOptions { /** * If true, disables fuzzy/soft matching and requires exact substring matching. * Defaults to false (soft search by default). */ strict?: boolean; /** * Maximum edit distance allowed for typo / missing letter tolerance. * Defaults based on query length: * - length <= 2: 0 (no fuzzy edits) * - length 3..5: 1 (missing 1 letter or 1 typo) * - length >= 6: 2 (missing 1-2 letters) */ maxDistance?: number; } export type MatchReason = | "exact" | "substring" | "initials" | "pinyin" | "fuzzy_pinyin" | "levenshtein" | "subsequence" | "tokens" | "abbreviation" | "none"; export interface MatchScoreResult { matched: boolean; score: number; reason: MatchReason; } /** * Standard Levenshtein distance between two strings. */ export function levenshteinDistance(a: string, b: string): number { const m = a.length; const n = b.length; if (m === 0) return n; if (n === 0) return m; let prevRow = Array.from({ length: n + 1 }, (_, j) => j); let currRow: number[] = Array.from({ length: n + 1 }, () => 0); for (let i = 1; i <= m; i += 1) { currRow[0] = i; for (let j = 1; j <= n; j += 1) { if (a[i - 1] === b[j - 1]) { currRow[j] = prevRow[j - 1] ?? 0; } else { const sub = prevRow[j - 1] ?? 0; const ins = currRow[j - 1] ?? 0; const del = prevRow[j] ?? 0; currRow[j] = Math.min(sub, ins, del) + 1; } } const temp = prevRow; prevRow = currRow; currRow = temp; } return prevRow[n] ?? 0; } /** * Finds the minimum Levenshtein distance between `query` and any sliding window substring in `target`. * Supports queries missing a letter, having an extra letter, or having an internal typo. */ export function minSubstringLevenshtein(query: string, target: string): number { if (!query || !target) return 999; if (target.includes(query)) return 0; const qLen = query.length; if (target.length < qLen - 2) { return levenshteinDistance(query, target); } let min = 999; const minWindow = Math.max(1, qLen - 2); const maxWindow = Math.min(target.length, qLen + 2); for (let len = minWindow; len <= maxWindow; len += 1) { for (let i = 0; i <= target.length - len; i += 1) { const sub = target.slice(i, i + len); const dist = levenshteinDistance(query, sub); if (dist < min) min = dist; if (min === 0) return 0; } } return min; } /** * Normalizes Chinese text to toneless pinyin with fuzzy sound rules: * - Retroflex vs flat consonants: zh -> z, ch -> c, sh -> s * - Front vs back nasal sounds: ang -> an, eng -> en, ing -> in, iang -> ian, uang -> uan * - Strips non-alphanumeric whitespace */ export function normalizeFuzzyPinyin(str: string): string { if (!str) return ""; const pyTokens = pinyin(str, { toneType: "none", type: "array" }); return pyTokens .map((token) => token .toLowerCase() .replace(/zh/g, "z") .replace(/ch/g, "c") .replace(/sh/g, "s") .replace(/iang/g, "ian") .replace(/uang/g, "uan") .replace(/ang/g, "an") .replace(/eng/g, "en") .replace(/ing/g, "in") ) .join(""); } /** * Checks if all characters of `query` appear in order inside `target` (subsequence). */ export function isSubsequence(query: string, target: string): boolean { if (!query || !target) return false; let qIdx = 0; for (let tIdx = 0; tIdx < target.length && qIdx < query.length; tIdx += 1) { if (query[qIdx] === target[tIdx]) { qIdx += 1; } } return qIdx === query.length; } function searchTerms(value: string): string[] { const chunks = value.trim().toLowerCase().match(/[\u4e00-\u9fa5]+|[a-z0-9]+/g) ?? []; return chunks.flatMap((chunk) => { if (!/[\u4e00-\u9fa5]/.test(chunk)) return [chunk]; if (chunk.length <= 2) return [chunk]; const terms: string[] = []; for (let index = 0; index < chunk.length - 1; index += 1) { terms.push(chunk.slice(index, index + 2)); } return terms; }); } let wordSegmenter: Intl.Segmenter | undefined; function searchWords(value: string): string[] { wordSegmenter ??= new Intl.Segmenter("zh", { granularity: "word" }); const words: string[] = []; let nameChars = ""; const flushName = () => { if (nameChars) words.push(nameChars); nameChars = ""; }; for (const part of wordSegmenter.segment(value.trim().toLowerCase())) { // Uncommon enterprise names are often segmented into individual characters. if (part.isWordLike && /^[\u4e00-\u9fa5]$/.test(part.segment)) { nameChars += part.segment; } else { flushName(); if (part.isWordLike) words.push(part.segment); } } flushName(); return words; } function matchTokenizedQuery(query: string, target: string): MatchScoreResult { if (!/[\u4e00-\u9fa5]/.test(query)) { return { matched: false, score: 0, reason: "none" }; } const queryWords = searchWords(query); const wordMatches = queryWords.map((word) => fuzzyMatchString(word, target).matched); if (queryWords.length >= 2 && wordMatches.filter(Boolean).length >= queryWords.length - 1) { const allWordsMatch = queryWords.every((word, index) => wordMatches[index] || ( // A second matching word supplies context for a typo in a two-character // name, e.g. "瑞泰 半导体" -> "钰泰半导体". Single-word searches stay conservative. /^[\u4e00-\u9fa5]{2}$/.test(word) && minSubstringLevenshtein(word, target) <= 1 )); if (allWordsMatch) return { matched: true, score: 0.76, reason: "tokens" }; } const queryTerms = searchTerms(query); if (queryTerms.length < 2) return { matched: false, score: 0, reason: "none" }; const matchedTerms = queryTerms.filter((term) => fuzzyMatchString(term, target).matched); if (matchedTerms.length > 0) { const coverage = matchedTerms.length / queryTerms.length; return { matched: true, score: queryWords.length >= 2 ? Math.min(0.64, 0.56 + coverage * 0.2) : 0.56 + coverage * 0.2, reason: "tokens" }; } return { matched: false, score: 0, reason: "none" }; } /** * Core fuzzy string match engine: * Evaluates match across exact, substring, initials, pinyin, homophone/fuzzy pinyin, * sliding-window edit distance (missing/typo tolerance), and character subsequence. */ export function fuzzyMatchString( query: string, target: string, options: FuzzyMatchOptions = {} ): MatchScoreResult { const normQuery = query.trim().toLowerCase(); const normTarget = target.trim().toLowerCase(); if (!normQuery || !normTarget) { return { matched: false, score: 0, reason: "none" }; } // 1. Exact match if (normTarget === normQuery) { return { matched: true, score: 1.0, reason: "exact" }; } // 2. Substring match if (normTarget.includes(normQuery)) { return { matched: true, score: 0.95, reason: "substring" }; } // If strict mode is requested, only exact or substring matches are accepted. if (options.strict) { return { matched: false, score: 0, reason: "none" }; } const targetHasChinese = /[\u4e00-\u9fa5]/.test(normTarget); const queryHasChinese = /[\u4e00-\u9fa5]/.test(normQuery); // 3. Initials / Acronym match (e.g. "xzh" matches "谢子豪", "sc" matches "生产") if (targetHasChinese && normQuery.length >= 2) { const targetInitials = pinyin(normTarget, { pattern: "first", toneType: "none", type: "array" }) .join("") .toLowerCase(); if (targetInitials.includes(normQuery)) { return { matched: true, score: 0.9, reason: "initials" }; } } // 4. Pinyin-pro built-in match (handles full/partial pinyin matching against Chinese targets) if (targetHasChinese) { try { const pm = pinyinMatch(normTarget, normQuery, { precision: "start" }); if (pm && pm.length > 0) { return { matched: true, score: 0.88, reason: "pinyin" }; } } catch { // ignore match errors if non-standard regex chars } } // 5. Fuzzy Pinyin & Homophones (同音字、前后鼻音、平翘舌音) let targetFuzzyPinyin = ""; let queryFuzzyPinyin = ""; if (targetHasChinese || queryHasChinese) { targetFuzzyPinyin = normalizeFuzzyPinyin(normTarget); queryFuzzyPinyin = normalizeFuzzyPinyin(normQuery); if (queryFuzzyPinyin.length >= 2 && targetFuzzyPinyin.includes(queryFuzzyPinyin)) { return { matched: true, score: 0.85, reason: "fuzzy_pinyin" }; } } // 6. Missing letter / Typo tolerance (Levenshtein Distance) // Determine allowed distance based on query length: // - <= 2: 0 (no fuzzy edits to prevent excessive false positives) // - 3..5: 1 (missing 1 letter or 1 typo) // - >= 6: 2 (missing 1-2 letters) const defaultMaxDist = normQuery.length <= 2 ? 0 : normQuery.length <= 5 ? 1 : 2; const maxAllowedDist = options.maxDistance ?? defaultMaxDist; if (maxAllowedDist > 0) { // Check raw string distance const rawDist = minSubstringLevenshtein(normQuery, normTarget); if (rawDist <= maxAllowedDist) { return { matched: true, score: Math.max(0.6, 0.8 - rawDist * 0.1), reason: "levenshtein" }; } // Check fuzzy pinyin distance (e.g. pinyin with 1 missing letter) if ( (targetHasChinese || queryHasChinese) && queryFuzzyPinyin.length >= 3 && targetFuzzyPinyin.length >= 3 ) { const pinyinDist = minSubstringLevenshtein(queryFuzzyPinyin, targetFuzzyPinyin); if (pinyinDist <= maxAllowedDist) { return { matched: true, score: Math.max(0.6, 0.78 - pinyinDist * 0.1), reason: "levenshtein" }; } } } // 7. Subsequence match (loose character order, min query length 3) if (normQuery.length >= 3) { if ( isSubsequence(normQuery, normTarget) || ((targetHasChinese || queryHasChinese) && isSubsequence(queryFuzzyPinyin, targetFuzzyPinyin)) ) { return { matched: true, score: 0.65, reason: "subsequence" }; } } return { matched: false, score: 0, reason: "none" }; } /** * Matches an enterprise (`CorpConfig`) against a query across all its searchable fields, * returning the highest match score and reason. */ export function matchCorp( corp: CorpConfig, query: string, options: FuzzyMatchOptions = {} ): MatchScoreResult { const fields: Array<{ text: string | undefined; weight: number }> = [ { text: corp.name, weight: 1.2 }, { text: corp.id, weight: 1.1 }, { text: corp.source.staffId, weight: 1.0 }, { text: (corp.source as any).domain, weight: 1.0 }, { text: (corp.source as any).corpId, weight: 1.0 }, { text: corp.seal.tenantSlug, weight: 1.0 }, { text: (corp.source as any).tenantSlug, weight: 1.0 }, { text: (corp.source as any).tenantName, weight: 1.1 }, { text: corp.testCorpId, weight: 1.0 }, { text: corp.prodCorpId, weight: 1.0 }, { text: corp.environment ?? "production", weight: 0.8 }, { text: corp.source.type, weight: 0.8 }, { text: (corp.source as any).provider, weight: 0.8 } ]; let bestScore = 0; let bestReason: MatchReason = "none"; for (const field of fields) { if (!field.text) continue; const res = fuzzyMatchString(query, field.text, options); if (res.matched) { const weightedScore = res.score * field.weight; if (weightedScore > bestScore) { bestScore = weightedScore; bestReason = res.reason; } } } // When a long Chinese query contains a compact enterprise name in order (for // example, "苏州园区测绘" contains the leading "园测" of "园测信息科技股份有限公司"), // retain that candidate as a lower-confidence abbreviation match. This is // deliberately below exact/substring/pinyin matches and disabled in strict mode. if (!options.strict) { const queryChinese = query.trim().match(/[\u4e00-\u9fa5]/g)?.join("") ?? ""; if (queryChinese.length >= 3) { for (const field of fields) { if (!field.text) continue; const targetChinese = field.text.match(/[\u4e00-\u9fa5]/g)?.join("") ?? ""; const prefix = targetChinese.slice(0, 2); if (prefix.length < 2 || !isSubsequence(prefix, queryChinese)) continue; const weightedScore = 0.74 * field.weight; if (weightedScore > bestScore) { bestScore = weightedScore; bestReason = "abbreviation"; } } } for (const field of fields) { if (!field.text) continue; const res = matchTokenizedQuery(query, field.text); if (res.matched) { const weightedScore = res.score * field.weight; if (weightedScore > bestScore) { bestScore = weightedScore; bestReason = res.reason; } } } } return { matched: bestScore > 0, score: bestScore, reason: bestReason }; } /** * Filters a list of enterprises using soft fuzzy search (or strict search if requested), * and automatically sorts the matching results from highest relevance to lowest. */ export function filterCorpsFuzzy( corps: CorpConfig[], query: string, options: FuzzyMatchOptions = {} ): CorpConfig[] { const trimmed = query.trim(); if (!trimmed) return corps; const scored: Array<{ corp: CorpConfig; score: number }> = []; for (const corp of corps) { const res = matchCorp(corp, trimmed, options); if (res.matched) { scored.push({ corp, score: res.score }); } } // Sort by match score descending (highest confidence first) scored.sort((a, b) => b.score - a.score); // Once a strong candidate exists, suppress weak token-only suggestions. This // keeps a query such as "苏州园区测绘" focused on the compact-name match // instead of also returning every enterprise that merely contains "测绘". const strongMatches = scored.filter((item) => item.score >= 0.8); return (strongMatches.length > 0 ? strongMatches : scored).map((item) => item.corp); }