export interface IWorkflowExecutionDataProcess {

keep keep keep keep add keep keep keep keep keep

/* eslint-disable @typescript-eslint/prefer-optional-chain */
/* eslint-disable no-await-in-loop */
/* eslint-disable no-labels */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable no-continue */
/* eslint-disable no-prototype-builtins */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-param-reassign */
/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
import PCancelable from 'p-cancelable';

import type {
	ExecutionError,
	ExecutionStatus,
	IConnection,
	IDataObject,
	IExecuteData,
	INode,
	INodeConnections,
	INodeExecutionData,
	IPinData,
	IRun,
	IRunData,
	IRunExecutionData,
	ISourceData,
	ITaskData,
	ITaskDataConnections,
	ITaskDataConnectionsSource,
	IWaitingForExecution,
	IWaitingForExecutionSource,
	IWorkflowExecuteAdditionalData,
	NodeApiError,
	NodeOperationError,
	Workflow,
	WorkflowExecuteMode,
} from 'n8n-workflow';
import { LoggerProxy as Logger, WorkflowOperationError } from 'n8n-workflow';
import get from 'lodash.get';
import * as NodeExecuteFunctions from './NodeExecuteFunctions';

export class WorkflowExecute {
	runExecutionData: IRunExecutionData;

	private additionalData: IWorkflowExecuteAdditionalData;

	private mode: WorkflowExecuteMode;

	private status: ExecutionStatus;

	constructor(
		additionalData: IWorkflowExecuteAdditionalData,
		mode: WorkflowExecuteMode,
		runExecutionData?: IRunExecutionData,
	) {
		this.additionalData = additionalData;
		this.mode = mode;
		this.status = 'new';
		this.runExecutionData = runExecutionData || {
			startData: {},
			resultData: {
				runData: {},
				pinData: {},
			},
			executionData: {
				contextData: {},
				nodeExecutionStack: [],
				waitingExecution: {},
				waitingExecutionSource: {},
			},
		};
	}

	/**
	 * Executes the given workflow.
	 *
	 * @param {Workflow} workflow The workflow to execute
	 * @param {INode[]} [startNodes] Node to start execution from
	 * @param {string} [destinationNode] Node to stop execution at
	 */
	// IMPORTANT: Do not add "async" to this function, it will then convert the
	//            PCancelable to a regular Promise and does so not allow canceling
	//            active executions anymore
	// eslint-disable-next-line @typescript-eslint/promise-function-async
	run(
		workflow: Workflow,
		startNode?: INode,
		destinationNode?: string,
		pinData?: IPinData,
	): PCancelable<IRun> {
		this.status = 'running';

		// Get the nodes to start workflow execution from
		startNode = startNode || workflow.getStartNode(destinationNode);

		if (startNode === undefined) {
			throw new Error('No node to start the workflow from could be found!');
		}

		// If a destination node is given we only run the direct parent nodes and no others
		let runNodeFilter: string[] | undefined;
		if (destinationNode) {
			runNodeFilter = workflow.getParentNodes(destinationNode);
			runNodeFilter.push(destinationNode);
		}

		// Initialize the data of the start nodes
		const nodeExecutionStack: IExecuteData[] = [
			{
				node: startNode,
				data: {
					main: [
						[
							{
								json: {},
							},
						],
					],
				},
				source: null,
			},
		];

		this.runExecutionData = {
			startData: {
				destinationNode,
				runNodeFilter,
			},
			resultData: {
				runData: {},
				pinData,
			},
			executionData: {
				contextData: {},
				nodeExecutionStack,
				waitingExecution: {},
				waitingExecutionSource: {},
			},
		};

		return this.processRunExecutionData(workflow);
	}

	/**
	 * Executes the given workflow but only
	 *
	 * @param {Workflow} workflow The workflow to execute
	 * @param {string[]} startNodes Nodes to start execution from
	 * @param {string} destinationNode Node to stop execution at
	 */
	// IMPORTANT: Do not add "async" to this function, it will then convert the
	//            PCancelable to a regular Promise and does so not allow canceling
	//            active executions anymore
	// eslint-disable-next-line @typescript-eslint/promise-function-async
	runPartialWorkflow(
		workflow: Workflow,
		runData: IRunData,
		startNodes: string[],
		destinationNode: string,
		pinData?: IPinData,
	): PCancelable<IRun> {
		let incomingNodeConnections: INodeConnections | undefined;
		let connection: IConnection;

		this.status = 'running';

		const runIndex = 0;

		// Initialize the nodeExecutionStack and waitingExecution with
		// the data from runData
		const nodeExecutionStack: IExecuteData[] = [];
		const waitingExecution: IWaitingForExecution = {};
		const waitingExecutionSource: IWaitingForExecutionSource = {};
		for (const startNode of startNodes) {
			incomingNodeConnections = workflow.connectionsByDestinationNode[startNode];

			const incomingData: INodeExecutionData[][] = [];
			let incomingSourceData: ITaskDataConnectionsSource | null = null;

			if (incomingNodeConnections === undefined) {
				// If it has no incoming data add the default empty data
				incomingData.push([
					{
						json: {},
					},
				]);
			} else {
				// Get the data of the incoming connections
				incomingSourceData = { main: [] };
				for (const connections of incomingNodeConnections.main) {
					for (let inputIndex = 0; inputIndex < connections.length; inputIndex++) {
						connection = connections[inputIndex];

						const node = workflow.getNode(connection.node);

						if (node?.disabled) continue;

						if (node && pinData && pinData[node.name]) {
							incomingData.push(pinData[node.name]);
						} else {
							incomingData.push(
								// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
								runData[connection.node][runIndex].data![connection.type][connection.index]!,
							);
						}

						incomingSourceData.main.push({
							previousNode: connection.node,
						});
					}
				}
			}

			const executeData: IExecuteData = {
				node: workflow.getNode(startNode) as INode,
				data: {
					main: incomingData,
				},
				source: incomingSourceData,
			};

			nodeExecutionStack.push(executeData);

			// Check if the destinationNode has to be added as waiting
			// because some input data is already fully available
			incomingNodeConnections = workflow.connectionsByDestinationNode[destinationNode];
			if (incomingNodeConnections !== undefined) {
				for (const connections of incomingNodeConnections.main) {
					for (let inputIndex = 0; inputIndex < connections.length; inputIndex++) {
						connection = connections[inputIndex];

						if (waitingExecution[destinationNode] === undefined) {
							waitingExecution[destinationNode] = {};
							waitingExecutionSource[destinationNode] = {};
						}
						if (waitingExecution[destinationNode][runIndex] === undefined) {
							waitingExecution[destinationNode][runIndex] = {};
							waitingExecutionSource[destinationNode][runIndex] = {};
						}
						if (waitingExecution[destinationNode][runIndex][connection.type] === undefined) {
							waitingExecution[destinationNode][runIndex][connection.type] = [];
							waitingExecutionSource[destinationNode][runIndex][connection.type] = [];
						}

						if (runData[connection.node] !== undefined) {
							// Input data exists so add as waiting
							// incomingDataDestination.push(runData[connection.node!][runIndex].data![connection.type][connection.index]);
							waitingExecution[destinationNode][runIndex][connection.type].push(
								runData[connection.node][runIndex].data![connection.type][connection.index],
							);
							waitingExecutionSource[destinationNode][runIndex][connection.type].push({
								previousNode: connection.node,
								previousNodeOutput: connection.index || undefined,
								previousNodeRun: runIndex || undefined,
							} as ISourceData);
						} else {
							waitingExecution[destinationNode][runIndex][connection.type].push(null);
							waitingExecutionSource[destinationNode][runIndex][connection.type].push(null);
						}
					}
				}
			}
		}

		// Only run the parent nodes and no others
		let runNodeFilter: string[] | undefined;
		// eslint-disable-next-line prefer-const
		runNodeFilter = workflow
			.getParentNodes(destinationNode)
			.filter((parentNodeName) => !workflow.getNode(parentNodeName)?.disabled);

		runNodeFilter.push(destinationNode);

		this.runExecutionData = {
			startData: {
				destinationNode,
				runNodeFilter,
			},
			resultData: {
				runData,
				pinData,
			},
			executionData: {
				contextData: {},
				nodeExecutionStack,
				waitingExecution,
				waitingExecutionSource,
			},
		};

		return this.processRunExecutionData(workflow);
	}

	/**
	 * Executes the hook with the given name
	 *
	 */
	// eslint-disable-next-line @typescript-eslint/no-explicit-any
	async executeHook(hookName: string, parameters: any[]): Promise<void> {
		if (this.additionalData.hooks === undefined) {
			return;
		}

		// eslint-disable-next-line consistent-return
		return this.additionalData.hooks.executeHookFunctions(hookName, parameters);
	}

	/**
	 * Checks the incoming connection does not receive any data
	 */
	incomingConnectionIsEmpty(
		runData: IRunData,
		inputConnections: IConnection[],
		runIndex: number,
	): boolean {
		// for (const inputConnection of workflow.connectionsByDestinationNode[nodeToAdd].main[0]) {
		for (const inputConnection of inputConnections) {
			const nodeIncomingData = get(
				runData,
				`[${inputConnection.node}][${runIndex}].data.main[${inputConnection.index}]`,
			);
			if (nodeIncomingData !== undefined && (nodeIncomingData as object[]).length !== 0) {
				return false;
			}
		}
		return true;
	}

