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(heartbeat): manage members, groups, channels, threads and events from flows and AI agents (#16169)

Odai Ahmad19be1dd565f8
diff --git a/bun.lock b/bun.lock
index 15136e436f0..8ad0c6417de 100644
--- a/bun.lock
+++ b/bun.lock
@@ -4285,7 +4285,7 @@
},
"packages/pieces/community/heartbeat": {
"name": "@activepieces/piece-heartbeat",
- "version": "0.2.1",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -4295,6 +4295,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/hedy": {
diff --git a/packages/pieces/community/heartbeat/package.json b/packages/pieces/community/heartbeat/package.json
index a1635dd603f..0bb174d2209 100644
--- a/packages/pieces/community/heartbeat/package.json
+++ b/packages/pieces/community/heartbeat/package.json
@@ -1,12 +1,13 @@
{
"name": "@activepieces/piece-heartbeat",
- "version": "0.2.1",
+ "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:*",
@@ -16,6 +17,7 @@
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/heartbeat/src/i18n/translation.json b/packages/pieces/community/heartbeat/src/i18n/translation.json
index 73552969adc..7802475ccd3 100644
--- a/packages/pieces/community/heartbeat/src/i18n/translation.json
+++ b/packages/pieces/community/heartbeat/src/i18n/translation.json
@@ -1,9 +1,97 @@
{
- "Monitoring and alerting made easy": "Monitoring and alerting made easy",
- "\n 1. Login to your Heartbeat account\n 2. On the bottom-left, click on 'Admin Settings'\n 3. On the left panel, click on 'API Keys'\n 5. Click on 'Create API Key'\n 6. On the popup form, Enter the 'Label' to name the Key\n 7. Copy the API key and paste it below.\n": "\n 1. Login to your Heartbeat account\n 2. On the bottom-left, click on 'Admin Settings'\n 3. On the left panel, click on 'API Keys'\n 5. Click on 'Create API Key'\n 6. On the popup form, Enter the 'Label' to name the Key\n 7. Copy the API key and paste it below.\n",
+ "Community platform for members, groups, channels, threads, events and courses": "Community platform for members, groups, channels, threads, events and courses",
+ "API access is included in Heartbeat's Scale plan. To create a key:\n1. Log in to your Heartbeat community as an admin.\n2. Open **Settings**, then **Automation**, then **API Keys**.\n3. Click **Create API Key** and give it a label.\n4. Copy the key and paste it here.\n\nActions run as the admin who created the key.": "API access is included in Heartbeat's Scale plan. To create a key:\n1. Log in to your Heartbeat community as an admin.\n2. Open **Settings**, then **Automation**, then **API Keys**.\n3. Click **Create API Key** and give it a label.\n4. Copy the key and paste it here.\n\nActions run as the admin who created the key.",
"Create User": "Create User",
+ "Create Member (by Role ID)": "Create Member (by Role ID)",
+ "List Members": "List Members",
+ "Get Member": "Get Member",
+ "Find Member by Email": "Find Member by Email",
+ "Update Member": "Update Member",
+ "Remove Member (Deactivate)": "Remove Member (Deactivate)",
+ "Reactivate Member": "Reactivate Member",
+ "Pre-register Member": "Pre-register Member",
+ "List Completed Lessons": "List Completed Lessons",
+ "Mark Lessons Completed": "Mark Lessons Completed",
+ "List Roles": "List Roles",
+ "List Groups": "List Groups",
+ "Get Group": "Get Group",
+ "Create Group": "Create Group",
+ "Update Group": "Update Group",
+ "Delete Group": "Delete Group",
+ "Add Members to Group": "Add Members to Group",
+ "Remove Members from Group": "Remove Members from Group",
+ "List Channels": "List Channels",
+ "List Channel Categories": "List Channel Categories",
+ "Create Channel Category": "Create Channel Category",
+ "Create Channel": "Create Channel",
+ "Update Channel": "Update Channel",
+ "Delete Channel": "Delete Channel",
+ "List Threads": "List Threads",
+ "Get Thread": "Get Thread",
+ "Create Thread": "Create Thread",
+ "Reply to Thread": "Reply to Thread",
+ "Send Channel Chat Message": "Send Channel Chat Message",
+ "List Channel Chat Messages": "List Channel Chat Messages",
+ "Send Direct Message": "Send Direct Message",
+ "Get Direct Chat": "Get Direct Chat",
+ "List Direct Messages": "List Direct Messages",
+ "List Events": "List Events",
+ "Get Event": "Get Event",
+ "Get Event Attendance": "Get Event Attendance",
+ "Create Event": "Create Event",
+ "List Invitation Links": "List Invitation Links",
+ "Create Invitation Link": "Create Invitation Link",
+ "Invite Emails to Invitation Link": "Invite Emails to Invitation Link",
+ "List Courses": "List Courses",
+ "Get Lesson": "Get Lesson",
+ "List Documents": "List Documents",
+ "Get Document": "Get Document",
"Custom API Call": "Custom API Call",
"Create a new user in a Heartbeat community": "Create a new user in a Heartbeat community",
+ "Creates a member with a role ID and optional group IDs.": "Creates a member with a role ID and optional group IDs.",
+ "Lists community members, optionally filtered by text, group, role or admin status.": "Lists community members, optionally filtered by text, group, role or admin status.",
+ "Gets one member by user ID, including profile details.": "Gets one member by user ID, including profile details.",
+ "Looks up a member by exact email address.": "Looks up a member by exact email address.",
+ "Updates a member's profile, identified by email. Fields left empty stay as they are.": "Updates a member's profile, identified by email. Fields left empty stay as they are.",
+ "Deactivates a member by email. Their threads, comments and messages stay; Reactivate Member undoes it.": "Deactivates a member by email. Their threads, comments and messages stay; Reactivate Member undoes it.",
+ "Gives a deactivated member access to the community again.": "Gives a deactivated member access to the community again.",
+ "Pre-registers a person who becomes a member with this role and groups the first time they log in.": "Pre-registers a person who becomes a member with this role and groups the first time they log in.",
+ "Lists a member's completed course lessons, newest completion first.": "Lists a member's completed course lessons, newest completion first.",
+ "Adds lessons to a member's completed lessons. Never removes completions.": "Adds lessons to a member's completed lessons. Never removes completions.",
+ "Lists the roles in the community with their IDs.": "Lists the roles in the community with their IDs.",
+ "Lists the groups in the community.": "Lists the groups in the community.",
+ "Gets one group with its members.": "Gets one group with its members.",
+ "Creates a group, optionally under a parent group and with initial members.": "Creates a group, optionally under a parent group and with initial members.",
+ "Changes a group. Fields left empty stay as they are.": "Changes a group. Fields left empty stay as they are.",
+ "Deletes a group. Members stay in the community.": "Deletes a group. Members stay in the community.",
+ "Adds members to a group by email, optionally moving them out of sibling groups.": "Adds members to a group by email, optionally moving them out of sibling groups.",
+ "Removes members from a group by email. They stay in the community.": "Removes members from a group by email. They stay in the community.",
+ "Lists the channels in the community, optionally only one type.": "Lists the channels in the community, optionally only one type.",
+ "Lists the channel categories (sidebar sections).": "Lists the channel categories (sidebar sections).",
+ "Creates a channel category (sidebar section).": "Creates a channel category (sidebar section).",
+ "Creates a posts (threads) or chat channel in a category.": "Creates a posts (threads) or chat channel in a category.",
+ "Changes a channel's name, description, read-only setting or who can access it.": "Changes a channel's name, description, read-only setting or who can access it.",
+ "Permanently deletes a channel and all its threads.": "Permanently deletes a channel and all its threads.",
+ "Lists threads in a posts channel, newest first, one page at a time.": "Lists threads in a posts channel, newest first, one page at a time.",
+ "Gets one thread with its comments and replies.": "Gets one thread with its comments and replies.",
+ "Posts a new thread in a posts channel.": "Posts a new thread in a posts channel.",
+ "Adds a comment to a thread, or a reply to a comment.": "Adds a comment to a thread, or a reply to a comment.",
+ "Sends a message to a chat channel.": "Sends a message to a chat channel.",
+ "Lists messages in a chat channel, newest first, one page at a time.": "Lists messages in a chat channel, newest first, one page at a time.",
+ "Sends a direct message from an admin to a member.": "Sends a direct message from an admin to a member.",
+ "Returns the direct chat between two users, creating an empty one if none exists.": "Returns the direct chat between two users, creating an empty one if none exists.",
+ "Lists the 100 most recent messages of a direct chat that includes an admin.": "Lists the 100 most recent messages of a direct chat that includes an admin.",
+ "Lists community events, optionally for one group or a time range.": "Lists community events, optionally for one group or a time range.",
+ "Gets one event, optionally with the dates of all its occurrences.": "Gets one event, optionally with the dates of all its occurrences.",
+ "Gets who attended the last 10 occurrences of an event.": "Gets who attended the last 10 occurrences of an event.",
+ "Creates a community event and invites members, groups or outside guests.": "Creates a community event and invites members, groups or outside guests.",
+ "Lists the invitation links with their role and groups.": "Lists the invitation links with their role and groups.",
+ "Creates an invitation link that gives new members a role and groups.": "Creates an invitation link that gives new members a role and groups.",
+ "Lets these emails join through an invitation link, optionally emailing them the invitation.": "Lets these emails join through an invitation link, optionally emailing them the invitation.",
+ "Lists courses with their cohorts, modules and lessons.": "Lists courses with their cohorts, modules and lessons.",
+ "Gets one course lesson with its Markdown content.": "Gets one course lesson with its Markdown content.",
+ "Lists the community documents (wiki pages), one page at a time.": "Lists the community documents (wiki pages), one page at a time.",
+ "Gets one community document (wiki page) with its Markdown content.": "Gets one community document (wiki page) with its Markdown content.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Name": "Name",
"Email": "Email",
@@ -15,15 +103,79 @@
"LinkedIn": "LinkedIn",
"Twitter": "Twitter",
"Instagram": "Instagram",
+ "Website": "Website",
"Create introduction thread": "Create introduction thread",
+ "Role ID": "Role ID",
+ "Group IDs": "Group IDs",
+ "LinkedIn URL": "LinkedIn URL",
+ "Twitter URL": "Twitter URL",
+ "Instagram URL": "Instagram URL",
+ "Website URL": "Website URL",
+ "Post Introduction Thread": "Post Introduction Thread",
+ "Name or Email Contains": "Name or Email Contains",
+ "Group ID": "Group ID",
+ "Role Name": "Role Name",
+ "Admins Only": "Admins Only",
+ "Include Profile Details": "Include Profile Details",
+ "Limit": "Limit",
+ "User ID": "User ID",
+ "Fields to Clear": "Fields to Clear",
+ "Starting After (Cursor)": "Starting After (Cursor)",
+ "Member Email": "Member Email",
+ "Lesson IDs": "Lesson IDs",
+ "Completed At": "Completed At",
+ "Include Archived": "Include Archived",
+ "Include Members": "Include Members",
+ "Description": "Description",
+ "Member Emails": "Member Emails",
+ "Parent Group ID": "Parent Group ID",
+ "Isolated": "Isolated",
+ "Joinable": "Joinable",
+ "Remove from Sibling Groups": "Remove from Sibling Groups",
+ "Type": "Type",
+ "Channel Category ID": "Channel Category ID",
+ "Channel Type": "Channel Type",
+ "Visibility": "Visibility",
+ "Invited Member Emails": "Invited Member Emails",
+ "Invited Group IDs": "Invited Group IDs",
+ "Read Only": "Read Only",
+ "Channel ID": "Channel ID",
+ "Access": "Access",
+ "Allowed Member Emails": "Allowed Member Emails",
+ "Allowed Group IDs": "Allowed Group IDs",
+ "Include Comments": "Include Comments",
+ "Thread ID": "Thread ID",
+ "Text": "Text",
+ "Author (Admin User ID)": "Author (Admin User ID)",
+ "Created At": "Created At",
+ "Parent Comment ID": "Parent Comment ID",
+ "Sender (Admin User ID)": "Sender (Admin User ID)",
+ "Recipient User ID": "Recipient User ID",
+ "First User ID": "First User ID",
+ "Second User ID": "Second User ID",
+ "Chat ID": "Chat ID",
+ "Starts After": "Starts After",
+ "Starts Before": "Starts Before",
+ "Event ID": "Event ID",
+ "Include Occurrences": "Include Occurrences",
+ "Start Time": "Start Time",
+ "Duration (Minutes)": "Duration (Minutes)",
+ "Location": "Location",
+ "Custom Location": "Custom Location",
+ "Invited Emails": "Invited Emails",
+ "Invitation Link ID": "Invitation Link ID",
+ "Emails": "Emails",
+ "Send Invitation Email": "Send Invitation Email",
+ "Lesson ID": "Lesson ID",
+ "Document ID": "Document ID",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
"Body Type": "Body Type",
"Body": "Body",
- "Response is Binary ?": "Response is Binary ?",
- "No Error on Failure": "No Error on Failure",
- "Timeout (in seconds)": "Timeout (in seconds)",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
"Follow redirects": "Follow redirects",
"The user's full name": "The user's full name",
"The user's email. Must be unique to the community": "The user's email. Must be unique to the community",
@@ -32,20 +184,124 @@
"A Data URI scheme in the JPG, GIF, or PNG format. Ensure you use the proper content type (image/jpeg, image/png, image/gif) that matches the image data being provided": "A Data URI scheme in the JPG, GIF, or PNG format. Ensure you use the proper content type (image/jpeg, image/png, image/gif) that matches the image data being provided",
"The user's bio": "The user's bio",
"The user's status": "The user's status",
- "A link to the user's LinkedIn profile": "A link to the user's LinkedIn profile",
- "A link to the user's Twitter profile": "A link to the user's Twitter profile",
- "A link to the user's Instagram profile": "A link to the user's Instagram profile",
+ "A link to the user's LinkedIn profile (full URL including https://)": "A link to the user's LinkedIn profile (full URL including https://)",
+ "A link to the user's Twitter profile (full URL including https://)": "A link to the user's Twitter profile (full URL including https://)",
+ "A link to the user's Instagram profile (full URL including https://)": "A link to the user's Instagram profile (full URL including https://)",
+ "A link to the user's website (full URL including https://)": "A link to the user's website (full URL including https://)",
"If true and a value for bio is provided, an introduction thread for the user will be created in the channel designated for introductions in your community settings.": "If true and a value for bio is provided, an introduction thread for the user will be created in the channel designated for introductions in your community settings.",
+ "The member's full name.": "The member's full name.",
+ "Must be unique in the community.": "Must be unique in the community.",
+ "Use List Roles to find the ID.": "Use List Roles to find the ID.",
+ "Groups the member joins. Use List Groups to find IDs.": "Groups the member joins. Use List Groups to find IDs.",
+ "Full URL including https://": "Full URL including https://",
+ "When on and a bio is given, posts an introduction thread for the member in the community introductions channel.": "When on and a bio is given, posts an introduction thread for the member in the community introductions channel.",
+ "Case-insensitive text to match in the name or email.": "Case-insensitive text to match in the name or email.",
+ "Only members of this group. Use List Groups to find the ID.": "Only members of this group. Use List Groups to find the ID.",
+ "Only members with this role, for example Administrator, Moderator or User (see List Roles).": "Only members with this role, for example Administrator, Moderator or User (see List Roles).",
+ "Also return LinkedIn data and onboarding answers (larger output).": "Also return LinkedIn data and onboarding answers (larger output).",
+ "How many items to return (1-1000, default 100).": "How many items to return (1-1000, default 100).",
+ "Use List Members to find the ID.": "Use List Members to find the ID.",
+ "Email of the member to update.": "Email of the member to update.",
+ "Blank these fields. A field cannot be both set and cleared.": "Blank these fields. A field cannot be both set and cleared.",
+ "Email of the member to deactivate.": "Email of the member to deactivate.",
+ "Email of the member to reactivate.": "Email of the member to reactivate.",
+ "The person's full name.": "The person's full name.",
+ "Use List Groups to find IDs.": "Use List Groups to find IDs.",
+ "How many items to return (1-100, default 50).": "How many items to return (1-100, default 50).",
+ "Leave empty for the first page. To get the next page, pass the Next Cursor value from the previous run.": "Leave empty for the first page. To get the next page, pass the Next Cursor value from the previous run.",
+ "1-100 lesson IDs. Use List Courses to find them.": "1-100 lesson IDs. Use List Courses to find them.",
+ "When the lessons were completed. Defaults to now.": "When the lessons were completed. Defaults to now.",
+ "Also return each group member (ID, name, email).": "Also return each group member (ID, name, email).",
+ "Use List Groups to find the ID.": "Use List Groups to find the ID.",
+ "Emails of existing members to add (up to 100).": "Emails of existing members to add (up to 100).",
+ "Makes this a sub-group. Use List Groups to find the ID.": "Makes this a sub-group. Use List Groups to find the ID.",
+ "Members of an isolated group only see content shared with the group (see Heartbeat docs).": "Members of an isolated group only see content shared with the group (see Heartbeat docs).",
+ "Members can join the group themselves.": "Members can join the group themselves.",
+ "Members of an isolated group only see content shared with the group.": "Members of an isolated group only see content shared with the group.",
+ "1-100 emails of existing members.": "1-100 emails of existing members.",
+ "Also remove these members from other groups with the same parent group (moves them between stages).": "Also remove these members from other groups with the same parent group (moves them between stages).",
+ "1-100 member emails.": "1-100 member emails.",
+ "Use List Channel Categories to find the ID.": "Use List Channel Categories to find the ID.",
+ "Private channels are only visible to the invited members and groups.": "Private channels are only visible to the invited members and groups.",
+ "Who can access a private channel.": "Who can access a private channel.",
+ "Groups that can access a private channel. Use List Groups to find IDs.": "Groups that can access a private channel. Use List Groups to find IDs.",
+ "Only admins and moderators can post threads. Not available for chat channels.": "Only admins and moderators can post threads. Not available for chat channels.",
+ "Use List Channels to find the ID.": "Use List Channels to find the ID.",
+ "Used when Access is Restricted. Replaces the current list.": "Used when Access is Restricted. Replaces the current list.",
+ "A posts channel. Use List Channels to find the ID.": "A posts channel. Use List Channels to find the ID.",
+ "Also return each thread's comments (larger output).": "Also return each thread's comments (larger output).",
+ "How many items to return (1-100, default 20).": "How many items to return (1-100, default 20).",
+ "Use List Threads to find the ID.": "Use List Threads to find the ID.",
+ "Plain text is sent as paragraphs (one per line). HTML is also supported: p, a, b, h1, h2, h3, ul, li and br (other tags are removed; text outside p, h1-h3 or ul blocks is dropped by Heartbeat). Mention a member or group with @ followed by their ID, for example @3f2b6c1e-8d4a-4f6b-9c1d-2e5a7b8c9d0e; mentioned people are notified.": "Plain text is sent as paragraphs (one per line). HTML is also supported: p, a, b, h1, h2, h3, ul, li and br (other tags are removed; text outside p, h1-h3 or ul blocks is dropped by Heartbeat). Mention a member or group with @ followed by their ID, for example @3f2b6c1e-8d4a-4f6b-9c1d-2e5a7b8c9d0e; mentioned people are notified.",
+ "User ID of an admin to post as. Leave empty to post as the admin who created the API key. Use List Members to find admin IDs.": "User ID of an admin to post as. Leave empty to post as the admin who created the API key. Use List Members to find admin IDs.",
+ "Optional backdated creation time, for example when migrating posts. Defaults to now.": "Optional backdated creation time, for example when migrating posts. Defaults to now.",
+ "Reply under this top-level comment. Leave empty to comment on the thread itself.": "Reply under this top-level comment. Leave empty to comment on the thread itself.",
+ "Optional backdated creation time. Defaults to now.": "Optional backdated creation time. Defaults to now.",
+ "A chat channel. Use List Channels to find the ID.": "A chat channel. Use List Channels to find the ID.",
+ "Use List Members or Find Member by Email to find the ID.": "Use List Members or Find Member by Email to find the ID.",
+ "Use Get Direct Chat to find the ID.": "Use Get Direct Chat to find the ID.",
+ "Only events assigned to this group. Use List Groups to find the ID.": "Only events assigned to this group. Use List Groups to find the ID.",
+ "Only events whose start time is at or after this time.": "Only events whose start time is at or after this time.",
+ "Only events whose start time is before this time.": "Only events whose start time is before this time.",
+ "Use List Events to find the ID.": "Use List Events to find the ID.",
+ "Also list the start and end time of each occurrence (for recurring events).": "Also list the start and end time of each occurrence (for recurring events).",
+ "ISO 8601, for example 2026-10-13T15:00:00Z.": "ISO 8601, for example 2026-10-13T15:00:00Z.",
+ "Heartbeat creates a voice channel for the event. Zoom needs the Zoom integration connected in your Heartbeat settings.": "Heartbeat creates a voice channel for the event. Zoom needs the Zoom integration connected in your Heartbeat settings.",
+ "Used when Location is Custom, for example an address or a meeting link.": "Used when Location is Custom, for example an address or a meeting link.",
+ "Members are invited in Heartbeat; other emails get an external invitation.": "Members are invited in Heartbeat; other emails get an external invitation.",
+ "Use List Groups to find IDs. Add invitees: with none, Heartbeat may limit the event to admins.": "Use List Groups to find IDs. Add invitees: with none, Heartbeat may limit the event to admins.",
+ "Groups new members join. Use List Groups to find IDs.": "Groups new members join. Use List Groups to find IDs.",
+ "Use List Invitation Links to find the ID.": "Use List Invitation Links to find the ID.",
+ "1-100 email addresses.": "1-100 email addresses.",
+ "Yes emails each person an invitation now. No only allows them to sign up through the link.": "Yes emails each person an invitation now. No only allows them to sign up through the link.",
+ "Use List Courses to find the ID.": "Use List Courses to find the ID.",
+ "Use List Documents to find the ID.": "Use List Documents to find the ID.",
"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.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
+ "Leave unchanged": "Leave unchanged",
+ "Yes": "Yes",
+ "No": "No",
+ "Posts (threads)": "Posts (threads)",
+ "Chat": "Chat",
+ "Voice": "Voice",
+ "Public": "Public",
+ "Private": "Private",
+ "Public (everyone)": "Public (everyone)",
+ "Restricted to the emails and groups below": "Restricted to the emails and groups below",
+ "Heartbeat voice channel": "Heartbeat voice channel",
+ "Zoom": "Zoom",
+ "Custom (enter below)": "Custom (enter below)",
+ "Yes, email the invitation": "Yes, email the invitation",
+ "No, do not email": "No, do not email",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
"HEAD": "HEAD",
- "None": "None",
- "JSON": "JSON",
- "Form Data": "Form Data",
- "Raw": "Raw"
+ "New Member Joined": "New Member Joined",
+ "New Thread": "New Thread",
+ "New Mention in Thread or Comment": "New Mention in Thread or Comment",
+ "New Event": "New Event",
+ "New Direct Message to Admin": "New Direct Message to Admin",
+ "Fires when a new member joins the community. Members added with Create User or Create Member do not fire it.": "Fires when a new member joins the community. Members added with Create User or Create Member do not fire it.",
+ "Fires when a new thread is posted, in any channel or one channel.": "Fires when a new thread is posted, in any channel or one channel.",
+ "Fires when chosen members or groups are @mentioned in a thread or comment.": "Fires when chosen members or groups are @mentioned in a thread or comment.",
+ "Fires when a new event is created in the community.": "Fires when a new event is created in the community.",
+ "Fires when a chosen admin receives a direct message.": "Fires when a chosen admin receives a direct message.",
+ "Include Threads Moved Into the Channel": "Include Threads Moved Into the Channel",
+ "Mentioned User IDs": "Mentioned User IDs",
+ "Mentioned Group IDs": "Mentioned Group IDs",
+ "Channel IDs": "Channel IDs",
+ "Admin User ID": "Admin User ID",
+ "Only threads in this posts channel. Leave empty for all channels. Use List Channels to find the ID.": "Only threads in this posts channel. Leave empty for all channels. Use List Channels to find the ID.",
+ "Also fire when an existing thread is moved into the chosen channel.": "Also fire when an existing thread is moved into the chosen channel.",
+ "Fire when any of these members is mentioned. Use List Members to find IDs.": "Fire when any of these members is mentioned. Use List Members to find IDs.",
+ "Fire when any of these groups is mentioned. Use List Groups to find IDs.": "Fire when any of these groups is mentioned. Use List Groups to find IDs.",
+ "Only mentions in these channels. Leave empty for all channels.": "Only mentions in these channels. Leave empty for all channels.",
+ "The admin whose incoming direct messages fire this trigger. Use List Members (Admins Only) to find the ID.": "The admin whose incoming direct messages fire this trigger. Use List Members (Admins Only) to find the ID."
}
\ No newline at end of file
diff --git a/packages/pieces/community/heartbeat/src/index.ts b/packages/pieces/community/heartbeat/src/index.ts
index cf322f8a90a..747181183d3 100644
--- a/packages/pieces/community/heartbeat/src/index.ts
+++ b/packages/pieces/community/heartbeat/src/index.ts
@@ -1,43 +1,119 @@
import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import { createPiece, PieceAuth } from '@activepieces/pieces-framework';
-import { PieceCategory } from '@activepieces/pieces-framework';
+import { PieceCategory, createPiece } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from './lib/auth';
+import { HEARTBEAT_BASE_URL, heartbeatApi } from './lib/common/client';
import { heartBeatCreateUser } from './lib/actions/create-user';
+import { createMemberAction } from './lib/actions/ai/create-member';
+import { listUsersAction } from './lib/actions/list-users';
+import { getUserAction } from './lib/actions/get-user';
+import { findUserByEmailAction } from './lib/actions/find-user-by-email';
+import { updateUserAction } from './lib/actions/update-user';
+import { removeUserAction } from './lib/actions/remove-user';
+import { reactivateUserAction } from './lib/actions/reactivate-user';
+import { createPendingUserAction } from './lib/actions/create-pending-user';
+import { listUserCompletedLessonsAction } from './lib/actions/list-user-completed-lessons';
+import { markLessonsCompletedAction } from './lib/actions/mark-lessons-completed';
+import { listRolesAction } from './lib/actions/list-roles';
+import { listGroupsAction } from './lib/actions/list-groups';
+import { getGroupAction } from './lib/actions/get-group';
+import { createGroupAction } from './lib/actions/create-group';
+import { updateGroupAction } from './lib/actions/update-group';
+import { deleteGroupAction } from './lib/actions/delete-group';
+import { addUsersToGroupAction } from './lib/actions/add-users-to-group';
+import { removeUsersFromGroupAction } from './lib/actions/remove-users-from-group';
+import { listChannelsAction } from './lib/actions/list-channels';
+import { listChannelCategoriesAction } from './lib/actions/list-channel-categories';
+import { createChannelCategoryAction } from './lib/actions/create-channel-category';
+import { createChannelAction } from './lib/actions/create-channel';
+import { updateChannelAction } from './lib/actions/update-channel';
+import { deleteChannelAction } from './lib/actions/delete-channel';
+import { listChannelThreadsAction } from './lib/actions/list-channel-threads';
+import { getThreadAction } from './lib/actions/get-thread';
+import { createThreadAction } from './lib/actions/create-thread';
+import { createCommentAction } from './lib/actions/create-comment';
+import { sendChatMessageAction } from './lib/actions/send-chat-message';
+import { listChatMessagesAction } from './lib/actions/list-chat-messages';
+import { sendDirectMessageAction } from './lib/actions/send-direct-message';
+import { getOrCreateDirectChatAction } from './lib/actions/get-or-create-direct-chat';
+import { listDirectMessagesAction } from './lib/actions/list-direct-messages';
+import { listEventsAction } from './lib/actions/list-events';
+import { getEventAction } from './lib/actions/get-event';
+import { getEventAttendanceAction } from './lib/actions/get-event-attendance';
+import { createEventAction } from './lib/actions/create-event';
+import { listInvitationsAction } from './lib/actions/list-invitations';
+import { createInvitationLinkAction } from './lib/actions/create-invitation-link';
+import { addEmailsToInvitationAction } from './lib/actions/add-emails-to-invitation';
+import { listCoursesAction } from './lib/actions/list-courses';
+import { getLessonAction } from './lib/actions/get-lesson';
+import { listDocumentsAction } from './lib/actions/list-documents';
+import { getDocumentAction } from './lib/actions/get-document';
+import { newMemberTrigger } from './lib/triggers/new-member';
+import { newThreadTrigger } from './lib/triggers/new-thread';
+import { newMentionTrigger } from './lib/triggers/new-mention';
+import { newEventTrigger } from './lib/triggers/new-event';
+import { newDirectMessageTrigger } from './lib/triggers/new-direct-message';
-const markdownPropertyDescription = `
- 1. Login to your Heartbeat account
- 2. On the bottom-left, click on 'Admin Settings'
- 3. On the left panel, click on 'API Keys'
- 5. Click on 'Create API Key'
- 6. On the popup form, Enter the 'Label' to name the Key
- 7. Copy the API key and paste it below.
-`;
-
-export const heartbeatAuth = PieceAuth.SecretText({
- displayName: 'API Key',
- description: markdownPropertyDescription,
- required: true,
-});
+export { heartbeatAuth } from './lib/auth';
export const Heartbeat = createPiece({
displayName: 'Heartbeat',
- description: 'Monitoring and alerting made easy',
-
+ description: 'Community platform for members, groups, channels, threads, events and courses',
auth: heartbeatAuth,
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/heartbeat.png',
categories: [PieceCategory.COMMUNICATION],
- authors: ["kanarelo","kishanprmr","abuaboud"],
+ authors: ['kanarelo', 'kishanprmr', 'abuaboud'],
actions: [
heartBeatCreateUser,
+ createMemberAction,
+ listUsersAction,
+ getUserAction,
+ findUserByEmailAction,
+ updateUserAction,
+ removeUserAction,
+ reactivateUserAction,
+ createPendingUserAction,
+ listUserCompletedLessonsAction,
+ markLessonsCompletedAction,
+ listRolesAction,
+ listGroupsAction,
+ getGroupAction,
+ createGroupAction,
+ updateGroupAction,
+ deleteGroupAction,
+ addUsersToGroupAction,
+ removeUsersFromGroupAction,
+ listChannelsAction,
+ listChannelCategoriesAction,
+ createChannelCategoryAction,
+ createChannelAction,
+ updateChannelAction,
+ deleteChannelAction,
+ listChannelThreadsAction,
+ getThreadAction,
+ createThreadAction,
+ createCommentAction,
+ sendChatMessageAction,
+ listChatMessagesAction,
+ sendDirectMessageAction,
+ getOrCreateDirectChatAction,
+ listDirectMessagesAction,
+ listEventsAction,
+ getEventAction,
+ getEventAttendanceAction,
+ createEventAction,
+ listInvitationsAction,
+ createInvitationLinkAction,
+ addEmailsToInvitationAction,
+ listCoursesAction,
+ getLessonAction,
+ listDocumentsAction,
+ getDocumentAction,
createCustomApiCallAction({
auth: heartbeatAuth,
- baseUrl: () => 'https://api.heartbeat.chat/v0',
- authMapping: async (auth) => {
- return {
- Authorization: `Bearer ${auth.secret_text}`,
- };
- },
+ baseUrl: () => HEARTBEAT_BASE_URL,
+ authMapping: async (auth) => heartbeatApi.authHeaders(auth.secret_text),
}),
],
- triggers: [],
+ triggers: [newMemberTrigger, newThreadTrigger, newMentionTrigger, newEventTrigger, newDirectMessageTrigger],
});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/add-emails-to-invitation.ts b/packages/pieces/community/heartbeat/src/lib/actions/add-emails-to-invitation.ts
new file mode 100644
index 00000000000..a9ded76ecb1
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/add-emails-to-invitation.ts
@@ -0,0 +1,52 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const addEmailsToInvitationAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_add_emails_to_invitation',
+ classification: 'WRITE',
+ displayName: 'Invite Emails to Invitation Link',
+ description: 'Lets these emails join through an invitation link, optionally emailing them the invitation.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Adds emails to an invitation link so those people can sign up with its role and groups; when Send Invitation Email is Yes, Heartbeat emails each of them an invitation. Get the ID from List Invitation Links. Not idempotent when emails are sent: repeating sends them again.',
+ idempotent: false,
+ },
+ props: {
+ invitationId: heartbeatProps.id({ displayName: 'Invitation Link ID', description: 'Use List Invitation Links to find the ID.', required: true }),
+ emails: heartbeatProps.emails({ displayName: 'Emails', description: '1-100 email addresses.', required: true }),
+ sendEmail: Property.StaticDropdown({
+ displayName: 'Send Invitation Email',
+ description: 'Yes emails each person an invitation now. No only allows them to sign up through the link.',
+ required: true,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Yes, email the invitation', value: 'yes' },
+ { label: 'No, do not email', value: 'no' },
+ ],
+ },
+ }),
+ },
+ outputSchema: heartbeatOutputSchemas.invitationEmails,
+ async run({ auth, propsValue }) {
+ const invitationId = heartbeatApi.uuid({ value: propsValue.invitationId, label: 'Invitation Link ID' });
+ const emails = heartbeatApi.emailList({ value: propsValue.emails, label: 'Emails', min: 1 });
+ const shouldSendEmail = heartbeatApi.triState(propsValue.sendEmail);
+ if (shouldSendEmail === undefined) {
+ throw new Error('Send Invitation Email must be yes or no.');
+ }
+ await heartbeatApi.request({
+ token: auth.secret_text,
+ method: HttpMethod.POST,
+ path: `/invitations/${invitationId}`,
+ operation: 'add emails to invitation link',
+ body: { emails, shouldSendEmail },
+ });
+ return { invitationId, emails, emailSent: shouldSendEmail };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/add-users-to-group.ts b/packages/pieces/community/heartbeat/src/lib/actions/add-users-to-group.ts
new file mode 100644
index 00000000000..fe9e1544b9f
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/add-users-to-group.ts
@@ -0,0 +1,55 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatGroups } from '../common/groups';
+
+export const addUsersToGroupAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_add_users_to_group',
+ classification: 'WRITE',
+ displayName: 'Add Members to Group',
+ description: 'Adds members to a group by email, optionally moving them out of sibling groups.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Adds existing members (by email) to a group, optionally removing them from sibling groups under the same parent to move them between stages. Heartbeat silently ignores emails that are not members, so they are listed in notAdded (if the read-back fails, all emails are listed in unverified with lookupError set). Adding existing group members changes nothing, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ groupId: heartbeatProps.id({ displayName: 'Group ID', description: 'Use List Groups to find the ID.', required: true }),
+ emails: heartbeatProps.emails({ displayName: 'Member Emails', description: '1-100 emails of existing members.', required: true }),
+ removeFromSiblingGroups: Property.Checkbox({
+ displayName: 'Remove from Sibling Groups',
+ description: 'Also remove these members from other groups with the same parent group (moves them between stages).',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: heartbeatOutputSchemas.groupMembership,
+ async run({ auth, propsValue }) {
+ const groupId = heartbeatApi.uuid({ value: propsValue.groupId, label: 'Group ID' });
+ const emails = heartbeatApi.emailList({ value: propsValue.emails, label: 'Member Emails', min: 1 });
+ await heartbeatApi.request({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: `/groups/${groupId}/memberships`,
+ operation: 'add members to group',
+ body: { emails, shouldRemoveFromSiblingGroups: propsValue.removeFromSiblingGroups === true },
+ });
+ const lookup = await heartbeatApi.afterWrite({
+ what: 'the group members',
+ load: async () => heartbeatGroups.memberEmails(await heartbeatGroups.getGroup({ token: auth.secret_text, groupId })),
+ });
+ const members = lookup.value;
+ return {
+ groupId,
+ emails,
+ added: members === null ? [] : emails.filter((email) => members.has(email.toLowerCase())),
+ notAdded: members === null ? [] : emails.filter((email) => !members.has(email.toLowerCase())),
+ unverified: members === null ? emails : [],
+ lookupError: lookup.lookupError,
+ };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/ai/create-member.ts b/packages/pieces/community/heartbeat/src/lib/actions/ai/create-member.ts
new file mode 100644
index 00000000000..4ceeb2e2d6d
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/ai/create-member.ts
@@ -0,0 +1,56 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../../auth';
+import { heartbeatApi } from '../../common/client';
+import { heartbeatProps } from '../../common/props';
+import { heartbeatUsers } from '../../common/users';
+import { heartbeatOutputSchemas } from '../../common/output-schemas';
+
+export const createMemberAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_create_member',
+ classification: 'WRITE',
+ displayName: 'Create Member (by Role ID)',
+ description: 'Creates a member with a role ID and optional group IDs.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Creates a member in the Heartbeat community from a name, unique email and role ID (get role IDs from List Roles, group IDs from List Groups), optionally with groups, bio, status and social links, and returns the new member. Use Find Member by Email first to avoid duplicates. Not idempotent: a second call with the same email is rejected as a duplicate.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', description: "The member's full name.", required: true }),
+ email: Property.ShortText({ displayName: 'Email', description: 'Must be unique in the community.', required: true }),
+ roleId: heartbeatProps.id({ displayName: 'Role ID', description: 'Use List Roles to find the ID.', required: true }),
+ groupIds: heartbeatProps.ids({ displayName: 'Group IDs', description: 'Groups the member joins. Use List Groups to find IDs.', required: false }),
+ bio: Property.LongText({ displayName: 'Bio', required: false }),
+ status: Property.ShortText({ displayName: 'Status', required: false }),
+ linkedin: Property.ShortText({ displayName: 'LinkedIn URL', description: 'Full URL including https://', required: false }),
+ twitter: Property.ShortText({ displayName: 'Twitter URL', description: 'Full URL including https://', required: false }),
+ instagram: Property.ShortText({ displayName: 'Instagram URL', description: 'Full URL including https://', required: false }),
+ website: Property.ShortText({ displayName: 'Website URL', description: 'Full URL including https://', required: false }),
+ createIntroductionThread: Property.Checkbox({
+ displayName: 'Post Introduction Thread',
+ description: 'When on and a bio is given, posts an introduction thread for the member in the community introductions channel.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ outputSchema: heartbeatOutputSchemas.createdUser,
+ async run({ auth, propsValue }) {
+ return heartbeatUsers.createUser({
+ token: auth.secret_text,
+ body: {
+ name: heartbeatApi.requiredText({ value: propsValue.name, label: 'Name' }),
+ email: heartbeatApi.email({ value: propsValue.email, label: 'Email' }),
+ roleID: heartbeatApi.uuid({ value: propsValue.roleId, label: 'Role ID' }),
+ groupIDs: heartbeatApi.listOrUndefined(heartbeatApi.uuidList({ value: propsValue.groupIds, label: 'Group IDs' })),
+ bio: heartbeatApi.optionalText(propsValue.bio),
+ status: heartbeatApi.optionalText(propsValue.status),
+ linkedin: heartbeatApi.optionalUrl({ value: propsValue.linkedin, label: 'LinkedIn URL' }),
+ twitter: heartbeatApi.optionalUrl({ value: propsValue.twitter, label: 'Twitter URL' }),
+ instagram: heartbeatApi.optionalUrl({ value: propsValue.instagram, label: 'Instagram URL' }),
+ website: heartbeatApi.optionalUrl({ value: propsValue.website, label: 'Website URL' }),
+ createIntroductionThread: propsValue.createIntroductionThread === true,
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/create-channel-category.ts b/packages/pieces/community/heartbeat/src/lib/actions/create-channel-category.ts
new file mode 100644
index 00000000000..8193a348d82
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/create-channel-category.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const createChannelCategoryAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_create_channel_category',
+ classification: 'WRITE',
+ displayName: 'Create Channel Category',
+ description: 'Creates a channel category (sidebar section).',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Creates a channel category (a sidebar section that groups channels) and returns its ID and name. Use before Create Channel when no suitable category exists. Not idempotent: each call creates another category even with the same name.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.category,
+ async run({ auth, propsValue }) {
+ return heartbeatApi.request<Record<string, unknown>>({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/channelCategories',
+ operation: 'create channel category',
+ body: { name: heartbeatApi.requiredText({ value: propsValue.name, label: 'Name' }) },
+ });
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/create-channel.ts b/packages/pieces/community/heartbeat/src/lib/actions/create-channel.ts
new file mode 100644
index 00000000000..a6408ddc77d
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/create-channel.ts
@@ -0,0 +1,90 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatChannels } from '../common/channels';
+
+export const createChannelAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_create_channel',
+ classification: 'WRITE',
+ displayName: 'Create Channel',
+ description: 'Creates a posts (threads) or chat channel in a category.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Creates a posts (threads) or chat channel in a channel category, public or private (private: only the invited emails and group IDs can see it), and returns its ID. Get the category ID from List Channel Categories. Not idempotent: each call creates another channel.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ channelCategoryId: heartbeatProps.id({ displayName: 'Channel Category ID', description: 'Use List Channel Categories to find the ID.', required: true }),
+ channelType: Property.StaticDropdown({
+ displayName: 'Channel Type',
+ required: true,
+ defaultValue: 'POSTS',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Posts (threads)', value: 'POSTS' },
+ { label: 'Chat', value: 'CHAT' },
+ ],
+ },
+ }),
+ visibility: Property.StaticDropdown({
+ displayName: 'Visibility',
+ description: 'Private channels are only visible to the invited members and groups.',
+ required: true,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Public', value: 'public' },
+ { label: 'Private', value: 'private' },
+ ],
+ },
+ }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ invitedEmails: heartbeatProps.emails({ displayName: 'Invited Member Emails', description: 'Who can access a private channel.', required: false }),
+ invitedGroupIds: heartbeatProps.ids({ displayName: 'Invited Group IDs', description: 'Groups that can access a private channel. Use List Groups to find IDs.', required: false }),
+ isReadOnly: Property.Checkbox({ displayName: 'Read Only', description: 'Only admins and moderators can post threads. Not available for chat channels.', required: false }),
+ },
+ outputSchema: heartbeatOutputSchemas.createdChannel,
+ async run({ auth, propsValue }) {
+ if (propsValue.visibility !== 'public' && propsValue.visibility !== 'private') {
+ throw new Error('Visibility must be public or private.');
+ }
+ if (propsValue.channelType !== 'POSTS' && propsValue.channelType !== 'CHAT') {
+ throw new Error('Channel Type must be POSTS or CHAT.');
+ }
+ if (propsValue.isReadOnly === true && propsValue.channelType === 'CHAT') {
+ throw new Error('Read Only is not available for chat channels.');
+ }
+ const name = heartbeatApi.requiredText({ value: propsValue.name, label: 'Name' });
+ const created = await heartbeatApi.request<unknown>({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/channels',
+ operation: 'create channel',
+ body: {
+ name,
+ description: heartbeatApi.optionalText(propsValue.description),
+ isPrivate: propsValue.visibility === 'private',
+ channelCategoryID: heartbeatApi.uuid({ value: propsValue.channelCategoryId, label: 'Channel Category ID' }),
+ channelType: propsValue.channelType,
+ invitedUsers: heartbeatApi.listOrUndefined(heartbeatApi.emailList({ value: propsValue.invitedEmails, label: 'Invited Member Emails' })),
+ invitedGroups: heartbeatApi.listOrUndefined(heartbeatApi.uuidList({ value: propsValue.invitedGroupIds, label: 'Invited Group IDs' })),
+ isReadOnly: propsValue.isReadOnly ?? undefined,
+ },
+ });
+ const channelId = heartbeatApi.isRecord(created) ? created['channelID'] : undefined;
+ if (typeof channelId !== 'string') {
+ throw new Error('Heartbeat created the channel but did not return its ID. Use List Channels to find it.');
+ }
+ const lookup = await heartbeatApi.afterWrite({
+ what: 'the new channel',
+ load: () => heartbeatChannels.findChannel({ token: auth.secret_text, channelId }),
+ });
+ return { ...(lookup.value ?? { id: channelId, name, type: propsValue.channelType }), lookupError: lookup.lookupError };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/create-comment.ts b/packages/pieces/community/heartbeat/src/lib/actions/create-comment.ts
new file mode 100644
index 00000000000..d60770cc84d
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/create-comment.ts
@@ -0,0 +1,45 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const createCommentAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_create_comment',
+ classification: 'WRITE',
+ displayName: 'Reply to Thread',
+ description: 'Adds a comment to a thread, or a reply to a comment.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Adds a comment to a thread, or a reply under an existing top-level comment when Parent Comment ID is given (Heartbeat has two levels), as the API-key admin or another admin; @<ID> mentions notify people. Get IDs from Get Thread. Not idempotent: each call posts another comment.',
+ idempotent: false,
+ },
+ props: {
+ threadId: heartbeatProps.id({ displayName: 'Thread ID', description: 'Use List Threads to find the ID.', required: true }),
+ text: heartbeatProps.richText({ displayName: 'Text', required: true }),
+ parentCommentId: heartbeatProps.id({ displayName: 'Parent Comment ID', description: 'Reply under this top-level comment. Leave empty to comment on the thread itself.', required: false }),
+ authorUserId: heartbeatProps.author({ displayName: 'Author (Admin User ID)' }),
+ createdAt: Property.DateTime({ displayName: 'Created At', description: 'Optional backdated creation time. Defaults to now.', required: false }),
+ },
+ outputSchema: heartbeatOutputSchemas.comment,
+ async run({ auth, propsValue }) {
+ const threadId = heartbeatApi.uuid({ value: propsValue.threadId, label: 'Thread ID' });
+ const parentCommentId = heartbeatApi.optionalUuid({ value: propsValue.parentCommentId, label: 'Parent Comment ID' }) ?? null;
+ const comment = await heartbeatApi.request<Record<string, unknown>>({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/comments',
+ operation: 'create comment',
+ body: {
+ text: heartbeatApi.richText({ value: propsValue.text, label: 'Text' }),
+ threadID: threadId,
+ parentCommentID: parentCommentId,
+ userID: heartbeatApi.optionalUuid({ value: propsValue.authorUserId, label: 'Author (Admin User ID)' }),
+ createdAt: heartbeatApi.isoDate({ value: propsValue.createdAt, label: 'Created At' }),
+ },
+ });
+ return { ...comment, threadId, parentCommentId };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/create-event.ts b/packages/pieces/community/heartbeat/src/lib/actions/create-event.ts
new file mode 100644
index 00000000000..ed2c6202a4d
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/create-event.ts
@@ -0,0 +1,96 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatEvents } from '../common/events';
+
+export const createEventAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_create_event',
+ classification: 'WRITE',
+ displayName: 'Create Event',
+ description: 'Creates a community event and invites members, groups or outside guests.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Creates a community event with a start time, duration in minutes and location (a new Heartbeat voice channel, Zoom if the community has the Zoom integration, or custom text), inviting members or guests by email and groups by ID. Emails that are not members get an external invite. Always pass invitees: with none, Heartbeat limited the event to the Administrator group in testing (the API docs say it is open to everyone). Invitees are notified. Not idempotent: each call creates another event.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ startTime: Property.DateTime({ displayName: 'Start Time', description: 'ISO 8601, for example 2026-10-13T15:00:00Z.', required: true }),
+ durationMinutes: Property.Number({ displayName: 'Duration (Minutes)', required: true }),
+ location: Property.StaticDropdown({
+ displayName: 'Location',
+ description: 'Heartbeat creates a voice channel for the event. Zoom needs the Zoom integration connected in your Heartbeat settings.',
+ required: true,
+ defaultValue: 'HEARTBEAT',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Heartbeat voice channel', value: 'HEARTBEAT' },
+ { label: 'Zoom', value: 'ZOOM' },
+ { label: 'Custom (enter below)', value: 'CUSTOM' },
+ ],
+ },
+ }),
+ customLocation: Property.ShortText({ displayName: 'Custom Location', description: 'Used when Location is Custom, for example an address or a meeting link.', required: false }),
+ invitedEmails: heartbeatProps.emails({ displayName: 'Invited Emails', description: 'Members are invited in Heartbeat; other emails get an external invitation.', required: false }),
+ invitedGroupIds: heartbeatProps.ids({ displayName: 'Invited Group IDs', description: 'Use List Groups to find IDs. Add invitees: with none, Heartbeat may limit the event to admins.', required: false }),
+ },
+ outputSchema: heartbeatOutputSchemas.createdEvent,
+ async run({ auth, propsValue }) {
+ const startTime = heartbeatApi.isoDate({ value: propsValue.startTime, label: 'Start Time' });
+ if (startTime === undefined) {
+ throw new Error('Start Time is required.');
+ }
+ const duration = Number(propsValue.durationMinutes);
+ if (!Number.isInteger(duration) || duration < 1 || duration > MAX_DURATION_MINUTES) {
+ throw new Error(`Duration must be a whole number of minutes between 1 and ${MAX_DURATION_MINUTES}.`);
+ }
+ const location = resolveLocation({ location: propsValue.location, customLocation: propsValue.customLocation });
+ const created = await heartbeatApi.request<unknown>({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/events',
+ operation: 'create event',
+ body: {
+ name: heartbeatApi.requiredText({ value: propsValue.name, label: 'Name' }),
+ description: heartbeatApi.optionalText(propsValue.description) ?? '',
+ startTime,
+ duration,
+ location,
+ invitedUsers: heartbeatApi.listOrUndefined(heartbeatApi.emailList({ value: propsValue.invitedEmails, label: 'Invited Emails' })),
+ invitedGroups: heartbeatApi.listOrUndefined(heartbeatApi.uuidList({ value: propsValue.invitedGroupIds, label: 'Invited Group IDs' })),
+ },
+ });
+ const vendorEvent = heartbeatApi.isRecord(created) && heartbeatApi.isRecord(created['event']) ? created['event'] : {};
+ const eventId = vendorEvent['id'];
+ if (typeof eventId !== 'string') {
+ throw new Error('Heartbeat created the event but did not return its ID. Use List Events to find it.');
+ }
+ const lookup = await heartbeatApi.afterWrite({
+ what: 'the new event',
+ load: () => heartbeatEvents.getEvent({ token: auth.secret_text, eventId }),
+ });
+ return { ...(lookup.value ?? vendorEvent), location: vendorEvent['location'] ?? null, lookupError: lookup.lookupError };
+ },
+});
+
+function resolveLocation({ location, customLocation }: { location: unknown; customLocation: unknown }): string {
+ if (location === 'HEARTBEAT' || location === 'ZOOM') {
+ return location;
+ }
+ if (location === 'CUSTOM') {
+ const text = heartbeatApi.optionalText(customLocation)?.trim();
+ if (text === undefined) {
+ throw new Error('Custom Location is required when Location is Custom.');
+ }
+ return text;
+ }
+ throw new Error('Location must be HEARTBEAT, ZOOM or CUSTOM.');
+}
+
+const MAX_DURATION_MINUTES = 10_080;
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/create-group.ts b/packages/pieces/community/heartbeat/src/lib/actions/create-group.ts
new file mode 100644
index 00000000000..df91ea0cef0
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/create-group.ts
@@ -0,0 +1,55 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatGroups } from '../common/groups';
+
+export const createGroupAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_create_group',
+ classification: 'WRITE',
+ displayName: 'Create Group',
+ description: 'Creates a group, optionally under a parent group and with initial members.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Creates a group with a name and optional description, parent group ID, initial member emails and isolated/joinable settings, and returns the new group. Use for cohorts, stages or access control. Not idempotent: each call creates another group even with the same name.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ memberEmails: heartbeatProps.emails({ displayName: 'Member Emails', description: 'Emails of existing members to add (up to 100).', required: false }),
+ parentGroupId: heartbeatProps.id({ displayName: 'Parent Group ID', description: 'Makes this a sub-group. Use List Groups to find the ID.', required: false }),
+ isIsolated: Property.Checkbox({ displayName: 'Isolated', description: 'Members of an isolated group only see content shared with the group (see Heartbeat docs).', required: false }),
+ isJoinable: Property.Checkbox({ displayName: 'Joinable', description: 'Members can join the group themselves.', required: false }),
+ },
+ outputSchema: heartbeatOutputSchemas.createdGroup,
+ async run({ auth, propsValue }) {
+ const name = heartbeatApi.requiredText({ value: propsValue.name, label: 'Name' });
+ const created = await heartbeatApi.request<unknown>({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/groups',
+ operation: 'create group',
+ body: {
+ name,
+ description: heartbeatApi.optionalText(propsValue.description),
+ members: heartbeatApi.listOrUndefined(heartbeatApi.emailList({ value: propsValue.memberEmails, label: 'Member Emails' })),
+ parentGroupID: heartbeatApi.optionalUuid({ value: propsValue.parentGroupId, label: 'Parent Group ID' }),
+ isIsolated: propsValue.isIsolated ?? undefined,
+ isJoinable: propsValue.isJoinable ?? undefined,
+ },
+ });
+ const groupId = heartbeatApi.isRecord(created) ? created['groupID'] : undefined;
+ if (typeof groupId !== 'string') {
+ throw new Error('Heartbeat created the group but did not return its ID. Use List Groups to find it.');
+ }
+ const lookup = await heartbeatApi.afterWrite({
+ what: 'the new group',
+ load: () => heartbeatGroups.getGroup({ token: auth.secret_text, groupId }),
+ });
+ return { ...(lookup.value ?? { id: groupId, name }), lookupError: lookup.lookupError };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/create-invitation-link.ts b/packages/pieces/community/heartbeat/src/lib/actions/create-invitation-link.ts
new file mode 100644
index 00000000000..e06bfc08716
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/create-invitation-link.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const createInvitationLinkAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_create_invitation_link',
+ classification: 'WRITE',
+ displayName: 'Create Invitation Link',
+ description: 'Creates an invitation link that gives new members a role and groups.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Creates an invitation link; people who join through it get the given role ID and group IDs. Returns the link ID and its 6-character code. No email is sent. Not idempotent: each call creates another link.',
+ idempotent: false,
+ },
+ props: {
+ roleId: heartbeatProps.id({ displayName: 'Role ID', description: 'Use List Roles to find the ID.', required: true }),
+ groupIds: heartbeatProps.ids({ displayName: 'Group IDs', description: 'Groups new members join. Use List Groups to find IDs.', required: false }),
+ },
+ outputSchema: heartbeatOutputSchemas.invitation,
+ async run({ auth, propsValue }) {
+ return heartbeatApi.request<Record<string, unknown>>({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/invitations',
+ operation: 'create invitation link',
+ body: {
+ roleID: heartbeatApi.uuid({ value: propsValue.roleId, label: 'Role ID' }),
+ groupIDs: heartbeatApi.uuidList({ value: propsValue.groupIds, label: 'Group IDs' }),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/create-pending-user.ts b/packages/pieces/community/heartbeat/src/lib/actions/create-pending-user.ts
new file mode 100644
index 00000000000..75b7ee37559
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/create-pending-user.ts
@@ -0,0 +1,44 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const createPendingUserAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_create_pending_user',
+ classification: 'WRITE',
+ displayName: 'Pre-register Member',
+ description: 'Pre-registers a person who becomes a member with this role and groups the first time they log in.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Pre-registers a person by email with a role ID and optional group IDs; they become a member the first time they log in. Use when someone should get a set role and groups on their first login. Fails if the email is already a member. Calling again for the same pending email updates the pre-registration, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ email: Property.ShortText({ displayName: 'Email', required: true }),
+ name: Property.ShortText({ displayName: 'Name', description: "The person's full name.", required: true }),
+ roleId: heartbeatProps.id({ displayName: 'Role ID', description: 'Use List Roles to find the ID.', required: true }),
+ groupIds: heartbeatProps.ids({ displayName: 'Group IDs', description: 'Use List Groups to find IDs.', required: false }),
+ bio: Property.LongText({ displayName: 'Bio', required: false }),
+ },
+ outputSchema: heartbeatOutputSchemas.pendingUser,
+ async run({ auth, propsValue }) {
+ const email = heartbeatApi.email({ value: propsValue.email, label: 'Email' });
+ const response = await heartbeatApi.request<unknown>({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/pendingUser',
+ operation: 'pre-register member',
+ body: {
+ email,
+ name: heartbeatApi.requiredText({ value: propsValue.name, label: 'Name' }),
+ roleID: heartbeatApi.uuid({ value: propsValue.roleId, label: 'Role ID' }),
+ groupIDs: heartbeatApi.listOrUndefined(heartbeatApi.uuidList({ value: propsValue.groupIds, label: 'Group IDs' })),
+ bio: heartbeatApi.optionalText(propsValue.bio),
+ },
+ });
+ return { email, success: heartbeatApi.isRecord(response) ? response['success'] === true : true };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/create-thread.ts b/packages/pieces/community/heartbeat/src/lib/actions/create-thread.ts
new file mode 100644
index 00000000000..fee6f1be500
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/create-thread.ts
@@ -0,0 +1,40 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const createThreadAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_create_thread',
+ classification: 'WRITE',
+ displayName: 'Create Thread',
+ description: 'Posts a new thread in a posts channel.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Posts a new thread in a posts channel as the API-key admin or another admin, with HTML-subset text; @<user or group ID> mentions notify those people. Use for announcements; get the channel ID from List Channels (type POSTS). Not idempotent: each call posts again.',
+ idempotent: false,
+ },
+ props: {
+ channelId: heartbeatProps.id({ displayName: 'Channel ID', description: 'A posts channel. Use List Channels to find the ID.', required: true }),
+ text: heartbeatProps.richText({ displayName: 'Text', required: true }),
+ authorUserId: heartbeatProps.author({ displayName: 'Author (Admin User ID)' }),
+ createdAt: Property.DateTime({ displayName: 'Created At', description: 'Optional backdated creation time, for example when migrating posts. Defaults to now.', required: false }),
+ },
+ outputSchema: heartbeatOutputSchemas.createdThread,
+ async run({ auth, propsValue }) {
+ return heartbeatApi.request<Record<string, unknown>>({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/threads',
+ operation: 'create thread',
+ body: {
+ text: heartbeatApi.richText({ value: propsValue.text, label: 'Text' }),
+ channelID: heartbeatApi.uuid({ value: propsValue.channelId, label: 'Channel ID' }),
+ userID: heartbeatApi.optionalUuid({ value: propsValue.authorUserId, label: 'Author (Admin User ID)' }),
+ createdAt: heartbeatApi.isoDate({ value: propsValue.createdAt, label: 'Created At' }),
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/create-user.ts b/packages/pieces/community/heartbeat/src/lib/actions/create-user.ts
index 45a836ec098..af3569a8c7d 100644
--- a/packages/pieces/community/heartbeat/src/lib/actions/create-user.ts
+++ b/packages/pieces/community/heartbeat/src/lib/actions/create-user.ts
@@ -1,15 +1,11 @@
-import {
- Property,
- createAction,
-} from '@activepieces/pieces-framework';
-import {
- AuthenticationType,
- HttpMethod,
- httpClient,
- propsValidation,
-} from '@activepieces/pieces-common';
-import { heartbeatAuth } from '../..';
-import * as z from 'zod/mini'
+import { propsValidation } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import * as z from 'zod/mini';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatUsers } from '../common/users';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
export const heartBeatCreateUser = createAction({
auth: heartbeatAuth,
@@ -17,8 +13,11 @@ export const heartBeatCreateUser = createAction({
classification: 'WRITE',
displayName: 'Create User',
description: 'Create a new user in a Heartbeat community',
- audience: 'both',
- aiMetadata: { description: 'Creates a member in a Heartbeat community via the Heartbeat API, assigning a role and optionally adding them to groups and setting profile fields (bio, social links, status). Use to onboard a new person; the email must be unique to the community. Not idempotent: each call creates a member (a duplicate email is rejected) and, if a bio is supplied with the introduction-thread option enabled, also posts an introduction thread.', idempotent: false },
+ audience: 'human',
+ aiMetadata: {
+ description: 'Creates a member in a Heartbeat community, assigning a role and optionally groups and profile fields (bio, social links, status). Use to onboard a new person; the email must be unique to the community. Not idempotent: a second call with the same email is rejected, and with the introduction-thread option on and a bio set it also posts an introduction thread.',
+ idempotent: false,
+ },
props: {
name: Property.ShortText({
displayName: 'Name',
@@ -30,105 +29,8 @@ export const heartBeatCreateUser = createAction({
description: "The user's email. Must be unique to the community",
required: true,
}),
- role_id: Property.Dropdown({
- auth: heartbeatAuth,
- displayName: 'Roles',
- description: 'The role the user should have',
- required: true,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth)
- return {
- disabled: true,
- options: [],
- placeholder: 'Please select a connection',
- };
-
- const response = await httpClient.sendRequest<
- {
- id: string;
- name: string;
- }[]
- >({
- method: HttpMethod.GET,
- url: `https://api.heartbeat.chat/v0/roles`,
- headers: {
- 'content-type': 'application/json',
- },
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: auth.secret_text,
- },
- body: {},
- });
-
- if (response.status === 200) {
- return {
- options: response.body.map((role) => ({
- label: role.name,
- value: role.id,
- })),
- disabled: false,
- };
- }
-
- return {
- options: [],
- disabled: true,
- placeholder: 'Error loading roles.',
- };
- },
- }),
- group_ids: Property.MultiSelectDropdown({
- displayName: 'Groups',
- auth: heartbeatAuth,
- description:
- 'A list of the ids of the groups that the user should belong to.',
- required: false,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth)
- return {
- disabled: true,
- options: [],
- placeholder: 'Error loading groups',
- };
-
- const response = await httpClient.sendRequest<
- {
- id: string;
- name: string;
- }[]
- >({
- method: HttpMethod.GET,
- url: `https://api.heartbeat.chat/v0/groups`,
- headers: {
- 'content-type': 'application/json',
- },
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: auth.secret_text,
- },
- body: {},
- });
-
- if (response.status === 200) {
- return {
- options: response.body.map((group) => ({
- label: group.name,
- value: group.id,
- })),
- disabled: false,
- };
- }
-
- return {
- disabled: true,
- options: [],
- placeholder: 'Error loading groups',
- };
- },
- }),
+ role_id: heartbeatProps.roleDropdown,
+ group_ids: heartbeatProps.groupsDropdown,
profile_picture: Property.ShortText({
displayName: 'Profile Picture',
description:
@@ -147,17 +49,22 @@ export const heartBeatCreateUser = createAction({
}),
linkedin: Property.LongText({
displayName: 'LinkedIn',
- description: "A link to the user's LinkedIn profile",
+ description: "A link to the user's LinkedIn profile (full URL including https://)",
required: false,
}),
twitter: Property.LongText({
displayName: 'Twitter',
- description: "A link to the user's Twitter profile",
+ description: "A link to the user's Twitter profile (full URL including https://)",
required: false,
}),
instagram: Property.LongText({
displayName: 'Instagram',
- description: "A link to the user's Instagram profile",
+ description: "A link to the user's Instagram profile (full URL including https://)",
+ required: false,
+ }),
+ website: Property.ShortText({
+ displayName: 'Website',
+ description: "A link to the user's website (full URL including https://)",
required: false,
}),
create_introduction_thread: Property.Checkbox({
@@ -167,39 +74,31 @@ export const heartBeatCreateUser = createAction({
required: false,
}),
},
+ outputSchema: heartbeatOutputSchemas.createdUser,
async run({ auth, propsValue }) {
await propsValidation.validateZod(propsValue, {
email: z.string().check(z.email()),
linkedin: z.optional(z.string().check(z.url())),
- twitter: z.optional(z.string().check(z.url())),
- instagram: z.optional(z.string().check(z.url()))
+ twitter: z.optional(z.string().check(z.url())),
+ instagram: z.optional(z.string().check(z.url())),
+ website: z.optional(z.string().check(z.url())),
});
-
- const response = await httpClient.sendRequest({
- method: HttpMethod.PUT,
- url: `https://api.heartbeat.chat/v0/users`,
- headers: {
- 'content-type': 'application/json',
- },
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: auth.secret_text,
- },
+ return heartbeatUsers.createUser({
+ token: auth.secret_text,
body: {
name: propsValue.name,
- email: propsValue.email,
- roleID: propsValue.role_id,
- groupIDs: propsValue.group_ids,
- profilePicture: propsValue.profile_picture,
- bio: propsValue.bio,
- status: propsValue.status,
- linkedin: propsValue.linkedin,
- twitter: propsValue.twitter,
- instagram: propsValue.instagram,
+ email: propsValue.email.trim(),
+ roleID: heartbeatApi.uuid({ value: propsValue.role_id, label: 'Role' }),
+ groupIDs: heartbeatApi.listOrUndefined(heartbeatApi.uuidList({ value: propsValue.group_ids, label: 'Groups' })),
+ profilePicture: heartbeatApi.optionalText(propsValue.profile_picture),
+ bio: heartbeatApi.optionalText(propsValue.bio),
+ status: heartbeatApi.optionalText(propsValue.status),
+ linkedin: heartbeatApi.optionalText(propsValue.linkedin),
+ twitter: heartbeatApi.optionalText(propsValue.twitter),
+ instagram: heartbeatApi.optionalText(propsValue.instagram),
+ website: heartbeatApi.optionalText(propsValue.website),
createIntroductionThread: propsValue.create_introduction_thread,
},
});
-
- return response.body;
},
});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/delete-channel.ts b/packages/pieces/community/heartbeat/src/lib/actions/delete-channel.ts
new file mode 100644
index 00000000000..ab0d5396afd
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/delete-channel.ts
@@ -0,0 +1,35 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const deleteChannelAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_delete_channel',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Channel',
+ description: 'Permanently deletes a channel and all its threads.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Permanently deletes a channel together with its threads or chat messages. Use only when the user explicitly asks; this cannot be undone. A repeat call finds it gone and reports alreadyDeleted=true, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ channelId: heartbeatProps.id({ displayName: 'Channel ID', description: 'Use List Channels to find the ID.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.deleted,
+ async run({ auth, propsValue }) {
+ const channelId = heartbeatApi.uuid({ value: propsValue.channelId, label: 'Channel ID' });
+ try {
+ await heartbeatApi.request({ token: auth.secret_text, method: HttpMethod.DELETE, path: `/channels/${channelId}`, operation: 'delete channel' });
+ return { id: channelId, deleted: true, alreadyDeleted: false };
+ } catch (error) {
+ if (heartbeatApi.statusOf(error) === 404) {
+ return { id: channelId, deleted: true, alreadyDeleted: true };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/delete-group.ts b/packages/pieces/community/heartbeat/src/lib/actions/delete-group.ts
new file mode 100644
index 00000000000..2188f81424a
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/delete-group.ts
@@ -0,0 +1,35 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const deleteGroupAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_delete_group',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Group',
+ description: 'Deletes a group. Members stay in the community.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Permanently deletes a group by ID; its members stay in the community but lose the group. Use only when explicitly asked. Heartbeat refuses some deletions and the reason is returned as the error. A repeat call finds it gone and reports alreadyDeleted=true, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ groupId: heartbeatProps.id({ displayName: 'Group ID', description: 'Use List Groups to find the ID.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.deleted,
+ async run({ auth, propsValue }) {
+ const groupId = heartbeatApi.uuid({ value: propsValue.groupId, label: 'Group ID' });
+ try {
+ await heartbeatApi.request({ token: auth.secret_text, method: HttpMethod.DELETE, path: `/groups/${groupId}`, operation: 'delete group' });
+ return { id: groupId, deleted: true, alreadyDeleted: false };
+ } catch (error) {
+ if (heartbeatApi.statusOf(error) === 404) {
+ return { id: groupId, deleted: true, alreadyDeleted: true };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/find-user-by-email.ts b/packages/pieces/community/heartbeat/src/lib/actions/find-user-by-email.ts
new file mode 100644
index 00000000000..de2421a28bf
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/find-user-by-email.ts
@@ -0,0 +1,29 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatUsers } from '../common/users';
+
+export const findUserByEmailAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_find_user_by_email',
+ classification: 'READ',
+ displayName: 'Find Member by Email',
+ description: 'Looks up a member by exact email address.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Looks up one member by exact email and returns found=false (not an error) when nobody in the community has it. Use before Create Member to avoid duplicates, or to get a member ID for messaging and groups. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ email: Property.ShortText({ displayName: 'Email', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.findUser,
+ async run({ auth, propsValue }) {
+ const user = await heartbeatUsers.findUserByEmail({
+ token: auth.secret_text,
+ email: heartbeatApi.email({ value: propsValue.email, label: 'Email' }),
+ });
+ return { found: user !== null, user };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/get-document.ts b/packages/pieces/community/heartbeat/src/lib/actions/get-document.ts
new file mode 100644
index 00000000000..07c57a561f3
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/get-document.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const getDocumentAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_get_document',
+ classification: 'READ',
+ displayName: 'Get Document',
+ description: 'Gets one community document (wiki page) with its Markdown content.',
+ audience: 'both',
+ aiMetadata: {
+ description: "Returns a wiki document's title, link and full Markdown content by ID. Use to read or summarise community knowledge after List Documents. Read-only and idempotent.",
+ idempotent: true,
+ },
+ props: {
+ documentId: heartbeatProps.id({ displayName: 'Document ID', description: 'Use List Documents to find the ID.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.document,
+ async run({ auth, propsValue }) {
+ return heartbeatApi.request<Record<string, unknown>>({
+ token: auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/documents/${heartbeatApi.uuid({ value: propsValue.documentId, label: 'Document ID' })}`,
+ operation: 'get document',
+ });
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/get-event-attendance.ts b/packages/pieces/community/heartbeat/src/lib/actions/get-event-attendance.ts
new file mode 100644
index 00000000000..c42bbbb5506
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/get-event-attendance.ts
@@ -0,0 +1,44 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const getEventAttendanceAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_get_event_attendance',
+ classification: 'READ',
+ displayName: 'Get Event Attendance',
+ description: 'Gets who attended the last 10 occurrences of an event.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns attendance for the last 10 occurrences of an event (one for a one-off event): start/end time and attendees with name, email and whether they are a member. For an event that has not happened yet it returns happened=false with no occurrences instead of failing. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ eventId: heartbeatProps.id({ displayName: 'Event ID', description: 'Use List Events to find the ID.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.eventAttendance,
+ async run({ auth, propsValue }) {
+ const eventId = heartbeatApi.uuid({ value: propsValue.eventId, label: 'Event ID' });
+ try {
+ const instances = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: auth.secret_text, method: HttpMethod.GET, path: `/events/${eventId}/attendance`, operation: 'get event attendance' }),
+ ).map((instance) => ({
+ ...instance,
+ attendees: Array.isArray(instance['attendees'])
+ ? heartbeatApi.recordList(instance['attendees'])
+ : heartbeatApi.isRecord(instance['attendees'])
+ ? [instance['attendees']]
+ : [],
+ }));
+ return { eventId, happened: true, instances };
+ } catch (error) {
+ if (heartbeatApi.statusOf(error) === 422 && /not happened/i.test(heartbeatApi.errorMessageOf(error))) {
+ return { eventId, happened: false, instances: [] };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/get-event.ts b/packages/pieces/community/heartbeat/src/lib/actions/get-event.ts
new file mode 100644
index 00000000000..f25b86ef29b
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/get-event.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatEvents } from '../common/events';
+
+export const getEventAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_get_event',
+ classification: 'READ',
+ displayName: 'Get Event',
+ description: 'Gets one event, optionally with the dates of all its occurrences.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns one event by ID with name, description, start/end time, recurring flag, creator, invited users and groups; with Include Occurrences it also lists every occurrence of a recurring event. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ eventId: heartbeatProps.id({ displayName: 'Event ID', description: 'Use List Events to find the ID.', required: true }),
+ includeInstances: Property.Checkbox({ displayName: 'Include Occurrences', description: 'Also list the start and end time of each occurrence (for recurring events).', required: false, defaultValue: false }),
+ },
+ outputSchema: heartbeatOutputSchemas.eventWithInstances,
+ async run({ auth, propsValue }) {
+ const eventId = heartbeatApi.uuid({ value: propsValue.eventId, label: 'Event ID' });
+ const event = await heartbeatEvents.getEvent({ token: auth.secret_text, eventId });
+ if (propsValue.includeInstances !== true) {
+ return event;
+ }
+ const instances = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: auth.secret_text, method: HttpMethod.GET, path: `/events/${eventId}/instances`, operation: 'list event occurrences' }),
+ );
+ return { ...event, instances };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/get-group.ts b/packages/pieces/community/heartbeat/src/lib/actions/get-group.ts
new file mode 100644
index 00000000000..6e6c7a6a2fe
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/get-group.ts
@@ -0,0 +1,26 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatGroups } from '../common/groups';
+
+export const getGroupAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_get_group',
+ classification: 'READ',
+ displayName: 'Get Group',
+ description: 'Gets one group with its members.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns one group by ID with name, description, color, parent group, archived flag and its members (ID, name, email). Use to check who is in a group. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ groupId: heartbeatProps.id({ displayName: 'Group ID', description: 'Use List Groups to find the ID.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.group,
+ async run({ auth, propsValue }) {
+ return heartbeatGroups.getGroup({ token: auth.secret_text, groupId: heartbeatApi.uuid({ value: propsValue.groupId, label: 'Group ID' }) });
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/get-lesson.ts b/packages/pieces/community/heartbeat/src/lib/actions/get-lesson.ts
new file mode 100644
index 00000000000..d1a4daaa5f1
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/get-lesson.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const getLessonAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_get_lesson',
+ classification: 'READ',
+ displayName: 'Get Lesson',
+ description: 'Gets one course lesson with its Markdown content.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns one course lesson by ID with title, Markdown content, author and embedded cards. Use to read or summarise lesson material; get the ID from List Courses. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ lessonId: heartbeatProps.id({ displayName: 'Lesson ID', description: 'Use List Courses to find the ID.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.lesson,
+ async run({ auth, propsValue }) {
+ return heartbeatApi.request<Record<string, unknown>>({
+ token: auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/lessons/${heartbeatApi.uuid({ value: propsValue.lessonId, label: 'Lesson ID' })}`,
+ operation: 'get lesson',
+ });
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/get-or-create-direct-chat.ts b/packages/pieces/community/heartbeat/src/lib/actions/get-or-create-direct-chat.ts
new file mode 100644
index 00000000000..fc5aecba561
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/get-or-create-direct-chat.ts
@@ -0,0 +1,38 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const getOrCreateDirectChatAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_get_or_create_direct_chat',
+ classification: 'WRITE',
+ displayName: 'Get Direct Chat',
+ description: 'Returns the direct chat between two users, creating an empty one if none exists.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns the chat ID and link of the direct chat between two users, creating an empty chat if they have none (no message is sent). Use to get a chat ID for List Direct Messages or a link to share. Calling again returns the same chat, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ userId1: heartbeatProps.id({ displayName: 'First User ID', description: 'Use List Members to find the ID.', required: true }),
+ userId2: heartbeatProps.id({ displayName: 'Second User ID', description: 'Use List Members to find the ID.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.directChat,
+ async run({ auth, propsValue }) {
+ const userID1 = heartbeatApi.uuid({ value: propsValue.userId1, label: 'First User ID' });
+ const userID2 = heartbeatApi.uuid({ value: propsValue.userId2, label: 'Second User ID' });
+ if (userID1 === userID2) {
+ throw new Error('The two user IDs must be different.');
+ }
+ return heartbeatApi.request<Record<string, unknown>>({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/directChats',
+ operation: 'get direct chat',
+ body: { userID1, userID2 },
+ });
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/get-thread.ts b/packages/pieces/community/heartbeat/src/lib/actions/get-thread.ts
new file mode 100644
index 00000000000..927858ce3a9
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/get-thread.ts
@@ -0,0 +1,31 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const getThreadAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_get_thread',
+ classification: 'READ',
+ displayName: 'Get Thread',
+ description: 'Gets one thread with its comments and replies.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns one thread by ID with its HTML content, author ID, channel, link and all comments with their replies (two levels). Use to read a discussion before replying. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ threadId: heartbeatProps.id({ displayName: 'Thread ID', description: 'Use List Threads to find the ID.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.thread,
+ async run({ auth, propsValue }) {
+ return heartbeatApi.request<Record<string, unknown>>({
+ token: auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/threads/${heartbeatApi.uuid({ value: propsValue.threadId, label: 'Thread ID' })}`,
+ operation: 'get thread',
+ });
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/get-user.ts b/packages/pieces/community/heartbeat/src/lib/actions/get-user.ts
new file mode 100644
index 00000000000..2feb846d99b
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/get-user.ts
@@ -0,0 +1,26 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatUsers } from '../common/users';
+
+export const getUserAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_get_user',
+ classification: 'READ',
+ displayName: 'Get Member',
+ description: 'Gets one member by user ID, including profile details.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns one member by user ID with email, role, groups, bio, social links, LinkedIn data and onboarding answers. Use when you have the ID (from List Members or a trigger); use Find Member by Email when you only have the email. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ userId: heartbeatProps.id({ displayName: 'User ID', description: 'Use List Members to find the ID.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.user,
+ async run({ auth, propsValue }) {
+ return heartbeatUsers.getUser({ token: auth.secret_text, userId: heartbeatApi.uuid({ value: propsValue.userId, label: 'User ID' }) });
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-channel-categories.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-channel-categories.ts
new file mode 100644
index 00000000000..6c5c73e5aac
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-channel-categories.ts
@@ -0,0 +1,26 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const listChannelCategoriesAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_channel_categories',
+ classification: 'SEARCH',
+ displayName: 'List Channel Categories',
+ description: 'Lists the channel categories (sidebar sections).',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists every channel category (sidebar section) with ID and name. Use to get the category ID that Create Channel requires. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: heartbeatOutputSchemas.categoryList,
+ async run({ auth }) {
+ const categories = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: auth.secret_text, method: HttpMethod.GET, path: '/channelCategories', operation: 'list channel categories' }),
+ );
+ return { categories, count: categories.length };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-channel-threads.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-channel-threads.ts
new file mode 100644
index 00000000000..6520a3fb53f
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-channel-threads.ts
@@ -0,0 +1,49 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const listChannelThreadsAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_channel_threads',
+ classification: 'SEARCH',
+ displayName: 'List Threads',
+ description: 'Lists threads in a posts channel, newest first, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists threads in a posts channel, newest first, with author ID, HTML content, link and comment count (full comments only when Include Comments is on). Use to read recent posts or find a thread ID; pass nextCursor as Starting After for older threads. hasMore can be true on an exactly full last page. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ channelId: heartbeatProps.id({ displayName: 'Channel ID', description: 'A posts channel. Use List Channels to find the ID.', required: true }),
+ includeComments: Property.Checkbox({ displayName: 'Include Comments', description: 'Also return each thread\'s comments (larger output).', required: false, defaultValue: false }),
+ limit: heartbeatProps.limit({ max: 100, defaultValue: 20 }),
+ startingAfter: heartbeatProps.startingAfter(),
+ },
+ outputSchema: heartbeatOutputSchemas.threadList,
+ async run({ auth, propsValue }) {
+ const pageLimit = heartbeatApi.limit({ value: propsValue.limit, max: 100, defaultValue: 20 });
+ const threads = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({
+ token: auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/channels/${heartbeatApi.uuid({ value: propsValue.channelId, label: 'Channel ID' })}/threads`,
+ operation: 'list threads',
+ query: {
+ limit: pageLimit,
+ startingAfter: heartbeatApi.optionalUuid({ value: propsValue.startingAfter, label: 'Starting After' }),
+ },
+ }),
+ ).map((thread) => {
+ const comments = heartbeatApi.recordList(thread['comments']);
+ const base = Object.fromEntries(Object.entries(thread).filter(([key]) => key !== 'comments'));
+ return propsValue.includeComments === true
+ ? { ...base, commentCount: comments.length, comments }
+ : { ...base, commentCount: comments.length };
+ });
+ const page = heartbeatApi.toPage({ items: threads, pageLimit });
+ return { threads: page.items, nextCursor: page.nextCursor, hasMore: page.hasMore };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-channels.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-channels.ts
new file mode 100644
index 00000000000..076e80e209a
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-channels.ts
@@ -0,0 +1,45 @@
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatChannels } from '../common/channels';
+
+export const listChannelsAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_channels',
+ classification: 'SEARCH',
+ displayName: 'List Channels',
+ description: 'Lists the channels in the community, optionally only one type.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists every channel (ID, name, emoji and type: POSTS for threads, CHAT for chat, VOICE for voice), optionally only one type. Use to get a channel ID for Create Thread, Send Channel Chat Message or List Threads. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ required: false,
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Posts (threads)', value: 'POSTS' },
+ { label: 'Chat', value: 'CHAT' },
+ { label: 'Voice', value: 'VOICE' },
+ ],
+ },
+ }),
+ },
+ outputSchema: heartbeatOutputSchemas.channelList,
+ async run({ auth, propsValue }) {
+ const type = heartbeatApi.optionalText(propsValue.type);
+ if (type !== undefined && !CHANNEL_TYPES.includes(type)) {
+ throw new Error(`Type must be one of ${CHANNEL_TYPES.join(', ')}.`);
+ }
+ const channels = (await heartbeatChannels.listChannels({ token: auth.secret_text })).filter(
+ (channel) => type === undefined || channel['type'] === type,
+ );
+ return { channels, count: channels.length };
+ },
+});
+
+const CHANNEL_TYPES = ['POSTS', 'CHAT', 'VOICE'];
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-chat-messages.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-chat-messages.ts
new file mode 100644
index 00000000000..d9fd20c826d
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-chat-messages.ts
@@ -0,0 +1,42 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const listChatMessagesAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_chat_messages',
+ classification: 'SEARCH',
+ displayName: 'List Channel Chat Messages',
+ description: 'Lists messages in a chat channel, newest first, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists messages in a chat channel, newest first, with sender ID, HTML content, attachments and time. Use to read recent chat; pass nextCursor as Starting After for older messages while hasMore is true. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ channelId: heartbeatProps.id({ displayName: 'Channel ID', description: 'A chat channel. Use List Channels to find the ID.', required: true }),
+ limit: heartbeatProps.limit({ max: 100, defaultValue: 50 }),
+ startingAfter: heartbeatProps.startingAfter(),
+ },
+ outputSchema: heartbeatOutputSchemas.chatMessageList,
+ async run({ auth, propsValue }) {
+ const pageLimit = heartbeatApi.limit({ value: propsValue.limit, max: 100, defaultValue: 50 });
+ const response = await heartbeatApi.request<unknown>({
+ token: auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/chatChannel/${heartbeatApi.uuid({ value: propsValue.channelId, label: 'Channel ID' })}/messages`,
+ operation: 'list chat messages',
+ query: {
+ limit: pageLimit,
+ startingAfter: heartbeatApi.optionalUuid({ value: propsValue.startingAfter, label: 'Starting After' }),
+ },
+ });
+ const messages = heartbeatApi.recordList(heartbeatApi.isRecord(response) ? response['data'] : undefined);
+ const hasMore = heartbeatApi.isRecord(response) && response['hasMore'] === true;
+ const lastId = messages[messages.length - 1]?.['id'];
+ return { messages, nextCursor: hasMore && typeof lastId === 'string' ? lastId : null, hasMore };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-courses.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-courses.ts
new file mode 100644
index 00000000000..e96504a0d4c
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-courses.ts
@@ -0,0 +1,26 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const listCoursesAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_courses',
+ classification: 'SEARCH',
+ displayName: 'List Courses',
+ description: 'Lists courses with their cohorts, modules and lessons.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists every course with its cohorts, modules and lessons (IDs and names). Use to find lesson IDs for Get Lesson or Mark Lessons Completed. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: heartbeatOutputSchemas.courseList,
+ async run({ auth }) {
+ const courses = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: auth.secret_text, method: HttpMethod.GET, path: '/courses', operation: 'list courses' }),
+ );
+ return { courses, count: courses.length };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-direct-messages.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-direct-messages.ts
new file mode 100644
index 00000000000..487dd435660
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-direct-messages.ts
@@ -0,0 +1,30 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const listDirectMessagesAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_direct_messages',
+ classification: 'SEARCH',
+ displayName: 'List Direct Messages',
+ description: 'Lists the 100 most recent messages of a direct chat that includes an admin.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Returns the 100 most recent messages (sender ID, HTML content, time) of a direct chat by chat ID. Only chats that include at least one admin can be read. Get the chat ID from Get Direct Chat or the New Direct Message trigger. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ chatId: heartbeatProps.id({ displayName: 'Chat ID', description: 'Use Get Direct Chat to find the ID.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.directMessageList,
+ async run({ auth, propsValue }) {
+ const chatId = heartbeatApi.uuid({ value: propsValue.chatId, label: 'Chat ID' });
+ const messages = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: auth.secret_text, method: HttpMethod.GET, path: `/directMessages/${chatId}`, operation: 'list direct messages' }),
+ );
+ return { chatId, messages, count: messages.length };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-documents.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-documents.ts
new file mode 100644
index 00000000000..3b3b5938370
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-documents.ts
@@ -0,0 +1,41 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const listDocumentsAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_documents',
+ classification: 'SEARCH',
+ displayName: 'List Documents',
+ description: 'Lists the community documents (wiki pages), one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists community documents (wiki pages) with ID, title and link, one page at a time. Use to find a document ID for Get Document; pass nextCursor as Starting After for the next page. hasMore can be true on an exactly full last page. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ limit: heartbeatProps.limit({ max: 100, defaultValue: 50 }),
+ startingAfter: heartbeatProps.startingAfter(),
+ },
+ outputSchema: heartbeatOutputSchemas.documentList,
+ async run({ auth, propsValue }) {
+ const pageLimit = heartbeatApi.limit({ value: propsValue.limit, max: 100, defaultValue: 50 });
+ const documents = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({
+ token: auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/documents',
+ operation: 'list documents',
+ query: {
+ limit: pageLimit,
+ startingAfter: heartbeatApi.optionalUuid({ value: propsValue.startingAfter, label: 'Starting After' }),
+ },
+ }),
+ );
+ const page = heartbeatApi.toPage({ items: documents, pageLimit });
+ return { documents: page.items, nextCursor: page.nextCursor, hasMore: page.hasMore };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-events.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-events.ts
new file mode 100644
index 00000000000..610b04e52f1
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-events.ts
@@ -0,0 +1,55 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const listEventsAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_events',
+ classification: 'SEARCH',
+ displayName: 'List Events',
+ description: 'Lists community events, optionally for one group or a time range.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists community events (ID, name, description, start/end time, recurring flag, invited users and groups), optionally only those for a group ID or starting within a time range. Use to find upcoming events or an event ID. Recurring events show their original start time. totalMatching counts all matches even when the list is cut at the limit. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ groupId: heartbeatProps.id({ displayName: 'Group ID', description: 'Only events assigned to this group. Use List Groups to find the ID.', required: false }),
+ startsAfter: Property.DateTime({ displayName: 'Starts After', description: 'Only events whose start time is at or after this time.', required: false }),
+ startsBefore: Property.DateTime({ displayName: 'Starts Before', description: 'Only events whose start time is before this time.', required: false }),
+ limit: heartbeatProps.limit({ max: 1000, defaultValue: 100 }),
+ },
+ outputSchema: heartbeatOutputSchemas.eventList,
+ async run({ auth, propsValue }) {
+ const max = heartbeatApi.limit({ value: propsValue.limit, max: 1000, defaultValue: 100 });
+ const after = heartbeatApi.isoDate({ value: propsValue.startsAfter, label: 'Starts After' });
+ const before = heartbeatApi.isoDate({ value: propsValue.startsBefore, label: 'Starts Before' });
+ if (after !== undefined && before !== undefined && Date.parse(after) >= Date.parse(before)) {
+ throw new Error('Starts After must be earlier than Starts Before.');
+ }
+ const events = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({
+ token: auth.secret_text,
+ method: HttpMethod.GET,
+ path: '/events',
+ operation: 'list events',
+ query: { groupID: heartbeatApi.optionalUuid({ value: propsValue.groupId, label: 'Group ID' }) },
+ }),
+ );
+ const matching = events.filter((event) => {
+ const start = typeof event['startTime'] === 'string' ? Date.parse(event['startTime']) : Number.NaN;
+ if (after !== undefined && !(start >= Date.parse(after))) {
+ return false;
+ }
+ if (before !== undefined && !(start < Date.parse(before))) {
+ return false;
+ }
+ return true;
+ });
+ const page = matching.slice(0, max);
+ return { events: page, count: page.length, totalMatching: matching.length, truncated: matching.length > page.length };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-groups.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-groups.ts
new file mode 100644
index 00000000000..73849d11f35
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-groups.ts
@@ -0,0 +1,34 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const listGroupsAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_groups',
+ classification: 'SEARCH',
+ displayName: 'List Groups',
+ description: 'Lists the groups in the community.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists all groups (ID, name, description, parent group, archived flag), optionally with their members. Use to get group IDs for membership, events, channels and invitations. Archived groups are left out unless Include Archived is on. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ includeArchived: Property.Checkbox({ displayName: 'Include Archived', required: false, defaultValue: false }),
+ includeMembers: Property.Checkbox({ displayName: 'Include Members', description: 'Also return each group member (ID, name, email).', required: false, defaultValue: false }),
+ },
+ outputSchema: heartbeatOutputSchemas.groupList,
+ async run({ auth, propsValue }) {
+ const groups = heartbeatApi
+ .recordList(await heartbeatApi.request<unknown>({ token: auth.secret_text, method: HttpMethod.GET, path: '/groups', operation: 'list groups' }))
+ .filter((group) => propsValue.includeArchived === true || group['archived'] !== true)
+ .map((group) =>
+ propsValue.includeMembers === true
+ ? group
+ : Object.fromEntries(Object.entries(group).filter(([key]) => key !== 'users')),
+ );
+ return { groups, count: groups.length };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-invitations.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-invitations.ts
new file mode 100644
index 00000000000..87f82a4a850
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-invitations.ts
@@ -0,0 +1,26 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const listInvitationsAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_invitations',
+ classification: 'SEARCH',
+ displayName: 'List Invitation Links',
+ description: 'Lists the invitation links with their role and groups.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists every invitation link (ID, 6-character code, role and groups new members get). Use to find an invitation ID for Invite Emails to Invitation Link. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: heartbeatOutputSchemas.invitationList,
+ async run({ auth }) {
+ const invitations = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: auth.secret_text, method: HttpMethod.GET, path: '/invitations', operation: 'list invitation links' }),
+ );
+ return { invitations, count: invitations.length };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-roles.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-roles.ts
new file mode 100644
index 00000000000..ac6963287c1
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-roles.ts
@@ -0,0 +1,26 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const listRolesAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_roles',
+ classification: 'SEARCH',
+ displayName: 'List Roles',
+ description: 'Lists the roles in the community with their IDs.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists every role in the community (ID and name, for example Administrator, Moderator, User). Use to get a role ID for Create Member, Pre-register Member or Create Invitation Link. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: heartbeatOutputSchemas.roleList,
+ async run({ auth }) {
+ const roles = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: auth.secret_text, method: HttpMethod.GET, path: '/roles', operation: 'list roles' }),
+ );
+ return { roles, count: roles.length };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-user-completed-lessons.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-user-completed-lessons.ts
new file mode 100644
index 00000000000..1fb9f889179
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-user-completed-lessons.ts
@@ -0,0 +1,43 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const listUserCompletedLessonsAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_user_completed_lessons',
+ classification: 'SEARCH',
+ displayName: 'List Completed Lessons',
+ description: "Lists a member's completed course lessons, newest completion first.",
+ audience: 'both',
+ aiMetadata: {
+ description: "Lists the course lessons a member has completed (lesson ID and completion time), newest first, one page at a time. Use to check course progress; pass nextCursor as Starting After for the next page. hasMore can be true on an exactly full last page. Read-only and idempotent.",
+ idempotent: true,
+ },
+ props: {
+ userId: heartbeatProps.id({ displayName: 'User ID', description: 'Use List Members to find the ID.', required: true }),
+ limit: heartbeatProps.limit({ max: 100, defaultValue: 50 }),
+ startingAfter: heartbeatProps.startingAfter(),
+ },
+ outputSchema: heartbeatOutputSchemas.completedLessons,
+ async run({ auth, propsValue }) {
+ const pageLimit = heartbeatApi.limit({ value: propsValue.limit, max: 100, defaultValue: 50 });
+ const items = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({
+ token: auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/users/${heartbeatApi.uuid({ value: propsValue.userId, label: 'User ID' })}/completed-lessons`,
+ operation: 'list completed lessons',
+ query: {
+ limit: pageLimit,
+ startingAfter: heartbeatApi.optionalUuid({ value: propsValue.startingAfter, label: 'Starting After' }),
+ },
+ }),
+ );
+ const last = items[items.length - 1]?.['lessonID'];
+ const hasMore = items.length >= pageLimit;
+ return { items, nextCursor: hasMore && typeof last === 'string' ? last : null, hasMore };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/list-users.ts b/packages/pieces/community/heartbeat/src/lib/actions/list-users.ts
new file mode 100644
index 00000000000..470128cc4cc
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/list-users.ts
@@ -0,0 +1,62 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatUsers } from '../common/users';
+
+export const listUsersAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_list_users',
+ classification: 'SEARCH',
+ displayName: 'List Members',
+ description: 'Lists community members, optionally filtered by text, group, role or admin status.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists community members with name, email, role, groups and last login, optionally filtered by name/email text, group ID, role name or admin flag. Use to find a member ID or email before updating, messaging or grouping them. totalMatching counts every match even when the list is cut at the limit. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ search: Property.ShortText({ displayName: 'Name or Email Contains', description: 'Case-insensitive text to match in the name or email.', required: false }),
+ groupId: heartbeatProps.id({ displayName: 'Group ID', description: 'Only members of this group. Use List Groups to find the ID.', required: false }),
+ role: Property.ShortText({ displayName: 'Role Name', description: 'Only members with this role, for example Administrator, Moderator or User (see List Roles).', required: false }),
+ adminsOnly: Property.Checkbox({ displayName: 'Admins Only', required: false, defaultValue: false }),
+ includeProfileDetails: Property.Checkbox({
+ displayName: 'Include Profile Details',
+ description: 'Also return LinkedIn data and onboarding answers (larger output).',
+ required: false,
+ defaultValue: false,
+ }),
+ limit: heartbeatProps.limit({ max: 1000, defaultValue: 100 }),
+ },
+ outputSchema: heartbeatOutputSchemas.userList,
+ async run({ auth, propsValue }) {
+ const max = heartbeatApi.limit({ value: propsValue.limit, max: 1000, defaultValue: 100 });
+ const groupId = heartbeatApi.optionalUuid({ value: propsValue.groupId, label: 'Group ID' });
+ const search = heartbeatApi.optionalText(propsValue.search)?.trim().toLowerCase();
+ const role = heartbeatApi.optionalText(propsValue.role)?.trim().toLowerCase();
+ const users = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: auth.secret_text, method: HttpMethod.GET, path: '/users', operation: 'list members' }),
+ );
+ const matching = users.filter((user) => {
+ if (search && !`${String(user['name'] ?? '')} ${String(user['email'] ?? '')}`.toLowerCase().includes(search)) {
+ return false;
+ }
+ if (role && String(user['role'] ?? '').toLowerCase() !== role) {
+ return false;
+ }
+ if (propsValue.adminsOnly === true && user['isAdmin'] !== true) {
+ return false;
+ }
+ if (groupId && !heartbeatApi.recordList(user['groups']).some((group) => group['id'] === groupId)) {
+ return false;
+ }
+ return true;
+ });
+ const page = matching.slice(0, max).map((user) =>
+ propsValue.includeProfileDetails === true ? user : heartbeatUsers.withoutProfileDetails(user),
+ );
+ return { users: page, count: page.length, totalMatching: matching.length, truncated: matching.length > page.length };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/mark-lessons-completed.ts b/packages/pieces/community/heartbeat/src/lib/actions/mark-lessons-completed.ts
new file mode 100644
index 00000000000..aff948e7e9e
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/mark-lessons-completed.ts
@@ -0,0 +1,92 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatUsers } from '../common/users';
+
+export const markLessonsCompletedAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_mark_lessons_completed',
+ classification: 'WRITE',
+ displayName: 'Mark Lessons Completed',
+ description: "Adds lessons to a member's completed lessons. Never removes completions.",
+ audience: 'both',
+ aiMetadata: {
+ description: "Marks one or more course lessons (by lesson ID, from List Courses) as completed for a member identified by email, at the given time or now. Use to sync progress from another learning tool. Heartbeat silently ignores unknown lesson IDs, so the result lists them in notConfirmed. If the read-back could not finish (more than 500 completions to scan, or a read error), the unchecked lessons are listed in unverified and checkComplete is false. It only adds completions and never removes any; marking an already completed lesson again changes nothing, so it is idempotent.",
+ idempotent: true,
+ },
+ props: {
+ email: Property.ShortText({ displayName: 'Member Email', required: true }),
+ lessonIds: heartbeatProps.ids({ displayName: 'Lesson IDs', description: '1-100 lesson IDs. Use List Courses to find them.', required: true }),
+ completedAt: Property.DateTime({ displayName: 'Completed At', description: 'When the lessons were completed. Defaults to now.', required: false }),
+ },
+ outputSchema: heartbeatOutputSchemas.markedLessons,
+ async run({ auth, propsValue }) {
+ const email = heartbeatApi.email({ value: propsValue.email, label: 'Member Email' });
+ const lessonIds = heartbeatApi.uuidList({ value: propsValue.lessonIds, label: 'Lesson IDs', min: 1 });
+ const completedAt = heartbeatApi.isoDate({ value: propsValue.completedAt, label: 'Completed At' }) ?? new Date().toISOString();
+ await heartbeatApi.request({
+ token: auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/users',
+ operation: 'mark lessons completed',
+ body: { email, completedLessons: lessonIds.map((lessonID) => ({ lessonID, timestamp: completedAt })) },
+ });
+ const lookup = await heartbeatApi.afterWrite({
+ what: "the member's completed lessons",
+ load: () => completedLessonIds({ token: auth.secret_text, email, wanted: lessonIds }),
+ });
+ const found = lookup.value?.found ?? new Set<string>();
+ const checkComplete = lookup.value?.complete ?? false;
+ const missing = lessonIds.filter((id) => !found.has(id));
+ return {
+ email,
+ lessonIds,
+ completedAt,
+ confirmed: lessonIds.filter((id) => found.has(id)),
+ notConfirmed: checkComplete ? missing : [],
+ unverified: checkComplete ? [] : missing,
+ checkComplete,
+ lookupError: lookup.lookupError,
+ };
+ },
+});
+
+async function completedLessonIds({ token, email, wanted }: { token: string; email: string; wanted: string[] }): Promise<CompletionCheck> {
+ const user = await heartbeatUsers.findUserByEmail({ token, email });
+ const userId = typeof user?.['id'] === 'string' ? user['id'] : undefined;
+ if (userId === undefined) {
+ return { found: new Set(), complete: true };
+ }
+ const found = new Set<string>();
+ let startingAfter: string | undefined;
+ for (let page = 0; page < MAX_VERIFY_PAGES; page++) {
+ const items = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({
+ token,
+ method: HttpMethod.GET,
+ path: `/users/${userId}/completed-lessons`,
+ operation: 'list completed lessons',
+ query: { limit: VERIFY_PAGE_SIZE, startingAfter },
+ }),
+ );
+ items.forEach((item) => {
+ if (typeof item['lessonID'] === 'string') {
+ found.add(item['lessonID']);
+ }
+ });
+ const last = items[items.length - 1]?.['lessonID'];
+ if (wanted.every((id) => found.has(id)) || items.length < VERIFY_PAGE_SIZE || typeof last !== 'string') {
+ return { found, complete: true };
+ }
+ startingAfter = last;
+ }
+ return { found, complete: false };
+}
+
+type CompletionCheck = { found: Set<string>; complete: boolean };
+
+const MAX_VERIFY_PAGES = 5;
+const VERIFY_PAGE_SIZE = 100;
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/reactivate-user.ts b/packages/pieces/community/heartbeat/src/lib/actions/reactivate-user.ts
new file mode 100644
index 00000000000..21e382a2c15
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/reactivate-user.ts
@@ -0,0 +1,40 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const reactivateUserAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_reactivate_user',
+ classification: 'WRITE',
+ displayName: 'Reactivate Member',
+ description: 'Gives a deactivated member access to the community again.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Restores community access for a member who was removed (deactivated), identified by email. Use to undo Remove Member. If the member is already active it reports alreadyActive=true instead of failing, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ email: Property.ShortText({ displayName: 'Email', description: 'Email of the member to reactivate.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.reactivatedUser,
+ async run({ auth, propsValue }) {
+ const email = heartbeatApi.email({ value: propsValue.email, label: 'Email' });
+ try {
+ await heartbeatApi.request({
+ token: auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/users/reactivate',
+ operation: 'reactivate member',
+ body: { email },
+ });
+ return { email, reactivated: true, alreadyActive: false };
+ } catch (error) {
+ if (heartbeatApi.statusOf(error) === 400 && /already active/i.test(heartbeatApi.errorMessageOf(error))) {
+ return { email, reactivated: true, alreadyActive: true };
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/remove-user.ts b/packages/pieces/community/heartbeat/src/lib/actions/remove-user.ts
new file mode 100644
index 00000000000..7d5c3f816a8
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/remove-user.ts
@@ -0,0 +1,33 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const removeUserAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_remove_user',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Remove Member (Deactivate)',
+ description: 'Deactivates a member by email. Their threads, comments and messages stay; Reactivate Member undoes it.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Deactivates a member by email so they can no longer access the community; their threads, comments and messages stay, and Reactivate Member undoes it. Use only when asked to remove someone. Fails if no member has that email. Repeating it on a deactivated member succeeds again, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ email: Property.ShortText({ displayName: 'Email', description: 'Email of the member to deactivate.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.removedUser,
+ async run({ auth, propsValue }) {
+ const email = heartbeatApi.email({ value: propsValue.email, label: 'Email' });
+ await heartbeatApi.request({
+ token: auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: '/users',
+ operation: 'remove member',
+ body: { email },
+ });
+ return { email, removed: true };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/remove-users-from-group.ts b/packages/pieces/community/heartbeat/src/lib/actions/remove-users-from-group.ts
new file mode 100644
index 00000000000..4755af75ccd
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/remove-users-from-group.ts
@@ -0,0 +1,36 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+
+export const removeUsersFromGroupAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_remove_users_from_group',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Remove Members from Group',
+ description: 'Removes members from a group by email. They stay in the community.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Removes members (by email) from a group; they stay in the community and keep their other groups. Use for offboarding from a cohort or stage. Removing someone who is not in the group changes nothing, so it is idempotent.',
+ idempotent: true,
+ },
+ props: {
+ groupId: heartbeatProps.id({ displayName: 'Group ID', description: 'Use List Groups to find the ID.', required: true }),
+ emails: heartbeatProps.emails({ displayName: 'Member Emails', description: '1-100 member emails.', required: true }),
+ },
+ outputSchema: heartbeatOutputSchemas.groupRemoval,
+ async run({ auth, propsValue }) {
+ const groupId = heartbeatApi.uuid({ value: propsValue.groupId, label: 'Group ID' });
+ const emails = heartbeatApi.emailList({ value: propsValue.emails, label: 'Member Emails', min: 1 });
+ await heartbeatApi.request({
+ token: auth.secret_text,
+ method: HttpMethod.DELETE,
+ path: `/groups/${groupId}/memberships`,
+ operation: 'remove members from group',
+ body: { emails },
+ });
+ return { groupId, emails, removed: true };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/send-chat-message.ts b/packages/pieces/community/heartbeat/src/lib/actions/send-chat-message.ts
new file mode 100644
index 00000000000..a25ed56383d
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/send-chat-message.ts
@@ -0,0 +1,61 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatMessages } from '../common/messages';
+
+export const sendChatMessageAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_send_chat_message',
+ classification: 'WRITE',
+ displayName: 'Send Channel Chat Message',
+ description: 'Sends a message to a chat channel.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Sends a message to a chat channel (type CHAT from List Channels) as the API-key admin or another admin; members of the channel can be notified. Returns the message ID when it can be matched right after sending, otherwise null. Not idempotent: each call sends another message.',
+ idempotent: false,
+ },
+ props: {
+ channelId: heartbeatProps.id({ displayName: 'Channel ID', description: 'A chat channel. Use List Channels to find the ID.', required: true }),
+ text: heartbeatProps.richText({ displayName: 'Text', required: true }),
+ fromUserId: heartbeatProps.author({ displayName: 'Sender (Admin User ID)' }),
+ },
+ outputSchema: heartbeatOutputSchemas.sentChatMessage,
+ async run({ auth, propsValue }) {
+ const channelId = heartbeatApi.uuid({ value: propsValue.channelId, label: 'Channel ID' });
+ const text = heartbeatApi.richText({ value: propsValue.text, label: 'Text' });
+ const fromUserId = heartbeatApi.optionalUuid({ value: propsValue.fromUserId, label: 'Sender (Admin User ID)' });
+ const sentAfter = Date.now();
+ await heartbeatApi.request({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: `/chatChannel/${channelId}/message`,
+ operation: 'send chat message',
+ body: { text, from: fromUserId },
+ });
+ const lookup = await heartbeatApi.afterWrite({
+ what: 'the sent message',
+ load: async () => {
+ const recent = await heartbeatApi.request<unknown>({
+ token: auth.secret_text,
+ method: HttpMethod.GET,
+ path: `/chatChannel/${channelId}/messages`,
+ operation: 'list chat messages',
+ query: { limit: 10 },
+ });
+ const messages = heartbeatApi.recordList(heartbeatApi.isRecord(recent) ? recent['data'] : undefined);
+ return heartbeatMessages.findSentMessage({ messages, text, senderId: fromUserId, sentAfter });
+ },
+ });
+ const message = lookup.value;
+ return {
+ channelId,
+ sent: true,
+ messageId: typeof message?.['id'] === 'string' ? message['id'] : null,
+ message,
+ lookupError: lookup.lookupError,
+ };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/send-direct-message.ts b/packages/pieces/community/heartbeat/src/lib/actions/send-direct-message.ts
new file mode 100644
index 00000000000..9d292b35948
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/send-direct-message.ts
@@ -0,0 +1,76 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatMessages } from '../common/messages';
+
+export const sendDirectMessageAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_send_direct_message',
+ classification: 'WRITE',
+ displayName: 'Send Direct Message',
+ description: 'Sends a direct message from an admin to a member.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Sends a direct message from an admin (the API-key admin, or the admin in Sender) to one member by user ID; the member is notified. Get IDs from List Members. When Sender is set it also returns the chat ID, link and message ID. Not idempotent: each call sends another message.',
+ idempotent: false,
+ },
+ props: {
+ toUserId: heartbeatProps.id({ displayName: 'Recipient User ID', description: 'Use List Members or Find Member by Email to find the ID.', required: true }),
+ text: heartbeatProps.richText({ displayName: 'Text', required: true }),
+ fromUserId: heartbeatProps.author({ displayName: 'Sender (Admin User ID)' }),
+ },
+ outputSchema: heartbeatOutputSchemas.sentDirectMessage,
+ async run({ auth, propsValue }) {
+ const to = heartbeatApi.uuid({ value: propsValue.toUserId, label: 'Recipient User ID' });
+ const from = heartbeatApi.optionalUuid({ value: propsValue.fromUserId, label: 'Sender (Admin User ID)' });
+ if (from !== undefined && from === to) {
+ throw new Error('Sender and recipient must be different users.');
+ }
+ const text = heartbeatApi.richText({ value: propsValue.text, label: 'Text' });
+ const sentAfter = Date.now();
+ await heartbeatApi.request({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/directMessages',
+ operation: 'send direct message',
+ body: { text, to, from },
+ });
+ if (from === undefined) {
+ return { to, from: null, sent: true, chatId: null, chatUrl: null, messageId: null, lookupError: null };
+ }
+ const lookup = await heartbeatApi.afterWrite({
+ what: 'the direct chat and sent message',
+ load: async () => {
+ const chat = await heartbeatApi.request<unknown>({
+ token: auth.secret_text,
+ method: HttpMethod.PUT,
+ path: '/directChats',
+ operation: 'get direct chat',
+ body: { userID1: from, userID2: to },
+ });
+ const chatId = heartbeatApi.isRecord(chat) && typeof chat['chatID'] === 'string' ? chat['chatID'] : null;
+ const chatUrl = heartbeatApi.isRecord(chat) && typeof chat['url'] === 'string' ? chat['url'] : null;
+ if (chatId === null) {
+ return { chatId, chatUrl, messageId: null };
+ }
+ const messages = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: auth.secret_text, method: HttpMethod.GET, path: `/directMessages/${chatId}`, operation: 'list direct messages' }),
+ );
+ const message = heartbeatMessages.findSentMessage({ messages, text, senderId: from, sentAfter });
+ return { chatId, chatUrl, messageId: typeof message?.['id'] === 'string' ? message['id'] : null };
+ },
+ });
+ return {
+ to,
+ from,
+ sent: true,
+ chatId: lookup.value?.chatId ?? null,
+ chatUrl: lookup.value?.chatUrl ?? null,
+ messageId: lookup.value?.messageId ?? null,
+ lookupError: lookup.lookupError,
+ };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/update-channel.ts b/packages/pieces/community/heartbeat/src/lib/actions/update-channel.ts
new file mode 100644
index 00000000000..36e5f315bfd
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/update-channel.ts
@@ -0,0 +1,75 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatChannels } from '../common/channels';
+
+export const updateChannelAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_update_channel',
+ classification: 'WRITE',
+ displayName: 'Update Channel',
+ description: "Changes a channel's name, description, read-only setting or who can access it.",
+ audience: 'both',
+ aiMetadata: {
+ description: "Changes a channel's name, description, read-only setting or access: 'public' opens it to everyone, 'restricted' limits it to the given emails and group IDs (replacing the previous list). Omitted fields stay as they are; a call with nothing to change is refused. Applying the same values again changes nothing, so it is idempotent.",
+ idempotent: true,
+ },
+ props: {
+ channelId: heartbeatProps.id({ displayName: 'Channel ID', description: 'Use List Channels to find the ID.', required: true }),
+ name: Property.ShortText({ displayName: 'Name', required: false }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ isReadOnly: heartbeatProps.triState({ displayName: 'Read Only', description: 'Only admins and moderators can post threads. Not available for chat channels.' }),
+ access: Property.StaticDropdown({
+ displayName: 'Access',
+ required: false,
+ defaultValue: 'unchanged',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Leave unchanged', value: 'unchanged' },
+ { label: 'Public (everyone)', value: 'public' },
+ { label: 'Restricted to the emails and groups below', value: 'restricted' },
+ ],
+ },
+ }),
+ invitedEmails: heartbeatProps.emails({ displayName: 'Allowed Member Emails', description: 'Used when Access is Restricted. Replaces the current list.', required: false }),
+ invitedGroupIds: heartbeatProps.ids({ displayName: 'Allowed Group IDs', description: 'Used when Access is Restricted. Replaces the current list.', required: false }),
+ },
+ outputSchema: heartbeatOutputSchemas.updatedChannel,
+ async run({ auth, propsValue }) {
+ const channelId = heartbeatApi.uuid({ value: propsValue.channelId, label: 'Channel ID' });
+ const access = propsValue.access ?? 'unchanged';
+ if (!['unchanged', 'public', 'restricted'].includes(access)) {
+ throw new Error('Access must be unchanged, public or restricted.');
+ }
+ const invitedUsers = heartbeatApi.emailList({ value: propsValue.invitedEmails, label: 'Allowed Member Emails' });
+ const invitedGroups = heartbeatApi.uuidList({ value: propsValue.invitedGroupIds, label: 'Allowed Group IDs' });
+ if (access !== 'restricted' && (invitedUsers.length > 0 || invitedGroups.length > 0)) {
+ throw new Error('Allowed emails and groups are only used when Access is Restricted.');
+ }
+ if (access === 'restricted' && invitedUsers.length === 0 && invitedGroups.length === 0) {
+ throw new Error('Access Restricted needs at least one allowed email or group ID.');
+ }
+ const changes: Record<string, unknown> = Object.fromEntries(
+ Object.entries({
+ name: heartbeatApi.optionalText(propsValue.name),
+ description: heartbeatApi.optionalText(propsValue.description),
+ isReadOnly: heartbeatApi.triState(propsValue.isReadOnly),
+ }).filter(([, value]) => value !== undefined),
+ );
+ const body = access === 'public'
+ ? { ...changes, restrictedTo: null }
+ : access === 'restricted'
+ ? { ...changes, restrictedTo: { invitedUsers, invitedGroups } }
+ : changes;
+ if (Object.keys(body).length === 0) {
+ throw new Error('Nothing to update: set at least one field or change Access.');
+ }
+ await heartbeatApi.request({ token: auth.secret_text, method: HttpMethod.POST, path: `/channels/${channelId}`, operation: 'update channel', body });
+ const lookup = await heartbeatApi.afterWrite({ what: 'the updated channel', load: () => heartbeatChannels.findChannel({ token: auth.secret_text, channelId }) });
+ return { id: channelId, updated: true, updatedFields: Object.keys(body), channel: lookup.value, lookupError: lookup.lookupError };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/update-group.ts b/packages/pieces/community/heartbeat/src/lib/actions/update-group.ts
new file mode 100644
index 00000000000..7481a852571
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/update-group.ts
@@ -0,0 +1,45 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatGroups } from '../common/groups';
+
+export const updateGroupAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_update_group',
+ classification: 'WRITE',
+ displayName: 'Update Group',
+ description: 'Changes a group. Fields left empty stay as they are.',
+ audience: 'both',
+ aiMetadata: {
+ description: "Changes a group's name, description, isolated or joinable setting; omitted fields (and 'unchanged') stay as they are, and a call with nothing to change is refused. Use after List Groups. Applying the same values again changes nothing, so it is idempotent.",
+ idempotent: true,
+ },
+ props: {
+ groupId: heartbeatProps.id({ displayName: 'Group ID', description: 'Use List Groups to find the ID.', required: true }),
+ name: Property.ShortText({ displayName: 'Name', required: false }),
+ description: Property.LongText({ displayName: 'Description', required: false }),
+ isIsolated: heartbeatProps.triState({ displayName: 'Isolated', description: 'Members of an isolated group only see content shared with the group.' }),
+ isJoinable: heartbeatProps.triState({ displayName: 'Joinable', description: 'Members can join the group themselves.' }),
+ },
+ outputSchema: heartbeatOutputSchemas.updatedGroup,
+ async run({ auth, propsValue }) {
+ const groupId = heartbeatApi.uuid({ value: propsValue.groupId, label: 'Group ID' });
+ const changes = Object.fromEntries(
+ Object.entries({
+ name: heartbeatApi.optionalText(propsValue.name),
+ description: heartbeatApi.optionalText(propsValue.description),
+ isIsolated: heartbeatApi.triState(propsValue.isIsolated),
+ isJoinable: heartbeatApi.triState(propsValue.isJoinable),
+ }).filter(([, value]) => value !== undefined),
+ );
+ if (Object.keys(changes).length === 0) {
+ throw new Error('Nothing to update: set at least one field.');
+ }
+ await heartbeatApi.request({ token: auth.secret_text, method: HttpMethod.POST, path: `/groups/${groupId}`, operation: 'update group', body: changes });
+ const lookup = await heartbeatApi.afterWrite({ what: 'the updated group', load: () => heartbeatGroups.getGroup({ token: auth.secret_text, groupId }) });
+ return { id: groupId, updated: true, updatedFields: Object.keys(changes), group: lookup.value, lookupError: lookup.lookupError };
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/actions/update-user.ts b/packages/pieces/community/heartbeat/src/lib/actions/update-user.ts
new file mode 100644
index 00000000000..1efeab67111
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/actions/update-user.ts
@@ -0,0 +1,83 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, createAction } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatUsers } from '../common/users';
+
+const CLEARABLE_FIELDS = [
+ { key: 'bio', label: 'Bio' },
+ { key: 'status', label: 'Status' },
+ { key: 'linkedin', label: 'LinkedIn URL' },
+ { key: 'twitter', label: 'Twitter URL' },
+ { key: 'instagram', label: 'Instagram URL' },
+];
+
+export const updateUserAction = createAction({
+ auth: heartbeatAuth,
+ name: 'heartbeat_update_user',
+ classification: 'WRITE',
+ displayName: 'Update Member',
+ description: "Updates a member's profile, identified by email. Fields left empty stay as they are.",
+ audience: 'both',
+ aiMetadata: {
+ description: "Changes a member's profile (name, bio, status, social links) identified by email; fields you omit stay as they are, and Fields to Clear blanks the chosen ones. Use after Find Member by Email. Setting the same values again changes nothing, so it is idempotent.",
+ idempotent: true,
+ },
+ props: {
+ email: Property.ShortText({ displayName: 'Email', description: 'Email of the member to update.', required: true }),
+ name: Property.ShortText({ displayName: 'Name', required: false }),
+ bio: Property.LongText({ displayName: 'Bio', required: false }),
+ status: Property.ShortText({ displayName: 'Status', required: false }),
+ linkedin: Property.ShortText({ displayName: 'LinkedIn URL', description: 'Full URL including https://', required: false }),
+ twitter: Property.ShortText({ displayName: 'Twitter URL', description: 'Full URL including https://', required: false }),
+ instagram: Property.ShortText({ displayName: 'Instagram URL', description: 'Full URL including https://', required: false }),
+ fieldsToClear: Property.StaticMultiSelectDropdown({
+ displayName: 'Fields to Clear',
+ description: 'Blank these fields. A field cannot be both set and cleared.',
+ required: false,
+ options: {
+ disabled: false,
+ options: CLEARABLE_FIELDS.map((field) => ({ label: field.label, value: field.key })),
+ },
+ }),
+ },
+ outputSchema: heartbeatOutputSchemas.updatedUser,
+ async run({ auth, propsValue }) {
+ const email = heartbeatApi.email({ value: propsValue.email, label: 'Email' });
+ const values: Record<string, string | undefined> = {
+ name: heartbeatApi.optionalText(propsValue.name),
+ bio: heartbeatApi.optionalText(propsValue.bio),
+ status: heartbeatApi.optionalText(propsValue.status),
+ linkedin: heartbeatApi.optionalUrl({ value: propsValue.linkedin, label: 'LinkedIn URL' }),
+ twitter: heartbeatApi.optionalUrl({ value: propsValue.twitter, label: 'Twitter URL' }),
+ instagram: heartbeatApi.optionalUrl({ value: propsValue.instagram, label: 'Instagram URL' }),
+ };
+ const clear = (propsValue.fieldsToClear ?? []).map(String);
+ const unknown = clear.filter((key) => !CLEARABLE_FIELDS.some((field) => field.key === key));
+ if (unknown.length > 0) {
+ throw new Error(`Fields to Clear: unknown field(s) ${unknown.join(', ')}. Allowed: ${CLEARABLE_FIELDS.map((field) => field.key).join(', ')}.`);
+ }
+ const conflicting = clear.filter((key) => values[key] !== undefined);
+ if (conflicting.length > 0) {
+ throw new Error(`These fields are both set and cleared: ${conflicting.join(', ')}. Choose one.`);
+ }
+ const changes = {
+ ...Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined)),
+ ...Object.fromEntries(clear.map((key) => [key, ''])),
+ };
+ if (Object.keys(changes).length === 0) {
+ throw new Error('Nothing to update: set at least one field or choose a field to clear.');
+ }
+ await heartbeatApi.request({
+ token: auth.secret_text,
+ method: HttpMethod.POST,
+ path: '/users',
+ operation: 'update member',
+ body: { email, ...changes },
+ });
+ const lookup = await heartbeatApi.afterWrite({ what: 'the updated member', load: () => heartbeatUsers.findUserByEmail({ token: auth.secret_text, email }) });
+ return { email, updated: true, updatedFields: Object.keys(changes), user: lookup.value, lookupError: lookup.lookupError };
+ },
+});
+
diff --git a/packages/pieces/community/heartbeat/src/lib/auth.ts b/packages/pieces/community/heartbeat/src/lib/auth.ts
new file mode 100644
index 00000000000..2bb0cbd4e73
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/auth.ts
@@ -0,0 +1,35 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { PieceAuth } from '@activepieces/pieces-framework';
+import { heartbeatApi } from './common/client';
+
+export const heartbeatAuth = PieceAuth.SecretText({
+ displayName: 'API Key',
+ description: `API access is included in Heartbeat's Scale plan. To create a key:
+1. Log in to your Heartbeat community as an admin.
+2. Open **Settings**, then **Automation**, then **API Keys**.
+3. Click **Create API Key** and give it a label.
+4. Copy the key and paste it here.
+
+Actions run as the admin who created the key.`,
+ required: true,
+ validate: async ({ auth }) => {
+ try {
+ await heartbeatApi.request({
+ token: auth,
+ method: HttpMethod.GET,
+ path: '/roles',
+ operation: 'check API key',
+ });
+ return { valid: true };
+ } catch (error) {
+ const status = heartbeatApi.statusOf(error);
+ if (status === 401 || status === 403) {
+ return {
+ valid: false,
+ error: 'Invalid API key, or your Heartbeat plan does not include API access (Scale plan). Create a new key under Settings > Automation > API Keys.',
+ };
+ }
+ return { valid: false, error: error instanceof Error ? error.message : 'Could not reach Heartbeat to check the API key.' };
+ }
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/common/channels.ts b/packages/pieces/community/heartbeat/src/lib/common/channels.ts
new file mode 100644
index 00000000000..855fe04e624
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/common/channels.ts
@@ -0,0 +1,18 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { heartbeatApi } from './client';
+
+async function listChannels({ token }: { token: string }): Promise<Record<string, unknown>[]> {
+ return heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token, method: HttpMethod.GET, path: '/channels', operation: 'list channels' }),
+ );
+}
+
+async function findChannel({ token, channelId }: { token: string; channelId: string }): Promise<Record<string, unknown> | null> {
+ const channels = await listChannels({ token });
+ return channels.find((channel) => channel['id'] === channelId) ?? null;
+}
+
+export const heartbeatChannels = {
+ listChannels,
+ findChannel,
+};
diff --git a/packages/pieces/community/heartbeat/src/lib/common/client.ts b/packages/pieces/community/heartbeat/src/lib/common/client.ts
new file mode 100644
index 00000000000..e56f734ac72
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/common/client.ts
@@ -0,0 +1,379 @@
+import {
+ AuthenticationType,
+ HttpMethod,
+ HttpRequest,
+ httpClient,
+} from '@activepieces/pieces-common';
+
+export const HEARTBEAT_BASE_URL = 'https://api.heartbeat.chat/v0';
+
+const REQUEST_TIMEOUT_MS = 30_000;
+const RATE_LIMIT_RETRY_DELAYS_MS = [1_000, 2_000];
+const MAX_ERROR_TEXT = 500;
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+const MAX_LIST_ITEMS = 100;
+const BLOCK_TAG_PATTERN = /^<(p|h1|h2|h3|ul)[\s>]/i;
+
+export class HeartbeatApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }) {
+ super(`Heartbeat ${operation} failed (${status}): ${describeStatus({ status, responseBody })}`);
+ this.name = 'HeartbeatApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function vendorMessage(responseBody: unknown): string {
+ if (typeof responseBody === 'string' && responseBody.trim().length > 0) {
+ return responseBody.trim().slice(0, MAX_ERROR_TEXT);
+ }
+ if (isRecord(responseBody)) {
+ const message = responseBody['message'];
+ if (typeof message === 'string' && message.length > 0) {
+ return message.slice(0, MAX_ERROR_TEXT);
+ }
+ return JSON.stringify(responseBody).slice(0, MAX_ERROR_TEXT);
+ }
+ return 'no details returned';
+}
+
+function describeStatus({ status, responseBody }: { status: number; responseBody: unknown }): string {
+ const detail = vendorMessage(responseBody);
+ switch (status) {
+ case 401:
+ case 403:
+ return `the API key is invalid or revoked, or your Heartbeat plan does not include API access. ${detail}`;
+ case 404:
+ return `not found. Check the IDs or email you passed. ${detail}`;
+ case 429:
+ return `Heartbeat rate limit reached, try again in a few seconds. ${detail}`;
+ default:
+ return detail;
+ }
+}
+
+function statusOf(error: unknown): number | undefined {
+ if (error instanceof HeartbeatApiError) {
+ return error.status;
+ }
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ if (isRecord(response) && typeof response['status'] === 'number') {
+ return response['status'];
+ }
+ return undefined;
+}
+
+function responseBodyOf(error: unknown): unknown {
+ if (error instanceof HeartbeatApiError) {
+ return error.responseBody;
+ }
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ return isRecord(response) ? response['body'] : undefined;
+}
+
+function errorMessageOf(error: unknown): string {
+ const body = responseBodyOf(error);
+ return isRecord(body) && typeof body['message'] === 'string' ? body['message'] : '';
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function toQueryParams(query: Record<string, QueryValue> | undefined): Record<string, string> {
+ if (!query) {
+ return {};
+ }
+ return Object.fromEntries(
+ Object.entries(query)
+ .filter(([, value]) => value !== undefined && value !== null && value !== '')
+ .map(([key, value]) => [key, String(value)]),
+ );
+}
+
+function authHeaders(token: string): Record<string, string> {
+ return { Authorization: `Bearer ${token.trim()}` };
+}
+
+async function request<T>({ token, method, path, operation, query, body, wait = sleep }: HeartbeatRequest): Promise<T> {
+ const httpRequest: HttpRequest = {
+ method,
+ url: `${HEARTBEAT_BASE_URL}${path}`,
+ authentication: { type: AuthenticationType.BEARER_TOKEN, token: token.trim() },
+ queryParams: toQueryParams(query),
+ timeout: REQUEST_TIMEOUT_MS,
+ followRedirects: false,
+ };
+ if (body !== undefined) {
+ httpRequest.body = body;
+ httpRequest.headers = { 'Content-Type': 'application/json' };
+ }
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await httpClient.sendRequest<T>(httpRequest);
+ if (response.status >= 300) {
+ throw new HeartbeatApiError({ operation, status: response.status, responseBody: response.body });
+ }
+ return response.body;
+ } catch (error) {
+ const status = statusOf(error);
+ if (status === undefined) {
+ throw error;
+ }
+ if (status === 429 && attempt < RATE_LIMIT_RETRY_DELAYS_MS.length) {
+ await wait(RATE_LIMIT_RETRY_DELAYS_MS[attempt]);
+ continue;
+ }
+ if (error instanceof HeartbeatApiError) {
+ throw error;
+ }
+ throw new HeartbeatApiError({ operation, status, responseBody: responseBodyOf(error) });
+ }
+ }
+}
+
+function isBlank(value: unknown): boolean {
+ return value === undefined || value === null || (typeof value === 'string' && value.trim() === '');
+}
+
+function uuid({ value, label }: Labeled): string {
+ if (isBlank(value)) {
+ throw new Error(`${label} is required.`);
+ }
+ const text = String(value).trim();
+ if (!UUID_PATTERN.test(text)) {
+ throw new Error(`${label} "${text.slice(0, 100)}" is not a valid Heartbeat ID (expected a UUID such as 3f2b6c1e-8d4a-4f6b-9c1d-2e5a7b8c9d0e).`);
+ }
+ return text.toLowerCase();
+}
+
+function optionalUuid({ value, label }: Labeled): string | undefined {
+ return isBlank(value) ? undefined : uuid({ value, label });
+}
+
+function toStringList({ value, label }: Labeled): string[] {
+ if (value === undefined || value === null || value === '') {
+ return [];
+ }
+ const raw: unknown[] = Array.isArray(value)
+ ? value
+ : typeof value === 'string'
+ ? value.split(/[\n,]/)
+ : [value];
+ return raw.flatMap((item) => {
+ if (item === undefined || item === null) {
+ return [];
+ }
+ if (isRecord(item)) {
+ throw new Error(`${label} must be a list of text values.`);
+ }
+ if (Array.isArray(item)) {
+ return toStringList({ value: item, label });
+ }
+ const text = String(item).trim();
+ return text.length > 0 ? [text] : [];
+ });
+}
+
+function uuidList({ value, label, min = 0, max = MAX_LIST_ITEMS }: Labeled & ListBounds): string[] {
+ const ids = [...new Set(toStringList({ value, label }).map((item) => uuid({ value: item, label })))];
+ checkBounds({ count: ids.length, label, min, max });
+ return ids;
+}
+
+function email({ value, label }: Labeled): string {
+ if (isBlank(value)) {
+ throw new Error(`${label} is required.`);
+ }
+ const text = String(value).trim();
+ if (!EMAIL_PATTERN.test(text) || text.length > 320) {
+ throw new Error(`${label} "${text.slice(0, 100)}" is not a valid email address.`);
+ }
+ return text;
+}
+
+function emailList({ value, label, min = 0, max = MAX_LIST_ITEMS }: Labeled & ListBounds): string[] {
+ const seen = new Set<string>();
+ const emails: string[] = [];
+ for (const item of toStringList({ value, label })) {
+ const checked = email({ value: item, label });
+ const key = checked.toLowerCase();
+ if (!seen.has(key)) {
+ seen.add(key);
+ emails.push(checked);
+ }
+ }
+ checkBounds({ count: emails.length, label, min, max });
+ return emails;
+}
+
+function listOrUndefined(values: string[]): string[] | undefined {
+ return values.length > 0 ? values : undefined;
+}
+
+function checkBounds({ count, label, min = 0, max = MAX_LIST_ITEMS }: { count: number; label: string } & ListBounds): void {
+ if (count < min) {
+ throw new Error(min === 1 ? `${label}: add at least one value.` : `${label}: add at least ${min} values.`);
+ }
+ if (count > max) {
+ throw new Error(`${label}: at most ${max} values per run (got ${count}).`);
+ }
+}
+
+function requiredText({ value, label }: Labeled): string {
+ if (isBlank(value)) {
+ throw new Error(`${label} is required.`);
+ }
+ return String(value);
+}
+
+function richText({ value, label }: Labeled): string {
+ const text = requiredText({ value, label }).trim();
+ if (BLOCK_TAG_PATTERN.test(text)) {
+ return text;
+ }
+ return text
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter((line) => line.length > 0)
+ .map((line) => `<p>${line}</p>`)
+ .join('');
+}
+
+function optionalText(value: unknown): string | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ const text = String(value);
+ return text.trim().length === 0 ? undefined : text;
+}
+
+function optionalUrl({ value, label }: Labeled): string | undefined {
+ if (isBlank(value)) {
+ return undefined;
+ }
+ const text = String(value).trim();
+ if (!/^https?:\/\/\S+$/i.test(text)) {
+ throw new Error(`${label} "${text.slice(0, 100)}" must be a full URL starting with http:// or https://.`);
+ }
+ return text;
+}
+
+function limit({ value, max, defaultValue }: { value: unknown; max: number; defaultValue: number }): number {
+ if (value === undefined || value === null || value === '') {
+ return defaultValue;
+ }
+ const parsed = Number(value);
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > max) {
+ throw new Error(`Limit must be a whole number between 1 and ${max}.`);
+ }
+ return parsed;
+}
+
+function isoDate({ value, label }: Labeled): string | undefined {
+ if (isBlank(value)) {
+ return undefined;
+ }
+ const text = String(value).trim();
+ const parsed = new Date(text);
+ if (Number.isNaN(parsed.getTime())) {
+ throw new Error(`${label} "${text.slice(0, 100)}" is not a valid date. Use ISO 8601, for example 2026-10-13T15:00:00Z.`);
+ }
+ return parsed.toISOString();
+}
+
+function triState(value: unknown): boolean | undefined {
+ if (value === 'yes' || value === true) {
+ return true;
+ }
+ if (value === 'no' || value === false) {
+ return false;
+ }
+ return undefined;
+}
+
+function toPage({ items, pageLimit }: { items: Record<string, unknown>[]; pageLimit: number }): PageOutput {
+ const hasMore = items.length >= pageLimit;
+ const lastId = items[items.length - 1]?.['id'];
+ return { items, nextCursor: hasMore && typeof lastId === 'string' ? lastId : null, hasMore };
+}
+
+function recordList(value: unknown): Record<string, unknown>[] {
+ return Array.isArray(value) ? value.filter(isRecord) : [];
+}
+
+async function afterWrite<T>({ load, what }: { load: () => Promise<T>; what: string }): Promise<AfterWriteResult<T>> {
+ try {
+ return { value: await load(), lookupError: null };
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error);
+ return {
+ value: null,
+ lookupError: `The change was saved in Heartbeat, but reading back ${what} failed (${reason}). Do not re-run this step for the same input, or the change may be made twice.`,
+ };
+ }
+}
+
+export const heartbeatApi = {
+ request,
+ authHeaders,
+ statusOf,
+ responseBodyOf,
+ errorMessageOf,
+ isRecord,
+ uuid,
+ optionalUuid,
+ uuidList,
+ email,
+ emailList,
+ listOrUndefined,
+ requiredText,
+ richText,
+ optionalText,
+ optionalUrl,
+ limit,
+ isoDate,
+ triState,
+ toPage,
+ recordList,
+ sleep,
+ afterWrite,
+};
+
+export type AfterWriteResult<T> = { value: T | null; lookupError: string | null };
+
+export type QueryValue = string | number | boolean | undefined | null;
+
+export type HeartbeatRequest = {
+ token: string;
+ method: HttpMethod;
+ path: string;
+ operation: string;
+ query?: Record<string, QueryValue>;
+ body?: unknown;
+ wait?: (ms: number) => Promise<void>;
+};
+
+export type ListBounds = { min?: number; max?: number };
+
+export type Labeled = { value: unknown; label: string };
+
+export type PageOutput = {
+ items: Record<string, unknown>[];
+ nextCursor: string | null;
+ hasMore: boolean;
+};
diff --git a/packages/pieces/community/heartbeat/src/lib/common/events.ts b/packages/pieces/community/heartbeat/src/lib/common/events.ts
new file mode 100644
index 00000000000..4813a878435
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/common/events.ts
@@ -0,0 +1,15 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { heartbeatApi } from './client';
+
+async function getEvent({ token, eventId }: { token: string; eventId: string }): Promise<Record<string, unknown>> {
+ return heartbeatApi.request<Record<string, unknown>>({
+ token,
+ method: HttpMethod.GET,
+ path: `/events/${eventId}`,
+ operation: 'get event',
+ });
+}
+
+export const heartbeatEvents = {
+ getEvent,
+};
diff --git a/packages/pieces/community/heartbeat/src/lib/common/groups.ts b/packages/pieces/community/heartbeat/src/lib/common/groups.ts
new file mode 100644
index 00000000000..2ade0f1a3bc
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/common/groups.ts
@@ -0,0 +1,24 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { heartbeatApi } from './client';
+
+async function getGroup({ token, groupId }: { token: string; groupId: string }): Promise<Record<string, unknown>> {
+ return heartbeatApi.request<Record<string, unknown>>({
+ token,
+ method: HttpMethod.GET,
+ path: `/groups/${groupId}`,
+ operation: 'get group',
+ });
+}
+
+function memberEmails(group: Record<string, unknown>): Set<string> {
+ return new Set(
+ heartbeatApi
+ .recordList(group['users'])
+ .flatMap((user) => (typeof user['email'] === 'string' ? [user['email'].toLowerCase()] : [])),
+ );
+}
+
+export const heartbeatGroups = {
+ getGroup,
+ memberEmails,
+};
diff --git a/packages/pieces/community/heartbeat/src/lib/common/messages.ts b/packages/pieces/community/heartbeat/src/lib/common/messages.ts
new file mode 100644
index 00000000000..0aa5ba3a4c1
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/common/messages.ts
@@ -0,0 +1,37 @@
+function plainText(html: string): string {
+ return html.replace(/<[^>]*>/g, ' ').replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ').trim();
+}
+
+function findSentMessage({ messages, text, senderId, sentAfter }: FindSentMessageParams): Record<string, unknown> | null {
+ const wanted = plainText(text);
+ const candidates = messages.filter((message) => {
+ if (senderId !== undefined && message['userID'] !== senderId) {
+ return false;
+ }
+ if (typeof message['content'] !== 'string' || plainText(message['content']) !== wanted) {
+ return false;
+ }
+ const createdAt = typeof message['createdAt'] === 'string' ? Date.parse(message['createdAt']) : Number.NaN;
+ return Number.isNaN(createdAt) || createdAt >= sentAfter - CLOCK_SKEW_MS;
+ });
+ return candidates.reduce<Record<string, unknown> | null>((latest, message) => {
+ if (latest === null) {
+ return message;
+ }
+ return String(message['createdAt'] ?? '') > String(latest['createdAt'] ?? '') ? message : latest;
+ }, null);
+}
+
+const CLOCK_SKEW_MS = 120_000;
+
+export const heartbeatMessages = {
+ plainText,
+ findSentMessage,
+};
+
+type FindSentMessageParams = {
+ messages: Record<string, unknown>[];
+ text: string;
+ senderId: string | undefined;
+ sentAfter: number;
+};
diff --git a/packages/pieces/community/heartbeat/src/lib/common/output-schemas.ts b/packages/pieces/community/heartbeat/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..315c2d69c9a
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/common/output-schemas.ts
@@ -0,0 +1,546 @@
+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+function field({ key, label, format, description, value }: FieldParams): OutputSchemaField {
+ return {
+ key,
+ label,
+ ...(value !== undefined ? { value } : {}),
+ ...(format !== undefined ? { format } : {}),
+ ...(description !== undefined ? { description } : {}),
+ };
+}
+
+function list({ key, label, items, labelKey, description }: ListParams): OutputSchemaField {
+ return {
+ key,
+ label,
+ listItems: items,
+ ...(labelKey !== undefined ? { labelKey } : {}),
+ ...(description !== undefined ? { description } : {}),
+ };
+}
+
+function object({ key, label, children, description }: ObjectParams): OutputSchemaField {
+ return { key, label, children, ...(description !== undefined ? { description } : {}) };
+}
+
+const idName: OutputSchemaField[] = [
+ field({ key: 'id', label: 'ID' }),
+ field({ key: 'name', label: 'Name' }),
+];
+
+const socialLinkFields: OutputSchemaField[] = [
+ field({ key: 'linkedin', label: 'LinkedIn', format: 'url' }),
+ field({ key: 'twitter', label: 'Twitter', format: 'url' }),
+ field({ key: 'instagram', label: 'Instagram', format: 'url' }),
+ field({ key: 'calendar', label: 'Calendar', format: 'url' }),
+ field({ key: 'personalWebsite', label: 'Website', format: 'url' }),
+ field({ key: 'community', label: 'Community', format: 'url' }),
+];
+
+const userSummaryFields: OutputSchemaField[] = [
+ field({ key: 'id', label: 'User ID', description: 'Use this to message the member or read their profile in a later step.' }),
+ field({ key: 'email', label: 'Email', format: 'email' }),
+ field({ key: 'name', label: 'Name' }),
+ field({ key: 'firstName', label: 'First Name' }),
+ field({ key: 'lastName', label: 'Last Name' }),
+ field({ key: 'role', label: 'Role' }),
+ field({ key: 'isAdmin', label: 'Is Admin', format: 'boolean' }),
+ list({ key: 'groups', label: 'Groups', items: idName, labelKey: 'name' }),
+ field({ key: 'bio', label: 'Bio' }),
+ field({ key: 'avatar', label: 'Avatar', format: 'image' }),
+ field({ key: 'createdAt', label: 'Joined At', format: 'datetime' }),
+ field({ key: 'lastLogin', label: 'Last Login', format: 'datetime', description: 'Empty if the member never logged in.' }),
+ object({ key: 'socialLinks', label: 'Social Links', children: socialLinkFields }),
+];
+
+const userFields: OutputSchemaField[] = [
+ ...userSummaryFields,
+ field({ key: 'linkedInSummary', label: 'LinkedIn Summary' }),
+ object({
+ key: 'linkedInData',
+ label: 'LinkedIn Data',
+ children: [
+ field({ key: 'profileUrl', label: 'Profile URL', format: 'url' }),
+ field({ key: 'headline', label: 'Headline' }),
+ field({ key: 'company', label: 'Company' }),
+ field({ key: 'location', label: 'Location' }),
+ ],
+ }),
+ list({
+ key: 'onboardingResponses',
+ label: 'Onboarding Answers',
+ labelKey: 'question',
+ items: [
+ field({ key: 'question', label: 'Question' }),
+ field({ key: 'answer', label: 'Answer' }),
+ field({ key: 'isPrivate', label: 'Private', format: 'boolean' }),
+ ],
+ }),
+];
+
+const groupFields: OutputSchemaField[] = [
+ field({ key: 'id', label: 'Group ID' }),
+ field({ key: 'name', label: 'Name' }),
+ field({ key: 'description', label: 'Description', format: 'html' }),
+ field({ key: 'color', label: 'Color' }),
+ field({ key: 'parentGroupID', label: 'Parent Group ID', description: 'Empty for a top-level group.' }),
+ field({ key: 'archived', label: 'Archived', format: 'boolean' }),
+ list({
+ key: 'users',
+ label: 'Members',
+ labelKey: 'name',
+ items: [
+ field({ key: 'id', label: 'User ID' }),
+ field({ key: 'name', label: 'Name' }),
+ field({ key: 'email', label: 'Email', format: 'email' }),
+ ],
+ }),
+];
+
+const channelFields: OutputSchemaField[] = [
+ field({ key: 'id', label: 'Channel ID' }),
+ field({ key: 'name', label: 'Name' }),
+ field({ key: 'emoji', label: 'Emoji' }),
+ field({ key: 'type', label: 'Type', description: 'POSTS (threads), CHAT or VOICE.' }),
+];
+
+const messageFields: OutputSchemaField[] = [
+ field({ key: 'id', label: 'Message ID' }),
+ field({ key: 'userID', label: 'Sender User ID' }),
+ field({ key: 'content', label: 'Content', format: 'html' }),
+ field({ key: 'createdAt', label: 'Sent At', format: 'datetime' }),
+ field({ key: 'images', label: 'Images' }),
+ field({ key: 'files', label: 'Files' }),
+];
+
+const replyFields: OutputSchemaField[] = [
+ field({ key: 'id', label: 'Comment ID' }),
+ field({ key: 'userID', label: 'Author User ID' }),
+ field({ key: 'content', label: 'Content', format: 'html' }),
+ field({ key: 'createdAt', label: 'Created At', format: 'datetime' }),
+];
+
+const commentFields: OutputSchemaField[] = [
+ ...replyFields,
+ field({ key: 'images', label: 'Images' }),
+ field({ key: 'files', label: 'Files' }),
+ list({ key: 'children', label: 'Replies', items: replyFields }),
+];
+
+const threadSummaryFields: OutputSchemaField[] = [
+ field({ key: 'id', label: 'Thread ID' }),
+ field({ key: 'channelID', label: 'Channel ID' }),
+ field({ key: 'userID', label: 'Author User ID' }),
+ field({ key: 'content', label: 'Content', format: 'html' }),
+ field({ key: 'createdAt', label: 'Created At', format: 'datetime' }),
+ field({ key: 'url', label: 'Thread URL', format: 'url' }),
+ field({ key: 'files', label: 'Files' }),
+];
+
+const threadFields: OutputSchemaField[] = [
+ ...threadSummaryFields,
+ object({
+ key: 'user',
+ label: 'Author',
+ children: [
+ field({ key: 'id', label: 'User ID' }),
+ field({ key: 'name', label: 'Name' }),
+ field({ key: 'email', label: 'Email', format: 'email' }),
+ ],
+ }),
+ list({ key: 'comments', label: 'Comments', items: commentFields }),
+];
+
+const eventFields: OutputSchemaField[] = [
+ field({ key: 'id', label: 'Event ID' }),
+ field({ key: 'name', label: 'Name' }),
+ field({ key: 'description', label: 'Description', format: 'html' }),
+ field({ key: 'startTime', label: 'Start Time', format: 'datetime', description: 'For recurring events this is the first occurrence and may be in the past.' }),
+ field({ key: 'endTime', label: 'End Time', format: 'datetime' }),
+ field({ key: 'recurring', label: 'Recurring', format: 'boolean' }),
+ field({ key: 'createdAt', label: 'Created At', format: 'datetime' }),
+ field({ key: 'createdBy', label: 'Created By (User ID)' }),
+ field({ key: 'invitedUsers', label: 'Invited User IDs' }),
+ field({ key: 'invitedGroups', label: 'Invited Group IDs' }),
+ field({ key: 'coverImage', label: 'Cover Image', format: 'image' }),
+];
+
+const instanceFields: OutputSchemaField[] = [
+ field({ key: 'startTime', label: 'Start Time', format: 'datetime' }),
+ field({ key: 'endTime', label: 'End Time', format: 'datetime' }),
+];
+
+const invitationFields: OutputSchemaField[] = [
+ field({ key: 'id', label: 'Invitation Link ID' }),
+ field({ key: 'code', label: 'Code', description: 'The 6-character code in the invitation link.' }),
+ object({ key: 'role', label: 'Role', children: idName }),
+ list({ key: 'groups', label: 'Groups', items: idName, labelKey: 'name' }),
+];
+
+const lessonFields: OutputSchemaField[] = [
+ field({ key: 'id', label: 'Lesson ID' }),
+ field({ key: 'title', label: 'Title' }),
+ field({ key: 'content', label: 'Content (Markdown)' }),
+ field({ key: 'createdAt', label: 'Created At', format: 'datetime' }),
+ field({ key: 'createdBy', label: 'Created By (User ID)' }),
+ list({
+ key: 'communityEmbedCards',
+ label: 'Embedded Cards',
+ labelKey: 'title',
+ items: [field({ key: 'id', label: 'Card ID' }), field({ key: 'title', label: 'Title' }), field({ key: 'description', label: 'Description' })],
+ }),
+];
+
+const documentSummaryFields: OutputSchemaField[] = [
+ field({ key: 'id', label: 'Document ID' }),
+ field({ key: 'name', label: 'Title' }),
+ field({ key: 'link', label: 'Link', format: 'url' }),
+];
+
+const nextCursorField = field({ key: 'nextCursor', label: 'Next Cursor', description: 'Pass as Starting After to get the next page. Empty when there are no more.' });
+const hasMoreField = field({ key: 'hasMore', label: 'Has More', format: 'boolean' });
+const countField = field({ key: 'count', label: 'Count', format: 'number' });
+
+const lookupErrorField = field({
+ key: 'lookupError',
+ label: 'Read-Back Error',
+ description: 'Empty on success. Set when the change was saved but reading the result back failed; the step still succeeds so a retry does not repeat the change.',
+});
+
+const deletedFields: OutputSchemaField[] = [
+ field({ key: 'id', label: 'ID' }),
+ field({ key: 'deleted', label: 'Deleted', format: 'boolean' }),
+ field({ key: 'alreadyDeleted', label: 'Already Deleted', format: 'boolean', description: 'True when it was already gone before this run.' }),
+];
+
+export const heartbeatOutputSchemas = {
+ user: { fields: userFields },
+ createdUser: {
+ fields: [
+ field({ key: 'userID', label: 'User ID', description: 'ID of the new member.' }),
+ ...userFields.filter((item) => item.key !== 'id'),
+ lookupErrorField,
+ ],
+ },
+ userList: {
+ fields: [
+ list({ key: 'users', label: 'Members', items: userSummaryFields, labelKey: 'name' }),
+ countField,
+ field({ key: 'totalMatching', label: 'Total Matching', format: 'number', description: 'All members matching the filters, even beyond the limit.' }),
+ field({ key: 'truncated', label: 'Truncated', format: 'boolean', description: 'True when more members matched than the limit allowed.' }),
+ ],
+ },
+ findUser: {
+ fields: [
+ field({ key: 'found', label: 'Found', format: 'boolean' }),
+ object({ key: 'user', label: 'Member', children: userFields, description: 'Empty when no member has this email.' }),
+ ],
+ },
+ updatedUser: {
+ fields: [
+ field({ key: 'email', label: 'Email', format: 'email' }),
+ field({ key: 'updated', label: 'Updated', format: 'boolean' }),
+ field({ key: 'updatedFields', label: 'Updated Fields' }),
+ object({ key: 'user', label: 'Member', children: userSummaryFields }),
+ lookupErrorField,
+ ],
+ },
+ removedUser: {
+ fields: [
+ field({ key: 'email', label: 'Email', format: 'email' }),
+ field({ key: 'removed', label: 'Removed', format: 'boolean' }),
+ ],
+ },
+ reactivatedUser: {
+ fields: [
+ field({ key: 'email', label: 'Email', format: 'email' }),
+ field({ key: 'reactivated', label: 'Reactivated', format: 'boolean' }),
+ field({ key: 'alreadyActive', label: 'Already Active', format: 'boolean' }),
+ ],
+ },
+ pendingUser: {
+ fields: [
+ field({ key: 'email', label: 'Email', format: 'email' }),
+ field({ key: 'success', label: 'Success', format: 'boolean' }),
+ ],
+ },
+ completedLessons: {
+ fields: [
+ list({
+ key: 'items',
+ label: 'Completed Lessons',
+ items: [field({ key: 'lessonID', label: 'Lesson ID' }), field({ key: 'completedAt', label: 'Completed At', format: 'datetime' })],
+ }),
+ nextCursorField,
+ hasMoreField,
+ ],
+ },
+ markedLessons: {
+ fields: [
+ field({ key: 'email', label: 'Email', format: 'email' }),
+ field({ key: 'lessonIds', label: 'Lesson IDs' }),
+ field({ key: 'completedAt', label: 'Completed At', format: 'datetime' }),
+ field({ key: 'confirmed', label: 'Confirmed Lesson IDs', description: 'Lessons that now show as completed for the member.' }),
+ field({ key: 'notConfirmed', label: 'Not Confirmed Lesson IDs', description: 'Lessons Heartbeat did not record after a full check, usually because the lesson ID does not exist.' }),
+ field({ key: 'unverified', label: 'Unverified Lesson IDs', description: 'Lessons that could not be checked because the read-back stopped early (more than 500 completions) or failed.' }),
+ field({ key: 'checkComplete', label: 'Check Complete', format: 'boolean', description: 'False when some lessons could not be checked; see Unverified Lesson IDs.' }),
+ lookupErrorField,
+ ],
+ },
+ roleList: {
+ fields: [list({ key: 'roles', label: 'Roles', items: idName, labelKey: 'name' }), countField],
+ },
+ groupList: {
+ fields: [list({ key: 'groups', label: 'Groups', items: groupFields, labelKey: 'name' }), countField],
+ },
+ group: { fields: groupFields },
+ createdGroup: { fields: [...groupFields, lookupErrorField] },
+ updatedGroup: {
+ fields: [
+ field({ key: 'id', label: 'Group ID' }),
+ field({ key: 'updated', label: 'Updated', format: 'boolean' }),
+ field({ key: 'updatedFields', label: 'Updated Fields' }),
+ object({ key: 'group', label: 'Group', children: groupFields }),
+ lookupErrorField,
+ ],
+ },
+ deleted: { fields: deletedFields },
+ groupMembership: {
+ fields: [
+ field({ key: 'groupId', label: 'Group ID' }),
+ field({ key: 'emails', label: 'Requested Emails' }),
+ field({ key: 'added', label: 'In Group Now' }),
+ field({ key: 'notAdded', label: 'Not Added', description: 'Emails that are not community members; Heartbeat ignores them.' }),
+ field({ key: 'unverified', label: 'Unverified', description: 'Emails that could not be checked because reading the group back failed.' }),
+ lookupErrorField,
+ ],
+ },
+ groupRemoval: {
+ fields: [
+ field({ key: 'groupId', label: 'Group ID' }),
+ field({ key: 'emails', label: 'Emails' }),
+ field({ key: 'removed', label: 'Removed', format: 'boolean' }),
+ ],
+ },
+ channelList: {
+ fields: [list({ key: 'channels', label: 'Channels', items: channelFields, labelKey: 'name' }), countField],
+ },
+ categoryList: {
+ fields: [list({ key: 'categories', label: 'Categories', items: idName, labelKey: 'name' }), countField],
+ },
+ category: { fields: idName },
+ channel: { fields: channelFields },
+ createdChannel: { fields: [...channelFields, lookupErrorField] },
+ updatedChannel: {
+ fields: [
+ field({ key: 'id', label: 'Channel ID' }),
+ field({ key: 'updated', label: 'Updated', format: 'boolean' }),
+ field({ key: 'updatedFields', label: 'Updated Fields' }),
+ object({ key: 'channel', label: 'Channel', children: channelFields }),
+ lookupErrorField,
+ ],
+ },
+ threadList: {
+ fields: [
+ list({
+ key: 'threads',
+ label: 'Threads',
+ items: [...threadSummaryFields, field({ key: 'commentCount', label: 'Comment Count', format: 'number' }), list({ key: 'comments', label: 'Comments', items: commentFields })],
+ }),
+ nextCursorField,
+ hasMoreField,
+ ],
+ },
+ thread: { fields: threadFields },
+ createdThread: { fields: [...threadSummaryFields, list({ key: 'comments', label: 'Comments', items: commentFields })] },
+ comment: {
+ fields: [
+ ...commentFields,
+ field({ key: 'threadId', label: 'Thread ID' }),
+ field({ key: 'parentCommentId', label: 'Parent Comment ID', description: 'Empty for a comment on the thread itself.' }),
+ ],
+ },
+ sentChatMessage: {
+ fields: [
+ field({ key: 'channelId', label: 'Channel ID' }),
+ field({ key: 'sent', label: 'Sent', format: 'boolean' }),
+ field({ key: 'messageId', label: 'Message ID', description: 'Empty if the message could not be matched right after sending.' }),
+ object({ key: 'message', label: 'Message', children: messageFields }),
+ lookupErrorField,
+ ],
+ },
+ chatMessageList: {
+ fields: [list({ key: 'messages', label: 'Messages', items: messageFields }), nextCursorField, hasMoreField],
+ },
+ sentDirectMessage: {
+ fields: [
+ field({ key: 'to', label: 'Recipient User ID' }),
+ field({ key: 'from', label: 'Sender User ID', description: 'Empty when sent as the API-key admin.' }),
+ field({ key: 'sent', label: 'Sent', format: 'boolean' }),
+ field({ key: 'chatId', label: 'Chat ID', description: 'Returned when a Sender is set.' }),
+ field({ key: 'chatUrl', label: 'Chat URL', format: 'url' }),
+ field({ key: 'messageId', label: 'Message ID' }),
+ lookupErrorField,
+ ],
+ },
+ directChat: {
+ fields: [field({ key: 'chatID', label: 'Chat ID' }), field({ key: 'url', label: 'Chat URL', format: 'url' })],
+ },
+ directMessageList: {
+ fields: [field({ key: 'chatId', label: 'Chat ID' }), list({ key: 'messages', label: 'Messages', items: messageFields }), countField],
+ },
+ eventList: {
+ fields: [
+ list({ key: 'events', label: 'Events', items: eventFields, labelKey: 'name' }),
+ countField,
+ field({ key: 'totalMatching', label: 'Total Matching', format: 'number' }),
+ field({ key: 'truncated', label: 'Truncated', format: 'boolean' }),
+ ],
+ },
+ event: { fields: eventFields },
+ eventWithInstances: {
+ fields: [...eventFields, list({ key: 'instances', label: 'Occurrences', items: instanceFields, description: 'Only with Include Occurrences.' })],
+ },
+ createdEvent: {
+ fields: [
+ ...eventFields,
+ object({
+ key: 'location',
+ label: 'Location',
+ children: [
+ field({ key: 'type', label: 'Type' }),
+ field({ key: 'voiceChannelID', label: 'Voice Channel ID', description: 'Set when the event is held in a Heartbeat voice channel.' }),
+ field({ key: 'locationStr', label: 'Custom Location', description: 'Set when a custom location was given.' }),
+ ],
+ }),
+ lookupErrorField,
+ ],
+ },
+ eventAttendance: {
+ fields: [
+ field({ key: 'eventId', label: 'Event ID' }),
+ field({ key: 'happened', label: 'Has Happened', format: 'boolean', description: 'False when the event has not taken place yet.' }),
+ list({
+ key: 'instances',
+ label: 'Occurrences',
+ items: [
+ ...instanceFields,
+ list({
+ key: 'attendees',
+ label: 'Attendees',
+ labelKey: 'name',
+ items: [
+ field({ key: 'id', label: 'User ID' }),
+ field({ key: 'name', label: 'Name' }),
+ field({ key: 'email', label: 'Email', format: 'email' }),
+ field({ key: 'isUser', label: 'Is Member', format: 'boolean' }),
+ ],
+ }),
+ ],
+ }),
+ ],
+ },
+ invitationList: {
+ fields: [list({ key: 'invitations', label: 'Invitation Links', items: invitationFields, labelKey: 'code' }), countField],
+ },
+ invitation: { fields: invitationFields },
+ invitationEmails: {
+ fields: [
+ field({ key: 'invitationId', label: 'Invitation Link ID' }),
+ field({ key: 'emails', label: 'Emails' }),
+ field({ key: 'emailSent', label: 'Invitation Email Sent', format: 'boolean' }),
+ ],
+ },
+ courseList: {
+ fields: [
+ list({
+ key: 'courses',
+ label: 'Courses',
+ labelKey: 'name',
+ items: [
+ field({ key: 'id', label: 'Course ID' }),
+ field({ key: 'name', label: 'Name' }),
+ field({ key: 'description', label: 'Description' }),
+ field({ key: 'thumbnail', label: 'Thumbnail', format: 'image' }),
+ list({
+ key: 'cohorts',
+ label: 'Cohorts',
+ labelKey: 'name',
+ items: [
+ ...idName,
+ list({
+ key: 'modules',
+ label: 'Modules',
+ labelKey: 'name',
+ items: [...idName, list({ key: 'lessons', label: 'Lessons', labelKey: 'name', items: idName })],
+ }),
+ ],
+ }),
+ ],
+ }),
+ countField,
+ ],
+ },
+ lesson: { fields: lessonFields },
+ documentList: {
+ fields: [list({ key: 'documents', label: 'Documents', items: documentSummaryFields, labelKey: 'name' }), nextCursorField, hasMoreField],
+ },
+ document: {
+ fields: [...documentSummaryFields, field({ key: 'content', label: 'Content (Markdown)' })],
+ },
+ mention: {
+ fields: [
+ field({ key: 'sourceType', label: 'Mentioned In', description: 'THREAD or COMMENT.' }),
+ list({
+ key: 'mentionedUsers',
+ label: 'Mentioned',
+ description: 'The chosen members or groups that were mentioned.',
+ items: [field({ key: 'id', label: 'User or Group ID' }), field({ key: 'type', label: 'Type', description: 'USER or GROUP.' })],
+ }),
+ field({ key: 'authorUserId', label: 'Author User ID' }),
+ field({ key: 'channelId', label: 'Channel ID' }),
+ field({ key: 'threadId', label: 'Thread ID' }),
+ field({ key: 'commentId', label: 'Comment ID', description: 'Empty when the mention is in the thread itself.' }),
+ field({ key: 'content', label: 'Content', format: 'html' }),
+ field({ key: 'threadUrl', label: 'Thread URL', format: 'url' }),
+ object({ key: 'thread', label: 'Thread', children: threadSummaryFields }),
+ object({ key: 'comment', label: 'Comment', children: commentFields }),
+ ],
+ },
+ directMessageEvent: {
+ fields: [
+ field({ key: 'chatId', label: 'Chat ID' }),
+ field({ key: 'messageId', label: 'Message ID' }),
+ field({ key: 'senderUserId', label: 'Sender User ID' }),
+ field({ key: 'receiverUserId', label: 'Receiver User ID' }),
+ field({ key: 'content', label: 'Content', format: 'html' }),
+ field({ key: 'createdAt', label: 'Sent At', format: 'datetime' }),
+ field({ key: 'images', label: 'Images' }),
+ field({ key: 'files', label: 'Files' }),
+ ],
+ },
+} satisfies Record<string, OutputSchema>;
+
+type FieldParams = {
+ key: string;
+ label: string;
+ format?: OutputSchemaField['format'];
+ description?: string;
+ value?: string;
+};
+
+type ListParams = {
+ key: string;
+ label: string;
+ items: OutputSchemaField[];
+ labelKey?: string;
+ description?: string;
+};
+
+type ObjectParams = {
+ key: string;
+ label: string;
+ children: OutputSchemaField[];
+ description?: string;
+};
diff --git a/packages/pieces/community/heartbeat/src/lib/common/props.ts b/packages/pieces/community/heartbeat/src/lib/common/props.ts
new file mode 100644
index 00000000000..870e17a0d45
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/common/props.ts
@@ -0,0 +1,136 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from './client';
+
+function idProp({ displayName, description, required }: IdPropParams) {
+ return required
+ ? Property.ShortText({ displayName, description, required: true })
+ : Property.ShortText({ displayName, description, required: false });
+}
+
+function emailsProp({ displayName, description, required }: IdPropParams) {
+ return required
+ ? Property.Array({ displayName, description, required: true })
+ : Property.Array({ displayName, description, required: false });
+}
+
+function idsProp({ displayName, description, required }: IdPropParams) {
+ return required
+ ? Property.Array({ displayName, description, required: true })
+ : Property.Array({ displayName, description, required: false });
+}
+
+function limitProp({ max, defaultValue }: { max: number; defaultValue: number }) {
+ return Property.Number({
+ displayName: 'Limit',
+ description: `How many items to return (1-${max}, default ${defaultValue}).`,
+ required: false,
+ defaultValue,
+ });
+}
+
+function startingAfterProp() {
+ return Property.ShortText({
+ displayName: 'Starting After (Cursor)',
+ description: 'Leave empty for the first page. To get the next page, pass the Next Cursor value from the previous run.',
+ required: false,
+ });
+}
+
+function richTextProp({ displayName, required }: { displayName: string; required: boolean }) {
+ const description = `Plain text is sent as paragraphs (one per line). HTML is also supported: p, a, b, h1, h2, h3, ul, li and br (other tags are removed; text outside p, h1-h3 or ul blocks is dropped by Heartbeat). Mention a member or group with @ followed by their ID, for example @3f2b6c1e-8d4a-4f6b-9c1d-2e5a7b8c9d0e; mentioned people are notified.`;
+ return required
+ ? Property.LongText({ displayName, description, required: true })
+ : Property.LongText({ displayName, description, required: false });
+}
+
+function authorProp({ displayName }: { displayName: string }) {
+ return Property.ShortText({
+ displayName,
+ description: 'User ID of an admin to post as. Leave empty to post as the admin who created the API key. Use List Members to find admin IDs.',
+ required: false,
+ });
+}
+
+function triStateProp({ displayName, description }: { displayName: string; description: string }) {
+ return Property.StaticDropdown({
+ displayName,
+ description,
+ required: false,
+ defaultValue: 'unchanged',
+ options: {
+ disabled: false,
+ options: [
+ { label: 'Leave unchanged', value: 'unchanged' },
+ { label: 'Yes', value: 'yes' },
+ { label: 'No', value: 'no' },
+ ],
+ },
+ });
+}
+
+async function loadOptions({ token, path, operation }: { token: string; path: string; operation: string }) {
+ try {
+ const items = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token, method: HttpMethod.GET, path, operation }),
+ );
+ return {
+ disabled: false,
+ options: items.flatMap((item) =>
+ typeof item['id'] === 'string' ? [{ label: String(item['name'] ?? item['id']), value: item['id'] }] : [],
+ ),
+ };
+ } catch (error) {
+ const status = heartbeatApi.statusOf(error);
+ const reason = status === 401 || status === 403
+ ? 'The API key was rejected. Reconnect with a valid key.'
+ : status === 429
+ ? 'Heartbeat rate limit reached. Try again in a few seconds.'
+ : `Could not load options from Heartbeat${status ? ` (${status})` : ''}.`;
+ return { disabled: true, options: [], placeholder: reason };
+ }
+}
+
+const roleDropdown = Property.Dropdown({
+ auth: heartbeatAuth,
+ displayName: 'Roles',
+ description: 'The role the user should have',
+ required: true,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Please select a connection first.' };
+ }
+ return loadOptions({ token: auth.secret_text, path: '/roles', operation: 'list roles' });
+ },
+});
+
+const groupsDropdown = Property.MultiSelectDropdown({
+ auth: heartbeatAuth,
+ displayName: 'Groups',
+ description: 'A list of the ids of the groups that the user should belong to.',
+ required: false,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Please select a connection first.' };
+ }
+ return loadOptions({ token: auth.secret_text, path: '/groups', operation: 'list groups' });
+ },
+});
+
+export const heartbeatProps = {
+ id: idProp,
+ ids: idsProp,
+ emails: emailsProp,
+ limit: limitProp,
+ startingAfter: startingAfterProp,
+ richText: richTextProp,
+ author: authorProp,
+ triState: triStateProp,
+ roleDropdown,
+ groupsDropdown,
+};
+
+type IdPropParams = { displayName: string; description: string; required: boolean };
diff --git a/packages/pieces/community/heartbeat/src/lib/common/samples.ts b/packages/pieces/community/heartbeat/src/lib/common/samples.ts
new file mode 100644
index 00000000000..416719c04f2
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/common/samples.ts
@@ -0,0 +1,95 @@
+const user = {
+ id: '0fed0eb0-9dc6-41e9-a09d-ea53d3158c3a',
+ email: '[email protected]',
+ name: 'Jane Doe',
+ firstName: 'Jane',
+ lastName: 'Doe',
+ bio: '',
+ createdAt: '2026-10-06T12:09:26.682Z',
+ lastLogin: null,
+ role: 'User',
+ isAdmin: false,
+ groups: [{ name: 'User', id: 'e611cac5-58a2-4b43-8328-4ae0fe5b5fcc' }],
+ avatar: 'https://dfle76rxbxaz7.cloudfront.net/assets/Default%20Profile%20Pics/placeholder-image-2.jpg',
+ linkedInSummary: '',
+ linkedInData: null,
+ socialLinks: {},
+ onboardingResponses: [],
+};
+
+const thread = {
+ id: 'e5285d90-ce1b-4620-b9f1-9444ff6f9bea',
+ userID: '871072f3-af66-4fb0-b8a4-49290816d64e',
+ channelID: 'a0bb7f6a-ad62-4ea7-99ac-5079bf0725fe',
+ content: '<p>Welcome to the community!</p>',
+ reactions: {},
+ createdAt: '2026-10-06T12:10:00.944Z',
+ files: [],
+ url: 'https://app.heartbeat.chat/example/t/announcements/e5285d90-ce1b-4620-b9f1-9444ff6f9bea',
+ comments: [],
+ user: { id: '871072f3-af66-4fb0-b8a4-49290816d64e', name: 'Alex Admin', email: '[email protected]' },
+};
+
+const event = {
+ id: 'acb92b02-b8cb-4e96-914b-825ac9d416d5',
+ name: 'Weekly community call',
+ description: '<p>Open Q&amp;A</p>',
+ startTime: '2026-10-13T15:00:00.000Z',
+ endTime: '2026-10-13T15:30:00.000Z',
+ createdAt: '2026-10-06T12:10:34.787Z',
+ createdBy: '871072f3-af66-4fb0-b8a4-49290816d64e',
+ invitedUsers: [],
+ invitedGroups: ['13fcd1ac-535f-46b6-bed8-a7eb1b87f96c'],
+ recurring: false,
+ coverImage: null,
+};
+
+const mention = {
+ sourceType: 'COMMENT',
+ mentionedUsers: [{ id: '0fed0eb0-9dc6-41e9-a09d-ea53d3158c3a', type: 'USER' }],
+ authorUserId: '871072f3-af66-4fb0-b8a4-49290816d64e',
+ channelId: 'a0bb7f6a-ad62-4ea7-99ac-5079bf0725fe',
+ threadId: 'e5285d90-ce1b-4620-b9f1-9444ff6f9bea',
+ commentId: '4f3467f8-7e8a-4c71-8699-2ca6ae806c66',
+ content: '<p>Thanks <span class="reference" data-denotation-char="@" data-id="mention.user.0fed0eb0-9dc6-41e9-a09d-ea53d3158c3a" data-value="Jane Doe">@Jane Doe</span>!</p>',
+ threadUrl: 'https://app.heartbeat.chat/example/t/announcements/e5285d90-ce1b-4620-b9f1-9444ff6f9bea',
+ thread: {
+ id: 'e5285d90-ce1b-4620-b9f1-9444ff6f9bea',
+ userID: '871072f3-af66-4fb0-b8a4-49290816d64e',
+ channelID: 'a0bb7f6a-ad62-4ea7-99ac-5079bf0725fe',
+ content: '<p>Welcome to the community!</p>',
+ reactions: {},
+ createdAt: '2026-10-06T12:10:00.944Z',
+ files: [],
+ url: 'https://app.heartbeat.chat/example/t/announcements/e5285d90-ce1b-4620-b9f1-9444ff6f9bea',
+ },
+ comment: {
+ id: '4f3467f8-7e8a-4c71-8699-2ca6ae806c66',
+ userID: '871072f3-af66-4fb0-b8a4-49290816d64e',
+ images: [],
+ createdAt: '2026-10-06T12:10:13.807Z',
+ content: '<p>Thanks <span class="reference" data-denotation-char="@" data-id="mention.user.0fed0eb0-9dc6-41e9-a09d-ea53d3158c3a" data-value="Jane Doe">@Jane Doe</span>!</p>',
+ reactions: {},
+ files: [],
+ children: [],
+ },
+};
+
+const directMessage = {
+ chatId: '654e5fe6-5208-4ca9-a3c3-ba47d9765d33',
+ messageId: '1ec429d3-86ba-4fec-a0d7-c7dee0e4c8f8',
+ senderUserId: '0fed0eb0-9dc6-41e9-a09d-ea53d3158c3a',
+ receiverUserId: '871072f3-af66-4fb0-b8a4-49290816d64e',
+ content: '<p>Hi, I have a question about the course.</p>',
+ createdAt: '2026-10-06T12:10:20.226Z',
+ images: [],
+ files: [],
+};
+
+export const heartbeatSamples = {
+ user,
+ thread,
+ event,
+ mention,
+ directMessage,
+};
diff --git a/packages/pieces/community/heartbeat/src/lib/common/users.ts b/packages/pieces/community/heartbeat/src/lib/common/users.ts
new file mode 100644
index 00000000000..997dc33e3ad
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/common/users.ts
@@ -0,0 +1,65 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { heartbeatApi } from './client';
+
+async function getUser({ token, userId }: { token: string; userId: string }): Promise<Record<string, unknown>> {
+ return heartbeatApi.request<Record<string, unknown>>({
+ token,
+ method: HttpMethod.GET,
+ path: `/users/${userId}`,
+ operation: 'get member',
+ });
+}
+
+async function findUserByEmail({ token, email }: { token: string; email: string }): Promise<Record<string, unknown> | null> {
+ try {
+ const result = await heartbeatApi.request<unknown>({
+ token,
+ method: HttpMethod.GET,
+ path: '/find/users',
+ operation: 'find member by email',
+ query: { email },
+ });
+ if (Array.isArray(result)) {
+ return result.find(heartbeatApi.isRecord) ?? null;
+ }
+ return heartbeatApi.isRecord(result) ? result : null;
+ } catch (error) {
+ if (heartbeatApi.statusOf(error) === 404) {
+ return null;
+ }
+ throw error;
+ }
+}
+
+function withoutProfileDetails(user: Record<string, unknown>): Record<string, unknown> {
+ return Object.fromEntries(
+ Object.entries(user).filter(([key]) => !PROFILE_DETAIL_KEYS.includes(key)),
+ );
+}
+
+async function createUser({ token, body }: { token: string; body: Record<string, unknown> }): Promise<Record<string, unknown>> {
+ const created = await heartbeatApi.request<unknown>({
+ token,
+ method: HttpMethod.PUT,
+ path: '/users',
+ operation: 'create member',
+ body,
+ });
+ const vendor = heartbeatApi.isRecord(created) ? created : {};
+ const userId = typeof vendor['userID'] === 'string' ? vendor['userID'] : undefined;
+ const lookup = await heartbeatApi.afterWrite({
+ what: 'the new member',
+ load: () => (userId ? getUser({ token, userId }) : findUserByEmail({ token, email: String(body['email']) })),
+ });
+ const user = lookup.value;
+ return { ...vendor, ...(user ?? {}), userID: userId ?? user?.['id'] ?? null, lookupError: lookup.lookupError };
+}
+
+const PROFILE_DETAIL_KEYS = ['linkedInData', 'linkedInSummary', 'onboardingResponses'];
+
+export const heartbeatUsers = {
+ getUser,
+ findUserByEmail,
+ withoutProfileDetails,
+ createUser,
+};
diff --git a/packages/pieces/community/heartbeat/src/lib/common/webhooks.ts b/packages/pieces/community/heartbeat/src/lib/common/webhooks.ts
new file mode 100644
index 00000000000..f05789879d5
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/common/webhooks.ts
@@ -0,0 +1,178 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { createHash, randomUUID } from 'crypto';
+import { heartbeatApi } from './client';
+
+async function deleteWebhook({ token, webhookId }: { token: string; webhookId: string }): Promise<void> {
+ try {
+ await heartbeatApi.request({ token, method: HttpMethod.DELETE, path: `/webhooks/${webhookId}`, operation: 'delete webhook' });
+ } catch (error) {
+ if (heartbeatApi.statusOf(error) !== 404) {
+ throw error;
+ }
+ }
+}
+
+async function enable({ token, store, webhookUrl, action }: EnableParams): Promise<string> {
+ const previous = await store.get<StoredWebhook>(WEBHOOK_STORE_KEY);
+ if (previous?.webhookId) {
+ await deleteWebhook({ token, webhookId: previous.webhookId });
+ await store.delete(WEBHOOK_STORE_KEY);
+ }
+ const existing = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token, method: HttpMethod.GET, path: '/webhooks', operation: 'list webhooks' }),
+ );
+ for (const hook of existing) {
+ if (hook['url'] === webhookUrl && typeof hook['id'] === 'string') {
+ await deleteWebhook({ token, webhookId: hook['id'] });
+ }
+ }
+ const created = await heartbeatApi.request<unknown>({
+ token,
+ method: HttpMethod.PUT,
+ path: '/webhooks',
+ operation: 'create webhook',
+ body: { action, url: webhookUrl },
+ });
+ const webhookId = heartbeatApi.isRecord(created) ? created['id'] : undefined;
+ if (typeof webhookId !== 'string') {
+ throw new Error('Heartbeat did not return a webhook ID, so the trigger could not be enabled. Try again.');
+ }
+ try {
+ await store.put<StoredWebhook>(WEBHOOK_STORE_KEY, { webhookId });
+ } catch (error) {
+ await deleteWebhook({ token, webhookId });
+ throw error;
+ }
+ return webhookId;
+}
+
+async function disable({ token, store }: { token: string; store: WebhookStore }): Promise<void> {
+ const stored = await store.get<StoredWebhook>(WEBHOOK_STORE_KEY);
+ if (!stored?.webhookId) {
+ return;
+ }
+ await deleteWebhook({ token, webhookId: stored.webhookId });
+ await store.delete(WEBHOOK_STORE_KEY);
+}
+
+async function isFirstDelivery({ store, key }: { store: WebhookStore; key: string }): Promise<boolean> {
+ const claimKey = claimKeyOf(key);
+ const existing = await store.get<DeliveryClaim>(claimKey);
+ if (existing !== null && !isAbandoned({ claim: existing, now: Date.now() })) {
+ return false;
+ }
+ const token = randomUUID();
+ const at = Date.now();
+ try {
+ await store.put<DeliveryClaim>(claimKey, { token, at, done: false });
+ await heartbeatApi.sleep(CLAIM_SETTLE_MS);
+ const winner = await store.get<DeliveryClaim>(claimKey);
+ if (winner?.token !== token) {
+ return false;
+ }
+ await rememberClaim({ store, claimKey });
+ await store.put<DeliveryClaim>(claimKey, { token, at, done: true });
+ return true;
+ } catch (error) {
+ await releaseClaim({ store, claimKey, token });
+ throw error;
+ }
+}
+
+function isAbandoned({ claim, now }: { claim: DeliveryClaim; now: number }): boolean {
+ return claim.done === false && typeof claim.at === 'number' && now - claim.at > ABANDONED_CLAIM_MS;
+}
+
+async function releaseClaim({ store, claimKey, token }: { store: WebhookStore; claimKey: string; token: string }): Promise<void> {
+ try {
+ const current = await store.get<DeliveryClaim>(claimKey);
+ if (current?.token === token) {
+ await store.delete(claimKey);
+ }
+ } catch {
+ // Store still failing: the unfinished claim is treated as abandoned after ABANDONED_CLAIM_MS, so a later retry can emit the event.
+ }
+}
+
+function claimKeyOf(key: string): string {
+ return `${CLAIM_KEY_PREFIX}${createHash('sha256').update(key).digest('hex').slice(0, 32)}`;
+}
+
+async function rememberClaim({ store, claimKey }: { store: WebhookStore; claimKey: string }): Promise<void> {
+ const seen = (await store.get<string[]>(SEEN_STORE_KEY)) ?? [];
+ const next = [...seen.filter((item) => item !== claimKey), claimKey];
+ const evicted = next.slice(0, Math.max(0, next.length - MAX_SEEN_KEYS));
+ await store.put<string[]>(SEEN_STORE_KEY, next.slice(-MAX_SEEN_KEYS));
+ for (const old of evicted) {
+ await store.delete(old);
+ }
+}
+
+function payloadOf(body: unknown): Record<string, unknown> {
+ if (typeof body === 'string') {
+ try {
+ const parsed: unknown = JSON.parse(body);
+ return heartbeatApi.isRecord(parsed) ? parsed : {};
+ } catch {
+ return {};
+ }
+ }
+ return heartbeatApi.isRecord(body) ? body : {};
+}
+
+function uuidOrNull(value: unknown): string | null {
+ try {
+ return heartbeatApi.uuid({ value, label: 'ID' });
+ } catch {
+ return null;
+ }
+}
+
+async function fetchOrNull<T>(load: () => Promise<T>): Promise<T | null> {
+ try {
+ return await load();
+ } catch (error) {
+ if (heartbeatApi.statusOf(error) === 404) {
+ return null;
+ }
+ throw error;
+ }
+}
+
+const WEBHOOK_STORE_KEY = 'heartbeat_webhook';
+const SEEN_STORE_KEY = 'heartbeat_seen_deliveries';
+const MAX_SEEN_KEYS = 500;
+const CLAIM_KEY_PREFIX = 'hb_delivery_';
+const CLAIM_SETTLE_MS = 500;
+const ABANDONED_CLAIM_MS = 60_000;
+
+export const heartbeatWebhooks = {
+ enable,
+ disable,
+ isFirstDelivery,
+ payloadOf,
+ uuidOrNull,
+ fetchOrNull,
+ MAX_SEEN_KEYS,
+ WEBHOOK_STORE_KEY,
+ SEEN_STORE_KEY,
+ claimKeyOf,
+ ABANDONED_CLAIM_MS,
+};
+
+type StoredWebhook = { webhookId: string };
+
+type DeliveryClaim = { token: string; at?: number; done?: boolean };
+
+type WebhookStore = {
+ get<T>(key: string): Promise<T | null>;
+ put<T>(key: string, value: T): Promise<T>;
+ delete(key: string): Promise<void>;
+};
+
+type EnableParams = {
+ token: string;
+ store: WebhookStore;
+ webhookUrl: string;
+ action: { name: string; filter?: Record<string, unknown> };
+};
diff --git a/packages/pieces/community/heartbeat/src/lib/triggers/new-direct-message.ts b/packages/pieces/community/heartbeat/src/lib/triggers/new-direct-message.ts
new file mode 100644
index 00000000000..8b51dca5ffd
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/triggers/new-direct-message.ts
@@ -0,0 +1,99 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatWebhooks } from '../common/webhooks';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatSamples } from '../common/samples';
+
+export const newDirectMessageTrigger = createTrigger({
+ auth: heartbeatAuth,
+ name: 'heartbeat_new_direct_message',
+ displayName: 'New Direct Message to Admin',
+ description: 'Fires when a chosen admin receives a direct message.',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Fires once when the chosen admin receives a direct message and returns the chat ID, the sender ID (from the stored message), the receiver ID (the chosen admin) and the message (content, time, attachments), re-read from Heartbeat. Messages the admin sent, and chats that are not between the admin and the sender, are ignored.',
+ },
+ props: {
+ adminUserId: heartbeatProps.id({ displayName: 'Admin User ID', description: 'The admin whose incoming direct messages fire this trigger. Use List Members (Admins Only) to find the ID.', required: true }),
+ },
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: heartbeatSamples.directMessage,
+ outputSchema: heartbeatOutputSchemas.directMessageEvent,
+ async onEnable(context) {
+ await heartbeatWebhooks.enable({
+ token: context.auth.secret_text,
+ store: context.store,
+ webhookUrl: context.webhookUrl,
+ action: { name: 'DIRECT_MESSAGE', filter: { userID: heartbeatApi.uuid({ value: context.propsValue.adminUserId, label: 'Admin User ID' }) } },
+ });
+ },
+ async onDisable(context) {
+ await heartbeatWebhooks.disable({ token: context.auth.secret_text, store: context.store });
+ },
+ async run(context) {
+ const payload = heartbeatWebhooks.payloadOf(context.payload.body);
+ const chatId = heartbeatWebhooks.uuidOrNull(payload['chatID']);
+ const messageId = heartbeatWebhooks.uuidOrNull(payload['chatMessageID']);
+ if (chatId === null || messageId === null) {
+ return [];
+ }
+ const messages = await heartbeatWebhooks.fetchOrNull(async () =>
+ heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: context.auth.secret_text, method: HttpMethod.GET, path: `/directMessages/${chatId}`, operation: 'list direct messages' }),
+ ),
+ );
+ const message = messages?.find((item) => item['id'] === messageId) ?? null;
+ const adminUserId = heartbeatApi.uuid({ value: context.propsValue.adminUserId, label: 'Admin User ID' });
+ const senderUserId = typeof message?.['userID'] === 'string' ? message['userID'] : null;
+ if (message === null || senderUserId === null || senderUserId === adminUserId) {
+ return [];
+ }
+ if (!(await isAdminChat({ token: context.auth.secret_text, chatId, adminUserId, senderUserId, messages: messages ?? [] }))) {
+ return [];
+ }
+ if (!(await heartbeatWebhooks.isFirstDelivery({ store: context.store, key: `DIRECT_MESSAGE:${messageId}` }))) {
+ return [];
+ }
+ return [
+ {
+ chatId,
+ messageId,
+ senderUserId,
+ receiverUserId: adminUserId,
+ content: message['content'] ?? null,
+ createdAt: message['createdAt'] ?? null,
+ images: message['images'] ?? [],
+ files: message['files'] ?? [],
+ },
+ ];
+ },
+});
+
+async function isAdminChat({ token, chatId, adminUserId, senderUserId, messages }: AdminChatCheck): Promise<boolean> {
+ const onlyTheTwo = messages.every((item) => item['userID'] === adminUserId || item['userID'] === senderUserId);
+ if (!onlyTheTwo) {
+ return false;
+ }
+ if (messages.some((item) => item['userID'] === adminUserId)) {
+ return true;
+ }
+ const chat = await heartbeatApi.request<unknown>({
+ token,
+ method: HttpMethod.PUT,
+ path: '/directChats',
+ operation: 'confirm direct chat',
+ body: { userID1: adminUserId, userID2: senderUserId },
+ });
+ return heartbeatApi.isRecord(chat) && chat['chatID'] === chatId;
+}
+
+type AdminChatCheck = {
+ token: string;
+ chatId: string;
+ adminUserId: string;
+ senderUserId: string;
+ messages: Record<string, unknown>[];
+};
diff --git a/packages/pieces/community/heartbeat/src/lib/triggers/new-event.ts b/packages/pieces/community/heartbeat/src/lib/triggers/new-event.ts
new file mode 100644
index 00000000000..4b911df8098
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/triggers/new-event.ts
@@ -0,0 +1,56 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatWebhooks } from '../common/webhooks';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatEvents } from '../common/events';
+import { heartbeatSamples } from '../common/samples';
+
+export const newEventTrigger = createTrigger({
+ auth: heartbeatAuth,
+ name: 'heartbeat_new_event',
+ displayName: 'New Event',
+ description: 'Fires when a new event is created in the community.',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Fires once when an event is created in the community and returns the event (name, description, start/end time, recurring flag, invited users and groups), re-read from Heartbeat.',
+ },
+ props: {},
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: heartbeatSamples.event,
+ outputSchema: heartbeatOutputSchemas.event,
+ async onEnable(context) {
+ await heartbeatWebhooks.enable({
+ token: context.auth.secret_text,
+ store: context.store,
+ webhookUrl: context.webhookUrl,
+ action: { name: 'EVENT_CREATE' },
+ });
+ },
+ async onDisable(context) {
+ await heartbeatWebhooks.disable({ token: context.auth.secret_text, store: context.store });
+ },
+ async test(context) {
+ const events = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: context.auth.secret_text, method: HttpMethod.GET, path: '/events', operation: 'list events' }),
+ );
+ return [...events]
+ .sort((a, b) => String(b['createdAt'] ?? '').localeCompare(String(a['createdAt'] ?? '')))
+ .slice(0, 5);
+ },
+ async run(context) {
+ const eventId = heartbeatWebhooks.uuidOrNull(heartbeatWebhooks.payloadOf(context.payload.body)['id']);
+ if (eventId === null) {
+ return [];
+ }
+ const event = await heartbeatWebhooks.fetchOrNull(() => heartbeatEvents.getEvent({ token: context.auth.secret_text, eventId }));
+ if (event === null) {
+ return [];
+ }
+ if (!(await heartbeatWebhooks.isFirstDelivery({ store: context.store, key: `EVENT_CREATE:${eventId}` }))) {
+ return [];
+ }
+ return [event];
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/triggers/new-member.ts b/packages/pieces/community/heartbeat/src/lib/triggers/new-member.ts
new file mode 100644
index 00000000000..f0e88b0c07f
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/triggers/new-member.ts
@@ -0,0 +1,56 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatWebhooks } from '../common/webhooks';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatUsers } from '../common/users';
+import { heartbeatSamples } from '../common/samples';
+
+export const newMemberTrigger = createTrigger({
+ auth: heartbeatAuth,
+ name: 'heartbeat_new_member',
+ displayName: 'New Member Joined',
+ description: 'Fires when a new member joins the community. Members added with Create User or Create Member do not fire it.',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Fires once when a person joins the Heartbeat community themselves (for example through an invitation link; members added through the API do not fire it) and returns their full member profile (ID, email, name, role, groups), re-read from Heartbeat so it cannot be forged.',
+ },
+ props: {},
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: heartbeatSamples.user,
+ outputSchema: heartbeatOutputSchemas.user,
+ async onEnable(context) {
+ await heartbeatWebhooks.enable({
+ token: context.auth.secret_text,
+ store: context.store,
+ webhookUrl: context.webhookUrl,
+ action: { name: 'USER_JOIN' },
+ });
+ },
+ async onDisable(context) {
+ await heartbeatWebhooks.disable({ token: context.auth.secret_text, store: context.store });
+ },
+ async test(context) {
+ const users = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token: context.auth.secret_text, method: HttpMethod.GET, path: '/users', operation: 'list members' }),
+ );
+ return [...users]
+ .sort((a, b) => String(b['createdAt'] ?? '').localeCompare(String(a['createdAt'] ?? '')))
+ .slice(0, 5);
+ },
+ async run(context) {
+ const userId = heartbeatWebhooks.uuidOrNull(heartbeatWebhooks.payloadOf(context.payload.body)['id']);
+ if (userId === null) {
+ return [];
+ }
+ const user = await heartbeatWebhooks.fetchOrNull(() => heartbeatUsers.getUser({ token: context.auth.secret_text, userId }));
+ if (user === null) {
+ return [];
+ }
+ if (!(await heartbeatWebhooks.isFirstDelivery({ store: context.store, key: `USER_JOIN:${userId}` }))) {
+ return [];
+ }
+ return [user];
+ },
+});
diff --git a/packages/pieces/community/heartbeat/src/lib/triggers/new-mention.ts b/packages/pieces/community/heartbeat/src/lib/triggers/new-mention.ts
new file mode 100644
index 00000000000..69d40d8b955
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/triggers/new-mention.ts
@@ -0,0 +1,131 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatWebhooks } from '../common/webhooks';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatSamples } from '../common/samples';
+
+export const newMentionTrigger = createTrigger({
+ auth: heartbeatAuth,
+ name: 'heartbeat_new_mention',
+ displayName: 'New Mention in Thread or Comment',
+ description: 'Fires when chosen members or groups are @mentioned in a thread or comment.',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Fires once when one of the chosen members or groups is @mentioned in a new thread or comment (optionally only in some channels). Returns which of the chosen members or groups were mentioned (read from the stored content, not the webhook), the author ID, and the thread and comment, re-read from Heartbeat.',
+ },
+ props: {
+ userIds: heartbeatProps.ids({ displayName: 'Mentioned User IDs', description: 'Fire when any of these members is mentioned. Use List Members to find IDs.', required: false }),
+ groupIds: heartbeatProps.ids({ displayName: 'Mentioned Group IDs', description: 'Fire when any of these groups is mentioned. Use List Groups to find IDs.', required: false }),
+ channelIds: heartbeatProps.ids({ displayName: 'Channel IDs', description: 'Only mentions in these channels. Leave empty for all channels.', required: false }),
+ },
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: heartbeatSamples.mention,
+ outputSchema: heartbeatOutputSchemas.mention,
+ async onEnable(context) {
+ const userIds = heartbeatApi.uuidList({ value: context.propsValue.userIds, label: 'Mentioned User IDs' });
+ const groupIds = heartbeatApi.uuidList({ value: context.propsValue.groupIds, label: 'Mentioned Group IDs' });
+ if (userIds.length === 0 && groupIds.length === 0) {
+ throw new Error('Add at least one Mentioned User ID or Mentioned Group ID.');
+ }
+ const channelIds = heartbeatApi.uuidList({ value: context.propsValue.channelIds, label: 'Channel IDs' });
+ await heartbeatWebhooks.enable({
+ token: context.auth.secret_text,
+ store: context.store,
+ webhookUrl: context.webhookUrl,
+ action: {
+ name: 'MENTION',
+ filter: {
+ userSelection: [
+ ...userIds.map((id) => ({ id, type: 'USER' })),
+ ...groupIds.map((id) => ({ id, type: 'GROUP' })),
+ ],
+ ...(channelIds.length > 0 ? { channelIDs: channelIds } : {}),
+ },
+ },
+ });
+ },
+ async onDisable(context) {
+ await heartbeatWebhooks.disable({ token: context.auth.secret_text, store: context.store });
+ },
+ async run(context) {
+ const payload = heartbeatWebhooks.payloadOf(context.payload.body);
+ const source = heartbeatApi.isRecord(payload['source']) ? payload['source'] : {};
+ const threadId = heartbeatWebhooks.uuidOrNull(source['threadID']);
+ if (threadId === null) {
+ return [];
+ }
+ const commentId = source['commentID'] === undefined || source['commentID'] === null ? null : heartbeatWebhooks.uuidOrNull(source['commentID']);
+ if (commentId === null && source['commentID'] !== undefined && source['commentID'] !== null) {
+ return [];
+ }
+ const thread = await heartbeatWebhooks.fetchOrNull(() =>
+ heartbeatApi.request<Record<string, unknown>>({ token: context.auth.secret_text, method: HttpMethod.GET, path: `/threads/${threadId}`, operation: 'get thread' }),
+ );
+ if (thread === null) {
+ return [];
+ }
+ const comment = commentId === null ? null : findComment({ thread, commentId });
+ if (commentId !== null && comment === null) {
+ return [];
+ }
+ const channelIds = heartbeatApi.uuidList({ value: context.propsValue.channelIds, label: 'Channel IDs' });
+ if (channelIds.length > 0 && !channelIds.includes(String(thread['channelID']))) {
+ return [];
+ }
+ const content = comment === null ? thread['content'] : comment['content'];
+ const mentionedTargets = matchTargets({
+ mentions: mentionsIn(typeof content === 'string' ? content : ''),
+ userIds: heartbeatApi.uuidList({ value: context.propsValue.userIds, label: 'Mentioned User IDs' }),
+ groupIds: heartbeatApi.uuidList({ value: context.propsValue.groupIds, label: 'Mentioned Group IDs' }),
+ });
+ if (mentionedTargets.length === 0) {
+ return [];
+ }
+ if (!(await heartbeatWebhooks.isFirstDelivery({ store: context.store, key: `MENTION:${commentId ?? threadId}` }))) {
+ return [];
+ }
+ return [
+ {
+ sourceType: commentId === null ? 'THREAD' : 'COMMENT',
+ mentionedUsers: mentionedTargets,
+ authorUserId: comment?.['userID'] ?? thread['userID'] ?? null,
+ channelId: thread['channelID'] ?? null,
+ threadId,
+ commentId,
+ content: comment?.['content'] ?? thread['content'] ?? null,
+ threadUrl: thread['url'] ?? null,
+ thread: Object.fromEntries(Object.entries(thread).filter(([key]) => key !== 'comments')),
+ comment,
+ },
+ ];
+ },
+});
+
+function mentionsIn(html: string): Mention[] {
+ const found = new Map<string, Mention>();
+ for (const match of html.matchAll(MENTION_REFERENCE)) {
+ const type = match[1].toUpperCase();
+ const id = match[2].toLowerCase();
+ found.set(`${type}:${id}`, { id, type });
+ }
+ return [...found.values()];
+}
+
+function matchTargets({ mentions, userIds, groupIds }: { mentions: Mention[]; userIds: string[]; groupIds: string[] }): Mention[] {
+ const users = new Set(userIds.map((id) => id.toLowerCase()));
+ const groups = new Set(groupIds.map((id) => id.toLowerCase()));
+ return mentions.filter((mention) => (mention.type === 'USER' ? users.has(mention.id) : groups.has(mention.id)));
+}
+
+const MENTION_REFERENCE = /data-id=["']mention\.([a-z]+)\.([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})["']/gi;
+
+type Mention = { id: string; type: string };
+
+function findComment({ thread, commentId }: { thread: Record<string, unknown>; commentId: string }): Record<string, unknown> | null {
+ const comments = heartbeatApi.recordList(thread['comments']);
+ const all = comments.flatMap((comment) => [comment, ...heartbeatApi.recordList(comment['children'])]);
+ return all.find((comment) => comment['id'] === commentId) ?? null;
+}
diff --git a/packages/pieces/community/heartbeat/src/lib/triggers/new-thread.ts b/packages/pieces/community/heartbeat/src/lib/triggers/new-thread.ts
new file mode 100644
index 00000000000..1ea401abceb
--- /dev/null
+++ b/packages/pieces/community/heartbeat/src/lib/triggers/new-thread.ts
@@ -0,0 +1,88 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Property, TriggerStrategy, createTrigger } from '@activepieces/pieces-framework';
+import { heartbeatAuth } from '../auth';
+import { heartbeatApi } from '../common/client';
+import { heartbeatProps } from '../common/props';
+import { heartbeatWebhooks } from '../common/webhooks';
+import { heartbeatOutputSchemas } from '../common/output-schemas';
+import { heartbeatSamples } from '../common/samples';
+
+export const newThreadTrigger = createTrigger({
+ auth: heartbeatAuth,
+ name: 'heartbeat_new_thread',
+ displayName: 'New Thread',
+ description: 'Fires when a new thread is posted, in any channel or one channel.',
+ classification: 'READ',
+ aiMetadata: {
+ description: 'Fires once when a thread is posted in a posts channel (any channel, or only the chosen one) and returns the thread with content, author ID, channel ID and link, re-read from Heartbeat.',
+ },
+ props: {
+ channelId: heartbeatProps.id({ displayName: 'Channel ID', description: 'Only threads in this posts channel. Leave empty for all channels. Use List Channels to find the ID.', required: false }),
+ includeMovedThreads: Property.Checkbox({
+ displayName: 'Include Threads Moved Into the Channel',
+ description: 'Also fire when an existing thread is moved into the chosen channel.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ type: TriggerStrategy.WEBHOOK,
+ sampleData: heartbeatSamples.thread,
+ outputSchema: heartbeatOutputSchemas.thread,
+ async onEnable(context) {
+ const channelId = heartbeatApi.optionalUuid({ value: context.propsValue.channelId, label: 'Channel ID' });
+ if (channelId === undefined && context.propsValue.includeMovedThreads === true) {
+ throw new Error('Include Threads Moved Into the Channel needs a Channel ID.');
+ }
+ await heartbeatWebhooks.enable({
+ token: context.auth.secret_text,
+ store: context.store,
+ webhookUrl: context.webhookUrl,
+ action: channelId === undefined
+ ? { name: 'THREAD_CREATE' }
+ : { name: 'THREAD_CREATE', filter: { channelID: channelId, triggerOnMove: context.propsValue.includeMovedThreads === true } },
+ });
+ },
+ async onDisable(context) {
+ await heartbeatWebhooks.disable({ token: context.auth.secret_text, store: context.store });
+ },
+ async test(context) {
+ const token = context.auth.secret_text;
+ const channelId = heartbeatApi.optionalUuid({ value: context.propsValue.channelId, label: 'Channel ID' });
+ const channelIds = channelId !== undefined
+ ? [channelId]
+ : heartbeatApi
+ .recordList(await heartbeatApi.request<unknown>({ token, method: HttpMethod.GET, path: '/channels', operation: 'list channels' }))
+ .filter((channel) => channel['type'] === 'POSTS' && typeof channel['id'] === 'string')
+ .map((channel) => String(channel['id']))
+ .slice(0, MAX_TEST_CHANNELS);
+ for (const id of channelIds) {
+ const threads = heartbeatApi.recordList(
+ await heartbeatApi.request<unknown>({ token, method: HttpMethod.GET, path: `/channels/${id}/threads`, operation: 'list threads', query: { limit: 5 } }),
+ );
+ if (threads.length > 0) {
+ return threads;
+ }
+ }
+ return [];
+ },
+ async run(context) {
+ const payload = heartbeatWebhooks.payloadOf(context.payload.body);
+ const threadId = heartbeatWebhooks.uuidOrNull(payload['id']);
+ if (threadId === null) {
+ return [];
+ }
+ const thread = await heartbeatWebhooks.fetchOrNull(() =>
+ heartbeatApi.request<Record<string, unknown>>({ token: context.auth.secret_text, method: HttpMethod.GET, path: `/threads/${threadId}`, operation: 'get thread' }),
+ );
+ if (thread === null) {
+ return [];
+ }
+ const key = `THREAD_CREATE:${threadId}:${String(thread['channelID'] ?? '')}`;
+ if (!(await heartbeatWebhooks.isFirstDelivery({ store: context.store, key }))) {
+ return [];
+ }
+ return [thread];
+ },
+});
+
+const MAX_TEST_CHANNELS = 10;
diff --git a/packages/pieces/community/heartbeat/test/auth-props.test.ts b/packages/pieces/community/heartbeat/test/auth-props.test.ts
new file mode 100644
index 00000000000..1186ae22ec9
--- /dev/null
+++ b/packages/pieces/community/heartbeat/test/auth-props.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { heartbeatAuth } from '../src/lib/auth';
+import { heartbeatProps } from '../src/lib/common/props';
+import { Heartbeat } from '../src/index';
+import { IDS, replies, runStep, stubFetch, TOKEN } from './helpers';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+type Validate = (params: { auth: string }) => Promise<{ valid: boolean; error?: string }>;
+type Options = (params: { auth?: { secret_text: string } }) => Promise<{ disabled: boolean; options: unknown[]; placeholder?: string }>;
+
+function validate(auth: string) {
+ const fn: Validate = Reflect.get(heartbeatAuth, 'validate');
+ return runStep(fn({ auth }));
+}
+
+function options({ prop, auth }: { prop: unknown; auth?: { secret_text: string } }) {
+ const fn: Options = Reflect.get(Object(prop), 'options');
+ return runStep(fn({ auth }));
+}
+
+describe('auth.validate', () => {
+ test('valid on GET /roles 200', async () => {
+ const seen = stubFetch(replies([{ body: [] }]));
+ expect(await validate(` ${TOKEN} `)).toEqual({ valid: true });
+ expect(seen[0].path).toBe('/roles');
+ expect(seen[0].auth).toBe(`Bearer ${TOKEN}`);
+ });
+ test('invalid with plan hint on 401', async () => {
+ stubFetch(replies([{ status: 401, body: { message: 'Unauthorized' } }]));
+ expect(await validate('bad')).toMatchObject({ valid: false, error: expect.stringContaining('Scale plan') });
+ });
+ test('other errors are reported with the vendor text, not as invalid key', async () => {
+ stubFetch(replies([{ status: 500, body: { message: 'boom' } }]));
+ const result = await validate('x');
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain('boom');
+ expect(result.error).not.toContain('Invalid API key');
+ });
+});
+
+describe('dropdowns', () => {
+ test('roles dropdown asks for a connection first', async () => {
+ expect(await options({ prop: heartbeatProps.roleDropdown })).toMatchObject({ disabled: true, placeholder: expect.stringContaining('connection') });
+ });
+ test('roles dropdown lists options', async () => {
+ stubFetch(replies([{ body: [{ id: IDS.role, name: 'User' }] }]));
+ expect(await options({ prop: heartbeatProps.roleDropdown, auth: { secret_text: TOKEN } })).toEqual({ disabled: false, options: [{ label: 'User', value: IDS.role }] });
+ });
+ test('groups dropdown shows a reason on 401 and 429', async () => {
+ stubFetch(replies([{ status: 401, body: {} }]));
+ expect(await options({ prop: heartbeatProps.groupsDropdown, auth: { secret_text: TOKEN } })).toMatchObject({ disabled: true, placeholder: expect.stringContaining('rejected') });
+ vi.unstubAllGlobals();
+ stubFetch(replies([{ status: 429, body: {} }]));
+ expect(await options({ prop: heartbeatProps.groupsDropdown, auth: { secret_text: TOKEN } })).toMatchObject({ disabled: true, placeholder: expect.stringContaining('rate limit') });
+ });
+});
+
+describe('piece metadata', () => {
+ test('description, version floor and every action tagged', () => {
+ expect(Heartbeat.description).not.toContain('Monitoring');
+ expect(Heartbeat.minimumSupportedRelease).toBe('0.88.2');
+ const actions = Object.values(Heartbeat.actions());
+ expect(actions).toHaveLength(46);
+ for (const action of actions) {
+ expect(action.audience, action.name).toBeDefined();
+ if (action.name !== 'custom_api_call') {
+ expect(action.classification, action.name).toBeDefined();
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ expect(action.name.startsWith('heartbeat_'), action.name).toBe(true);
+ }
+ }
+ const triggers = Object.values(Heartbeat.triggers());
+ expect(triggers).toHaveLength(5);
+ for (const trigger of triggers) {
+ expect(trigger.classification).toBe('READ');
+ expect(trigger.aiMetadata?.description).toBeTruthy();
+ expect(trigger.sampleData).toBeTruthy();
+ }
+ });
+});
diff --git a/packages/pieces/community/heartbeat/test/client.test.ts b/packages/pieces/community/heartbeat/test/client.test.ts
new file mode 100644
index 00000000000..370d399c301
--- /dev/null
+++ b/packages/pieces/community/heartbeat/test/client.test.ts
@@ -0,0 +1,129 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { HeartbeatApiError, heartbeatApi } from '../src/lib/common/client';
+import { heartbeatMessages } from '../src/lib/common/messages';
+import { IDS, replies, runStep, stubFetch, TOKEN } from './helpers';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('validators', () => {
+ test('uuid accepts and lower-cases a UUID', () => {
+ expect(heartbeatApi.uuid({ value: ` ${IDS.user.toUpperCase()} `, label: 'User ID' })).toBe(IDS.user);
+ });
+ test.each(['', 'abc', '../users', `${IDS.user}/x`, '//evil.io', undefined])('uuid rejects %p', (value) => {
+ expect(() => heartbeatApi.uuid({ value, label: 'User ID' })).toThrow(/User ID/);
+ });
+ test('optionalUuid returns undefined for blank', () => {
+ expect(heartbeatApi.optionalUuid({ value: ' ', label: 'X' })).toBeUndefined();
+ });
+ test('uuidList dedupes, accepts comma text and enforces bounds', () => {
+ expect(heartbeatApi.uuidList({ value: `${IDS.user},${IDS.user}\n${IDS.admin}`, label: 'IDs' })).toEqual([IDS.user, IDS.admin]);
+ expect(() => heartbeatApi.uuidList({ value: [], label: 'IDs', min: 1 })).toThrow(/at least one/);
+ expect(() => heartbeatApi.uuidList({ value: [{ a: 1 }], label: 'IDs' })).toThrow(/list of text/);
+ });
+ test('emailList validates, dedupes case-insensitively and caps at 100', () => {
+ expect(heartbeatApi.emailList({ value: ['[email protected]', '[email protected]', '[email protected]'], label: 'Emails' })).toEqual(['[email protected]', '[email protected]']);
+ expect(() => heartbeatApi.emailList({ value: ['nope'], label: 'Emails' })).toThrow(/not a valid email/);
+ const many = Array.from({ length: 101 }, (_, i) => `u${i}@x.io`);
+ expect(() => heartbeatApi.emailList({ value: many, label: 'Emails' })).toThrow(/at most 100/);
+ });
+ test('limit validates range and type', () => {
+ expect(heartbeatApi.limit({ value: undefined, max: 100, defaultValue: 20 })).toBe(20);
+ expect(heartbeatApi.limit({ value: '5', max: 100, defaultValue: 20 })).toBe(5);
+ expect(() => heartbeatApi.limit({ value: 0, max: 100, defaultValue: 20 })).toThrow();
+ expect(() => heartbeatApi.limit({ value: 2.5, max: 100, defaultValue: 20 })).toThrow();
+ expect(() => heartbeatApi.limit({ value: 101, max: 100, defaultValue: 20 })).toThrow();
+ });
+ test('isoDate normalises and rejects garbage', () => {
+ expect(heartbeatApi.isoDate({ value: '2026-10-13T15:00:00Z', label: 'Start' })).toBe('2026-10-13T15:00:00.000Z');
+ expect(heartbeatApi.isoDate({ value: '', label: 'Start' })).toBeUndefined();
+ expect(() => heartbeatApi.isoDate({ value: 'tomorrow-ish', label: 'Start' })).toThrow(/not a valid date/);
+ });
+ test('optionalUrl requires http(s)', () => {
+ expect(heartbeatApi.optionalUrl({ value: 'https://x.io/a', label: 'URL' })).toBe('https://x.io/a');
+ expect(() => heartbeatApi.optionalUrl({ value: 'javascript:alert(1)', label: 'URL' })).toThrow();
+ expect(() => heartbeatApi.optionalUrl({ value: 'linkedin.com/in/x', label: 'URL' })).toThrow();
+ });
+ test('triState maps yes/no/unchanged', () => {
+ expect(heartbeatApi.triState('yes')).toBe(true);
+ expect(heartbeatApi.triState('no')).toBe(false);
+ expect(heartbeatApi.triState('unchanged')).toBeUndefined();
+ });
+ test('toPage sets cursor only on a full page', () => {
+ expect(heartbeatApi.toPage({ items: [{ id: 'a' }, { id: 'b' }], pageLimit: 2 })).toEqual({ items: [{ id: 'a' }, { id: 'b' }], nextCursor: 'b', hasMore: true });
+ expect(heartbeatApi.toPage({ items: [{ id: 'a' }], pageLimit: 2 })).toEqual({ items: [{ id: 'a' }], nextCursor: null, hasMore: false });
+ });
+});
+
+describe('request', () => {
+ test('sends bearer auth to the v0 base URL with JSON body', async () => {
+ const seen = stubFetch(replies([{ body: { ok: true } }]));
+ await runStep(heartbeatApi.request({ token: ` ${TOKEN} `, method: HttpMethod.PUT, path: '/groups', operation: 'x', body: { name: 'A' } }));
+ expect(seen[0].url).toBe('https://api.heartbeat.chat/v0/groups');
+ expect(seen[0].auth).toBe(`Bearer ${TOKEN}`);
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].body).toEqual({ name: 'A' });
+ });
+ test('drops empty query values', async () => {
+ const seen = stubFetch(replies([{ body: [] }]));
+ await runStep(heartbeatApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/events', operation: 'x', query: { groupID: undefined, limit: 5 } }));
+ expect(seen[0].query.has('groupID')).toBe(false);
+ expect(seen[0].query.get('limit')).toBe('5');
+ });
+ test('retries 429 twice then succeeds', async () => {
+ const seen = stubFetch(replies([{ status: 429, body: { message: 'slow' } }, { status: 429 }, { body: [1] }]));
+ await expect(runStep(heartbeatApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/roles', operation: 'list roles' }))).resolves.toEqual([1]);
+ expect(seen).toHaveLength(3);
+ });
+ test('gives up after two 429 retries', async () => {
+ const seen = stubFetch(replies([{ status: 429, body: { message: 'slow down' } }]));
+ await expect(runStep(heartbeatApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/roles', operation: 'list roles' }))).rejects.toThrow(/rate limit/);
+ expect(seen).toHaveLength(3);
+ });
+ test('wraps errors with status, vendor message and responseBody', async () => {
+ stubFetch(replies([{ status: 400, body: { code: 'VALIDATION_ERROR', message: 'User already exists in community', type: 'ValidationError' } }]));
+ const error = await runStep(heartbeatApi.request({ token: TOKEN, method: HttpMethod.PUT, path: '/users', operation: 'create member' })).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(HeartbeatApiError);
+ expect(String(error)).toContain('Heartbeat create member failed (400): User already exists in community');
+ expect(Reflect.get(Object(error), 'responseBody')).toEqual({ code: 'VALIDATION_ERROR', message: 'User already exists in community', type: 'ValidationError' });
+ expect(Reflect.get(Object(error), 'body')).toBeUndefined();
+ expect(heartbeatApi.statusOf(error)).toBe(400);
+ expect(heartbeatApi.errorMessageOf(error)).toBe('User already exists in community');
+ });
+ test('truncates long vendor text to 500 chars', async () => {
+ stubFetch(replies([{ status: 500, text: 'x'.repeat(2000) }]));
+ const error = await runStep(heartbeatApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/roles', operation: 'list roles' })).catch((e: unknown) => e);
+ expect(String(error).length).toBeLessThan(600);
+ });
+ test('401 explains the plan gate', async () => {
+ stubFetch(replies([{ status: 401, body: { message: 'Unauthorized' } }]));
+ await expect(runStep(heartbeatApi.request({ token: TOKEN, method: HttpMethod.GET, path: '/roles', operation: 'list roles' }))).rejects.toThrow(/plan does not include API access/);
+ });
+ test('204 resolves without a body', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(null, { status: 204 })));
+ await expect(runStep(heartbeatApi.request({ token: TOKEN, method: HttpMethod.PUT, path: '/directMessages', operation: 'send' }))).resolves.toBeFalsy();
+ });
+});
+
+describe('messages.findSentMessage', () => {
+ const sentAfter = Date.parse('2026-10-06T12:10:00Z');
+ test('matches by plain text and sender, newest first', () => {
+ const messages = [
+ { id: 'old', userID: IDS.admin, content: '<p>Hi</p>', createdAt: '2026-10-06T12:10:01Z' },
+ { id: 'new', userID: IDS.admin, content: '<p>Hi</p>', createdAt: '2026-10-06T12:10:05Z' },
+ { id: 'other', userID: IDS.user, content: '<p>Hi</p>', createdAt: '2026-10-06T12:10:06Z' },
+ ];
+ expect(heartbeatMessages.findSentMessage({ messages, text: 'Hi', senderId: IDS.admin, sentAfter })?.['id']).toBe('new');
+ });
+ test('ignores messages older than the send time', () => {
+ const messages = [{ id: 'stale', userID: IDS.admin, content: 'Hi', createdAt: '2026-10-05T00:00:00Z' }];
+ expect(heartbeatMessages.findSentMessage({ messages, text: 'Hi', senderId: undefined, sentAfter })).toBeNull();
+ });
+});
diff --git a/packages/pieces/community/heartbeat/test/content.test.ts b/packages/pieces/community/heartbeat/test/content.test.ts
new file mode 100644
index 00000000000..e2d132b84dc
--- /dev/null
+++ b/packages/pieces/community/heartbeat/test/content.test.ts
@@ -0,0 +1,224 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { listChannelThreadsAction } from '../src/lib/actions/list-channel-threads';
+import { getThreadAction } from '../src/lib/actions/get-thread';
+import { createThreadAction } from '../src/lib/actions/create-thread';
+import { createCommentAction } from '../src/lib/actions/create-comment';
+import { sendChatMessageAction } from '../src/lib/actions/send-chat-message';
+import { listChatMessagesAction } from '../src/lib/actions/list-chat-messages';
+import { sendDirectMessageAction } from '../src/lib/actions/send-direct-message';
+import { getOrCreateDirectChatAction } from '../src/lib/actions/get-or-create-direct-chat';
+import { listDirectMessagesAction } from '../src/lib/actions/list-direct-messages';
+import { listEventsAction } from '../src/lib/actions/list-events';
+import { getEventAction } from '../src/lib/actions/get-event';
+import { getEventAttendanceAction } from '../src/lib/actions/get-event-attendance';
+import { createEventAction } from '../src/lib/actions/create-event';
+import { listInvitationsAction } from '../src/lib/actions/list-invitations';
+import { createInvitationLinkAction } from '../src/lib/actions/create-invitation-link';
+import { addEmailsToInvitationAction } from '../src/lib/actions/add-emails-to-invitation';
+import { listCoursesAction } from '../src/lib/actions/list-courses';
+import { getLessonAction } from '../src/lib/actions/get-lesson';
+import { listDocumentsAction } from '../src/lib/actions/list-documents';
+import { getDocumentAction } from '../src/lib/actions/get-document';
+import { IDS, replies, run, stubFetch } from './helpers';
+
+const thread = { id: IDS.thread, channelID: IDS.channel, userID: IDS.admin, content: '<p>x</p>', comments: [{ id: IDS.comment, children: [] }] };
+const event = { id: IDS.event, name: 'AP-TEST event', startTime: '2026-10-13T15:00:00.000Z' };
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-06T12:00:00Z'));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('threads', () => {
+ test('list threads pages and strips comments by default', async () => {
+ const seen = stubFetch(replies([{ body: [thread, { ...thread, id: 'b' }] }]));
+ const result = await run({ action: listChannelThreadsAction, propsValue: { channelId: IDS.channel, limit: 2, startingAfter: IDS.comment } });
+ expect(seen[0].path).toBe(`/channels/${IDS.channel}/threads`);
+ expect(seen[0].query.get('startingAfter')).toBe(IDS.comment);
+ expect(result).toMatchObject({ nextCursor: 'b', hasMore: true, threads: [{ commentCount: 1 }, {}] });
+ expect(result).not.toHaveProperty('threads.0.comments');
+ });
+ test('list threads can include comments', async () => {
+ stubFetch(replies([{ body: [thread] }]));
+ expect(await run({ action: listChannelThreadsAction, propsValue: { channelId: IDS.channel, includeComments: true } })).toMatchObject({ threads: [{ comments: thread.comments }], hasMore: false, nextCursor: null });
+ });
+ test('get thread', async () => {
+ const seen = stubFetch(replies([{ body: thread }]));
+ expect(await run({ action: getThreadAction, propsValue: { threadId: IDS.thread } })).toEqual(thread);
+ expect(seen[0].path).toBe(`/threads/${IDS.thread}`);
+ });
+ test('create thread wraps plain text in paragraphs', async () => {
+ const seen = stubFetch(replies([{ body: thread }]));
+ await run({ action: createThreadAction, propsValue: { channelId: IDS.channel, text: 'Hello @x\nSecond <b>bold</b>', authorUserId: IDS.admin, createdAt: '2026-01-01T00:00:00Z' } });
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].path).toBe('/threads');
+ expect(seen[0].body).toEqual({ text: '<p>Hello @x</p><p>Second <b>bold</b></p>', channelID: IDS.channel, userID: IDS.admin, createdAt: '2026-01-01T00:00:00.000Z' });
+ });
+ test('create thread keeps block HTML as is', async () => {
+ const seen = stubFetch(replies([{ body: thread }]));
+ await run({ action: createThreadAction, propsValue: { channelId: IDS.channel, text: '<h1>T</h1><p>x</p>' } });
+ expect(seen[0].body).toEqual({ text: '<h1>T</h1><p>x</p>', channelID: IDS.channel });
+ });
+ test('create comment sends parentCommentID null by default', async () => {
+ const seen = stubFetch(replies([{ body: { id: IDS.comment } }]));
+ expect(await run({ action: createCommentAction, propsValue: { threadId: IDS.thread, text: '<p>hi</p>' } })).toEqual({ id: IDS.comment, threadId: IDS.thread, parentCommentId: null });
+ expect(seen[0].body).toEqual({ text: '<p>hi</p>', threadID: IDS.thread, parentCommentID: null });
+ });
+ test('create reply passes the parent comment', async () => {
+ const seen = stubFetch(replies([{ body: { id: 'r' } }]));
+ await run({ action: createCommentAction, propsValue: { threadId: IDS.thread, text: '<p>hi</p>', parentCommentId: IDS.comment } });
+ expect(seen[0].body).toMatchObject({ parentCommentID: IDS.comment });
+ });
+});
+
+describe('chat', () => {
+ test('send chat message handles 204 and matches the new message', async () => {
+ const seen = stubFetch((request) =>
+ request.method === 'PUT'
+ ? { status: 204, text: '' }
+ : { body: { data: [{ id: 'm1', userID: IDS.admin, content: '<p>Hi</p>', createdAt: '2026-10-06T12:00:01Z' }], hasMore: false } },
+ );
+ const result = await run({ action: sendChatMessageAction, propsValue: { channelId: IDS.channel, text: 'Hi', fromUserId: IDS.admin } });
+ expect(seen[0].path).toBe(`/chatChannel/${IDS.channel}/message`);
+ expect(seen[0].body).toEqual({ text: '<p>Hi</p>', from: IDS.admin });
+ expect(seen[1].query.get('limit')).toBe('10');
+ expect(result).toMatchObject({ sent: true, messageId: 'm1' });
+ });
+ test('send chat message stays successful when the read-back fails', async () => {
+ const seen = stubFetch(replies([{ status: 204, text: '' }, { status: 503, body: { message: 'unavailable' } }]));
+ const result = await run({ action: sendChatMessageAction, propsValue: { channelId: IDS.channel, text: 'Hi' } });
+ expect(seen.filter((request) => request.method === 'PUT')).toHaveLength(1);
+ expect(result).toMatchObject({ sent: true, messageId: null, message: null, lookupError: expect.stringMatching(/unavailable/) });
+ });
+ test('send chat message returns null ID when no match', async () => {
+ stubFetch((request) => (request.method === 'PUT' ? { status: 204, text: '' } : { body: { data: [], hasMore: false } }));
+ expect(await run({ action: sendChatMessageAction, propsValue: { channelId: IDS.channel, text: 'Hi' } })).toMatchObject({ sent: true, messageId: null, message: null });
+ });
+ test('list chat messages uses vendor hasMore', async () => {
+ stubFetch(replies([{ body: { data: [{ id: 'm1' }, { id: 'm2' }], hasMore: true } }]));
+ expect(await run({ action: listChatMessagesAction, propsValue: { channelId: IDS.channel, limit: 2 } })).toEqual({ messages: [{ id: 'm1' }, { id: 'm2' }], nextCursor: 'm2', hasMore: true });
+ });
+});
+
+describe('direct messages', () => {
+ test('send without sender returns no chat info', async () => {
+ const seen = stubFetch(replies([{ status: 204, text: '' }]));
+ expect(await run({ action: sendDirectMessageAction, propsValue: { toUserId: IDS.user, text: 'Hi' } })).toEqual({ to: IDS.user, from: null, sent: true, chatId: null, chatUrl: null, messageId: null, lookupError: null });
+ expect(seen[0].body).toEqual({ text: '<p>Hi</p>', to: IDS.user });
+ expect(seen).toHaveLength(1);
+ });
+ test('send with sender looks up chat and message', async () => {
+ const seen = stubFetch(replies([
+ { status: 204, text: '' },
+ { body: { chatID: IDS.chat, url: 'https://app.heartbeat.chat/x/c/1' } },
+ { body: [{ id: IDS.message, userID: IDS.admin, content: '<p>Hi</p>', createdAt: '2026-10-06T12:00:02Z' }] },
+ ]));
+ const result = await run({ action: sendDirectMessageAction, propsValue: { toUserId: IDS.user, text: 'Hi', fromUserId: IDS.admin } });
+ expect(seen[1].body).toEqual({ userID1: IDS.admin, userID2: IDS.user });
+ expect(seen[2].path).toBe(`/directMessages/${IDS.chat}`);
+ expect(result).toEqual({ to: IDS.user, from: IDS.admin, sent: true, chatId: IDS.chat, chatUrl: 'https://app.heartbeat.chat/x/c/1', messageId: IDS.message, lookupError: null });
+ });
+ test('send with sender stays successful when the chat lookup fails', async () => {
+ stubFetch(replies([{ status: 204, text: '' }, { status: 500, body: { message: 'down' } }]));
+ const result = await run({ action: sendDirectMessageAction, propsValue: { toUserId: IDS.user, text: 'Hi', fromUserId: IDS.admin } });
+ expect(result).toMatchObject({ sent: true, chatId: null, messageId: null, lookupError: expect.stringMatching(/Do not re-run/) });
+ });
+ test('send refuses same sender and recipient', async () => {
+ stubFetch(replies([{ body: {} }]));
+ await expect(run({ action: sendDirectMessageAction, propsValue: { toUserId: IDS.user, text: 'Hi', fromUserId: IDS.user } })).rejects.toThrow(/different/);
+ });
+ test('get direct chat PUTs /directChats', async () => {
+ const seen = stubFetch(replies([{ body: { chatID: IDS.chat, url: 'u' } }]));
+ expect(await run({ action: getOrCreateDirectChatAction, propsValue: { userId1: IDS.admin, userId2: IDS.user } })).toEqual({ chatID: IDS.chat, url: 'u' });
+ expect(seen[0].method).toBe('PUT');
+ });
+ test('list direct messages', async () => {
+ stubFetch(replies([{ body: [{ id: IDS.message }] }]));
+ expect(await run({ action: listDirectMessagesAction, propsValue: { chatId: IDS.chat } })).toEqual({ chatId: IDS.chat, messages: [{ id: IDS.message }], count: 1 });
+ });
+});
+
+describe('events', () => {
+ test('list events filters by time window and limit', async () => {
+ const seen = stubFetch(replies([{ body: [event, { ...event, id: 'old', startTime: '2026-01-01T00:00:00Z' }, { ...event, id: 'late', startTime: '2026-12-01T00:00:00Z' }] }]));
+ const result = await run({ action: listEventsAction, propsValue: { groupId: IDS.group, startsAfter: '2026-10-01T00:00:00Z', startsBefore: '2026-11-01T00:00:00Z' } });
+ expect(seen[0].query.get('groupID')).toBe(IDS.group);
+ expect(result).toEqual({ events: [event], count: 1, totalMatching: 1, truncated: false });
+ });
+ test('list events rejects an inverted window', async () => {
+ stubFetch(replies([{ body: [] }]));
+ await expect(run({ action: listEventsAction, propsValue: { startsAfter: '2026-11-01T00:00:00Z', startsBefore: '2026-10-01T00:00:00Z' } })).rejects.toThrow(/earlier/);
+ });
+ test('get event with occurrences', async () => {
+ const seen = stubFetch(replies([{ body: event }, { body: [{ startTime: 'a', endTime: 'b' }] }]));
+ expect(await run({ action: getEventAction, propsValue: { eventId: IDS.event, includeInstances: true } })).toEqual({ ...event, instances: [{ startTime: 'a', endTime: 'b' }] });
+ expect(seen[1].path).toBe(`/events/${IDS.event}/instances`);
+ });
+ test('attendance normalises a single attendee object to a list', async () => {
+ stubFetch(replies([{ body: [{ startTime: 'a', endTime: 'b', attendees: { id: IDS.user, name: 'A', isUser: true } }] }]));
+ expect(await run({ action: getEventAttendanceAction, propsValue: { eventId: IDS.event } })).toEqual({ eventId: IDS.event, happened: true, instances: [{ startTime: 'a', endTime: 'b', attendees: [{ id: IDS.user, name: 'A', isUser: true }] }] });
+ });
+ test('attendance maps 422 not-happened to happened=false', async () => {
+ stubFetch(replies([{ status: 422, body: { error: true, message: 'Event has not happened yet' } }]));
+ expect(await run({ action: getEventAttendanceAction, propsValue: { eventId: IDS.event } })).toEqual({ eventId: IDS.event, happened: false, instances: [] });
+ });
+ test('create event sends description "" and re-reads the event', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, event: { id: IDS.event, location: { type: 'CUSTOM', locationStr: 'Room' } } } }, { body: event }]));
+ const result = await run({ action: createEventAction, propsValue: { name: 'E', startTime: '2026-10-13T15:00:00Z', durationMinutes: 30, location: 'CUSTOM', customLocation: 'Room', invitedEmails: ['[email protected]'] } });
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].body).toEqual({ name: 'E', description: '', startTime: '2026-10-13T15:00:00.000Z', duration: 30, location: 'Room', invitedUsers: ['[email protected]'] });
+ expect(result).toEqual({ ...event, location: { type: 'CUSTOM', locationStr: 'Room' }, lookupError: null });
+ });
+ test('create event keeps the new ID when the read-back fails', async () => {
+ stubFetch(replies([{ body: { success: true, event: { id: IDS.event, location: { type: 'HEARTBEAT' } } } }, { status: 500, body: { message: 'down' } }]));
+ const result = await run({ action: createEventAction, propsValue: { name: 'E', startTime: '2026-10-13T15:00:00Z', durationMinutes: 30, location: 'HEARTBEAT' } });
+ expect(result).toMatchObject({ id: IDS.event, location: { type: 'HEARTBEAT' }, lookupError: expect.stringMatching(/saved in Heartbeat/) });
+ });
+ test('create event validates duration and custom location', async () => {
+ stubFetch(replies([{ body: {} }]));
+ await expect(run({ action: createEventAction, propsValue: { name: 'E', startTime: '2026-10-13T15:00:00Z', durationMinutes: 0, location: 'HEARTBEAT' } })).rejects.toThrow(/Duration/);
+ await expect(run({ action: createEventAction, propsValue: { name: 'E', startTime: '2026-10-13T15:00:00Z', durationMinutes: 30, location: 'CUSTOM' } })).rejects.toThrow(/Custom Location/);
+ });
+});
+
+describe('invitations, courses, documents', () => {
+ test('list invitations', async () => {
+ stubFetch(replies([{ body: [{ id: IDS.invitation, code: 'ABC123' }] }]));
+ expect(await run({ action: listInvitationsAction, propsValue: {} })).toEqual({ invitations: [{ id: IDS.invitation, code: 'ABC123' }], count: 1 });
+ });
+ test('create invitation link sends groupIDs [] when none', async () => {
+ const seen = stubFetch(replies([{ body: { id: IDS.invitation, code: 'ABC123' } }]));
+ await run({ action: createInvitationLinkAction, propsValue: { roleId: IDS.role } });
+ expect(seen[0].body).toEqual({ roleID: IDS.role, groupIDs: [] });
+ });
+ test('add emails requires an explicit send choice', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }]));
+ await expect(run({ action: addEmailsToInvitationAction, propsValue: { invitationId: IDS.invitation, emails: ['[email protected]'] } })).rejects.toThrow(/yes or no/);
+ expect(await run({ action: addEmailsToInvitationAction, propsValue: { invitationId: IDS.invitation, emails: ['[email protected]'], sendEmail: 'no' } })).toEqual({ invitationId: IDS.invitation, emails: ['[email protected]'], emailSent: false });
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].body).toEqual({ emails: ['[email protected]'], shouldSendEmail: false });
+ });
+ test('list courses', async () => {
+ stubFetch(replies([{ body: [] }]));
+ expect(await run({ action: listCoursesAction, propsValue: {} })).toEqual({ courses: [], count: 0 });
+ });
+ test('get lesson surfaces 404', async () => {
+ stubFetch(replies([{ status: 404, body: { message: 'Could not find data' } }]));
+ await expect(run({ action: getLessonAction, propsValue: { lessonId: IDS.lesson } })).rejects.toThrow(/404/);
+ });
+ test('list documents pages', async () => {
+ const seen = stubFetch(replies([{ body: [{ id: IDS.document, name: 'Doc' }] }]));
+ expect(await run({ action: listDocumentsAction, propsValue: { limit: 1 } })).toEqual({ documents: [{ id: IDS.document, name: 'Doc' }], nextCursor: IDS.document, hasMore: true });
+ expect(seen[0].query.get('limit')).toBe('1');
+ });
+ test('get document', async () => {
+ const seen = stubFetch(replies([{ body: { id: IDS.document, content: '# x' } }]));
+ expect(await run({ action: getDocumentAction, propsValue: { documentId: IDS.document } })).toEqual({ id: IDS.document, content: '# x' });
+ expect(seen[0].path).toBe(`/documents/${IDS.document}`);
+ });
+});
diff --git a/packages/pieces/community/heartbeat/test/groups-channels.test.ts b/packages/pieces/community/heartbeat/test/groups-channels.test.ts
new file mode 100644
index 00000000000..882f6853b87
--- /dev/null
+++ b/packages/pieces/community/heartbeat/test/groups-channels.test.ts
@@ -0,0 +1,179 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { listRolesAction } from '../src/lib/actions/list-roles';
+import { listGroupsAction } from '../src/lib/actions/list-groups';
+import { getGroupAction } from '../src/lib/actions/get-group';
+import { createGroupAction } from '../src/lib/actions/create-group';
+import { updateGroupAction } from '../src/lib/actions/update-group';
+import { deleteGroupAction } from '../src/lib/actions/delete-group';
+import { addUsersToGroupAction } from '../src/lib/actions/add-users-to-group';
+import { removeUsersFromGroupAction } from '../src/lib/actions/remove-users-from-group';
+import { listChannelsAction } from '../src/lib/actions/list-channels';
+import { listChannelCategoriesAction } from '../src/lib/actions/list-channel-categories';
+import { createChannelCategoryAction } from '../src/lib/actions/create-channel-category';
+import { createChannelAction } from '../src/lib/actions/create-channel';
+import { updateChannelAction } from '../src/lib/actions/update-channel';
+import { deleteChannelAction } from '../src/lib/actions/delete-channel';
+import { IDS, replies, run, stubFetch } from './helpers';
+
+const group = { id: IDS.group, name: 'AP-TEST group', archived: false, parentGroupID: null, users: [{ id: IDS.user, name: 'A', email: '[email protected]' }] };
+const channels = [
+ { id: IDS.channel, name: 'AP-TEST posts', emoji: 'x', type: 'POSTS' },
+ { id: IDS.thread, name: 'AP-TEST chat', emoji: 'y', type: 'CHAT' },
+];
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('roles and groups', () => {
+ test('list roles wraps the array', async () => {
+ stubFetch(replies([{ body: [{ id: IDS.role, name: 'User' }] }]));
+ expect(await run({ action: listRolesAction, propsValue: {} })).toEqual({ roles: [{ id: IDS.role, name: 'User' }], count: 1 });
+ });
+ test('list groups hides archived and members by default', async () => {
+ stubFetch(replies([{ body: [group, { ...group, id: 'g2', archived: true }] }]));
+ expect(await run({ action: listGroupsAction, propsValue: {} })).toEqual({ groups: [{ id: IDS.group, name: 'AP-TEST group', archived: false, parentGroupID: null }], count: 1 });
+ });
+ test('list groups can include archived and members', async () => {
+ stubFetch(replies([{ body: [group, { ...group, id: 'g2', archived: true }] }]));
+ expect(await run({ action: listGroupsAction, propsValue: { includeArchived: true, includeMembers: true } })).toMatchObject({ count: 2, groups: [{ users: group.users }, {}] });
+ });
+ test('get group reads /groups/{id}', async () => {
+ const seen = stubFetch(replies([{ body: group }]));
+ expect(await run({ action: getGroupAction, propsValue: { groupId: IDS.group } })).toEqual(group);
+ expect(seen[0].path).toBe(`/groups/${IDS.group}`);
+ });
+ test('create group PUTs and re-reads by the returned groupID', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, groupID: IDS.group } }, { body: group }]));
+ expect(await run({ action: createGroupAction, propsValue: { name: 'AP-TEST group', memberEmails: ['[email protected]'], parentGroupId: IDS.admin } })).toEqual({ ...group, lookupError: null });
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].body).toEqual({ name: 'AP-TEST group', members: ['[email protected]'], parentGroupID: IDS.admin });
+ });
+ test('create group keeps the new ID when the read-back fails', async () => {
+ stubFetch(replies([{ body: { success: true, groupID: IDS.group } }, { status: 500, body: { message: 'down' } }]));
+ const result = await run({ action: createGroupAction, propsValue: { name: 'AP-TEST group' } });
+ expect(result).toMatchObject({ id: IDS.group, name: 'AP-TEST group', lookupError: expect.stringMatching(/Do not re-run/) });
+ });
+ test('create group fails loudly without an ID', async () => {
+ stubFetch(replies([{ body: { success: true } }]));
+ await expect(run({ action: createGroupAction, propsValue: { name: 'X' } })).rejects.toThrow(/did not return its ID/);
+ });
+ test('update group sends only set fields and refuses no-op', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }, { body: group }]));
+ expect(await run({ action: updateGroupAction, propsValue: { groupId: IDS.group, name: 'New', isIsolated: 'unchanged', isJoinable: 'no' } })).toMatchObject({ updated: true, updatedFields: ['name', 'isJoinable'] });
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].body).toEqual({ name: 'New', isJoinable: false });
+ await expect(run({ action: updateGroupAction, propsValue: { groupId: IDS.group, isIsolated: 'unchanged' } })).rejects.toThrow(/Nothing to update/);
+ });
+ test('delete group maps 404 to alreadyDeleted and rethrows 400 with reason', async () => {
+ stubFetch(replies([{ status: 404, body: { error: true, message: 'Could not find group' } }]));
+ expect(await run({ action: deleteGroupAction, propsValue: { groupId: IDS.group } })).toEqual({ id: IDS.group, deleted: true, alreadyDeleted: true });
+ vi.unstubAllGlobals();
+ stubFetch(replies([{ status: 400, body: { message: 'Group has child groups' } }]));
+ await expect(run({ action: deleteGroupAction, propsValue: { groupId: IDS.group } })).rejects.toThrow(/Group has child groups/);
+ });
+ test('delete group success', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }]));
+ expect(await run({ action: deleteGroupAction, propsValue: { groupId: IDS.group } })).toEqual({ id: IDS.group, deleted: true, alreadyDeleted: false });
+ expect(seen[0].method).toBe('DELETE');
+ });
+ test('add members lists emails as unverified when the group read-back fails', async () => {
+ stubFetch(replies([{ status: 204, text: '' }, { status: 500, body: { message: 'down' } }]));
+ const result = await run({ action: addUsersToGroupAction, propsValue: { groupId: IDS.group, emails: ['[email protected]'] } });
+ expect(result).toMatchObject({ added: [], notAdded: [], unverified: ['[email protected]'], lookupError: expect.stringMatching(/saved in Heartbeat/) });
+ });
+ test('update group stays successful when the read-back fails', async () => {
+ stubFetch(replies([{ status: 204, text: '' }, { status: 500, body: { message: 'down' } }]));
+ const result = await run({ action: updateGroupAction, propsValue: { groupId: IDS.group, name: 'New' } });
+ expect(result).toMatchObject({ id: IDS.group, updated: true, group: null, lookupError: expect.stringMatching(/saved in Heartbeat/) });
+ });
+ test('add members PUTs memberships and reports ignored emails', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }, { body: group }]));
+ const result = await run({ action: addUsersToGroupAction, propsValue: { groupId: IDS.group, emails: ['[email protected]', '[email protected]'], removeFromSiblingGroups: true } });
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].path).toBe(`/groups/${IDS.group}/memberships`);
+ expect(seen[0].body).toEqual({ emails: ['[email protected]', '[email protected]'], shouldRemoveFromSiblingGroups: true });
+ expect(result).toMatchObject({ added: ['[email protected]'], notAdded: ['[email protected]'] });
+ });
+ test('remove members sends DELETE memberships', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }]));
+ expect(await run({ action: removeUsersFromGroupAction, propsValue: { groupId: IDS.group, emails: ['[email protected]'] } })).toEqual({ groupId: IDS.group, emails: ['[email protected]'], removed: true });
+ expect(seen[0].method).toBe('DELETE');
+ expect(seen[0].body).toEqual({ emails: ['[email protected]'] });
+ });
+ test('membership actions refuse empty email lists', async () => {
+ stubFetch(replies([{ body: {} }]));
+ await expect(run({ action: removeUsersFromGroupAction, propsValue: { groupId: IDS.group, emails: [] } })).rejects.toThrow(/at least one/);
+ });
+});
+
+describe('channels', () => {
+ test('list channels filters by type', async () => {
+ stubFetch(replies([{ body: channels }]));
+ expect(await run({ action: listChannelsAction, propsValue: { type: 'CHAT' } })).toEqual({ channels: [channels[1]], count: 1 });
+ });
+ test('list channels rejects an unknown type', async () => {
+ stubFetch(replies([{ body: channels }]));
+ await expect(run({ action: listChannelsAction, propsValue: { type: 'VIDEO' } })).rejects.toThrow(/Type must be/);
+ });
+ test('list categories', async () => {
+ stubFetch(replies([{ body: [{ id: IDS.category, name: 'Everyone' }] }]));
+ expect(await run({ action: listChannelCategoriesAction, propsValue: {} })).toEqual({ categories: [{ id: IDS.category, name: 'Everyone' }], count: 1 });
+ });
+ test('create category PUTs name', async () => {
+ const seen = stubFetch(replies([{ body: { id: IDS.category, name: 'C' } }]));
+ expect(await run({ action: createChannelCategoryAction, propsValue: { name: 'C' } })).toEqual({ id: IDS.category, name: 'C' });
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].body).toEqual({ name: 'C' });
+ });
+ test('create channel maps visibility and re-reads the channel', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, channelID: IDS.channel } }, { body: channels }]));
+ const result = await run({ action: createChannelAction, propsValue: { name: 'AP-TEST posts', channelCategoryId: IDS.category, channelType: 'POSTS', visibility: 'private', invitedEmails: ['[email protected]'], isReadOnly: true } });
+ expect(seen[0].body).toEqual({ name: 'AP-TEST posts', isPrivate: true, channelCategoryID: IDS.category, channelType: 'POSTS', invitedUsers: ['[email protected]'], isReadOnly: true });
+ expect(result).toEqual({ ...channels[0], lookupError: null });
+ });
+ test('create channel keeps the new ID when the read-back fails', async () => {
+ stubFetch(replies([{ body: { success: true, channelID: IDS.channel } }, { status: 500, body: { message: 'down' } }]));
+ const result = await run({ action: createChannelAction, propsValue: { name: 'AP-TEST posts', channelCategoryId: IDS.category, channelType: 'POSTS', visibility: 'public' } });
+ expect(result).toMatchObject({ id: IDS.channel, name: 'AP-TEST posts', type: 'POSTS', lookupError: expect.stringMatching(/saved in Heartbeat/) });
+ });
+ test('create channel requires an explicit visibility and refuses read-only chat', async () => {
+ stubFetch(replies([{ body: {} }]));
+ await expect(run({ action: createChannelAction, propsValue: { name: 'x', channelCategoryId: IDS.category, channelType: 'POSTS' } })).rejects.toThrow(/Visibility/);
+ await expect(run({ action: createChannelAction, propsValue: { name: 'x', channelCategoryId: IDS.category, channelType: 'CHAT', visibility: 'public', isReadOnly: true } })).rejects.toThrow(/chat channels/);
+ });
+ test('update channel: public sends restrictedTo null', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }, { body: channels }]));
+ await run({ action: updateChannelAction, propsValue: { channelId: IDS.channel, access: 'public' } });
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].path).toBe(`/channels/${IDS.channel}`);
+ expect(seen[0].body).toEqual({ restrictedTo: null });
+ });
+ test('update channel: restricted sends lists, unchanged omits restrictedTo', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }, { body: channels }]));
+ await run({ action: updateChannelAction, propsValue: { channelId: IDS.channel, access: 'restricted', invitedGroupIds: [IDS.group] } });
+ expect(seen[0].body).toEqual({ restrictedTo: { invitedUsers: [], invitedGroups: [IDS.group] } });
+ await run({ action: updateChannelAction, propsValue: { channelId: IDS.channel, name: 'N' } });
+ expect(seen[2].body).toEqual({ name: 'N' });
+ });
+ test('update channel validation', async () => {
+ stubFetch(replies([{ body: {} }]));
+ await expect(run({ action: updateChannelAction, propsValue: { channelId: IDS.channel } })).rejects.toThrow(/Nothing to update/);
+ await expect(run({ action: updateChannelAction, propsValue: { channelId: IDS.channel, access: 'restricted' } })).rejects.toThrow(/at least one/);
+ await expect(run({ action: updateChannelAction, propsValue: { channelId: IDS.channel, invitedEmails: ['[email protected]'] } })).rejects.toThrow(/only used when Access is Restricted/);
+ });
+ test('delete channel maps 404 to alreadyDeleted', async () => {
+ stubFetch(replies([{ status: 404, body: { code: 'NOT_FOUND_ERROR', message: 'Could not find channel' } }]));
+ expect(await run({ action: deleteChannelAction, propsValue: { channelId: IDS.channel } })).toEqual({ id: IDS.channel, deleted: true, alreadyDeleted: true });
+ });
+ test('delete channel success', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }]));
+ expect(await run({ action: deleteChannelAction, propsValue: { channelId: IDS.channel } })).toMatchObject({ alreadyDeleted: false });
+ expect(seen[0].method).toBe('DELETE');
+ });
+});
diff --git a/packages/pieces/community/heartbeat/test/helpers.ts b/packages/pieces/community/heartbeat/test/helpers.ts
new file mode 100644
index 00000000000..c57635fc226
--- /dev/null
+++ b/packages/pieces/community/heartbeat/test/helpers.ts
@@ -0,0 +1,147 @@
+import { AppConnectionType, Store } from '@activepieces/pieces-framework';
+import { vi } from 'vitest';
+
+export type SeenRequest = {
+ url: string;
+ method: string;
+ path: string;
+ query: URLSearchParams;
+ auth: string | null;
+ accept: string | null;
+ body: unknown;
+};
+
+export type FakeReply = {
+ status?: number;
+ body?: unknown;
+ text?: string;
+ headers?: Record<string, string>;
+};
+
+export function stubFetch(respond: (request: SeenRequest, index: number) => FakeReply): SeenRequest[] {
+ const seen: SeenRequest[] = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : String(input);
+ const headers = new Headers(init?.headers);
+ const parsed = new URL(url);
+ const rawBody = typeof init?.body === 'string' ? init.body : null;
+ const request: SeenRequest = {
+ url,
+ method: (init?.method ?? 'GET').toUpperCase(),
+ path: parsed.pathname.replace('/v0', ''),
+ query: parsed.searchParams,
+ auth: headers.get('authorization'),
+ accept: headers.get('accept'),
+ body: rawBody ? JSON.parse(rawBody) : null,
+ };
+ seen.push(request);
+ const reply = respond(request, seen.length - 1);
+ const payload = reply.status === 204 ? null : (reply.text ?? JSON.stringify(reply.body ?? {}));
+ return new Response(payload, {
+ status: reply.status ?? 200,
+ headers: { 'content-type': reply.text !== undefined ? 'text/plain' : 'application/json', ...(reply.headers ?? {}) },
+ });
+ }),
+ );
+ return seen;
+}
+
+export function replies(list: FakeReply[]): (request: SeenRequest, index: number) => FakeReply {
+ return (_request, index) => list[Math.min(index, list.length - 1)];
+}
+
+export const TOKEN = 'test-token';
+
+export const SERVER = { apiUrl: 'http://localhost:3000/api/', publicUrl: 'http://localhost:4200/', token: 'x' };
+
+export function codaConnection() {
+ return { type: AppConnectionType.SECRET_TEXT as const, secret_text: TOKEN };
+}
+
+export function actionContext(propsValue: Record<string, unknown>): TestActionContext {
+ return { auth: codaConnection(), propsValue, store: memoryStore(), server: SERVER };
+}
+
+export function memoryStore(initial: Record<string, unknown> = {}): MemoryStore {
+ const data = new Map<string, string>(Object.entries(initial).map(([key, value]) => [key, JSON.stringify(value)]));
+ return {
+ read: (key: string): unknown => {
+ const raw = data.get(key);
+ return raw === undefined ? undefined : JSON.parse(raw);
+ },
+ put: async <T>(key: string, value: T): Promise<T> => {
+ data.set(key, JSON.stringify(value));
+ return value;
+ },
+ get: async <T>(key: string): Promise<T | null> => {
+ const raw = data.get(key);
+ return raw === undefined ? null : JSON.parse(raw);
+ },
+ delete: async (key: string): Promise<void> => {
+ data.delete(key);
+ },
+ };
+}
+
+export async function runStep<T>(promise: Promise<T>): Promise<T> {
+ const settled = promise.then(
+ (value) => ({ ok: true as const, value }),
+ (error: unknown) => ({ ok: false as const, error }),
+ );
+ await vi.runAllTimersAsync();
+ const result = await settled;
+ if (!result.ok) {
+ throw result.error;
+ }
+ return result.value;
+}
+
+export function run({ action, propsValue }: { action: Runnable; propsValue: Record<string, unknown> }): Promise<unknown> {
+ return runStep(action.run(actionContext(propsValue)));
+}
+
+export function idsOf(items: unknown): unknown[] {
+ return Array.isArray(items) ? items.map((item: unknown) => (item !== null && typeof item === 'object' ? Reflect.get(item, 'id') : undefined)) : [];
+}
+
+export type MemoryStore = Store & { read: (key: string) => unknown };
+
+type TestActionContext = {
+ auth: { type: AppConnectionType.SECRET_TEXT; secret_text: string };
+ propsValue: Record<string, unknown>;
+ store: Store;
+ server: typeof SERVER;
+};
+
+type Runnable = { run(context: TestActionContext): Promise<unknown> };
+
+export function triggerContext({ propsValue = {}, body = {}, store = memoryStore() }: { propsValue?: Record<string, unknown>; body?: unknown; store?: ReturnType<typeof memoryStore> }) {
+ return {
+ auth: { type: 'SECRET_TEXT', secret_text: TOKEN },
+ propsValue,
+ store,
+ webhookUrl: 'https://example.ngrok.dev/api/v1/webhooks/flow123',
+ payload: { body, headers: {}, queryParams: {} },
+ server: { apiUrl: 'http://localhost:3000/api/', publicUrl: 'http://localhost:4200/', token: 'x' },
+ };
+}
+
+export const IDS = {
+ user: '0fed0eb0-9dc6-41e9-a09d-ea53d3158c3a',
+ admin: '871072f3-af66-4fb0-b8a4-49290816d64e',
+ group: '13fcd1ac-535f-46b6-bed8-a7eb1b87f96c',
+ role: '670577ce-7912-4a4e-b041-50cf578a1f44',
+ channel: 'a0bb7f6a-ad62-4ea7-99ac-5079bf0725fe',
+ category: '37a94b50-1f50-4e10-ab79-38d5b9c7f043',
+ thread: 'e5285d90-ce1b-4620-b9f1-9444ff6f9bea',
+ comment: '4f3467f8-7e8a-4c71-8699-2ca6ae806c66',
+ chat: '654e5fe6-5208-4ca9-a3c3-ba47d9765d33',
+ message: '1ec429d3-86ba-4fec-a0d7-c7dee0e4c8f8',
+ event: 'acb92b02-b8cb-4e96-914b-825ac9d416d5',
+ invitation: 'b6124913-dc2a-48c7-a9bc-f3e2d251135a',
+ lesson: '11111111-2222-4333-8444-555555555555',
+ document: '66666666-7777-4888-9999-000000000000',
+ webhook: '77777777-8888-4999-aaaa-bbbbbbbbbbbb',
+};
diff --git a/packages/pieces/community/heartbeat/test/triggers.test.ts b/packages/pieces/community/heartbeat/test/triggers.test.ts
new file mode 100644
index 00000000000..55f9e6aa8d4
--- /dev/null
+++ b/packages/pieces/community/heartbeat/test/triggers.test.ts
@@ -0,0 +1,295 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { heartbeatApi } from '../src/lib/common/client';
+import { heartbeatWebhooks } from '../src/lib/common/webhooks';
+import { newMemberTrigger } from '../src/lib/triggers/new-member';
+import { newThreadTrigger } from '../src/lib/triggers/new-thread';
+import { newMentionTrigger } from '../src/lib/triggers/new-mention';
+import { newEventTrigger } from '../src/lib/triggers/new-event';
+import { newDirectMessageTrigger } from '../src/lib/triggers/new-direct-message';
+import { IDS, memoryStore, replies, runStep, stubFetch, TOKEN, triggerContext } from './helpers';
+
+type Hook = (context: ReturnType<typeof triggerContext>) => Promise<unknown>;
+
+function hook({ trigger, name, context }: { trigger: unknown; name: 'onEnable' | 'onDisable' | 'run' | 'test'; context: ReturnType<typeof triggerContext> }) {
+ const fn: Hook = Reflect.get(Object(trigger), name);
+ return runStep(fn(context));
+}
+
+const WEBHOOK_URL = 'https://example.ngrok.dev/api/v1/webhooks/flow123';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(heartbeatApi, 'sleep').mockResolvedValue(undefined);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('webhook lifecycle', () => {
+ test('enable deletes orphans on the same URL, registers and stores the ID', async () => {
+ const store = memoryStore();
+ const seen = stubFetch((request) => {
+ if (request.method === 'GET') {
+ return { body: [{ id: 'orphan-1', url: WEBHOOK_URL }, { id: 'other', url: 'https://elsewhere' }] };
+ }
+ if (request.method === 'PUT') {
+ return { body: { id: IDS.webhook } };
+ }
+ return { body: { success: true } };
+ });
+ await hook({ trigger: newEventTrigger, name: 'onEnable', context: triggerContext({ store }) });
+ expect(seen.map((r) => `${r.method} ${r.path}`)).toEqual(['GET /webhooks', 'DELETE /webhooks/orphan-1', 'PUT /webhooks']);
+ expect(seen[2].body).toEqual({ action: { name: 'EVENT_CREATE' }, url: WEBHOOK_URL });
+ expect(store.read(heartbeatWebhooks.WEBHOOK_STORE_KEY)).toEqual({ webhookId: IDS.webhook });
+ });
+ test('enable replaces a previously stored webhook', async () => {
+ const store = memoryStore({ [heartbeatWebhooks.WEBHOOK_STORE_KEY]: { webhookId: 'old' } });
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: [] } : request.method === 'PUT' ? { body: { id: IDS.webhook } } : { status: 404, body: {} }));
+ await hook({ trigger: newMemberTrigger, name: 'onEnable', context: triggerContext({ store }) });
+ expect(seen[0].method).toBe('DELETE');
+ expect(seen[0].path).toBe('/webhooks/old');
+ expect(seen[2].body).toEqual({ action: { name: 'USER_JOIN' }, url: WEBHOOK_URL });
+ });
+ test('enable deletes the new webhook if storing its ID fails', async () => {
+ const store = memoryStore();
+ store.put = async () => {
+ throw new Error('store down');
+ };
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: [] } : request.method === 'PUT' ? { body: { id: IDS.webhook } } : { body: {} }));
+ await expect(hook({ trigger: newEventTrigger, name: 'onEnable', context: triggerContext({ store }) })).rejects.toThrow('store down');
+ expect(seen[seen.length - 1].method).toBe('DELETE');
+ expect(seen[seen.length - 1].path).toBe(`/webhooks/${IDS.webhook}`);
+ });
+ test('disable forgets the ID after a 2xx or 404, keeps it on other errors', async () => {
+ const store = memoryStore({ [heartbeatWebhooks.WEBHOOK_STORE_KEY]: { webhookId: IDS.webhook } });
+ stubFetch(replies([{ status: 404, body: {} }]));
+ await hook({ trigger: newEventTrigger, name: 'onDisable', context: triggerContext({ store }) });
+ expect(store.read(heartbeatWebhooks.WEBHOOK_STORE_KEY)).toBeUndefined();
+ vi.unstubAllGlobals();
+ const kept = memoryStore({ [heartbeatWebhooks.WEBHOOK_STORE_KEY]: { webhookId: IDS.webhook } });
+ stubFetch(replies([{ status: 500, body: { message: 'down' } }]));
+ await expect(hook({ trigger: newEventTrigger, name: 'onDisable', context: triggerContext({ store: kept }) })).rejects.toThrow();
+ expect(kept.read(heartbeatWebhooks.WEBHOOK_STORE_KEY)).toEqual({ webhookId: IDS.webhook });
+ });
+ test('dedupe ring is bounded', async () => {
+ const store = memoryStore();
+ for (let i = 0; i < heartbeatWebhooks.MAX_SEEN_KEYS + 10; i++) {
+ await heartbeatWebhooks.isFirstDelivery({ store, key: `k${i}` });
+ }
+ const seenKeys = store.read(heartbeatWebhooks.SEEN_STORE_KEY);
+ expect(Array.isArray(seenKeys) && seenKeys.length).toBe(heartbeatWebhooks.MAX_SEEN_KEYS);
+ expect(store.read(heartbeatWebhooks.claimKeyOf('k0'))).toBeUndefined();
+ expect(store.read(heartbeatWebhooks.claimKeyOf(`k${heartbeatWebhooks.MAX_SEEN_KEYS + 9}`))).toBeDefined();
+ expect(await heartbeatWebhooks.isFirstDelivery({ store, key: 'k0' })).toBe(true);
+ expect(await heartbeatWebhooks.isFirstDelivery({ store, key: 'k0' })).toBe(false);
+ });
+ test('claim keys stay short and are one entry per delivery', () => {
+ const key = heartbeatWebhooks.claimKeyOf(`THREAD_CREATE:${IDS.thread}:${IDS.channel}`);
+ expect(key.length).toBeLessThanOrEqual(48);
+ expect(key).not.toBe(heartbeatWebhooks.claimKeyOf(`THREAD_CREATE:${IDS.thread}:${IDS.category}`));
+ });
+ test('two overlapping deliveries of one event emit once', async () => {
+ const store = memoryStore();
+ const [first, second] = await Promise.all([
+ heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:a' }),
+ heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:a' }),
+ ]);
+ expect([first, second].filter(Boolean)).toHaveLength(1);
+ });
+ test('a store failure after claiming releases the claim so the retry emits', async () => {
+ const store = memoryStore();
+ const put = store.put;
+ store.put = async (key, value) => {
+ if (key === heartbeatWebhooks.SEEN_STORE_KEY) {
+ throw new Error('store down');
+ }
+ return put(key, value);
+ };
+ await expect(heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:a' })).rejects.toThrow('store down');
+ expect(store.read(heartbeatWebhooks.claimKeyOf('MENTION:a'))).toBeUndefined();
+ store.put = put;
+ expect(await heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:a' })).toBe(true);
+ });
+ test('an unfinished claim that could not be released expires, a finished one never does', async () => {
+ vi.setSystemTime(new Date('2026-10-06T12:00:00Z'));
+ const store = memoryStore();
+ const put = store.put;
+ store.put = async (key, value) => {
+ if (key === heartbeatWebhooks.SEEN_STORE_KEY) {
+ throw new Error('store down');
+ }
+ return put(key, value);
+ };
+ store.delete = async () => {
+ throw new Error('store down');
+ };
+ await expect(heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:a' })).rejects.toThrow('store down');
+ store.put = put;
+ expect(await heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:a' })).toBe(false);
+ vi.setSystemTime(Date.now() + heartbeatWebhooks.ABANDONED_CLAIM_MS + 1);
+ expect(await heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:a' })).toBe(true);
+ vi.setSystemTime(Date.now() + heartbeatWebhooks.ABANDONED_CLAIM_MS * 10);
+ expect(await heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:a' })).toBe(false);
+ });
+ test('overlapping deliveries of different events both emit and keep each other', async () => {
+ const store = memoryStore();
+ const results = await Promise.all([
+ heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:a' }),
+ heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:b' }),
+ ]);
+ expect(results).toEqual([true, true]);
+ expect(await heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:a' })).toBe(false);
+ expect(await heartbeatWebhooks.isFirstDelivery({ store, key: 'MENTION:b' })).toBe(false);
+ });
+});
+
+describe('trigger filters', () => {
+ test('new thread sends the channel filter', async () => {
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: [] } : { body: { id: IDS.webhook } }));
+ await hook({ trigger: newThreadTrigger, name: 'onEnable', context: triggerContext({ propsValue: { channelId: IDS.channel, includeMovedThreads: true } }) });
+ expect(seen[1].body).toEqual({ action: { name: 'THREAD_CREATE', filter: { channelID: IDS.channel, triggerOnMove: true } }, url: WEBHOOK_URL });
+ });
+ test('new thread refuses moved threads without a channel', async () => {
+ stubFetch(replies([{ body: [] }]));
+ await expect(hook({ trigger: newThreadTrigger, name: 'onEnable', context: triggerContext({ propsValue: { includeMovedThreads: true } }) })).rejects.toThrow(/Channel ID/);
+ });
+ test('new mention builds userSelection and requires at least one target', async () => {
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: [] } : { body: { id: IDS.webhook } }));
+ await hook({ trigger: newMentionTrigger, name: 'onEnable', context: triggerContext({ propsValue: { userIds: [IDS.user], groupIds: [IDS.group], channelIds: [IDS.channel] } }) });
+ expect(seen[1].body).toEqual({
+ action: { name: 'MENTION', filter: { userSelection: [{ id: IDS.user, type: 'USER' }, { id: IDS.group, type: 'GROUP' }], channelIDs: [IDS.channel] } },
+ url: WEBHOOK_URL,
+ });
+ await expect(hook({ trigger: newMentionTrigger, name: 'onEnable', context: triggerContext({ propsValue: {} }) })).rejects.toThrow(/at least one/);
+ });
+ test('new direct message requires the admin filter', async () => {
+ const seen = stubFetch((request) => (request.method === 'GET' ? { body: [] } : { body: { id: IDS.webhook } }));
+ await hook({ trigger: newDirectMessageTrigger, name: 'onEnable', context: triggerContext({ propsValue: { adminUserId: IDS.admin } }) });
+ expect(seen[1].body).toEqual({ action: { name: 'DIRECT_MESSAGE', filter: { userID: IDS.admin } }, url: WEBHOOK_URL });
+ });
+});
+
+describe('trigger runs re-fetch and dedupe', () => {
+ test('new member emits the re-read user once', async () => {
+ const store = memoryStore();
+ const seen = stubFetch(replies([{ body: { id: IDS.user, email: '[email protected]' } }]));
+ const context = triggerContext({ store, body: { id: IDS.user, name: 'A', email: '[email protected]' } });
+ expect(await hook({ trigger: newMemberTrigger, name: 'run', context })).toEqual([{ id: IDS.user, email: '[email protected]' }]);
+ expect(seen[0].path).toBe(`/users/${IDS.user}`);
+ expect(seen[0].auth).toBe(`Bearer ${TOKEN}`);
+ expect(await hook({ trigger: newMemberTrigger, name: 'run', context })).toEqual([]);
+ });
+ test('forged or non-UUID IDs emit nothing without calling the API', async () => {
+ const seen = stubFetch(replies([{ body: {} }]));
+ expect(await hook({ trigger: newEventTrigger, name: 'run', context: triggerContext({ body: { id: '../users' } }) })).toEqual([]);
+ expect(await hook({ trigger: newMemberTrigger, name: 'run', context: triggerContext({ body: 'not json' }) })).toEqual([]);
+ expect(seen).toHaveLength(0);
+ });
+ test('a 404 on re-fetch emits nothing; other errors throw', async () => {
+ stubFetch(replies([{ status: 404, body: { message: 'Could not find event' } }]));
+ expect(await hook({ trigger: newEventTrigger, name: 'run', context: triggerContext({ body: { id: IDS.event } }) })).toEqual([]);
+ vi.unstubAllGlobals();
+ stubFetch(replies([{ status: 500, body: { message: 'down' } }]));
+ await expect(hook({ trigger: newEventTrigger, name: 'run', context: triggerContext({ body: { id: IDS.event } }) })).rejects.toThrow(/down/);
+ });
+ test('new event accepts a JSON string body', async () => {
+ stubFetch(replies([{ body: { id: IDS.event } }]));
+ expect(await hook({ trigger: newEventTrigger, name: 'run', context: triggerContext({ body: JSON.stringify({ id: IDS.event }) }) })).toEqual([{ id: IDS.event }]);
+ });
+ test('new thread dedupes per thread and channel', async () => {
+ const store = memoryStore();
+ stubFetch(replies([{ body: { id: IDS.thread, channelID: IDS.channel } }]));
+ const context = triggerContext({ store, body: { id: IDS.thread, channelID: IDS.channel } });
+ expect(await hook({ trigger: newThreadTrigger, name: 'run', context })).toHaveLength(1);
+ expect(await hook({ trigger: newThreadTrigger, name: 'run', context })).toHaveLength(0);
+ });
+ const mentionOf = ({ id, kind = 'user' }: { id: string; kind?: string }) => `<p>Hi <span class="reference" data-denotation-char="@" data-id="mention.${kind}.${id}" data-value="X">@X</span></p>`;
+ test('new mention picks the nested comment and reads mentions from its stored content', async () => {
+ const reply = { id: IDS.comment, userID: IDS.user, content: mentionOf({ id: IDS.user }) };
+ stubFetch(replies([{ body: { id: IDS.thread, channelID: IDS.channel, userID: IDS.admin, url: 'u', comments: [{ id: 'c0', children: [reply] }] } }]));
+ const events = await hook({ trigger: newMentionTrigger, name: 'run', context: triggerContext({ propsValue: { userIds: [IDS.user] }, body: { mentionedUsers: [{ id: IDS.admin, type: 'USER' }], userID: IDS.user, source: { type: 'COMMENT', channelID: IDS.channel, threadID: IDS.thread, commentID: IDS.comment } } }) });
+ expect(events).toHaveLength(1);
+ const event = Array.isArray(events) ? events[0] : undefined;
+ expect(event).toMatchObject({ sourceType: 'COMMENT', commentId: IDS.comment, authorUserId: IDS.user, content: reply.content, thread: { id: IDS.thread } });
+ expect(event).toHaveProperty('mentionedUsers', [{ id: IDS.user, type: 'USER' }]);
+ expect(event).not.toHaveProperty('thread.comments');
+ });
+ test('new mention ignores supplied member IDs that the stored content does not mention', async () => {
+ stubFetch(replies([{ body: { id: IDS.thread, channelID: IDS.channel, content: '<p>no mentions here</p>', comments: [] } }]));
+ const context = triggerContext({ propsValue: { userIds: [IDS.user] }, body: { mentionedUsers: [{ id: IDS.user, type: 'USER' }], source: { threadID: IDS.thread } } });
+ expect(await hook({ trigger: newMentionTrigger, name: 'run', context })).toEqual([]);
+ });
+ test('new mention ignores mentions of members or groups that were not chosen', async () => {
+ stubFetch(replies([{ body: { id: IDS.thread, channelID: IDS.channel, content: mentionOf({ id: IDS.admin }) + mentionOf({ id: IDS.role, kind: 'group' }), comments: [] } }]));
+ const context = triggerContext({ propsValue: { userIds: [IDS.user], groupIds: [IDS.group] }, body: { source: { threadID: IDS.thread } } });
+ expect(await hook({ trigger: newMentionTrigger, name: 'run', context })).toEqual([]);
+ });
+ test('new mention matches a chosen group and honours the channel filter', async () => {
+ const thread = { id: IDS.thread, channelID: IDS.channel, content: mentionOf({ id: IDS.group, kind: 'group' }), comments: [] };
+ stubFetch(replies([{ body: thread }]));
+ const events = await hook({ trigger: newMentionTrigger, name: 'run', context: triggerContext({ propsValue: { groupIds: [IDS.group], channelIds: [IDS.channel] }, body: { source: { threadID: IDS.thread } } }) });
+ expect(events).toMatchObject([{ sourceType: 'THREAD', mentionedUsers: [{ id: IDS.group, type: 'GROUP' }] }]);
+ const otherChannel = triggerContext({ propsValue: { groupIds: [IDS.group], channelIds: [IDS.category] }, body: { source: { threadID: IDS.thread } } });
+ expect(await hook({ trigger: newMentionTrigger, name: 'run', context: otherChannel })).toEqual([]);
+ });
+ test('new mention ignores a comment ID that is not in the thread', async () => {
+ stubFetch(replies([{ body: { id: IDS.thread, comments: [] } }]));
+ expect(await hook({ trigger: newMentionTrigger, name: 'run', context: triggerContext({ propsValue: { userIds: [IDS.user] }, body: { source: { threadID: IDS.thread, commentID: IDS.comment } } }) })).toEqual([]);
+ });
+ test('new direct message takes sender from the stored message and receiver from the chosen admin', async () => {
+ const seen = stubFetch(replies([{ body: [{ id: 'x', userID: IDS.admin }, { id: IDS.message, userID: IDS.user, content: '<p>hi</p>', createdAt: 't' }] }]));
+ const result = await hook({ trigger: newDirectMessageTrigger, name: 'run', context: triggerContext({ propsValue: { adminUserId: IDS.admin }, body: { senderUserID: IDS.group, receiverUserID: IDS.role, chatID: IDS.chat, chatMessageID: IDS.message } }) });
+ expect(seen.map((r) => r.path)).toEqual([`/directMessages/${IDS.chat}`]);
+ expect(result).toEqual([{ chatId: IDS.chat, messageId: IDS.message, senderUserId: IDS.user, receiverUserId: IDS.admin, content: '<p>hi</p>', createdAt: 't', images: [], files: [] }]);
+ });
+ test('new direct message confirms the chat ID with Heartbeat when the admin has not written in it yet', async () => {
+ const seen = stubFetch((request) => (request.method === 'PUT' ? { body: { chatID: IDS.chat } } : { body: [{ id: IDS.message, userID: IDS.user }] }));
+ const context = triggerContext({ propsValue: { adminUserId: IDS.admin }, body: { chatID: IDS.chat, chatMessageID: IDS.message } });
+ expect(await hook({ trigger: newDirectMessageTrigger, name: 'run', context })).toMatchObject([{ senderUserId: IDS.user, receiverUserId: IDS.admin }]);
+ expect(seen[1]).toMatchObject({ method: 'PUT', path: '/directChats', body: { userID1: IDS.admin, userID2: IDS.user } });
+ });
+ test('new direct message ignores a sender-only chat that belongs to another admin', async () => {
+ stubFetch((request) => (request.method === 'PUT' ? { body: { chatID: IDS.thread } } : { body: [{ id: IDS.message, userID: IDS.user }] }));
+ const context = triggerContext({ propsValue: { adminUserId: IDS.admin }, body: { chatID: IDS.chat, chatMessageID: IDS.message } });
+ expect(await hook({ trigger: newDirectMessageTrigger, name: 'run', context })).toEqual([]);
+ });
+ test('new direct message ignores chats where someone other than the admin and sender wrote', async () => {
+ const seen = stubFetch(replies([{ body: [{ id: 'x', userID: IDS.group }, { id: IDS.message, userID: IDS.user }] }]));
+ const context = triggerContext({ propsValue: { adminUserId: IDS.admin }, body: { chatID: IDS.chat, chatMessageID: IDS.message } });
+ expect(await hook({ trigger: newDirectMessageTrigger, name: 'run', context })).toEqual([]);
+ expect(seen.map((request) => request.method)).toEqual(['GET']);
+ });
+ test('new direct message ignores messages the admin sent', async () => {
+ stubFetch(replies([{ body: [{ id: IDS.message, userID: IDS.admin }] }]));
+ const context = triggerContext({ propsValue: { adminUserId: IDS.admin }, body: { chatID: IDS.chat, chatMessageID: IDS.message } });
+ expect(await hook({ trigger: newDirectMessageTrigger, name: 'run', context })).toEqual([]);
+ });
+ test('new direct message drops unknown message IDs', async () => {
+ stubFetch(replies([{ body: [{ id: 'x' }] }]));
+ expect(await hook({ trigger: newDirectMessageTrigger, name: 'run', context: triggerContext({ propsValue: { adminUserId: IDS.admin }, body: { chatID: IDS.chat, chatMessageID: IDS.message } }) })).toEqual([]);
+ });
+});
+
+describe('trigger test()', () => {
+ test('new member returns newest members first', async () => {
+ stubFetch(replies([{ body: [{ id: 'a', createdAt: '2026-01-01' }, { id: 'b', createdAt: '2026-02-01' }] }]));
+ expect(await hook({ trigger: newMemberTrigger, name: 'test', context: triggerContext({}) })).toEqual([{ id: 'b', createdAt: '2026-02-01' }, { id: 'a', createdAt: '2026-01-01' }]);
+ });
+ test('new event returns newest events first', async () => {
+ stubFetch(replies([{ body: [{ id: 'a', createdAt: '2026-01-01' }, { id: 'b', createdAt: '2026-02-01' }] }]));
+ expect(await hook({ trigger: newEventTrigger, name: 'test', context: triggerContext({}) })).toMatchObject([{ id: 'b' }, { id: 'a' }]);
+ });
+ test('new thread walks posts channels until it finds threads', async () => {
+ const seen = stubFetch((request) => {
+ if (request.path === '/channels') {
+ return { body: [{ id: 'c1', type: 'POSTS' }, { id: 'c2', type: 'CHAT' }, { id: 'c3', type: 'POSTS' }] };
+ }
+ return request.path === '/channels/c1/threads' ? { body: [] } : { body: [{ id: IDS.thread }] };
+ });
+ expect(await hook({ trigger: newThreadTrigger, name: 'test', context: triggerContext({}) })).toEqual([{ id: IDS.thread }]);
+ expect(seen.map((r) => r.path)).toEqual(['/channels', '/channels/c1/threads', '/channels/c3/threads']);
+ });
+});
diff --git a/packages/pieces/community/heartbeat/test/users.test.ts b/packages/pieces/community/heartbeat/test/users.test.ts
new file mode 100644
index 00000000000..5b84e0bff0a
--- /dev/null
+++ b/packages/pieces/community/heartbeat/test/users.test.ts
@@ -0,0 +1,227 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { heartBeatCreateUser } from '../src/lib/actions/create-user';
+import { createMemberAction } from '../src/lib/actions/ai/create-member';
+import { listUsersAction } from '../src/lib/actions/list-users';
+import { getUserAction } from '../src/lib/actions/get-user';
+import { findUserByEmailAction } from '../src/lib/actions/find-user-by-email';
+import { updateUserAction } from '../src/lib/actions/update-user';
+import { removeUserAction } from '../src/lib/actions/remove-user';
+import { reactivateUserAction } from '../src/lib/actions/reactivate-user';
+import { createPendingUserAction } from '../src/lib/actions/create-pending-user';
+import { listUserCompletedLessonsAction } from '../src/lib/actions/list-user-completed-lessons';
+import { markLessonsCompletedAction } from '../src/lib/actions/mark-lessons-completed';
+import { IDS, replies, run, stubFetch } from './helpers';
+
+const user = {
+ id: IDS.user,
+ email: '[email protected]',
+ name: 'AP-TEST One',
+ role: 'User',
+ isAdmin: false,
+ groups: [{ id: IDS.group, name: 'AP-TEST group' }],
+ linkedInData: { headline: 'x' },
+ linkedInSummary: 's',
+ onboardingResponses: [{ question: 'q', answer: 'a' }],
+ createdAt: '2026-10-06T12:09:26.682Z',
+};
+const admin = { id: IDS.admin, email: '[email protected]', name: 'Admin Person', role: 'Administrator', isAdmin: true, groups: [] };
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe('create user (human)', () => {
+ test('PUTs /users, then reads the new user by the returned userID', async () => {
+ const seen = stubFetch(replies([{ body: { userID: IDS.user } }, { body: user }]));
+ const result = await run({ action: heartBeatCreateUser, propsValue: { name: 'AP-TEST One', email: user.email, role_id: IDS.role, group_ids: [IDS.group], bio: 'b', website: 'https://x.io' } });
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].path).toBe('/users');
+ expect(seen[0].body).toEqual({ name: 'AP-TEST One', email: user.email, roleID: IDS.role, groupIDs: [IDS.group], bio: 'b', website: 'https://x.io' });
+ expect(seen[1].path).toBe(`/users/${IDS.user}`);
+ expect(result).toMatchObject({ userID: IDS.user, id: IDS.user, email: user.email });
+ });
+ test('omits groupIDs when none chosen, and falls back to find by email without userID', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }, { body: user }]));
+ const result = await run({ action: heartBeatCreateUser, propsValue: { name: 'A', email: user.email, role_id: IDS.role } });
+ expect(seen[0].body).not.toHaveProperty('groupIDs');
+ expect(seen[1].path).toBe('/find/users');
+ expect(seen[1].query.get('email')).toBe(user.email);
+ expect(result).toMatchObject({ userID: IDS.user });
+ });
+ test('keeps the new user ID when the read-back fails, so a retry does not create again', async () => {
+ stubFetch(replies([{ body: { userID: IDS.user } }, { status: 500, body: { message: 'down' } }]));
+ const result = await run({ action: heartBeatCreateUser, propsValue: { name: 'A', email: user.email, role_id: IDS.role } });
+ expect(result).toMatchObject({ userID: IDS.user, lookupError: expect.stringMatching(/saved in Heartbeat/) });
+ });
+ test('rejects a social link without scheme before any request', async () => {
+ const seen = stubFetch(replies([{ body: {} }]));
+ await expect(run({ action: heartBeatCreateUser, propsValue: { name: 'A', email: user.email, role_id: IDS.role, linkedin: 'linkedin.com/in/x' } })).rejects.toThrow();
+ expect(seen).toHaveLength(0);
+ });
+ test('is human-only now', () => {
+ expect(heartBeatCreateUser.audience).toBe('human');
+ expect(heartBeatCreateUser.name).toBe('heartbeat_create_user');
+ });
+});
+
+describe('create member (ai)', () => {
+ test('validates role ID and sends the same request shape', async () => {
+ const seen = stubFetch(replies([{ body: { userID: IDS.user } }, { body: user }]));
+ await run({ action: createMemberAction, propsValue: { name: 'A', email: user.email, roleId: IDS.role, groupIds: [IDS.group], createIntroductionThread: false } });
+ expect(seen[0].body).toEqual({ name: 'A', email: user.email, roleID: IDS.role, groupIDs: [IDS.group], createIntroductionThread: false });
+ expect(createMemberAction.audience).toBe('ai');
+ });
+ test('refuses a non-UUID role ID', async () => {
+ const seen = stubFetch(replies([{ body: {} }]));
+ await expect(run({ action: createMemberAction, propsValue: { name: 'A', email: user.email, roleId: 'User' } })).rejects.toThrow(/Role ID/);
+ expect(seen).toHaveLength(0);
+ });
+});
+
+describe('list members', () => {
+ test('filters client-side, strips profile details and reports totals', async () => {
+ stubFetch(replies([{ body: [user, admin] }]));
+ const result = await run({ action: listUsersAction, propsValue: { search: 'ap-test', limit: 10 } });
+ expect(result).toEqual({ users: [expect.not.objectContaining({ linkedInData: expect.anything() })], count: 1, totalMatching: 1, truncated: false });
+ });
+ test('group, role, admin filters and truncation', async () => {
+ stubFetch(replies([{ body: [user, admin, { ...user, id: 'x2', email: '[email protected]' }] }]));
+ expect(await run({ action: listUsersAction, propsValue: { groupId: IDS.group, limit: 1 } })).toMatchObject({ count: 1, totalMatching: 2, truncated: true });
+ expect(await run({ action: listUsersAction, propsValue: { role: 'administrator' } })).toMatchObject({ count: 1 });
+ expect(await run({ action: listUsersAction, propsValue: { adminsOnly: true } })).toMatchObject({ users: [expect.objectContaining({ id: IDS.admin })] });
+ });
+ test('keeps profile details when asked', async () => {
+ stubFetch(replies([{ body: [user] }]));
+ const result = await run({ action: listUsersAction, propsValue: { includeProfileDetails: true } });
+ expect(result).toMatchObject({ users: [expect.objectContaining({ linkedInData: { headline: 'x' } })] });
+ });
+});
+
+describe('get / find member', () => {
+ test('get reads /users/{id}', async () => {
+ const seen = stubFetch(replies([{ body: user }]));
+ await run({ action: getUserAction, propsValue: { userId: IDS.user } });
+ expect(seen[0].path).toBe(`/users/${IDS.user}`);
+ });
+ test('find returns found=true with the object body', async () => {
+ stubFetch(replies([{ body: user }]));
+ expect(await run({ action: findUserByEmailAction, propsValue: { email: user.email } })).toEqual({ found: true, user });
+ });
+ test('find maps the documented 404 to found=false', async () => {
+ stubFetch(replies([{ status: 404, body: { error: true, message: 'Could not find user' } }]));
+ expect(await run({ action: findUserByEmailAction, propsValue: { email: '[email protected]' } })).toEqual({ found: false, user: null });
+ });
+ test('find rethrows other errors', async () => {
+ stubFetch(replies([{ status: 401, body: { message: 'no' } }]));
+ await expect(run({ action: findUserByEmailAction, propsValue: { email: '[email protected]' } })).rejects.toThrow(/401/);
+ });
+});
+
+describe('update member', () => {
+ test('POSTs only changed fields plus clears, then re-reads', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }, { body: user }]));
+ const result = await run({ action: updateUserAction, propsValue: { email: user.email, bio: 'New bio', fieldsToClear: ['status', 'twitter'] } });
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].path).toBe('/users');
+ expect(seen[0].body).toEqual({ email: user.email, bio: 'New bio', status: '', twitter: '' });
+ expect(result).toMatchObject({ updated: true, updatedFields: ['bio', 'status', 'twitter'], user });
+ });
+ test('refuses a no-op', async () => {
+ const seen = stubFetch(replies([{ body: {} }]));
+ await expect(run({ action: updateUserAction, propsValue: { email: user.email } })).rejects.toThrow(/Nothing to update/);
+ expect(seen).toHaveLength(0);
+ });
+ test('refuses set and clear of the same field', async () => {
+ stubFetch(replies([{ body: {} }]));
+ await expect(run({ action: updateUserAction, propsValue: { email: user.email, bio: 'x', fieldsToClear: ['bio'] } })).rejects.toThrow(/both set and cleared/);
+ });
+});
+
+describe('remove / reactivate member', () => {
+ test('remove sends DELETE /users with the email body', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }]));
+ expect(await run({ action: removeUserAction, propsValue: { email: user.email } })).toEqual({ email: user.email, removed: true });
+ expect(seen[0].method).toBe('DELETE');
+ expect(seen[0].body).toEqual({ email: user.email });
+ });
+ test('remove surfaces 404 for an unknown email', async () => {
+ stubFetch(replies([{ status: 404, body: { message: 'Could not find user' } }]));
+ await expect(run({ action: removeUserAction, propsValue: { email: '[email protected]' } })).rejects.toThrow(/Could not find user/);
+ });
+ test('reactivate POSTs /users/reactivate', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }]));
+ expect(await run({ action: reactivateUserAction, propsValue: { email: user.email } })).toEqual({ email: user.email, reactivated: true, alreadyActive: false });
+ expect(seen[0].path).toBe('/users/reactivate');
+ expect(seen[0].method).toBe('POST');
+ });
+ test('reactivate treats "already active" as success', async () => {
+ stubFetch(replies([{ status: 400, body: { code: 'VALIDATION_ERROR', message: 'This user is already active' } }]));
+ expect(await run({ action: reactivateUserAction, propsValue: { email: user.email } })).toEqual({ email: user.email, reactivated: true, alreadyActive: true });
+ });
+ test('reactivate rethrows other 400s', async () => {
+ stubFetch(replies([{ status: 400, body: { message: 'Invalid input' } }]));
+ await expect(run({ action: reactivateUserAction, propsValue: { email: user.email } })).rejects.toThrow(/Invalid input/);
+ });
+});
+
+describe('pre-register member', () => {
+ test('PUTs /pendingUser', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }]));
+ expect(await run({ action: createPendingUserAction, propsValue: { email: '[email protected]', name: 'A', roleId: IDS.role } })).toEqual({ email: '[email protected]', success: true });
+ expect(seen[0].method).toBe('PUT');
+ expect(seen[0].path).toBe('/pendingUser');
+ expect(seen[0].body).toEqual({ email: '[email protected]', name: 'A', roleID: IDS.role });
+ });
+});
+
+describe('completed lessons', () => {
+ test('list pages with lessonID cursor', async () => {
+ const seen = stubFetch(replies([{ body: [{ lessonID: IDS.lesson, completedAt: '2026-10-01T00:00:00Z' }] }]));
+ const result = await run({ action: listUserCompletedLessonsAction, propsValue: { userId: IDS.user, limit: 1 } });
+ expect(seen[0].path).toBe(`/users/${IDS.user}/completed-lessons`);
+ expect(seen[0].query.get('limit')).toBe('1');
+ expect(result).toEqual({ items: [{ lessonID: IDS.lesson, completedAt: '2026-10-01T00:00:00Z' }], nextCursor: IDS.lesson, hasMore: true });
+ });
+ test('mark POSTs completedLessons and confirms by re-reading', async () => {
+ const other = '22222222-2222-4333-8444-555555555555';
+ const seen = stubFetch(replies([
+ { body: { success: true } },
+ { body: user },
+ { body: [{ lessonID: IDS.lesson, completedAt: '2026-10-01T10:00:00Z' }] },
+ ]));
+ const result = await run({ action: markLessonsCompletedAction, propsValue: { email: '[email protected]', lessonIds: [IDS.lesson, other], completedAt: '2026-10-01T10:00:00Z' } });
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].body).toEqual({ email: '[email protected]', completedLessons: [{ lessonID: IDS.lesson, timestamp: '2026-10-01T10:00:00.000Z' }, { lessonID: other, timestamp: '2026-10-01T10:00:00.000Z' }] });
+ expect(seen[2].path).toBe(`/users/${IDS.user}/completed-lessons`);
+ expect(result).toEqual({ email: '[email protected]', lessonIds: [IDS.lesson, other], completedAt: '2026-10-01T10:00:00.000Z', confirmed: [IDS.lesson], notConfirmed: [other], unverified: [], checkComplete: true, lookupError: null });
+ });
+ test('mark reports lessons beyond the fifth page as unverified, not missing', async () => {
+ const page = (n: number) => Array.from({ length: 100 }, (_, i) => ({ lessonID: `00000000-0000-4000-8000-${String(n * 100 + i).padStart(12, '0')}` }));
+ const seen = stubFetch(replies([{ body: {} }, { body: user }, { body: page(0) }, { body: page(1) }, { body: page(2) }, { body: page(3) }, { body: page(4) }, { body: [{ lessonID: IDS.lesson }] }]));
+ const result = await run({ action: markLessonsCompletedAction, propsValue: { email: '[email protected]', lessonIds: [IDS.lesson] } });
+ expect(seen).toHaveLength(7);
+ expect(result).toMatchObject({ confirmed: [], notConfirmed: [], unverified: [IDS.lesson], checkComplete: false, lookupError: null });
+ });
+ test('mark keeps the saved completion when the read-back fails', async () => {
+ stubFetch(replies([{ body: {} }, { status: 500, body: { message: 'down' } }]));
+ const result = await run({ action: markLessonsCompletedAction, propsValue: { email: '[email protected]', lessonIds: [IDS.lesson] } });
+ expect(result).toMatchObject({ confirmed: [], notConfirmed: [], unverified: [IDS.lesson], checkComplete: false });
+ expect(result).toHaveProperty('lookupError', expect.stringMatching(/saved in Heartbeat.*down/));
+ });
+ test('mark follows completed-lesson pages until all are found', async () => {
+ const full = Array.from({ length: 100 }, (_, i) => ({ lessonID: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}` }));
+ const seen = stubFetch(replies([{ body: {} }, { body: user }, { body: full }, { body: [{ lessonID: IDS.lesson }] }]));
+ const result = await run({ action: markLessonsCompletedAction, propsValue: { email: '[email protected]', lessonIds: [IDS.lesson] } });
+ expect(seen[3].query.get('startingAfter')).toBe(full[99].lessonID);
+ expect(result).toMatchObject({ confirmed: [IDS.lesson], notConfirmed: [] });
+ });
+ test('mark refuses an empty lesson list', async () => {
+ stubFetch(replies([{ body: {} }]));
+ await expect(run({ action: markLessonsCompletedAction, propsValue: { email: '[email protected]', lessonIds: [] } })).rejects.toThrow(/at least one/);
+ });
+});
diff --git a/packages/pieces/community/heartbeat/vitest.config.ts b/packages/pieces/community/heartbeat/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/heartbeat/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ 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'),
+ },
+ },
+})