import {z} from 'zod' export type GetApiCardsArgs = {accountId?: Array | undefined, status?: (Array<'active' | 'frozen' | 'cancelled' | 'inactive' | 'expired' | 'suspended'>) | undefined, type?: (Array<'virtual' | 'physical'>) | undefined, kind?: (Array<'debit' | 'credit'>) | undefined, userId?: string | undefined, isAgentCard?: boolean | undefined, limit?: number | undefined, order?: ('asc' | 'desc') | undefined, start_after?: string | undefined, end_before?: string | undefined}; export type GetApiCardsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const cardBudget = z.object({amountCents: z.number().int().gte(0), id: z.string(), name: z.string(), remainingAmountCents: z.number().int().gte(0)}); export const mercuryCategory = z.enum(["Other", "Advertising", "Airlines", "AlcoholAndBars", "BooksAndNewspaper", "CarRental", "Charity", "Clothing", "Conferences", "Education", "Electronics", "Entertainment", "FacilitiesExpenses", "Fees", "FoodDelivery", "FuelAndGas", "Gambling", "GovernmentServices", "Grocery", "GroundTransportation", "Insurance", "InternetAndTelephone", "Legal", "Lodging", "Medical", "Memberships", "OfficeSupplies", "OtherTravel", "Parking", "Political", "ProfessionalServices", "Restaurants", "Retail", "RideshareAndTaxis", "Shipping", "Software", "Taxes", "Utilities", "VehicleExpenses"]); export const merchantId = z.string(); export const card = z.object({accountId: z.string(), budgets: z.array(cardBudget), categoryLocks: z.array(mercuryCategory), createdAt: z.string(), expiration: z.object({month: z.number().int().gte(1).lte(12), year: z.number().int().gte(2000).lte(2999)}), id: z.string(), isAgentCard: z.boolean(), kind: z.enum(["debit", "credit"]), lastFour: z.string(), merchantLock: z.object({id: merchantId, name: z.string()}).nullable().optional(), nameOnCard: z.string(), nickname: z.string().nullable().optional(), physicalCardStatus: z.enum(["inactive", "active", "locked"]).nullable().optional(), spendLimit: z.object({amountCents: z.number().int().gte(0), atmAmountCents: z.number().int().gte(0).nullable().optional(), interval: z.enum(["daily", "weekly", "monthly", "yearly"])}).nullable().optional(), spendLimitType: z.enum(["cardLimit", "budgets"]), status: z.enum(["active", "frozen", "cancelled", "inactive", "expired", "suspended"]), type: z.enum(["virtual", "physical"]), updatedAt: z.string(), userId: z.string()}); export const cardListResponse = z.object({cards: z.array(card), page: z.object({nextPage: z.string().optional(), previousPage: 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 }; /** * List cards * * GET /cards */ export const getApiCards = async (args: GetApiCardsArgs, options?: GetApiCardsOptions) => { const {baseUrl = "https://api.mercury.com/api/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") for (const item of args.accountId ?? []) query.append("accountId", String(item)) for (const item of args.status ?? []) query.append("status", String(item)) for (const item of args.type ?? []) query.append("type", String(item)) for (const item of args.kind ?? []) query.append("kind", String(item)) if (args.userId != null) query.append("userId", String(args.userId)) if (args.isAgentCard != null) query.append("isAgentCard", String(args.isAgentCard)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.order != null) query.append("order", String(args.order)) if (args.start_after != null) query.append("start_after", String(args.start_after)) if (args.end_before != null) query.append("end_before", String(args.end_before)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/cards${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(cardListResponse, await res.json()) };