import {z} from 'zod' export type CreateApiApiAnalyticsV1QueryArgs = {body: {website_id: string, columns: Array<{column_id: string, transformation_id?: string | undefined, goal_id?: number | undefined}>, date_from?: (string | unknown) | undefined, date_to?: (string | unknown) | undefined, relative_date?: ('today' | 'yesterday' | 'last_week' | 'last_month' | 'last_year' | 'last_X_days') | undefined, filters?: ({operator: 'and' | 'or', conditions: Array<{column_id: string, transformation_id?: string | undefined, condition: {operator: string, value: unknown}}>}) | undefined, metric_filters?: ({operator: 'and' | 'or', conditions: Array<{column_id: string, transformation_id?: string | undefined, goal_id?: number | undefined, condition: {operator: 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte', value: number}}>}) | undefined, offset?: number | undefined, limit?: number | undefined, order_by?: (Array>) | undefined, format?: ('json' | 'json-kv' | 'csv' | 'xml') | undefined, column_format?: ('id' | 'name') | undefined, options?: ({sampling?: number | undefined}) | undefined}}; export type CreateApiApiAnalyticsV1QueryOptions = {baseUrl?: string | undefined, OAuth2ClientCredentials?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiApiAnalyticsV1QueryResponse = z.object({data: z.array(z.object({})).optional(), meta: z.object({count: z.number().int().optional(), scope: z.enum(["session", "event", "product", "google ads map", "google ads stats", "google search console"]).optional(), blended_datasets: z.array(z.enum(["google ads map", "google ads stats", "google search console"])).optional()}).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 }; /** * Execute query * * POST /api/analytics/v1/query/ */ export const createApiApiAnalyticsV1Query = async (args: CreateApiApiAnalyticsV1QueryArgs, options?: CreateApiApiAnalyticsV1QueryOptions) => { const {baseUrl = "https://example.piwik.pro", fetch: fetchFn = fetch, OAuth2ClientCredentials} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (OAuth2ClientCredentials !== undefined) headers.set('authorization', `Bearer ${OAuth2ClientCredentials}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/analytics/v1/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(createApiApiAnalyticsV1QueryResponse, await res.json()) };