import {z} from 'zod' export type GetApiProductsSearchArgs = {q?: string | undefined, query?: string | undefined, deliver_to?: ('SG' | 'US' | 'VN' | 'TH' | 'MY' | 'ID' | 'PH') | undefined, domain?: string | undefined, region?: string | undefined, country_code?: ('SG' | 'US' | 'VN' | 'TH' | 'MY') | undefined, include_unshippable?: boolean | undefined, min_price?: number | undefined, max_price?: number | undefined, currency?: string | undefined, compact?: boolean | undefined, limit?: number | undefined, offset?: number | undefined, mode?: ('keyword' | 'semantic' | 'hybrid') | undefined}; export type GetApiProductsSearchOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiProductsSearchResponse = z.object({data: z.array(z.object({id: z.string().optional(), title: z.string().optional(), price: z.object({amount: z.number().optional(), currency: z.string().optional()}).optional(), merchant: z.string().optional(), url: z.string().optional(), image_url: z.string().optional(), country_code: z.enum(["SG", "US", "VN", "TH", "MY"]).optional(), category_path: z.array(z.string()).optional(), updated_at: z.string().optional(), click_url: z.string().optional(), affiliate_disclosure: z.string().optional(), metadata: z.object({}).optional()})).optional(), meta: z.object({total: z.number().int().optional(), limit: z.number().int().optional(), offset: z.number().int().optional(), response_time_ms: z.number().int().optional(), cached: z.boolean().optional(), mode_used: z.enum(["keyword", "semantic", "hybrid"]).optional(), mode_used_engine: z.string().optional(), has_more: z.boolean().optional(), hint: z.string().optional(), degraded: z.boolean().optional(), status: z.enum(["ok", "degraded"]).optional(), emptiness_reason: z.string().optional(), confidence: z.enum(["high", "medium", "low"]).optional(), diagnostic: z.object({engine_status: z.string().optional(), indexed_for_region: z.boolean().optional(), category_recognized: z.boolean().optional(), timed_out_stage: z.string().optional(), deliver_to_present: z.boolean().optional(), rate_limit_remaining: z.number().int().nullable().optional()}).optional(), degraded_kind: z.string().optional(), degraded_reason: z.string().optional(), deliver_to: z.string().optional(), deliver_to_inferred: z.boolean().optional()}).optional(), search_mode: z.object({requested_mode: z.enum(["keyword", "semantic", "hybrid", "null"]).nullable().optional(), executed_mode: z.enum(["keyword", "semantic", "hybrid"]).optional(), fallback_reason: z.string().nullable().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 products by keyword with full-text search * * GET /products/search */ export const getApiProductsSearch = async (args: GetApiProductsSearchArgs, options?: GetApiProductsSearchOptions) => { const {baseUrl = "https://api.buywhere.ai/v1", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.q != null) query.append("q", String(args.q)) if (args.query != null) query.append("query", String(args.query)) if (args.deliver_to != null) query.append("deliver_to", String(args.deliver_to)) if (args.domain != null) query.append("domain", String(args.domain)) if (args.region != null) query.append("region", String(args.region)) if (args.country_code != null) query.append("country_code", String(args.country_code)) if (args.include_unshippable != null) query.append("include_unshippable", String(args.include_unshippable)) if (args.min_price != null) query.append("min_price", String(args.min_price)) if (args.max_price != null) query.append("max_price", String(args.max_price)) if (args.currency != null) query.append("currency", String(args.currency)) if (args.compact != null) query.append("compact", String(args.compact)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.offset != null) query.append("offset", String(args.offset)) if (args.mode != null) query.append("mode", String(args.mode)) const url = `${baseUrl.replace(/\/+$/, '')}/products/search${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(getApiProductsSearchResponse, await res.json()) };