import {z} from 'zod' export type GetApiV1VoiceUsageArgs = {start_date: string, end_date: string}; export type GetApiV1VoiceUsageOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const getUsageResponseV1Data = z.object({date: z.string(), voice_id: z.string(), name: z.string().optional(), style: z.string().optional(), language: z.string().optional(), total_minutes_used: z.number(), model: z.string().optional(), thumbnail_url: z.string().optional()}); export const getUsageListV1Response = z.object({usages: z.array(getUsageResponseV1Data)}); 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 }; /** * Retrieve TTS API usage data * * GET /v1/voice-usage */ export const getApiV1VoiceUsage = async (args: GetApiV1VoiceUsageArgs, options?: GetApiV1VoiceUsageOptions) => { const {baseUrl = "https://supertoneapi.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.start_date != null) query.append("start_date", String(args.start_date)) if (args.end_date != null) query.append("end_date", String(args.end_date)) if (apiKey !== undefined) headers.set("x-sup-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/voice-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(getUsageListV1Response, await res.json()) };