import {z} from 'zod' export type AdGroupAudienceSizingCreativeTypes = 'REGULAR' | 'VIDEO' | 'SHOPPING' | 'CAROUSEL' | 'MAX_VIDEO' | 'SHOP_THE_PIN' | 'COLLECTION' | 'IDEA'; export type NullalbleMatchType = 'BROAD' | 'PHRASE' | 'EXACT' | 'EXACT_NEGATIVE' | 'PHRASE_NEGATIVE' | 'null' | null; export type AdGroupDeliveryEstimatesKeywordsItems = {match_type: NullalbleMatchType | null, value: string}; export type AttributionWindows = {click_window_days?: number | undefined, engagement_window_days?: number | undefined, view_window_days?: number | undefined}; export type ConversionEvent = 'PAGE_VISIT' | 'SIGNUP' | 'CHECKOUT' | 'CUSTOM' | 'VIEW_CATEGORY' | 'SEARCH' | 'ADD_TO_CART' | 'WATCH_VIDEO' | 'LEAD' | 'APP_INSTALL'; export type ConversionTagV3GoalMetadata = {attribution_windows?: AttributionWindows | undefined, conversion_event?: ConversionEvent | undefined, conversion_tag_id?: string | undefined, cpa_goal_value_in_micro_currency?: string | undefined, is_roas_optimized?: (boolean | null) | undefined, reporting_event?: string | undefined}; export type FrequencyGoalMetadataTimerange = 'THIRTY_DAY' | 'DAY' | 'SEVEN_DAY' | 'TWENTY_MINUTE' | 'TEN_MINUTE' | 'TWENTY_FOUR_HOUR'; export type FrequencyGoalMetadata = {frequency?: number | undefined, timerange?: FrequencyGoalMetadataTimerange | undefined}; export type ScrollupGoalMetadata = {scrollup_goal_value_in_micro_currency?: (string | null) | undefined}; export type OptimizationGoalMetadata = {conversion_tag_v3_goal_metadata?: ConversionTagV3GoalMetadata | undefined, frequency_goal_metadata?: FrequencyGoalMetadata | undefined, scrollup_goal_metadata?: ScrollupGoalMetadata | undefined}; export type OptimizationType = 'CLICKTHROUGH' | 'IMPRESSION' | 'WEB_CONVERSION' | 'ROAS' | 'OUTBOUND_CLICK'; export type PlacementGroupType = 'ALL' | 'SEARCH' | 'BROWSE' | 'OTHER'; export type DeliveryEstimatesProductGroupId = string; export type TargetingSpecAgeBucket = '18-24' | '19+' | '20+' | '21+' | '25-34' | '35-44' | '45-49' | '50-54' | '55-64' | '65+'; export type TargetingSpecAppType = 'android_mobile' | 'android_tablet' | 'ipad' | 'iphone' | 'web' | 'web_mobile'; export type PinterestLibIntegerFormatType = string; export type TargetingSpecGender = 'unknown' | 'male' | 'female'; export type TargetingSpecShoppingRetargeting = {exclusion_window?: number | undefined, lookback_window?: number | undefined, tag_types?: Array | undefined}; export type TargetingStrategy = 'CHOOSE_YOUR_OWN' | 'FIND_NEW_CUSTOMERS' | 'RECONNECT_WITH_USERS'; export type TargetingSpecOptimal = {AGE_BUCKET?: (Array | null) | undefined, APPTYPE?: (Array | null) | undefined, AUDIENCE_EXCLUDE?: (Array | null) | undefined, AUDIENCE_INCLUDE?: (Array | null) | undefined, GENDER?: (Array | null) | undefined, GEO?: (Array | null) | undefined, GEO_EXCLUDE?: Array | undefined, INTEREST?: Array | undefined, LOCALE?: (Array | null) | undefined, LOCATION?: (Array | null) | undefined, LOCATION_EXCLUDE?: Array | undefined, MAXIMUM_AGE?: string | undefined, MINIMUM_AGE?: string | undefined, SHOPPING_RETARGETING?: (Array | null) | undefined, TARGETING_STRATEGY?: (Array | null) | undefined}; export type AdGroupDeliveryEstimates = {auto_targeting_enabled?: boolean | undefined, creative_types?: Array | undefined, keywords?: (Array | null) | undefined, monthly_frequency_cap?: number | undefined, optimization_goal_metadata?: OptimizationGoalMetadata | undefined, optimization_type?: OptimizationType | undefined, placement_group?: PlacementGroupType | undefined, product_group_ids?: Array | undefined, targeting_spec?: TargetingSpecOptimal | undefined}; export type BudgetDurationType = 'FIXED_DAILY' | 'FLEXIBLE_DAILY' | 'LIFETIME'; export type DeliveryEstimateObjectiveType = 'AWARENESS' | 'CONSIDERATION' | 'CATALOG_SALES' | 'WEB_CONVERSION'; export type CampaignDeliveryEstimatesCampaign = {ad_groups: Array, budget_duration_type: BudgetDurationType, daily_spend_cap?: number | undefined, end_date?: string | undefined, lifetime_spend_cap?: number | undefined, objective_type: DeliveryEstimateObjectiveType, start_date: string}; export type CampaignDeliveryEstimatesCampaignRequest = Array; export type CreateApiAdAccountsAdAccountIdCampaignsDeliveryEstimatesArgs = {ad_account_id: string, body: CampaignDeliveryEstimatesCampaignRequest}; export type CreateApiAdAccountsAdAccountIdCampaignsDeliveryEstimatesOptions = {baseUrl?: string | undefined, pinterestOauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const campaignPlanningEstimationType = z.enum(["IMPRESSION", "CLICK", "CONVERSION", "WEEKLY_FREQUENCY", "WEEKLY_REACH", "LIFETIME_FREQUENCY", "LIFETIME_REACH", "CPM", "CPC", "CPA"]); export const campaignPlanningPointEstimate = z.object({budget: z.number().int(), double_y: z.number().nullable(), max_y: z.number().int().nullable(), min_y: z.number().int().nullable(), y: z.number().int().nullable()}); export const campaignPlanningCurveEstimate = z.object({estimation_type: campaignPlanningEstimationType.optional(), points: z.array(campaignPlanningPointEstimate).optional()}); export const campaignDeliveryEstimatesDerivedMetrics = z.object({cpc: z.number().optional(), cpc_lower: z.number().optional(), cpc_upper: z.number().optional(), cpm: z.number().optional(), cpm_lower: z.number().optional(), cpm_upper: z.number().optional(), lifetime_frequency: z.number().optional(), lifetime_frequency_lower: z.number().optional(), lifetime_frequency_upper: z.number().optional(), lifetime_impression: z.number().optional(), lifetime_impression_lower: z.number().optional(), lifetime_impression_upper: z.number().optional(), lifetime_reach: z.number().optional(), lifetime_reach_lower: z.number().optional(), lifetime_reach_upper: z.number().optional(), weekly_click: z.number().optional(), weekly_click_lower: z.number().optional(), weekly_click_upper: z.number().optional(), weekly_frequency: z.number().optional(), weekly_frequency_lower: z.number().optional(), weekly_frequency_upper: z.number().optional(), weekly_impression: z.number().optional(), weekly_impression_lower: z.number().optional(), weekly_impression_upper: z.number().optional(), weekly_reach: z.number().optional(), weekly_reach_lower: z.number().optional(), weekly_reach_upper: z.number().optional()}); export const campaignDeliveryEstimatesResponse = z.object({curves: z.array(campaignPlanningCurveEstimate).optional(), derived_metrics: campaignDeliveryEstimatesDerivedMetrics.optional(), max_potential_spend: z.number().int().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 campaign delivery estimates * * POST /ad_accounts/{ad_account_id}/campaigns/delivery_estimates */ export const createApiAdAccountsAdAccountIdCampaignsDeliveryEstimates = async (args: CreateApiAdAccountsAdAccountIdCampaignsDeliveryEstimatesArgs, options?: CreateApiAdAccountsAdAccountIdCampaignsDeliveryEstimatesOptions) => { const {baseUrl = "https://api.pinterest.com/v5", fetch: fetchFn = fetch, pinterestOauth2} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (pinterestOauth2 !== undefined) headers.set('authorization', `Bearer ${pinterestOauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/ad_accounts/${encodeURIComponent(String(args.ad_account_id))}/campaigns/delivery_estimates${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(campaignDeliveryEstimatesResponse, await res.json()) };