import {z} from 'zod' export type UsageInterval = 'day' | 'week' | 'month'; export type UsageCreditsGroupBy = 'capability' | 'model' | 'voice' | 'api_key'; export type GetApiUsageCreditsArgs = {'Cartesia-Version': '2026-03-01', start_ts?: (string | null) | undefined, end_ts?: (string | null) | undefined, interval?: UsageInterval | undefined, api_key_id?: (string | null) | undefined, group_by?: UsageCreditsGroupBy | undefined}; export type GetApiUsageCreditsOptions = {baseUrl?: string | undefined, AdminAPIKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const usageCreditsGroupBy = z.enum(["capability", "model", "voice", "api_key"]); export const usageBucketStartTimestamp = z.string(); export const usageBucketEndTimestamp = z.string(); export const usageCreditsBucket = z.object({start_ts: usageBucketStartTimestamp, end_ts: usageBucketEndTimestamp, credits: z.number().int()}); export const usageCreditsBreakdownSeries = z.object({id: z.string(), label: z.string().nullable().optional(), buckets: z.array(usageCreditsBucket)}); export const usageCreditsResponse = z.object({group_by: usageCreditsGroupBy.optional(), data: z.array(z.union([usageCreditsBucket, usageCreditsBreakdownSeries]))}); 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 Credit Usage * * GET /usage/credits */ export const getApiUsageCredits = async (args: GetApiUsageCreditsArgs, options?: GetApiUsageCreditsOptions) => { const {baseUrl = "https://api.cartesia.ai", fetch: fetchFn = fetch, AdminAPIKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['Cartesia-Version'] != null) headers.set("Cartesia-Version", String(args['Cartesia-Version'])) if (args.start_ts != null) query.append("start_ts", String(args.start_ts)) if (args.end_ts != null) query.append("end_ts", String(args.end_ts)) if (args.interval != null) query.append("interval", String(args.interval)) if (args.api_key_id != null) query.append("api_key_id", String(args.api_key_id)) if (args.group_by != null) query.append("group_by", String(args.group_by)) if (AdminAPIKeyAuth !== undefined) headers.set('authorization', `Bearer ${AdminAPIKeyAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/usage/credits${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(usageCreditsResponse, await res.json()) };