	addNodeToBeExecuted(
		workflow: Workflow,
		connectionData: IConnection,
		outputIndex: number,
		parentNodeName: string,
		nodeSuccessData: INodeExecutionData[][],
		runIndex: number,
	): void {
		let stillDataMissing = false;

		// Check if node has multiple inputs as then we have to wait for all input data
		// to be present before we can add it to the node-execution-stack
		if (workflow.connectionsByDestinationNode[connectionData.node].main.length > 1) {
			// Node has multiple inputs
			let nodeWasWaiting = true;

			if (!this.runExecutionData.executionData!.waitingExecutionSource) {
				this.runExecutionData.executionData!.waitingExecutionSource = {};
			}

			// Check if there is already data for the node
			if (
				this.runExecutionData.executionData!.waitingExecution[connectionData.node] === undefined
			) {
				// Node does not have data yet so create a new empty one
				this.runExecutionData.executionData!.waitingExecution[connectionData.node] = {};
				this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node] = {};
				nodeWasWaiting = false;
			}
			if (
				this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex] ===
				undefined
			) {
				// Node does not have data for runIndex yet so create also empty one and init it
				this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex] = {
					main: [],
				};
				this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][runIndex] =
					{
						main: [],
					};
				for (
					let i = 0;
					i < workflow.connectionsByDestinationNode[connectionData.node].main.length;
					i++
				) {
					this.runExecutionData.executionData!.waitingExecution[connectionData.node][
						runIndex
					].main.push(null);

					this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
						runIndex
					].main.push(null);
				}
			}

			// Add the new data
			if (nodeSuccessData === null) {
				this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex].main[
					connectionData.index
				] = null;
				this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
					runIndex
				].main[connectionData.index] = null;
			} else {
				this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex].main[
					connectionData.index
				] = nodeSuccessData[outputIndex];
				this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
					runIndex
				].main[connectionData.index] = {
					previousNode: parentNodeName,
					previousNodeOutput: outputIndex || undefined,
					previousNodeRun: runIndex || undefined,
				};
			}

			// Check if all data exists now
			let thisExecutionData: INodeExecutionData[] | null;
			let allDataFound = true;
			for (
				let i = 0;
				i <
				this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex].main
					.length;
				i++
			) {
				thisExecutionData =
					this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex].main[
						i
					];
				if (thisExecutionData === null) {
					allDataFound = false;
					break;
				}
			}

			if (allDataFound) {
				// All data exists for node to be executed
				// So add it to the execution stack

				const executionStackItem = {
					node: workflow.nodes[connectionData.node],
					data: this.runExecutionData.executionData!.waitingExecution[connectionData.node][
						runIndex
					],
					source:
						this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
							runIndex
						],
				} as IExecuteData;

				if (
					this.runExecutionData.executionData!.waitingExecutionSource !== null &&
					this.runExecutionData.executionData!.waitingExecutionSource !== undefined
				) {
					executionStackItem.source =
						this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
							runIndex
						];
				}

				this.runExecutionData.executionData!.nodeExecutionStack.push(executionStackItem);

				// Remove the data from waiting
				delete this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex];
				delete this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node][
					runIndex
				];

				if (
					Object.keys(this.runExecutionData.executionData!.waitingExecution[connectionData.node])
						.length === 0
				) {
					// No more data left for the node so also delete that one
					delete this.runExecutionData.executionData!.waitingExecution[connectionData.node];
					delete this.runExecutionData.executionData!.waitingExecutionSource[connectionData.node];
				}
				return;
			}
			stillDataMissing = true;

			if (!nodeWasWaiting) {
				// Get a list of all the output nodes that we can check for siblings easier
				const checkOutputNodes = [];
				// eslint-disable-next-line @typescript-eslint/no-for-in-array
				for (const outputIndexParent in workflow.connectionsBySourceNode[parentNodeName].main) {
					if (
						!workflow.connectionsBySourceNode[parentNodeName].main.hasOwnProperty(outputIndexParent)
					) {
						continue;
					}
					for (const connectionDataCheck of workflow.connectionsBySourceNode[parentNodeName].main[
						outputIndexParent
					]) {
						checkOutputNodes.push(connectionDataCheck.node);
					}
				}

				// Node was not on "waitingExecution" so it is the first time it gets
				// checked. So we have to go through all the inputs and check if they
				// are already on the list to be processed.
				// If that is not the case add it.
				for (
					let inputIndex = 0;
					inputIndex < workflow.connectionsByDestinationNode[connectionData.node].main.length;
					inputIndex++
				) {
					for (const inputData of workflow.connectionsByDestinationNode[connectionData.node].main[
						inputIndex
					]) {
						if (inputData.node === parentNodeName) {
							// Is the node we come from so its data will be available for sure
							continue;
						}

						const executionStackNodes = this.runExecutionData.executionData!.nodeExecutionStack.map(
							(stackData) => stackData.node.name,
						);

						// Check if that node is also an output connection of the
						// previously processed one
						if (inputData.node !== parentNodeName && checkOutputNodes.includes(inputData.node)) {
							// So the parent node will be added anyway which
							// will then process this node next. So nothing to do
							// unless the incoming data of the node is empty
							// because then it would not be executed
							if (
								!this.incomingConnectionIsEmpty(
									this.runExecutionData.resultData.runData,
									workflow.connectionsByDestinationNode[inputData.node].main[0],
									runIndex,
								)
							) {
								continue;
							}
						}

						// Check if it is already in the execution stack
						if (executionStackNodes.includes(inputData.node)) {
							// Node is already on the list to be executed
							// so there is nothing to do
							continue;
						}

						// Check if node got processed already
						if (this.runExecutionData.resultData.runData[inputData.node] !== undefined) {
							// Node got processed already so no need to add it
							continue;
						}

						// Check if any of the parent nodes does not have any inputs. That
						// would mean that it has to get added to the list of nodes to process.
						const parentNodes = workflow.getParentNodes(inputData.node, 'main', -1);
						let nodeToAdd: string | undefined = inputData.node;
						parentNodes.push(inputData.node);
						parentNodes.reverse();

						for (const parentNode of parentNodes) {
							// Check if that node is also an output connection of the
							// previously processed one
							if (inputData.node !== parentNode && checkOutputNodes.includes(parentNode)) {
								// So the parent node will be added anyway which
								// will then process this node next. So nothing to do.
								nodeToAdd = undefined;
								break;
							}

							// Check if it is already in the execution stack
							if (executionStackNodes.includes(parentNode)) {
								// Node is already on the list to be executed
								// so there is nothing to do
								nodeToAdd = undefined;
								break;
							}

							// Check if node got processed already
							if (this.runExecutionData.resultData.runData[parentNode] !== undefined) {
								// Node got processed already so we can use the
								// output data as input of this node
								break;
							}

							nodeToAdd = parentNode;
						}
						const parentNodesNodeToAdd = workflow.getParentNodes(nodeToAdd as string);
						if (
							parentNodesNodeToAdd.includes(parentNodeName) &&
							nodeSuccessData[outputIndex].length === 0
						) {
							// We do not add the node if there is no input data and the node that should be connected
							// is a child of the parent node. Because else it would run a node even though it should be
							// specifically not run, as it did not receive any data.
							nodeToAdd = undefined;
						}

						if (nodeToAdd === undefined) {
							// No node has to get added so process
							continue;
						}

						let addEmptyItem = false;

						if (workflow.connectionsByDestinationNode[nodeToAdd] === undefined) {
							// Add empty item if the node does not have any input connections
							addEmptyItem = true;
						} else if (
							this.incomingConnectionIsEmpty(
								this.runExecutionData.resultData.runData,
								workflow.connectionsByDestinationNode[nodeToAdd].main[0],
								runIndex,
							)
						) {
							// Add empty item also if the input data is empty
							addEmptyItem = true;
						}

						if (addEmptyItem) {
							// Add only node if it does not have any inputs because else it will
							// be added by its input node later anyway.
							this.runExecutionData.executionData!.nodeExecutionStack.push({
								node: workflow.getNode(nodeToAdd) as INode,
								data: {
									main: [
										[
											{
												json: {},
											},
										],
									],
								},
								source: {
									main: [
										{
											previousNode: parentNodeName,
											previousNodeOutput: outputIndex || undefined,
											previousNodeRun: runIndex || undefined,
										},
									],
								},
							});
						}
					}
				}
			}
		}

		// Make sure the array has all the values
		const connectionDataArray: Array<INodeExecutionData[] | null> = [];
		for (let i: number = connectionData.index; i >= 0; i--) {
			connectionDataArray[i] = null;
		}

		// Add the data of the current execution
		if (nodeSuccessData === null) {
			connectionDataArray[connectionData.index] = null;
		} else {
			connectionDataArray[connectionData.index] = nodeSuccessData[outputIndex];
		}

		if (stillDataMissing) {
			// Additional data is needed to run node so add it to waiting
			if (
				!this.runExecutionData.executionData!.waitingExecution.hasOwnProperty(connectionData.node)
			) {
				this.runExecutionData.executionData!.waitingExecution[connectionData.node] = {};
			}
			this.runExecutionData.executionData!.waitingExecution[connectionData.node][runIndex] = {
				main: connectionDataArray,
			};
		} else {
			// All data is there so add it directly to stack
			this.runExecutionData.executionData!.nodeExecutionStack.push({
				node: workflow.nodes[connectionData.node],
				data: {
					main: connectionDataArray,
				},
				source: {
					main: [
						{
							previousNode: parentNodeName,
							previousNodeOutput: outputIndex || undefined,
							previousNodeRun: runIndex || undefined,
						},
					],
				},
			});
		}
	}

	/**
	 * Runs the given execution data.
	 *
	 */
	// IMPORTANT: Do not add "async" to this function, it will then convert the
	//            PCancelable to a regular Promise and does so not allow canceling
	//            active executions anymore
	// eslint-disable-next-line @typescript-eslint/promise-function-async
	processRunExecutionData(workflow: Workflow): PCancelable<IRun> {
		Logger.verbose('Workflow execution started', { workflowId: workflow.id });

		const startedAt = new Date();

		this.status = 'running';

		const startNode = this.runExecutionData.executionData!.nodeExecutionStack[0].node.name;

		let destinationNode: string | undefined;
		if (this.runExecutionData.startData && this.runExecutionData.startData.destinationNode) {
			destinationNode = this.runExecutionData.startData.destinationNode;
		}

		const pinDataNodeNames = Object.keys(this.runExecutionData.resultData.pinData ?? {});

		const workflowIssues = workflow.checkReadyForExecution({
			startNode,
			destinationNode,
			pinDataNodeNames,
		});
		if (workflowIssues !== null) {
			throw new Error(
				'The workflow has issues and can for that reason not be executed. Please fix them first.',
			);
		}

		// Variables which hold temporary data for each node-execution
		let executionData: IExecuteData;
		let executionError: ExecutionError | undefined;
		let executionNode: INode;
		let nodeSuccessData: INodeExecutionData[][] | null | undefined;
		let runIndex: number;
		let startTime: number;
		let taskData: ITaskData;

		if (this.runExecutionData.startData === undefined) {
			this.runExecutionData.startData = {};
		}

		if (this.runExecutionData.waitTill) {
			const lastNodeExecuted = this.runExecutionData.resultData.lastNodeExecuted as string;
			this.runExecutionData.executionData!.nodeExecutionStack[0].node.disabled = true;
			this.runExecutionData.waitTill = undefined;
			this.runExecutionData.resultData.runData[lastNodeExecuted].pop();
		}

		let currentExecutionTry = '';
		let lastExecutionTry = '';
		let closeFunction: Promise<void> | undefined;

		return new PCancelable(async (resolve, reject, onCancel) => {
			let gotCancel = false;

			onCancel.shouldReject = false;
			onCancel(() => {
				gotCancel = true;
			});

			const returnPromise = (async () => {
				try {
					await this.executeHook('workflowExecuteBefore', [workflow]);
				} catch (error) {
					// Set the error that it can be saved correctly
					executionError = {
						...(error as NodeOperationError | NodeApiError),
						message: (error as NodeOperationError | NodeApiError).message,
						stack: (error as NodeOperationError | NodeApiError).stack,
					};

					// Set the incoming data of the node that it can be saved correctly
					// eslint-disable-next-line prefer-destructuring
					executionData = this.runExecutionData.executionData!.nodeExecutionStack[0];
					this.runExecutionData.resultData = {
						runData: {
							[executionData.node.name]: [
								{
									startTime,
									executionTime: new Date().getTime() - startTime,
									data: {
										main: executionData.data.main,
									} as ITaskDataConnections,
									source: [],
									executionStatus: 'error',
								},
							],
						},
						lastNodeExecuted: executionData.node.name,
						error: executionError,
					};

					throw error;
				}

				executionLoop: while (
					this.runExecutionData.executionData!.nodeExecutionStack.length !== 0
				) {
					if (
						this.additionalData.executionTimeoutTimestamp !== undefined &&
						Date.now() >= this.additionalData.executionTimeoutTimestamp
					) {
						gotCancel = true;
					}

					if (gotCancel) {
						return Promise.resolve();
					}

					nodeSuccessData = null;
					executionError = undefined;
					executionData =
						this.runExecutionData.executionData!.nodeExecutionStack.shift() as IExecuteData;
					executionNode = executionData.node;

					// Update the pairedItem information on items
					const newTaskDataConnections: ITaskDataConnections = {};
					for (const inputName of Object.keys(executionData.data)) {
						newTaskDataConnections[inputName] = executionData.data[inputName].map(
							(input, inputIndex) => {
								if (input === null) {
									return input;
								}

								return input.map((item, itemIndex) => {
									return {
										...item,
										pairedItem: {
											item: itemIndex,
											input: inputIndex || undefined,
										},
									};
								});
							},
						);
					}
					executionData.data = newTaskDataConnections;

					Logger.debug(`Start processing node "${executionNode.name}"`, {
						node: executionNode.name,
						workflowId: workflow.id,
					});
					await this.executeHook('nodeExecuteBefore', [executionNode.name]);

					// Get the index of the current run
					runIndex = 0;
					if (this.runExecutionData.resultData.runData.hasOwnProperty(executionNode.name)) {
						runIndex = this.runExecutionData.resultData.runData[executionNode.name].length;
					}

					currentExecutionTry = `${executionNode.name}:${runIndex}`;

					if (currentExecutionTry === lastExecutionTry) {
						throw new Error('Did stop execution because execution seems to be in endless loop.');
					}

					if (
						this.runExecutionData.startData!.runNodeFilter !== undefined &&
						this.runExecutionData.startData!.runNodeFilter.indexOf(executionNode.name) === -1
					) {
						// If filter is set and node is not on filter skip it, that avoids the problem that it executes
						// leafs that are parallel to a selected destinationNode. Normally it would execute them because
						// they have the same parent and it executes all child nodes.
						continue;
					}

					// Check if all the data which is needed to run the node is available
					if (workflow.connectionsByDestinationNode.hasOwnProperty(executionNode.name)) {
						// Check if the node has incoming connections
						if (workflow.connectionsByDestinationNode[executionNode.name].hasOwnProperty('main')) {
							let inputConnections: IConnection[][];
							let connectionIndex: number;

							// eslint-disable-next-line prefer-const
							inputConnections = workflow.connectionsByDestinationNode[executionNode.name].main;

							for (
								connectionIndex = 0;
								connectionIndex < inputConnections.length;
								connectionIndex++
							) {
								if (
									workflow.getHighestNode(executionNode.name, 'main', connectionIndex).length === 0
								) {
									// If there is no valid incoming node (if all are disabled)
									// then ignore that it has inputs and simply execute it as it is without
									// any data
									continue;
								}

								if (!executionData.data.hasOwnProperty('main')) {
									// ExecutionData does not even have the connection set up so can
									// not have that data, so add it again to be executed later
									this.runExecutionData.executionData!.nodeExecutionStack.push(executionData);
									lastExecutionTry = currentExecutionTry;
									continue executionLoop;
								}

								// Check if it has the data for all the inputs
								// The most nodes just have one but merge node for example has two and data
								// of both inputs has to be available to be able to process the node.
								if (
									executionData.data.main.length < connectionIndex ||
									executionData.data.main[connectionIndex] === null
								) {
									// Does not have the data of the connections so add back to stack
									this.runExecutionData.executionData!.nodeExecutionStack.push(executionData);
									lastExecutionTry = currentExecutionTry;
									continue executionLoop;
								}
							}
						}
					}

					startTime = new Date().getTime();

					let maxTries = 1;
					if (executionData.node.retryOnFail === true) {
						// TODO: Remove the hardcoded default-values here and also in NodeSettings.vue
						maxTries = Math.min(5, Math.max(2, executionData.node.maxTries || 3));
					}

					let waitBetweenTries = 0;
					if (executionData.node.retryOnFail === true) {
						// TODO: Remove the hardcoded default-values here and also in NodeSettings.vue
						waitBetweenTries = Math.min(
							5000,
							Math.max(0, executionData.node.waitBetweenTries || 1000),
						);
					}

					for (let tryIndex = 0; tryIndex < maxTries; tryIndex++) {
						if (gotCancel) {
							return Promise.resolve();
						}
						try {
							if (tryIndex !== 0) {
								// Reset executionError from previous error try
								executionError = undefined;
								if (waitBetweenTries !== 0) {
									// TODO: Improve that in the future and check if other nodes can
									//       be executed in the meantime
									// eslint-disable-next-line @typescript-eslint/no-shadow
									await new Promise((resolve) => {
										setTimeout(() => {
											resolve(undefined);
										}, waitBetweenTries);
									});
								}
							}

							const { pinData } = this.runExecutionData.resultData;

							if (pinData && !executionNode.disabled && pinData[executionNode.name] !== undefined) {
								const nodePinData = pinData[executionNode.name];

								nodeSuccessData = [nodePinData]; // always zeroth runIndex
							} else {
								Logger.debug(`Running node "${executionNode.name}" started`, {
									node: executionNode.name,
									workflowId: workflow.id,
								});
								const runNodeData = await workflow.runNode(
									executionData,
									this.runExecutionData,
									runIndex,
									this.additionalData,
									NodeExecuteFunctions,
									this.mode,
								);
								nodeSuccessData = runNodeData.data;

								if (runNodeData.closeFunction) {
									// Explanation why we do this can be found in n8n-workflow/Workflow.ts -> runNode
									// eslint-disable-next-line @typescript-eslint/no-unsafe-call
									closeFunction = runNodeData.closeFunction();
								}
							}

							Logger.debug(`Running node "${executionNode.name}" finished successfully`, {
								node: executionNode.name,
								workflowId: workflow.id,
							});

							if (nodeSuccessData) {
								// Check if the output data contains pairedItem data
								checkOutputData: for (const outputData of nodeSuccessData) {
									if (outputData === null) {
										continue;
									}
									for (const [index, item] of outputData.entries()) {
										if (!item.pairedItem) {
											// The pairedItem data is missing, so check if it can get automatically fixed
											if (
												executionData.data.main.length === 1 &&
												executionData.data.main[0]?.length === 1
											) {
												// The node has one input and one incoming item, so we know
												// that all items must originate from that single
												item.pairedItem = {
													item: 0,
												};
											} else if (
												nodeSuccessData.length === 1 &&
												executionData.data.main.length === 1 &&
												executionData.data.main[0]?.length === nodeSuccessData[0].length
											) {
												// The node has one input and one output. The number of items on both is
												// identical so we can make the reasonable assumption that each of the input
												// items is the origin of the corresponding output items
												item.pairedItem = {
													item: index,
												};
											} else {
												// In all other cases autofixing is not possible
												break checkOutputData;
											}
										}
									}
								}
							}

							if (nodeSuccessData === undefined) {
								// Node did not get executed
								nodeSuccessData = null;
							} else {
								this.runExecutionData.resultData.lastNodeExecuted = executionData.node.name;
							}

							if (nodeSuccessData === null || nodeSuccessData[0][0] === undefined) {
								if (executionData.node.alwaysOutputData === true) {
									nodeSuccessData = nodeSuccessData || [];
									nodeSuccessData[0] = [
										{
											json: {},
										},
									];
								}
							}

							if (nodeSuccessData === null && !this.runExecutionData.waitTill!) {
								// If null gets returned it means that the node did succeed
								// but did not have any data. So the branch should end
								// (meaning the nodes afterwards should not be processed)
								continue executionLoop;
							}

							break;
						} catch (error) {
							this.runExecutionData.resultData.lastNodeExecuted = executionData.node.name;

							executionError = {
								...(error as NodeOperationError | NodeApiError),
								message: (error as NodeOperationError | NodeApiError).message,
								stack: (error as NodeOperationError | NodeApiError).stack,
							};

							Logger.debug(`Running node "${executionNode.name}" finished with error`, {
								node: executionNode.name,
								workflowId: workflow.id,
							});
						}
					}

					// Add the data to return to the user
					// (currently does not get cloned as data does not get changed, maybe later we should do that?!?!)

					if (!this.runExecutionData.resultData.runData.hasOwnProperty(executionNode.name)) {
						this.runExecutionData.resultData.runData[executionNode.name] = [];
					}

					taskData = {
						startTime,
						executionTime: new Date().getTime() - startTime,
						source: !executionData.source ? [] : executionData.source.main,
						executionStatus: 'success',
					};

					if (executionError !== undefined) {
						taskData.error = executionError;
						taskData.executionStatus = 'error';

						if (executionData.node.continueOnFail === true) {
							// Workflow should continue running even if node errors
							if (executionData.data.hasOwnProperty('main') && executionData.data.main.length > 0) {
								// Simply get the input data of the node if it has any and pass it through
								// to the next node
								if (executionData.data.main[0] !== null) {
									nodeSuccessData = [executionData.data.main[0]];
								}
							}
						} else {
							// Node execution did fail so add error and stop execution
							this.runExecutionData.resultData.runData[executionNode.name].push(taskData);

							// Add the execution data again so that it can get restarted
							this.runExecutionData.executionData!.nodeExecutionStack.unshift(executionData);

							await this.executeHook('nodeExecuteAfter', [
								executionNode.name,
								taskData,
								this.runExecutionData,
							]);

							break;
						}
					}

					// Merge error information to default output for now
					// As the new nodes can report the errors in
					// the `error` property.
					for (const execution of nodeSuccessData!) {
						for (const lineResult of execution) {
							if (
								lineResult.json !== undefined &&
								lineResult.json.$error !== undefined &&
								lineResult.json.$json !== undefined
							) {
								lineResult.error = lineResult.json.$error as NodeApiError | NodeOperationError;
								lineResult.json = {
									error: (lineResult.json.$error as NodeApiError | NodeOperationError).message,
								};
							} else if (lineResult.error !== undefined) {
								lineResult.json = { error: lineResult.error.message };
							}
						}
					}

					// Node executed successfully. So add data and go on.
					taskData.data = {
						main: nodeSuccessData,
					} as ITaskDataConnections;

					this.runExecutionData.resultData.runData[executionNode.name].push(taskData);

					if (this.runExecutionData.waitTill!) {
						await this.executeHook('nodeExecuteAfter', [
							executionNode.name,
							taskData,
							this.runExecutionData,
						]);

						// Add the node back to the stack that the workflow can start to execute again from that node
						this.runExecutionData.executionData!.nodeExecutionStack.unshift(executionData);

						break;
					}

					if (
						this.runExecutionData.startData &&
						this.runExecutionData.startData.destinationNode &&
						this.runExecutionData.startData.destinationNode === executionNode.name
					) {
						// Before stopping, make sure we are executing hooks so
						// That frontend is notified for example for manual executions.
						await this.executeHook('nodeExecuteAfter', [
							executionNode.name,
							taskData,
							this.runExecutionData,
						]);

						// If destination node is defined and got executed stop execution
						continue;
					}

					// Add the nodes to which the current node has an output connection to that they can
					// be executed next
					if (workflow.connectionsBySourceNode.hasOwnProperty(executionNode.name)) {
						if (workflow.connectionsBySourceNode[executionNode.name].hasOwnProperty('main')) {
							let outputIndex: string;
							let connectionData: IConnection;
							// Iterate over all the outputs

							// Add the nodes to be executed
							// eslint-disable-next-line @typescript-eslint/no-for-in-array
							for (outputIndex in workflow.connectionsBySourceNode[executionNode.name].main) {
								if (
									!workflow.connectionsBySourceNode[executionNode.name].main.hasOwnProperty(
										outputIndex,
									)
								) {
									continue;
								}

								// Iterate over all the different connections of this output
								for (connectionData of workflow.connectionsBySourceNode[executionNode.name].main[
									outputIndex
								]) {
									if (!workflow.nodes.hasOwnProperty(connectionData.node)) {
										return Promise.reject(
											new Error(
												`The node "${executionNode.name}" connects to not found node "${connectionData.node}"`,
											),
										);
									}

									if (
										nodeSuccessData![outputIndex] &&
										(nodeSuccessData![outputIndex].length !== 0 || connectionData.index > 0)
									) {
										// Add the node only if it did execute or if connected to second "optional" input
										this.addNodeToBeExecuted(
											workflow,
											connectionData,
											parseInt(outputIndex, 10),
											executionNode.name,
											nodeSuccessData!,
											runIndex,
										);
									}
								}
							}
						}
					}

					// If we got here, it means that we did not stop executing from manual executions / destination.
					// Execute hooks now to make sure that all hooks are executed properly
					// Await is needed to make sure that we don't fall into concurrency problems
					// When saving node execution data
					await this.executeHook('nodeExecuteAfter', [
						executionNode.name,
						taskData,
						this.runExecutionData,
					]);
				}

				return Promise.resolve();
			})()
				.then(async () => {
					if (gotCancel && executionError === undefined) {
						return this.processSuccessExecution(
							startedAt,
							workflow,
							new WorkflowOperationError('Workflow has been canceled or timed out!'),
							closeFunction,
						);
					}
					return this.processSuccessExecution(startedAt, workflow, executionError, closeFunction);
				})
				.catch(async (error) => {
					const fullRunData = this.getFullRunData(startedAt);

					fullRunData.data.resultData.error = {
						...error,
						message: error.message,
						stack: error.stack,
					};

					// Check if static data changed
					let newStaticData: IDataObject | undefined;
					// eslint-disable-next-line no-underscore-dangle
					if (workflow.staticData.__dataChanged === true) {
						// Static data of workflow changed
						newStaticData = workflow.staticData;
					}
					await this.executeHook('workflowExecuteAfter', [fullRunData, newStaticData]).catch(
						// eslint-disable-next-line @typescript-eslint/no-shadow
						(error) => {
							// eslint-disable-next-line no-console
							console.error('There was a problem running hook "workflowExecuteAfter"', error);
						},
					);

					if (closeFunction) {
						try {
							await closeFunction;
						} catch (errorClose) {
							Logger.error(
								// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/restrict-template-expressions
								`There was a problem deactivating trigger of workflow "${workflow.id}": "${errorClose.message}"`,
								{
									workflowId: workflow.id,
								},
							);
						}
					}

					return fullRunData;
				});

			return returnPromise.then(resolve);
		});
	}

	async processSuccessExecution(
		startedAt: Date,
		workflow: Workflow,
		executionError?: ExecutionError,
		closeFunction?: Promise<void>,
	): Promise<IRun> {
		const fullRunData = this.getFullRunData(startedAt);

		if (executionError !== undefined) {
			Logger.verbose('Workflow execution finished with error', {
				error: executionError,
				workflowId: workflow.id,
			});
			fullRunData.data.resultData.error = {
				...executionError,
				message: executionError.message,
				stack: executionError.stack,
			} as ExecutionError;
		} else if (this.runExecutionData.waitTill!) {
			// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
			Logger.verbose(`Workflow execution will wait until ${this.runExecutionData.waitTill}`, {
				workflowId: workflow.id,
			});
			fullRunData.waitTill = this.runExecutionData.waitTill;
		} else {
			Logger.verbose('Workflow execution finished successfully', { workflowId: workflow.id });
			fullRunData.finished = true;
		}

		// Check if static data changed
		let newStaticData: IDataObject | undefined;
		// eslint-disable-next-line no-underscore-dangle
		if (workflow.staticData.__dataChanged === true) {
			// Static data of workflow changed
			newStaticData = workflow.staticData;
		}

		await this.executeHook('workflowExecuteAfter', [fullRunData, newStaticData]);

		if (closeFunction) {
			try {
				await closeFunction;
			} catch (error) {
				Logger.error(
					// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
					`There was a problem deactivating trigger of workflow "${workflow.id}": "${error.message}"`,
					{
						workflowId: workflow.id,
					},
				);
			}
		}

		return fullRunData;
	}

	getFullRunData(startedAt: Date): IRun {
		const fullRunData: IRun = {
			data: this.runExecutionData,
			mode: this.mode,
			startedAt,
			stoppedAt: new Date(),
			status: this.status,
		};

		return fullRunData;
	}
}


