import {z} from 'zod' export type CreateContactPropertyInput = {name: string, label: string, type?: ('text' | 'number' | 'boolean' | 'date' | 'select') | undefined, options?: Array | undefined, required?: boolean | undefined}; export type CreateApiContactPropertiesArgs = {body: CreateContactPropertyInput}; export type CreateApiContactPropertiesOptions = {baseUrl?: string | undefined, bearerApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const contactProperty = z.object({id: z.number().int(), name: z.string(), label: z.string(), type: z.enum(["text", "number", "boolean", "date", "select"]), options: z.array(z.string()).nullable().optional(), required: z.boolean(), createdAt: z.string().optional()}); export const createApiContactPropertiesResponse = z.object({property: contactProperty}); 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 custom property * * POST /contact-properties * * Also accepts auth: bearerOAuth */ export const createApiContactProperties = async (args: CreateApiContactPropertiesArgs, options?: CreateApiContactPropertiesOptions) => { const {baseUrl = "https://api.poststack.dev", fetch: fetchFn = fetch, bearerApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerApiKey !== undefined) headers.set('authorization', `Bearer ${bearerApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/contact-properties${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(createApiContactPropertiesResponse, await res.json()) };