import {z} from 'zod' export type GetApiConversationsArgs = {limit?: number | undefined, offset?: number | undefined, phone_id?: string | undefined, phone_number?: string | undefined, status?: ('delivered' | 'sent' | 'unconfirmed' | 'failed' | 'queued') | undefined, error_code?: ('phone_unreachable' | 'no_result' | 'policy_off' | 'expired' | 'no_subscription' | 'no_service' | 'radio_off' | 'carrier_rejected' | 'phone_rate_limited' | 'media_fetch_failed' | 'connection_lost' | 'queue_full' | 'send_failed') | undefined, replied?: ('true' | 'false') | undefined, period_start_at?: string | undefined, period_end_at?: string | undefined, search?: string | undefined}; export type GetApiConversationsOptions = {baseUrl: string, apiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const phoneMessagePart = z.object({file_id: z.string().optional(), mime_type: z.string().optional(), name: z.string().optional(), size_bytes: z.number().int().optional(), text: z.string().optional(), type: z.enum(["text", "media"])}); export const phoneMessagePhoneDeletion = z.object({next_check_at: z.string().nullable(), reason: z.string(), status: z.enum(["pending", "deleted", "not_found", "ambiguous", "not_default_app", "not_matched", "failed", "unconfirmed", "not_sent"])}); export const phoneMessage = z.object({$schema: z.string().optional(), accepted_at: z.string().optional(), api_key_id: z.string().optional(), body: z.string(), channel: z.enum(["sms", "mms", "rcs"]), conversation_id: z.string(), created_at: z.string(), deleted_at: z.string().optional(), delivered_at: z.string().optional(), direction: z.enum(["inbound", "outbound"]), error: z.string().optional(), error_code: z.enum(["phone_unreachable", "no_result", "policy_off", "expired", "no_subscription", "no_service", "radio_off", "carrier_rejected", "phone_rate_limited", "media_fetch_failed", "connection_lost", "queue_full", "send_failed"]).optional(), failed_at: z.string().optional(), from: z.string().nullable(), id: z.string(), is_group: z.boolean(), parts: z.array(phoneMessagePart).nullable(), phone_deletion: phoneMessagePhoneDeletion.optional(), phone_id: z.string(), received_at: z.string().nullable(), sent_at: z.string().nullable(), status: z.enum(["queued", "sent", "delivered", "failed", "unconfirmed"]).optional(), to: z.array(z.string()).nullable(), truncated: z.boolean(), user_id: z.string().optional()}); export const conversationParticipant = z.object({handle: z.string()}); export const conversation = z.object({$schema: z.string().optional(), created_at: z.string(), id: z.string(), is_group: z.boolean(), last_message: phoneMessage, last_message_at: z.string(), participants: z.array(conversationParticipant).nullable(), phone_id: z.string(), phone_number: z.string().nullable()}); export const conversationListResponse = z.object({$schema: z.string().optional(), conversations: z.array(conversation).nullable(), total: z.number().int()}); 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 conversations * * GET /conversations */ export const getApiConversations = async (args: GetApiConversationsArgs, options: GetApiConversationsOptions) => { const {baseUrl, fetch: fetchFn = fetch, apiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.offset != null) query.append("offset", String(args.offset)) if (args.phone_id != null) query.append("phone_id", String(args.phone_id)) if (args.phone_number != null) query.append("phone_number", String(args.phone_number)) if (args.status != null) query.append("status", String(args.status)) if (args.error_code != null) query.append("error_code", String(args.error_code)) if (args.replied != null) query.append("replied", String(args.replied)) if (args.period_start_at != null) query.append("period_start_at", String(args.period_start_at)) if (args.period_end_at != null) query.append("period_end_at", String(args.period_end_at)) if (args.search != null) query.append("search", String(args.search)) if (apiKeyAuth !== undefined) headers.set("X-Axilio-Api-Key", apiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/conversations${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(conversationListResponse, await res.json()) };