import {z} from 'zod' export type GetApiAiSearchFiltersOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, ShopId?: string | undefined, fetch?: typeof fetch | undefined}; export const region = z.enum(["US", "UK", "IT", "ES", "DE", "FR", "IE", "MX", "BR", "JP", "NL", "AT", "BE", "CZ", "GR", "HU", "PL", "PT"]); export const filterOption = z.object({label: z.string(), value: z.string(), min: z.number().nullable().optional(), max: z.number().nullable().optional()}); export const sliderFilterConfig = z.object({min: z.number(), max: z.number(), step: z.number()}); export const filtersResponse = z.object({region: region, filters: z.record(z.string(), z.array(filterOption)), sliders: z.record(z.string(), sliderFilterConfig)}); 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 }; /** * Valid AI-search filters for your region * * GET /ai-search/filters */ export const getApiAiSearchFilters = async (options?: GetApiAiSearchFiltersOptions) => { const {baseUrl = "https://api.reacherapp.com/public/v1", fetch: fetchFn = fetch, ApiKeyAuth, ShopId} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (ApiKeyAuth !== undefined) headers.set("x-api-key", ApiKeyAuth) if (ShopId !== undefined) headers.set("x-shop-id", ShopId) const url = `${baseUrl.replace(/\/+$/, '')}/ai-search/filters${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(filtersResponse, await res.json()) };