import {z} from 'zod' export type GetApiUsageArgs = {period?: string | undefined, timezone?: string | undefined}; export type GetApiUsageOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const usagePeriod = z.object({start: z.string(), end: z.string()}); export const emailCounts = z.object({sent: z.number().int(), delivered: z.number().int(), soft_failed: z.number().int(), hard_failed: z.number().int(), bounced: z.number().int(), held: z.number().int()}); export const emailRates = z.object({delivery_rate: z.number(), bounce_rate: z.number()}); export const apiMeta = z.object({requestId: z.string()}); export const orgUsageSummaryResponse = z.object({success: z.literal(true), data: z.object({period: usagePeriod, emails: emailCounts, rates: emailRates, tenants: z.object({total: z.number().int(), active: z.number().int(), withActivity: z.number().int()})}), meta: apiMeta}); 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 org-wide usage summary * * GET /usage */ export const getApiUsage = async (args: GetApiUsageArgs, options?: GetApiUsageOptions) => { const {baseUrl = "https://api.arkhq.io/v1", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.period != null) query.append("period", String(args.period)) if (args.timezone != null) query.append("timezone", String(args.timezone)) if (apiKey !== undefined) headers.set('authorization', `Bearer ${apiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/usage${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(orgUsageSummaryResponse, await res.json()) };