import {z} from 'zod' export type GetApiEventsArgs = {nextToken?: string | undefined, status?: string | undefined, account_id?: string | undefined, schema_name?: string | undefined, pageSize?: number | undefined}; export type GetApiEventsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const attribute = z.object({name: z.string().min(1).max(50), value: z.string(), unit: z.string().min(1).max(50).optional()}); export const dimensions = z.record(z.string(), z.string().min(1).max(200)); export const event = z.object({schemaName: z.string().min(1).max(50), id: z.string().max(512).optional(), timestamp: z.string(), accountId: z.string().max(512), attributes: z.array(attribute), dimensions: dimensions}); export const ingestionStatus = z.object({status: z.enum(["INGESTION_IN_PROGRESS", "INGESTION_FAILED", "INGESTION_FAILED_SCHEMA_NOT_DEFINED", "INGESTION_FAILED_ENRICHMENT_FAILED", "INGESTION_FAILED_UNITS_INVALID", "INGESTION_COMPLETED_NO_MATCHING_METERS", "INGESTION_COMPLETED_EVENT_METERED", "INGESTION_COMPLETED_EVENT_NOT_METERED", "INGESTION_FAILED_PAST_GRACE_PERIOD", "INGESTION_FAILED_ACCOUNT_NOT_FOUND", "INGESTION_FAILED_DUPLICATE_EVENT", "INGESTION_FAILED_NO_EVENT_ID", "INGESTION_FAILED_INVALID_NAMED_LICENSE_EVENT", "INGESTION_FAILED_INSUFFICIENT_CREDITS", "REVERTED", "UNKNOWN"]), statusDescription: z.string().max(250).optional()}); export const eventSource = z.object({id: z.string().max(100), type: z.string().max(100)}); export const eventWithStatus = z.object({referenceId: z.string(), eventPayload: event, ingestionStatus: ingestionStatus, customerId: z.string().max(50).optional(), source: eventSource.optional(), createdAt: z.string()}); export const getEventsResponse = z.object({events: z.array(eventWithStatus), nextToken: z.string().max(500).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 a list of usage events with multiple query options * * GET /events */ export const getApiEvents = async (args: GetApiEventsArgs, options?: GetApiEventsOptions) => { const {baseUrl = "https://api.togai.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.nextToken != null) query.append("nextToken", String(args.nextToken)) if (args.status != null) query.append("status", String(args.status)) if (args.account_id != null) query.append("account_id", String(args.account_id)) if (args.schema_name != null) query.append("schema_name", String(args.schema_name)) if (args.pageSize != null) query.append("pageSize", String(args.pageSize)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/events${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(getEventsResponse, await res.json()) };