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

paletteSearch.ts

1,250 lines47.6 KB

1/** Shared ranking keeps command palettes and MCP thread search consistent across surfaces. */
2​
3import type { OrchestrationV2ThreadOpens } from "@t3tools/contracts";
4​
5import { WORKTREE_BRANCH_PREFIX } from "./git.ts";
6​
7const ALPHANUMERIC = /[\p{L}\p{N}]/u;
8const LOWERCASE = /\p{Ll}/u;
9const UPPERCASE = /\p{Lu}/u;
10const DIGIT = /\p{N}/u;
11const LETTER = /\p{L}/u;
12const COMBINING_MARKS = /\p{M}/gu;
13// Emoji and other symbols can be searched for, so they start words too.
14const SYMBOL = /\p{So}/u;
15const APOSTROPHE = /['’]/;
16const CURLY_APOSTROPHES = /[\u2018\u2019]/g;
17​
18interface SearchField {
19 /** Case- and accent-folded text, one UTF-16 unit per source unit. */
20 readonly text: string;
21 /** 1 where a word starts in `text`. */
22 readonly wordStarts: Uint8Array;
24​
25export interface SearchRange {
26 readonly start: number;
27 readonly end: number;
29​
30// Thread titles, branches, and project names repeat across keystrokes; folding
31// them once keeps a keystroke to plain string scans. Each keystroke reads every
32// field, so the limit must hold all of them or the cache clears every time; a
33// field is a few bytes per character.
34const fieldCache = new Map<string, SearchField>();
35const FIELD_CACHE_LIMIT = 100_000;
36​
37function foldCharacter(character: string): string {
38 // A typed straight apostrophe finds a curly one: iOS keyboards type "’".
39 return character
40 .normalize("NFKD")
41 .replace(COMBINING_MARKS, "")
42 .toLowerCase()
43 .replace("ς", "σ")
44 .replace(/[‘’]/, "'");
46​
47/**
48 * `text` with case and accents folded one UTF-16 unit at a time, so offsets
49 * and word starts still read from `text` and highlights need no mapping. A
50 * letter that folds to more or less than one unit ("ß", "fi") stays as it is.
51 */
52function foldInPlace(text: string): string {
53 return text
54 .replace(/[\u0080-\uffff]/g, (character) => {
55 const folded = foldCharacter(character);
56 return folded.length === 1 ? folded : character;
57 })
58 .toLowerCase();
60​
61// Chinese and Japanese text has no spaces, so each ideograph or kana starts a word.
62function isCjk(character: string): boolean {
63 const code = character.codePointAt(0)!;
64 return (
65 (code >= 0x3040 && code <= 0x30ff) ||
66 (code >= 0x3400 && code <= 0x4dbf) ||
67 (code >= 0x4e00 && code <= 0x9fff) ||
68 (code >= 0xf900 && code <= 0xfaff)
69 );
71​
72// Two Chinese, Japanese, or Korean characters already make a common word.
73function hasCjkWord(token: string): boolean {
74 return Array.from(token).some((character) => {
75 const code = character.codePointAt(0)!;
76 return isCjk(character) || (code >= 0xac00 && code <= 0xd7af);
77 });
79​
80/**
81 * Whether `character` starts a word after `previous` and `beforePrevious`
82 * ("" at the start): after a non-letter, at a camelCase or digit boundary, or
83 * at any Chinese or Japanese character. The one rule for titles and messages.
84 */
85function isWordStart(
86 beforePrevious: string,
87 previous: string,
88 character: string,
89 next: string,
90): boolean {
91 // "Julius’s": a possessive or contraction does not start a word.
92 const afterApostrophe = APOSTROPHE.test(previous) && ALPHANUMERIC.test(beforePrevious);
93 return (
94 (ALPHANUMERIC.test(character) || SYMBOL.test(character)) &&
95 !afterApostrophe &&
96 (previous === "" ||
97 !ALPHANUMERIC.test(previous) ||
98 (LOWERCASE.test(previous) && UPPERCASE.test(character)) ||
99 // The last capital of an acronym starts the next word: "JSONSchema".
100 (UPPERCASE.test(previous) && UPPERCASE.test(character) && LOWERCASE.test(next)) ||
101 DIGIT.test(previous) !== DIGIT.test(character) ||
102 isCjk(character))
103 );
105​
106function foldSearchField(source: string): SearchField {
107 const wordStarts = new Uint8Array(source.length);
108 const characters = Array.from(source);
109 let index = 0;
110 for (const [position, character] of characters.entries()) {
111 const previous = characters[position - 1] ?? "";
112 const next = characters[position + 1] ?? "";
113 if (isWordStart(characters[position - 2] ?? "", previous, character, next)) {
114 wordStarts[index] = 1;
115 }
116 index += character.length;
117 }
118 return { text: foldInPlace(source), wordStarts };
120​
121function prepareSearchField(source: string): SearchField {
122 const cached = fieldCache.get(source);
123 if (cached) return cached;
124 // Oldest first out. A read does not re-insert: that would cost more than the
125 // fold it saves, and the limit holds far more fields than a keystroke reads.
126 if (fieldCache.size >= FIELD_CACHE_LIMIT) {
127 fieldCache.delete(fieldCache.keys().next().value!);
128 }
129 const field = foldSearchField(source);
130 fieldCache.set(source, field);
131 return field;
133​
134// Quotes around a pasted query: "fix sidebar".
135const WRAPPING_QUOTES = /^\s*["'`“”‘’]+|["'`“”‘’]+\s*$/g;
136​
137/** Folded, whitespace-collapsed query; empty when there is nothing to match. */
138export function foldSearchQuery(query: string): string {
139 return foldInPlace(query.replace(WRAPPING_QUOTES, "").normalize("NFC"))
140 .split(/\s+/)
141 .filter((token) => token.length > 0)
142 .join(" ");
144​
145function wordEnd(field: SearchField, index: number): number {
146 let end = index + 1;
147 while (end < field.text.length && !field.wordStarts[end] && ALPHANUMERIC.test(field.text[end]!)) {
148 end++;
149 }
150 return end;
152​
153// One substitution, insertion, deletion, or swap of neighbours; with
154// `swapOnly`, only a swap.
155function withinOneEdit(left: string, right: string, swapOnly: boolean): boolean {
156 if (Math.abs(left.length - right.length) > (swapOnly ? 0 : 1)) return false;
157 let index = 0;
158 while (index < left.length && index < right.length && left[index] === right[index]) index++;
159 const restLeft = left.slice(index);
160 const restRight = right.slice(index);
161 const swapped =
162 restLeft.length > 1 &&
163 restLeft[0] === restRight[1] &&
164 restLeft[1] === restRight[0] &&
165 restLeft.slice(2) === restRight.slice(2);
166 if (swapOnly) return swapped;
167 return (
168 swapped ||
169 restLeft === restRight ||
170 restLeft.slice(1) === restRight.slice(1) ||
171 restLeft.slice(1) === restRight ||
172 restLeft === restRight.slice(1)
173 );
175​
176const WHOLE_WORD = 1;
177// The bonus for a field equal to the whole query lifts a whole word to this.
178const WHOLE_NAME = 1.5;
179const MID_WORD = 0.3;
180const TYPO = 0.45;
181// Whole words typed together are exact, so they rank with typos and above
182// mid-word hits, though below a match at a word start.
183const JOINED_WORDS = 0.6;
184​
185interface TokenMatch extends SearchRange {
186 readonly score: number;
187 /** Separate ranges, for words typed together. */
188 readonly letters?: ReadonlyArray<SearchRange>;
190​
191/**
192 * Mid-word hits need four or more characters and `midWord`, so "del" does not find "model".
193 * Typos preserve the first letter except for swaps; short tokens allow fewer edits to limit noise.
194 * Numbers never match with a typo because different pull request numbers must stay distinct.
195 */
196function matchToken(
197 field: SearchField,
198 token: string,
199 typos: boolean,
200 isPrimary: boolean,
201 midWord: boolean,
202): TokenMatch | null {
203 if (token.length === 0) return null;
204 let best: TokenMatch | null = null;
205 let ownBoundary: boolean | undefined;
206 for (
207 let index = field.text.indexOf(token);
208 index !== -1;
209 index = field.text.indexOf(token, index + 1)
210 ) {
211 // A token that opens with punctuation (".ts") brings its own boundary, as in messages.
212 if (
213 field.wordStarts[index] ||
214 (ownBoundary ??= !ALPHANUMERIC.test(token[0]!) && !SYMBOL.test(token[0]!))
215 ) {
216 // Whole when the match ends where a word ends: "t3c" is a prefix of
217 // "t3code", ".ts" whole in "index.ts" but a prefix in "parser.tsx".
218 const end = index + token.length;
219 const whole =
220 end >= field.text.length ||
221 field.wordStarts[end] === 1 ||
222 !ALPHANUMERIC.test(field.text[end]!);
223 let runEnd = end;
224 while (runEnd < field.text.length && ALPHANUMERIC.test(field.text[runEnd]!)) runEnd++;
225 const score = whole ? WHOLE_WORD : 0.7 + (0.2 * token.length) / (runEnd - index);
226 if (best === null || score > best.score) {
227 best = { score, start: index, end: index + token.length };
228 }
229 if (score === WHOLE_WORD) return best;
230 } else if (midWord && token.length >= 4 && best === null) {
231 best = { score: MID_WORD, start: index, end: index + token.length };
232 }
233 }
234 // Joined words are exact, so they count without the typo pass: a strong
235 // match elsewhere must not hide "VS Code" for "vscode".
236 if ((best === null || best.score <= MID_WORD) && isPrimary) {
237 const joined = matchJoinedWords(field, token);
238 if (joined) return joined;
239 }
240 if ((best !== null && best.score > MID_WORD) || !typos || token.length < 3) return best;
241 // Numbers skip typos to keep pull requests distinct. Words with digits ("t3code") do not.
242 if (LETTER.test(token)) {
243 for (let index = 0; index < field.text.length; index++) {
244 if (!field.wordStarts[index]) continue;
245 // People rarely mistype the first letter, so a typo keeps it, unless it
246 // swaps the first two of a longer word ("ing" is not "nig…").
247 const first = field.text[index];
248 const firstLetterKept =
249 first === token[0] ||
250 (token.length > 3 && first === token[1] && field.text[index + 1] === token[0]);
251 if (!firstLetterKept) continue;
252 // The whole run, across camelCase joins: "githbu" is "GitHub".
253 let runEnd = index + 1;
254 while (runEnd < field.text.length && ALPHANUMERIC.test(field.text[runEnd]!)) runEnd++;
255 const word = field.text.slice(index, runEnd);
256 // Short tokens forgive a swapped pair or one missing letter ("srv" for
257 // "serv…"); any other edit of a three- or four-letter word matches too
258 // much ("cron" would find every "con…").
259 const short = token.length <= 4;
260 // The same length first, so "githbu" highlights all of "GitHub".
261 const lengths = short
262 ? [token.length, token.length + 1]
263 : [token.length, token.length - 1, token.length + 1];
264 for (const length of lengths) {
265 if (length > word.length) continue;
266 const prefix = word.slice(0, length);
267 if (withinOneEdit(token, prefix, short && length === token.length)) {
268 return { score: TYPO, start: index, end: index + length };
269 }
270 }
271 }
272 }
273 return best;
275​
276/**
277 * Short words followed by a short prefix are noise inside a title ("inth" in "in thread").
278 * Allow them at its start ("t3co"), before three letters ("gomod"), or a whole word ("vscode").
279 */
280function matchJoinedWords(field: SearchField, token: string): TokenMatch | null {
281 for (
282 let start = field.text.indexOf(token[0]!);
283 start !== -1;
284 start = field.text.indexOf(token[0]!, start + 1)
285 ) {
286 if (!field.wordStarts[start]) continue;
287 const runs: SearchRange[] = [];
288 let at = start;
289 let rest = token;
290 while (rest.length > 0 && at < field.text.length) {
291 const end = wordEnd(field, at);
292 if (rest.length <= end - at && field.text.startsWith(rest, at)) {
293 runs.push({ start: at, end: at + rest.length });
294 rest = "";
295 } else if (rest.startsWith(field.text.slice(at, end))) {
296 runs.push({ start: at, end });
297 rest = rest.slice(end - at);
298 at = end;
299 while (at < field.text.length && !field.wordStarts[at]) at++;
300 } else {
301 break;
302 }
303 }
304 const last = runs.at(-1);
305 if (rest.length > 0 || last === undefined || runs.length < 2) continue;
306 if (
307 last.end === wordEnd(field, last.start) ||
308 last.end - last.start >= 3 ||
309 start === field.wordStarts.indexOf(1) ||
310 runs.slice(0, -1).every((run) => run.end - run.start >= 3)
311 ) {
312 return { score: JOINED_WORDS, start, end: last.end, letters: runs };
313 }
314 }
315 return null;
317​
318interface WeightedSearchField {
319 readonly value: string;
320 /** `value` folded; set on first use, so fields kept across keystrokes fold once. */
321 prepared?: SearchField;
322 readonly weight: number;
323 /** Only a whole-word match counts, as for a short query against keywords. */
324 readonly wholeWords?: boolean;
325 /**
326 * Only a match at a word start counts, without typos: hidden keywords that
327 * matched loosely would list results the user cannot see why for.
328 */
329 readonly keyword?: boolean;
330 /**
331 * Where the thread lives (project, environment): it helps a match, but a
332 * word start there does not make the match strong, so it never turns off
333 * joined words or typos for the titles.
334 */
335 readonly context?: boolean;
336 /**
337 * A token of four or more letters may match inside a word here. Only thread
338 * titles allow it: inside a command name or a branch it reads as junk
339 * ("arch" in "Search").
340 */
341 readonly midWord?: boolean;
343​
344interface SearchFieldsMatch {
345 /** Roughly 0.3 (inside a word) to 1.5 (exact title). */
346 readonly quality: number;
347 /** Every token matched at a word start, without a typo. */
348 readonly strong: boolean;
349 /** Source ranges matched in the first field, for highlighting. */
350 readonly primaryRanges: ReadonlyArray<SearchRange>;
352​
353function preparedField(weighted: WeightedSearchField): SearchField {
354 return (weighted.prepared ??= prepareSearchField(weighted.value));
356​
357const FILLER_WORDS = new Set(["a", "an", "and", "for", "in", "of", "on", "the", "to", "with"]);
358​
359// Sorted, with overlapping ranges joined.
360function mergeRanges(ranges: ReadonlyArray<SearchRange>): SearchRange[] {
361 const merged: SearchRange[] = [];
362 for (const range of [...ranges].sort((left, right) => left.start - right.start)) {
363 const last = merged.at(-1);
364 if (last && range.start <= last.end) {
365 merged[merged.length - 1] = { start: last.start, end: Math.max(last.end, range.end) };
366 } else {
367 merged.push({ start: range.start, end: range.end });
368 }
369 }
370 return merged;
372​
373// A keystroke scores every thread for one query, so its tokens are split once.
374let lastQuery:
375 | { readonly query: string; readonly tokens: string[]; readonly fillerOptional: boolean }
376 | undefined;
377​
378function queryTokens(normalizedQuery: string) {
379 if (lastQuery?.query !== normalizedQuery) {
380 const tokens = normalizedQuery.split(" ").filter((token) => token.length > 0);
381 // A phrase-style query ("fix the sidebar") carries filler words a name may
382 // leave out; they count where they match but are not required.
383 lastQuery = {
384 query: normalizedQuery,
385 tokens,
386 fillerOptional: tokens.some((token) => !FILLER_WORDS.has(token)),
387 };
388 }
389 return lastQuery;
391​
392/**
393 * Every query token must match some field. Quality is the mean of each token's
394 * best weighted match, plus a bonus when the first field holds the whole query
395 * as a phrase or equals it.
396 */
397function matchSearchFields(
398 normalizedQuery: string,
399 fields: ReadonlyArray<WeightedSearchField>,
400 options?: { readonly typos?: boolean },
401): SearchFieldsMatch | null {
402 if (normalizedQuery.length === 0) return null;
403 const primary = fields[0]?.value ? preparedField(fields[0]) : undefined;
404 // An empty token would match everywhere, and loop forever in `matchToken`.
405 const { tokens, fillerOptional } = queryTokens(normalizedQuery);
406 if (tokens.length === 0) return null;
407 const primaryRanges: SearchRange[] = [];
408 let total = 0;
409 let counted = 0;
410 let strong = true;
411 for (const token of tokens) {
412 let best = 0;
413 let bestPrimary: TokenMatch | null = null;
414 let atWordStart = false;
415 for (const weighted of fields) {
416 if (weighted.value.length === 0) continue;
417 const { weight, wholeWords, keyword, context, midWord } = weighted;
418 const field = preparedField(weighted);
419 if (best >= weight && field !== primary && atWordStart) continue;
420 const typos = (options?.typos ?? false) && !keyword;
421 // Joined words only count in the name.
422 const match = matchToken(field, token, typos, field === primary, midWord ?? false);
423 if (match === null || match.score < (wholeWords ? WHOLE_WORD : keyword ? 0.7 : 0)) continue;
424 if (field === primary) bestPrimary = match;
425 if (match.score >= 0.7 && !context) atWordStart = true;
426 if (match.score * weight > best) best = match.score * weight;
427 }
428 if (best === 0) {
429 if (fillerOptional && FILLER_WORDS.has(token)) continue;
430 return null;
431 }
432 strong &&= atWordStart;
433 if (bestPrimary) primaryRanges.push(...(bestPrimary.letters ?? [bestPrimary]));
434 total += best;
435 counted += 1;
436 }
437 let quality = total / counted;
438 if (primary) {
439 if (primary.text === normalizedQuery) quality += WHOLE_NAME - WHOLE_WORD;
440 else if (tokens.length > 1 && primary.text.includes(normalizedQuery)) quality += 0.25;
441 }
442 return {
443 quality,
444 strong,
445 primaryRanges: mergeRanges(primaryRanges),
446 };
448​
449// A two-letter Latin substring of a message is noise rather than a match.
450const MESSAGE_TOKEN_MIN_LENGTH = 3;
451​
452/**
453 * Keep accents: the server index folds Latin accents, and stripping marks breaks Korean/Japanese.
454 * Every `long` token must match; `short` tokens only narrow hits. No long tokens means no search.
455 * Two CJK characters count as long.
456 */
457export function messageSearchTokens(query: string): {
458 readonly long: ReadonlyArray<string>;
459 readonly short: ReadonlyArray<string>;
460 /** Every token, in the order typed. */
461 readonly words: ReadonlyArray<string>;
462} {
463 const tokens = query
464 .replace(WRAPPING_QUOTES, "")
465 // The index stores apostrophes straight, as `indexedMessageText` writes them.
466 .replace(CURLY_APOSTROPHES, "'")
467 .normalize("NFC")
468 .toLowerCase()
469 .split(/\s+/)
470 .filter((token) => token.length > 0);
471 const searchable = (token: string) => {
472 const length = Array.from(token).length;
473 return length >= MESSAGE_TOKEN_MIN_LENGTH || (length === 2 && hasCjkWord(token));
474 };
475 return {
476 long: tokens.filter(searchable),
477 short: tokens.filter((token) => !searchable(token)),
478 words: tokens,
479 };
481​
482/**
483 * Matches the query's words side by side as whole words, as typed, whatever
484 * whitespace is between them and ignoring case; null for a single word.
485 */
486export function messagePhrase(query: string): RegExp | null {
487 const { words } = messageSearchTokens(query);
488 return words.length > 1
489 ? new RegExp(
490 `(?<![\\p{L}\\p{N}])${words
491 .map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
492 .join("\\s+")}(?![\\p{L}\\p{N}])`,
493 "iu",
494 )
495 : null;
497​
498// Words written together, as typed, rank above the same words apart, as in
499// titles; words near each other rank above words far apart.
500const MESSAGE_PHRASE_BONUS = 0.25;
501const MESSAGE_NEAR_BONUS = 0.1;
502// About what a result row shows.
503const MESSAGE_NEAR_SPAN = 60;
504​
505const NON_ASCII = /[\u0080-\uffff]/;
506// A message token shorter than this must start a word: "fts" is not in "drafts".
507const MESSAGE_WORD_START_LENGTH = 4;
508const MESSAGE_PREFIX = 0.8;
509​
510function startsWordAt(text: string, index: number): boolean {
511 const character = text[index]!;
512 // A token that opens with punctuation (such as ".ts") brings its own boundary.
513 if (!ALPHANUMERIC.test(character) && !SYMBOL.test(character)) return true;
514 return isWordStart(
515 text[index - 2] ?? "",
516 text[index - 1] ?? "",
517 character,
518 text[index + 1] ?? "",
519 );
521​
522// Whether a word ends right before `end` in `text`.
523function endsWordAt(text: string, end: number): boolean {
524 return end >= text.length || !ALPHANUMERIC.test(text[end]!) || startsWordAt(text, end);
526​
527// A commit SHA or UUID part: seven or more hex characters with a digit.
528const HEX_ID = /^(?=[a-f]*\d)[0-9a-f]{7,}$/i;
529​
530// Where `token` best sits in `folded`, a fold of `text`: every place it is a
531// whole word, else a word start, else inside a word. Hits past the start of a
532// hex ID do not count ("cafe" in "7cafe52bb8"), though a pasted SHA prefix
533// does.
534function findMessageToken(
535 text: string,
536 folded: string,
537 token: string,
538): { readonly at: ReadonlyArray<number>; readonly quality: number } | null {
539 let quality = 0;
540 let at: number[] = [];
541 // The letters-and-digits run around the hit, kept for later hits in the
542 // same run: rescanning it per hit is quadratic in a long run ("0000" in a
543 // hex dump).
544 let run = { start: 0, end: -1, hex: false };
545 for (let index = folded.indexOf(token); index !== -1; index = folded.indexOf(token, index + 1)) {
546 if (index + token.length > run.end) {
547 let start = index;
548 while (start > 0 && ALPHANUMERIC.test(text[start - 1]!)) start--;
549 let end = index + token.length;
550 while (end < text.length && ALPHANUMERIC.test(text[end]!)) end++;
551 run = { start, end, hex: HEX_ID.test(text.slice(start, end)) };
552 }
553 if (run.hex && run.start < index) continue;
554 const found = !startsWordAt(text, index)
555 ? MID_WORD
556 : endsWordAt(text, index + token.length)
557 ? 1
558 : MESSAGE_PREFIX;
559 if (found > quality) {
560 quality = found;
561 at = [index];
562 } else if (found === quality) {
563 at.push(index);
564 }
565 }
566 return at.length === 0 ? null : { at, quality };
568​
569export interface MessageMatch {
570 /**
571 * 1 when every searched word is a whole word, MESSAGE_PREFIX when one only
572 * starts a word ("mode" in "model"), MID_WORD when one only appears inside
573 * words, plus MESSAGE_PHRASE_BONUS when the words are written together as
574 * typed, else MESSAGE_NEAR_BONUS when they sit within a row's width.
575 */
576 readonly quality: number;
577 /** Where a snippet should start to show the match. */
578 readonly offset: number;
580​
581/**
582 * Grades messages against a query, so message hits rank like titles: null
583 * when a token is missing or a short one never starts a word ("fts" in
584 * "drafts"). Case and accents are ignored, as in the server's index. The
585 * query is prepared once, since the server grades thousands of hits for it.
586 */
587export function messageMatcher(query: string): (text: string) => MessageMatch | null {
588 const { long, short, words } = messageSearchTokens(query);
589 const tokens = [...long, ...short].map((token) => ({
590 token,
591 // Marks go from the folded token: lowercasing "İ" adds one.
592 folded: foldInPlace(token).replace(COMBINING_MARKS, ""),
593 nonAscii: NON_ASCII.test(token),
594 mustStartWord: Array.from(token).length < MESSAGE_WORD_START_LENGTH,
595 // Too short to search, so it only narrows: grading by it would reorder
596 // results on each keystroke while the next word is typed ("nvme s").
597 grades: long.includes(token),
598 }));
599 const phrase = messagePhrase(query);
600 // Accents typed or left out still read as written together: "cafe open"
601 // in "Café open".
602 const foldedPhrase = messagePhrase(
603 words.map((word) => foldInPlace(word).replace(COMBINING_MARKS, "")).join(" "),
604 );
605 const queryNonAscii = NON_ASCII.test(query);
606 return (text) => {
607 const lower = text.toLowerCase();
608 // "İ" lowercases to two units, which would shift every offset after it.
609 const plain = lower.length === text.length ? lower : foldInPlace(text);
610 let folded: string | null = null;
611 let quality = 1;
612 const positions: Array<ReadonlyArray<number>> = [];
613 for (const { token, folded: foldedToken, nonAscii, mustStartWord, grades } of tokens) {
614 let found = findMessageToken(text, plain, token);
615 // Accents typed or left out: "cafe" finds "Café", also after "cafeteria".
616 if (found?.quality !== 1 && foldedToken.length > 0 && (nonAscii || NON_ASCII.test(text))) {
617 found = findMessageToken(text, (folded ??= foldInPlace(text)), foldedToken);
618 }
619 if (found === null) return null;
620 if (found.quality === MID_WORD && mustStartWord) return null;
621 if (grades) quality = Math.min(quality, found.quality);
622 positions.push(found.at);
623 }
624 // Written together as typed: the snippet starts there. Apostrophes are
625 // straight in the query, and straightening keeps offsets.
626 const straight = (value: string) => value.replace(CURLY_APOSTROPHES, "'");
627 const together =
628 phrase?.exec(straight(plain)) ??
629 (queryNonAscii || NON_ASCII.test(text)
630 ? foldedPhrase?.exec(straight((folded ??= foldInPlace(text))))
631 : null);
632 if (together) return { quality: quality + MESSAGE_PHRASE_BONUS, offset: together.index };
633 // Else the shortest stretch that holds every word: the snippet starts
634 // there, so it shows them all, and words close together rank above words
635 // far apart ("lakebed perf").
636 const near = shortestSpan(positions);
637 return {
638 quality:
639 long.length > 1 && near.length <= MESSAGE_NEAR_SPAN
640 ? quality + MESSAGE_NEAR_BONUS
641 : quality,
642 offset: near.start,
643 };
644 };
646​
647// The shortest stretch of text holding one place of each word, from each
648// word's places in order.
649function shortestSpan(places: ReadonlyArray<ReadonlyArray<number>>): {
650 readonly start: number;
651 readonly length: number;
652} {
653 const hits = places
654 .flatMap((at, word) => at.map((index) => ({ index, word })))
655 .sort((left, right) => left.index - right.index);
656 const counts = places.map(() => 0);
657 let covered = 0;
658 let best = { start: hits[0]?.index ?? 0, length: Number.POSITIVE_INFINITY };
659 let left = 0;
660 for (const hit of hits) {
661 counts[hit.word] = (counts[hit.word] ?? 0) + 1;
662 if (counts[hit.word] === 1) covered++;
663 while (covered === places.length) {
664 const first = hits[left]!;
665 if (hit.index - first.index < best.length) {
666 best = { start: first.index, length: hit.index - first.index };
667 }
668 counts[first.word] = (counts[first.word] ?? 1) - 1;
669 if (counts[first.word] === 0) covered--;
670 left++;
671 }
672 }
673 return best;
675​
676/**
677 * Ranges of `text` that contain a long message search token, for message
678 * snippets, ignoring case and accents. Shorter tokens would light up half the
679 * snippet, and a short long token only counts where it starts a word.
680 * Snippets vary per query, so they skip the field cache.
681 */
682export function findSearchTokenRanges(text: string, query: string): SearchRange[] {
683 const tokens = new Map(
684 messageSearchTokens(query)
685 .long.map(
686 (token) =>
687 [foldSearchQuery(token), Array.from(token).length < MESSAGE_WORD_START_LENGTH] as const,
688 )
689 // Some tokens fold to nothing ("´´´"), which would match everywhere.
690 .filter(([token]) => token.length > 0),
691 );
692 if (tokens.size === 0) return [];
693 const field = foldSearchField(text);
694 const ranges: SearchRange[] = [];
695 for (const [token, needsWordStart] of tokens) {
696 // A token that opens with punctuation brings its own boundary, as in scoring.
697 const ownBoundary = !ALPHANUMERIC.test(token[0]!) && !SYMBOL.test(token[0]!);
698 for (let index = field.text.indexOf(token); index !== -1;) {
699 if (needsWordStart && !ownBoundary && !field.wordStarts[index]) {
700 index = field.text.indexOf(token, index + 1);
701 continue;
702 }
703 ranges.push({ start: index, end: index + token.length });
704 index = field.text.indexOf(token, index + token.length);
705 }
706 }
707 return mergeRanges(ranges);
709​
710export interface SearchTextPart {
711 readonly text: string;
712 readonly highlighted: boolean;
713 readonly start: number;
715​
716/** `text` cut into plain and highlighted parts at sorted, non-overlapping `ranges`. */
717export function splitSearchText(
718 text: string,
719 ranges: ReadonlyArray<SearchRange>,
720): SearchTextPart[] {
721 const parts: SearchTextPart[] = [];
722 let cursor = 0;
723 for (const range of ranges) {
724 if (range.start > cursor) {
725 parts.push({ text: text.slice(cursor, range.start), highlighted: false, start: cursor });
726 }
727 parts.push({ text: text.slice(range.start, range.end), highlighted: true, start: range.start });
728 cursor = range.end;
729 }
730 if (cursor < text.length || parts.length === 0) {
731 parts.push({ text: text.slice(cursor), highlighted: false, start: cursor });
732 }
733 return parts;
735​
736const DAY_MS = 24 * 60 * 60 * 1000;
737/** Both activity recency and open counts halve every two weeks. */
738export const SEARCH_RECENCY_HALF_LIFE_MS = 14 * DAY_MS;
739/**
740 * Opens closer together than this count once, so flipping between threads is
741 * not frequency. Clients skip sending them.
742 */
743export const THREAD_OPEN_DEDUPE_MS = 10 * 60 * 1000;
744const THREAD_SEARCH_PICK_LIMIT = 3;
745/** Picked queries are stored this long; clients send no more. */
746const THREAD_SEARCH_PICK_MAX_LENGTH = 32;
747​
748/**
749 * `query` as a pick is stored and compared: folded, then cut to the stored
750 * length without splitting an emoji in two. Clients and the server both use
751 * it, so a long pick matches its query again.
752 */
753export function pickedQuery(query: string): string {
754 const cut = foldSearchQuery(query).slice(0, THREAD_SEARCH_PICK_MAX_LENGTH);
755 return (/[\ud800-\udbff]$/.test(cut) ? cut.slice(0, -1) : cut).trim();
757​
758function decay(ageMs: number): number {
759 return 2 ** (-Math.max(0, ageMs) / SEARCH_RECENCY_HALF_LIFE_MS);
761​
762/** Server-stored open history; see `OrchestrationV2ThreadOpens`. */
763export type ThreadOpenStats = OrchestrationV2ThreadOpens;
764​
765/**
766 * Next open stats after an open at `at`. `query` is the palette query that
767 * picked the thread, when it was opened from search.
768 */
769export function recordThreadOpen(
770 previous: ThreadOpenStats | null,
771 at: number,
772 query: string | undefined,
773): ThreadOpenStats {
774 const pick = pickedQuery(query ?? "");
775 // Picks that no longer count are not kept or synced.
776 const earlier = (previous?.picks ?? []).filter((entry) => at - entry.at <= PICK_WINDOW_MS);
777 const picks = pick
778 ? [{ query: pick, at }, ...earlier.filter((entry) => entry.query !== pick)].slice(
779 0,
780 THREAD_SEARCH_PICK_LIMIT,
781 )
782 : earlier;
783 if (previous !== null && at - previous.openedAt < THREAD_OPEN_DEDUPE_MS) {
784 return { ...previous, picks };
785 }
786 const score = previous === null ? 1 : previous.score * decay(at - previous.openedAt) + 1;
787 return { openedAt: at, score, picks };
789​
790export interface ThreadSearchSubject {
791 /** Matched only by the whole query, like references. */
792 readonly id?: string;
793 readonly title: string;
794 readonly branch?: string | null;
795 readonly projectTitle?: string | null;
796 /** Only set with two or more environments; it tells same-named threads apart. */
797 readonly environmentLabel?: string | null;
798 readonly pullRequests?: ReadonlyArray<{
799 readonly number: number;
800 readonly title?: string | null;
801 /** Values such as URLs, matched only by the whole query. */
802 readonly references?: ReadonlyArray<string>;
803 }>;
804 /** Latest user activity, in epoch ms. */
805 readonly activityAt: number | null;
806 readonly opens?: ThreadOpenStats | null;
808​
809// Use reorders matches of about the same quality but never turns a mid-word
810// hit on a busy thread into a better result than a whole word on a quiet one.
811const USE_BOOST_LIMIT = 2.5;
812​
813/**
814 * How much use lifts a thread: 1 for a stale, never-opened thread, about 2 for
815 * one active today, and up to 2.5 for threads opened often.
816 */
817function threadUsageBoost(thread: ThreadSearchSubject, now: number): number {
818 const recency = thread.activityAt === null ? 0 : decay(now - thread.activityAt);
819 const opens = thread.opens ? thread.opens.score * decay(now - thread.opens.openedAt) : 0;
820 return Math.min(USE_BOOST_LIMIT, 1 + recency + 0.5 * Math.log2(1 + opens));
822​
823const REFERENCE_PREFIX_MIN = 8;
824​
825// A number is never cut short: ".../pull/2288" is not pull request 22889.
826const notCut = (text: string, end: number) => !DIGIT.test(text[end] ?? "");
827​
828// IDs and URLs have many word starts, so field matching would let short queries hit every thread.
829// Require a long prefix, or any long part containing a digit. Both are ASCII; lowercasing suffices.
830function matchReference(
831 normalizedQuery: string,
832 thread: ThreadSearchSubject,
833): SearchFieldsMatch | null {
834 if (normalizedQuery.length < REFERENCE_PREFIX_MIN) return null;
835 const anywhere = DIGIT.test(normalizedQuery);
836 const matches = (reference: string) => {
837 const folded = reference.toLowerCase();
838 const at = folded.indexOf(normalizedQuery);
839 // A pasted link may go on past the reference: ".../pull/22889/files".
840 return anywhere
841 ? (at !== -1 && notCut(folded, at + normalizedQuery.length)) ||
842 (normalizedQuery.startsWith(folded) && notCut(normalizedQuery, folded.length))
843 : at === 0;
844 };
845 return (thread.id && matches(thread.id)) ||
846 thread.pullRequests?.some((pullRequest) => pullRequest.references?.some(matches))
847 ? { quality: 0.6, strong: true, primaryRanges: [] }
848 : null;
850​
851// Picks expire from the pick time; opening a thread another way must not extend their priority.
852// They reorder word matches within a group, never the groups themselves.
853const PICK_WINDOW_MS = 21 * DAY_MS;
854// The start of a picked query counts from three letters: "n" is too little to
855// go on.
856const PICK_PREFIX_MIN_LENGTH = 3;
857​
858/** The latest pick of the thread for this query, while it lasts. */
859function activePick(
860 thread: ThreadSearchSubject,
861 normalizedQuery: string,
862 now: number,
863): ThreadOpenStats["picks"][number] | undefined {
864 // Stored picks are cut to a length, so compare the query cut the same way.
865 const query = pickedQuery(normalizedQuery);
866 const prefix = query.length >= PICK_PREFIX_MIN_LENGTH;
867 // The latest exact pick, else the latest pick the query starts.
868 let exact: ThreadOpenStats["picks"][number] | undefined;
869 let latest: ThreadOpenStats["picks"][number] | undefined;
870 for (const pick of thread.opens?.picks ?? []) {
871 if (now - pick.at > PICK_WINDOW_MS) continue;
872 if (pick.query === query && (exact === undefined || pick.at > exact.at)) exact = pick;
873 const matches = pick.query === query || (prefix && pick.query.startsWith(query));
874 if (matches && (latest === undefined || pick.at > latest.at)) latest = pick;
875 }
876 return exact ?? latest;
878​
879export interface ThreadSearchMatch {
880 /** Match quality times use; what results sort by. */
881 readonly score: number;
882 /** Match quality alone; see `rankSearchGroups`. */
883 readonly quality: number;
884 /** Every token matched at a word start; see `rankSearchGroups`. */
885 readonly strong: boolean;
886 /** Matched ranges in the title. */
887 readonly ranges: ReadonlyArray<SearchRange>;
888 /**
889 * Why the thread matched when its title shows no match, for the result row.
890 * Built on demand, so only the rows shown pay for it.
891 */
892 readonly explain?: () => SearchMatchHint | undefined;
893 /** When the thread was picked for this query, while that pick lasts; see `rankSearchGroups`. */
894 readonly pickedAt?: number;
895 /** Picked for exactly this query, before newer picks for longer ones; see `rankSearchGroups`. */
896 readonly pickedExactly?: boolean;
897 /** Below the whole-name class; see `scoreThreadSearch`. */
898 readonly groupQuality: number;
900​
901export interface SearchMatchHint {
902 readonly label: string;
903 readonly text: string;
904 readonly ranges: ReadonlyArray<SearchRange>;
906​
907// Most threads' branches start with the app's own worktree prefix ("t3/", and
908// "t3code/" before it), so "t3 connect" would match nearly every thread.
909// Only before more text, so typing "t3/" does not empty the list for a keystroke.
910const WORKTREE_BRANCH_PREFIX_PATTERN = new RegExp(`^(?:${WORKTREE_BRANCH_PREFIX}|t3code)/(?=\\S)`);
911​
912function searchableBranch(branch: string | null | undefined): string | null {
913 return branch ? branch.replace(WORKTREE_BRANCH_PREFIX_PATTERN, "") : null;
915​
916/**
917 * The field that explains a match whose title shows none: the first that holds
918 * the whole query, else, past the words the project or environment holds, the
919 * first that holds the rest ("lakebed perf" in project "lakebed" with the PR
920 * title "perf: …").
921 */
922function matchHint(
923 normalizedQuery: string,
924 thread: ThreadSearchSubject,
925 typos: boolean,
926): SearchMatchHint | undefined {
927 const candidates: Array<{ readonly label: string; readonly text: string | null | undefined }> = [
928 ...(thread.pullRequests ?? []).map((pullRequest) => ({
929 label: "PR",
930 text: `#${pullRequest.number}${pullRequest.title ? ` ${pullRequest.title}` : ""}`,
931 })),
932 { label: "Branch", text: searchableBranch(thread.branch) },
933 { label: "Project", text: thread.projectTitle },
934 { label: "Environment", text: thread.environmentLabel },
935 ];
936 const holds = (text: string, query: string) =>
937 matchSearchFields(query, [{ value: text, weight: 1 }], { typos })?.primaryRanges;
938 const hintFor = (query: string) => {
939 for (const { label, text } of candidates) {
940 const ranges = text ? holds(text, query) : undefined;
941 if (text && ranges) return { label, text, ranges };
942 }
943 return undefined;
944 };
945 const whole = hintFor(normalizedQuery);
946 if (whole) return whole;
947 const contexts = [thread.projectTitle, thread.environmentLabel].filter(
948 (text): text is string => !!text,
949 );
950 const rest = normalizedQuery
951 .split(" ")
952 .filter((token) => !contexts.some((text) => holds(text, token)))
953 .join(" ");
954 return rest && rest !== normalizedQuery ? hintFor(rest) : undefined;
956​
957// A keystroke scores each thread's fields again, so they are listed once per subject.
958const threadFieldsCache = new WeakMap<ThreadSearchSubject, ReadonlyArray<WeightedSearchField>>();
959​
960function threadSearchFields(thread: ThreadSearchSubject): ReadonlyArray<WeightedSearchField> {
961 const cached = threadFieldsCache.get(thread);
962 if (cached) return cached;
963 const fields: WeightedSearchField[] = [{ value: thread.title, weight: 1, midWord: true }];
964 for (const pullRequest of thread.pullRequests ?? []) {
965 fields.push({ value: `#${pullRequest.number}`, weight: 1 });
966 if (pullRequest.title) fields.push({ value: pullRequest.title, weight: 0.5 });
967 }
968 const branch = searchableBranch(thread.branch);
969 if (branch) fields.push({ value: branch, weight: 0.6 });
970 if (thread.projectTitle) {
971 fields.push({ value: thread.projectTitle, weight: 0.25, context: true });
972 }
973 if (thread.environmentLabel) {
974 fields.push({ value: thread.environmentLabel, weight: 0.25, context: true });
975 }
976 threadFieldsCache.set(thread, fields);
977 return fields;
979​
980let lastFieldQuery: { readonly query: string; readonly fieldQuery: string } | undefined;
981​
982// Strip pull request prefixes and the worktree prefix so queries match the stored fields.
983function threadFieldQuery(normalizedQuery: string): string {
984 if (lastFieldQuery?.query !== normalizedQuery) {
985 lastFieldQuery = {
986 query: normalizedQuery,
987 fieldQuery: normalizedQuery
988 .replace(/^(?:pr|pull request|pull)\s*(?=#?\d)/, "")
989 .replace(/^#\s*/, "")
990 .replace(WORKTREE_BRANCH_PREFIX_PATTERN, ""),
991 };
992 }
993 return lastFieldQuery.fieldQuery;
995​
996/**
997 * Scores a thread for a normalized query, or null when it does not match.
998 * Titles and pull request numbers count fully, pull request titles and
999 * branches less, project and environment names least.
1000 */
1001export function scoreThreadSearch(
1002 normalizedQuery: string,
1003 thread: ThreadSearchSubject,
1004 now: number,
1005 options?: {
1006 readonly typos?: boolean;
1007 /**
1008 * Palette picks; off where a pick would show up unexplained, such as a
1009 * sidebar filter or an agent's search.
1010 */
1011 readonly picks?: boolean;
1012 },
1013): ThreadSearchMatch | null {
1014 const fields = threadSearchFields(thread);
1015 const fieldQuery = threadFieldQuery(normalizedQuery);
1016 const fieldMatch = matchSearchFields(fieldQuery, fields, options);
1017 const referenceMatch = fieldMatch ? null : matchReference(normalizedQuery, thread);
1018 const match = fieldMatch ?? referenceMatch;
1019 if (match === null) return null;
1020 // A row whose title shows no match must say why. With several words, one
1021 // that cannot (its words spread over unrelated fields) is a coincidence and
1022 // is left out; a single word always sits in the field that matched it, so
1023 // its hint waits until the row is shown.
1024 const typos = options?.typos ?? false;
1025 const titleShowsMatch = match.primaryRanges.length > 0;
1026 const checkHint = !titleShowsMatch && referenceMatch === null && fieldQuery.includes(" ");
1027 const checkedHint = checkHint ? matchHint(fieldQuery, thread, typos) : undefined;
1028 if (checkHint && checkedHint === undefined) return null;
1029 const explain = titleShowsMatch
1030 ? undefined
1031 : (): SearchMatchHint | undefined =>
1032 referenceMatch
1033 ? { label: "ID or link", text: normalizedQuery, ranges: [] }
1034 : (checkedHint ?? matchHint(fieldQuery, thread, typos));
1035 const pick = options?.picks === false ? undefined : activePick(thread, normalizedQuery, now);
1036 return {
1037 score: match.quality * threadUsageBoost(thread, now),
1038 quality: match.quality,
1039 // A thread's whole title never lifts its group over a command or project
1040 // of that name: every new thread is titled "New thread" for a while.
1041 groupQuality: Math.min(match.quality, WHOLE_NAME - 0.01),
1042 strong: match.strong,
1043 ranges: match.primaryRanges,
1044 ...(explain ? { explain } : {}),
1045 ...(pick ? { pickedAt: pick.at } : {}),
1046 ...(pick?.query === pickedQuery(normalizedQuery) ? { pickedExactly: true } : {}),
1047 };
1049​
1050/** When the user last used a thread: their last message or their last open. */
1051export function threadRecentUse(thread: ThreadSearchSubject): number {
1052 return Math.max(thread.activityAt ?? 0, thread.opens?.openedAt ?? 0);
1054​
1055/**
1056 * How strongly a thread's messages match among matches of one quality: a
1057 * thread that keeps using the word outweighs a recent passing mention, as
1058 * hits count for more than recency or use (21 hits about 5.5, one hit 2).
1059 */
1060function messageMatchWeight(hits: number): number {
1061 return 1 + Math.log2(1 + hits);
1063​
1064/** `withoutTitleMatches` reserves message rows for threads the palette has not already listed. */
1065export function rankMessageMatches<
1066 T extends {
1067 readonly quality?: number;
1068 readonly hits?: number;
1069 readonly messageCreatedAt?: string | null;
1070 },
1072 matches: ReadonlyArray<T>,
1073 subjectOf: (match: T) => ThreadSearchSubject | undefined,
1074 normalizedQuery: string,
1075 now: number,
1076 options?: { readonly picks?: boolean; readonly withoutTitleMatches?: boolean },
1077): T[] {
1078 return matches
1079 .flatMap((match) => {
1080 const subject = subjectOf(match);
1081 if (!subject) return [];
1082 if (
1083 options?.withoutTitleMatches &&
1084 scoreThreadSearch(normalizedQuery, subject, now, { picks: false }) !== null
1085 ) {
1086 return [];
1088 // Older servers send no quality; their matches count as words.
1089 const quality = match.quality ?? 1;
1090 return [
1092 match,
1093 quality,
1094 pickedAt:
1095 options?.picks === false ? 0 : (activePick(subject, normalizedQuery, now)?.at ?? 0),
1096 score: messageMatchWeight(match.hits ?? 1) * threadUsageBoost(subject, now),
1097 },
1098 ];
1099 })
1100 .sort(
1101 (left, right) =>
1102 // Word matches first; among them a pick, then the closer match.
1103 Number(right.quality >= MESSAGE_PREFIX) - Number(left.quality >= MESSAGE_PREFIX) ||
1104 right.pickedAt - left.pickedAt ||
1105 right.quality - left.quality ||
1106 right.score - left.score ||
1107 (right.match.messageCreatedAt ?? "").localeCompare(left.match.messageCreatedAt ?? ""),
1109 .map(({ match }) => match);
1111​
1112/** Palette limits shared by web and mobile. */
1113export const PALETTE_THREAD_LIMIT = 20;
1114export const PALETTE_MESSAGE_LIMIT = 10;
1115/** Next to matching threads, other groups show only their best few rows. */
1116export const PALETTE_SECONDARY_LIMIT = 3;
1117​
1118// Whole words and prefixes share a class so "Compact" does not lift settings over "Compaction".
1119function matchClass(quality: number): number {
1120 return quality >= WHOLE_NAME ? 3 : quality >= 0.7 ? 2 : quality >= 0.4 ? 1 : 0;
1122​
1123export interface RankedSearchItem<T, M> {
1124 readonly item: T;
1125 readonly match: M;
1127​
1128/**
1129 * Rank groups by match class to keep typing stable and thread use from outweighing equal commands.
1130 * Try typos only without word-start matches: they add noise beside real matches and cost per key.
1131 */
1132export function rankSearchGroups<
1133 G,
1134 T,
1135 M extends {
1136 readonly score: number;
1137 readonly quality: number;
1138 readonly strong: boolean;
1139 readonly pickedAt?: number;
1140 readonly pickedExactly?: boolean;
1141 readonly groupQuality?: number;
1142 },
1144 groups: ReadonlyArray<{ readonly group: G; readonly items: ReadonlyArray<T> }>,
1145 score: (item: T, options: { readonly typos: boolean }, group: G) => M | null,
1146): Array<{ readonly group: G; readonly ranked: ReadonlyArray<RankedSearchItem<T, M>> }> {
1147 const rank = (typos: boolean) =>
1148 groups.map(({ group, items }) => {
1149 const options = { typos };
1150 const ranked: Array<RankedSearchItem<T, M>> = [];
1151 for (const item of items) {
1152 const match = score(item, options, group);
1153 if (match !== null) ranked.push({ item, match });
1155 return { group, ranked };
1156 });
1157 let ranked = rank(false);
1158 if (!ranked.some((entry) => entry.ranked.some(({ match }) => match.strong))) {
1159 ranked = rank(true);
1161 return ranked
1162 .flatMap(({ group, ranked: items }, order) => {
1163 if (items.length === 0) return [];
1164 // Use cannot lift a project-only match above a title match or cross match classes.
1165 // Picks reorder word matches, keeping typos and mid-word hits below them.
1166 // A longer-query pick must not pass a whole-name match for the current query.
1167 const wordMatch = (match: M) => Math.min(matchClass(match.quality), 2);
1168 const exactPickAt = (match: M) => (match.pickedExactly ? (match.pickedAt ?? 0) : 0);
1169 const sorted = [...items].sort(
1170 (left, right) =>
1171 wordMatch(right.match) - wordMatch(left.match) ||
1172 exactPickAt(right.match) - exactPickAt(left.match) ||
1173 matchClass(right.match.quality) - matchClass(left.match.quality) ||
1174 (right.match.pickedAt ?? 0) - (left.match.pickedAt ?? 0) ||
1175 right.match.score - left.match.score,
1176 );
1177 const best = Math.max(
1178 ...items.map(({ match }) => matchClass(match.groupQuality ?? match.quality)),
1179 );
1180 return [{ group, ranked: sorted, best, order }];
1181 })
1182 .sort((left, right) => right.best - left.best || left.order - right.order)
1183 .map(({ group, ranked: items }) => ({ group, ranked: items }));
1185​
1186/** `rankSearchGroups` for a single list. */
1187export function rankSearchItems<
1188 T,
1189 M extends { readonly score: number; readonly quality: number; readonly strong: boolean },
1191 items: ReadonlyArray<T>,
1192 score: (item: T, options: { readonly typos: boolean }) => M | null,
1193): ReadonlyArray<RankedSearchItem<T, M>> {
1194 return rankSearchGroups([{ group: null, items }], score)[0]?.ranked ?? [];
1196​
1197export interface SearchTermsMatch {
1198 readonly score: number;
1199 readonly quality: number;
1200 /** The quality its group ranks by, when lower; see `scoreSearchTerms`. */
1201 readonly groupQuality?: number;
1202 readonly strong: boolean;
1203 readonly ranges: ReadonlyArray<SearchRange>;
1205​
1206const KEYWORD_QUALITY = 0.65;
1207// Below this, keyword prefixes match too much: "co" or "pro" would list most
1208// settings. A short query still matches a keyword it equals ("pr").
1209const KEYWORD_QUERY_MIN_LENGTH = 4;
1210​
1211/**
1212 * Keywords count less so hidden terms cannot lift a group above a matching name.
1213 * Short queries need whole keywords to avoid listing most settings for common prefixes.
1214 */
1215export function scoreSearchTerms(
1216 normalizedQuery: string,
1217 terms: ReadonlyArray<string>,
1218 options?: { readonly typos?: boolean },
1219): SearchTermsMatch | null {
1220 // Filler words ("the ci") do not make a short query long.
1221 const meaningful = normalizedQuery
1222 .split(" ")
1223 .filter((token) => !FILLER_WORDS.has(token))
1224 .join(" ");
1225 const short = (meaningful || normalizedQuery).length < KEYWORD_QUERY_MIN_LENGTH;
1226 const match = matchSearchFields(
1227 normalizedQuery,
1228 terms.map((value, index) =>
1229 index === 0
1230 ? { value, weight: 1 }
1231 : // An alias typed in full ("pr") is deliberate, above a mere name prefix.
1232 { value, weight: short ? 0.8 : 0.6, wholeWords: short, keyword: true },
1233 ),
1234 options,
1235 );
1236 return (
1237 match && {
1238 score: match.quality,
1239 quality: match.quality,
1240 // Below the word-start class: a match only in hidden keywords must not put
1241 // its group above a result whose name matches. Inside the group an exact
1242 // alias still beats a name prefix ("pr" lists "Open pull requests" first).
1243 ...(match.primaryRanges.length > 0
1244 ? {}
1245 : { groupQuality: Math.min(match.quality, KEYWORD_QUALITY) }),
1246 strong: match.strong,
1247 ranges: match.primaryRanges,
1249 );