import {z} from 'zod' export type AggFunction = 'avg' | 'min' | 'max' | 'sum' | 'count' | 'median' | 'p50' | 'p75' | 'p90' | 'p95' | 'p99'; export type Operator = '=' | '!=' | '>' | '>=' | '<' | '<=' | 'contains' | 'not_contains' | 'is_null' | 'is_not_null' | 'is_empty' | 'is_not_empty'; export type Condition = {column: string, ignore_case?: boolean | undefined, operator: Operator, value: Record}; export type Aggregation = {function: AggFunction, group_by?: (Array | null) | undefined, having: Condition, multi_alert?: boolean | undefined, warning_value?: (number | null) | undefined}; export type CompareHistoricData = {offSet: string}; export type SearchEventType = 'ui' | 'dashboards' | 'reports' | 'alerts' | 'values' | 'other' | 'rum' | 'derivedstream' | 'searchjob' | 'download' | 'insights' | 'public_dashboard'; export type SloAlertKind = 'error_budget' | 'burn_rate'; export type SloCondition = {critical: number, kind: SloAlertKind, long_window_secs?: (number | null) | undefined, multi_alert?: boolean | undefined, operator: Operator, short_window_secs?: (number | null) | undefined, slo_id: string, warning?: (number | null) | undefined}; export type QueryType = 'custom' | 'sql' | 'promql' | 'slo'; export type QueryCondition = {aggregation?: (Aggregation | null) | undefined, conditions?: (Record | null) | undefined, multi_time_range?: (Array | null) | undefined, promql?: (string | null) | undefined, promql_condition?: (Condition | null) | undefined, promql_multi_alert?: boolean | undefined, promql_rule_mode?: boolean | undefined, promql_warning_value?: (number | null) | undefined, search_event_type?: (SearchEventType | null) | undefined, slo_condition?: (SloCondition | null) | undefined, sql?: (string | null) | undefined, type?: QueryType | undefined, vrl_function?: (string | null) | undefined}; export type RowTemplateType = 'String' | 'Json'; export type StreamType = 'logs' | 'metrics' | 'traces' | 'profiles' | 'service_graph' | 'enrichment_tables' | 'file_list' | 'metadata' | 'index'; export type FrequencyType = 'cron' | 'minutes'; export type TriggerCondition = {align_time?: boolean | undefined, cron?: string | undefined, frequency?: number | undefined, frequency_type?: FrequencyType | undefined, notify_on_warning?: (boolean | null) | undefined, operator?: Operator | undefined, period?: number | undefined, silence?: number | undefined, threshold?: number | undefined, timezone?: (string | null) | undefined, tolerance_in_secs?: (number | null) | undefined, warning_threshold?: (number | null) | undefined}; export type AlertTypeFilter = 'all' | 'scheduled' | 'realtime' | 'anomaly_detection' | 'slo' | 'composite'; export type AnomalyAlertFields = {alert_budget_per_day?: (number | null) | undefined, alert_direction?: (string | null) | undefined, alert_enabled?: (boolean | null) | undefined, alert_window_buckets?: (number | null) | undefined, alert_window_fire_pct?: (number | null) | undefined, alert_window_recover_pct?: (number | null) | undefined, band_width?: (number | null) | undefined, custom_sql?: (string | null) | undefined, detection_function: string, detection_function_field?: (string | null) | undefined, detection_window_seconds: number, filters: unknown, histogram_interval: string, level_half_width_seconds?: (number | null) | undefined, percentile?: (number | null) | undefined, query_mode: string, rcf_num_trees?: (number | null) | undefined, rcf_shingle_size?: (number | null) | undefined, rcf_tree_size?: (number | null) | undefined, retrain_interval_days?: (number | null) | undefined, schedule_interval: string, template?: (string | null) | undefined, training_window_days?: (number | null) | undefined}; export type CompositeStaleChildPolicy = 'use_last_state' | 'treat_as_false' | 'treat_as_true'; export type CompositeCondition = {expression: string, stale_child_policy?: CompositeStaleChildPolicy | undefined, warning_counts_as_firing?: boolean | undefined}; export type CreateApiApiV2OrgIdAlertsArgs = {org_id: string, folder?: string | undefined, body: {context_attributes?: ({[key: string]: string} | null) | undefined, creates_incident?: boolean | undefined, description?: string | undefined, destinations?: Array | undefined, enabled?: boolean | undefined, id?: (string | null) | undefined, incident_title_template?: (string | null) | undefined, is_real_time?: boolean | undefined, keep_firing_for?: number | undefined, last_edited_by?: (string | null) | undefined, last_satisfied_at?: (number | null) | undefined, last_triggered_at?: (number | null) | undefined, name?: string | undefined, notify_on_recovery?: boolean | undefined, oncall_team?: (string | null) | undefined, org_id?: string | undefined, owner?: (string | null) | undefined, pending_period_sec?: number | undefined, priority?: (number | null) | undefined, query_condition?: QueryCondition | undefined, recovery_destinations?: Array | undefined, row_template?: string | undefined, row_template_type?: RowTemplateType | undefined, runbook_url?: (string | null) | undefined, scheduler_job_present?: (boolean | null) | undefined, stream_name?: string | undefined, stream_type?: StreamType | undefined, suppress_repeats?: boolean | undefined, tags?: Array | undefined, template?: (string | null) | undefined, trigger_condition?: TriggerCondition | undefined, tz_offset?: number | undefined, updated_at?: (number | null) | undefined, workflows?: Array | undefined, alert_type?: (AlertTypeFilter | null) | undefined, anomaly_config?: (AnomalyAlertFields | null) | undefined, composite_condition?: (CompositeCondition | null) | undefined, folder_id?: (string | null) | undefined}}; export type CreateApiApiV2OrgIdAlertsOptions = {baseUrl: string, Authorization?: string | undefined, fetch?: typeof fetch | undefined}; export const httpResponse = z.object({code: z.number().int().gte(0), error_detail: z.string().nullable().optional(), hint: z.string().nullable().optional(), id: z.string().nullable().optional(), message: z.string(), name: z.string().nullable().optional(), suggestions: z.array(z.string()).nullable().optional(), trace_id: z.string().nullable().optional(), warnings: z.array(z.string()).nullable().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 new alert * * POST /api/v2/{org_id}/alerts */ export const createApiApiV2OrgIdAlerts = async (args: CreateApiApiV2OrgIdAlertsArgs, options: CreateApiApiV2OrgIdAlertsOptions) => { 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 (args.folder != null) query.append("folder", String(args.folder)) if (Authorization !== undefined) headers.set("Authorization", Authorization) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/${encodeURIComponent(String(args.org_id))}/alerts${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(httpResponse, await res.json()) };