import {z} from 'zod' export type GetApiInboundArgs = {page?: number | undefined, per_page?: number | undefined, domain?: string | undefined, to?: string | undefined, q?: string | undefined, reports?: ('include' | 'exclude' | 'only') | undefined}; export type GetApiInboundOptions = {baseUrl?: string | undefined, bearerApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const inboundEmail = z.object({id: z.number().int(), domainId: z.number().int().optional(), fromAddress: z.string(), fromName: z.string().nullable().optional(), toAddress: z.string(), toAddresses: z.array(z.string()).nullable().optional(), ccAddresses: z.array(z.string()).nullable().optional(), messageId: z.string().nullable().optional(), subject: z.string().nullable().optional(), htmlBody: z.string().nullable().optional(), textBody: z.string().nullable().optional(), headers: z.object({}).nullable().optional(), mailboxHash: z.string().nullable().optional(), spamScore: z.number().nullable().optional(), spamVerdict: z.string().nullable().optional(), strippedReply: z.string().nullable().optional(), replyCount: z.number().int().optional(), createdAt: z.string()}); export const paginationMeta = z.object({page: z.number().int(), perPage: z.number().int(), total: z.number().int(), totalPages: z.number().int()}); export const getApiInboundResponse = z.object({data: z.array(inboundEmail), meta: paginationMeta}); 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 received emails * * GET /inbound * * Also accepts auth: bearerOAuth */ export const getApiInbound = async (args: GetApiInboundArgs, options?: GetApiInboundOptions) => { const {baseUrl = "https://api.poststack.dev", fetch: fetchFn = fetch, bearerApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.page != null) query.append("page", String(args.page)) if (args.per_page != null) query.append("per_page", String(args.per_page)) if (args.domain != null) query.append("domain", String(args.domain)) if (args.to != null) query.append("to", String(args.to)) if (args.q != null) query.append("q", String(args.q)) if (args.reports != null) query.append("reports", String(args.reports)) if (bearerApiKey !== undefined) headers.set('authorization', `Bearer ${bearerApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/inbound${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(getApiInboundResponse, await res.json()) };