import {z} from 'zod' export type GetApiAccountsArgs = {customer_id?: string | undefined, from_id?: string | undefined, connection_id: string}; export type GetApiAccountsOptions = {baseUrl?: string | undefined, appId?: string | undefined, secret?: string | undefined, fetch?: typeof fetch | undefined}; export const accountExtra = z.object({account_name: z.string().optional(), account_number: z.string().optional(), assets: z.array(z.string()).optional(), available_amount: z.number().optional(), balance_type: z.string().optional(), blocked_amount: z.number().optional(), card_type: z.enum(["american_express", "china_unionpay", "diners_club", "jcb", "maestro", "master_card", "uatp", "visa", "mir"]).optional(), cards: z.array(z.string()).optional(), client_name: z.string().optional(), closing_balance: z.number().optional(), credit_limit: z.number().optional(), current_date: z.string().optional(), current_time: z.string().optional(), expiry_date: z.string().optional(), iban: z.string().optional(), bban: z.string().optional(), interest_rate: z.number().optional(), interest_type: z.string().optional(), floating_interest_rate: z.object({min_value: z.number().optional(), max_value: z.number().optional()}).optional(), remaining_payments: z.number().optional(), penalty_amount: z.number().optional(), next_payment_amount: z.number().optional(), next_payment_date: z.string().optional(), open_date: z.string().optional(), opening_balance: z.number().optional(), partial: z.boolean().optional(), provider_account_id: z.string().optional(), raw_balance: z.string().optional(), sort_code: z.string().optional(), statement_cut_date: z.string().optional(), status: z.string().optional(), swift: z.string().optional(), total_payment_amount: z.number().optional(), transactions_count: z.object({posted: z.number().int().optional(), pending: z.number().int().optional()}).optional(), payment_type: z.string().optional(), cashback_amount: z.number().optional(), monthly_total_payment: z.number().optional(), minimum_payment: z.number().optional(), premium_frequency: z.string().optional(), policy_status: z.string().optional(), life_assured_name: z.string().optional(), premium_amount: z.number().optional(), single_premium_amount: z.number().optional(), financial_consultant: z.string().optional(), total_reversionary_bonus: z.number().optional(), gross_surrender: z.number().optional(), guaranteed_gross_surrender: z.number().optional(), reversionary_bonus_cash_value: z.number().optional(), owned_policy_amount: z.number().optional(), policy_loan_limit: z.number().optional(), policy_converted_to_paid_up: z.number().optional(), paid_up_conversion_reversionary_bonus: z.number().optional(), policy_components: z.object({}).optional(), investment_amount: z.number().optional(), unit_price: z.number().optional(), units: z.number().optional(), indicative_unit_price: z.number().optional(), interest_income: z.number().optional(), interest_amount: z.number().optional(), profit_amount: z.number().optional(), profit_rate: z.number().optional(), asset_class: z.string().optional(), product_type: z.string().optional(), total_unit_value: z.number().optional(), fund_holdings: z.object({}).optional()}); export const account = z.object({id: z.string(), name: z.string(), nature: z.enum(["account", "bonus", "card", "checking", "credit", "credit_card", "debit_card", "ewallet", "insurance", "investment", "loan", "mortgage", "savings"]), balance: z.number(), currency_code: z.string(), extra: accountExtra, connection_id: z.string(), created_at: z.string(), updated_at: z.string()}); export const metaObject = z.object({next_id: z.string().optional(), next_page: z.string().optional()}); export const accountsResponse = z.object({data: z.array(account).optional(), meta: metaObject.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 of accounts * * GET /accounts */ export const getApiAccounts = async (args: GetApiAccountsArgs, options?: GetApiAccountsOptions) => { const {baseUrl = "https://www.saltedge.com/api/v5", fetch: fetchFn = fetch, appId, secret} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.customer_id != null) query.append("customer_id", String(args.customer_id)) if (args.from_id != null) query.append("from_id", String(args.from_id)) if (args.connection_id != null) query.append("connection_id", String(args.connection_id)) if (appId !== undefined) headers.set("App-id", appId) if (secret !== undefined) headers.set("Secret", secret) const url = `${baseUrl.replace(/\/+$/, '')}/accounts${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(accountsResponse, await res.json()) };