/* eslint-disable n8n-nodes-base/node-filename-against-convention */
import type {
	IDataObject,
	IExecuteFunctions,
	ILoadOptionsFunctions,
	INodeExecutionData,
	INodeType,
	INodeTypeDescription,
	JsonObject,
} from 'n8n-workflow';
import { NodeApiError, NodeOperationError } from 'n8n-workflow';

import { apiRequest, apiRequestAllItems, downloadRecordAttachments } from './GenericFunctions';

import { operationFields } from './OperationDescription';

export class NocoDB implements INodeType {
	description: INodeTypeDescription = {
		displayName: 'NocoDB',
		name: 'nocoDb',
		icon: 'file:nocodb.svg',
		group: ['input'],
		version: [1, 2],
		subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
		description: 'Read, update, write and delete data from NocoDB',
		defaults: {
			name: 'NocoDB',
		},
		inputs: ['main'],
		outputs: ['main'],
		credentials: [
			{
				name: 'nocoDb',
				required: true,
				displayOptions: {
					show: {
						authentication: ['nocoDb'],
					},
				},
			},
			{
				name: 'nocoDbApiToken',
				required: true,
				displayOptions: {
					show: {
						authentication: ['nocoDbApiToken'],
					},
				},
			},
		],
		properties: [
			{
				displayName: 'Authentication',
				name: 'authentication',
				type: 'options',
				options: [
					{
						name: 'User Token',
						value: 'nocoDb',
					},
					{
						name: 'API Token',
						value: 'nocoDbApiToken',
					},
				],
				default: 'nocoDb',
			},
			{
				displayName: 'API Version',
				name: 'version',
				type: 'options',
				displayOptions: {
					show: {
						'@version': [1],
					},
				},
				isNodeSetting: true,
				options: [
					{
						name: 'Before v0.90.0',
						value: 1,
					},
					{
						name: 'v0.90.0 Onwards',
						value: 2,
					},
				],
				default: 1,
			},
			{
				displayName: 'API Version',
				name: 'version',
				type: 'options',
				displayOptions: {
					show: {
						'@version': [2],
					},
				},
				isNodeSetting: true,
				options: [
					{
						name: 'Before v0.90.0',
						value: 1,
					},
					{
						name: 'v0.90.0 Onwards',
						value: 2,
					},
				],
				default: 2,
			},
			{
				displayName: 'Resource',
				name: 'resource',
				type: 'options',
				noDataExpression: true,
				options: [
					{
						name: 'Row',
						value: 'row',
					},
				],
				default: 'row',
			},
			{
				displayName: 'Operation',
				name: 'operation',
				type: 'options',
				noDataExpression: true,
				displayOptions: {
					show: {
						resource: ['row'],
					},
				},
				options: [
					{
						name: 'Create',
						value: 'create',
						description: 'Create a row',
						action: 'Create a row',
					},
					{
						name: 'Delete',
						value: 'delete',
						description: 'Delete a row',
						action: 'Delete a row',
					},
					{
						name: 'Get',
						value: 'get',
						description: 'Retrieve a row',
						action: 'Get a row',
					},
					{
						name: 'Get Many',
						value: 'getAll',
						description: 'Retrieve many rows',
						action: 'Get many rows',
					},
					{
						name: 'Update',
						value: 'update',
						description: 'Update a row',
						action: 'Update a row',
					},
				],
				default: 'get',
			},
			...operationFields,
		],
	};

