import {z} from 'zod' export type V3Signals = 'co2_moer' | 'health_damage'; export type V3HistoricalSignals = 'co2_aoer'; export type GetApiV3HistoricalArgs = {start: string, end: string, region: string, signal_type: V3Signals | V3HistoricalSignals, model?: (string | null) | undefined, include_imputed_marker?: boolean | undefined, updated_since?: (string | null) | undefined}; export type GetApiV3HistoricalOptions = {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 v3Signals = z.enum(["co2_moer", "health_damage"]); export const v3HistoricalSignals = z.literal("co2_aoer"); 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 v3Metadata = z.object({data_point_period_seconds: z.number().int(), region: z.string(), signal_type: z.union([v3Signals, v3HistoricalSignals]), units: z.string(), warnings: z.array(warningType), model: v3ModelMetadata.nullable().optional()}); export const v3Response = z.object({data: z.array(aPIV3DataResponseFormat), meta: v3Metadata}); 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 signal data * * GET /v3/historical */ export const getApiV3Historical = async (args: GetApiV3HistoricalArgs, options?: GetApiV3HistoricalOptions) => { 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.include_imputed_marker != null) query.append("include_imputed_marker", String(args.include_imputed_marker)) if (args.updated_since != null) query.append("updated_since", String(args.updated_since)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/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(v3Response, await res.json()) };