import type { BasePayload } from 'payload' import { readdirSync, readFileSync } from 'node:fs' import path from 'node:path' import { vi } from 'vitest' import type { FakeRelayOptions } from '../../src/modules/email/relay/fake.js' import type { RelayOptions, ResolvedRelayOptions } from '../../src/modules/email/relay/options.js' import { relayConfirmEndpoint } from '../../src/modules/email/relay/confirm.js' import { createFakeRelay } from '../../src/modules/email/relay/fake.js' import { resolveRelayOptions } from '../../src/modules/email/relay/options.js' export const CONTRACT_DIR = path.resolve(import.meta.dirname, '../../contracts/mail-relay') export type ContractExample = { client?: { reEnrol?: boolean; retry?: boolean; status?: null | string } direction?: string given?: Record id: string request: { body?: unknown; headers?: Record; method: string; path: string; schema?: string } response: { body?: Record; schema?: string; status: number } then?: { mail?: Record; mails?: number } } export const contractExamples = (): ContractExample[] => readdirSync(path.join(CONTRACT_DIR, 'examples')) .filter((f) => f.endsWith('.json')) .sort() .map((f) => JSON.parse(readFileSync(path.join(CONTRACT_DIR, 'examples', f), 'utf8')) as ContractExample) /** The slice of Payload the relay client touches: the key-value store, the config, the logger, the two globals. */ export function relayPayload({ custom, endpoints = [relayConfirmEndpoint()], integrations = {}, serverURL = 'https://example.com', siteName = '' }: { custom?: object; endpoints?: unknown[]; integrations?: Record; serverURL?: string; siteName?: string } = {}) { const store = new Map() const logger = { error: vi.fn(), info: vi.fn(), warn: vi.fn() } const settings = { ...integrations } const payload = { config: { custom: custom ?? {}, endpoints, globals: [{ slug: 'site-integrations' }, { slug: 'site-settings' }], routes: { api: '/api' }, serverURL }, findGlobal: vi.fn(async ({ slug }: { slug: string }) => (slug === 'site-settings' ? { siteName } : settings)), kv: { delete: async (key: string) => void store.delete(key), get: async (key: string) => (store.has(key) ? structuredClone(store.get(key)) : null), keys: async () => [...store.keys()], set: async (key: string, value: object) => void store.set(key, structuredClone(value)), }, logger, updateGlobal: vi.fn(async ({ data }: { data: Record }) => Object.assign(settings, data)), } return { logger, payload: payload as unknown as BasePayload, settings, store } } /** How the fake service reaches this site's confirm route: straight into the endpoint's handler. */ export function callConfirmRoute(payload: BasePayload) { const endpoint = relayConfirmEndpoint() return async (url: string, init: { body: string; headers: Record }): Promise => { const target = new URL(url) if (target.pathname !== '/api/iapl/mail-relay/confirm') {return new Response(null, { status: 404 })} const req = { headers: new Headers({ ...init.headers, 'x-forwarded-for': '198.51.100.7' }), payload, text: async () => init.body, url } return (await endpoint.handler(req as never)) } } /** A site (the payload double) and a fake service that can call it back. */ export function relaySite({ fake: fakeOptions, options: own, ...site }: { fake?: FakeRelayOptions; options?: RelayOptions } & Parameters[0] = {}) { const made = relayPayload(site) const fake = createFakeRelay({ callSite: callConfirmRoute(made.payload), ...fakeOptions }) const options = resolveRelayOptions(made.payload, { fetchImpl: fake.fetch, retryBackoffMs: 1, url: fake.url, ...own }) as ResolvedRelayOptions return { ...made, fake, options } }