import {z} from 'zod' export type GetApiV4UserOptions = {baseUrl: string, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiV4UserResponse = z.object({data: z.object({oneId: z.string(), email: z.string().optional(), name: z.string().optional(), divisions: z.array(z.number()), accounts: z.array(z.object({id: z.string(), server: z.enum(["oanda", "oanda-demo", "otms", "v20", "v20-demo", "oj", "oj-demo", "opt", "ftmo-1"]), fund: z.enum(["DEMO", "LIVE"]), currency: z.string(), displayName: z.string(), marginRate: z.number().optional(), tags: z.array(z.enum(["OGM", "V20", "PAXOS", "MT4", "HEDGING", "SPREAD_BETTING", "LIMITED_RISK", "CFD", "PREMIUM", "OANDA_ONE", "ADMINISTRATORS", "CONNECT", "CONNECT_PREMIUM", "CONNECT_PREMIUM_EXPERIENCED", "CONNECT_PROFESSIONAL", "DEALERS", "OANDA", "PRIME", "STOCKS", "TECH", "TRADER", "STOCK", "DEMO", "CURRENCY", "INDEX", "COMMODITY", "TRADING_VIEW", "PROP_TRADER_US", "PROP_TRADER_US_TV", "FTMO", "TRADINGVIEW"])), experience: z.enum(["MARGIN", "SPOT"]), disabled: z.boolean(), isGSLOAllowed: z.boolean().optional(), closeOnly: z.boolean().optional(), groupHash: z.string(), conversionGroupHash: z.string().optional(), uplPriceTypeHash: z.string().nullable().optional(), division: z.number()}))})}); 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 }; /** * GET /v4/user */ export const getApiV4User = async (options: GetApiV4UserOptions) => { const {baseUrl, fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v4/user${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(getApiV4UserResponse, await res.json()) };