	methods = {
		loadOptions: {
			async getProjects(this: ILoadOptionsFunctions) {
				try {
					const requestMethod = 'GET';
					const endpoint = '/api/v1/db/meta/projects/';
					const responseData = await apiRequest.call(this, requestMethod, endpoint, {}, {});
					return responseData.list.map((i: IDataObject) => ({ name: i.title, value: i.id }));
				} catch (e) {
					throw new NodeOperationError(
						this.getNode(),
						new Error('Error while fetching projects!', { cause: e }),
					);
				}
			},
			// This only supports using the Project ID
			async getTables(this: ILoadOptionsFunctions) {
				const projectId = this.getNodeParameter('projectId', 0) as string;
				if (projectId) {
					try {
						const requestMethod = 'GET';
						const endpoint = `/api/v1/db/meta/projects/${projectId}/tables`;
						const responseData = await apiRequest.call(this, requestMethod, endpoint, {}, {});
						return responseData.list.map((i: IDataObject) => ({ name: i.title, value: i.id }));
					} catch (e) {
						throw new NodeOperationError(
							this.getNode(),
							new Error('Error while fetching tables!', { cause: e }),
						);
					}
				} else {
					throw new NodeOperationError(this.getNode(), 'No project selected!');
				}
			},
		},
	};

	async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
		const items = this.getInputData();
		const returnData: IDataObject[] = [];
		let responseData;

		const version = this.getNodeParameter('version', 0) as number;
		const resource = this.getNodeParameter('resource', 0);
		const operation = this.getNodeParameter('operation', 0);

		let returnAll = false;
		let requestMethod = '';

		let qs: IDataObject = {};

		let endPoint = '';

		const projectId = this.getNodeParameter('projectId', 0) as string;
		const table = this.getNodeParameter('table', 0) as string;

