import {z} from 'zod' export type ExtendedV1LoadRequestQueryTimeDimension = {dimension: string, granularity?: ('second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year' | null) | undefined, dateRange?: (string | Array | null) | undefined, compareDateRange?: (Array> | null) | undefined}; export type V1LoadRequestQueryFilterBase = {member?: (string | null) | undefined, operator?: ('equals' | 'notEquals' | 'contains' | 'notContains' | 'startsWith' | 'notStartsWith' | 'endsWith' | 'notEndsWith' | 'gt' | 'gte' | 'lt' | 'lte' | 'set' | 'notSet' | 'inDateRange' | 'notInDateRange' | 'beforeDate' | 'afterDate' | 'measureFilter' | null) | undefined, values?: (Array | null) | undefined}; export type V1LoadRequestQueryFilterLogicalAnd = {and?: (Array | null) | undefined}; export type V1LoadRequestQueryFilterLogicalOr = {or?: (Array | null) | undefined}; export type ExtendedV1LoadRequestQuery = {measures?: (Array | null) | undefined, dimensions?: (Array | null) | undefined, segments?: (Array | Array<{[key: string]: unknown}> | null) | undefined, timeDimensions?: (Array | null) | undefined, order?: (Array> | null) | undefined, limit?: (number | null) | undefined, offset?: (number | null) | undefined, filters?: (Array | null) | undefined, timezone?: (string | null) | undefined, renewQuery?: (boolean | null) | undefined, ungrouped?: (boolean | null) | undefined, forceNoCache?: (boolean | null) | undefined}; export type ComputeResourceRequest = {cpu?: string | undefined, memory?: string | undefined, timeoutSeconds?: number | undefined}; export type ApiQueryRequest = {sql?: string | undefined, cube_query?: (ExtendedV1LoadRequestQuery | null) | undefined, integration_id?: string | undefined, log_event?: boolean | undefined, persist?: boolean | undefined, invalidate?: boolean | undefined, raw?: boolean | undefined, resources?: (ComputeResourceRequest | null) | undefined}; export type CreateApiV1QueryArgs = {raw?: boolean | undefined, format?: ('json' | 'arrow') | undefined, body: ApiQueryRequest}; export type CreateApiV1QueryOptions = {baseUrl: string, AsyncAPIKeyHeaderAuthenticator?: string | undefined, fetch?: typeof fetch | undefined}; export const blockResultsRowSchema = z.object({name: z.string(), type: z.string(), sql_value_type: z.string().nullable().optional(), format: z.string().nullable().optional(), meta: z.record(z.string(), z.unknown()).nullable().optional()}); export const apiQueryResponse = z.object({data: z.array(z.unknown()).optional(), raw_data: z.unknown(), schema: z.array(blockResultsRowSchema).optional(), integration_id: z.union([z.string(), z.string()]), executed_query: z.union([z.string(), z.record(z.string(), z.unknown())]).nullable().optional(), query_type: z.string().nullable().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 }; /** * Queries an integration * * POST /v1/query */ export const createApiV1Query = async (args: CreateApiV1QueryArgs, options: CreateApiV1QueryOptions) => { const {baseUrl, fetch: fetchFn = fetch, AsyncAPIKeyHeaderAuthenticator} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.raw != null) query.append("raw", String(args.raw)) if (args.format != null) query.append("format", String(args.format)) if (AsyncAPIKeyHeaderAuthenticator !== undefined) headers.set("Authorization", AsyncAPIKeyHeaderAuthenticator) const url = `${baseUrl.replace(/\/+$/, '')}/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(apiQueryResponse, await res.json()) };