The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): wire Platform Webhooks UI to real backend API (#51352)
Monica Khoury2d5768d3c114
diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.constants.ts b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.constants.tsnew file mode 100644index 00000000000..793b8101b56--- /dev/null+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.constants.ts@@ -0,0 +1,26 @@+import type { WebhookEventType } from '@/data/platform-webhooks/platform-webhooks-fetchers'++// The full list of event types the real API accepts, identical for organization-scoped+// and project-scoped endpoints.+export const PLATFORM_WEBHOOK_EVENT_TYPES = [+ 'v1.project.paused',+ 'v1.project.created',+ 'v1.project.restored',+ 'v1.project.transferred',+ 'v1.project.removed',+ 'v1.project.restarted',+ 'v1.project.status.changed',+ 'v1.project.backup.started',+ 'v1.project.branch.created',+ 'v1.project.branch.updated',+ 'v1.project.branch.removed',+ 'v1.organization.member.invitation.created',+ 'v1.organization.member.invitation.canceled',+ 'v1.organization.member.added',+ 'v1.organization.member.removed',+ 'v1.organization.member.role.assigned',+ 'v1.organization.member.role.removed',+ 'v1.organization.member.role.updated',+ 'v1.organization.billing.plan.upgraded',+ 'v1.organization.billing.plan.downgraded',+] as const satisfies readonly WebhookEventType[]diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.mock.ts b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.mock.tsdeleted file mode 100644index a5e5efa4192..00000000000--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.mock.ts+++ /dev/null@@ -1,224 +0,0 @@-import type {- PlatformWebhooksMockSeed,- WebhookDelivery,- WebhookScope,-} from './PlatformWebhooks.types'--const createDeliveries = (- endpointId: string,- prefix: string,- deliveries: Array<Pick<WebhookDelivery, 'eventType' | 'status' | 'responseCode' | 'attemptAt'>>-): WebhookDelivery[] =>- deliveries.map((delivery, index) => ({- id: `${prefix}-${index + 1}`,- endpointId,- ...delivery,- }))--const organizationPrimaryDeliveries = createDeliveries(- '7f2c9d4a-6e31-4d9d-9a1f-2c4b5e6f7081',- 'org-delivery',- [- {- eventType: 'project.created',- status: 'success',- responseCode: 200,- attemptAt: '2026-02-27T08:04:00.000Z',- },- {- eventType: 'project.updated',- status: 'failure',- responseCode: 500,- attemptAt: '2026-02-27T07:56:00.000Z',- },- {- eventType: 'project.deleted',- status: 'pending',- attemptAt: '2026-02-27T07:45:00.000Z',- },- {- eventType: 'organization.member_invited',- status: 'success',- responseCode: 202,- attemptAt: '2026-02-27T07:37:00.000Z',- },- {- eventType: 'project.resumed',- status: 'success',- responseCode: 204,- attemptAt: '2026-02-27T07:18:00.000Z',- },- {- eventType: 'organization.member_removed',- status: 'failure',- responseCode: 400,- attemptAt: '2026-02-27T06:59:00.000Z',- },- {- eventType: 'organization.updated',- status: 'skipped',- attemptAt: '2026-02-27T06:40:00.000Z',- },- {- eventType: 'project.paused',- status: 'success',- responseCode: 200,- attemptAt: '2026-02-27T06:21:00.000Z',- },- {- eventType: 'project.created',- status: 'failure',- responseCode: 503,- attemptAt: '2026-02-27T06:03:00.000Z',- },- {- eventType: 'project.updated',- status: 'success',- responseCode: 200,- attemptAt: '2026-02-27T05:44:00.000Z',- },- {- eventType: 'project.deleted',- status: 'skipped',- attemptAt: '2026-02-27T05:25:00.000Z',- },- {- eventType: 'organization.member_invited',- status: 'success',- responseCode: 201,- attemptAt: '2026-02-27T05:07:00.000Z',- },- ]-)--const organizationSecondaryDeliveries = createDeliveries(- '1a4e8c73-5b29-44af-8c62-9f1d2b3c4d5e',- 'org-secondary-delivery',- [- {- eventType: 'organization.updated',- status: 'skipped',- attemptAt: '2026-02-26T14:12:00.000Z',- },- ]-)--const projectDeliveries = createDeliveries(- '3c9b7e21-8d54-4f63-b2a1-6e7d8c9f0a12',- 'project-delivery',- [- {- eventType: 'project.updated',- status: 'success',- responseCode: 200,- attemptAt: '2026-02-27T09:01:00.000Z',- },- {- eventType: 'project.resource_exhausted',- status: 'failure',- responseCode: 429,- attemptAt: '2026-02-27T08:47:00.000Z',- },- {- eventType: 'project.paused',- status: 'success',- responseCode: 202,- attemptAt: '2026-02-26T21:10:00.000Z',- },- {- eventType: 'project.branch_created',- status: 'success',- responseCode: 200,- attemptAt: '2026-02-26T19:45:00.000Z',- },- {- eventType: 'project.resumed',- status: 'pending',- attemptAt: '2026-02-26T18:30:00.000Z',- },- {- eventType: 'project.branch_deleted',- status: 'success',- responseCode: 204,- attemptAt: '2026-02-26T17:04:00.000Z',- },- {- eventType: 'project.updated',- status: 'failure',- responseCode: 500,- attemptAt: '2026-02-26T15:59:00.000Z',- },- {- eventType: 'project.resource_exhausted',- status: 'skipped',- attemptAt: '2026-02-26T14:12:00.000Z',- },- ]-)--export const PLATFORM_WEBHOOKS_MOCK_DATA: Record<WebhookScope, PlatformWebhooksMockSeed> = {- organization: {- eventTypes: [- 'organization.member_invited',- 'organization.member_removed',- 'organization.updated',- 'project.created',- 'project.updated',- 'project.deleted',- 'project.paused',- 'project.resumed',- ],- endpoints: [- {- id: '7f2c9d4a-6e31-4d9d-9a1f-2c4b5e6f7081',- name: 'Lovable production',- url: 'https://api.lovable.dev/webhooks/supabase',- description: 'Primary organization webhook endpoint',- enabled: true,- eventTypes: ['project.created', 'project.updated', 'project.deleted'],- customHeaders: [- { id: 'org-header-1', key: 'X-Lovable-Version', value: 'v2' },- { id: 'org-header-2', key: 'X-Environment', value: 'production' },- ],- createdBy: '[email protected]',- createdAt: '2026-02-15T21:30:00.000Z',- },- {- id: '1a4e8c73-5b29-44af-8c62-9f1d2b3c4d5e',- name: 'Slack notifications',- url: 'https://hooks.slack.com/services/abc1234/def5678/ghi9012',- description: 'Operational alerts for organization-level events',- enabled: false,- eventTypes: ['organization.updated'],- customHeaders: [],- createdBy: '[email protected]',- createdAt: '2026-02-12T10:14:00.000Z',- },- ],- deliveries: [...organizationPrimaryDeliveries, ...organizationSecondaryDeliveries],- },- project: {- eventTypes: [- 'project.updated',- 'project.paused',- 'project.resumed',- 'project.branch_created',- 'project.branch_deleted',- 'project.resource_exhausted',- ],- endpoints: [- {- id: '3c9b7e21-8d54-4f63-b2a1-6e7d8c9f0a12',- name: 'Project analytics',- url: 'https://analytics.example.com/hooks/supabase-project',- description: 'Project-level status updates for analytics pipeline',- enabled: true,- eventTypes: ['project.updated', 'project.resource_exhausted'],- customHeaders: [{ id: 'project-header-1', key: 'X-Project-Type', value: 'platform' }],- createdBy: '[email protected]',- createdAt: '2026-02-18T11:23:00.000Z',- },- ],- deliveries: projectDeliveries,- },-}diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.store.test.ts b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.store.test.tsdeleted file mode 100644index 7b5d2630ed6..00000000000--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.store.test.ts+++ /dev/null@@ -1,161 +0,0 @@-import { describe, expect, it } from 'vitest'--import {- createInitialPlatformWebhooksState,- createWebhookEndpoint,- filterWebhookDeliveries,- filterWebhookEndpoints,- retryWebhookDelivery,- updateWebhookEndpoint,-} from './PlatformWebhooks.store'-import type { PlatformWebhooksState, WebhookEndpoint } from './PlatformWebhooks.types'--const EMPTY_STATE: PlatformWebhooksState = {- endpoints: [],- deliveries: [],-}--const createEndpoint = (overrides?: Partial<WebhookEndpoint>): WebhookEndpoint => ({- id: '3c9b7e21-8d54-4f63-b2a1-6e7d8c9f0a12',- name: 'Billing events',- url: 'https://hooks.example.com/billing',- description: 'Invoices and receipts',- enabled: true,- eventTypes: ['project.updated'],- customHeaders: [],- createdBy: '[email protected]',- createdAt: '2026-03-16T00:00:00.000Z',- ...overrides,-})--describe('PlatformWebhooks.store', () => {- it('stores an explicit non-empty endpoint name on create', () => {- const result = createWebhookEndpoint(- EMPTY_STATE,- {- name: ' Project analytics ',- url: 'https://hooks.example.com/analytics',- description: '',- enabled: true,- eventTypes: ['project.updated'],- customHeaders: [],- },- {- endpointId: '9e4b1d62-7c35-4f18-a9d1-2b6e7f8c9012',- signingSecret: 'whsec_example',- }- )-- expect(result.endpoint.name).toBe('Project analytics')- })-- it('allows an empty endpoint name on create', () => {- const result = createWebhookEndpoint(- EMPTY_STATE,- {- name: ' ',- url: 'https://hooks.example.com/fallback',- description: '',- enabled: true,- eventTypes: ['project.updated'],- customHeaders: [],- },- {- endpointId: '9e4b1d62-7c35-4f18-a9d1-2b6e7f8c9012',- signingSecret: 'whsec_example',- }- )-- expect(result.endpoint.name).toBe('')- })-- it('allows clearing an existing endpoint name on update', () => {- const state: PlatformWebhooksState = {- endpoints: [createEndpoint()],- deliveries: [],- }-- const result = updateWebhookEndpoint(state, '3c9b7e21-8d54-4f63-b2a1-6e7d8c9f0a12', {- name: ' ',- url: 'https://hooks.example.com/billing',- description: 'Invoices and receipts',- enabled: true,- eventTypes: ['project.updated'],- customHeaders: [],- })-- expect(result.endpoints[0].name).toBe('')- })-- it('filters endpoints by name, url, and description', () => {- const endpoints = [- createEndpoint(),- createEndpoint({- id: '1a4e8c73-5b29-44af-8c62-9f1d2b3c4d5e',- name: '',- url: 'https://hooks.example.com/slack',- description: 'Operational alerts',- }),- ]-- expect(filterWebhookEndpoints(endpoints, 'billing')).toEqual([endpoints[0]])- expect(filterWebhookEndpoints(endpoints, 'slack')).toEqual([endpoints[1]])- expect(filterWebhookEndpoints(endpoints, 'alerts')).toEqual([endpoints[1]])- })-- it('retries an individual delivery by resetting it to pending with a new timestamp', () => {- const nextState = retryWebhookDelivery(- createInitialPlatformWebhooksState('project'),- 'project-delivery-2',- { now: '2026-03-17T02:15:00.000Z' }- )-- expect(nextState.deliveries.find((delivery) => delivery.id === 'project-delivery-2')).toEqual({- id: 'project-delivery-2',- endpointId: '3c9b7e21-8d54-4f63-b2a1-6e7d8c9f0a12',- eventType: 'project.resource_exhausted',- status: 'pending',- responseCode: undefined,- attemptAt: '2026-03-17T02:15:00.000Z',- })- })-- it('returns endpoint deliveries sorted by latest attempt first after a retry', () => {- const nextState = retryWebhookDelivery(- createInitialPlatformWebhooksState('project'),- 'project-delivery-2',- { now: '2026-03-17T02:15:00.000Z' }- )- const endpointDeliveries = filterWebhookDeliveries(- nextState.deliveries,- '3c9b7e21-8d54-4f63-b2a1-6e7d8c9f0a12',- ''- )-- expect(endpointDeliveries).toHaveLength(8)- expect(endpointDeliveries.map((delivery) => delivery.id).slice(0, 3)).toEqual([- 'project-delivery-2',- 'project-delivery-1',- 'project-delivery-3',- ])- expect(- endpointDeliveries.every((delivery, index) => {- if (index === 0) return true-- return (- new Date(endpointDeliveries[index - 1].attemptAt).getTime() >=- new Date(delivery.attemptAt).getTime()- )- })- ).toBe(true)- })-- it('does not retry successful deliveries', () => {- const initialState = createInitialPlatformWebhooksState('project')- const nextState = retryWebhookDelivery(initialState, 'project-delivery-1', {- now: '2026-03-17T02:15:00.000Z',- })-- expect(nextState).toBe(initialState)- })-})diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.store.ts b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.store.tsdeleted file mode 100644index 95147dd59da..00000000000--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.store.ts+++ /dev/null@@ -1,313 +0,0 @@-import { useEffect, useState } from 'react'--import { PLATFORM_WEBHOOKS_MOCK_DATA } from './PlatformWebhooks.mock'-import type {- PlatformWebhooksState,- UpsertWebhookEndpointInput,- WebhookDelivery,- WebhookEndpoint,- WebhookScope,-} from './PlatformWebhooks.types'-import { getWebhookEndpointDisplayName } from './PlatformWebhooks.utils'--interface CreateEndpointOptions {- now?: string- endpointId?: string- createdBy?: string- signingSecret?: string-}--interface UpdateEndpointOptions {- headerIdFactory?: () => string-}--interface RetryDeliveryOptions {- now?: string-}--const secureRandomHex = (length: number) => {- if (length <= 0) return ''-- const cryptoApi = globalThis.crypto- if (!cryptoApi?.getRandomValues) {- throw new Error('Web Crypto API is not available')- }-- const byteCount = Math.ceil(length / 2)- const bytes = new Uint8Array(byteCount)- cryptoApi.getRandomValues(bytes)-- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0'))- .join('')- .slice(0, length)-}--const randomId = (prefix: string) => `${prefix}-${secureRandomHex(8)}`-const randomUuid = () => {- const cryptoApi = globalThis.crypto- if (cryptoApi?.randomUUID) return cryptoApi.randomUUID()-- return [- secureRandomHex(8),- secureRandomHex(4),- `4${secureRandomHex(3)}`,- `${((parseInt(secureRandomHex(2), 16) & 0x3f) | 0x80).toString(16)}${secureRandomHex(2)}`,- secureRandomHex(12),- ].join('-')-}--const generateSigningSecret = () => `whsec_${secureRandomHex(16)}`--const deepClone = <T>(value: T): T => JSON.parse(JSON.stringify(value))--const toHeaders = (- headers: UpsertWebhookEndpointInput['customHeaders'],- options?: UpdateEndpointOptions-) => {- const headerIdFactory = options?.headerIdFactory ?? (() => randomId('header'))- return headers- .map((header) => ({- id: headerIdFactory(),- key: header.key.trim(),- value: header.value.trim(),- }))- .filter((header) => header.key.length > 0 && header.value.length > 0)-}--const normalizeSearch = (value: string) => value.trim().toLowerCase()--export const createInitialPlatformWebhooksState = (scope: WebhookScope): PlatformWebhooksState => {- const seed = PLATFORM_WEBHOOKS_MOCK_DATA[scope]- return {- endpoints: deepClone(seed.endpoints),- deliveries: deepClone(seed.deliveries),- }-}--const persistedMockStateByScope: Partial<Record<WebhookScope, PlatformWebhooksState>> = {}--const getPersistedMockState = (scope: WebhookScope) => {- const persistedState = persistedMockStateByScope[scope]- if (persistedState) return persistedState-- const initialState = createInitialPlatformWebhooksState(scope)- persistedMockStateByScope[scope] = initialState- return initialState-}--// Test-only helper to avoid cross-test state leakage in hook tests.-export const resetPlatformWebhooksMockStateForTests = (scope?: WebhookScope) => {- if (scope) {- delete persistedMockStateByScope[scope]- return- }-- for (const key of Object.keys(persistedMockStateByScope) as WebhookScope[]) {- delete persistedMockStateByScope[key]- }-}--export const createWebhookEndpoint = (- state: PlatformWebhooksState,- input: UpsertWebhookEndpointInput,- options?: CreateEndpointOptions-): { state: PlatformWebhooksState; endpoint: WebhookEndpoint; signingSecret: string } => {- const endpointId = options?.endpointId ?? randomUuid()- const signingSecret = options?.signingSecret ?? generateSigningSecret()- const endpoint: WebhookEndpoint = {- id: endpointId,- name: input.name.trim(),- url: input.url.trim(),- description: input.description.trim(),- enabled: input.enabled,- eventTypes: input.eventTypes.length > 0 ? input.eventTypes : ['*'],- customHeaders: toHeaders(input.customHeaders),- createdBy: options?.createdBy ?? '[email protected]',- createdAt: options?.now ?? new Date().toISOString(),- }-- return {- endpoint,- signingSecret,- state: {- ...state,- endpoints: [endpoint, ...state.endpoints],- },- }-}--export const updateWebhookEndpoint = (- state: PlatformWebhooksState,- endpointId: string,- input: UpsertWebhookEndpointInput,- options?: UpdateEndpointOptions-) => {- return {- ...state,- endpoints: state.endpoints.map((endpoint) =>- endpoint.id === endpointId- ? {- ...endpoint,- name: input.name.trim(),- url: input.url.trim(),- description: input.description.trim(),- enabled: input.enabled,- eventTypes: input.eventTypes.length > 0 ? input.eventTypes : ['*'],- customHeaders: toHeaders(input.customHeaders, options),- }- : endpoint- ),- }-}--export const deleteWebhookEndpoint = (state: PlatformWebhooksState, endpointId: string) => {- return {- endpoints: state.endpoints.filter((endpoint) => endpoint.id !== endpointId),- deliveries: state.deliveries.filter((delivery) => delivery.endpointId !== endpointId),- }-}--export const toggleWebhookEndpoint = (- state: PlatformWebhooksState,- endpointId: string,- enabled?: boolean-) => {- return {- ...state,- endpoints: state.endpoints.map((endpoint) =>- endpoint.id === endpointId- ? { ...endpoint, enabled: enabled === undefined ? !endpoint.enabled : enabled }- : endpoint- ),- }-}--export const regenerateWebhookEndpointSecret = (- state: PlatformWebhooksState,- endpointId: string,- secret?: string-) => {- const endpointExists = state.endpoints.some((endpoint) => endpoint.id === endpointId)- if (!endpointExists) return { state, signingSecret: null }-- return {- state: { ...state },- signingSecret: secret ?? generateSigningSecret(),- }-}--export const retryWebhookDelivery = (- state: PlatformWebhooksState,- deliveryId: string,- options?: RetryDeliveryOptions-) => {- const delivery = state.deliveries.find((item) => item.id === deliveryId)- if (!delivery || delivery.status === 'success') return state-- const now = options?.now ?? new Date().toISOString()-- return {- ...state,- deliveries: state.deliveries.map<WebhookDelivery>((delivery) => {- if (delivery.id !== deliveryId) return delivery-- return {- ...delivery,- status: 'pending',- responseCode: undefined,- attemptAt: now,- }- }),- }-}--export const filterWebhookEndpoints = (endpoints: WebhookEndpoint[], search: string) => {- const normalizedSearch = normalizeSearch(search)- if (normalizedSearch.length === 0) return endpoints-- return endpoints.filter((endpoint) => {- const haystack =- `${getWebhookEndpointDisplayName(endpoint)} ${endpoint.url} ${endpoint.description}`.toLowerCase()- return haystack.includes(normalizedSearch)- })-}--export const filterWebhookDeliveries = (- deliveries: WebhookDelivery[],- endpointId: string,- search: string-) => {- const normalizedSearch = normalizeSearch(search)-- return deliveries- .filter((delivery) => delivery.endpointId === endpointId)- .filter((delivery) => {- if (normalizedSearch.length === 0) return true- const haystack =- `${delivery.eventType} ${delivery.status} ${delivery.responseCode ?? ''}`.toLowerCase()- return haystack.includes(normalizedSearch)- })- .sort((a, b) => new Date(b.attemptAt).getTime() - new Date(a.attemptAt).getTime())-}--export const usePlatformWebhooksMockStore = (scope: WebhookScope) => {- const [state, setState] = useState<PlatformWebhooksState>(() =>- deepClone(getPersistedMockState(scope))- )-- useEffect(() => {- setState(deepClone(getPersistedMockState(scope)))- }, [scope])-- const applyStateUpdate = (- updater: (previous: PlatformWebhooksState) => PlatformWebhooksState- ) => {- setState((previous) => {- const next = updater(previous)- persistedMockStateByScope[scope] = next- return next- })- }-- return {- ...state,- createEndpoint: (input: UpsertWebhookEndpointInput) => {- const endpointId = randomUuid()- const now = new Date().toISOString()- const signingSecret = generateSigningSecret()- const createdBy = '[email protected]'- let createdSecret = signingSecret- applyStateUpdate((prev) => {- const next = createWebhookEndpoint(prev, input, {- endpointId,- now,- signingSecret,- createdBy,- })- createdSecret = next.signingSecret- return next.state- })- return { endpointId, signingSecret: createdSecret }- },- updateEndpoint: (endpointId: string, input: UpsertWebhookEndpointInput) => {- applyStateUpdate((prev) => updateWebhookEndpoint(prev, endpointId, input))- },- deleteEndpoint: (endpointId: string) => {- applyStateUpdate((prev) => deleteWebhookEndpoint(prev, endpointId))- },- toggleEndpoint: (endpointId: string, enabled?: boolean) => {- applyStateUpdate((prev) => toggleWebhookEndpoint(prev, endpointId, enabled))- },- regenerateSecret: (endpointId: string) => {- const currentState = persistedMockStateByScope[scope] ?? state- const next = regenerateWebhookEndpointSecret(currentState, endpointId)- if (!next.signingSecret) return null-- applyStateUpdate(() => next.state)- return next.signingSecret- },- retryDelivery: (deliveryId: string) => {- applyStateUpdate((prev) => retryWebhookDelivery(prev, deliveryId))- },- }-}diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.types.ts b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.types.tsindex b98c56268db..197eadf73fb 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.types.ts+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.types.ts@@ -2,6 +2,8 @@ export type WebhookScope = 'organization' | 'project'export type WebhookDeliveryStatus = 'pending' | 'success' | 'failure' | 'skipped'+// UI-only row shape for the headers form (add/edit by key+value). The real API+// stores these as a plain `{ [key]: value }` object — converted in the data layer.export interface WebhookHeader {id: stringkey: string@@ -10,6 +12,7 @@ export interface WebhookHeader {export interface WebhookEndpoint {id: string+ // No `name` field in the real API — client-only until backend adds one.name: stringurl: stringdescription: string@@ -23,9 +26,15 @@ export interface WebhookEndpoint {export interface WebhookDelivery {id: stringendpointId: string- eventType: string+ eventId: string+ // Only present when fetched via the single-delivery endpoint (drill-down view) —+ // the deliveries *list* endpoint doesn't return either, so list rows leave these unset.+ eventType?: string+ eventPayload?: Record<string, unknown>status: WebhookDeliveryStatus- responseCode?: number+ responseCode: number+ responseBody: string | Record<string, string> | null+ responseHeaders: Record<string, string> | nullattemptAt: string}@@ -47,4 +56,5 @@ export interface UpsertWebhookEndpointInput {enabled: booleaneventTypes: string[]customHeaders: Array<Pick<WebhookHeader, 'key' | 'value'>>+ signingSecret: string}diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.utils.test.ts b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.utils.test.tsindex bec11771d10..32dd5a09644 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.utils.test.ts+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.utils.test.ts@@ -1,10 +1,38 @@import { afterEach, describe, expect, it, vi } from 'vitest'+import type { WebhookDelivery, WebhookEndpoint } from './PlatformWebhooks.types'import {+ filterWebhookDeliveries,+ filterWebhookEndpoints,generateWebhookEndpointName,getWebhookEndpointDisplayName,} from './PlatformWebhooks.utils'+const createEndpoint = (overrides: Partial<WebhookEndpoint> = {}): WebhookEndpoint => ({+ id: 'endpoint-1',+ name: '',+ url: 'https://hooks.example.com/billing',+ description: '',+ enabled: true,+ eventTypes: ['v1.project.updated'],+ customHeaders: [],+ createdBy: '[email protected]',+ createdAt: '2026-03-16T00:00:00.000Z',+ ...overrides,+})++const createDelivery = (overrides: Partial<WebhookDelivery> = {}): WebhookDelivery => ({+ id: 'delivery-1',+ endpointId: 'endpoint-1',+ eventId: 'event-1',+ status: 'success',+ responseCode: 200,+ responseBody: null,+ responseHeaders: null,+ attemptAt: '2026-03-16T00:00:00.000Z',+ ...overrides,+})+describe('PlatformWebhooks.utils', () => {afterEach(() => {vi.restoreAllMocks()@@ -33,4 +61,43 @@ describe('PlatformWebhooks.utils', () => {expect(generateWebhookEndpointName()).toBe('swift-courier')})++ it('filters endpoints by name, url, and description', () => {+ const endpoints = [+ createEndpoint({ id: '1', name: 'Billing events', url: 'https://hooks.example.com/billing' }),+ createEndpoint({+ id: '2',+ name: 'Slack alerts',+ url: 'https://hooks.slack.com/x',+ description: 'operational alerts',+ }),+ ]++ expect(filterWebhookEndpoints(endpoints, 'billing')).toEqual([endpoints[0]])+ expect(filterWebhookEndpoints(endpoints, 'slack')).toEqual([endpoints[1]])+ expect(filterWebhookEndpoints(endpoints, 'alerts')).toEqual([endpoints[1]])+ })++ it('filters deliveries by event type, status, and response code, sorted newest first', () => {+ const deliveries = [+ createDelivery({+ id: 'a',+ eventType: 'v1.project.updated',+ status: 'success',+ responseCode: 200,+ attemptAt: '2026-03-16T00:00:00.000Z',+ }),+ createDelivery({+ id: 'b',+ eventType: 'v1.project.paused',+ status: 'failure',+ responseCode: 500,+ attemptAt: '2026-03-17T00:00:00.000Z',+ }),+ ]++ expect(filterWebhookDeliveries(deliveries, '')).toEqual([deliveries[1], deliveries[0]])+ expect(filterWebhookDeliveries(deliveries, 'paused')).toEqual([deliveries[1]])+ expect(filterWebhookDeliveries(deliveries, '500')).toEqual([deliveries[1]])+ })})diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.utils.ts b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.utils.tsindex 6cc989ef063..fbc974cfd42 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.utils.ts+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooks.utils.ts@@ -1,4 +1,4 @@-import type { WebhookEndpoint } from './PlatformWebhooks.types'+import type { WebhookDelivery, WebhookEndpoint } from './PlatformWebhooks.types'const WEBHOOK_NAME_ADJECTIVES = ['swift',@@ -45,5 +45,50 @@ const getRandomItem = (values: string[]) => values[Math.floor(Math.random() * vaexport const generateWebhookEndpointName = () =>`${getRandomItem(WEBHOOK_NAME_ADJECTIVES)}-${getRandomItem(WEBHOOK_NAME_NOUNS)}`+const secureRandomHex = (length: number) => {+ if (length <= 0) return ''++ const cryptoApi = globalThis.crypto+ if (!cryptoApi?.getRandomValues) {+ throw new Error('Web Crypto API is not available')+ }++ const byteCount = Math.ceil(length / 2)+ const bytes = new Uint8Array(byteCount)+ cryptoApi.getRandomValues(bytes)++ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0'))+ .join('')+ .slice(0, length)+}++export const generateSigningSecret = () => `whsec_${secureRandomHex(16)}`+export const getWebhookEndpointDisplayName = (endpoint: Pick<WebhookEndpoint, 'name' | 'url'>) =>endpoint.name.trim() || endpoint.url++const normalizeSearch = (value: string) => value.trim().toLowerCase()++export const filterWebhookEndpoints = (endpoints: WebhookEndpoint[], search: string) => {+ const normalizedSearch = normalizeSearch(search)+ if (normalizedSearch.length === 0) return endpoints++ return endpoints.filter((endpoint) => {+ const haystack =+ `${getWebhookEndpointDisplayName(endpoint)} ${endpoint.url} ${endpoint.description}`.toLowerCase()+ return haystack.includes(normalizedSearch)+ })+}++export const filterWebhookDeliveries = (deliveries: WebhookDelivery[], search: string) => {+ const normalizedSearch = normalizeSearch(search)++ return deliveries+ .filter((delivery) => {+ if (normalizedSearch.length === 0) return true+ const haystack =+ `${delivery.eventType ?? ''} ${delivery.status} ${delivery.responseCode ?? ''}`.toLowerCase()+ return haystack.includes(normalizedSearch)+ })+ .sort((a, b) => new Date(b.attemptAt).getTime() - new Date(a.attemptAt).getTime())+}diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointDetails.test.tsx b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointDetails.test.tsxindex 4f1a0327051..51e7906e68d 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointDetails.test.tsx+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointDetails.test.tsx@@ -3,7 +3,7 @@ import userEvent from '@testing-library/user-event'import type { ComponentProps } from 'react'import { describe, expect, it, vi } from 'vitest'-import { PLATFORM_WEBHOOKS_MOCK_DATA } from './PlatformWebhooks.mock'+import type { WebhookDelivery, WebhookEndpoint } from './PlatformWebhooks.types'import { PlatformWebhooksEndpointDetails } from './PlatformWebhooksEndpointDetails'vi.mock('@/components/ui/DataTable/DataTableColumn/DataTableColumnStatusCode', () => ({@@ -42,12 +42,121 @@ vi.mock('ui-patterns/TimestampInfo', async () => {}})-describe('PlatformWebhooksEndpointDetails', () => {- const selectedEndpoint = PLATFORM_WEBHOOKS_MOCK_DATA.organization.endpoints[0]- const allDeliveries = PLATFORM_WEBHOOKS_MOCK_DATA.organization.deliveries.filter(- (delivery) => delivery.endpointId === selectedEndpoint.id- )+const SELECTED_ENDPOINT_ID = '7f2c9d4a-6e31-4d9d-9a1f-2c4b5e6f7081'++const selectedEndpoint: WebhookEndpoint = {+ id: SELECTED_ENDPOINT_ID,+ name: 'Lovable production',+ url: 'https://api.lovable.dev/webhooks/supabase',+ description: 'Primary organization webhook endpoint',+ enabled: true,+ eventTypes: ['v1.project.created', 'v1.project.updated'],+ customHeaders: [],+ createdBy: '[email protected]',+ createdAt: '2026-02-15T21:30:00.000Z',+}++const createDelivery = (overrides: Partial<WebhookDelivery>): WebhookDelivery => ({+ id: 'delivery',+ endpointId: SELECTED_ENDPOINT_ID,+ eventId: 'event',+ eventType: 'v1.project.updated',+ status: 'success',+ responseCode: 200,+ responseBody: null,+ responseHeaders: null,+ attemptAt: '2026-02-27T00:00:00.000Z',+ ...overrides,+})+const allDeliveries: WebhookDelivery[] = [+ createDelivery({+ id: 'org-delivery-1',+ eventType: 'project.created',+ status: 'success',+ responseCode: 200,+ attemptAt: '2026-02-27T08:04:00.000Z',+ }),+ createDelivery({+ id: 'org-delivery-2',+ eventType: 'project.updated',+ status: 'failure',+ responseCode: 500,+ attemptAt: '2026-02-27T07:56:00.000Z',+ }),+ createDelivery({+ id: 'org-delivery-3',+ eventType: 'project.deleted',+ status: 'pending',+ responseCode: 0,+ attemptAt: '2026-02-27T07:45:00.000Z',+ }),+ createDelivery({+ id: 'org-delivery-4',+ eventType: 'organization.member_invited',+ status: 'success',+ responseCode: 202,+ attemptAt: '2026-02-27T07:37:00.000Z',+ }),+ createDelivery({+ id: 'org-delivery-5',+ eventType: 'project.resumed',+ status: 'success',+ responseCode: 204,+ attemptAt: '2026-02-27T07:18:00.000Z',+ }),+ createDelivery({+ id: 'org-delivery-6',+ eventType: 'organization.member_removed',+ status: 'failure',+ responseCode: 400,+ attemptAt: '2026-02-27T06:59:00.000Z',+ }),+ createDelivery({+ id: 'org-delivery-7',+ eventType: 'organization.updated',+ status: 'skipped',+ responseCode: 0,+ attemptAt: '2026-02-27T06:40:00.000Z',+ }),+ createDelivery({+ id: 'org-delivery-8',+ eventType: 'project.paused',+ status: 'success',+ responseCode: 200,+ attemptAt: '2026-02-27T06:21:00.000Z',+ }),+ createDelivery({+ id: 'org-delivery-9',+ eventType: 'project.created',+ status: 'failure',+ responseCode: 503,+ attemptAt: '2026-02-27T06:03:00.000Z',+ }),+ createDelivery({+ id: 'org-delivery-10',+ eventType: 'project.updated',+ status: 'success',+ responseCode: 200,+ attemptAt: '2026-02-27T05:44:00.000Z',+ }),+ createDelivery({+ id: 'org-delivery-11',+ eventType: 'project.deleted',+ status: 'skipped',+ responseCode: 0,+ attemptAt: '2026-02-27T05:25:00.000Z',+ }),+ createDelivery({+ id: 'org-delivery-12',+ eventType: 'organization.member_invited',+ status: 'success',+ responseCode: 201,+ attemptAt: '2026-02-27T05:07:00.000Z',+ }),+]++describe('PlatformWebhooksEndpointDetails', () => {const renderComponent = (props?: Partial<ComponentProps<typeof PlatformWebhooksEndpointDetails>>) =>@@ -70,37 +179,23 @@ describe('PlatformWebhooksEndpointDetails', () => {renderComponent()expect(screen.getByText('Showing 1 to 5 of 12 deliveries')).toBeInTheDocument()- expect(screen.queryByText('organization.member_removed')).not.toBeInTheDocument()+ expect(screen.queryByText('2026-02-27T06:59:00.000Z')).not.toBeInTheDocument()await user.click(screen.getByLabelText('Next page'))expect(screen.getByText('Showing 6 to 10 of 12 deliveries')).toBeInTheDocument()- expect(screen.getByText('organization.member_removed')).toBeInTheDocument()+ expect(screen.getByText('2026-02-27T06:59:00.000Z')).toBeInTheDocument()await user.click(screen.getByLabelText('Previous page'))expect(screen.getByText('Showing 1 to 5 of 12 deliveries')).toBeInTheDocument()- expect(screen.queryByText('organization.member_removed')).not.toBeInTheDocument()- })-- it('sorts deliveries by event type from the header', async () => {- const user = userEvent.setup()-- renderComponent()-- await user.click(screen.getByRole('button', { name: 'Event type' }))-- expect(screen.getAllByRole('row')[1]).toHaveTextContent('organization.member_invited')-- await user.click(screen.getByRole('button', { name: 'Event type' }))-- expect(screen.getAllByRole('row')[1]).toHaveTextContent('project.updated')+ expect(screen.queryByText('2026-02-27T06:59:00.000Z')).not.toBeInTheDocument()})it('resets to the first page when the delivery search changes', async () => {const user = userEvent.setup()const projectDeliveries = allDeliveries.filter((delivery) =>- delivery.eventType.includes('project')+ delivery.eventType?.includes('project'))const { rerender } = renderComponent()diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointDetails.tsx b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointDetails.tsxindex 720b21eb601..cccafaa19b0 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointDetails.tsx+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointDetails.tsx@@ -72,13 +72,6 @@ const DELIVERY_COLUMNS: ColumnDef<WebhookDelivery>[] = [<Badge variant={statusBadgeVariant[row.original.status]}>{row.original.status}</Badge>),},- {- accessorKey: 'eventType',- header: ({ column }) => (- <TanStackTableHeadSort column={column}>Event type</TanStackTableHeadSort>- ),- cell: ({ row }) => <code className="text-code-inline">{row.original.eventType}</code>,- },{accessorKey: 'responseCode',header: ({ column }) => <TanStackTableHeadSort column={column}>Response</TanStackTableHeadSort>,diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.test.tsx b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.test.tsxindex 417f4740ad5..7cad2e3b852 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.test.tsx+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.test.tsx@@ -258,6 +258,7 @@ describe('PlatformWebhooksEndpointSheet', () => {{ key: 'X-Webhook-Secret', value: 'super-secret' },{ key: '', value: '' },],+ signingSecret: 'whsec_example',})).toEqual(expect.objectContaining({diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.tsx b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.tsxindex 08ba37d4360..92ea686ea6f 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.tsx+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksEndpointSheet.tsx@@ -39,7 +39,7 @@ import type {WebhookEndpoint,WebhookScope,} from './PlatformWebhooks.types'-import { generateWebhookEndpointName } from './PlatformWebhooks.utils'+import { generateSigningSecret, generateWebhookEndpointName } from './PlatformWebhooks.utils'import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'import { InlineLink } from '@/components/ui/InlineLink'import { Shortcut } from '@/components/ui/Shortcut'@@ -47,52 +47,64 @@ import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'import { httpEndpointUrlSchema } from '@/lib/validation/http-url'import { SHORTCUT_IDS } from '@/state/shortcuts/registry'-const endpointFormSchema = z- .object({- name: z.string().trim().max(64, 'Name cannot exceed 64 characters'),- url: httpEndpointUrlSchema({- requiredMessage: 'Please provide a URL',- invalidMessage: 'Please provide a valid URL',- prefixMessage: 'Please prefix your URL with http:// or https://',- }),- description: z.string().trim().max(512, 'Description cannot exceed 512 characters'),- enabled: z.boolean().default(true),- subscribeAll: z.boolean().default(false),- eventTypes: z.array(z.string()).default([]),- customHeaders: z- .array(- z.object({- key: z.string().trim(),- value: z.string().trim(),+const buildEndpointFormSchema = (mode: 'create' | 'edit') =>+ z+ .object({+ name: z.string().trim().max(64, 'Name cannot exceed 64 characters'),+ url: httpEndpointUrlSchema({+ requiredMessage: 'Please provide a URL',+ invalidMessage: 'Please provide a valid URL',+ prefixMessage: 'Please prefix your URL with http:// or https://',+ }),+ description: z.string().trim().max(512, 'Description cannot exceed 512 characters'),+ enabled: z.boolean().default(true),+ subscribeAll: z.boolean().default(false),+ eventTypes: z.array(z.string()).default([]),+ customHeaders: z+ .array(+ z.object({+ key: z.string().trim(),+ value: z.string().trim(),+ })+ )+ .default([]),+ // Only required on create — the API only accepts a new secret on create,+ // rotating it on an existing endpoint is a separate flow (regenerateSecret).+ signingSecret: z.string().trim().default(''),+ })+ .superRefine((data, ctx) => {+ if (!data.subscribeAll && data.eventTypes.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Select at least one event type',+ path: ['eventTypes'],})- )- .default([]),- })- .superRefine((data, ctx) => {- if (!data.subscribeAll && data.eventTypes.length === 0) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: 'Select at least one event type',- path: ['eventTypes'],- })- }+ }- getKeyValueFieldArrayValidationIssues({- rows: data.customHeaders,- keyFieldName: 'key',- valueFieldName: 'value',- keyRequiredMessage: 'Header name is required',- valueRequiredMessage: 'Header value is required',- }).forEach((issue) => {- ctx.addIssue({- code: z.ZodIssueCode.custom,- message: issue.message,- path: ['customHeaders', ...issue.path],+ if (mode === 'create' && data.signingSecret.length === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Please provide a signing secret',+ path: ['signingSecret'],+ })+ }++ getKeyValueFieldArrayValidationIssues({+ rows: data.customHeaders,+ keyFieldName: 'key',+ valueFieldName: 'value',+ keyRequiredMessage: 'Header name is required',+ valueRequiredMessage: 'Header value is required',+ }).forEach((issue) => {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: issue.message,+ path: ['customHeaders', ...issue.path],+ })})})- })-export type EndpointFormValues = z.infer<typeof endpointFormSchema>+export type EndpointFormValues = z.infer<ReturnType<typeof buildEndpointFormSchema>>const toEventTypes = (values: EndpointFormValues) =>values.subscribeAll ? ['*'] : values.eventTypes@@ -108,10 +120,12 @@ const buildEventTypeGroups = (scope: WebhookScope, eventTypes: string[]): EventTreturn [{ id: 'project', label: 'Project events', eventTypes }]}- const organizationEvents = eventTypes.filter((eventType) => eventType.startsWith('organization.'))- const projectEvents = eventTypes.filter((eventType) => eventType.startsWith('project.'))+ const organizationEvents = eventTypes.filter((eventType) =>+ eventType.startsWith('v1.organization.')+ )+ const projectEvents = eventTypes.filter((eventType) => eventType.startsWith('v1.project.'))const ungroupedEvents = eventTypes.filter(- (eventType) => !eventType.startsWith('organization.') && !eventType.startsWith('project.')+ (eventType) => !eventType.startsWith('v1.organization.') && !eventType.startsWith('v1.project.'))return [@@ -149,6 +163,7 @@ export const toEndpointPayload = (values: EndpointFormValues): UpsertWebhookEndpkeyFieldName: 'key',valueFieldName: 'value',}),+ signingSecret: values.signingSecret,})interface EndpointSheetProps {@@ -175,7 +190,7 @@ export const PlatformWebhooksEndpointSheet = ({onSubmit,}: EndpointSheetProps) => {const form = useForm<EndpointFormValues>({- resolver: zodResolver(endpointFormSchema),+ resolver: zodResolver(buildEndpointFormSchema(mode)),defaultValues: {name: generateWebhookEndpointName(),url: '',@@ -184,6 +199,7 @@ export const PlatformWebhooksEndpointSheet = ({subscribeAll: false,eventTypes: [],customHeaders: [],+ signingSecret: mode === 'create' ? generateSigningSecret() : '',},})const isDirty = form.formState.isDirty@@ -216,6 +232,7 @@ export const PlatformWebhooksEndpointSheet = ({subscribeAll: false,eventTypes: [],customHeaders: [],+ signingSecret: generateSigningSecret(),})return}@@ -231,6 +248,7 @@ export const PlatformWebhooksEndpointSheet = ({key: header.key,value: header.value,})),+ signingSecret: '',})}, [enabledOverride, endpoint, eventTypes, form, visible])@@ -306,6 +324,33 @@ export const PlatformWebhooksEndpointSheet = ({)}/>+ {mode === 'create' && (+ <FormField+ control={form.control}+ name="signingSecret"+ render={({ field }) => (+ <FormItemLayout+ label="Signing secret"+ description="Shown only once after creation — used to verify delivery payloads."+ layout="vertical"+ className="gap-1"+ >+ <div className="flex gap-2">+ <FormControl>+ <Input {...field} placeholder="whsec_..." className="font-mono" />+ </FormControl>+ <Button+ type="button"+ onClick={() => field.onChange(generateSigningSecret())}+ >+ Generate+ </Button>+ </div>+ </FormItemLayout>+ )}+ />+ )}+<FormFieldcontrol={form.control}name="description"diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.tsx b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.tsxindex e14be6dab08..6a154c2a18a 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.tsx+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.tsx@@ -1,5 +1,5 @@import { LOCAL_STORAGE_KEYS, useParams } from 'common'-import { EllipsisVertical, Pencil, RotateCw, Trash2 } from 'lucide-react'+import { EllipsisVertical, Pencil, RotateCw, Send, Trash2 } from 'lucide-react'import { useRouter } from 'next/router'import { parseAsString, parseAsStringLiteral, useQueryState } from 'nuqs'import { useEffect, useMemo, useState } from 'react'@@ -26,14 +26,14 @@ import { Input } from 'ui-patterns/DataInputs/Input'import { PageContainer } from 'ui-patterns/PageContainer'import { PageSection, PageSectionContent } from 'ui-patterns/PageSection'-import { PLATFORM_WEBHOOKS_MOCK_DATA } from './PlatformWebhooks.mock'+import { PLATFORM_WEBHOOK_EVENT_TYPES } from './PlatformWebhooks.constants'+import type { WebhookScope } from './PlatformWebhooks.types'import {filterWebhookDeliveries,filterWebhookEndpoints,- usePlatformWebhooksMockStore,-} from './PlatformWebhooks.store'-import type { WebhookScope } from './PlatformWebhooks.types'-import { getWebhookEndpointDisplayName } from './PlatformWebhooks.utils'+ generateSigningSecret,+ getWebhookEndpointDisplayName,+} from './PlatformWebhooks.utils'import { PlatformWebhooksDeliveryDetailsSheet } from './PlatformWebhooksDeliveryDetailsSheet'import { PlatformWebhooksEndpointDetails } from './PlatformWebhooksEndpointDetails'import { PlatformWebhooksEndpointList } from './PlatformWebhooksEndpointList'@@ -48,10 +48,24 @@ import {getPendingSigningSecretReveal,setPendingSigningSecretReveal,shouldHandleEndpointNotFound,+ shouldRedirectFromWebhooks,} from './PlatformWebhooksPage.utils'-import { useIsPlatformWebhooksEnabled } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'+import {+ useFeaturePreviewContext,+ useIsPlatformWebhooksEnabled,+} from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { InlineLink } from '@/components/ui/InlineLink'import { Shortcut } from '@/components/ui/Shortcut'+import { useWebhookDeliveriesQuery } from '@/data/platform-webhooks/platform-webhook-deliveries-query'+import { useWebhookDeliveryQuery } from '@/data/platform-webhooks/platform-webhook-delivery-query'+import { useWebhookDeliveryRetryMutation } from '@/data/platform-webhooks/platform-webhook-delivery-retry-mutation'+import { useWebhookEndpointCreateMutation } from '@/data/platform-webhooks/platform-webhook-endpoint-create-mutation'+import { useWebhookEndpointDeleteMutation } from '@/data/platform-webhooks/platform-webhook-endpoint-delete-mutation'+import { useWebhookEndpointRegenerateSecretMutation } from '@/data/platform-webhooks/platform-webhook-endpoint-regenerate-secret-mutation'+import { useWebhookEndpointTestMutation } from '@/data/platform-webhooks/platform-webhook-endpoint-test-mutation'+import { useWebhookEndpointUpdateMutation } from '@/data/platform-webhooks/platform-webhook-endpoint-update-mutation'+import { useWebhookEndpointsQuery } from '@/data/platform-webhooks/platform-webhook-endpoints-query'+import type { WebhookScopeParams } from '@/data/platform-webhooks/platform-webhooks-fetchers'import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'import { SHORTCUT_IDS } from '@/state/shortcuts/registry'import { useShortcut } from '@/state/shortcuts/useShortcut'@@ -70,15 +84,26 @@ export const PlatformWebhooksPage = ({ scope, endpointId }: PlatformWebhooksPageenabled: scope === 'project',})const platformWebhooksEnabled = useIsPlatformWebhooksEnabled()- const {- endpoints,- deliveries,- createEndpoint,- updateEndpoint,- deleteEndpoint,- regenerateSecret,- retryDelivery,- } = usePlatformWebhooksMockStore(scope)+ const { isInitialized: isFeaturePreviewInitialized } = useFeaturePreviewContext()++ const isScopeReady = scope === 'organization' ? !!slug : !!ref+ const apiScope: WebhookScopeParams =+ scope === 'organization'+ ? { scope: 'organization', orgSlug: slug ?? '' }+ : { scope: 'project', projectRef: ref ?? '' }+ const queryEnabled = platformWebhooksEnabled && isScopeReady++ const { data: endpoints = [], isSuccess: isEndpointsLoaded } = useWebhookEndpointsQuery(+ { scope: apiScope },+ { enabled: queryEnabled }+ )+ const createEndpointMutation = useWebhookEndpointCreateMutation()+ const updateEndpointMutation = useWebhookEndpointUpdateMutation()+ const deleteEndpointMutation = useWebhookEndpointDeleteMutation()+ const regenerateSecretMutation = useWebhookEndpointRegenerateSecretMutation()+ const testEndpointMutation = useWebhookEndpointTestMutation()+ const retryDeliveryMutation = useWebhookDeliveryRetryMutation()+const [deliveryId, setDeliveryId] = useQueryState('deliveryId', parseAsString)const [panel, setPanel] = useQueryState('panel', parseAsStringLiteral(PANEL_VALUES))const [search, setSearch] = useQueryState(@@ -107,7 +132,12 @@ export const PlatformWebhooksPage = ({ scope, endpointId }: PlatformWebhooksPageconst fallbackHref =scope === 'organization' ? `/org/${slug}/general` : `/project/${ref}/settings/general`- const eventTypeOptions = PLATFORM_WEBHOOKS_MOCK_DATA[scope].eventTypes+ // A project-scoped endpoint only ever receives project events — subscribing it to an+ // organization event would be a dead option, since the backend never delivers one there.+ const eventTypeOptions =+ scope === 'project'+ ? PLATFORM_WEBHOOK_EVENT_TYPES.filter((eventType) => eventType.startsWith('v1.project.'))+ : [...PLATFORM_WEBHOOK_EVENT_TYPES]const webhooksHref =scope === 'organization' ? `/org/${slug}/webhooks` : `/project/${ref}/settings/webhooks`@@ -115,6 +145,19 @@ export const PlatformWebhooksPage = ({ scope, endpointId }: PlatformWebhooksPage() => endpoints.find((endpoint) => endpoint.id === endpointId) ?? null,[endpoints, endpointId])+ const { data: deliveries = [] } = useWebhookDeliveriesQuery(+ { scope: apiScope, endpointId: selectedEndpoint?.id ?? '' },+ { enabled: queryEnabled && !!selectedEndpoint }+ )+ const {+ data: selectedDelivery = null,+ isSuccess: isSelectedDeliveryLoaded,+ isError: isSelectedDeliveryError,+ } = useWebhookDeliveryQuery(+ { scope: apiScope, endpointId: selectedEndpoint?.id ?? '', id: deliveryId ?? '' },+ { enabled: queryEnabled && !!selectedEndpoint && !!deliveryId }+ )+const isEndpointView = !!selectedEndpointconst selectedEndpointHasName = selectedEndpoint ? selectedEndpoint.name.trim().length > 0 : falseconst selectedEndpointDisplayName = selectedEndpoint@@ -144,13 +187,21 @@ export const PlatformWebhooksPage = ({ scope, endpointId }: PlatformWebhooksPage: 'Deleting this endpoint stops all deliveries to the URL below. This can’t be undone.'}+ const shouldRedirect = shouldRedirectFromWebhooks({+ areFlagsReady: isFeaturePreviewInitialized,+ isScopeReady,+ isEnabled: !!platformWebhooksEnabled,+ })+useEffect(() => {- if (!platformWebhooksEnabled) {+ if (shouldRedirect) {router.replace(fallbackHref)}- }, [fallbackHref, platformWebhooksEnabled, router])+ }, [fallbackHref, shouldRedirect, router])useEffect(() => {+ if (!isEndpointsLoaded) return+if (shouldHandleEndpointNotFound({endpointId,@@ -161,7 +212,14 @@ export const PlatformWebhooksPage = ({ scope, endpointId }: PlatformWebhooksPagetoast('Endpoint not found')router.replace(webhooksHref)}- }, [endpointId, pendingCreatedEndpointId, selectedEndpoint, router, webhooksHref])+ }, [+ endpointId,+ isEndpointsLoaded,+ pendingCreatedEndpointId,+ selectedEndpoint,+ router,+ webhooksHref,+ ])useEffect(() => {if (!pendingCreatedEndpointId) return@@ -186,60 +244,49 @@ export const PlatformWebhooksPage = ({ scope, endpointId }: PlatformWebhooksPageconst filteredDeliveries = useMemo(() => {if (!selectedEndpoint) return []- return filterWebhookDeliveries(deliveries, selectedEndpoint.id, deliverySearch)+ return filterWebhookDeliveries(deliveries, deliverySearch)}, [deliveries, deliverySearch, selectedEndpoint])- const selectedDelivery = useMemo(() => {- if (!selectedEndpoint || !deliveryId) return null- return (- deliveries.find(- (delivery) => delivery.id === deliveryId && delivery.endpointId === selectedEndpoint.id- ) ?? null- )- }, [deliveries, deliveryId, selectedEndpoint])-const deliveryAttempt = useMemo(() => {- if (!selectedEndpoint || !selectedDelivery) return null- const endpointDeliveries = deliveries- .filter((delivery) => delivery.endpointId === selectedEndpoint.id)- .sort((a, b) => new Date(b.attemptAt).getTime() - new Date(a.attemptAt).getTime())- const index = endpointDeliveries.findIndex((delivery) => delivery.id === selectedDelivery.id)+ if (!selectedDelivery) return null+ const sortedDeliveries = [...deliveries].sort(+ (a, b) => new Date(b.attemptAt).getTime() - new Date(a.attemptAt).getTime()+ )+ const index = sortedDeliveries.findIndex((delivery) => delivery.id === selectedDelivery.id)return index >= 0 ? index + 1 : null- }, [deliveries, selectedDelivery, selectedEndpoint])+ }, [deliveries, selectedDelivery])const deliveryEventPayload = useMemo(() => {- if (!selectedEndpoint || !selectedDelivery) return ''+ if (!selectedDelivery) return ''return JSON.stringify({- endpoint_id: selectedEndpoint.id,- endpoint_url: selectedEndpoint.url,- event_type: selectedDelivery.eventType,- event_id: selectedDelivery.id,- attempted_at: selectedDelivery.attemptAt,- scope,+ id: selectedDelivery.eventId,+ type: selectedDelivery.eventType,+ timestamp: selectedDelivery.attemptAt,+ payload: selectedDelivery.eventPayload,},null,2)- }, [scope, selectedDelivery, selectedEndpoint])+ }, [selectedDelivery])const deliveryResponsePayload = useMemo(() => {- if (!selectedEndpoint || !selectedDelivery) return ''+ if (!selectedDelivery) return ''return JSON.stringify({- endpoint_id: selectedEndpoint.id,- delivery_id: selectedDelivery.id,status: selectedDelivery.status,- response_code: selectedDelivery.responseCode ?? null,+ response_code: selectedDelivery.responseCode,+ response_headers: selectedDelivery.responseHeaders,+ response_body: selectedDelivery.responseBody,},null,2)- }, [selectedDelivery, selectedEndpoint])+ }, [selectedDelivery])- const handleDeleteEndpoint = () => {+ const handleDeleteEndpoint = async () => {if (!endpointPendingDelete) return- deleteEndpoint(endpointPendingDelete.id)+ await deleteEndpointMutation.mutateAsync({ scope: apiScope, id: endpointPendingDelete.id })if (endpointPendingDelete.id === endpointId) {router.push(webhooksHref)setDeliverySearch('')@@ -248,18 +295,19 @@ export const PlatformWebhooksPage = ({ scope, endpointId }: PlatformWebhooksPagetoast.success('Endpoint deleted')}- const handleUpsertEndpoint = (values: EndpointFormValues) => {+ const handleUpsertEndpoint = async (values: EndpointFormValues) => {if (panel === 'create') {- const { endpointId: createdEndpointId, signingSecret } = createEndpoint(- toEndpointPayload(values)- )- setPendingCreatedEndpointId(createdEndpointId)+ const input = toEndpointPayload(values)+ const created = await createEndpointMutation.mutateAsync({ scope: apiScope, input })+ // The server never echoes the secret back — we already know it, since the+ // user (or the "Generate" button) chose it client-side before submitting.+ setPendingCreatedEndpointId(created.id)setPendingSigningSecretReveal(scope, {- endpointId: createdEndpointId,- signingSecret,+ endpointId: created.id,+ signingSecret: input.signingSecret,})- router.push(`${webhooksHref}/${encodeURIComponent(createdEndpointId)}`)- setSigningSecretReveal({ signingSecret })+ router.push(`${webhooksHref}/${encodeURIComponent(created.id)}`)+ setSigningSecretReveal({ signingSecret: input.signingSecret })setPanel(null)setEditEnabledOverride(null)toast.success('Endpoint created')@@ -267,27 +315,46 @@ export const PlatformWebhooksPage = ({ scope, endpointId }: PlatformWebhooksPage}if (panel === 'edit' && selectedEndpoint) {- updateEndpoint(selectedEndpoint.id, toEndpointPayload(values))+ await updateEndpointMutation.mutateAsync({+ scope: apiScope,+ id: selectedEndpoint.id,+ input: toEndpointPayload(values),+ })setPanel(null)setEditEnabledOverride(null)toast.success('Endpoint updated')}}- const handleRegenerateSecret = () => {+ const handleRegenerateSecret = async () => {if (!selectedEndpoint) return- const nextSecret = regenerateSecret(selectedEndpoint.id)- if (!nextSecret) return+ const nextSecret = generateSigningSecret()+ await regenerateSecretMutation.mutateAsync({+ scope: apiScope,+ id: selectedEndpoint.id,+ signingSecret: nextSecret,+ })setSigningSecretReveal({ signingSecret: nextSecret })setShowRegenerateSecretConfirm(false)toast.success('Signing secret regenerated')}- const handleRetryDelivery = (deliveryId: string) => {+ const handleSendTestEvent = async () => {+ if (!selectedEndpoint) return+ await testEndpointMutation.mutateAsync({ scope: apiScope, id: selectedEndpoint.id })+ toast.success('Test event sent — check deliveries shortly')+ }++ const handleRetryDelivery = async (deliveryId: string) => {+ if (!selectedEndpoint) returnconst delivery = deliveries.find((item) => item.id === deliveryId)if (!delivery || delivery.status === 'success') return- retryDelivery(deliveryId)+ await retryDeliveryMutation.mutateAsync({+ scope: apiScope,+ endpointId: selectedEndpoint.id,+ id: deliveryId,+ })toast.success('Delivery queued for retry')}@@ -311,10 +378,18 @@ export const PlatformWebhooksPage = ({ scope, endpointId }: PlatformWebhooksPage}, [deliveryId, selectedEndpoint, setDeliveryId])useEffect(() => {- if (!!deliveryId && !selectedDelivery) {+ const deliveryUnavailable =+ (isSelectedDeliveryLoaded && !selectedDelivery) || isSelectedDeliveryError+ if (!!deliveryId && deliveryUnavailable) {setDeliveryId(null)}- }, [deliveryId, selectedDelivery, setDeliveryId])+ }, [+ deliveryId,+ isSelectedDeliveryError,+ isSelectedDeliveryLoaded,+ selectedDelivery,+ setDeliveryId,+ ])if (!platformWebhooksEnabled) {return null@@ -356,6 +431,10 @@ export const PlatformWebhooksPage = ({ scope, endpointId }: PlatformWebhooksPage<Button icon={<EllipsisVertical />} className="w-7" /></DropdownMenuTrigger><DropdownMenuContent align="end" side="bottom" className="w-48">+ <DropdownMenuItem className="gap-x-2" onClick={handleSendTestEvent}>+ <Send size={14} className="text-foreground-lighter" />+ <span>Send test event</span>+ </DropdownMenuItem><DropdownMenuItemclassName="gap-x-2"onClick={() => setShowRegenerateSecretConfirm(true)}diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.utils.test.ts b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.utils.test.tsindex 52e8c831aee..f8bdf1eed4b 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.utils.test.ts+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.utils.test.ts@@ -6,6 +6,7 @@ import {resetPendingSigningSecretRevealForTests,setPendingSigningSecretReveal,shouldHandleEndpointNotFound,+ shouldRedirectFromWebhooks,} from './PlatformWebhooksPage.utils'describe('PlatformWebhooksPage.utils', () => {@@ -57,6 +58,32 @@ describe('PlatformWebhooksPage.utils', () => {).toBe(true)})+ describe('shouldRedirectFromWebhooks', () => {+ it('does not redirect while flags are still loading', () => {+ expect(+ shouldRedirectFromWebhooks({ areFlagsReady: false, isScopeReady: true, isEnabled: false })+ ).toBe(false)+ })++ it('does not redirect before route params are populated', () => {+ expect(+ shouldRedirectFromWebhooks({ areFlagsReady: true, isScopeReady: false, isEnabled: false })+ ).toBe(false)+ })++ it('does not redirect when webhooks are enabled', () => {+ expect(+ shouldRedirectFromWebhooks({ areFlagsReady: true, isScopeReady: true, isEnabled: true })+ ).toBe(false)+ })++ it('redirects once ready and webhooks are disabled', () => {+ expect(+ shouldRedirectFromWebhooks({ areFlagsReady: true, isScopeReady: true, isEnabled: false })+ ).toBe(true)+ })+ })+it('stores and reads pending signing secret reveal for matching endpoint route', () => {setPendingSigningSecretReveal('project', {endpointId,diff --git a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.utils.ts b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.utils.tsindex 7979419afeb..b83eefe9da0 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.utils.ts+++ b/apps/studio/components/interfaces/Platform/Webhooks/PlatformWebhooksPage.utils.ts@@ -14,6 +14,20 @@ export const shouldHandleEndpointNotFound = ({return endpointId !== pendingCreatedEndpointId}+/**+ * Only redirect away once the flags have loaded and the route params are populated; before+ * that, the flag reads `false` and `slug`/`ref` are undefined even for enabled users.+ */+export const shouldRedirectFromWebhooks = ({+ areFlagsReady,+ isScopeReady,+ isEnabled,+}: {+ areFlagsReady: boolean+ isScopeReady: boolean+ isEnabled: boolean+}) => areFlagsReady && isScopeReady && !isEnabled+interface PendingSigningSecretReveal {endpointId: stringsigningSecret: stringdiff --git a/apps/studio/components/interfaces/Platform/Webhooks/index.ts b/apps/studio/components/interfaces/Platform/Webhooks/index.tsindex bd9de77af43..f6a78a6e090 100644--- a/apps/studio/components/interfaces/Platform/Webhooks/index.ts+++ b/apps/studio/components/interfaces/Platform/Webhooks/index.ts@@ -1,5 +1,4 @@export { PlatformWebhooksPage } from './PlatformWebhooksPage'-export { usePlatformWebhooksMockStore } from './PlatformWebhooks.store'export {generateWebhookEndpointName,getWebhookEndpointDisplayName,diff --git a/apps/studio/data/platform-webhooks/keys.ts b/apps/studio/data/platform-webhooks/keys.tsnew file mode 100644index 00000000000..6dcbc966106--- /dev/null+++ b/apps/studio/data/platform-webhooks/keys.ts@@ -0,0 +1,37 @@+import type { WebhookScopeParams } from './platform-webhooks-fetchers'++const scopeId = (scope: WebhookScopeParams) =>+ scope.scope === 'organization' ? scope.orgSlug : scope.projectRef++export const platformWebhooksKeys = {+ endpoints: (scope: WebhookScopeParams, limit?: number, offset?: number) =>+ ['platform-webhooks', scope.scope, scopeId(scope), 'endpoints', { limit, offset }] as const,+ endpoint: (scope: WebhookScopeParams, id: string | undefined) =>+ ['platform-webhooks', scope.scope, scopeId(scope), 'endpoints', id] as const,+ deliveries: (+ scope: WebhookScopeParams,+ endpointId: string | undefined,+ size?: number,+ after?: string,+ before?: string+ ) =>+ [+ 'platform-webhooks',+ scope.scope,+ scopeId(scope),+ 'endpoints',+ endpointId,+ 'deliveries',+ { size, after, before },+ ] as const,+ delivery: (scope: WebhookScopeParams, endpointId: string | undefined, id: string | undefined) =>+ [+ 'platform-webhooks',+ scope.scope,+ scopeId(scope),+ 'endpoints',+ endpointId,+ 'deliveries',+ id,+ ] as const,+}diff --git a/apps/studio/data/platform-webhooks/platform-webhook-deliveries-query.ts b/apps/studio/data/platform-webhooks/platform-webhook-deliveries-query.tsnew file mode 100644index 00000000000..c6c12e42b36--- /dev/null+++ b/apps/studio/data/platform-webhooks/platform-webhook-deliveries-query.ts@@ -0,0 +1,43 @@+import { useQuery } from '@tanstack/react-query'++import { platformWebhooksKeys } from './keys'+import { listWebhookDeliveries, type WebhookScopeParams } from './platform-webhooks-fetchers'+import { toWebhookDeliverySummary } from './platform-webhooks-mappers'+import type { WebhookDelivery } from '@/components/interfaces/Platform/Webhooks/PlatformWebhooks.types'+import type { ResponseError, UseCustomQueryOptions } from '@/types'++interface WebhookDeliveriesVariables {+ scope: WebhookScopeParams+ endpointId: string+ size?: number+ after?: string+ before?: string+}++async function getWebhookDeliveries(+ { scope, endpointId, size, after, before }: WebhookDeliveriesVariables,+ signal?: AbortSignal+): Promise<WebhookDelivery[]> {+ const result = await listWebhookDeliveries(scope, endpointId, { size, after, before }, signal)+ return (result?.data ?? []).map((delivery) => toWebhookDeliverySummary(delivery, endpointId))+}++export type WebhookDeliveriesData = Awaited<ReturnType<typeof getWebhookDeliveries>>++export const useWebhookDeliveriesQuery = <TData = WebhookDeliveriesData>(+ variables: WebhookDeliveriesVariables,+ {+ enabled = true,+ ...options+ }: UseCustomQueryOptions<WebhookDeliveriesData, ResponseError, TData> = {}+) => {+ const { scope, endpointId, size, after, before } = variables++ return useQuery<WebhookDeliveriesData, ResponseError, TData>({+ queryKey: platformWebhooksKeys.deliveries(scope, endpointId, size, after, before),+ queryFn: ({ signal }) =>+ getWebhookDeliveries({ scope, endpointId, size, after, before }, signal),+ enabled: enabled && Boolean(endpointId),+ ...options,+ })+}diff --git a/apps/studio/data/platform-webhooks/platform-webhook-delivery-query.ts b/apps/studio/data/platform-webhooks/platform-webhook-delivery-query.tsnew file mode 100644index 00000000000..4011137a8bf--- /dev/null+++ b/apps/studio/data/platform-webhooks/platform-webhook-delivery-query.ts@@ -0,0 +1,40 @@+import { useQuery } from '@tanstack/react-query'++import { platformWebhooksKeys } from './keys'+import { getWebhookDelivery, type WebhookScopeParams } from './platform-webhooks-fetchers'+import { toWebhookDelivery } from './platform-webhooks-mappers'+import type { WebhookDelivery } from '@/components/interfaces/Platform/Webhooks/PlatformWebhooks.types'+import type { ResponseError, UseCustomQueryOptions } from '@/types'++interface WebhookDeliveryVariables {+ scope: WebhookScopeParams+ endpointId: string+ id: string+}++async function fetchWebhookDelivery(+ { scope, endpointId, id }: WebhookDeliveryVariables,+ signal?: AbortSignal+): Promise<WebhookDelivery | null> {+ const result = await getWebhookDelivery(scope, id, signal)+ return result?.data ? toWebhookDelivery(result.data, endpointId) : null+}++export type WebhookDeliveryData = Awaited<ReturnType<typeof fetchWebhookDelivery>>++export const useWebhookDeliveryQuery = <TData = WebhookDeliveryData>(+ variables: WebhookDeliveryVariables,+ {+ enabled = true,+ ...options+ }: UseCustomQueryOptions<WebhookDeliveryData, ResponseError, TData> = {}+) => {+ const { scope, endpointId, id } = variables++ return useQuery<WebhookDeliveryData, ResponseError, TData>({+ queryKey: platformWebhooksKeys.delivery(scope, endpointId, id),+ queryFn: ({ signal }) => fetchWebhookDelivery({ scope, endpointId, id }, signal),+ enabled: enabled && Boolean(id),+ ...options,+ })+}diff --git a/apps/studio/data/platform-webhooks/platform-webhook-delivery-retry-mutation.ts b/apps/studio/data/platform-webhooks/platform-webhook-delivery-retry-mutation.tsnew file mode 100644index 00000000000..6dfc069c0a4--- /dev/null+++ b/apps/studio/data/platform-webhooks/platform-webhook-delivery-retry-mutation.ts@@ -0,0 +1,56 @@+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { platformWebhooksKeys } from './keys'+import {+ isWebhookRateLimitError,+ retryWebhookDelivery,+ type WebhookScopeParams,+} from './platform-webhooks-fetchers'+import type { ResponseError, UseCustomMutationOptions } from '@/types'++export type WebhookDeliveryRetryVariables = {+ scope: WebhookScopeParams+ endpointId: string+ id: string+}++async function retryDelivery({ scope, id }: WebhookDeliveryRetryVariables) {+ return retryWebhookDelivery(scope, id)+}++type WebhookDeliveryRetryData = Awaited<ReturnType<typeof retryDelivery>>++export const useWebhookDeliveryRetryMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<WebhookDeliveryRetryData, ResponseError, WebhookDeliveryRetryVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<WebhookDeliveryRetryData, ResponseError, WebhookDeliveryRetryVariables>({+ mutationFn: retryDelivery,+ async onSuccess(data, variables, context) {+ await queryClient.invalidateQueries({+ queryKey: platformWebhooksKeys.deliveries(variables.scope, variables.endpointId),+ })++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ if (isWebhookRateLimitError(data)) {+ toast.error('Too many retries — wait a minute and try again (limit: 10 per minute).')+ } else {+ toast.error(`Failed to retry delivery: ${data.message}`)+ }+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/platform-webhooks/platform-webhook-endpoint-create-mutation.ts b/apps/studio/data/platform-webhooks/platform-webhook-endpoint-create-mutation.tsnew file mode 100644index 00000000000..10e5bb8d9d5--- /dev/null+++ b/apps/studio/data/platform-webhooks/platform-webhook-endpoint-create-mutation.ts@@ -0,0 +1,71 @@+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { platformWebhooksKeys } from './keys'+import { createWebhookEndpoint, type WebhookScopeParams } from './platform-webhooks-fetchers'+import { toWebhookEndpoint, toWebhookEndpointAttributes } from './platform-webhooks-mappers'+import type {+ UpsertWebhookEndpointInput,+ WebhookEndpoint,+} from '@/components/interfaces/Platform/Webhooks/PlatformWebhooks.types'+import type { ResponseError, UseCustomMutationOptions } from '@/types'++export type WebhookEndpointCreateVariables = {+ scope: WebhookScopeParams+ input: UpsertWebhookEndpointInput+}++async function createEndpoint({+ scope,+ input,+}: WebhookEndpointCreateVariables): Promise<WebhookEndpoint> {+ const attributes = toWebhookEndpointAttributes(input)+ if (!attributes.signing_secret) throw new Error('A signing secret is required')++ const result = await createWebhookEndpoint(scope, {+ ...attributes,+ signing_secret: attributes.signing_secret,+ })+ if (!result?.data) throw new Error('Endpoint was created but no data was returned')++ // The server never stores `name` (see PlatformWebhooks.types.ts) — carry through+ // what the user typed so it's visible for this session, even though it won't+ // survive a refetch or page reload.+ return { ...toWebhookEndpoint(result.data), name: input.name }+}++type WebhookEndpointCreateData = Awaited<ReturnType<typeof createEndpoint>>++export const useWebhookEndpointCreateMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<+ WebhookEndpointCreateData,+ ResponseError,+ WebhookEndpointCreateVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<WebhookEndpointCreateData, ResponseError, WebhookEndpointCreateVariables>({+ mutationFn: createEndpoint,+ async onSuccess(data, variables, context) {+ await queryClient.invalidateQueries({+ queryKey: platformWebhooksKeys.endpoints(variables.scope),+ })++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to create webhook endpoint: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/platform-webhooks/platform-webhook-endpoint-delete-mutation.ts b/apps/studio/data/platform-webhooks/platform-webhook-endpoint-delete-mutation.tsnew file mode 100644index 00000000000..d97ebe7e288--- /dev/null+++ b/apps/studio/data/platform-webhooks/platform-webhook-endpoint-delete-mutation.ts@@ -0,0 +1,51 @@+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { platformWebhooksKeys } from './keys'+import { deleteWebhookEndpoint, type WebhookScopeParams } from './platform-webhooks-fetchers'+import type { ResponseError, UseCustomMutationOptions } from '@/types'++export type WebhookEndpointDeleteVariables = {+ scope: WebhookScopeParams+ id: string+}++async function deleteEndpoint({ scope, id }: WebhookEndpointDeleteVariables) {+ return deleteWebhookEndpoint(scope, id)+}++type WebhookEndpointDeleteData = Awaited<ReturnType<typeof deleteEndpoint>>++export const useWebhookEndpointDeleteMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<+ WebhookEndpointDeleteData,+ ResponseError,+ WebhookEndpointDeleteVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<WebhookEndpointDeleteData, ResponseError, WebhookEndpointDeleteVariables>({+ mutationFn: deleteEndpoint,+ async onSuccess(data, variables, context) {+ await queryClient.invalidateQueries({+ queryKey: platformWebhooksKeys.endpoints(variables.scope),+ })++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to delete webhook endpoint: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/platform-webhooks/platform-webhook-endpoint-regenerate-secret-mutation.ts b/apps/studio/data/platform-webhooks/platform-webhook-endpoint-regenerate-secret-mutation.tsnew file mode 100644index 00000000000..6bf84ee29dc--- /dev/null+++ b/apps/studio/data/platform-webhooks/platform-webhook-endpoint-regenerate-secret-mutation.ts@@ -0,0 +1,65 @@+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { platformWebhooksKeys } from './keys'+import {+ regenerateWebhookEndpointSecret,+ type WebhookScopeParams,+} from './platform-webhooks-fetchers'+import type { ResponseError, UseCustomMutationOptions } from '@/types'++export type WebhookEndpointRegenerateSecretVariables = {+ scope: WebhookScopeParams+ id: string+ signingSecret: string+}++async function regenerateSecret({+ scope,+ id,+ signingSecret,+}: WebhookEndpointRegenerateSecretVariables) {+ await regenerateWebhookEndpointSecret(scope, id, signingSecret)+ // The server never returns the secret — hand back what we sent so callers can reveal it.+ return { signingSecret }+}++type WebhookEndpointRegenerateSecretData = Awaited<ReturnType<typeof regenerateSecret>>++export const useWebhookEndpointRegenerateSecretMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<+ WebhookEndpointRegenerateSecretData,+ ResponseError,+ WebhookEndpointRegenerateSecretVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<+ WebhookEndpointRegenerateSecretData,+ ResponseError,+ WebhookEndpointRegenerateSecretVariables+ >({+ mutationFn: regenerateSecret,+ async onSuccess(data, variables, context) {+ await queryClient.invalidateQueries({+ queryKey: platformWebhooksKeys.endpoint(variables.scope, variables.id),+ })++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to regenerate signing secret: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/platform-webhooks/platform-webhook-endpoint-test-mutation.ts b/apps/studio/data/platform-webhooks/platform-webhook-endpoint-test-mutation.tsnew file mode 100644index 00000000000..fba46f1f6a7--- /dev/null+++ b/apps/studio/data/platform-webhooks/platform-webhook-endpoint-test-mutation.ts@@ -0,0 +1,56 @@+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { platformWebhooksKeys } from './keys'+import {+ isWebhookRateLimitError,+ sendTestWebhookEvent,+ type WebhookScopeParams,+} from './platform-webhooks-fetchers'+import type { ResponseError, UseCustomMutationOptions } from '@/types'++export type WebhookEndpointTestVariables = {+ scope: WebhookScopeParams+ id: string+}++async function testEndpoint({ scope, id }: WebhookEndpointTestVariables) {+ return sendTestWebhookEvent(scope, id)+}++type WebhookEndpointTestData = Awaited<ReturnType<typeof testEndpoint>>++export const useWebhookEndpointTestMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<WebhookEndpointTestData, ResponseError, WebhookEndpointTestVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<WebhookEndpointTestData, ResponseError, WebhookEndpointTestVariables>({+ mutationFn: testEndpoint,+ async onSuccess(data, variables, context) {+ // The test delivery lands asynchronously — invalidate so it shows up once it does.+ await queryClient.invalidateQueries({+ queryKey: platformWebhooksKeys.deliveries(variables.scope, variables.id),+ })++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ if (isWebhookRateLimitError(data)) {+ toast.error('Too many test events — wait a minute and try again (limit: 10 per minute).')+ } else {+ toast.error(`Failed to send test event: ${data.message}`)+ }+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/platform-webhooks/platform-webhook-endpoint-update-mutation.ts b/apps/studio/data/platform-webhooks/platform-webhook-endpoint-update-mutation.tsnew file mode 100644index 00000000000..ab9c34a8872--- /dev/null+++ b/apps/studio/data/platform-webhooks/platform-webhook-endpoint-update-mutation.ts@@ -0,0 +1,76 @@+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { platformWebhooksKeys } from './keys'+import { updateWebhookEndpoint, type WebhookScopeParams } from './platform-webhooks-fetchers'+import { toWebhookEndpoint, toWebhookEndpointAttributes } from './platform-webhooks-mappers'+import type {+ UpsertWebhookEndpointInput,+ WebhookEndpoint,+} from '@/components/interfaces/Platform/Webhooks/PlatformWebhooks.types'+import type { ResponseError, UseCustomMutationOptions } from '@/types'++export type WebhookEndpointUpdateVariables = {+ scope: WebhookScopeParams+ id: string+ input: UpsertWebhookEndpointInput+}++async function updateEndpoint({+ scope,+ id,+ input,+}: WebhookEndpointUpdateVariables): Promise<WebhookEndpoint> {+ const attributes = toWebhookEndpointAttributes(input)+ // Edits never rotate the secret here — that's a separate, explicit "Regenerate secret" action.+ const result = await updateWebhookEndpoint(scope, id, {+ ...attributes,+ signing_secret: undefined,+ })+ if (!result?.data) throw new Error('Endpoint was updated but no data was returned')++ // See the comment in platform-webhook-endpoint-create-mutation.ts — `name` isn't+ // persisted by the server, so it's carried through from what the user submitted.+ return { ...toWebhookEndpoint(result.data), name: input.name }+}++type WebhookEndpointUpdateData = Awaited<ReturnType<typeof updateEndpoint>>++export const useWebhookEndpointUpdateMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<+ WebhookEndpointUpdateData,+ ResponseError,+ WebhookEndpointUpdateVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<WebhookEndpointUpdateData, ResponseError, WebhookEndpointUpdateVariables>({+ mutationFn: updateEndpoint,+ async onSuccess(data, variables, context) {+ await Promise.all([+ queryClient.invalidateQueries({+ queryKey: platformWebhooksKeys.endpoints(variables.scope),+ }),+ queryClient.invalidateQueries({+ queryKey: platformWebhooksKeys.endpoint(variables.scope, variables.id),+ }),+ ])++ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to update webhook endpoint: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/platform-webhooks/platform-webhook-endpoints-query.ts b/apps/studio/data/platform-webhooks/platform-webhook-endpoints-query.tsnew file mode 100644index 00000000000..857710df93b--- /dev/null+++ b/apps/studio/data/platform-webhooks/platform-webhook-endpoints-query.ts@@ -0,0 +1,40 @@+import { useQuery } from '@tanstack/react-query'++import { platformWebhooksKeys } from './keys'+import { listWebhookEndpoints, type WebhookScopeParams } from './platform-webhooks-fetchers'+import { toWebhookEndpoint } from './platform-webhooks-mappers'+import type { WebhookEndpoint } from '@/components/interfaces/Platform/Webhooks/PlatformWebhooks.types'+import type { ResponseError, UseCustomQueryOptions } from '@/types'++interface WebhookEndpointsVariables {+ scope: WebhookScopeParams+ limit?: number+ offset?: number+}++async function getWebhookEndpoints(+ { scope, limit, offset }: WebhookEndpointsVariables,+ signal?: AbortSignal+): Promise<WebhookEndpoint[]> {+ const result = await listWebhookEndpoints(scope, { limit, offset }, signal)+ return (result?.data ?? []).map(toWebhookEndpoint)+}++export type WebhookEndpointsData = Awaited<ReturnType<typeof getWebhookEndpoints>>++export const useWebhookEndpointsQuery = <TData = WebhookEndpointsData>(+ variables: WebhookEndpointsVariables,+ {+ enabled = true,+ ...options+ }: UseCustomQueryOptions<WebhookEndpointsData, ResponseError, TData> = {}+) => {+ const { scope, limit, offset } = variables++ return useQuery<WebhookEndpointsData, ResponseError, TData>({+ queryKey: platformWebhooksKeys.endpoints(scope, limit, offset),+ queryFn: ({ signal }) => getWebhookEndpoints({ scope, limit, offset }, signal),+ enabled,+ ...options,+ })+}diff --git a/apps/studio/data/platform-webhooks/platform-webhooks-fetchers.ts b/apps/studio/data/platform-webhooks/platform-webhooks-fetchers.tsnew file mode 100644index 00000000000..3f649323048--- /dev/null+++ b/apps/studio/data/platform-webhooks/platform-webhooks-fetchers.ts@@ -0,0 +1,214 @@+import type { operations } from 'api-types'++import { del, get, handleError, patch, post } from '@/data/fetchers'++export type WebhookScopeParams =+ | { scope: 'organization'; orgSlug: string }+ | { scope: 'project'; projectRef: string }++export type WebhookEventType =+ operations['v2-organizations-slug-webhooks-endpoints-post']['requestBody']['content']['application/json']['data']['attributes']['event_types'][number]['type']++export interface WebhookEndpointAttributesInput {+ url: string+ description?: string | null+ enabled?: boolean+ event_types: { type: WebhookEventType }[]+ custom_headers?: Record<string, string> | null+ signing_secret?: string+}++interface ListPageParams {+ limit?: number+ offset?: number+}++// Every function below is the single place that branches on organization vs project —+// hooks never need to know which URL family they're calling.++export async function listWebhookEndpoints(+ scope: WebhookScopeParams,+ page?: ListPageParams,+ signal?: AbortSignal+) {+ const query = {+ 'page[limit]': page?.limit?.toString(),+ 'page[offset]': page?.offset?.toString(),+ }++ const { data, error } =+ scope.scope === 'organization'+ ? await get('/v2/organizations/{slug}/webhooks/endpoints', {+ params: { path: { slug: scope.orgSlug }, query },+ signal,+ })+ : await get('/v2/projects/{ref}/webhooks/endpoints', {+ params: { path: { ref: scope.projectRef }, query },+ signal,+ })++ if (error) handleError(error)+ return data+}++export async function createWebhookEndpoint(+ scope: WebhookScopeParams,+ attributes: WebhookEndpointAttributesInput & { signing_secret: string }+) {+ const body = { data: { type: 'endpoint' as const, attributes } }++ const { data, error } =+ scope.scope === 'organization'+ ? await post('/v2/organizations/{slug}/webhooks/endpoints', {+ params: { path: { slug: scope.orgSlug } },+ body,+ })+ : await post('/v2/projects/{ref}/webhooks/endpoints', {+ params: { path: { ref: scope.projectRef } },+ body,+ })++ if (error) handleError(error)+ return data+}++export async function updateWebhookEndpoint(+ scope: WebhookScopeParams,+ id: string,+ attributes: WebhookEndpointAttributesInput+) {+ const body = { data: { type: 'endpoint' as const, attributes } }++ const { data, error } =+ scope.scope === 'organization'+ ? await patch('/v2/organizations/{slug}/webhooks/endpoints/{id}', {+ params: { path: { slug: scope.orgSlug, id } },+ body,+ })+ : await patch('/v2/projects/{ref}/webhooks/endpoints/{id}', {+ params: { path: { ref: scope.projectRef, id } },+ body,+ })++ if (error) handleError(error)+ return data+}++export async function regenerateWebhookEndpointSecret(+ scope: WebhookScopeParams,+ id: string,+ signingSecret: string+) {+ const body = {+ data: { type: 'endpoint' as const, attributes: { signing_secret: signingSecret } },+ }++ const { data, error } =+ scope.scope === 'organization'+ ? await patch('/v2/organizations/{slug}/webhooks/endpoints/{id}', {+ params: { path: { slug: scope.orgSlug, id } },+ body,+ })+ : await patch('/v2/projects/{ref}/webhooks/endpoints/{id}', {+ params: { path: { ref: scope.projectRef, id } },+ body,+ })++ if (error) handleError(error)+ return data+}++export async function deleteWebhookEndpoint(scope: WebhookScopeParams, id: string) {+ const { data, error } =+ scope.scope === 'organization'+ ? await del('/v2/organizations/{slug}/webhooks/endpoints/{id}', {+ params: { path: { slug: scope.orgSlug, id } },+ })+ : await del('/v2/projects/{ref}/webhooks/endpoints/{id}', {+ params: { path: { ref: scope.projectRef, id } },+ })++ if (error) handleError(error)+ return data+}++export async function listWebhookDeliveries(+ scope: WebhookScopeParams,+ endpointId: string,+ page?: { size?: number; after?: string; before?: string },+ signal?: AbortSignal+) {+ const query = {+ 'page[size]': page?.size?.toString(),+ 'page[after]': page?.after,+ 'page[before]': page?.before,+ }++ const { data, error } =+ scope.scope === 'organization'+ ? await get('/v2/organizations/{slug}/webhooks/endpoints/{id}/deliveries', {+ params: { path: { slug: scope.orgSlug, id: endpointId }, query },+ signal,+ })+ : await get('/v2/projects/{ref}/webhooks/endpoints/{id}/deliveries', {+ params: { path: { ref: scope.projectRef, id: endpointId }, query },+ signal,+ })++ if (error) handleError(error)+ return data+}++export async function getWebhookDelivery(+ scope: WebhookScopeParams,+ id: string,+ signal?: AbortSignal+) {+ const { data, error } =+ scope.scope === 'organization'+ ? await get('/v2/organizations/{slug}/webhooks/deliveries/{id}', {+ params: { path: { slug: scope.orgSlug, id } },+ signal,+ })+ : await get('/v2/projects/{ref}/webhooks/deliveries/{id}', {+ params: { path: { ref: scope.projectRef, id } },+ signal,+ })++ if (error) handleError(error)+ return data+}++export async function sendTestWebhookEvent(scope: WebhookScopeParams, id: string) {+ const { data, error } =+ scope.scope === 'organization'+ ? await post('/v2/organizations/{slug}/webhooks/endpoints/{id}/test', {+ params: { path: { slug: scope.orgSlug, id } },+ body: {},+ })+ : await post('/v2/projects/{ref}/webhooks/endpoints/{id}/test', {+ params: { path: { ref: scope.projectRef, id } },+ body: {},+ })++ if (error) handleError(error)+ return data+}++// Retry and test-event are rate-limited to 10 requests/60s.+export const isWebhookRateLimitError = (error: { message?: string }) =>+ error.message === 'Rate limit exceeded'++export async function retryWebhookDelivery(scope: WebhookScopeParams, id: string) {+ const { data, error } =+ scope.scope === 'organization'+ ? await post('/v2/organizations/{slug}/webhooks/deliveries/{id}/retry', {+ params: { path: { slug: scope.orgSlug, id } },+ })+ : await post('/v2/projects/{ref}/webhooks/deliveries/{id}/retry', {+ params: { path: { ref: scope.projectRef, id } },+ })++ if (error) handleError(error)+ return data+}diff --git a/apps/studio/data/platform-webhooks/platform-webhooks-mappers.ts b/apps/studio/data/platform-webhooks/platform-webhooks-mappers.tsnew file mode 100644index 00000000000..7850c527f11--- /dev/null+++ b/apps/studio/data/platform-webhooks/platform-webhooks-mappers.ts@@ -0,0 +1,102 @@+import type { operations } from 'api-types'+import * as z from 'zod'++import type { WebhookEndpointAttributesInput, WebhookEventType } from './platform-webhooks-fetchers'+import { PLATFORM_WEBHOOK_EVENT_TYPES } from '@/components/interfaces/Platform/Webhooks/PlatformWebhooks.constants'+import type {+ UpsertWebhookEndpointInput,+ WebhookDelivery,+ WebhookEndpoint,+} from '@/components/interfaces/Platform/Webhooks/PlatformWebhooks.types'++// '*' (subscribe to all) is handled separately by the form's "subscribe all" toggle,+// so it's not part of the selectable catalog, but it's still a value the API accepts.+const webhookEventTypeSchema = z.enum([...PLATFORM_WEBHOOK_EVENT_TYPES, '*'])++const toWebhookEventTypes = (eventTypes: string[]): { type: WebhookEventType }[] =>+ eventTypes+ .map((eventType) => webhookEventTypeSchema.safeParse(eventType))+ .filter((result) => result.success)+ .map((result) => ({ type: result.data }))++const toCustomHeaders = (+ headers: Array<{ key: string; value: string }>+): Record<string, string> | undefined =>+ headers.length > 0+ ? Object.fromEntries(headers.map((header) => [header.key, header.value]))+ : undefined++// The real API has no `name` field on an endpoint — it is never sent here.+// See the comment on `WebhookEndpoint.name` in PlatformWebhooks.types.ts.+export const toWebhookEndpointAttributes = (+ input: UpsertWebhookEndpointInput+): WebhookEndpointAttributesInput => ({+ url: input.url,+ description: input.description || null,+ enabled: input.enabled,+ event_types: toWebhookEventTypes(input.eventTypes),+ custom_headers: toCustomHeaders(input.customHeaders),+ signing_secret: input.signingSecret || undefined,+})++type WebhookEndpointResource =+ operations['v2-organizations-slug-webhooks-endpoints-id-get']['responses'][200]['content']['application/json']['data']++// The single-delivery endpoint — includes the full nested `event` (type + payload).+type WebhookDeliveryResource =+ operations['v2-organizations-slug-webhooks-deliveries-id-get']['responses'][200]['content']['application/json']['data']++// The deliveries-list-for-an-endpoint endpoint — lighter weight, no `event` at all.+type WebhookDeliveryListItemResource =+ operations['v2-organizations-slug-webhooks-endpoints-id-deliveries-get']['responses'][200]['content']['application/json']['data'][number]++// Response → UI direction. The real API never returns a `name` — `name` is left blank+// here; until the backend adds a field for it, there's nowhere to read a saved name+// back from. Flagged with Ali/Paweł as an open product question, not yet resolved.+export const toWebhookEndpoint = (resource: WebhookEndpointResource): WebhookEndpoint => ({+ id: resource.id,+ name: '',+ url: resource.attributes.url,+ description: resource.attributes.description ?? '',+ enabled: resource.attributes.enabled,+ eventTypes: resource.attributes.event_types.map((eventType) => eventType.type),+ customHeaders: Object.entries(resource.attributes.custom_headers ?? {}).map(([key, value]) => ({+ id: key,+ key,+ value,+ })),+ createdBy: resource.attributes.created_by,+ createdAt: resource.attributes.created_at,+})++export const toWebhookDelivery = (+ resource: WebhookDeliveryResource,+ endpointId: string+): WebhookDelivery => ({+ id: resource.id,+ endpointId,+ eventId: resource.attributes.event_id,+ eventType: resource.attributes.event.type,+ eventPayload: resource.attributes.event.payload,+ status: resource.attributes.status,+ responseCode: resource.attributes.response_code,+ responseBody: resource.attributes.response_body,+ responseHeaders: resource.attributes.response_headers,+ attemptAt: resource.attributes.attempt_timestamp,+})++// No `eventType` here — the list endpoint doesn't return it. See the comment on+// `WebhookDelivery.eventType` in PlatformWebhooks.types.ts.+export const toWebhookDeliverySummary = (+ resource: WebhookDeliveryListItemResource,+ endpointId: string+): WebhookDelivery => ({+ id: resource.id,+ endpointId,+ eventId: resource.attributes.event_id,+ status: resource.attributes.status,+ responseCode: resource.attributes.response_code,+ responseBody: resource.attributes.response_body,+ responseHeaders: resource.attributes.response_headers,+ attemptAt: resource.attributes.attempt_timestamp,+})diff --git a/packages/api-types/types/api-v1.d.ts b/packages/api-types/types/api-v1.d.tsindex 3384e1afb06..6ca5d56a6b2 100644--- a/packages/api-types/types/api-v1.d.ts+++ b/packages/api-types/types/api-v1.d.ts@@ -4034,6 +4034,8 @@ export interface components {message: string}PostgresConfigResponse_Output: {+ autovacuum_max_workers?: number+ autovacuum_work_mem?: string/** @description Default unit: s */checkpoint_timeout?: string'cron.log_statement'?: boolean@@ -4067,6 +4069,8 @@ export interface components {max_wal_senders?: numbermax_wal_size?: stringmax_worker_processes?: number+ 'pg_net.batch_size'?: number+ 'pg_stat_statements.max'?: number/** @enum {string} */session_replication_role?: 'origin' | 'replica' | 'local'shared_buffers?: string@@ -4950,6 +4954,8 @@ export interface components {* "statement_timeout": "60000ms"* } */UpdatePostgresConfigBody: {+ autovacuum_max_workers?: number+ autovacuum_work_mem?: string/** @description Default unit: s */checkpoint_timeout?: string'cron.log_statement'?: boolean@@ -4983,6 +4989,8 @@ export interface components {max_wal_senders?: numbermax_wal_size?: stringmax_worker_processes?: number+ 'pg_net.batch_size'?: number+ 'pg_stat_statements.max'?: numberrestart_database?: boolean/** @enum {string} */session_replication_role?: 'origin' | 'replica' | 'local'diff --git a/packages/api-types/types/api-v2.d.ts b/packages/api-types/types/api-v2.d.tsindex e8adbe0699b..d43fd10a505 100644--- a/packages/api-types/types/api-v2.d.ts+++ b/packages/api-types/types/api-v2.d.ts@@ -2573,6 +2573,8 @@ export interface components {}/** @description Postgres parameter overrides. Empty when the project runs entirely on defaults. */postgres_settings: {+ autovacuum_max_workers?: number+ autovacuum_work_mem?: string/** @description Default unit: s */checkpoint_timeout?: stringcron_log_statement?: boolean@@ -2606,6 +2608,8 @@ export interface components {max_wal_senders?: numbermax_wal_size?: stringmax_worker_processes?: number+ pg_net_batch_size?: number+ pg_stat_statements_max?: number/** @enum {string} */session_replication_role?: 'origin' | 'replica' | 'local'shared_buffers?: stringdiff --git a/packages/api-types/types/platform.d.ts b/packages/api-types/types/platform.d.tsindex 1624cd0861e..931fe1051fe 100644--- a/packages/api-types/types/platform.d.ts+++ b/packages/api-types/types/platform.d.ts@@ -5866,19 +5866,7 @@ export interface components {description?: stringname: string/** @enum {string} */- type:- | 'postgres'- | 'bigquery'- | 'clickhouse'- | 'webhook'- | 'datadog'- | 'loki'- | 'sentry'- | 's3'- | 'axiom'- | 'last9'- | 'otlp'- | 'syslog'+ type: 'webhook' | 'datadog' | 'loki' | 'sentry' | 's3' | 'axiom' | 'last9' | 'otlp' | 'syslog'}CreateBucketIndexBody: {/** @enum {string} */@@ -13309,9 +13297,6 @@ export interface components {name?: string/** @enum {string} */type?:- | 'postgres'- | 'bigquery'- | 'clickhouse'| 'webhook'| 'datadog'| 'loki'