import {z} from 'zod' export type GetApiV1SnapshotVenueArgs = {'Accept-Encoding': 'gzip', venue: 'stocks' | 'crypto' | 'forex' | 'dex', symbols?: string | undefined}; export type GetApiV1SnapshotVenueOptions = {baseUrl?: string | undefined, ApiKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const snapshotEntry = z.object({s: z.string().optional(), p: z.string().optional(), P: z.string().optional(), b: z.string().optional(), B: z.string().optional(), a: z.string().optional(), A: z.string().optional(), t: z.number().int().optional()}); export const snapshotResponse = z.object({data: z.array(snapshotEntry).optional(), meta: z.object({as_of: z.string().optional(), venue: z.string().optional(), count: z.number().int().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 }; /** * Full market snapshot (gzip required) * * GET /v1/snapshot/{venue} * * Also accepts auth: ApiKeyQuery */ export const getApiV1SnapshotVenue = async (args: GetApiV1SnapshotVenueArgs, options?: GetApiV1SnapshotVenueOptions) => { const {baseUrl = "https://api.sifting.io", fetch: fetchFn = fetch, ApiKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['Accept-Encoding'] != null) headers.set("Accept-Encoding", String(args['Accept-Encoding'])) if (args.symbols != null) query.append("symbols", String(args.symbols)) if (ApiKeyHeader !== undefined) headers.set("X-API-Key", ApiKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/snapshot/${encodeURIComponent(String(args.venue))}${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(snapshotResponse, await res.json()) };