import {z} from 'zod' export type GetApiChatsArgs = {limit?: number | undefined, status?: ('all' | 'unread' | 'unresolved' | 'done' | 'waiting_for_response' | 'open' | 'open_cart') | undefined, tags?: string | undefined, assignedUserPhone?: string | undefined, wabaNumbers?: string | undefined, instagramHandles?: string | undefined, nextChatId?: string | undefined, nextChatTimestamp?: number | undefined}; export type GetApiChatsOptions = {baseUrl?: string | undefined, basic?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiChatsResponse = z.object({chats: z.array(z.object({chatType: z.string().optional(), name: z.string().optional(), phoneNumber: z.string().nullable().optional(), imageUrl: z.string().nullable().optional(), unreadCount: z.number().optional(), isDone: z.boolean().optional(), optIn: z.boolean().optional(), chatUpdatedTime: z.number().optional(), lastMessageTime: z.number().optional(), wabaNumber: z.string().nullable().optional(), wabaPhoneName: z.string().nullable().optional(), wabaDisplayName: z.string().nullable().optional(), assignedUserName: z.string().nullable().optional(), assignedUserNumber: z.string().nullable().optional(), tagNames: z.array(z.string()).optional(), customFields: z.array(z.object({name: z.string().optional(), type: z.string().optional(), value: z.string().nullable().optional(), values: z.array(z.object({})).optional()})).optional(), lastMessage: z.object({}).optional(), isSlaActive: z.boolean().optional(), slaDueDate: z.string().nullable().optional(), slaBreachLevel: z.string().nullable().optional(), eligibleMessageTypes: z.array(z.string()).optional(), isReminderTriggered: z.boolean().optional(), providerType: z.enum(["INSTAGRAM", "GENERIC_CHANNEL", "null"]).nullable().optional()})).optional(), paginationOptions: z.object({hasMoreChats: z.boolean().optional(), nextChatId: z.string().nullable().optional(), nextChatTimestamp: z.number().nullable().optional()}).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 }; /** * Fetch chat list (inbox) * * GET /chats */ export const getApiChats = async (args: GetApiChatsArgs, options?: GetApiChatsOptions) => { const {baseUrl = "https://public.doubletick.io", fetch: fetchFn = fetch, basic} = 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.status != null) query.append("status", String(args.status)) if (args.tags != null) query.append("tags", String(args.tags)) if (args.assignedUserPhone != null) query.append("assignedUserPhone", String(args.assignedUserPhone)) if (args.wabaNumbers != null) query.append("wabaNumbers", String(args.wabaNumbers)) if (args.instagramHandles != null) query.append("instagramHandles", String(args.instagramHandles)) if (args.nextChatId != null) query.append("nextChatId", String(args.nextChatId)) if (args.nextChatTimestamp != null) query.append("nextChatTimestamp", String(args.nextChatTimestamp)) if (basic !== undefined) headers.set("Authorization", basic) const url = `${baseUrl.replace(/\/+$/, '')}/chats${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(getApiChatsResponse, await res.json()) };