import { day } from '@vrplatform/utils'; import * as z from 'zod'; import { EmailDeliveryError } from './send-email'; const postmarkMessagesResponseSchema = z.object({ TotalCount: z.number().int().nonnegative(), Messages: z.array( z.object({ MessageID: z.string().min(1), ReceivedAt: z.string().refine((value) => day(value).isValid()), Metadata: z.object({ deliveryId: z.string() }).passthrough(), }) ), }); export async function findPostmarkEmail( deliveryId: string, options: { fetch?: ( input: string | URL | Request, init?: RequestInit ) => Promise; postmarkToken?: string; } ) { if (!options.postmarkToken) { throw new EmailDeliveryError( 'Postmark is not configured', undefined, false, false ); } const url = new URL('https://api.postmarkapp.com/messages/outbound'); url.searchParams.set('count', '1'); url.searchParams.set('offset', '0'); url.searchParams.set('messagestream', 'outbound'); url.searchParams.set('metadata_deliveryId', deliveryId); const response = await (options.fetch ?? fetch)(url, { method: 'GET', headers: { Accept: 'application/json', 'X-Postmark-Server-Token': options.postmarkToken, }, }); const providerResponse: unknown = await response.json().catch(() => ({})); if (!response.ok) { throw new EmailDeliveryError( 'Postmark message lookup failed', { provider: 'postmark', providerCategory: 'rejected', httpStatus: response.status, }, false, response.status === 429 || response.status >= 500 ); } const result = postmarkMessagesResponseSchema.safeParse(providerResponse); if (!result.success) { throw new EmailDeliveryError('Postmark returned an invalid response'); } if (result.data.TotalCount === 0) return undefined; const message = result.data.Messages.find( ({ Metadata }) => Metadata.deliveryId === deliveryId ); if (!message) { throw new EmailDeliveryError('Postmark returned an invalid response'); } return { httpStatus: response.status, messageId: message.MessageID, submittedAt: message.ReceivedAt, }; }