		if (resource === 'row') {
			if (operation === 'create') {
				requestMethod = 'POST';

				if (version === 1) {
					endPoint = `/nc/${projectId}/api/v1/${table}/bulk`;
				} else if (version === 2) {
					endPoint = `/api/v1/db/data/bulk/noco/${projectId}/${table}`;
				}

				const body: IDataObject[] = [];

				for (let i = 0; i < items.length; i++) {
					const newItem: IDataObject = {};
					const dataToSend = this.getNodeParameter('dataToSend', i) as
						| 'defineBelow'
						| 'autoMapInputData';

					if (dataToSend === 'autoMapInputData') {
						const incomingKeys = Object.keys(items[i].json);
						const rawInputsToIgnore = this.getNodeParameter('inputsToIgnore', i) as string;
						const inputDataToIgnore = rawInputsToIgnore.split(',').map((c) => c.trim());
						for (const key of incomingKeys) {
							if (inputDataToIgnore.includes(key)) continue;
							newItem[key] = items[i].json[key];
						}
					} else {
						const fields = this.getNodeParameter('fieldsUi.fieldValues', i, []) as Array<{
							fieldName: string;
							binaryData: boolean;
							fieldValue?: string;
							binaryProperty?: string;
						}>;

						for (const field of fields) {
							if (!field.binaryData) {
								newItem[field.fieldName] = field.fieldValue;
							} else if (field.binaryProperty) {
								const binaryPropertyName = field.binaryProperty;
								const binaryData = this.helpers.assertBinaryData(i, binaryPropertyName);
								const dataBuffer = await this.helpers.getBinaryDataBuffer(i, binaryPropertyName);

								const formData = {
									file: {
										value: dataBuffer,
										options: {
											filename: binaryData.fileName,
											contentType: binaryData.mimeType,
										},
									},
									json: JSON.stringify({
										api: 'xcAttachmentUpload',
										project_id: projectId,
										dbAlias: 'db',
										args: {},
									}),
								};

								let postUrl = '';
								if (version === 1) {
									postUrl = '/dashboard';
								} else if (version === 2) {
									postUrl = '/api/v1/db/storage/upload';
								}

								responseData = await apiRequest.call(
									this,
									'POST',
									postUrl,
									{},
									{ project_id: projectId },
									undefined,
									{
										formData,
									},
								);
								newItem[field.fieldName] = JSON.stringify([responseData]);
							}
						}
					}
					body.push(newItem);
				}
				try {
					responseData = await apiRequest.call(this, requestMethod, endPoint, body, qs);

					// Calculate ID manually and add to return data
					let id = responseData[0];
					for (let i = body.length - 1; i >= 0; i--) {
						body[i].id = id--;
					}

					returnData.push(...body);
				} catch (error) {
					if (this.continueOnFail()) {
						returnData.push({ error: error.toString() });
					}
					throw new NodeApiError(this.getNode(), error as JsonObject);
				}
			}

			if (operation === 'delete') {
				requestMethod = 'DELETE';
				if (version === 1) {
					endPoint = `/nc/${projectId}/api/v1/${table}/bulk`;
				} else if (version === 2) {
					endPoint = `/api/v1/db/data/bulk/noco/${projectId}/${table}`;
				}

				const body: IDataObject[] = [];

				for (let i = 0; i < items.length; i++) {
					const id = this.getNodeParameter('id', i) as string;
					body.push({ id });
				}

				try {
					responseData = (await apiRequest.call(
						this,
						requestMethod,
						endPoint,
						body,
						qs,
					)) as number[];
					if (version === 1) {
						returnData.push(...items.map((item) => item.json));
					} else if (version === 2) {
						returnData.push(
							...responseData.map((result: number, index: number) => {
								if (result === 0) {
									const errorMessage = `The row with the ID "${body[index].id}" could not be deleted. It probably doesn't exist.`;
									if (this.continueOnFail()) {
										return { error: errorMessage };
									}
									throw new NodeApiError(
										this.getNode(),
										{ message: errorMessage },
										{ message: errorMessage, itemIndex: index },
									);
								}
								return {
									success: true,
								};
							}),
						);
					}
				} catch (error) {
					if (this.continueOnFail()) {
						returnData.push({ error: error.toString() });
					}
					throw new NodeApiError(this.getNode(), error as JsonObject);
				}
			}

			if (operation === 'getAll') {
				const data = [];
				const downloadAttachments = this.getNodeParameter('downloadAttachments', 0) as boolean;
				try {
					for (let i = 0; i < items.length; i++) {
						requestMethod = 'GET';

						if (version === 1) {
							endPoint = `/nc/${projectId}/api/v1/${table}`;
						} else if (version === 2) {
							endPoint = `/api/v1/db/data/noco/${projectId}/${table}`;
						}

						returnAll = this.getNodeParameter('returnAll', 0);
						qs = this.getNodeParameter('options', i, {});

						if (qs.sort) {
							const properties = (qs.sort as IDataObject).property as Array<{
								field: string;
								direction: string;
							}>;
							qs.sort = properties
								.map((prop) => `${prop.direction === 'asc' ? '' : '-'}${prop.field}`)
								.join(',');
						}

						if (qs.fields) {
							qs.fields = (qs.fields as IDataObject[]).join(',');
						}

						if (returnAll) {
							responseData = await apiRequestAllItems.call(this, requestMethod, endPoint, {}, qs);
						} else {
							qs.limit = this.getNodeParameter('limit', 0);
							responseData = await apiRequest.call(this, requestMethod, endPoint, {}, qs);
							if (version === 2) {
								responseData = responseData.list;
							}
						}

						const executionData = this.helpers.constructExecutionMetaData(
							this.helpers.returnJsonArray(responseData as IDataObject),
							{ itemData: { item: i } },
						);
						returnData.push(...executionData);

						if (downloadAttachments) {
							const downloadFieldNames = (
								this.getNodeParameter('downloadFieldNames', 0) as string
							).split(',');
							const response = await downloadRecordAttachments.call(
								this,
								responseData as IDataObject[],
								downloadFieldNames,
							);
							data.push(...response);
						}
					}

					if (downloadAttachments) {
						return [data];
					}
				} catch (error) {
					if (this.continueOnFail()) {
						returnData.push({ json: { error: error.toString() } });
					} else {
						throw error;
					}
				}

				return this.prepareOutputData(returnData as INodeExecutionData[]);
			}

			if (operation === 'get') {
				requestMethod = 'GET';
				const newItems: INodeExecutionData[] = [];

				for (let i = 0; i < items.length; i++) {
					try {
						const id = this.getNodeParameter('id', i) as string;

						if (version === 1) {
							endPoint = `/nc/${projectId}/api/v1/${table}/${id}`;
						} else if (version === 2) {
							endPoint = `/api/v1/db/data/noco/${projectId}/${table}/${id}`;
						}

						responseData = await apiRequest.call(this, requestMethod, endPoint, {}, qs);

						if (version === 2) {
							if (Object.keys(responseData as IDataObject).length === 0) {
								// Get did fail
								const errorMessage = `The row with the ID "${id}" could not be queried. It probably doesn't exist.`;
								if (this.continueOnFail()) {
									newItems.push({ json: { error: errorMessage } });
									continue;
								}
								throw new NodeApiError(
									this.getNode(),
									{ message: errorMessage },
									{ message: errorMessage, itemIndex: i },
								);
							}
						}

						const downloadAttachments = this.getNodeParameter('downloadAttachments', i) as boolean;

						if (downloadAttachments) {
							const downloadFieldNames = (
								this.getNodeParameter('downloadFieldNames', i) as string
							).split(',');
							const data = await downloadRecordAttachments.call(
								this,
								[responseData as IDataObject],
								downloadFieldNames,
							);
							const newItem = {
								binary: data[0].binary,
								json: {},
							};

							const executionData = this.helpers.constructExecutionMetaData(
								[newItem] as INodeExecutionData[],
								{ itemData: { item: i } },
							);

							newItems.push(...executionData);
						} else {
							const executionData = this.helpers.constructExecutionMetaData(
								this.helpers.returnJsonArray(responseData as IDataObject),
								{ itemData: { item: i } },
							);

							newItems.push(...executionData);
						}
					} catch (error) {
						if (this.continueOnFail()) {
							const executionData = this.helpers.constructExecutionMetaData(
								this.helpers.returnJsonArray({ error: error.toString() }),
								{ itemData: { item: i } },
							);

							newItems.push(...executionData);
							continue;
						}
						throw new NodeApiError(this.getNode(), error as JsonObject, { itemIndex: i });
					}
				}
				return this.prepareOutputData(newItems);
			}

			if (operation === 'update') {
				requestMethod = 'PATCH';

				if (version === 1) {
					endPoint = `/nc/${projectId}/api/v1/${table}/bulk`;
					requestMethod = 'PUT';
				} else if (version === 2) {
					endPoint = `/api/v1/db/data/bulk/noco/${projectId}/${table}`;
				}
				const body: IDataObject[] = [];

				for (let i = 0; i < items.length; i++) {
					const id = this.getNodeParameter('id', i) as string;
					const newItem: IDataObject = { id };
					const dataToSend = this.getNodeParameter('dataToSend', i) as
						| 'defineBelow'
						| 'autoMapInputData';

					if (dataToSend === 'autoMapInputData') {
						const incomingKeys = Object.keys(items[i].json);
						const rawInputsToIgnore = this.getNodeParameter('inputsToIgnore', i) as string;
						const inputDataToIgnore = rawInputsToIgnore.split(',').map((c) => c.trim());
						for (const key of incomingKeys) {
							if (inputDataToIgnore.includes(key)) continue;
							newItem[key] = items[i].json[key];
						}
					} else {
						const fields = this.getNodeParameter('fieldsUi.fieldValues', i, []) as Array<{
							fieldName: string;
							binaryData: boolean;
							fieldValue?: string;
							binaryProperty?: string;
						}>;

						for (const field of fields) {
							if (!field.binaryData) {
								newItem[field.fieldName] = field.fieldValue;
							} else if (field.binaryProperty) {
								const binaryPropertyName = field.binaryProperty;
								const binaryData = this.helpers.assertBinaryData(i, binaryPropertyName);
								const dataBuffer = await this.helpers.getBinaryDataBuffer(i, binaryPropertyName);

								const formData = {
									file: {
										value: dataBuffer,
										options: {
											filename: binaryData.fileName,
											contentType: binaryData.mimeType,
										},
									},
									json: JSON.stringify({
										api: 'xcAttachmentUpload',
										project_id: projectId,
										dbAlias: 'db',
										args: {},
									}),
								};
								let postUrl = '';
								if (version === 1) {
									postUrl = '/dashboard';
								} else if (version === 2) {
									postUrl = '/api/v1/db/storage/upload';
								}
								responseData = await apiRequest.call(
									this,
									'POST',
									postUrl,
									{},
									{ project_id: projectId },
									undefined,
									{
										formData,
									},
								);
								newItem[field.fieldName] = JSON.stringify([responseData]);
							}
						}
					}
					body.push(newItem);
				}

				try {
					responseData = (await apiRequest.call(
						this,
						requestMethod,
						endPoint,
						body,
						qs,
					)) as number[];

					if (version === 1) {
						returnData.push(...body);
					} else if (version === 2) {
						returnData.push(
							...responseData.map((result: number, index: number) => {
								if (result === 0) {
									const errorMessage = `The row with the ID "${body[index].id}" could not be updated. It probably doesn't exist.`;
									if (this.continueOnFail()) {
										return { error: errorMessage };
									}
									throw new NodeApiError(
										this.getNode(),
										{ message: errorMessage },
										{ message: errorMessage, itemIndex: index },
									);
								}
								return {
									success: true,
								};
							}),
						);
					}
				} catch (error) {
					if (this.continueOnFail()) {
						returnData.push({ error: error.toString() });
					}
					throw new NodeApiError(this.getNode(), error as JsonObject);
				}
			}
		}
		return [this.helpers.returnJsonArray(returnData)];
	}
}


