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