import {z} from 'zod' export type GetApiDataV1MetricsMETRICIDInsightsArgs = {METRIC_ID: 'aggregate_startup_time' | 'downscale_percentage' | 'exits_before_video_start' | 'live_stream_latency' | 'max_downscale_percentage' | 'max_request_latency' | 'max_upscale_percentage' | 'page_load_time' | 'playback_failure_percentage' | 'playback_success_score' | 'player_startup_time' | 'playing_time' | 'rebuffer_count' | 'rebuffer_duration' | 'rebuffer_frequency' | 'rebuffer_percentage' | 'request_latency' | 'request_throughput' | 'rebuffer_score' | 'requests_for_first_preroll' | 'seek_latency' | 'startup_time_score' | 'unique_viewers' | 'upscale_percentage' | 'video_quality_score' | 'video_startup_preroll_load_time' | 'video_startup_preroll_request_time' | 'video_startup_time' | 'viewer_experience_score' | 'views' | 'weighted_average_bitrate' | 'video_startup_failure_percentage' | 'ad_attempt_count' | 'ad_break_count' | 'ad_break_error_count' | 'ad_break_error_percentage' | 'ad_error_count' | 'ad_error_percentage' | 'ad_exit_before_start_count' | 'ad_exit_before_start_percentage' | 'ad_impression_count' | 'ad_startup_error_count' | 'ad_startup_error_percentage' | 'playback_business_exception_percentage' | 'video_startup_business_exception_percentage' | 'view_content_startup_time' | 'ad_preroll_startup_time' | 'view_dropped_percentage' | 'rendition_change_count' | 'rendition_upshift_count' | 'rendition_downshift_count', measurement?: ('95th' | 'median' | 'avg' | 'count' | 'sum') | undefined, order_direction?: ('asc' | 'desc') | undefined, timeframe?: Array | undefined, filters?: Array | undefined, metric_filters?: Array | undefined}; export type GetApiDataV1MetricsMETRICIDInsightsOptions = {baseUrl?: string | undefined, accessToken?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const insight = z.object({total_watch_time: z.number().int().nullable(), total_playing_time: z.number().int().nullable(), total_views: z.number().int(), negative_impact_score: z.number(), metric: z.number(), filter_value: z.string().nullable(), filter_column: z.string()}); export const listInsightsResponse = z.object({data: z.array(insight), total_row_count: z.number().int(), timeframe: z.array(z.number().int()), meta: z.object({granularity: z.string().optional(), aggregation: z.string().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 }; /** * List Insights * * GET /data/v1/metrics/{METRIC_ID}/insights * * Also accepts auth: authorizationToken */ export const getApiDataV1MetricsMETRICIDInsights = async (args: GetApiDataV1MetricsMETRICIDInsightsArgs, options?: GetApiDataV1MetricsMETRICIDInsightsOptions) => { const {baseUrl = "https://api.mux.com", fetch: fetchFn = fetch, accessToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.measurement != null) query.append("measurement", String(args.measurement)) if (args.order_direction != null) query.append("order_direction", String(args.order_direction)) for (const item of args.timeframe ?? []) query.append("timeframe", String(item)) for (const item of args.filters ?? []) query.append("filters", String(item)) for (const item of args.metric_filters ?? []) query.append("metric_filters", String(item)) if (accessToken !== undefined) headers.set('authorization', `Basic ${btoa(`${accessToken.username}:${accessToken.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/data/v1/metrics/${encodeURIComponent(String(args.METRIC_ID))}/insights${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(listInsightsResponse, await res.json()) };