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(pastefy): add AI actions, output schemas and list/search actions (#16903)

Odai Ahmad8774a20dc28b
diff --git a/bun.lock b/bun.lock
index 597e49bc5d0..430655ab7c7 100644
--- a/bun.lock
+++ b/bun.lock
@@ -6981,17 +6981,19 @@
},
"packages/pieces/community/pastefy": {
"name": "@activepieces/piece-pastefy",
- "version": "0.3.2",
+ "version": "0.4.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"crypto-js": "4.2.0",
+ "undici": "7.29.1",
},
"devDependencies": {
"@types/crypto-js": "4.2.2",
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/paywhirl": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index f990e751f11..5ef831ee5b2 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,28 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### 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.
+
+These actions are no longer offered as tools to AI agents and MCP clients. They still work as normal flow steps. Agents use the replacement instead:
+- **Create Paste** → **Create Paste (by Folder ID)**
+- **Edit Paste** → **Update Paste (by IDs)**
+- **Create Folder** → **Create Folder (by Parent ID)**
+- **Get Folder** → **Get Folder (by ID)**
+- **Get Folder Hierarchy** → **List Folders**
+- **Delete Folder** → **Delete Folder (by ID)**
+
+**Edit Paste** now returns the updated paste, and **Delete Paste** and **Delete Folder** return `{ deleted, id }`. All three used to return `{ success }`, so a later step that reads `{{step.success}}` gets nothing after the upgrade.
+
+Every action and the **Paste Changed** trigger now call the connection's **Instance URL**. Before, they always called pastefy.app. An Instance URL that is not a plain http(s) URL now fails the step. TLS certificates are now checked, so a self-hosted Pastefy with a self-signed certificate fails (Custom API Call and the folder dropdowns already reached that server before). **Custom API Call** only accepts URLs under `<instance>/api/v2`.
+
+**Get Paste** with a wrong password now fails, and so does **Edit Paste** when it changes an encrypted paste's text without the password. **Delete Paste** on a paste that does not exist now returns `deleted: false` instead of failing.
+
+#### What you need to do
+
+Give agents the replacement actions listed above. Change later steps that read `success` from Edit Paste, Delete Paste or Delete Folder to read the paste fields or `deleted`. Check that the connection's Instance URL is the server you want, and give a self-hosted server a certificate from a trusted authority. Point Custom API Call steps at paths under `/api/v2`.
+
#### SmartLead 0.2.0: four actions are builder-only, and Update Campaign Settings skips empty settings
**Create Campaign**, **Add Leads to Campaign**, **Get Campaign Statistics** and **Update Campaign Settings** are no longer offered to AI agents. They keep working in flows with the same names and inputs, but an agent or MCP server that used them as tools loses them after the upgrade.
diff --git a/packages/pieces/community/pastefy/package.json b/packages/pieces/community/pastefy/package.json
index 0fab1b2cd73..9f0cc727ab1 100644
--- a/packages/pieces/community/pastefy/package.json
+++ b/packages/pieces/community/pastefy/package.json
@@ -1,22 +1,25 @@
{
"name": "@activepieces/piece-pastefy",
- "version": "0.3.2",
+ "version": "0.4.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"crypto-js": "4.2.0",
+ "undici": "7.29.1",
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*"
},
"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"
},
"devDependencies": {
"@types/crypto-js": "4.2.2",
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/pastefy/src/i18n/translation.json b/packages/pieces/community/pastefy/src/i18n/translation.json
index 145d843bbfe..61889607f36 100644
--- a/packages/pieces/community/pastefy/src/i18n/translation.json
+++ b/packages/pieces/community/pastefy/src/i18n/translation.json
@@ -1,8 +1,9 @@
{
"Sharing code snippets platform": "Sharing code snippets platform",
"Pastefy Instance URL": "Pastefy Instance URL",
- "API-Token": "API-Token",
- "\nCreate an account and obtain the API Key from Pastefy.\n": "\nCreate an account and obtain the API Key from Pastefy.\n",
+ "API Key": "API Key",
+ "Base URL of your Pastefy server, for example https://pastefy.app.": "Base URL of your Pastefy server, for example https://pastefy.app.",
+ "\nTo connect Pastefy:\n1. Sign in at [pastefy.app](https://pastefy.app) (or your own Pastefy instance).\n2. Open [API Keys](https://pastefy.app/apikeys) and create a key with the paste and folder permissions you need.\n3. Paste the key below. Leave the instance URL as is unless you run your own Pastefy server.\n": "\nTo connect Pastefy:\n1. Sign in at [pastefy.app](https://pastefy.app) (or your own Pastefy instance).\n2. Open [API Keys](https://pastefy.app/apikeys) and create a key with the paste and folder permissions you need.\n3. Paste the key below. Leave the instance URL as is unless you run your own Pastefy server.\n",
"Create Paste": "Create Paste",
"Get Paste": "Get Paste",
"Edit Paste": "Edit Paste",
@@ -11,15 +12,31 @@
"Get Folder": "Get Folder",
"Get Folder Hierarchy": "Get Folder Hierarchy",
"Delete Folder": "Delete Folder",
+ "List My Pastes": "List My Pastes",
+ "Search Public Pastes": "Search Public Pastes",
+ "Create Paste (by Folder ID)": "Create Paste (by Folder ID)",
+ "Update Paste (by IDs)": "Update Paste (by IDs)",
+ "Create Folder (by Parent ID)": "Create Folder (by Parent ID)",
+ "Get Folder (by ID)": "Get Folder (by ID)",
+ "Delete Folder (by ID)": "Delete Folder (by ID)",
+ "List Folders": "List Folders",
"Custom API Call": "Custom API Call",
- "Creates a new paste": "Creates a new paste",
- "Retrieves a paste": "Retrieves a paste",
- "Edits an existing private paste": "Edits an existing private paste",
- "Deletes a paste": "Deletes a paste",
- "Creates a new folder": "Creates a new folder",
- "Retrieves information about a folder": "Retrieves information about a folder",
- "Retrieves a hierarchy of all folders": "Retrieves a hierarchy of all folders",
- "Deletes a folder": "Deletes a folder",
+ "Creates a new paste.": "Creates a new paste.",
+ "Retrieves a paste.": "Retrieves a paste.",
+ "Changes a paste you own. Empty fields stay unchanged.": "Changes a paste you own. Empty fields stay unchanged.",
+ "Deletes a paste. Returns deleted: false when it was already gone.": "Deletes a paste. Returns deleted: false when it was already gone.",
+ "Creates a new folder.": "Creates a new folder.",
+ "Retrieves a folder with its subfolders and pastes.": "Retrieves a folder with its subfolders and pastes.",
+ "Retrieves the tree of all your folders.": "Retrieves the tree of all your folders.",
+ "Deletes a folder.": "Deletes a folder.",
+ "Lists pastes in your account, one page at a time.": "Lists pastes in your account, one page at a time.",
+ "Searches public pastes from everyone on the instance.": "Searches public pastes from everyone on the instance.",
+ "Creates a paste, with the folder given by ID.": "Creates a paste, with the folder given by ID.",
+ "Changes a paste you own, with paste and folder given by ID.": "Changes a paste you own, with paste and folder given by ID.",
+ "Creates a folder, with the parent given by ID.": "Creates a folder, with the parent given by ID.",
+ "Gets a folder by ID with its subfolders and pastes.": "Gets a folder by ID with its subfolders and pastes.",
+ "Deletes a folder by ID.": "Deletes a folder by ID.",
+ "Lists all your folders as a flat list with paths.": "Lists all your folders as a flat list with paths.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Content": "Content",
"Title": "Title",
@@ -27,10 +44,20 @@
"Folder": "Folder",
"Visibility": "Visibility",
"Expiry Date": "Expiry Date",
+ "Tags": "Tags",
"Paste ID": "Paste ID",
+ "Clear Tags": "Clear Tags",
"Name": "Name",
"Parent Folder": "Parent Folder",
+ "Include Contents": "Include Contents",
"Start Folder": "Start Folder",
+ "Search": "Search",
+ "Folder ID": "Folder ID",
+ "Page": "Page",
+ "Page Size": "Page Size",
+ "Shorten Content": "Shorten Content",
+ "List": "List",
+ "Parent Folder ID": "Parent Folder ID",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
@@ -40,9 +67,41 @@
"Return Error as Output": "Return Error as Output",
"Timeout": "Timeout",
"Follow redirects": "Follow redirects",
- "Encrypts the paste with this password": "Encrypts the paste with this password",
- "A folder": "A folder",
- "Decrypts the paste with this password": "Decrypts the paste with this password",
+ "Encrypts the content and title before upload. It cannot be recovered.": "Encrypts the content and title before upload. It cannot be recovered.",
+ "Folder to put the paste in.": "Folder to put the paste in.",
+ "Who can see the paste. Pastefy defaults to Unlisted.": "Who can see the paste. Pastefy defaults to Unlisted.",
+ "When Pastefy deletes the paste.": "When Pastefy deletes the paste.",
+ "Tags to add to the paste.": "Tags to add to the paste.",
+ "The 8-character paste ID, as in https://pastefy.app/<id>. Get it from List My Pastes or Search Public Pastes.": "The 8-character paste ID, as in https://pastefy.app/<id>. Get it from List My Pastes or Search Public Pastes.",
+ "Decrypts an encrypted paste with this password.": "Decrypts an encrypted paste with this password.",
+ "Needed to edit an encrypted paste; on a plain paste it encrypts it.": "Needed to edit an encrypted paste; on a plain paste it encrypts it.",
+ "Move the paste to this folder.": "Move the paste to this folder.",
+ "New visibility.": "New visibility.",
+ "Replaces all tags of the paste.": "Replaces all tags of the paste.",
+ "Remove all tags (ignored when Tags is filled).": "Remove all tags (ignored when Tags is filled).",
+ "Create the folder inside this folder.": "Create the folder inside this folder.",
+ "The folder to get.": "The folder to get.",
+ "Add pastes and subfolder contents.": "Add pastes and subfolder contents.",
+ "Only return the folders inside this folder.": "Only return the folders inside this folder.",
+ "The folder to delete.": "The folder to delete.",
+ "Text to search for in title and content.": "Text to search for in title and content.",
+ "Only pastes in this folder (ID from List Folders).": "Only pastes in this folder (ID from List Folders).",
+ "Only pastes with these tags.": "Only pastes with these tags.",
+ "Page number, starting at 1.": "Page number, starting at 1.",
+ "Pastes per page, 1 to 50.": "Pastes per page, 1 to 50.",
+ "Cut content to 300 characters.": "Cut content to 300 characters.",
+ "Text to search for.": "Text to search for.",
+ "Which public list to search.": "Which public list to search.",
+ "Encrypts content and title with this password.": "Encrypts content and title with this password.",
+ "Folder ID from List Folders.": "Folder ID from List Folders.",
+ "PUBLIC, UNLISTED or PRIVATE. Default UNLISTED.": "PUBLIC, UNLISTED or PRIVATE. Default UNLISTED.",
+ "ISO 8601 date-time, for example 2026-12-31T18:00:00Z.": "ISO 8601 date-time, for example 2026-12-31T18:00:00Z.",
+ "Tags to add.": "Tags to add.",
+ "Move the paste to this folder (ID from List Folders).": "Move the paste to this folder (ID from List Folders).",
+ "PUBLIC, UNLISTED or PRIVATE.": "PUBLIC, UNLISTED or PRIVATE.",
+ "ISO 8601 date-time in the future.": "ISO 8601 date-time in the future.",
+ "Replaces all tags.": "Replaces all tags.",
+ "Remove all tags (ignored when Tags is given).": "Remove all tags (ignored when Tags is given).",
"Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
"Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
"Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
@@ -52,6 +111,9 @@
"Public": "Public",
"Unlisted": "Unlisted",
"Private": "Private",
+ "All public pastes": "All public pastes",
+ "Latest": "Latest",
+ "Trending": "Trending",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
diff --git a/packages/pieces/community/pastefy/src/index.ts b/packages/pieces/community/pastefy/src/index.ts
index 1b75710fe76..7f12ba3040e 100644
--- a/packages/pieces/community/pastefy/src/index.ts
+++ b/packages/pieces/community/pastefy/src/index.ts
@@ -1,60 +1,22 @@
-import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import {
- PieceAuth,
- Property,
- createPiece,
-} from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
import actions from './lib/actions';
+import { pastefyAuth } from './lib/common/auth';
+import { pastefyCustomApiCallAction } from './lib/actions/custom-api-call';
import triggers from './lib/triggers';
-const markdown = `
-Create an account and obtain the API Key from Pastefy.
-`;
-
-export const pastefyAuth = PieceAuth.CustomAuth({
- description: markdown,
- required: true,
- props: {
- instance_url: Property.ShortText({
- displayName: 'Pastefy Instance URL',
- required: false,
- defaultValue: 'https://pastefy.app',
- }),
- token: PieceAuth.SecretText({
- displayName: 'API-Token',
- required: false,
- }),
- },
-});
-
export const pastefy = createPiece({
displayName: 'Pastefy',
description: 'Sharing code snippets platform',
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/pastefy.png',
- categories: [],
- authors: ["JanHolger","kishanprmr","MoShizzle","khaledmashaly","abuaboud"],
+ categories: [PieceCategory.DEVELOPER_TOOLS],
+ authors: ['JanHolger', 'kishanprmr', 'MoShizzle', 'khaledmashaly', 'abuaboud', 'OdaiAhmed99'],
auth: pastefyAuth,
actions: [
...actions,
- createCustomApiCallAction({
- baseUrl: (auth) => {
- if (!auth) {
- return '';
- }
- const typedAuth = auth.props as { instance_url: string };
- return typedAuth.instance_url + '/api/v2';
- },
- auth: pastefyAuth,
- authMapping: async (auth) => {
- const typedAuth = auth as { token?: string };
- return {
- Authorization: typedAuth.token
- ? `Bearer ${typedAuth.token}`
- : undefined,
- };
- },
- }),
+ pastefyCustomApiCallAction,
],
- triggers: triggers,
+ triggers,
});
+
+export { pastefyAuth };
diff --git a/packages/pieces/community/pastefy/src/lib/actions/ai/create-folder-ai.ts b/packages/pieces/community/pastefy/src/lib/actions/ai/create-folder-ai.ts
new file mode 100644
index 00000000000..73fce106396
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/actions/ai/create-folder-ai.ts
@@ -0,0 +1,26 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pastefyAiProps } from '../../common/ai-props';
+import { pastefyAuth } from '../../common/auth';
+import { pastefyOutputSchemas } from '../../common/output-schemas';
+import { pastefyRequests } from '../../common/requests';
+
+export default createAction({
+ auth: pastefyAuth,
+ name: 'create_folder_ai',
+ classification: 'WRITE',
+ displayName: 'Create Folder (by Parent ID)',
+ description: 'Creates a folder, with the parent given by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Creates a folder and returns it with its ID. Give parent_folder_id (from List Folders) to nest it; the step fails if that parent does not exist. Creates a new folder on every call, even with the same name, so it is not idempotent: call List Folders first to reuse an existing one. Needs an API key in the Pastefy connection.',
+ idempotent: false,
+ },
+ props: {
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ parent_folder_id: pastefyAiProps.folderId({ required: false, displayName: 'Parent Folder ID', description: 'Folder ID from List Folders.' }),
+ },
+ outputSchema: pastefyOutputSchemas.folder,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.createFolder({ auth, name: propsValue.name, parentId: propsValue.parent_folder_id });
+ },
+});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/ai/create-paste-ai.ts b/packages/pieces/community/pastefy/src/lib/actions/ai/create-paste-ai.ts
new file mode 100644
index 00000000000..f28bfa87376
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/actions/ai/create-paste-ai.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pastefyAiProps } from '../../common/ai-props';
+import { pastefyAuth } from '../../common/auth';
+import { pastefyOutputSchemas } from '../../common/output-schemas';
+import { pastefyProps } from '../../common/props';
+import { pastefyRequests } from '../../common/requests';
+
+export default createAction({
+ auth: pastefyAuth,
+ name: 'create_paste_ai',
+ classification: 'WRITE',
+ displayName: 'Create Paste (by Folder ID)',
+ description: 'Creates a paste, with the folder given by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Creates a new paste (code or text snippet) and returns it with its ID and raw_url. Optional: title, folder_id (from List Folders; the step fails if Pastefy did not file it there), visibility PUBLIC/UNLISTED/PRIVATE (default UNLISTED), expiry as an ISO 8601 date-time in the future, tags, and an encryption password that AES-encrypts content and title before upload. Creates a new paste on every call, so it is not idempotent. Works without an API key (anonymous paste); folder_id needs a key.',
+ idempotent: false,
+ },
+ props: {
+ content: Property.LongText({ displayName: 'Content', required: true }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ password: Property.ShortText({ displayName: 'Encryption Password', description: 'Encrypts content and title with this password.', required: false }),
+ folder_id: pastefyAiProps.folderId({ required: false, displayName: 'Folder ID', description: 'Folder ID from List Folders.' }),
+ visibility: pastefyProps.visibility({ required: false, description: 'PUBLIC, UNLISTED or PRIVATE. Default UNLISTED.' }),
+ expiry: Property.ShortText({ displayName: 'Expiry Date', description: 'ISO 8601 date-time, for example 2026-12-31T18:00:00Z.', required: false }),
+ tags: pastefyProps.tags({ description: 'Tags to add.' }),
+ },
+ outputSchema: pastefyOutputSchemas.paste,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.createPaste({
+ auth,
+ input: {
+ content: propsValue.content,
+ title: propsValue.title,
+ password: propsValue.password,
+ folderId: propsValue.folder_id,
+ visibility: propsValue.visibility,
+ expiry: propsValue.expiry,
+ tags: propsValue.tags,
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/ai/delete-folder-ai.ts b/packages/pieces/community/pastefy/src/lib/actions/ai/delete-folder-ai.ts
new file mode 100644
index 00000000000..42b4aff3b8b
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/actions/ai/delete-folder-ai.ts
@@ -0,0 +1,25 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { pastefyAiProps } from '../../common/ai-props';
+import { pastefyAuth } from '../../common/auth';
+import { pastefyOutputSchemas } from '../../common/output-schemas';
+import { pastefyRequests } from '../../common/requests';
+
+export default createAction({
+ auth: pastefyAuth,
+ name: 'delete_folder_ai',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Folder (by ID)',
+ description: 'Deletes a folder by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Permanently deletes a folder you own by folder_id (from List Folders). Returns {deleted: true, id}; if the folder does not exist it returns {deleted: false, id} instead of failing, so repeat calls are safe and idempotent. Needs an API key in the Pastefy connection.',
+ idempotent: true,
+ },
+ props: {
+ folder_id: pastefyAiProps.folderId({ required: true, displayName: 'Folder ID', description: 'Folder ID from List Folders.' }),
+ },
+ outputSchema: pastefyOutputSchemas.deleted,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.deleteItem({ auth, kind: 'folder', id: propsValue.folder_id, missingIsOk: true });
+ },
+});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/ai/edit-paste-ai.ts b/packages/pieces/community/pastefy/src/lib/actions/ai/edit-paste-ai.ts
new file mode 100644
index 00000000000..144ca51c329
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/actions/ai/edit-paste-ai.ts
@@ -0,0 +1,47 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pastefyAiProps } from '../../common/ai-props';
+import { pastefyAuth } from '../../common/auth';
+import { pastefyOutputSchemas } from '../../common/output-schemas';
+import { pastefyProps } from '../../common/props';
+import { pastefyRequests } from '../../common/requests';
+
+export default createAction({
+ auth: pastefyAuth,
+ name: 'edit_paste_ai',
+ classification: 'WRITE',
+ displayName: 'Update Paste (by IDs)',
+ description: 'Changes a paste you own, with paste and folder given by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Updates a paste you own by paste_id and returns the updated paste. Only the fields you give change: content, title, folder_id (from List Folders), visibility, expiry (ISO 8601, future), tags (replace all) or clear_tags. An encrypted paste stays encrypted; changing its content or title needs its password, and a password on a plain paste encrypts it (content required). Re-applying the same values gives the same result, so it is idempotent. Needs an API key in the Pastefy connection.',
+ idempotent: true,
+ },
+ props: {
+ paste_id: pastefyAiProps.pasteId(),
+ content: Property.LongText({ displayName: 'Content', required: false }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ password: Property.ShortText({ displayName: 'Encryption Password', required: false }),
+ folder_id: pastefyAiProps.folderId({ required: false, displayName: 'Folder ID', description: 'Move the paste to this folder (ID from List Folders).' }),
+ visibility: pastefyProps.visibility({ required: false, description: 'PUBLIC, UNLISTED or PRIVATE.' }),
+ expiry: Property.ShortText({ displayName: 'Expiry Date', description: 'ISO 8601 date-time in the future.', required: false }),
+ tags: pastefyProps.tags({ description: 'Replaces all tags.' }),
+ clear_tags: Property.Checkbox({ displayName: 'Clear Tags', description: 'Remove all tags (ignored when Tags is given).', required: false, defaultValue: false }),
+ },
+ outputSchema: pastefyOutputSchemas.paste,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.editPaste({
+ auth,
+ pasteId: propsValue.paste_id,
+ input: {
+ content: propsValue.content,
+ title: propsValue.title,
+ password: propsValue.password,
+ folderId: propsValue.folder_id,
+ visibility: propsValue.visibility,
+ expiry: propsValue.expiry,
+ tags: propsValue.tags,
+ clearTags: propsValue.clear_tags,
+ },
+ });
+ },
+});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/ai/get-folder-ai.ts b/packages/pieces/community/pastefy/src/lib/actions/ai/get-folder-ai.ts
new file mode 100644
index 00000000000..4f07d36ac7d
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/actions/ai/get-folder-ai.ts
@@ -0,0 +1,26 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pastefyAiProps } from '../../common/ai-props';
+import { pastefyAuth } from '../../common/auth';
+import { pastefyOutputSchemas } from '../../common/output-schemas';
+import { pastefyRequests } from '../../common/requests';
+
+export default createAction({
+ auth: pastefyAuth,
+ name: 'get_folder_ai',
+ classification: 'READ',
+ displayName: 'Get Folder (by ID)',
+ description: 'Gets a folder by ID with its subfolders and pastes.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Gets one folder by folder_id (from List Folders): name, owner, created date its pastes and subfolders with their contents. With include_contents false, pastes is empty and subfolders carry only ID and name. Read-only and idempotent. Needs an API key in the Pastefy connection.',
+ idempotent: true,
+ },
+ props: {
+ folder_id: pastefyAiProps.folderId({ required: true, displayName: 'Folder ID', description: 'Folder ID from List Folders.' }),
+ include_contents: Property.Checkbox({ displayName: 'Include Contents', description: 'Add pastes and subfolder contents.', required: false, defaultValue: true }),
+ },
+ outputSchema: pastefyOutputSchemas.folder,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.getFolder({ auth, folderId: propsValue.folder_id, includeContents: propsValue.include_contents !== false });
+ },
+});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/ai/list-folders.ts b/packages/pieces/community/pastefy/src/lib/actions/ai/list-folders.ts
new file mode 100644
index 00000000000..b59b7ca5aab
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/actions/ai/list-folders.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { pastefyAuth } from '../../common/auth';
+import { pastefyOutputSchemas } from '../../common/output-schemas';
+import { pastefyRequests } from '../../common/requests';
+
+export default createAction({
+ auth: pastefyAuth,
+ name: 'list_folders',
+ classification: 'READ',
+ displayName: 'List Folders',
+ description: 'Lists all your folders as a flat list with paths.',
+ audience: 'ai',
+ aiMetadata: {
+ description: 'Lists every folder of the connected account in one call as a flat list of {id, name, path, parent_id}, where path joins names from the top folder down with " / ". Use it to find a folder_id by name before creating, moving or listing pastes. Read-only and idempotent. Needs an API key in the Pastefy connection.',
+ idempotent: true,
+ },
+ props: {},
+ outputSchema: pastefyOutputSchemas.folderList,
+ async run({ auth }) {
+ const tree = await pastefyRequests.folderTree({ auth });
+ const folders = pastefyRequests.flattenTree({ tree, parentPath: '', parentId: null });
+ return { folders, count: folders.length };
+ },
+});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/create-folder.ts b/packages/pieces/community/pastefy/src/lib/actions/create-folder.ts
index 5f02121a231..0f8df0b29ea 100644
--- a/packages/pieces/community/pastefy/src/lib/actions/create-folder.ts
+++ b/packages/pieces/community/pastefy/src/lib/actions/create-folder.ts
@@ -1,28 +1,26 @@
-import { Property, createAction } from '@activepieces/pieces-framework';
-import { makeClient, pastefyCommon } from '../common';
-import { pastefyAuth } from '../..';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pastefyAuth } from '../common/auth';
+import { pastefyOutputSchemas } from '../common/output-schemas';
+import { pastefyProps } from '../common/props';
+import { pastefyRequests } from '../common/requests';
export default createAction({
auth: pastefyAuth,
name: 'create_folder',
classification: 'WRITE',
displayName: 'Create Folder',
- description: 'Creates a new folder',
- audience: 'both',
- aiMetadata: { description: 'Creates a new folder on a Pastefy instance to organize pastes, optionally nested under a parent folder. Use before placing pastes into a folder. Creates a new folder with a new ID on every call, so it is not idempotent.', idempotent: false },
+ description: 'Creates a new folder.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Creates a folder, optionally inside a parent folder picked from a dropdown. Creates a new folder with a new ID on every call, so it is not idempotent. Needs an API key in the Pastefy connection.',
+ idempotent: false,
+ },
props: {
- name: Property.ShortText({
- displayName: 'Name',
- required: true,
- }),
- parent_id: pastefyCommon.folder_id(false, 'Parent Folder'),
+ name: Property.ShortText({ displayName: 'Name', required: true }),
+ parent_id: pastefyProps.folderDropdown({ required: false, displayName: 'Parent Folder', description: 'Create the folder inside this folder.' }),
},
- async run(context) {
- const client = makeClient(context.auth, context.propsValue);
- const res = await client.createFolder({
- name: context.propsValue.name as string,
- parent: context.propsValue.parent_id,
- });
- return res.folder;
+ outputSchema: pastefyOutputSchemas.folder,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.createFolder({ auth, name: propsValue.name, parentId: propsValue.parent_id });
},
});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/create-paste.ts b/packages/pieces/community/pastefy/src/lib/actions/create-paste.ts
index ca3ad053736..150536ef45a 100644
--- a/packages/pieces/community/pastefy/src/lib/actions/create-paste.ts
+++ b/packages/pieces/community/pastefy/src/lib/actions/create-paste.ts
@@ -1,57 +1,42 @@
-import { Property, createAction } from '@activepieces/pieces-framework';
-import { formatDate, makeClient, pastefyCommon } from '../common';
-import { pastefyAuth } from '../..';
-import CryptoJS from 'crypto-js';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pastefyAuth } from '../common/auth';
+import { pastefyOutputSchemas } from '../common/output-schemas';
+import { pastefyProps } from '../common/props';
+import { pastefyRequests } from '../common/requests';
export default createAction({
auth: pastefyAuth,
-
name: 'create_paste',
classification: 'WRITE',
displayName: 'Create Paste',
- description: 'Creates a new paste',
- audience: 'both',
- aiMetadata: { description: 'Creates a new paste (code/text snippet) on a Pastefy instance, optionally setting a title, folder, visibility, and expiry. Use to publish a snippet; if an encryption password is supplied, the content (and title) are AES-encrypted client-side before upload. Creates a new paste with a new ID on every call, so it is not idempotent.', idempotent: false },
+ description: 'Creates a new paste.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Creates a new paste with content, optional title, folder picked from a dropdown, visibility, expiry and tags. With an encryption password the content and title are AES-encrypted before upload. Creates a new paste with a new ID on every call, so it is not idempotent. Works without an API key (anonymous paste); a folder needs a key.',
+ idempotent: false,
+ },
props: {
- content: Property.LongText({
- displayName: 'Content',
- required: true,
- }),
- title: Property.ShortText({
- displayName: 'Title',
- required: false,
- }),
- password: Property.ShortText({
- displayName: 'Encryption Password',
- description: 'Encrypts the paste with this password',
- required: false,
- }),
- folder_id: pastefyCommon.folder_id(false),
- visibility: pastefyCommon.visibility(false),
- expiry: Property.DateTime({
- displayName: 'Expiry Date',
- required: false,
- }),
+ content: Property.LongText({ displayName: 'Content', required: true }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ password: Property.ShortText({ displayName: 'Encryption Password', description: 'Encrypts the content and title before upload. It cannot be recovered.', required: false }),
+ folder_id: pastefyProps.folderDropdown({ required: false, displayName: 'Folder', description: 'Folder to put the paste in.' }),
+ visibility: pastefyProps.visibility({ required: false, description: 'Who can see the paste. Pastefy defaults to Unlisted.' }),
+ expiry: Property.DateTime({ displayName: 'Expiry Date', description: 'When Pastefy deletes the paste.', required: false }),
+ tags: pastefyProps.tags({ description: 'Tags to add to the paste.' }),
},
- async run(context) {
- const client = makeClient(context.auth, context.propsValue);
- const password = context.propsValue.password;
- let content = context.propsValue.content;
- let title = context.propsValue.title;
- if (password) {
- content = CryptoJS.AES.encrypt(content, password).toString();
- if (title) {
- title = CryptoJS.AES.encrypt(title, password).toString();
- }
- }
- const res = await client.createPaste({
- title,
- content,
- encrypted: !!password,
- folder: context.propsValue.folder_id,
- visibility: context.propsValue.visibility,
- expire_at: formatDate(context.propsValue.expiry),
+ outputSchema: pastefyOutputSchemas.paste,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.createPaste({
+ auth,
+ input: {
+ content: propsValue.content,
+ title: propsValue.title,
+ password: propsValue.password,
+ folderId: propsValue.folder_id,
+ visibility: propsValue.visibility,
+ expiry: propsValue.expiry,
+ tags: propsValue.tags,
+ },
});
- return res.paste;
},
});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/custom-api-call.ts b/packages/pieces/community/pastefy/src/lib/actions/custom-api-call.ts
new file mode 100644
index 00000000000..030f3683f08
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/actions/custom-api-call.ts
@@ -0,0 +1,189 @@
+import { createCustomApiCallAction, HttpMethod, HttpRequest, httpClient, toFailsafeOutput } from '@activepieces/pieces-common';
+import { createAction } from '@activepieces/pieces-framework';
+import { pastefyAuth } from '../common/auth';
+import { pastefyClient, PastefyAuthValue } from '../common/client';
+
+const base = createCustomApiCallAction({
+ auth: pastefyAuth,
+ baseUrl: (auth) => (auth ? pastefyClient.apiBase({ auth }) : ''),
+ authMapping: async (auth) => authHeadersOf({ auth }),
+ props: {
+ followRedirects: {
+ description: 'Has no effect here: redirects are never followed, so the API key is not sent to another host.',
+ },
+ },
+});
+
+export const pastefyCustomApiCallAction = createAction({
+ auth: pastefyAuth,
+ name: 'custom_api_call',
+ displayName: base.displayName,
+ description: base.description,
+ props: base.props,
+ propertyGroups: base.propertyGroups,
+ classification: 'WRITE',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Sends a raw request to the Pastefy API v2 of the connected instance (<instance>/api/v2), with the API key when the connection has one. Needs a method and a path relative to that base; absolute URLs outside it are refused. Returns the HTTP status, response headers and body.',
+ idempotent: false,
+ },
+ async run({ auth, propsValue, files }) {
+ const method = methodOf(propsValue['method']);
+ const url = apiUrlOf({ baseUrl: pastefyClient.apiBase({ auth }), url: urlOf(propsValue['url']) });
+ const timeout = propsValue['timeout'];
+ const request: HttpRequest = {
+ method,
+ url,
+ headers: { ...withoutAuthHeader(stringMap(propsValue['headers'])), ...authHeadersOf({ auth }) },
+ queryParams: stringMap(propsValue['queryParams']),
+ timeout: typeof timeout === 'number' && timeout > 0 ? timeout * 1000 : 0,
+ followRedirects: false,
+ body: bodyOf({ body: propsValue['body'], bodyType: propsValue['body_type'] }),
+ };
+ const binary = propsValue['response_is_binary'] === true;
+ if (binary) {
+ request.responseType = 'arraybuffer';
+ }
+ try {
+ const response = await httpClient.sendRequest(request, { dispatcher: await pastefyClient.verifiedTls() });
+ const data: unknown = response.body;
+ if (binary && (data instanceof ArrayBuffer || Buffer.isBuffer(data))) {
+ const buffer = Buffer.isBuffer(data) ? data : Buffer.from(new Uint8Array(data));
+ return { status: response.status, headers: response.headers, body: await files.write({ fileName: `output.${extensionOf(response.headers)}`, data: buffer }) };
+ }
+ return { status: response.status, headers: response.headers, body: data };
+ } catch (error) {
+ if (propsValue['failsafe'] === true) {
+ return toFailsafeOutput({ error, requestBody: request.body });
+ }
+ throw error;
+ }
+ },
+});
+
+export function apiUrlOf({ baseUrl, url }: { baseUrl: string; url: string }): string {
+ if (url === '') {
+ throw new Error('URL is required.');
+ }
+ if (url.split(/[/?#\\]/).some((part) => part === '..' || /^%2e%2e$/i.test(part) || part === '.')) {
+ throw new Error('The URL must not contain "." or ".." segments.');
+ }
+ const isAbsolute = /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//') || url.startsWith('\\');
+ if (!isAbsolute) {
+ return `${baseUrl}/${url.replace(/^\/+/, '')}`;
+ }
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ throw new Error('The URL is not valid.');
+ }
+ const allowed = new URL(baseUrl);
+ const onInstance =
+ parsed.protocol === allowed.protocol &&
+ parsed.host === allowed.host &&
+ parsed.username === '' &&
+ parsed.password === '' &&
+ (parsed.pathname === allowed.pathname || parsed.pathname.startsWith(`${allowed.pathname}/`));
+ if (!onInstance) {
+ throw new Error(`The URL must start with ${baseUrl}/ or be a path relative to it.`);
+ }
+ return parsed.toString();
+}
+
+function authHeadersOf({ auth }: { auth: PastefyAuthValue }): Record<string, string> {
+ const token = pastefyClient.tokenOf({ auth });
+ return token ? { Authorization: `Bearer ${token}` } : {};
+}
+
+function urlOf(value: unknown): string {
+ return pastefyClient.isRecord(value) && typeof value['url'] === 'string' ? value['url'].trim() : '';
+}
+
+function methodOf(value: unknown): HttpMethod {
+ const method = Object.values(HttpMethod).find((candidate) => candidate === value);
+ if (!method) {
+ throw new Error('Method is required.');
+ }
+ return method;
+}
+
+function stringMap(value: unknown): Record<string, string> {
+ if (!pastefyClient.isRecord(value)) {
+ return {};
+ }
+ const entries: [string, string][] = [];
+ for (const [key, item] of Object.entries(value)) {
+ const text = Array.isArray(item) ? item.filter(isScalar).map(String).join(',') : isScalar(item) ? String(item) : undefined;
+ if (text !== undefined) {
+ entries.push([key, text]);
+ }
+ }
+ return Object.fromEntries(entries);
+}
+
+function isScalar(value: unknown): value is string | number | boolean {
+ return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';
+}
+
+function withoutAuthHeader(headers: Record<string, string>): Record<string, string> {
+ return Object.fromEntries(Object.entries(headers).filter(([key]) => key.toLowerCase() !== 'authorization'));
+}
+
+function extensionOf(headers: unknown): string {
+ const raw = pastefyClient.isRecord(headers) ? headers['content-type'] : undefined;
+ const value = Array.isArray(raw) ? raw[0] : raw;
+ const type = typeof value === 'string' ? value.split(';')[0].trim().toLowerCase() : '';
+ return CONTENT_TYPE_EXTENSIONS[type] ?? 'txt';
+}
+
+function bodyOf({ body, bodyType }: { body: unknown; bodyType: unknown }): HttpRequest['body'] {
+ if (body === undefined || body === null) {
+ return undefined;
+ }
+ if (!bodyType) {
+ return pastefyClient.isRecord(body) || Array.isArray(body) || typeof body === 'string' ? body : undefined;
+ }
+ if (bodyType === 'none' || !pastefyClient.isRecord(body)) {
+ return undefined;
+ }
+ const data = body['data'];
+ if (bodyType !== 'form_data') {
+ return pastefyClient.isRecord(data) || Array.isArray(data) || typeof data === 'string' ? data : undefined;
+ }
+ const form = new FormData();
+ for (const field of Array.isArray(data) ? data : []) {
+ if (!pastefyClient.isRecord(field) || typeof field['fieldName'] !== 'string') {
+ continue;
+ }
+ const text = field['textFieldValue'];
+ const file = pastefyClient.isRecord(field['fileFieldValue']) ? field['fileFieldValue'] : {};
+ if (field['fieldType'] === 'text' && typeof text === 'string' && text !== '') {
+ form.append(field['fieldName'], text);
+ } else if (field['fieldType'] === 'file' && Buffer.isBuffer(file['data'])) {
+ form.append(field['fieldName'], new Blob([new Uint8Array(file['data'])]), typeof file['filename'] === 'string' ? file['filename'] : undefined);
+ }
+ }
+ return form;
+}
+
+const CONTENT_TYPE_EXTENSIONS: Record<string, string> = {
+ 'application/json': 'json',
+ 'application/pdf': 'pdf',
+ 'application/zip': 'zip',
+ 'application/gzip': 'gz',
+ 'application/octet-stream': 'bin',
+ 'application/xml': 'xml',
+ 'text/xml': 'xml',
+ 'text/csv': 'csv',
+ 'text/plain': 'txt',
+ 'text/html': 'html',
+ 'image/png': 'png',
+ 'image/jpeg': 'jpg',
+ 'image/gif': 'gif',
+ 'image/webp': 'webp',
+ 'image/svg+xml': 'svg',
+ 'video/mp4': 'mp4',
+ 'audio/mpeg': 'mp3',
+};
diff --git a/packages/pieces/community/pastefy/src/lib/actions/delete-folder.ts b/packages/pieces/community/pastefy/src/lib/actions/delete-folder.ts
index 0d458cc3357..0010b7d43b0 100644
--- a/packages/pieces/community/pastefy/src/lib/actions/delete-folder.ts
+++ b/packages/pieces/community/pastefy/src/lib/actions/delete-folder.ts
@@ -1,23 +1,25 @@
import { createAction } from '@activepieces/pieces-framework';
-import { makeClient, pastefyCommon } from '../common';
-import { pastefyAuth } from '../..';
+import { pastefyAuth } from '../common/auth';
+import { pastefyOutputSchemas } from '../common/output-schemas';
+import { pastefyProps } from '../common/props';
+import { pastefyRequests } from '../common/requests';
export default createAction({
auth: pastefyAuth,
name: 'delete_folder',
classification: 'DESTRUCTIVE',
displayName: 'Delete Folder',
- description: 'Deletes a folder',
- audience: 'both',
- aiMetadata: { description: 'Permanently deletes a folder by its ID from a Pastefy instance. Use to remove a folder you no longer need. Keyed on the stable folder ID, so the end state (folder absent) is the same on repeat calls; idempotent.', idempotent: true },
+ description: 'Deletes a folder.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Permanently deletes a folder picked from a dropdown. Fails when the folder no longer exists, so a repeat call is not silent; not idempotent. Needs an API key in the Pastefy connection.',
+ idempotent: false,
+ },
props: {
- folder_id: pastefyCommon.folder_id(true),
+ folder_id: pastefyProps.folderDropdown({ required: true, displayName: 'Folder', description: 'The folder to delete.' }),
},
- async run(context) {
- const client = makeClient(context.auth, context.propsValue);
- const res = await client.deleteFolder(
- context.propsValue.folder_id as string
- );
- return res;
+ outputSchema: pastefyOutputSchemas.deleted,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.deleteItem({ auth, kind: 'folder', id: propsValue.folder_id, missingIsOk: false });
},
});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/delete-paste.ts b/packages/pieces/community/pastefy/src/lib/actions/delete-paste.ts
index 6b490b32d6c..86f133dd1ac 100644
--- a/packages/pieces/community/pastefy/src/lib/actions/delete-paste.ts
+++ b/packages/pieces/community/pastefy/src/lib/actions/delete-paste.ts
@@ -1,24 +1,25 @@
-import { Property, createAction } from '@activepieces/pieces-framework';
-import { makeClient } from '../common';
-import { pastefyAuth } from '../..';
+import { createAction } from '@activepieces/pieces-framework';
+import { pastefyAiProps } from '../common/ai-props';
+import { pastefyAuth } from '../common/auth';
+import { pastefyOutputSchemas } from '../common/output-schemas';
+import { pastefyRequests } from '../common/requests';
export default createAction({
auth: pastefyAuth,
name: 'delete_paste',
classification: 'DESTRUCTIVE',
displayName: 'Delete Paste',
- description: 'Deletes a paste',
+ description: 'Deletes a paste. Returns deleted: false when it was already gone.',
audience: 'both',
- aiMetadata: { description: 'Permanently deletes a paste by its ID from a Pastefy instance. Use to remove a snippet you no longer want hosted. Keyed on the stable paste ID, so the end state (paste absent) is the same on repeat calls; idempotent.', idempotent: true },
+ aiMetadata: {
+ description: 'Permanently deletes a paste you own by its ID. Returns {deleted: true, id}; if the paste does not exist (already deleted) it returns {deleted: false, id} instead of failing, so repeat calls are safe and idempotent. Needs an API key in the Pastefy connection.',
+ idempotent: true,
+ },
props: {
- paste_id: Property.ShortText({
- displayName: 'Paste ID',
- required: true,
- }),
+ paste_id: pastefyAiProps.pasteId(),
},
- async run(context) {
- const client = makeClient(context.auth, context.propsValue);
- const res = await client.deletePaste(context.propsValue.paste_id);
- return res;
+ outputSchema: pastefyOutputSchemas.deleted,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.deleteItem({ auth, kind: 'paste', id: propsValue.paste_id, missingIsOk: true });
},
});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/edit-paste.ts b/packages/pieces/community/pastefy/src/lib/actions/edit-paste.ts
index 4355918ba12..b99430047c4 100644
--- a/packages/pieces/community/pastefy/src/lib/actions/edit-paste.ts
+++ b/packages/pieces/community/pastefy/src/lib/actions/edit-paste.ts
@@ -1,62 +1,47 @@
-import { Property, createAction } from '@activepieces/pieces-framework';
-import { formatDate, makeClient, pastefyCommon } from '../common';
-import { pastefyAuth } from '../..';
-import CryptoJS from 'crypto-js';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pastefyAiProps } from '../common/ai-props';
+import { pastefyAuth } from '../common/auth';
+import { pastefyOutputSchemas } from '../common/output-schemas';
+import { pastefyProps } from '../common/props';
+import { pastefyRequests } from '../common/requests';
export default createAction({
auth: pastefyAuth,
name: 'edit_paste',
classification: 'WRITE',
displayName: 'Edit Paste',
- description: 'Edits an existing private paste',
- audience: 'both',
- aiMetadata: { description: 'Updates an existing private paste identified by its ID, replacing fields such as content, title, folder, visibility, and expiry. Use to modify a paste you already know the ID of. If an encryption password is supplied, the provided content/title are AES-encrypted client-side. Idempotent: re-applying the same field values to the same paste yields the same result.', idempotent: true },
+ description: 'Changes a paste you own. Empty fields stay unchanged.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Updates a paste you own by ID, changing only the given fields (content, title, folder picked from a dropdown, visibility, expiry, tags) and returns the updated paste. An encrypted paste stays encrypted; changing its content or title needs its password. Re-applying the same values gives the same result, so it is idempotent. Needs an API key in the Pastefy connection.',
+ idempotent: true,
+ },
props: {
- paste_id: Property.ShortText({
- displayName: 'Paste ID',
- required: true,
- }),
- content: Property.LongText({
- displayName: 'Content',
- required: false,
- }),
- title: Property.ShortText({
- displayName: 'Title',
- required: false,
- }),
- password: Property.ShortText({
- displayName: 'Encryption Password',
- description: 'Encrypts the paste with this password',
- required: false,
- }),
- folder_id: pastefyCommon.folder_id(false),
- visibility: pastefyCommon.visibility(false),
- expiry: Property.DateTime({
- displayName: 'Expiry Date',
- required: false,
- }),
+ paste_id: pastefyAiProps.pasteId(),
+ content: Property.LongText({ displayName: 'Content', required: false }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ password: Property.ShortText({ displayName: 'Encryption Password', description: 'Needed to edit an encrypted paste; on a plain paste it encrypts it.', required: false }),
+ folder_id: pastefyProps.folderDropdown({ required: false, displayName: 'Folder', description: 'Move the paste to this folder.' }),
+ visibility: pastefyProps.visibility({ required: false, description: 'New visibility.' }),
+ expiry: Property.DateTime({ displayName: 'Expiry Date', required: false }),
+ tags: pastefyProps.tags({ description: 'Replaces all tags of the paste.' }),
+ clear_tags: Property.Checkbox({ displayName: 'Clear Tags', description: 'Remove all tags (ignored when Tags is filled).', required: false, defaultValue: false }),
},
- async run(context) {
- const client = makeClient(context.auth, context.propsValue);
- const password = context.propsValue.password;
- let content = context.propsValue.content;
- let title = context.propsValue.title;
- if (password) {
- if (content) {
- content = CryptoJS.AES.encrypt(content, password).toString();
- }
- if (title) {
- title = CryptoJS.AES.encrypt(title, password).toString();
- }
- }
- const res = await client.editPaste(context.propsValue.paste_id, {
- title,
- content,
- encrypted: !!password,
- folder: context.propsValue.folder_id,
- visibility: context.propsValue.visibility,
- expire_at: formatDate(context.propsValue.expiry),
+ outputSchema: pastefyOutputSchemas.paste,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.editPaste({
+ auth,
+ pasteId: propsValue.paste_id,
+ input: {
+ content: propsValue.content,
+ title: propsValue.title,
+ password: propsValue.password,
+ folderId: propsValue.folder_id,
+ visibility: propsValue.visibility,
+ expiry: propsValue.expiry,
+ tags: propsValue.tags,
+ clearTags: propsValue.clear_tags,
+ },
});
- return res;
},
});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/get-folder-hierarchy.ts b/packages/pieces/community/pastefy/src/lib/actions/get-folder-hierarchy.ts
index 9c9ccf453e3..72d92b12155 100644
--- a/packages/pieces/community/pastefy/src/lib/actions/get-folder-hierarchy.ts
+++ b/packages/pieces/community/pastefy/src/lib/actions/get-folder-hierarchy.ts
@@ -1,23 +1,33 @@
import { createAction } from '@activepieces/pieces-framework';
-import { makeClient, pastefyCommon } from '../common';
-import { pastefyAuth } from '../..';
+import { pastefyAuth } from '../common/auth';
+import { pastefyOutputSchemas } from '../common/output-schemas';
+import { pastefyProps } from '../common/props';
+import { pastefyRequests } from '../common/requests';
export default createAction({
auth: pastefyAuth,
name: 'get_folder_hierarchy',
- classification: 'SEARCH',
+ classification: 'READ',
displayName: 'Get Folder Hierarchy',
- description: 'Retrieves a hierarchy of all folders',
- audience: 'both',
- aiMetadata: { description: 'Retrieves the nested tree of folders on a Pastefy instance, recursively listing each folder and its children. Pass a start folder ID to scope the tree to that subtree, or omit it to walk from the root. Use to discover folder structure or resolve folder IDs by name. Read-only and idempotent.', idempotent: true },
+ description: 'Retrieves the tree of all your folders.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Returns the full nested folder tree of the account in one request, or the subtree under a start folder picked from a dropdown. Read-only and idempotent. Needs an API key in the Pastefy connection.',
+ idempotent: true,
+ },
props: {
- parent_id: pastefyCommon.folder_id(false, 'Start Folder'),
+ parent_id: pastefyProps.folderDropdown({ required: false, displayName: 'Start Folder', description: 'Only return the folders inside this folder.' }),
},
- async run(context) {
- const client = makeClient(context.auth, context.propsValue);
- const hierarchy = await client.getFolderHierarchy(
- context.propsValue.parent_id
- );
- return hierarchy;
+ outputSchema: pastefyOutputSchemas.folderTree,
+ async run({ auth, propsValue }) {
+ const tree = await pastefyRequests.folderTree({ auth });
+ if (!propsValue.parent_id) {
+ return tree;
+ }
+ const children = pastefyRequests.subtree({ tree, folderId: propsValue.parent_id });
+ if (children === null) {
+ throw new Error(`Folder ${propsValue.parent_id} was not found in your folders.`);
+ }
+ return children;
},
});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/get-folder.ts b/packages/pieces/community/pastefy/src/lib/actions/get-folder.ts
index 0302272c293..8102e59ea29 100644
--- a/packages/pieces/community/pastefy/src/lib/actions/get-folder.ts
+++ b/packages/pieces/community/pastefy/src/lib/actions/get-folder.ts
@@ -1,23 +1,26 @@
-import { createAction } from '@activepieces/pieces-framework';
-import { makeClient, pastefyCommon } from '../common';
-import { pastefyAuth } from '../..';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pastefyAuth } from '../common/auth';
+import { pastefyOutputSchemas } from '../common/output-schemas';
+import { pastefyProps } from '../common/props';
+import { pastefyRequests } from '../common/requests';
export default createAction({
auth: pastefyAuth,
name: 'get_folder',
classification: 'READ',
displayName: 'Get Folder',
- description: 'Retrieves information about a folder',
- audience: 'both',
- aiMetadata: { description: 'Fetches metadata for a single folder by its ID from a Pastefy instance. Use to read details of a known folder. Read-only and idempotent.', idempotent: true },
+ description: 'Retrieves a folder with its subfolders and pastes.',
+ audience: 'human',
+ aiMetadata: {
+ description: 'Gets one folder picked from a dropdown, with its pastes and subfolders (each with their own pastes and subfolders) unless Include Contents is off; then only the direct subfolders (ID, name) are listed and pastes is empty. Read-only and idempotent. Needs an API key in the Pastefy connection.',
+ idempotent: true,
+ },
props: {
- folder_id: pastefyCommon.folder_id(true),
+ folder_id: pastefyProps.folderDropdown({ required: true, displayName: 'Folder', description: 'The folder to get.' }),
+ include_contents: Property.Checkbox({ displayName: 'Include Contents', description: 'Add pastes and subfolder contents.', required: false, defaultValue: true }),
},
- async run(context) {
- const client = makeClient(context.auth, context.propsValue);
- const folder = await client.getFolder(
- context.propsValue.folder_id as string
- );
- return folder;
+ outputSchema: pastefyOutputSchemas.folder,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.getFolder({ auth, folderId: propsValue.folder_id, includeContents: propsValue.include_contents !== false });
},
});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/get-paste.ts b/packages/pieces/community/pastefy/src/lib/actions/get-paste.ts
index 2e209381f21..5f0f4f0f271 100644
--- a/packages/pieces/community/pastefy/src/lib/actions/get-paste.ts
+++ b/packages/pieces/community/pastefy/src/lib/actions/get-paste.ts
@@ -1,41 +1,26 @@
-import { Property, createAction } from '@activepieces/pieces-framework';
-import { makeClient } from '../common';
-import { pastefyAuth } from '../..';
-import CryptoJS from 'crypto-js';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pastefyAiProps } from '../common/ai-props';
+import { pastefyAuth } from '../common/auth';
+import { pastefyOutputSchemas } from '../common/output-schemas';
+import { pastefyRequests } from '../common/requests';
export default createAction({
auth: pastefyAuth,
name: 'get_paste',
classification: 'READ',
displayName: 'Get Paste',
- description: 'Retrieves a paste',
+ description: 'Retrieves a paste.',
audience: 'both',
- aiMetadata: { description: 'Fetches a single paste by its ID from a Pastefy instance. Use to read the content/metadata of a known paste. If the paste is encrypted and an encryption password is provided, the content (and title) are AES-decrypted client-side. Read-only and idempotent.', idempotent: true },
+ aiMetadata: {
+ description: 'Gets one paste by its 8-character ID: content, title, visibility, folder ID, tags, owner and raw URL. For an encrypted paste give the encryption password to get plain text (decrypted: true); a wrong password fails the step, and without one the content stays ciphertext. Read-only and idempotent. Works without an API key for public and unlisted pastes.',
+ idempotent: true,
+ },
props: {
- paste_id: Property.ShortText({
- displayName: 'Paste ID',
- required: true,
- }),
- password: Property.ShortText({
- displayName: 'Encryption Password',
- description: 'Decrypts the paste with this password',
- required: false,
- }),
+ paste_id: pastefyAiProps.pasteId(),
+ password: Property.ShortText({ displayName: 'Encryption Password', description: 'Decrypts an encrypted paste with this password.', required: false }),
},
- async run(context) {
- const client = makeClient(context.auth, context.propsValue);
- const password = context.propsValue.password;
- const paste = await client.getPaste(context.propsValue.paste_id);
- if (paste.encrypted && password) {
- paste.content = CryptoJS.AES.decrypt(paste.content, password).toString(
- CryptoJS.enc.Utf8
- );
- if (paste.title) {
- paste.title = CryptoJS.AES.decrypt(paste.title, password).toString(
- CryptoJS.enc.Utf8
- );
- }
- }
- return paste;
+ outputSchema: pastefyOutputSchemas.paste,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.getPaste({ auth, pasteId: propsValue.paste_id, password: propsValue.password });
},
});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/index.ts b/packages/pieces/community/pastefy/src/lib/actions/index.ts
index 27f498fd963..2e964f3ad48 100644
--- a/packages/pieces/community/pastefy/src/lib/actions/index.ts
+++ b/packages/pieces/community/pastefy/src/lib/actions/index.ts
@@ -1,3 +1,9 @@
+import createFolderAi from './ai/create-folder-ai';
+import createPasteAi from './ai/create-paste-ai';
+import deleteFolderAi from './ai/delete-folder-ai';
+import editPasteAi from './ai/edit-paste-ai';
+import getFolderAi from './ai/get-folder-ai';
+import listFolders from './ai/list-folders';
import createFolder from './create-folder';
import createPaste from './create-paste';
import deleteFolder from './delete-folder';
@@ -6,6 +12,8 @@ import editPaste from './edit-paste';
import getFolder from './get-folder';
import getFolderHierarchy from './get-folder-hierarchy';
import getPaste from './get-paste';
+import listMyPastes from './list-my-pastes';
+import searchPublicPastes from './search-public-pastes';
export default [
createPaste,
@@ -16,4 +24,12 @@ export default [
getFolder,
getFolderHierarchy,
deleteFolder,
+ listMyPastes,
+ searchPublicPastes,
+ createPasteAi,
+ editPasteAi,
+ createFolderAi,
+ getFolderAi,
+ deleteFolderAi,
+ listFolders,
];
diff --git a/packages/pieces/community/pastefy/src/lib/actions/list-my-pastes.ts b/packages/pieces/community/pastefy/src/lib/actions/list-my-pastes.ts
new file mode 100644
index 00000000000..24c579d213e
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/actions/list-my-pastes.ts
@@ -0,0 +1,38 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pastefyAuth } from '../common/auth';
+import { pastefyOutputSchemas } from '../common/output-schemas';
+import { pastefyRequests } from '../common/requests';
+
+export default createAction({
+ auth: pastefyAuth,
+ name: 'list_my_pastes',
+ classification: 'SEARCH',
+ displayName: 'List My Pastes',
+ description: 'Lists pastes in your account, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Lists pastes owned by the connected account, newest first, filtered by search text, folder ID and tags. Returns one page {pastes, page, page_limit, count, has_more}; has_more true means request page + 1. Content is cut to 300 characters unless Shorten Content is off. Read-only and idempotent. Needs an API key in the Pastefy connection.',
+ idempotent: true,
+ },
+ props: {
+ search: Property.ShortText({ displayName: 'Search', description: 'Text to search for in title and content.', required: false }),
+ folder_id: Property.ShortText({ displayName: 'Folder ID', description: 'Only pastes in this folder (ID from Get Folder Hierarchy or List Folders).', required: false }),
+ tags: Property.Array({ displayName: 'Tags', description: 'Only pastes with these tags.', required: false }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number, starting at 1.', required: false, defaultValue: 1 }),
+ page_limit: Property.Number({ displayName: 'Page Size', description: 'Pastes per page, 1 to 50.', required: false, defaultValue: 20 }),
+ shorten_content: Property.Checkbox({ displayName: 'Shorten Content', description: 'Cut content to 300 characters.', required: false, defaultValue: true }),
+ },
+ outputSchema: pastefyOutputSchemas.pasteList,
+ async run({ auth, propsValue }) {
+ return pastefyRequests.listPastes({
+ auth,
+ source: 'mine',
+ search: propsValue.search,
+ folderId: propsValue.folder_id,
+ tags: propsValue.tags,
+ page: propsValue.page,
+ pageLimit: propsValue.page_limit,
+ shortenContent: propsValue.shorten_content,
+ });
+ },
+});
diff --git a/packages/pieces/community/pastefy/src/lib/actions/search-public-pastes.ts b/packages/pieces/community/pastefy/src/lib/actions/search-public-pastes.ts
new file mode 100644
index 00000000000..db4823645a6
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/actions/search-public-pastes.ts
@@ -0,0 +1,48 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pastefyAuth } from '../common/auth';
+import { pastefyOutputSchemas } from '../common/output-schemas';
+import { pastefyRequests } from '../common/requests';
+
+export default createAction({
+ auth: pastefyAuth,
+ name: 'search_public_pastes',
+ classification: 'SEARCH',
+ displayName: 'Search Public Pastes',
+ description: 'Searches public pastes from everyone on the instance.',
+ audience: 'both',
+ aiMetadata: {
+ description: 'Searches PUBLIC pastes from all users on the Pastefy instance by text and tags, from all public pastes, the latest or the trending list. Returns one page {pastes, page, page_limit, count, has_more}; has_more true means request page + 1. Content is cut to 300 characters unless Shorten Content is off. Read-only and idempotent. Works without an API key.',
+ idempotent: true,
+ },
+ props: {
+ search: Property.ShortText({ displayName: 'Search', description: 'Text to search for.', required: false }),
+ list: Property.StaticDropdown({
+ displayName: 'List',
+ description: 'Which public list to search.',
+ required: false,
+ defaultValue: 'public',
+ options: { options: [
+ { label: 'All public pastes', value: 'public' },
+ { label: 'Latest', value: 'latest' },
+ { label: 'Trending', value: 'trending' },
+ ] },
+ }),
+ tags: Property.Array({ displayName: 'Tags', description: 'Only pastes with these tags.', required: false }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number, starting at 1.', required: false, defaultValue: 1 }),
+ page_limit: Property.Number({ displayName: 'Page Size', description: 'Pastes per page, 1 to 50.', required: false, defaultValue: 20 }),
+ shorten_content: Property.Checkbox({ displayName: 'Shorten Content', description: 'Cut content to 300 characters.', required: false, defaultValue: true }),
+ },
+ outputSchema: pastefyOutputSchemas.pasteList,
+ async run({ auth, propsValue }) {
+ const list = propsValue.list;
+ return pastefyRequests.listPastes({
+ auth,
+ source: list === 'latest' || list === 'trending' ? list : 'public',
+ search: propsValue.search,
+ tags: propsValue.tags,
+ page: propsValue.page,
+ pageLimit: propsValue.page_limit,
+ shortenContent: propsValue.shorten_content,
+ });
+ },
+});
diff --git a/packages/pieces/community/pastefy/src/lib/common/ai-props.ts b/packages/pieces/community/pastefy/src/lib/common/ai-props.ts
new file mode 100644
index 00000000000..ee7e6b6f022
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/common/ai-props.ts
@@ -0,0 +1,15 @@
+import { Property } from '@activepieces/pieces-framework';
+
+export const pastefyAiProps = { pasteId, folderId };
+
+function pasteId() {
+ return Property.ShortText({
+ displayName: 'Paste ID',
+ description: 'The 8-character paste ID, as in https://pastefy.app/<id>. Get it from List My Pastes or Search Public Pastes.',
+ required: true,
+ });
+}
+
+function folderId({ required, displayName, description }: { required: boolean; displayName: string; description: string }) {
+ return Property.ShortText({ displayName, description, required });
+}
diff --git a/packages/pieces/community/pastefy/src/lib/common/auth.ts b/packages/pieces/community/pastefy/src/lib/common/auth.ts
new file mode 100644
index 00000000000..01da32f4f03
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/common/auth.ts
@@ -0,0 +1,52 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { PieceAuth, Property } from '@activepieces/pieces-framework';
+import { pastefyClient } from './client';
+
+export const pastefyAuth = PieceAuth.CustomAuth({
+ displayName: 'Pastefy Connection',
+ description: `
+To connect Pastefy:
+1. Sign in at [pastefy.app](https://pastefy.app) (or your own Pastefy instance).
+2. Open [API Keys](https://pastefy.app/apikeys) and create a key with the paste and folder permissions you need.
+3. Paste the key below (optional: without it you can only create and read pastes anonymously). Leave the instance URL as is unless you run your own Pastefy server.
+`,
+ required: true,
+ props: {
+ instance_url: Property.ShortText({
+ displayName: 'Pastefy Instance URL',
+ description: 'Base URL of your Pastefy server, for example https://pastefy.app.',
+ required: false,
+ defaultValue: 'https://pastefy.app',
+ }),
+ token: PieceAuth.SecretText({
+ displayName: 'API Key',
+ description: 'Optional. Without a key you can only create and read pastes anonymously; folders, your own pastes, editing and deleting need a key.',
+ required: false,
+ }),
+ },
+ validate: async ({ auth }) => {
+ if (!pastefyClient.tokenOf({ auth: { props: auth } })) {
+ return { valid: true };
+ }
+ try {
+ const user = await pastefyClient.request({
+ auth: { props: auth },
+ method: HttpMethod.GET,
+ path: '/user',
+ });
+ if (pastefyClient.isRecord(user) && user['logged_in'] === true) {
+ return { valid: true };
+ }
+ return { valid: false, error: 'Pastefy did not accept this API key.' };
+ } catch (error) {
+ const status = pastefyClient.statusOf(error);
+ if (status === 401 || status === 403) {
+ return { valid: false, error: 'Invalid API key.' };
+ }
+ return {
+ valid: false,
+ error: error instanceof Error ? error.message : 'Could not reach the Pastefy instance.',
+ };
+ }
+ },
+});
diff --git a/packages/pieces/community/pastefy/src/lib/common/client.ts b/packages/pieces/community/pastefy/src/lib/common/client.ts
index 5fe344cbb29..7aff3634e99 100644
--- a/packages/pieces/community/pastefy/src/lib/common/client.ts
+++ b/packages/pieces/community/pastefy/src/lib/common/client.ts
@@ -1,156 +1,168 @@
-import {
- Authentication,
- AuthenticationType,
- HttpMessageBody,
- HttpMethod,
- QueryParams,
- httpClient,
-} from '@activepieces/pieces-common';
-import {
- Folder,
- FolderCreateRequest,
- FolderCreateResponse,
- FolderGetRequest,
- FolderHierarchy,
- FolderListRequest,
-} from './models/folder';
-import { ActionResponse, prepareQueryRequest } from './models/common';
-import {
- Paste,
- PasteCreateRequest,
- PasteCreateResponse,
- PasteEditRequest,
- PasteListRequest,
- PasteShareRequest,
-} from './models/paste';
-
-function ensureSuccessfulResponse<T extends ActionResponse>(res: T): T {
- if (!res.success) {
- throw 'Request failed';
- }
- return res;
-}
+import { httpClient, HttpMethod, HttpResponse, QueryParams } from '@activepieces/pieces-common';
+
+export const pastefyClient = { request, send, seg, isRecord, statusOf, instanceUrl, apiBase, tokenOf, requireToken, wholeNumber, toApiError, verifiedTls };
-export class PastefyClient {
+const DEFAULT_INSTANCE = 'https://pastefy.app';
+const REQUEST_TIMEOUT_MS = 30_000;
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+export class PastefyApiError extends Error {
constructor(
- private apiKey?: string,
- private instanceUrl = 'https://pastefy.app'
- ) {}
-
- async makeRequest<T extends HttpMessageBody>(
- method: HttpMethod,
- url: string,
- query?: QueryParams,
- body?: object
- ): Promise<T> {
- const authentication: Authentication | undefined = this.apiKey
- ? {
- type: AuthenticationType.BEARER_TOKEN,
- token: this.apiKey,
- }
- : undefined;
- const res = await httpClient.sendRequest<T>({
- method,
- url: this.instanceUrl + '/api/v2' + url,
- queryParams: query,
- body,
- authentication,
- });
- return res.body;
+ message: string,
+ public readonly status: number,
+ public readonly responseBody: unknown,
+ ) {
+ super(message);
+ this.name = 'PastefyApiError';
}
+}
- async createFolder(
- request: FolderCreateRequest
- ): Promise<FolderCreateResponse> {
- return ensureSuccessfulResponse<FolderCreateResponse>(
- await this.makeRequest(HttpMethod.POST, '/folder', undefined, request)
- );
- }
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
- async listFolders(request: FolderListRequest): Promise<Folder[]> {
- return await this.makeRequest(
- HttpMethod.GET,
- '/folder',
- prepareQueryRequest(request)
- );
+function instanceUrl({ auth }: { auth: PastefyAuthValue }): string {
+ const raw = (auth.props.instance_url ?? '').trim() || DEFAULT_INSTANCE;
+ const parsed = URL.canParse(raw) ? new URL(raw) : null;
+ if (!parsed || (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || parsed.username || parsed.password || parsed.search || parsed.hash) {
+ throw new Error('The Pastefy Instance URL must be a plain http(s) URL such as https://pastefy.app.');
}
+ return `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`;
+}
- async getFolder(id: string, request?: FolderGetRequest): Promise<Folder> {
- return await this.makeRequest(
- HttpMethod.GET,
- '/folder/' + id,
- prepareQueryRequest(request)
- );
- }
+function apiBase({ auth }: { auth: PastefyAuthValue }): string {
+ return `${instanceUrl({ auth })}/api/v2`;
+}
- async getFolderHierarchy(parentId?: string): Promise<FolderHierarchy[]> {
- const folders = await this.listFolders({
- page_size: 99999,
- filter: {
- parent: parentId || 'null',
- },
- });
- const hierarchies: FolderHierarchy[] = [];
- for (const folder of folders) {
- hierarchies.push({
- id: folder.id,
- name: folder.name,
- children: await this.getFolderHierarchy(folder.id),
- });
- }
- return hierarchies;
- }
+function tokenOf({ auth }: { auth: PastefyAuthValue }): string | undefined {
+ const token = (auth.props.token ?? '').trim();
+ return token === '' ? undefined : token;
+}
- async deleteFolder(id: string): Promise<ActionResponse> {
- return ensureSuccessfulResponse(
- await this.makeRequest(HttpMethod.DELETE, '/folder/' + id)
- );
+function requireToken({ auth }: { auth: PastefyAuthValue }): string {
+ const token = tokenOf({ auth });
+ if (!token) {
+ throw new Error('This action needs an API key in the Pastefy connection. Create one at https://pastefy.app/apikeys and add it to the connection.');
}
+ return token;
+}
- async createPaste(request: PasteCreateRequest): Promise<PasteCreateResponse> {
- return ensureSuccessfulResponse<PasteCreateResponse>(
- await this.makeRequest(HttpMethod.POST, '/paste', undefined, request)
- );
+function seg({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'string' ? value.trim() : typeof value === 'number' ? String(value) : '';
+ if (text === '' || text === '.' || text === '..') {
+ throw new Error(`${label} is required.`);
}
+ return encodeURIComponent(text);
+}
- async listPastes(request: PasteListRequest): Promise<Paste[]> {
- return await this.makeRequest(
- HttpMethod.GET,
- '/paste',
- prepareQueryRequest(request)
- );
+function exceptionOf(responseBody: unknown): string {
+ if (isRecord(responseBody)) {
+ const exception = responseBody['exception'];
+ const message = responseBody['message'];
+ if (typeof message === 'string' && message.trim()) return message.trim();
+ if (typeof exception === 'string' && exception.trim()) return exception.trim();
}
-
- async getPaste(id: string): Promise<Paste> {
- return await this.makeRequest(HttpMethod.GET, '/paste/' + id);
+ if (typeof responseBody === 'string' && responseBody.trim()) {
+ return responseBody.trim().slice(0, 300);
}
+ return 'request failed';
+}
+
+function hintFor({ status, exception }: { status: number; exception: string }): string {
+ if (exception === 'PastePrivateException') return ' The paste is private and does not belong to this API key\'s account.';
+ if (status === 401) return ' Check the API key in the Pastefy connection.';
+ if (status === 403) return ' The API key lacks the permission this step needs (for example pastes:edit or folders:delete). Create a key with that permission.';
+ if (status === 404) return ' Nothing with that ID exists on this Pastefy instance.';
+ if (status === 429) return ' Pastefy rate limit reached; try again later.';
+ return '';
+}
+
+function toApiError({ status, responseBody }: { status: number; responseBody: unknown }): PastefyApiError {
+ const exception = status >= 300 && status < 400 ? 'unexpected redirect' : exceptionOf(responseBody);
+ return new PastefyApiError(`Pastefy API error (${status}): ${exception}.${hintFor({ status, exception })}`, status, responseBody);
+}
- async editPaste(
- id: string,
- request: PasteEditRequest
- ): Promise<ActionResponse> {
- return ensureSuccessfulResponse(
- await this.makeRequest(HttpMethod.PUT, '/paste/' + id, undefined, request)
+function buildQuery(query?: Record<string, QueryValue>): QueryParams {
+ return Object.fromEntries(
+ Object.entries(query ?? {})
+ .filter(([, value]) => value !== undefined && value !== null && value !== '')
+ .map(([key, value]) => [key, String(value)]),
+ );
+}
+
+function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));
+ return verifiedTlsAgent;
+}
+
+function failureOf(error: unknown): { status: number; body: unknown } | null {
+ if (error === null || typeof error !== 'object') return null;
+ const response = Reflect.get(error, 'response');
+ if (!isRecord(response)) return null;
+ const status = response['status'];
+ return typeof status === 'number' ? { status, body: response['body'] } : null;
+}
+
+async function send({ auth, method, path, query, body, allowAnonymous }: PastefyRequest): Promise<{ status: number; body: unknown }> {
+ const token = allowAnonymous === true ? tokenOf({ auth }) : requireToken({ auth });
+ const dispatcher = await verifiedTls();
+ const hasBody = body !== undefined && method !== HttpMethod.GET && method !== HttpMethod.DELETE;
+ const headers: Record<string, string> = { accept: 'application/json' };
+ if (token) headers['authorization'] = `Bearer ${token}`;
+ if (hasBody) headers['content-type'] = 'application/json';
+ try {
+ const response: HttpResponse = await httpClient.sendRequest(
+ {
+ method,
+ url: `${apiBase({ auth })}${path}`,
+ headers,
+ queryParams: buildQuery(query),
+ body: hasBody ? body : undefined,
+ timeout: REQUEST_TIMEOUT_MS,
+ followRedirects: false,
+ redactBodyInErrors: true,
+ },
+ { dispatcher },
);
+ return { status: response.status, body: response.body };
+ } catch (error) {
+ const failure = failureOf(error);
+ if (failure) return failure;
+ throw error;
}
+}
- async deletePaste(id: string): Promise<ActionResponse> {
- return ensureSuccessfulResponse(
- await this.makeRequest(HttpMethod.DELETE, '/paste/' + id)
- );
+async function request(req: PastefyRequest): Promise<unknown> {
+ const response = await send(req);
+ if (response.status < 200 || response.status >= 300) {
+ throw toApiError({ status: response.status, responseBody: response.body });
+ }
+ if (isRecord(response.body) && response.body['success'] === false) {
+ throw new PastefyApiError(`Pastefy did not apply the change: ${exceptionOf(response.body)}. The item may not exist or may belong to another account.`, response.status, response.body);
}
+ return response.body;
+}
- async sharePaste(
- id: string,
- request: PasteShareRequest
- ): Promise<ActionResponse> {
- return ensureSuccessfulResponse(
- await this.makeRequest(
- HttpMethod.POST,
- '/paste/' + id + '/friend',
- undefined,
- request
- )
- );
+function statusOf(error: unknown): number | undefined {
+ return error instanceof PastefyApiError ? error.status : undefined;
+}
+
+function wholeNumber({ value, label, min, max, fallback }: { value: unknown; label: string; min: number; max: number; fallback: number }): number {
+ const parsed = typeof value === 'string' && value.trim() !== '' ? Number(value) : value;
+ if (parsed === undefined || parsed === null || parsed === '') return fallback;
+ if (typeof parsed !== 'number' || !Number.isInteger(parsed) || parsed < min || parsed > max) {
+ throw new Error(`${label} must be a whole number from ${min} to ${max}.`);
}
+ return parsed;
}
+
+type QueryValue = string | number | boolean | undefined | null;
+export type PastefyAuthValue = { props: { instance_url?: string; token?: string } };
+export type PastefyRequest = {
+ auth: PastefyAuthValue;
+ method: HttpMethod;
+ path: string;
+ query?: Record<string, QueryValue>;
+ body?: unknown;
+ allowAnonymous?: boolean;
+};
diff --git a/packages/pieces/community/pastefy/src/lib/common/index.ts b/packages/pieces/community/pastefy/src/lib/common/index.ts
deleted file mode 100644
index 0d851015812..00000000000
--- a/packages/pieces/community/pastefy/src/lib/common/index.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import {
- AppConnectionValueForAuthProperty,
- PiecePropValueSchema,
- PiecePropertyMap,
- Property,
- StaticPropsValue,
-} from '@activepieces/pieces-framework';
-import { PastefyClient } from './client';
-import { FolderHierarchy } from './models/folder';
-import { PasteVisibility } from './models/paste';
-import { pastefyAuth } from '../..';
-
-interface FlatFolder {
- id: string;
- name: string;
-}
-
-function flattenFolderHierarchy(hierarchy: FolderHierarchy[]): FlatFolder[] {
- const folders: FlatFolder[] = [];
- for (const h of hierarchy) {
- folders.push({ id: h.id, name: h.name });
- flattenFolderHierarchy(h.children).forEach((e) => {
- folders.push({
- id: e.id,
- name: h.name + ' / ' + e.name,
- });
- });
- }
- return folders;
-}
-
-export function formatDate(date?: string): string | undefined {
- if (!date) return date;
- return date
- .replace('T', ' ')
- .replace('Z', '')
- .replace(/\.[0-9]{3}/, '');
-}
-
-export const pastefyCommon = {
- folder_id: (required = true, displayName = 'Folder') =>
- Property.Dropdown({
- auth: pastefyAuth,
- description: 'A folder',
- displayName: displayName,
- required,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- placeholder: 'setup authentication first',
- options: [],
- };
- }
- const client = makeClient(
- auth,
- { ...auth.props }
- );
- const folders = await client.getFolderHierarchy();
-
- return {
- disabled: false,
- options: flattenFolderHierarchy(folders).map((folder) => {
- return {
- label: folder.name,
- value: folder.id,
- };
- }),
- };
- },
- }),
- visibility: (required = true) =>
- Property.StaticDropdown({
- displayName: 'Visibility',
- required,
- options: {
- options: [
- { label: 'Public', value: PasteVisibility.PUBLIC },
- { label: 'Unlisted', value: PasteVisibility.UNLISTED },
- { label: 'Private', value: PasteVisibility.PRIVATE },
- ],
- },
- }),
-};
-
-export function makeClient(
- auth: AppConnectionValueForAuthProperty<typeof pastefyAuth>,
- propsValue: StaticPropsValue<PiecePropertyMap>
-): PastefyClient {
- return new PastefyClient(auth.props.token || undefined, propsValue.instance_url);
-}
diff --git a/packages/pieces/community/pastefy/src/lib/common/models/common.ts b/packages/pieces/community/pastefy/src/lib/common/models/common.ts
deleted file mode 100644
index 99e584775ba..00000000000
--- a/packages/pieces/community/pastefy/src/lib/common/models/common.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { QueryParams } from '@activepieces/pieces-common';
-
-export interface ActionResponse {
- success: boolean;
-}
-
-export interface ListRequest {
- page?: number;
- page_size?: number;
- search?: string;
- filter?: Record<string, any>;
-}
-
-function emptyValueFilter(
- accessor: (key: string) => any
-): (key: string) => boolean {
- return (key: string) => {
- const val = accessor(key);
- return (
- val !== null &&
- val !== undefined &&
- (typeof val != 'string' || val.length > 0)
- );
- };
-}
-
-export function prepareQueryRequest(
- request?: ListRequest | Record<string, any | undefined>
-): QueryParams {
- const params: QueryParams = {};
- if (!request) return params;
- const requestObj = request as Record<string, any>;
- Object.keys(request)
- .filter((k) => k != 'filter')
- .filter(emptyValueFilter((k) => requestObj[k]))
- .forEach((k: string) => {
- params[k] = (request as Record<string, any>)[k].toString();
- });
- if (request.filter) {
- const filter = request.filter; // For some reason required to pass the unidentified check
- Object.keys(request.filter)
- .filter(emptyValueFilter((k) => filter[k]))
- .forEach((k) => {
- params['filter[' + k + ']'] = filter[k].toString();
- });
- }
- return params;
-}
diff --git a/packages/pieces/community/pastefy/src/lib/common/models/folder.ts b/packages/pieces/community/pastefy/src/lib/common/models/folder.ts
deleted file mode 100644
index 0c248c0946a..00000000000
--- a/packages/pieces/community/pastefy/src/lib/common/models/folder.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { ActionResponse, ListRequest } from './common';
-import { Paste } from './paste';
-
-export interface Folder {
- exists: boolean;
- id: string;
- name: string;
- user_id: string;
- children?: Folder[];
- pastes?: Paste[];
- created: string;
-}
-
-export interface FolderCreateRequest {
- name: string;
- parent?: string;
-}
-
-export interface FolderCreateResponse extends ActionResponse {
- folder: Folder;
-}
-
-export interface FolderEditRequest {
- name?: string;
-}
-
-export interface FolderEditResponse extends ActionResponse {
- folder: Folder;
-}
-
-export interface FolderGetRequest {
- hide_children?: string;
-}
-
-export interface FolderListRequest extends ListRequest {
- user_id?: string;
-}
-
-export interface FolderHierarchy {
- id: string;
- name: string;
- children: FolderHierarchy[];
-}
diff --git a/packages/pieces/community/pastefy/src/lib/common/models/paste.ts b/packages/pieces/community/pastefy/src/lib/common/models/paste.ts
deleted file mode 100644
index 4231fbe9d6e..00000000000
--- a/packages/pieces/community/pastefy/src/lib/common/models/paste.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { ActionResponse } from './common';
-
-export enum PasteType {
- PASTE = 'PASTE',
- MULTI_PASTE = 'MULTI_PASTE',
-}
-
-export enum PasteVisibility {
- PUBLIC = 'PUBLIC',
- UNLISTED = 'UNLISTED',
- PRIVATE = 'PRIVATE',
-}
-
-export interface Paste {
- exists: boolean;
- id: string;
- content: string;
- title: string;
- encrypted: boolean;
- folder: string;
- user_id?: string;
- visibility: PasteVisibility;
- forked_from?: string;
- raw_url: string;
- type: PasteType;
- created_at: string;
- expire_at?: string;
-}
-
-export interface PasteCreateRequest {
- title?: string;
- content: string;
- encrypted?: boolean;
- folder?: string;
- expire_at?: string;
- forked_from?: string;
- visibility?: PasteVisibility;
- type?: PasteType;
-}
-
-export interface PasteCreateResponse extends ActionResponse {
- paste: Paste;
-}
-
-export interface PasteEditRequest {
- title?: string;
- content?: string;
- encrypted?: boolean;
- folder?: string;
- type?: PasteType;
- visibility?: PasteVisibility;
- expire_at?: string;
-}
-
-export interface PasteEditResponse extends ActionResponse {
- paste: Paste;
-}
-
-export interface PasteShareRequest {
- friend: string;
-}
-
-export interface PasteListRequest {
- page?: number;
- page_size?: number;
- search?: string;
- shorten_content?: boolean;
-}
-
-export interface PasteListTrendingRequest {
- page?: number;
- page_size?: number;
- trending?: boolean;
- shorten_content?: boolean;
-}
diff --git a/packages/pieces/community/pastefy/src/lib/common/models/user.ts b/packages/pieces/community/pastefy/src/lib/common/models/user.ts
deleted file mode 100644
index e82c7511da5..00000000000
--- a/packages/pieces/community/pastefy/src/lib/common/models/user.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-export enum UserType {
- USER,
- ADMIN,
- BLOCKED,
- AWAITING_ACCESS,
-}
-
-export interface User {
- name: string;
- avatar?: string;
- displayName: string;
-}
-
-export interface DetailedUser extends User {
- id: string;
- color: string;
- profile_picture?: string;
- logged_in: true;
- auth_type: string;
- type: UserType;
-}
diff --git a/packages/pieces/community/pastefy/src/lib/common/output-schemas.ts b/packages/pieces/community/pastefy/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..bfc6c40d7b9
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/common/output-schemas.ts
@@ -0,0 +1,82 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+const userFields: Fields = [
+ { key: 'id', label: 'User ID' },
+ { key: 'name', label: 'Username' },
+ { key: 'display_name', label: 'Display Name' },
+ { key: 'avatar', label: 'Avatar URL', format: 'url' },
+];
+
+const pasteFields: Fields = [
+ { key: 'id', label: 'Paste ID' },
+ { key: 'title', label: 'Title' },
+ { key: 'content', label: 'Content', description: 'Paste text. Ciphertext when the paste is encrypted and was not decrypted; cut to 300 characters in lists with Shorten Content on.' },
+ { key: 'encrypted', label: 'Encrypted', format: 'boolean' },
+ { key: 'folder', label: 'Folder ID' },
+ { key: 'user_id', label: 'Owner User ID' },
+ { key: 'visibility', label: 'Visibility', description: 'PUBLIC, UNLISTED or PRIVATE.' },
+ { key: 'type', label: 'Type', description: 'PASTE or MULTI_PASTE.' },
+ { key: 'raw_url', label: 'Raw URL', format: 'url' },
+ { key: 'forked_from', label: 'Forked From Paste ID' },
+ { key: 'created_at', label: 'Created At', description: 'Server time, format YYYY-MM-DD HH:MM:SS.f.' },
+ { key: 'expire_at', label: 'Expires At', description: 'Server time, format YYYY-MM-DD HH:MM:SS.f; absent when the paste never expires.' },
+ { key: 'tags', label: 'Tags', description: 'List of tag strings.' },
+ { key: 'starred', label: 'Starred', format: 'boolean' },
+ { key: 'exists', label: 'Exists', format: 'boolean' },
+ { key: 'user', label: 'Owner', children: userFields },
+];
+
+const singlePasteFields: Fields = [
+ ...pasteFields,
+ { key: 'decrypted', label: 'Decrypted', format: 'boolean', description: 'True when the piece decrypted content and title with the given password.' },
+];
+
+const folderFields: Fields = [
+ { key: 'id', label: 'Folder ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'user_id', label: 'Owner User ID' },
+ { key: 'created', label: 'Created At' },
+ { key: 'exists', label: 'Exists', format: 'boolean' },
+ { key: 'children', label: 'Subfolders', description: 'Direct subfolders; with contents included each also carries its own children and pastes.', listItems: [{ key: 'id', label: 'Folder ID' }, { key: 'name', label: 'Name' }, { key: 'user_id', label: 'Owner User ID' }, { key: 'created', label: 'Created At' }], labelKey: 'name' },
+ { key: 'pastes', label: 'Pastes', listItems: pasteFields, labelKey: 'title' },
+];
+
+const treeNodeFields: Fields = [
+ { key: 'id', label: 'Folder ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'children', label: 'Subfolders', description: 'Same shape, nested to any depth.', listItems: [{ key: 'id', label: 'Folder ID' }, { key: 'name', label: 'Name' }, { key: 'children', label: 'Subfolders' }], labelKey: 'name' },
+];
+
+export const pastefyOutputSchemas = {
+ paste: { fields: singlePasteFields },
+ folder: { fields: folderFields },
+ folderTree: { fields: treeNodeFields, itemLabel: '{name}' },
+ folderList: {
+ fields: [
+ { key: 'folders', label: 'Folders', labelKey: 'path', listItems: [
+ { key: 'id', label: 'Folder ID' },
+ { key: 'name', label: 'Name' },
+ { key: 'path', label: 'Path', description: 'Names from the top folder down, joined with " / ".' },
+ { key: 'parent_id', label: 'Parent Folder ID', description: 'Null for top-level folders.' },
+ ] },
+ { key: 'count', label: 'Count', format: 'number' },
+ ],
+ },
+ pasteList: {
+ fields: [
+ { key: 'pastes', label: 'Pastes', listItems: pasteFields, labelKey: 'title' },
+ { key: 'page', label: 'Page', format: 'number' },
+ { key: 'page_limit', label: 'Page Size', format: 'number' },
+ { key: 'count', label: 'Count On This Page', format: 'number' },
+ { key: 'has_more', label: 'Has More', format: 'boolean', description: 'True when this page is full, so the next page may hold more.' },
+ ],
+ },
+ deleted: {
+ fields: [
+ { key: 'deleted', label: 'Deleted', format: 'boolean', description: 'False when the item was already gone.' },
+ { key: 'id', label: 'ID' },
+ ],
+ },
+} satisfies Record<string, OutputSchema>;
+
+type Fields = OutputSchema['fields'];
diff --git a/packages/pieces/community/pastefy/src/lib/common/props.ts b/packages/pieces/community/pastefy/src/lib/common/props.ts
new file mode 100644
index 00000000000..437de0ce1d2
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/common/props.ts
@@ -0,0 +1,50 @@
+import { Property } from '@activepieces/pieces-framework';
+import { pastefyAuth } from './auth';
+import { pastefyRequests } from './requests';
+
+export const pastefyProps = { folderDropdown, visibility, tags };
+
+function folderDropdown({ required, displayName, description }: { required: boolean; displayName: string; description: string }) {
+ return Property.Dropdown({
+ auth: pastefyAuth,
+ displayName,
+ description,
+ required,
+ refreshers: [],
+ options: async ({ auth }) => {
+ if (!auth) {
+ return { disabled: true, placeholder: 'Connect your Pastefy account first.', options: [] };
+ }
+ try {
+ const tree = await pastefyRequests.folderTree({ auth });
+ const folders = pastefyRequests.flattenTree({ tree, parentPath: '', parentId: null });
+ return {
+ disabled: false,
+ placeholder: folders.length === 0 ? 'No folders yet.' : undefined,
+ options: folders.map((folder) => ({ label: folder.path, value: folder.id })),
+ };
+ } catch (error) {
+ return { disabled: true, placeholder: error instanceof Error ? error.message : 'Could not load folders.', options: [] };
+ }
+ },
+ });
+}
+
+function visibility({ required, description }: { required: boolean; description: string }) {
+ return Property.StaticDropdown({
+ displayName: 'Visibility',
+ description,
+ required,
+ options: { options: VISIBILITY_OPTIONS },
+ });
+}
+
+function tags({ description }: { description: string }) {
+ return Property.Array({ displayName: 'Tags', description, required: false });
+}
+
+const VISIBILITY_OPTIONS = [
+ { label: 'Public', value: 'PUBLIC' },
+ { label: 'Unlisted', value: 'UNLISTED' },
+ { label: 'Private', value: 'PRIVATE' },
+];
diff --git a/packages/pieces/community/pastefy/src/lib/common/requests.ts b/packages/pieces/community/pastefy/src/lib/common/requests.ts
new file mode 100644
index 00000000000..69fc92ff41c
--- /dev/null
+++ b/packages/pieces/community/pastefy/src/lib/common/requests.ts
@@ -0,0 +1,269 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import CryptoJS from 'crypto-js';
+import { PastefyAuthValue, pastefyClient } from './client';
+
+export const pastefyRequests = { getPaste, createPaste, editPaste, deleteItem, createFolder, getFolder, folderTree, subtree, flattenTree, listPastes, formatExpiry, tagList, decryptPaste, encrypt };
+
+async function getPaste({ auth, pasteId, password }: { auth: PastefyAuthValue; pasteId: string; password?: string }): Promise<PasteOutput> {
+ const body = await pastefyClient.request({
+ auth,
+ method: HttpMethod.GET,
+ path: `/paste/${pastefyClient.seg({ value: pasteId, label: 'Paste ID' })}`,
+ allowAnonymous: true,
+ });
+ return decryptPaste({ paste: asRecord(body), password });
+}
+
+async function createPaste({ auth, input }: { auth: PastefyAuthValue; input: PasteInput }): Promise<PasteOutput> {
+ if (!input.content) {
+ throw new Error('Content is required.');
+ }
+ const password = passwordOf(input.password);
+ const title = cleanText(input.title);
+ const requestedFolder = cleanText(input.folderId);
+ if (requestedFolder) {
+ await getFolder({ auth, folderId: requestedFolder, includeContents: false });
+ }
+ const body = await pastefyClient.request({
+ auth,
+ method: HttpMethod.POST,
+ path: '/paste',
+ allowAnonymous: true,
+ body: {
+ content: password ? encrypt({ text: input.content, password }) : input.content,
+ ...(title ? { title: password ? encrypt({ text: title, password }) : title } : {}),
+ encrypted: password !== undefined,
+ ...(requestedFolder ? { folder: requestedFolder } : {}),
+ ...(input.visibility ? { visibility: input.visibility } : {}),
+ ...(input.expiry ? { expire_at: formatExpiry(input.expiry) } : {}),
+ ...(tagList(input.tags).length > 0 ? { tags: tagList(input.tags) } : {}),
+ },
+ });
+ const paste = asRecord(pastefyClient.isRecord(body) ? body['paste'] : undefined);
+ if (requestedFolder && paste['folder'] !== requestedFolder) {
+ throw new Error(`The paste ${String(paste['id'])} was created, but Pastefy did not put it in folder ${requestedFolder} (the folder does not exist or belongs to another account).`);
+ }
+ return decryptPaste({ paste, password });
+}
+
+async function editPaste({ auth, pasteId, input }: { auth: PastefyAuthValue; pasteId: string; input: PasteEditInput }): Promise<PasteOutput> {
+ pastefyClient.requireToken({ auth });
+ const password = passwordOf(input.password);
+ const current = await getPaste({ auth, pasteId, password: undefined });
+ const wasEncrypted = current.encrypted === true;
+ const changesText = input.content !== undefined && input.content !== '' || cleanText(input.title) !== undefined;
+ if (wasEncrypted && changesText && !password) {
+ throw new Error('This paste is encrypted. Give the Encryption Password to change its content or title, or the stored text would no longer decrypt.');
+ }
+ if (wasEncrypted && password) {
+ decryptPaste({ paste: current, password });
+ }
+ if (!wasEncrypted && password && !input.content) {
+ throw new Error('To encrypt a paste that is not encrypted yet, give its Content too.');
+ }
+ const title = cleanText(input.title) ?? (!wasEncrypted && password && typeof current.title === 'string' && current.title ? current.title : undefined);
+ const tags = tagList(input.tags);
+ const update = {
+ ...(input.content ? { content: password ? encrypt({ text: input.content, password }) : input.content } : {}),
+ ...(title ? { title: password ? encrypt({ text: title, password }) : title } : {}),
+ ...(password ? { encrypted: true } : {}),
+ ...(cleanText(input.folderId) ? { folder: cleanText(input.folderId) } : {}),
+ ...(input.visibility ? { visibility: input.visibility } : {}),
+ ...(input.expiry ? { expire_at: formatExpiry(input.expiry) } : {}),
+ ...(tags.length > 0 ? { tags } : input.clearTags === true ? { tags: [] } : {}),
+ };
+ if (Object.keys(update).length === 0) {
+ throw new Error('Nothing to update: give at least one field to change.');
+ }
+ await pastefyClient.request({
+ auth,
+ method: HttpMethod.PUT,
+ path: `/paste/${pastefyClient.seg({ value: pasteId, label: 'Paste ID' })}`,
+ body: update,
+ });
+ return getPaste({ auth, pasteId, password });
+}
+
+async function deleteItem({ auth, kind, id, missingIsOk }: { auth: PastefyAuthValue; kind: 'paste' | 'folder'; id: string | undefined; missingIsOk: boolean }): Promise<DeleteOutput> {
+ const label = kind === 'paste' ? 'Paste ID' : 'Folder ID';
+ const path = `/${kind}/${pastefyClient.seg({ value: id, label })}`;
+ if (kind === 'folder') {
+ const response = await pastefyClient.send({ auth, method: HttpMethod.GET, path });
+ if (response.status === 404 || (pastefyClient.isRecord(response.body) && response.body['exists'] === false)) {
+ if (missingIsOk) return { deleted: false, id: id ?? '' };
+ throw pastefyClient.toApiError({ status: 404, responseBody: response.body });
+ }
+ }
+ try {
+ await pastefyClient.request({ auth, method: HttpMethod.DELETE, path });
+ return { deleted: true, id: id ?? '' };
+ } catch (error) {
+ if (missingIsOk && pastefyClient.statusOf(error) === 404) {
+ return { deleted: false, id: id ?? '' };
+ }
+ throw error;
+ }
+}
+
+async function createFolder({ auth, name, parentId }: { auth: PastefyAuthValue; name: string; parentId?: string }): Promise<Record<string, unknown>> {
+ const cleanName = cleanText(name);
+ if (!cleanName) {
+ throw new Error('Name is required.');
+ }
+ const parent = cleanText(parentId);
+ if (parent) {
+ await getFolder({ auth, folderId: parent, includeContents: false });
+ }
+ const body = await pastefyClient.request({
+ auth,
+ method: HttpMethod.POST,
+ path: '/folder',
+ body: { name: cleanName, ...(parent ? { parent } : {}) },
+ });
+ return asRecord(pastefyClient.isRecord(body) ? body['folder'] : undefined);
+}
+
+async function getFolder({ auth, folderId, includeContents }: { auth: PastefyAuthValue; folderId: string | undefined; includeContents: boolean }): Promise<Record<string, unknown>> {
+ const body = await pastefyClient.request({
+ auth,
+ method: HttpMethod.GET,
+ path: `/folder/${pastefyClient.seg({ value: folderId, label: 'Folder ID' })}`,
+ query: { hide_children: includeContents ? undefined : 'true' },
+ });
+ const folder = asRecord(body);
+ if (folder['exists'] === false) {
+ throw pastefyClient.toApiError({ status: 404, responseBody: body });
+ }
+ return folder;
+}
+
+async function folderTree({ auth }: { auth: PastefyAuthValue }): Promise<FolderNode[]> {
+ const body = await pastefyClient.request({
+ auth,
+ method: HttpMethod.GET,
+ path: '/user/folders',
+ query: { hide_pastes: 'true' },
+ });
+ return Array.isArray(body) ? body.map(toNode) : [];
+}
+
+function subtree({ tree, folderId }: { tree: FolderNode[]; folderId: string }): FolderNode[] | null {
+ for (const node of tree) {
+ if (node.id === folderId) return node.children;
+ const found = subtree({ tree: node.children, folderId });
+ if (found) return found;
+ }
+ return null;
+}
+
+function flattenTree({ tree, parentPath, parentId }: { tree: FolderNode[]; parentPath: string; parentId: string | null }): FlatFolder[] {
+ return tree.flatMap((node) => {
+ const path = parentPath ? `${parentPath} / ${node.name}` : node.name;
+ return [{ id: node.id, name: node.name, path, parent_id: parentId }, ...flattenTree({ tree: node.children, parentPath: path, parentId: node.id })];
+ });
+}
+
+async function listPastes({ auth, source, search, folderId, tags, page, pageLimit, shortenContent }: ListPastesInput): Promise<PasteListOutput> {
+ const currentPage = pastefyClient.wholeNumber({ value: page, label: 'Page', min: 1, max: 100000, fallback: 1 });
+ const limit = pastefyClient.wholeNumber({ value: pageLimit, label: 'Page Size', min: 1, max: 50, fallback: 20 });
+ const path = source === 'mine' ? '/user/pastes' : source === 'latest' ? '/public-pastes/latest' : source === 'trending' ? '/public-pastes/trending' : '/public-pastes';
+ const tagFilter = tagList(tags);
+ const body = await pastefyClient.request({
+ auth,
+ method: HttpMethod.GET,
+ path,
+ allowAnonymous: source !== 'mine',
+ query: {
+ page: currentPage,
+ page_limit: limit,
+ search: cleanText(search),
+ 'filter[folder]': cleanText(folderId),
+ filter_tags: tagFilter.length > 0 ? tagFilter.join(',') : undefined,
+ shorten_content: shortenContent === false ? 'false' : 'true',
+ },
+ });
+ const pastes = Array.isArray(body) ? body.map(asRecord) : [];
+ return { pastes, page: currentPage, page_limit: limit, count: pastes.length, has_more: pastes.length === limit };
+}
+
+function formatExpiry(value: string): string {
+ const date = new Date(value.trim());
+ if (Number.isNaN(date.getTime())) {
+ throw new Error(`Expiry Date "${value}" is not a valid date.`);
+ }
+ if (date.getTime() <= Date.now()) {
+ throw new Error('Expiry Date must be in the future.');
+ }
+ return date.toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, '');
+}
+
+function tagList(tags: unknown): string[] {
+ const raw = Array.isArray(tags) ? tags : typeof tags === 'string' ? tags.split(',') : [];
+ return [...new Set(raw.filter((tag): tag is string => typeof tag === 'string').map((tag) => tag.trim()).filter((tag) => tag !== ''))];
+}
+
+function decryptPaste({ paste, password }: { paste: Record<string, unknown>; password?: string }): PasteOutput {
+ const secret = passwordOf(password);
+ if (paste['encrypted'] !== true || !secret) {
+ return { ...paste, decrypted: false };
+ }
+ const content = decrypt({ text: paste['content'], password: secret });
+ if (content === null) {
+ throw new Error('Wrong Encryption Password: the paste content could not be decrypted.');
+ }
+ const title = typeof paste['title'] === 'string' && paste['title'] ? decrypt({ text: paste['title'], password: secret }) : paste['title'];
+ return { ...paste, content, title: title ?? paste['title'], decrypted: true };
+}
+
+function encrypt({ text, password }: { text: string; password: string }): string {
+ return CryptoJS.AES.encrypt(text, password).toString();
+}
+
+function decrypt({ text, password }: { text: unknown; password: string }): string | null {
+ if (typeof text !== 'string' || text === '') return null;
+ try {
+ const plain = CryptoJS.AES.decrypt(text, password).toString(CryptoJS.enc.Utf8);
+ return plain === '' ? null : plain;
+ } catch {
+ return null;
+ }
+}
+
+function passwordOf(value: unknown): string | undefined {
+ return typeof value === 'string' && value !== '' ? value : undefined;
+}
+
+function cleanText(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
+}
+
+function asRecord(value: unknown): Record<string, unknown> {
+ return pastefyClient.isRecord(value) ? value : {};
+}
+
+function toNode(value: unknown): FolderNode {
+ const record = asRecord(value);
+ return {
+ id: String(record['id'] ?? ''),
+ name: String(record['name'] ?? ''),
+ children: Array.isArray(record['children']) ? record['children'].map(toNode) : [],
+ };
+}
+
+export type PasteInput = { content: string; title?: string; password?: string; folderId?: string; visibility?: string; expiry?: string; tags?: unknown };
+export type PasteEditInput = { content?: string; title?: string; password?: string; folderId?: string; visibility?: string; expiry?: string; tags?: unknown; clearTags?: boolean };
+export type PasteOutput = Record<string, unknown> & { decrypted: boolean };
+export type DeleteOutput = { deleted: boolean; id: string };
+export type FolderNode = { id: string; name: string; children: FolderNode[] };
+export type FlatFolder = { id: string; name: string; path: string; parent_id: string | null };
+export type PasteListOutput = { pastes: Record<string, unknown>[]; page: number; page_limit: number; count: number; has_more: boolean };
+export type ListPastesInput = {
+ auth: PastefyAuthValue;
+ source: 'mine' | 'public' | 'latest' | 'trending';
+ search?: string;
+ folderId?: string;
+ tags?: unknown;
+ page?: unknown;
+ pageLimit?: unknown;
+ shortenContent?: boolean;
+};
diff --git a/packages/pieces/community/pastefy/src/lib/triggers/paste-changed.ts b/packages/pieces/community/pastefy/src/lib/triggers/paste-changed.ts
index bbb4ad5fa0a..56229179245 100644
--- a/packages/pieces/community/pastefy/src/lib/triggers/paste-changed.ts
+++ b/packages/pieces/community/pastefy/src/lib/triggers/paste-changed.ts
@@ -1,13 +1,8 @@
-import {
- createTrigger,
- isNil,
- Property,
- StoreScope,
- TriggerStrategy,
-} from '@activepieces/pieces-framework';
-import { makeClient } from '../common';
+import { createTrigger, isNil, Property, StoreScope, TriggerStrategy } from '@activepieces/pieces-framework';
import { createHash } from 'crypto';
-import { pastefyAuth } from '../..';
+import { pastefyAuth } from '../common/auth';
+import { pastefyOutputSchemas } from '../common/output-schemas';
+import { pastefyRequests } from '../common/requests';
export default createTrigger({
auth: pastefyAuth,
@@ -16,71 +11,72 @@ export default createTrigger({
displayName: 'Paste Changed',
description: 'Triggers when the content (or title) of the paste changes',
aiMetadata: {
- description: 'Fires when a specific paste (identified by its ID) has its content change since the last poll, optionally also detecting title changes when Include Title is enabled. Represents an edit to that tracked paste.',
+ description: 'Fires once when a specific paste (by ID) has new content since the last check, and also on title changes when Include Title is on. Returns the paste as stored (ciphertext for encrypted pastes).',
},
type: TriggerStrategy.POLLING,
props: {
- paste_id: Property.ShortText({
- displayName: 'Paste ID',
- required: true,
- }),
- include_title: Property.Checkbox({
- displayName: 'Include Title',
- required: false,
- }),
+ paste_id: Property.ShortText({ displayName: 'Paste ID', required: true }),
+ include_title: Property.Checkbox({ displayName: 'Include Title', required: false }),
},
- sampleData: {},
- onEnable: async (context) => {
- if (
- context.isRepublish &&
- !isNil(await context.store.get('paste_changed_trigger_hash', StoreScope.FLOW))
- ) {
+ sampleData: {
+ exists: true,
+ id: 'aB3dE5gH',
+ content: 'console.log("hello");',
+ title: 'hello.js',
+ encrypted: false,
+ folder: 'Fo1dEr2x',
+ user_id: 'UsEr1234',
+ visibility: 'UNLISTED',
+ raw_url: 'https://pastefy.app/aB3dE5gH/raw',
+ type: 'PASTE',
+ created_at: '2026-10-26 15:20:00.0',
+ tags: ['javascript'],
+ starred: false,
+ user: { id: 'UsEr1234', name: 'jane', display_name: 'Jane', avatar: 'https://pastefy.app/avatar.png' },
+ decrypted: false,
+ },
+ outputSchema: pastefyOutputSchemas.paste,
+ onEnable: async ({ auth, propsValue, store, isRepublish }) => {
+ if (isRepublish && !isNil(await store.get(STORE_KEY, StoreScope.FLOW))) {
return;
}
- const client = makeClient(context.auth, context.propsValue);
- const paste = await client.getPaste(context.propsValue.paste_id);
- const hash = createHash('md5')
- .update(
- paste.content + (context.propsValue.include_title ? paste.title : '')
- )
- .digest('hex');
- await context.store.put(
- 'paste_changed_trigger_hash',
- hash,
- StoreScope.FLOW
- );
+ const paste = await pastefyRequests.getPaste({ auth, pasteId: propsValue.paste_id });
+ await store.put(STORE_KEY, hashOf({ paste, includeTitle: propsValue.include_title === true }), StoreScope.FLOW);
},
- onDisable: async (context) => {
- if (context.isRepublish) {
+ onDisable: async ({ store, isRepublish }) => {
+ if (isRepublish) {
return;
}
- await context.store.delete('paste_changed_trigger_hash', StoreScope.FLOW);
+ await store.delete(STORE_KEY, StoreScope.FLOW);
},
- run: async (context) => {
- const oldHash = await context.store.get(
- 'paste_changed_trigger_hash',
- StoreScope.FLOW
- );
- const client = makeClient(context.auth, context.propsValue);
- const paste = await client.getPaste(context.propsValue.paste_id);
- const newHash = createHash('md5')
- .update(
- paste.content + (context.propsValue.include_title ? paste.title : '')
- )
- .digest('hex');
- if (oldHash != newHash) {
- await context.store.put(
- 'paste_changed_trigger_hash',
- newHash,
- StoreScope.FLOW
- );
- return [paste];
+ run: async ({ auth, propsValue, store }) => {
+ const oldHash = await store.get<string>(STORE_KEY, StoreScope.FLOW);
+ const paste = await pastefyRequests.getPaste({ auth, pasteId: propsValue.paste_id });
+ const newHash = hashOf({ paste, includeTitle: propsValue.include_title === true });
+ if (oldHash === newHash) {
+ return [];
+ }
+ if (oldHash === legacyHashOf({ paste, includeTitle: propsValue.include_title === true })) {
+ await store.put(STORE_KEY, newHash, StoreScope.FLOW);
+ return [];
}
- return [];
+ await store.put(STORE_KEY, newHash, StoreScope.FLOW);
+ return [paste];
},
- test: async (context) => {
- const client = makeClient(context.auth, context.propsValue);
- const paste = await client.getPaste(context.propsValue.paste_id);
+ test: async ({ auth, propsValue }) => {
+ const paste = await pastefyRequests.getPaste({ auth, pasteId: propsValue.paste_id });
return [paste];
},
});
+
+function hashOf({ paste, includeTitle }: { paste: Record<string, unknown>; includeTitle: boolean }): string {
+ const parts = includeTitle ? [paste['content'] ?? null, paste['title'] ?? null] : [paste['content'] ?? null];
+ return createHash('md5').update(JSON.stringify(parts)).digest('hex');
+}
+
+function legacyHashOf({ paste, includeTitle }: { paste: Record<string, unknown>; includeTitle: boolean }): string {
+ const title = includeTitle ? String(paste['title']) : '';
+ return createHash('md5').update(`${String(paste['content'])}${title}`).digest('hex');
+}
+
+const STORE_KEY = 'paste_changed_trigger_hash';
diff --git a/packages/pieces/community/pastefy/test/actions.test.ts b/packages/pieces/community/pastefy/test/actions.test.ts
new file mode 100644
index 00000000000..c3e1155fa57
--- /dev/null
+++ b/packages/pieces/community/pastefy/test/actions.test.ts
@@ -0,0 +1,262 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import CryptoJS from 'crypto-js';
+import { createHash } from 'crypto';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import createPaste from '../src/lib/actions/create-paste';
+import getPaste from '../src/lib/actions/get-paste';
+import editPaste from '../src/lib/actions/edit-paste';
+import deletePaste from '../src/lib/actions/delete-paste';
+import deleteFolder from '../src/lib/actions/delete-folder';
+import getFolderHierarchy from '../src/lib/actions/get-folder-hierarchy';
+import listMyPastes from '../src/lib/actions/list-my-pastes';
+import searchPublicPastes from '../src/lib/actions/search-public-pastes';
+import deleteFolderAi from '../src/lib/actions/ai/delete-folder-ai';
+import listFolders from '../src/lib/actions/ai/list-folders';
+import createFolderAi from '../src/lib/actions/ai/create-folder-ai';
+import pasteChanged from '../src/lib/triggers/paste-changed';
+import { pastefyClient, PastefyApiError } from '../src/lib/common/client';
+import { pastefyRequests } from '../src/lib/common/requests';
+import { pastefyAuth } from '../src/lib/common/auth';
+import editPasteAi from '../src/lib/actions/ai/edit-paste-ai';
+import { replies, run, stubFetch } from './helpers';
+
+afterEach(() => vi.unstubAllGlobals());
+
+const PASTE = { exists: true, id: 'abc12345', title: 't', content: 'c', encrypted: false, folder: 'f1', visibility: 'UNLISTED' };
+
+describe('client', () => {
+ test('uses the connection instance URL and trimmed bearer key', async () => {
+ const seen = stubFetch(replies([{ body: PASTE }]));
+ await run(getPaste)({ paste_id: 'abc12345' });
+ expect(seen[0].url).toBe('https://paste.example.com/api/v2/paste/abc12345');
+ expect(seen[0].auth).toBe('Bearer key-1');
+ });
+
+ test('defaults to pastefy.app and rejects bad instance URLs', () => {
+ expect(pastefyClient.apiBase({ auth: { props: { token: 'k' } } })).toBe('https://pastefy.app/api/v2');
+ expect(() => pastefyClient.apiBase({ auth: { props: { instance_url: 'ftp://x', token: 'k' } } })).toThrow(/plain http/);
+ expect(() => pastefyClient.apiBase({ auth: { props: { instance_url: 'https://u:[email protected]', token: 'k' } } })).toThrow(/plain http/);
+ });
+
+ test('path IDs are encoded', async () => {
+ const seen = stubFetch(replies([{ body: PASTE }]));
+ await run(getPaste)({ paste_id: 'a/b?c' });
+ expect(seen[0].path).toBe('/api/v2/paste/a%2Fb%3Fc');
+ });
+
+ test('errors keep the vendor exception in responseBody', async () => {
+ stubFetch(replies([{ status: 403, body: { success: false, exception: 'PermissionsDeniedException' } }]));
+ const error = await run(getPaste)({ paste_id: 'x' }).catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(PastefyApiError);
+ expect(error).toMatchObject({ status: 403, responseBody: { exception: 'PermissionsDeniedException' } });
+ expect(String(error)).toMatch(/PermissionsDeniedException.*permission/);
+ });
+
+ test('200 with success:false is an error', async () => {
+ stubFetch(replies([{ body: { success: false } }]));
+ await expect(pastefyClient.request({ auth: { props: { token: 'k' } }, method: HttpMethod.DELETE, path: '/x' })).rejects.toThrow(/did not apply/);
+ });
+});
+
+describe('no API key', () => {
+ const ANON = { props: { instance_url: 'https://paste.example.com' } };
+
+ test('create and get work anonymously without an Authorization header', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, paste: PASTE } }, { body: PASTE }]));
+ await run(createPaste)({ content: 'hello' }, ANON);
+ await run(getPaste)({ paste_id: 'abc12345' }, ANON);
+ expect(seen.map((r) => r.method)).toEqual(['POST', 'GET']);
+ expect(seen.every((r) => r.auth === null)).toBe(true);
+ });
+
+ test('public search works anonymously', async () => {
+ const seen = stubFetch(replies([{ body: [PASTE] }]));
+ await run(searchPublicPastes)({ search: 'x' }, ANON);
+ expect(seen[0].auth).toBeNull();
+ });
+
+ test('account actions fail early with a clear message and send nothing', async () => {
+ const seen = stubFetch(replies([{ body: PASTE }]));
+ await expect(run(listFolders)({}, ANON)).rejects.toThrow(/needs an API key/);
+ await expect(run(listMyPastes)({}, ANON)).rejects.toThrow(/needs an API key/);
+ await expect(run(editPasteAi)({ paste_id: 'abc12345', title: 'n' }, ANON)).rejects.toThrow(/needs an API key/);
+ await expect(run(deletePaste)({ paste_id: 'abc12345' }, ANON)).rejects.toThrow(/needs an API key/);
+ await expect(run(deleteFolderAi)({ folder_id: 'f1' }, ANON)).rejects.toThrow(/needs an API key/);
+ expect(seen).toHaveLength(0);
+ });
+
+ test('validate accepts a connection without a key and checks a given key', async () => {
+ const seen = stubFetch(replies([{ body: { logged_in: true } }]));
+ expect(await pastefyAuth.validate?.({ auth: { instance_url: 'https://paste.example.com' }, server: { apiUrl: '', publicUrl: '' } })).toEqual({ valid: true });
+ expect(seen).toHaveLength(0);
+ expect(await pastefyAuth.validate?.({ auth: { instance_url: 'https://paste.example.com', token: 'k' }, server: { apiUrl: '', publicUrl: '' } })).toEqual({ valid: true });
+ expect(seen[0].auth).toBe('Bearer k');
+ });
+});
+
+describe('pastes', () => {
+ test('create encrypts content and title, formats expiry in UTC, sends tags', async () => {
+ const seen = stubFetch((request) => ({ body: { success: true, paste: { ...PASTE, ...request.body, folder: null } } }));
+ const out = await run(createPaste)({ content: 'secret', title: 'name', password: 'pw', expiry: '2099-01-02T03:04:05+02:00', tags: ['a', ' a ', 'b'] });
+ const body = seen[0].body;
+ expect(body['encrypted']).toBe(true);
+ expect(CryptoJS.AES.decrypt(String(body['content']), 'pw').toString(CryptoJS.enc.Utf8)).toBe('secret');
+ expect(body['expire_at']).toBe('2099-01-02 01:04:05');
+ expect(body['tags']).toEqual(['a', 'b']);
+ expect(body).not.toHaveProperty('folder');
+ expect(out).toMatchObject({ content: 'secret', title: 'name', decrypted: true });
+ });
+
+ test('create rejects a bad or past expiry before any request', async () => {
+ const seen = stubFetch(replies([{ body: {} }]));
+ await expect(run(createPaste)({ content: 'x', expiry: 'tomorrow' })).rejects.toThrow(/not a valid date/);
+ await expect(run(createPaste)({ content: 'x', expiry: '2001-01-01T00:00:00Z' })).rejects.toThrow(/future/);
+ expect(seen).toHaveLength(0);
+ });
+
+ test('create checks the folder first, so a bad folder creates nothing', async () => {
+ const seen = stubFetch(replies([{ status: 404, body: { exception: 'NotFoundException' } }]));
+ await expect(run(createPaste)({ content: 'x', folder_id: 'nope' })).rejects.toThrow(/404/);
+ expect(seen).toHaveLength(1);
+ });
+
+ test('create fails loudly when Pastefy ignored the folder', async () => {
+ stubFetch(replies([{ body: { exists: true, id: 'f9' } }, { body: { success: true, paste: { ...PASTE, folder: null } } }]));
+ await expect(run(createPaste)({ content: 'x', folder_id: 'f9' })).rejects.toThrow(/did not put it in folder f9/);
+ });
+
+ test('get with wrong password fails, right password decrypts', async () => {
+ const enc = { ...PASTE, encrypted: true, content: CryptoJS.AES.encrypt('hi', 'pw').toString(), title: CryptoJS.AES.encrypt('tt', 'pw').toString() };
+ stubFetch(replies([{ body: enc }]));
+ await expect(run(getPaste)({ paste_id: 'p', password: 'nope' })).rejects.toThrow(/Wrong Encryption Password/);
+ expect(await run(getPaste)({ paste_id: 'p', password: 'pw' })).toMatchObject({ content: 'hi', title: 'tt', decrypted: true });
+ expect(await run(getPaste)({ paste_id: 'p' })).toMatchObject({ content: enc.content, decrypted: false });
+ });
+
+ test('edit of only the folder keeps encryption and returns the re-read paste', async () => {
+ const enc = { ...PASTE, encrypted: true, content: CryptoJS.AES.encrypt('hi', 'pw').toString() };
+ const seen = stubFetch(replies([{ body: enc }, { body: { success: true } }, { body: { ...enc, folder: 'f2' } }]));
+ const out = await run(editPaste)({ paste_id: 'p', folder_id: 'f2', tags: [] });
+ expect(seen[1]).toMatchObject({ method: 'PUT', body: { folder: 'f2' } });
+ expect(seen[1].body).not.toHaveProperty('encrypted');
+ expect(seen[1].body).not.toHaveProperty('tags');
+ expect(out).toMatchObject({ folder: 'f2', encrypted: true });
+ });
+
+ test('edit refuses new content on an encrypted paste without password', async () => {
+ const seen = stubFetch(replies([{ body: { ...PASTE, encrypted: true } }]));
+ await expect(run(editPaste)({ paste_id: 'p', content: 'plain' })).rejects.toThrow(/encrypted/);
+ expect(seen).toHaveLength(1);
+ });
+
+ test('edit clear tags sends an empty list; nothing to update fails', async () => {
+ const seen = stubFetch(replies([{ body: PASTE }, { body: { success: true } }, { body: PASTE }]));
+ await run(editPaste)({ paste_id: 'p', clear_tags: true });
+ expect(seen[1].body).toEqual({ tags: [] });
+ stubFetch(replies([{ body: PASTE }]));
+ await expect(run(editPaste)({ paste_id: 'p' })).rejects.toThrow(/Nothing to update/);
+ });
+
+ test('delete paste twice: second returns deleted false', async () => {
+ stubFetch(replies([{ body: { success: true } }, { status: 404, body: { success: false, exception: 'NotFoundException' } }]));
+ expect(await run(deletePaste)({ paste_id: 'p' })).toEqual({ deleted: true, id: 'p' });
+ expect(await run(deletePaste)({ paste_id: 'p' })).toEqual({ deleted: false, id: 'p' });
+ });
+
+ test('list my pastes sends page_limit and filters, has_more from a full page', async () => {
+ const seen = stubFetch(replies([{ body: [PASTE, PASTE] }]));
+ const out = await run(listMyPastes)({ search: 'q', folder_id: 'f1', tags: ['x', 'y'], page: 2, page_limit: 2 });
+ expect(seen[0].path).toBe('/api/v2/user/pastes');
+ expect(Object.fromEntries(seen[0].query)).toEqual({ page: '2', page_limit: '2', search: 'q', 'filter[folder]': 'f1', filter_tags: 'x,y', shorten_content: 'true' });
+ expect(out).toMatchObject({ count: 2, has_more: true, page: 2, page_limit: 2 });
+ });
+
+ test('page size over 50 is refused', async () => {
+ await expect(run(searchPublicPastes)({ page_limit: 51 })).rejects.toThrow(/1 to 50/);
+ });
+
+ test('public search picks the trending list', async () => {
+ const seen = stubFetch(replies([{ body: [] }]));
+ expect(await run(searchPublicPastes)({ list: 'trending' })).toMatchObject({ has_more: false, count: 0 });
+ expect(seen[0].path).toBe('/api/v2/public-pastes/trending');
+ });
+});
+
+describe('folders', () => {
+ const TREE = [{ id: 'a', name: 'A', children: [{ id: 'b', name: 'B', children: [] }] }, { id: 'c', name: 'C', children: [] }];
+
+ test('one tree call with hide_pastes, flattened with paths', async () => {
+ const seen = stubFetch(replies([{ body: TREE }]));
+ const out = await run(listFolders)({});
+ expect(seen).toHaveLength(1);
+ expect(seen[0].path).toBe('/api/v2/user/folders');
+ expect(seen[0].query.get('hide_pastes')).toBe('true');
+ expect(out).toEqual({ count: 3, folders: [
+ { id: 'a', name: 'A', path: 'A', parent_id: null },
+ { id: 'b', name: 'B', path: 'A / B', parent_id: 'a' },
+ { id: 'c', name: 'C', path: 'C', parent_id: null },
+ ] });
+ });
+
+ test('hierarchy subtree and unknown start folder', async () => {
+ stubFetch(replies([{ body: TREE }]));
+ expect(await run(getFolderHierarchy)({ parent_id: 'a' })).toEqual([{ id: 'b', name: 'B', children: [] }]);
+ await expect(run(getFolderHierarchy)({ parent_id: 'zz' })).rejects.toThrow(/not found/);
+ });
+
+ test('create folder checks the parent first', async () => {
+ const seen = stubFetch(replies([{ status: 404, body: { exception: 'NotFoundException' } }]));
+ await expect(run(createFolderAi)({ name: 'x', parent_folder_id: 'nope' })).rejects.toThrow(/404/);
+ expect(seen).toHaveLength(1);
+ });
+
+ test('delete folder: AI twin returns deleted false when missing, human fails', async () => {
+ stubFetch(replies([{ status: 404, body: { exists: false } }]));
+ expect(await run(deleteFolderAi)({ folder_id: 'f' })).toEqual({ deleted: false, id: 'f' });
+ await expect(run(deleteFolder)({ folder_id: 'f' })).rejects.toThrow(/404/);
+ });
+});
+
+describe('passwords are used exactly as typed', () => {
+ test('a password with surrounding spaces decrypts and is not trimmed', async () => {
+ const enc = { ...PASTE, encrypted: true, content: CryptoJS.AES.encrypt('hi', ' secret ').toString(), title: '' };
+ stubFetch(replies([{ body: enc }]));
+ expect(await run(getPaste)({ paste_id: 'p', password: ' secret ' })).toMatchObject({ content: 'hi', decrypted: true });
+ await expect(run(getPaste)({ paste_id: 'p', password: 'secret' })).rejects.toThrow(/Wrong Encryption Password/);
+ });
+
+ test('create encrypts with the untrimmed password', async () => {
+ const seen = stubFetch(replies([{ body: { success: true, paste: { ...PASTE, encrypted: true, content: CryptoJS.AES.encrypt('x', ' pw ').toString(), title: '' } } }]));
+ await run(createPaste)({ content: 'x', password: ' pw ' });
+ const content = String(seen[0].body['content']);
+ expect(CryptoJS.AES.decrypt(content, ' pw ').toString(CryptoJS.enc.Utf8)).toBe('x');
+ });
+});
+
+describe('trigger', () => {
+ test('a hash stored by the previous version does not fire for an unchanged paste', async () => {
+ const data = new Map<string, unknown>();
+ const store = { put: async (k: string, v: unknown) => data.set(k, v), get: async (k: string) => data.get(k) ?? null, delete: async (k: string) => data.delete(k) };
+ const ctx = { auth: { props: { token: 'k' } }, propsValue: { paste_id: 'p', include_title: true }, store };
+ data.set('paste_changed_trigger_hash', createHash('md5').update('c' + 'ab').digest('hex'));
+ stubFetch(replies([{ body: { ...PASTE, title: 'ab', content: 'c' } }, { body: { ...PASTE, title: 'ab', content: 'c' } }, { body: { ...PASTE, title: 'ab', content: 'd' } }]));
+ expect(await Reflect.apply(pasteChanged.run, pasteChanged, [ctx])).toEqual([]);
+ expect(await Reflect.apply(pasteChanged.run, pasteChanged, [ctx])).toEqual([]);
+ expect(await Reflect.apply(pasteChanged.run, pasteChanged, [ctx])).toHaveLength(1);
+ });
+
+ test('fires once per change and hashes content and title separately', async () => {
+ const data = new Map<string, unknown>();
+ const store = { put: async (k: string, v: unknown) => data.set(k, v), get: async (k: string) => data.get(k) ?? null, delete: async (k: string) => data.delete(k) };
+ const ctx = { auth: { props: { token: 'k' } }, propsValue: { paste_id: 'p', include_title: true }, store };
+ const replyList = [{ body: { ...PASTE, title: 'ab', content: 'c' } }, { body: { ...PASTE, title: 'ab', content: 'c' } }, { body: { ...PASTE, title: 'a', content: 'bc' } }];
+ stubFetch(replies(replyList));
+ await Reflect.apply(pasteChanged.onEnable, pasteChanged, [ctx]);
+ expect(await Reflect.apply(pasteChanged.run, pasteChanged, [ctx])).toEqual([]);
+ expect(await Reflect.apply(pasteChanged.run, pasteChanged, [ctx])).toHaveLength(1);
+ });
+});
+
+test('tag list ignores blanks and duplicates', () => {
+ expect(pastefyRequests.tagList(['a', '', ' a', 'b'])).toEqual(['a', 'b']);
+});
diff --git a/packages/pieces/community/pastefy/test/custom-api-call.test.ts b/packages/pieces/community/pastefy/test/custom-api-call.test.ts
new file mode 100644
index 00000000000..540fac310f3
--- /dev/null
+++ b/packages/pieces/community/pastefy/test/custom-api-call.test.ts
@@ -0,0 +1,59 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { apiUrlOf, pastefyCustomApiCallAction } from '../src/lib/actions/custom-api-call';
+import { AUTH, stubFetch } from './helpers';
+
+afterEach(() => vi.unstubAllGlobals());
+
+const BASE = 'https://paste.example.com/api/v2';
+
+describe('custom api call', () => {
+ test('relative paths and same-base URLs stay on the instance API', () => {
+ expect(apiUrlOf({ baseUrl: BASE, url: '/user' })).toBe(`${BASE}/user`);
+ expect(apiUrlOf({ baseUrl: BASE, url: `${BASE}/paste/abc` })).toBe(`${BASE}/paste/abc`);
+ });
+
+ test.each([
+ 'https://evil.example.com/api/v2/user',
+ 'https://paste.example.com.evil.io/api/v2/user',
+ '//evil.example.com/api/v2/user',
+ 'http://paste.example.com/api/v2/user',
+ 'https://[email protected]/api/v2/user',
+ 'https://paste.example.com/other',
+ '/../user',
+ ])('rejects %s', (url) => {
+ expect(() => apiUrlOf({ baseUrl: BASE, url })).toThrow();
+ });
+
+ test('sends the key to the instance only, without following redirects', async () => {
+ const seen = stubFetch(() => ({ body: { name: 'me' } }));
+ const output = await Reflect.apply(pastefyCustomApiCallAction.run, pastefyCustomApiCallAction, [
+ { auth: AUTH, propsValue: { method: HttpMethod.GET, url: { url: '/user' }, headers: { Authorization: 'Bearer other' }, queryParams: {} }, files: {} },
+ ]);
+ expect(seen).toHaveLength(1);
+ expect(seen[0].url).toBe(`${BASE}/user`);
+ expect(seen[0].auth).toBe('Bearer key-1');
+ expect(output).toMatchObject({ status: 200 });
+ });
+
+ test('keeps array query values and names binary downloads by content type', async () => {
+ const seen = stubFetch(() => ({ body: { ok: true } }));
+ const written: string[] = [];
+ const files = { write: async ({ fileName }: { fileName: string }) => { written.push(fileName); return `file://${fileName}`; } };
+ await Reflect.apply(pastefyCustomApiCallAction.run, pastefyCustomApiCallAction, [
+ { auth: AUTH, propsValue: { method: HttpMethod.GET, url: { url: '/user/pastes' }, headers: {}, queryParams: { filter_tags: ['a', 'b'] }, response_is_binary: true }, files },
+ ]);
+ expect(seen[0].query.get('filter_tags')).toBe('a,b');
+ expect(written).toEqual(['output.json']);
+ });
+
+ test('refuses an outside URL without a request', async () => {
+ const seen = stubFetch(() => ({ body: {} }));
+ await expect(
+ Reflect.apply(pastefyCustomApiCallAction.run, pastefyCustomApiCallAction, [
+ { auth: AUTH, propsValue: { method: HttpMethod.GET, url: { url: 'https://attacker.example/api/v2/user' }, headers: {}, queryParams: {} }, files: {} },
+ ]),
+ ).rejects.toThrow('must start with');
+ expect(seen).toHaveLength(0);
+ });
+});
diff --git a/packages/pieces/community/pastefy/test/helpers.ts b/packages/pieces/community/pastefy/test/helpers.ts
new file mode 100644
index 00000000000..d52b0f24b66
--- /dev/null
+++ b/packages/pieces/community/pastefy/test/helpers.ts
@@ -0,0 +1,41 @@
+import { vi } from 'vitest';
+
+
+export const AUTH = { props: { instance_url: 'https://paste.example.com/', token: ' key-1 ' } };
+
+export function stubFetch(respond: (request: SeenRequest, index: number) => FakeReply): SeenRequest[] {
+ const seen: SeenRequest[] = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : String(input);
+ const headers = new Headers(init?.headers);
+ const parsed = new URL(url);
+ const rawBody = typeof init?.body === 'string' ? init.body : null;
+ const request: SeenRequest = {
+ url,
+ method: (init?.method ?? 'GET').toUpperCase(),
+ path: parsed.pathname,
+ query: parsed.searchParams,
+ auth: headers.get('authorization'),
+ body: rawBody ? JSON.parse(rawBody) : {},
+ };
+ seen.push(request);
+ const reply = respond(request, seen.length - 1);
+ return new Response(JSON.stringify(reply.body ?? {}), { status: reply.status ?? 200, headers: { 'content-type': 'application/json' } });
+ }),
+ );
+ return seen;
+}
+
+export function replies(list: FakeReply[]): (request: SeenRequest, index: number) => FakeReply {
+ return (_request, index) => list[Math.min(index, list.length - 1)];
+}
+
+export function run(action: { run: (...args: never[]) => unknown }) {
+ return (propsValue: Record<string, unknown>, auth: unknown = AUTH): Promise<unknown> =>
+ Promise.resolve(Reflect.apply(action.run, action, [{ auth, propsValue }]));
+}
+
+export type SeenRequest = { url: string; method: string; path: string; query: URLSearchParams; auth: string | null; body: Record<string, unknown> };
+export type FakeReply = { status?: number; body?: unknown };
diff --git a/packages/pieces/community/pastefy/test/metadata.test.ts b/packages/pieces/community/pastefy/test/metadata.test.ts
new file mode 100644
index 00000000000..0fa3c2c05cd
--- /dev/null
+++ b/packages/pieces/community/pastefy/test/metadata.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, test } from 'vitest';
+import { pastefy } from '../src/index';
+
+describe('piece metadata', () => {
+ const actions = Object.values(pastefy.actions());
+ const triggers = Object.values(pastefy.triggers());
+
+ test('audience counts', () => {
+ const count = (audience: string) => actions.filter((a) => a.name !== 'custom_api_call' && a.audience === audience).length;
+ expect({ human: count('human'), ai: count('ai'), both: count('both') }).toEqual({ human: 6, ai: 6, both: 4 });
+ });
+
+ test('every action and trigger has outputSchema and aiMetadata', () => {
+ for (const action of actions.filter((a) => a.name !== 'custom_api_call')) {
+ expect(action.outputSchema?.fields.length, action.name).toBeGreaterThan(0);
+ expect(action.aiMetadata?.description, action.name).toBeTruthy();
+ }
+ for (const trigger of triggers) {
+ expect(trigger.outputSchema?.fields.length, trigger.name).toBeGreaterThan(0);
+ }
+ });
+
+ test('legacy names are kept', () => {
+ const names = actions.map((a) => a.name);
+ for (const name of ['create_paste', 'get_paste', 'edit_paste', 'delete_paste', 'create_folder', 'get_folder', 'get_folder_hierarchy', 'delete_folder']) {
+ expect(names).toContain(name);
+ }
+ expect(triggers.map((t) => t.name)).toEqual(['paste_changed']);
+ });
+
+ test('ai actions take IDs as text, not dropdowns', () => {
+ for (const action of actions.filter((a) => a.audience === 'ai')) {
+ for (const [key, prop] of Object.entries(action.props)) {
+ expect(prop.type, `${action.name}.${key}`).not.toBe('DROPDOWN');
+ }
+ }
+ });
+});
diff --git a/packages/pieces/community/pastefy/vitest.config.ts b/packages/pieces/community/pastefy/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/pastefy/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'),
+ },
+ },
+})