import {z} from 'zod' export type GetApiWebhooksOptions = {baseUrl?: string | undefined, bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const webhookExecutionLog = z.object({id: z.string(), dateCreated: z.string(), url: z.string().max(2048), signature: z.string().max(128), requestBody: z.string().max(8192), responseCode: z.number().int().nullable().optional(), responseBody: z.string().max(8192).nullable().optional(), webhookId: z.string().nullable().optional(), userId: z.string().max(36).nullable().optional(), retryCount: z.number().int(), userAgent: z.string().max(512).nullable().optional(), orderId: z.string().nullable().optional()}); export const webhook = z.object({id: z.string(), dateCreated: z.string(), url: z.string().min(1).max(3000), events: z.array(z.string()), storeIds: z.array(z.string()), executionLogs: z.array(webhookExecutionLog), userId: z.string().min(1).max(36)}); export const webhookArrayResponse = z.object({success: z.boolean(), message: z.string().nullable().optional(), code: z.string().nullable().optional(), data: z.array(webhook).nullable().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 all webhooks owned by the current user (account-wide). * * GET /webhooks */ export const getApiWebhooks = async (options?: GetApiWebhooksOptions) => { const {baseUrl = "https://api.komerza.com", fetch: fetchFn = fetch, bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (bearer !== undefined) headers.set('authorization', `Bearer ${bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/webhooks${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(webhookArrayResponse, await res.json()) };