query-input.ts (2391B)
1 import { PUBLIC_SEARCH_BUDGETS } from '../config/budgets.ts'; 2 3 export type PublicQuery = 4 | { 5 readonly ok: true; 6 readonly text: string; 7 readonly terms: readonly string[]; 8 } 9 | { 10 readonly ok: false; 11 readonly error: 'invalid_query' | 'query_too_long' | 'too_many_terms'; 12 }; 13 14 const encoder = new TextEncoder(); 15 16 export function normalizePublicQuery(input: unknown): PublicQuery { 17 if (typeof input !== 'string') return { ok: false, error: 'invalid_query' }; 18 if (input.length > PUBLIC_SEARCH_BUDGETS.queryBytes) 19 return { ok: false, error: 'query_too_long' }; 20 if (!input.isWellFormed()) return { ok: false, error: 'invalid_query' }; 21 for (const character of input) { 22 const code = character.charCodeAt(0); 23 if (code <= 8 || (code >= 14 && code <= 31) || (code >= 127 && code <= 159)) 24 return { ok: false, error: 'invalid_query' }; 25 } 26 if (encoder.encode(input).length > PUBLIC_SEARCH_BUDGETS.queryBytes) 27 return { ok: false, error: 'query_too_long' }; 28 const normalized = input.normalize('NFKC').toLowerCase().trim(); 29 const terms = normalized === '' ? [] : normalized.split(/\s+/u); 30 if (terms.length > PUBLIC_SEARCH_BUDGETS.terms) 31 return { ok: false, error: 'too_many_terms' }; 32 const text = terms.join(' '); 33 if (encoder.encode(text).length > PUBLIC_SEARCH_BUDGETS.queryBytes) 34 return { ok: false, error: 'query_too_long' }; 35 return { ok: true, text, terms }; 36 } 37 38 export function readPublicQuery( 39 url: Readonly<{ 40 pathname: string; 41 hash: string; 42 search: string; 43 searchParams: Readonly<Pick<URLSearchParams, 'keys' | 'get'>>; 44 }> 45 ): PublicQuery { 46 if (url.pathname !== '/search' || url.hash !== '' || url.search.length > 8192) 47 return { ok: false, error: 'invalid_query' }; 48 const keys = [...url.searchParams.keys()]; 49 if (keys.length > 1 || keys.some((key) => key !== 'q')) 50 return { ok: false, error: 'invalid_query' }; 51 return normalizePublicQuery(url.searchParams.get('q') ?? ''); 52 } 53 54 export function queryErrorMessage( 55 error: 'invalid_query' | 'query_too_long' | 'too_many_terms' 56 ): string { 57 switch (error) { 58 case 'query_too_long': 59 return 'Use at most 512 UTF-8 bytes for your search.'; 60 case 'too_many_terms': 61 return 'Use at most 12 words for your search.'; 62 case 'invalid_query': 63 return 'Enter plain search words without private URL context.'; 64 } 65 }