<template>

 0" data-test-id="node-auth-type-selector">

			<parameter-input-full
				:parameter="parameter"
				:value="authRelatedFieldsValues[parameter.name] || parameter.default"
				:path="parameter.name"
				:displayOptions="false"
				@valueChanged="valueChanged"
			/>

			<n8n-input-label
				:label="$locale.baseText('credentialEdit.credentialConfig.authTypeSelectorLabel')"
				:tooltipText="$locale.baseText('credentialEdit.credentialConfig.authTypeSelectorTooltip')"
				:required="true"
			/>

		<el-radio
			v-for="prop in filteredNodeAuthOptions"
			:key="prop.value"
			v-model="selected"
			:label="prop.value"
			:class="$style.authRadioButton"
			border
			@change="onAuthTypeChange"
			>{{ prop.name }}</el-radio
		>

</template>


@use './common/var';
@use 'mixins/mixins';

@include mixins.b(divider) {
	background-color: var(--border-color-base);
	position: relative;

	@include mixins.m(horizontal) {
		display: block;
		height: 1px;
		width: 100%;
		margin: 24px 0;
	}

	@include mixins.m(vertical) {
		display: inline-block;
		width: 1px;
		height: 1em;
		margin: 0 8px;
		vertical-align: middle;
		position: relative;
	}

	@include mixins.e(text) {
		position: absolute;
		background-color: var.$color-white;
		padding: 0 20px;
		font-weight: 500;
		color: var(--color-text-dark);
		font-size: 14px;

		@include mixins.when(left) {
			left: 20px;
			transform: translateY(-50%);
		}

		@include mixins.when(center) {
			left: 50%;
			transform: translateX(-50%) translateY(-50%);
		}

		@include mixins.when(right) {
			right: 20px;
			transform: translateY(-50%);
		}
	}
}


/* eslint-disable @typescript-eslint/no-unsafe-argument */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-console */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/restrict-template-expressions */
/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable @typescript-eslint/no-floating-promises */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/prefer-optional-chain */
/* eslint-disable no-param-reassign */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/no-unused-vars */
import type { IProcessMessage } from 'n8n-core';
import { BinaryDataManager, WorkflowExecute } from 'n8n-core';

import type {
	ExecutionError,
	IDeferredPromise,
	IExecuteResponsePromiseData,
	IRun,
	WorkflowExecuteMode,
	WorkflowHooks,
	WorkflowSettings,
} from 'n8n-workflow';
import {
	ErrorReporterProxy as ErrorReporter,
	LoggerProxy as Logger,
	Workflow,
	WorkflowOperationError,
} from 'n8n-workflow';

import PCancelable from 'p-cancelable';
import { join as pathJoin } from 'path';
import { fork } from 'child_process';

import { ActiveExecutions } from '@/ActiveExecutions';
import config from '@/config';
import * as Db from '@/Db';
import { ExternalHooks } from '@/ExternalHooks';
import type {
	IExecutionFlattedDb,
	IProcessMessageDataHook,
	IWorkflowExecutionDataProcess,
	IWorkflowExecutionDataProcessWithExecution,
} from '@/Interfaces';
import { NodeTypes } from '@/NodeTypes';
import type { Job, JobData, JobQueue, JobResponse } from '@/Queue';
import { Queue } from '@/Queue';
import * as ResponseHelper from '@/ResponseHelper';
import * as WebhookHelpers from '@/WebhookHelpers';
import * as WorkflowHelpers from '@/WorkflowHelpers';
import * as WorkflowExecuteAdditionalData from '@/WorkflowExecuteAdditionalData';
import { generateFailedExecutionFromError } from '@/WorkflowHelpers';
import { initErrorHandling } from '@/ErrorReporting';
import { PermissionChecker } from '@/UserManagement/PermissionChecker';
import { Push } from '@/push';
import { eventBus } from './eventbus';
import { recoverExecutionDataFromEventLogMessages } from './eventbus/MessageEventBus/recoverEvents';
import { Container } from 'typedi';
import { InternalHooks } from './InternalHooks';

export class WorkflowRunner {
	activeExecutions: ActiveExecutions;

	push: Push;

	jobQueue: JobQueue;

	constructor() {
		this.push = Container.get(Push);
		this.activeExecutions = Container.get(ActiveExecutions);
	}

	/**
	 * The process did send a hook message so execute the appropriate hook
	 */
	processHookMessage(workflowHooks: WorkflowHooks, hookData: IProcessMessageDataHook) {
		// eslint-disable-next-line @typescript-eslint/no-floating-promises
		workflowHooks.executeHookFunctions(hookData.hook, hookData.parameters);
	}

	/**
	 * The process did error
	 */
	async processError(
		error: ExecutionError,
		startedAt: Date,
		executionMode: WorkflowExecuteMode,
		executionId: string,
		hooks?: WorkflowHooks,
	) {
		ErrorReporter.error(error);

		const fullRunData: IRun = {
			data: {
				resultData: {
					error: {
						...error,
						message: error.message,
						stack: error.stack,
					},
					runData: {},
				},
			},
			finished: false,
			mode: executionMode,
			startedAt,
			stoppedAt: new Date(),
			status: 'error',
		};

		// The following will attempt to recover runData from event logs
		// Note that this will only work as long as the event logs actually contain the events from this workflow execution
		// Since processError is run almost immediately after the workflow execution has failed, it is likely that the event logs
		// does contain those messages.
		try {
			// Search for messages for this executionId in event logs
			const eventLogMessages = await eventBus.getEventsByExecutionId(executionId);
			// Attempt to recover more better runData from these messages (but don't update the execution db entry yet)
			if (eventLogMessages.length > 0) {
				const eventLogExecutionData = await recoverExecutionDataFromEventLogMessages(
					executionId,
					eventLogMessages,
					false,
				);
				if (eventLogExecutionData) {
					fullRunData.data.resultData.runData = eventLogExecutionData.resultData.runData;
					fullRunData.status = 'crashed';
				}
			}

			const executionFlattedData = await Db.collections.Execution.findOneBy({ id: executionId });

			void Container.get(InternalHooks).onWorkflowCrashed(
				executionId,
				executionMode,
				executionFlattedData?.workflowData,
			);
		} catch {
			// Ignore errors
		}

		// Remove from active execution with empty data. That will
		// set the execution to failed.
		this.activeExecutions.remove(executionId, fullRunData);

		if (hooks) {
			await hooks.executeHookFunctions('workflowExecuteAfter', [fullRunData]);
		}
	}

	/**
	 * Run the workflow
	 *
	 * @param {boolean} [loadStaticData] If set will the static data be loaded from
	 *                                   the workflow and added to input data
	 */
	async run(
		data: IWorkflowExecutionDataProcess,
		loadStaticData?: boolean,
		realtime?: boolean,
		executionId?: string,
		responsePromise?: IDeferredPromise<IExecuteResponsePromiseData>,
	): Promise<string> {
		const executionsMode = config.getEnv('executions.mode');
		const executionsProcess = config.getEnv('executions.process');

		await initErrorHandling();

		if (executionsMode === 'queue') {
			const queue = Container.get(Queue);
			this.jobQueue = queue.getBullObjectInstance();
		}

		if (executionsMode === 'queue' && data.executionMode !== 'manual') {
			// Do not run "manual" executions in bull because sending events to the
			// frontend would not be possible
			executionId = await this.enqueueExecution(
				data,
				loadStaticData,
				realtime,
				executionId,
				responsePromise,
			);
		} else if (executionsProcess === 'main') {
			executionId = await this.runMainProcess(data, loadStaticData, executionId, responsePromise);
		} else {
			executionId = await this.runSubprocess(data, loadStaticData, executionId, responsePromise);
		}

		void Container.get(InternalHooks).onWorkflowBeforeExecute(executionId, data);

		const postExecutePromise = this.activeExecutions.getPostExecutePromise(executionId);

		const externalHooks = Container.get(ExternalHooks);
		postExecutePromise
			.then(async (executionData) => {
				void Container.get(InternalHooks).onWorkflowPostExecute(
					executionId!,
					data.workflowData,
					executionData,
					data.userId,
				);
			})
			.catch((error) => {
				ErrorReporter.error(error);
				console.error('There was a problem running internal hook "onWorkflowPostExecute"', error);
			});

		if (externalHooks.exists('workflow.postExecute')) {
			postExecutePromise
				.then(async (executionData) => {
					await externalHooks.run('workflow.postExecute', [
						executionData,
						data.workflowData,
						executionId,
					]);
				})
				.catch((error) => {
					ErrorReporter.error(error);
					console.error('There was a problem running hook "workflow.postExecute"', error);
				});
		}

		return executionId;
	}

