import {z} from 'zod' export type GetApiV1DistributionStatsHitShareArgs = {domain_names: Array, start_date?: (number | null) | undefined, end_date?: (number | null) | undefined, is_publisher?: boolean | undefined}; export type GetApiV1DistributionStatsHitShareOptions = {baseUrl?: string | undefined, APIKey?: string | undefined, fetch?: typeof fetch | undefined}; export const hitShareItem = z.object({domain: z.string(), hit_share: z.number()}); export const hitSharePoolTotals = z.object({surfaces: z.number().int(), citations: z.number().int(), full_text: z.number().int(), grounded: z.number().int()}); export const hitShareResponse = z.object({data: z.array(hitShareItem), total_share: z.number(), pool_totals: hitSharePoolTotals.nullable().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 hit share for a list of domains in a time period * * GET /v1/distribution/stats/hit_share */ export const getApiV1DistributionStatsHitShare = async (args: GetApiV1DistributionStatsHitShareArgs, options?: GetApiV1DistributionStatsHitShareOptions) => { const {baseUrl = "https://api.asknews.app", fetch: fetchFn = fetch, APIKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") for (const item of args.domain_names ?? []) query.append("domain_names", String(item)) if (args.start_date != null) query.append("start_date", String(args.start_date)) if (args.end_date != null) query.append("end_date", String(args.end_date)) if (args.is_publisher != null) query.append("is_publisher", String(args.is_publisher)) if (APIKey !== undefined) headers.set("Authorization", APIKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/distribution/stats/hit_share${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(hitShareResponse, await res.json()) };