import {z} from 'zod' export type GetApiV1PrivacyAuditStatsArgs = {from?: (string | null) | undefined, to?: (string | null) | undefined, bucket?: ('day' | 'hour') | undefined}; export type GetApiV1PrivacyAuditStatsOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const auditEntityStat = z.object({entity_type: z.string(), event_count: z.number().int()}); export const auditTrendBucket = z.object({bucket_start: z.string(), event_count: z.number().int(), detection_count: z.number().int()}); export const auditStatsResponse = z.object({period_start: z.string(), period_end: z.string(), total_events: z.number().int(), total_detections: z.number().int(), by_source: z.record(z.string(), z.number().int()), by_entity_type: z.array(auditEntityStat), trend: z.array(auditTrendBucket)}); 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 }; /** * Aggregate PII scrub stats * * GET /v1/privacy/audit-stats */ export const getApiV1PrivacyAuditStats = async (args: GetApiV1PrivacyAuditStatsArgs, options: GetApiV1PrivacyAuditStatsOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.from != null) query.append("from", String(args.from)) if (args.to != null) query.append("to", String(args.to)) if (args.bucket != null) query.append("bucket", String(args.bucket)) if (APIKeyHeader !== undefined) headers.set("x-api-key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/privacy/audit-stats${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(auditStatsResponse, await res.json()) };