import {z} from 'zod' export type V3Signals = 'co2_moer' | 'health_damage'; export type GetApiV3ForecastHistoricalArgs = {start: string, end: string, region: string, signal_type: V3Signals | unknown, model?: (string | null) | undefined, horizon_hours?: number | undefined}; export type GetApiV3ForecastHistoricalOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const aPIV3DataResponseFormat = z.object({point_time: z.string(), value: z.number(), last_updated: z.string().nullable().optional(), imputed_data_used: z.boolean().nullable().optional()}); export const aPIV3ExtendedForecastType = z.object({generated_at: z.string(), forecast: z.array(aPIV3DataResponseFormat)}); export const v3Signals = z.enum(["co2_moer", "health_damage"]); export const warningType = z.object({type: z.string(), message: z.string()}); export const modelTypes = z.enum(["interchange", "average", "binned_regression", "heatrate", "proxy", "synthetic_proxy", "forecast", "synthetic_vre_potential"]); export const v3ModelMetadata = z.object({date: z.string(), type: modelTypes.nullable().optional()}); export const v3ForecastMetadata = z.object({data_point_period_seconds: z.number().int(), region: z.string(), signal_type: z.union([z.unknown(), v3Signals]), units: z.string(), warnings: z.array(warningType), model: v3ModelMetadata.nullable().optional(), generated_at_period_seconds: z.number().int()}); export const v3ExtendedForecastResponse = z.object({data: z.array(aPIV3ExtendedForecastType), meta: v3ForecastMetadata}); 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 }; /** * Get a range of historical forecasted data * * GET /v3/forecast/historical */ export const getApiV3ForecastHistorical = async (args: GetApiV3ForecastHistoricalArgs, options?: GetApiV3ForecastHistoricalOptions) => { 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.start != null) query.append("start", String(args.start)) if (args.end != null) query.append("end", String(args.end)) if (args.region != null) query.append("region", String(args.region)) if (args.signal_type != null) query.append("signal_type", String(args.signal_type)) if (args.model != null) query.append("model", String(args.model)) if (args.horizon_hours != null) query.append("horizon_hours", String(args.horizon_hours)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/forecast/historical${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(v3ExtendedForecastResponse, await res.json()) };