import {z} from 'zod' export type ForwardRequestSource = {type: string, id: string, cvv_token?: string | undefined, pin_token?: string | undefined} | {type: string, token: string, store_for_future_use?: boolean | undefined}; export type ForwardRequestNetworkToken = {enabled?: boolean | undefined, request_cryptogram?: boolean | undefined}; export type ForwardBodyHeadersRequest = {encrypted?: string | undefined, raw: {[key: string]: string}}; export type ForwardRequestSignature = {type: string, dlocal_parameters: {secret_key: string}} | {type: string, mastercard_parameters: {consumer_key: string, signing_key: string}} | {type: string, visa_parameters: {shared_secret: string, remove_resource_path_prefix?: string | undefined}}; export type ForwardDestinationRequest = {url: string, method: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'TRACE' | 'PATCH', headers: ForwardBodyHeadersRequest, body: string, signature?: ForwardRequestSignature | undefined, variables?: (Array<{name?: string | undefined, value?: string | undefined}>) | undefined, query?: (Array<{name?: string | undefined, value?: string | undefined}>) | undefined}; export type ForwardRequest = {source: ForwardRequestSource, reference?: string | undefined, processing_channel_id?: string | undefined, network_token?: ForwardRequestNetworkToken | undefined, destination_request: ForwardDestinationRequest}; export type CreateApiForwardArgs = {body: ForwardRequest}; export type CreateApiForwardOptions = {baseUrl?: string | undefined, OAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const forwardBodyResponse = z.object({status: z.number(), headers: z.record(z.string(), z.array(z.string())), body: z.string()}); export const forwardResponse = z.object({request_id: z.string(), destination_response: forwardBodyResponse.optional(), source: z.object({id: z.string().optional(), bin: z.string().max(8), last4: z.string().min(4).max(4), fingerprint: z.string().min(64).max(64)}).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 }; /** * Forward an API request * * POST /forward * * Also accepts auth: ApiSecretKey */ export const createApiForward = async (args: CreateApiForwardArgs, options?: CreateApiForwardOptions) => { const {baseUrl = "https://forward.checkout.com", fetch: fetchFn = fetch, OAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (OAuth !== undefined) headers.set('authorization', `Bearer ${OAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/forward${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(forwardResponse, await res.json()) };