import {z} from 'zod' export type AudienceInsightType = 'YOUR_TOTAL_AUDIENCE' | 'YOUR_ENGAGED_AUDIENCE' | 'PINTEREST_TOTAL_AUDIENCE'; export type GetApiAdAccountsAdAccountIdAudienceInsightsArgs = {ad_account_id: string, audience_insight_type: AudienceInsightType}; export type GetApiAdAccountsAdAccountIdAudienceInsightsOptions = {baseUrl?: string | undefined, pinterestOauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const audienceSubcategory = z.object({id: z.string().optional(), index: z.number().optional(), key: z.string().optional(), name: z.string().optional(), ratio: z.number().optional()}); export const audienceCategory = z.object({id: z.string().optional(), index: z.number().optional(), key: z.string().optional(), name: z.string().optional(), ratio: z.number().optional(), subcategories: z.array(audienceSubcategory).optional()}); export const audienceDemographicValue = z.object({key: z.string().optional(), name: z.string().optional(), ratio: z.number().optional()}); export const audienceDemographics = z.object({ages: z.array(audienceDemographicValue).optional(), countries: z.array(audienceDemographicValue).optional(), devices: z.array(audienceDemographicValue).optional(), genders: z.array(audienceDemographicValue).optional(), metros: z.array(audienceDemographicValue).optional()}); export const audienceInsightType = z.enum(["YOUR_TOTAL_AUDIENCE", "YOUR_ENGAGED_AUDIENCE", "PINTEREST_TOTAL_AUDIENCE"]); export const audienceInsights = z.object({categories: z.array(audienceCategory).optional(), date: z.string().nullable().optional(), demographics: audienceDemographics.optional(), size: z.number().int().optional(), size_is_upper_bound: z.boolean().optional(), type: audienceInsightType.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 audience insights * * GET /ad_accounts/{ad_account_id}/audience_insights * * Also accepts auth: client_credentials */ export const getApiAdAccountsAdAccountIdAudienceInsights = async (args: GetApiAdAccountsAdAccountIdAudienceInsightsArgs, options?: GetApiAdAccountsAdAccountIdAudienceInsightsOptions) => { const {baseUrl = "https://api.pinterest.com/v5", fetch: fetchFn = fetch, pinterestOauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.audience_insight_type != null) query.append("audience_insight_type", String(args.audience_insight_type)) if (pinterestOauth2 !== undefined) headers.set('authorization', `Bearer ${pinterestOauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/ad_accounts/${encodeURIComponent(String(args.ad_account_id))}/audience_insights${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(audienceInsights, await res.json()) };