import {z} from 'zod' export type GetApiApiV2NewsArgs = {tickers?: string | undefined, eventTypes?: ('earnings' | 'dividends' | 'guidance' | 'mna' | 'financing' | 'buyback' | 'rating' | 'analyst' | 'management' | 'legal_regulatory' | 'operations' | 'market_move' | 'macro' | 'other') | undefined, sentiment?: ('positive' | 'negative' | 'neutral' | 'mixed') | undefined, minImportance?: number | undefined, from?: string | undefined, to?: string | undefined, limit?: number | undefined, cursor?: string | undefined, includeArticle?: ('true' | 'false') | undefined}; export type GetApiApiV2NewsOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const newsImage = z.object({url: z.string(), smallUrl: z.string(), width: z.number().int(), height: z.number().int(), alt: z.string(), source: z.enum(["commons", "ai"]), credit: z.string().nullable(), license: z.string().nullable(), licenseUrl: z.string().nullable(), sourceUrl: z.string().nullable()}).nullable(); export const newsAsset = z.object({ticker: z.string(), tickers: z.array(z.string()), name: z.string(), type: z.enum(["stock", "fii", "fiagro", "fiinfra", "fidc", "fip", "etf", "bdr", "index", "currency"]), relevance: z.enum(["primary", "secondary"]), sentiment: z.enum(["positive", "negative", "neutral"]).nullable(), reason: z.string().nullable()}); export const newsSource = z.object({name: z.string(), title: z.string(), url: z.string(), publishedAt: z.string()}); export const newsStory = z.object({id: z.string(), slug: z.string(), url: z.string(), title: z.string(), description: z.string().nullable(), summary: z.string(), image: newsImage, keyPoints: z.array(z.string()), article: z.string().nullable(), eventType: z.enum(["earnings", "dividends", "guidance", "mna", "financing", "buyback", "rating", "analyst", "management", "legal_regulatory", "operations", "market_move", "macro", "other"]), scope: z.enum(["company", "market"]), sentiment: z.object({label: z.enum(["positive", "negative", "neutral", "mixed"]), score: z.number()}), importance: z.number().int().gte(1).lte(5), topics: z.array(z.string()), assets: z.array(newsAsset), sources: z.array(newsSource), publishedAt: z.string(), updatedAt: z.string(), articleWrittenAt: z.string().nullable()}); export const newsListResponse = z.object({results: z.array(newsStory), nextCursor: z.string().nullable(), requestedAt: z.string(), took: z.number().int().gte(0)}); 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 }; /** * Notícias de empresas * * GET /api/v2/news */ export const getApiApiV2News = async (args: GetApiApiV2NewsArgs, options?: GetApiApiV2NewsOptions) => { const {baseUrl = "https://brapi.dev", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.tickers != null) query.append("tickers", String(args.tickers)) if (args.eventTypes != null) query.append("eventTypes", String(args.eventTypes)) if (args.sentiment != null) query.append("sentiment", String(args.sentiment)) if (args.minImportance != null) query.append("minImportance", String(args.minImportance)) if (args.from != null) query.append("from", String(args.from)) if (args.to != null) query.append("to", String(args.to)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.includeArticle != null) query.append("includeArticle", String(args.includeArticle)) if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/news${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(newsListResponse, await res.json()) };