import {z} from 'zod' export type GetApiIpV1IpArgs = {ip: string, response_fields?: string | undefined, response_fields_omit?: string | undefined, pretty?: boolean | undefined}; export type GetApiIpV1IpOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const iPRecord = z.object({ip: z.string().optional(), type: z.enum(["IPv4", "IPv6"]).optional(), location: z.object({label: z.string().nullable().optional(), continent: z.object({name: z.string().nullable().optional(), codes: z.object({common: z.string().nullable().optional()}).optional()}).optional(), country: z.object({name: z.string().nullable().optional(), codes: z.object({alpha_2: z.string().nullable().optional()}).optional(), flag: z.object({emoji: z.string().nullable().optional(), html_entity: z.string().nullable().optional(), url_png: z.string().nullable().optional(), url_svg: z.string().nullable().optional()}).optional(), attributes: z.object({is_eu: z.boolean().nullable().optional()}).optional()}).optional(), subdivision: z.object({name: z.string().nullable().optional(), codes: z.object({common: z.string().nullable().optional(), iso_3166_2: z.string().nullable().optional()}).optional()}).optional(), city: z.object({name: z.string().nullable().optional()}).optional(), coordinates: z.object({lat: z.number().nullable().optional(), lng: z.number().nullable().optional()}).optional(), postal: z.object({code: z.string().nullable().optional()}).optional()}).optional(), connection: z.object({asn: z.object({number: z.number().int().nullable().optional()}).optional(), organization: z.object({name: z.string().nullable().optional()}).optional(), domain: z.string().nullable().optional()}).optional(), security: z.object({tor: z.boolean().nullable().optional(), proxy: z.boolean().nullable().optional(), vpn: z.boolean().nullable().optional(), anonymous: z.boolean().nullable().optional(), data_center: z.boolean().nullable().optional()}).optional(), timezone: z.object({id: z.string().nullable().optional(), current: z.object({abbreviation: z.string().nullable().optional(), offset: z.object({seconds: z.number().int().nullable().optional(), iso_8601: z.string().nullable().optional()}).optional(), attributes: z.object({is_dst: z.boolean().nullable().optional()}).optional()}).optional()}).optional()}); export const resultMeta = z.object({total: z.number().int(), request_id: z.string(), duration: z.number().int()}); export const iPLookupResponse = z.object({data: z.object({objects: z.array(iPRecord), meta: resultMeta.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 }; /** * Look up an IP address (path slug) * * GET /ip/v1/{ip} * * Also accepts auth: KeyQuery */ export const getApiIpV1Ip = async (args: GetApiIpV1IpArgs, options?: GetApiIpV1IpOptions) => { const {baseUrl = "https://api.restcountries.com", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.response_fields != null) query.append("response_fields", String(args.response_fields)) if (args.response_fields_omit != null) query.append("response_fields_omit", String(args.response_fields_omit)) if (args.pretty != null) query.append("pretty", String(args.pretty)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/ip/v1/${encodeURIComponent(String(args.ip))}${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(iPLookupResponse, await res.json()) };