import {z} from 'zod' export type GetApiSuggestArgs = {projects: string, field: string, caret: number, full?: string | undefined, defs?: string | undefined, refs?: string | undefined, path?: string | undefined, hist?: string | undefined, type?: string | undefined}; export type GetApiSuggestOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const suggestion = z.object({phrase: z.string().optional(), projects: z.array(z.string()).optional(), score: z.number().optional()}); export const suggestResponse = z.object({time: z.number().int().optional(), suggestions: z.array(suggestion).optional(), identifier: z.string().optional(), queryText: z.string().optional(), partialResult: z.boolean().optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Return suggestions * * GET /suggest */ export const getApiSuggest = async (args: GetApiSuggestArgs, options: GetApiSuggestOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.projects != null) query.append("projects", String(args.projects)) if (args.field != null) query.append("field", String(args.field)) if (args.caret != null) query.append("caret", String(args.caret)) if (args.full != null) query.append("full", String(args.full)) if (args.defs != null) query.append("defs", String(args.defs)) if (args.refs != null) query.append("refs", String(args.refs)) if (args.path != null) query.append("path", String(args.path)) if (args.hist != null) query.append("hist", String(args.hist)) if (args.type != null) query.append("type", String(args.type)) const url = `${baseUrl.replace(/\/+$/, '')}/suggest${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(suggestResponse, await res.json()) };