import {z} from 'zod' export type GetApiV1UsageArgs = {period_start: string, period_end: string, workspace_id?: (string | null) | undefined, group_by?: ('day' | 'kind' | 'workspace' | 'tenant') | undefined}; export type GetApiV1UsageOptions = {baseUrl?: string | undefined, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const usageBucket = z.object({bytes_ingested: z.number().int(), credits: z.number().int(), jobs: z.number().int(), key: z.string(), pages: z.number().int(), unfinalized_jobs: z.number().int(), units: z.number().int()}); export const ndiServiceAppPlatformApiOperationsSchemasUsageResponse = z.object({buckets: z.array(usageBucket), credits_total: z.number().int(), group_by: z.string(), period_end: z.string(), period_start: z.string(), units_total: z.number().int()}); 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_usage * * GET /v1/usage */ export const getApiV1Usage = async (args: GetApiV1UsageArgs, options?: GetApiV1UsageOptions) => { const {baseUrl = "https://ndi-api.nace.ai", fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.period_start != null) query.append("period_start", String(args.period_start)) if (args.period_end != null) query.append("period_end", String(args.period_end)) if (args.workspace_id != null) query.append("workspace_id", String(args.workspace_id)) if (args.group_by != null) query.append("group_by", String(args.group_by)) if (APIKeyHeader !== undefined) headers.set("X-API-Key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/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(ndiServiceAppPlatformApiOperationsSchemasUsageResponse, await res.json()) };