import {z} from 'zod' export type GetApiEventSchemaArgs = {status?: ('ACTIVE' | 'INACTIVE') | undefined, nextToken?: string | undefined, pageSize?: number | undefined}; export type GetApiEventSchemaOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const eventAttributeSchema = z.object({name: z.string().max(50), defaultUnit: z.string().max(10).optional()}); export const dimensionsSchema = z.object({name: z.string().max(50)}); export const featureDetails = z.object({featureId: z.string(), attributeName: z.string()}); export const dependency = z.object({type: z.literal("SETTING"), key: z.string(), name: z.string()}); export const field = z.object({name: z.string(), type: z.enum(["ATTRIBUTE", "DIMENSION"]), enrichmentType: z.enum(["VALUE", "JSON_LOGIC", "JSON_LOGIC_FROM_DEPENDENCY"]), value: z.string(), order: z.number().int()}); export const enrichments = z.object({dependencies: z.array(dependency).optional(), fields: z.array(field)}); export const eventSchemaListData = z.object({name: z.string().max(50), description: z.string().max(255).optional(), version: z.number().int().gte(1), status: z.enum(["DRAFT", "ACTIVE", "INACTIVE", "ARCHIVED"]).optional(), attributes: z.array(eventAttributeSchema).optional(), dimensions: z.array(dimensionsSchema).optional(), filterFields: z.array(z.string()).optional(), featureDetails: featureDetails.optional(), enrichments: enrichments.optional(), eventIdTemplate: z.string().optional(), eventLevelRevenue: z.boolean().optional(), createdAt: z.string().optional(), updatedAt: z.string().optional(), usageMetersCount: z.number().int().optional()}); export const paginationOptions = z.object({pageSize: z.number().int().optional(), sortOrder: z.enum(["ASC", "DESC"]).optional()}); export const eventSchemaListPaginatedResponse = z.object({data: z.array(eventSchemaListData).optional(), nextToken: z.string().optional(), context: paginationOptions.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 }; /** * List event schemas * * GET /event_schema */ export const getApiEventSchema = async (args: GetApiEventSchemaArgs, options?: GetApiEventSchemaOptions) => { 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.status != null) query.append("status", String(args.status)) if (args.nextToken != null) query.append("nextToken", String(args.nextToken)) if (args.pageSize != null) query.append("pageSize", String(args.pageSize)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/event_schema${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(eventSchemaListPaginatedResponse, await res.json()) };