import {z} from 'zod' export type CreateApi30SegmentsArgs = {body: {definition: {conditions: Array>, contacts?: ({email?: ({marketing?: (Array<{consent?: ('unknown' | 'confirmed' | 'denied') | undefined, reason?: 'deliverability' | undefined, sendable: boolean}>) | undefined, transactional?: Array<{sendable: boolean}> | undefined}) | undefined, sms?: ({marketing?: (Array<{consent?: ('unknown' | 'confirmed' | 'denied') | undefined, reason?: 'deliverability' | undefined, sendable: boolean}>) | undefined, transactional?: Array<{sendable: boolean}> | undefined}) | undefined, whatsapp?: ({marketing?: (Array<{consent?: ('unknown' | 'confirmed' | 'denied') | undefined, reason?: 'deliverability' | undefined, sendable: boolean}>) | undefined, transactional?: Array<{sendable: boolean}> | undefined}) | undefined}) | undefined, extra: unknown, field?: string | undefined, filters?: Array> | undefined, location?: ({city?: string | undefined, country_code?: string | undefined, lat?: number | undefined, lng?: number | undefined, region?: string | undefined}) | undefined, match: 'all' | 'any', op?: string | undefined, schema_version?: number | undefined, value: unknown, value_op?: ('and' | 'or') | undefined}, list_id: string, name: string}}; export type CreateApi30SegmentsOptions = {baseUrl?: string | undefined, bearerToken?: string | undefined, fetch?: typeof fetch | undefined}; export const createApi30SegmentsResponse = z.object({created_at: z.string().optional(), definition: z.record(z.string(), z.unknown()).optional(), id: z.string().optional(), list_id: z.string().optional(), read_only: z.boolean().optional(), name: 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 }; /** * Add Segment * * POST /3.0/segments * * Also accepts auth: oauth2 */ export const createApi30Segments = async (args: CreateApi30SegmentsArgs, options?: CreateApi30SegmentsOptions) => { const {baseUrl = "https://api.mailchimp.com", fetch: fetchFn = fetch, bearerToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerToken !== undefined) headers.set('authorization', `Bearer ${bearerToken}`) const url = `${baseUrl.replace(/\/+$/, '')}/3.0/segments${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(createApi30SegmentsResponse, await res.json()) };