import {z} from 'zod' export type GetApiIndexUuidCapsArgs = {uuid: string, base_symbol?: string | undefined, base_name?: string | undefined, base_plot_metric?: string | undefined, format?: 'csv' | undefined}; export type GetApiIndexUuidCapsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiIndexUuidCapsResponse = z.object({results: z.array(z.object({caps: z.object({}).optional(), date: z.string().optional(), id: z.string().optional()})).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 the caps of buffer MerQube index * * GET /index/{uuid}/caps */ export const getApiIndexUuidCaps = async (args: GetApiIndexUuidCapsArgs, options?: GetApiIndexUuidCapsOptions) => { const {baseUrl = "https://api.merqube.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.base_symbol != null) query.append("base_symbol", String(args.base_symbol)) if (args.base_name != null) query.append("base_name", String(args.base_name)) if (args.base_plot_metric != null) query.append("base_plot_metric", String(args.base_plot_metric)) if (args.format != null) query.append("format", String(args.format)) const url = `${baseUrl.replace(/\/+$/, '')}/index/${encodeURIComponent(String(args.uuid))}/caps${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(getApiIndexUuidCapsResponse, await res.json()) };