import {z} from 'zod' export type CheckoutSessionRequest = {priceDetails: {price: number, currency: string}, offer: {name: string, sku: string, displayName?: string | undefined, pricePointMetadata?: number | undefined}, items?: (Array<{name: string, assetUrl?: string | undefined, sku: string, quantity: number, quantityDisplay?: string | undefined, displayName?: string | undefined}>) | undefined, countryCode2?: string | undefined, playerIp?: string | undefined, customer: {id: string, email?: string | undefined, identitySignals?: ({firstSeenAt?: string | undefined}) | undefined}, receiptMetadata?: ({locale?: string | undefined}) | undefined, sessionMetadata?: Record | undefined, attributes?: Record | undefined, redirectUrl?: string | undefined}; export type CreateApiCheckoutV1SessionArgs = {'x-publisher-token': string, body: CheckoutSessionRequest}; export type CreateApiCheckoutV1SessionOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const checkoutSessionResponse = z.object({checkoutSessionToken: z.string().optional(), purchaseId: z.string().optional(), url: z.string().optional(), parsedUrl: 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 Checkout Session * * POST /checkout/v1/session */ export const createApiCheckoutV1Session = async (args: CreateApiCheckoutV1SessionArgs, options: CreateApiCheckoutV1SessionOptions) => { const {baseUrl, 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-publisher-token'] != null) headers.set("x-publisher-token", String(args['x-publisher-token'])) const url = `${baseUrl.replace(/\/+$/, '')}/checkout/v1/session${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(checkoutSessionResponse, await res.json()) };