import {z} from 'zod' export type MeteringReport = {project_id: string, resource_kind: string, resource_id: string, interval_start: string, interval_end: string, metrics: {[key: string]: Record}, idempotency_key: string, kind?: ('JOB_CLOSE' | 'DATA_DELETE' | 'ADJUSTMENT' | 'DELTA_SLICE') | undefined, source_ref?: string | undefined, reporter?: string | undefined, adjustment_reason?: ('RECONCILE_SCRAPY_FINAL' | 'RECONCILE_STORAGE' | 'MANUAL') | undefined}; export type CreateApiApiV1MeteringReportArgs = {body: MeteringReport}; export type CreateApiApiV1MeteringReportOptions = {baseUrl?: string | undefined, Basic?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const meteringReportResponse = z.object({id: z.string(), recorded_at: z.string(), duplicate: z.boolean(), resource_kind: z.string().min(1), resource_id: z.string().min(1)}); 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 }; /** * Append one metered usage fact. Deduplicated by ``idempotency_key``. * * POST /api/v1/metering/report */ export const createApiApiV1MeteringReport = async (args: CreateApiApiV1MeteringReportArgs, options?: CreateApiApiV1MeteringReportOptions) => { const {baseUrl = "http://127.0.0.1:8000", fetch: fetchFn = fetch, Basic} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (Basic !== undefined) headers.set('authorization', `Basic ${btoa(`${Basic.username}:${Basic.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/metering/report${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(meteringReportResponse, await res.json()) };