import { convexTriggerDefinitions } from "@automate.ax/catalog/triggers/convex" import { getConvexEventEndpoint } from "@automate.ax/catalog/triggers/convex" import type { IntegrationAccountReference } from "../../automation/integrations" import { getAutomationInvocationEnvironment, getNextHookLocation, } from "../../automation/runtime" import { createTrigger } from "../../automation/create-trigger" import { subscribe } from "../../automation/subscribe" import type { Signal } from "../../automation/signal-protocol" import type { TriggerEvent } from "@automate.ax/integration-contracts/triggers" export interface ConvexDocumentTriggerOptions { /** Convex project or deployment account binding. */ account?: string | IntegrationAccountReference<"convex"> /** Component path, or an empty string for the root component. */ component?: string /** Deployment reference for project OAuth accounts. Defaults to `prod`. */ deployment?: string /** Convex table name. */ table: string } export interface ConvexEventTriggerOptions { /** Deployment-key account containing the shared webhook secret. */ account?: string | IntegrationAccountReference<"convex"> /** Application-defined event name accepted by this trigger. */ name: string } export type ConvexEventTrigger = Signal< TriggerEvent<"convex.event.received"> > & { readonly endpoint: string } export const onConvexDocumentEvent = createTrigger( convexTriggerDefinitions.convexDocumentEvent, mapDocumentOptions, ) export const onConvexDocumentCreated = createTrigger( convexTriggerDefinitions.convexDocumentCreated, mapDocumentOptions, ) export const onConvexDocumentUpdated = createTrigger( convexTriggerDefinitions.convexDocumentUpdated, mapDocumentOptions, ) export const onConvexDocumentDeleted = createTrigger( convexTriggerDefinitions.convexDocumentDeleted, mapDocumentOptions, ) /** * Starts an automation for one explicitly emitted, signed Convex event. * * @param options - Static account binding and semantic event name. * @throws When declared outside an automation invocation. */ export function onConvexEvent( options: ConvexEventTriggerOptions, ): ConvexEventTrigger { const environment = getAutomationInvocationEnvironment() const location = getNextHookLocation() if (!environment || !location) { throw new Error( "Convex event triggers must be declared inside an automation invocation.", ) } return subscribe(convexTriggerDefinitions.convexEvent, options, { endpoint: getConvexEventEndpoint({ ...environment, hookSlot: location.slot, scopePath: location.scopePath, }), }) } /** * Maps public document options to the canonical trigger configuration. * * @param options - Public account and document scope. */ function mapDocumentOptions(options: ConvexDocumentTriggerOptions) { return { account: options.account, component: options.component ?? "", deployment: options.deployment ?? "prod", table: options.table, } }