import {z} from 'zod' export type GetApiApiV2AccountAccountUidSpacesArgs = {accountUid: string}; export type GetApiApiV2AccountAccountUidSpacesOptions = {baseUrl: string, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const currencyAndAmount = z.object({currency: z.string().min(1), minorUnits: z.number().int().gte(0)}); export const savingsGoalOrdered = z.object({savingsGoalUid: z.string(), name: z.string().min(1), target: currencyAndAmount.optional(), totalSaved: currencyAndAmount, savedPercentage: z.number().int().gte(0).optional(), sortOrder: z.number().int().optional(), state: z.enum(["CREATING", "ACTIVE", "ARCHIVING", "ARCHIVED", "RESTORING", "PENDING"])}); export const spendingSpace = z.object({spaceUid: z.string(), name: z.string().min(1), balance: currencyAndAmount, cardAssociationUid: z.string().optional(), sortOrder: z.number().int().optional(), spendingSpaceType: z.enum(["EXPENSE", "U16", "CONNECTED"]), state: z.enum(["CREATING", "ACTIVE", "ARCHIVING", "ARCHIVED", "RESTORING", "PENDING"])}); export const spaces = z.object({savingsGoals: z.array(savingsGoalOrdered), spendingSpaces: z.array(spendingSpace)}); 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 all active savings and spending spaces * * GET /api/v2/account/{accountUid}/spaces */ export const getApiApiV2AccountAccountUidSpaces = async (args: GetApiApiV2AccountAccountUidSpacesArgs, options: GetApiApiV2AccountAccountUidSpacesOptions) => { const {baseUrl, fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/account/${encodeURIComponent(String(args.accountUid))}/spaces${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(spaces, await res.json()) };