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(pdfmonkey): let AI agents generate, find and manage PDF documents (#16570)

Odai Ahmad085a88c10734
diff --git a/bun.lock b/bun.lock
index 21440578e29..252e9a54e66 100644
--- a/bun.lock
+++ b/bun.lock
@@ -7004,16 +7004,18 @@
},
"packages/pieces/community/pdfmonkey": {
"name": "@activepieces/piece-pdfmonkey",
- "version": "0.2.1",
+ "version": "0.3.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
"dayjs": "1.11.9",
+ "undici": "7.29.1",
},
"devDependencies": {
"tslib": "^2.3.0",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/peekshot": {
diff --git a/docs/install/reference/breaking-changes-unreleased.mdx b/docs/install/reference/breaking-changes-unreleased.mdx
index 4ad057d857a..5d95b0492f0 100644
--- a/docs/install/reference/breaking-changes-unreleased.mdx
+++ b/docs/install/reference/breaking-changes-unreleased.mdx
@@ -8,6 +8,14 @@ Entries here move to [Breaking Changes](/install/reference/breaking-changes) aut
## What has changed?
+#### PDFMonkey 0.3.0: Generate Document, Find Document and Delete Document are builder-only
+
+Generate Document, Find Document and Delete Document are no longer offered to AI agents. They keep working in flows, but an agent that used them as tools loses them after the upgrade.
+
+#### What you need to do
+
+Agents that used these actions switch to their twins: Generate Document (AI), Get Document (AI) and Delete Document (AI). Flow steps keep running on the version they were built with until you upgrade them.
+
#### Netlify 0.2.0: Start Deploy returns a build, and four actions are builder-only
Start Deploy used to return a deploy. From Netlify 0.2.0 it starts a build through `/sites/{id}/builds` and returns that build: `id` is now the build ID, the deploy fields are gone, and the new `deploy_id` points to the deploy the build creates.
diff --git a/packages/pieces/community/pdfmonkey/package.json b/packages/pieces/community/pdfmonkey/package.json
index d3a920dd7f0..51cf773dd3f 100644
--- a/packages/pieces/community/pdfmonkey/package.json
+++ b/packages/pieces/community/pdfmonkey/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-pdfmonkey",
- "version": "0.2.1",
+ "version": "0.3.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -9,14 +9,17 @@
"@activepieces/pieces-framework": "workspace:*",
"dayjs": "1.11.9",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "undici": "7.29.1"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "tslib": "^2.3.0",
+ "vitest": "3.2.6"
},
"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"
}
}
diff --git a/packages/pieces/community/pdfmonkey/src/i18n/translation.json b/packages/pieces/community/pdfmonkey/src/i18n/translation.json
index bfbac03132a..204e081d5f5 100644
--- a/packages/pieces/community/pdfmonkey/src/i18n/translation.json
+++ b/packages/pieces/community/pdfmonkey/src/i18n/translation.json
@@ -1,19 +1,46 @@
{
- "You can obtain your API key by navigating to [Account Settings](https://dashboard.pdfmonkey.io/account).": "You can obtain your API key by navigating to [Account Settings](https://dashboard.pdfmonkey.io/account).",
+ "Generate PDF documents from templates and JSON data.": "Generate PDF documents from templates and JSON data.",
+ "Your PDFMonkey secret API key. In PDFMonkey, open [My Account](https://dashboard.pdfmonkey.io/account) and copy the API Secret Key.": "Your PDFMonkey secret API key. In PDFMonkey, open [My Account](https://dashboard.pdfmonkey.io/account) and copy the API Secret Key.",
"Generate Document": "Generate Document",
- "Delete Document": "Delete Document",
+ "Generate Document (AI)": "Generate Document (AI)",
"Find Document": "Find Document",
+ "Get Document (AI)": "Get Document (AI)",
+ "List Documents": "List Documents",
+ "Update Document": "Update Document",
+ "Download Document": "Download Document",
+ "Delete Document": "Delete Document",
+ "Delete Document (AI)": "Delete Document (AI)",
+ "List Templates": "List Templates",
+ "Get Template": "Get Template",
+ "Get Account Info": "Get Account Info",
"Custom API Call": "Custom API Call",
"Generates a new document using a specified template.": "Generates a new document using a specified template.",
- "Deletes a document.": "Deletes a document.",
+ "Generate a document from a template ID and wait for the finished file link.": "Generate a document from a template ID and wait for the finished file link.",
"Finds a document by ID.": "Finds a document by ID.",
+ "Get a document's status, file name and download link by its ID.": "Get a document's status, file name and download link by its ID.",
+ "List documents, newest first, filtered by template, status, file name or update date.": "List documents, newest first, filtered by template, status, file name or update date.",
+ "Change a document's data, metadata, file name or template, and optionally generate it again.": "Change a document's data, metadata, file name or template, and optionally generate it again.",
+ "Download a generated document as a file you can attach or upload in later steps.": "Download a generated document as a file you can attach or upload in later steps.",
+ "Deletes a document.": "Deletes a document.",
+ "Permanently delete a document and its file by ID.": "Permanently delete a document and its file by ID.",
+ "List the document templates in your PDFMonkey workspaces.": "List the document templates in your PDFMonkey workspaces.",
+ "Get a template with its HTML, test data and page settings.": "Get a template with its HTML, test data and page settings.",
+ "Get the connected PDFMonkey account, its plan and how many documents it can still generate.": "Get the connected PDFMonkey account, its plan and how many documents it can still generate.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Template ID": "Template ID",
"Payload": "Payload",
"Meta": "Meta",
"Custom File Name": "Custom File Name",
"Document Status": "Document Status",
+ "Wait for Completion": "Wait for Completion",
"Document ID": "Document ID",
+ "Status": "Status",
+ "Search": "Search",
+ "Updated Since": "Updated Since",
+ "Page": "Page",
+ "Generate Now": "Generate Now",
+ "File Name": "File Name",
+ "Workspace ID": "Workspace ID",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
@@ -25,6 +52,24 @@
"Follow redirects": "Follow redirects",
"Data to use for the Document generation.": "Data to use for the Document generation.",
"Meta-Data to attach to the Document.": "Meta-Data to attach to the Document.",
+ "Draft only saves the document; Pending generates the file right away.": "Draft only saves the document; Pending generates the file right away.",
+ "Generate now and wait (up to 7 minutes) until the file is ready, so the output has the download URL. Overrides Document Status.": "Generate now and wait (up to 7 minutes) until the file is ready, so the output has the download URL. Overrides Document Status.",
+ "The template ID (a UUID). Use List Templates to find it.": "The template ID (a UUID). Use List Templates to find it.",
+ "The data merged into the template, as a JSON object, e.g. {\"clientName\": \"Jane Doe\", \"total\": 120}.": "The data merged into the template, as a JSON object, e.g. {\"clientName\": \"Jane Doe\", \"total\": 120}.",
+ "Optional metadata to keep with the document, as a JSON object. It is returned with the document and in triggers.": "Optional metadata to keep with the document, as a JSON object. It is returned with the document and in triggers.",
+ "Name of the generated file, e.g. \"Invoice 2026-001.pdf\". Stored as the _filename meta key.": "Name of the generated file, e.g. \"Invoice 2026-001.pdf\". Stored as the _filename meta key.",
+ "Wait until the file is generated and return its download URL.": "Wait until the file is generated and return its download URL.",
+ "The document ID (a UUID), e.g. from Generate Document or List Documents.": "The document ID (a UUID), e.g. from Generate Document or List Documents.",
+ "Only documents made from this template. Use List Templates to find the ID.": "Only documents made from this template. Use List Templates to find the ID.",
+ "A document ID (exact match) or part of a file name.": "A document ID (exact match) or part of a file name.",
+ "Only documents updated after this date and time.": "Only documents updated after this date and time.",
+ "Page number, starting at 1. Each page has up to 24 documents.": "Page number, starting at 1. Each page has up to 24 documents.",
+ "Switch the document to another template. Leave empty to keep the current one.": "Switch the document to another template. Leave empty to keep the current one.",
+ "New data for the document, as a JSON object. Replaces the whole payload. Leave empty to keep it.": "New data for the document, as a JSON object. Replaces the whole payload. Leave empty to keep it.",
+ "New metadata, as a JSON object. Replaces all meta keys. Leave empty to keep it.": "New metadata, as a JSON object. Replaces all meta keys. Leave empty to keep it.",
+ "Queue the document for generation after the update (sets its status to pending).": "Queue the document for generation after the update (sets its status to pending).",
+ "Name for the downloaded file. Defaults to the document file name.": "Name for the downloaded file. Defaults to the document file name.",
+ "Only templates of this workspace. Leave empty to list the templates of every workspace you can access.": "Only templates of this workspace. Leave empty to list the templates of every workspace you can access.",
"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.",
@@ -33,6 +78,9 @@
"Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
"Draft": "Draft",
"Pending": "Pending",
+ "Generating": "Generating",
+ "Success": "Success",
+ "Failure": "Failure",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
diff --git a/packages/pieces/community/pdfmonkey/src/index.ts b/packages/pieces/community/pdfmonkey/src/index.ts
index 0c826fd33fc..6cda6201814 100644
--- a/packages/pieces/community/pdfmonkey/src/index.ts
+++ b/packages/pieces/community/pdfmonkey/src/index.ts
@@ -1,33 +1,49 @@
-import { createPiece } from '@activepieces/pieces-framework';
+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';
+import { createCustomApiCallAction } from '@activepieces/pieces-common';
import { pdfmonkeyAuth } from './lib/common/auth';
+import { BASE_URL } from './lib/common/client';
import { generateDocumentAction } from './lib/actions/generate-document';
-import { deleteDocumentAction } from './lib/actions/delete-document';
+import { generateDocumentAiAction } from './lib/actions/generate-document-ai';
import { findDocumentAction } from './lib/actions/find-document';
-import { PieceCategory } from '@activepieces/pieces-framework';
-import { createCustomApiCallAction } from '@activepieces/pieces-common';
-import { BASE_URL } from './lib/common/client';
+import { getDocumentAiAction } from './lib/actions/get-document-ai';
+import { listDocumentsAction } from './lib/actions/list-documents';
+import { updateDocumentAction } from './lib/actions/update-document';
+import { downloadDocumentAction } from './lib/actions/download-document';
+import { deleteDocumentAction } from './lib/actions/delete-document';
+import { deleteDocumentAiAction } from './lib/actions/delete-document-ai';
+import { listTemplatesAction } from './lib/actions/list-templates';
+import { getTemplateAction } from './lib/actions/get-template';
+import { getCurrentUserAction } from './lib/actions/get-current-user';
import { documentGeneratedTrigger } from './lib/triggers/document-generated';
export const pdfmonkey = createPiece({
- displayName: 'PDFMonkey',
- auth: pdfmonkeyAuth,
- minimumSupportedRelease: '0.36.1',
- logoUrl: 'https://cdn.activepieces.com/pieces/pdfmonkey.png',
- authors: ['Sanket6652'],
- categories: [PieceCategory.CONTENT_AND_FILES],
- actions: [
- generateDocumentAction,
- deleteDocumentAction,
- findDocumentAction,
- createCustomApiCallAction({
- auth: pdfmonkeyAuth,
- baseUrl: () => BASE_URL,
- authMapping: async (auth) => {
- return {
- Authorization: `Bearer ${auth}`,
- };
- },
- }),
- ],
- triggers: [documentGeneratedTrigger],
+ displayName: 'PDFMonkey',
+ description: 'Generate PDF documents from templates and JSON data.',
+ auth: pdfmonkeyAuth,
+ minimumSupportedRelease: '0.36.1',
+ logoUrl: 'https://cdn.activepieces.com/pieces/pdfmonkey.png',
+ authors: ['Sanket6652'],
+ categories: [PieceCategory.CONTENT_AND_FILES],
+ actions: [
+ generateDocumentAction,
+ generateDocumentAiAction,
+ findDocumentAction,
+ getDocumentAiAction,
+ listDocumentsAction,
+ updateDocumentAction,
+ downloadDocumentAction,
+ deleteDocumentAction,
+ deleteDocumentAiAction,
+ listTemplatesAction,
+ getTemplateAction,
+ getCurrentUserAction,
+ createCustomApiCallAction({
+ auth: pdfmonkeyAuth,
+ baseUrl: () => BASE_URL,
+ authMapping: async (auth) => ({
+ Authorization: `Bearer ${auth.secret_text}`,
+ }),
+ }),
+ ],
+ triggers: [documentGeneratedTrigger],
});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/delete-document-ai.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/delete-document-ai.ts
new file mode 100644
index 00000000000..d5440e0c26c
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/delete-document-ai.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { pdfmonkeyAuth } from '../common/auth';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
+import { documentIdText } from '../common/props';
+
+export const deleteDocumentAiAction = createAction({
+ auth: pdfmonkeyAuth,
+ name: 'delete_document_ai',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Document (AI)',
+ description: 'Permanently delete a document and its file by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a PDFMonkey document and its generated file by document ID. Irreversible. A second call for the same ID fails with not found.',
+ idempotent: false,
+ },
+ outputSchema: pdfmonkeySchemas.deleted,
+ props: { document_id: documentIdText },
+ async run({ auth, propsValue }) {
+ return pdfmonkeyOperations.deleteDocument({ auth, documentId: propsValue.document_id });
+ },
+});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/delete-document.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/delete-document.ts
index fb3d5d9158d..a2ff35d7b8b 100644
--- a/packages/pieces/community/pdfmonkey/src/lib/actions/delete-document.ts
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/delete-document.ts
@@ -1,34 +1,31 @@
import { createAction } from '@activepieces/pieces-framework';
import { pdfmonkeyAuth } from '../common/auth';
-import { makeRequest } from '../common/client';
-import { HttpMethod } from '@activepieces/pieces-common';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
import { documentIdDropdown } from '../common/props';
export const deleteDocumentAction = createAction({
- auth: pdfmonkeyAuth,
- name: 'deleteDocument',
- classification: 'DESTRUCTIVE',
- displayName: 'Delete Document',
- description: 'Deletes a document.',
- audience: 'both',
- aiMetadata: { description: 'Permanently delete a generated document in PDFMonkey by its document ID. Use to clean up documents no longer needed. The document ID is required; deletion is irreversible, and a repeat call for an already-deleted ID is not a successful no-op, so treat it as not idempotent.', idempotent: false },
- props: {
- document_id: documentIdDropdown,
- },
- async run({ auth, propsValue }) {
- const { document_id } = propsValue;
- if (!document_id) {
- throw new Error('Document ID is required');
- }
- const response = await makeRequest(
- auth,
- HttpMethod.DELETE,
- `/documents/${document_id}`,
- );
- return {
- status: 'success',
- message: 'Document deleted successfully.',
- data: response,
- };
- },
+ auth: pdfmonkeyAuth,
+ name: 'deleteDocument',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Document',
+ description: 'Deletes a document.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Permanently deletes a PDFMonkey document picked in a dropdown, together with its file. Irreversible; a second call for the same ID fails with not found.',
+ idempotent: false,
+ },
+ outputSchema: pdfmonkeySchemas.legacyDeleted,
+ props: {
+ document_id: documentIdDropdown,
+ },
+ async run({ auth, propsValue }) {
+ const result = await pdfmonkeyOperations.deleteDocument({ auth, documentId: propsValue.document_id });
+ return {
+ status: 'success',
+ message: 'Document deleted successfully.',
+ document_id: result.document_id,
+ };
+ },
});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/download-document.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/download-document.ts
new file mode 100644
index 00000000000..834bfa08110
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/download-document.ts
@@ -0,0 +1,31 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pdfmonkeyAuth } from '../common/auth';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
+import { documentIdText } from '../common/props';
+
+export const downloadDocumentAction = createAction({
+ auth: pdfmonkeyAuth,
+ name: 'download_document',
+ classification: 'READ',
+ displayName: 'Download Document',
+ description: 'Download a generated document as a file you can attach or upload in later steps.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Downloads the generated PDF (or image) of a PDFMonkey document by document ID and returns it as a file. The document must have status "success"; otherwise it fails and says the current status. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: pdfmonkeySchemas.download,
+ props: {
+ document_id: documentIdText,
+ file_name: Property.ShortText({
+ displayName: 'File Name',
+ description: 'Name for the downloaded file. Defaults to the document file name.',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue, files }) {
+ return pdfmonkeyOperations.downloadDocument({ auth, documentId: propsValue.document_id, fileName: propsValue.file_name, files });
+ },
+});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/find-document.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/find-document.ts
index 100affca736..77ba6178754 100644
--- a/packages/pieces/community/pdfmonkey/src/lib/actions/find-document.ts
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/find-document.ts
@@ -1,22 +1,27 @@
import { createAction } from '@activepieces/pieces-framework';
import { pdfmonkeyAuth } from '../common/auth';
-import { makeRequest } from '../common/client';
-import { HttpMethod } from '@activepieces/pieces-common';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
import { documentIdDropdown } from '../common/props';
export const findDocumentAction = createAction({
- auth: pdfmonkeyAuth,
- name: 'findDocument',
- classification: 'READ',
- displayName: 'Find Document',
- description: 'Finds a document by ID.',
- audience: 'both',
- aiMetadata: { description: 'Look up a single PDFMonkey document by its document ID, returning its current state including generation status and download URL. Use to check whether a document finished generating or to retrieve its download link. Read-only and idempotent.', idempotent: true },
- props: {
- document_id: documentIdDropdown,
- },
- async run({ auth, propsValue }) {
- const { document_id } = propsValue;
- return await makeRequest(auth, HttpMethod.GET, `/documents/${document_id}`);
- },
+ auth: pdfmonkeyAuth,
+ name: 'findDocument',
+ classification: 'READ',
+ displayName: 'Find Document',
+ description: 'Finds a document by ID.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Gets a PDFMonkey document picked in a dropdown, with its status, payload, generation logs and download URL. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: pdfmonkeySchemas.wrappedFullDocument,
+ props: {
+ document_id: documentIdDropdown,
+ },
+ async run({ auth, propsValue }) {
+ const document = await pdfmonkeyOperations.getDocument({ auth, documentId: propsValue.document_id });
+ return { document };
+ },
});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/generate-document-ai.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/generate-document-ai.ts
new file mode 100644
index 00000000000..c3e84488b00
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/generate-document-ai.ts
@@ -0,0 +1,44 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pdfmonkeyAuth } from '../common/auth';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
+import { fileNameProp, metaProp, payloadProp, templateIdText } from '../common/props';
+
+export const generateDocumentAiAction = createAction({
+ auth: pdfmonkeyAuth,
+ name: 'generate_document_ai',
+ classification: 'WRITE',
+ displayName: 'Generate Document (AI)',
+ description: 'Generate a document from a template ID and wait for the finished file link.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Generates a PDF (or image) in PDFMonkey from a template ID and a JSON payload, with optional meta and file name. By default it waits up to 4 minutes and returns the finished document with status "success" and its download URL (valid 1 hour). If it is still "pending" or "generating" after 4 minutes, it returns the document ID with that status instead of failing: call Get Document (AI) with that ID later rather than generating again; set wait_for_completion=false to only queue it and poll Get Document (AI). Get the template ID from List Templates and the expected payload fields from Get Template. Every call creates a new document.',
+ idempotent: false,
+ },
+ outputSchema: pdfmonkeySchemas.document,
+ props: {
+ template_id: templateIdText,
+ payload: payloadProp,
+ meta: metaProp,
+ file_name: fileNameProp,
+ wait_for_completion: Property.Checkbox({
+ displayName: 'Wait for Completion',
+ description: 'Wait up to 4 minutes for the file and return its download URL; if it is not ready by then, return the document ID and current status.',
+ required: false,
+ defaultValue: true,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ return pdfmonkeyOperations.createDocument({
+ auth,
+ templateId: propsValue.template_id,
+ payload: propsValue.payload,
+ meta: propsValue.meta,
+ filename: propsValue.file_name,
+ status: 'pending',
+ waitForCompletion: propsValue.wait_for_completion !== false,
+ maxWaitMs: pdfmonkeyOperations.AI_MAX_WAIT_MS,
+ });
+ },
+});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/generate-document.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/generate-document.ts
index cb6c7bee400..7b745561ba4 100644
--- a/packages/pieces/community/pdfmonkey/src/lib/actions/generate-document.ts
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/generate-document.ts
@@ -1,73 +1,67 @@
import { createAction, Property } from '@activepieces/pieces-framework';
import { pdfmonkeyAuth } from '../common/auth';
-import { makeRequest } from '../common/client';
-import { HttpMethod } from '@activepieces/pieces-common';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
import { templateIdDropdown } from '../common/props';
export const generateDocumentAction = createAction({
- auth: pdfmonkeyAuth,
- name: 'generateDocument',
- classification: 'WRITE',
- displayName: 'Generate Document',
- description: 'Generates a new document using a specified template.',
- audience: 'both',
- aiMetadata: { description: 'Generate a PDF document in PDFMonkey from a template, merging in a JSON payload of data; optionally set a custom filename, attach metadata, and choose draft vs pending status. Use to produce a PDF from structured data. Each call creates a new document, so it is not idempotent.', idempotent: false },
- props: {
- document_template_id: templateIdDropdown,
- payload: Property.Json({
- displayName: 'Payload',
- description: 'Data to use for the Document generation.',
- required: true,
- }),
- meta: Property.Json({
- displayName: 'Meta',
- description: 'Meta-Data to attach to the Document.',
- required: false,
- }),
- fileName: Property.ShortText({
- displayName: 'Custom File Name',
- required: false,
- }),
- status: Property.StaticDropdown({
- displayName: 'Document Status',
- required: false,
- defaultValue: 'draft',
- options: {
- options: [
- {
- label: 'Draft',
- value: 'draft',
- },
- {
- label: 'Pending',
- value: 'pending',
- },
- ],
- },
- }),
- },
- async run({ auth, propsValue }) {
- const { document_template_id, payload, meta, status, fileName } = propsValue;
-
- const metapayload = { ...meta };
-
- if (fileName) metapayload['_filename'] = fileName;
-
- const body = {
- document: {
- document_template_id,
- status,
- payload,
- meta: metapayload,
- },
- };
- const response = await makeRequest(
- auth,
- HttpMethod.POST,
- '/documents',
- undefined,
- body,
- );
- return response;
- },
+ auth: pdfmonkeyAuth,
+ name: 'generateDocument',
+ classification: 'WRITE',
+ displayName: 'Generate Document',
+ description: 'Generates a new document using a specified template.',
+ audience: 'human',
+ aiMetadata: {
+ description:
+ 'Generates a PDF document in PDFMonkey from a template picked in a dropdown and a JSON payload, with optional meta, file name and draft or pending status; can wait for the finished file. Each call creates a new document.',
+ idempotent: false,
+ },
+ outputSchema: pdfmonkeySchemas.wrappedDocument,
+ props: {
+ document_template_id: templateIdDropdown,
+ payload: Property.Json({
+ displayName: 'Payload',
+ description: 'Data to use for the Document generation.',
+ required: true,
+ }),
+ meta: Property.Json({
+ displayName: 'Meta',
+ description: 'Meta-Data to attach to the Document.',
+ required: false,
+ }),
+ fileName: Property.ShortText({
+ displayName: 'Custom File Name',
+ required: false,
+ }),
+ status: Property.StaticDropdown({
+ displayName: 'Document Status',
+ description: 'Draft only saves the document; Pending generates the file right away.',
+ required: false,
+ defaultValue: 'draft',
+ options: {
+ options: [
+ { label: 'Draft', value: 'draft' },
+ { label: 'Pending', value: 'pending' },
+ ],
+ },
+ }),
+ wait_for_completion: Property.Checkbox({
+ displayName: 'Wait for Completion',
+ description: 'Generate now and wait (up to 7 minutes) until the file is ready, so the output has the download URL. Overrides Document Status.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ const document = await pdfmonkeyOperations.createDocument({
+ auth,
+ templateId: propsValue.document_template_id,
+ payload: propsValue.payload,
+ meta: propsValue.meta,
+ filename: propsValue.fileName,
+ status: propsValue.status,
+ waitForCompletion: propsValue.wait_for_completion === true,
+ });
+ return { document };
+ },
});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/get-current-user.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/get-current-user.ts
new file mode 100644
index 00000000000..04749a72ecc
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/get-current-user.ts
@@ -0,0 +1,23 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { pdfmonkeyAuth } from '../common/auth';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
+
+export const getCurrentUserAction = createAction({
+ auth: pdfmonkeyAuth,
+ name: 'get_current_user',
+ classification: 'READ',
+ displayName: 'Get Account Info',
+ description: 'Get the connected PDFMonkey account, its plan and how many documents it can still generate.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Gets the connected PDFMonkey account: name, email, plan, billing interval and available_documents (documents it can still generate in the current period). Use it before a large batch to check the remaining quota. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: pdfmonkeySchemas.currentUser,
+ props: {},
+ async run({ auth }) {
+ return pdfmonkeyOperations.getCurrentUser({ auth });
+ },
+});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/get-document-ai.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/get-document-ai.ts
new file mode 100644
index 00000000000..1e7364b83e9
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/get-document-ai.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { pdfmonkeyAuth } from '../common/auth';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
+import { documentIdText } from '../common/props';
+
+export const getDocumentAiAction = createAction({
+ auth: pdfmonkeyAuth,
+ name: 'get_document_ai',
+ classification: 'READ',
+ displayName: 'Get Document (AI)',
+ description: 'Get a document\'s status, file name and download link by its ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Gets one PDFMonkey document by document ID: status (draft, pending, generating, success, failure), failure cause, file name, template, meta and a download URL valid for 1 hour once status is "success". Use it to check whether generation finished. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: pdfmonkeySchemas.document,
+ props: { document_id: documentIdText },
+ async run({ auth, propsValue }) {
+ return pdfmonkeyOperations.getDocumentCard({ auth, documentId: propsValue.document_id });
+ },
+});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/get-template.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/get-template.ts
new file mode 100644
index 00000000000..2ab37e47c13
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/get-template.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { pdfmonkeyAuth } from '../common/auth';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
+import { templateIdText } from '../common/props';
+
+export const getTemplateAction = createAction({
+ auth: pdfmonkeyAuth,
+ name: 'get_template',
+ classification: 'READ',
+ displayName: 'Get Template',
+ description: 'Get a template with its HTML, test data and page settings.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Gets one PDFMonkey template by template ID, including its published HTML/Liquid body and its sample (test) data. Read the sample data to learn which payload fields Generate Document expects. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: pdfmonkeySchemas.template,
+ props: { template_id: templateIdText },
+ async run({ auth, propsValue }) {
+ return pdfmonkeyOperations.getTemplate({ auth, templateId: propsValue.template_id });
+ },
+});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/list-documents.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/list-documents.ts
new file mode 100644
index 00000000000..17cfef19d98
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/list-documents.ts
@@ -0,0 +1,65 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pdfmonkeyAuth } from '../common/auth';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
+
+export const listDocumentsAction = createAction({
+ auth: pdfmonkeyAuth,
+ name: 'list_documents',
+ classification: 'SEARCH',
+ displayName: 'List Documents',
+ description: 'List documents, newest first, filtered by template, status, file name or update date.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists PDFMonkey documents one page (up to 24) at a time, optionally filtered by template ID, status (draft, pending, generating, success, failure), a file name search or an updated-since date. Returns has_more; ask for the next page to continue. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: pdfmonkeySchemas.documentList,
+ props: {
+ template_id: Property.ShortText({
+ displayName: 'Template ID',
+ description: 'Only documents made from this template. Use List Templates to find the ID.',
+ required: false,
+ }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ options: {
+ options: [
+ { label: 'Draft', value: 'draft' },
+ { label: 'Pending', value: 'pending' },
+ { label: 'Generating', value: 'generating' },
+ { label: 'Success', value: 'success' },
+ { label: 'Failure', value: 'failure' },
+ ],
+ },
+ }),
+ search: Property.ShortText({
+ displayName: 'Search',
+ description: 'A document ID (exact match) or part of a file name.',
+ required: false,
+ }),
+ updated_since: Property.DateTime({
+ displayName: 'Updated Since',
+ description: 'Only documents updated after this date and time.',
+ required: false,
+ }),
+ page: Property.Number({
+ displayName: 'Page',
+ description: 'Page number, starting at 1. Each page has up to 24 documents.',
+ required: false,
+ defaultValue: 1,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ return pdfmonkeyOperations.listDocuments({
+ auth,
+ templateId: propsValue.template_id,
+ status: propsValue.status,
+ search: propsValue.search,
+ updatedSince: propsValue.updated_since,
+ page: propsValue.page,
+ });
+ },
+});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/list-templates.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/list-templates.ts
new file mode 100644
index 00000000000..212fa9340dc
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/list-templates.ts
@@ -0,0 +1,29 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pdfmonkeyAuth } from '../common/auth';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
+
+export const listTemplatesAction = createAction({
+ auth: pdfmonkeyAuth,
+ name: 'list_templates',
+ classification: 'SEARCH',
+ displayName: 'List Templates',
+ description: 'List the document templates in your PDFMonkey workspaces.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the PDFMonkey templates of every workspace the API key can access (or of one workspace ID) with its ID, name, output type (pdf or image) and folder. Use it to find the template ID needed by Generate Document or Get Template. Read-only.',
+ idempotent: true,
+ },
+ outputSchema: pdfmonkeySchemas.templateList,
+ props: {
+ workspace_id: Property.ShortText({
+ displayName: 'Workspace ID',
+ description: 'Only templates of this workspace. Leave empty to list the templates of every workspace you can access.',
+ required: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ return pdfmonkeyOperations.listTemplates({ auth, workspaceId: propsValue.workspace_id });
+ },
+});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/actions/update-document.ts b/packages/pieces/community/pdfmonkey/src/lib/actions/update-document.ts
new file mode 100644
index 00000000000..d529e2e9c9c
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/src/lib/actions/update-document.ts
@@ -0,0 +1,56 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { pdfmonkeyAuth } from '../common/auth';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
+import { documentIdText, fileNameProp } from '../common/props';
+
+export const updateDocumentAction = createAction({
+ auth: pdfmonkeyAuth,
+ name: 'update_document',
+ classification: 'WRITE',
+ displayName: 'Update Document',
+ description: 'Change a document\'s data, metadata, file name or template, and optionally generate it again.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Updates a PDFMonkey document by document ID: replaces its payload and/or meta, sets a new file name or template, and with generate=true queues it for (re)generation. Fields left empty are not changed; a new file name keeps the other meta keys. Use Get Document afterwards to see when generation finished.',
+ idempotent: false,
+ },
+ outputSchema: pdfmonkeySchemas.document,
+ props: {
+ document_id: documentIdText,
+ template_id: Property.ShortText({
+ displayName: 'Template ID',
+ description: 'Switch the document to another template. Leave empty to keep the current one.',
+ required: false,
+ }),
+ payload: Property.Json({
+ displayName: 'Payload',
+ description: 'New data for the document, as a JSON object. Replaces the whole payload. Leave empty to keep it.',
+ required: false,
+ }),
+ meta: Property.Json({
+ displayName: 'Meta',
+ description: 'New metadata, as a JSON object. Replaces all meta keys. Leave empty to keep it.',
+ required: false,
+ }),
+ file_name: fileNameProp,
+ generate: Property.Checkbox({
+ displayName: 'Generate Now',
+ description: 'Queue the document for generation after the update (sets its status to pending).',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run({ auth, propsValue }) {
+ return pdfmonkeyOperations.updateDocument({
+ auth,
+ documentId: propsValue.document_id,
+ templateId: propsValue.template_id,
+ payload: propsValue.payload,
+ meta: propsValue.meta,
+ filename: propsValue.file_name,
+ generate: propsValue.generate === true,
+ });
+ },
+});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/common/auth.ts b/packages/pieces/community/pdfmonkey/src/lib/common/auth.ts
index fdcaaa72649..ee5534fd1c9 100644
--- a/packages/pieces/community/pdfmonkey/src/lib/common/auth.ts
+++ b/packages/pieces/community/pdfmonkey/src/lib/common/auth.ts
@@ -1,26 +1,20 @@
import { PieceAuth } from '@activepieces/pieces-framework';
-import { makeRequest } from './client';
import { HttpMethod } from '@activepieces/pieces-common';
-import { AppConnectionType } from '@activepieces/pieces-framework';
+import { pdfmonkeyClient, PdfmonkeyApiError } from './client';
export const pdfmonkeyAuth = PieceAuth.SecretText({
- displayName: 'API Key',
- description: `You can obtain your API key by navigating to [Account Settings](https://dashboard.pdfmonkey.io/account).`,
- required: true,
- validate: async ({ auth }) => {
- try {
- await makeRequest({
- type: AppConnectionType.SECRET_TEXT,
- secret_text: auth,
- }, HttpMethod.GET, '/documents', {});
- return {
- valid: true,
- };
- } catch {
- return {
- valid: false,
- error: 'Invalid API Key.',
- };
- }
- },
+ displayName: 'API Key',
+ description: 'Your PDFMonkey secret API key. In PDFMonkey, open [My Account](https://dashboard.pdfmonkey.io/account) and copy the API Secret Key.',
+ required: true,
+ validate: async ({ auth }) => {
+ try {
+ await pdfmonkeyClient.request({ auth, method: HttpMethod.GET, path: '/current_user' });
+ return { valid: true };
+ } catch (error) {
+ if (error instanceof PdfmonkeyApiError && (error.status === 401 || error.status === 403)) {
+ return { valid: false, error: 'Invalid API key.' };
+ }
+ return { valid: false, error: `Could not verify the API key: ${error instanceof Error ? error.message : 'unknown error'}` };
+ }
+ },
});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/common/client.ts b/packages/pieces/community/pdfmonkey/src/lib/common/client.ts
index 98a9d76dde3..462528d477b 100644
--- a/packages/pieces/community/pdfmonkey/src/lib/common/client.ts
+++ b/packages/pieces/community/pdfmonkey/src/lib/common/client.ts
@@ -1,33 +1,212 @@
-import { HttpMethod, QueryParams, httpClient } from '@activepieces/pieces-common';
-import { pdfmonkeyAuth } from './auth';
-import { AppConnectionValueForAuthProperty } from '@activepieces/pieces-framework';
-
-
-export const BASE_URL = `https://api.pdfmonkey.io/api/v1`;
-
-export async function makeRequest<T>(
- api_key: AppConnectionValueForAuthProperty<typeof pdfmonkeyAuth>,
- method: HttpMethod,
- path: string,
- query?:QueryParams,
- body?: unknown,
-) {
- try {
-
- const response = await httpClient.sendRequest<T>({
- method,
- url: `${BASE_URL}${path}`,
- headers: {
- 'Authorization': `Bearer ${api_key.secret_text}`,
- 'Content-Type': 'application/json',
- },
- body,
- queryParams:query
- });
- return response.body;
-
- } catch (error: any) {
- throw new Error(`Unexpected error: ${error.message || String(error)}`);
+import { Readable } from 'stream';
+import { httpClient, HttpMethod, QueryParams } from '@activepieces/pieces-common';
+
+export const BASE_URL = 'https://api.pdfmonkey.io/api/v1';
+
+const REQUEST_TIMEOUT_MS = 30000;
+const SYNC_TIMEOUT_MS = 420000;
+const DOWNLOAD_TIMEOUT_MS = 120000;
+const MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024;
+
+let verifiedTlsAgent: Promise<unknown> | undefined;
+
+export class PdfmonkeyApiError extends Error {
+ constructor(message: string, public readonly status: number, public readonly responseBody: unknown) {
+ super(message);
+ this.name = 'PdfmonkeyApiError';
+ }
+}
+
+type QueryValue = string | number | boolean | undefined | null;
+
+function verifiedTls(): Promise<unknown> {
+ verifiedTlsAgent ??= import('undici').then(({ Agent }) => new Agent({ connect: { rejectUnauthorized: true } }));
+ return verifiedTlsAgent;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function apiKeyOf(auth: unknown): string {
+ const raw = isRecord(auth) ? auth['secret_text'] : auth;
+ const key = typeof raw === 'string' ? raw.trim() : '';
+ if (!key) {
+ throw new Error('The PDFMonkey connection has no API key. Reconnect your PDFMonkey account.');
+ }
+ return key;
+}
+
+function segment({ value, label }: { value: unknown; label: string }): string {
+ const text = typeof value === 'string' ? value.trim() : '';
+ if (text === '' || text === '.' || text === '..') {
+ throw new Error(`${label} is required.`);
+ }
+ return encodeURIComponent(text);
+}
+
+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 vendorMessage(body: unknown): string {
+ if (isRecord(body)) {
+ const errors = body['errors'];
+ if (isRecord(errors)) {
+ const parts = Object.entries(errors).map(([field, value]) => `${field} ${Array.isArray(value) ? value.join(', ') : String(value)}`);
+ if (parts.length > 0) return parts.join('; ');
+ }
+ if (Array.isArray(errors) && errors.length > 0) {
+ return errors
+ .map((item) => (isRecord(item) ? String(item['detail'] ?? item['title'] ?? JSON.stringify(item)) : String(item)))
+ .join('; ');
+ }
+ const message = body['message'] ?? body['error'];
+ if (typeof message === 'string' && message.trim()) return message.trim();
+ }
+ if (typeof body === 'string' && body.trim()) {
+ return body.trim().slice(0, 300);
+ }
+ return 'request failed';
+}
+
+function hintFor(status: number): string {
+ if (status === 401) return ' Check the API key or reconnect your PDFMonkey account.';
+ if (status === 403) return ' This API key has no access to this resource.';
+ if (status === 404) return ' Check the ID; the resource does not exist or belongs to another workspace.';
+ if (status === 429) return ' PDFMonkey rate limit reached; try again later.';
+ return '';
+}
+
+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;
+}
+
+function toApiError({ status, body }: { status: number; body: unknown }): PdfmonkeyApiError {
+ const message = vendorMessage(body).replace(/\.$/, '');
+ return new PdfmonkeyApiError(`PDFMonkey API error (${status}): ${message}.${hintFor(status)}`, status, body);
+}
+
+async function request<T = unknown>({
+ auth,
+ method,
+ path,
+ query,
+ body,
+ timeout,
+}: {
+ auth: unknown;
+ method: HttpMethod;
+ path: string;
+ query?: Record<string, QueryValue>;
+ body?: Record<string, unknown>;
+ timeout?: number;
+}): Promise<{ status: number; body: T }> {
+ const hasBody = body !== undefined && method !== HttpMethod.GET && method !== HttpMethod.DELETE;
+ const headers: Record<string, string> = {
+ Authorization: `Bearer ${apiKeyOf(auth)}`,
+ Accept: 'application/json',
+ };
+ if (hasBody) headers['Content-Type'] = 'application/json';
+ const dispatcher = await verifiedTls();
+ try {
+ const response = await httpClient.sendRequest<T>(
+ {
+ method,
+ url: `${BASE_URL}${path}`,
+ headers,
+ queryParams: buildQuery(query),
+ body: hasBody ? body : undefined,
+ timeout: timeout ?? REQUEST_TIMEOUT_MS,
+ followRedirects: false,
+ redactBodyInErrors: hasBody,
+ },
+ { dispatcher },
+ );
+ if (response.status >= 300) {
+ throw new PdfmonkeyApiError(`PDFMonkey API error (${response.status}): unexpected redirect.`, response.status, undefined);
+ }
+ return { status: response.status, body: response.body };
+ } catch (error) {
+ const failure = failureOf(error);
+ if (failure) throw toApiError(failure);
+ if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
+ throw new Error(`PDFMonkey did not answer within ${Math.round((timeout ?? REQUEST_TIMEOUT_MS) / 1000)} seconds.`);
+ }
+ throw error;
+ }
+}
+
+async function download({ url }: { url: string }): Promise<{ data: Buffer; contentType: string | undefined }> {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ throw new Error('PDFMonkey returned an invalid download URL.');
+ }
+ if (parsed.protocol !== 'https:') {
+ throw new Error('PDFMonkey returned a download URL that is not HTTPS.');
+ }
+ const dispatcher = await verifiedTls();
+ const deadline = Date.now() + DOWNLOAD_TIMEOUT_MS;
+ let response;
+ try {
+ response = await httpClient.sendRequest<unknown>(
+ {
+ method: HttpMethod.GET,
+ url: parsed.toString(),
+ headers: { Accept: 'application/pdf, image/*, */*' },
+ responseType: 'stream',
+ timeout: DOWNLOAD_TIMEOUT_MS,
+ followRedirects: false,
+ },
+ { dispatcher },
+ );
+ } catch (error) {
+ const failure = failureOf(error);
+ if (failure) {
+ throw new Error(`Downloading the file failed with status ${failure.status}. The download link is valid for 1 hour; get the document again for a fresh link.`);
+ }
+ throw error;
+ }
+ if (response.status >= 300) {
+ throw new Error(`Downloading the file failed with status ${response.status}.`);
+ }
+ const data = await readCapped({ body: response.body, deadline });
+ const header = response.headers?.['content-type'];
+ return { data, contentType: Array.isArray(header) ? header[0] : header };
+}
+
+async function readCapped({ body, deadline }: { body: unknown; deadline: number }): Promise<Buffer> {
+ if (!(body instanceof Readable)) {
+ throw new Error('PDFMonkey returned an empty file.');
+ }
+ const remaining = Math.max(deadline - Date.now(), 1);
+ const timer = setTimeout(() => body.destroy(new Error(`The download did not finish within ${DOWNLOAD_TIMEOUT_MS / 1000} seconds.`)), remaining);
+ try {
+ const chunks: Buffer[] = [];
+ let total = 0;
+ for await (const chunk of body) {
+ const piece = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ total += piece.length;
+ if (total > MAX_DOWNLOAD_BYTES) {
+ body.destroy();
+ throw new Error('The file is larger than 100 MB and cannot be downloaded in a flow step.');
+ }
+ chunks.push(piece);
}
+ return Buffer.concat(chunks);
+ } finally {
+ clearTimeout(timer);
+ }
+}
-}
\ No newline at end of file
+export const pdfmonkeyClient = { request, download, segment, isRecord, SYNC_TIMEOUT_MS };
diff --git a/packages/pieces/community/pdfmonkey/src/lib/common/operations.ts b/packages/pieces/community/pdfmonkey/src/lib/common/operations.ts
new file mode 100644
index 00000000000..8d4856a1219
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/src/lib/common/operations.ts
@@ -0,0 +1,437 @@
+import { HttpMethod } from '@activepieces/pieces-common';
+import { pdfmonkeyClient, PdfmonkeyApiError } from './client';
+
+const MAX_LIST_PAGES = 20;
+const POLL_INTERVAL_MS = 3000;
+const AI_MAX_WAIT_MS = 240000;
+const DOCUMENT_STATUSES = ['draft', 'pending', 'generating', 'success', 'failure'];
+
+async function createDocument({
+ auth,
+ templateId,
+ payload,
+ meta,
+ filename,
+ status,
+ waitForCompletion,
+ maxWaitMs,
+}: {
+ auth: unknown;
+ templateId: unknown;
+ payload: unknown;
+ meta?: unknown;
+ filename?: unknown;
+ status?: unknown;
+ waitForCompletion?: boolean;
+ maxWaitMs?: number;
+}): Promise<Record<string, unknown>> {
+ const document_template_id = requiredText({ value: templateId, label: 'Template ID' });
+ const parsedPayload = jsonObject({ value: payload, label: 'Payload' }) ?? {};
+ const mergedMeta = withFilename({ meta: jsonObject({ value: meta, label: 'Meta' }), filename });
+ const finalStatus = waitForCompletion ? 'pending' : createStatus(status);
+ const document: Record<string, unknown> = { document_template_id, status: finalStatus, payload: parsedPayload };
+ if (mergedMeta !== undefined) document['meta'] = mergedMeta;
+ if (waitForCompletion && maxWaitMs !== undefined) {
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/documents',
+ body: { document },
+ });
+ const created = unwrap({ body: response.body, key: 'document' });
+ return waitForDocument({ auth, created, deadline: Date.now() + maxWaitMs });
+ }
+ if (waitForCompletion) {
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/documents/sync',
+ body: { document },
+ timeout: pdfmonkeyClient.SYNC_TIMEOUT_MS,
+ });
+ const card = unwrap({ body: response.body, key: 'document_card' });
+ if (card['status'] === 'failure') {
+ throw new Error(`PDFMonkey could not generate document ${String(card['id'])}: ${failureCause(card)}.`);
+ }
+ return card;
+ }
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.POST,
+ path: '/documents',
+ body: { document },
+ });
+ return unwrap({ body: response.body, key: 'document' });
+}
+
+async function waitForDocument({
+ auth,
+ created,
+ deadline,
+}: {
+ auth: unknown;
+ created: Record<string, unknown>;
+ deadline: number;
+}): Promise<Record<string, unknown>> {
+ let lastKnown = created;
+ for (;;) {
+ const card = await readCardIfReachable({ auth, documentId: created['id'] });
+ if (card !== null) {
+ if (card['status'] === 'failure') {
+ throw new Error(`PDFMonkey could not generate document ${String(card['id'])}: ${failureCause(card)}.`);
+ }
+ if (card['status'] === 'success') return card;
+ lastKnown = card;
+ }
+ if (Date.now() + POLL_INTERVAL_MS > deadline) return lastKnown;
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
+ }
+}
+
+async function readCardIfReachable({ auth, documentId }: { auth: unknown; documentId: unknown }): Promise<Record<string, unknown> | null> {
+ try {
+ return await getDocumentCard({ auth, documentId });
+ } catch (error) {
+ if (isTransient(error)) return null;
+ throw error;
+ }
+}
+
+function isTransient(error: unknown): boolean {
+ if (!(error instanceof PdfmonkeyApiError)) return true;
+ return error.status === 408 || error.status === 429 || error.status >= 500;
+}
+
+async function updateDocument({
+ auth,
+ documentId,
+ templateId,
+ payload,
+ meta,
+ filename,
+ generate,
+}: {
+ auth: unknown;
+ documentId: unknown;
+ templateId?: unknown;
+ payload?: unknown;
+ meta?: unknown;
+ filename?: unknown;
+ generate?: boolean;
+}): Promise<Record<string, unknown>> {
+ const id = pdfmonkeyClient.segment({ value: documentId, label: 'Document ID' });
+ const document: Record<string, unknown> = {};
+ const template = optionalText(templateId);
+ if (template !== undefined) document['document_template_id'] = template;
+ const parsedPayload = jsonObject({ value: payload, label: 'Payload' });
+ if (parsedPayload !== undefined) document['payload'] = parsedPayload;
+ const parsedMeta = jsonObject({ value: meta, label: 'Meta' });
+ const name = optionalText(filename);
+ if (parsedMeta !== undefined || name !== undefined) {
+ const base = parsedMeta ?? parseMeta((await getDocumentCard({ auth, documentId }))['meta']);
+ document['meta'] = withFilename({ meta: base, filename: name });
+ }
+ if (generate) document['status'] = 'pending';
+ if (Object.keys(document).length === 0) {
+ throw new Error('Nothing to update. Set a template, payload, meta, file name or turn on Generate Now.');
+ }
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.PUT,
+ path: `/documents/${id}`,
+ body: { document },
+ });
+ return unwrap({ body: response.body, key: 'document' });
+}
+
+async function getDocument({ auth, documentId }: { auth: unknown; documentId: unknown }): Promise<Record<string, unknown>> {
+ const id = pdfmonkeyClient.segment({ value: documentId, label: 'Document ID' });
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: `/documents/${id}` });
+ return unwrap({ body: response.body, key: 'document' });
+}
+
+async function getDocumentCard({ auth, documentId }: { auth: unknown; documentId: unknown }): Promise<DocumentCard> {
+ const id = pdfmonkeyClient.segment({ value: documentId, label: 'Document ID' });
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: `/document_cards/${id}` });
+ return unwrap({ body: response.body, key: 'document_card' });
+}
+
+async function listDocuments({
+ auth,
+ templateId,
+ status,
+ search,
+ updatedSince,
+ page,
+}: {
+ auth: unknown;
+ templateId?: unknown;
+ status?: unknown;
+ search?: unknown;
+ updatedSince?: unknown;
+ page?: unknown;
+}): Promise<{ documents: DocumentCard[]; page: number; total_pages: number; has_more: boolean }> {
+ const statusFilter = optionalText(status);
+ if (statusFilter !== undefined && !DOCUMENT_STATUSES.includes(statusFilter)) {
+ throw new Error(`Status must be one of: ${DOCUMENT_STATUSES.join(', ')}.`);
+ }
+ const pageNumber = positiveInteger({ value: page, label: 'Page' }) ?? 1;
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/document_cards',
+ query: {
+ 'page[number]': pageNumber,
+ 'q[document_template_id]': optionalText(templateId),
+ 'q[status]': statusFilter,
+ 'q[search]': optionalText(search),
+ 'q[updated_since]': unixSeconds(updatedSince),
+ },
+ });
+ const documents = arrayOf(response.body['document_cards']);
+ const meta = pageMeta(response.body['meta']);
+ return { documents, page: meta.current_page ?? pageNumber, total_pages: meta.total_pages ?? pageNumber, has_more: meta.next_page !== null && meta.next_page !== undefined };
+}
+
+async function listAllDocumentCards({
+ auth,
+ query,
+ maxPages = MAX_LIST_PAGES,
+}: {
+ auth: unknown;
+ query: Record<string, string | undefined>;
+ maxPages?: number;
+}): Promise<{ items: DocumentCard[]; truncated: boolean }> {
+ const items: DocumentCard[] = [];
+ for (let page = 1; page <= maxPages; page++) {
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/document_cards',
+ query: { ...query, 'page[number]': page },
+ });
+ items.push(...arrayOf(response.body['document_cards']));
+ const meta = pageMeta(response.body['meta']);
+ if (meta.next_page === null || meta.next_page === undefined) {
+ return { items, truncated: false };
+ }
+ }
+ return { items, truncated: true };
+}
+
+async function deleteDocument({ auth, documentId }: { auth: unknown; documentId: unknown }): Promise<{ success: true; document_id: string }> {
+ const id = pdfmonkeyClient.segment({ value: documentId, label: 'Document ID' });
+ await pdfmonkeyClient.request({ auth, method: HttpMethod.DELETE, path: `/documents/${id}` });
+ return { success: true, document_id: decodeURIComponent(id) };
+}
+
+async function downloadDocument({
+ auth,
+ documentId,
+ fileName,
+ files,
+}: {
+ auth: unknown;
+ documentId: unknown;
+ fileName?: unknown;
+ files: { write: (params: { fileName: string; data: Buffer }) => Promise<string> };
+}): Promise<Record<string, unknown>> {
+ const card = await getDocumentCard({ auth, documentId });
+ if (card['status'] !== 'success') {
+ throw new Error(`Document ${String(card['id'])} is "${String(card['status'])}", not "success", so there is no file to download yet.`);
+ }
+ const url = card['download_url'];
+ if (typeof url !== 'string' || url === '') {
+ throw new Error('PDFMonkey did not return a download URL for this document.');
+ }
+ const { data, contentType } = await pdfmonkeyClient.download({ url });
+ const name = optionalText(fileName) ?? (typeof card['filename'] === 'string' && card['filename'] ? card['filename'] : `${String(card['id'])}.${card['output_type'] === 'image' ? 'png' : 'pdf'}`);
+ const file = await files.write({ fileName: name, data });
+ return {
+ file,
+ file_name: name,
+ size: data.length,
+ content_type: contentType ?? null,
+ document_id: card['id'],
+ document_template_id: card['document_template_id'],
+ document_template_identifier: card['document_template_identifier'],
+ status: card['status'],
+ };
+}
+
+async function listTemplates({ auth, workspaceId }: { auth: unknown; workspaceId?: unknown }): Promise<{ templates: Record<string, unknown>[]; truncated: boolean }> {
+ const given = optionalText(workspaceId);
+ const workspaces = given !== undefined ? [given] : await listWorkspaceIds({ auth });
+ const templates: Record<string, unknown>[] = [];
+ for (const workspace of workspaces) {
+ for (let page = 1; page <= MAX_LIST_PAGES; page++) {
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({
+ auth,
+ method: HttpMethod.GET,
+ path: '/document_template_cards',
+ query: { 'q[workspace_id]': workspace, page },
+ });
+ templates.push(...arrayOf(response.body['document_template_cards']).map(withoutHiddenFields));
+ const meta = pageMeta(response.body['meta']);
+ if (meta.next_page === null || meta.next_page === undefined) break;
+ if (page === MAX_LIST_PAGES) return { templates, truncated: true };
+ }
+ }
+ return { templates, truncated: false };
+}
+
+async function listWorkspaceIds({ auth }: { auth: unknown }): Promise<string[]> {
+ const ids: string[] = [];
+ for (let page = 1; page <= MAX_LIST_PAGES; page++) {
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: '/workspaces', query: { page } });
+ for (const workspace of arrayOf(response.body['apps'])) {
+ if (typeof workspace['id'] === 'string') ids.push(workspace['id']);
+ }
+ const meta = pageMeta(response.body['meta']);
+ if (meta.next_page === null || meta.next_page === undefined) break;
+ }
+ return ids;
+}
+
+async function getTemplate({ auth, templateId }: { auth: unknown; templateId: unknown }): Promise<Record<string, unknown>> {
+ const id = pdfmonkeyClient.segment({ value: templateId, label: 'Template ID' });
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: `/document_templates/${id}` });
+ const template = unwrap({ body: response.body, key: 'document_template' });
+ return withoutHiddenFields(template);
+}
+
+function withoutHiddenFields(template: Record<string, unknown>): Record<string, unknown> {
+ return Object.fromEntries(Object.entries(template).filter(([key]) => !HIDDEN_TEMPLATE_FIELDS.includes(key)));
+}
+
+async function getCurrentUser({ auth }: { auth: unknown }): Promise<Record<string, unknown>> {
+ const response = await pdfmonkeyClient.request<Record<string, unknown>>({ auth, method: HttpMethod.GET, path: '/current_user' });
+ const user = unwrap({ body: response.body, key: 'current_user' });
+ return Object.fromEntries(USER_FIELDS.map((key) => [key, user[key] ?? null]));
+}
+
+function unwrap({ body, key }: { body: unknown; key: string }): Record<string, unknown> {
+ const value = pdfmonkeyClient.isRecord(body) ? body[key] : undefined;
+ if (!pdfmonkeyClient.isRecord(value)) {
+ throw new PdfmonkeyApiError(`PDFMonkey returned an unexpected response (no ${key}).`, 200, body);
+ }
+ return value;
+}
+
+function failureCause(card: Record<string, unknown>): string {
+ return typeof card['failure_cause'] === 'string' && card['failure_cause'] ? card['failure_cause'] : 'no reason given';
+}
+
+function arrayOf(value: unknown): Record<string, unknown>[] {
+ return Array.isArray(value) ? value.filter(pdfmonkeyClient.isRecord) : [];
+}
+
+function pageMeta(value: unknown): { current_page?: number; total_pages?: number; next_page?: number | null } {
+ if (!pdfmonkeyClient.isRecord(value)) return { next_page: null };
+ const number = (input: unknown) => (typeof input === 'number' ? input : undefined);
+ return {
+ current_page: number(value['current_page']),
+ total_pages: number(value['total_pages']),
+ next_page: typeof value['next_page'] === 'number' ? value['next_page'] : null,
+ };
+}
+
+function requiredText({ value, label }: { value: unknown; label: string }): string {
+ const text = optionalText(value);
+ if (text === undefined) throw new Error(`${label} is required.`);
+ return text;
+}
+
+function optionalText(value: unknown): string | undefined {
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);
+ if (typeof value !== 'string') return undefined;
+ const text = value.trim();
+ return text === '' ? undefined : text;
+}
+
+function positiveInteger({ value, label }: { value: unknown; label: string }): number | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const number = Number(value);
+ if (!Number.isInteger(number) || number < 1) throw new Error(`${label} must be a whole number of 1 or more.`);
+ return number;
+}
+
+function unixSeconds(value: unknown): number | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const ms = typeof value === 'number' ? value : Date.parse(String(value));
+ if (!Number.isFinite(ms)) throw new Error('Updated Since must be a date, e.g. 2026-01-31T00:00:00Z.');
+ return Math.floor(ms / 1000);
+}
+
+function jsonObject({ value, label }: { value: unknown; label: string }): Record<string, unknown> | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ let parsed = value;
+ if (typeof value === 'string') {
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ throw new Error(`${label} must be a JSON object.`);
+ }
+ }
+ if (!pdfmonkeyClient.isRecord(parsed)) throw new Error(`${label} must be a JSON object, not a list or a single value.`);
+ return parsed;
+}
+
+function parseMeta(value: unknown): Record<string, unknown> | undefined {
+ if (pdfmonkeyClient.isRecord(value)) return value;
+ if (typeof value !== 'string' || value.trim() === '') return undefined;
+ try {
+ const parsed: unknown = JSON.parse(value);
+ return pdfmonkeyClient.isRecord(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function withFilename({ meta, filename }: { meta: Record<string, unknown> | undefined; filename: unknown }): Record<string, unknown> | undefined {
+ const name = optionalText(filename);
+ if (name === undefined) return meta;
+ return { ...(meta ?? {}), _filename: name };
+}
+
+function createStatus(value: unknown): string {
+ const status = optionalText(value) ?? 'draft';
+ if (status !== 'draft' && status !== 'pending') throw new Error('Status must be "draft" or "pending".');
+ return status;
+}
+
+const USER_FIELDS = [
+ 'id',
+ 'email',
+ 'first_name',
+ 'last_name',
+ 'company_name',
+ 'current_plan',
+ 'current_plan_interval',
+ 'available_documents',
+ 'paying_customer',
+ 'share_links',
+ 'trial_ends_on',
+ 'lang',
+ 'created_at',
+];
+
+const HIDDEN_TEMPLATE_FIELDS = ['auth_token', 'checksum'];
+
+export const pdfmonkeyOperations = {
+ createDocument,
+ updateDocument,
+ getDocument,
+ getDocumentCard,
+ listDocuments,
+ listAllDocumentCards,
+ deleteDocument,
+ downloadDocument,
+ listTemplates,
+ getTemplate,
+ getCurrentUser,
+ parseMeta,
+ AI_MAX_WAIT_MS,
+};
+
+type DocumentCard = Record<string, unknown>;
diff --git a/packages/pieces/community/pdfmonkey/src/lib/common/output-schemas.ts b/packages/pieces/community/pdfmonkey/src/lib/common/output-schemas.ts
new file mode 100644
index 00000000000..fc99789243f
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/src/lib/common/output-schemas.ts
@@ -0,0 +1,133 @@
+import { OutputSchema } from '@activepieces/pieces-framework';
+
+type Fields = OutputSchema['fields'];
+
+const documentFields: Fields = [
+ { key: 'id', label: 'Document ID' },
+ { key: 'status', label: 'Status', description: 'draft, pending, generating, success or failure.' },
+ { key: 'filename', label: 'File Name' },
+ { key: 'download_url', label: 'Download URL', format: 'url', description: 'Signed link to the file, valid for 1 hour. Empty until status is success.' },
+ { key: 'public_share_link', label: 'Public Share Link', format: 'url', description: 'Permanent public link. Only on plans with Share Links.' },
+ { key: 'preview_url', label: 'Preview URL', format: 'url' },
+ { key: 'failure_cause', label: 'Failure Cause' },
+ { key: 'output_type', label: 'Output Type', description: 'pdf or image.' },
+ { key: 'document_template_id', label: 'Template ID' },
+ { key: 'document_template_identifier', label: 'Template Name' },
+ { key: 'meta', label: 'Meta (JSON)', description: 'The document metadata as a JSON string.' },
+ { key: 'app_id', label: 'Workspace ID' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+const fullDocumentFields: Fields = [
+ ...documentFields.filter((field) => field.key !== 'document_template_identifier'),
+ { key: 'payload', label: 'Payload (JSON)', description: 'The data merged into the template, as a JSON string.' },
+ {
+ key: 'generation_logs',
+ label: 'Generation Logs',
+ listItems: [
+ { key: 'type', label: 'Type' },
+ { key: 'message', label: 'Message' },
+ { key: 'timestamp', label: 'Time' },
+ ],
+ },
+];
+
+const templateCardFields: Fields = [
+ { key: 'id', label: 'Template ID' },
+ { key: 'identifier', label: 'Name' },
+ { key: 'output_type', label: 'Output Type' },
+ { key: 'edition_mode', label: 'Edition Mode' },
+ { key: 'template_folder_id', label: 'Folder ID' },
+ { key: 'app_id', label: 'Workspace ID' },
+ { key: 'pdf_engine_id', label: 'PDF Engine ID' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ { key: 'updated_at', label: 'Updated At', format: 'datetime' },
+];
+
+export const pdfmonkeySchemas = {
+ document: { fields: documentFields },
+ wrappedDocument: {
+ fields: documentFields.map((field) => ({ ...field, value: `document.${field.value ?? field.key}` })),
+ },
+ wrappedFullDocument: {
+ fields: fullDocumentFields.map((field) => ({ ...field, value: `document.${field.value ?? field.key}` })),
+ },
+ documentList: {
+ fields: [
+ { key: 'documents', label: 'Documents', labelKey: 'filename', listItems: documentFields },
+ { key: 'page', label: 'Page', format: 'number' },
+ { key: 'total_pages', label: 'Total Pages', format: 'number' },
+ { key: 'has_more', label: 'Has More', format: 'boolean' },
+ ],
+ },
+ deleted: {
+ fields: [
+ { key: 'success', label: 'Deleted', format: 'boolean' },
+ { key: 'document_id', label: 'Document ID' },
+ ],
+ },
+ legacyDeleted: {
+ fields: [
+ { key: 'status', label: 'Status' },
+ { key: 'message', label: 'Message' },
+ { key: 'document_id', label: 'Document ID' },
+ ],
+ },
+ download: {
+ fields: [
+ { key: 'file', label: 'File', format: 'url', description: 'The downloaded file. Pass it to any step that takes a file.' },
+ { key: 'file_name', label: 'File Name' },
+ { key: 'size', label: 'Size', format: 'filesize' },
+ { key: 'content_type', label: 'Content Type' },
+ { key: 'document_id', label: 'Document ID' },
+ { key: 'document_template_id', label: 'Template ID' },
+ { key: 'document_template_identifier', label: 'Template Name' },
+ { key: 'status', label: 'Status' },
+ ],
+ },
+ templateList: {
+ fields: [
+ {
+ key: 'templates',
+ label: 'Templates',
+ labelKey: 'identifier',
+ listItems: [
+ ...templateCardFields.filter((field) => field.key !== 'pdf_engine_id'),
+ { key: 'template_folder_identifier', label: 'Folder Name' },
+ { key: 'pdf_engine_name', label: 'PDF Engine' },
+ { key: 'is_draft', label: 'Has Unpublished Changes', format: 'boolean' },
+ ],
+ },
+ { key: 'truncated', label: 'Truncated', format: 'boolean', description: 'True when the list stopped early; there are more templates.' },
+ ],
+ },
+ template: {
+ fields: [
+ ...templateCardFields,
+ { key: 'body_draft', label: 'Draft Body (HTML/Liquid)', format: 'html' },
+ { key: 'sample_data', label: 'Sample Data (JSON)', description: 'Published test data: shows which payload fields the template uses.' },
+ { key: 'body', label: 'Body (HTML/Liquid)', format: 'html' },
+ { key: 'scss_style', label: 'Styles' },
+ { key: 'ttl', label: 'Retention (Seconds)', format: 'number' },
+ { key: 'preview_url', label: 'Preview URL', format: 'url' },
+ ],
+ },
+ currentUser: {
+ fields: [
+ { key: 'id', label: 'User ID' },
+ { key: 'email', label: 'Email', format: 'email' },
+ { key: 'first_name', label: 'First Name' },
+ { key: 'last_name', label: 'Last Name' },
+ { key: 'company_name', label: 'Company' },
+ { key: 'current_plan', label: 'Plan' },
+ { key: 'current_plan_interval', label: 'Billing Interval' },
+ { key: 'available_documents', label: 'Available Documents', format: 'number', description: 'Documents the account can still generate in the current period.' },
+ { key: 'paying_customer', label: 'Paying Customer', format: 'boolean' },
+ { key: 'share_links', label: 'Share Links Enabled', format: 'boolean' },
+ { key: 'trial_ends_on', label: 'Trial Ends On', format: 'date' },
+ { key: 'lang', label: 'Language' },
+ { key: 'created_at', label: 'Created At', format: 'datetime' },
+ ],
+ },
+} satisfies Record<string, OutputSchema>;
diff --git a/packages/pieces/community/pdfmonkey/src/lib/common/props.ts b/packages/pieces/community/pdfmonkey/src/lib/common/props.ts
index 6ba87f1cb51..6b58e7b7c76 100644
--- a/packages/pieces/community/pdfmonkey/src/lib/common/props.ts
+++ b/packages/pieces/community/pdfmonkey/src/lib/common/props.ts
@@ -1,103 +1,102 @@
-import { DropdownOption, Property } from '@activepieces/pieces-framework';
-import { makeRequest } from './client';
-import { HttpMethod } from '@activepieces/pieces-common';
+import { DropdownState, Property } from '@activepieces/pieces-framework';
import { pdfmonkeyAuth } from './auth';
+import { pdfmonkeyOperations } from './operations';
-export const templateIdDropdown = Property.Dropdown({
- displayName: 'Template ID',
- auth: pdfmonkeyAuth,
- required: true,
- refreshers: [],
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Please connect your account first.',
- };
- }
-
- try {
- let page = 1;
- let hasMore = true;
-
- const options: DropdownOption<string>[] = [];
-
- do {
- const response = await makeRequest<{
- document_template_cards: Array<{ id: string; identifier: string }>;
- meta: { total_pages: number; current_page: number };
- }>(auth, HttpMethod.GET, '/document_template_cards',{ page: page.toString() });
+async function dropdown({
+ auth,
+ load,
+}: {
+ auth: unknown;
+ load: () => Promise<{ options: { label: string; value: string }[]; truncated: boolean }>;
+}): Promise<DropdownState<string>> {
+ if (!auth) {
+ return { disabled: true, options: [], placeholder: 'Connect your PDFMonkey account first.' };
+ }
+ try {
+ const { options, truncated } = await load();
+ return {
+ disabled: false,
+ options,
+ placeholder: options.length === 0 ? 'Nothing found in this account.' : truncated ? `Showing the first ${options.length}; map an ID instead.` : 'Select one',
+ };
+ } catch (error) {
+ return { disabled: true, options: [], placeholder: `Could not load the list: ${error instanceof Error ? error.message : 'unknown error'}` };
+ }
+}
- const items = response.document_template_cards ?? [];
+function text(value: unknown): string {
+ return typeof value === 'string' ? value : '';
+}
- for (const template of items) {
- options.push({ label: template.identifier, value: template.id });
- }
-
- page++;
- hasMore = response.meta.current_page < response.meta.total_pages;
- } while (hasMore);
-
- return {
- disabled: false,
- options,
- };
- } catch (error) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Error loading document templates.',
- };
- }
- },
+export const templateIdDropdown = Property.Dropdown({
+ displayName: 'Template ID',
+ auth: pdfmonkeyAuth,
+ required: true,
+ refreshers: [],
+ options: async ({ auth }) =>
+ dropdown({
+ auth,
+ load: async () => {
+ const { templates, truncated } = await pdfmonkeyOperations.listTemplates({ auth });
+ return {
+ truncated,
+ options: templates
+ .filter((template) => typeof template['id'] === 'string')
+ .map((template) => ({ label: text(template['identifier']) || text(template['id']), value: text(template['id']) })),
+ };
+ },
+ }),
});
export const documentIdDropdown = Property.Dropdown({
- displayName: 'Document ID',
- required: true,
- refreshers: [],
- auth: pdfmonkeyAuth,
- options: async ({ auth }) => {
- if (!auth) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Please connect your account first.',
- };
- }
-
- try {
- let page = 1;
- let hasMore = true;
+ displayName: 'Document ID',
+ required: true,
+ refreshers: [],
+ auth: pdfmonkeyAuth,
+ options: async ({ auth }) =>
+ dropdown({
+ auth,
+ load: async () => {
+ const { items, truncated } = await pdfmonkeyOperations.listAllDocumentCards({ auth, query: {} });
+ return {
+ truncated,
+ options: items
+ .filter((document) => typeof document['id'] === 'string')
+ .map((document) => ({
+ label: `${text(document['filename']) || text(document['document_template_identifier']) || 'Untitled'} (${text(document['status'])}, ${text(document['id']).slice(0, 8)})`,
+ value: text(document['id']),
+ })),
+ };
+ },
+ }),
+});
- const options: DropdownOption<string>[] = [];
+export const documentIdText = Property.ShortText({
+ displayName: 'Document ID',
+ description: 'The document ID (a UUID), e.g. from Generate Document or List Documents.',
+ required: true,
+});
- do {
- const response = await makeRequest<{
- document_cards: Array<{ id: string; filename: string }>;
- meta: { total_pages: number; current_page: number };
- }>(auth, HttpMethod.GET, '/document_cards', { page: page.toString() });
+export const templateIdText = Property.ShortText({
+ displayName: 'Template ID',
+ description: 'The template ID (a UUID). Use List Templates to find it.',
+ required: true,
+});
- const items = response.document_cards ?? [];
+export const payloadProp = Property.Json({
+ displayName: 'Payload',
+ description: 'The data merged into the template, as a JSON object, e.g. {"clientName": "Jane Doe", "total": 120}.',
+ required: true,
+});
- for (const doc of items) {
- options.push({ label: doc.filename, value: doc.id });
- }
- page++;
- hasMore = response.meta.current_page < response.meta.total_pages;
- } while (hasMore);
+export const metaProp = Property.Json({
+ displayName: 'Meta',
+ description: 'Optional metadata to keep with the document, as a JSON object. It is returned with the document and in triggers.',
+ required: false,
+});
- return {
- disabled: false,
- options,
- };
- } catch (error) {
- return {
- disabled: true,
- options: [],
- placeholder: 'Error loading documents.',
- };
- }
- },
+export const fileNameProp = Property.ShortText({
+ displayName: 'Custom File Name',
+ description: 'Name of the generated file, e.g. "Invoice 2026-001.pdf". Stored as the _filename meta key.',
+ required: false,
});
diff --git a/packages/pieces/community/pdfmonkey/src/lib/triggers/document-generated.ts b/packages/pieces/community/pdfmonkey/src/lib/triggers/document-generated.ts
index 123ec9dca91..8e7864ca6a8 100644
--- a/packages/pieces/community/pdfmonkey/src/lib/triggers/document-generated.ts
+++ b/packages/pieces/community/pdfmonkey/src/lib/triggers/document-generated.ts
@@ -1,61 +1,43 @@
import {
createTrigger,
TriggerStrategy,
- PiecePropValueSchema,
AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
-import {
- DedupeStrategy,
- HttpMethod,
- Polling,
- pollingHelper,
- QueryParams,
-} from '@activepieces/pieces-common';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
import dayjs from 'dayjs';
import { pdfmonkeyAuth } from '../common/auth';
-import { makeRequest } from '../common/client';
+import { pdfmonkeyOperations } from '../common/operations';
+import { pdfmonkeySchemas } from '../common/output-schemas';
const polling: Polling<AppConnectionValueForAuthProperty<typeof pdfmonkeyAuth>, Record<string, never>> = {
strategy: DedupeStrategy.TIMEBASED,
items: async ({ auth, lastFetchEpochMS }) => {
- let page = 1;
- let hasMore = true;
const isTest = lastFetchEpochMS === 0;
-
- const documents = [];
-
- do {
- const qs: QueryParams = {
- 'page[number]': page.toString(),
- 'q[status]': 'success',
- };
-
- if (!isTest) qs['q[updated_since]'] = lastFetchEpochMS.toString();
-
- const response = await makeRequest<{
- document_cards: Array<{ id: string; created_at: string }>;
- meta: { total_pages: number; current_page: number };
- }>(auth, HttpMethod.GET, '/document_cards', qs);
-
- const items = response.document_cards ?? [];
-
- documents.push(...items);
-
- if (isTest) break;
-
- page++;
- hasMore = response.meta.current_page < response.meta.total_pages;
- } while (hasMore);
-
- return documents.map((doc) => {
- return {
- epochMilliSeconds: dayjs(doc.created_at).valueOf(),
- data: doc,
- };
- });
+ const query: Record<string, string | undefined> = {
+ 'q[status]': 'success',
+ 'q[updated_since]': isTest ? undefined : String(Math.floor(lastFetchEpochMS / 1000)),
+ };
+ const documents = isTest
+ ? (await pdfmonkeyOperations.listDocuments({ auth, status: 'success' })).documents.slice(0, 5)
+ : await listSincePoll({ auth, query });
+ return documents.map((document) => ({
+ epochMilliSeconds: dayjs(String(document['updated_at'] ?? document['created_at'])).valueOf(),
+ data: document,
+ }));
},
};
+async function listSincePoll({ auth, query }: { auth: unknown; query: Record<string, string | undefined> }) {
+ const { items, truncated } = await pdfmonkeyOperations.listAllDocumentCards({ auth, query, maxPages: MAX_POLL_PAGES });
+ if (truncated) {
+ throw new Error(`More than ${MAX_POLL_PAGES * PAGE_SIZE} documents finished since the last check. The trigger stopped without moving its checkpoint so no document is skipped; it retries on the next poll.`);
+ }
+ return items;
+}
+
+const MAX_POLL_PAGES = 400;
+const PAGE_SIZE = 24;
+
export const documentGeneratedTrigger = createTrigger({
auth: pdfmonkeyAuth,
name: 'documentGenerated',
@@ -65,35 +47,33 @@ export const documentGeneratedTrigger = createTrigger({
aiMetadata: {
description: 'Fires when a PDFMonkey document finishes generating with a success status. Each event represents one completed document, carrying its download URL, filename, template, and metadata. Polls for documents updated since the last check.',
},
+ outputSchema: pdfmonkeySchemas.document,
props: {},
sampleData: {
- id: '11475e57-0334-4ad5-8896-9462a2243957',
- app_id: 'c2b67b84-4aac-49ea-bed8-69a15d7a65d3',
- created_at: '2022-04-07T11:01:38.201+02:00',
- document_template_id: '96611e9e-ab03-4ac3-8551-1b485210c892',
- document_template_identifier: 'My Awesome Template',
- download_url:
- 'https://pdfmonkey.s3.eu-west-1.amazonaws.com/production/backend/document/11475e57-0334-4ad5-8896-9462a2243957/my-test-document.pdf?...',
- failure_cause: null,
- filename: 'my-test-document.pdf',
- meta: '{ "_filename":"my-test-document.pdf" }',
- public_share_link:
- 'https://files.pdfmonkey.io/share/5CEA8C37-D130-4C19-9E11-72BE2293C82B/my-test-document.pdf',
+ id: '472b1c2e-6a4b-4f04-ad78-0aa040fd9f09',
+ app_id: '9dd42e52-2c1f-4fde-adf1-50c12afb612e',
+ created_at: '2026-10-15T13:54:20.177+02:00',
+ updated_at: '2026-10-15T13:54:22.021+02:00',
+ document_template_id: '07fdc6bb-8eff-4d1a-9cc6-9083775905df',
+ document_template_identifier: 'Invoice',
status: 'success',
- updated_at: '2022-04-03T11:12:56.023+02:00',
+ output_type: 'pdf',
+ filename: 'Invoice INV-42.pdf',
+ meta: '{"ref":"INV-42","_filename":"Invoice INV-42.pdf"}',
+ download_url: 'https://pdfmonkey-store.s3.eu-west-3.amazonaws.com/production/backend/document/472b1c2e-6a4b-4f04-ad78-0aa040fd9f09/Invoice%20INV-42.pdf?X-Amz-Expires=3600',
+ preview_url: 'https://preview.pdfmonkey.io/pdf/web/viewer.html?file=https%3A%2F%2Fpreview.pdfmonkey.io%2Fdocument-render%2F472b1c2e-6a4b-4f04-ad78-0aa040fd9f09',
+ public_share_link: null,
+ failure_cause: null,
},
type: TriggerStrategy.POLLING,
async test(context) {
return await pollingHelper.test(polling, context);
},
async onEnable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onEnable(polling, { store, auth, propsValue });
+ await pollingHelper.onEnable(polling, context);
},
-
async onDisable(context) {
- const { store, auth, propsValue } = context;
- await pollingHelper.onDisable(polling, { store, auth, propsValue });
+ await pollingHelper.onDisable(polling, context);
},
async run(context) {
diff --git a/packages/pieces/community/pdfmonkey/test/pdfmonkey.test.ts b/packages/pieces/community/pdfmonkey/test/pdfmonkey.test.ts
new file mode 100644
index 00000000000..b8df7437670
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/test/pdfmonkey.test.ts
@@ -0,0 +1,280 @@
+import { Readable } from 'stream';
+import { httpClient, HttpError } from '@activepieces/pieces-common';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { PdfmonkeyApiError } from '../src/lib/common/client';
+import { pdfmonkeyOperations } from '../src/lib/common/operations';
+import { documentGeneratedTrigger } from '../src/lib/triggers/document-generated';
+
+const auth = { type: 'SECRET_TEXT', secret_text: ' key-123 ' };
+const CARD = {
+ id: 'doc-1',
+ status: 'success',
+ filename: 'Invoice.pdf',
+ output_type: 'pdf',
+ document_template_id: 'tpl-1',
+ document_template_identifier: 'Invoice',
+ download_url: 'https://pdfmonkey-store.s3.eu-west-3.amazonaws.com/doc-1/Invoice.pdf?sig=1',
+ meta: '{"ref":"a"}',
+ updated_at: '2026-10-15T13:54:22.021+02:00',
+};
+
+type Call = { method: string; url: string; query: unknown; body: unknown; headers: unknown; redact: boolean | undefined; followRedirects: boolean | undefined };
+type Route = { method: string; path: string; status?: number; body?: unknown; match?: (query: Record<string, string>) => boolean };
+
+function mockRoutes(routes: Route[]) {
+ const calls: Call[] = [];
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ const url = new URL(request.url);
+ calls.push({
+ method: request.method,
+ url: request.url,
+ query: request.queryParams,
+ body: request.body,
+ headers: request.headers,
+ redact: request.redactBodyInErrors,
+ followRedirects: request.followRedirects,
+ });
+ const query = request.queryParams ?? {};
+ const route = routes.find((r) => r.method === request.method && (url.pathname === `/api/v1${r.path}` || url.href.startsWith(r.path)) && (!r.match || r.match(query)));
+ if (!route) throw new Error(`unexpected ${request.method} ${url.pathname}`);
+ if ((route.status ?? 200) >= 400) throw new HttpError({ secret: 'x' }, { status: route.status ?? 500, responseBody: route.body });
+ return { status: route.status ?? 200, headers: { 'content-type': 'application/pdf' }, body: route.body };
+ });
+ return calls;
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('createDocument', () => {
+ it('waits through the sync endpoint with status pending and the file name in meta', async () => {
+ const calls = mockRoutes([{ method: 'POST', path: '/documents/sync', body: { document_card: CARD } }]);
+ const result = await pdfmonkeyOperations.createDocument({
+ auth,
+ templateId: ' tpl-1 ',
+ payload: '{"name":"Jane"}',
+ meta: { ref: 'a' },
+ filename: 'Invoice.pdf',
+ status: 'draft',
+ waitForCompletion: true,
+ });
+ expect(result['id']).toBe('doc-1');
+ expect(calls[0].url).toBe('https://api.pdfmonkey.io/api/v1/documents/sync');
+ expect(calls[0].body).toEqual({ document: { document_template_id: 'tpl-1', status: 'pending', payload: { name: 'Jane' }, meta: { ref: 'a', _filename: 'Invoice.pdf' } } });
+ expect(calls[0].headers).toMatchObject({ Authorization: 'Bearer key-123', 'Content-Type': 'application/json' });
+ expect(calls[0].redact).toBe(true);
+ expect(calls[0].followRedirects).toBe(false);
+ });
+
+ it('fails when the sync generation fails', async () => {
+ mockRoutes([{ method: 'POST', path: '/documents/sync', body: { document_card: { ...CARD, status: 'failure', failure_cause: 'Liquid error' } } }]);
+ await expect(pdfmonkeyOperations.createDocument({ auth, templateId: 'tpl-1', payload: {}, waitForCompletion: true })).rejects.toThrow('Liquid error');
+ });
+
+ it('rejects array payloads and unknown statuses before any request', async () => {
+ const calls = mockRoutes([]);
+ await expect(pdfmonkeyOperations.createDocument({ auth, templateId: 'tpl-1', payload: [1] })).rejects.toThrow('JSON object');
+ await expect(pdfmonkeyOperations.createDocument({ auth, templateId: 'tpl-1', payload: {}, status: 'success' })).rejects.toThrow('draft');
+ await expect(pdfmonkeyOperations.createDocument({ auth, templateId: '', payload: {} })).rejects.toThrow('Template ID is required');
+ expect(calls).toHaveLength(0);
+ });
+});
+
+describe('createDocument with an agent deadline', () => {
+ it('queues the document, polls it, and returns the finished card', async () => {
+ vi.useFakeTimers();
+ let polls = 0;
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ if (request.method === 'POST') return { status: 200, headers: {}, body: { document: { id: 'doc-1', status: 'pending' } } };
+ polls += 1;
+ return { status: 200, headers: {}, body: { document_card: polls < 2 ? { ...CARD, status: 'generating' } : CARD } };
+ });
+ const pending = pdfmonkeyOperations.createDocument({ auth, templateId: 'tpl-1', payload: {}, waitForCompletion: true, maxWaitMs: pdfmonkeyOperations.AI_MAX_WAIT_MS });
+ await vi.advanceTimersByTimeAsync(10000);
+ const result = await pending;
+ expect(result['status']).toBe('success');
+ expect(polls).toBe(2);
+ vi.useRealTimers();
+ });
+
+ it('returns the document ID and current status when the deadline passes', async () => {
+ vi.useFakeTimers();
+ const urls: string[] = [];
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ urls.push(request.url);
+ if (request.method === 'POST') return { status: 200, headers: {}, body: { document: { id: 'doc-1', status: 'pending' } } };
+ return { status: 200, headers: {}, body: { document_card: { ...CARD, status: 'generating', download_url: null } } };
+ });
+ const pending = pdfmonkeyOperations.createDocument({ auth, templateId: 'tpl-1', payload: {}, waitForCompletion: true, maxWaitMs: pdfmonkeyOperations.AI_MAX_WAIT_MS });
+ await vi.advanceTimersByTimeAsync(pdfmonkeyOperations.AI_MAX_WAIT_MS + 10000);
+ const result = await pending;
+ expect(result).toMatchObject({ id: 'doc-1', status: 'generating' });
+ expect(urls[0]).toBe('https://api.pdfmonkey.io/api/v1/documents');
+ expect(urls.some((url) => url.includes('/documents/sync'))).toBe(false);
+ expect(pdfmonkeyOperations.AI_MAX_WAIT_MS).toBeLessThan(5 * 60 * 1000);
+ vi.useRealTimers();
+ });
+
+ it('keeps polling through temporary status failures and still returns the created document', async () => {
+ vi.useFakeTimers();
+ let polls = 0;
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ if (request.method === 'POST') return { status: 200, headers: {}, body: { document: { id: 'doc-1', status: 'pending' } } };
+ polls += 1;
+ if (polls === 1) throw new HttpError({}, { status: 503, responseBody: {} });
+ if (polls === 2) throw new Error('socket hang up');
+ return { status: 200, headers: {}, body: { document_card: CARD } };
+ });
+ const pending = pdfmonkeyOperations.createDocument({ auth, templateId: 'tpl-1', payload: {}, waitForCompletion: true, maxWaitMs: pdfmonkeyOperations.AI_MAX_WAIT_MS });
+ await vi.advanceTimersByTimeAsync(20000);
+ const result = await pending;
+ expect(result).toMatchObject({ id: 'doc-1', status: 'success' });
+ vi.useRealTimers();
+ });
+
+ it('returns the created ID when every status check fails until the deadline', async () => {
+ vi.useFakeTimers();
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ if (request.method === 'POST') return { status: 200, headers: {}, body: { document: { id: 'doc-1', status: 'pending' } } };
+ throw new HttpError({}, { status: 429, responseBody: {} });
+ });
+ const pending = pdfmonkeyOperations.createDocument({ auth, templateId: 'tpl-1', payload: {}, waitForCompletion: true, maxWaitMs: pdfmonkeyOperations.AI_MAX_WAIT_MS });
+ await vi.advanceTimersByTimeAsync(pdfmonkeyOperations.AI_MAX_WAIT_MS + 10000);
+ const result = await pending;
+ expect(result).toMatchObject({ id: 'doc-1', status: 'pending' });
+ vi.useRealTimers();
+ });
+
+ it('stops on a permanent status error such as 401', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ if (request.method === 'POST') return { status: 200, headers: {}, body: { document: { id: 'doc-1', status: 'pending' } } };
+ throw new HttpError({}, { status: 401, responseBody: {} });
+ });
+ await expect(pdfmonkeyOperations.createDocument({ auth, templateId: 'tpl-1', payload: {}, waitForCompletion: true, maxWaitMs: 1000 })).rejects.toBeInstanceOf(PdfmonkeyApiError);
+ });
+
+ it('fails with the cause when generation fails while polling', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ if (request.method === 'POST') return { status: 200, headers: {}, body: { document: { id: 'doc-1', status: 'pending' } } };
+ return { status: 200, headers: {}, body: { document_card: { ...CARD, status: 'failure', failure_cause: 'Liquid error' } } };
+ });
+ await expect(pdfmonkeyOperations.createDocument({ auth, templateId: 'tpl-1', payload: {}, waitForCompletion: true, maxWaitMs: 1000 })).rejects.toThrow('Liquid error');
+ });
+});
+
+describe('updateDocument', () => {
+ it('keeps the other meta keys when only the file name changes', async () => {
+ const calls = mockRoutes([
+ { method: 'GET', path: '/document_cards/doc-1', body: { document_card: CARD } },
+ { method: 'PUT', path: '/documents/doc-1', body: { document: { ...CARD, status: 'pending' } } },
+ ]);
+ await pdfmonkeyOperations.updateDocument({ auth, documentId: 'doc-1', filename: 'New.pdf', generate: true });
+ expect(calls[1].body).toEqual({ document: { meta: { ref: 'a', _filename: 'New.pdf' }, status: 'pending' } });
+ });
+
+ it('refuses an empty update', async () => {
+ const calls = mockRoutes([]);
+ await expect(pdfmonkeyOperations.updateDocument({ auth, documentId: 'doc-1' })).rejects.toThrow('Nothing to update');
+ expect(calls).toHaveLength(0);
+ });
+});
+
+describe('listDocuments', () => {
+ it('sends page[number], filters and updated_since in Unix seconds', async () => {
+ const calls = mockRoutes([{ method: 'GET', path: '/document_cards', body: { document_cards: [CARD], meta: { current_page: 2, total_pages: 3, next_page: 3 } } }]);
+ const result = await pdfmonkeyOperations.listDocuments({ auth, templateId: 'tpl-1', status: 'success', updatedSince: '2022-01-01T00:00:00Z', page: 2 });
+ expect(calls[0].query).toEqual({ 'page[number]': '2', 'q[document_template_id]': 'tpl-1', 'q[status]': 'success', 'q[updated_since]': '1640995200' });
+ expect(result).toMatchObject({ page: 2, total_pages: 3, has_more: true });
+ });
+});
+
+describe('listTemplates', () => {
+ it('lists every workspace and strips the internal auth token', async () => {
+ const calls = mockRoutes([
+ { method: 'GET', path: '/workspaces', body: { apps: [{ id: 'ws-1' }, { id: 'ws-2' }], meta: { next_page: null } } },
+ { method: 'GET', path: '/document_template_cards', match: (q) => q['q[workspace_id]'] === 'ws-1', body: { document_template_cards: [{ id: 't1', identifier: 'A', auth_token: 'secret' }], meta: { next_page: null } } },
+ { method: 'GET', path: '/document_template_cards', match: (q) => q['q[workspace_id]'] === 'ws-2', body: { document_template_cards: [{ id: 't2', identifier: 'B' }], meta: { next_page: null } } },
+ ]);
+ const result = await pdfmonkeyOperations.listTemplates({ auth });
+ expect(result.templates).toEqual([{ id: 't1', identifier: 'A' }, { id: 't2', identifier: 'B' }]);
+ expect(calls).toHaveLength(3);
+ });
+});
+
+describe('getCurrentUser', () => {
+ it('never returns the account API key', async () => {
+ mockRoutes([{ method: 'GET', path: '/current_user', body: { current_user: { id: 'u1', email: '[email protected]', auth_token: 'secret', available_documents: 20 } } }]);
+ const user = await pdfmonkeyOperations.getCurrentUser({ auth });
+ expect(JSON.stringify(user)).not.toContain('secret');
+ expect(user['available_documents']).toBe(20);
+ });
+});
+
+describe('deleteDocument', () => {
+ it('deletes by encoded ID and maps a 404 to a readable error', async () => {
+ const calls = mockRoutes([{ method: 'DELETE', path: '/documents/doc-1', status: 204 }]);
+ await expect(pdfmonkeyOperations.deleteDocument({ auth, documentId: 'doc-1' })).resolves.toEqual({ success: true, document_id: 'doc-1' });
+ expect(calls[0].method).toBe('DELETE');
+ vi.restoreAllMocks();
+ mockRoutes([{ method: 'DELETE', path: '/documents/doc-2', status: 404, body: { errors: [{ status: '404', title: 'Not Found', detail: 'We could not find it.' }] } }]);
+ const error = await pdfmonkeyOperations.deleteDocument({ auth, documentId: 'doc-2' }).catch((e) => e);
+ expect(error).toBeInstanceOf(PdfmonkeyApiError);
+ expect(error.message).toContain('PDFMonkey API error (404): We could not find it.');
+ });
+
+ it('refuses path traversal in IDs', async () => {
+ await expect(pdfmonkeyOperations.deleteDocument({ auth, documentId: '..' })).rejects.toThrow('Document ID is required');
+ });
+});
+
+describe('downloadDocument', () => {
+ it('downloads without the API key and writes the file', async () => {
+ const calls = mockRoutes([
+ { method: 'GET', path: '/document_cards/doc-1', body: { document_card: CARD } },
+ { method: 'GET', path: 'https://pdfmonkey-store.s3.eu-west-3.amazonaws.com/', body: Readable.from([Buffer.from('%PDF-1.7')]) },
+ ]);
+ const write = vi.fn(async () => 'file-url');
+ const result = await pdfmonkeyOperations.downloadDocument({ auth, documentId: 'doc-1', files: { write } });
+ expect(result).toMatchObject({ file: 'file-url', file_name: 'Invoice.pdf', size: 8, content_type: 'application/pdf' });
+ expect(JSON.stringify(calls[1].headers)).not.toContain('key-123');
+ });
+
+ it('refuses documents that are not generated yet', async () => {
+ mockRoutes([{ method: 'GET', path: '/document_cards/doc-1', body: { document_card: { ...CARD, status: 'pending', download_url: null } } }]);
+ await expect(pdfmonkeyOperations.downloadDocument({ auth, documentId: 'doc-1', files: { write: vi.fn() } })).rejects.toThrow('"pending"');
+ });
+});
+
+describe('documentGenerated trigger', () => {
+ it('polls successful documents updated since the last poll, in seconds', async () => {
+ const calls = mockRoutes([{ method: 'GET', path: '/document_cards', body: { document_cards: [CARD], meta: { next_page: null } } }]);
+ const lastPoll = Date.parse('2026-10-15T11:00:00Z');
+ const store = { get: vi.fn(async () => lastPoll), put: vi.fn(async () => undefined), delete: vi.fn() };
+ const items = await Reflect.apply(documentGeneratedTrigger.run, undefined, [{ auth, store, propsValue: {}, files: {} }]);
+ expect(calls[0].query).toMatchObject({ 'q[status]': 'success', 'q[updated_since]': String(lastPoll / 1000), 'page[number]': '1' });
+ expect(items).toEqual([CARD]);
+ });
+
+ it('reads every page past the dropdown cap so no document is skipped', async () => {
+ const pages = 25;
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ const page = Number(request.queryParams?.['page[number]']);
+ return { status: 200, headers: {}, body: { document_cards: [{ ...CARD, id: `doc-${page}`, updated_at: new Date(Date.parse('2026-10-15T12:00:00Z') + page * 1000).toISOString() }], meta: { next_page: page < pages ? page + 1 : null } } };
+ });
+ const store = { get: vi.fn(async () => Date.parse('2026-10-15T11:00:00Z')), put: vi.fn(async () => undefined), delete: vi.fn() };
+ const items = await Reflect.apply(documentGeneratedTrigger.run, undefined, [{ auth, store, propsValue: {}, files: {} }]);
+ expect(items).toHaveLength(pages);
+ expect(store.put).toHaveBeenCalledWith('lastPoll', Date.parse('2026-10-15T12:00:00Z') + pages * 1000);
+ });
+
+ it('fails without moving the checkpoint when the backlog exceeds the safety cap', async () => {
+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {
+ const page = Number(request.queryParams?.['page[number]']);
+ return { status: 200, headers: {}, body: { document_cards: [{ ...CARD, id: `doc-${page}` }], meta: { next_page: page + 1 } } };
+ });
+ const store = { get: vi.fn(async () => Date.parse('2026-10-15T11:00:00Z')), put: vi.fn(async () => undefined), delete: vi.fn() };
+ await expect(Reflect.apply(documentGeneratedTrigger.run, undefined, [{ auth, store, propsValue: {}, files: {} }])).rejects.toThrow('without moving its checkpoint');
+ expect(store.put).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pieces/community/pdfmonkey/vitest.config.ts b/packages/pieces/community/pdfmonkey/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/pdfmonkey/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'),
+ },
+ },
+})