import {z} from 'zod' export type RepeatInterval = {strategy?: 'default' | undefined} | {strategy: 'fixed', interval: number} | {strategy: 'linear', min: number, max: number} | {strategy: 'exponential', min: number, max: number}; export type MonitorMetric = {name: string, alias?: string | undefined}; export type Column = {name?: string | undefined, unit?: string | undefined}; export type Recovery = {minValue?: number | undefined, maxValue?: number | undefined}; export type ManualDetectorParams = {minValue?: number | undefined, maxValue?: number | undefined, recovery?: Recovery | undefined}; export type AutoDetectorParams = {tolerance?: ('low' | 'medium' | 'high') | undefined, trainingPeriod?: number | undefined, minDevFraction?: number | undefined, minDevAbsolute?: number | undefined}; export type DetectorConfig = {type: 'manual' | 'auto', params: ManualDetectorParams | AutoDetectorParams}; export type MetricMonitorParams = {metrics: Array, query: string, column?: Column | undefined, resolution?: number | undefined, numEvalPoints?: number | undefined, absentPoints?: ('zero' | 'ignore' | 'alert') | undefined, timeOffset?: number | undefined, detector: DetectorConfig}; export type MetricMonitorRequest = {name: string, notifyEveryoneByEmail?: boolean | undefined, teamIds?: Array | undefined, channelIds?: Array | undefined, repeatInterval?: RepeatInterval | undefined, trendAggFunc?: ('sum' | 'avg' | 'median' | 'last') | undefined, trendSensitivity?: ('low' | 'medium' | 'high') | undefined, type: 'metric', params: MetricMonitorParams}; export type ErrorMonitorParams = {metrics: Array, query: string}; export type ErrorMonitorRequest = {name: string, notifyEveryoneByEmail?: boolean | undefined, teamIds?: Array | undefined, channelIds?: Array | undefined, repeatInterval?: RepeatInterval | undefined, trendAggFunc?: ('sum' | 'avg' | 'median' | 'last') | undefined, trendSensitivity?: ('low' | 'medium' | 'high') | undefined, type: 'error', params: ErrorMonitorParams}; export type CreateApiInternalV1MonitorsProjectIdArgs = {project_id: number, body: MetricMonitorRequest | ErrorMonitorRequest}; export type CreateApiInternalV1MonitorsProjectIdOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const repeatInterval = z.union([z.object({strategy: z.literal("default").optional()}), z.object({strategy: z.literal("fixed"), interval: z.number()}), z.object({strategy: z.literal("linear"), min: z.number(), max: z.number()}), z.object({strategy: z.literal("exponential"), min: z.number(), max: z.number()})]); export const monitor = z.object({id: z.number().int(), projectId: z.number().int().optional(), key: z.string().optional(), name: z.string(), isNameTemplated: z.boolean().optional(), type: z.enum(["metric", "error"]), status: z.enum(["active", "paused", "firing", "no_data", "disabled"]), pausedUntil: z.number().optional(), error: z.string().optional(), notifyEveryoneByEmail: z.boolean().optional(), teamIds: z.array(z.number().int()).optional(), channelIds: z.array(z.number().int()).optional(), repeatInterval: repeatInterval.optional(), params: z.record(z.string(), z.unknown()).optional(), trendAggFunc: z.enum(["sum", "avg", "median", "last"]).optional(), trendSensitivity: z.enum(["low", "medium", "high"]).optional(), trendUpdatedAt: z.number().optional(), createdAt: z.number().optional(), updatedAt: z.number().optional(), checkedAt: z.number().optional(), nextCheckTime: z.number().optional()}); export const monitorResponse = z.object({monitor: monitor}); 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 monitor * * POST /internal/v1/monitors/{project_id} * * Also accepts auth: authTokenQuery */ export const createApiInternalV1MonitorsProjectId = async (args: CreateApiInternalV1MonitorsProjectIdArgs, options?: CreateApiInternalV1MonitorsProjectIdOptions) => { const {baseUrl = "https://api.uptrace.dev", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/internal/v1/monitors/${encodeURIComponent(String(args.project_id))}${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(monitorResponse, await res.json()) };