import {z} from 'zod' export type TestWebhookRequestDto = {event_type?: (string | null) | undefined}; export type CreateApiV1WebhooksWebhookIdTestArgs = {webhook_id: string, body: TestWebhookRequestDto | null}; export type CreateApiV1WebhooksWebhookIdTestOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const testDeliveryResultDto = z.object({status_code: z.number().int(), response_time_ms: z.number().int(), timestamp: z.string()}); export const eventLinkDto = z.object({version: z.string(), url: z.string()}); export const eventNotificationDto = z.object({event_id: z.string(), event_type: z.string(), links: z.array(eventLinkDto)}); export const testWebhookResponseDto = z.object({success: z.boolean(), delivery: testDeliveryResultDto, payload: eventNotificationDto}); 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 }; /** * Test a webhook delivery * * POST /v1/webhooks/{webhook_id}/test */ export const createApiV1WebhooksWebhookIdTest = async (args: CreateApiV1WebhooksWebhookIdTestArgs, options?: CreateApiV1WebhooksWebhookIdTestOptions) => { const {baseUrl = "https://api.whitepages.com", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKeyAuth !== undefined) headers.set("x-api-key", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/v1/webhooks/${encodeURIComponent(String(args.webhook_id))}/test${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(testWebhookResponseDto, await res.json()) };