import {z} from 'zod' export type EventInputObject = {transaction_id: string, external_subscription_id: string, code: string, timestamp?: (number | string) | undefined, precise_total_amount_cents?: (string | null) | undefined, properties?: ({target_wallet_code?: (string | null) | undefined} | {[key: string]: string | number | number} | null) | undefined}; export type EventInput = {event: EventInputObject}; export type CreateApiEventsArgs = {body: EventInput}; export type CreateApiEventsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const eventCreated = z.object({event: z.object({lago_id: z.string().nullable().optional(), transaction_id: z.string(), lago_customer_id: z.string().nullable(), code: z.string(), timestamp: z.string(), precise_total_amount_cents: z.string().nullable().optional(), properties: z.object({operation_type: z.enum(["add", "remove"]).nullable().optional()}).and(z.record(z.string(), z.union([z.string(), z.number().int(), z.number()]))).optional(), lago_subscription_id: z.string().nullable(), external_subscription_id: z.string(), created_at: z.string().nullable().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 }; /** * Send a usage event * * POST /events */ export const createApiEvents = async (args: CreateApiEventsArgs, options?: CreateApiEventsOptions) => { const {baseUrl = "https://api.getlago.com/api/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/events${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(eventCreated, await res.json()) };