import {z} from 'zod' export type AgentSearchMode = 'default' | 'partition'; export type OutputFormat = 'json' | 'csv' | 'md_table'; export type SearchAgentOptions = {mode?: AgentSearchMode | undefined, output_format?: OutputFormat | undefined}; export type RequestEncoding = 'base64' | 'Empty'; export type SearchQuery = {analyze_profile?: boolean | undefined, end_time: number, from?: number | undefined, histogram_interval?: number | undefined, query_fn?: (string | null) | undefined, quick_mode?: boolean | undefined, sampling_config?: (Record | null) | undefined, sampling_ratio?: (number | null) | undefined, size?: number | undefined, skip_wal?: boolean | undefined, sql: string, start_time: number, streaming_id?: (string | null) | undefined, streaming_output?: boolean | undefined, timezone?: (string | null) | undefined, track_total_hits?: boolean | undefined, uses_zo_fn?: boolean | undefined}; export type SearchEventContext = {alert_key?: (string | null) | undefined, alert_name?: (string | null) | undefined, dashboard_id?: (string | null) | undefined, dashboard_name?: (string | null) | undefined, derived_stream_key?: (string | null) | undefined, folder_id?: (string | null) | undefined, folder_name?: (string | null) | undefined, panel_id?: (string | null) | undefined, public_dashboard_link_id?: (string | null) | undefined, range_key?: (string | null) | undefined, report_id?: (string | null) | undefined}; export type SearchEventType = 'ui' | 'dashboards' | 'reports' | 'alerts' | 'values' | 'other' | 'rum' | 'derivedstream' | 'searchjob' | 'download' | 'insights' | 'public_dashboard'; export type CreateApiApiOrgIdResultSchemaArgs = {org_id: string, is_streaming?: boolean | undefined, cross_linking?: boolean | undefined, body: {agent_options?: (SearchAgentOptions | null) | undefined, clear_cache?: boolean | undefined, clusters?: Array | undefined, encoding?: RequestEncoding | undefined, local_mode?: (boolean | null) | undefined, query: SearchQuery, regions?: Array | undefined, search_event_context?: (SearchEventContext | null) | undefined, search_type?: (SearchEventType | null) | undefined, timeout?: number | undefined, use_cache?: boolean | undefined, use_index?: boolean | undefined}}; export type CreateApiApiOrgIdResultSchemaOptions = {baseUrl: string, Authorization?: string | undefined, fetch?: typeof fetch | undefined}; export const crossLinkField = z.object({alias: z.string().nullable().optional(), name: z.string()}); export const crossLink = z.object({fields: z.array(crossLinkField).optional(), name: z.string(), url: z.string()}); export const crossLinksResponse = z.object({org_links: z.array(crossLink), stream_links: z.array(crossLink)}); export const resultSchemaResponse = z.object({cross_links: crossLinksResponse.nullable().optional(), group_by: z.array(z.string()), having: z.object({}).nullable().optional(), projections: z.array(z.string()), timeseries_field: z.string().nullable().optional(), where_by_stream: z.record(z.string(), z.string()).optional(), where_clause: z.string().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 search result schema * * POST /api/{org_id}/result_schema */ export const createApiApiOrgIdResultSchema = async (args: CreateApiApiOrgIdResultSchemaArgs, options: CreateApiApiOrgIdResultSchemaOptions) => { const {baseUrl, fetch: fetchFn = fetch, Authorization} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.is_streaming != null) query.append("is_streaming", String(args.is_streaming)) if (args.cross_linking != null) query.append("cross_linking", String(args.cross_linking)) if (Authorization !== undefined) headers.set("Authorization", Authorization) const url = `${baseUrl.replace(/\/+$/, '')}/api/${encodeURIComponent(String(args.org_id))}/result_schema${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(resultSchemaResponse, await res.json()) };