import {z} from 'zod' export type CreateApiWebstoreCheckoutArgs = {'x-store-domain': string, body: {gateway: 'PIX' | 'MERCADOPAGO' | 'STRIPE' | 'PAYPAL' | 'PICPAY' | 'PAGSEGURO' | 'PAGARME' | 'OTHER', client_email: string, client_name: string, client_phone?: string | undefined, client_document?: string | undefined, client_discord?: string | undefined, terms: boolean, fields?: {[key: string]: unknown} | undefined, cart?: (Array<{package_id: number, quantity: number, options?: {[key: string]: unknown} | undefined, fields?: {[key: string]: unknown} | undefined}>) | undefined, coupon?: string | undefined}}; export type CreateApiWebstoreCheckoutOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiWebstoreCheckoutResponse = z.union([z.object({checkout_url: z.string().optional()}), z.object({pix_code: z.string().optional(), qr_code: z.string().optional(), return_url: z.string().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 }; /** * Create Webstore Checkout * * POST /webstore/checkout */ export const createApiWebstoreCheckout = async (args: CreateApiWebstoreCheckoutArgs, options?: CreateApiWebstoreCheckoutOptions) => { const {baseUrl = "https://api.centralcart.io/v1", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['x-store-domain'] != null) headers.set("x-store-domain", String(args['x-store-domain'])) const url = `${baseUrl.replace(/\/+$/, '')}/webstore/checkout${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(createApiWebstoreCheckoutResponse, await res.json()) };