import {z} from 'zod' export type CheckLimitRequest = {customerRef: string, freeAllowance?: ({cap?: number | undefined, meter?: string | undefined, scope?: ('rolling_window' | 'lifetime') | undefined, windowDays?: number | undefined}) | undefined, includeCheckoutSession?: boolean | undefined, meterName?: string | undefined, productRef: string, usageType?: string | undefined}; export type CreateApiV1SdkLimitsArgs = {body: CheckLimitRequest}; export type CreateApiV1SdkLimitsOptions = {baseUrl?: string | undefined, SecretKey?: string | undefined, fetch?: typeof fetch | undefined}; export const limitAutoRechargeDto = z.object({enabled: z.boolean(), status: z.string().optional()}); export const limitBalanceDto = z.object({creditBalance: z.number(), creditsPerMinorUnit: z.number().optional(), creditsPerUnit: z.number(), currency: z.string(), displayExchangeRate: z.number().optional(), remainingUnits: z.number().optional()}); export const limitPlanItemDto = z.object({billingCycle: z.string().optional(), checkoutUrl: z.string().optional(), creditsPerUnit: z.number().optional(), currency: z.string(), freeUnits: z.number().optional(), name: z.string().optional(), options: z.array(z.record(z.string(), z.unknown())).optional(), perUnitChargeMinor: z.number().optional(), price: z.number(), reference: z.string(), requiresPayment: z.boolean(), type: z.string()}); export const limitProductBriefDto = z.object({name: z.string().optional(), reference: z.string()}); export const limitResponse = z.object({activationRequired: z.boolean().optional(), autoRecharge: limitAutoRechargeDto.optional(), balance: limitBalanceDto.optional(), checkoutSessionId: z.string().optional(), checkoutUrl: z.string().optional(), confirmationUrl: z.string().optional(), creditBalance: z.number().optional(), creditsPerUnit: z.number().optional(), currency: z.string().optional(), limit: z.number().optional(), meterName: z.string().optional(), needsTopUp: z.boolean().optional(), overage: z.boolean().optional(), paywallReason: z.enum(["activation_required", "topup_required", "payment_required", "limit_reached"]).optional(), planName: z.string().optional(), planRef: z.string().optional(), plans: z.array(limitPlanItemDto).optional(), product: limitProductBriefDto.optional(), purchaseRef: z.string().optional(), remaining: z.number(), used: z.number().optional(), withinLimits: z.boolean()}); 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 }; /** * Check usage limits for a customer and product * * POST /v1/sdk/limits */ export const createApiV1SdkLimits = async (args: CreateApiV1SdkLimitsArgs, options?: CreateApiV1SdkLimitsOptions) => { const {baseUrl = "https://api.solvapay.com", fetch: fetchFn = fetch, SecretKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (SecretKey !== undefined) headers.set('authorization', `Bearer ${SecretKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/sdk/limits${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(limitResponse, await res.json()) };