import {z} from 'zod' export type GetApiSearchArgs = {name?: string | undefined, 'profile-required'?: boolean | undefined, 'reverse-resolution-required'?: boolean | undefined}; export type GetApiSearchOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const serializedProfileSearch = z.object({address: z.string().optional(), name: z.string().optional(), avatarUrl: z.string().optional(), imageUrl: z.string().optional(), imageType: z.string().optional(), imagePath: z.string().optional(), linkUrl: z.string().optional(), ownerAddress: z.string().optional(), market: z.object({price: z.number().optional(), location: z.string().optional()}).optional()}); export const serializedProfileSearchResponse = z.array(serializedProfileSearch); 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 }; /** * Retrieves list of domains based on query * * GET /search */ export const getApiSearch = async (args: GetApiSearchArgs, options?: GetApiSearchOptions) => { const {baseUrl = "https://api.unstoppabledomains.com/profile", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.name != null) query.append("name", String(args.name)) if (args['profile-required'] != null) query.append("profile-required", String(args['profile-required'])) if (args['reverse-resolution-required'] != null) query.append("reverse-resolution-required", String(args['reverse-resolution-required'])) const url = `${baseUrl.replace(/\/+$/, '')}/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(serializedProfileSearchResponse, await res.json()) };