import {z} from 'zod' export type GetApiContactsArgs = {cursor?: string | undefined, waId?: string | undefined, phoneNumber?: string | undefined}; export type GetApiContactsOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiContactsResponse = z.object({data: z.array(z.object({id: z.string(), waId: z.string().nullable(), waProfileName: z.string().nullable(), firstName: z.string().nullable(), lastName: z.string().nullable(), email: z.string().nullable(), phone: z.string().nullable(), occupation: z.string().nullable(), gender: z.string().nullable(), birthdate: z.string().nullable(), age: z.number().nullable(), notes: z.string().nullable(), tags: z.array(z.object({id: z.string(), name: z.string()})), createDate: z.string(), updateDate: z.string(), customProperties: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]).nullable())})), cursors: z.object({next: z.string().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 }; /** * List contacts * * GET /contacts */ export const getApiContacts = async (args: GetApiContactsArgs, options?: GetApiContactsOptions) => { const {baseUrl = "https://messenger-public-api.cogfy.com", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.waId != null) query.append("waId", String(args.waId)) if (args.phoneNumber != null) query.append("phoneNumber", String(args.phoneNumber)) if (ApiKeyAuth !== undefined) headers.set("api-key", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/contacts${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(getApiContactsResponse, await res.json()) };