import {z} from 'zod' export type GetApiLogSchemasOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const enumValue = z.object({value: z.string(), display: z.string()}); export const type: z.ZodType = z.object({name: z.enum(["address", "array", "byte-count", "correlation-id", "country-code", "duration", "enum", "host", "label", "path", "port", "query", "script", "status-code", "string", "timestamp", "url", "url-map-id", "web-control-id"]), element_type: z.lazy(() => type.optional()), values: z.array(enumValue).optional()}); export const field = z.object({name: z.string(), type: type, display: z.string(), description: z.string(), is_metric: z.boolean(), aliases: z.array(z.string()).optional()}); export const retention = z.object({online_age: z.number().int().optional()}); export const logSchema = z.object({type: z.enum(["access", "cdn", "csp-reports", "custom", "pageviews", "events"]), display: z.enum(["CDN logs", "CSP reports", "Pageview logs", "Traffic viewer", "Event logs"]), default_order: z.string(), fields: z.array(field), retention: z.union([z.array(retention), retention])}); export const getApiLogSchemasResponse = z.array(logSchema); 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 log schemas * * GET /log-schemas */ export const getApiLogSchemas = async (options?: GetApiLogSchemasOptions) => { const {baseUrl = "https://api.webscale.com/v2", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/log-schemas${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiLogSchemasResponse, await res.json()) };