Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

providerSkillSearch.ts

105 lines2.6 KB

1import type { ServerProviderSkill } from "@t3tools/contracts";
2import {
3 insertRankedSearchResult,
4 normalizeSearchQuery,
5 scoreQueryMatch,
6} from "@t3tools/shared/searchRanking";
7​
8import { formatProviderSkillDisplayName } from "./providerSkillPresentation";
9​
10function scoreProviderSkill(skill: ServerProviderSkill, query: string): number | null {
11 const normalizedName = skill.name.toLowerCase();
12 const normalizedLabel = formatProviderSkillDisplayName(skill).toLowerCase();
13 const normalizedShortDescription = skill.shortDescription?.toLowerCase() ?? "";
14 const normalizedDescription = skill.description?.toLowerCase() ?? "";
15 const normalizedScope = skill.scope?.toLowerCase() ?? "";
16​
17 const scores = [
18 scoreQueryMatch({
19 value: normalizedName,
20 query,
21 exactBase: 0,
22 prefixBase: 2,
23 boundaryBase: 4,
24 includesBase: 6,
25 fuzzyBase: 100,
26 boundaryMarkers: ["-", "_", "/"],
27 }),
28 scoreQueryMatch({
29 value: normalizedLabel,
30 query,
31 exactBase: 1,
32 prefixBase: 3,
33 boundaryBase: 5,
34 includesBase: 7,
35 fuzzyBase: 110,
36 }),
37 scoreQueryMatch({
38 value: normalizedShortDescription,
39 query,
40 exactBase: 20,
41 prefixBase: 22,
42 boundaryBase: 24,
43 includesBase: 26,
44 }),
45 scoreQueryMatch({
46 value: normalizedDescription,
47 query,
48 exactBase: 30,
49 prefixBase: 32,
50 boundaryBase: 34,
51 includesBase: 36,
52 }),
53 scoreQueryMatch({
54 value: normalizedScope,
55 query,
56 exactBase: 40,
57 prefixBase: 42,
58 includesBase: 44,
59 }),
60 ].filter((score): score is number => score !== null);
61​
62 if (scores.length === 0) {
63 return null;
64 }
65​
66 return Math.min(...scores);
68​
69export function searchProviderSkills(
70 skills: ReadonlyArray<ServerProviderSkill>,
71 query: string,
72 limit = Number.POSITIVE_INFINITY,
73): ServerProviderSkill[] {
74 const enabledSkills = skills.filter((skill) => skill.enabled);
75 const normalizedQuery = normalizeSearchQuery(query, { trimLeadingPattern: /^\$+/ });
76​
77 if (!normalizedQuery) {
78 return enabledSkills;
79 }
80​
81 const ranked: Array<{
82 item: ServerProviderSkill;
83 score: number;
84 tieBreaker: string;
85 }> = [];
86​
87 for (const skill of enabledSkills) {
88 const score = scoreProviderSkill(skill, normalizedQuery);
89 if (score === null) {
90 continue;
91 }
92​
93 insertRankedSearchResult(
94 ranked,
95 {
96 item: skill,
97 score,
98 tieBreaker: `${formatProviderSkillDisplayName(skill).toLowerCase()}\u0000${skill.name}`,
99 },
100 limit,
101 );
102 }
103​
104 return ranked.map((entry) => entry.item);