import {z} from 'zod' export type WebhookType = 'CustomerCreated' | 'InvoiceCreated' | 'CustomerDeleted' | 'CustomerUpdated' | 'ProductCreated' | 'ProductUpdated' | 'ProductDeleted' | 'InvoiceUpdated' | 'ContactUpdated' | 'ContactCreated' | 'QuoteUpdated' | 'QuoteCreated' | 'ContactDeleted' | 'QuoteDeleted' | 'InvoiceDeleted'; export type WebhookCreate = {name: string, secretKey?: (string | null) | undefined, types: Array, url: string}; export type CreateApiV1WebhooksArgs = {body: WebhookCreate}; export type CreateApiV1WebhooksOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const webhookType = z.enum(["CustomerCreated", "InvoiceCreated", "CustomerDeleted", "CustomerUpdated", "ProductCreated", "ProductUpdated", "ProductDeleted", "InvoiceUpdated", "ContactUpdated", "ContactCreated", "QuoteUpdated", "QuoteCreated", "ContactDeleted", "QuoteDeleted", "InvoiceDeleted"]); export const webhook = z.object({id: z.number().int().optional(), name: z.string().min(1), secretKey: z.string().nullable().optional(), types: z.array(webhookType), url: z.string().min(1)}); 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 }; /** * Register a new webhook * * POST /v1/webhooks */ export const createApiV1Webhooks = async (args: CreateApiV1WebhooksArgs, options?: CreateApiV1WebhooksOptions) => { const {baseUrl = "https://api.altoviz.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v1/webhooks${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(webhook, await res.json()) };