Skip to content

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

feat(cognito-forms): let AI agents create, read, update and delete entries and fetch documents (#16673)

Odai Ahmad43f0ffd9ea6f
diff --git a/bun.lock b/bun.lock
index 3a6163eeba9..f2ee16e131f 100644
--- a/bun.lock
+++ b/bun.lock
@@ -2144,15 +2144,17 @@
},
"packages/pieces/community/cognito-forms": {
"name": "@activepieces/piece-cognito-forms",
- "version": "0.2.2",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "undici": "7.29.1",
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/cohere": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index ed95cb64d3d..3845265c2e3 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,23 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### Cognito Forms 0.3.0: Update Entry skips empty fields, and the entry actions move to new AI versions
+
+From Cognito Forms 0.3.0 the **Update Entry** action only sends the fields you fill in. Before, empty values (blank text, null, empty lists) were sent too, which cleared the value stored on the entry. Now an empty field keeps its current value, and the step fails with "Fill in at least one field to update." when every field is empty. Yes/No fields in Update Entry are now a **Yes** / **No** dropdown; left empty, the field keeps its current value. Before, an untouched Yes/No checkbox was sent as No and overwrote the entry. **Create Entry** also leaves out empty fields, so the form's own default values apply.
+
+The builder's **Delete Entry** now succeeds when the entry is already gone and returns `deleted` and `already_deleted` instead of Cognito's raw response. A wrong form ID or any other not-found error still fails the step.
+
+**Create Entry**, **Update Entry**, **Get Entry** and **Delete Entry** are no longer offered to AI agents. Agents get **Create Entry (by Form ID)**, **Update Entry (by IDs)**, **Get Entry (by IDs)** and **Delete Entry (by IDs)** instead, which take the form ID, entry ID and field values directly.
+
+#### What you need to do
+
+- Update Entry: to clear a field, use **Custom API Call** with a `PATCH` to `/forms/{formId}/entries/{entryId}` and set the field to `null`.
+- Update Entry steps with Yes/No fields: open the step after upgrading and set each Yes/No field you want to change; the rest are left unchanged.
+- Delete Entry: if a later step read Cognito's raw delete response, map `deleted` / `already_deleted` instead.
+- Agents that used the old entry actions as tools: add the new "(by IDs)" versions to the agent.
+
+Steps keep running on the version they were built with until you upgrade them.
+
#### Mindee 0.4.0: the piece moves to the Mindee v2 API, and Predict Document is builder-only
Mindee 0.4.0 adds actions for the Mindee v2 API (app.mindee.com). The old action is renamed **Predict Document (Legacy v1)** and keeps calling the v1 API, but it is no longer offered as a tool to AI agents. Steps keep running on the version they were built with until you upgrade them.
diff --git a/packages/pieces/community/cognito-forms/package.json b/packages/pieces/community/cognito-forms/package.json
index d056cbc14fd..1d02130f52d 100644
--- a/packages/pieces/community/cognito-forms/package.json
+++ b/packages/pieces/community/cognito-forms/package.json
@@ -1,20 +1,23 @@
{
"name": "@activepieces/piece-cognito-forms",
- "version": "0.2.2",
+ "version": "0.3.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "undici": "7.29.1"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/cognito-forms/src/i18n/translation.json b/packages/pieces/community/cognito-forms/src/i18n/translation.json
index 6e431aeaa92..5ed28055b54 100644
--- a/packages/pieces/community/cognito-forms/src/i18n/translation.json
+++ b/packages/pieces/community/cognito-forms/src/i18n/translation.json
@@ -1,18 +1,43 @@
{
- "\n 1. Click your organization's name in the top left corner and then click Settings.\n 2. Go to the Integrations section and select + New API Key.\n 3. Make sure to copy and store your API key, as it cannot be retrieved later.\n ": "\n 1. Click your organization's name in the top left corner and then click Settings.\n 2. Go to the Integrations section and select + New API Key.\n 3. Make sure to copy and store your API key, as it cannot be retrieved later.\n ",
+ "Online form builder for collecting and managing submissions.": "Online form builder for collecting and managing submissions.",
+ "\n1. Sign in to Cognito Forms as an organization owner or admin.\n2. Click your organization's name in the top left corner, then click **Settings**.\n3. Open **Integrations** and click **+ New API Key**.\n4. Give the key the scopes you need (**Read** to look up forms and entries, **Write** to create or update entries, **Delete** to delete entries) and access to the forms you want to use.\n5. Copy the key and paste it here. Cognito Forms only shows it once.\n\nThe Cognito Forms API needs a paid plan.\n ": "\n1. Sign in to Cognito Forms as an organization owner or admin.\n2. Click your organization's name in the top left corner, then click **Settings**.\n3. Open **Integrations** and click **+ New API Key**.\n4. Give the key the scopes you need (**Read** to look up forms and entries, **Write** to create or update entries, **Delete** to delete entries) and access to the forms you want to use.\n5. Copy the key and paste it here. Cognito Forms only shows it once.\n\nThe Cognito Forms API needs a paid plan.\n ",
"Create Entry": "Create Entry",
"Update Entry": "Update Entry",
"Delete Entry": "Delete Entry",
"Get Entry": "Get Entry",
+ "Create Entry (by Form ID)": "Create Entry (by Form ID)",
+ "Update Entry (by IDs)": "Update Entry (by IDs)",
+ "Get Entry (by IDs)": "Get Entry (by IDs)",
+ "Delete Entry (by IDs)": "Delete Entry (by IDs)",
+ "List Forms": "List Forms",
+ "Get Form Schema": "Get Form Schema",
+ "Set Form Availability": "Set Form Availability",
+ "Get Entry Document": "Get Entry Document",
+ "Download File": "Download File",
"Custom API Call": "Custom API Call",
- "Creates a new entry.": "Creates a new entry.",
- "Update an existing entry.": "Update an existing entry.",
- "Deletes a specified entry.": "Deletes a specified entry.",
- "Gets a specified entry.": "Gets a specified entry.",
+ "Creates a new entry in a form.": "Creates a new entry in a form.",
+ "Updates an existing entry. Fields you leave empty keep their current value.": "Updates an existing entry. Fields you leave empty keep their current value.",
+ "Permanently deletes an entry. Entries that are already gone are reported as already deleted.": "Permanently deletes an entry. Entries that are already gone are reported as already deleted.",
+ "Gets an entry by its number or ID.": "Gets an entry by its number or ID.",
+ "Creates a new entry from a form ID and a JSON object of field values.": "Creates a new entry from a form ID and a JSON object of field values.",
+ "Updates an entry from a form ID, an entry ID and a JSON object of field values.": "Updates an entry from a form ID, an entry ID and a JSON object of field values.",
+ "Gets an entry from a form ID and an entry ID.": "Gets an entry from a form ID and an entry ID.",
+ "Permanently deletes an entry from a form ID and an entry ID.": "Permanently deletes an entry from a form ID and an entry ID.",
+ "Lists the forms the API key can access.": "Lists the forms the API key can access.",
+ "Gets the fields of a form: names, types and which are required or read-only.": "Gets the fields of a form: names, types and which are required or read-only.",
+ "Opens or closes a form's public link for a date range. Leave both dates empty to make the form always available.": "Opens or closes a form's public link for a date range. Leave both dates empty to make the form always available.",
+ "Generates a document (PDF or Word) for an entry from one of the form's document templates.": "Generates a document (PDF or Word) for an entry from one of the form's document templates.",
+ "Downloads a file uploaded to an entry (from a File Upload or Signature field).": "Downloads a file uploaded to an entry (from a File Upload or Signature field).",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Form": "Form",
"Fields": "Fields",
"Entry ID": "Entry ID",
+ "Form ID": "Form ID",
+ "Available From": "Available From",
+ "Available Until": "Available Until",
+ "Not Available Message": "Not Available Message",
+ "Template Number": "Template Number",
+ "File ID": "File ID",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
@@ -22,9 +47,18 @@
"Return Error as Output": "Return Error as Output",
"Timeout": "Timeout",
"Follow redirects": "Follow redirects",
- "Enter the ID of the entry you want to update.": "Enter the ID of the entry you want to update.",
- "Enter the ID of the entry to delete.": "Enter the ID of the entry to delete.",
- "Enter the ID of the entry to retrieve.": "Enter the ID of the entry to retrieve.",
+ "Pick the form. Only forms the API key has access to are listed.": "Pick the form. Only forms the API key has access to are listed.",
+ "The entry number (for example 12) or the full entry ID (for example 5-12). You can map it from a trigger or a \"Create Entry\" step.": "The entry number (for example 12) or the full entry ID (for example 5-12). You can map it from a trigger or a \"Create Entry\" step.",
+ "The entry number (for example 12) or the full entry ID (for example 5-12) of the entry to delete.": "The entry number (for example 12) or the full entry ID (for example 5-12) of the entry to delete.",
+ "The entry number (for example 12) or the full entry ID (for example 5-12).": "The entry number (for example 12) or the full entry ID (for example 5-12).",
+ "The form ID or internal name, as returned by \"List Forms\".": "The form ID or internal name, as returned by \"List Forms\".",
+ "Field values keyed by field name, for example {\"Name\": {\"First\": \"Ada\", \"Last\": \"Lovelace\"}, \"Email\": \"[email protected]\"}.": "Field values keyed by field name, for example {\"Name\": {\"First\": \"Ada\", \"Last\": \"Lovelace\"}, \"Email\": \"[email protected]\"}.",
+ "Field values to change, keyed by field name. Fields not listed keep their value; null or \"\" clears a field.": "Field values to change, keyed by field name. Fields not listed keep their value; null or \"\" clears a field.",
+ "When the form starts accepting entries. Empty means no start limit.": "When the form starts accepting entries. Empty means no start limit.",
+ "When the form stops accepting entries. Leave empty for no end limit.": "When the form stops accepting entries. Leave empty for no end limit.",
+ "Shown to people who open the form outside the availability window.": "Shown to people who open the form outside the availability window.",
+ "The document template number (the first template is 1).": "The document template number (the first template is 1).",
+ "The \"Id\" of an uploaded file or a signature's PngFile from an entry.": "The \"Id\" of an uploaded file or a signature's PngFile from an entry.",
"Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
"Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
"Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
@@ -44,6 +78,6 @@
"Triggers when a new form entry is submitted.": "Triggers when a new form entry is submitted.",
"Triggers when an existing form entry is updated.": "Triggers when an existing form entry is updated.",
"Markdown": "Markdown",
- "\n\t\t\tTo use this trigger, you need to manually set up a webhook in your Cognito Forms account:\n\n\t\t\t1. Login to your Cognito Forms account.\n\t\t\t2. Select desired form and go to Form Settings.\n\t\t\t3. Enable **Post JSON Data to Website** and add following URL in **Submit Entry Endpoint** field:\n\t\t\t```text\n\t\t\t{{webhookUrl}}\n\t\t\t```\n\t\t\t4. Click Save to save the form changes.\n\t\t\t": "\n\t\t\tTo use this trigger, you need to manually set up a webhook in your Cognito Forms account:\n\n\t\t\t1. Login to your Cognito Forms account.\n\t\t\t2. Select desired form and go to Form Settings.\n\t\t\t3. Enable **Post JSON Data to Website** and add following URL in **Submit Entry Endpoint** field:\n\t\t\t```text\n\t\t\t{{webhookUrl}}\n\t\t\t```\n\t\t\t4. Click Save to save the form changes.\n\t\t\t",
- "\n To use this trigger, you need to manually set up a webhook in your Cognito Forms account:\n \n 1. Login to your Cognito Forms account.\n 2. Select desired form and go to Form Settings.\n 3. Enable **Post JSON Data to Website** and add following URL in **Update Entry Endpoint** field:\n ```text\n {{webhookUrl}}\n ```\n 4. Click Save to save the form changes.\n ": "\n To use this trigger, you need to manually set up a webhook in your Cognito Forms account:\n \n 1. Login to your Cognito Forms account.\n 2. Select desired form and go to Form Settings.\n 3. Enable **Post JSON Data to Website** and add following URL in **Update Entry Endpoint** field:\n ```text\n {{webhookUrl}}\n ```\n 4. Click Save to save the form changes.\n "
+ "\nTo use this trigger, connect your form to the webhook URL in Cognito Forms:\n\n1. Open your form in Cognito Forms and go to **Build**, then **Form Settings**.\n2. Turn on **Post JSON Data to Website**.\n3. Paste the following URL into the **Submit Entry Endpoint** field only:\n```text\n{{webhookUrl}}\n```\n4. Save the form.\n\nCognito Forms does not sign these requests, so keep the URL private. Posting JSON data needs a paid Cognito Forms plan.\n": "\nTo use this trigger, connect your form to the webhook URL in Cognito Forms:\n\n1. Open your form in Cognito Forms and go to **Build**, then **Form Settings**.\n2. Turn on **Post JSON Data to Website**.\n3. Paste the following URL into the **Submit Entry Endpoint** field only:\n```text\n{{webhookUrl}}\n```\n4. Save the form.\n\nCognito Forms does not sign these requests, so keep the URL private. Posting JSON data needs a paid Cognito Forms plan.\n",
+ "\nTo use this trigger, connect your form to the webhook URL in Cognito Forms:\n\n1. Open your form in Cognito Forms and go to **Build**, then **Form Settings**.\n2. Turn on **Post JSON Data to Website**.\n3. Paste the following URL into the **Update Entry Endpoint** field only:\n```text\n{{webhookUrl}}\n```\n4. Save the form.\n\nCognito Forms does not sign these requests, so keep the URL private. Posting JSON data needs a paid Cognito Forms plan.\n": "\nTo use this trigger, connect your form to the webhook URL in Cognito Forms:\n\n1. Open your form in Cognito Forms and go to **Build**, then **Form Settings**.\n2. Turn on **Post JSON Data to Website**.\n3. Paste the following URL into the **Update Entry Endpoint** field only:\n```text\n{{webhookUrl}}\n```\n4. Save the form.\n\nCognito Forms does not sign these requests, so keep the URL private. Posting JSON data needs a paid Cognito Forms plan.\n"
}
\ No newline at end of file
diff --git a/packages/pieces/community/cognito-forms/src/index.ts b/packages/pieces/community/cognito-forms/src/index.ts
index 44a87ad0c71..87f31bd4e29 100644
--- a/packages/pieces/community/cognito-forms/src/index.ts
+++ b/packages/pieces/community/cognito-forms/src/index.ts
@@ -1,38 +1,45 @@
-import { createPiece, PieceAuth } from '@activepieces/pieces-framework';
-import { AppConnectionType, PieceCategory } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { createEntryAiAction } from './lib/actions/ai/create-entry-ai';
+import { deleteEntryAiAction } from './lib/actions/ai/delete-entry-ai';
+import { getEntryAiAction } from './lib/actions/ai/get-entry-ai';
+import { updateEntryAiAction } from './lib/actions/ai/update-entry-ai';
+import { customApiCallAction } from './lib/actions/custom-api-call';
import { createEntryAction } from './lib/actions/create-entry';
-import { updateEntryAction } from './lib/actions/update-entry';
import { deleteEntryAction } from './lib/actions/delete-entry';
+import { downloadFileAction } from './lib/actions/download-file';
import { getEntryAction } from './lib/actions/get-entry';
-import { newEntryTrigger } from './lib/triggers/new-entry-submitted';
-import { entryUpdatedTrigger } from './lib/triggers/entry-updated';
-import {
- createCustomApiCallAction,
- HttpMethod,
-} from '@activepieces/pieces-common';
-import { makeRequest } from './lib/common';
+import { getEntryDocumentAction } from './lib/actions/get-entry-document';
+import { getFormSchemaAction } from './lib/actions/get-form-schema';
+import { listFormsAction } from './lib/actions/list-forms';
+import { setFormAvailabilityAction } from './lib/actions/set-form-availability';
+import { updateEntryAction } from './lib/actions/update-entry';
import { cognitoFormsAuth } from './lib/auth';
+import { entryUpdatedTrigger } from './lib/triggers/entry-updated';
+import { newEntryTrigger } from './lib/triggers/new-entry-submitted';
export const cognitoForms = createPiece({
displayName: 'Cognito Forms',
+ description: 'Online form builder for collecting and managing submissions.',
auth: cognitoFormsAuth,
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/cognito-forms.png',
- authors: ['krushnarout'],
+ authors: ['krushnarout', 'OdaiAhmed99'],
categories: [PieceCategory.PRODUCTIVITY, PieceCategory.FORMS_AND_SURVEYS],
actions: [
createEntryAction,
updateEntryAction,
deleteEntryAction,
getEntryAction,
- createCustomApiCallAction({
- auth: cognitoFormsAuth,
- baseUrl: () => 'https://www.cognitoforms.com/api',
- authMapping: async (auth) => {
- return {
- Authorization: `Bearer ${auth}`,
- };
- },
- }),
+ createEntryAiAction,
+ updateEntryAiAction,
+ getEntryAiAction,
+ deleteEntryAiAction,
+ listFormsAction,
+ getFormSchemaAction,
+ setFormAvailabilityAction,
+ getEntryDocumentAction,
+ downloadFileAction,
+ customApiCallAction,
],
triggers: [newEntryTrigger, entryUpdatedTrigger],
});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/ai/create-entry-ai.ts b/packages/pieces/community/cognito-forms/src/lib/actions/ai/create-entry-ai.ts
new file mode 100644
index 00000000000..7988fd7ed8f
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/ai/create-entry-ai.ts
@@ -0,0 +1,35 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { cognitoFormsAuth } from '../../auth';
+import { cognitoRequest } from '../../common/client';
+import { formPath, normalizeEntry, parseFieldsObject } from '../../common/entries';
+import { entryFieldsJson, formIdText } from '../../common/props';
+import { entryOutputSchema } from '../../output-schemas';
+
+export const createEntryAiAction = createAction({
+ auth: cognitoFormsAuth,
+ name: 'create_entry_ai',
+ classification: 'WRITE',
+ displayName: 'Create Entry (by Form ID)',
+ description: 'Creates a new entry from a form ID and a JSON object of field values.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Creates a new entry (submission) in a Cognito Forms form. Call "Get Form Schema" first to learn the field names and types, then pass the values as a JSON object keyed by field name; complex fields (Name, Address, choice lists, tables) take nested objects or arrays. Not idempotent: every call creates another entry.',
+ idempotent: false,
+ },
+ outputSchema: entryOutputSchema,
+ props: {
+ form_id: formIdText,
+ fields: entryFieldsJson('Field values keyed by field name, for example {"Name": {"First": "Ada", "Last": "Lovelace"}, "Email": "[email protected]"}.'),
+ },
+ async run(context) {
+ const { form_id, fields } = context.propsValue;
+ const entry = await cognitoRequest<unknown>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: `${formPath(form_id)}/entries`,
+ body: parseFieldsObject(fields),
+ });
+ return normalizeEntry(entry);
+ },
+});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/ai/delete-entry-ai.ts b/packages/pieces/community/cognito-forms/src/lib/actions/ai/delete-entry-ai.ts
new file mode 100644
index 00000000000..74fea3ec9b1
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/ai/delete-entry-ai.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cognitoFormsAuth } from '../../auth';
+import { deleteEntry } from '../../common/delete';
+import { entryIdText, formIdText } from '../../common/props';
+import { deleteEntryOutputSchema } from '../../output-schemas';
+
+export const deleteEntryAiAction = createAction({
+ auth: cognitoFormsAuth,
+ name: 'delete_entry_ai',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Entry (by IDs)',
+ description: 'Permanently deletes an entry from a form ID and an entry ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Permanently deletes one Cognito Forms entry by form ID and entry number or ID. Cannot be undone. Idempotent: if the entry is already gone the call succeeds with already_deleted true.',
+ idempotent: true,
+ },
+ outputSchema: deleteEntryOutputSchema,
+ props: {
+ form_id: formIdText,
+ entry_id: entryIdText('The entry number (for example 12) or the full entry ID (for example 5-12).'),
+ },
+ async run(context) {
+ const { form_id, entry_id } = context.propsValue;
+ return deleteEntry({ apiKey: context.auth.secret_text, formId: form_id, entryId: entry_id });
+ },
+});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/ai/get-entry-ai.ts b/packages/pieces/community/cognito-forms/src/lib/actions/ai/get-entry-ai.ts
new file mode 100644
index 00000000000..e957b8aee69
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/ai/get-entry-ai.ts
@@ -0,0 +1,34 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { cognitoFormsAuth } from '../../auth';
+import { cognitoRequest } from '../../common/client';
+import { entryPath, normalizeEntry } from '../../common/entries';
+import { entryIdText, formIdText } from '../../common/props';
+import { entryOutputSchema } from '../../output-schemas';
+
+export const getEntryAiAction = createAction({
+ auth: cognitoFormsAuth,
+ name: 'get_entry_ai',
+ classification: 'READ',
+ displayName: 'Get Entry (by IDs)',
+ description: 'Gets an entry from a form ID and an entry ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Retrieves one Cognito Forms entry by form ID and entry number or ID, returning its status, dates, links and field values under "fields". Read-only and idempotent. There is no search; you need the entry ID (for example from a trigger).',
+ idempotent: true,
+ },
+ outputSchema: entryOutputSchema,
+ props: {
+ form_id: formIdText,
+ entry_id: entryIdText('The entry number (for example 12) or the full entry ID (for example 5-12).'),
+ },
+ async run(context) {
+ const { form_id, entry_id } = context.propsValue;
+ const entry = await cognitoRequest<unknown>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: entryPath({ formId: form_id, entryId: entry_id }),
+ });
+ return normalizeEntry(entry);
+ },
+});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/ai/update-entry-ai.ts b/packages/pieces/community/cognito-forms/src/lib/actions/ai/update-entry-ai.ts
new file mode 100644
index 00000000000..a704b485537
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/ai/update-entry-ai.ts
@@ -0,0 +1,40 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { cognitoFormsAuth } from '../../auth';
+import { cognitoRequest } from '../../common/client';
+import { entryPath, normalizeEntry, parseFieldsObject } from '../../common/entries';
+import { entryFieldsJson, entryIdText, formIdText } from '../../common/props';
+import { entryOutputSchema } from '../../output-schemas';
+
+export const updateEntryAiAction = createAction({
+ auth: cognitoFormsAuth,
+ name: 'update_entry_ai',
+ classification: 'WRITE',
+ displayName: 'Update Entry (by IDs)',
+ description: 'Updates an entry from a form ID, an entry ID and a JSON object of field values.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Updates an existing Cognito Forms entry. Only the fields in the JSON object change; send a field as null or "" to clear it. Use "Get Form Schema" for field names. Fails for entries with a paid order. Idempotent: the same values give the same result.',
+ idempotent: true,
+ },
+ outputSchema: entryOutputSchema,
+ props: {
+ form_id: formIdText,
+ entry_id: entryIdText('The entry number (for example 12) or the full entry ID (for example 5-12).'),
+ fields: entryFieldsJson('Field values to change, keyed by field name. Fields not listed keep their value; null or "" clears a field.'),
+ },
+ async run(context) {
+ const { form_id, entry_id, fields } = context.propsValue;
+ const body = parseFieldsObject(fields);
+ if (Object.keys(body).length === 0) {
+ throw new Error('Fields must contain at least one field to update.');
+ }
+ const entry = await cognitoRequest<unknown>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.PATCH,
+ path: entryPath({ formId: form_id, entryId: entry_id }),
+ body,
+ });
+ return normalizeEntry(entry);
+ },
+});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/create-entry.ts b/packages/pieces/community/cognito-forms/src/lib/actions/create-entry.ts
index d29e3cfb1aa..67e0f000f74 100644
--- a/packages/pieces/community/cognito-forms/src/lib/actions/create-entry.ts
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/create-entry.ts
@@ -1,7 +1,8 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest } from '../common';
+import { createAction } from '@activepieces/pieces-framework';
import { cognitoFormsAuth } from '../auth';
+import { cognitoRequest } from '../common/client';
+import { formPath, stripEmptyValues } from '../common/entries';
import { formFields, formIdDropdown } from '../common/props';
export const createEntryAction = createAction({
@@ -9,22 +10,23 @@ export const createEntryAction = createAction({
name: 'create_entry',
classification: 'WRITE',
displayName: 'Create Entry',
- description: 'Creates a new entry.',
- audience: 'both',
- aiMetadata: { description: 'Creates a new entry (form submission) in a specified Cognito Forms form. Choose this to submit data into a form programmatically; the entry field values must match the target form\'s schema. Not idempotent: each call creates a separate entry.', idempotent: false },
+ description: 'Creates a new entry in a form.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Creates a new entry (form submission) in a Cognito Forms form using fields picked from the form. Not idempotent: each call creates a separate entry.',
+ idempotent: false,
+ },
props: {
formId: formIdDropdown,
entryData: formFields,
},
async run(context) {
- const apiKey = context.auth;
const { formId, entryData } = context.propsValue;
-
- return await makeRequest(
- apiKey,
- HttpMethod.POST,
- `/forms/${formId}/entries`,
- entryData
- );
+ return cognitoRequest<unknown>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: `${formPath(formId)}/entries`,
+ body: stripEmptyValues(entryData),
+ });
},
});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/custom-api-call.ts b/packages/pieces/community/cognito-forms/src/lib/actions/custom-api-call.ts
new file mode 100644
index 00000000000..2765546f472
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/custom-api-call.ts
@@ -0,0 +1,181 @@
+import {
+ createCustomApiCallAction,
+ HttpMethod,
+ HttpRequest,
+ httpClient,
+ toFailsafeOutput,
+} from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { cognitoFormsAuth } from '../auth';
+import { COGNITO_API_BASE, isRecord, verifiedTls } from '../common/client';
+
+const base = createCustomApiCallAction({
+ auth: cognitoFormsAuth,
+ baseUrl: () => COGNITO_API_BASE,
+ authMapping: async (auth) => ({ Authorization: `Bearer ${auth.secret_text}` }),
+});
+
+export const customApiCallAction = createAction({
+ auth: cognitoFormsAuth,
+ name: 'custom_api_call',
+ displayName: base.displayName,
+ description: base.description,
+ props: base.props,
+ propertyGroups: base.propertyGroups,
+ classification: 'WRITE',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Send any request to the Cognito Forms API (https://www.cognitoforms.com/api) with the connection key, for endpoints the other actions do not cover. Returns status, headers and body. Can change or delete data depending on the method and path.',
+ idempotent: false,
+ },
+ async run({ auth, propsValue, files }) {
+ const method = methodOf(propsValue['method']);
+ const url = urlOf(propsValue['url']);
+ if (url === '') throw new Error('URL is required.');
+ const fullUrl = fullUrlOf(url);
+ const timeout = propsValue['timeout'];
+ const request: HttpRequest = {
+ method,
+ url: fullUrl,
+ headers: { ...stringMap(propsValue['headers']), Authorization: `Bearer ${auth.secret_text}` },
+ queryParams: stringMap(propsValue['queryParams']),
+ timeout: typeof timeout === 'number' && timeout > 0 ? timeout * 1000 : 0,
+ followRedirects: propsValue['followRedirects'] === true,
+ body: bodyOf({ body: propsValue['body'], bodyType: propsValue['body_type'] }),
+ redactBodyInErrors: true,
+ };
+ const binary = propsValue['response_is_binary'] === true;
+ if (binary) request.responseType = 'arraybuffer';
+ try {
+ const response = await httpClient.sendRequest(request, { dispatcher: await verifiedTls() });
+ const data: unknown = response.body;
+ if (binary && (data instanceof ArrayBuffer || Buffer.isBuffer(data))) {
+ const buffer = Buffer.isBuffer(data) ? data : Buffer.from(new Uint8Array(data));
+ return { status: response.status, headers: response.headers, body: await files.write({ fileName: `output.${extensionOf(response.headers)}`, data: buffer }) };
+ }
+ return { status: response.status, headers: response.headers, body: data };
+ } catch (error) {
+ if (propsValue['failsafe'] === true) return toFailsafeOutput({ error, requestBody: request.body });
+ throw error;
+ }
+ },
+});
+
+function fullUrlOf(url: string): string {
+ if (url.split(/[/?#]/).some((part) => part === '..' || part.toLowerCase() === '%2e%2e')) {
+ throw new Error('The URL must not contain ".." segments.');
+ }
+ const absolute = /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//');
+ const full = absolute ? url : `${COGNITO_API_BASE}/${url.replace(/^\/+/, '')}`;
+ let parsed: URL;
+ try {
+ parsed = new URL(full, COGNITO_API_BASE);
+ } catch {
+ throw new Error('The URL is not valid.');
+ }
+ const allowed = new URL(COGNITO_API_BASE);
+ if (parsed.protocol !== 'https:' || parsed.host !== allowed.host) {
+ throw new Error(`The URL must be on ${allowed.origin}.`);
+ }
+ return parsed.toString();
+}
+
+function urlOf(value: unknown): string {
+ return isRecord(value) && typeof value['url'] === 'string' ? value['url'].trim() : '';
+}
+
+function methodOf(value: unknown): HttpMethod {
+ const method = Object.values(HttpMethod).find((m) => m === value);
+ if (!method) throw new Error('Method is required.');
+ return method;
+}
+
+function stringMap(value: unknown): Record<string, string> {
+ if (!isRecord(value)) return {};
+ const entries: [string, string][] = [];
+ for (const [key, item] of Object.entries(value)) {
+ if (key.toLowerCase() === 'authorization') continue;
+ if (typeof item === 'string') entries.push([key, item]);
+ else if (typeof item === 'number' || typeof item === 'boolean' || typeof item === 'bigint') entries.push([key, String(item)]);
+ }
+ return Object.fromEntries(entries);
+}
+
+function bodyOf({ body, bodyType }: { body: unknown; bodyType: unknown }): HttpRequest['body'] {
+ if (body === undefined || body === null) return undefined;
+ if (!bodyType) return isRecord(body) || Array.isArray(body) || typeof body === 'string' ? body : undefined;
+ if (bodyType === 'none' || !isRecord(body)) return undefined;
+ const data = body['data'];
+ if (bodyType !== 'form_data') return isRecord(data) || Array.isArray(data) || typeof data === 'string' ? data : undefined;
+ const form = new FormData();
+ for (const field of Array.isArray(data) ? data : []) {
+ if (!isRecord(field) || typeof field['fieldName'] !== 'string') continue;
+ const text = field['textFieldValue'];
+ const file = isRecord(field['fileFieldValue']) ? field['fileFieldValue'] : {};
+ if (field['fieldType'] === 'text' && typeof text === 'string' && text !== '') form.append(field['fieldName'], text);
+ else if (field['fieldType'] === 'file' && Buffer.isBuffer(file['data'])) {
+ form.append(field['fieldName'], new Blob([new Uint8Array(file['data'])]), typeof file['filename'] === 'string' ? file['filename'] : undefined);
+ }
+ }
+ return form;
+}
+
+function extensionOf(headers: unknown): string {
+ const raw = isRecord(headers) ? headers['content-type'] : undefined;
+ const value = Array.isArray(raw) ? raw[0] : raw;
+ const type = typeof value === 'string' ? value.split(';')[0].trim().toLowerCase() : '';
+ return CONTENT_TYPE_EXTENSIONS[type] ?? 'txt';
+}
+
+const CONTENT_TYPE_EXTENSIONS: Record<string, string> = {
+ 'application/json': 'json',
+ 'application/pdf': 'pdf',
+ 'application/xml': 'xml',
+ 'text/xml': 'xml',
+ 'application/zip': 'zip',
+ 'application/gzip': 'gz',
+ 'application/x-tar': 'tar',
+ 'application/octet-stream': 'bin',
+ 'application/msword': 'doc',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
+ 'application/vnd.ms-excel': 'xls',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
+ 'application/vnd.ms-powerpoint': 'ppt',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',
+ 'application/rtf': 'rtf',
+ 'application/javascript': 'js',
+ 'application/x-www-form-urlencoded': 'bin',
+ 'text/plain': 'txt',
+ 'text/html': 'html',
+ 'text/css': 'css',
+ 'text/csv': 'csv',
+ 'text/calendar': 'ics',
+ 'text/markdown': 'md',
+ 'image/png': 'png',
+ 'image/jpeg': 'jpeg',
+ 'image/jpg': 'jpg',
+ 'image/gif': 'gif',
+ 'image/webp': 'webp',
+ 'image/svg+xml': 'svg',
+ 'image/bmp': 'bmp',
+ 'image/tiff': 'tiff',
+ 'image/x-icon': 'ico',
+ 'image/vnd.microsoft.icon': 'ico',
+ 'image/heic': 'heic',
+ 'audio/mpeg': 'mp3',
+ 'audio/mp4': 'm4a',
+ 'audio/wav': 'wav',
+ 'audio/x-wav': 'wav',
+ 'audio/ogg': 'ogg',
+ 'audio/webm': 'weba',
+ 'video/mp4': 'mp4',
+ 'video/mpeg': 'mpeg',
+ 'video/webm': 'webm',
+ 'video/quicktime': 'mov',
+ 'video/x-msvideo': 'avi',
+ 'font/woff': 'woff',
+ 'font/woff2': 'woff2',
+ 'font/ttf': 'ttf',
+ 'font/otf': 'otf',
+};
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/delete-entry.ts b/packages/pieces/community/cognito-forms/src/lib/actions/delete-entry.ts
index 6b2871b73b3..8ac4bb87ac1 100644
--- a/packages/pieces/community/cognito-forms/src/lib/actions/delete-entry.ts
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/delete-entry.ts
@@ -1,33 +1,27 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest } from '../common';
+import { createAction } from '@activepieces/pieces-framework';
import { cognitoFormsAuth } from '../auth';
-import { formIdDropdown } from '../common/props';
+import { deleteEntry } from '../common/delete';
+import { entryIdText, formIdDropdown } from '../common/props';
+import { deleteEntryOutputSchema } from '../output-schemas';
export const deleteEntryAction = createAction({
auth: cognitoFormsAuth,
name: 'delete_entry',
classification: 'DESTRUCTIVE',
displayName: 'Delete Entry',
- description: 'Deletes a specified entry.',
- audience: 'both',
- aiMetadata: { description: 'Permanently deletes a single entry from a Cognito Forms form, identified by its entry ID. Choose this to remove a specific submission you can identify by ID. Idempotent: once the entry is gone, repeating the call converges to the same deleted state.', idempotent: true },
+ description: 'Permanently deletes an entry. Entries that are already gone are reported as already deleted.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Permanently deletes one Cognito Forms entry by form and entry ID. Idempotent: deleting an entry that no longer exists succeeds with already_deleted true.',
+ idempotent: true,
+ },
+ outputSchema: deleteEntryOutputSchema,
props: {
formId: formIdDropdown,
- entryId: Property.ShortText({
- displayName: 'Entry ID',
- required: true,
- description: 'Enter the ID of the entry to delete.',
- }),
+ entryId: entryIdText('The entry number (for example 12) or the full entry ID (for example 5-12) of the entry to delete.'),
},
async run(context) {
- const apiKey = context.auth;
const { formId, entryId } = context.propsValue;
-
- return await makeRequest(
- apiKey,
- HttpMethod.DELETE,
- `/forms/${formId}/entries/${entryId}`
- );
+ return deleteEntry({ apiKey: context.auth.secret_text, formId, entryId });
},
});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/download-file.ts b/packages/pieces/community/cognito-forms/src/lib/actions/download-file.ts
new file mode 100644
index 00000000000..818fe0d1e70
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/download-file.ts
@@ -0,0 +1,36 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { cognitoFormsAuth } from '../auth';
+import { encodeSegment } from '../common/client';
+import { requireText } from '../common/entries';
+import { fetchCognitoFile } from '../common/files';
+import { fileOutputSchema } from '../output-schemas';
+
+export const downloadFileAction = createAction({
+ auth: cognitoFormsAuth,
+ name: 'download_file',
+ classification: 'READ',
+ displayName: 'Download File',
+ description: 'Downloads a file uploaded to an entry (from a File Upload or Signature field).',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Downloads one file stored in Cognito Forms by its file ID: the "Id" of an item in an entry\'s File Upload field, the "Id" of a Signature field\'s PngFile or SvgFile (from Get Entry), or the file_id returned by Get Entry Document and returns it as a file. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: fileOutputSchema,
+ props: {
+ file_id: Property.ShortText({
+ displayName: 'File ID',
+ description: 'The "Id" of an uploaded file or a signature\'s PngFile from an entry.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const fileId = requireText({ value: context.propsValue.file_id, label: 'File ID' });
+ return fetchCognitoFile({
+ apiKey: context.auth.secret_text,
+ path: `/files/${encodeSegment(fileId)}`,
+ files: context.files,
+ fallbackName: `cognito-file-${fileId}`,
+ });
+ },
+});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/get-entry-document.ts b/packages/pieces/community/cognito-forms/src/lib/actions/get-entry-document.ts
new file mode 100644
index 00000000000..01dc6fe2bb2
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/get-entry-document.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { cognitoFormsAuth } from '../auth';
+import { encodeSegment } from '../common/client';
+import { entryPath } from '../common/entries';
+import { fetchCognitoFile } from '../common/files';
+import { entryIdText, formIdText } from '../common/props';
+import { fileOutputSchema } from '../output-schemas';
+
+export const getEntryDocumentAction = createAction({
+ auth: cognitoFormsAuth,
+ name: 'get_entry_document',
+ classification: 'READ',
+ displayName: 'Get Entry Document',
+ description: 'Generates a document (PDF or Word) for an entry from one of the form\'s document templates.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Generates the document for one Cognito Forms entry using a template number (1 is the form\'s first document template) and returns it as a file. Needs a plan with document templates. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: fileOutputSchema,
+ props: {
+ form_id: formIdText,
+ entry_id: entryIdText('The entry number (for example 12) or the full entry ID (for example 5-12).'),
+ template_number: Property.Number({
+ displayName: 'Template Number',
+ description: 'The document template number (the first template is 1).',
+ required: true,
+ defaultValue: 1,
+ }),
+ },
+ async run(context) {
+ const { form_id, entry_id, template_number } = context.propsValue;
+ if (!Number.isInteger(template_number) || template_number < 1) {
+ throw new Error('Template Number must be a whole number of 1 or more.');
+ }
+ return fetchCognitoFile({
+ apiKey: context.auth.secret_text,
+ path: `${entryPath({ formId: form_id, entryId: entry_id })}/documents/${encodeSegment(template_number)}`,
+ files: context.files,
+ fallbackName: `entry-${entry_id}-document-${template_number}.pdf`,
+ });
+ },
+});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/get-entry.ts b/packages/pieces/community/cognito-forms/src/lib/actions/get-entry.ts
index 09fc2191829..435bae03460 100644
--- a/packages/pieces/community/cognito-forms/src/lib/actions/get-entry.ts
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/get-entry.ts
@@ -1,33 +1,31 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest } from '../common';
+import { createAction } from '@activepieces/pieces-framework';
import { cognitoFormsAuth } from '../auth';
-import { formIdDropdown } from '../common/props';
+import { cognitoRequest } from '../common/client';
+import { entryPath } from '../common/entries';
+import { entryIdText, formIdDropdown } from '../common/props';
export const getEntryAction = createAction({
auth: cognitoFormsAuth,
name: 'get_entry',
classification: 'READ',
displayName: 'Get Entry',
- description: 'Gets a specified entry.',
- audience: 'both',
- aiMetadata: { description: 'Retrieves a single entry from a Cognito Forms form by its entry ID. Choose this to read back the field values of one known submission. Read-only and idempotent; requires both the form ID and the entry ID.', idempotent: true },
+ description: 'Gets an entry by its number or ID.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Retrieves one Cognito Forms entry by form and entry ID. Read-only and idempotent.',
+ idempotent: true,
+ },
props: {
formId: formIdDropdown,
- entryId: Property.ShortText({
- displayName: 'Entry ID',
- required: true,
- description: 'Enter the ID of the entry to retrieve.',
- }),
+ entryId: entryIdText('The entry number (for example 12) or the full entry ID (for example 5-12).'),
},
async run(context) {
- const apiKey = context.auth;
const { formId, entryId } = context.propsValue;
-
- return await makeRequest(
- apiKey,
- HttpMethod.GET,
- `/forms/${formId}/entries/${entryId}`
- );
+ return cognitoRequest<unknown>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: entryPath({ formId: formId, entryId: entryId }),
+ });
},
});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/get-form-schema.ts b/packages/pieces/community/cognito-forms/src/lib/actions/get-form-schema.ts
new file mode 100644
index 00000000000..323565b46fd
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/get-form-schema.ts
@@ -0,0 +1,42 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { cognitoFormsAuth } from '../auth';
+import { cognitoRequest } from '../common/client';
+import { formPath } from '../common/entries';
+import { formIdText, readSchemaFields } from '../common/props';
+import { formSchemaOutputSchema } from '../output-schemas';
+
+export const getFormSchemaAction = createAction({
+ auth: cognitoFormsAuth,
+ name: 'get_form_schema',
+ classification: 'READ',
+ displayName: 'Get Form Schema',
+ description: 'Gets the fields of a form: names, types and which are required or read-only.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns the field list of one Cognito Forms form (name, type, required, read-only, allowed values) plus the raw JSON schema. Call it before creating or updating an entry to know the exact field names and value shapes. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: formSchemaOutputSchema,
+ props: {
+ form_id: formIdText,
+ },
+ async run(context) {
+ const { form_id } = context.propsValue;
+ const schema = await cognitoRequest<unknown>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${formPath(form_id)}/schema`,
+ });
+ const fields = readSchemaFields(schema).map((field) => ({
+ name: field.name,
+ title: field.title ?? null,
+ type: field.type,
+ required: field.required,
+ read_only: field.readOnly,
+ description: field.description ?? null,
+ allowed_values: field.enumValues,
+ }));
+ return { form_id, field_count: fields.length, fields, raw_schema: schema };
+ },
+});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/list-forms.ts b/packages/pieces/community/cognito-forms/src/lib/actions/list-forms.ts
new file mode 100644
index 00000000000..4f817eaa97e
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/list-forms.ts
@@ -0,0 +1,30 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { cognitoFormsAuth } from '../auth';
+import { listForms } from '../common/entries';
+import { listFormsOutputSchema } from '../output-schemas';
+
+export const listFormsAction = createAction({
+ auth: cognitoFormsAuth,
+ name: 'list_forms',
+ classification: 'SEARCH',
+ displayName: 'List Forms',
+ description: 'Lists the forms the API key can access.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists all non-archived Cognito Forms forms the API key can access, with each form ID, name and internal name. Use it to find the form ID other actions need. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: listFormsOutputSchema,
+ props: {},
+ async run(context) {
+ const forms = await listForms(context.auth.secret_text);
+ return {
+ count: forms.length,
+ forms: forms.map((form) => ({
+ id: form.Id ?? null,
+ name: form.Name ?? null,
+ internal_name: form.InternalName ?? null,
+ })),
+ };
+ },
+});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/set-form-availability.ts b/packages/pieces/community/cognito-forms/src/lib/actions/set-form-availability.ts
new file mode 100644
index 00000000000..f7e6916367f
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/set-form-availability.ts
@@ -0,0 +1,62 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { cognitoFormsAuth } from '../auth';
+import { cognitoRequest, isRecord } from '../common/client';
+import { formPath, readString } from '../common/entries';
+import { formIdText } from '../common/props';
+import { availabilityOutputSchema } from '../output-schemas';
+
+export const setFormAvailabilityAction = createAction({
+ auth: cognitoFormsAuth,
+ name: 'set_form_availability',
+ classification: 'WRITE',
+ displayName: 'Set Form Availability',
+ description: 'Opens or closes a form\'s public link for a date range. Leave both dates empty to make the form always available.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Sets when a Cognito Forms form\'s public link accepts entries: an optional start and end date-time plus the message shown outside that window. Omitting both dates makes the form available all the time. Replaces the previous availability settings. Idempotent.',
+ idempotent: true,
+ },
+ outputSchema: availabilityOutputSchema,
+ props: {
+ form_id: formIdText,
+ start: Property.DateTime({
+ displayName: 'Available From',
+ description: 'When the form starts accepting entries. Empty means no start limit.',
+ required: false,
+ }),
+ end: Property.DateTime({
+ displayName: 'Available Until',
+ description: 'When the form stops accepting entries. Leave empty for no end limit.',
+ required: false,
+ }),
+ message: Property.LongText({
+ displayName: 'Not Available Message',
+ description: 'Shown to people who open the form outside the availability window.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const { form_id, start, end, message } = context.propsValue;
+ if (start && end && new Date(start).getTime() > new Date(end).getTime()) {
+ throw new Error('"Available From" must be before "Available Until".');
+ }
+ const body: Record<string, string> = {};
+ if (start) body['start'] = start;
+ if (end) body['end'] = end;
+ if (message) body['message'] = message;
+ const response = await cognitoRequest<unknown>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.POST,
+ path: `${formPath(form_id)}/public-link-availability`,
+ body,
+ });
+ const result = isRecord(response) ? response : {};
+ return {
+ form_id,
+ availability_start: readString(result['AvailabilityStart'] ?? result['availabilityStart']) ?? null,
+ availability_end: readString(result['AvailabilityEnd'] ?? result['availabilityEnd']) ?? null,
+ not_available_message: readString(result['NotAvailableMessage'] ?? result['notAvailableMessage']) ?? null,
+ };
+ },
+});
diff --git a/packages/pieces/community/cognito-forms/src/lib/actions/update-entry.ts b/packages/pieces/community/cognito-forms/src/lib/actions/update-entry.ts
index 56891bc33e9..67e89e8c4cb 100644
--- a/packages/pieces/community/cognito-forms/src/lib/actions/update-entry.ts
+++ b/packages/pieces/community/cognito-forms/src/lib/actions/update-entry.ts
@@ -1,35 +1,37 @@
-import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { makeRequest } from '../common';
+import { createAction } from '@activepieces/pieces-framework';
import { cognitoFormsAuth } from '../auth';
-import { formFields, formIdDropdown } from '../common/props';
+import { cognitoRequest } from '../common/client';
+import { entryPath, stripEmptyValues } from '../common/entries';
+import { entryIdText, formIdDropdown, updateFormFields } from '../common/props';
export const updateEntryAction = createAction({
auth: cognitoFormsAuth,
name: 'update_entry',
classification: 'WRITE',
displayName: 'Update Entry',
- description: 'Update an existing entry.',
- audience: 'both',
- aiMetadata: { description: 'Updates an existing entry in a Cognito Forms form, identified by its entry ID, applying the provided field values. Choose this when you already have the entry ID and want to modify its data rather than create a new one. Idempotent: repeating with the same field values leaves the entry in the same state.', idempotent: true },
+ description: 'Updates an existing entry. Fields you leave empty keep their current value.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Updates an existing Cognito Forms entry by entry ID with the fields filled in; empty fields are left unchanged. Idempotent: repeating with the same values leaves the entry in the same state.',
+ idempotent: true,
+ },
props: {
formId: formIdDropdown,
- entryId: Property.ShortText({
- displayName: 'Entry ID',
- required: true,
- description: 'Enter the ID of the entry you want to update.',
- }),
- entryData: formFields,
+ entryId: entryIdText('The entry number (for example 12) or the full entry ID (for example 5-12). You can map it from a trigger or a "Create Entry" step.'),
+ entryData: updateFormFields,
},
async run(context) {
- const apiKey = context.auth;
const { formId, entryId, entryData } = context.propsValue;
-
- return await makeRequest(
- apiKey,
- HttpMethod.PATCH,
- `/forms/${formId}/entries/${entryId}`,
- entryData
- );
+ const body = stripEmptyValues(entryData);
+ if (Object.keys(body).length === 0) {
+ throw new Error('Fill in at least one field to update.');
+ }
+ return cognitoRequest<unknown>({
+ apiKey: context.auth.secret_text,
+ method: HttpMethod.PATCH,
+ path: entryPath({ formId: formId, entryId: entryId }),
+ body,
+ });
},
});
diff --git a/packages/pieces/community/cognito-forms/src/lib/auth.ts b/packages/pieces/community/cognito-forms/src/lib/auth.ts
index fad17d83d91..401112dbea0 100644
--- a/packages/pieces/community/cognito-forms/src/lib/auth.ts
+++ b/packages/pieces/community/cognito-forms/src/lib/auth.ts
@@ -1,26 +1,31 @@
-import { PieceAuth } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
-import { AppConnectionType } from '@activepieces/pieces-framework';
-import { makeRequest } from './common';
+import { PieceAuth } from '@activepieces/pieces-framework';
+import { CognitoFormsApiError, cognitoRequest } from './common/client';
export const cognitoFormsAuth = PieceAuth.SecretText({
displayName: 'API Key',
required: true,
description: `
- 1. Click your organization's name in the top left corner and then click Settings.
- 2. Go to the Integrations section and select + New API Key.
- 3. Make sure to copy and store your API key, as it cannot be retrieved later.
+1. Sign in to Cognito Forms as an organization owner or admin.
+2. Click your organization's name in the top left corner, then click **Settings**.
+3. Open **Integrations** and click **+ New API Key**.
+4. Give the key the scopes you need (**Read** to look up forms and entries, **Write** to create or update entries, **Delete** to delete entries) and access to the forms you want to use.
+5. Copy the key and paste it here. Cognito Forms only shows it once.
+
+The Cognito Forms API needs a paid plan.
`,
validate: async ({ auth }) => {
try {
- await makeRequest({secret_text: auth, type: AppConnectionType.SECRET_TEXT}, HttpMethod.GET, '/forms');
-
+ await cognitoRequest<unknown>({ apiKey: auth, method: HttpMethod.GET, path: '/forms' });
return { valid: true };
- } catch {
- return {
- valid: false,
- error: 'Invalid API Key.',
- };
+ } catch (error) {
+ if (error instanceof CognitoFormsApiError && error.status === 401) {
+ return { valid: false, error: 'Invalid API key. Copy the key again from Organization Settings > Integrations.' };
+ }
+ if (error instanceof CognitoFormsApiError && error.status === 403) {
+ return { valid: false, error: 'This API key cannot read forms. Give it the Read scope in Organization Settings > Integrations.' };
+ }
+ return { valid: false, error: error instanceof Error ? error.message : 'Could not verify the API key.' };
}
},
});
diff --git a/packages/pieces/community/cognito-forms/src/lib/common/client.ts b/packages/pieces/community/cognito-forms/src/lib/common/client.ts
new file mode 100644
index 00000000000..10fd331a5aa
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/common/client.ts
@@ -0,0 +1,133 @@
+import { httpClient, HttpError, HttpMethod, QueryParams } from '@activepieces/pieces-common';
+
+export const COGNITO_API_BASE = 'https://www.cognitoforms.com/api';
+
+
+export class CognitoFormsApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ readonly errorType: string | undefined,
+ readonly responseBody: unknown,
+ ) {
+ super(message);
+ this.name = 'CognitoFormsApiError';
+ }
+}
+
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+export function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));
+ return verifiedTlsAgent;
+}
+
+export async function cognitoRequest<T>({
+ apiKey,
+ method,
+ path,
+ body,
+ query,
+}: {
+ apiKey: string;
+ method: HttpMethod;
+ path: string;
+ body?: unknown;
+ query?: QueryParams;
+}): Promise<T> {
+ try {
+ const response = await httpClient.sendRequest<T>({
+ method,
+ url: `${COGNITO_API_BASE}${path}`,
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ Accept: 'application/json',
+ },
+ body,
+ queryParams: query,
+ timeout: REQUEST_TIMEOUT_MS,
+ redactBodyInErrors: true,
+ }, { dispatcher: await verifiedTls() });
+ return response.body;
+ } catch (error) {
+ throw toCognitoError(error);
+ }
+}
+
+export function toCognitoError(error: unknown): Error {
+ if (error instanceof CognitoFormsApiError) {
+ return error;
+ }
+ if (error instanceof HttpError) {
+ const status = error.response.status;
+ const responseBody = error.response.body;
+ const vendor = readVendorError(responseBody);
+ return new CognitoFormsApiError(describeStatus({ status, vendor }), status, vendor.type, responseBody);
+ }
+ if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
+ return new Error(`Cognito Forms did not respond within ${REQUEST_TIMEOUT_MS / 1000} seconds. Please try again.`);
+ }
+ const reason = error instanceof Error ? error.message : String(error);
+ return new Error(`Could not reach Cognito Forms: ${reason}`);
+}
+
+export function encodeSegment(value: string | number): string {
+ return encodeURIComponent(String(value).trim());
+}
+
+function describeStatus({ status, vendor }: { status: number; vendor: VendorError }): string {
+ const detail = vendor.message ? ` Cognito Forms said: "${vendor.message}"` : '';
+ const data = vendor.data ? ` Details: ${vendor.data}` : '';
+ switch (status) {
+ case 400:
+ case 422:
+ return `Cognito Forms rejected the request (${status}).${detail}${data} Check that the field names and values match the form (use "Get Form Schema").`;
+ case 401:
+ return `Cognito Forms rejected the API key (401). Check the key in your connection, or create a new one under Organization Settings > Integrations.${detail}`;
+ case 402:
+ return `This feature needs a paid Cognito Forms plan (402).${detail}`;
+ case 403:
+ return `The API key is not allowed to do this (403). In Cognito Forms, open Organization Settings > Integrations and give the key the needed scope (Read, Write or Delete) and access to this form.${detail}`;
+ case 404:
+ return `Not found (404).${detail} Check the IDs you passed.`;
+ case 429:
+ return `Cognito Forms rate limit reached (429). Wait a minute and try again.${detail}`;
+ default:
+ return `Cognito Forms request failed (${status}).${detail}${data}`;
+ }
+}
+
+type VendorError = { message?: string; type?: string; data?: string };
+
+function readVendorError(body: unknown): VendorError {
+ if (typeof body === 'string') {
+ return { message: body.slice(0, 500) || undefined };
+ }
+ if (!isRecord(body)) {
+ return {};
+ }
+ const message = typeof body['Message'] === 'string' ? body['Message'] : undefined;
+ const type = typeof body['Type'] === 'string' ? body['Type'] : undefined;
+ const rawData = body['Data'];
+ const data = hasContent(rawData) ? JSON.stringify(rawData).slice(0, 1000) : undefined;
+ return { message, type, data };
+}
+
+function hasContent(value: unknown): boolean {
+ if (value === null || value === undefined) {
+ return false;
+ }
+ if (Array.isArray(value)) {
+ return value.length > 0;
+ }
+ if (isRecord(value)) {
+ return Object.keys(value).length > 0;
+ }
+ return true;
+}
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+const REQUEST_TIMEOUT_MS = 60000;
diff --git a/packages/pieces/community/cognito-forms/src/lib/common/delete.ts b/packages/pieces/community/cognito-forms/src/lib/common/delete.ts
new file mode 100644
index 00000000000..ca7fab3b510
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/common/delete.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { CognitoFormsApiError, cognitoRequest } from './client';
+import { entryPath } from './entries';
+
+export async function deleteEntry({
+ apiKey,
+ formId,
+ entryId,
+}: {
+ apiKey: string;
+ formId: string;
+ entryId: string;
+}): Promise<DeleteEntryResult> {
+ const path = entryPath({ formId: formId, entryId: entryId });
+ try {
+ await cognitoRequest<unknown>({ apiKey, method: HttpMethod.DELETE, path });
+ return { deleted: true, already_deleted: false, form_id: formId, entry_id: entryId };
+ } catch (error) {
+ if (error instanceof CognitoFormsApiError && error.status === 404 && error.errorType === 'EntryNotFound') {
+ return { deleted: true, already_deleted: true, form_id: formId, entry_id: entryId };
+ }
+ throw error;
+ }
+}
+
+export type DeleteEntryResult = {
+ deleted: boolean;
+ already_deleted: boolean;
+ form_id: string;
+ entry_id: string;
+};
diff --git a/packages/pieces/community/cognito-forms/src/lib/common/entries.ts b/packages/pieces/community/cognito-forms/src/lib/common/entries.ts
new file mode 100644
index 00000000000..d26ba9d5430
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/common/entries.ts
@@ -0,0 +1,134 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { cognitoRequest, encodeSegment, isRecord } from './client';
+
+
+export async function listForms(apiKey: string): Promise<CognitoForm[]> {
+ const body = await cognitoRequest<unknown>({ apiKey, method: HttpMethod.GET, path: '/forms' });
+ if (!Array.isArray(body)) {
+ return [];
+ }
+ return body.filter(isRecord).map((form) => ({
+ Id: readString(form['Id']),
+ Name: readString(form['Name']),
+ InternalName: readString(form['InternalName']),
+ }));
+}
+
+export function formPath(formId: string): string {
+ return `/forms/${encodeSegment(requireText({ value: formId, label: 'Form' }))}`;
+}
+
+export function entryPath({ formId, entryId }: { formId: string; entryId: string | number }): string {
+ return `${formPath(formId)}/entries/${encodeSegment(requireText({ value: String(entryId), label: 'Entry ID' }))}`;
+}
+
+export function requireText({ value, label }: { value: string | undefined | null; label: string }): string {
+ const trimmed = (value ?? '').trim();
+ if (trimmed.length === 0) {
+ throw new Error(`${label} is required.`);
+ }
+ return trimmed;
+}
+
+export function stripEmptyValues(values: Record<string, unknown> | undefined | null): Record<string, unknown> {
+ const result: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(values ?? {})) {
+ if (value === undefined || value === null) {
+ continue;
+ }
+ if (typeof value === 'string' && value.trim() === '') {
+ continue;
+ }
+ if (Array.isArray(value) && value.length === 0) {
+ continue;
+ }
+ if (isRecord(value) && Object.keys(value).length === 0) {
+ continue;
+ }
+ result[key] = value;
+ }
+ return result;
+}
+
+export function parseFieldsObject(value: unknown): Record<string, unknown> {
+ const parsed = typeof value === 'string' ? safeJsonParse(value) : value;
+ if (!isRecord(parsed)) {
+ throw new Error('Fields must be a JSON object that maps field names to values, for example {"Name": {"First": "Ada", "Last": "Lovelace"}, "Email": "[email protected]"}.');
+ }
+ return parsed;
+}
+
+function safeJsonParse(value: string): unknown {
+ try {
+ return JSON.parse(value);
+ } catch {
+ throw new Error('Fields is not valid JSON.');
+ }
+}
+
+export const ENTRY_META_KEYS = new Set(['Id', 'Form', 'Entry', '$type', '$etag', '$version']);
+
+export function normalizeEntry(raw: unknown): NormalizedEntry {
+ const entry = isRecord(raw) ? raw : {};
+ const meta = isRecord(entry['Entry']) ? entry['Entry'] : {};
+ const form = isRecord(entry['Form']) ? entry['Form'] : {};
+ const fields: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(entry)) {
+ if (!ENTRY_META_KEYS.has(key)) {
+ fields[key] = value;
+ }
+ }
+ return {
+ entry_id: readString(entry['Id']) ?? null,
+ entry_number: readNumber(meta['Number']) ?? null,
+ status: readString(meta['Status']) ?? null,
+ version: readNumber(meta['Version']) ?? null,
+ date_created: readString(meta['DateCreated']) ?? null,
+ date_submitted: readString(meta['DateSubmitted']) ?? null,
+ date_updated: readString(meta['DateUpdated']) ?? null,
+ admin_link: readString(meta['AdminLink']) ?? null,
+ public_link: readString(meta['PublicLink']) ?? null,
+ internal_link: readString(meta['InternalLink']) ?? null,
+ form_id: readString(form['Id']) ?? null,
+ form_name: readString(form['Name']) ?? null,
+ fields,
+ };
+}
+
+export type NormalizedEntry = {
+ entry_id: string | null;
+ entry_number: number | null;
+ status: string | null;
+ version: number | null;
+ date_created: string | null;
+ date_submitted: string | null;
+ date_updated: string | null;
+ admin_link: string | null;
+ public_link: string | null;
+ internal_link: string | null;
+ form_id: string | null;
+ form_name: string | null;
+ fields: Record<string, unknown>;
+};
+
+export function readString(value: unknown): string | undefined {
+ if (typeof value === 'string') {
+ return value;
+ }
+ if (typeof value === 'number') {
+ return String(value);
+ }
+ return undefined;
+}
+
+function readNumber(value: unknown): number | undefined {
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ return value;
+ }
+ if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) {
+ return Number(value);
+ }
+ return undefined;
+}
+
+export type CognitoForm = { Id?: string; Name?: string; InternalName?: string };
diff --git a/packages/pieces/community/cognito-forms/src/lib/common/files.ts b/packages/pieces/community/cognito-forms/src/lib/common/files.ts
new file mode 100644
index 00000000000..19c952aec82
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/common/files.ts
@@ -0,0 +1,117 @@
+import { httpClient, HttpMethod } from '@activepieces/pieces-common';
+import { FilesService } from '@activepieces/pieces-framework';
+import { Readable } from 'node:stream';
+import { cognitoRequest, isRecord, toCognitoError, verifiedTls } from './client';
+import { readString } from './entries';
+
+
+export async function fetchCognitoFile({
+ apiKey,
+ path,
+ files,
+ fallbackName,
+}: {
+ apiKey: string;
+ path: string;
+ files: FilesService;
+ fallbackName: string;
+}): Promise<CognitoFileOutput> {
+ const body = await cognitoRequest<unknown>({ apiKey, method: HttpMethod.GET, path });
+ const ref = isRecord(body) ? body : {};
+ const fileName = readString(ref['Name']) ?? fallbackName;
+ const url = readString(ref['File']) ?? null;
+ const content = readString(ref['Content']);
+ const data = content ? decodeContent(content) : url ? await downloadUrl(url) : null;
+ if (!data) {
+ throw new Error('Cognito Forms returned the file details without any content or download link.');
+ }
+ const file = await files.write({ fileName, data });
+ return {
+ file,
+ file_id: readString(ref['Id']) ?? null,
+ file_name: fileName,
+ content_type: readString(ref['ContentType']) ?? null,
+ size: typeof ref['Size'] === 'number' ? ref['Size'] : data.length,
+ url,
+ };
+}
+
+export function decodeContent(content: string): Buffer {
+ const padding = content.endsWith('==') ? 2 : content.endsWith('=') ? 1 : 0;
+ const estimated = Math.floor((content.replace(/\s/g, '').length * 3) / 4) - padding;
+ if (estimated > MAX_FILE_BYTES) {
+ throw tooLarge();
+ }
+ return Buffer.from(content, 'base64');
+}
+
+async function downloadUrl(url: string): Promise<Buffer> {
+ let stream: Readable;
+ let declared: number;
+ try {
+ const response = await httpClient.sendRequest<Readable>({
+ method: HttpMethod.GET,
+ url,
+ headers: { Accept: '*/*' },
+ responseType: 'stream',
+ timeout: DOWNLOAD_TIMEOUT_MS,
+ }, { dispatcher: await verifiedTls() });
+ stream = response.body;
+ const header = response.headers?.['content-length'];
+ declared = Number(Array.isArray(header) ? header[0] : header);
+ } catch (error) {
+ throw toCognitoError(error);
+ }
+ if (Number.isFinite(declared) && declared > MAX_FILE_BYTES) {
+ stream.destroy();
+ throw tooLarge();
+ }
+ return readCapped(stream);
+}
+
+function readCapped(stream: Readable): Promise<Buffer> {
+ return new Promise((resolve, reject) => {
+ const chunks: Buffer[] = [];
+ let total = 0;
+ let settled = false;
+ const finish = (error?: Error) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (error) {
+ stream.destroy();
+ reject(error);
+ } else {
+ resolve(Buffer.concat(chunks, total));
+ }
+ };
+ const timer = setTimeout(() => finish(new Error(`The file download did not finish within ${DOWNLOAD_TIMEOUT_MS / 1000} seconds.`)), DOWNLOAD_TIMEOUT_MS);
+ stream.on('data', (chunk: Buffer | string) => {
+ const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
+ total += buffer.length;
+ if (total > MAX_FILE_BYTES) {
+ finish(tooLarge());
+ return;
+ }
+ chunks.push(buffer);
+ });
+ stream.on('end', () => finish());
+ stream.on('error', (error: Error) => finish(new Error(`Could not download the file: ${error.message}`)));
+ });
+}
+
+function tooLarge(): Error {
+ return new Error(`The file is larger than ${MAX_FILE_BYTES / 1024 / 1024} MB.`);
+}
+
+export type CognitoFileOutput = {
+ file: string;
+ file_id: string | null;
+ file_name: string;
+ content_type: string | null;
+ size: number;
+ url: string | null;
+};
+
+const DOWNLOAD_TIMEOUT_MS = 120000;
+export const MAX_FILE_BYTES = 100 * 1024 * 1024;
diff --git a/packages/pieces/community/cognito-forms/src/lib/common/index.ts b/packages/pieces/community/cognito-forms/src/lib/common/index.ts
deleted file mode 100644
index 4f20cd5e2d1..00000000000
--- a/packages/pieces/community/cognito-forms/src/lib/common/index.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
-import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';
-import { cognitoFormsAuth } from '../auth';
-
-export const BASE_URL = 'https://www.cognitoforms.com/api';
-
-export async function makeRequest(
- {secret_text}: AppConnectionValueForAuthProperty<typeof cognitoFormsAuth>,
- method: HttpMethod,
- path: string,
- body?: unknown
-) {
- const response = await httpClient.sendRequest({
- method,
- url: `${BASE_URL}${path}`,
- headers: {
- Authorization: `Bearer ${secret_text}`,
- 'Content-Type': 'application/json',
- },
- body,
- });
-
- return response.body;
-}
diff --git a/packages/pieces/community/cognito-forms/src/lib/common/props.ts b/packages/pieces/community/cognito-forms/src/lib/common/props.ts
index f2f271051f8..231b13f5c99 100644
--- a/packages/pieces/community/cognito-forms/src/lib/common/props.ts
+++ b/packages/pieces/community/cognito-forms/src/lib/common/props.ts
@@ -1,107 +1,181 @@
-import {
- Property,
- DropdownOption,
- DynamicPropsValue,
-} from '@activepieces/pieces-framework';
-import { makeRequest } from './index';
import { HttpMethod } from '@activepieces/pieces-common';
+import { DynamicPropsValue, Property } from '@activepieces/pieces-framework';
import { cognitoFormsAuth } from '../auth';
+import { cognitoRequest, isRecord } from './client';
+import { ENTRY_META_KEYS, formPath, listForms } from './entries';
export const formIdDropdown = Property.Dropdown({
auth: cognitoFormsAuth,
displayName: 'Form',
+ description: 'Pick the form. Only forms the API key has access to are listed.',
required: true,
refreshers: [],
options: async ({ auth }) => {
if (!auth) {
+ return { disabled: true, placeholder: 'Please connect your Cognito Forms account first', options: [] };
+ }
+ try {
+ const forms = await listForms(auth.secret_text);
+ const options = forms
+ .filter((form) => form.Id !== undefined)
+ .map((form) => ({ label: form.Name ?? form.InternalName ?? String(form.Id), value: String(form.Id) }));
+ if (options.length === 0) {
+ return { disabled: true, placeholder: 'No forms found for this API key', options: [] };
+ }
+ return { disabled: false, options };
+ } catch (error) {
return {
disabled: true,
- placeholder: 'Please connect your Cognito Forms account',
+ placeholder: error instanceof Error ? error.message.slice(0, 200) : 'Could not load forms',
options: [],
};
}
-
- const apiKey = auth;
- const forms = await makeRequest(apiKey, HttpMethod.GET, '/forms');
-
- const options: DropdownOption<string>[] = forms.map((form: any) => ({
- label: form.Name,
- value: form.Id,
- }));
-
- return {
- disabled: false,
- options,
- };
},
});
-export const formFields = Property.DynamicProperties({
- displayName: 'Fields',
- auth: cognitoFormsAuth,
- refreshers: ['formId'],
+export const formIdText = Property.ShortText({
+ displayName: 'Form ID',
+ description: 'The form ID or internal name, as returned by "List Forms".',
required: true,
- props: async ({ auth, formId }) => {
- if (!auth || !formId) return {};
+});
- const apiKey = auth;
- const response = await makeRequest(
- apiKey,
- HttpMethod.GET,
- `/forms/${formId}/schema`
- );
+export const entryIdText = (description: string) =>
+ Property.ShortText({
+ displayName: 'Entry ID',
+ description,
+ required: true,
+ });
- const fields = response as FormSchemaResponse;
+export const entryFieldsJson = (description: string) =>
+ Property.Json({
+ displayName: 'Fields',
+ description,
+ required: true,
+ });
- const props: DynamicPropsValue = {};
+export const formFields = fieldsProp({ forUpdate: false });
- for (const [key, value] of Object.entries(fields.properties)) {
- const fieldType = value.type;
- const fieldName = key;
- const fieldDes = value.description;
- const isReadOnly = value.readOnly;
+export const updateFormFields = fieldsProp({ forUpdate: true });
- if (isReadOnly) continue;
+function fieldsProp({ forUpdate }: { forUpdate: boolean }) {
+ return Property.DynamicProperties({
+ displayName: 'Fields',
+ auth: cognitoFormsAuth,
+ refreshers: ['formId'],
+ required: true,
+ props: async ({ auth, formId }) => {
+ if (!auth || typeof formId !== 'string' || formId.length === 0) {
+ return {};
+ }
+ const schema = await cognitoRequest<unknown>({
+ apiKey: auth.secret_text,
+ method: HttpMethod.GET,
+ path: `${formPath(formId)}/schema`,
+ });
+ return buildFieldProps({ schema, forUpdate });
+ },
+ });
+}
- switch (fieldType) {
- case 'string':
- props[fieldName] = Property.ShortText({
- displayName: fieldName,
- description: fieldDes ?? '',
- required: false,
- });
- break;
- case 'boolean':
- props[fieldName] = Property.Checkbox({
- displayName: fieldName,
- description: fieldDes ?? '',
+export function buildFieldProps({ schema, forUpdate = false }: { schema: unknown; forUpdate?: boolean }): DynamicPropsValue {
+ const props: DynamicPropsValue = {};
+ for (const field of readSchemaFields(schema)) {
+ if (field.readOnly) {
+ continue;
+ }
+ const displayName = field.title ?? field.description ?? field.name;
+ const description = field.title && field.description ? field.description : '';
+ if (field.enumValues.length > 0 && field.type === 'string') {
+ props[field.name] = Property.StaticDropdown({
+ displayName,
+ description,
+ required: false,
+ options: { disabled: false, options: field.enumValues.map((value) => ({ label: value, value })) },
+ });
+ continue;
+ }
+ switch (field.type) {
+ case 'string':
+ props[field.name] = Property.ShortText({ displayName, description, required: false });
+ break;
+ case 'boolean':
+ props[field.name] = forUpdate
+ ? Property.StaticDropdown({
+ displayName,
+ description: description || 'Leave empty to keep the current value.',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Yes', value: true },
+ { label: 'No', value: false },
+ ],
+ },
+ })
+ : Property.Checkbox({ displayName, description, required: false });
+ break;
+ case 'number':
+ case 'integer':
+ props[field.name] = Property.Number({ displayName, description, required: false });
+ break;
+ default:
+ props[field.name] = Property.Json({
+ displayName,
+ description: `${description ? `${description} ` : ''}Enter this field as JSON (for example a name, address, choice list or table rows).`,
+ required: false,
+ });
+ break;
+ }
+ }
+ return props;
+}
- required: false,
- });
- break;
- case 'number':
- props[fieldName] = Property.Number({
- displayName: fieldName,
- description: fieldDes ?? '',
- required: false,
- });
- break;
- default:
- break;
- }
+export function readSchemaFields(schema: unknown): SchemaField[] {
+ if (!isRecord(schema) || !isRecord(schema['properties'])) {
+ return [];
+ }
+ const required = Array.isArray(schema['required'])
+ ? schema['required'].filter((item): item is string => typeof item === 'string')
+ : [];
+ const fields: SchemaField[] = [];
+ for (const [name, value] of Object.entries(schema['properties'])) {
+ if (!isRecord(value) || ENTRY_META_KEYS.has(name)) {
+ continue;
}
- return props;
- },
-});
+ fields.push({
+ name,
+ type: readType(value),
+ title: typeof value['title'] === 'string' ? value['title'] : undefined,
+ description: typeof value['description'] === 'string' ? value['description'] : undefined,
+ readOnly: value['readOnly'] === true,
+ required: required.includes(name),
+ enumValues: Array.isArray(value['enum'])
+ ? value['enum'].filter((item): item is string => typeof item === 'string')
+ : [],
+ });
+ }
+ return fields;
+}
+
+function readType(value: Record<string, unknown>): string {
+ const type = value['type'];
+ if (typeof type === 'string') {
+ return type;
+ }
+ if (Array.isArray(type)) {
+ const first = type.find((item): item is string => typeof item === 'string' && item !== 'null');
+ return first ?? 'object';
+ }
+ return 'object';
+}
-type FormSchemaResponse = {
+export type SchemaField = {
+ name: string;
type: string;
- properties: {
- [x: string]: {
- type: string;
- readOnly: boolean;
- description: string;
- };
- };
+ title?: string;
+ description?: string;
+ readOnly: boolean;
+ required: boolean;
+ enumValues: string[];
};
diff --git a/packages/pieces/community/cognito-forms/src/lib/common/trigger-helpers.ts b/packages/pieces/community/cognito-forms/src/lib/common/trigger-helpers.ts
new file mode 100644
index 00000000000..ca0d85740ec
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/common/trigger-helpers.ts
@@ -0,0 +1,82 @@
+export const sampleEntry = {
+ Form: { Id: '1', InternalName: 'ContactUs', Name: 'Contact Us' },
+ Name: 'Ada Lovelace',
+ Address: {
+ City: 'Austin',
+ CityStatePostalCode: 'Austin, TX 78701',
+ Country: 'United States',
+ CountryCode: null,
+ FullAddress: '1 Test St, Austin, TX 78701',
+ FullInternationalAddress: '1 Test St, Austin, TX 78701, United States',
+ Latitude: null,
+ Line1: '1 Test St',
+ Line2: null,
+ Line3: null,
+ Longitude: null,
+ PostalCode: '78701',
+ State: 'TX',
+ StreetAddress: '1 Test St',
+ Type: 'Home',
+ },
+ Phone: '(555) 010-0100',
+ Email: '[email protected]',
+ Signature: {
+ Name: 'Signature.png',
+ ContentType: 'image/png',
+ Content: 'iVBORw0KGgo=',
+ File: 'https://www.cognitoforms.com/sf/temporary-signature-link',
+ },
+ Files: [
+ {
+ ContentType: 'application/pdf',
+ Id: 'F-Wb5Xb2YH8YuTOBuEh83zu',
+ IsEncrypted: false,
+ Name: 'resume.pdf',
+ Size: 120766,
+ File: 'https://www.cognitoforms.com/fa/temporary-file-link',
+ },
+ ],
+ Id: '1-12',
+ Entry: {
+ AdminLink: 'https://www.cognitoforms.com/acme/1/entries/12',
+ DateCreated: '2026-10-20T15:04:00.723Z',
+ DateSubmitted: '2026-10-20T15:04:00.723Z',
+ DateUpdated: '2026-10-20T15:04:00.723Z',
+ Number: 12,
+ Order: null,
+ Origin: {
+ City: null,
+ CountryCode: null,
+ IpAddress: '203.0.113.10',
+ IsImported: false,
+ Region: null,
+ Timezone: null,
+ UserAgent: 'Mozilla/5.0',
+ },
+ Timestamp: '2026-10-20T15:04:00.723Z',
+ User: { Email: '[email protected]', FirstName: 'Ada', LastName: 'Lovelace', Name: 'Ada Lovelace' },
+ Version: 1,
+ Action: 'Submit',
+ Role: 'Public',
+ Status: 'Submitted',
+ PublicLink: 'https://www.cognitoforms.com/acme/ContactUs#public-link-token',
+ InternalLink: 'https://www.cognitoforms.com/acme/ContactUs#internal-link-token',
+ Document1: 'https://www.cognitoforms.com/d/temporary-document-link',
+ },
+};
+
+export function webhookInstructions(endpointLabel: string): string {
+ return `
+To use this trigger, connect your form to the webhook URL in Cognito Forms:
+
+1. Open your form in Cognito Forms and go to **Build**, then **Form Settings**.
+2. Turn on **Post JSON Data to Website**.
+3. Paste the following URL into the **${endpointLabel}** field only:
+\`\`\`text
+{{webhookUrl}}
+\`\`\`
+4. Save the form.
+
+Cognito Forms does not sign these requests, so keep the URL private. Posting JSON data needs a paid Cognito Forms plan.
+`;
+}
diff --git a/packages/pieces/community/cognito-forms/src/lib/output-schemas.ts b/packages/pieces/community/cognito-forms/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..03feb282c8d
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/src/lib/output-schemas.ts
@@ -0,0 +1,86 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+export const entryOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'entry_id', label: 'Entry ID' },
+ { key: 'entry_number', label: 'Entry Number', format: 'number' },
+ { key: 'status', label: 'Status' },
+ { key: 'version', label: 'Version', format: 'number' },
+ { key: 'date_created', label: 'Date Created', format: 'datetime' },
+ { key: 'date_submitted', label: 'Date Submitted', format: 'datetime' },
+ { key: 'date_updated', label: 'Date Updated', format: 'datetime' },
+ { key: 'admin_link', label: 'Admin Link', format: 'url' },
+ { key: 'public_link', label: 'Public Link', format: 'url' },
+ { key: 'internal_link', label: 'Internal Link', format: 'url' },
+ { key: 'form_id', label: 'Form ID' },
+ { key: 'form_name', label: 'Form Name' },
+ { key: 'fields', label: 'Fields' },
+ ],
+};
+
+export const deleteEntryOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean' },
+ { key: 'already_deleted', label: 'Already Deleted', format: 'boolean' },
+ { key: 'form_id', label: 'Form ID' },
+ { key: 'entry_id', label: 'Entry ID' },
+ ],
+};
+
+export const listFormsOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'count', label: 'Count', format: 'number' },
+ {
+ key: 'forms',
+ label: 'Forms',
+ labelKey: 'name',
+ listItems: [
+ { key: 'id', label: 'Form ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'internal_name', label: 'Internal Name' },
+ ],
+ },
+ ],
+};
+
+export const formSchemaOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'form_id', label: 'Form ID' },
+ { key: 'field_count', label: 'Field Count', format: 'number' },
+ {
+ key: 'fields',
+ label: 'Fields',
+ labelKey: 'name',
+ listItems: [
+ { key: 'name', label: 'Name' },
+ { key: 'title', label: 'Title' },
+ { key: 'type', label: 'Type' },
+ { key: 'required', label: 'Required', format: 'boolean' },
+ { key: 'read_only', label: 'Read Only', format: 'boolean' },
+ { key: 'description', label: 'Description' },
+ { key: 'allowed_values', label: 'Allowed Values' },
+ ],
+ },
+ { key: 'raw_schema', label: 'Raw Schema' },
+ ],
+};
+
+export const availabilityOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'form_id', label: 'Form ID' },
+ { key: 'availability_start', label: 'Available From', format: 'datetime' },
+ { key: 'availability_end', label: 'Available Until', format: 'datetime' },
+ { key: 'not_available_message', label: 'Not Available Message' },
+ ],
+};
+
+export const fileOutputSchema: OutputSchema = {
+ fields: [
+ { key: 'file', label: 'File', format: 'url' },
+ { key: 'file_id', label: 'File ID' },
+ { key: 'file_name', label: 'File Name' },
+ { key: 'content_type', label: 'Content Type' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'url', label: 'Temporary Download Link', format: 'url' },
+ ],
+};
diff --git a/packages/pieces/community/cognito-forms/src/lib/triggers/entry-updated.ts b/packages/pieces/community/cognito-forms/src/lib/triggers/entry-updated.ts
index b25cef3dd27..17e1bd355eb 100644
--- a/packages/pieces/community/cognito-forms/src/lib/triggers/entry-updated.ts
+++ b/packages/pieces/community/cognito-forms/src/lib/triggers/entry-updated.ts
@@ -1,9 +1,6 @@
-import {
- createTrigger,
- Property,
- TriggerStrategy,
-} from '@activepieces/pieces-framework';
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
import { cognitoFormsAuth } from '../auth';
+import { sampleEntry, webhookInstructions } from '../common/trigger-helpers';
export const entryUpdatedTrigger = createTrigger({
name: 'entry_updated',
@@ -11,33 +8,22 @@ export const entryUpdatedTrigger = createTrigger({
displayName: 'Entry Updated',
description: 'Triggers when an existing form entry is updated.',
aiMetadata: {
- description: 'Fires when an existing entry in a Cognito Forms form is updated, delivering the updated entry data. Requires the form to be configured to post JSON to the webhook URL on entry update.',
+ description: 'Fires when an existing entry in a Cognito Forms form is updated, delivering the updated entry with its field values at the top level and status, dates and links under "Entry". Requires the form to post JSON to the webhook URL on update. Cognito Forms may resend an update if delivery fails.',
},
auth: cognitoFormsAuth,
props: {
webhookInstructions: Property.MarkDown({
- value: `
- To use this trigger, you need to manually set up a webhook in your Cognito Forms account:
-
- 1. Login to your Cognito Forms account.
- 2. Select desired form and go to Form Settings.
- 3. Enable **Post JSON Data to Website** and add following URL in **Update Entry Endpoint** field:
- \`\`\`text
- {{webhookUrl}}
- \`\`\`
- 4. Click Save to save the form changes.
- `,
+ value: webhookInstructions('Update Entry Endpoint'),
}),
},
type: TriggerStrategy.WEBHOOK,
- sampleData: undefined,
- async onEnable(context) {
- // No need to register webhooks programmatically as user will do it manually
+ sampleData: sampleEntry,
+ async onEnable() {
+ return;
},
- async onDisable(context) {
- // No need to unregister webhooks as user will do it manually
+ async onDisable() {
+ return;
},
-
async run(context) {
return [context.payload.body];
},
diff --git a/packages/pieces/community/cognito-forms/src/lib/triggers/new-entry-submitted.ts b/packages/pieces/community/cognito-forms/src/lib/triggers/new-entry-submitted.ts
index 42994cb3268..ff458932507 100644
--- a/packages/pieces/community/cognito-forms/src/lib/triggers/new-entry-submitted.ts
+++ b/packages/pieces/community/cognito-forms/src/lib/triggers/new-entry-submitted.ts
@@ -1,9 +1,6 @@
-import {
- createTrigger,
- Property,
- TriggerStrategy,
-} from '@activepieces/pieces-framework';
+import { createTrigger, Property, TriggerStrategy } from '@activepieces/pieces-framework';
import { cognitoFormsAuth } from '../auth';
+import { sampleEntry, webhookInstructions } from '../common/trigger-helpers';
export const newEntryTrigger = createTrigger({
name: 'new_entry',
@@ -11,33 +8,22 @@ export const newEntryTrigger = createTrigger({
displayName: 'New Entry',
description: 'Triggers when a new form entry is submitted.',
aiMetadata: {
- description: 'Fires when a new entry is submitted to a Cognito Forms form, delivering the submitted entry data. Requires the form to be configured to post JSON to the webhook URL on entry submission.',
+ description: 'Fires when a new entry is submitted to a Cognito Forms form, delivering the entry with its field values at the top level and status, dates and links under "Entry". Requires the form to post JSON to the webhook URL on submit. Cognito Forms may resend an entry if delivery fails, so the same entry can arrive more than once.',
},
auth: cognitoFormsAuth,
props: {
webhookInstructions: Property.MarkDown({
- value: `
- To use this trigger, you need to manually set up a webhook in your Cognito Forms account:
-
- 1. Login to your Cognito Forms account.
- 2. Select desired form and go to Form Settings.
- 3. Enable **Post JSON Data to Website** and add following URL in **Submit Entry Endpoint** field:
- \`\`\`text
- {{webhookUrl}}
- \`\`\`
- 4. Click Save to save the form changes.
- `,
+ value: webhookInstructions('Submit Entry Endpoint'),
}),
},
type: TriggerStrategy.WEBHOOK,
- sampleData: undefined,
- async onEnable(context) {
- // No need to register webhooks programmatically as user will do it manually
+ sampleData: sampleEntry,
+ async onEnable() {
+ return;
},
- async onDisable(context) {
- // No need to unregister webhooks as user will do it manually
+ async onDisable() {
+ return;
},
-
async run(context) {
return [context.payload.body];
},
diff --git a/packages/pieces/community/cognito-forms/test/cognito-forms.test.ts b/packages/pieces/community/cognito-forms/test/cognito-forms.test.ts
new file mode 100644
index 00000000000..1d6febad4e5
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/test/cognito-forms.test.ts
@@ -0,0 +1,395 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { cognitoForms } from '../src';
+import { createEntryAiAction } from '../src/lib/actions/ai/create-entry-ai';
+import { deleteEntryAiAction } from '../src/lib/actions/ai/delete-entry-ai';
+import { getEntryAiAction } from '../src/lib/actions/ai/get-entry-ai';
+import { updateEntryAiAction } from '../src/lib/actions/ai/update-entry-ai';
+import { createEntryAction } from '../src/lib/actions/create-entry';
+import { deleteEntryAction } from '../src/lib/actions/delete-entry';
+import { downloadFileAction } from '../src/lib/actions/download-file';
+import { getEntryDocumentAction } from '../src/lib/actions/get-entry-document';
+import { getFormSchemaAction } from '../src/lib/actions/get-form-schema';
+import { listFormsAction } from '../src/lib/actions/list-forms';
+import { setFormAvailabilityAction } from '../src/lib/actions/set-form-availability';
+import { updateEntryAction } from '../src/lib/actions/update-entry';
+import { cognitoFormsAuth } from '../src/lib/auth';
+import { CognitoFormsApiError } from '../src/lib/common/client';
+import { normalizeEntry, stripEmptyValues } from '../src/lib/common/entries';
+import { decodeContent, MAX_FILE_BYTES } from '../src/lib/common/files';
+import { buildFieldProps } from '../src/lib/common/props';
+import { sampleEntry } from '../src/lib/common/trigger-helpers';
+
+const KEY = 'test-key';
+const BASE = 'https://www.cognitoforms.com/api';
+
+
+function stubFetch(responses: Fake[]): Call[] {
+ const calls: Call[] = [];
+ const fetchMock = vi.fn(async (input: string | URL, init?: RequestInit) => {
+ const headers: Record<string, string> = {};
+ new Headers(init?.headers).forEach((value, key) => {
+ headers[key] = value;
+ });
+ const raw = typeof init?.body === 'string' ? init.body : undefined;
+ calls.push({ method: init?.method ?? 'GET', url: String(input), headers, body: raw ? JSON.parse(raw) : undefined });
+ const next = responses.shift();
+ if (!next) {
+ throw new Error(`Unexpected request ${String(input)}`);
+ }
+ const status = next.status ?? 200;
+ const payload = next.body === undefined ? null : JSON.stringify(next.body);
+ return new Response(status === 204 ? null : payload, { status, headers: { 'content-type': 'application/json' } });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return calls;
+}
+
+function ctx(props: Record<string, unknown>) {
+ const written: { fileName: string; data: Buffer }[] = [];
+ return {
+ written,
+ context: {
+ auth: { type: 'SECRET_TEXT', secret_text: KEY },
+ propsValue: props,
+ files: {
+ write: async ({ fileName, data }: { fileName: string; data: Buffer }) => {
+ written.push({ fileName, data });
+ return `file://${fileName}`;
+ },
+ },
+ },
+ };
+}
+
+async function run({ action, props }: { action: { run: unknown }; props: Record<string, unknown> }) {
+ const { context, written } = ctx(props);
+ if (typeof action.run !== 'function') {
+ throw new Error('no run');
+ }
+ const output: unknown = await Reflect.apply(action.run, action, [context]);
+ return { output, written };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('piece wiring', () => {
+ it('registers 13 actions plus custom call and keeps one agent tool per job', () => {
+ const actions = Object.values(cognitoForms.actions());
+ expect(actions).toHaveLength(14);
+ const agentVisible = actions.filter((a) => a.audience === 'ai' || a.audience === 'both').map((a) => a.name);
+ expect(agentVisible.sort()).toEqual(
+ ['create_entry_ai', 'delete_entry_ai', 'download_file', 'get_entry_ai', 'get_entry_document', 'get_form_schema', 'list_forms', 'set_form_availability', 'update_entry_ai'].sort(),
+ );
+ for (const name of ['create_entry', 'update_entry', 'get_entry', 'delete_entry']) {
+ expect(cognitoForms.actions()[name].audience).toBe('human');
+ }
+ });
+
+ it('custom API call sends the secret text, not the auth object', async () => {
+ const custom = cognitoForms.actions()['custom_api_call'];
+ expect(custom).toBeDefined();
+ const calls = stubFetch([{ body: [] }]);
+ await run({ action: custom, props: { url: { url: `${BASE}/forms` }, method: 'GET', headers: {}, queryParams: {}, failsafe: false } });
+ expect(calls[0].headers['authorization']).toBe(`Bearer ${KEY}`);
+ });
+});
+
+describe('custom api call', () => {
+ const custom = () => cognitoForms.actions()['custom_api_call'];
+ const props = (url: string) => ({ url: { url }, method: 'GET', headers: {}, queryParams: {}, failsafe: false });
+
+ it('uses the TLS-verifying dispatcher and resolves relative paths', async () => {
+ const inits: RequestInit[] = [];
+ const urls: string[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (input: string | URL, init?: RequestInit) => {
+ urls.push(String(input));
+ inits.push(init ?? {});
+ return new Response('[]', { status: 200, headers: { 'content-type': 'application/json' } });
+ }));
+ await run({ action: custom(), props: props('/forms') });
+ const { Agent } = await import('undici');
+ expect(urls[0]).toBe(`${BASE}/forms`);
+ expect(Reflect.get(inits[0], 'dispatcher')).toBeInstanceOf(Agent);
+ });
+
+ it.each([
+ ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'output.docx'],
+ ['application/msword; charset=binary', 'output.doc'],
+ ['application/vnd.ms-excel', 'output.xls'],
+ ['application/x-unknown', 'output.txt'],
+ ])('names binary %s responses %s', async (contentType, fileName) => {
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(new Uint8Array([1, 2, 3]), { status: 200, headers: { 'content-type': contentType } })));
+ const { output, written } = await run({ action: custom(), props: { ...props('/forms'), response_is_binary: true } });
+ expect(written.map((w) => w.fileName)).toEqual([fileName]);
+ expect(Reflect.get(Object(output), 'body')).toBe(`file://${fileName}`);
+ });
+
+ it('refuses other hosts and dot segments', async () => {
+ stubFetch([]);
+ await expect(run({ action: custom(), props: props('https://evil.example/api/forms') })).rejects.toThrow('must be on');
+ await expect(run({ action: custom(), props: props('http://www.cognitoforms.com/api/forms') })).rejects.toThrow('must be on');
+ await expect(run({ action: custom(), props: props('/forms/../../x') })).rejects.toThrow('..');
+ });
+});
+
+describe('auth validate', () => {
+ const validate = cognitoFormsAuth.validate;
+ it('accepts a working key', async () => {
+ stubFetch([{ body: [] }]);
+ expect(await validate?.({ auth: KEY, server: { apiUrl: '', publicUrl: '' } })).toEqual({ valid: true });
+ });
+ it('reports 401 as invalid key and 403 as missing scope', async () => {
+ stubFetch([{ status: 401, body: { Message: 'AccessToken invalid.' } }, { status: 403, body: { Message: 'nope' } }]);
+ const r401 = await validate?.({ auth: KEY, server: { apiUrl: '', publicUrl: '' } });
+ expect(r401?.valid).toBe(false);
+ expect(r401?.error).toContain('Invalid API key');
+ const r403 = await validate?.({ auth: KEY, server: { apiUrl: '', publicUrl: '' } });
+ expect(r403?.error).toContain('Read scope');
+ });
+});
+
+describe('human entry actions', () => {
+ it('create strips empty values and posts to the form', async () => {
+ const calls = stubFetch([{ body: sampleEntry }]);
+ const { output } = await run({ action: createEntryAction, props: { formId: '5', entryData: { Email: '[email protected]', Phone: '', Note: undefined, Agree: false, Tags: [] } } });
+ expect(calls[0].method).toBe('POST');
+ expect(calls[0].url).toBe(`${BASE}/forms/5/entries`);
+ expect(calls[0].body).toEqual({ Email: '[email protected]', Agree: false });
+ expect(output).toEqual(sampleEntry);
+ });
+
+ it('update PATCHes only filled values and refuses an empty update', async () => {
+ const calls = stubFetch([{ body: sampleEntry }]);
+ await run({ action: updateEntryAction, props: { formId: '5', entryId: ' 12 ', entryData: { Email: '[email protected]', Name: '' } } });
+ expect(calls[0].method).toBe('PATCH');
+ expect(calls[0].url).toBe(`${BASE}/forms/5/entries/12`);
+ expect(calls[0].body).toEqual({ Email: '[email protected]' });
+ await expect(run({ action: updateEntryAction, props: { formId: '5', entryId: '12', entryData: { Name: '' } } })).rejects.toThrow('at least one field');
+ });
+
+ it('delete treats a missing entry as already deleted but not a missing form', async () => {
+ stubFetch([{ status: 204 }, { status: 404, body: { Type: 'EntryNotFound', Message: 'Entry not found.' } }, { status: 404, body: { Type: 'FormNotFound', Message: 'Form not found.' } }]);
+ expect((await run({ action: deleteEntryAction, props: { formId: '5', entryId: '12' } })).output).toEqual({ deleted: true, already_deleted: false, form_id: '5', entry_id: '12' });
+ expect((await run({ action: deleteEntryAction, props: { formId: '5', entryId: '12' } })).output).toEqual({ deleted: true, already_deleted: true, form_id: '5', entry_id: '12' });
+ await expect(run({ action: deleteEntryAction, props: { formId: '9', entryId: '12' } })).rejects.toThrow('Form not found');
+ });
+
+ it('delete fails on a 404 that is not EntryNotFound', async () => {
+ stubFetch([{ status: 404, body: { Message: 'Not found.' } }]);
+ await expect(run({ action: deleteEntryAction, props: { formId: '9', entryId: '12' } })).rejects.toThrow();
+ });
+});
+
+describe('ai entry actions', () => {
+ it('create parses JSON fields and normalizes output', async () => {
+ const calls = stubFetch([{ body: sampleEntry }]);
+ const { output } = await run({ action: createEntryAiAction, props: { form_id: 'ContactUs', fields: '{"Email":"[email protected]","Name":{"First":"Ada"}}' } });
+ expect(calls[0].body).toEqual({ Email: '[email protected]', Name: { First: 'Ada' } });
+ expect(output).toMatchObject({ entry_id: '1-12', entry_number: 12, status: 'Submitted', form_name: 'Contact Us', internal_link: 'https://www.cognitoforms.com/acme/ContactUs#internal-link-token' });
+ });
+
+ it('create rejects non-object fields', async () => {
+ stubFetch([]);
+ await expect(run({ action: createEntryAiAction, props: { form_id: '5', fields: '[1]' } })).rejects.toThrow('JSON object');
+ await expect(run({ action: createEntryAiAction, props: { form_id: '5', fields: '{bad' } })).rejects.toThrow('not valid JSON');
+ });
+
+ it('update sends null to clear a field', async () => {
+ const calls = stubFetch([{ body: sampleEntry }]);
+ await run({ action: updateEntryAiAction, props: { form_id: '5', entry_id: '5-12', fields: { Message: null } } });
+ expect(calls[0].url).toBe(`${BASE}/forms/5/entries/5-12`);
+ expect(calls[0].body).toEqual({ Message: null });
+ });
+
+ it('get encodes path segments', async () => {
+ const calls = stubFetch([{ body: sampleEntry }]);
+ await run({ action: getEntryAiAction, props: { form_id: 'a/b', entry_id: '1' } });
+ expect(calls[0].url).toBe(`${BASE}/forms/a%2Fb/entries/1`);
+ });
+
+ it('delete ai shares the delete logic', async () => {
+ stubFetch([{ status: 204 }]);
+ expect((await run({ action: deleteEntryAiAction, props: { form_id: '5', entry_id: '1' } })).output).toMatchObject({ deleted: true });
+ });
+});
+
+describe('form actions', () => {
+ it('list forms maps the response', async () => {
+ stubFetch([{ body: [{ Id: '5', Name: 'Contact Us', InternalName: 'ContactUs' }] }]);
+ expect((await run({ action: listFormsAction, props: {} })).output).toEqual({ count: 1, forms: [{ id: '5', name: 'Contact Us', internal_name: 'ContactUs' }] });
+ });
+
+ it('get form schema flattens fields', async () => {
+ const schema = {
+ type: 'object',
+ required: ['Email'],
+ properties: {
+ Email: { type: 'string', title: 'Email' },
+ Size: { type: 'string', enum: ['S', 'M'] },
+ Name: { $ref: '#/definitions/Name' },
+ Notes: { type: 'string', readOnly: true },
+ Id: { type: 'string' },
+ Entry: { type: 'object' },
+ },
+ };
+ stubFetch([{ body: schema }]);
+ const { output } = await run({ action: getFormSchemaAction, props: { form_id: '5' } });
+ expect(output).toMatchObject({
+ form_id: '5',
+ field_count: 4,
+ fields: [
+ { name: 'Email', type: 'string', required: true, read_only: false },
+ { name: 'Size', allowed_values: ['S', 'M'] },
+ { name: 'Name', type: 'object' },
+ { name: 'Notes', read_only: true },
+ ],
+ });
+ });
+
+ it('set availability posts only given values and maps the response', async () => {
+ const calls = stubFetch([{ body: { AvailabilityStart: null, AvailabilityEnd: '2026-12-01T00:00:00Z', NotAvailableMessage: 'Closed' } }]);
+ const { output } = await run({ action: setFormAvailabilityAction, props: { form_id: '5', end: '2026-12-01T00:00:00Z', message: 'Closed' } });
+ expect(calls[0].method).toBe('POST');
+ expect(calls[0].url).toBe(`${BASE}/forms/5/public-link-availability`);
+ expect(calls[0].body).toEqual({ end: '2026-12-01T00:00:00Z', message: 'Closed' });
+ expect(output).toEqual({ form_id: '5', availability_start: null, availability_end: '2026-12-01T00:00:00Z', not_available_message: 'Closed' });
+ });
+
+ it('set availability rejects start after end', async () => {
+ stubFetch([]);
+ await expect(run({ action: setFormAvailabilityAction, props: { form_id: '5', start: '2026-12-02T00:00:00Z', end: '2026-12-01T00:00:00Z' } })).rejects.toThrow('before');
+ });
+});
+
+describe('files', () => {
+ it('download file writes base64 content', async () => {
+ stubFetch([{ body: { Id: 'f1', Name: 'a.txt', ContentType: 'text/plain', Size: 5, File: 'https://files.example/a', Content: Buffer.from('hello').toString('base64') } }]);
+ const { output, written } = await run({ action: downloadFileAction, props: { file_id: 'f1' } });
+ expect(written[0].data.toString()).toBe('hello');
+ expect(output).toEqual({ file: 'file://a.txt', file_id: 'f1', file_name: 'a.txt', content_type: 'text/plain', size: 5, url: 'https://files.example/a' });
+ });
+
+ it('document falls back to the temporary link without sending the API key', async () => {
+ const calls = stubFetch([{ body: { Id: 'd1', Name: 'doc.pdf', ContentType: 'application/pdf', File: 'https://files.example/doc' } }, { body: 'PDF' }]);
+ const { written } = await run({ action: getEntryDocumentAction, props: { form_id: '5', entry_id: '12', template_number: 2 } });
+ expect(calls[0].url).toBe(`${BASE}/forms/5/entries/12/documents/2`);
+ expect(calls[1].headers['authorization']).toBeUndefined();
+ expect(written[0].fileName).toBe('doc.pdf');
+ });
+
+ it('rejects base64 content over the size cap before decoding', () => {
+ const spy = vi.spyOn(Buffer, 'from');
+ expect(() => decodeContent('A'.repeat(Math.ceil((MAX_FILE_BYTES * 4) / 3) + 8))).toThrow('larger than');
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it('rejects a download whose Content-Length is over the cap', async () => {
+ vi.stubGlobal('fetch', vi.fn(async (input: string | URL) => String(input).startsWith(BASE)
+ ? new Response(JSON.stringify({ Id: 'f1', Name: 'a.bin', File: 'https://files.example/a' }), { status: 200, headers: { 'content-type': 'application/json' } })
+ : new Response('x', { status: 200, headers: { 'content-length': String(MAX_FILE_BYTES + 1) } })));
+ await expect(run({ action: downloadFileAction, props: { file_id: 'f1' } })).rejects.toThrow('larger than');
+ });
+
+ it('aborts a streamed download once it passes the cap', async () => {
+ let pulled = 0;
+ const chunk = new Uint8Array(8 * 1024 * 1024);
+ const body = new ReadableStream<Uint8Array>({
+ pull(controller) {
+ pulled += 1;
+ if (pulled > 40) controller.close();
+ else controller.enqueue(chunk);
+ },
+ });
+ vi.stubGlobal('fetch', vi.fn(async (input: string | URL) => String(input).startsWith(BASE)
+ ? new Response(JSON.stringify({ Id: 'f1', Name: 'a.bin', File: 'https://files.example/a' }), { status: 200, headers: { 'content-type': 'application/json' } })
+ : new Response(body, { status: 200 })));
+ await expect(run({ action: downloadFileAction, props: { file_id: 'f1' } })).rejects.toThrow('larger than');
+ expect(pulled).toBeLessThan(20);
+ });
+
+ it('document rejects a bad template number', async () => {
+ stubFetch([]);
+ await expect(run({ action: getEntryDocumentAction, props: { form_id: '5', entry_id: '12', template_number: 0 } })).rejects.toThrow('Template Number');
+ });
+});
+
+describe('tls', () => {
+ it('passes a TLS-verifying undici dispatcher on API and download requests', async () => {
+ const inits: RequestInit[] = [];
+ const fetchMock = vi.fn(async (_input: string | URL, init?: RequestInit) => {
+ inits.push(init ?? {});
+ const body = inits.length === 1 ? { Id: 'f1', Name: 'a.txt', File: 'https://files.example/a' } : 'hello';
+ return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ await run({ action: downloadFileAction, props: { file_id: 'f1' } });
+ const { Agent } = await import('undici');
+ expect(inits).toHaveLength(2);
+ for (const init of inits) {
+ expect(Reflect.get(init, 'dispatcher')).toBeInstanceOf(Agent);
+ }
+ });
+});
+
+describe('errors', () => {
+ it('maps vendor errors to readable messages without a body field', async () => {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ stubFetch([{ status: 400, body: { Type: 'ValidationError', Message: 'Email is invalid.', Data: { Email: 'bad' } } }]);
+ const error = await run({ action: createEntryAiAction, props: { form_id: '5', fields: { Email: '[email protected]' } } }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(CognitoFormsApiError);
+ expect(String(error)).toContain('Email is invalid.');
+ expect(error).not.toHaveProperty('body');
+ expect(JSON.stringify(spy.mock.calls)).not.toContain('[email protected]');
+ });
+
+ it('429 explains the rate limit', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ stubFetch([{ status: 429, body: { Message: 'Too many' } }]);
+ await expect(run({ action: listFormsAction, props: {} })).rejects.toThrow('rate limit');
+ });
+});
+
+describe('helpers', () => {
+ it('stripEmptyValues keeps false and 0', () => {
+ expect(stripEmptyValues({ a: 0, b: false, c: '', d: null, e: {}, f: 'x' })).toEqual({ a: 0, b: false, f: 'x' });
+ });
+
+ it('buildFieldProps maps integer, enum and complex types', () => {
+ const props = buildFieldProps({
+ schema: { properties: {
+ Count: { type: 'integer' },
+ Size: { type: 'string', enum: ['S'] },
+ Address: { type: 'object' },
+ Rows: { type: 'array' },
+ Maybe: { type: ['null', 'number'] },
+ Locked: { type: 'string', readOnly: true },
+ Id: { type: 'string' },
+ } },
+ });
+ expect(Object.keys(props)).toEqual(['Count', 'Size', 'Address', 'Rows', 'Maybe']);
+ expect(props['Count'].type).toBe('NUMBER');
+ expect(props['Size'].type).toBe('STATIC_DROPDOWN');
+ expect(props['Address'].type).toBe('JSON');
+ expect(props['Maybe'].type).toBe('NUMBER');
+ });
+
+ it('buildFieldProps shows Yes/No fields as a dropdown on update, so unset ones are not sent', () => {
+ const schema = { properties: { Agree: { type: 'boolean' }, OptIn: { type: ['boolean', 'null'] } } };
+ expect(buildFieldProps({ schema })['Agree'].type).toBe('CHECKBOX');
+ const props = buildFieldProps({ schema, forUpdate: true });
+ expect(props['Agree'].type).toBe('STATIC_DROPDOWN');
+ expect(props['OptIn'].type).toBe('STATIC_DROPDOWN');
+ expect(stripEmptyValues({ Agree: undefined, OptIn: false, Status: 'Open' })).toEqual({ OptIn: false, Status: 'Open' });
+ });
+
+ it('normalizeEntry moves form fields under fields', () => {
+ const entry = normalizeEntry(sampleEntry);
+ expect(Object.keys(entry.fields).sort()).toEqual(['Address', 'Email', 'Files', 'Name', 'Phone', 'Signature']);
+ });
+});
+
+type Call = { method: string; url: string; headers: Record<string, string>; body: unknown };
+type Fake = { status?: number; body?: unknown };
diff --git a/packages/pieces/community/cognito-forms/vitest.config.ts b/packages/pieces/community/cognito-forms/vitest.config.ts
new file mode 100644
index 00000000000..ba8ade4a178
--- /dev/null
+++ b/packages/pieces/community/cognito-forms/vitest.config.ts
@@ -0,0 +1,17 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'node',
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})