import {z} from 'zod' export type AutomationStep = {type: 'message' | 'wait' | 'condition' | 'tag' | 'question' | 'wait_payment', config?: ({[key: string]: unknown} | null) | undefined, branches?: ({[key: string]: Array} | null) | undefined, id?: (string | null) | undefined}; export type AutomationUpsertRequest = {name: string, trigger: 'webhook' | 'cart.abandoned' | 'payment.failed' | 'tag.applied' | 'conversation.started' | 'button.replied' | 'charge.paid' | 'charge.expired', triggerConfig?: ({[key: string]: unknown} | null) | undefined, steps?: Array | undefined}; export type CreateApiV1AutomationsArgs = {'Idempotency-Key'?: string | undefined, body: AutomationUpsertRequest}; export type CreateApiV1AutomationsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const automationStep: z.ZodType = z.object({type: z.enum(["message", "wait", "condition", "tag", "question", "wait_payment"]), config: z.record(z.string(), z.unknown()).nullable().optional(), branches: z.record(z.string(), z.array(z.lazy(() => automationStep))).nullable().optional(), id: z.string().nullable().optional()}); export const automationHook = z.object({url: z.string(), signatureEnabled: z.boolean(), hasSecret: z.boolean()}); export const automation = z.object({id: z.string(), name: z.string(), trigger: z.string(), triggerConfig: z.record(z.string(), z.unknown()).nullable().optional(), active: z.boolean(), steps: z.array(automationStep), costPerRunBrl: z.number(), stats: z.object({runsLast30Days: z.number().int().optional(), inFlight: z.number().int().optional(), completed: z.number().int().optional(), stopped: z.number().int().optional()}).nullable().optional(), webhookUrl: z.string().nullable().optional(), hook: automationHook.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 }; /** * Criar automação * * POST /v1/automations */ export const createApiV1Automations = async (args: CreateApiV1AutomationsArgs, options?: CreateApiV1AutomationsOptions) => { const {baseUrl = "https://api.ararahq.com", 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 (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/automations${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(automation, await res.json()) };