import {z} from 'zod' export type GetApiV1BillingUsageArgs = {periodOffset?: number | undefined}; export type GetApiV1BillingUsageOptions = {baseUrl: string, OAuth2AuthorizationCodeBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const billingPeriod = z.object({start: z.string(), end: z.string(), anchor_day: z.number().int()}); export const usageBreakdown = z.object({spans: z.number().int(), metrics: z.number().int()}); export const projectUsage = z.object({project_name: z.string(), project_id: z.string(), observations: z.number().int()}); export const usageSummary = z.object({total_observations: z.number().int(), breakdown: usageBreakdown, included_observations: z.number().int(), billable_observations: z.number().int(), project_breakdown: z.array(projectUsage)}); export const costSummary = z.object({currency: z.string(), price_per_million_observations: z.number(), included_observations_value: z.number(), usage_cost: z.number(), discount: z.number(), total_cost: z.number()}); export const billingUsageResponse = z.object({organization: z.string(), billing_period: billingPeriod, plan: z.string(), usage: usageSummary, cost: costSummary}); 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 Billing Usage * * GET /v1/billing/usage/ */ export const getApiV1BillingUsage = async (args: GetApiV1BillingUsageArgs, options: GetApiV1BillingUsageOptions) => { const {baseUrl, fetch: fetchFn = fetch, OAuth2AuthorizationCodeBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.periodOffset != null) query.append("periodOffset", String(args.periodOffset)) if (OAuth2AuthorizationCodeBearer !== undefined) headers.set('authorization', `Bearer ${OAuth2AuthorizationCodeBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/billing/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(billingUsageResponse, await res.json()) };