staging-tester / ocean-landing-serve / src/ lib/ search.ts

import { ApiFailure, request } from '#lib/live/http.js';

// Mirrors SearchResults in sailfork/client/src/contract.ts; ranges are [start, end) in UTF-8 bytes of the string beside them.
export type SearchRange = [number, number];
export type SearchLine = { number: number; column: number; text: string; ranges: SearchRange[] };
export type SearchFile = {
	repo: string;
	ref?: string;
	path: string;
	language: string;
	matchCount: number;
	snippets: { lines: SearchLine[] }[];
};
export type SearchResults = {
	query: string;
	repos: { owner: string; name: string; about: string; visibility: 'public' | 'private'; ranges: SearchRange[] }[];
	paths: { repo: string; ref?: string; path: string; language: string; ranges: SearchRange[] }[];
	files: SearchFile[];
	truncated: boolean;
	tookMs: number;
};
export type SearchParams = { q: string; repo?: string; lang?: string; path?: string; limit?: number; caseSensitive?: boolean; ref?: string };

export const maxQuery = 256;

export async function searchCode(params: SearchParams, signal?: AbortSignal): Promise<SearchResults> {
	const qs = new URLSearchParams({ q: params.q });
	if (params.repo) qs.set('repo', params.repo);
	if (params.lang) qs.set('lang', params.lang);
	if (params.path) qs.set('path', params.path);
	if (params.ref) qs.set('ref', params.ref);
	if (params.limit) qs.set('limit', String(params.limit));
	if (params.caseSensitive) qs.set('case', 'true');
	const res = await fetch(`/api/search?${qs}`, { credentials: 'include', headers: { accept: 'application/json' }, signal });
	const text = await res.text();
	const json: unknown = text ? JSON.parse(text) : null;
	if (!res.ok) {
		const message = typeof json === 'object' && json !== null && 'error' in json ? String(json.error) : `Search failed (${res.status})`;
		throw new ApiFailure(res.status, message, json);
	}
	return json as SearchResults;
}

export const searchFailure = (err: unknown) => {
	if (err instanceof ApiFailure && err.status === 422) return { kind: 'invalid' as const, message: err.message };
	if (err instanceof ApiFailure && err.status === 503) return { kind: 'slow' as const, message: 'The search took longer than its time limit.' };
	return { kind: 'down' as const, message: 'Search is not reachable right now.' };
};

export type Segment = { text: string; hit: boolean };

// Ranges are UTF-8 byte offsets; slicing a JS string needs UTF-16 indices.
export const segments = (text: string, ranges: SearchRange[]): Segment[] => {
	if (ranges.length === 0) return [{ text, hit: false }];
	const at = new Map<number, number>();
	let byte = 0;
	for (let i = 0; i < text.length; ) {
		at.set(byte, i);
		const cp = text.codePointAt(i) ?? 0;
		byte += cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4;
		i += cp > 0xffff ? 2 : 1;
	}
	at.set(byte, text.length);
	const out: Segment[] = [];
	let last = 0;
	for (const [from, to] of ranges) {
		const a = at.get(from);
		const b = at.get(to);
		if (a === undefined || b === undefined || a < last || b <= a) continue;
		if (a > last) out.push({ text: text.slice(last, a), hit: false });
		out.push({ text: text.slice(a, b), hit: true });
		last = b;
	}
	if (last < text.length) out.push({ text: text.slice(last), hit: false });
	return out;
};

// Indentation is dropped; with `lead`, text before the first match is cut to that many characters (with an ellipsis) so a narrow row still shows the match.
export const lineSegments = (line: SearchLine, lead = Infinity): Segment[] => {
	const segs = segments(line.text, line.ranges);
	const first = segs[0];
	if (first && !first.hit) {
		const trimmed = first.text.trimStart();
		if (!trimmed) segs.shift();
		else if (trimmed.length > lead && segs.length > 1) segs[0] = { text: `…${trimmed.slice(-lead)}`, hit: false };
		else segs[0] = { text: trimmed, hit: false };
	}
	return segs;
};

const branches = new Map<string, Promise<string>>();

export const defaultBranch = (repo: string): Promise<string> => {
	let found = branches.get(repo);
	if (!found) {
		found = request<{ defaultBranch: string }>('GET', `/api/repos/${repo}`).then((r) => r.defaultBranch);
		branches.set(repo, found);
		found.catch(() => branches.delete(repo));
	}
	return found;
};

const enc = (path: string) => path.split('/').map(encodeURIComponent).join('/');

export const blobHref = (repo: string, branch: string, path: string, line?: number) =>
	`/${repo}/blob/${encodeURIComponent(branch)}/${enc(path)}${line ? `#L${line}` : ''}`;

export const searchHref = (q: string, repo?: string | null) => `/search?${new URLSearchParams(repo ? { q, repo } : { q })}`;