@fsai-flow/core 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/README.md +31 -0
  2. package/dist/package.json +54 -0
  3. package/dist/src/index.d.ts +16 -0
  4. package/dist/src/index.js +30 -0
  5. package/dist/src/index.js.map +1 -0
  6. package/dist/src/lib/ActiveWebhooks.d.ts +59 -0
  7. package/dist/src/lib/ActiveWebhooks.js +184 -0
  8. package/dist/src/lib/ActiveWebhooks.js.map +1 -0
  9. package/dist/src/lib/ActiveWorkflows.d.ts +87 -0
  10. package/dist/src/lib/ActiveWorkflows.js +456 -0
  11. package/dist/src/lib/ActiveWorkflows.js.map +1 -0
  12. package/dist/src/lib/BinaryDataManager/FileSystem.d.ts +26 -0
  13. package/dist/src/lib/BinaryDataManager/FileSystem.js +179 -0
  14. package/dist/src/lib/BinaryDataManager/FileSystem.js.map +1 -0
  15. package/dist/src/lib/BinaryDataManager/index.d.ts +21 -0
  16. package/dist/src/lib/BinaryDataManager/index.js +146 -0
  17. package/dist/src/lib/BinaryDataManager/index.js.map +1 -0
  18. package/dist/src/lib/ChangeCase.d.ts +9 -0
  19. package/dist/src/lib/ChangeCase.js +43 -0
  20. package/dist/src/lib/ChangeCase.js.map +1 -0
  21. package/dist/src/lib/Constants.d.ts +14 -0
  22. package/dist/src/lib/Constants.js +19 -0
  23. package/dist/src/lib/Constants.js.map +1 -0
  24. package/dist/src/lib/Credentials.d.ts +27 -0
  25. package/dist/src/lib/Credentials.js +89 -0
  26. package/dist/src/lib/Credentials.js.map +1 -0
  27. package/dist/src/lib/FileSystem.d.ts +26 -0
  28. package/dist/src/lib/FileSystem.js +179 -0
  29. package/dist/src/lib/FileSystem.js.map +1 -0
  30. package/dist/src/lib/InputConnectionDataLegacy.d.ts +2 -0
  31. package/dist/src/lib/InputConnectionDataLegacy.js +79 -0
  32. package/dist/src/lib/InputConnectionDataLegacy.js.map +1 -0
  33. package/dist/src/lib/Interfaces.d.ts +148 -0
  34. package/dist/src/lib/Interfaces.js +3 -0
  35. package/dist/src/lib/Interfaces.js.map +1 -0
  36. package/dist/src/lib/LoadNodeParameterOptions.d.ts +39 -0
  37. package/dist/src/lib/LoadNodeParameterOptions.js +150 -0
  38. package/dist/src/lib/LoadNodeParameterOptions.js.map +1 -0
  39. package/dist/src/lib/NodeExecuteFunctions.d.ts +226 -0
  40. package/dist/src/lib/NodeExecuteFunctions.js +2479 -0
  41. package/dist/src/lib/NodeExecuteFunctions.js.map +1 -0
  42. package/dist/src/lib/NodesLoader/constants.d.ts +5 -0
  43. package/dist/src/lib/NodesLoader/constants.js +106 -0
  44. package/dist/src/lib/NodesLoader/constants.js.map +1 -0
  45. package/dist/src/lib/NodesLoader/custom-directory-loader.d.ts +9 -0
  46. package/dist/src/lib/NodesLoader/custom-directory-loader.js +36 -0
  47. package/dist/src/lib/NodesLoader/custom-directory-loader.js.map +1 -0
  48. package/dist/src/lib/NodesLoader/directory-loader.d.ts +66 -0
  49. package/dist/src/lib/NodesLoader/directory-loader.js +325 -0
  50. package/dist/src/lib/NodesLoader/directory-loader.js.map +1 -0
  51. package/dist/src/lib/NodesLoader/index.d.ts +5 -0
  52. package/dist/src/lib/NodesLoader/index.js +12 -0
  53. package/dist/src/lib/NodesLoader/index.js.map +1 -0
  54. package/dist/src/lib/NodesLoader/lazy-package-directory-loader.d.ts +7 -0
  55. package/dist/src/lib/NodesLoader/lazy-package-directory-loader.js +52 -0
  56. package/dist/src/lib/NodesLoader/lazy-package-directory-loader.js.map +1 -0
  57. package/dist/src/lib/NodesLoader/load-class-in-isolation.d.ts +1 -0
  58. package/dist/src/lib/NodesLoader/load-class-in-isolation.js +22 -0
  59. package/dist/src/lib/NodesLoader/load-class-in-isolation.js.map +1 -0
  60. package/dist/src/lib/NodesLoader/package-directory-loader.d.ts +17 -0
  61. package/dist/src/lib/NodesLoader/package-directory-loader.js +100 -0
  62. package/dist/src/lib/NodesLoader/package-directory-loader.js.map +1 -0
  63. package/dist/src/lib/NodesLoader/types.d.ts +14 -0
  64. package/dist/src/lib/NodesLoader/types.js +3 -0
  65. package/dist/src/lib/NodesLoader/types.js.map +1 -0
  66. package/dist/src/lib/RedisLeaderElectionManager.d.ts +53 -0
  67. package/dist/src/lib/RedisLeaderElectionManager.js +294 -0
  68. package/dist/src/lib/RedisLeaderElectionManager.js.map +1 -0
  69. package/dist/src/lib/UserSettings.d.ts +80 -0
  70. package/dist/src/lib/UserSettings.js +261 -0
  71. package/dist/src/lib/UserSettings.js.map +1 -0
  72. package/dist/src/lib/WorkflowExecute.d.ts +53 -0
  73. package/dist/src/lib/WorkflowExecute.js +854 -0
  74. package/dist/src/lib/WorkflowExecute.js.map +1 -0
  75. package/dist/src/lib/index.d.ts +21 -0
  76. package/dist/src/lib/index.js +146 -0
  77. package/dist/src/lib/index.js.map +1 -0
  78. package/dist/src/utils/crypto.d.ts +1 -0
  79. package/dist/src/utils/crypto.js +8 -0
  80. package/dist/src/utils/crypto.js.map +1 -0
  81. package/package.json +2 -2
  82. package/src/lib/ActiveWebhooks.ts +1 -1
  83. package/src/lib/ActiveWorkflows.ts +1 -1
  84. package/src/lib/LoadNodeParameterOptions.ts +1 -1
  85. package/src/lib/NodeExecuteFunctions.ts +1 -1
  86. package/src/lib/RedisLeaderElectionManager.ts +82 -0
  87. package/src/lib/UserSettings.ts +1 -1
  88. package/src/lib/WorkflowExecute.ts +1 -5
  89. package/tsconfig.json +0 -1
  90. package/tsconfig.base.json +0 -28
