AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(facebook-leads): add AI actions and output schemas (#16209)
Kishan Parmar072e24eda850
diff --git a/packages/pieces/community/facebook-leads/package.json b/packages/pieces/community/facebook-leads/package.jsonindex 15d06b73b2e..558f5a8f1b9 100644--- a/packages/pieces/community/facebook-leads/package.json+++ b/packages/pieces/community/facebook-leads/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-facebook-leads",- "version": "0.3.7",+ "version": "0.4.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","scripts": {diff --git a/packages/pieces/community/facebook-leads/src/index.ts b/packages/pieces/community/facebook-leads/src/index.tsindex 8f0ac1bb8ba..bb5f0f321ee 100644--- a/packages/pieces/community/facebook-leads/src/index.ts+++ b/packages/pieces/community/facebook-leads/src/index.ts@@ -1,20 +1,30 @@-import { createPiece } from '@activepieces/pieces-framework';-import { PieceCategory } from '@activepieces/pieces-framework';-import { newLead } from './lib/triggers/new-lead';-import { facebookLeadsAuth } from './lib/auth';import crypto from 'node:crypto';+import { createCustomApiCallAction } from '@activepieces/pieces-common';+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';++import { facebookLeadsAiActions } from './lib/actions/ai';+import { facebookLeadsAuth } from './lib/auth';+import { facebookLeadsClient } from './lib/common/client';+import { newLeadTrigger } from './lib/triggers/new-lead';export const facebookLeads = createPiece({displayName: 'Facebook Leads',description: 'Capture leads from Facebook',- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/facebook.png',authors: ['kishanprmr', 'MoShizzle', 'khaledmashaly', 'abuaboud', 'AbdulTheActivePiecer'],categories: [PieceCategory.MARKETING],auth: facebookLeadsAuth,- actions: [],- triggers: [newLead],+ actions: [+ ...facebookLeadsAiActions,+ createCustomApiCallAction({+ auth: facebookLeadsAuth,+ baseUrl: () => facebookLeadsClient.baseUrl(),+ authMapping: async (auth) => ({ Authorization: `Bearer ${auth.access_token}` }),+ }),+ ],+ triggers: [newLeadTrigger],events: {parseAndReply: (context) => {const payload = context.payload;diff --git a/packages/pieces/community/facebook-leads/src/lib/actions/ai/create-lead-form.ts b/packages/pieces/community/facebook-leads/src/lib/actions/ai/create-lead-form.tsnew file mode 100644index 00000000000..392e919a86e--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/actions/ai/create-lead-form.ts@@ -0,0 +1,88 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { facebookLeadsAuth } from '../../auth';+import { facebookLeadsAiProps } from '../../common/ai-props';+import { facebookLeadsApi } from '../../common/api';+import { facebookLeadsCreateLeadFormOutputSchema } from '../../output-schemas';++export const createLeadFormAction = createAction({+ auth: facebookLeadsAuth,+ name: 'facebook_leads_create_lead_form',+ outputSchema: facebookLeadsCreateLeadFormOutputSchema,+ displayName: 'Create Lead Form',+ description: 'Creates a lead form on a Facebook Page.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a lead form (instant form) on a Facebook Page and returns its ID. A published form cannot be edited or deleted afterwards, only archived with Update Lead Form Status. The Page must have accepted the Lead Ads terms.',+ idempotent: false,+ },+ props: {+ pageId: facebookLeadsAiProps.pageId({ required: true }),+ name: Property.ShortText({+ displayName: 'Form Name',+ description: 'Internal name of the form, shown in Ads Manager.',+ required: true,+ }),+ questions: Property.Json({+ displayName: 'Questions',+ description:+ 'JSON array of questions. Standard fields only need a type, e.g. [{"type":"FULL_NAME"},{"type":"EMAIL"},{"type":"PHONE"}]. Custom questions use {"type":"CUSTOM","key":"budget","label":"What is your budget?"}, with "options":[{"key":"low","value":"Under $1k"}] for multiple choice.',+ required: true,+ }),+ privacyPolicyUrl: Property.ShortText({+ displayName: 'Privacy Policy URL',+ description: 'Link to the advertiser privacy policy. Required by Facebook.',+ required: true,+ }),+ privacyPolicyLinkText: Property.ShortText({+ displayName: 'Privacy Policy Link Text',+ description: 'Text of the privacy policy link. Defaults to "Privacy Policy".',+ required: false,+ }),+ followUpActionUrl: Property.ShortText({+ displayName: 'Follow-up URL',+ description:+ 'Website the "thank you" screen links to after submission. Required by Facebook.',+ required: true,+ }),+ locale: Property.ShortText({+ displayName: 'Locale',+ description: 'Form language, e.g. "EN_US" or "DE_DE". Defaults to the Page locale.',+ required: false,+ }),+ },+ async run(context) {+ const {+ pageId,+ name,+ questions,+ privacyPolicyUrl,+ privacyPolicyLinkText,+ followUpActionUrl,+ locale,+ } = context.propsValue;+ if (!Array.isArray(questions) || questions.length === 0) {+ throw new Error('Questions must be a non-empty JSON array.');+ }+ const pageAccessToken = await facebookLeadsApi.getPageAccessToken({+ pageId,+ accessToken: context.auth.access_token,+ });+ return await facebookLeadsApi.createLeadForm({+ pageId,+ accessToken: pageAccessToken,+ body: {+ name,+ questions,+ privacy_policy: {+ url: privacyPolicyUrl,+ link_text: privacyPolicyLinkText ?? 'Privacy Policy',+ },+ follow_up_action_url: followUpActionUrl,+ ...(locale ? { locale } : {}),+ },+ });+ },+});diff --git a/packages/pieces/community/facebook-leads/src/lib/actions/ai/get-current-user.ts b/packages/pieces/community/facebook-leads/src/lib/actions/ai/get-current-user.tsnew file mode 100644index 00000000000..361d4b50940--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/actions/ai/get-current-user.ts@@ -0,0 +1,24 @@+import { createAction } from '@activepieces/pieces-framework';++import { facebookLeadsAuth } from '../../auth';+import { facebookLeadsApi } from '../../common/api';+import { facebookLeadsGetCurrentUserOutputSchema } from '../../output-schemas';++export const getCurrentUserAction = createAction({+ auth: facebookLeadsAuth,+ name: 'facebook_leads_get_current_user',+ outputSchema: facebookLeadsGetCurrentUserOutputSchema,+ displayName: 'Get Current User',+ description: 'Gets the Facebook user the connection belongs to.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns the id and name of the Facebook user behind this connection. Use it to confirm which account is connected; use List Pages to see the Pages it manages.',+ idempotent: true,+ },+ props: {},+ async run(context) {+ return await facebookLeadsApi.getMe({ accessToken: context.auth.access_token });+ },+});diff --git a/packages/pieces/community/facebook-leads/src/lib/actions/ai/get-lead-form.ts b/packages/pieces/community/facebook-leads/src/lib/actions/ai/get-lead-form.tsnew file mode 100644index 00000000000..e05978b2e87--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/actions/ai/get-lead-form.ts@@ -0,0 +1,30 @@+import { createAction } from '@activepieces/pieces-framework';++import { facebookLeadsAuth } from '../../auth';+import { facebookLeadsAiProps } from '../../common/ai-props';+import { facebookLeadsApi } from '../../common/api';+import { facebookLeadsGetLeadFormOutputSchema } from '../../output-schemas';++export const getLeadFormAction = createAction({+ auth: facebookLeadsAuth,+ name: 'facebook_leads_get_lead_form',+ outputSchema: facebookLeadsGetLeadFormOutputSchema,+ displayName: 'Get Lead Form',+ description: 'Gets a lead form, including its questions.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns one lead form by ID: name, status, locale, lead and expired-lead counts, its questions (the field keys a lead answers), privacy policy URL and the Page it belongs to. Use it to learn which field keys the leads of a form carry.',+ idempotent: true,+ },+ props: {+ formId: facebookLeadsAiProps.formId({ required: true }),+ },+ async run(context) {+ return await facebookLeadsApi.getLeadForm({+ formId: context.propsValue.formId,+ accessToken: context.auth.access_token,+ });+ },+});diff --git a/packages/pieces/community/facebook-leads/src/lib/actions/ai/get-lead.ts b/packages/pieces/community/facebook-leads/src/lib/actions/ai/get-lead.tsnew file mode 100644index 00000000000..6ac65eb2b1e--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/actions/ai/get-lead.ts@@ -0,0 +1,35 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { facebookLeadsAuth } from '../../auth';+import { facebookLeadsApi } from '../../common/api';+import { facebookLeadsUtils } from '../../common/utils';+import { facebookLeadsGetLeadOutputSchema } from '../../output-schemas';++export const getLeadAction = createAction({+ auth: facebookLeadsAuth,+ name: 'facebook_leads_get_lead',+ outputSchema: facebookLeadsGetLeadOutputSchema,+ displayName: 'Get Lead',+ description: 'Gets one lead by ID.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description:+ 'Returns one lead by ID with its answers keyed by question, its form and its ad, ad set and campaign. Lead IDs come from List Leads or the New Lead trigger. Leads older than 90 days are no longer returned by Facebook.',+ idempotent: true,+ },+ props: {+ leadId: Property.ShortText({+ displayName: 'Lead ID',+ description: 'Lead ID, e.g. "987654321098765". Use List Leads to find it.',+ required: true,+ }),+ },+ async run(context) {+ const lead = await facebookLeadsApi.getLead({+ leadId: context.propsValue.leadId,+ accessToken: context.auth.access_token,+ });+ return facebookLeadsUtils.transformLeadData({ lead });+ },+});diff --git a/packages/pieces/community/facebook-leads/src/lib/actions/ai/index.ts b/packages/pieces/community/facebook-leads/src/lib/actions/ai/index.tsnew file mode 100644index 00000000000..96244f675cf--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/actions/ai/index.ts@@ -0,0 +1,19 @@+import { createLeadFormAction } from './create-lead-form';+import { getCurrentUserAction } from './get-current-user';+import { getLeadAction } from './get-lead';+import { getLeadFormAction } from './get-lead-form';+import { listLeadFormsAction } from './list-lead-forms';+import { listLeadsAction } from './list-leads';+import { listPagesAction } from './list-pages';+import { updateLeadFormStatusAction } from './update-lead-form-status';++export const facebookLeadsAiActions = [+ getCurrentUserAction,+ listPagesAction,+ listLeadFormsAction,+ getLeadFormAction,+ createLeadFormAction,+ updateLeadFormStatusAction,+ listLeadsAction,+ getLeadAction,+];diff --git a/packages/pieces/community/facebook-leads/src/lib/actions/ai/list-lead-forms.ts b/packages/pieces/community/facebook-leads/src/lib/actions/ai/list-lead-forms.tsnew file mode 100644index 00000000000..8576e4c9359--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/actions/ai/list-lead-forms.ts@@ -0,0 +1,47 @@+import { createAction } from '@activepieces/pieces-framework';++import { facebookLeadsAuth } from '../../auth';+import { facebookLeadsAiProps } from '../../common/ai-props';+import { facebookLeadsApi } from '../../common/api';+import { facebookLeadsListLeadFormsOutputSchema } from '../../output-schemas';++export const listLeadFormsAction = createAction({+ auth: facebookLeadsAuth,+ name: 'facebook_leads_list_lead_forms',+ outputSchema: facebookLeadsListLeadFormsOutputSchema,+ displayName: 'List Lead Forms',+ description: 'Lists the lead forms of a Facebook Page.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists every lead form (instant form) on a Facebook Page, active and archived, with its id, name, status, locale, creation time and lead count. Use it to find the Form ID that List Leads and Get Lead Form need.',+ idempotent: true,+ },+ props: {+ pageId: facebookLeadsAiProps.pageId({ required: true }),+ },+ async run(context) {+ const { pageId } = context.propsValue;+ const pageAccessToken = await facebookLeadsApi.getPageAccessToken({+ pageId,+ accessToken: context.auth.access_token,+ });+ const forms = await facebookLeadsApi.listLeadForms({+ pageId,+ accessToken: pageAccessToken,+ detailed: true,+ });+ return {+ forms: forms.map((form) => ({+ id: form.id,+ name: form.name,+ status: form.status,+ locale: form.locale ?? null,+ created_time: form.created_time ?? null,+ leads_count: form.leads_count ?? null,+ })),+ count: forms.length,+ };+ },+});diff --git a/packages/pieces/community/facebook-leads/src/lib/actions/ai/list-leads.ts b/packages/pieces/community/facebook-leads/src/lib/actions/ai/list-leads.tsnew file mode 100644index 00000000000..4d82e024ae4--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/actions/ai/list-leads.ts@@ -0,0 +1,92 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { facebookLeadsAuth } from '../../auth';+import { facebookLeadsAiProps } from '../../common/ai-props';+import { facebookLeadsApi } from '../../common/api';+import { facebookLeadsUtils } from '../../common/utils';+import { facebookLeadsListLeadsOutputSchema } from '../../output-schemas';++const DEFAULT_LIMIT = 25;+const MAX_LIMIT = 100;++export const listLeadsAction = createAction({+ auth: facebookLeadsAuth,+ name: 'facebook_leads_list_leads',+ outputSchema: facebookLeadsListLeadsOutputSchema,+ displayName: 'List Leads',+ description: 'Lists the leads submitted to a lead form.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists one page of leads submitted to a lead form, newest first, each with its answers keyed by question and its ad/campaign context. Filter by submission time with Created After / Created Before, and pass Next Cursor back as Cursor to get the next page. Facebook only returns leads from the last 90 days, and there is no search by email or phone: list and match the answers instead.',+ idempotent: true,+ },+ props: {+ formId: facebookLeadsAiProps.formId({ required: true }),+ createdAfter: Property.DateTime({+ displayName: 'Created After',+ description: 'Only leads submitted after this time (ISO 8601).',+ required: false,+ }),+ createdBefore: Property.DateTime({+ displayName: 'Created Before',+ description: 'Only leads submitted before this time (ISO 8601).',+ required: false,+ }),+ limit: Property.Number({+ displayName: 'Limit',+ description: `Leads per page (1-${MAX_LIMIT}). Defaults to ${DEFAULT_LIMIT}.`,+ required: false,+ }),+ cursor: Property.ShortText({+ displayName: 'Cursor',+ description: 'Next Cursor from a previous List Leads call, to get the next page.',+ required: false,+ }),+ },+ async run(context) {+ const { formId, createdAfter, createdBefore, limit, cursor } = context.propsValue;+ const filters = [+ ...(createdAfter+ ? [+ {+ field: 'time_created',+ operator: 'GREATER_THAN',+ value: toUnixSeconds({ value: createdAfter }),+ },+ ]+ : []),+ ...(createdBefore+ ? [+ {+ field: 'time_created',+ operator: 'LESS_THAN',+ value: toUnixSeconds({ value: createdBefore }),+ },+ ]+ : []),+ ];+ const response = await facebookLeadsApi.listFormLeadsPage({+ formId,+ accessToken: context.auth.access_token,+ limit: Math.min(Math.max(Math.floor(limit ?? DEFAULT_LIMIT), 1), MAX_LIMIT),+ after: cursor,+ filtering: filters.length > 0 ? JSON.stringify(filters) : undefined,+ });+ const leads = response.data.map((lead) => facebookLeadsUtils.transformLeadData({ lead }));+ return {+ leads,+ count: leads.length,+ next_cursor: response.paging?.next ? response.paging.cursors?.after ?? null : null,+ };+ },+});++function toUnixSeconds({ value }: { value: string }): number {+ const time = Date.parse(value);+ if (Number.isNaN(time)) {+ throw new Error(`Invalid date: ${value}`);+ }+ return Math.floor(time / 1000);+}diff --git a/packages/pieces/community/facebook-leads/src/lib/actions/ai/list-pages.ts b/packages/pieces/community/facebook-leads/src/lib/actions/ai/list-pages.tsnew file mode 100644index 00000000000..1da06aee06c--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/actions/ai/list-pages.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';++import { facebookLeadsAuth } from '../../auth';+import { facebookLeadsApi } from '../../common/api';+import { facebookLeadsListPagesOutputSchema } from '../../output-schemas';++export const listPagesAction = createAction({+ auth: facebookLeadsAuth,+ name: 'facebook_leads_list_pages',+ outputSchema: facebookLeadsListPagesOutputSchema,+ displayName: 'List Pages',+ description: 'Lists the Facebook Pages the connected user manages.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists every Facebook Page the connected user manages, with its id, name, category and the tasks the user may perform on it. Use it to find the Page ID that List Lead Forms and Create Lead Form need.',+ idempotent: true,+ },+ props: {},+ async run(context) {+ const pages = await facebookLeadsApi.listPages({ accessToken: context.auth.access_token });+ return {+ pages: pages.map((page) => ({+ id: page.id,+ name: page.name,+ category: page.category ?? null,+ tasks: page.tasks ?? [],+ })),+ count: pages.length,+ };+ },+});diff --git a/packages/pieces/community/facebook-leads/src/lib/actions/ai/update-lead-form-status.ts b/packages/pieces/community/facebook-leads/src/lib/actions/ai/update-lead-form-status.tsnew file mode 100644index 00000000000..41a3d573312--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/actions/ai/update-lead-form-status.ts@@ -0,0 +1,55 @@+import { createAction, Property } from '@activepieces/pieces-framework';++import { facebookLeadsAuth } from '../../auth';+import { facebookLeadsAiProps } from '../../common/ai-props';+import { facebookLeadsApi } from '../../common/api';+import { facebookLeadsUpdateLeadFormStatusOutputSchema } from '../../output-schemas';++import type { FacebookLeadsFormStatus } from '../../common/types';++export const updateLeadFormStatusAction = createAction({+ auth: facebookLeadsAuth,+ name: 'facebook_leads_update_lead_form_status',+ outputSchema: facebookLeadsUpdateLeadFormStatusOutputSchema,+ displayName: 'Update Lead Form Status',+ description: 'Archives or reactivates a lead form.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Sets a lead form to ARCHIVED (stops it from being used in new ads) or back to ACTIVE. Facebook has no way to delete or edit a form; archiving is the reversible way to retire one. Its existing leads stay readable.',+ idempotent: true,+ },+ props: {+ pageId: facebookLeadsAiProps.pageId({+ required: true,+ description: 'ID of the Facebook Page that owns the form. Use List Pages to find it.',+ }),+ formId: facebookLeadsAiProps.formId({ required: true }),+ status: Property.StaticDropdown<FacebookLeadsFormStatus, true>({+ displayName: 'Status',+ description: 'ARCHIVED to retire the form, ACTIVE to reactivate it.',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Archived', value: 'ARCHIVED' },+ { label: 'Active', value: 'ACTIVE' },+ ],+ },+ }),+ },+ async run(context) {+ const { pageId, formId, status } = context.propsValue;+ const pageAccessToken = await facebookLeadsApi.getPageAccessToken({+ pageId,+ accessToken: context.auth.access_token,+ });+ const response = await facebookLeadsApi.updateLeadFormStatus({+ formId,+ accessToken: pageAccessToken,+ status,+ });+ return { form_id: formId, status, success: response.success };+ },+});diff --git a/packages/pieces/community/facebook-leads/src/lib/common/ai-props.ts b/packages/pieces/community/facebook-leads/src/lib/common/ai-props.tsnew file mode 100644index 00000000000..aa6766e87e4--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/common/ai-props.ts@@ -0,0 +1,21 @@+import { Property } from '@activepieces/pieces-framework';++import type { PropParams } from './props';++function pageId<R extends boolean>({+ required,+ displayName = 'Page ID',+ description = 'Facebook Page ID, e.g. "104857839123456". Use List Pages to find it.',+}: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++function formId<R extends boolean>({+ required,+ displayName = 'Form ID',+ description = 'Lead form ID, e.g. "1234567890123456". Use List Lead Forms to find it.',+}: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++export const facebookLeadsAiProps = { pageId, formId };diff --git a/packages/pieces/community/facebook-leads/src/lib/common/api.ts b/packages/pieces/community/facebook-leads/src/lib/common/api.tsnew file mode 100644index 00000000000..0549a2eb44e--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/common/api.ts@@ -0,0 +1,218 @@+import { HttpMethod } from '@activepieces/pieces-common';++import { facebookLeadsClient } from './client';++import type {+ FacebookLeadsForm,+ FacebookLeadsFormStatus,+ FacebookLeadsLead,+ FacebookLeadsPage,+ FacebookLeadsPaginatedResponse,+ FacebookLeadsUser,+} from './types';++async function getMe({ accessToken }: { accessToken: string }): Promise<FacebookLeadsUser> {+ return await facebookLeadsClient.request<FacebookLeadsUser>({+ method: HttpMethod.GET,+ path: '/me',+ query: { access_token: accessToken, fields: 'id,name' },+ });+}++async function listPages({ accessToken }: { accessToken: string }): Promise<FacebookLeadsPage[]> {+ return await facebookLeadsClient.paginate<FacebookLeadsPage>({+ path: '/me/accounts',+ query: { access_token: accessToken },+ });+}++async function getPageAccessToken({+ pageId,+ accessToken,+}: {+ pageId: string;+ accessToken: string;+}): Promise<string> {+ const response = await facebookLeadsClient.request<{ id: string; access_token?: string }>({+ method: HttpMethod.GET,+ path: `/${pageId}`,+ query: { access_token: accessToken, fields: 'access_token' },+ });+ if (!response.access_token) {+ throw new Error(+ `No Page access token for page ${pageId}. Make sure the connected user manages this Page.`,+ );+ }+ return response.access_token;+}++async function listLeadForms({+ pageId,+ accessToken,+ detailed,+}: {+ pageId: string;+ accessToken: string;+ detailed?: boolean;+}): Promise<FacebookLeadsForm[]> {+ return await facebookLeadsClient.paginate<FacebookLeadsForm>({+ path: `/${pageId}/leadgen_forms`,+ query: { access_token: accessToken, ...(detailed ? { fields: FORM_LIST_FIELDS } : {}) },+ });+}++async function getPageForms({+ pageId,+ accessToken,+}: {+ pageId: string;+ accessToken: string;+}): Promise<FacebookLeadsForm[]> {+ const response = await facebookLeadsClient.request<+ FacebookLeadsPaginatedResponse<FacebookLeadsForm>+ >({+ method: HttpMethod.GET,+ path: `/${pageId}/leadgen_forms`,+ query: { access_token: accessToken },+ });+ return response.data;+}++async function getLeadForm({+ formId,+ accessToken,+}: {+ formId: string;+ accessToken: string;+}): Promise<FacebookLeadsForm> {+ return await facebookLeadsClient.request<FacebookLeadsForm>({+ method: HttpMethod.GET,+ path: `/${formId}`,+ query: { access_token: accessToken, fields: FORM_DETAIL_FIELDS },+ });+}++async function createLeadForm({+ pageId,+ accessToken,+ body,+}: {+ pageId: string;+ accessToken: string;+ body: Record<string, unknown>;+}): Promise<{ id: string }> {+ return await facebookLeadsClient.request<{ id: string }>({+ method: HttpMethod.POST,+ path: `/${pageId}/leadgen_forms`,+ query: { access_token: accessToken },+ body,+ });+}++async function updateLeadFormStatus({+ formId,+ accessToken,+ status,+}: {+ formId: string;+ accessToken: string;+ status: FacebookLeadsFormStatus;+}): Promise<{ success: boolean }> {+ return await facebookLeadsClient.request<{ success: boolean }>({+ method: HttpMethod.POST,+ path: `/${formId}`,+ query: { access_token: accessToken },+ body: { status },+ });+}++async function subscribePageToApp({+ pageId,+ accessToken,+}: {+ pageId: string;+ accessToken: string;+}): Promise<void> {+ await facebookLeadsClient.request<unknown>({+ method: HttpMethod.POST,+ path: `/${pageId}/subscribed_apps`,+ body: {+ access_token: accessToken,+ subscribed_fields: ['leadgen'],+ },+ });+}++async function getLead({+ leadId,+ accessToken,+}: {+ leadId: string;+ accessToken: string;+}): Promise<FacebookLeadsLead> {+ return await facebookLeadsClient.request<FacebookLeadsLead>({+ method: HttpMethod.GET,+ path: `/${leadId}`,+ query: { access_token: accessToken, fields: LEAD_FIELDS },+ });+}++async function listFormLeadsPage({+ formId,+ accessToken,+ limit,+ after,+ filtering,+}: {+ formId: string;+ accessToken: string;+ limit?: number;+ after?: string;+ filtering?: string;+}): Promise<FacebookLeadsPaginatedResponse<FacebookLeadsLead>> {+ return await facebookLeadsClient.request<FacebookLeadsPaginatedResponse<FacebookLeadsLead>>({+ method: HttpMethod.GET,+ path: `/${formId}/leads`,+ query: {+ access_token: accessToken,+ fields: LEAD_FIELDS,+ ...(limit !== undefined ? { limit: String(limit) } : {}),+ ...(after ? { after } : {}),+ ...(filtering ? { filtering } : {}),+ },+ });+}++async function listFormLeads({+ formId,+ accessToken,+}: {+ formId: string;+ accessToken: string;+}): Promise<FacebookLeadsLead[]> {+ const response = await listFormLeadsPage({ formId, accessToken });+ return response.data;+}++export const facebookLeadsApi = {+ getMe,+ listPages,+ getPageAccessToken,+ listLeadForms,+ getPageForms,+ getLeadForm,+ createLeadForm,+ updateLeadFormStatus,+ subscribePageToApp,+ getLead,+ listFormLeadsPage,+ listFormLeads,+};++const LEAD_FIELDS =+ 'field_data,created_time,ad_id,ad_name,adset_id,adset_name,campaign_id,campaign_name,form_id,platform';++const FORM_LIST_FIELDS = 'id,name,status,locale,created_time,leads_count';++const FORM_DETAIL_FIELDS =+ 'id,name,status,locale,created_time,leads_count,expired_leads_count,questions,privacy_policy_url,follow_up_action_url,page';diff --git a/packages/pieces/community/facebook-leads/src/lib/common/client.ts b/packages/pieces/community/facebook-leads/src/lib/common/client.tsnew file mode 100644index 00000000000..77cdd94be52--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/common/client.ts@@ -0,0 +1,50 @@+import { HttpMethod, httpClient, QueryParams } from '@activepieces/pieces-common';++import type { FacebookLeadsPaginatedResponse } from './types';++function baseUrl(): string {+ return BASE_URL;+}++async function request<T>({ method, path, query, body }: RequestParams): Promise<T> {+ const response = await httpClient.sendRequest<T>({+ method,+ url: `${BASE_URL}${path}`,+ queryParams: query,+ body,+ });+ return response.body;+}++async function paginate<T>({ path, query }: PaginateParams): Promise<T[]> {+ const items: T[] = [];+ let url: string | null = `${BASE_URL}${path}`;+ while (url) {+ const response: { body: FacebookLeadsPaginatedResponse<T> } = await httpClient.sendRequest<+ FacebookLeadsPaginatedResponse<T>+ >({+ method: HttpMethod.GET,+ url,+ queryParams: query,+ });+ items.push(...(response.body.data ?? []));+ url = response.body.paging?.next ?? null;+ }+ return items;+}++export const facebookLeadsClient = { baseUrl, request, paginate };++const BASE_URL = 'https://graph.facebook.com';++type RequestParams = {+ method: HttpMethod;+ path: string;+ query?: QueryParams;+ body?: unknown;+};++type PaginateParams = {+ path: string;+ query?: QueryParams;+};diff --git a/packages/pieces/community/facebook-leads/src/lib/common/index.ts b/packages/pieces/community/facebook-leads/src/lib/common/index.tsdeleted file mode 100644index f334771839d..00000000000--- a/packages/pieces/community/facebook-leads/src/lib/common/index.ts+++ /dev/null@@ -1,215 +0,0 @@-import { DropdownOption, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';-import { HttpRequest, HttpMethod, httpClient } from '@activepieces/pieces-common';-import {- FacebookForm,- FacebookLead,- FacebookPage,- FacebookPageDropdown,- FacebookPaginatedResponse,-} from './types';-import { facebookLeadsAuth } from '../auth';--export const facebookLeadsCommon = {- baseUrl: 'https://graph.facebook.com',- page: Property.Dropdown({- auth: facebookLeadsAuth,- displayName: 'Page',- required: true,- refreshers: [],- options: async ({ auth }) => {- if (!auth) {- return {- disabled: true,- options: [],- placeholder: 'Connect your account first.',- };- }-- try {- const authValue = auth as OAuth2PropertyValue;-- const options: DropdownOption<FacebookPageDropdown>[] = [];-- let nextUrl: string | null = `${facebookLeadsCommon.baseUrl}/me/accounts`;-- do {- const response = await httpClient.sendRequest({- method: HttpMethod.GET,- url: nextUrl,- queryParams: {- access_token: authValue.access_token,- },- });-- const { data, paging } = response.body as FacebookPaginatedResponse<FacebookPage>;-- const items = data ?? [];- for (const page of items) {- options.push({- label: page.name,- value: {- id: page.id,- accessToken: page.access_token,- },- });- }-- nextUrl = paging?.next ?? null;- } while (nextUrl);-- return {- disabled: false,- options,- };- } catch (e) {- return {- disabled: true,- options: [],- placeholder: 'Error occured while fetching pages.',- };- }- },- }),- form: Property.Dropdown({- auth: facebookLeadsAuth,- displayName: 'Form',- required: false,- refreshers: ['page'],- options: async ({ page }) => {- if (!page) {- return {- disabled: true,- options: [],- placeholder: 'Select page first.',- };- }-- try {- const pageDeatils = page as {- id: string;- accessToken: string;- };-- const options: DropdownOption<string>[] = [- {- label: 'All Forms (Default)',- value: 'all',- },- ];-- let nextUrl:- | string- | null = `${facebookLeadsCommon.baseUrl}/${pageDeatils.id}/leadgen_forms`;-- do {- const response = await httpClient.sendRequest({- method: HttpMethod.GET,- url: nextUrl,- queryParams: {- access_token: pageDeatils.accessToken,- },- });-- const { data, paging } = response.body as FacebookPaginatedResponse<FacebookForm>;-- const items = data ?? [];- for (const form of items) {- options.push({- label: form.name,- value: form.id,- });- }-- nextUrl = paging?.next ?? null;- } while (nextUrl);-- return {- disabled: false,- options,- };- } catch (e) {- return {- disabled: true,- options: [],- placeholder: 'Error occured while fetching forms.',- };- }- },- }),-- subscribePageToApp: async (pageId: any, accessToken: string) => {- const request: HttpRequest = {- method: HttpMethod.POST,- url: `${facebookLeadsCommon.baseUrl}/${pageId}/subscribed_apps`,- body: {- access_token: accessToken,- subscribed_fields: ['leadgen'],- },- };-- await httpClient.sendRequest(request);- },-- getPageForms: async (pageId: string, accessToken: string) => {- const request: HttpRequest = {- method: HttpMethod.GET,- url: `${facebookLeadsCommon.baseUrl}/${pageId}/leadgen_forms`,- queryParams: {- access_token: accessToken,- },- };-- const response = await httpClient.sendRequest(request);- return response.body.data;- },-- getLeadDetails: async (leadId: string, accessToken: string) => {- const response = await httpClient.sendRequest<FacebookLead>({- method: HttpMethod.GET,- url: `${facebookLeadsCommon.baseUrl}/${leadId}`,- queryParams: {- access_token: accessToken,- fields:- 'field_data,created_time,ad_id,ad_name,adset_id,adset_name,campaign_id,campaign_name,form_id,platform',- },- });-- return response.body;- },-- loadSampleData: async (formId: string, accessToken: string) => {- const response = await httpClient.sendRequest<FacebookPaginatedResponse<FacebookLead>>({- method: HttpMethod.GET,- url: `${facebookLeadsCommon.baseUrl}/${formId}/leads`,- queryParams: {- access_token: accessToken,- fields:- 'field_data,created_time,ad_id,ad_name,adset_id,adset_name,campaign_id,campaign_name,form_id,platform',- },- });-- return response.body;- },-- transformLeadData: (leadData: FacebookLead) => {- return {- lead_id: leadData.id,- form_id: leadData.form_id,- platform: leadData.platform,- ad_id: leadData.ad_id,- ad_name: leadData.ad_name,- adset_id: leadData.adset_id,- adset_name: leadData.adset_name,- campaign_id: leadData.campaign_id,- campaign_name: leadData.campaign_name,- created_time: leadData.created_time,- data: leadData.field_data.reduce(- (acc, field) => ({- ...acc,- [field.name]: field.values && field.values.length > 0 ? field.values[0] : null,- }),- {},- ),- };- },-};diff --git a/packages/pieces/community/facebook-leads/src/lib/common/props.ts b/packages/pieces/community/facebook-leads/src/lib/common/props.tsnew file mode 100644index 00000000000..7e7c0dffd72--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/common/props.ts@@ -0,0 +1,86 @@+import { DropdownState, Property } from '@activepieces/pieces-framework';++import { facebookLeadsAuth } from '../auth';+import { facebookLeadsApi } from './api';++import type { FacebookLeadsPageDropdown } from './types';++function page<R extends boolean>({ required, displayName = 'Page', description }: PropParams<R>) {+ return Property.Dropdown<FacebookLeadsPageDropdown, R, typeof facebookLeadsAuth>({+ auth: facebookLeadsAuth,+ displayName,+ description,+ required,+ refreshers: [],+ options: async ({ auth }) => {+ if (!auth) {+ return disabledOptions({ placeholder: 'Connect your account first.' });+ }+ try {+ const pages = await facebookLeadsApi.listPages({ accessToken: auth.access_token });+ return {+ disabled: false,+ options: pages.map((page) => ({+ label: page.name,+ value: { id: page.id, accessToken: page.access_token },+ })),+ };+ } catch (e) {+ return disabledOptions({ placeholder: 'Error occured while fetching pages.' });+ }+ },+ });+}++function form<R extends boolean>({ required, displayName = 'Form', description }: PropParams<R>) {+ return Property.Dropdown<string, R, typeof facebookLeadsAuth>({+ auth: facebookLeadsAuth,+ displayName,+ description,+ required,+ refreshers: ['page'],+ options: async ({ page }) => {+ if (!isPageDropdownValue(page)) {+ return disabledOptions({ placeholder: 'Select page first.' });+ }+ try {+ const forms = await facebookLeadsApi.listLeadForms({+ pageId: page.id,+ accessToken: page.accessToken,+ });+ return {+ disabled: false,+ options: [+ { label: 'All Forms (Default)', value: 'all' },+ ...forms.map((form) => ({ label: form.name, value: form.id })),+ ],+ };+ } catch (e) {+ return disabledOptions({ placeholder: 'Error occured while fetching forms.' });+ }+ },+ });+}++function isPageDropdownValue(value: unknown): value is FacebookLeadsPageDropdown {+ return (+ typeof value === 'object' &&+ value !== null &&+ 'id' in value &&+ typeof value.id === 'string' &&+ 'accessToken' in value &&+ typeof value.accessToken === 'string'+ );+}++function disabledOptions({ placeholder }: { placeholder: string }): DropdownState<never> {+ return { disabled: true, options: [], placeholder };+}++export const facebookLeadsProps = { page, form };++export type PropParams<R extends boolean> = {+ required: R;+ displayName?: string;+ description?: string;+};diff --git a/packages/pieces/community/facebook-leads/src/lib/common/types.ts b/packages/pieces/community/facebook-leads/src/lib/common/types.tsindex 13e82309a68..6c98319582c 100644--- a/packages/pieces/community/facebook-leads/src/lib/common/types.ts+++ b/packages/pieces/community/facebook-leads/src/lib/common/types.ts@@ -1,11 +1,18 @@-export interface FacebookPaginatedResponse<T> {+import type { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';++import type { facebookLeadsAuth } from '../auth';++export type FacebookLeadsAuthValue = AppConnectionValueForAuthProperty<typeof facebookLeadsAuth>;++export type FacebookLeadsPaginatedResponse<T> = {data: T[];paging?: {+ cursors?: { before?: string; after?: string };next?: string;};-}+};-export interface FacebookTriggerPayloadBody {+export type FacebookLeadsWebhookPayload = {entry: {changes: {value: {@@ -14,31 +21,45 @@ export interface FacebookTriggerPayloadBody {};}[];}[];-}+};-export interface FacebookPage {+export type FacebookLeadsPage = {id: string;name: string;category: string;category_list: string[];access_token: string;tasks: string[];-}+};-export interface FacebookPageDropdown {+export type FacebookLeadsPageDropdown = {id: string;accessToken: string;-}+};-export interface FacebookForm {+export type FacebookLeadsForm = {id: string;locale: string;name: string;status: string;-}+ created_time?: string;+ leads_count?: number;+ expired_leads_count?: number;+ questions?: unknown[];+ privacy_policy_url?: string;+ follow_up_action_url?: string;+ page?: { id: string; name: string };+};++export type FacebookLeadsFormStatus = 'ACTIVE' | 'ARCHIVED';++export type FacebookLeadsUser = {+ id: string;+ name: string;+};-export interface FacebookLead {- field_data: Array<{ name: string; values: any[] }>;+export type FacebookLeadsLead = {+ field_data: Array<{ name: string; values: unknown[] }>;created_time: string;ad_id: string;ad_name: string;@@ -49,4 +70,4 @@ export interface FacebookLead {form_id: string;platform: string;id: string;-}+};diff --git a/packages/pieces/community/facebook-leads/src/lib/common/utils.ts b/packages/pieces/community/facebook-leads/src/lib/common/utils.tsnew file mode 100644index 00000000000..89a47344491--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/common/utils.ts@@ -0,0 +1,25 @@+import type { FacebookLeadsLead } from './types';++function transformLeadData({ lead }: { lead: FacebookLeadsLead }) {+ return {+ lead_id: lead.id,+ form_id: lead.form_id,+ platform: lead.platform ?? null,+ ad_id: lead.ad_id ?? null,+ ad_name: lead.ad_name ?? null,+ adset_id: lead.adset_id ?? null,+ adset_name: lead.adset_name ?? null,+ campaign_id: lead.campaign_id ?? null,+ campaign_name: lead.campaign_name ?? null,+ created_time: lead.created_time,+ data: lead.field_data.reduce(+ (acc, field) => ({+ ...acc,+ [field.name]: field.values && field.values.length > 0 ? field.values[0] : null,+ }),+ {},+ ),+ };+}++export const facebookLeadsUtils = { transformLeadData };diff --git a/packages/pieces/community/facebook-leads/src/lib/output-schemas.ts b/packages/pieces/community/facebook-leads/src/lib/output-schemas.tsnew file mode 100644index 00000000000..2b32847ef85--- /dev/null+++ b/packages/pieces/community/facebook-leads/src/lib/output-schemas.ts@@ -0,0 +1,121 @@+import { OutputSchema } from '@activepieces/pieces-framework';++const leadFields: OutputSchema['fields'] = [+ { key: 'lead_id', label: 'Lead ID' },+ { key: 'form_id', label: 'Form ID' },+ { key: 'platform', label: 'Platform' },+ { key: 'ad_id', label: 'Ad ID' },+ { key: 'ad_name', label: 'Ad Name' },+ { key: 'adset_id', label: 'Ad Set ID' },+ { key: 'adset_name', label: 'Ad Set Name' },+ { key: 'campaign_id', label: 'Campaign ID' },+ { key: 'campaign_name', label: 'Campaign Name' },+ { key: 'created_time', label: 'Submitted At', format: 'datetime' },+ {+ key: 'data',+ label: 'Answers',+ dynamicKey: true,+ description: 'Answers keyed by the form question key, e.g. email, full_name, phone_number.',+ },+];++const formSummaryFields: OutputSchema['fields'] = [+ { key: 'id', label: 'Form ID' },+ { key: 'name', label: 'Name' },+ { key: 'status', label: 'Status' },+ { key: 'locale', label: 'Locale' },+ { key: 'created_time', label: 'Created At', format: 'datetime' },+ { key: 'leads_count', label: 'Leads Count', format: 'number' },+];++export const facebookLeadsUpdateLeadFormStatusOutputSchema: OutputSchema = {+ fields: [+ { key: 'form_id', label: 'Form ID' },+ { key: 'status', label: 'Status' },+ { key: 'success', label: 'Success', format: 'boolean' },+ ],+};++export const facebookLeadsCreateLeadFormOutputSchema: OutputSchema = {+ fields: [{ key: 'id', label: 'Form ID' }],+};++export const facebookLeadsGetLeadFormOutputSchema: OutputSchema = {+ fields: [+ ...formSummaryFields,+ { key: 'expired_leads_count', label: 'Expired Leads Count', format: 'number' },+ {+ key: 'questions',+ label: 'Questions',+ labelKey: 'key',+ listItems: [+ { key: 'id', label: 'Question ID' },+ { key: 'key', label: 'Key' },+ { key: 'label', label: 'Label' },+ { key: 'type', label: 'Type' },+ {+ key: 'options',+ label: 'Options',+ labelKey: 'value',+ listItems: [+ { key: 'key', label: 'Key' },+ { key: 'value', label: 'Value' },+ ],+ },+ ],+ },+ { key: 'privacy_policy_url', label: 'Privacy Policy URL', format: 'url' },+ { key: 'follow_up_action_url', label: 'Follow-up URL', format: 'url' },+ {+ key: 'page',+ label: 'Page',+ children: [+ { key: 'id', label: 'Page ID' },+ { key: 'name', label: 'Name' },+ ],+ },+ ],+};++export const facebookLeadsGetLeadOutputSchema: OutputSchema = {+ fields: leadFields,+};++export const facebookLeadsListLeadFormsOutputSchema: OutputSchema = {+ fields: [+ { key: 'forms', label: 'Forms', labelKey: 'name', listItems: formSummaryFields },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const facebookLeadsListLeadsOutputSchema: OutputSchema = {+ fields: [+ { key: 'leads', label: 'Leads', labelKey: 'lead_id', listItems: leadFields },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'next_cursor', label: 'Next Cursor' },+ ],+};++export const facebookLeadsGetCurrentUserOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'User ID' },+ { key: 'name', label: 'Name' },+ ],+};++export const facebookLeadsListPagesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'pages',+ label: 'Pages',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Page ID' },+ { key: 'name', label: 'Name' },+ { key: 'category', label: 'Category' },+ { key: 'tasks', label: 'Your Tasks on the Page' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};diff --git a/packages/pieces/community/facebook-leads/src/lib/triggers/new-lead.ts b/packages/pieces/community/facebook-leads/src/lib/triggers/new-lead.tsindex 8376e08fee6..97f86dd31b5 100644--- a/packages/pieces/community/facebook-leads/src/lib/triggers/new-lead.ts+++ b/packages/pieces/community/facebook-leads/src/lib/triggers/new-lead.ts@@ -1,11 +1,17 @@import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';-import { facebookLeadsCommon } from '../common';+import { facebookLeadsAuth } from '../auth';-import { FacebookTriggerPayloadBody, FacebookPageDropdown } from '../common/types';+import { facebookLeadsApi } from '../common/api';+import { facebookLeadsProps } from '../common/props';+import { facebookLeadsUtils } from '../common/utils';+import { facebookLeadsGetLeadOutputSchema } from '../output-schemas';++import type { FacebookLeadsWebhookPayload } from '../common/types';-export const newLead = createTrigger({+export const newLeadTrigger = createTrigger({auth: facebookLeadsAuth,name: 'new_lead',+ outputSchema: facebookLeadsGetLeadOutputSchema,classification: 'READ',displayName: 'New Lead',description: 'Triggers when a new lead is created.',@@ -16,59 +22,74 @@ export const newLead = createTrigger({type: TriggerStrategy.APP_WEBHOOK,sampleData: {},props: {- page: facebookLeadsCommon.page,- form: facebookLeadsCommon.form,+ page: facebookLeadsProps.page({ required: true }),+ form: facebookLeadsProps.form({ required: false }),},async onEnable(context) {- const page = context.propsValue['page'] as FacebookPageDropdown;- await facebookLeadsCommon.subscribePageToApp(page.id, page.accessToken);+ const page = context.propsValue.page;+ await facebookLeadsApi.subscribePageToApp({+ pageId: page.id,+ accessToken: page.accessToken,+ });context.app.createListeners({ events: ['lead'], identifierValue: page.id });},async onDisable() {- //+ return;},async test(context) {- let form = context.propsValue.form as string;- const page = context.propsValue.page as FacebookPageDropdown;- if (form == undefined || form == '' || form == null) {- const forms = await facebookLeadsCommon.getPageForms(page.id, page.accessToken);+ let form = selectedFormId({ form: context.propsValue.form });+ const page = context.propsValue.page;+ if (form === undefined) {+ const forms = await facebookLeadsApi.getPageForms({+ pageId: page.id,+ accessToken: page.accessToken,+ });form = forms[0].id;}- const response = await facebookLeadsCommon.loadSampleData(form, context.auth.access_token);- return response.data.map((lead) => facebookLeadsCommon.transformLeadData(lead));+ const leads = await facebookLeadsApi.listFormLeads({+ formId: form,+ accessToken: context.auth.access_token,+ });+ return leads.map((lead) => facebookLeadsUtils.transformLeadData({ lead }));},- //Return new leadasync run(context) {- let leadPings: any[] = [];- const leads: any[] = [];- const form = context.propsValue.form;- const payloadBody = context.payload.body as FacebookTriggerPayloadBody;+ const form = selectedFormId({ form: context.propsValue.form });+ const payloadBody = context.payload.body;+ const entries = isWebhookPayload(payloadBody) ? payloadBody.entry : [];- if (form !== undefined && form !== '' && form !== null) {- for (const lead of payloadBody.entry) {- if (form == lead.changes[0].value.form_id) {- leadPings.push(lead);- }- }- } else {- leadPings = payloadBody.entry;- }+ const leadPings =+ form !== undefined+ ? entries.filter((lead) => form == lead.changes[0].value.form_id)+ : entries;+ const leads = [];for (const lead of leadPings) {- const leadData = await facebookLeadsCommon.getLeadDetails(- lead.changes[0].value.leadgen_id,- context.auth.access_token,- );- const transformLead = facebookLeadsCommon.transformLeadData(leadData);- leads.push(transformLead);+ const leadData = await facebookLeadsApi.getLead({+ leadId: lead.changes[0].value.leadgen_id,+ accessToken: context.auth.access_token,+ });+ leads.push(facebookLeadsUtils.transformLeadData({ lead: leadData }));}return leads;},});++function isWebhookPayload(body: unknown): body is FacebookLeadsWebhookPayload {+ return typeof body === 'object' && body !== null && 'entry' in body && Array.isArray(body.entry);+}++function selectedFormId({ form }: { form: string | undefined }): string | undefined {+ if (form === undefined || form === null || form === '' || form === ALL_FORMS) {+ return undefined;+ }+ return form;+}++const ALL_FORMS = 'all';