import {z} from 'zod' export type GetApiV3RankTrackingKeywordsSummaryArgs = {teamId?: string | undefined, includeInactive?: boolean | undefined, sort?: 'position' | undefined, search?: string | undefined, page?: number | undefined, pageSize?: string | undefined}; export type GetApiV3RankTrackingKeywordsSummaryOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiV3RankTrackingKeywordsSummaryResponse = z.object({page: z.number().int().optional(), pageSize: z.number().int().optional(), total: z.number().int().optional(), totalPages: z.number().int().optional(), items: z.array(z.object({id: z.string().optional(), keywordId: z.string().optional(), keyword: z.string().optional(), countryId: z.string().nullable().optional(), languageId: z.string().nullable().optional(), locationCriteriaId: z.number().nullable().optional(), locationCanonicalName: z.string().nullable().optional(), position: z.number().optional(), active: z.boolean().optional(), status: z.enum(["completed", "processing", "failed", "pending"]).optional(), refreshedAt: z.string().nullable().optional(), createdAt: z.string().optional(), updatedAt: z.string().optional(), isTracked: z.boolean().optional(), trackingId: z.string().optional(), monthlyVolume: z.number().nullable().optional(), difficulty: z.string().nullable().optional(), competitionScore: z.number().nullable().optional(), cpc: z.number().nullable().optional(), intent: z.string().nullable().optional(), positionHistory: z.array(z.object({date: z.string().optional(), position: z.number().optional()})).optional(), positionTrend: z.enum(["improved", "declined", "same", "new"]).nullable().optional(), nextRunAt: z.string().nullable().optional(), serpFeatures: z.record(z.string(), z.unknown()).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 }; /** * Tracked keywords with position history and trend * * GET /v3/rank-tracking/keywords/summary * * Also accepts auth: apiKey */ export const getApiV3RankTrackingKeywordsSummary = async (args: GetApiV3RankTrackingKeywordsSummaryArgs, options?: GetApiV3RankTrackingKeywordsSummaryOptions) => { const {baseUrl = "https://api.snowseo.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.teamId != null) query.append("teamId", String(args.teamId)) if (args.includeInactive != null) query.append("includeInactive", String(args.includeInactive)) if (args.sort != null) query.append("sort", String(args.sort)) if (args.search != null) query.append("search", String(args.search)) if (args.page != null) query.append("page", String(args.page)) if (args.pageSize != null) query.append("pageSize", String(args.pageSize)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/rank-tracking/keywords/summary${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(getApiV3RankTrackingKeywordsSummaryResponse, await res.json()) };