import type { AnalyticsAnnotationType, AnalyticsRoutes, AudienceRange, analyticsContract, GetAnalyticsAnnotationsResult, GetAnalyticsOverviewResult, GetAnalyticsSchemaResult, GetAudienceResult, GetContentStatsResult, GetExperimentResultsResult, GetLiveVisitorFlowResult, GetPageFlowResult, GetPageMetadataResult, IngestAnalyticsBody, IngestAnalyticsResult, RunAnalyticsRealtimeReportBody, RunAnalyticsReportBody, RunAnalyticsReportResult, } from '@intlayer/backend-contract/analytics'; import type { RouteEndpoints } from '@intlayer/backend-contract/defineRoute'; import { buildRouteURL } from '@intlayer/backend-contract/defineRoute'; import { editor } from '@intlayer/config/built'; import { BACKEND_URL } from '@intlayer/config/defaultValues'; import type { IntlayerConfig } from '@intlayer/types/config'; import { createEndpoint } from '../cms/createIntlayerCMS'; import { type FetcherOptions, fetcher } from '../fetcher'; /** Prefix of the routes, checked against the backend contract. */ const analyticsGroup = { prefix: '/api/analytics', } as const satisfies Pick; /** * Method and path of every route, checked against the backend contract at * compile time (the contract's zod schemas are never loaded). */ const analyticsEndpoints = { ingestAnalyticsEvents: { method: 'POST', path: '/events' }, getAnalyticsOverview: { method: 'GET', path: '/overview' }, getAnalyticsAudience: { method: 'GET', path: '/audience' }, getPageFlow: { method: 'GET', path: '/page-flow' }, getLiveVisitorFlow: { method: 'GET', path: '/audience/live/visitors/:visitorId', }, getContentStats: { method: 'GET', path: '/content-stats' }, getExperimentResults: { method: 'GET', path: '/experiments/:experimentKey' }, getPageMetadata: { method: 'GET', path: '/page-metadata' }, getAnalyticsSchema: { method: 'GET', path: '/schema' }, runAnalyticsReport: { method: 'POST', path: '/report' }, runAnalyticsRealtimeReport: { method: 'POST', path: '/realtime-report' }, getAnalyticsAnnotations: { method: 'GET', path: '/annotations' }, } as const satisfies RouteEndpoints; export const getAnalyticsAPI = ( authAPIOptions: FetcherOptions = {}, intlayerConfig?: IntlayerConfig ) => { const backendURL = intlayerConfig?.editor?.backendURL ?? editor.backendURL ?? BACKEND_URL; /** * Ingest a batch of analytics events. Public — attribution is by the * project's `clientId` in the body. * @param body - Session id, sdk version, and the collected events. * @returns The number of accepted events. */ const sendEvents = async ( body: IngestAnalyticsBody, otherOptions: FetcherOptions = {} ) => await fetcher( buildRouteURL( backendURL, analyticsGroup, analyticsEndpoints.ingestAnalyticsEvents ), authAPIOptions, otherOptions, { method: analyticsEndpoints.ingestAnalyticsEvents.method, body, } ); /** * Page/locale totals for the authenticated project. * @returns Views grouped by url and locale. */ const getOverview = async (otherOptions: FetcherOptions = {}) => await fetcher( buildRouteURL( backendURL, analyticsGroup, analyticsEndpoints.getAnalyticsOverview ), authAPIOptions, otherOptions, { method: analyticsEndpoints.getAnalyticsOverview.method } ); /** * Audience report: distinct visitors (today / 7d / window), page views, the * evolution series, and locale + country breakdowns. * @param range - Rolling window, either a named range (`1h`, `24h`, `7d`, * `30d`, `90d`, `6mo`, `1y`, `3y`) or a number of days (default 30). * @returns The audience statistics. */ const getAudience = async ( range: AudienceRange | number = 30, otherOptions: FetcherOptions = {} ) => await fetcher( buildRouteURL( backendURL, analyticsGroup, analyticsEndpoints.getAnalyticsAudience ), authAPIOptions, otherOptions, { method: analyticsEndpoints.getAnalyticsAudience.method, params: typeof range === 'number' ? { days: String(range) } : { range }, } ); /** * Per-content exposure totals — "which content is actually shown". * @returns Exposures grouped by dictionary key, key path, and locale. */ const getContentStats = async (otherOptions: FetcherOptions = {}) => await fetcher( buildRouteURL( backendURL, analyticsGroup, analyticsEndpoints.getContentStats ), authAPIOptions, otherOptions, { method: analyticsEndpoints.getContentStats.method } ); /** * A/B experiment results with per-variant conversion rates and significance. * @param experimentKey - The experiment to evaluate. * @returns The experiment result set. */ const getExperimentResults = async ( experimentKey: string, otherOptions: FetcherOptions = {} ) => await fetcher( buildRouteURL( backendURL, analyticsGroup, analyticsEndpoints.getExperimentResults, { experimentKey } ), authAPIOptions, otherOptions, { method: analyticsEndpoints.getExperimentResults.method } ); /** * Averaged page-to-page navigation flow from a starting page. * @param range - Rolling window of the report. * @param startUrl - Starting page pathname (default `/`). * @returns The flow steps and the links between them. */ const getPageFlow = async ( range: AudienceRange, startUrl: string, otherOptions: FetcherOptions = {} ) => await fetcher( buildRouteURL(backendURL, analyticsGroup, analyticsEndpoints.getPageFlow), authAPIOptions, otherOptions, { method: analyticsEndpoints.getPageFlow.method, params: { range, startUrl }, } ); /** * Page journey of a visitor active in the last 30 minutes. * @param visitorId - The visitor id from the `live` audience report. * @returns The visitor and its steps (`visitor: null` once it went quiet). */ const getLiveVisitorFlow = async ( visitorId: string, otherOptions: FetcherOptions = {} ) => await fetcher( buildRouteURL( backendURL, analyticsGroup, analyticsEndpoints.getLiveVisitorFlow, { visitorId } ), authAPIOptions, otherOptions, { method: analyticsEndpoints.getLiveVisitorFlow.method } ); /** * Page metadata (title and meta description) for a given url. * @param url - The page url to inspect. * @returns Title and description of the page. */ const getPageMetadata = async ( url: string, otherOptions: FetcherOptions = {} ) => await fetcher( buildRouteURL( backendURL, analyticsGroup, analyticsEndpoints.getPageMetadata ), authAPIOptions, otherOptions, { method: analyticsEndpoints.getPageMetadata.method, params: { url }, } ); /** * What can be reported on: dimensions, metrics and their compatibility, * retention, the project's locales and its experiments. */ const getSchema = async (otherOptions: FetcherOptions = {}) => await fetcher( buildRouteURL( backendURL, analyticsGroup, analyticsEndpoints.getAnalyticsSchema ), authAPIOptions, otherOptions, { method: analyticsEndpoints.getAnalyticsSchema.method } ); /** * Aggregated report: metrics broken down by dimensions over date ranges. * @param body - Date ranges, dimensions, metrics, filters, order, paging. */ const runReport = async ( body: RunAnalyticsReportBody, otherOptions: FetcherOptions = {} ) => await fetcher( buildRouteURL( backendURL, analyticsGroup, analyticsEndpoints.runAnalyticsReport ), authAPIOptions, otherOptions, { method: analyticsEndpoints.runAnalyticsReport.method, body } ); /** * Aggregated activity of the last minutes (up to one hour). * @param body - Dimensions, metrics, window and filters. */ const runRealtimeReport = async ( body: RunAnalyticsRealtimeReportBody, otherOptions: FetcherOptions = {} ) => await fetcher( buildRouteURL( backendURL, analyticsGroup, analyticsEndpoints.runAnalyticsRealtimeReport ), authAPIOptions, otherOptions, { method: analyticsEndpoints.runAnalyticsRealtimeReport.method, body } ); /** * Dated content and traffic events, to explain report changes. * @param query - Window (`YYYY-MM-DD`, `today`, `NdaysAgo`), types, limit. */ const getAnnotations = async ( query: { startDate?: string; endDate?: string; types?: AnalyticsAnnotationType[]; limit?: number; } = {}, otherOptions: FetcherOptions = {} ) => await fetcher( buildRouteURL( backendURL, analyticsGroup, analyticsEndpoints.getAnalyticsAnnotations ), authAPIOptions, otherOptions, { method: analyticsEndpoints.getAnalyticsAnnotations.method, params: { ...(query.startDate && { startDate: query.startDate }), ...(query.endDate && { endDate: query.endDate }), ...(query.types?.length && { types: query.types.join(',') }), ...(query.limit !== undefined && { limit: String(query.limit) }), }, } ); return { sendEvents, getSchema, runReport, runRealtimeReport, getAnnotations, getOverview, getAudience, getLiveVisitorFlow, getPageFlow, getContentStats, getExperimentResults, getPageMetadata, }; }; /** * Authenticated `analytics` endpoint bound to an Intlayer CMS authenticator. * * Pass an authenticator created with `createIntlayerCMS`, or omit it to use * the build-time configuration (`@intlayer/config/built`). */ export const analyticsEndpoint = createEndpoint(getAnalyticsAPI);