import {z} from 'zod' export type MiniAppSubscriptionPurchaseRequest = {initData: string, subscriptionId?: (number | null) | undefined, selection?: ({[key: string]: unknown} | null) | undefined, periodId?: (string | null) | undefined, periodDays?: (number | null) | undefined, period?: (string | null) | undefined, trafficValue?: (number | null) | undefined, traffic?: (number | null) | undefined, trafficGb?: (number | null) | undefined, servers?: (Array | null) | undefined, countries?: (Array | null) | undefined, serverUuids?: (Array | null) | undefined, devices?: (number | null) | undefined, deviceLimit?: (number | null) | undefined}; export type CreateApiMiniappSubscriptionPurchaseArgs = {body: MiniAppSubscriptionPurchaseRequest}; export type CreateApiMiniappSubscriptionPurchaseOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const miniAppSubscriptionPurchaseResponse = z.object({success: z.boolean().optional(), message: z.string().nullable().optional(), balanceKopeks: z.number().int().nullable().optional(), balanceLabel: z.string().nullable().optional(), subscriptionId: z.number().int().nullable().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 }; /** * Subscription Purchase Endpoint * * POST /miniapp/subscription/purchase */ export const createApiMiniappSubscriptionPurchase = async (args: CreateApiMiniappSubscriptionPurchaseArgs, options: CreateApiMiniappSubscriptionPurchaseOptions) => { 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") const url = `${baseUrl.replace(/\/+$/, '')}/miniapp/subscription/purchase${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(miniAppSubscriptionPurchaseResponse, await res.json()) };