import {z} from 'zod' export type FunnelConversionWindowUnit = 'hours' | 'days' | 'weeks'; export type ExcludeFunnelDatePresetCustom = 'last_7_days' | 'last_14_days' | 'last_30_days' | 'last_90_days' | 'last_6_months' | 'last_12_months'; export type FunnelDateRange = {preset: ExcludeFunnelDatePresetCustom, type: 'preset'} | {end: string, start: string, type: 'custom'}; export type FunnelStep = {eventName: string, stepOrder: number}; export type FunnelQueryRequest = {breakdownDimensionId?: string | undefined, conversionWindow?: {unit: FunnelConversionWindowUnit, value: number} | undefined, dateRange: FunnelDateRange, steps: Array, eventNameFieldId: string, userIdFieldId: string, timestampFieldId: string, exploreName: string}; export type CreateApiApiV1ProjectsProjectUuidFunnelQueryArgs = {projectUuid: string, body: FunnelQueryRequest}; export type CreateApiApiV1ProjectsProjectUuidFunnelQueryOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const funnelStepResult = z.object({breakdownValue: z.string().optional(), medianTimeToConvertSeconds: z.number().nullable(), stepConversionRate: z.number(), conversionRate: z.number(), totalUsers: z.number(), stepName: z.string(), stepOrder: z.number()}); export const funnelQueryResult = z.object({sql: z.string(), steps: z.array(funnelStepResult)}); export const apiFunnelQueryResponse = z.object({results: funnelQueryResult, status: z.literal("ok")}); 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 }; /** * Run funnel query * * POST /api/v1/projects/{projectUuid}/funnel/query */ export const createApiApiV1ProjectsProjectUuidFunnelQuery = async (args: CreateApiApiV1ProjectsProjectUuidFunnelQueryArgs, options: CreateApiApiV1ProjectsProjectUuidFunnelQueryOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/projects/${encodeURIComponent(String(args.projectUuid))}/funnel/query${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(apiFunnelQueryResponse, await res.json()) };