Files
seal-use/src/core/corp-search/tokens.ts
T

55 lines
2.1 KiB
TypeScript

import { minSubstringLevenshtein } from "./distance.js";
import { fuzzyMatchString } from "./engine.js";
import { searchTerms, searchWords } from "./segment.js";
import type { MatchScoreResult } from "./types.js";
function noMatch(): MatchScoreResult {
return { matched: false, score: 0, reason: "none" };
}
/** Word-level pass: every segmented word matches the target (one typo tolerated via context). */
function matchQueryWords(queryWords: string[], target: string): MatchScoreResult | null {
if (queryWords.length < 2) return null;
const wordMatches = queryWords.map((word) => fuzzyMatchString(word, target).matched);
if (wordMatches.filter(Boolean).length < queryWords.length - 1) return null;
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 null;
return { matched: true, score: 0.76, reason: "tokens" };
}
/** Term-coverage pass: overlapping two-character terms of the query hit the target. */
function matchQueryTerms(
query: string,
queryWordCount: number,
target: string
): MatchScoreResult | null {
const queryTerms = searchTerms(query);
if (queryTerms.length < 2) return null;
const matchedTerms = queryTerms.filter((term) => fuzzyMatchString(term, target).matched);
if (matchedTerms.length === 0) return null;
const coverage = matchedTerms.length / queryTerms.length;
return {
matched: true,
score: queryWordCount >= 2 ? Math.min(0.64, 0.56 + coverage * 0.2) : 0.56 + coverage * 0.2,
reason: "tokens"
};
}
export function matchTokenizedQuery(query: string, target: string): MatchScoreResult {
if (!/[\u4e00-\u9fa5]/.test(query)) {
return noMatch();
}
const queryWords = searchWords(query);
return matchQueryWords(queryWords, target) ?? matchQueryTerms(query, queryWords.length, target) ?? noMatch();
}