	/**
	 * Run the workflow in current process
	 *
	 * @param {boolean} [loadStaticData] If set will the static data be loaded from
	 *                                   the workflow and added to input data
	 */
	async runMainProcess(
		data: IWorkflowExecutionDataProcess,
		loadStaticData?: boolean,
		restartExecutionId?: string,
		responsePromise?: IDeferredPromise<IExecuteResponsePromiseData>,
	): Promise<string> {
		const workflowId = data.workflowData.id;
		if (loadStaticData === true && workflowId) {
			data.workflowData.staticData = await WorkflowHelpers.getStaticDataById(workflowId);
		}

		const nodeTypes = Container.get(NodeTypes);

		// Soft timeout to stop workflow execution after current running node
		// Changes were made by adding the `workflowTimeout` to the `additionalData`
		// So that the timeout will also work for executions with nested workflows.
		let executionTimeout: NodeJS.Timeout;

		const workflowSettings = data.workflowData.settings ?? {};
		let workflowTimeout = workflowSettings.executionTimeout ?? config.getEnv('executions.timeout'); // initialize with default
		if (workflowTimeout > 0) {
			workflowTimeout = Math.min(workflowTimeout, config.getEnv('executions.maxTimeout'));
		}

		const workflow = new Workflow({
			id: workflowId,
			name: data.workflowData.name,
			nodes: data.workflowData.nodes,
			connections: data.workflowData.connections,
			active: data.workflowData.active,
			nodeTypes,
			staticData: data.workflowData.staticData,
			settings: workflowSettings,
		});
		const additionalData = await WorkflowExecuteAdditionalData.getBase(
			data.userId,
			undefined,
			workflowTimeout <= 0 ? undefined : Date.now() + workflowTimeout * 1000,
		);

		// Register the active execution
		const executionId = await this.activeExecutions.add(data, undefined, restartExecutionId);
		additionalData.executionId = executionId;

		Logger.verbose(
			`Execution for workflow ${data.workflowData.name} was assigned id ${executionId}`,
			{ executionId },
		);
		let workflowExecution: PCancelable<IRun>;

		try {
			Logger.verbose(
				`Execution for workflow ${data.workflowData.name} was assigned id ${executionId}`,
				{ executionId },
			);

			additionalData.hooks = WorkflowExecuteAdditionalData.getWorkflowHooksMain(
				data,
				executionId,
				true,
			);

			try {
				await PermissionChecker.check(workflow, data.userId);
			} catch (error) {
				ErrorReporter.error(error);
				// Create a failed execution with the data for the node
				// save it and abort execution
				const failedExecution = generateFailedExecutionFromError(
					data.executionMode,
					error,
					error.node,
				);
				additionalData.hooks
					.executeHookFunctions('workflowExecuteAfter', [failedExecution])
					.then(() => {
						this.activeExecutions.remove(executionId, failedExecution);
					});
				return executionId;
			}

			additionalData.hooks.hookFunctions.sendResponse = [
				async (response: IExecuteResponsePromiseData): Promise<void> => {
					if (responsePromise) {
						responsePromise.resolve(response);
					}
				},
			];

			additionalData.setExecutionStatus = WorkflowExecuteAdditionalData.setExecutionStatus.bind({
				executionId,
			});

			additionalData.sendMessageToUI = WorkflowExecuteAdditionalData.sendMessageToUI.bind({
				sessionId: data.sessionId,
			});

			if (data.executionData !== undefined) {
				Logger.debug(`Execution ID ${executionId} had Execution data. Running with payload.`, {
					executionId,
				});
				const workflowExecute = new WorkflowExecute(
					additionalData,
					data.executionMode,
					data.executionData,
				);
				workflowExecution = workflowExecute.processRunExecutionData(workflow);
			} else if (
				data.runData === undefined ||
				data.startNodes === undefined ||
				data.startNodes.length === 0 ||
				data.destinationNode === undefined
			) {
				Logger.debug(`Execution ID ${executionId} will run executing all nodes.`, { executionId });
				// Execute all nodes

				let startNode;
				if (
					data.startNodes?.length === 1 &&
					Object.keys(data.pinData ?? {}).includes(data.startNodes[0])
				) {
					startNode = workflow.getNode(data.startNodes[0]) ?? undefined;
				}

				// Can execute without webhook so go on
				const workflowExecute = new WorkflowExecute(additionalData, data.executionMode);
				workflowExecution = workflowExecute.run(
					workflow,
					startNode,
					data.destinationNode,
					data.pinData,
				);
			} else {
				Logger.debug(`Execution ID ${executionId} is a partial execution.`, { executionId });
				// Execute only the nodes between start and destination nodes
				const workflowExecute = new WorkflowExecute(additionalData, data.executionMode);
				workflowExecution = workflowExecute.runPartialWorkflow(
					workflow,
					data.runData,
					data.startNodes,
					data.destinationNode,
					data.pinData,
				);
			}

			this.activeExecutions.attachWorkflowExecution(executionId, workflowExecution);

			if (workflowTimeout > 0) {
				const timeout = Math.min(workflowTimeout, config.getEnv('executions.maxTimeout')) * 1000; // as seconds
				executionTimeout = setTimeout(() => {
					this.activeExecutions.stopExecution(executionId, 'timeout');
				}, timeout);
			}

			workflowExecution
				.then((fullRunData) => {
					clearTimeout(executionTimeout);
					if (workflowExecution.isCanceled) {
						fullRunData.finished = false;
					}
					fullRunData.status = this.activeExecutions.getStatus(executionId);
					this.activeExecutions.remove(executionId, fullRunData);
				})
				.catch((error) => {
					this.processError(
						error,
						new Date(),
						data.executionMode,
						executionId,
						additionalData.hooks,
					);
				});
		} catch (error) {
			await this.processError(
				error,
				new Date(),
				data.executionMode,
				executionId,
				additionalData.hooks,
			);

			throw error;
		}

		return executionId;
	}

	async enqueueExecution(
		data: IWorkflowExecutionDataProcess,
		loadStaticData?: boolean,
		realtime?: boolean,
		restartExecutionId?: string,
		responsePromise?: IDeferredPromise<IExecuteResponsePromiseData>,
	): Promise<string> {
		// TODO: If "loadStaticData" is set to true it has to load data new on worker

		// Register the active execution
		const executionId = await this.activeExecutions.add(data, undefined, restartExecutionId);
		if (responsePromise) {
			this.activeExecutions.attachResponsePromise(executionId, responsePromise);
		}

		const jobData: JobData = {
			executionId,
			loadStaticData: !!loadStaticData,
		};

		let priority = 100;
		if (realtime === true) {
			// Jobs which require a direct response get a higher priority
			priority = 50;
		}
		// TODO: For realtime jobs should probably also not do retry or not retry if they are older than x seconds.
		//       Check if they get retried by default and how often.
		const jobOptions = {
			priority,
			removeOnComplete: true,
			removeOnFail: true,
		};
		let job: Job;
		let hooks: WorkflowHooks;
		try {
			job = await this.jobQueue.add(jobData, jobOptions);

			console.log(`Started with job ID: ${job.id.toString()} (Execution ID: ${executionId})`);

			hooks = WorkflowExecuteAdditionalData.getWorkflowHooksWorkerMain(
				data.executionMode,
				executionId,
				data.workflowData,
				{ retryOf: data.retryOf ? data.retryOf.toString() : undefined },
			);

			// Normally also workflow should be supplied here but as it only used for sending
			// data to editor-UI is not needed.
			hooks.executeHookFunctions('workflowExecuteBefore', []);
		} catch (error) {
			// We use "getWorkflowHooksWorkerExecuter" as "getWorkflowHooksWorkerMain" does not contain the
			// "workflowExecuteAfter" which we require.
			const hooks = WorkflowExecuteAdditionalData.getWorkflowHooksWorkerExecuter(
				data.executionMode,
				executionId,
				data.workflowData,
				{ retryOf: data.retryOf ? data.retryOf.toString() : undefined },
			);
			await this.processError(error, new Date(), data.executionMode, executionId, hooks);
			throw error;
		}

		const workflowExecution: PCancelable<IRun> = new PCancelable(
			async (resolve, reject, onCancel) => {
				onCancel.shouldReject = false;
				onCancel(async () => {
					const queue = Container.get(Queue);
					await queue.stopJob(job);

					// We use "getWorkflowHooksWorkerExecuter" as "getWorkflowHooksWorkerMain" does not contain the
					// "workflowExecuteAfter" which we require.
					const hooksWorker = WorkflowExecuteAdditionalData.getWorkflowHooksWorkerExecuter(
						data.executionMode,
						executionId,
						data.workflowData,
						{ retryOf: data.retryOf ? data.retryOf.toString() : undefined },
					);

					const error = new WorkflowOperationError('Workflow-Execution has been canceled!');
					await this.processError(error, new Date(), data.executionMode, executionId, hooksWorker);

					reject(error);
				});

				const jobData: Promise<JobResponse> = job.finished();

				const queueRecoveryInterval = config.getEnv('queue.bull.queueRecoveryInterval');

				const racingPromises: Array<Promise<JobResponse | object>> = [jobData];

				let clearWatchdogInterval;
				if (queueRecoveryInterval > 0) {
					/** ***********************************************
					 * Long explanation about what this solves:      *
					 * This only happens in a very specific scenario *
					 * when Redis crashes and recovers shortly       *
					 * but during this time, some execution(s)       *
					 * finished. The end result is that the main     *
					 * process will wait indefinitely and never      *
					 * get a response. This adds an active polling to*
					 * the queue that allows us to identify that the *
					 * execution finished and get information from   *
					 * the database.                                 *
					 ************************************************ */
					let watchDogInterval: NodeJS.Timeout | undefined;

					const watchDog: Promise<object> = new Promise((res) => {
						watchDogInterval = setInterval(async () => {
							const currentJob = await this.jobQueue.getJob(job.id);
							// When null means job is finished (not found in queue)
							if (currentJob === null) {
								// Mimic worker's success message
								res({ success: true });
							}
						}, queueRecoveryInterval * 1000);
					});

					racingPromises.push(watchDog);

					clearWatchdogInterval = () => {
						if (watchDogInterval) {
							clearInterval(watchDogInterval);
							watchDogInterval = undefined;
						}
					};
				}

				try {
					await Promise.race(racingPromises);
					if (clearWatchdogInterval !== undefined) {
						clearWatchdogInterval();
					}
				} catch (error) {
					ErrorReporter.error(error);
					// We use "getWorkflowHooksWorkerExecuter" as "getWorkflowHooksWorkerMain" does not contain the
					// "workflowExecuteAfter" which we require.
					const hooks = WorkflowExecuteAdditionalData.getWorkflowHooksWorkerExecuter(
						data.executionMode,
						executionId,
						data.workflowData,
						{ retryOf: data.retryOf ? data.retryOf.toString() : undefined },
					);
					Logger.error(`Problem with execution ${executionId}: ${error.message}. Aborting.`);
					if (clearWatchdogInterval !== undefined) {
						clearWatchdogInterval();
					}
					await this.processError(error, new Date(), data.executionMode, executionId, hooks);

					reject(error);
				}

				const executionDb = (await Db.collections.Execution.findOneBy({
					id: executionId,
				})) as IExecutionFlattedDb;
				const fullExecutionData = ResponseHelper.unflattenExecutionData(executionDb);
				const runData = {
					data: fullExecutionData.data,
					finished: fullExecutionData.finished,
					mode: fullExecutionData.mode,
					startedAt: fullExecutionData.startedAt,
					stoppedAt: fullExecutionData.stoppedAt,
				} as IRun;

				this.activeExecutions.remove(executionId, runData);
				// Normally also static data should be supplied here but as it only used for sending
				// data to editor-UI is not needed.
				hooks.executeHookFunctions('workflowExecuteAfter', [runData]);
				try {
					// Check if this execution data has to be removed from database
					// based on workflow settings.
					const workflowSettings = data.workflowData.settings ?? {};
					const saveDataErrorExecution =
						workflowSettings.saveDataErrorExecution ?? config.getEnv('executions.saveDataOnError');
					const saveDataSuccessExecution =
						workflowSettings.saveDataSuccessExecution ??
						config.getEnv('executions.saveDataOnSuccess');

					const workflowDidSucceed = !runData.data.resultData.error;
					if (
						(workflowDidSucceed && saveDataSuccessExecution === 'none') ||
						(!workflowDidSucceed && saveDataErrorExecution === 'none')
					) {
						await Db.collections.Execution.delete(executionId);
						await BinaryDataManager.getInstance().markDataForDeletionByExecutionId(executionId);
					}
					// eslint-disable-next-line id-denylist
				} catch (err) {
					// We don't want errors here to crash n8n. Just log and proceed.
					console.log('Error removing saved execution from database. More details: ', err);
				}

				resolve(runData);
			},
		);

		workflowExecution.catch(() => {
			// We `reject` this promise if the execution fails
			// but the error is handled already by processError
			// So we're just preventing crashes here.
		});

		this.activeExecutions.attachWorkflowExecution(executionId, workflowExecution);
		return executionId;
	}

