import {z} from 'zod' export type LogicalOp = 'and' | 'or'; export type PairOperator = '=' | '!='; export type DimensionCondition = {items: Array>, op: LogicalOp, type: 'group'} | {key: string, operator: PairOperator, type: 'pair', value: string}; export type ResourcesRequest = {condition: DimensionCondition, refine_by: string}; export type CreateApiApiV2OrgIdDowntimesResourcesArgs = {org_id: string, body: ResourcesRequest}; export type CreateApiApiV2OrgIdDowntimesResourcesOptions = {baseUrl: string, Authorization?: string | undefined, fetch?: typeof fetch | undefined}; export const resourceValue = z.object({last_seen: z.number().int(), streams: z.array(z.string()), value: z.string()}); export const resourcesResponse = z.object({dimension: z.string(), source: z.string(), total: z.number().int().gte(0), values: z.array(resourceValue)}); 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 }; /** * Resources behind a condition * * POST /api/v2/{org_id}/downtimes/resources */ export const createApiApiV2OrgIdDowntimesResources = async (args: CreateApiApiV2OrgIdDowntimesResourcesArgs, options: CreateApiApiV2OrgIdDowntimesResourcesOptions) => { const {baseUrl, fetch: fetchFn = fetch, Authorization} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (Authorization !== undefined) headers.set("Authorization", Authorization) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/${encodeURIComponent(String(args.org_id))}/downtimes/resources${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(resourcesResponse, await res.json()) };