import {z} from 'zod' export type Investment = {T: string, A: number}; export type Portfolio = Array; export type CreateApiPortfolioExposuresArgs = {body: {portfolio?: Array | undefined}}; export type CreateApiPortfolioExposuresOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const getPortfolioExposuresResponse = z.object({exposure_dicts: z.object({country: z.record(z.string(), z.number()).optional(), sector: z.record(z.string(), z.number()).optional(), holding: z.record(z.string(), z.number()).optional()}).optional(), country_exposure_chart_markdown: z.string().optional(), sector_exposure_chart_markdown: z.string().optional(), holding_exposure_chart_markdown: 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 }; /** * Get sector, country, and holding exposures for the given portfolio and the markdown of respective charts * * POST /portfolio_exposures */ export const createApiPortfolioExposures = async (args: CreateApiPortfolioExposuresArgs, options?: CreateApiPortfolioExposuresOptions) => { const {baseUrl = "https://portfoliopilot.com/api/gpt", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/portfolio_exposures${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getPortfolioExposuresResponse, await res.json()) };