import { getHighLevelApi as getHighLevelContractApi, HighLevelApiError, HIGH_LEVEL_OPERATION_DEFINITIONS, highLevelOperation, highLevelOperationInputSchema, highLevelOperationOutputSchema, type HighLevelOperationKey, } from "@automate.ax/integration-contracts/highlevel" import { defineAction, parseRetryAfter, retryableActionError, terminalActionError, } from "../../../automation/actions" import type { IntegrationScopeRequirement } from "../../../automation/integrations" export const HIGH_LEVEL_ACCOUNT = "highlevel" /** * Builds OAuth and private-token alternatives for one HighLevel scope. * * @param requiredScope - HighLevel scope required by the action. */ export function highLevelAccountRequirement( requiredScope: IntegrationScopeRequirement, ) { return { connections: [ { connectionMethodId: "oauth", requiredScope }, { connectionMethodId: "private-integration-token", requiredScope }, ], } as const } /** * Defines one named action backed by a frozen HighLevel OpenAPI operation. * * @param key - Frozen product and operation identifier. * @throws When the manifest has no definition for the operation. */ export function defineHighLevelAction( key: TKey, ) { const definition = HIGH_LEVEL_OPERATION_DEFINITIONS.find( ({ operationId, product }) => `${product}:${operationId}` === key, ) if (!definition) throw new Error(`Unknown HighLevel operation: ${key}`) return defineAction(definition.title) .describe(definition.description) .account( HIGH_LEVEL_ACCOUNT, highLevelAccountRequirement(highLevelOperation(key).requiredScope), ) .input(highLevelOperationInputSchema(key)) .output(highLevelOperationOutputSchema(key)) .retry({ replaySafety: definition.replaySafety }) .handler(async ({ account, input }) => { const api = getHighLevelContractApi(account) try { return await api.operation(key, input) } catch (error) { if (error instanceof HighLevelApiError) { if (error.status === 429) { throw retryableActionError(error, { retryAt: parseRetryAfter(error.retryAfter), }) } if (error.status < 500) throw terminalActionError(error) } throw error } }) }