@@ -0,0 +1,2479 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getBinaryDataBuffer = getBinaryDataBuffer;
4
+ exports.prepareBinaryData = prepareBinaryData;
5
+ exports.getCurrentOAuth2AccessToken = getCurrentOAuth2AccessToken;
6
+ exports.requestOAuth2 = requestOAuth2;
7
+ exports.requestOAuth1 = requestOAuth1;
8
+ exports.httpRequestWithAuthentication = httpRequestWithAuthentication;
9
+ exports.returnJsonArray = returnJsonArray;
10
+ exports.normalizeItems = normalizeItems;
11
+ exports.requestWithAuthentication = requestWithAuthentication;
12
+ exports.getAdditionalKeys = getAdditionalKeys;
13
+ exports.getCredentials = getCredentials;
14
+ exports.getNode = getNode;
15
+ exports.getNodeParameter = getNodeParameter;
16
+ exports.continueOnFail = continueOnFail;
17
+ exports.getNodeWebhookUrl = getNodeWebhookUrl;
18
+ exports.getTimezone = getTimezone;
19
+ exports.getWebhookDescription = getWebhookDescription;
20
+ exports.getWorkflowMetadata = getWorkflowMetadata;
21
+ exports.getExecutePollFunctions = getExecutePollFunctions;
22
+ exports.getExecuteTriggerFunctions = getExecuteTriggerFunctions;
23
+ exports.getExecuteFunctions = getExecuteFunctions;
24
+ exports.getExecuteSingleFunctions = getExecuteSingleFunctions;
25
+ exports.getCredentialTestFunctions = getCredentialTestFunctions;
26
+ exports.getLoadOptionsFunctions = getLoadOptionsFunctions;
27
+ exports.getExecuteHookFunctions = getExecuteHookFunctions;
28
+ exports.getExecuteWebhookFunctions = getExecuteWebhookFunctions;
29
+ exports.getSupplyDataFunctions = getSupplyDataFunctions;
30
+ exports.getInputConnectionData = getInputConnectionData;
31
+ const tslib_1 = require("tslib");
32
+ const workflow_1 = require("@fsai-flow/workflow");
33
+ const https_1 = require("https");
34
+ const qs_1 = require("qs");
35
+ const clientOAuth1 = require('oauth-1.0a');
36
+ const simple_oauth2_1 = require("simple-oauth2");
37
+ const crypto = tslib_1.__importStar(require("crypto"));
38
+ const url = tslib_1.__importStar(require("url"));
39
+ const lodash_1 = require("lodash");
40
+ const FormData = require('form-data');
41
+ const path = tslib_1.__importStar(require("path"));
42
+ const crypto_1 = require("crypto");
43
+ const file_type_1 = require("file-type");
44
+ const mime_types_1 = require("mime-types");
45
+ const axios_1 = tslib_1.__importDefault(require("axios"));
46
+ const url_1 = require("url");
47
+ const BinaryDataManager_1 = require("./BinaryDataManager");
48
+ const __1 = require("..");
49
+ const fs_1 = require("fs");
50
+ axios_1.default.defaults.timeout = 900000;
51
+ // Prevent axios from adding x-form-www-urlencoded headers by default
52
+ axios_1.default.defaults.headers.post = {};
53
+ axios_1.default.defaults.headers.put = {};
54
+ axios_1.default.defaults.headers.patch = {};
55
+ axios_1.default.defaults.paramsSerializer = (params) => {
56
+ if (params instanceof url_1.URLSearchParams) {
57
+ return params.toString();
58
+ }
59
+ return (0, qs_1.stringify)(params, { arrayFormat: 'indices' });
60
+ };
61
+ const pushFormDataValue = (form, key, value) => {
62
+ // eslint-disable-next-line no-prototype-builtins
63
+ if ((value === null || value === void 0 ? void 0 : value.hasOwnProperty('value')) && Object.prototype.hasOwnProperty.call(value, 'options')) {
64
+ // @ts-ignore
65
+ form.append(key, value.value, value.options);
66
+ }
67
+ else {
68
+ form.append(key, value);
69
+ }
70
+ };
71
+ const createFormDataObject = (data) => {
72
+ const formData = new FormData();
73
+ const keys = Object.keys(data);
74
+ keys.forEach((key) => {
75
+ // @ts-ignore
76
+ const formField = data[key];
77
+ if (formField instanceof Array) {
78
+ formField.forEach((item) => {
79
+ pushFormDataValue(formData, key, item);
80
+ });
81
+ }
82
+ else {
83
+ pushFormDataValue(formData, key, formField);
84
+ }
85
+ });
86
+ return formData;
87
+ };
88
+ function searchForHeader(headers, headerName) {
89
+ if (headers === undefined) {
90
+ return undefined;
91
+ }
92
+ const headerNames = Object.keys(headers);
93
+ headerName = headerName.toLowerCase();
94
+ return headerNames.find((thisHeader) => thisHeader.toLowerCase() === headerName);
95
+ }
96
+ function generateContentLengthHeader(formData, headers) {
97
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
98
+ if (!formData || !formData.getLength) {
99
+ return;
100
+ }
101
+ try {
102
+ const length = yield new Promise((res, rej) => {
103
+ formData.getLength((error, length) => {
104
+ if (error) {
105
+ rej(error);
106
+ return;
107
+ }
108
+ res(length);
109
+ });
110
+ });
111
+ headers = Object.assign(headers, {
112
+ 'content-length': length,
113
+ });
114
+ }
115
+ catch (error) {
116
+ workflow_1.LoggerProxy.error('Unable to calculate form data length', { error });
117
+ }
118
+ });
119
+ }
120
+ function parseRequestObject(requestObject) {
121
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
122
+ var _a, _b, _c, _d, _e;
123
+ // This function is a temporary implementation
124
+ // That translates all http requests done via
125
+ // the request library to axios directly
126
+ // We are not using n8n's interface as it would
127
+ // an unnecessary step, considering the `request`
128
+ // helper can be deprecated and removed.
129
+ const axiosConfig = {};
130
+ if (typeof requestObject['headers'] === 'object' && requestObject['headers'] !== null) {
131
+ axiosConfig.headers = requestObject['headers'];
132
+ }
133
+ // Let's start parsing the hardest part, which is the request body.
134
+ // The process here is as following?
135
+ // - Check if we have a `content-type` header. If this was set,
136
+ // we will follow
137
+ // - Check if the `form` property was set. If yes, then it's x-www-form-urlencoded
138
+ // - Check if the `formData` property exists. If yes, then it's multipart/form-data
139
+ // - Lastly, we should have a regular `body` that is probably a JSON.
140
+ const contentTypeHeaderKeyName = axiosConfig.headers &&
141
+ Object.keys(axiosConfig.headers).find((headerName) => headerName.toLowerCase() === 'content-type');
142
+ const contentType = contentTypeHeaderKeyName &&
143
+ axiosConfig.headers &&
144
+ axiosConfig.headers[contentTypeHeaderKeyName];
145
+ if (contentType === 'application/x-www-form-urlencoded' && requestObject['formData'] === undefined) {
146
+ // there are nodes incorrectly created, informing the content type header
147
+ // and also using formData. Request lib takes precedence for the formData.
148
+ // We will do the same.
149
+ // Merge body and form properties.
150
+ if (typeof requestObject['body'] === 'string') {
151
+ axiosConfig.data = requestObject['body'];
152
+ }
153
+ else {
154
+ const allData = Object.assign(requestObject['body'] || {}, requestObject['form'] || {});
155
+ if (requestObject['useQuerystring'] === true) {
156
+ axiosConfig.data = (0, qs_1.stringify)(allData, { arrayFormat: 'repeat' });
157
+ }
158
+ else {
159
+ axiosConfig.data = (0, qs_1.stringify)(allData);
160
+ }
161
+ }
162
+ }
163
+ else if (contentType && contentType.includes('multipart/form-data') !== false) {
164
+ if (requestObject['formData'] !== undefined && requestObject['formData'] instanceof FormData) {
165
+ axiosConfig.data = requestObject['formData'];
166
+ }
167
+ else {
168
+ const allData = Object.assign(Object.assign({}, requestObject['body']), requestObject['formData']);
169
+ axiosConfig.data = createFormDataObject(allData);
170
+ }
171
+ // replace the existing header with a new one that
172
+ // contains the boundary property.
173
+ // @ts-ignore
174
+ delete axiosConfig.headers[contentTypeHeaderKeyName];
175
+ const headers = axiosConfig.data.getHeaders();
176
+ axiosConfig.headers = Object.assign(axiosConfig.headers || {}, headers);
177
+ if (!axiosConfig.headers) {
178
+ axiosConfig.headers = {};
179
+ }
180
+ yield generateContentLengthHeader(axiosConfig.data, axiosConfig.headers);
181
+ }
182
+ else {
183
+ // When using the `form` property it means the content should be x-www-form-urlencoded.
184
+ if (requestObject['form'] !== undefined && requestObject['body'] === undefined) {
185
+ // If we have only form
186
+ axiosConfig.data =
187
+ typeof requestObject['form'] === 'string'
188
+ ? (0, qs_1.stringify)(requestObject['form'], { format: 'RFC3986' })
189
+ : (0, qs_1.stringify)(requestObject['form']).toString();
190
+ if (axiosConfig.headers !== undefined) {
191
+ const headerName = searchForHeader(axiosConfig.headers, 'content-type');
192
+ if (headerName) {
193
+ delete axiosConfig.headers[headerName];
194
+ }
195
+ axiosConfig.headers['Content-Type'] = 'application/x-www-form-urlencoded';
196
+ }
197
+ else {
198
+ axiosConfig.headers = {
199
+ 'Content-Type': 'application/x-www-form-urlencoded',
200
+ };
201
+ }
202
+ }
203
+ else if (requestObject['formData'] !== undefined) {
204
+ // remove any "content-type" that might exist.
205
+ if (axiosConfig.headers !== undefined) {
206
+ const headers = Object.keys(axiosConfig.headers);
207
+ headers.forEach((header) => header.toLowerCase() === 'content-type' && axiosConfig.headers ? delete axiosConfig.headers[header] : null);
208
+ }
209
+ if (requestObject['formData'] instanceof FormData) {
210
+ axiosConfig.data = requestObject['formData'];
211
+ }
212
+ else {
213
+ axiosConfig.data = createFormDataObject(requestObject['formData']);
214
+ }
215
+ // Mix in headers as FormData creates the boundary.
216
+ const headers = axiosConfig.data.getHeaders();
217
+ axiosConfig.headers = Object.assign(axiosConfig.headers || {}, headers);
218
+ yield generateContentLengthHeader(axiosConfig.data, axiosConfig.headers);
219
+ }
220
+ else if (requestObject['body'] !== undefined) {
221
+ // If we have body and possibly form
222
+ if (requestObject['form'] !== undefined) {
223
+ // merge both objects when exist.
224
+ if (requestObject['body'] && requestObject['form']) {
225
+ requestObject['body'] = Object.assign(requestObject['body'], requestObject['form']);
226
+ }
227
+ }
228
+ axiosConfig.data = requestObject['body'];
229
+ }
230
+ }
231
+ if (requestObject['uri'] !== undefined) {
232
+ axiosConfig.url = (_a = requestObject['uri']) === null || _a === void 0 ? void 0 : _a.toString();
233
+ }
234
+ if (requestObject['url'] !== undefined) {
235
+ axiosConfig.url = (_b = requestObject['url']) === null || _b === void 0 ? void 0 : _b.toString();
236
+ }
237
+ if (requestObject['baseURL'] !== undefined) {
238
+ axiosConfig.baseURL = (_c = requestObject['baseURL']) === null || _c === void 0 ? void 0 : _c.toString();
239
+ }
240
+ if (requestObject['method'] !== undefined) {
241
+ axiosConfig.method = requestObject['method'];
242
+ }
243
+ if (requestObject['qs'] !== undefined && Object.keys(requestObject['qs']).length > 0) {
244
+ axiosConfig.params = requestObject['qs'];
245
+ }
246
+ if (requestObject['useQuerystring'] === true ||
247
+ // @ts-ignore
248
+ ((_d = requestObject.qsStringifyOptions) === null || _d === void 0 ? void 0 : _d.arrayFormat) === 'repeat') {
249
+ axiosConfig.paramsSerializer = (params) => {
250
+ return (0, qs_1.stringify)(params, { arrayFormat: 'repeat' });
251
+ };
252
+ }
253
+ else if (requestObject['useQuerystring'] === false) {
254
+ axiosConfig.paramsSerializer = (params) => {
255
+ return (0, qs_1.stringify)(params, { arrayFormat: 'indices' });
256
+ };
257
+ }
258
+ // @ts-ignore
259
+ if (((_e = requestObject.qsStringifyOptions) === null || _e === void 0 ? void 0 : _e.arrayFormat) === 'brackets') {
260
+ axiosConfig.paramsSerializer = (params) => {
261
+ return (0, qs_1.stringify)(params, { arrayFormat: 'brackets' });
262
+ };
263
+ }
264
+ if (requestObject['auth'] !== undefined) {
265
+ // Check support for sendImmediately
266
+ if (requestObject['auth']['bearer'] !== undefined) {
267
+ axiosConfig.headers = Object.assign(axiosConfig.headers || {}, {
268
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
269
+ Authorization: `Bearer ${requestObject['auth']['bearer']}`,
270
+ });
271
+ }
272
+ else {
273
+ const authObj = requestObject['auth'];
274
+ // Request accepts both user/username and pass/password
275
+ axiosConfig.auth = {
276
+ username: (authObj['user'] || authObj['username']),
277
+ password: (authObj['password'] || authObj['pass']),
278
+ };
279
+ }
280
+ }
281
+ // Only set header if we have a body, otherwise it may fail
282
+ if (requestObject['json'] === true) {
283
+ // Add application/json headers - do not set charset as it breaks a lot of stuff
284
+ // only add if no other accept headers was sent.
285
+ const acceptHeaderExists = axiosConfig.headers === undefined
286
+ ? false
287
+ : Object.keys(axiosConfig.headers)
288
+ .map((headerKey) => headerKey.toLowerCase())
289
+ .includes('accept');
290
+ if (!acceptHeaderExists) {
291
+ axiosConfig.headers = Object.assign(axiosConfig.headers || {}, {
292
+ Accept: 'application/json',
293
+ });
294
+ }
295
+ }
296
+ if (requestObject['json'] === false || requestObject['json'] === undefined) {
297
+ // Prevent json parsing
298
+ axiosConfig.transformResponse = (res) => res;
299
+ }
300
+ // Axios will follow redirects by default, so we simply tell it otherwise if needed.
301
+ if (requestObject['followRedirect'] === false &&
302
+ (requestObject['method'] || 'get').toLowerCase() === 'get') {
303
+ axiosConfig.maxRedirects = 0;
304
+ }
305
+ if (requestObject['followAllRedirects'] === false &&
306
+ (requestObject['method'] || 'get').toLowerCase() !== 'get') {
307
+ axiosConfig.maxRedirects = 0;
308
+ }
309
+ if (requestObject['rejectUnauthorized'] === false) {
310
+ axiosConfig.httpsAgent = new https_1.Agent({
311
+ rejectUnauthorized: false,
312
+ });
313
+ }
314
+ if (requestObject['timeout'] !== undefined) {
315
+ axiosConfig.timeout = requestObject['timeout'];
316
+ }
317
+ if (requestObject['proxy'] !== undefined) {
318
+ // try our best to parse the url provided.
319
+ if (typeof requestObject['proxy'] === 'string') {
320
+ try {
321
+ const url = new url_1.URL(requestObject['proxy']);
322
+ axiosConfig.proxy = {
323
+ host: url.hostname,
324
+ port: parseInt(url.port, 10),
325
+ protocol: url.protocol,
326
+ };
327
+ if (!url.port) {
328
+ // Sets port to a default if not informed
329
+ if (url.protocol === 'http') {
330
+ axiosConfig.proxy.port = 80;
331
+ }
332
+ else if (url.protocol === 'https') {
333
+ axiosConfig.proxy.port = 443;
334
+ }
335
+ }
336
+ if (url.username || url.password) {
337
+ axiosConfig.proxy.auth = {
338
+ username: url.username,
339
+ password: url.password,
340
+ };
341
+ }
342
+ }
343
+ catch (error) {
344
+ // Not a valid URL. We will try to simply parse stuff
345
+ // such as user:pass@host:port without protocol (we'll assume http)
346
+ if (requestObject['proxy'].includes('@')) {
347
+ const [userpass, hostport] = requestObject['proxy'].split('@');
348
+ const [username, password] = userpass.split(':');
349
+ const [hostname, port] = hostport.split(':');
350
+ axiosConfig.proxy = {
351
+ host: hostname,
352
+ port: parseInt(port, 10),
353
+ protocol: 'http',
354
+ auth: {
355
+ username,
356
+ password,
357
+ },
358
+ };
359
+ }
360
+ else if (requestObject['proxy'].includes(':')) {
361
+ const [hostname, port] = requestObject['proxy'].split(':');
362
+ axiosConfig.proxy = {
363
+ host: hostname,
364
+ port: parseInt(port, 10),
365
+ protocol: 'http',
366
+ };
367
+ }
368
+ else {
369
+ axiosConfig.proxy = {
370
+ host: requestObject['proxy'],
371
+ port: 80,
372
+ protocol: 'http',
373
+ };
374
+ }
375
+ }
376
+ }
377
+ else {
378
+ axiosConfig.proxy = requestObject['proxy'];
379
+ }
380
+ }
381
+ if (requestObject['encoding'] === null) {
382
+ // When downloading files, return an arrayBuffer.
383
+ axiosConfig.responseType = 'arraybuffer';
384
+ }
385
+ // If we don't set an accept header
386
+ // Axios forces "application/json, text/plan, */*"
387
+ // Which causes some nodes like NextCloud to break
388
+ // as the service returns XML unless requested otherwise.
389
+ const allHeaders = axiosConfig.headers ? Object.keys(axiosConfig.headers) : [];
390
+ if (!allHeaders.some((headerKey) => headerKey.toLowerCase() === 'accept')) {
391
+ axiosConfig.headers = Object.assign(axiosConfig.headers || {}, { accept: '*/*' });
392
+ }
393
+ if (requestObject['json'] !== false &&
394
+ axiosConfig.data !== undefined &&
395
+ axiosConfig.data !== '' &&
396
+ !(axiosConfig.data instanceof Buffer) &&
397
+ !allHeaders.some((headerKey) => headerKey.toLowerCase() === 'content-type')) {
398
+ // Use default header for application/json
399
+ // If we don't specify this here, axios will add
400
+ // application/json; charset=utf-8
401
+ // and this breaks a lot of stuff
402
+ axiosConfig.headers = Object.assign(axiosConfig.headers || {}, {
403
+ 'content-type': 'application/json',
404
+ });
405
+ }
406
+ /**
407
+ * Missing properties:
408
+ * encoding (need testing)
409
+ * gzip (ignored - default already works)
410
+ * resolveWithFullResponse (implemented elsewhere)
411
+ * simple (???)
412
+ */
413
+ return axiosConfig;
414
+ });
415
+ }
416
+ function digestAuthAxiosConfig(axiosConfig, response, auth) {
417
+ var _a;
418
+ const authDetails = response.headers['www-authenticate']
419
+ .split(',')
420
+ .map((v) => v.split('='));
421
+ if (authDetails) {
422
+ const nonceCount = `000000001`;
423
+ const cnonce = crypto.randomBytes(24).toString('hex');
424
+ const realm = authDetails
425
+ .find((el) => el[0].toLowerCase().indexOf('realm') > -1)[1]
426
+ .replace(/"/g, '');
427
+ const opaque = authDetails
428
+ .find((el) => el[0].toLowerCase().indexOf('opaque') > -1)[1]
429
+ .replace(/"/g, '');
430
+ const nonce = authDetails
431
+ .find((el) => el[0].toLowerCase().indexOf('nonce') > -1)[1]
432
+ .replace(/"/g, '');
433
+ const ha1 = crypto
434
+ .createHash('md5')
435
+ .update(`${auth === null || auth === void 0 ? void 0 : auth.username}:${realm}:${auth === null || auth === void 0 ? void 0 : auth.password}`)
436
+ .digest('hex');
437
+ const path = new url.URL(axiosConfig.url).pathname;
438
+ const ha2 = crypto
439
+ .createHash('md5')
440
+ .update(`${(_a = axiosConfig.method) !== null && _a !== void 0 ? _a : 'GET'}:${path}`)
441
+ .digest('hex');
442
+ const response = crypto
443
+ .createHash('md5')
444
+ .update(`${ha1}:${nonce}:${nonceCount}:${cnonce}:auth:${ha2}`)
445
+ .digest('hex');
446
+ const authorization = `Digest username="${auth === null || auth === void 0 ? void 0 : auth.username}",realm="${realm}",` +
447
+ `nonce="${nonce}",uri="${path}",qop="auth",algorithm="MD5",` +
448
+ `response="${response}",nc="${nonceCount}",cnonce="${cnonce}",opaque="${opaque}"`;
449
+ if (axiosConfig.headers) {
450
+ axiosConfig.headers['authorization'] = authorization;
451
+ }
452
+ else {
453
+ axiosConfig.headers = { authorization };
454
+ }
455
+ }
456
+ return axiosConfig;
457
+ }
458
+ function proxyRequestToAxios(uriOrObject, options) {
459
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
460
+ // tslint:disable-line:no-any
461
+ var _a;
462
+ let axiosConfig = {};
463
+ let axiosPromise;
464
+ let configObject;
465
+ if (uriOrObject !== undefined && typeof uriOrObject === 'string') {
466
+ axiosConfig.url = uriOrObject;
467
+ }
468
+ if (uriOrObject !== undefined && typeof uriOrObject === 'object') {
469
+ configObject = uriOrObject;
470
+ }
471
+ else {
472
+ configObject = options || {};
473
+ }
474
+ axiosConfig = Object.assign(axiosConfig, yield parseRequestObject(configObject));
475
+ workflow_1.LoggerProxy.debug('Proxying request to axios');
476
+ if (((_a = configObject.auth) === null || _a === void 0 ? void 0 : _a.sendImmediately) === false) {
477
+ // for digest-auth
478
+ const { auth } = axiosConfig;
479
+ delete axiosConfig.auth;
480
+ // eslint-disable-next-line no-async-promise-executor
481
+ axiosPromise = new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
482
+ var _a;
483
+ try {
484
+ const result = yield (0, axios_1.default)(axiosConfig);
485
+ resolve(result);
486
+ }
487
+ catch (resp) {
488
+ if (resp.response === undefined ||
489
+ resp.response.status !== 401 ||
490
+ !((_a = resp.response.headers['www-authenticate']) === null || _a === void 0 ? void 0 : _a.includes('nonce'))) {
491
+ reject(resp);
492
+ }
493
+ axiosConfig = digestAuthAxiosConfig(axiosConfig, resp.response, auth);
494
+ resolve((0, axios_1.default)(axiosConfig));
495
+ }
496
+ }));
497
+ }
498
+ else {
499
+ axiosPromise = (0, axios_1.default)(axiosConfig);
500
+ }
501
+ return new Promise((resolve, reject) => {
502
+ axiosPromise
503
+ .then((response) => {
504
+ if (configObject.resolveWithFullResponse === true) {
505
+ let body = response.data;
506
+ if (response.data === '') {
507
+ if (axiosConfig.responseType === 'arraybuffer') {
508
+ body = Buffer.alloc(0);
509
+ }
510
+ else {
511
+ body = undefined;
512
+ }
513
+ }
514
+ resolve({
515
+ body,
516
+ headers: response.headers,
517
+ statusCode: response.status,
518
+ statusMessage: response.statusText,
519
+ request: response.request,
520
+ });
521
+ }
522
+ else {
523
+ let body = response.data;
524
+ if (response.data === '') {
525
+ if (axiosConfig.responseType === 'arraybuffer') {
526
+ body = Buffer.alloc(0);
527
+ }
528
+ else {
529
+ body = undefined;
530
+ }
531
+ }
532
+ resolve(body);
533
+ }
534
+ })
535
+ .catch((error) => {
536
+ var _a, _b;
537
+ if (configObject.simple === false && error.response) {
538
+ if (configObject.resolveWithFullResponse) {
539
+ resolve({
540
+ body: error.response.data,
541
+ headers: error.response.headers,
542
+ statusCode: error.response.status,
543
+ statusMessage: error.response.statusText,
544
+ });
545
+ }
546
+ else {
547
+ resolve(error.response.data);
548
+ }
549
+ return;
550
+ }
551
+ workflow_1.LoggerProxy.debug('Request proxied to Axios failed', { error });
552
+ // Axios hydrates the original error with more data. We extract them.
553
+ // https://github.com/axios/axios/blob/master/lib/core/enhanceError.js
554
+ // Note: `code` is ignored as it's an expected part of the errorData.
555
+ const { request, response, isAxiosError, toJSON, config } = error, errorData = tslib_1.__rest(error, ["request", "response", "isAxiosError", "toJSON", "config"]);
556
+ if (response) {
557
+ error.message = `${response.status} - ${JSON.stringify(response.data)}`;
558
+ }
559
+ error.cause = errorData;
560
+ error.error = ((_a = error.response) === null || _a === void 0 ? void 0 : _a.data) || errorData;
561
+ error.statusCode = (_b = error.response) === null || _b === void 0 ? void 0 : _b.status;
562
+ error.options = config || {};
563
+ // Remove not needed data and so also remove circular references
564
+ error.request = undefined;
565
+ error.config = undefined;
566
+ error.options.adapter = undefined;
567
+ error.options.httpsAgent = undefined;
568
+ error.options.paramsSerializer = undefined;
569
+ error.options.transformRequest = undefined;
570
+ error.options.transformResponse = undefined;
571
+ error.options.validateStatus = undefined;
572
+ reject(error);
573
+ });
574
+ });
575
+ });
576
+ }
577
+ function convertN8nRequestToAxios(n8nRequest) {
578
+ // Destructure properties with the same name first.
579
+ const { headers, method, timeout, auth, proxy, url } = n8nRequest;
580
+ const axiosRequest = {
581
+ headers: headers !== null && headers !== void 0 ? headers : {},
582
+ method,
583
+ timeout,
584
+ auth,
585
+ proxy,
586
+ url,
587
+ };
588
+ axiosRequest.params = n8nRequest.qs;
589
+ if (n8nRequest.baseURL !== undefined) {
590
+ axiosRequest.baseURL = n8nRequest.baseURL;
591
+ }
592
+ if (n8nRequest.disableFollowRedirect === true) {
593
+ axiosRequest.maxRedirects = 0;
594
+ }
595
+ if (n8nRequest.encoding !== undefined) {
596
+ axiosRequest.responseType = n8nRequest.encoding;
597
+ }
598
+ if (n8nRequest.skipSslCertificateValidation === true) {
599
+ axiosRequest.httpsAgent = new https_1.Agent({
600
+ rejectUnauthorized: false,
601
+ });
602
+ }
603
+ if (n8nRequest.arrayFormat !== undefined) {
604
+ axiosRequest.paramsSerializer = (params) => {
605
+ return (0, qs_1.stringify)(params, { arrayFormat: n8nRequest.arrayFormat });
606
+ };
607
+ }
608
+ if (n8nRequest.body) {
609
+ axiosRequest.data = n8nRequest.body;
610
+ // Let's add some useful header standards here.
611
+ const existingContentTypeHeaderKey = axiosRequest.headers ? searchForHeader(axiosRequest.headers, 'content-type') : undefined;
612
+ if (existingContentTypeHeaderKey === undefined) {
613
+ // We are only setting content type headers if the user did
614
+ // not set it already manually. We're not overriding, even if it's wrong.
615
+ if (axiosRequest.data instanceof FormData) {
616
+ axiosRequest.headers = axiosRequest.headers || {};
617
+ axiosRequest.headers['Content-Type'] = 'multipart/form-data';
618
+ }
619
+ else if (axiosRequest.data instanceof url_1.URLSearchParams) {
620
+ axiosRequest.headers = axiosRequest.headers || {};
621
+ axiosRequest.headers['Content-Type'] = 'application/x-www-form-urlencoded';
622
+ }
623
+ }
624
+ }
625
+ if (n8nRequest.json) {
626
+ const key = axiosRequest.headers ? searchForHeader(axiosRequest.headers, 'accept') : undefined;
627
+ // If key exists, then the user has set both accept
628
+ // header and the json flag. Header should take precedence.
629
+ if (!key) {
630
+ axiosRequest.headers = axiosRequest.headers || {};
631
+ axiosRequest.headers.Accept = 'application/json';
632
+ }
633
+ }
634
+ const userAgentHeader = axiosRequest.headers ? searchForHeader(axiosRequest.headers, 'user-agent') : undefined;
635
+ // If key exists, then the user has set both accept
636
+ // header and the json flag. Header should take precedence.
637
+ if (!userAgentHeader) {
638
+ axiosRequest.headers = axiosRequest.headers || {};
639
+ axiosRequest.headers['User-Agent'] = 'n8n';
640
+ }
641
+ if (n8nRequest.ignoreHttpStatusErrors) {
642
+ axiosRequest.validateStatus = () => true;
643
+ }
644
+ return axiosRequest;
645
+ }
646
+ function httpRequest(requestOptions) {
647
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
648
+ const axiosRequest = convertN8nRequestToAxios(requestOptions);
649
+ const result = yield (0, axios_1.default)(axiosRequest);
650
+ if (requestOptions.returnFullResponse) {
651
+ return {
652
+ body: result.data,
653
+ headers: result.headers,
654
+ statusCode: result.status,
655
+ statusMessage: result.statusText,
656
+ };
657
+ }
658
+ return result.data;
659
+ });
660
+ }
661
+ /**
662
+ * Returns binary data buffer for given item index and property name.
663
+ *
664
+ * @export
665
+ * @param {ITaskDataConnections} inputData
666
+ * @param {number} itemIndex
667
+ * @param {string} propertyName
668
+ * @param {number} inputIndex
669
+ * @returns {Promise<Buffer>}
670
+ */
671
+ function getBinaryDataBuffer(inputData, itemIndex, propertyName, inputIndex) {
672
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
673
+ const binaryData = inputData['main'][inputIndex][itemIndex].binary[propertyName];
674
+ return BinaryDataManager_1.BinaryDataManager.getInstance().retrieveBinaryData(binaryData);
675
+ });
676
+ }
677
+ /**
678
+ * Takes a buffer and converts it into the format n8n uses. It encodes the binary data as
679
+ * base64 and adds metadata.
680
+ *
681
+ * @export
682
+ * @param {Buffer} binaryData
683
+ * @param {string} [filePath]
684
+ * @param {string} [mimeType]
685
+ * @returns {Promise<IBinaryData>}
686
+ */
687
+ function prepareBinaryData(binaryData, executionId, filePath, mimeType) {
688
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
689
+ if (!mimeType) {
690
+ // If no mime type is given figure it out
691
+ if (filePath) {
692
+ // Use file path to guess mime type
693
+ const mimeTypeLookup = (0, mime_types_1.lookup)(filePath);
694
+ if (mimeTypeLookup) {
695
+ mimeType = mimeTypeLookup;
696
+ }
697
+ }
698
+ if (!mimeType) {
699
+ // Use buffer to guess mime type
700
+ const fileTypeData = yield (0, file_type_1.fromBuffer)(binaryData);
701
+ if (fileTypeData) {
702
+ mimeType = fileTypeData.mime;
703
+ }
704
+ }
705
+ if (!mimeType) {
706
+ // Fall back to text
707
+ mimeType = 'text/plain';
708
+ }
709
+ }
710
+ const returnData = {
711
+ mimeType,
712
+ data: '',
713
+ };
714
+ if (filePath) {
715
+ if (filePath.includes('?')) {
716
+ // Remove maybe present query parameters
717
+ filePath = filePath.split('?').shift();
718
+ }
719
+ const filePathParts = path.parse(filePath);
720
+ if (filePathParts.dir !== '') {
721
+ returnData.directory = filePathParts.dir;
722
+ }
723
+ returnData.fileName = filePathParts.base;
724
+ // Remove the dot
725
+ const fileExtension = filePathParts.ext.slice(1);
726
+ if (fileExtension) {
727
+ returnData.fileExtension = fileExtension;
728
+ }
729
+ }
730
+ return BinaryDataManager_1.BinaryDataManager.getInstance().storeBinaryData(returnData, binaryData, executionId);
731
+ });
732
+ }
733
+ function getCurrentOAuth2AccessToken(credentialsType, node, additionalData, oAuth2Options) {
734
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
735
+ var _a, _b, _c, _d, _e, _f;
736
+ const credentials = yield this.getCredentials(credentialsType);
737
+ if (!credentials) {
738
+ throw new workflow_1.NodeOperationError(node, `No credentials of type "${credentialsType}" were returned!`, { description: 'Credentials not found' });
739
+ }
740
+ const clientId = credentials['clientId'];
741
+ const clientSecret = credentials['clientSecret'];
742
+ const scope = credentials['scope'];
743
+ const grantType = credentials['grantType'];
744
+ const authUrl = credentials['authUrl'];
745
+ const accessTokenUrl = credentials['accessTokenUrl'];
746
+ const httpAgent = credentials['httpAgent'];
747
+ const oauthTokenData = ((_a = credentials['oauthTokenData']) !== null && _a !== void 0 ? _a : {});
748
+ let accessToken = ((_b = oauthTokenData === null || oauthTokenData === void 0 ? void 0 : oauthTokenData['accessToken']) !== null && _b !== void 0 ? _b : "");
749
+ let refreshToken = ((_c = oauthTokenData === null || oauthTokenData === void 0 ? void 0 : oauthTokenData['refreshToken']) !== null && _c !== void 0 ? _c : "");
750
+ let expiresAt = ((_d = oauthTokenData === null || oauthTokenData === void 0 ? void 0 : oauthTokenData['expiresAt']) !== null && _d !== void 0 ? _d : "");
751
+ let expiresIn = ((_e = oauthTokenData === null || oauthTokenData === void 0 ? void 0 : oauthTokenData['expiresIn']) !== null && _e !== void 0 ? _e : 0);
752
+ let tokenType = ((_f = oauthTokenData === null || oauthTokenData === void 0 ? void 0 : oauthTokenData['tokenType']) !== null && _f !== void 0 ? _f : "");
753
+ const isExpired = !accessToken || !expiresAt || new Date(expiresAt).getTime() <= Date.now();
754
+ if (isExpired) {
755
+ workflow_1.LoggerProxy.debug(`Node "${node.name}" is using credential "${credentialsType}", however the access token has expired. This will now be refreshed using the "${grantType}" flow.`);
756
+ if (!authUrl) {
757
+ throw new workflow_1.NodeOperationError(node, `The "authUrl" property is required for the "${grantType}" flow. Please check your credentials configuration.`, { description: 'Missing authUrl' });
758
+ }
759
+ const config = {
760
+ client: { id: clientId, secret: clientSecret },
761
+ auth: { tokenHost: authUrl, tokenPath: accessTokenUrl },
762
+ http: { agent: httpAgent },
763
+ };
764
+ if (grantType === 'authorizationCode') {
765
+ const client = new simple_oauth2_1.AuthorizationCode(config);
766
+ let token = client.createToken({
767
+ access_token: (0, lodash_1.get)(oauthTokenData, oAuth2Options === null || oAuth2Options === void 0 ? void 0 : oAuth2Options.property) || accessToken,
768
+ refresh_token: refreshToken,
769
+ token_type: (oAuth2Options === null || oAuth2Options === void 0 ? void 0 : oAuth2Options.tokenType) || tokenType || 'Bearer',
770
+ expires_at: expiresAt,
771
+ expires_in: expiresIn,
772
+ });
773
+ const refreshOptions = (oAuth2Options === null || oAuth2Options === void 0 ? void 0 : oAuth2Options.includeCredentialsOnRefreshOnBody) ? {
774
+ body: {
775
+ client_id: clientId,
776
+ client_secret: clientSecret,
777
+ },
778
+ headers: {
779
+ Authorization: '', // override default basic auth
780
+ },
781
+ } : {};
782
+ token = yield token.refresh(refreshOptions);
783
+ accessToken = token.token['access_token'];
784
+ refreshToken = token.token['refresh_token'] || refreshToken;
785
+ expiresAt = token.token['expires_at'];
786
+ expiresIn = token.token['expires_in'];
787
+ tokenType = token.token['token_type'] || 'Bearer';
788
+ }
789
+ else if (grantType === 'clientCredentials') {
790
+ const client = new simple_oauth2_1.ClientCredentials(config);
791
+ const token = yield client.getToken({ scope });
792
+ accessToken = token.token['access_token'];
793
+ refreshToken = token.token['refresh_token'] || refreshToken;
794
+ expiresAt = token.token['expires_at'];
795
+ expiresIn = token.token['expires_in'];
796
+ tokenType = token.token['token_type'] || 'Bearer';
797
+ }
798
+ else {
799
+ throw new Error(`Unsupported grant type "${grantType}" for Microsoft Graph API`);
800
+ }
801
+ oauthTokenData["accessToken"] = accessToken;
802
+ oauthTokenData["refreshToken"] = refreshToken;
803
+ oauthTokenData["expiresAt"] = expiresAt;
804
+ oauthTokenData["expiresIn"] = expiresIn;
805
+ oauthTokenData["tokenType"] = tokenType;
806
+ if (!node.credentials || !node.credentials[credentialsType]) {
807
+ throw new Error(`Node "${node.name}" has no credentials of type "${credentialsType}"`);
808
+ }
809
+ yield additionalData.credentialsHelper.updateCredentials(node.credentials[credentialsType], credentialsType, credentials);
810
+ workflow_1.LoggerProxy.debug(`Access token for credential "${credentialsType}" has been refreshed.`);
811
+ }
812
+ return accessToken;
813
+ });
814
+ }
815
+ function requestOAuth2(credentialsType_1, requestOptions_1, node_1, additionalData_1, oAuth2Options_1) {
816
+ return tslib_1.__awaiter(this, arguments, void 0, function* (credentialsType, requestOptions, node, additionalData, oAuth2Options, isN8nRequest = false) {
817
+ var _a;
818
+ const credentials = (yield this.getCredentials(credentialsType));
819
+ if (!credentials) {
820
+ throw new Error('No credentials were returned!');
821
+ }
822
+ const oauthTokenData = credentials['oauthTokenData'];
823
+ if (!oauthTokenData) {
824
+ throw new Error('OAuth credentials not connected!');
825
+ }
826
+ const config = {
827
+ client: {
828
+ id: credentials['clientId'],
829
+ secret: credentials['clientSecret'],
830
+ },
831
+ auth: {
832
+ tokenHost: credentials['authUrl'],
833
+ tokenPath: credentials['accessTokenUrl'],
834
+ },
835
+ http: {
836
+ agent: credentials['httpAgent'],
837
+ },
838
+ };
839
+ const client = new simple_oauth2_1.AuthorizationCode(config);
840
+ // Construct token from saved data
841
+ const tokenObject = client.createToken({
842
+ access_token: (0, lodash_1.get)(oauthTokenData, oAuth2Options === null || oAuth2Options === void 0 ? void 0 : oAuth2Options.property) || oauthTokenData['accessToken'],
843
+ refresh_token: oauthTokenData['refreshToken'],
844
+ token_type: (oAuth2Options === null || oAuth2Options === void 0 ? void 0 : oAuth2Options.tokenType) || oauthTokenData['tokenType'] || 'Bearer',
845
+ expires_at: oauthTokenData['expiresAt'],
846
+ expires_in: oauthTokenData['expiresIn'],
847
+ });
848
+ const currentToken = tokenObject;
849
+ const signedOptions = Object.assign(Object.assign({}, requestOptions), { headers: Object.assign(Object.assign({}, (requestOptions.headers || {})), { Authorization: `${currentToken.token["token_type"]} ${currentToken.token["access_token"]}` }) });
850
+ // Remove 'Bearer' if `keepBearer` is false
851
+ if ((oAuth2Options === null || oAuth2Options === void 0 ? void 0 : oAuth2Options.keepBearer) === false && signedOptions.headers.Authorization) {
852
+ signedOptions.headers.Authorization = signedOptions.headers.Authorization.split(' ')[1];
853
+ }
854
+ try {
855
+ return yield this.helpers['request'](signedOptions);
856
+ }
857
+ catch (error) {
858
+ const statusCodeReturned = (_a = oAuth2Options === null || oAuth2Options === void 0 ? void 0 : oAuth2Options.tokenExpiredStatusCode) !== null && _a !== void 0 ? _a : 401;
859
+ if (error.statusCode === statusCodeReturned && currentToken.expired()) {
860
+ // Refresh token
861
+ workflow_1.LoggerProxy.debug(`OAuth2 token for "${credentialsType}" used by node "${node.name}" expired. Refreshing...`);
862
+ workflow_1.LoggerProxy.info(`OAuth2 token for "${credentialsType}" used by node "${node.name}" expired. Refreshing...`);
863
+ const refreshOptions = {};
864
+ if (oAuth2Options === null || oAuth2Options === void 0 ? void 0 : oAuth2Options.includeCredentialsOnRefreshOnBody) {
865
+ refreshOptions.body = {
866
+ client_id: credentials['clientId'],
867
+ client_secret: credentials['clientSecret'],
868
+ };
869
+ refreshOptions.headers = {
870
+ Authorization: '', // override default basic auth
871
+ };
872
+ }
873
+ let refreshedToken;
874
+ try {
875
+ refreshedToken = yield currentToken.refresh(refreshOptions);
876
+ }
877
+ catch (error) {
878
+ throw new Error("Failed to refresh token: " + error.message);
879
+ }
880
+ credentials['oauthTokenData'] = {
881
+ accessToken: refreshedToken.token["access_token"],
882
+ refreshToken: refreshedToken.token["refresh_token"] || currentToken.token["refresh_token"],
883
+ expiresAt: refreshedToken.token["expires_at"],
884
+ expiresIn: refreshedToken.token["expires_in"],
885
+ tokenType: refreshedToken.token["token_type"],
886
+ };
887
+ // Persist new token
888
+ if (!node.credentials || !node.credentials[credentialsType]) {
889
+ throw new Error(`Node "${node.name}" has no credentials of type "${credentialsType}"`);
890
+ }
891
+ yield additionalData.credentialsHelper.updateCredentials(node.credentials[credentialsType], credentialsType, credentials);
892
+ workflow_1.LoggerProxy.debug(`OAuth2 token for "${credentialsType}" used by node "${node.name}" has been renewed.`);
893
+ workflow_1.LoggerProxy.info(`OAuth2 token for "${credentialsType}" used by node "${node.name}" has been renewed.`);
894
+ // Retry the original request with the new token
895
+ const retryOptions = Object.assign(Object.assign({}, requestOptions), { headers: Object.assign(Object.assign({}, (requestOptions.headers || {})), { Authorization: `${refreshedToken.token["token_type"]} ${refreshedToken.token["access_token"]}` }) });
896
+ if ((oAuth2Options === null || oAuth2Options === void 0 ? void 0 : oAuth2Options.keepBearer) === false && retryOptions.headers.Authorization) {
897
+ retryOptions.headers.Authorization = retryOptions.headers.Authorization.split(' ')[1];
898
+ }
899
+ return isN8nRequest
900
+ ? this.helpers.httpRequest(retryOptions)
901
+ : this.helpers['request'](retryOptions);
902
+ }
903
+ throw error;
904
+ }
905
+ });
906
+ }
907
+ /* Makes a request using OAuth1 data for authentication
908
+ *
909
+ * @export
910
+ * @param {IAllExecuteFunctions} this
911
+ * @param {string} credentialsType
912
+ * @param {(OptionsWithUrl | requestPromise.RequestPromiseOptions)} requestOptionså
913
+ * @returns
914
+ */
915
+ function requestOAuth1(credentialsType_1, requestOptions_1) {
916
+ return tslib_1.__awaiter(this, arguments, void 0, function* (credentialsType, requestOptions, isN8nRequest = false) {
917
+ const credentials = (yield this.getCredentials(credentialsType));
918
+ if (credentials === undefined) {
919
+ throw new Error('No credentials were returned!');
920
+ }
921
+ if (credentials['oauthTokenData'] === undefined) {
922
+ throw new Error('OAuth credentials not connected!');
923
+ }
924
+ const oauth = new clientOAuth1({
925
+ consumer: {
926
+ key: credentials['consumerKey'],
927
+ secret: credentials['consumerSecret'],
928
+ },
929
+ signature_method: credentials['signatureMethod'],
930
+ hash_function(base, key) {
931
+ const algorithm = credentials['signatureMethod'] === 'HMAC-SHA1' ? 'sha1' : 'sha256';
932
+ return (0, crypto_1.createHmac)(algorithm, key).update(base).digest('base64');
933
+ },
934
+ });
935
+ const oauthTokenData = credentials['oauthTokenData'];
936
+ const token = {
937
+ key: oauthTokenData['oauth_token'],
938
+ secret: oauthTokenData['oauth_token_secret'],
939
+ };
940
+ // @ts-ignore
941
+ requestOptions.data = Object.assign(Object.assign({}, requestOptions.qs), requestOptions.form);
942
+ // Fixes issue that OAuth1 library only works with "url" property and not with "uri"
943
+ // @ts-ignore
944
+ if (requestOptions.uri && !requestOptions.url) {
945
+ // @ts-ignore
946
+ requestOptions.url = requestOptions.uri;
947
+ // @ts-ignore
948
+ delete requestOptions.uri;
949
+ }
950
+ // @ts-ignore
951
+ requestOptions.headers = oauth.toHeader(oauth.authorize(requestOptions, token));
952
+ if (isN8nRequest) {
953
+ return this.helpers.httpRequest(requestOptions);
954
+ }
955
+ return this.helpers['request'](requestOptions).catch((error) => tslib_1.__awaiter(this, void 0, void 0, function* () {
956
+ // Unknown error so simply throw it
957
+ throw error;
958
+ }));
959
+ });
960
+ }
961
+ function httpRequestWithAuthentication(credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions) {
962
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
963
+ try {
964
+ const parentTypes = additionalData.credentialsHelper.getParentTypes(credentialsType);
965
+ if (parentTypes.includes('oAuth1Api')) {
966
+ return yield requestOAuth1.call(this, credentialsType, requestOptions, true);
967
+ }
968
+ if (parentTypes.includes('oAuth2Api')) {
969
+ return yield requestOAuth2.call(this, credentialsType, requestOptions, node, additionalData, additionalCredentialOptions === null || additionalCredentialOptions === void 0 ? void 0 : additionalCredentialOptions.oauth2, true);
970
+ }
971
+ let credentialsDecrypted;
972
+ if (additionalCredentialOptions === null || additionalCredentialOptions === void 0 ? void 0 : additionalCredentialOptions.credentialsDecrypted) {
973
+ credentialsDecrypted = additionalCredentialOptions.credentialsDecrypted.data;
974
+ }
975
+ else {
976
+ credentialsDecrypted = yield this.getCredentials(credentialsType);
977
+ }
978
+ if (credentialsDecrypted === undefined) {
979
+ throw new workflow_1.NodeOperationError(node, `Node "${node.name}" does not have any credentials of type "${credentialsType}" set!`);
980
+ }
981
+ requestOptions = yield additionalData.credentialsHelper.authenticate(credentialsDecrypted, credentialsType, requestOptions, workflow, node);
982
+ return yield httpRequest(requestOptions);
983
+ }
984
+ catch (error) {
985
+ throw new workflow_1.NodeApiError(this.getNode(), error);
986
+ }
987
+ });
988
+ }
989
+ /**
990
+ * Takes generic input data and brings it into the json format n8n uses.
991
+ *
992
+ * @export
993
+ * @param {(IDataObject | IDataObject[])} jsonData
994
+ * @returns {INodeExecutionData[]}
995
+ */
996
+ function returnJsonArray(jsonData) {
997
+ const returnData = [];
998
+ if (!Array.isArray(jsonData)) {
999
+ jsonData = [jsonData];
1000
+ }
1001
+ jsonData.forEach((data) => {
1002
+ returnData.push({ json: data });
1003
+ });
1004
+ return returnData;
1005
+ }
1006
+ /**
1007
+ * Automatically put the objects under a 'json' key and don't error,
1008
+ * if some objects contain json/binary keys and others don't, throws error 'Inconsistent item format'
1009
+ *
1010
+ * @export
1011
+ * @param {INodeExecutionData | INodeExecutionData[]} executionData
1012
+ * @returns {INodeExecutionData[]}
1013
+ */
1014
+ function normalizeItems(executionData) {
1015
+ if (typeof executionData === 'object' && !Array.isArray(executionData))
1016
+ executionData = [{ json: executionData }];
1017
+ if (executionData.every((item) => typeof item === 'object' && 'json' in item))
1018
+ return executionData;
1019
+ if (executionData.some((item) => typeof item === 'object' && 'json' in item)) {
1020
+ throw new Error('Inconsistent item format');
1021
+ }
1022
+ if (executionData.every((item) => typeof item === 'object' && 'binary' in item)) {
1023
+ const normalizedItems = [];
1024
+ executionData.forEach((item) => {
1025
+ const json = Object.keys(item).reduce((acc, key) => {
1026
+ if (key === 'binary')
1027
+ return acc;
1028
+ return Object.assign(Object.assign({}, acc), { [key]: item[key] });
1029
+ }, {});
1030
+ normalizedItems.push({
1031
+ json,
1032
+ binary: item.binary,
1033
+ });
1034
+ });
1035
+ return normalizedItems;
1036
+ }
1037
+ if (executionData.some((item) => typeof item === 'object' && 'binary' in item)) {
1038
+ throw new Error('Inconsistent item format');
1039
+ }
1040
+ return executionData.map((item) => {
1041
+ return { json: item };
1042
+ });
1043
+ }
1044
+ // TODO: Move up later
1045
+ function requestWithAuthentication(credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions) {
1046
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1047
+ try {
1048
+ const parentTypes = additionalData.credentialsHelper.getParentTypes(credentialsType);
1049
+ if (parentTypes.includes('oAuth1Api')) {
1050
+ return yield requestOAuth1.call(this, credentialsType, requestOptions, false);
1051
+ }
1052
+ if (parentTypes.includes('oAuth2Api')) {
1053
+ return yield requestOAuth2.call(this, credentialsType, requestOptions, node, additionalData, additionalCredentialOptions === null || additionalCredentialOptions === void 0 ? void 0 : additionalCredentialOptions.oauth2, false);
1054
+ }
1055
+ let credentialsDecrypted;
1056
+ if (additionalCredentialOptions === null || additionalCredentialOptions === void 0 ? void 0 : additionalCredentialOptions.credentialsDecrypted) {
1057
+ credentialsDecrypted = additionalCredentialOptions.credentialsDecrypted.data;
1058
+ }
1059
+ else {
1060
+ credentialsDecrypted = yield this.getCredentials(credentialsType);
1061
+ }
1062
+ if (credentialsDecrypted === undefined) {
1063
+ throw new workflow_1.NodeOperationError(node, `Node "${node.name}" does not have any credentials of type "${credentialsType}" set!`);
1064
+ }
1065
+ requestOptions = yield additionalData.credentialsHelper.authenticate(credentialsDecrypted, credentialsType, requestOptions, workflow, node);
1066
+ return yield proxyRequestToAxios(requestOptions);
1067
+ }
1068
+ catch (error) {
1069
+ throw new workflow_1.NodeApiError(this.getNode(), error);
1070
+ }
1071
+ });
1072
+ }
1073
+ /**
1074
+ * Returns the additional keys for Expressions and Function-Nodes
1075
+ *
1076
+ * @export
1077
+ * @param {IWorkflowExecuteAdditionalData} additionalData
1078
+ * @returns {(IWorkflowDataProxyAdditionalKeys)}
1079
+ */
1080
+ function getAdditionalKeys(additionalData) {
1081
+ const executionId = additionalData.executionId || __1.PLACEHOLDER_EMPTY_EXECUTION_ID;
1082
+ return {
1083
+ $executionId: executionId,
1084
+ $resumeWebhookUrl: `${additionalData.webhookWaitingBaseUrl}/${executionId}`,
1085
+ };
1086
+ }
1087
+ /**
1088
+ * Returns the requested decrypted credentials if the node has access to them.
1089
+ *
1090
+ * @export
1091
+ * @param {Workflow} workflow Workflow which requests the data
1092
+ * @param {INode} node Node which request the data
1093
+ * @param {string} type The credential type to return
1094
+ * @param {IWorkflowExecuteAdditionalData} additionalData
1095
+ * @returns {(ICredentialDataDecryptedObject | undefined)}
1096
+ */
1097
+ function getCredentials(workflow, node, type, additionalData, mode, runExecutionData, runIndex, connectionInputData, itemIndex) {
1098
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1099
+ // Get the NodeType as it has the information if the credentials are required
1100
+ const nodeType = workflow.nodeTypes.getByNameAndVersion(node.type, node.typeVersion);
1101
+ if (nodeType === undefined) {
1102
+ throw new workflow_1.NodeOperationError(node, `Node type "${node.type}" is not known so can not get credentials!`);
1103
+ }
1104
+ // Hardcode for now for security reasons that only a single node can access
1105
+ // all credentials
1106
+ const fullAccess = ['n8n-nodes-base.httpRequest'].includes(node.type);
1107
+ let nodeCredentialDescription;
1108
+ if (!fullAccess) {
1109
+ if (nodeType.description.credentials === undefined) {
1110
+ throw new workflow_1.NodeOperationError(node, `Node type "${node.type}" does not have any credentials defined!`);
1111
+ }
1112
+ nodeCredentialDescription = nodeType.description.credentials.find((credentialTypeDescription) => credentialTypeDescription.name === type);
1113
+ if (nodeCredentialDescription === undefined) {
1114
+ throw new workflow_1.NodeOperationError(node, `Node type "${node.type}" does not have any credentials of type "${type}" defined!`);
1115
+ }
1116
+ if (!workflow_1.NodeHelpers.displayParameter(additionalData.currentNodeParameters || node.parameters, nodeCredentialDescription, node.parameters)) {
1117
+ // Credentials should not be displayed so return undefined even if they would be defined
1118
+ return undefined;
1119
+ }
1120
+ }
1121
+ // Check if node has any credentials defined
1122
+ if (!fullAccess && (!node.credentials || !node.credentials[type])) {
1123
+ // If none are defined check if the credentials are required or not
1124
+ if ((nodeCredentialDescription === null || nodeCredentialDescription === void 0 ? void 0 : nodeCredentialDescription.required) === true) {
1125
+ // Credentials are required so error
1126
+ if (!node.credentials) {
1127
+ throw new workflow_1.NodeOperationError(node, 'Node does not have any credentials set!');
1128
+ }
1129
+ if (!node.credentials[type]) {
1130
+ throw new workflow_1.NodeOperationError(node, `Node does not have any credentials set for "${type}"!`);
1131
+ }
1132
+ }
1133
+ else {
1134
+ // Credentials are not required so resolve with undefined
1135
+ return undefined;
1136
+ }
1137
+ }
1138
+ if (fullAccess && (!node.credentials || !node.credentials[type])) {
1139
+ // Make sure that fullAccess nodes still behave like before that if they
1140
+ // request access to credentials that are currently not set it returns undefined
1141
+ return undefined;
1142
+ }
1143
+ let expressionResolveValues;
1144
+ if (connectionInputData && runExecutionData && runIndex !== undefined) {
1145
+ expressionResolveValues = {
1146
+ connectionInputData,
1147
+ itemIndex: itemIndex || 0,
1148
+ node,
1149
+ runExecutionData,
1150
+ runIndex,
1151
+ workflow,
1152
+ };
1153
+ }
1154
+ const nodeCredentials = node.credentials
1155
+ ? node.credentials[type]
1156
+ : {};
1157
+ // TODO: solve using credentials via expression
1158
+ // if (name.charAt(0) === '=') {
1159
+ // // If the credential name is an expression resolve it
1160
+ // const additionalKeys = getAdditionalKeys(additionalData);
1161
+ // name = workflow.expression.getParameterValue(
1162
+ // name,
1163
+ // runExecutionData || null,
1164
+ // runIndex || 0,
1165
+ // itemIndex || 0,
1166
+ // node.name,
1167
+ // connectionInputData || [],
1168
+ // mode,
1169
+ // additionalKeys,
1170
+ // ) as string;
1171
+ // }
1172
+ const decryptedDataObject = yield additionalData.credentialsHelper.getDecrypted(nodeCredentials, type, mode, false, expressionResolveValues);
1173
+ return decryptedDataObject;
1174
+ });
1175
+ }
1176
+ /**
1177
+ * Returns a copy of the node
1178
+ *
1179
+ * @export
1180
+ * @param {INode} node
1181
+ * @returns {INode}
1182
+ */
1183
+ function getNode(node) {
1184
+ return JSON.parse(JSON.stringify(node));
1185
+ }
1186
+ /**
1187
+ * Returns the requested resolved (all expressions replaced) node parameters.
1188
+ *
1189
+ * @export
1190
+ * @param {Workflow} workflow
1191
+ * @param {(IRunExecutionData | null)} runExecutionData
1192
+ * @param {number} runIndex
1193
+ * @param {INodeExecutionData[]} connectionInputData
1194
+ * @param {INode} node
1195
+ * @param {string} parameterName
1196
+ * @param {number} itemIndex
1197
+ * @param {*} [fallbackValue]
1198
+ * @returns {(NodeParameterValue | INodeParameters | NodeParameterValue[] | INodeParameters[] | object)}
1199
+ */
1200
+ function getNodeParameter(workflow, runExecutionData, runIndex, connectionInputData, node, parameterName, itemIndex, mode, additionalKeys, fallbackValue) {
1201
+ const nodeType = workflow.nodeTypes.getByNameAndVersion(node.type, node.typeVersion);
1202
+ if (nodeType === undefined) {
1203
+ throw new Error(`Node type "${node.type}" is not known so can not return paramter value!`);
1204
+ }
1205
+ const value = (0, lodash_1.get)(node.parameters, parameterName, fallbackValue);
1206
+ if (value === undefined) {
1207
+ throw new Error(`Could not get parameter "${parameterName}"!`);
1208
+ }
1209
+ let returnData;
1210
+ try {
1211
+ returnData = workflow.expression.getParameterValue(value, runExecutionData, runIndex, itemIndex, node.name, connectionInputData, mode, additionalKeys);
1212
+ }
1213
+ catch (e) {
1214
+ e.message += ` [Error in parameter: "${parameterName}"]`;
1215
+ throw e;
1216
+ }
1217
+ return returnData;
1218
+ }
1219
+ /**
1220
+ * Returns if execution should be continued even if there was an error.
1221
+ *
1222
+ * @export
1223
+ * @param {INode} node
1224
+ * @returns {boolean}
1225
+ */
1226
+ function continueOnFail(node) {
1227
+ return (0, lodash_1.get)(node, 'continueOnFail', false);
1228
+ }
1229
+ /**
1230
+ * Returns the webhook URL of the webhook with the given name
1231
+ *
1232
+ * @export
1233
+ * @param {string} name
1234
+ * @param {Workflow} workflow
1235
+ * @param {INode} node
1236
+ * @param {IWorkflowExecuteAdditionalData} additionalData
1237
+ * @param {boolean} [isTest]
1238
+ * @returns {(string | undefined)}
1239
+ */
1240
+ function getNodeWebhookUrl(name, workflow, node, additionalData, mode, additionalKeys, isTest) {
1241
+ let baseUrl = additionalData.webhookBaseUrl;
1242
+ if (isTest === true) {
1243
+ baseUrl = additionalData.webhookTestBaseUrl;
1244
+ }
1245
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
1246
+ const webhookDescription = getWebhookDescription(name, workflow, node);
1247
+ if (webhookDescription === undefined) {
1248
+ return undefined;
1249
+ }
1250
+ const path = workflow.expression.getSimpleParameterValue(node, webhookDescription.path, mode, additionalKeys);
1251
+ if (path === undefined) {
1252
+ return undefined;
1253
+ }
1254
+ const isFullPath = workflow.expression.getSimpleParameterValue(node, webhookDescription.isFullPath, mode, additionalKeys, false);
1255
+ return workflow_1.NodeHelpers.getNodeWebhookUrl(baseUrl, workflow.id, node, path.toString(), isFullPath);
1256
+ }
1257
+ /**
1258
+ * Returns the timezone for the workflow
1259
+ *
1260
+ * @export
1261
+ * @param {Workflow} workflow
1262
+ * @param {IWorkflowExecuteAdditionalData} additionalData
1263
+ * @returns {string}
1264
+ */
1265
+ function getTimezone(workflow, additionalData) {
1266
+ // eslint-disable-next-line @typescript-eslint/prefer-optional-chain
1267
+ if (workflow.settings !== undefined && workflow.settings['timezone'] !== undefined) {
1268
+ return workflow.settings.timezone;
1269
+ }
1270
+ return additionalData.timezone;
1271
+ }
1272
+ /**
1273
+ * Returns the full webhook description of the webhook with the given name
1274
+ *
1275
+ * @export
1276
+ * @param {string} name
1277
+ * @param {Workflow} workflow
1278
+ * @param {INode} node
1279
+ * @returns {(IWebhookDescription | undefined)}
1280
+ */
1281
+ function getWebhookDescription(name, workflow, node) {
1282
+ const nodeType = workflow.nodeTypes.getByNameAndVersion(node.type, node.typeVersion);
1283
+ if (nodeType.description.webhooks === undefined) {
1284
+ // Node does not have any webhooks so return
1285
+ return undefined;
1286
+ }
1287
+ // eslint-disable-next-line no-restricted-syntax
1288
+ for (const webhookDescription of nodeType.description.webhooks) {
1289
+ if (webhookDescription.name === name) {
1290
+ return webhookDescription;
1291
+ }
1292
+ }
1293
+ return undefined;
1294
+ }
1295
+ /**
1296
+ * Returns the workflow metadata
1297
+ *
1298
+ * @export
1299
+ * @param {Workflow} workflow
1300
+ * @returns {IWorkflowMetadata}
1301
+ */
1302
+ function getWorkflowMetadata(workflow) {
1303
+ return {
1304
+ id: workflow.id,
1305
+ name: workflow.name,
1306
+ active: workflow.active,
1307
+ };
1308
+ }
1309
+ /**
1310
+ * Returns the execute functions the poll nodes have access to.
1311
+ *
1312
+ * @export
1313
+ * @param {Workflow} workflow
1314
+ * @param {INode} node
1315
+ * @param {IWorkflowExecuteAdditionalData} additionalData
1316
+ * @param {WorkflowExecuteMode} mode
1317
+ * @returns {ITriggerFunctions}
1318
+ */
1319
+ // TODO: Check if I can get rid of: additionalData, and so then maybe also at ActiveWorkflowRunner.add
1320
+ function getExecutePollFunctions(workflow, node, additionalData, mode, activation) {
1321
+ return ((workflow, node) => {
1322
+ return {
1323
+ __emit: (data) => {
1324
+ throw new Error('Overwrite NodeExecuteFunctions.getExecutePullFunctions.__emit function!');
1325
+ },
1326
+ getCredentials(type) {
1327
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1328
+ return getCredentials(workflow, node, type, additionalData, mode);
1329
+ });
1330
+ },
1331
+ getMode: () => {
1332
+ return mode;
1333
+ },
1334
+ getActivationMode: () => {
1335
+ return activation;
1336
+ },
1337
+ getNode: () => {
1338
+ return getNode(node);
1339
+ },
1340
+ getNodeParameter: (parameterName, fallbackValue) => {
1341
+ const runExecutionData = null;
1342
+ const itemIndex = 0;
1343
+ const runIndex = 0;
1344
+ const connectionInputData = [];
1345
+ return getNodeParameter(workflow, runExecutionData, runIndex, connectionInputData, node, parameterName, itemIndex, mode, getAdditionalKeys(additionalData), fallbackValue);
1346
+ },
1347
+ getRestApiUrl: () => {
1348
+ return additionalData.restApiUrl;
1349
+ },
1350
+ getTimezone: () => {
1351
+ return getTimezone(workflow, additionalData);
1352
+ },
1353
+ getWorkflow: () => {
1354
+ return getWorkflowMetadata(workflow);
1355
+ },
1356
+ getWorkflowStaticData(type) {
1357
+ return workflow.getStaticData(type, node);
1358
+ },
1359
+ helpers: {
1360
+ httpRequest,
1361
+ prepareBinaryData(binaryData, filePath, mimeType) {
1362
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1363
+ return prepareBinaryData.call(this, binaryData, additionalData.executionId, filePath, mimeType);
1364
+ });
1365
+ },
1366
+ request: proxyRequestToAxios,
1367
+ requestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1368
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1369
+ return requestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1370
+ });
1371
+ },
1372
+ requestOAuth2(credentialsType, requestOptions, oAuth2Options) {
1373
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1374
+ return requestOAuth2.call(this, credentialsType, requestOptions, node, additionalData, oAuth2Options);
1375
+ });
1376
+ },
1377
+ getCurrentOAuth2AccessToken(credentialsType, oAuth2Options) {
1378
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1379
+ return getCurrentOAuth2AccessToken.call(this, credentialsType, node, additionalData, oAuth2Options);
1380
+ });
1381
+ },
1382
+ requestOAuth1(credentialsType, requestOptions) {
1383
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1384
+ return requestOAuth1.call(this, credentialsType, requestOptions);
1385
+ });
1386
+ },
1387
+ httpRequestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1388
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1389
+ return httpRequestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1390
+ });
1391
+ },
1392
+ returnJsonArray,
1393
+ },
1394
+ };
1395
+ })(workflow, node);
1396
+ }
1397
+ /**
1398
+ * Returns the execute functions the trigger nodes have access to.
1399
+ *
1400
+ * @export
1401
+ * @param {Workflow} workflow
1402
+ * @param {INode} node
1403
+ * @param {IWorkflowExecuteAdditionalData} additionalData
1404
+ * @param {WorkflowExecuteMode} mode
1405
+ * @returns {ITriggerFunctions}
1406
+ */
1407
+ // TODO: Check if I can get rid of: additionalData, and so then maybe also at ActiveWorkflowRunner.add
1408
+ function getExecuteTriggerFunctions(workflow, node, additionalData, mode, activation) {
1409
+ return ((workflow, node) => {
1410
+ return {
1411
+ emit: (data) => {
1412
+ throw new Error('Overwrite NodeExecuteFunctions.getExecuteTriggerFunctions.emit function!');
1413
+ },
1414
+ getCredentials(type) {
1415
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1416
+ return getCredentials(workflow, node, type, additionalData, mode);
1417
+ });
1418
+ },
1419
+ getNode: () => {
1420
+ return getNode(node);
1421
+ },
1422
+ getMode: () => {
1423
+ return mode;
1424
+ },
1425
+ getActivationMode: () => {
1426
+ return activation;
1427
+ },
1428
+ getNodeParameter: (parameterName, fallbackValue) => {
1429
+ const runExecutionData = null;
1430
+ const itemIndex = 0;
1431
+ const runIndex = 0;
1432
+ const connectionInputData = [];
1433
+ return getNodeParameter(workflow, runExecutionData, runIndex, connectionInputData, node, parameterName, itemIndex, mode, getAdditionalKeys(additionalData), fallbackValue);
1434
+ },
1435
+ getRestApiUrl: () => {
1436
+ return additionalData.restApiUrl;
1437
+ },
1438
+ getTimezone: () => {
1439
+ return getTimezone(workflow, additionalData);
1440
+ },
1441
+ getWorkflow: () => {
1442
+ return getWorkflowMetadata(workflow);
1443
+ },
1444
+ getWorkflowStaticData(type) {
1445
+ return workflow.getStaticData(type, node);
1446
+ },
1447
+ helpers: {
1448
+ httpRequest,
1449
+ requestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1450
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1451
+ return requestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1452
+ });
1453
+ },
1454
+ prepareBinaryData(binaryData, filePath, mimeType) {
1455
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1456
+ return prepareBinaryData.call(this, binaryData, additionalData.executionId, filePath, mimeType);
1457
+ });
1458
+ },
1459
+ request: proxyRequestToAxios,
1460
+ requestOAuth2(credentialsType, requestOptions, oAuth2Options) {
1461
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1462
+ return requestOAuth2.call(this, credentialsType, requestOptions, node, additionalData, oAuth2Options);
1463
+ });
1464
+ },
1465
+ requestOAuth1(credentialsType, requestOptions) {
1466
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1467
+ return requestOAuth1.call(this, credentialsType, requestOptions);
1468
+ });
1469
+ },
1470
+ httpRequestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1471
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1472
+ return httpRequestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1473
+ });
1474
+ },
1475
+ returnJsonArray,
1476
+ },
1477
+ };
1478
+ })(workflow, node);
1479
+ }
1480
+ /**
1481
+ * Returns the execute functions regular nodes have access to.
1482
+ *
1483
+ * @export
1484
+ * @param {Workflow} workflow
1485
+ * @param {IRunExecutionData} runExecutionData
1486
+ * @param {number} runIndex
1487
+ * @param {INodeExecutionData[]} connectionInputData
1488
+ * @param {ITaskDataConnections} inputData
1489
+ * @param {INode} node
1490
+ * @param {IWorkflowExecuteAdditionalData} additionalData
1491
+ * @param {WorkflowExecuteMode} mode
1492
+ * @returns {IExecuteFunctions}
1493
+ */
1494
+ function getExecuteFunctions(workflow, runExecutionData, runIndex, connectionInputData, inputData, node, additionalData, mode, nodeTypeData, closeFunctions) {
1495
+ return ((workflow, runExecutionData, connectionInputData, inputData, node, nodeTypeData, closeFunctions) => {
1496
+ return {
1497
+ continueOnFail: () => {
1498
+ return continueOnFail(node);
1499
+ },
1500
+ evaluateExpression: (expression, itemIndex) => {
1501
+ return workflow.expression.resolveSimpleParameterValue(`=${expression}`, {}, runExecutionData, runIndex, itemIndex, node.name, connectionInputData, mode, getAdditionalKeys(additionalData));
1502
+ },
1503
+ executeWorkflow(workflowInfo, inputData) {
1504
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1505
+ return additionalData
1506
+ .executeWorkflow(workflowInfo, additionalData, inputData)
1507
+ .then((result) => tslib_1.__awaiter(this, void 0, void 0, function* () {
1508
+ return BinaryDataManager_1.BinaryDataManager.getInstance().duplicateBinaryData(result, additionalData.executionId);
1509
+ }));
1510
+ });
1511
+ },
1512
+ getContext(type) {
1513
+ return workflow_1.NodeHelpers.getContext(runExecutionData, type, node);
1514
+ },
1515
+ getCredentials(type, itemIndex) {
1516
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1517
+ return getCredentials(workflow, node, type, additionalData, mode, runExecutionData, runIndex, connectionInputData, itemIndex);
1518
+ });
1519
+ },
1520
+ getExecutionId: () => {
1521
+ return additionalData.executionId;
1522
+ },
1523
+ getInputData: (inputIndex = 0, inputName = 'main') => {
1524
+ if (!Object.prototype.hasOwnProperty.call(inputData, inputName)) {
1525
+ // Return empty array because else it would throw error when nothing is connected to input
1526
+ return [];
1527
+ }
1528
+ // TODO: Check if nodeType has input with that index defined
1529
+ if (inputData[inputName].length < inputIndex) {
1530
+ throw new Error(`Could not get input index "${inputIndex}" of input "${inputName}"!`);
1531
+ }
1532
+ if (inputData[inputName][inputIndex] === null) {
1533
+ // return [];
1534
+ throw new Error(`Value "${inputIndex}" of input "${inputName}" did not get set!`);
1535
+ }
1536
+ return inputData[inputName][inputIndex];
1537
+ },
1538
+ getNodeParameter: (parameterName, itemIndex, fallbackValue) => {
1539
+ return getNodeParameter(workflow, runExecutionData, runIndex, connectionInputData, node, parameterName, itemIndex, mode, getAdditionalKeys(additionalData), fallbackValue);
1540
+ },
1541
+ getMode: () => {
1542
+ return mode;
1543
+ },
1544
+ getNode: () => {
1545
+ return getNode(node);
1546
+ },
1547
+ getRestApiUrl: () => {
1548
+ return additionalData.restApiUrl;
1549
+ },
1550
+ getTimezone: () => {
1551
+ return getTimezone(workflow, additionalData);
1552
+ },
1553
+ getWorkflow: () => {
1554
+ return getWorkflowMetadata(workflow);
1555
+ },
1556
+ getWorkflowDataProxy: (itemIndex) => {
1557
+ const dataProxy = new workflow_1.WorkflowDataProxy(workflow, runExecutionData, runIndex, itemIndex, node.name, connectionInputData, {}, mode, getAdditionalKeys(additionalData));
1558
+ return dataProxy.getDataProxy();
1559
+ },
1560
+ getWorkflowStaticData(type) {
1561
+ return workflow.getStaticData(type, node);
1562
+ },
1563
+ prepareOutputData: workflow_1.NodeHelpers.prepareOutputData,
1564
+ putExecutionToWait(waitTill) {
1565
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1566
+ runExecutionData.waitTill = waitTill;
1567
+ });
1568
+ },
1569
+ sendMessageToUI(...args) {
1570
+ if (mode !== 'manual') {
1571
+ return;
1572
+ }
1573
+ try {
1574
+ if (additionalData.sendMessageToUI) {
1575
+ additionalData.sendMessageToUI(node.name, args);
1576
+ }
1577
+ }
1578
+ catch (error) {
1579
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1580
+ workflow_1.LoggerProxy.warn(`There was a problem sending messsage to UI: ${error.message}`);
1581
+ }
1582
+ },
1583
+ sendResponse(response) {
1584
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1585
+ var _a;
1586
+ yield ((_a = additionalData.hooks) === null || _a === void 0 ? void 0 : _a.executeHookFunctions('sendResponse', [response]));
1587
+ });
1588
+ },
1589
+ helpers: {
1590
+ httpRequest,
1591
+ requestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1592
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1593
+ return requestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1594
+ });
1595
+ },
1596
+ assertBinaryData(itemIndex, propertyName, inputIndex = 0) {
1597
+ const binaryKeyData = inputData['main'][inputIndex][itemIndex].binary;
1598
+ if (binaryKeyData === undefined) {
1599
+ throw new workflow_1.NodeOperationError(node, `This operation expects the node's input data to contain a binary file '${propertyName}', but none was found [item ${itemIndex}]`, {
1600
+ itemIndex,
1601
+ description: 'Make sure that the previous node outputs a binary file',
1602
+ });
1603
+ }
1604
+ const binaryPropertyData = binaryKeyData[propertyName];
1605
+ if (binaryPropertyData === undefined) {
1606
+ throw new workflow_1.NodeOperationError(node, `The item has no binary field '${propertyName}' [item ${itemIndex}]`, {
1607
+ itemIndex,
1608
+ description: 'Check that the parameter where you specified the input binary field name is correct, and that it matches a field in the binary input',
1609
+ });
1610
+ }
1611
+ return binaryPropertyData;
1612
+ },
1613
+ prepareBinaryData(binaryData, filePath, mimeType) {
1614
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1615
+ return prepareBinaryData.call(this, binaryData, additionalData.executionId, filePath, mimeType);
1616
+ });
1617
+ },
1618
+ getBinaryDataBuffer(itemIndex_1, propertyName_1) {
1619
+ return tslib_1.__awaiter(this, arguments, void 0, function* (itemIndex, propertyName, inputIndex = 0) {
1620
+ return getBinaryDataBuffer.call(this, inputData, itemIndex, propertyName, inputIndex);
1621
+ });
1622
+ },
1623
+ request: proxyRequestToAxios,
1624
+ requestOAuth2(credentialsType, requestOptions, oAuth2Options) {
1625
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1626
+ return requestOAuth2.call(this, credentialsType, requestOptions, node, additionalData, oAuth2Options);
1627
+ });
1628
+ },
1629
+ requestOAuth1(credentialsType, requestOptions) {
1630
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1631
+ return requestOAuth1.call(this, credentialsType, requestOptions);
1632
+ });
1633
+ },
1634
+ httpRequestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1635
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1636
+ return httpRequestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1637
+ });
1638
+ },
1639
+ returnJsonArray,
1640
+ normalizeItems,
1641
+ },
1642
+ getInstanceId: () => {
1643
+ // Return the node's instance ID if available, otherwise return an empty string
1644
+ return node.id || '';
1645
+ },
1646
+ getInputConnectionData(connectionType, itemIndex) {
1647
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1648
+ return yield getInputConnectionData.call(this, workflow, runExecutionData, runIndex, connectionInputData, inputData, additionalData, connectionType, mode, itemIndex, nodeTypeData, closeFunctions);
1649
+ });
1650
+ },
1651
+ addInputData(data, node) {
1652
+ const nodeName = node.name;
1653
+ let currentNodeRunIndex = 0;
1654
+ runExecutionData = {
1655
+ startData: {
1656
+ destinationNode: nodeName,
1657
+ },
1658
+ resultData: {
1659
+ runData: {
1660
+ [nodeName]: [JSON.parse(JSON.stringify(data))]
1661
+ },
1662
+ lastNodeExecuted: nodeName,
1663
+ },
1664
+ };
1665
+ return { index: currentNodeRunIndex, inputExecutionData: runExecutionData };
1666
+ },
1667
+ addOutputData(data, node) {
1668
+ const nodeName = node.name;
1669
+ const outputExecutionData = {
1670
+ startData: {
1671
+ destinationNode: nodeName,
1672
+ },
1673
+ resultData: {
1674
+ error: typeof data === 'object' && 'error' in data ? data.error : undefined,
1675
+ runData: {
1676
+ [nodeName]: [JSON.parse(JSON.stringify(data))]
1677
+ },
1678
+ lastNodeExecuted: nodeName,
1679
+ },
1680
+ };
1681
+ return { outputExecutionData };
1682
+ },
1683
+ getExecutionCancelSignal: () => {
1684
+ return undefined;
1685
+ },
1686
+ };
1687
+ })(workflow, runExecutionData, connectionInputData, inputData, node, nodeTypeData, closeFunctions);
1688
+ }
1689
+ /**
1690
+ * Returns the execute functions regular nodes have access to when single-function is defined.
1691
+ *
1692
+ * @export
1693
+ * @param {Workflow} workflow
1694
+ * @param {IRunExecutionData} runExecutionData
1695
+ * @param {number} runIndex
1696
+ * @param {INodeExecutionData[]} connectionInputData
1697
+ * @param {ITaskDataConnections} inputData
1698
+ * @param {INode} node
1699
+ * @param {number} itemIndex
1700
+ * @param {IWorkflowExecuteAdditionalData} additionalData
1701
+ * @param {WorkflowExecuteMode} mode
1702
+ * @returns {IExecuteSingleFunctions}
1703
+ */
1704
+ function getExecuteSingleFunctions(workflow, runExecutionData, runIndex, connectionInputData, inputData, node, itemIndex, additionalData, mode) {
1705
+ return ((workflow, runExecutionData, connectionInputData, inputData, node, itemIndex) => {
1706
+ return {
1707
+ continueOnFail: () => {
1708
+ return continueOnFail(node);
1709
+ },
1710
+ evaluateExpression: (expression, evaluateItemIndex) => {
1711
+ evaluateItemIndex = evaluateItemIndex === undefined ? itemIndex : evaluateItemIndex;
1712
+ return workflow.expression.resolveSimpleParameterValue(`=${expression}`, {}, runExecutionData, runIndex, evaluateItemIndex, node.name, connectionInputData, mode, getAdditionalKeys(additionalData));
1713
+ },
1714
+ getContext(type) {
1715
+ return workflow_1.NodeHelpers.getContext(runExecutionData, type, node);
1716
+ },
1717
+ getCredentials(type) {
1718
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1719
+ return getCredentials(workflow, node, type, additionalData, mode, runExecutionData, runIndex, connectionInputData, itemIndex);
1720
+ });
1721
+ },
1722
+ getInputData: (inputIndex = 0, inputName = 'main') => {
1723
+ if (!Object.prototype.hasOwnProperty.call(inputData, inputName)) {
1724
+ // Return empty array because else it would throw error when nothing is connected to input
1725
+ return { json: {} };
1726
+ }
1727
+ // TODO: Check if nodeType has input with that index defined
1728
+ if (inputData[inputName].length < inputIndex) {
1729
+ throw new Error(`Could not get input index "${inputIndex}" of input "${inputName}"!`);
1730
+ }
1731
+ const allItems = inputData[inputName][inputIndex];
1732
+ if (allItems === null) {
1733
+ // return [];
1734
+ throw new Error(`Value "${inputIndex}" of input "${inputName}" did not get set!`);
1735
+ }
1736
+ if (allItems[itemIndex] === null) {
1737
+ // return [];
1738
+ throw new Error(`Value "${inputIndex}" of input "${inputName}" with itemIndex "${itemIndex}" did not get set!`);
1739
+ }
1740
+ return allItems[itemIndex];
1741
+ },
1742
+ getMode: () => {
1743
+ return mode;
1744
+ },
1745
+ getNode: () => {
1746
+ return getNode(node);
1747
+ },
1748
+ getRestApiUrl: () => {
1749
+ return additionalData.restApiUrl;
1750
+ },
1751
+ getTimezone: () => {
1752
+ return getTimezone(workflow, additionalData);
1753
+ },
1754
+ getNodeParameter: (parameterName, fallbackValue) => {
1755
+ return getNodeParameter(workflow, runExecutionData, runIndex, connectionInputData, node, parameterName, itemIndex, mode, getAdditionalKeys(additionalData), fallbackValue);
1756
+ },
1757
+ getWorkflow: () => {
1758
+ return getWorkflowMetadata(workflow);
1759
+ },
1760
+ getWorkflowDataProxy: () => {
1761
+ const dataProxy = new workflow_1.WorkflowDataProxy(workflow, runExecutionData, runIndex, itemIndex, node.name, connectionInputData, {}, mode, getAdditionalKeys(additionalData));
1762
+ return dataProxy.getDataProxy();
1763
+ },
1764
+ getWorkflowStaticData(type) {
1765
+ return workflow.getStaticData(type, node);
1766
+ },
1767
+ helpers: {
1768
+ httpRequest,
1769
+ requestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1770
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1771
+ return requestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1772
+ });
1773
+ },
1774
+ prepareBinaryData(binaryData, filePath, mimeType) {
1775
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1776
+ return prepareBinaryData.call(this, binaryData, additionalData.executionId, filePath, mimeType);
1777
+ });
1778
+ },
1779
+ request: proxyRequestToAxios,
1780
+ requestOAuth2(credentialsType, requestOptions, oAuth2Options) {
1781
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1782
+ return requestOAuth2.call(this, credentialsType, requestOptions, node, additionalData, oAuth2Options);
1783
+ });
1784
+ },
1785
+ requestOAuth1(credentialsType, requestOptions) {
1786
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1787
+ return requestOAuth1.call(this, credentialsType, requestOptions);
1788
+ });
1789
+ },
1790
+ httpRequestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1791
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1792
+ return httpRequestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1793
+ });
1794
+ },
1795
+ },
1796
+ getInstanceId: () => {
1797
+ // Return the node's instance ID if available, otherwise return an empty string
1798
+ return node.id || '';
1799
+ },
1800
+ };
1801
+ })(workflow, runExecutionData, connectionInputData, inputData, node, itemIndex);
1802
+ }
1803
+ function getCredentialTestFunctions() {
1804
+ return {
1805
+ helpers: {
1806
+ request: proxyRequestToAxios,
1807
+ },
1808
+ };
1809
+ }
1810
+ /**
1811
+ * Returns the execute functions regular nodes have access to in load-options-function.
1812
+ *
1813
+ * @export
1814
+ * @param {Workflow} workflow
1815
+ * @param {INode} node
1816
+ * @param {IWorkflowExecuteAdditionalData} additionalData
1817
+ * @returns {ILoadOptionsFunctions}
1818
+ */
1819
+ function getLoadOptionsFunctions(workflow, node, path, additionalData) {
1820
+ return ((workflow, node, path) => {
1821
+ const that = {
1822
+ getCredentials(type) {
1823
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1824
+ return getCredentials(workflow, node, type, additionalData, 'internal');
1825
+ });
1826
+ },
1827
+ getCurrentNodeParameter: (parameterPath) => {
1828
+ const nodeParameters = additionalData.currentNodeParameters;
1829
+ if (parameterPath.charAt(0) === '&') {
1830
+ parameterPath = `${path.split('.').slice(1, -1).join('.')}.${parameterPath.slice(1)}`;
1831
+ }
1832
+ return (0, lodash_1.get)(nodeParameters, parameterPath);
1833
+ },
1834
+ getCurrentNodeParameters: () => {
1835
+ return additionalData.currentNodeParameters;
1836
+ },
1837
+ getNode: () => {
1838
+ return getNode(node);
1839
+ },
1840
+ getNodeParameter: (parameterName, fallbackValue) => {
1841
+ const runExecutionData = null;
1842
+ const itemIndex = 0;
1843
+ const runIndex = 0;
1844
+ const connectionInputData = [];
1845
+ return getNodeParameter(workflow, runExecutionData, runIndex, connectionInputData, node, parameterName, itemIndex, 'internal', getAdditionalKeys(additionalData), fallbackValue);
1846
+ },
1847
+ getTimezone: () => {
1848
+ return getTimezone(workflow, additionalData);
1849
+ },
1850
+ getRestApiUrl: () => {
1851
+ return additionalData.restApiUrl;
1852
+ },
1853
+ helpers: {
1854
+ httpRequest,
1855
+ requestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1856
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1857
+ return requestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1858
+ });
1859
+ },
1860
+ request: proxyRequestToAxios,
1861
+ requestOAuth2(credentialsType, requestOptions, oAuth2Options) {
1862
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1863
+ return requestOAuth2.call(this, credentialsType, requestOptions, node, additionalData, oAuth2Options);
1864
+ });
1865
+ },
1866
+ requestOAuth1(credentialsType, requestOptions) {
1867
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1868
+ return requestOAuth1.call(this, credentialsType, requestOptions);
1869
+ });
1870
+ },
1871
+ httpRequestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1872
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1873
+ return httpRequestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1874
+ });
1875
+ },
1876
+ },
1877
+ getInstanceId: () => {
1878
+ // Return the node's instance ID if available, otherwise return an empty string
1879
+ return node.id || '';
1880
+ },
1881
+ };
1882
+ return that;
1883
+ })(workflow, node, path);
1884
+ }
1885
+ /**
1886
+ * Returns the execute functions regular nodes have access to in hook-function.
1887
+ *
1888
+ * @export
1889
+ * @param {Workflow} workflow
1890
+ * @param {INode} node
1891
+ * @param {IWorkflowExecuteAdditionalData} additionalData
1892
+ * @param {WorkflowExecuteMode} mode
1893
+ * @returns {IHookFunctions}
1894
+ */
1895
+ function getExecuteHookFunctions(workflow, node, additionalData, mode, activation, isTest, webhookData) {
1896
+ return ((workflow, node) => {
1897
+ const that = {
1898
+ getCredentials(type) {
1899
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1900
+ return getCredentials(workflow, node, type, additionalData, mode);
1901
+ });
1902
+ },
1903
+ getMode: () => {
1904
+ return mode;
1905
+ },
1906
+ getActivationMode: () => {
1907
+ return activation;
1908
+ },
1909
+ getNode: () => {
1910
+ return getNode(node);
1911
+ },
1912
+ getNodeParameter: (parameterName, fallbackValue) => {
1913
+ const runExecutionData = null;
1914
+ const itemIndex = 0;
1915
+ const runIndex = 0;
1916
+ const connectionInputData = [];
1917
+ return getNodeParameter(workflow, runExecutionData, runIndex, connectionInputData, node, parameterName, itemIndex, mode, getAdditionalKeys(additionalData), fallbackValue);
1918
+ },
1919
+ getNodeWebhookUrl: (name) => {
1920
+ return getNodeWebhookUrl(name, workflow, node, additionalData, mode, getAdditionalKeys(additionalData), isTest);
1921
+ },
1922
+ getTimezone: () => {
1923
+ return getTimezone(workflow, additionalData);
1924
+ },
1925
+ getWebhookName() {
1926
+ if (webhookData === undefined) {
1927
+ throw new Error('Is only supported in webhook functions!');
1928
+ }
1929
+ return webhookData.webhookDescription.name;
1930
+ },
1931
+ getWebhookDescription(name) {
1932
+ return getWebhookDescription(name, workflow, node);
1933
+ },
1934
+ getWorkflow: () => {
1935
+ return getWorkflowMetadata(workflow);
1936
+ },
1937
+ getWorkflowStaticData(type) {
1938
+ return workflow.getStaticData(type, node);
1939
+ },
1940
+ helpers: {
1941
+ httpRequest,
1942
+ requestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1943
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1944
+ return requestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1945
+ });
1946
+ },
1947
+ request: proxyRequestToAxios,
1948
+ requestOAuth2(credentialsType, requestOptions, oAuth2Options) {
1949
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1950
+ return requestOAuth2.call(this, credentialsType, requestOptions, node, additionalData, oAuth2Options);
1951
+ });
1952
+ },
1953
+ requestOAuth1(credentialsType, requestOptions) {
1954
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1955
+ return requestOAuth1.call(this, credentialsType, requestOptions);
1956
+ });
1957
+ },
1958
+ httpRequestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
1959
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
1960
+ return httpRequestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
1961
+ });
1962
+ },
1963
+ },
1964
+ getInstanceId: () => {
1965
+ // Return the node's instance ID if available, otherwise return an empty string
1966
+ return node.id || '';
1967
+ },
1968
+ };
1969
+ return that;
1970
+ })(workflow, node);
1971
+ }
1972
+ /**
1973
+ * Returns the execute functions regular nodes have access to when webhook-function is defined.
1974
+ *
1975
+ * @export
1976
+ * @param {Workflow} workflow
1977
+ * @param {IRunExecutionData} runExecutionData
1978
+ * @param {INode} node
1979
+ * @param {IWorkflowExecuteAdditionalData} additionalData
1980
+ * @param {WorkflowExecuteMode} mode
1981
+ * @returns {IWebhookFunctions}
1982
+ */
1983
+ function getExecuteWebhookFunctions(workflow, node, additionalData, mode, webhookData, runExecutionData) {
1984
+ return ((workflow, node) => {
1985
+ return {
1986
+ logger: workflow_1.LoggerProxy,
1987
+ evaluateExpression: (expression, itemIndex) => {
1988
+ //TODO: Implement this EVALUATE EXPRESSION in get webhook execute function
1989
+ return {};
1990
+ },
1991
+ getChildNodes: (nodeName, options) => {
1992
+ return [];
1993
+ },
1994
+ getParentNodes: (nodeName) => {
1995
+ return [];
1996
+ },
1997
+ getBodyData() {
1998
+ if (additionalData.httpRequest === undefined) {
1999
+ throw new Error('Request is missing!');
2000
+ }
2001
+ return additionalData.httpRequest.body;
2002
+ },
2003
+ getCredentials(type) {
2004
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2005
+ return getCredentials(workflow, node, type, additionalData, mode);
2006
+ });
2007
+ },
2008
+ nodeHelpers: {
2009
+ copyBinaryFile: (filePath, fileName, mimeType) => tslib_1.__awaiter(this, void 0, void 0, function* () {
2010
+ // Use fs.promises.readFile instead of fsReadFileAsync
2011
+ const buffer = yield fs_1.promises.readFile(filePath);
2012
+ return prepareBinaryData(buffer, workflow.id || '', filePath, mimeType);
2013
+ }),
2014
+ },
2015
+ getHeaderData() {
2016
+ if (additionalData.httpRequest === undefined) {
2017
+ throw new Error('Request is missing!');
2018
+ }
2019
+ return additionalData.httpRequest.headers;
2020
+ },
2021
+ getMode: () => {
2022
+ return mode;
2023
+ },
2024
+ getNode: () => {
2025
+ return getNode(node);
2026
+ },
2027
+ getNodeParameter: (parameterName, fallbackValue, options) => {
2028
+ var _a;
2029
+ const itemIndex = 0;
2030
+ const runIndex = 0;
2031
+ let connectionInputData = [];
2032
+ let executionData;
2033
+ if ((runExecutionData === null || runExecutionData === void 0 ? void 0 : runExecutionData.executionData) !== undefined) {
2034
+ executionData = runExecutionData.executionData.nodeExecutionStack[0];
2035
+ if (executionData !== undefined) {
2036
+ connectionInputData = ((_a = executionData.data['main']) === null || _a === void 0 ? void 0 : _a[0]) || [];
2037
+ }
2038
+ }
2039
+ return getNodeParameter(workflow, runExecutionData || null, runIndex, connectionInputData, node, parameterName, itemIndex, mode, getAdditionalKeys(additionalData), fallbackValue);
2040
+ },
2041
+ getParamsData() {
2042
+ if (additionalData.httpRequest === undefined) {
2043
+ throw new Error('Request is missing!');
2044
+ }
2045
+ return additionalData.httpRequest.params;
2046
+ },
2047
+ getQueryData() {
2048
+ if (additionalData.httpRequest === undefined) {
2049
+ throw new Error('Request is missing!');
2050
+ }
2051
+ return additionalData.httpRequest.query;
2052
+ },
2053
+ getRequestObject() {
2054
+ if (additionalData.httpRequest === undefined) {
2055
+ throw new Error('Request is missing!');
2056
+ }
2057
+ return additionalData.httpRequest;
2058
+ },
2059
+ getResponseObject() {
2060
+ if (additionalData.httpResponse === undefined) {
2061
+ throw new Error('Response is missing!');
2062
+ }
2063
+ return additionalData.httpResponse;
2064
+ },
2065
+ getNodeWebhookUrl: (name) => {
2066
+ return getNodeWebhookUrl(name, workflow, node, additionalData, mode, getAdditionalKeys(additionalData));
2067
+ },
2068
+ getTimezone: () => {
2069
+ return getTimezone(workflow, additionalData);
2070
+ },
2071
+ getWorkflow: () => {
2072
+ return getWorkflowMetadata(workflow);
2073
+ },
2074
+ getWorkflowStaticData(type) {
2075
+ return workflow.getStaticData(type, node);
2076
+ },
2077
+ getWebhookName() {
2078
+ return webhookData.webhookDescription.name;
2079
+ },
2080
+ addInputData(data, node) {
2081
+ const nodeName = node.name;
2082
+ let currentNodeRunIndex = 0;
2083
+ runExecutionData = {
2084
+ startData: {
2085
+ destinationNode: nodeName,
2086
+ },
2087
+ resultData: {
2088
+ error: undefined,
2089
+ runData: {
2090
+ [nodeName]: [JSON.parse(JSON.stringify(data))]
2091
+ },
2092
+ lastNodeExecuted: nodeName,
2093
+ },
2094
+ executionData: {
2095
+ contextData: {},
2096
+ nodeExecutionStack: [],
2097
+ waitingExecution: {},
2098
+ },
2099
+ waitTill: undefined,
2100
+ };
2101
+ return { index: currentNodeRunIndex, inputExecutionData: runExecutionData };
2102
+ },
2103
+ addOutputData(data, node) {
2104
+ const nodeName = node.name;
2105
+ const outputExecutionData = {
2106
+ startData: {
2107
+ destinationNode: nodeName,
2108
+ },
2109
+ resultData: {
2110
+ error: undefined,
2111
+ runData: {
2112
+ [nodeName]: [JSON.parse(JSON.stringify(data))]
2113
+ },
2114
+ lastNodeExecuted: nodeName,
2115
+ },
2116
+ executionData: {
2117
+ contextData: {},
2118
+ nodeExecutionStack: [],
2119
+ waitingExecution: {},
2120
+ },
2121
+ waitTill: undefined,
2122
+ };
2123
+ return { outputExecutionData };
2124
+ },
2125
+ logAiEvent: (event, data) => {
2126
+ // Simple implementation for logAiEvent in webhook functions
2127
+ return;
2128
+ },
2129
+ prepareOutputData: workflow_1.NodeHelpers.prepareOutputData,
2130
+ helpers: {
2131
+ httpRequest,
2132
+ requestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
2133
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2134
+ return requestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
2135
+ });
2136
+ },
2137
+ prepareBinaryData(binaryData, filePath, mimeType) {
2138
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2139
+ return prepareBinaryData.call(this, binaryData, additionalData.executionId, filePath, mimeType);
2140
+ });
2141
+ },
2142
+ request: proxyRequestToAxios,
2143
+ requestOAuth2(credentialsType, requestOptions, oAuth2Options) {
2144
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2145
+ return requestOAuth2.call(this, credentialsType, requestOptions, node, additionalData, oAuth2Options);
2146
+ });
2147
+ },
2148
+ requestOAuth1(credentialsType, requestOptions) {
2149
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2150
+ return requestOAuth1.call(this, credentialsType, requestOptions);
2151
+ });
2152
+ },
2153
+ httpRequestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
2154
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2155
+ return httpRequestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
2156
+ });
2157
+ },
2158
+ returnJsonArray,
2159
+ },
2160
+ getInstanceId: () => {
2161
+ // Return the node's instance ID if available, otherwise return an empty string
2162
+ return node.id || '';
2163
+ },
2164
+ };
2165
+ })(workflow, node);
2166
+ }
2167
+ function getSupplyDataFunctions(workflow, runExecutionData, runIndex, connectionInputData, inputData, node, additionalData, mode, nodeTypeData, closeFunctions) {
2168
+ return ((workflow, runExecutionData, connectionInputData, inputData, node, nodeTypeData, closeFunctions) => {
2169
+ return {
2170
+ logger: workflow_1.LoggerProxy,
2171
+ continueOnFail: () => {
2172
+ return continueOnFail(node);
2173
+ },
2174
+ evaluateExpression: (expression, itemIndex) => {
2175
+ return workflow.expression.resolveSimpleParameterValue(`=${expression}`, {}, runExecutionData, runIndex, itemIndex, node.name, connectionInputData, mode, getAdditionalKeys(additionalData));
2176
+ },
2177
+ executeWorkflow(workflowInfo, inputData) {
2178
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2179
+ return additionalData
2180
+ .executeWorkflow(workflowInfo, additionalData, inputData)
2181
+ .then((result) => tslib_1.__awaiter(this, void 0, void 0, function* () {
2182
+ return BinaryDataManager_1.BinaryDataManager.getInstance().duplicateBinaryData(result, additionalData.executionId);
2183
+ }));
2184
+ });
2185
+ },
2186
+ getContext(type) {
2187
+ return workflow_1.NodeHelpers.getContext(runExecutionData, type, node);
2188
+ },
2189
+ getCredentials(type, itemIndex) {
2190
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2191
+ return getCredentials(workflow, node, type, additionalData, mode, runExecutionData, runIndex, connectionInputData, itemIndex);
2192
+ });
2193
+ },
2194
+ getExecutionId: () => {
2195
+ return additionalData.executionId;
2196
+ },
2197
+ getInputData: (inputIndex = 0, inputName = 'main') => {
2198
+ if (!Object.prototype.hasOwnProperty.call(inputData, inputName)) {
2199
+ // Return empty array because else it would throw error when nothing is connected to input
2200
+ return [];
2201
+ }
2202
+ // TODO: Check if nodeType has input with that index defined
2203
+ if (inputData[inputName].length < inputIndex) {
2204
+ throw new Error(`Could not get input index "${inputIndex}" of input "${inputName}"!`);
2205
+ }
2206
+ if (inputData[inputName][inputIndex] === null) {
2207
+ // return [];
2208
+ throw new Error(`Value "${inputIndex}" of input "${inputName}" did not get set!`);
2209
+ }
2210
+ return inputData[inputName][inputIndex];
2211
+ },
2212
+ getNodeParameter: (parameterName, itemIndex, fallbackValue) => {
2213
+ return getNodeParameter(workflow, runExecutionData, runIndex, connectionInputData, node, parameterName, itemIndex, mode, getAdditionalKeys(additionalData), fallbackValue);
2214
+ },
2215
+ getMode: () => {
2216
+ return mode;
2217
+ },
2218
+ getNode: () => {
2219
+ return getNode(node);
2220
+ },
2221
+ getRestApiUrl: () => {
2222
+ return additionalData.restApiUrl;
2223
+ },
2224
+ getTimezone: () => {
2225
+ return getTimezone(workflow, additionalData);
2226
+ },
2227
+ getWorkflow: () => {
2228
+ return getWorkflowMetadata(workflow);
2229
+ },
2230
+ getWorkflowDataProxy: (itemIndex) => {
2231
+ const dataProxy = new workflow_1.WorkflowDataProxy(workflow, runExecutionData, runIndex, itemIndex, node.name, connectionInputData, {}, mode, getAdditionalKeys(additionalData));
2232
+ return dataProxy.getDataProxy();
2233
+ },
2234
+ getWorkflowStaticData(type) {
2235
+ return workflow.getStaticData(type, node);
2236
+ },
2237
+ prepareOutputData: workflow_1.NodeHelpers.prepareOutputData,
2238
+ putExecutionToWait(waitTill) {
2239
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2240
+ runExecutionData.waitTill = waitTill;
2241
+ });
2242
+ },
2243
+ sendMessageToUI(...args) {
2244
+ if (mode !== 'manual') {
2245
+ return;
2246
+ }
2247
+ try {
2248
+ if (additionalData.sendMessageToUI) {
2249
+ additionalData.sendMessageToUI(node.name, args);
2250
+ }
2251
+ }
2252
+ catch (error) {
2253
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2254
+ workflow_1.LoggerProxy.warn(`There was a problem sending messsage to UI: ${error.message}`);
2255
+ }
2256
+ },
2257
+ sendResponse(response) {
2258
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2259
+ var _a;
2260
+ yield ((_a = additionalData.hooks) === null || _a === void 0 ? void 0 : _a.executeHookFunctions('sendResponse', [response]));
2261
+ });
2262
+ },
2263
+ helpers: {
2264
+ httpRequest,
2265
+ requestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
2266
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2267
+ return requestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
2268
+ });
2269
+ },
2270
+ assertBinaryData(itemIndex, propertyName, inputIndex = 0) {
2271
+ const binaryKeyData = inputData['main'][inputIndex][itemIndex].binary;
2272
+ if (binaryKeyData === undefined) {
2273
+ throw new workflow_1.NodeOperationError(node, `This operation expects the node's input data to contain a binary file '${propertyName}', but none was found [item ${itemIndex}]`, {
2274
+ itemIndex,
2275
+ description: 'Make sure that the previous node outputs a binary file',
2276
+ });
2277
+ }
2278
+ const binaryPropertyData = binaryKeyData[propertyName];
2279
+ if (binaryPropertyData === undefined) {
2280
+ throw new workflow_1.NodeOperationError(node, `The item has no binary field '${propertyName}' [item ${itemIndex}]`, {
2281
+ itemIndex,
2282
+ description: 'Check that the parameter where you specified the input binary field name is correct, and that it matches a field in the binary input',
2283
+ });
2284
+ }
2285
+ return binaryPropertyData;
2286
+ },
2287
+ prepareBinaryData(binaryData, filePath, mimeType) {
2288
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2289
+ return prepareBinaryData.call(this, binaryData, additionalData.executionId, filePath, mimeType);
2290
+ });
2291
+ },
2292
+ getBinaryDataBuffer(itemIndex_1, propertyName_1) {
2293
+ return tslib_1.__awaiter(this, arguments, void 0, function* (itemIndex, propertyName, inputIndex = 0) {
2294
+ return getBinaryDataBuffer.call(this, inputData, itemIndex, propertyName, inputIndex);
2295
+ });
2296
+ },
2297
+ request: proxyRequestToAxios,
2298
+ requestOAuth2(credentialsType, requestOptions, oAuth2Options) {
2299
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2300
+ return requestOAuth2.call(this, credentialsType, requestOptions, node, additionalData, oAuth2Options);
2301
+ });
2302
+ },
2303
+ requestOAuth1(credentialsType, requestOptions) {
2304
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2305
+ return requestOAuth1.call(this, credentialsType, requestOptions);
2306
+ });
2307
+ },
2308
+ httpRequestWithAuthentication(credentialsType, requestOptions, additionalCredentialOptions) {
2309
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2310
+ return httpRequestWithAuthentication.call(this, credentialsType, requestOptions, workflow, node, additionalData, additionalCredentialOptions);
2311
+ });
2312
+ },
2313
+ returnJsonArray,
2314
+ normalizeItems,
2315
+ },
2316
+ getInstanceId: () => {
2317
+ // Return the node's instance ID if available, otherwise return an empty string
2318
+ return node.id || '';
2319
+ },
2320
+ addInputData(data, node) {
2321
+ const nodeName = node.name;
2322
+ let currentNodeRunIndex = 0;
2323
+ runExecutionData = {
2324
+ startData: {
2325
+ destinationNode: nodeName,
2326
+ },
2327
+ resultData: {
2328
+ error: undefined,
2329
+ runData: {
2330
+ [nodeName]: [JSON.parse(JSON.stringify(data))]
2331
+ },
2332
+ lastNodeExecuted: nodeName,
2333
+ },
2334
+ executionData: {
2335
+ contextData: {},
2336
+ nodeExecutionStack: [],
2337
+ waitingExecution: {},
2338
+ },
2339
+ waitTill: undefined,
2340
+ };
2341
+ return { index: currentNodeRunIndex, inputExecutionData: runExecutionData };
2342
+ },
2343
+ addOutputData(data, node) {
2344
+ const nodeName = node.name;
2345
+ const outputExecutionData = {
2346
+ startData: {
2347
+ destinationNode: nodeName,
2348
+ },
2349
+ resultData: {
2350
+ error: undefined,
2351
+ runData: {
2352
+ [nodeName]: [JSON.parse(JSON.stringify(data))]
2353
+ },
2354
+ lastNodeExecuted: nodeName,
2355
+ },
2356
+ executionData: {
2357
+ contextData: {},
2358
+ nodeExecutionStack: [],
2359
+ waitingExecution: {},
2360
+ },
2361
+ waitTill: undefined,
2362
+ };
2363
+ return { outputExecutionData };
2364
+ },
2365
+ getInputConnectionData(connectionType, itemIndex) {
2366
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2367
+ return yield getInputConnectionData.call(this, workflow, runExecutionData, runIndex, connectionInputData, inputData, additionalData, connectionType, mode, itemIndex, nodeTypeData, closeFunctions);
2368
+ });
2369
+ },
2370
+ };
2371
+ })(workflow, runExecutionData, connectionInputData, inputData, node, nodeTypeData, closeFunctions);
2372
+ }
2373
+ function getInputConnectionData(workflow, runExecutionData, runIndex, connectionInputData, inputData, additionalData, connectionType, mode, itemIndex, nodeTypeData, closeFunctions) {
2374
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
2375
+ var _a, _b, _c, _d, _e, _f, _g;
2376
+ const parentNode = this.getNode();
2377
+ const startTime = Date.now();
2378
+ const nodeInputs = getNodeInputs(workflow, parentNode, nodeTypeData.description).map((input) => (typeof input === 'string' ? { type: input } : input));
2379
+ const inputConfiguration = nodeInputs.find((input) => input.type === connectionType);
2380
+ if (inputConfiguration === undefined) {
2381
+ throw new workflow_1.NodeOperationError(parentNode, `Node does not have input of type`, {
2382
+ description: `Node ${parentNode.name} does not have input of type ${connectionType}`,
2383
+ });
2384
+ }
2385
+ const connectedNodes = getConnectedNodes(workflow, parentNode, connectionType);
2386
+ if (connectedNodes.length === 0) {
2387
+ if (inputConfiguration.required) {
2388
+ throw new workflow_1.NodeOperationError(parentNode, `A ${(_a = inputConfiguration === null || inputConfiguration === void 0 ? void 0 : inputConfiguration.displayName) !== null && _a !== void 0 ? _a : connectionType} sub-node must be connected and enabled`);
2389
+ }
2390
+ return inputConfiguration.maxConnections === 1 ? undefined : [];
2391
+ }
2392
+ if (inputConfiguration.maxConnections !== undefined &&
2393
+ connectedNodes.length > inputConfiguration.maxConnections) {
2394
+ throw new workflow_1.NodeOperationError(parentNode, `Only ${inputConfiguration.maxConnections} ${connectionType} sub-nodes are/is allowed to be connected`);
2395
+ }
2396
+ const nodes = [];
2397
+ for (const connectedNode of connectedNodes) {
2398
+ const connectedNodeType = workflow.nodeTypes.getByNameAndVersion(connectedNode.type, connectedNode.typeVersion);
2399
+ if (!connectedNodeType) {
2400
+ continue;
2401
+ }
2402
+ if (connectedNodeType && !connectedNodeType.supplyData) {
2403
+ throw new workflow_1.NodeOperationError(connectedNode, 'Node does not have a `supplyData` method defined', {
2404
+ itemIndex,
2405
+ });
2406
+ }
2407
+ else {
2408
+ try {
2409
+ yield ((_b = additionalData.hooks) === null || _b === void 0 ? void 0 : _b.executeHookFunctions('nodeExecuteBefore', [connectedNode.name, {
2410
+ startTime: startTime,
2411
+ executionTime: new Date().getTime() - startTime
2412
+ }]));
2413
+ const context = getSupplyDataFunctions(workflow, runExecutionData, runIndex, connectionInputData, inputData, connectedNode, additionalData, mode, nodeTypeData, closeFunctions);
2414
+ const supplyData = yield ((_c = connectedNodeType.supplyData) === null || _c === void 0 ? void 0 : _c.call(context, itemIndex));
2415
+ if (supplyData) {
2416
+ nodes.push(supplyData);
2417
+ if (supplyData.closeFunction) {
2418
+ closeFunctions.push(supplyData.closeFunction);
2419
+ }
2420
+ const taskData = {
2421
+ startTime: startTime,
2422
+ executionTime: new Date().getTime() - startTime
2423
+ };
2424
+ if (!Object.prototype.hasOwnProperty.call(runExecutionData.resultData.runData, connectedNode.name)) {
2425
+ runExecutionData.resultData.runData[connectedNode.name] = [];
2426
+ }
2427
+ runExecutionData.resultData.runData[connectedNode.name][runIndex] = taskData;
2428
+ yield ((_d = additionalData.hooks) === null || _d === void 0 ? void 0 : _d.executeHookFunctions('nodeExecuteAfter', [
2429
+ connectedNode.name,
2430
+ taskData,
2431
+ runExecutionData
2432
+ ]));
2433
+ }
2434
+ }
2435
+ catch (error) {
2436
+ const taskData = {
2437
+ startTime: startTime,
2438
+ executionTime: new Date().getTime() - startTime,
2439
+ error: error
2440
+ };
2441
+ runExecutionData.resultData.runData[connectedNode.name][runIndex] = taskData;
2442
+ yield ((_e = additionalData.hooks) === null || _e === void 0 ? void 0 : _e.executeHookFunctions('nodeExecuteAfter', [
2443
+ connectedNode.name,
2444
+ taskData,
2445
+ runExecutionData
2446
+ ]));
2447
+ throw new workflow_1.NodeOperationError(connectedNode, `Error in sub-node ${connectedNode.name}`, {
2448
+ itemIndex,
2449
+ description: (_f = error === null || error === void 0 ? void 0 : error.message) !== null && _f !== void 0 ? _f : 'Unknown error',
2450
+ });
2451
+ }
2452
+ }
2453
+ }
2454
+ return inputConfiguration.maxConnections === 1
2455
+ ? (_g = (nodes || [])[0]) === null || _g === void 0 ? void 0 : _g.response
2456
+ : nodes.map((node) => node.response);
2457
+ });
2458
+ }
2459
+ function getNodeInputs(workflow, node, nodeTypeData) {
2460
+ if (Array.isArray(nodeTypeData === null || nodeTypeData === void 0 ? void 0 : nodeTypeData.inputs)) {
2461
+ return nodeTypeData.inputs;
2462
+ }
2463
+ // Calculate the outputs dynamically
2464
+ try {
2465
+ return (workflow.expression.getSimpleParameterValue(node, nodeTypeData.inputs, 'internal', {}) || []);
2466
+ }
2467
+ catch (e) {
2468
+ console.warn('Could not calculate inputs dynamically for node: ', node.name);
2469
+ return [];
2470
+ }
2471
+ }
2472
+ function getConnectedNodes(workflow, node, connectionType) {
2473
+ return workflow
2474
+ .getParentNodes(node.name, connectionType, 1)
2475
+ .map((nodeName) => workflow.getNode(nodeName))
2476
+ .filter((node) => !!node)
2477
+ .filter((node) => node.disabled !== true);
2478
+ }
2479
+ //# sourceMappingURL=NodeExecuteFunctions.js.map