import {z} from 'zod' export type GetApiLookupMeFieldArgs = {field: 'ip' | 'hostname' | 'geo' | 'geo/city' | 'geo/region' | 'geo/region_code' | 'geo/country' | 'geo/country_code' | 'geo/continent' | 'geo/continent_code' | 'geo/latitude' | 'geo/longitude' | 'geo/timezone' | 'geo/postal_code' | 'geo/dma_code' | 'geo/geoname_id' | 'geo/radius' | 'geo/last_changed' | 'as' | 'as/asn' | 'as/name' | 'as/domain' | 'as/type' | 'as/last_changed' | 'mobile' | 'mobile/name' | 'mobile/mcc' | 'mobile/mnc' | 'anonymous' | 'anonymous/name' | 'anonymous/last_seen' | 'anonymous/percent_days_seen' | 'anonymous/is_proxy' | 'anonymous/is_relay' | 'anonymous/is_tor' | 'anonymous/is_vpn' | 'anonymous/is_res_proxy' | 'is_anonymous' | 'is_anycast' | 'is_hosting' | 'is_mobile' | 'is_satellite'}; export type GetApiLookupMeFieldOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const getApiLookupMeFieldResponse = z.object({}); 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 }; /** * Returns a specific field from IP information about the current IP. * * GET /lookup/me/{field} * * Also accepts auth: BearerAuth, ApiKeyAuth */ export const getApiLookupMeField = async (args: GetApiLookupMeFieldArgs, options?: GetApiLookupMeFieldOptions) => { const {baseUrl = "https://api.ipinfo.io", fetch: fetchFn = fetch, BasicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (BasicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${BasicAuth.username}:${BasicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/lookup/me/${encodeURIComponent(String(args.field))}${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(getApiLookupMeFieldResponse, await res.json()) };