import {z} from 'zod' export type GetApiGeolocationIpJsonArgs = {elevation?: boolean | undefined}; export type GetApiGeolocationIpJsonOptions = {baseUrl?: string | undefined, key?: string | undefined, fetch?: typeof fetch | undefined}; export const geolocationResult = z.object({country: z.string().optional(), country_code: z.string().optional(), country_bounds: z.array(z.number()).optional(), country_languages: z.array(z.string()).optional(), continent: z.string().optional(), continent_code: z.string().optional(), eu: z.boolean().optional(), city: z.string().optional(), latitude: z.number().optional(), longitude: z.number().optional(), postal: z.string().optional(), region: z.string().optional(), region_code: z.string().optional(), timezone: z.string().optional(), elevation: z.number().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 }; /** * IP Geolocation * * GET /geolocation/ip.json */ export const getApiGeolocationIpJson = async (args: GetApiGeolocationIpJsonArgs, options?: GetApiGeolocationIpJsonOptions) => { const {baseUrl = "https://api.maptiler.com", fetch: fetchFn = fetch, key} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.elevation != null) query.append("elevation", String(args.elevation)) if (key !== undefined) query.set("key", key) const url = `${baseUrl.replace(/\/+$/, '')}/geolocation/ip.json${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(geolocationResult, await res.json()) };