import {z} from 'zod' export type V3Signals = 'co2_moer' | 'health_damage'; export type V3HistoricalSignals = 'co2_aoer'; export type GetApiV3RegionFromLocArgs = {signal_type: V3Signals | V3HistoricalSignals, latitude: number, longitude: number}; export type GetApiV3RegionFromLocOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const regionLocResponse = z.object({region: z.string(), region_full_name: z.string(), signal_type: z.string()}); 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 }; /** * Determine Grid Region * * GET /v3/region-from-loc */ export const getApiV3RegionFromLoc = async (args: GetApiV3RegionFromLocArgs, options?: GetApiV3RegionFromLocOptions) => { const {baseUrl = "https://api.watttime.org", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.signal_type != null) query.append("signal_type", String(args.signal_type)) if (args.latitude != null) query.append("latitude", String(args.latitude)) if (args.longitude != null) query.append("longitude", String(args.longitude)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/region-from-loc${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(regionLocResponse, await res.json()) };