first commit
Security: Sync from Public / sync-from-public (push) Has been cancelled
Test: Benchmark Nightly / build (push) Has been cancelled
Test: Benchmark Nightly / Notify Cats on failure (push) Has been cancelled
CI: Python / Checks (push) Has been cancelled
Test: Evals Python / Workflow Comparison Python (push) Has been cancelled
Util: Check Docs URLs / check-docs-urls (push) Has been cancelled
Test: Visual Storybook / Cloudflare Pages (push) Has been cancelled
Test: E2E Performance / build-and-test-performance (push) Has been cancelled
Test: Workflows Nightly / Run Workflow Tests (push) Has been cancelled
Util: Cleanup CI Docker Images / Delete stale CI images (push) Has been cancelled
Test: Benchmark Destroy Env / build (push) Has been cancelled
Util: Update Node Popularity / update-popularity (push) Has been cancelled
Test: E2E Coverage Weekly / Coverage Tests (push) Has been cancelled

This commit is contained in:
2026-03-17 16:22:57 +03:30
commit 3d5eaf9445
15349 changed files with 2847338 additions and 0 deletions
@@ -0,0 +1,64 @@
import { ApplicationError, NodeOperationError, WAIT_INDEFINITELY } from 'n8n-workflow';
import type { IExecuteFunctions, IDataObject } from 'n8n-workflow';
export function configureWaitTillDate(
context: IExecuteFunctions,
location: 'options' | 'root' = 'options',
) {
let waitTill = WAIT_INDEFINITELY;
let limitOptions: IDataObject = {};
if (location === 'options') {
limitOptions = context.getNodeParameter('options.limitWaitTime.values', 0, {}) as {
limitType?: string;
resumeAmount?: number;
resumeUnit?: string;
maxDateAndTime?: string;
};
} else {
const limitWaitTime = context.getNodeParameter('limitWaitTime', 0, false);
if (limitWaitTime) {
limitOptions.limitType = context.getNodeParameter('limitType', 0, 'afterTimeInterval');
if (limitOptions.limitType === 'afterTimeInterval') {
limitOptions.resumeAmount = context.getNodeParameter('resumeAmount', 0, 1) as number;
limitOptions.resumeUnit = context.getNodeParameter('resumeUnit', 0, 'hours');
} else {
limitOptions.maxDateAndTime = context.getNodeParameter('maxDateAndTime', 0, '');
}
}
}
if (Object.keys(limitOptions).length) {
try {
if (limitOptions.limitType === 'afterTimeInterval') {
let waitAmount = limitOptions.resumeAmount as number;
if (limitOptions.resumeUnit === 'minutes') {
waitAmount *= 60;
}
if (limitOptions.resumeUnit === 'hours') {
waitAmount *= 60 * 60;
}
if (limitOptions.resumeUnit === 'days') {
waitAmount *= 60 * 60 * 24;
}
waitAmount *= 1000;
waitTill = new Date(new Date().getTime() + waitAmount);
} else {
waitTill = new Date(limitOptions.maxDateAndTime as string);
}
if (isNaN(waitTill.getTime())) {
throw new ApplicationError('Invalid date format');
}
} catch (error) {
throw new NodeOperationError(context.getNode(), 'Could not configure Limit Wait Time', {
description: error.message,
});
}
}
return waitTill;
}
@@ -0,0 +1,115 @@
import type { INodeProperties, IWebhookDescription } from 'n8n-workflow';
export const sendAndWaitWebhooksDescription: IWebhookDescription[] = [
{
name: 'default',
httpMethod: 'GET',
responseMode: 'onReceived',
responseData: '',
path: '={{ $nodeId }}',
restartWebhook: true,
isFullPath: true,
},
{
name: 'default',
httpMethod: 'POST',
responseMode: 'onReceived',
responseData: '',
path: '={{ $nodeId }}',
restartWebhook: true,
isFullPath: true,
},
];
export const limitWaitTimeProperties: INodeProperties[] = [
{
displayName: 'Limit Type',
name: 'limitType',
type: 'options',
default: 'afterTimeInterval',
description:
'Sets the condition for the execution to resume. Can be a specified date or after some time.',
options: [
{
name: 'After Time Interval',
description: 'Waits for a certain amount of time',
value: 'afterTimeInterval',
},
{
name: 'At Specified Time',
description: 'Waits until the set date and time to continue',
value: 'atSpecifiedTime',
},
],
},
{
displayName: 'Amount',
name: 'resumeAmount',
type: 'number',
displayOptions: {
show: {
limitType: ['afterTimeInterval'],
},
},
typeOptions: {
minValue: 0,
numberPrecision: 2,
},
default: 1,
description: 'The time to wait',
},
{
displayName: 'Unit',
name: 'resumeUnit',
type: 'options',
displayOptions: {
show: {
limitType: ['afterTimeInterval'],
},
},
options: [
{
name: 'Minutes',
value: 'minutes',
},
{
name: 'Hours',
value: 'hours',
},
{
name: 'Days',
value: 'days',
},
],
default: 'hours',
description: 'Unit of the interval value',
},
{
displayName: 'Max Date and Time',
name: 'maxDateAndTime',
type: 'dateTime',
displayOptions: {
show: {
limitType: ['atSpecifiedTime'],
},
},
default: '',
description: 'Continue execution after the specified date and time',
},
];
export const limitWaitTimeOption: INodeProperties = {
displayName: 'Limit Wait Time',
name: 'limitWaitTime',
type: 'fixedCollection',
description:
'Whether to limit the time this node should wait for a user response before execution resumes',
default: { values: { limitType: 'afterTimeInterval', resumeAmount: 45, resumeUnit: 'minutes' } },
options: [
{
displayName: 'Values',
name: 'values',
values: limitWaitTimeProperties,
},
],
};
@@ -0,0 +1,194 @@
export const BUTTON_STYLE_SECONDARY =
'display:inline-block; text-decoration:none; background-color:#fff; color:#4a4a4a; padding:12px 24px; font-family: Arial,sans-serif; font-size:14px;font-weight:600; border:1px solid #d1d1d1; border-radius:6px; min-width:120px; margin: 12px 6px 0 6px;';
export const BUTTON_STYLE_PRIMARY =
'display:inline-block; text-decoration:none; background-color:#ff6d5a; color: #fff; padding:12px 24px; font-family: Arial,sans-serif; font-size:14px;font-weight:600; border-radius:6px; min-width:120px; margin: 12px 2px 0 2px;';
export const ACTION_RECORDED_PAGE = `
<html lang='en'>
<head>
<meta charset='UTF-8' />
<meta name='viewport' content='width=device-width, initial-scale=1.0' />
<link rel='icon' type='image/png' href='https://n8n.io/favicon.ico' />
<link
href='https://fonts.googleapis.com/css?family=Open+Sans'
rel='stylesheet'
type='text/css'
/>
<title>Action recorded</title>
<style>
*, ::after, ::before { box-sizing: border-box; margin: 0; padding: 0; } body { font-family:
Open Sans, sans-serif; font-weight: 400; font-size: 12px; display: flex; flex-direction:
column; justify-content: start; background-color: #FBFCFE; } .container { margin: auto;
text-align: center; padding-top: 24px; width: 448px; } .card { padding: 24px;
background-color: white; border: 1px solid #DBDFE7; border-radius: 8px; box-shadow: 0px 4px
16px 0px #634DFF0F; margin-bottom: 16px; } .n8n-link a { color: #7E8186; font-weight: 600;
font-size: 12px; text-decoration: none; } .n8n-link svg { display: inline-block;
vertical-align: middle; } .header h1 { color: #525356; font-size: 20px; font-weight: 400;
padding-bottom: 8px; } .header p { color: #7E8186; font-size: 14px; font-weight: 400; }
</style>
</head>
<body>
<div class='container'>
<section>
<div class='card'>
<div class='header'>
<h1>Got it, thanks</h1>
<p>This page can be closed now</p>
</div>
</div>
<div class='n8n-link'>
<a
href='https://n8n.io/?utm_source=n8n-internal&amp;utm_medium=send-and-wait'
target='_blank'
>
Automated with
<svg
width='73'
height='20'
viewBox='0 0 73 20'
fill='none'
xmlns='http://www.w3.org/2000/svg'
>
<path
fill-rule='evenodd'
clip-rule='evenodd'
d='M40.2373 4C40.2373 6.20915 38.4464 8 36.2373 8C34.3735 8 32.8074 6.72525 32.3633 5H26.7787C25.801 5 24.9666 5.70685 24.8059 6.6712L24.6415 7.6576C24.4854 8.59415 24.0116 9.40925 23.3417 10C24.0116 10.5907 24.4854 11.4058 24.6415 12.3424L24.8059 13.3288C24.9666 14.2931 25.801 15 26.7787 15H28.3633C28.8074 13.2747 30.3735 12 32.2373 12C34.4464 12 36.2373 13.7908 36.2373 16C36.2373 18.2092 34.4464 20 32.2373 20C30.3735 20 28.8074 18.7253 28.3633 17H26.7787C24.8233 17 23.1546 15.5864 22.8331 13.6576L22.6687 12.6712C22.508 11.7069 21.6736 11 20.6959 11H19.0645C18.5652 12.64 17.0406 13.8334 15.2373 13.8334C13.434 13.8334 11.9094 12.64 11.4101 11H9.06449C8.56519 12.64 7.04059 13.8334 5.2373 13.8334C3.02817 13.8334 1.2373 12.0424 1.2373 9.83335C1.2373 7.6242 3.02817 5.83335 5.2373 5.83335C7.16069 5.83335 8.76699 7.19085 9.15039 9H11.3242C11.7076 7.19085 13.3139 5.83335 15.2373 5.83335C17.1607 5.83335 18.767 7.19085 19.1504 9H20.6959C21.6736 9 22.508 8.29315 22.6687 7.3288L22.8331 6.3424C23.1546 4.41365 24.8233 3 26.7787 3H32.3633C32.8074 1.27478 34.3735 0 36.2373 0C38.4464 0 40.2373 1.79086 40.2373 4ZM38.2373 4C38.2373 5.10455 37.3419 6 36.2373 6C35.1327 6 34.2373 5.10455 34.2373 4C34.2373 2.89543 35.1327 2 36.2373 2C37.3419 2 38.2373 2.89543 38.2373 4ZM5.2373 11.8334C6.34189 11.8334 7.23729 10.9379 7.23729 9.83335C7.23729 8.72875 6.34189 7.83335 5.2373 7.83335C4.13273 7.83335 3.2373 8.72875 3.2373 9.83335C3.2373 10.9379 4.13273 11.8334 5.2373 11.8334ZM15.2373 11.8334C16.3419 11.8334 17.2373 10.9379 17.2373 9.83335C17.2373 8.72875 16.3419 7.83335 15.2373 7.83335C14.1327 7.83335 13.2373 8.72875 13.2373 9.83335C13.2373 10.9379 14.1327 11.8334 15.2373 11.8334ZM32.2373 18C33.3419 18 34.2373 17.1045 34.2373 16C34.2373 14.8954 33.3419 14 32.2373 14C31.1327 14 30.2373 14.8954 30.2373 16C30.2373 17.1045 31.1327 18 32.2373 18Z'
fill='#EA4B71'
></path>
<path
d='M44.2393 15.0007H46.3277V10.5791C46.3277 9.12704 47.2088 8.49074 48.204 8.49074C49.183 8.49074 49.9498 9.14334 49.9498 10.4812V15.0007H52.038V10.057C52.038 7.91969 50.798 6.67969 48.8567 6.67969C47.633 6.67969 46.9477 7.16914 46.4582 7.80544H46.3277L46.1482 6.84284H44.2393V15.0007Z'
fill='#101330'
></path>
<path
d='M60.0318 9.50205V9.40415C60.7498 9.0452 61.4678 8.4252 61.4678 7.20155C61.4678 5.43945 60.0153 4.37891 58.0088 4.37891C55.9528 4.37891 54.4843 5.5047 54.4843 7.23415C54.4843 8.4089 55.1698 9.0452 55.9203 9.40415V9.50205C55.0883 9.79575 54.0928 10.6768 54.0928 12.1452C54.0928 13.9237 55.5613 15.1637 57.9923 15.1637C60.4233 15.1637 61.8428 13.9237 61.8428 12.1452C61.8428 10.6768 60.8638 9.81205 60.0318 9.50205ZM57.9923 5.87995C58.8083 5.87995 59.4118 6.40205 59.4118 7.2831C59.4118 8.16415 58.7918 8.6863 57.9923 8.6863C57.1928 8.6863 56.5238 8.16415 56.5238 7.2831C56.5238 6.38575 57.1603 5.87995 57.9923 5.87995ZM57.9923 13.5974C57.0458 13.5974 56.2793 12.9937 56.2793 11.9658C56.2793 11.0358 56.9153 10.3342 57.9758 10.3342C59.0203 10.3342 59.6568 11.0195 59.6568 11.9984C59.6568 12.9937 58.9223 13.5974 57.9923 13.5974Z'
fill='#101330'
></path>
<path
d='M63.9639 15.0007H66.0524V10.5791C66.0524 9.12704 66.9334 8.49074 67.9289 8.49074C68.9079 8.49074 69.6744 9.14334 69.6744 10.4812V15.0007H71.7629V10.057C71.7629 7.91969 70.5229 6.67969 68.5814 6.67969C67.3579 6.67969 66.6724 7.16914 66.1829 7.80544H66.0524L65.8729 6.84284H63.9639V15.0007Z'
fill='#101330'
></path>
</svg>
</a>
</div>
</section>
</div>
</body>
</html>`;
export function createEmailBodyWithN8nAttribution(
message: string,
buttons: string,
instanceId?: string,
) {
const utm_campaign = instanceId ? `&utm_campaign=${instanceId}` : '';
const n8nWebsiteLink = `https://n8n.io/?utm_source=n8n-internal&utm_medium=send-and-wait${utm_campaign}`;
return `
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My form</title>
</head>
<body
style="font-family: Arial, sans-serif; font-size: 12px; background-color: #fbfcfe; margin: 0; padding: 0;">
<table width="100%" cellpadding="0" cellspacing="0"
style="background-color:#fbfcfe; border: 1px solid #dbdfe7; border-radius: 8px;">
<tr>
<td align="center" style="padding: 24px 0;">
<table width="448" cellpadding="0" cellspacing="0" border="0"
style="width: 100%; max-width: 448px; background-color: #ffffff; border: 1px solid #dbdfe7; border-radius: 8px; padding: 24px; box-shadow: 0px 4px 16px rgba(99, 77, 255, 0.06);">
<tr>
<td
style="text-align: center; padding-top: 8px; font-family: Arial, sans-serif; font-size: 14px; color: #7e8186;">
<p style="white-space: pre-line;">${message}</p>
</td>
</tr>
<tr>
<td align="center" style="padding-top: 12px;">
${buttons}
</td>
</tr>
</table>
<!-- Divider -->
<table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom: 24px;">
<tr>
<td style="border-top: 0px solid #dbdfe7;"></td>
</tr>
</table>
<!-- Footer -->
<table width="100%" cellpadding="0" cellspacing="0" border="0"
style="text-align: center; color: #7e8186; font-family: Arial, sans-serif; font-size: 12px;">
<tr>
<td>
<a href=${n8nWebsiteLink}
target="_blank" style="color: #7e8186; text-decoration: none;">Automated with
n8n</a>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
`;
}
export function createEmailBodyWithoutN8nAttribution(message: string, buttons: string) {
return `
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My form</title>
</head>
<body
style="font-family: Arial, sans-serif; font-size: 12px; background-color: #fbfcfe; margin: 0; padding: 0;">
<table width="100%" cellpadding="0" cellspacing="0"
style="background-color:#fbfcfe; border: 1px solid #dbdfe7; border-radius: 8px;">
<tr>
<td align="center" style="padding: 24px 0;">
<table width="448" cellpadding="0" cellspacing="0" border="0"
style="width: 100%; max-width: 448px; background-color: #ffffff; border: 1px solid #dbdfe7; border-radius: 8px; padding: 24px; box-shadow: 0px 4px 16px rgba(99, 77, 255, 0.06);">
<tr>
<td
style="text-align: center; padding-top: 8px; font-family: Arial, sans-serif; font-size: 14px; color: #7e8186;">
<p style="white-space: pre-line;">${message}</p>
</td>
</tr>
<tr>
<td align="center" style="padding-top: 12px;">
${buttons}
</td>
</tr>
</table>
<!-- Divider -->
<table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom: 24px;">
<tr>
<td style="border-top: 0px solid #dbdfe7;"></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
`;
}
@@ -0,0 +1,16 @@
import type { IDataObject } from 'n8n-workflow';
export interface IEmail {
from?: string;
to?: string;
cc?: string;
bcc?: string;
replyTo?: string;
inReplyTo?: string;
reference?: string;
references?: string;
subject: string;
body: string;
htmlBody?: string;
attachments?: IDataObject[];
}
@@ -0,0 +1,704 @@
import { type MockProxy, mock } from 'jest-mock-extended';
import type {
IExecuteFunctions,
INodeProperties,
IWebhookFunctions,
IWorkflowSettings,
} from 'n8n-workflow';
import { NodeOperationError, WAIT_INDEFINITELY } from 'n8n-workflow';
import { configureWaitTillDate } from '../configureWaitTillDate.util';
import {
getSendAndWaitProperties,
getSendAndWaitConfig,
createEmail,
sendAndWaitWebhook,
} from '../utils';
describe('Send and Wait utils tests', () => {
let mockExecuteFunctions: MockProxy<IExecuteFunctions>;
let mockWebhookFunctions: MockProxy<IWebhookFunctions>;
beforeEach(() => {
mockExecuteFunctions = mock<IExecuteFunctions>();
mockWebhookFunctions = mock<IWebhookFunctions>();
mockWebhookFunctions.getWorkflowSettings.mockReturnValue(mock<IWorkflowSettings>({}));
});
describe('getSendAndWaitProperties', () => {
it('should return properties with correct display options', () => {
const targetProperties: INodeProperties[] = [
{
displayName: 'Test Property',
name: 'testProperty',
type: 'string',
default: '',
},
];
const extraOptions: INodeProperties[] = [
{
displayName: 'Extra Property',
name: 'extraProperty',
type: 'string',
default: '',
},
];
const result = getSendAndWaitProperties(targetProperties, undefined, undefined, {
extraOptions,
});
expect(result).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: 'options',
options: expect.arrayContaining([
expect.objectContaining({
name: 'extraProperty',
}),
]),
}),
]),
);
});
it('should include extra options when provided', () => {
const targetProperties: INodeProperties[] = [
{
displayName: 'Test Property',
name: 'testProperty',
type: 'string',
default: '',
},
];
const extraOptions: INodeProperties[] = [
{
displayName: 'Extra Property',
name: 'extraProperty',
type: 'string',
default: '',
},
];
const result = getSendAndWaitProperties(targetProperties, undefined, undefined, {
extraOptions,
});
expect(result).toEqual(
expect.arrayContaining([
expect.objectContaining({
displayOptions: {
show: {
resource: ['message'],
operation: ['sendAndWait'],
},
},
}),
]),
);
});
});
describe('getSendAndWaitConfig', () => {
it('should return correct config for single approval', () => {
mockExecuteFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
message: 'Test message',
subject: 'Test subject',
'approvalOptions.values': {
approvalType: 'single',
approveLabel: 'Approve',
buttonApprovalStyle: 'primary',
},
};
return params[parameterName];
});
mockExecuteFunctions.getSignedResumeUrl.mockReturnValue(
'http://localhost/waiting-webhook/nodeID?approved=true&signature=abc',
);
const config = getSendAndWaitConfig(mockExecuteFunctions);
expect(config).toEqual({
appendAttribution: undefined,
title: 'Test subject',
message: 'Test message',
options: [
{
label: 'Approve',
style: 'primary',
url: 'http://localhost/waiting-webhook/nodeID?approved=true&signature=abc',
},
],
});
});
it('should return correct config for double approval', () => {
mockExecuteFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
message: 'Test message',
subject: 'Test subject',
'approvalOptions.values': {
approvalType: 'double',
approveLabel: 'Approve',
buttonApprovalStyle: 'primary',
disapproveLabel: 'Reject',
buttonDisapprovalStyle: 'secondary',
},
};
return params[parameterName];
});
mockExecuteFunctions.getSignedResumeUrl.mockReturnValueOnce(
'http://localhost/waiting-webhook/nodeID?approved=true&signature=abc',
);
mockExecuteFunctions.getSignedResumeUrl.mockReturnValueOnce(
'http://localhost/waiting-webhook/nodeID?approved=false&signature=abc',
);
const config = getSendAndWaitConfig(mockExecuteFunctions);
expect(config.options).toHaveLength(2);
expect(config.options).toEqual(
expect.arrayContaining([
{
label: 'Reject',
style: 'secondary',
url: 'http://localhost/waiting-webhook/nodeID?approved=false&signature=abc',
},
{
label: 'Approve',
style: 'primary',
url: 'http://localhost/waiting-webhook/nodeID?approved=true&signature=abc',
},
]),
);
});
});
describe('createEmail', () => {
beforeEach(() => {
mockExecuteFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
sendTo: 'test@example.com',
message: 'Test message',
subject: 'Test subject',
'approvalOptions.values': {
approvalType: 'single',
approveLabel: 'Approve',
buttonApprovalStyle: 'primary',
},
};
return params[parameterName];
});
mockExecuteFunctions.getSignedResumeUrl.mockReturnValue('http://localhost/testNodeId');
});
it('should create a valid email object', () => {
const email = createEmail(mockExecuteFunctions);
expect(email).toEqual({
to: 'test@example.com',
subject: 'Test subject',
body: '',
htmlBody: expect.stringContaining('Test message'),
});
});
it('should throw NodeOperationError for invalid email address', () => {
mockExecuteFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
sendTo: 'invalid@@email.com',
message: 'Test message',
subject: 'Test subject',
'approvalOptions.values': {
approvalType: 'single',
},
};
return params[parameterName];
});
expect(() => createEmail(mockExecuteFunctions)).toThrow(NodeOperationError);
});
});
describe('sendAndWaitWebhook', () => {
it('should handle approved webhook', async () => {
mockWebhookFunctions.getRequestObject.mockReturnValue({
query: { approved: 'true' },
} as any);
const result = await sendAndWaitWebhook.call(mockWebhookFunctions);
expect(result).toEqual({
webhookResponse: expect.any(String),
workflowData: [[{ json: { data: { approved: true } } }]],
});
});
it('should handle disapproved webhook', async () => {
mockWebhookFunctions.getRequestObject.mockReturnValue({
query: { approved: 'false' },
} as any);
const result = await sendAndWaitWebhook.call(mockWebhookFunctions);
expect(result).toEqual({
webhookResponse: expect.any(String),
workflowData: [[{ json: { data: { approved: false } } }]],
});
});
it('should handle freeText GET webhook', async () => {
const mockRender = jest.fn();
const mockSetHeader = jest.fn();
mockWebhookFunctions.getRequestObject.mockReturnValue({
method: 'GET',
} as any);
mockWebhookFunctions.getResponseObject.mockReturnValue({
render: mockRender,
setHeader: mockSetHeader,
} as any);
mockWebhookFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
responseType: 'freeText',
message: 'Test message',
options: {},
};
return params[parameterName];
});
const result = await sendAndWaitWebhook.call(mockWebhookFunctions);
expect(result).toEqual({
noWebhookResponse: true,
});
expect(mockSetHeader).toHaveBeenCalledWith(
'Content-Security-Policy',
'sandbox allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts allow-top-navigation allow-top-navigation-by-user-activation allow-top-navigation-to-custom-protocols',
);
expect(mockRender).toHaveBeenCalledWith('form-trigger', {
testRun: false,
formTitle: '',
formDescription: 'Test message',
formDescriptionMetadata: 'Test message',
formSubmittedHeader: 'Got it, thanks',
formSubmittedText: 'This page can be closed now',
n8nWebsiteLink: 'https://n8n.io/?utm_source=n8n-internal&utm_medium=form-trigger',
formFields: [
{
id: 'field-0',
errorId: 'error-field-0',
label: 'Response',
inputRequired: 'form-required',
defaultValue: '',
isTextarea: true,
},
],
appendAttribution: true,
buttonLabel: 'Submit',
});
});
it('should handle freeText POST webhook', async () => {
mockWebhookFunctions.getRequestObject.mockReturnValue({
method: 'POST',
} as any);
mockWebhookFunctions.getBodyData.mockReturnValue({
data: {
'field-0': 'test value',
},
} as any);
mockWebhookFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
responseType: 'freeText',
};
return params[parameterName];
});
const result = await sendAndWaitWebhook.call(mockWebhookFunctions);
expect(result.workflowData).toEqual([[{ json: { data: { text: 'test value' } } }]]);
});
it('should handle customForm GET webhook', async () => {
const mockRender = jest.fn();
const mockSetHeader = jest.fn();
mockWebhookFunctions.getRequestObject.mockReturnValue({
method: 'GET',
} as any);
mockWebhookFunctions.getResponseObject.mockReturnValue({
render: mockRender,
setHeader: mockSetHeader,
} as any);
mockWebhookFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
responseType: 'customForm',
message: 'Test message',
defineForm: 'fields',
'formFields.values': [{ label: 'Field 1', fieldType: 'text', requiredField: true }],
options: {
responseFormTitle: 'Test title',
responseFormDescription: 'Test description',
responseFormButtonLabel: 'Test button',
responseFormCustomCss: 'body { background-color: red; }',
},
};
return params[parameterName];
});
const result = await sendAndWaitWebhook.call(mockWebhookFunctions);
expect(result).toEqual({
noWebhookResponse: true,
});
expect(mockSetHeader).toHaveBeenCalledWith(
'Content-Security-Policy',
'sandbox allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts allow-top-navigation allow-top-navigation-by-user-activation allow-top-navigation-to-custom-protocols',
);
expect(mockRender).toHaveBeenCalledWith('form-trigger', {
testRun: false,
formTitle: 'Test title',
formDescription: 'Test description',
formDescriptionMetadata: 'Test description',
formSubmittedHeader: 'Got it, thanks',
formSubmittedText: 'This page can be closed now',
n8nWebsiteLink: 'https://n8n.io/?utm_source=n8n-internal&utm_medium=form-trigger',
formFields: [
{
id: 'field-0',
errorId: 'error-field-0',
inputRequired: 'form-required',
defaultValue: '',
isInput: true,
type: 'text',
},
],
appendAttribution: true,
buttonLabel: 'Test button',
dangerousCustomCss: 'body { background-color: red; }',
});
});
it('should resolve expressions in HTML fields for customForm GET webhook', async () => {
const mockRender = jest.fn();
const mockSetHeader = jest.fn();
mockWebhookFunctions.getRequestObject.mockReturnValue({
method: 'GET',
} as any);
mockWebhookFunctions.getResponseObject.mockReturnValue({
render: mockRender,
setHeader: mockSetHeader,
} as any);
// Mock evaluateExpression to resolve the expression
mockWebhookFunctions.evaluateExpression.mockImplementation((expression) => {
if (expression === '{{ $json.videoUrl }}') {
return 'https://example.com/video.mp4';
}
return expression;
});
mockWebhookFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
responseType: 'customForm',
message: 'Test message',
defineForm: 'fields',
'formFields.values': [
{
fieldLabel: 'Custom HTML',
fieldType: 'html',
// Use <source> tag inside <video> since sanitizeHtml allows src on source, not video
html: '<video controls><source src="{{ $json.videoUrl }}" type="video/mp4" /></video>',
},
],
options: {},
};
return params[parameterName];
});
await sendAndWaitWebhook.call(mockWebhookFunctions);
expect(mockRender).toHaveBeenCalledWith(
'form-trigger',
expect.objectContaining({
formFields: expect.arrayContaining([
expect.objectContaining({
html: '<video controls><source src="https://example.com/video.mp4" type="video/mp4"></source></video>',
}),
]),
}),
);
});
it('should handle customForm POST webhook', async () => {
mockWebhookFunctions.getRequestObject.mockReturnValue({
method: 'POST',
contentType: 'multipart/form-data',
} as any);
mockWebhookFunctions.getNode.mockReturnValue({} as any);
mockWebhookFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
responseType: 'customForm',
defineForm: 'fields',
'formFields.values': [
{
fieldLabel: 'test 1',
fieldType: 'text',
},
],
};
return params[parameterName];
});
mockWebhookFunctions.getBodyData.mockReturnValue({
data: {
'field-0': 'test value',
},
} as any);
const result = await sendAndWaitWebhook.call(mockWebhookFunctions);
expect(result.workflowData).toEqual([[{ json: { data: { 'test 1': 'test value' } } }]]);
});
it('should return noWebhookResponse if method GET and user-agent is bot', async () => {
mockWebhookFunctions.getRequestObject.mockReturnValue({
method: 'GET',
headers: {
'user-agent': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
},
query: { approved: 'false' },
} as any);
const send = jest.fn();
mockWebhookFunctions.getResponseObject.mockReturnValue({
send,
} as any);
mockWebhookFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
responseType: 'approval',
};
return params[parameterName];
});
const result = await sendAndWaitWebhook.call(mockWebhookFunctions);
expect(send).toHaveBeenCalledWith('');
expect(result).toEqual({ noWebhookResponse: true });
});
it('should return noWebhookResponse if user-agent is Microsoft Teams link preview service (SkypeSpaces)', async () => {
mockWebhookFunctions.getRequestObject.mockReturnValue({
method: 'GET',
headers: {
'user-agent': 'SkypeSpaces/1.0a$*+',
},
query: { approved: 'true' },
} as any);
const send = jest.fn();
mockWebhookFunctions.getResponseObject.mockReturnValue({
send,
} as any);
mockWebhookFunctions.getNodeParameter.mockImplementation((parameterName: string) => {
const params: { [key: string]: any } = {
responseType: 'approval',
};
return params[parameterName];
});
const result = await sendAndWaitWebhook.call(mockWebhookFunctions);
expect(send).toHaveBeenCalledWith('');
expect(result).toEqual({ noWebhookResponse: true });
});
});
});
describe('configureWaitTillDate', () => {
let mockExecuteFunctions: MockProxy<IExecuteFunctions>;
beforeEach(() => {
mockExecuteFunctions = mock<IExecuteFunctions>();
});
afterEach(() => {
jest.clearAllMocks();
});
it('should return WAIT_INDEFINITELY if limitWaitTime is empty', () => {
mockExecuteFunctions.getNodeParameter.mockReturnValueOnce({});
const result = configureWaitTillDate(mockExecuteFunctions);
expect(result).toBe(WAIT_INDEFINITELY);
});
it('should calculate future date correctly for afterTimeInterval with minutes', () => {
const resumeAmount = 5;
const resumeUnit = 'minutes';
mockExecuteFunctions.getNodeParameter.mockReturnValueOnce({
limitType: 'afterTimeInterval',
resumeAmount,
resumeUnit,
});
const result = configureWaitTillDate(mockExecuteFunctions);
const expectedDate = new Date(new Date().getTime() + 5 * 60 * 1000);
expect(result.getTime()).toBeCloseTo(expectedDate.getTime(), -2); // Allowing 100ms difference
});
it('should calculate future date correctly for afterTimeInterval with hours', () => {
const resumeAmount = 2;
const resumeUnit = 'hours';
mockExecuteFunctions.getNodeParameter.mockReturnValueOnce({
limitType: 'afterTimeInterval',
resumeAmount,
resumeUnit,
});
const result = configureWaitTillDate(mockExecuteFunctions);
const expectedDate = new Date(new Date().getTime() + 2 * 60 * 60 * 1000);
expect(result.getTime()).toBeCloseTo(expectedDate.getTime(), -2);
});
it('should calculate future date correctly for afterTimeInterval with days', () => {
const resumeAmount = 1;
const resumeUnit = 'days';
mockExecuteFunctions.getNodeParameter.mockReturnValueOnce({
limitType: 'afterTimeInterval',
resumeAmount,
resumeUnit,
});
const result = configureWaitTillDate(mockExecuteFunctions);
const expectedDate = new Date(new Date().getTime() + 1 * 24 * 60 * 60 * 1000);
expect(result.getTime()).toBeCloseTo(expectedDate.getTime(), -2);
});
it('should return the specified maxDateAndTime for maxDateAndTime limitType', () => {
const maxDateAndTime = '2023-12-31T23:59:59Z';
mockExecuteFunctions.getNodeParameter.mockReturnValueOnce({
limitType: 'maxDateAndTime',
maxDateAndTime,
});
const result = configureWaitTillDate(mockExecuteFunctions);
expect(result).toEqual(new Date(maxDateAndTime));
});
it('should throw NodeOperationError for invalid maxDateAndTime format', () => {
const invalidMaxDateAndTime = 'invalid-date';
mockExecuteFunctions.getNodeParameter.mockReturnValue({
limitType: 'maxDateAndTime',
maxDateAndTime: invalidMaxDateAndTime,
});
expect(() => configureWaitTillDate(mockExecuteFunctions)).toThrow(NodeOperationError);
expect(() => configureWaitTillDate(mockExecuteFunctions)).toThrow(
'Could not configure Limit Wait Time',
);
});
it('should throw NodeOperationError for invalid resumeAmount or resumeUnit', () => {
mockExecuteFunctions.getNodeParameter.mockReturnValue({
limitType: 'afterTimeInterval',
resumeAmount: 'invalid',
resumeUnit: 'minutes',
});
expect(() => configureWaitTillDate(mockExecuteFunctions)).toThrow(NodeOperationError);
expect(() => configureWaitTillDate(mockExecuteFunctions)).toThrow(
'Could not configure Limit Wait Time',
);
});
it('should return WAIT_INDEFINITELY when limitWaitTime is false', () => {
mockExecuteFunctions.getNodeParameter.mockReturnValueOnce(false);
const result = configureWaitTillDate(mockExecuteFunctions, 'root');
expect(result).toBe(WAIT_INDEFINITELY);
});
it('should calculate minutes correctly in root location', () => {
mockExecuteFunctions.getNodeParameter
.mockReturnValueOnce(true) // limitWaitTime
.mockReturnValueOnce('afterTimeInterval') // limitType
.mockReturnValueOnce(15) // resumeAmount
.mockReturnValueOnce('minutes'); // resumeUnit
const result = configureWaitTillDate(mockExecuteFunctions, 'root');
const expectedDate = new Date(new Date().getTime() + 15 * 60 * 1000);
expect(result.getTime()).toBeCloseTo(expectedDate.getTime(), -2);
});
it('should calculate hours correctly in root location', () => {
mockExecuteFunctions.getNodeParameter
.mockReturnValueOnce(true)
.mockReturnValueOnce('afterTimeInterval')
.mockReturnValueOnce(3)
.mockReturnValueOnce('hours');
const result = configureWaitTillDate(mockExecuteFunctions, 'root');
const expectedDate = new Date(new Date().getTime() + 3 * 60 * 60 * 1000);
expect(result.getTime()).toBeCloseTo(expectedDate.getTime(), -2);
});
it('should calculate days correctly in root location', () => {
mockExecuteFunctions.getNodeParameter
.mockReturnValueOnce(true)
.mockReturnValueOnce('afterTimeInterval')
.mockReturnValueOnce(5)
.mockReturnValueOnce('days');
const result = configureWaitTillDate(mockExecuteFunctions, 'root');
const expectedDate = new Date(new Date().getTime() + 5 * 24 * 60 * 60 * 1000);
expect(result.getTime()).toBeCloseTo(expectedDate.getTime(), -2);
});
it('should handle maxDateAndTime in root location', () => {
const maxDateAndTime = '2024-12-31T23:59:59Z';
mockExecuteFunctions.getNodeParameter
.mockReturnValueOnce(true)
.mockReturnValueOnce('maxDateAndTime')
.mockReturnValueOnce(maxDateAndTime);
const result = configureWaitTillDate(mockExecuteFunctions, 'root');
expect(result).toEqual(new Date(maxDateAndTime));
});
it('should throw error for invalid date in root location', () => {
mockExecuteFunctions.getNodeParameter
.mockReturnValueOnce(true)
.mockReturnValueOnce('maxDateAndTime')
.mockReturnValueOnce('not-a-valid-date');
expect(() => configureWaitTillDate(mockExecuteFunctions, 'root')).toThrow(NodeOperationError);
});
it('should throw error for invalid resumeAmount in root location', () => {
mockExecuteFunctions.getNodeParameter
.mockReturnValueOnce(true)
.mockReturnValueOnce('afterTimeInterval')
.mockReturnValueOnce('not-a-number')
.mockReturnValueOnce('minutes');
expect(() => configureWaitTillDate(mockExecuteFunctions, 'root')).toThrow(NodeOperationError);
});
});
@@ -0,0 +1,579 @@
import isbot from 'isbot';
import { getWebhookSandboxCSP } from 'n8n-core';
import type {
FormFieldsParameter,
IDataObject,
IExecuteFunctions,
INodeProperties,
IWebhookFunctions,
} from 'n8n-workflow';
import { NodeOperationError, SEND_AND_WAIT_OPERATION, updateDisplayOptions } from 'n8n-workflow';
import { cssVariables } from '../../nodes/Form/cssVariables';
import { formFieldsProperties } from '../../nodes/Form/Form.node';
import {
parseFormFields,
prepareFormData,
prepareFormFields,
prepareFormReturnItem,
} from '../../nodes/Form/utils/utils';
import { escapeHtml } from '../utilities';
import { limitWaitTimeOption } from './descriptions';
import {
ACTION_RECORDED_PAGE,
BUTTON_STYLE_PRIMARY,
BUTTON_STYLE_SECONDARY,
createEmailBodyWithN8nAttribution,
createEmailBodyWithoutN8nAttribution,
} from './email-templates';
import type { IEmail } from './interfaces';
export type SendAndWaitConfig = {
title: string;
message: string;
options: Array<{ label: string; url: string; style: string }>;
appendAttribution?: boolean;
};
type FormResponseTypeOptions = {
messageButtonLabel?: string;
responseFormTitle?: string;
responseFormDescription?: string;
responseFormButtonLabel?: string;
responseFormCustomCss?: string;
};
const INPUT_FIELD_IDENTIFIER = 'field-0';
const appendAttributionOption: INodeProperties = {
displayName: 'Append n8n Attribution',
name: 'appendAttribution',
type: 'boolean',
default: true,
description:
'Whether to include the phrase "This message was sent automatically with n8n" to the end of the message',
};
// Operation Properties ----------------------------------------------------------
export function getSendAndWaitProperties(
targetProperties: INodeProperties[],
resource: string | null = 'message',
additionalProperties: INodeProperties[] = [],
options?: {
noButtonStyle?: boolean;
defaultApproveLabel?: string;
defaultDisapproveLabel?: string;
extraOptions?: INodeProperties[];
},
): INodeProperties[] {
const buttonStyle: INodeProperties = {
displayName: 'Button Style',
name: 'buttonStyle',
type: 'options',
default: 'primary',
options: [
{
name: 'Primary',
value: 'primary',
},
{
name: 'Secondary',
value: 'secondary',
},
],
};
const approvalOptionsValues = [
{
displayName: 'Type of Approval',
name: 'approvalType',
type: 'options',
placeholder: 'Add option',
default: 'single',
options: [
{
name: 'Approve Only',
value: 'single',
},
{
name: 'Approve and Disapprove',
value: 'double',
},
],
},
{
displayName: 'Approve Button Label',
name: 'approveLabel',
type: 'string',
default: options?.defaultApproveLabel || 'Approve',
displayOptions: {
show: {
approvalType: ['single', 'double'],
},
},
},
...[
options?.noButtonStyle
? ({} as INodeProperties)
: {
...buttonStyle,
displayName: 'Approve Button Style',
name: 'buttonApprovalStyle',
displayOptions: {
show: {
approvalType: ['single', 'double'],
},
},
},
],
{
displayName: 'Disapprove Button Label',
name: 'disapproveLabel',
type: 'string',
default: options?.defaultDisapproveLabel || 'Decline',
displayOptions: {
show: {
approvalType: ['double'],
},
},
},
...[
options?.noButtonStyle
? ({} as INodeProperties)
: {
...buttonStyle,
displayName: 'Disapprove Button Style',
name: 'buttonDisapprovalStyle',
default: 'secondary',
displayOptions: {
show: {
approvalType: ['double'],
},
},
},
],
].filter((p) => Object.keys(p).length) as INodeProperties[];
const sendAndWait: INodeProperties[] = [
...targetProperties,
{
displayName: 'Subject',
name: 'subject',
type: 'string',
default: '',
required: true,
placeholder: 'e.g. Approval required',
},
{
displayName: 'Message',
name: 'message',
type: 'string',
default: '',
required: true,
typeOptions: {
rows: 4,
},
},
{
displayName: 'Response Type',
name: 'responseType',
type: 'options',
default: 'approval',
options: [
{
name: 'Approval',
value: 'approval',
description: 'User can approve/disapprove from within the message',
},
{
name: 'Free Text',
value: 'freeText',
description: 'User can submit a response via a form',
},
{
name: 'Custom Form',
value: 'customForm',
description: 'User can submit a response via a custom form',
},
],
},
...updateDisplayOptions(
{
show: {
responseType: ['customForm'],
},
},
formFieldsProperties,
),
{
displayName: 'Approval Options',
name: 'approvalOptions',
type: 'fixedCollection',
placeholder: 'Add option',
default: {},
options: [
{
displayName: 'Values',
name: 'values',
values: approvalOptionsValues,
},
],
displayOptions: {
show: {
responseType: ['approval'],
},
},
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add option',
default: {},
options: [limitWaitTimeOption, appendAttributionOption, ...(options?.extraOptions ?? [])],
displayOptions: {
show: {
responseType: ['approval'],
},
},
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add option',
default: {},
options: [
{
displayName: 'Message Button Label',
name: 'messageButtonLabel',
type: 'string',
default: 'Respond',
},
{
displayName: 'Response Form Title',
name: 'responseFormTitle',
description: 'Title of the form that the user can access to provide their response',
type: 'string',
default: '',
},
{
displayName: 'Response Form Description',
name: 'responseFormDescription',
description: 'Description of the form that the user can access to provide their response',
type: 'string',
default: '',
},
{
displayName: 'Response Form Button Label',
name: 'responseFormButtonLabel',
type: 'string',
default: 'Submit',
},
{
displayName: 'Response Form Custom Styling',
name: 'responseFormCustomCss',
type: 'string',
typeOptions: {
rows: 10,
editor: 'cssEditor',
},
default: cssVariables.trim(),
description: 'Override default styling of the response form with CSS',
},
limitWaitTimeOption,
appendAttributionOption,
...(options?.extraOptions ?? []),
],
displayOptions: {
show: {
responseType: ['freeText', 'customForm'],
},
},
},
...additionalProperties,
];
return updateDisplayOptions(
{
show: {
...(resource ? { resource: [resource] } : {}),
operation: [SEND_AND_WAIT_OPERATION],
},
},
sendAndWait,
);
}
// Webhook Function --------------------------------------------------------------
const getFormResponseCustomizations = (context: IWebhookFunctions) => {
const message = context.getNodeParameter('message', '') as string;
const options = context.getNodeParameter('options', {}) as FormResponseTypeOptions;
let formTitle = '';
if (options.responseFormTitle) {
formTitle = options.responseFormTitle;
}
let formDescription = message;
if (options.responseFormDescription) {
formDescription = options.responseFormDescription;
}
formDescription = formDescription.replace(/\\n/g, '\n').replace(/<br>/g, '\n');
let buttonLabel = 'Submit';
if (options.responseFormButtonLabel) {
buttonLabel = options.responseFormButtonLabel;
}
return {
formTitle,
formDescription,
buttonLabel,
customCss: options.responseFormCustomCss,
};
};
export async function sendAndWaitWebhook(this: IWebhookFunctions) {
const method = this.getRequestObject().method;
const res = this.getResponseObject();
const req = this.getRequestObject();
const responseType = this.getNodeParameter('responseType', 'approval') as
| 'approval'
| 'freeText'
| 'customForm';
if (
responseType === 'approval' &&
(isbot(req.headers['user-agent']) ||
// Microsoft Teams link preview service (SkypeSpaces) automatically fetches
// URLs in chat messages for rich previews, which would trigger the approval
req.headers['user-agent']?.includes('SkypeSpaces'))
) {
res.send('');
return { noWebhookResponse: true };
}
if (responseType === 'freeText') {
if (method === 'GET') {
const { formTitle, formDescription, buttonLabel, customCss } =
getFormResponseCustomizations(this);
const data = prepareFormData({
formTitle,
formDescription,
formSubmittedHeader: 'Got it, thanks',
formSubmittedText: 'This page can be closed now',
buttonLabel,
redirectUrl: undefined,
formFields: [
{
fieldLabel: 'Response',
fieldType: 'textarea',
requiredField: true,
},
],
testRun: false,
query: {},
customCss,
});
res.setHeader('Content-Security-Policy', getWebhookSandboxCSP());
res.render('form-trigger', data);
return {
noWebhookResponse: true,
};
}
if (method === 'POST') {
const data = this.getBodyData().data as IDataObject;
return {
webhookResponse: ACTION_RECORDED_PAGE,
workflowData: [[{ json: { data: { text: data[INPUT_FIELD_IDENTIFIER] } } }]],
};
}
}
if (responseType === 'customForm') {
const defineForm = this.getNodeParameter('defineForm', 'fields') as 'fields' | 'json';
let fields: FormFieldsParameter = [];
if (defineForm === 'json') {
fields = parseFormFields(this, {
defineForm: 'json',
fieldsParameterName: 'jsonOutput',
});
} else {
fields = parseFormFields(this, {
defineForm: 'fields',
fieldsParameterName: 'formFields.values',
});
}
if (method === 'GET') {
const { formTitle, formDescription, buttonLabel, customCss } =
getFormResponseCustomizations(this);
fields = prepareFormFields(fields);
const data = prepareFormData({
formTitle,
formDescription,
formSubmittedHeader: 'Got it, thanks',
formSubmittedText: 'This page can be closed now',
buttonLabel,
redirectUrl: undefined,
formFields: fields,
testRun: false,
query: {},
customCss,
});
res.setHeader('Content-Security-Policy', getWebhookSandboxCSP());
res.render('form-trigger', data);
return {
noWebhookResponse: true,
};
}
if (method === 'POST') {
const returnItem = await prepareFormReturnItem(this, fields, 'production', true);
const json = returnItem.json;
delete json.submittedAt;
delete json.formMode;
returnItem.json = { data: json };
return {
webhookResponse: ACTION_RECORDED_PAGE,
workflowData: [[returnItem]],
};
}
}
const query = req.query as { approved: 'false' | 'true' };
const approved = query.approved === 'true';
return {
webhookResponse: ACTION_RECORDED_PAGE,
workflowData: [[{ json: { data: { approved } } }]],
};
}
// Send and Wait Config -----------------------------------------------------------
export function getSendAndWaitConfig(context: IExecuteFunctions): SendAndWaitConfig {
const message = escapeHtml((context.getNodeParameter('message', 0, '') as string).trim())
.replace(/\\n/g, '\n')
.replace(/<br>/g, '\n');
const subject = escapeHtml(context.getNodeParameter('subject', 0, '') as string);
const approvalOptions = context.getNodeParameter('approvalOptions.values', 0, {}) as {
approvalType?: 'single' | 'double';
approveLabel?: string;
buttonApprovalStyle?: string;
disapproveLabel?: string;
buttonDisapprovalStyle?: string;
};
const options = context.getNodeParameter('options', 0, {});
const config: SendAndWaitConfig = {
title: subject,
message,
options: [],
appendAttribution: options?.appendAttribution as boolean,
};
const responseType = context.getNodeParameter('responseType', 0, 'approval') as string;
context.setSignatureValidationRequired();
const approvedSignedResumeUrl = context.getSignedResumeUrl({ approved: 'true' });
if (responseType === 'freeText' || responseType === 'customForm') {
const label = context.getNodeParameter('options.messageButtonLabel', 0, 'Respond') as string;
config.options.push({
label,
url: approvedSignedResumeUrl,
style: 'primary',
});
} else if (approvalOptions.approvalType === 'double') {
const approveLabel = escapeHtml(approvalOptions.approveLabel || 'Approve');
const buttonApprovalStyle = approvalOptions.buttonApprovalStyle || 'primary';
const disapproveLabel = escapeHtml(approvalOptions.disapproveLabel || 'Disapprove');
const buttonDisapprovalStyle = approvalOptions.buttonDisapprovalStyle || 'secondary';
const disapprovedSignedResumeUrl = context.getSignedResumeUrl({ approved: 'false' });
config.options.push({
label: disapproveLabel,
url: disapprovedSignedResumeUrl,
style: buttonDisapprovalStyle,
});
config.options.push({
label: approveLabel,
url: approvedSignedResumeUrl,
style: buttonApprovalStyle,
});
} else {
const label = escapeHtml(approvalOptions.approveLabel || 'Approve');
const style = approvalOptions.buttonApprovalStyle || 'primary';
config.options.push({
label,
url: approvedSignedResumeUrl,
style,
});
}
return config;
}
export function createButton(url: string, label: string, style: string) {
let buttonStyle = BUTTON_STYLE_PRIMARY;
if (style === 'secondary') {
buttonStyle = BUTTON_STYLE_SECONDARY;
}
return `<a href="${url}" target="_blank" style="${buttonStyle}">${label}</a>`;
}
export function createEmail(context: IExecuteFunctions) {
const to = (context.getNodeParameter('sendTo', 0, '') as string).trim();
const config = getSendAndWaitConfig(context);
if (to.indexOf('@') === -1 || (to.match(/@/g) || []).length > 1) {
const description = `The email address '${to}' in the 'To' field isn't valid or contains multiple addresses. Please provide only a single email address.`;
throw new NodeOperationError(context.getNode(), 'Invalid email address', {
description,
itemIndex: 0,
});
}
const buttons: string[] = [];
for (const option of config.options) {
buttons.push(createButton(option.url, option.label, option.style));
}
let emailBody: string;
if (config.appendAttribution !== false) {
const instanceId = context.getInstanceId();
emailBody = createEmailBodyWithN8nAttribution(config.message, buttons.join('\n'), instanceId);
} else {
emailBody = createEmailBodyWithoutN8nAttribution(config.message, buttons.join('\n'));
}
const email: IEmail = {
to,
subject: config.title,
body: '',
htmlBody: emailBody,
};
return email;
}
const sendAndWaitWaitingTooltip = (parameters: { operation: string }) => {
if (parameters?.operation === 'sendAndWait') {
return "Execution will continue after the user's response";
}
return '';
};
export const SEND_AND_WAIT_WAITING_TOOLTIP = `={{ (${sendAndWaitWaitingTooltip})($parameter) }}`;