import {z} from 'zod' export type GetApiApiV1ProjectsProjectUuidCodeAlertsArgs = {projectUuid: string, slugs?: Array | undefined}; export type GetApiApiV1ProjectsProjectUuidCodeAlertsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const scheduledDeliveryAsCodeSkip = z.object({reason: z.string(), name: z.string()}); export const parameterValue = z.union([z.string(), z.number(), z.array(z.string()), z.array(z.number())]); export const parametersValuesMap = z.record(z.string(), parameterValue); export const fieldTarget = z.object({fieldId: z.string()}); export const filterOperator = z.enum(["isNull", "notNull", "equals", "notEquals", "startsWith", "endsWith", "include", "doesNotInclude", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual", "inThePast", "notInThePast", "inTheNext", "inTheCurrent", "notInTheCurrent", "inBetween", "notInBetween", "inPeriodToDate"]); export const filterRuleInput = z.object({target: fieldTarget, settings: z.unknown(), disabled: z.boolean().optional(), required: z.boolean().optional(), caseSensitive: z.boolean().optional(), operator: filterOperator, values: z.array(z.unknown()).optional(), includeNull: z.boolean().optional(), id: z.string().optional()}); export const filterGroupItemInput = z.union([z.lazy(() => filterGroupInput), filterRuleInput]); export const orFilterGroupInput = z.object({or: z.array(filterGroupItemInput), id: z.string().optional()}); export const andFilterGroupInput = z.object({and: z.array(filterGroupItemInput), id: z.string().optional()}); export const filterGroupInput: z.ZodType = z.union([orFilterGroupInput, andFilterGroupInput]); export const filtersInput = z.object({tableCalculations: filterGroupInput.optional(), metrics: filterGroupInput.optional(), dimensions: filterGroupInput.optional()}); export const notificationFrequency = z.enum(["always", "once"]); export const thresholdOperator = z.enum(["greaterThan", "lessThan", "increasedBy", "decreasedBy"]); export const thresholdOptions = z.object({value: z.number(), fieldId: z.string(), operator: thresholdOperator}); export const scheduledDeliveryTargetAsCode = z.union([z.object({recipient: z.string(), type: z.literal("email")}), z.object({channel: z.string(), type: z.literal("slack")})]); export const contentAsCodeTypeALERT = z.literal("alert"); export const alertAsCode = z.object({downloadedAt: z.string().optional(), parameters: parametersValuesMap.nullable(), filters: filtersInput.nullable(), notificationFrequency: notificationFrequency, thresholds: z.array(thresholdOptions), resource: z.object({slug: z.string(), type: z.literal("chart")}), targets: z.array(scheduledDeliveryTargetAsCode), includeLinks: z.boolean(), enabled: z.boolean(), timezone: z.string().nullable(), cron: z.string(), message: z.string().nullable(), name: z.string(), slug: z.string(), version: z.number(), contentType: contentAsCodeTypeALERT}); export const apiAlertAsCodeListResponse = z.object({results: z.object({skipped: z.array(scheduledDeliveryAsCodeSkip), alerts: z.array(alertAsCode)}), status: z.literal("ok")}); 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 }; /** * List alerts as code * * GET /api/v1/projects/{projectUuid}/code/alerts */ export const getApiApiV1ProjectsProjectUuidCodeAlerts = async (args: GetApiApiV1ProjectsProjectUuidCodeAlertsArgs, options: GetApiApiV1ProjectsProjectUuidCodeAlertsOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") for (const item of args.slugs ?? []) query.append("slugs", String(item)) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/projects/${encodeURIComponent(String(args.projectUuid))}/code/alerts${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(apiAlertAsCodeListResponse, await res.json()) };