import {z} from 'zod' export type WebhookEndpointCreateRequest = {url: string, event_types?: (Array<'account_created' | 'account_disabled' | 'account_disabled_for_copied_connection' | 'account_enabled' | 'account_enabled_for_copied_connection' | 'account_item_changed' | 'account_name_changed' | 'additional_params_changed' | 'agency_created' | 'agency_invite_created' | 'agency_is_test_changed' | 'agency_migrated_to_workspace_separated_schemas' | 'agency_offboarded' | 'agency_toggle' | 'connection_accounts_update_error' | 'connection_accounts_update_fail' | 'connection_accounts_update_started' | 'connection_accounts_update_success' | 'connection_created' | 'connection_deleted' | 'connection_invalidated' | 'connection_privacy_updated' | 'connection_reconnected' | 'create_load_changed' | 'custom_filters_changed' | 'data_table_created' | 'data_table_marked_as_deleting' | 'destination_connection_changed' | 'destination_connection_check_run' | 'destination_connection_created' | 'destination_connection_deleted' | 'enabled_for_embedded_extraction_changed' | 'error_changed' | 'error_text_changed' | 'execution_policy_changed' | 'extraction_account_changed' | 'extraction_added' | 'extraction_completed' | 'extraction_created' | 'extraction_marked_as_deleting' | 'extraction_paused' | 'extraction_schedules_changed' | 'extraction_template_changed' | 'extraction_unpaused' | 'fields_changed' | 'gbq_by_improvado_created' | 'gbq_by_improvado_for_sandbox_created' | 'historical_download_started' | 'invite_accepted' | 'invite_deleted' | 'invite_sent' | 'load_completed' | 'load_created' | 'load_started' | 'order_paused' | 'order_started' | 'recipe_activated' | 'recipe_backward_compatibility_validated' | 'recipe_backward_compatibility_validation_failed' | 'recipe_backward_compatibility_validation_skipped' | 'recipe_columns_validated' | 'recipe_deactivated' | 'recipe_promoted' | 'recipe_validate_complexity_failed' | 'recipe_validate_complexity_success' | 'recipe_view_name_updated' | 'regular_download_started' | 'run_policy_changed' | 'schedules_changed' | 'secret_key_changed' | 'status_changed' | 'sync_historical_data_changed' | 'table_auto_add_new_fields_changed' | 'table_auto_extract_new_accounts_changed' | 'table_extract_template_changed' | 'table_freshness_changed' | 'table_meta_set' | 'table_sql_available_at_changed' | 'table_title_changed' | 'title_changed' | 'transformation_completed' | 'transformation_created' | 'transformation_started' | 'user_added_to_workspace' | 'user_deactivated' | 'user_invited_to_workspaces' | 'user_removed_from_workspace' | 'user_workspace_role_changed' | 'workspace_connector_changed' | 'workspace_created'>) | undefined}; export type CreateApiApiV3WebhookEndpointsArgs = {body: WebhookEndpointCreateRequest}; export type CreateApiApiV3WebhookEndpointsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const webhookSubscription = z.object({id: z.number().int().optional(), event_type_name: z.string().optional(), is_active: z.boolean().optional(), created_at: z.string().optional()}); export const webhookEndpointDetail = z.object({id: z.number().int().optional(), url: z.string().optional(), secret: z.string().optional(), status: z.enum(["unverified", "active"]).optional(), consecutive_failures: z.number().int().optional(), subscriptions: z.array(webhookSubscription).optional(), created_at: z.string().optional(), updated_at: 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 webhook endpoint * * POST /api/v3/webhook_endpoints/ * * Also accepts auth: cookieAuth */ export const createApiApiV3WebhookEndpoints = async (args: CreateApiApiV3WebhookEndpointsArgs, options?: CreateApiApiV3WebhookEndpointsOptions) => { const {baseUrl = "https://embedded.improvado.io", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v3/webhook_endpoints/${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(webhookEndpointDetail, await res.json()) };