import {z} from 'zod' export type StoreRefreshProductsSequence = Array<{index: number, products: Array<{publisherProductId: string, quantity: number, priority: 'Main' | 'Sub'}>, priceInUsdCents: number, playerAvailability?: number | undefined, hidePlayerAvailability?: boolean | undefined}>; export type StoreRefreshDisplayRule = {frequency: number, cooldownInMinutes: number}; export type Schedule = {permanent: boolean, timeFrames: Array<{startTime: string, endTime: string, notes?: string | undefined}>}; export type ProductSale = {sale?: number | undefined, type?: 'percentage' | undefined}; export type PriceDiscount = {discount?: number | undefined, type?: 'percentage' | undefined}; export type Badges = Array<{publisherBadgeId: string}>; export type CreateStoreRefreshPopupDto = {publisherOfferId: string, name: string, displayName?: string | undefined, description?: string | undefined, type: 'PopUp', subType: 'StoreRefresh', active: boolean, priority: number, offerUiId?: string | undefined, offerExternalUiId?: string | undefined, segments: Array, productsSequence: StoreRefreshProductsSequence, displayRule: StoreRefreshDisplayRule, schedule?: Schedule | undefined, productSale?: ProductSale | undefined, priceDiscount?: PriceDiscount | undefined, badges?: Badges | undefined, publisherSectionId?: string | undefined, publisherTabId?: string | undefined}; export type CreateApiV2OfferArgs = {'x-publisher-token': string, body: CreateStoreRefreshPopupDto}; export type CreateApiV2OfferOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const storeRefreshProductsSequence = z.array(z.object({index: z.number().int(), products: z.array(z.object({publisherProductId: z.string(), quantity: z.number().int(), priority: z.enum(["Main", "Sub"])})), priceInUsdCents: z.number().int(), playerAvailability: z.number().optional(), hidePlayerAvailability: z.boolean().optional()})); export const storeRefreshDisplayRule = z.object({frequency: z.number().int(), cooldownInMinutes: z.number().int()}); export const schedule = z.object({permanent: z.boolean(), timeFrames: z.array(z.object({startTime: z.string(), endTime: z.string(), notes: z.string().optional()}))}); export const productSale = z.object({sale: z.number().int().optional(), type: z.literal("percentage").optional()}); export const priceDiscount = z.object({discount: z.number().int().optional(), type: z.literal("percentage").optional()}); export const badges = z.array(z.object({publisherBadgeId: z.string()})); export const storeRefreshPopupDtoResponse = z.object({publisherId: z.string().optional(), offerId: z.string().optional(), publisherOfferId: z.string().optional(), name: z.string().optional(), displayName: z.string().optional(), description: z.string().optional(), type: z.string().optional(), subType: z.string().optional(), active: z.boolean().optional(), priority: z.number().int().optional(), offerUi: z.object({offerUiId: z.string().optional(), offerExternalUiId: z.string().optional(), active: z.boolean().optional(), offerUiType: z.string().optional(), name: z.string().optional(), description: z.string().optional()}).optional(), segments: z.array(z.string()).optional(), productsSequence: storeRefreshProductsSequence.optional(), displayRule: storeRefreshDisplayRule.optional(), schedule: schedule.optional(), productSale: productSale.optional(), priceDiscount: priceDiscount.optional(), badges: badges.optional(), createdAt: z.string().optional(), updatedAt: z.string().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 }; /** * Create a new Store Refresh Popup * * POST /v2/offer */ export const createApiV2Offer = async (args: CreateApiV2OfferArgs, options: CreateApiV2OfferOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['x-publisher-token'] != null) headers.set("x-publisher-token", String(args['x-publisher-token'])) const url = `${baseUrl.replace(/\/+$/, '')}/v2/offer${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(storeRefreshPopupDtoResponse, await res.json()) };