import {z} from 'zod' export type GetApiWalletUserTokenArgs = {user_token: string, 'Idempotency-Key'?: string | undefined, client_only?: boolean | undefined}; export type GetApiWalletUserTokenOptions = {baseUrl?: string | undefined, AUTHORIZERNAME?: string | undefined, fetch?: typeof fetch | undefined}; export const walletTxnResp = z.object({user_token: z.string(), token: z.string(), balance: z.number(), currency_code: z.string(), type: z.enum(["MASSPAY_CARD", "USER_FUNDS", "CLIENT_FUNDS", "SUBLEDGER_FUNDS"]), card_type: z.enum(["MASTERCARD", "VISA", "AMEX", "DISCOVER", "UNIONPAY"]).optional(), last_4: z.string().optional(), active: z.boolean(), client_paying_fees: z.boolean().optional(), fee_wallet_token: z.string().optional(), wiring_instructions: z.record(z.string(), z.unknown()).optional()}); export const getApiWalletUserTokenResponse = z.array(walletTxnResp); 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 }; /** * Retrieve all available wallets for a user * * GET /wallet/{user_token} * * Also accepts auth: api_key */ export const getApiWalletUserToken = async (args: GetApiWalletUserTokenArgs, options?: GetApiWalletUserTokenOptions) => { const {baseUrl = "https://api.masspay.io/v1.0.0", fetch: fetchFn = fetch, AUTHORIZERNAME} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (args.client_only != null) query.append("client_only", String(args.client_only)) if (AUTHORIZERNAME !== undefined) headers.set("Authorization", AUTHORIZERNAME) const url = `${baseUrl.replace(/\/+$/, '')}/wallet/${encodeURIComponent(String(args.user_token))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiWalletUserTokenResponse, await res.json()) };