import {z} from 'zod' export type GetApiAnalyticsInsightsArgs = {period?: number | undefined, force?: boolean | undefined, cached_only?: boolean | undefined, environment?: (0 | 1) | undefined}; export type GetApiAnalyticsInsightsOptions = {baseUrl?: string | undefined, secretAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const v4AnalyticsInsight = z.object({type: z.enum(["critical", "positive", "tip", "info"]), metric: z.string(), title: z.string(), body: z.string(), action: z.string()}); export const v4AnalyticsInsights = z.object({object: z.literal("analytics_insights"), url: z.string(), generated_at: z.string().nullable(), period_days: z.number().int().gte(1).lte(365), health: z.enum(["healthy", "watch", "critical", "null"]).nullable(), health_score: z.number().int().gte(0).lte(10).optional(), summary: z.string(), insights: z.array(v4AnalyticsInsight), is_cached: z.boolean().optional(), is_stale: z.boolean().optional(), is_empty: z.boolean().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 }; /** * Get analytics insights * * GET /analytics/insights */ export const getApiAnalyticsInsights = async (args: GetApiAnalyticsInsightsArgs, options?: GetApiAnalyticsInsightsOptions) => { const {baseUrl = "https://api.qonversion.io/v4", fetch: fetchFn = fetch, secretAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.period != null) query.append("period", String(args.period)) if (args.force != null) query.append("force", String(args.force)) if (args.cached_only != null) query.append("cached_only", String(args.cached_only)) if (args.environment != null) query.append("environment", String(args.environment)) if (secretAuth !== undefined) headers.set('authorization', `Bearer ${secretAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/analytics/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(v4AnalyticsInsights, await res.json()) };