import {z} from 'zod' export type ViewFilter = {[key: string]: Array}; export type ViewConnectionsEmail = {addresses?: Array | undefined, include_all_organizers?: boolean | undefined}; export type ViewConnectionsSlack = {id: string, name: string}; export type ViewConnections = {email?: ViewConnectionsEmail | undefined, slack?: Array | undefined}; export type ViewPrincipalDimension = string; export type ViewAnomaliesThresholdType = 'Automatic' | 'Percent'; export type ViewAnomaliesThresholdAmount = number; export type ViewAnomalies = {enabled?: boolean | undefined, threshold_type?: ViewAnomaliesThresholdType | undefined, threshold_amount?: ViewAnomaliesThresholdAmount | undefined, min_cost_impact?: number | undefined}; export type ViewNotifications = {weekly?: boolean | undefined, monthly?: boolean | undefined}; export type ViewNew = {name: string, filter: ViewFilter, connections: ViewConnections, principal_dimension: ViewPrincipalDimension, anomalies?: ViewAnomalies | undefined, notifications?: ViewNotifications | undefined}; export type CreateApiV2ViewsArgs = {'cloudzero-idempotency-key'?: string | undefined, 'cloudzero-test-key'?: string | undefined, body: ViewNew}; export type CreateApiV2ViewsOptions = {baseUrl?: string | undefined, APIKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const viewFilter = z.record(z.string(), z.array(z.string())); export const viewConnectionsEmail = z.object({addresses: z.array(z.string()).optional(), include_all_organizers: z.boolean().optional()}); export const viewConnectionsSlack = z.object({id: z.string(), name: z.string()}); export const viewConnections = z.object({email: viewConnectionsEmail.optional(), slack: z.array(viewConnectionsSlack).optional()}); export const viewPrincipalDimension = z.string(); export const viewAnomaliesThresholdType = z.enum(["Automatic", "Percent"]); export const viewAnomaliesThresholdAmount = z.number().int(); export const viewAnomalies = z.object({enabled: z.boolean().optional(), threshold_type: viewAnomaliesThresholdType.optional(), threshold_amount: viewAnomaliesThresholdAmount.optional(), min_cost_impact: z.number().gte(0).optional()}); export const epoch = z.string(); export const isoDatetime = z.string(); export const viewCreateUpdateResponse = z.object({view: z.object({name: z.string(), filter: viewFilter, connections: viewConnections, principal_dimension: viewPrincipalDimension, anomalies: viewAnomalies.optional(), notifications: z.object({weekly: z.boolean(), monthly: z.boolean()}).optional(), id: z.string(), last_updated: epoch, last_edited: isoDatetime}).optional()}); 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 }; /** * Create a new View * * POST /v2/views */ export const createApiV2Views = async (args: CreateApiV2ViewsArgs, options?: CreateApiV2ViewsOptions) => { const {baseUrl = "https://api.cloudzero.com", fetch: fetchFn = fetch, APIKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['cloudzero-idempotency-key'] != null) headers.set("cloudzero-idempotency-key", String(args['cloudzero-idempotency-key'])) if (args['cloudzero-test-key'] != null) headers.set("cloudzero-test-key", String(args['cloudzero-test-key'])) if (APIKeyAuth !== undefined) headers.set("Authorization", APIKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/v2/views${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(viewCreateUpdateResponse, await res.json()) };