import {z} from 'zod' export type GetApiSearchSimilarImagesArgs = {api_token: string, vhash?: string | undefined, num_results_per_page?: number | undefined, page?: number | undefined, gallery_id?: string | undefined, url?: string | undefined}; export type GetApiSearchSimilarImagesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiSearchSimilarImagesResponse = z.object({results: z.array(z.object({visual_id: z.string().optional(), org_image_key: z.string().optional(), source_url: z.string().optional()})).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 }; /** * Search by Image * * GET /search_similar_images */ export const getApiSearchSimilarImages = async (args: GetApiSearchSimilarImagesArgs, options?: GetApiSearchSimilarImagesOptions) => { const {baseUrl = "https://engine.prod.bria-api.com/v1", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.api_token != null) headers.set("api_token", String(args.api_token)) if (args.vhash != null) query.append("vhash", String(args.vhash)) if (args.num_results_per_page != null) query.append("num_results_per_page", String(args.num_results_per_page)) if (args.page != null) query.append("page", String(args.page)) if (args.gallery_id != null) query.append("gallery_id", String(args.gallery_id)) if (args.url != null) query.append("url", String(args.url)) const url = `${baseUrl.replace(/\/+$/, '')}/search_similar_images${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(getApiSearchSimilarImagesResponse, await res.json()) };