import {z} from 'zod' export type CreateApiCardsGenericArgs = {body: {first_name: string, last_name: string, card_number: string, expiration_year: string, expiration_month: string, cvv?: (string | null) | undefined, address_line_one: string, address_line_two?: (string | null) | undefined, address_city: string, address_state: string, address_zip_code: string, address_country: string}}; export type CreateApiCardsGenericOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiCardsGenericResponse = z.object({token: z.string()}); 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 }; /** * Obtain a card token * * POST /cards/generic */ export const createApiCardsGeneric = async (args: CreateApiCardsGenericArgs, options?: CreateApiCardsGenericOptions) => { const {baseUrl = "https://payments.dailypay.com/v2", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/cards/generic${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(createApiCardsGenericResponse, await res.json()) };