	/**
	 * Run the workflow
	 *
	 * @param {boolean} [loadStaticData] If set will the static data be loaded from
	 *                                   the workflow and added to input data
	 */
	async runSubprocess(
		data: IWorkflowExecutionDataProcess,
		loadStaticData?: boolean,
		restartExecutionId?: string,
		responsePromise?: IDeferredPromise<IExecuteResponsePromiseData>,
	): Promise<string> {
		const workflowId = data.workflowData.id;
		let startedAt = new Date();
		const subprocess = fork(pathJoin(__dirname, 'WorkflowRunnerProcess.js'));

		if (loadStaticData === true && workflowId) {
			data.workflowData.staticData = await WorkflowHelpers.getStaticDataById(workflowId);
		}

		// Register the active execution
		const executionId = await this.activeExecutions.add(data, subprocess, restartExecutionId);

		(data as unknown as IWorkflowExecutionDataProcessWithExecution).executionId = executionId;

		const workflowHooks = WorkflowExecuteAdditionalData.getWorkflowHooksMain(data, executionId);

		try {
			// Send all data to subprocess it needs to run the workflow
			subprocess.send({ type: 'startWorkflow', data } as IProcessMessage);
		} catch (error) {
			await this.processError(error, new Date(), data.executionMode, executionId, workflowHooks);
			return executionId;
		}

		// Start timeout for the execution
		let executionTimeout: NodeJS.Timeout;

		const workflowSettings = data.workflowData.settings ?? {};
		let workflowTimeout = workflowSettings.executionTimeout ?? config.getEnv('executions.timeout'); // initialize with default

		const processTimeoutFunction = (timeout: number) => {
			this.activeExecutions.stopExecution(executionId, 'timeout');
			executionTimeout = setTimeout(() => subprocess.kill(), Math.max(timeout * 0.2, 5000)); // minimum 5 seconds
		};

		if (workflowTimeout > 0) {
			workflowTimeout = Math.min(workflowTimeout, config.getEnv('executions.maxTimeout')) * 1000; // as seconds
			// Start timeout already now but give process at least 5 seconds to start.
			// Without it could would it be possible that the workflow executions times out before it even got started if
			// the timeout time is very short as the process start time can be quite long.
			executionTimeout = setTimeout(
				processTimeoutFunction,
				Math.max(5000, workflowTimeout),
				workflowTimeout,
			);
		}

		// Create a list of child spawned executions
		// If after the child process exits we have
		// outstanding executions, we remove them
		const childExecutionIds: string[] = [];

		// Listen to data from the subprocess
		subprocess.on('message', async (message: IProcessMessage) => {
			Logger.debug(
				`Received child process message of type ${message.type} for execution ID ${executionId}.`,
				{ executionId },
			);
			if (message.type === 'start') {
				// Now that the execution actually started set the timeout again so that does not time out to early.
				startedAt = new Date();
				if (workflowTimeout > 0) {
					clearTimeout(executionTimeout);
					executionTimeout = setTimeout(processTimeoutFunction, workflowTimeout, workflowTimeout);
				}
			} else if (message.type === 'end') {
				clearTimeout(executionTimeout);
				this.activeExecutions.remove(executionId, message.data.runData);
			} else if (message.type === 'sendResponse') {
				if (responsePromise) {
					responsePromise.resolve(WebhookHelpers.decodeWebhookResponse(message.data.response));
				}
			} else if (message.type === 'sendMessageToUI') {
				// eslint-disable-next-line @typescript-eslint/no-unsafe-call
				WorkflowExecuteAdditionalData.sendMessageToUI.bind({ sessionId: data.sessionId })(
					message.data.source,
					message.data.message,
				);
			} else if (message.type === 'processError') {
				clearTimeout(executionTimeout);
				const executionError = message.data.executionError as ExecutionError;
				await this.processError(
					executionError,
					startedAt,
					data.executionMode,
					executionId,
					workflowHooks,
				);
			} else if (message.type === 'processHook') {
				this.processHookMessage(workflowHooks, message.data as IProcessMessageDataHook);
			} else if (message.type === 'timeout') {
				// Execution timed out and its process has been terminated
				const timeoutError = new WorkflowOperationError('Workflow execution timed out!');

				// No need to add hook here as the subprocess takes care of calling the hooks
				this.processError(timeoutError, startedAt, data.executionMode, executionId);
			} else if (message.type === 'startExecution') {
				const executionId = await this.activeExecutions.add(message.data.runData);
				childExecutionIds.push(executionId);
				subprocess.send({ type: 'executionId', data: { executionId } } as IProcessMessage);
			} else if (message.type === 'finishExecution') {
				const executionIdIndex = childExecutionIds.indexOf(message.data.executionId);
				if (executionIdIndex !== -1) {
					childExecutionIds.splice(executionIdIndex, 1);
				}

				// eslint-disable-next-line @typescript-eslint/await-thenable
				this.activeExecutions.remove(message.data.executionId, message.data.result);
			}
		});

		// Also get informed when the processes does exit especially when it did crash or timed out
		subprocess.on('exit', async (code, signal) => {
			if (signal === 'SIGTERM') {
				Logger.debug(`Subprocess for execution ID ${executionId} timed out.`, { executionId });
				// Execution timed out and its process has been terminated
				const timeoutError = new WorkflowOperationError('Workflow execution timed out!');

				await this.processError(
					timeoutError,
					startedAt,
					data.executionMode,
					executionId,
					workflowHooks,
				);
			} else if (code !== 0) {
				Logger.debug(
					`Subprocess for execution ID ${executionId} finished with error code ${code}.`,
					{ executionId },
				);
				// Process did exit with error code, so something went wrong.
				const executionError = new WorkflowOperationError(
					'Workflow execution process crashed for an unknown reason!',
				);

				await this.processError(
					executionError,
					startedAt,
					data.executionMode,
					executionId,
					workflowHooks,
				);
			}

			for (const executionId of childExecutionIds) {
				// When the child process exits, if we still have
				// pending child executions, we mark them as finished
				// They will display as unknown to the user
				// Instead of pending forever as executing when it
				// actually isn't anymore.
				// eslint-disable-next-line @typescript-eslint/await-thenable, no-await-in-loop
				this.activeExecutions.remove(executionId);
			}

			clearTimeout(executionTimeout);
		});

		return executionId;
	}
}


import type { ICredentialType, INodeProperties } from 'n8n-workflow';

export class PayPalApi implements ICredentialType {
	name = 'payPalApi';

	displayName = 'PayPal API';

	documentationUrl = 'payPal';

	properties: INodeProperties[] = [
		{
			displayName: 'Client ID',
			name: 'clientId',
			type: 'string',
			default: '',
		},
		{
			displayName: 'Secret',
			name: 'secret',
			type: 'string',
			default: '',
		},
		{
			displayName: 'Environment',
			name: 'env',
			type: 'options',
			default: 'live',
			options: [
				{
					name: 'Sandbox',
					value: 'sanbox',
				},
				{
					name: 'Live',
					value: 'live',
				},
			],
		},
	];
}


post:
  x-eov-operation-id: createCredential
  x-eov-operation-handler: v1/handlers/credentials/credentials.handler
  tags:
    - Credential
  summary: Create a credential
  description: Creates a credential that can be used by nodes of the specified type.
  requestBody:
    description: Credential to be created.
    required: true
    content:
      application/json:
        schema:
          $ref: '../schemas/credential.yml'
  responses:
    '200':
      description: Operation successful.
      content:
        application/json:
          schema:
            $ref: '../schemas/credential.yml'
    '401':
      $ref: '../../../../shared/spec/responses/unauthorized.yml'
    '415':
      description: Unsupported media type.


import type { INodeTypeBaseDescription, IVersionedNodeType } from 'n8n-workflow';
import { VersionedNodeType } from 'n8n-workflow';

import { ItemListsV1 } from './V1/ItemListsV1.node';

import { ItemListsV2 } from './V2/ItemListsV2.node';

export class ItemLists extends VersionedNodeType {
	constructor() {
		const baseDescription: INodeTypeBaseDescription = {
			displayName: 'Item Lists',
			name: 'itemLists',
			icon: 'file:itemLists.svg',
			group: ['input'],
			subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
			description: 'Helper for working with lists of items and transforming arrays',
			defaultVersion: 2,
		};

		const nodeVersions: IVersionedNodeType['nodeVersions'] = {
			1: new ItemListsV1(baseDescription),
			2: new ItemListsV2(baseDescription),
		};

		super(nodeVersions, baseDescription);
	}
}


if (loadStaticData === true && workflowId) {

data.workflowData.staticData = await WorkflowHelpers.getStaticDataById(workflowId);

const executionId = await this.activeExecutions.add(data, subprocess, restartExecutionId);

(data as unknown as IWorkflowExecutionDataProcessWithExecution).executionId = executionId;

keep keep keep keep add keep keep keep keep


import type { INodeProperties } from 'n8n-workflow';

export const mediaOperations: INodeProperties[] = [
	{
		displayName: 'Operation',
		name: 'operation',
		noDataExpression: true,
		type: 'options',
		displayOptions: {
			show: {
				resource: ['media'],
			},
		},
		options: [
			{
				name: 'Download',
				value: 'download',
				description: 'Download media',
				action: 'Download media',
			},
		],
		default: 'download',
	},
];

export const mediaFields: INodeProperties[] = [
	/* -------------------------------------------------------------------------- */
	/*                                 media:download                             */
	/* -------------------------------------------------------------------------- */
	{
		displayName: 'Resource Name',
		name: 'resourceName',
		type: 'string',
		required: true,
		displayOptions: {
			show: {
				resource: ['media'],
				operation: ['download'],
			},
		},
		default: '',
		description: 'Name of the media that is being downloaded',
	},
	{
		displayName: 'Binary Property',
		name: 'binaryPropertyName',
		type: 'string',
		default: 'data',
		required: true,
		displayOptions: {
			show: {
				resource: ['media'],
				operation: ['download'],
			},
		},
		description: 'Name of the binary property to which to write the data of the read file',
	},
];


import { del as execute } from './execute';
import { channelDeleteDescription as description } from './description';

export { description, execute };


import type { ICredentialType, INodeProperties } from 'n8n-workflow';

export class SentryIoServerApi implements ICredentialType {
	name = 'sentryIoServerApi';

	displayName = 'Sentry.io Server API';

	documentationUrl = 'sentryIo';

	properties: INodeProperties[] = [
		{
			displayName: 'Token',
			name: 'token',
			type: 'string',
			default: '',
		},
		{
			displayName: 'URL',
			name: 'url',
			type: 'string',
			default: '',
			placeholder: 'https://example.com',
		},
	];
}