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(send-it): add AI actions, output schemas and webhook signature checks (#16869)

Odai Ahmadb529a1156941
diff --git a/bun.lock b/bun.lock
index 430655ab7c7..ae1e457a222 100644
--- a/bun.lock
+++ b/bun.lock
@@ -8263,15 +8263,17 @@
},
"packages/pieces/community/send-it": {
"name": "@activepieces/piece-send-it",
- "version": "0.2.0",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "undici": "7.29.1",
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/sender": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index 5ef831ee5b2..b4511990dd9 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,19 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### SendIt 0.3.0: two scheduled-post actions leave AI agents, and publishing checks inputs before sending
+
+From SendIt 0.3.0, **Cancel Scheduled Post** and **Trigger Scheduled Post Now** are no longer offered to AI agents and MCP clients. They stay available as flow steps. An agent or MCP client that called them by name no longer finds them.
+
+SendIt 0.3.0 also changes what an existing **Publish Post** or **Schedule Post** step does once it is upgraded to that version. Steps keep running on the version they were built with until you upgrade them.
+
+- A media URL that starts with `http://` now stops the step. Media URLs must be public `https://` URLs.
+- A post that targets Instagram, Pinterest, TikTok or YouTube without a media URL now stops the whole step before anything is sent, including to the other selected platforms. Before, a text-only post to LinkedIn and Instagram still reached SendIt.
+
+#### What you need to do
+
+For agents and MCP clients, use **Cancel Scheduled Post by ID** instead of Cancel Scheduled Post, and **Publish Scheduled Post Now** instead of Trigger Scheduled Post Now. Before you upgrade a Publish Post or Schedule Post step to 0.3.0, make sure its media URLs use `https://`, and add a media URL or remove Instagram, Pinterest, TikTok and YouTube from posts that have none.
+
#### Pastefy 0.4.0: six actions leave the agent tool list, and existing steps change behavior
Pastefy 0.4.0 changes what an existing step does once it is upgraded to that version. Steps keep running on the version they were built with until you upgrade them.
diff --git a/packages/pieces/community/send-it/package.json b/packages/pieces/community/send-it/package.json
index ad75e6fd45e..7f60bd018ee 100644
--- a/packages/pieces/community/send-it/package.json
+++ b/packages/pieces/community/send-it/package.json
@@ -1,20 +1,23 @@
{
"name": "@activepieces/piece-send-it",
- "version": "0.2.0",
+ "version": "0.3.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "undici": "7.29.1"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/send-it/src/index.ts b/packages/pieces/community/send-it/src/index.ts
index f72cf0e4f2b..8d14fb127b0 100644
--- a/packages/pieces/community/send-it/src/index.ts
+++ b/packages/pieces/community/send-it/src/index.ts
@@ -1,7 +1,7 @@
-import { createPiece } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import { PieceCategory } from '@activepieces/pieces-framework';
-import { sendItAuth } from './lib/auth';
+import { sendItAuth } from './lib/common/auth';
+import { BASE_URL, apiKeyOf, authHeaders } from './lib/common/client';
import { publishPost } from './lib/actions/publish-post';
import { schedulePost } from './lib/actions/schedule-post';
import { cancelScheduledPost } from './lib/actions/cancel-scheduled-post';
@@ -9,20 +9,25 @@ import { triggerScheduledPost } from './lib/actions/trigger-scheduled-post';
import { validateContent } from './lib/actions/validate-content';
import { listAccounts } from './lib/actions/list-accounts';
import { listScheduledPosts } from './lib/actions/list-scheduled-posts';
+import { getPostAnalytics } from './lib/actions/get-post-analytics';
+import { listFailedPosts } from './lib/actions/list-failed-posts';
+import { cancelScheduledPostById } from './lib/actions/ai/cancel-scheduled-post-by-id';
+import { publishScheduledPostNow } from './lib/actions/ai/publish-scheduled-post-now';
+import { getScheduledPost } from './lib/actions/ai/get-scheduled-post';
+import { getPlatformRequirements } from './lib/actions/ai/get-platform-requirements';
import { postPublished } from './lib/triggers/post-published';
import { postScheduled } from './lib/triggers/post-scheduled';
import { postFailed } from './lib/triggers/post-failed';
-import { BASE_URL } from './lib/common';
export const sendIt = createPiece({
displayName: 'SendIt',
description:
'Multi-platform social media publishing. Schedule and publish content to LinkedIn, Instagram, Threads, TikTok, X, and 30+ more platforms.',
auth: sendItAuth,
- minimumSupportedRelease: '0.20.0',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/send-it.png',
categories: [PieceCategory.MARKETING],
- authors: ['infiniteappsai', 'sanket-a11y'],
+ authors: ['infiniteappsai', 'sanket-a11y', 'OdaiAhmed99'],
actions: [
publishPost,
schedulePost,
@@ -31,12 +36,16 @@ export const sendIt = createPiece({
validateContent,
listAccounts,
listScheduledPosts,
+ getPostAnalytics,
+ listFailedPosts,
+ cancelScheduledPostById,
+ publishScheduledPostNow,
+ getScheduledPost,
+ getPlatformRequirements,
createCustomApiCallAction({
baseUrl: () => BASE_URL,
auth: sendItAuth,
- authMapping: async (auth) => ({
- Authorization: `Bearer ${auth.secret_text}`,
- }),
+ authMapping: async (auth) => authHeaders(apiKeyOf(auth)),
}),
],
triggers: [postPublished, postScheduled, postFailed],
diff --git a/packages/pieces/community/send-it/src/lib/actions/ai/cancel-scheduled-post-by-id.ts b/packages/pieces/community/send-it/src/lib/actions/ai/cancel-scheduled-post-by-id.ts
new file mode 100644
index 00000000000..a6ba68025ad
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/actions/ai/cancel-scheduled-post-by-id.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { sendItAuth } from '../../common/auth';
+import { aiProps } from '../../common/ai-props';
+import { apiKeyOf } from '../../common/client';
+import { sendItOutputSchemas } from '../../common/output-schemas';
+import { sendItRequests } from '../../common/requests';
+
+export const cancelScheduledPostById = createAction({
+ auth: sendItAuth,
+ name: 'cancel_scheduled_post_by_id',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Cancel Scheduled Post by ID',
+ description: 'Cancels a pending scheduled post by schedule ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Cancels one pending scheduled post by its schedule ID (from Schedule Post or List Scheduled Posts) so it will not be published. Not idempotent: an ID that is already cancelled, published or unknown fails with SendIt 404 "Scheduled post not found".',
+ idempotent: false,
+ },
+ props: {
+ scheduleId: aiProps.scheduleId(),
+ },
+ outputSchema: sendItOutputSchemas.cancelResult,
+ async run(context) {
+ return sendItRequests.cancel({ apiKey: apiKeyOf(context.auth), scheduleId: context.propsValue.scheduleId });
+ },
+});
diff --git a/packages/pieces/community/send-it/src/lib/actions/ai/get-platform-requirements.ts b/packages/pieces/community/send-it/src/lib/actions/ai/get-platform-requirements.ts
new file mode 100644
index 00000000000..0e28c9c282e
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/actions/ai/get-platform-requirements.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { sendItAuth } from '../../common/auth';
+import { aiProps } from '../../common/ai-props';
+import { apiKeyOf } from '../../common/client';
+import { sendItOutputSchemas } from '../../common/output-schemas';
+import { sendItRequests } from '../../common/requests';
+
+export const getPlatformRequirements = createAction({
+ auth: sendItAuth,
+ name: 'get_platform_requirements',
+ classification: 'READ',
+ displayName: 'Get Platform Requirements',
+ description: 'Gets the text limit and media rules for one platform.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Gets the posting rules for one platform before writing a post: textLimit, image formats and max size, max images, video formats, max duration and size, rate limit and notes. Unknown platforms fail with SendIt\'s list of valid values. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ platform: aiProps.platform(),
+ },
+ outputSchema: sendItOutputSchemas.requirements,
+ async run(context) {
+ return sendItRequests.requirements({ apiKey: apiKeyOf(context.auth), platform: context.propsValue.platform });
+ },
+});
diff --git a/packages/pieces/community/send-it/src/lib/actions/ai/get-scheduled-post.ts b/packages/pieces/community/send-it/src/lib/actions/ai/get-scheduled-post.ts
new file mode 100644
index 00000000000..ae716b6ffa2
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/actions/ai/get-scheduled-post.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { sendItAuth } from '../../common/auth';
+import { aiProps } from '../../common/ai-props';
+import { apiKeyOf } from '../../common/client';
+import { sendItOutputSchemas } from '../../common/output-schemas';
+import { sendItRequests } from '../../common/requests';
+
+export const getScheduledPost = createAction({
+ auth: sendItAuth,
+ name: 'get_scheduled_post',
+ classification: 'READ',
+ displayName: 'Get Scheduled Post',
+ description: 'Gets one pending scheduled post by schedule ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Gets one pending scheduled post (platforms, content, scheduledTime) by schedule ID. Fails with a clear message when the ID is not pending (already published, cancelled or unknown). Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ scheduleId: aiProps.scheduleId(),
+ },
+ outputSchema: sendItOutputSchemas.scheduledPost,
+ async run(context) {
+ return sendItRequests.getScheduled({ apiKey: apiKeyOf(context.auth), scheduleId: context.propsValue.scheduleId });
+ },
+});
diff --git a/packages/pieces/community/send-it/src/lib/actions/ai/publish-scheduled-post-now.ts b/packages/pieces/community/send-it/src/lib/actions/ai/publish-scheduled-post-now.ts
new file mode 100644
index 00000000000..997bbce53a6
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/actions/ai/publish-scheduled-post-now.ts
@@ -0,0 +1,27 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { sendItAuth } from '../../common/auth';
+import { aiProps } from '../../common/ai-props';
+import { apiKeyOf } from '../../common/client';
+import { sendItOutputSchemas } from '../../common/output-schemas';
+import { sendItRequests } from '../../common/requests';
+
+export const publishScheduledPostNow = createAction({
+ auth: sendItAuth,
+ name: 'publish_scheduled_post_now',
+ classification: 'WRITE',
+ displayName: 'Publish Scheduled Post Now',
+ description: 'Publishes a pending scheduled post immediately, by schedule ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Publishes one pending scheduled post right now instead of at its scheduled time, by schedule ID (from Schedule Post or List Scheduled Posts). Returns per-platform results with post IDs and URLs. Not idempotent: it performs a real publish that counts against the plan post quota; an unknown or already-published ID fails with SendIt 404.',
+ idempotent: false,
+ },
+ props: {
+ scheduleId: aiProps.scheduleId(),
+ },
+ outputSchema: sendItOutputSchemas.triggerNowResult,
+ async run(context) {
+ return sendItRequests.triggerNow({ apiKey: apiKeyOf(context.auth), scheduleId: context.propsValue.scheduleId });
+ },
+});
diff --git a/packages/pieces/community/send-it/src/lib/actions/cancel-scheduled-post.ts b/packages/pieces/community/send-it/src/lib/actions/cancel-scheduled-post.ts
index df3deb508cb..c644dd86a1a 100644
--- a/packages/pieces/community/send-it/src/lib/actions/cancel-scheduled-post.ts
+++ b/packages/pieces/community/send-it/src/lib/actions/cancel-scheduled-post.ts
@@ -1,7 +1,9 @@
import { createAction } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { sendItAuth } from '../auth';
-import { scheduleIdProperty, sendItRequest } from '../common';
+import { sendItAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { sendItOutputSchemas } from '../common/output-schemas';
+import { scheduleIdProperty } from '../common/props';
+import { sendItRequests } from '../common/requests';
export const cancelScheduledPost = createAction({
auth: sendItAuth,
@@ -9,22 +11,17 @@ export const cancelScheduledPost = createAction({
classification: 'DESTRUCTIVE',
displayName: 'Cancel Scheduled Post',
description: 'Cancel a scheduled post before it is published',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Cancels a pending scheduled post by its schedule ID so it will not be published. Use this to call off a future post created by Schedule Post; only posts in Pending status can be cancelled. Idempotent: cancelling an already-cancelled or non-existent schedule leaves it in the same cancelled end state.',
- idempotent: true,
+ 'Cancels a pending scheduled post chosen from a dropdown so it will not be published. Not idempotent: SendIt returns 404 "Scheduled post not found" for an ID that is already cancelled, published or unknown.',
+ idempotent: false,
},
props: {
scheduleId: scheduleIdProperty,
},
+ outputSchema: sendItOutputSchemas.cancelResult,
async run(context) {
- const { scheduleId } = context.propsValue;
-
- return await sendItRequest(
- context.auth.secret_text,
- HttpMethod.DELETE,
- `/scheduled/${scheduleId}`
- );
+ return sendItRequests.cancel({ apiKey: apiKeyOf(context.auth), scheduleId: context.propsValue.scheduleId });
},
});
diff --git a/packages/pieces/community/send-it/src/lib/actions/get-post-analytics.ts b/packages/pieces/community/send-it/src/lib/actions/get-post-analytics.ts
new file mode 100644
index 00000000000..54e664ae2bb
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/actions/get-post-analytics.ts
@@ -0,0 +1,31 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { sendItAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { sendItOutputSchemas } from '../common/output-schemas';
+import { singlePlatformProperty } from '../common/props';
+import { sendItRequests, validateLimit } from '../common/requests';
+
+export const getPostAnalytics = createAction({
+ auth: sendItAuth,
+ name: 'get_post_analytics',
+ classification: 'SEARCH',
+ displayName: 'Get Post Analytics',
+ description: 'Get engagement metrics for posts published on one platform',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Gets per-post engagement metrics SendIt collected for one platform (lowercase platform value such as instagram, linkedin, bluesky), optionally between startDate and endDate (ISO-8601). X analytics are disabled by SendIt (pay-per-use read charges) and return an error. posts is empty when nothing was published in the range. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ platform: { ...singlePlatformProperty, description: 'Platform to get analytics for. SendIt disables analytics for X.' },
+ startDate: Property.DateTime({ displayName: 'Start Date', description: 'Only posts published on or after this date.', required: false }),
+ endDate: Property.DateTime({ displayName: 'End Date', description: 'Only posts published on or before this date.', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: 'Maximum number of posts (1-100).', required: false }),
+ },
+ outputSchema: sendItOutputSchemas.analytics,
+ async run(context) {
+ const { platform, startDate, endDate, limit } = context.propsValue;
+ return sendItRequests.analytics({ apiKey: apiKeyOf(context.auth), platform, startDate, endDate, limit: validateLimit({ value: limit, label: 'Limit', max: 100 }) });
+ },
+});
diff --git a/packages/pieces/community/send-it/src/lib/actions/list-accounts.ts b/packages/pieces/community/send-it/src/lib/actions/list-accounts.ts
index 015de8817da..fa3ac7804e2 100644
--- a/packages/pieces/community/send-it/src/lib/actions/list-accounts.ts
+++ b/packages/pieces/community/send-it/src/lib/actions/list-accounts.ts
@@ -1,7 +1,8 @@
-import { createAction } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { sendItAuth } from '../auth';
-import { sendItRequest } from '../common';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { sendItAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { sendItOutputSchemas } from '../common/output-schemas';
+import { sendItRequests, validateLimit } from '../common/requests';
export const listAccounts = createAction({
auth: sendItAuth,
@@ -12,15 +13,18 @@ export const listAccounts = createAction({
audience: 'both',
aiMetadata: {
description:
- 'Retrieves the social media accounts currently connected to the SendIt account. Use this to discover which platforms are available before publishing or scheduling, or to verify a connection exists. Takes no input. Idempotent: it is a read-only lookup.',
+ 'Lists the social media accounts connected to SendIt (id, platform, username, connectedAt). Use it to see which platform values can be published to before Publish Post or Schedule Post. count is the number returned in this response. Read-only and idempotent.',
idempotent: true,
},
- props: {},
+ props: {
+ limit: Property.Number({
+ displayName: 'Limit',
+ description: 'Maximum accounts to return (1-100). Empty uses the SendIt default.',
+ required: false,
+ }),
+ },
+ outputSchema: sendItOutputSchemas.accountList,
async run(context) {
- return await sendItRequest(
- context.auth.secret_text,
- HttpMethod.GET,
- '/accounts'
- );
+ return sendItRequests.listAccounts({ apiKey: apiKeyOf(context.auth), limit: validateLimit({ value: context.propsValue.limit, label: 'Limit', max: 100 }) });
},
});
diff --git a/packages/pieces/community/send-it/src/lib/actions/list-failed-posts.ts b/packages/pieces/community/send-it/src/lib/actions/list-failed-posts.ts
new file mode 100644
index 00000000000..9c867048543
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/actions/list-failed-posts.ts
@@ -0,0 +1,27 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { sendItAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { sendItOutputSchemas } from '../common/output-schemas';
+import { sendItRequests, validateLimit } from '../common/requests';
+
+export const listFailedPosts = createAction({
+ auth: sendItAuth,
+ name: 'list_failed_posts',
+ classification: 'SEARCH',
+ displayName: 'List Failed Posts',
+ description: 'List posts that exhausted their retries (dead letter queue)',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists posts SendIt gave up on after retries (the dead letter queue), each with the error and retry count. Use it to find why scheduled posts did not go out. count is the number returned in this response. Read-only and idempotent.',
+ idempotent: true,
+ },
+ props: {
+ status: Property.ShortText({ displayName: 'Status', description: 'Optional status filter as SendIt reports it (e.g. pending).', required: false }),
+ limit: Property.Number({ displayName: 'Limit', description: 'Maximum number of posts (1-100).', required: false }),
+ },
+ outputSchema: sendItOutputSchemas.deadLetterList,
+ async run(context) {
+ return sendItRequests.listDeadLetter({ apiKey: apiKeyOf(context.auth), status: context.propsValue.status ?? undefined, limit: validateLimit({ value: context.propsValue.limit, label: 'Limit', max: 100 }) });
+ },
+});
diff --git a/packages/pieces/community/send-it/src/lib/actions/list-scheduled-posts.ts b/packages/pieces/community/send-it/src/lib/actions/list-scheduled-posts.ts
index 33bbe5de750..d8dd7731f10 100644
--- a/packages/pieces/community/send-it/src/lib/actions/list-scheduled-posts.ts
+++ b/packages/pieces/community/send-it/src/lib/actions/list-scheduled-posts.ts
@@ -1,7 +1,9 @@
import { createAction } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { sendItAuth } from '../auth';
-import { platformFilterProperty, sendItRequest } from '../common';
+import { sendItAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { sendItOutputSchemas } from '../common/output-schemas';
+import { platformFilterProperty } from '../common/props';
+import { sendItRequests } from '../common/requests';
export const listScheduledPosts = createAction({
auth: sendItAuth,
@@ -12,22 +14,14 @@ export const listScheduledPosts = createAction({
audience: 'both',
aiMetadata: {
description:
- 'Lists pending scheduled posts, optionally filtered to a single platform; leaving the platform filter empty returns scheduled posts across all platforms. Use this to find the schedule ID of a post you want to cancel or trigger early, or to review the publishing queue. Idempotent: it is a read-only list.',
+ 'Lists pending scheduled posts, optionally filtered to one platform; leave the filter empty for all platforms. Each post has its schedule id, platforms, content and scheduledTime. Use it to find the schedule ID to cancel or publish early. count is the number returned in this response. Read-only and idempotent.',
idempotent: true,
},
props: {
platformFilter: platformFilterProperty,
},
+ outputSchema: sendItOutputSchemas.scheduledList,
async run(context) {
- const { platformFilter } = context.propsValue;
- const params = platformFilter ? { platform: platformFilter } : undefined;
-
- return await sendItRequest(
- context.auth.secret_text,
- HttpMethod.GET,
- '/scheduled',
- undefined,
- params
- );
+ return sendItRequests.listScheduled({ apiKey: apiKeyOf(context.auth), platform: context.propsValue.platformFilter ?? undefined });
},
});
diff --git a/packages/pieces/community/send-it/src/lib/actions/publish-post.ts b/packages/pieces/community/send-it/src/lib/actions/publish-post.ts
index 3df44c9bc9d..40e1e1eb4e9 100644
--- a/packages/pieces/community/send-it/src/lib/actions/publish-post.ts
+++ b/packages/pieces/community/send-it/src/lib/actions/publish-post.ts
@@ -1,14 +1,19 @@
import { createAction } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { sendItAuth } from '../auth';
+import { sendItAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { sendItOutputSchemas } from '../common/output-schemas';
import {
- platformProperty,
- textProperty,
+ firstCommentProperty,
+ idempotencyKeyProperty,
+ mediaTypeProperty,
mediaUrlProperty,
mediaUrlsProperty,
- mediaTypeProperty,
- sendItRequest,
-} from '../common';
+ platformProperty,
+ platformSettingsProperty,
+ textProperty,
+ titleProperty,
+} from '../common/props';
+import { sendItRequests } from '../common/requests';
export const publishPost = createAction({
auth: sendItAuth,
@@ -19,7 +24,7 @@ export const publishPost = createAction({
audience: 'both',
aiMetadata: {
description:
- 'Immediately publishes a post (text plus optional image/video URL or a multi-image carousel) to one or more connected social platforms (X, LinkedIn, Instagram, Threads, TikTok, and others). Choose this to post right now rather than at a future time (use Schedule Post for that). Requires at least one selected platform whose account is connected in SendIt; note Instagram and TikTok require a media URL. Not idempotent: each call publishes a new post.',
+ 'Immediately publishes a post (text plus optional image/video URL or a multi-image carousel) to one or more connected social platforms (X, LinkedIn, Instagram, Threads, Bluesky, TikTok and others). Use Schedule Post to publish later. Each selected platform must be connected in SendIt (check with List Connected Accounts); Instagram, Pinterest, TikTok and YouTube require a public https media URL. Each publish counts against the SendIt plan post quota (Free: 30 per month). Returns per-platform results with post IDs and URLs. Not idempotent: every call publishes a new post. An Idempotency-Key header is sent, but SendIt was not seen to deduplicate on it, so do not retry blindly after a timeout; check the account first.',
idempotent: false,
},
props: {
@@ -28,24 +33,18 @@ export const publishPost = createAction({
mediaUrl: mediaUrlProperty,
mediaUrls: mediaUrlsProperty,
mediaType: mediaTypeProperty,
+ title: titleProperty,
+ firstComment: firstCommentProperty,
+ platformSettings: platformSettingsProperty,
+ idempotencyKey: idempotencyKeyProperty,
},
+ outputSchema: sendItOutputSchemas.publishResult,
async run(context) {
- const { platforms, text, mediaUrl, mediaUrls, mediaType } =
- context.propsValue;
-
- return await sendItRequest(
- context.auth.secret_text,
- HttpMethod.POST,
- '/publish',
- {
- platforms,
- content: {
- text,
- mediaUrl,
- mediaUrls,
- mediaType,
- },
- }
- );
+ const { idempotencyKey, ...input } = context.propsValue;
+ return sendItRequests.publish({
+ apiKey: apiKeyOf(context.auth),
+ input,
+ key: sendItRequests.idempotencyKey({ override: idempotencyKey, runId: context.run.id, stepName: context.step.name, input, operation: 'publish' }),
+ });
},
});
diff --git a/packages/pieces/community/send-it/src/lib/actions/schedule-post.ts b/packages/pieces/community/send-it/src/lib/actions/schedule-post.ts
index 6c3d6cf6092..ac0282a0971 100644
--- a/packages/pieces/community/send-it/src/lib/actions/schedule-post.ts
+++ b/packages/pieces/community/send-it/src/lib/actions/schedule-post.ts
@@ -1,13 +1,20 @@
import { createAction } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { sendItAuth } from '../auth';
+import { sendItAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { sendItOutputSchemas } from '../common/output-schemas';
import {
- platformProperty,
- textProperty,
+ firstCommentProperty,
+ idempotencyKeyProperty,
+ mediaTypeProperty,
mediaUrlProperty,
+ mediaUrlsProperty,
+ platformProperty,
+ platformSettingsProperty,
scheduledTimeProperty,
- sendItRequest,
-} from '../common';
+ textProperty,
+ titleProperty,
+} from '../common/props';
+import { sendItRequests } from '../common/requests';
export const schedulePost = createAction({
auth: sendItAuth,
@@ -18,30 +25,29 @@ export const schedulePost = createAction({
audience: 'both',
aiMetadata: {
description:
- 'Queues a post (text plus optional media URL) to be published at a specified future time on one or more connected social platforms. Choose this when publishing should be deferred; use Publish Post to send immediately. The scheduled time must be in the future and is interpreted in UTC. Not idempotent: each call creates a new scheduled post.',
+ 'Queues a post (text plus optional media URL or carousel) to be published at a future ISO-8601 time (UTC) on one or more connected social platforms. Use Publish Post to send immediately. Rejects past times and missing media for Instagram, Pinterest, TikTok and YouTube before calling SendIt. Returns the scheduleId to pass to the cancel or publish-now actions. Each scheduled post counts against the plan post quota once published. Not idempotent: every call creates a new schedule, even with the same Idempotency-Key (verified live), so check List Scheduled Posts before retrying.',
idempotent: false,
},
props: {
platforms: platformProperty,
text: textProperty,
mediaUrl: mediaUrlProperty,
+ mediaUrls: mediaUrlsProperty,
+ mediaType: mediaTypeProperty,
+ title: titleProperty,
+ firstComment: firstCommentProperty,
+ platformSettings: platformSettingsProperty,
scheduledTime: scheduledTimeProperty,
+ idempotencyKey: idempotencyKeyProperty,
},
+ outputSchema: sendItOutputSchemas.scheduleResult,
async run(context) {
- const { platforms, text, mediaUrl, scheduledTime } = context.propsValue;
-
- return await sendItRequest(
- context.auth.secret_text,
- HttpMethod.POST,
- '/schedule',
- {
- platforms,
- content: {
- text,
- mediaUrl,
- },
- scheduledTime,
- }
- );
+ const { idempotencyKey, scheduledTime, ...input } = context.propsValue;
+ return sendItRequests.schedule({
+ apiKey: apiKeyOf(context.auth),
+ input,
+ scheduledTime,
+ key: sendItRequests.idempotencyKey({ override: idempotencyKey, runId: context.run.id, stepName: context.step.name, input: { ...input, scheduledTime }, operation: 'schedule' }),
+ });
},
});
diff --git a/packages/pieces/community/send-it/src/lib/actions/trigger-scheduled-post.ts b/packages/pieces/community/send-it/src/lib/actions/trigger-scheduled-post.ts
index 15a229ca5d6..33aeb7ddfca 100644
--- a/packages/pieces/community/send-it/src/lib/actions/trigger-scheduled-post.ts
+++ b/packages/pieces/community/send-it/src/lib/actions/trigger-scheduled-post.ts
@@ -1,7 +1,9 @@
import { createAction } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { sendItAuth } from '../auth';
-import { scheduleIdProperty, sendItRequest } from '../common';
+import { sendItAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { sendItOutputSchemas } from '../common/output-schemas';
+import { scheduleIdProperty } from '../common/props';
+import { sendItRequests } from '../common/requests';
export const triggerScheduledPost = createAction({
auth: sendItAuth,
@@ -9,22 +11,17 @@ export const triggerScheduledPost = createAction({
classification: 'WRITE',
displayName: 'Trigger Scheduled Post Now',
description: 'Immediately publish a scheduled post',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Publishes a pending scheduled post right away instead of waiting for its scheduled time, identified by its schedule ID. Use this to push out a queued post early. Not idempotent: it performs an actual publish, so repeating the call can re-publish the content.',
+ 'Publishes a pending scheduled post chosen from a dropdown right away instead of waiting for its scheduled time. Not idempotent: it performs a real publish.',
idempotent: false,
},
props: {
scheduleId: scheduleIdProperty,
},
+ outputSchema: sendItOutputSchemas.triggerNowResult,
async run(context) {
- const { scheduleId } = context.propsValue;
-
- return await sendItRequest(
- context.auth.secret_text,
- HttpMethod.POST,
- `/scheduled/${scheduleId}/trigger`
- );
+ return sendItRequests.triggerNow({ apiKey: apiKeyOf(context.auth), scheduleId: context.propsValue.scheduleId });
},
});
diff --git a/packages/pieces/community/send-it/src/lib/actions/validate-content.ts b/packages/pieces/community/send-it/src/lib/actions/validate-content.ts
index bc4dfa7700a..b472696c357 100644
--- a/packages/pieces/community/send-it/src/lib/actions/validate-content.ts
+++ b/packages/pieces/community/send-it/src/lib/actions/validate-content.ts
@@ -1,14 +1,9 @@
import { createAction } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { sendItAuth } from '../auth';
-import {
- platformProperty,
- textProperty,
- mediaUrlProperty,
- mediaUrlsProperty,
- mediaTypeProperty,
- sendItRequest,
-} from '../common';
+import { sendItAuth } from '../common/auth';
+import { apiKeyOf } from '../common/client';
+import { sendItOutputSchemas } from '../common/output-schemas';
+import { mediaTypeProperty, mediaUrlProperty, mediaUrlsProperty, platformProperty, textProperty } from '../common/props';
+import { sendItRequests } from '../common/requests';
export const validateContent = createAction({
auth: sendItAuth,
@@ -19,7 +14,7 @@ export const validateContent = createAction({
audience: 'both',
aiMetadata: {
description:
- 'Validates that a post (text plus optional media) meets the requirements of the selected social platforms, such as character limits and media rules, without publishing anything. Use this as a pre-flight check before Publish Post or Schedule Post. Idempotent: it is a read-only check with no side effects.',
+ 'Checks a post (text plus optional media) against the selected platforms without publishing anything. Returns valid (boolean), errors and warnings per platform (e.g. "Instagram requires media"), and platformLimits per platform (text limit, media required, max images). Use before Publish Post or Schedule Post. Read-only and idempotent.',
idempotent: true,
},
props: {
@@ -29,23 +24,9 @@ export const validateContent = createAction({
mediaUrls: mediaUrlsProperty,
mediaType: mediaTypeProperty,
},
+ outputSchema: sendItOutputSchemas.validationResult,
async run(context) {
- const { platforms, text, mediaUrl, mediaUrls, mediaType } =
- context.propsValue;
-
- return await sendItRequest(
- context.auth.secret_text,
- HttpMethod.POST,
- '/validate',
- {
- platforms,
- content: {
- text,
- mediaUrl,
- mediaUrls,
- mediaType,
- },
- }
- );
+ const { platforms, text, mediaUrl, mediaUrls, mediaType } = context.propsValue;
+ return sendItRequests.validate({ apiKey: apiKeyOf(context.auth), input: { platforms, text, mediaUrl, mediaUrls, mediaType } });
},
});
diff --git a/packages/pieces/community/send-it/src/lib/auth.ts b/packages/pieces/community/send-it/src/lib/auth.ts
deleted file mode 100644
index 39c51bdc0bb..00000000000
--- a/packages/pieces/community/send-it/src/lib/auth.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { PieceAuth } from '@activepieces/pieces-framework';
-import { httpClient, HttpMethod } from '@activepieces/pieces-common';
-
-const BASE_URL = 'https://sendit.infiniteappsai.com/api/v1';
-
-export const sendItAuth = PieceAuth.SecretText({
- displayName: 'API Key',
- description: `To get your SendIt API key:
-1. Log in to your [SendIt dashboard](https://sendit.infiniteappsai.com/dashboard)
-2. Go to **Settings > API Keys**
-3. Click **Create API Key** — the key is only shown once, so copy it immediately
-4. Paste the key below (it starts with \`sk_live_\`)`,
- required: true,
- validate: async ({ auth }) => {
- try {
- await httpClient.sendRequest({
- method: HttpMethod.GET,
- url: `${BASE_URL}/accounts`,
- headers: { Authorization: `Bearer ${auth}` },
- });
- return { valid: true };
- } catch {
- return {
- valid: false,
- error:
- 'Invalid API key. Make sure you copied the full key starting with sk_live_.',
- };
- }
- },
-});
diff --git a/packages/pieces/community/send-it/src/lib/common/ai-props.ts b/packages/pieces/community/send-it/src/lib/common/ai-props.ts
new file mode 100644
index 00000000000..bed8291b7cb
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/common/ai-props.ts
@@ -0,0 +1,19 @@
+import { Property } from '@activepieces/pieces-framework';
+
+export const aiProps = { scheduleId, platform };
+
+function scheduleId() {
+ return Property.ShortText({
+ displayName: 'Schedule ID',
+ description: 'The schedule ID returned by Schedule Post or listed by List Scheduled Posts (field id).',
+ required: true,
+ });
+}
+
+function platform() {
+ return Property.ShortText({
+ displayName: 'Platform',
+ description: 'Lowercase SendIt platform value, e.g. x, linkedin, instagram, threads, bluesky, tiktok, youtube, telegram, discord.',
+ required: true,
+ });
+}
diff --git a/packages/pieces/community/send-it/src/lib/common/auth.ts b/packages/pieces/community/send-it/src/lib/common/auth.ts
new file mode 100644
index 00000000000..b21f4795838
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/common/auth.ts
@@ -0,0 +1,28 @@
+import { PieceAuth } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SendItApiError, apiKeyOf, sendItApi } from './client';
+
+export const sendItAuth = PieceAuth.SecretText({
+ displayName: 'API Key',
+ description: `To get your SendIt API key:
+1. Log in to your [SendIt dashboard](https://sendit.infiniteappsai.com/dashboard)
+2. Go to **Settings > API Keys**
+3. Click **Create API Key** — the key is only shown once, so copy it immediately
+4. Paste the key below (it starts with \`sk_live_\`)`,
+ required: true,
+ validate: async ({ auth }) => {
+ const apiKey = apiKeyOf(auth);
+ if (apiKey === '') {
+ return { valid: false, error: 'Enter your SendIt API key.' };
+ }
+ try {
+ await sendItApi.request({ apiKey, method: HttpMethod.GET, path: '/accounts', operation: 'validate API key', query: { limit: 1 } });
+ return { valid: true };
+ } catch (error) {
+ if (error instanceof SendItApiError && (error.status === 401 || error.status === 403)) {
+ return { valid: false, error: 'Invalid API key. Make sure you copied the full key starting with sk_live_.' };
+ }
+ return { valid: false, error: `Could not reach SendIt to check the key: ${error instanceof Error ? error.message : String(error)}` };
+ }
+ },
+});
diff --git a/packages/pieces/community/send-it/src/lib/common/client.ts b/packages/pieces/community/send-it/src/lib/common/client.ts
new file mode 100644
index 00000000000..f429f81564a
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/common/client.ts
@@ -0,0 +1,209 @@
+import { HttpMethod, HttpRequest, httpClient } from '@activepieces/pieces-common';
+
+export const SENDIT_ORIGIN = 'https://sendit.infiniteappsai.com';
+
+export const BASE_URL = `${SENDIT_ORIGIN}/api/v1`;
+
+export class SendItApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({ operation, status, responseBody }: { operation: string; status: number; responseBody: unknown }) {
+ super(`SendIt ${operation} failed (${status}): ${describeStatus({ status, responseBody })}`);
+ this.name = 'SendItApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+export function isRecord(value: unknown): value is SendItRecord {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+export function vendorMessage(responseBody: unknown): string {
+ if (typeof responseBody === 'string' && responseBody.trim() !== '') {
+ return responseBody.slice(0, MAX_ERROR_TEXT);
+ }
+ if (!isRecord(responseBody)) {
+ return 'no details returned';
+ }
+ const parts: string[] = [];
+ const add = (value: unknown) => {
+ if (typeof value === 'string' && value.trim() !== '' && !parts.includes(value)) {
+ parts.push(value);
+ }
+ };
+ add(responseBody['error']);
+ add(responseBody['message']);
+ if (isRecord(responseBody['error'])) {
+ add(responseBody['error']['message']);
+ }
+ if (Array.isArray(responseBody['errors'])) {
+ for (const item of responseBody['errors']) {
+ add(isRecord(item) ? item['message'] : item);
+ }
+ }
+ return (parts.length > 0 ? parts.join(' - ') : JSON.stringify(responseBody)).slice(0, MAX_ERROR_TEXT);
+}
+
+export function isNotFound(error: unknown): boolean {
+ return statusOf(error) === 404;
+}
+
+export function apiKeyOf(auth: unknown): string {
+ const raw = typeof auth === 'string' ? auth : isRecord(auth) ? auth['secret_text'] : undefined;
+ return String(raw ?? '').trim();
+}
+
+export function authHeaders(apiKey: string): Record<string, string> {
+ return { Authorization: `Bearer ${apiKey.trim()}` };
+}
+
+export function verifiedTlsDispatcher(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));
+ return verifiedTlsAgent;
+}
+
+export function requireText({ value, label }: { value: unknown; label: string }): string {
+ const text = optionalText(value);
+ if (text === undefined) {
+ throw new Error(`${label} is required.`);
+ }
+ return text;
+}
+
+export function optionalText(value: unknown): string | undefined {
+ if (value === undefined || value === null) {
+ return undefined;
+ }
+ const text = String(value).trim();
+ return text === '' ? undefined : text;
+}
+
+export function pathId({ value, label }: { value: unknown; label: string }): string {
+ const text = requireText({ value, label });
+ if (text === '.' || text === '..') {
+ throw new Error(`${label} "${text}" is not valid.`);
+ }
+ return encodeURIComponent(text);
+}
+
+export function readList({ body, key }: { body: unknown; key: string }): SendItRecord[] {
+ const list = isRecord(body) ? body[key] : undefined;
+ return Array.isArray(list) ? list.filter(isRecord) : [];
+}
+
+export const sendItApi = { request, sleep };
+
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+const REQUEST_TIMEOUT_MS = 60_000;
+
+const RATE_LIMIT_RETRY_DELAYS_MS = [10_000, 20_000];
+
+const MAX_ERROR_TEXT = 500;
+
+function describeStatus({ status, responseBody }: { status: number; responseBody: unknown }): string {
+ const detail = vendorMessage(responseBody);
+ switch (status) {
+ case 401:
+ return `the API key is invalid or was revoked. ${detail}`;
+ case 403:
+ return `SendIt refused the request (the feature may not be on your plan, or the post quota is used up). ${detail}`;
+ case 404:
+ return `not found, or not in a state that allows this. ${detail}`;
+ case 429:
+ return `SendIt rate limit reached; try again in a minute. ${detail}`;
+ default:
+ return detail;
+ }
+}
+
+function statusOf(error: unknown): number | undefined {
+ if (error instanceof SendItApiError) {
+ return error.status;
+ }
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ return isRecord(response) && typeof response['status'] === 'number' ? response['status'] : undefined;
+}
+
+function responseBodyOf(error: unknown): unknown {
+ if (!isRecord(error) && !(error instanceof Error)) {
+ return undefined;
+ }
+ const response: unknown = Reflect.get(error, 'response');
+ return isRecord(response) ? response['body'] : undefined;
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function toQuery(query: Record<string, QueryValue> | undefined): Record<string, string> {
+ const result: Record<string, string> = {};
+ for (const [key, value] of Object.entries(query ?? {})) {
+ if (value !== undefined && value !== null && value !== '') {
+ result[key] = String(value);
+ }
+ }
+ return result;
+}
+
+async function request<T = SendItRecord>({ apiKey, method, path, operation, query, body, headers, wait = sleep }: SendItRequest): Promise<T> {
+ if (!path.startsWith('/') || path.startsWith('//') || path.includes('..')) {
+ throw new Error(`Internal error: SendIt path must be relative (${operation}).`);
+ }
+ const httpRequest: HttpRequest = {
+ method,
+ url: `${BASE_URL}${path}`,
+ headers: { ...authHeaders(apiKey), Accept: 'application/json', ...headers },
+ queryParams: toQuery(query),
+ timeout: REQUEST_TIMEOUT_MS,
+ followRedirects: false,
+ };
+ if (body !== undefined) {
+ httpRequest.body = body;
+ httpRequest.headers = { ...httpRequest.headers, 'Content-Type': 'application/json' };
+ }
+ const dispatcher = await verifiedTlsDispatcher();
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await httpClient.sendRequest<T>(httpRequest, { dispatcher });
+ if (response.status >= 300) {
+ throw new SendItApiError({ operation, status: response.status, responseBody: response.body });
+ }
+ return response.body;
+ } catch (error) {
+ if (error instanceof SendItApiError) {
+ throw 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;
+ }
+ throw new SendItApiError({ operation, status, responseBody: responseBodyOf(error) });
+ }
+ }
+}
+
+export type SendItRecord = Record<string, unknown>;
+
+type QueryValue = string | number | boolean | undefined | null;
+
+export type SendItRequest = {
+ apiKey: string;
+ method: HttpMethod;
+ path: string;
+ operation: string;
+ query?: Record<string, QueryValue>;
+ body?: unknown;
+ headers?: Record<string, string>;
+ wait?: (ms: number) => Promise<void>;
+};
diff --git a/packages/pieces/community/send-it/src/lib/common/output-schemas.ts b/packages/pieces/community/send-it/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..69bc16ccf2e
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/common/output-schemas.ts
@@ -0,0 +1,247 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+export const sendItOutputSchemas = {
+ publishResult: publishResult(),
+ scheduleResult: scheduleResult(),
+ triggerNowResult: triggerNowResult(),
+ cancelResult: cancelResult(),
+ validationResult: validationResult(),
+ accountList: accountList(),
+ scheduledList: scheduledList(),
+ scheduledPost: scheduledPost(),
+ requirements: requirements(),
+ analytics: analytics(),
+ deadLetterList: deadLetterList(),
+ postPublishedEvent: postPublishedEvent(),
+ postFailedEvent: postFailedEvent(),
+ postScheduledEvent: postScheduledEvent(),
+};
+
+function contentFields(): Fields {
+ return [
+ { key: 'text', label: 'Text' },
+ { key: 'mediaUrl', label: 'Media URL', format: 'url' },
+ { key: 'mediaUrls', label: 'Media URLs' },
+ ];
+}
+
+function accountFields(): Fields {
+ return [
+ { key: 'id', label: 'Account ID' },
+ { key: 'platform', label: 'Platform' },
+ { key: 'username', label: 'Username' },
+ { key: 'platformUserId', label: 'Platform User ID' },
+ { key: 'connectedAt', label: 'Connected At', format: 'datetime' },
+ ];
+}
+
+function scheduledPostFields(): Fields {
+ return [
+ { key: 'id', label: 'Schedule ID' },
+ { key: 'platforms', label: 'Platforms' },
+ { key: 'content', label: 'Content', children: contentFields() },
+ { key: 'scheduledTime', label: 'Scheduled Time', format: 'datetime' },
+ { key: 'status', label: 'Status' },
+ { key: 'createdAt', label: 'Created At', format: 'datetime' },
+ ];
+}
+
+function publishResultFields(): Fields {
+ return [
+ { key: 'platform', label: 'Platform' },
+ { key: 'platformPostId', label: 'Platform Post ID', description: 'The post ID on the platform (e.g. a Bluesky at:// URI).' },
+ { key: 'postUrl', label: 'Post URL', format: 'url' },
+ { key: 'postType', label: 'Post Type' },
+ ];
+}
+
+function publishResult(): OutputSchema {
+ return {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'results', label: 'Per-Platform Results', listItems: publishResultFields(), labelKey: 'platform' },
+ { key: 'errors', label: 'Errors' },
+ { key: 'errorDetails', label: 'Error Details' },
+ { key: 'idempotencyKey', label: 'Idempotency Key', description: 'Key sent as the Idempotency-Key header.' },
+ ],
+ };
+}
+
+function scheduleResult(): OutputSchema {
+ return {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'scheduleId', label: 'Schedule ID', description: 'Pass to Cancel or Publish Scheduled Post Now.' },
+ { key: 'platforms', label: 'Platforms' },
+ { key: 'scheduledTime', label: 'Scheduled Time', format: 'datetime' },
+ { key: 'status', label: 'Status' },
+ { key: 'idempotencyKey', label: 'Idempotency Key' },
+ ],
+ };
+}
+
+function triggerNowResult(): OutputSchema {
+ return {
+ fields: [
+ { key: 'scheduleId', label: 'Schedule ID' },
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'results', label: 'Per-Platform Results', listItems: publishResultFields(), labelKey: 'platform' },
+ { key: 'errors', label: 'Errors' },
+ { key: 'errorDetails', label: 'Error Details' },
+ ],
+ };
+}
+
+function cancelResult(): OutputSchema {
+ return {
+ fields: [
+ { key: 'scheduleId', label: 'Schedule ID' },
+ { key: 'cancelled', label: 'Cancelled', format: 'boolean' },
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'message', label: 'Message' },
+ ],
+ };
+}
+
+function validationResult(): OutputSchema {
+ return {
+ fields: [
+ { key: 'valid', label: 'Valid', format: 'boolean' },
+ {
+ key: 'errors',
+ label: 'Errors',
+ labelKey: 'message',
+ listItems: [
+ { key: 'platform', label: 'Platform' },
+ { key: 'field', label: 'Field' },
+ { key: 'message', label: 'Message' },
+ ],
+ },
+ { key: 'warnings', label: 'Warnings' },
+ { key: 'platformLimits', label: 'Platform Limits', description: 'Object keyed by platform: name, textLimit, mediaRequired, maxImages, maxMediaItems, videoOnly, textOnly.' },
+ ],
+ };
+}
+
+function accountList(): OutputSchema {
+ return {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'accounts', label: 'Accounts', listItems: accountFields(), labelKey: 'username' },
+ { key: 'count', label: 'Count (this response)', format: 'number' },
+ ],
+ };
+}
+
+function scheduledList(): OutputSchema {
+ return {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ { key: 'posts', label: 'Scheduled Posts', listItems: scheduledPostFields(), labelKey: 'id' },
+ { key: 'count', label: 'Count (this response)', format: 'number' },
+ ],
+ };
+}
+
+function scheduledPost(): OutputSchema {
+ return { fields: scheduledPostFields() };
+}
+
+function requirements(): OutputSchema {
+ return {
+ fields: [
+ { key: 'platform', label: 'Platform' },
+ { key: 'name', label: 'Platform Name' },
+ { key: 'textLimit', label: 'Text Limit', format: 'number' },
+ { key: 'hashtagLimit', label: 'Hashtag Limit', format: 'number' },
+ { key: 'accountTypes', label: 'Supported Account Types' },
+ { key: 'imageFormats', label: 'Image Formats' },
+ { key: 'imageSize', label: 'Max Image Size' },
+ { key: 'maxImages', label: 'Max Images', format: 'number' },
+ { key: 'videoFormats', label: 'Video Formats' },
+ { key: 'videoDuration', label: 'Max Video Duration' },
+ { key: 'videoSize', label: 'Max Video Size' },
+ { key: 'rateLimit', label: 'Rate Limit' },
+ { key: 'tokenExpiry', label: 'Token Expiry' },
+ { key: 'notes', label: 'Notes' },
+ ],
+ };
+}
+
+function analytics(): OutputSchema {
+ return {
+ fields: [
+ { key: 'platform', label: 'Platform' },
+ { key: 'posts', label: 'Posts', description: 'Per-post metrics as returned by SendIt for this platform.' },
+ { key: 'count', label: 'Count (this response)', format: 'number' },
+ ],
+ };
+}
+
+function deadLetterList(): OutputSchema {
+ return {
+ fields: [
+ { key: 'success', label: 'Success', format: 'boolean' },
+ {
+ key: 'posts',
+ label: 'Failed Posts',
+ labelKey: 'id',
+ listItems: [
+ { key: 'id', label: 'ID' },
+ { key: 'scheduleId', label: 'Schedule ID' },
+ { key: 'platforms', label: 'Platforms' },
+ { key: 'content', label: 'Content', children: contentFields() },
+ { key: 'error', label: 'Error' },
+ { key: 'retryCount', label: 'Retry Count', format: 'number' },
+ { key: 'status', label: 'Status' },
+ ],
+ },
+ { key: 'count', label: 'Count (this response)', format: 'number' },
+ ],
+ };
+}
+
+function triggerBase(): Fields {
+ return [
+ { key: 'delivery_id', label: 'Delivery ID' },
+ { key: 'event', label: 'Event' },
+ { key: 'timestamp', label: 'Delivered At', format: 'datetime' },
+ { key: 'content_text', label: 'Post Text' },
+ ];
+}
+
+function postPublishedEvent(): OutputSchema {
+ return {
+ fields: [
+ ...triggerBase(),
+ { key: 'platform', label: 'Platform' },
+ { key: 'post_id', label: 'Post ID', description: 'As sent by SendIt; for Bluesky this is the post URL.' },
+ { key: 'post_url', label: 'Post URL', format: 'url' },
+ { key: 'published_at', label: 'Published At', format: 'datetime' },
+ ],
+ };
+}
+
+function postFailedEvent(): OutputSchema {
+ return {
+ fields: [
+ ...triggerBase(),
+ { key: 'platform', label: 'Platform' },
+ { key: 'error', label: 'Error' },
+ { key: 'failed_at', label: 'Failed At', format: 'datetime' },
+ ],
+ };
+}
+
+function postScheduledEvent(): OutputSchema {
+ return {
+ fields: [
+ ...triggerBase(),
+ { key: 'schedule_id', label: 'Schedule ID' },
+ { key: 'platforms', label: 'Platforms' },
+ { key: 'scheduled_time', label: 'Scheduled Time', format: 'datetime' },
+ ],
+ };
+}
+
+type Fields = OutputSchema['fields'];
diff --git a/packages/pieces/community/send-it/src/lib/common.ts b/packages/pieces/community/send-it/src/lib/common/props.ts
similarity index 55%
rename from packages/pieces/community/send-it/src/lib/common.ts
rename to packages/pieces/community/send-it/src/lib/common/props.ts
index a24ff1fe7f0..f0df5821ad4 100644
--- a/packages/pieces/community/send-it/src/lib/common.ts
+++ b/packages/pieces/community/send-it/src/lib/common/props.ts
@@ -1,10 +1,9 @@
-import { HttpMethod, httpClient } from '@activepieces/pieces-common';
import { Property } from '@activepieces/pieces-framework';
import { sendItAuth } from './auth';
+import { apiKeyOf } from './client';
+import { sendItRequests } from './requests';
-const API_BASE = 'https://sendit.infiniteappsai.com/api/v1';
-
-const options = [
+export const platformOptions = [
{ label: 'X (Twitter)', value: 'x' },
{ label: 'LinkedIn', value: 'linkedin' },
{ label: 'LinkedIn Page', value: 'linkedin-page' },
@@ -38,27 +37,6 @@ const options = [
{ label: 'Twitch', value: 'twitch' },
{ label: 'Product Hunt', value: 'producthunt' },
];
-export async function sendItRequest(
- apiKey: string,
- method: HttpMethod,
- path: string,
- body?: unknown,
- params?: Record<string, string>
-) {
- const response = await httpClient.sendRequest({
- method,
- url: `${API_BASE}${path}`,
- headers: {
- Authorization: `Bearer ${apiKey}`,
- 'Content-Type': 'application/json',
- },
- body,
- queryParams: params,
- });
- return response.body;
-}
-
-export const BASE_URL = API_BASE;
export const platformProperty = Property.StaticMultiSelectDropdown({
displayName: 'Platforms',
@@ -66,35 +44,35 @@ export const platformProperty = Property.StaticMultiSelectDropdown({
'Select one or more social media platforms to publish to. Make sure your accounts are connected in the SendIt dashboard under **Settings > Connected Accounts**.',
required: true,
options: {
- options,
+ options: platformOptions,
},
});
export const textProperty = Property.LongText({
displayName: 'Post Text',
description:
- 'The text content of your post. Character limits vary by platform (e.g. X/Twitter: 280, LinkedIn: 3000, Instagram: 2200).',
+ 'The text content of your post. Character limits vary by platform (e.g. X: 280, or more with X Premium; LinkedIn: 3000; Instagram: 2200).',
required: true,
});
export const mediaUrlProperty = Property.ShortText({
displayName: 'Media URL',
description:
- 'A publicly accessible URL to an image (JPG, PNG, GIF) or video (MP4). **Required for Instagram and TikTok.** Images must be under 10 MB and videos under 100 MB.',
+ 'A public https:// URL to an image (JPG, PNG, GIF, WebP) or video (MP4, MOV). **Required for Instagram, Pinterest, TikTok and YouTube.** Images must be under 10 MB and videos under 100 MB.',
required: false,
});
export const mediaUrlsProperty = Property.Array({
displayName: 'Media URLs (Carousel)',
description:
- 'Add multiple publicly accessible image URLs to create a carousel post. Supported on Instagram and Threads. Add one URL per item.',
+ 'Add multiple public https:// image URLs to create a carousel post. Supported on Instagram and Threads. Add one URL per item.',
required: false,
});
export const mediaTypeProperty = Property.StaticDropdown({
displayName: 'Media Type',
description:
- 'Leave as **Auto-detect** unless SendIt misidentifies your media. Choose **Image** or **Video** to force a specific type.',
+ 'Leave as **Auto-detect** unless SendIt misidentifies your media. Choose **Image** or **Video** to force a specific type. Only sent when media is attached.',
required: false,
defaultValue: 'auto',
options: {
@@ -106,6 +84,31 @@ export const mediaTypeProperty = Property.StaticDropdown({
},
});
+export const titleProperty = Property.ShortText({
+ displayName: 'Title',
+ description: 'Optional title, used by platforms that support one (e.g. YouTube, Pinterest, Reddit-style communities).',
+ required: false,
+});
+
+export const firstCommentProperty = Property.LongText({
+ displayName: 'First Comment',
+ description: 'Optional comment SendIt posts right after the post on platforms that support it (e.g. Instagram, LinkedIn).',
+ required: false,
+});
+
+export const platformSettingsProperty = Property.Json({
+ displayName: 'Platform Settings',
+ description: 'Optional advanced settings keyed by platform, e.g. `{"pinterest": {"boardId": "123"}}`. Leave empty for defaults.',
+ required: false,
+});
+
+export const idempotencyKeyProperty = Property.ShortText({
+ displayName: 'Idempotency Key',
+ description:
+ 'Optional value for the Idempotency-Key header. Leave empty to use one generated from this flow run and step. Note: in testing SendIt did not reject repeated schedule requests with the same key.',
+ required: false,
+});
+
export const scheduleIdProperty = Property.Dropdown({
displayName: 'Scheduled Post',
description:
@@ -122,57 +125,25 @@ export const scheduleIdProperty = Property.Dropdown({
};
}
try {
- const response = (await sendItRequest(
- auth.secret_text,
- HttpMethod.GET,
- '/scheduled'
- )) as Record<string, unknown>;
-
- const posts = (response['posts'] ??
- response['data'] ??
- response) as Record<string, unknown>[];
-
- if (!Array.isArray(posts) || posts.length === 0) {
+ const { posts } = await sendItRequests.listScheduled({ apiKey: apiKeyOf(auth) });
+ if (posts.length === 0) {
return {
disabled: false,
options: [],
placeholder: 'No scheduled posts found. Create one first.',
};
}
-
return {
disabled: false,
options: posts
- .map((post) => {
- const platforms = Array.isArray(post['platforms'])
- ? (post['platforms'] as string[]).join(', ')
- : String(post['platform'] ?? 'Unknown');
- const content = post['content'] as
- | Record<string, unknown>
- | undefined;
- const rawText = String(content?.['text'] ?? '');
- const snippet =
- rawText.length > 40
- ? rawText.substring(0, 40) + '…'
- : rawText || 'No text';
- const scheduledTime = post['scheduledTime']
- ? new Date(String(post['scheduledTime'])).toLocaleString()
- : '';
- const id = String(post['id'] ?? post['scheduleId'] ?? '');
- return {
- label: `${platforms} — ${snippet}${
- scheduledTime ? ` (${scheduledTime})` : ''
- }`,
- value: id,
- };
- })
- .filter((opt) => opt.value !== ''),
+ .map((post) => ({ label: scheduleLabel(post), value: sendItRequests.scheduleIdOf(post) ?? '' }))
+ .filter((option) => option.value !== ''),
};
- } catch {
+ } catch (error) {
return {
disabled: true,
options: [],
- placeholder: 'Failed to load scheduled posts. Check your API key.',
+ placeholder: `Failed to load scheduled posts: ${error instanceof Error ? error.message : String(error)}`.slice(0, 300),
};
}
},
@@ -191,6 +162,25 @@ export const platformFilterProperty = Property.StaticDropdown({
'Only return scheduled posts for a specific platform. Leave empty to see all platforms.',
required: false,
options: {
- options,
+ options: platformOptions,
},
});
+
+export const singlePlatformProperty = Property.StaticDropdown({
+ displayName: 'Platform',
+ required: true,
+ options: {
+ options: platformOptions,
+ },
+});
+
+export const sendItPlatformValues = platformOptions.map((option) => option.value);
+
+function scheduleLabel(post: Record<string, unknown>): string {
+ const platforms = Array.isArray(post['platforms']) ? post['platforms'].map(String).join(', ') : String(post['platform'] ?? 'Unknown');
+ const content = post['content'];
+ const rawText = content !== null && typeof content === 'object' && 'text' in content ? String(content.text ?? '') : '';
+ const snippet = rawText.length > 40 ? `${rawText.substring(0, 40)}…` : rawText || 'No text';
+ const time = typeof post['scheduledTime'] === 'string' && !Number.isNaN(Date.parse(post['scheduledTime'])) ? ` (${new Date(post['scheduledTime']).toISOString().replace('.000Z', 'Z')} UTC)` : '';
+ return `${platforms} — ${snippet}${time}`;
+}
diff --git a/packages/pieces/community/send-it/src/lib/common/requests.ts b/packages/pieces/community/send-it/src/lib/common/requests.ts
new file mode 100644
index 00000000000..ccf2e7f4cd0
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/common/requests.ts
@@ -0,0 +1,269 @@
+import crypto from 'crypto';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SendItRecord, isRecord, optionalText, pathId, readList, requireText, sendItApi } from './client';
+
+export function validateLimit({ value, label, max }: { value: unknown; label: string; max: number }): number | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const number = Number(value);
+ if (!Number.isInteger(number) || number < 1 || number > max) {
+ throw new Error(`${label} must be a whole number between 1 and ${max}.`);
+ }
+ return number;
+}
+
+export const sendItRequests = {
+ buildPost,
+ idempotencyKey,
+ futureIso,
+ publish,
+ schedule,
+ validate,
+ listAccounts,
+ listScheduled,
+ getScheduled,
+ cancel,
+ triggerNow,
+ requirements,
+ analytics,
+ listDeadLetter,
+ scheduleIdOf,
+};
+
+const MEDIA_REQUIRED_PLATFORMS = ['instagram', 'instagram-standalone', 'pinterest', 'youtube', 'tiktok'];
+
+const MAX_IDEMPOTENCY_KEY = 255;
+
+const SCHEDULE_SLACK_MS = 60_000;
+
+function normalizePlatforms(value: unknown): string[] {
+ const raw = Array.isArray(value) ? value.flat() : typeof value === 'string' ? value.split(',') : [];
+ const platforms = [...new Set(raw.map((item) => optionalText(item)?.toLowerCase()).filter((item): item is string => item !== undefined))];
+ if (platforms.length === 0) {
+ throw new Error('Select at least one platform.');
+ }
+ return platforms;
+}
+
+function httpsUrl({ value, label }: { value: string; label: string }): string {
+ let parsed: URL;
+ try {
+ parsed = new URL(value);
+ } catch {
+ throw new Error(`${label} "${value.slice(0, 200)}" is not a valid URL.`);
+ }
+ if (parsed.protocol !== 'https:') {
+ throw new Error(`${label} must be a public https:// URL.`);
+ }
+ return value;
+}
+
+function normalizeMediaUrls(value: unknown): string[] {
+ if (value === undefined || value === null || value === '') {
+ return [];
+ }
+ const raw = Array.isArray(value) ? value : typeof value === 'string' ? value.split(/[\n,]/) : [value];
+ const urls = raw
+ .map((item) => (isRecord(item) ? Object.values(item).find((inner) => typeof inner === 'string') : item))
+ .map((item) => optionalText(item))
+ .filter((item): item is string => item !== undefined);
+ return urls.map((url) => httpsUrl({ value: url, label: 'Media URL' }));
+}
+
+function parsePlatformSettings(value: unknown): SendItRecord | undefined {
+ if (value === undefined || value === null || value === '') {
+ return undefined;
+ }
+ const parsed: unknown = typeof value === 'string' ? JSON.parse(value) : value;
+ if (!isRecord(parsed)) {
+ throw new Error('Platform Settings must be a JSON object keyed by platform, e.g. {"pinterest": {"boardId": "123"}}.');
+ }
+ return Object.keys(parsed).length > 0 ? parsed : undefined;
+}
+
+function buildPost({ input, requireMedia = true }: { input: PostInput; requireMedia?: boolean }): { platforms: string[]; content: SendItRecord } {
+ const platforms = normalizePlatforms(input.platforms);
+ const text = requireText({ value: input.text, label: 'Post Text' });
+ const mediaUrl = optionalText(input.mediaUrl);
+ const mediaUrls = normalizeMediaUrls(input.mediaUrls);
+ const hasMedia = mediaUrl !== undefined || mediaUrls.length > 0;
+ const needsMedia = platforms.filter((platform) => MEDIA_REQUIRED_PLATFORMS.includes(platform));
+ if (requireMedia && !hasMedia && needsMedia.length > 0) {
+ throw new Error(`${needsMedia.join(', ')}: a Media URL (image or video) is required. Add one or remove these platforms.`);
+ }
+ const mediaType = optionalText(input.mediaType);
+ const content: SendItRecord = { text };
+ if (mediaUrl !== undefined) {
+ content['mediaUrl'] = httpsUrl({ value: mediaUrl, label: 'Media URL' });
+ }
+ if (mediaUrls.length > 0) {
+ content['mediaUrls'] = mediaUrls;
+ }
+ if (hasMedia && mediaType !== undefined) {
+ content['mediaType'] = mediaType;
+ }
+ const title = optionalText(input.title);
+ if (title !== undefined) {
+ content['title'] = title;
+ }
+ const firstComment = optionalText(input.firstComment);
+ if (firstComment !== undefined) {
+ content['firstComment'] = firstComment;
+ }
+ const platformSettings = parsePlatformSettings(input.platformSettings);
+ if (platformSettings !== undefined) {
+ content['platformSettings'] = platformSettings;
+ }
+ return { platforms, content };
+}
+
+function canonical(value: unknown): string {
+ if (Array.isArray(value)) {
+ return `[${value.map(canonical).join(',')}]`;
+ }
+ if (value !== null && typeof value === 'object') {
+ const entries = Object.entries(value)
+ .filter((entry) => entry[1] !== undefined)
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;
+ }
+ return JSON.stringify(value ?? null);
+}
+
+// The default key hashes the step input so each Loop iteration (same run + step, different post) gets its own key.
+function idempotencyKey({ override, runId, stepName, operation, input }: { override: unknown; runId: string; stepName: string; operation: string; input: unknown }): string {
+ const custom = optionalText(override);
+ if (custom !== undefined) {
+ return custom.slice(0, MAX_IDEMPOTENCY_KEY);
+ }
+ const digest = crypto.createHash('sha256').update(`${runId}|${stepName}|${operation}|${canonical(input)}`).digest('hex').slice(0, 40);
+ return `activepieces:${operation}:${digest}`.slice(0, MAX_IDEMPOTENCY_KEY);
+}
+
+function futureIso({ value, now = Date.now() }: { value: unknown; now?: number }): string {
+ const text = requireText({ value, label: 'Scheduled Time' });
+ const ms = Date.parse(text);
+ if (!/^\d{4}-\d{2}-\d{2}T/.test(text) || Number.isNaN(ms)) {
+ throw new Error('Scheduled Time must be an ISO-8601 date-time, e.g. 2026-01-31T09:00:00Z.');
+ }
+ if (ms < now - SCHEDULE_SLACK_MS) {
+ throw new Error(`Scheduled Time ${new Date(ms).toISOString()} is in the past. Pick a future time (UTC).`);
+ }
+ return new Date(ms).toISOString();
+}
+
+async function publish({ apiKey, input, key }: { apiKey: string; input: PostInput; key: string }): Promise<SendItRecord> {
+ const body = buildPost({ input });
+ const response = await sendItApi.request({ apiKey, method: HttpMethod.POST, path: '/publish', operation: 'publish post', body, headers: { 'Idempotency-Key': key } });
+ return withResultIds({ response, idempotencyKey: key });
+}
+
+async function schedule({ apiKey, input, scheduledTime, key }: { apiKey: string; input: PostInput; scheduledTime: unknown; key: string }): Promise<SendItRecord> {
+ const body = { ...buildPost({ input }), scheduledTime: futureIso({ value: scheduledTime }) };
+ const response = await sendItApi.request({ apiKey, method: HttpMethod.POST, path: '/schedule', operation: 'schedule post', body, headers: { 'Idempotency-Key': key } });
+ const record = isRecord(response) ? response : {};
+ const nested = isRecord(record['schedule']) ? record['schedule'] : isRecord(record['post']) ? record['post'] : {};
+ const scheduleId = optionalText(record['scheduleId']) ?? optionalText(record['id']) ?? optionalText(nested['scheduleId']) ?? optionalText(nested['id']) ?? null;
+ return { ...record, scheduleId, scheduledTime: record['scheduledTime'] ?? body.scheduledTime, idempotencyKey: key };
+}
+
+async function validate({ apiKey, input }: { apiKey: string; input: PostInput }): Promise<SendItRecord> {
+ const body = buildPost({ input, requireMedia: false });
+ return sendItApi.request({ apiKey, method: HttpMethod.POST, path: '/validate', operation: 'validate content', body });
+}
+
+async function listAccounts({ apiKey, limit }: { apiKey: string; limit?: number }): Promise<SendItRecord & { accounts: SendItRecord[]; count: number }> {
+ const response = await sendItApi.request({ apiKey, method: HttpMethod.GET, path: '/accounts', operation: 'list accounts', query: { limit } });
+ const accounts = readList({ body: response, key: 'accounts' });
+ return { ...(isRecord(response) ? response : {}), accounts, count: accounts.length };
+}
+
+async function listScheduled({ apiKey, platform }: { apiKey: string; platform?: string }): Promise<SendItRecord & { posts: SendItRecord[]; count: number }> {
+ const response = await sendItApi.request({ apiKey, method: HttpMethod.GET, path: '/scheduled', operation: 'list scheduled posts', query: { platform: optionalText(platform) } });
+ const posts = readList({ body: response, key: 'posts' });
+ return { ...(isRecord(response) ? response : {}), posts, count: posts.length };
+}
+
+async function getScheduled({ apiKey, scheduleId }: { apiKey: string; scheduleId: unknown }): Promise<SendItRecord> {
+ const id = requireText({ value: scheduleId, label: 'Schedule ID' });
+ const { posts } = await listScheduled({ apiKey });
+ const post = posts.find((item) => scheduleIdOf(item) === id);
+ if (post === undefined) {
+ throw new Error(`No pending scheduled post with ID "${id.slice(0, 100)}". It may have been published, cancelled or never existed; use List Scheduled Posts to see pending ones.`);
+ }
+ return post;
+}
+
+async function cancel({ apiKey, scheduleId }: { apiKey: string; scheduleId: unknown }): Promise<SendItRecord> {
+ const id = requireText({ value: scheduleId, label: 'Schedule ID' });
+ const response = await sendItApi.request({ apiKey, method: HttpMethod.DELETE, path: `/scheduled/${pathId({ value: id, label: 'Schedule ID' })}`, operation: 'cancel scheduled post' });
+ return { ...(isRecord(response) ? response : {}), scheduleId: id, cancelled: true };
+}
+
+async function triggerNow({ apiKey, scheduleId }: { apiKey: string; scheduleId: unknown }): Promise<SendItRecord> {
+ const id = requireText({ value: scheduleId, label: 'Schedule ID' });
+ const response = await sendItApi.request({ apiKey, method: HttpMethod.POST, path: `/scheduled/${pathId({ value: id, label: 'Schedule ID' })}/trigger`, operation: 'publish scheduled post now' });
+ return { ...withResultIds({ response }), scheduleId: id };
+}
+
+async function requirements({ apiKey, platform }: { apiKey: string; platform: unknown }): Promise<SendItRecord> {
+ const value = requireText({ value: platform, label: 'Platform' }).toLowerCase();
+ return sendItApi.request({ apiKey, method: HttpMethod.GET, path: '/requirements', operation: 'get platform requirements', query: { platform: value } });
+}
+
+async function analytics({ apiKey, platform, startDate, endDate, limit }: { apiKey: string; platform: unknown; startDate?: unknown; endDate?: unknown; limit?: number }): Promise<SendItRecord> {
+ const value = requireText({ value: platform, label: 'Platform' }).toLowerCase();
+ const response = await sendItApi.request({
+ apiKey,
+ method: HttpMethod.GET,
+ path: '/analytics',
+ operation: 'get post analytics',
+ query: { platform: value, startDate: dateOnly({ value: startDate, label: 'Start Date' }), endDate: dateOnly({ value: endDate, label: 'End Date' }), limit },
+ });
+ const posts = readList({ body: response, key: 'posts' });
+ return { ...(isRecord(response) ? response : {}), platform: value, posts, count: posts.length };
+}
+
+async function listDeadLetter({ apiKey, status, limit }: { apiKey: string; status?: string; limit?: number }): Promise<SendItRecord & { posts: SendItRecord[]; count: number }> {
+ const response = await sendItApi.request({ apiKey, method: HttpMethod.GET, path: '/dead-letter', operation: 'list failed posts', query: { status: optionalText(status), limit } });
+ const posts = readList({ body: response, key: 'posts' });
+ return { ...(isRecord(response) ? response : {}), posts, count: posts.length };
+}
+
+function dateOnly({ value, label }: { value: unknown; label: string }): string | undefined {
+ const text = optionalText(value);
+ if (text === undefined) {
+ return undefined;
+ }
+ const ms = Date.parse(text);
+ if (!/^\d{4}-\d{2}-\d{2}/.test(text) || Number.isNaN(ms)) {
+ throw new Error(`${label} must be an ISO-8601 date, e.g. 2026-01-31.`);
+ }
+ return new Date(ms).toISOString();
+}
+
+function scheduleIdOf(post: SendItRecord): string | undefined {
+ return optionalText(post['id']) ?? optionalText(post['scheduleId']);
+}
+
+function withResultIds({ response, idempotencyKey: key }: { response: unknown; idempotencyKey?: string }): SendItRecord {
+ const record = isRecord(response) ? response : {};
+ const results = Array.isArray(record['results']) ? record['results'].filter(isRecord) : [];
+ const out: SendItRecord = { ...record, results };
+ if (key !== undefined) {
+ out['idempotencyKey'] = key;
+ }
+ return out;
+}
+
+export type PostInput = {
+ platforms: unknown;
+ text: unknown;
+ mediaUrl?: unknown;
+ mediaUrls?: unknown;
+ mediaType?: unknown;
+ title?: unknown;
+ firstComment?: unknown;
+ platformSettings?: unknown;
+};
diff --git a/packages/pieces/community/send-it/src/lib/common/trigger-mappers.ts b/packages/pieces/community/send-it/src/lib/common/trigger-mappers.ts
new file mode 100644
index 00000000000..aca7d02ea1d
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/common/trigger-mappers.ts
@@ -0,0 +1,41 @@
+import { SendItRecord, isRecord } from './client';
+
+export const triggerMappers = { published, failed, scheduled };
+
+function dataOf(body: SendItRecord): SendItRecord {
+ return isRecord(body['data']) ? body['data'] : {};
+}
+
+function textOf(value: unknown): string | null {
+ return typeof value === 'string' ? value : null;
+}
+
+function base(body: SendItRecord): SendItRecord {
+ const content = dataOf(body)['content'];
+ return {
+ delivery_id: textOf(body['deliveryId']),
+ event: textOf(body['event']),
+ timestamp: textOf(body['timestamp']),
+ content_text: isRecord(content) ? textOf(content['text']) : null,
+ };
+}
+
+function published(body: SendItRecord): SendItRecord {
+ const data = dataOf(body);
+ return { ...base(body), platform: textOf(data['platform']), post_id: textOf(data['postId']), post_url: textOf(data['postUrl']), published_at: textOf(data['publishedAt']) };
+}
+
+function failed(body: SendItRecord): SendItRecord {
+ const data = dataOf(body);
+ return { ...base(body), platform: textOf(data['platform']), error: textOf(data['error']), failed_at: textOf(data['failedAt']) };
+}
+
+function scheduled(body: SendItRecord): SendItRecord {
+ const data = dataOf(body);
+ return {
+ ...base(body),
+ schedule_id: textOf(data['scheduleId']),
+ platforms: Array.isArray(data['platforms']) ? data['platforms'].map(String).join(', ') : null,
+ scheduled_time: textOf(data['scheduledTime']),
+ };
+}
diff --git a/packages/pieces/community/send-it/src/lib/common/webhook-trigger.ts b/packages/pieces/community/send-it/src/lib/common/webhook-trigger.ts
new file mode 100644
index 00000000000..46f4b016e48
--- /dev/null
+++ b/packages/pieces/community/send-it/src/lib/common/webhook-trigger.ts
@@ -0,0 +1,196 @@
+import { createHmac, timingSafeEqual } from 'node:crypto';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { DEDUPE_KEY_PROPERTY, Store, TriggerStrategy } from '@activepieces/pieces-framework';
+import { SendItRecord, apiKeyOf, isNotFound, isRecord, optionalText, sendItApi } from './client';
+
+export const sendItWebhook = { enable, disable, handle, verifySignature };
+
+export function sendItWebhookHooks({ event, sampleData, mapEvent }: SendItWebhookHooksParams) {
+ return {
+ type: TriggerStrategy.WEBHOOK,
+ async onEnable(context: { auth: unknown; store: Store; webhookUrl: string }): Promise<void> {
+ await enable({ apiKey: apiKeyOf(context.auth), store: context.store, event, webhookUrl: context.webhookUrl });
+ },
+ async onDisable(context: { auth: unknown; store: Store }): Promise<void> {
+ await disable({ apiKey: apiKeyOf(context.auth), store: context.store });
+ },
+ async run(context: { store: Store; payload: WebhookPayload }): Promise<unknown[]> {
+ return handle({ store: context.store, event, payload: context.payload, mapEvent });
+ },
+ async test(): Promise<unknown[]> {
+ return [sampleData];
+ },
+ } satisfies { type: TriggerStrategy.WEBHOOK } & Record<string, unknown>;
+}
+
+async function enable({ apiKey, store, event, webhookUrl }: { apiKey: string; store: Store; event: string; webhookUrl: string }): Promise<void> {
+ const response = await sendItApi.request({ apiKey, method: HttpMethod.POST, path: '/webhooks', operation: 'create webhook', body: { url: webhookUrl, events: [event] } });
+ const webhook = isRecord(response) && isRecord(response['webhook']) ? response['webhook'] : {};
+ const webhookId = optionalText(webhook['id']);
+ const secret = optionalText(webhook['secret']);
+ if (webhookId === undefined || secret === undefined) {
+ if (webhookId !== undefined) {
+ await deleteWebhook({ apiKey, webhookId }).catch(() => undefined);
+ }
+ throw new Error('SendIt created the webhook but returned no webhook ID or signing secret.');
+ }
+ try {
+ await store.put(WEBHOOK_ID_KEY, webhookId);
+ await store.put(SECRET_KEY, secret);
+ } catch (error) {
+ await deleteWebhook({ apiKey, webhookId }).catch(() => undefined);
+ throw error;
+ }
+}
+
+async function disable({ apiKey, store }: { apiKey: string; store: Store }): Promise<void> {
+ const webhookId = optionalText(await store.get<string>(WEBHOOK_ID_KEY));
+ if (webhookId !== undefined) {
+ await deleteWebhook({ apiKey, webhookId });
+ }
+ await store.delete(WEBHOOK_ID_KEY);
+ await store.delete(SECRET_KEY);
+ await store.delete(SEEN_KEY);
+ const index = await readSeenIndex({ store });
+ for (let start = 0; start < index.length; start += SEEN_PRUNE_PER_EVENT) {
+ await Promise.all(index.slice(start, start + SEEN_PRUNE_PER_EVENT).map((entry) => store.delete(`${SEEN_KEY_PREFIX}${entry.id}`)));
+ }
+ await store.delete(SEEN_INDEX_KEY);
+}
+
+async function deleteWebhook({ apiKey, webhookId }: { apiKey: string; webhookId: string }): Promise<void> {
+ try {
+ await sendItApi.request({ apiKey, method: HttpMethod.DELETE, path: `/webhooks/${encodeURIComponent(webhookId)}`, operation: 'delete webhook' });
+ } catch (error) {
+ if (!isNotFound(error)) {
+ throw error;
+ }
+ }
+}
+
+async function handle({
+ store,
+ event,
+ payload,
+ mapEvent,
+ now = Date.now(),
+}: {
+ store: Store;
+ event: string;
+ payload: WebhookPayload;
+ mapEvent: (body: SendItRecord) => SendItRecord;
+ now?: number;
+}): Promise<unknown[]> {
+ const body = payload.body;
+ if (!isRecord(body) || body['event'] !== event) {
+ return [];
+ }
+ const secret = optionalText(await store.get<string>(SECRET_KEY));
+ if (secret === undefined) {
+ const webhookId = optionalText(await store.get<string>(WEBHOOK_ID_KEY));
+ if (webhookId === undefined) {
+ return [];
+ }
+ } else if (!verifySignature({ secret, header: headerOf({ headers: payload.headers, name: 'x-sendit-signature' }), rawBody: rawBodyText(payload.rawBody), now })) {
+ return [];
+ }
+ const deliveryId = optionalText(body['deliveryId']);
+ if (deliveryId !== undefined) {
+ const markerKey = `${SEEN_KEY_PREFIX}${deliveryId}`;
+ const legacy = await store.get<string[]>(SEEN_KEY);
+ if ((await store.get<number>(markerKey)) !== null || (Array.isArray(legacy) && legacy.includes(deliveryId))) {
+ return [];
+ }
+ await store.put(markerKey, now);
+ await pruneSeenMarkers({ store, added: { id: deliveryId, at: now }, now });
+ }
+ const mapped = mapEvent(body);
+ return [deliveryId === undefined ? mapped : { ...mapped, [DEDUPE_KEY_PROPERTY]: `sendit:${deliveryId}` }];
+}
+
+async function readSeenIndex({ store }: { store: Store }): Promise<SeenIndexEntry[]> {
+ const stored = await store.get<unknown>(SEEN_INDEX_KEY);
+ if (!Array.isArray(stored)) {
+ return [];
+ }
+ return stored.filter((entry): entry is SeenIndexEntry => isRecord(entry) && typeof entry['id'] === 'string' && typeof entry['at'] === 'number');
+}
+
+async function pruneSeenMarkers({ store, added, now }: { store: Store; added: SeenIndexEntry; now: number }): Promise<void> {
+ const cutoff = now - SEEN_RETENTION_MS;
+ const index = (await readSeenIndex({ store })).filter((entry) => entry.id !== added.id);
+ const expired = index.filter((entry) => entry.at < cutoff).slice(0, SEEN_PRUNE_PER_EVENT);
+ const expiredIds = new Set(expired.map((entry) => entry.id));
+ await Promise.all(expired.map((entry) => store.delete(`${SEEN_KEY_PREFIX}${entry.id}`)));
+ const remaining = index.filter((entry) => !expiredIds.has(entry.id));
+ await store.put(SEEN_INDEX_KEY, remaining.length < SEEN_INDEX_LIMIT ? [...remaining, added] : remaining);
+}
+
+function verifySignature({ secret, header, rawBody, now }: { secret: string; header: string | undefined; rawBody: string | undefined; now: number }): boolean {
+ if (header === undefined || rawBody === undefined) {
+ return false;
+ }
+ const parts = header.split(',').map((part) => part.trim());
+ const timestamp = parts.find((part) => part.startsWith('t='))?.slice(2);
+ const signatures = parts.filter((part) => part.startsWith('v1=')).map((part) => part.slice(3));
+ if (timestamp === undefined || !/^\d+$/.test(timestamp) || signatures.length === 0) {
+ return false;
+ }
+ if (Math.abs(Math.floor(now / 1000) - Number(timestamp)) > SIGNATURE_TOLERANCE_SECONDS) {
+ return false;
+ }
+ const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest();
+ return signatures.some((signature) => {
+ if (!/^[0-9a-f]+$/i.test(signature)) {
+ return false;
+ }
+ const given = Buffer.from(signature, 'hex');
+ return given.length === expected.length && timingSafeEqual(given, expected);
+ });
+}
+
+function headerOf({ headers, name }: { headers: unknown; name: string }): string | undefined {
+ if (!isRecord(headers)) {
+ return undefined;
+ }
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
+ const value = entry?.[1];
+ return optionalText(Array.isArray(value) ? value[0] : value);
+}
+
+function rawBodyText(rawBody: unknown): string | undefined {
+ if (typeof rawBody === 'string') {
+ return rawBody;
+ }
+ if (Buffer.isBuffer(rawBody)) {
+ return rawBody.toString('utf8');
+ }
+ if (isRecord(rawBody) && rawBody['type'] === 'Buffer' && Array.isArray(rawBody['data'])) {
+ return Buffer.from(rawBody['data'].map(Number)).toString('utf8');
+ }
+ return undefined;
+}
+
+
+const SIGNATURE_TOLERANCE_SECONDS = 900;
+
+const WEBHOOK_ID_KEY = 'webhookId';
+
+const SECRET_KEY = 'webhookSecret';
+
+const SEEN_KEY = 'seenDeliveryIds';
+const SEEN_KEY_PREFIX = 'seenDelivery:';
+const SEEN_INDEX_KEY = 'seenDeliveryIndex';
+const SEEN_INDEX_LIMIT = 5000;
+const SEEN_PRUNE_PER_EVENT = 25;
+const SEEN_RETENTION_MS = 2 * SIGNATURE_TOLERANCE_SECONDS * 1000;
+
+export type WebhookPayload = { body: unknown; headers?: unknown; rawBody?: unknown };
+
+export type SendItWebhookHooksParams = {
+ event: string;
+ sampleData: SendItRecord;
+ mapEvent: (body: SendItRecord) => SendItRecord;
+};
+
+type SeenIndexEntry = { id: string; at: number };
diff --git a/packages/pieces/community/send-it/src/lib/triggers/post-failed.ts b/packages/pieces/community/send-it/src/lib/triggers/post-failed.ts
index 122f355937c..15f57c6f64f 100644
--- a/packages/pieces/community/send-it/src/lib/triggers/post-failed.ts
+++ b/packages/pieces/community/send-it/src/lib/triggers/post-failed.ts
@@ -1,76 +1,31 @@
-import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { sendItAuth } from '../auth';
-import { sendItRequest } from '../common';
+import { createTrigger } from '@activepieces/pieces-framework';
+import { sendItAuth } from '../common/auth';
+import { sendItWebhookHooks } from '../common/webhook-trigger';
+import { sendItOutputSchemas } from '../common/output-schemas';
+import { triggerMappers } from '../common/trigger-mappers';
-type FailedPayload = {
- deliveryId?: string;
- event?: string;
- timestamp?: string;
- data?: {
- platform?: string;
- content?: { text?: string };
- error?: string;
- failedAt?: string;
- };
+export const postFailedSampleData = {
+ delivery_id: 'dlv_sample789',
+ event: 'post.failed',
+ timestamp: '2026-01-15T10:05:00.000Z',
+ content_text: 'Check this out!',
+ platform: 'instagram',
+ error: 'Media URL is not accessible',
+ failed_at: '2026-01-15T10:05:00Z',
};
export const postFailed = createTrigger({
auth: sendItAuth,
name: 'post_failed',
- classification: 'READ',
displayName: 'Post Failed',
description: 'Triggers when a post fails to publish to a platform',
+ classification: 'READ',
aiMetadata: {
description:
- 'Fires when SendIt fails to publish a post to a connected social platform, representing a failed publication attempt. Each event carries the platform, the post content, and an error message describing why it failed.',
+ 'Fires when SendIt fails to publish a post to a connected social platform, representing a failed publication attempt. Each event carries the platform, the post content, and an error message describing why it failed. Deliveries are verified with the X-SendIt-Signature header and deduplicated by delivery ID.',
},
props: {},
- type: TriggerStrategy.WEBHOOK,
- async onEnable(context) {
- const response = (await sendItRequest(
- context.auth.secret_text,
- HttpMethod.POST,
- '/webhooks',
- {
- url: context.webhookUrl,
- events: ['post.failed'],
- }
- )) as { webhook: { id: string; secret: string } };
-
- await context.store.put('webhookId', response.webhook.id);
- },
- async onDisable(context) {
- const webhookId = await context.store.get<string>('webhookId');
- if (webhookId) {
- await sendItRequest(
- context.auth.secret_text,
- HttpMethod.DELETE,
- `/webhooks/${webhookId}`
- );
- }
- },
- async run(context) {
- const payload = context.payload.body as FailedPayload;
- return [
- {
- delivery_id: payload.deliveryId ?? null,
- event: payload.event ?? null,
- timestamp: payload.timestamp ?? null,
- platform: payload.data?.platform ?? null,
- content_text: payload.data?.content?.text ?? null,
- error: payload.data?.error ?? null,
- failed_at: payload.data?.failedAt ?? null,
- },
- ];
- },
- sampleData: {
- delivery_id: 'dlv_sample789',
- event: 'post.failed',
- timestamp: '2025-01-14T12:00:00.000Z',
- platform: 'instagram',
- content_text: 'Failed post content',
- error: 'Instagram API rate limit exceeded',
- failed_at: '2025-01-14T12:00:00.000Z',
- },
+ outputSchema: sendItOutputSchemas.postFailedEvent,
+ sampleData: postFailedSampleData,
+ ...sendItWebhookHooks({ event: 'post.failed', sampleData: postFailedSampleData, mapEvent: triggerMappers.failed }),
});
diff --git a/packages/pieces/community/send-it/src/lib/triggers/post-published.ts b/packages/pieces/community/send-it/src/lib/triggers/post-published.ts
index 1c37292f04a..a9993407fc4 100644
--- a/packages/pieces/community/send-it/src/lib/triggers/post-published.ts
+++ b/packages/pieces/community/send-it/src/lib/triggers/post-published.ts
@@ -1,79 +1,32 @@
-import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { sendItAuth } from '../auth';
-import { sendItRequest } from '../common';
+import { createTrigger } from '@activepieces/pieces-framework';
+import { sendItAuth } from '../common/auth';
+import { sendItWebhookHooks } from '../common/webhook-trigger';
+import { sendItOutputSchemas } from '../common/output-schemas';
+import { triggerMappers } from '../common/trigger-mappers';
-type PublishedPayload = {
- deliveryId?: string;
- event?: string;
- timestamp?: string;
- data?: {
- platform?: string;
- postId?: string;
- postUrl?: string;
- content?: { text?: string };
- publishedAt?: string;
- };
+export const postPublishedSampleData = {
+ delivery_id: 'dlv_sample123',
+ event: 'post.published',
+ timestamp: '2026-01-15T10:00:00.000Z',
+ content_text: 'Hello world!',
+ platform: 'linkedin',
+ post_id: 'urn:li:share:12345',
+ post_url: 'https://www.linkedin.com/feed/update/urn:li:share:12345',
+ published_at: '2026-01-15T10:00:00Z',
};
export const postPublished = createTrigger({
auth: sendItAuth,
name: 'post_published',
- classification: 'READ',
displayName: 'Post Published',
description: 'Triggers when a post is successfully published to a platform',
+ classification: 'READ',
aiMetadata: {
description:
- 'Fires when SendIt successfully publishes a post to a connected social platform, representing a completed publication. Each event carries the platform, post ID, post URL, and content of the published post.',
+ 'Fires when SendIt successfully publishes a post to a connected social platform, representing a completed publication. Each event carries the platform, post ID, post URL, and content of the published post. Deliveries are verified with the X-SendIt-Signature header and deduplicated by delivery ID.',
},
props: {},
- type: TriggerStrategy.WEBHOOK,
- async onEnable(context) {
- const response = (await sendItRequest(
- context.auth.secret_text,
- HttpMethod.POST,
- '/webhooks',
- {
- url: context.webhookUrl,
- events: ['post.published'],
- }
- )) as { webhook: { id: string; secret: string } };
-
- await context.store.put('webhookId', response.webhook.id);
- },
- async onDisable(context) {
- const webhookId = await context.store.get<string>('webhookId');
- if (webhookId) {
- await sendItRequest(
- context.auth.secret_text,
- HttpMethod.DELETE,
- `/webhooks/${webhookId}`
- );
- }
- },
- async run(context) {
- const payload = context.payload.body as PublishedPayload;
- return [
- {
- delivery_id: payload.deliveryId ?? null,
- event: payload.event ?? null,
- timestamp: payload.timestamp ?? null,
- platform: payload.data?.platform ?? null,
- post_id: payload.data?.postId ?? null,
- post_url: payload.data?.postUrl ?? null,
- content_text: payload.data?.content?.text ?? null,
- published_at: payload.data?.publishedAt ?? null,
- },
- ];
- },
- sampleData: {
- delivery_id: 'dlv_sample123',
- event: 'post.published',
- timestamp: '2025-01-14T12:00:00.000Z',
- platform: 'linkedin',
- post_id: 'urn:li:share:1234567890',
- post_url: 'https://www.linkedin.com/feed/update/urn:li:share:1234567890',
- content_text: 'Sample post content',
- published_at: '2025-01-14T12:00:00.000Z',
- },
+ outputSchema: sendItOutputSchemas.postPublishedEvent,
+ sampleData: postPublishedSampleData,
+ ...sendItWebhookHooks({ event: 'post.published', sampleData: postPublishedSampleData, mapEvent: triggerMappers.published }),
});
diff --git a/packages/pieces/community/send-it/src/lib/triggers/post-scheduled.ts b/packages/pieces/community/send-it/src/lib/triggers/post-scheduled.ts
index bdf517d6004..8bfe73a86a6 100644
--- a/packages/pieces/community/send-it/src/lib/triggers/post-scheduled.ts
+++ b/packages/pieces/community/send-it/src/lib/triggers/post-scheduled.ts
@@ -1,78 +1,31 @@
-import { createTrigger, TriggerStrategy } from '@activepieces/pieces-framework';
-import { HttpMethod } from '@activepieces/pieces-common';
-import { sendItAuth } from '../auth';
-import { sendItRequest } from '../common';
+import { createTrigger } from '@activepieces/pieces-framework';
+import { sendItAuth } from '../common/auth';
+import { sendItWebhookHooks } from '../common/webhook-trigger';
+import { sendItOutputSchemas } from '../common/output-schemas';
+import { triggerMappers } from '../common/trigger-mappers';
-type ScheduledPayload = {
- deliveryId?: string;
- event?: string;
- timestamp?: string;
- data?: {
- scheduleId?: string;
- platforms?: string[];
- content?: { text?: string };
- scheduledTime?: string;
- };
+export const postScheduledSampleData = {
+ delivery_id: 'dlv_sample456',
+ event: 'post.scheduled',
+ timestamp: '2026-01-15T10:00:00.000Z',
+ content_text: 'Launching soon!',
+ schedule_id: 'sched_abc123',
+ platforms: 'linkedin, x',
+ scheduled_time: '2026-01-20T14:00:00Z',
};
export const postScheduled = createTrigger({
auth: sendItAuth,
name: 'post_scheduled',
- classification: 'READ',
displayName: 'Post Scheduled',
description: 'Triggers when a post is scheduled for future publishing',
+ classification: 'READ',
aiMetadata: {
description:
- 'Fires when a post is queued in SendIt for future publishing, representing a newly created schedule. Each event carries the schedule ID, target platforms, content, and the scheduled publish time.',
+ 'Fires when a post is queued in SendIt for future publishing, representing a newly created schedule. Each event carries the schedule ID, target platforms (comma-separated), content, and the scheduled publish time. Deliveries are verified with the X-SendIt-Signature header and deduplicated by delivery ID.',
},
props: {},
- type: TriggerStrategy.WEBHOOK,
- async onEnable(context) {
- const response = (await sendItRequest(
- context.auth.secret_text,
- HttpMethod.POST,
- '/webhooks',
- {
- url: context.webhookUrl,
- events: ['post.scheduled'],
- }
- )) as { webhook: { id: string; secret: string } };
-
- await context.store.put('webhookId', response.webhook.id);
- },
- async onDisable(context) {
- const webhookId = await context.store.get<string>('webhookId');
- if (webhookId) {
- await sendItRequest(
- context.auth.secret_text,
- HttpMethod.DELETE,
- `/webhooks/${webhookId}`
- );
- }
- },
- async run(context) {
- const payload = context.payload.body as ScheduledPayload;
- return [
- {
- delivery_id: payload.deliveryId ?? null,
- event: payload.event ?? null,
- timestamp: payload.timestamp ?? null,
- schedule_id: payload.data?.scheduleId ?? null,
- platforms: Array.isArray(payload.data?.platforms)
- ? payload.data.platforms.join(', ')
- : null,
- content_text: payload.data?.content?.text ?? null,
- scheduled_time: payload.data?.scheduledTime ?? null,
- },
- ];
- },
- sampleData: {
- delivery_id: 'dlv_sample456',
- event: 'post.scheduled',
- timestamp: '2025-01-14T12:00:00.000Z',
- schedule_id: 'sch_abc123',
- platforms: 'linkedin, instagram',
- content_text: 'Scheduled post content',
- scheduled_time: '2025-01-15T12:00:00.000Z',
- },
+ outputSchema: sendItOutputSchemas.postScheduledEvent,
+ sampleData: postScheduledSampleData,
+ ...sendItWebhookHooks({ event: 'post.scheduled', sampleData: postScheduledSampleData, mapEvent: triggerMappers.scheduled }),
});
diff --git a/packages/pieces/community/send-it/test/client.test.ts b/packages/pieces/community/send-it/test/client.test.ts
new file mode 100644
index 00000000000..ac8aeb4e43f
--- /dev/null
+++ b/packages/pieces/community/send-it/test/client.test.ts
@@ -0,0 +1,67 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { SendItApiError, sendItApi } from '../src/lib/common/client';
+import { sendItAuth } from '../src/lib/common/auth';
+import { API_KEY, TEST_SERVER, replies, stubFetch } from './helpers';
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('sendit client', () => {
+ test('sends the trimmed bearer key to the fixed v1 base with a verified-TLS dispatcher', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }]));
+ await sendItApi.request({ apiKey: ` ${API_KEY} `, method: HttpMethod.GET, path: '/accounts', operation: 'list' });
+ expect(seen[0].url).toBe('https://sendit.infiniteappsai.com/api/v1/accounts');
+ expect(seen[0].headers.get('authorization')).toBe(`Bearer ${API_KEY}`);
+ expect(seen[0].hasDispatcher).toBe(true);
+ });
+
+ test('refuses absolute or traversal paths', async () => {
+ await expect(sendItApi.request({ apiKey: API_KEY, method: HttpMethod.GET, path: '//evil.io/x', operation: 'x' })).rejects.toThrow('relative');
+ await expect(sendItApi.request({ apiKey: API_KEY, method: HttpMethod.GET, path: '/../x', operation: 'x' })).rejects.toThrow('relative');
+ });
+
+ test('keeps the vendor error text and status, without a body field', async () => {
+ stubFetch(replies([{ status: 404, body: { success: false, error: 'Scheduled post not found: sched_x' } }]));
+ const error = await sendItApi.request({ apiKey: API_KEY, method: HttpMethod.DELETE, path: '/scheduled/sched_x', operation: 'cancel' }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(SendItApiError);
+ expect(Reflect.get(Object(error), 'status')).toBe(404);
+ expect(String(Reflect.get(Object(error), 'message'))).toContain('Scheduled post not found: sched_x');
+ expect(Reflect.has(Object(error), 'body')).toBe(false);
+ });
+
+ test('reads errors[] arrays and nested error.message', async () => {
+ stubFetch(replies([{ status: 400, body: { success: false, errors: ['first problem'] } }]));
+ await expect(sendItApi.request({ apiKey: API_KEY, method: HttpMethod.POST, path: '/x', operation: 'x' })).rejects.toThrow('first problem');
+ });
+
+ test('retries 429 twice (10 s, 20 s) then fails', async () => {
+ const seen = stubFetch(replies([{ status: 429, body: { error: 'slow down' } }]));
+ const waits: number[] = [];
+ const error = await sendItApi.request({ apiKey: API_KEY, method: HttpMethod.GET, path: '/accounts', operation: 'list', wait: async (ms) => { waits.push(ms); } }).catch((e: unknown) => e);
+ expect(seen).toHaveLength(3);
+ expect(waits).toEqual([10_000, 20_000]);
+ expect(error).toBeInstanceOf(SendItApiError);
+ });
+
+});
+
+describe('auth validate', () => {
+ test('401 is invalid key', async () => {
+ stubFetch(replies([{ status: 401, body: { error: 'Unauthorized' } }]));
+ const result = await sendItAuth.validate?.({ auth: 'sk_live_bad', server: TEST_SERVER });
+ expect(result).toEqual({ valid: false, error: expect.stringContaining('Invalid API key') });
+ });
+
+ test('500 is reported as unreachable, not invalid', async () => {
+ stubFetch(replies([{ status: 500, body: { error: 'boom' } }]));
+ const result = await sendItAuth.validate?.({ auth: 'sk_live_ok', server: TEST_SERVER });
+ expect(result).toEqual({ valid: false, error: expect.stringContaining('Could not reach SendIt') });
+ });
+
+ test('200 is valid', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, accounts: [] } }]));
+ const result = await sendItAuth.validate?.({ auth: ' sk_live_ok ', server: TEST_SERVER });
+ expect(result).toEqual({ valid: true });
+ expect(seen[0].headers.get('authorization')).toBe('Bearer sk_live_ok');
+ });
+});
diff --git a/packages/pieces/community/send-it/test/helpers.ts b/packages/pieces/community/send-it/test/helpers.ts
new file mode 100644
index 00000000000..1b60e15b613
--- /dev/null
+++ b/packages/pieces/community/send-it/test/helpers.ts
@@ -0,0 +1,57 @@
+import { Store } from '@activepieces/pieces-framework';
+import { vi } from 'vitest';
+
+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 & { dispatcher?: unknown }) => {
+ 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,
+ query: parsed.searchParams,
+ headers,
+ body: rawBody ? JSON.parse(rawBody) : null,
+ hasDispatcher: init?.dispatcher !== undefined,
+ };
+ seen.push(request);
+ const reply = respond(request, seen.length - 1);
+ const status = reply.status ?? 200;
+ return new Response(status === 204 ? null : JSON.stringify(reply.body ?? {}), { status, headers: { 'content-type': '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 function memoryStore(initial: Record<string, unknown> = {}): Store & { data: Map<string, unknown> } {
+ const data = new Map<string, unknown>(Object.entries(initial));
+ return {
+ data,
+ async put<T>(key: string, value: T): Promise<T> {
+ data.set(key, value);
+ return value;
+ },
+ async get<T>(key: string): Promise<T | null> {
+ return data.has(key) ? JSON.parse(JSON.stringify(data.get(key))) : null;
+ },
+ async delete(key: string): Promise<void> {
+ data.delete(key);
+ },
+ };
+}
+
+export const API_KEY = 'sk_live_test';
+
+export const TEST_SERVER = { apiUrl: '', publicUrl: '', mintOidcToken: async (): Promise<string> => '' };
+
+export type SeenRequest = { url: string; method: string; path: string; query: URLSearchParams; headers: Headers; body: unknown; hasDispatcher: boolean };
+export type FakeReply = { status?: number; body?: unknown; headers?: Record<string, string> };
diff --git a/packages/pieces/community/send-it/test/metadata.test.ts b/packages/pieces/community/send-it/test/metadata.test.ts
new file mode 100644
index 00000000000..cd9379eb443
--- /dev/null
+++ b/packages/pieces/community/send-it/test/metadata.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, test } from 'vitest';
+import { sendIt } from '../src/index';
+
+describe('piece metadata', () => {
+ const actions = Object.values(sendIt.actions());
+ const triggers = Object.values(sendIt.triggers());
+
+ test('every action except Custom API Call has an outputSchema and aiMetadata', () => {
+ for (const action of actions.filter((a) => a.name !== 'custom_api_call')) {
+ expect(action.outputSchema, action.name).toBeDefined();
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ }
+ });
+
+ test('every trigger has an outputSchema', () => {
+ for (const trigger of triggers) {
+ expect(trigger.outputSchema, trigger.name).toBeDefined();
+ }
+ });
+
+ test('audiences: dropdown actions are human, their twins are ai', () => {
+ const audience = Object.fromEntries(actions.map((a) => [a.name, a.audience]));
+ expect(audience).toMatchObject({
+ cancel_scheduled_post: 'human',
+ trigger_scheduled_post: 'human',
+ cancel_scheduled_post_by_id: 'ai',
+ publish_scheduled_post_now: 'ai',
+ get_scheduled_post: 'ai',
+ get_platform_requirements: 'ai',
+ publish_post: 'both',
+ schedule_post: 'both',
+ validate_content: 'both',
+ list_accounts: 'both',
+ list_scheduled_posts: 'both',
+ get_post_analytics: 'both',
+ list_failed_posts: 'both',
+ });
+ });
+
+ test('ai-visible actions take no dropdown props', () => {
+ for (const action of actions.filter((a) => a.audience !== 'human')) {
+ for (const [key, prop] of Object.entries(action.props)) {
+ const type = typeof prop === 'object' && prop !== null && 'type' in prop ? prop.type : undefined;
+ expect(type, `${action.name}.${key}`).not.toBe('DROPDOWN');
+ }
+ }
+ });
+});
diff --git a/packages/pieces/community/send-it/test/requests.test.ts b/packages/pieces/community/send-it/test/requests.test.ts
new file mode 100644
index 00000000000..e67f6346591
--- /dev/null
+++ b/packages/pieces/community/send-it/test/requests.test.ts
@@ -0,0 +1,116 @@
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { sendItRequests } from '../src/lib/common/requests';
+import { API_KEY, replies, stubFetch } from './helpers';
+
+afterEach(() => vi.unstubAllGlobals());
+
+const future = new Date(Date.now() + 86_400_000).toISOString();
+
+describe('post building', () => {
+ test('sends only set content fields, normalises platforms and media URLs', () => {
+ const body = sendItRequests.buildPost({ input: { platforms: ['X', 'x', 'threads'], text: ' hi ', mediaUrls: [{ url: 'https://a.io/1.png' }, 'https://a.io/2.png'], mediaType: 'image', firstComment: 'c', platformSettings: '{"threads":{"a":1}}' } });
+ expect(body).toEqual({ platforms: ['x', 'threads'], content: { text: 'hi', mediaUrls: ['https://a.io/1.png', 'https://a.io/2.png'], mediaType: 'image', firstComment: 'c', platformSettings: { threads: { a: 1 } } } });
+ });
+
+ test('drops mediaType without media', () => {
+ expect(sendItRequests.buildPost({ input: { platforms: ['x'], text: 'hi', mediaType: 'auto' } }).content).toEqual({ text: 'hi' });
+ });
+
+ test('requires media for instagram, pinterest, tiktok, youtube', () => {
+ expect(() => sendItRequests.buildPost({ input: { platforms: ['instagram'], text: 'hi' } })).toThrow('a Media URL (image or video) is required');
+ expect(sendItRequests.buildPost({ input: { platforms: ['instagram'], text: 'hi' }, requireMedia: false }).platforms).toEqual(['instagram']);
+ });
+
+ test('rejects non-https media, empty platforms and empty text', () => {
+ expect(() => sendItRequests.buildPost({ input: { platforms: ['x'], text: 'hi', mediaUrl: 'http://a.io/x.png' } })).toThrow('https');
+ expect(() => sendItRequests.buildPost({ input: { platforms: [], text: 'hi' } })).toThrow('at least one platform');
+ expect(() => sendItRequests.buildPost({ input: { platforms: ['x'], text: ' ' } })).toThrow('Post Text is required');
+ });
+
+ test('rejects non-object platform settings', () => {
+ expect(() => sendItRequests.buildPost({ input: { platforms: ['x'], text: 'hi', platformSettings: '[1]' } })).toThrow('JSON object');
+ });
+
+ test('scheduled time must be ISO and in the future', () => {
+ expect(() => sendItRequests.futureIso({ value: 'tomorrow' })).toThrow('ISO-8601');
+ expect(() => sendItRequests.futureIso({ value: '2020-01-01T00:00:00Z' })).toThrow('in the past');
+ expect(sendItRequests.futureIso({ value: future })).toBe(future);
+ });
+
+ test('idempotency key defaults to run + step and honours an override', () => {
+ const a = sendItRequests.idempotencyKey({ override: undefined, runId: 'run1', stepName: 'step_2', operation: 'publish', input: { text: 'a', platforms: ['x'] } });
+ const aAgain = sendItRequests.idempotencyKey({ override: undefined, runId: 'run1', stepName: 'step_2', operation: 'publish', input: { platforms: ['x'], text: 'a' } });
+ const b = sendItRequests.idempotencyKey({ override: undefined, runId: 'run1', stepName: 'step_2', operation: 'publish', input: { text: 'b', platforms: ['x'] } });
+ expect(a).toMatch(/^activepieces:publish:[0-9a-f]{40}$/);
+ expect(aAgain).toBe(a);
+ expect(b).not.toBe(a);
+ expect(sendItRequests.idempotencyKey({ override: ' mine ', runId: 'run1', stepName: 'step_2', operation: 'publish', input: {} })).toBe('mine');
+ });
+});
+
+describe('requests', () => {
+ test('publish sends Idempotency-Key and returns results', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, results: [{ platform: 'bluesky', postUrl: 'https://bsky.app/profile/did:plc:a/post/1', postType: 'text', platformPostId: 'at://did:plc:a/app.bsky.feed.post/1' }], errors: [], errorDetails: [] } }]));
+ const out = await sendItRequests.publish({ apiKey: API_KEY, input: { platforms: ['x'], text: 'hi' }, key: 'k1' });
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].path).toBe('/api/v1/publish');
+ expect(seen[0].headers.get('idempotency-key')).toBe('k1');
+ expect(seen[0].body).toEqual({ platforms: ['x'], content: { text: 'hi' } });
+ expect(out['results']).toHaveLength(1);
+ expect(out['idempotencyKey']).toBe('k1');
+ });
+
+ test('schedule returns a scheduleId from either shape', async () => {
+ stubFetch(replies([{ body: { success: true, scheduleId: 'sched_1' } }, { body: { success: true, schedule: { id: 'sched_2' } } }]));
+ expect((await sendItRequests.schedule({ apiKey: API_KEY, input: { platforms: ['x'], text: 'hi' }, scheduledTime: future, key: 'k' }))['scheduleId']).toBe('sched_1');
+ expect((await sendItRequests.schedule({ apiKey: API_KEY, input: { platforms: ['x'], text: 'hi' }, scheduledTime: future, key: 'k' }))['scheduleId']).toBe('sched_2');
+ });
+
+ test('cancel encodes the ID and DELETEs', async () => {
+ const seen = stubFetch(replies([{ body: { success: true } }]));
+ const out = await sendItRequests.cancel({ apiKey: API_KEY, scheduleId: 'a/b' });
+ expect(seen[0].method).toBe('DELETE');
+ expect(seen[0].url).toBe('https://sendit.infiniteappsai.com/api/v1/scheduled/a%2Fb');
+ expect(out).toMatchObject({ scheduleId: 'a/b', cancelled: true });
+ });
+
+ test('trigger now POSTs to /trigger', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, results: [] } }]));
+ await sendItRequests.triggerNow({ apiKey: API_KEY, scheduleId: 'sched_1' });
+ expect(seen[0].method).toBe('POST');
+ expect(seen[0].path).toBe('/api/v1/scheduled/sched_1/trigger');
+ });
+
+ test('get scheduled filters the list and fails clearly when missing', async () => {
+ stubFetch(replies([{ body: { success: true, posts: [{ id: 'sched_1', platforms: ['x'] }] } }]));
+ expect(await sendItRequests.getScheduled({ apiKey: API_KEY, scheduleId: 'sched_1' })).toMatchObject({ id: 'sched_1' });
+ await expect(sendItRequests.getScheduled({ apiKey: API_KEY, scheduleId: 'nope' })).rejects.toThrow('No pending scheduled post');
+ });
+
+ test('list accounts passes limit and counts', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, accounts: [{ id: 'acc_1' }] } }]));
+ expect(await sendItRequests.listAccounts({ apiKey: API_KEY, limit: 5 })).toEqual({ success: true, accounts: [{ id: 'acc_1' }], count: 1 });
+ expect(seen[0].query.get('limit')).toBe('5');
+ });
+
+ test('list scheduled keeps the SendIt response fields and adds count', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, total: 1, posts: [{ id: 'sched_1' }] } }]));
+ expect(await sendItRequests.listScheduled({ apiKey: API_KEY, platform: 'x' })).toEqual({ success: true, total: 1, posts: [{ id: 'sched_1' }], count: 1 });
+ expect(seen[0].query.get('platform')).toBe('x');
+ });
+
+ test('analytics requires a platform and lowercases it', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, platform: 'instagram', posts: [] } }]));
+ const out = await sendItRequests.analytics({ apiKey: API_KEY, platform: 'Instagram' });
+ expect(seen[0].query.get('platform')).toBe('instagram');
+ expect(out).toMatchObject({ platform: 'instagram', posts: [], count: 0 });
+ });
+
+ test('requirements and dead letter', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, platform: 'x', textLimit: 280 } }, { body: { success: true, posts: [] } }]));
+ expect(await sendItRequests.requirements({ apiKey: API_KEY, platform: 'X' })).toMatchObject({ textLimit: 280 });
+ expect(await sendItRequests.listDeadLetter({ apiKey: API_KEY, limit: 10 })).toEqual({ success: true, posts: [], count: 0 });
+ expect(seen[0].query.get('platform')).toBe('x');
+ expect(seen[1].query.get('limit')).toBe('10');
+ });
+});
diff --git a/packages/pieces/community/send-it/test/webhook.test.ts b/packages/pieces/community/send-it/test/webhook.test.ts
new file mode 100644
index 00000000000..c23b9647d3f
--- /dev/null
+++ b/packages/pieces/community/send-it/test/webhook.test.ts
@@ -0,0 +1,142 @@
+import { createHmac } from 'node:crypto';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { DEDUPE_KEY_PROPERTY } from '@activepieces/pieces-framework';
+import { sendItWebhook } from '../src/lib/common/webhook-trigger';
+import { triggerMappers } from '../src/lib/common/trigger-mappers';
+import { API_KEY, memoryStore, replies, stubFetch } from './helpers';
+
+afterEach(() => vi.unstubAllGlobals());
+
+const SECRET = 'whsec_test';
+const NOW = 1_800_000_000_000;
+const body = { deliveryId: 'dlv_1', event: 'post.published', timestamp: '2026-01-01T00:00:00Z', data: { platform: 'x', postId: '1', postUrl: 'https://x.com/1', content: { text: 'hi' }, publishedAt: '2026-01-01T00:00:00Z' } };
+const raw = JSON.stringify(body);
+
+function sign({ t = Math.floor(NOW / 1000), payload = raw, secret = SECRET } = {}): string {
+ return `t=${t},v1=${createHmac('sha256', secret).update(`${t}.${payload}`).digest('hex')}`;
+}
+
+function handle({ store, signature, rawBody = raw, parsed = body }: { store: ReturnType<typeof memoryStore>; signature?: string; rawBody?: unknown; parsed?: unknown }) {
+ return sendItWebhook.handle({ store, event: 'post.published', payload: { body: parsed, rawBody, headers: signature === undefined ? {} : { 'X-SendIt-Signature': signature } }, mapEvent: triggerMappers.published, now: NOW });
+}
+
+describe('webhook signature', () => {
+ test('accepts a valid signature and maps the event', async () => {
+ const out = await handle({ store: memoryStore({ webhookId: 'wh_1', webhookSecret: SECRET }), signature: sign() });
+ expect(out).toEqual([expect.objectContaining({ delivery_id: 'dlv_1', platform: 'x', post_id: '1', [DEDUPE_KEY_PROPERTY]: 'sendit:dlv_1' })]);
+ });
+
+ test('accepts a Buffer raw body', async () => {
+ expect(await handle({ store: memoryStore({ webhookId: 'wh_1', webhookSecret: SECRET }), signature: sign(), rawBody: Buffer.from(raw) })).toHaveLength(1);
+ });
+
+ test('drops unsigned, forged, wrong-secret, tampered and stale deliveries', async () => {
+ const stored = () => memoryStore({ webhookId: 'wh_1', webhookSecret: SECRET });
+ expect(await handle({ store: stored() })).toEqual([]);
+ expect(await handle({ store: stored(), signature: 't=1800000000,v1=deadbeef' })).toEqual([]);
+ expect(await handle({ store: stored(), signature: sign({ secret: 'other' }) })).toEqual([]);
+ expect(await handle({ store: stored(), signature: sign(), rawBody: raw.replace('hi', 'ho') })).toEqual([]);
+ expect(await handle({ store: stored(), signature: sign({ t: Math.floor(NOW / 1000) - 901 }) })).toEqual([]);
+ expect(await handle({ store: stored(), signature: 'v1=abc' })).toEqual([]);
+ });
+
+ test('allows queue lag inside the 15 minute window', async () => {
+ expect(await handle({ store: memoryStore({ webhookId: 'wh_1', webhookSecret: SECRET }), signature: sign({ t: Math.floor(NOW / 1000) - 600 }) })).toHaveLength(1);
+ });
+
+ test('ignores other events and dedupes replays by deliveryId', async () => {
+ const store = memoryStore({ webhookId: 'wh_1', webhookSecret: SECRET });
+ expect(await handle({ store, signature: sign(), parsed: { ...body, event: 'post.failed' } })).toEqual([]);
+ expect(await handle({ store, signature: sign() })).toHaveLength(1);
+ expect(await handle({ store, signature: sign() })).toEqual([]);
+ });
+
+ test('concurrent deliveries keep each other deduplicated', async () => {
+ const store = memoryStore({ webhookId: 'wh_1', webhookSecret: SECRET });
+ const second = { ...body, deliveryId: 'dlv_2' };
+ const rawSecond = JSON.stringify(second);
+ const [a, b] = await Promise.all([
+ handle({ store, signature: sign() }),
+ handle({ store, signature: sign({ payload: rawSecond }), rawBody: rawSecond, parsed: second }),
+ ]);
+ expect(a).toHaveLength(1);
+ expect(b).toHaveLength(1);
+ expect(await handle({ store, signature: sign() })).toEqual([]);
+ expect(await handle({ store, signature: sign({ payload: rawSecond }), rawBody: rawSecond, parsed: second })).toEqual([]);
+ });
+
+ test('deliveries recorded in the old shared list stay deduplicated', async () => {
+ const store = memoryStore({ webhookId: 'wh_1', webhookSecret: SECRET, seenDeliveryIds: ['dlv_1'] });
+ expect(await handle({ store, signature: sign() })).toEqual([]);
+ });
+
+ test('old delivery markers are cleaned up after the replay window', async () => {
+ const store = memoryStore({ webhookId: 'wh_1', webhookSecret: SECRET });
+ await handle({ store, signature: sign() });
+ expect(store.data.has('seenDelivery:dlv_1')).toBe(true);
+ const later = { ...body, deliveryId: 'dlv_9' };
+ const rawLater = JSON.stringify(later);
+ const laterNow = NOW + 31 * 60 * 1000;
+ const out = await sendItWebhook.handle({ store, event: 'post.published', payload: { body: later, rawBody: rawLater, headers: { 'X-SendIt-Signature': sign({ t: Math.floor(laterNow / 1000), payload: rawLater }) } }, mapEvent: triggerMappers.published, now: laterNow });
+ expect(out).toHaveLength(1);
+ expect(store.data.has('seenDelivery:dlv_1')).toBe(false);
+ expect(store.data.has('seenDelivery:dlv_9')).toBe(true);
+ });
+
+ test('markers inside the replay window are never deleted, and cleanup is bounded per event', async () => {
+ const recent = Array.from({ length: 1500 }, (_, i) => ({ id: `r${i}`, at: NOW - 60 * 1000 }));
+ const old = Array.from({ length: 100 }, (_, i) => ({ id: `o${i}`, at: NOW - 60 * 60 * 1000 }));
+ const initial: Record<string, unknown> = { webhookId: 'wh_1', webhookSecret: SECRET, seenDeliveryIndex: [...old, ...recent] };
+ for (const entry of [...old, ...recent]) initial[`seenDelivery:${entry.id}`] = entry.at;
+ const store = memoryStore(initial);
+ expect(await handle({ store, signature: sign() })).toHaveLength(1);
+ expect(recent.every((entry) => store.data.has(`seenDelivery:${entry.id}`))).toBe(true);
+ expect(old.filter((entry) => !store.data.has(`seenDelivery:${entry.id}`))).toHaveLength(25);
+ });
+
+ test('legacy store without a secret still fires; no webhook at all drops', async () => {
+ expect(await handle({ store: memoryStore({ webhookId: 'wh_old' }) })).toHaveLength(1);
+ expect(await handle({ store: memoryStore() })).toEqual([]);
+ });
+});
+
+describe('webhook lifecycle', () => {
+ test('enable stores id + secret', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, webhook: { id: 'wh_1', secret: SECRET } } }]));
+ const store = memoryStore();
+ await sendItWebhook.enable({ apiKey: API_KEY, store, event: 'post.published', webhookUrl: 'https://hook' });
+ expect(seen[0].body).toEqual({ url: 'https://hook', events: ['post.published'] });
+ expect(store.data.get('webhookId')).toBe('wh_1');
+ expect(store.data.get('webhookSecret')).toBe(SECRET);
+ });
+
+ test('enable deletes the webhook when the store write fails', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, webhook: { id: 'wh_1', secret: SECRET } } }, { body: { success: true } }]));
+ const store = memoryStore();
+ store.put = async () => { throw new Error('store down'); };
+ await expect(sendItWebhook.enable({ apiKey: API_KEY, store, event: 'post.published', webhookUrl: 'https://hook' })).rejects.toThrow('store down');
+ expect(seen[1].method).toBe('DELETE');
+ expect(seen[1].path).toBe('/api/v1/webhooks/wh_1');
+ });
+
+ test('enable fails and cleans up when no secret is returned', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, webhook: { id: 'wh_1' } } }, { body: {} }]));
+ await expect(sendItWebhook.enable({ apiKey: API_KEY, store: memoryStore(), event: 'post.published', webhookUrl: 'https://hook' })).rejects.toThrow('signing secret');
+ expect(seen[1].method).toBe('DELETE');
+ });
+
+ test('disable treats 404 as done and clears the store', async () => {
+ stubFetch(replies([{ status: 404, body: { success: false, error: 'not found' } }]));
+ const store = memoryStore({ webhookId: 'wh_1', webhookSecret: SECRET, seenDeliveryIds: ['a'] });
+ await handle({ store, signature: sign() });
+ await sendItWebhook.disable({ apiKey: API_KEY, store });
+ expect(store.data.size).toBe(0);
+ });
+
+ test('disable keeps the store when delete fails for another reason', async () => {
+ stubFetch(replies([{ status: 500, body: { error: 'boom' } }]));
+ const store = memoryStore({ webhookId: 'wh_1', webhookSecret: SECRET });
+ await expect(sendItWebhook.disable({ apiKey: API_KEY, store })).rejects.toThrow('boom');
+ expect(store.data.get('webhookId')).toBe('wh_1');
+ });
+});
diff --git a/packages/pieces/community/send-it/vitest.config.ts b/packages/pieces/community/send-it/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/send-it/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'),
+ },
+ },
+})