import {z} from 'zod' export type GetApiSiteExplorerDomainRatingHistoryArgs = {target: string, date_from: string, date_to?: string | undefined, history_grouping?: ('daily' | 'weekly' | 'monthly') | undefined, output?: ('json' | 'csv' | 'xml' | 'php') | undefined}; export type GetApiSiteExplorerDomainRatingHistoryOptions = {baseUrl?: string | undefined, http?: string | undefined, fetch?: typeof fetch | undefined}; export const siteExplorerDomainRatingHistory = z.object({domain_ratings: z.array(z.object({date: z.string().optional(), domain_rating: z.number().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 }; /** * Domain Rating history * * GET /site-explorer/domain-rating-history */ export const getApiSiteExplorerDomainRatingHistory = async (args: GetApiSiteExplorerDomainRatingHistoryArgs, options?: GetApiSiteExplorerDomainRatingHistoryOptions) => { const {baseUrl = "https://api.ahrefs.com/v3", fetch: fetchFn = fetch, http} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.target != null) query.append("target", String(args.target)) if (args.date_from != null) query.append("date_from", String(args.date_from)) if (args.date_to != null) query.append("date_to", String(args.date_to)) if (args.history_grouping != null) query.append("history_grouping", String(args.history_grouping)) if (args.output != null) query.append("output", String(args.output)) if (http !== undefined) headers.set('authorization', `Bearer ${http}`) const url = `${baseUrl.replace(/\/+$/, '')}/site-explorer/domain-rating-history${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(siteExplorerDomainRatingHistory, await res.json()) };