import {z} from 'zod' export type GetApiUsageExportArgs = {period?: string | undefined, format?: ('csv' | 'jsonl') | undefined, status?: ('active' | 'suspended' | 'archived') | undefined, minSent?: number | undefined, timezone?: string | undefined}; export type GetApiUsageExportOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const tenantUsageExportRow = z.object({tenant_id: z.string(), tenant_name: z.string(), external_id: z.string().nullable().optional(), status: z.enum(["active", "suspended", "archived"]), 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(), delivery_rate: z.number(), bounce_rate: z.number()}); export const getApiUsageExportResponse = z.array(tenantUsageExportRow); 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 }; /** * Export tenant usage data * * GET /usage/export */ export const getApiUsageExport = async (args: GetApiUsageExportArgs, options?: GetApiUsageExportOptions) => { 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.format != null) query.append("format", String(args.format)) if (args.status != null) query.append("status", String(args.status)) if (args.minSent != null) query.append("minSent", String(args.minSent)) if (args.timezone != null) query.append("timezone", String(args.timezone)) if (apiKey !== undefined) headers.set('authorization', `Bearer ${apiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/usage/export${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(getApiUsageExportResponse, await res.json()) };