plugin-document-understanding 1.1.8 → 1.1.11
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.
- package/dist/client/345.17f88ffb846ec69b.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/345.1e0c321d30702aa1.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +6 -6
- package/dist/locale/en-US.json +171 -121
- package/dist/locale/vi-VN.json +171 -121
- package/dist/locale/zh-CN.json +171 -1
- package/dist/server/actions.js +1 -1
- package/dist/server/plugin.js +11 -10
- package/dist/server/services/DocumentUnderstandingService.js +25 -6
- package/dist/server/services/PipelineExecutor.js +8 -32
- package/package.json +46 -49
- package/src/client/index.tsx +7 -1
- package/src/client-v2/components/EndpointsTab.tsx +177 -108
- package/src/client-v2/components/JobsTab.tsx +94 -59
- package/src/client-v2/components/PipelinesTab.tsx +244 -154
- package/src/client-v2/components/PluginSettings.tsx +2 -0
- package/src/client-v2/components/ServiceConfigTab.tsx +56 -39
- package/src/client-v2/types.ts +32 -0
- package/src/locale/en-US.json +171 -121
- package/src/locale/vi-VN.json +171 -121
- package/src/locale/zh-CN.json +171 -1
- package/src/server/__tests__/document-understanding-service.test.ts +82 -0
- package/src/server/__tests__/pipeline-executor.test.ts +55 -33
- package/src/server/actions.ts +176 -176
- package/src/server/plugin.ts +134 -134
- package/src/server/services/DocumentUnderstandingService.ts +29 -7
- package/src/server/services/PipelineExecutor.ts +477 -502
- package/src/server/types.ts +78 -73
- package/dist/client-v2/794.9b984a25b2fc7c14.js +0 -10
|
@@ -1,502 +1,477 @@
|
|
|
1
|
-
import { existsSync, realpathSync, readFileSync, statSync } from 'fs';
|
|
2
|
-
import { basename, resolve, sep } from 'path';
|
|
3
|
-
import { Database } from '@nocobase/database';
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
private
|
|
75
|
-
private
|
|
76
|
-
private
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
this.
|
|
81
|
-
this.
|
|
82
|
-
this.
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
const
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
const
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
return fieldVal === val;
|
|
479
|
-
case 'neq':
|
|
480
|
-
return fieldVal !== val;
|
|
481
|
-
case 'gt':
|
|
482
|
-
return fieldVal > val;
|
|
483
|
-
case 'gte':
|
|
484
|
-
return fieldVal >= val;
|
|
485
|
-
case 'lt':
|
|
486
|
-
return fieldVal < val;
|
|
487
|
-
case 'lte':
|
|
488
|
-
return fieldVal <= val;
|
|
489
|
-
case 'in':
|
|
490
|
-
return Array.isArray(val) && val.includes(fieldVal);
|
|
491
|
-
case 'contains':
|
|
492
|
-
return typeof fieldVal === 'string' && fieldVal.includes(String(val));
|
|
493
|
-
default:
|
|
494
|
-
return false;
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
private getNestedValue(obj: any, path: string): any {
|
|
499
|
-
if (!obj) return obj;
|
|
500
|
-
return path.split('.').reduce((acc, part) => acc && acc[part], obj);
|
|
501
|
-
}
|
|
502
|
-
}
|
|
1
|
+
import { existsSync, realpathSync, readFileSync, statSync } from 'fs';
|
|
2
|
+
import { basename, resolve, sep } from 'path';
|
|
3
|
+
import { Database } from '@nocobase/database';
|
|
4
|
+
import mime from 'mime-types';
|
|
5
|
+
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
6
|
+
import { AsyncJobManager } from './AsyncJobManager';
|
|
7
|
+
import { PipelineDef, PipelineStepDef, JobState, EndpointDef } from '../types';
|
|
8
|
+
|
|
9
|
+
interface LoggerLike {
|
|
10
|
+
error: (...args: unknown[]) => void;
|
|
11
|
+
warn?: (...args: unknown[]) => void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface FileReferenceInput {
|
|
15
|
+
buffer?: Buffer;
|
|
16
|
+
url?: string;
|
|
17
|
+
fieldName?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const UPLOAD_ROOTS = [resolve(process.cwd(), 'storage', 'uploads')];
|
|
21
|
+
|
|
22
|
+
const isInsidePath = (basePath: string, targetPath: string) =>
|
|
23
|
+
targetPath === basePath || targetPath.startsWith(`${basePath}${sep}`);
|
|
24
|
+
|
|
25
|
+
export function resolveUploadFilePath(urlOrPath: string): string | null {
|
|
26
|
+
if (!urlOrPath || urlOrPath.includes('\0')) return null;
|
|
27
|
+
|
|
28
|
+
let pathname = urlOrPath.replace(/\\/g, '/').split(/[?#]/)[0];
|
|
29
|
+
try {
|
|
30
|
+
if (pathname.startsWith('http://') || pathname.startsWith('https://')) {
|
|
31
|
+
pathname = new URL(pathname).pathname;
|
|
32
|
+
}
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
pathname = decodeURIComponent(pathname).replace(/^\/+/, '');
|
|
38
|
+
const uploadsIndex = pathname.indexOf('uploads/');
|
|
39
|
+
if (pathname.startsWith('storage/uploads/')) {
|
|
40
|
+
pathname = pathname.slice('storage/uploads/'.length);
|
|
41
|
+
} else if (pathname.startsWith('uploads/')) {
|
|
42
|
+
pathname = pathname.slice('uploads/'.length);
|
|
43
|
+
} else if (uploadsIndex >= 0) {
|
|
44
|
+
pathname = pathname.slice(uploadsIndex + 'uploads/'.length);
|
|
45
|
+
} else {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const parts = pathname.split('/').filter(Boolean);
|
|
50
|
+
if (parts.some((part) => part === '..' || part.includes('\0'))) return null;
|
|
51
|
+
|
|
52
|
+
for (const root of UPLOAD_ROOTS) {
|
|
53
|
+
const candidate = resolve(root, ...parts);
|
|
54
|
+
const realRoot = existsSync(root) ? realpathSync(root) : root;
|
|
55
|
+
if (!existsSync(candidate)) continue;
|
|
56
|
+
const realCandidate = realpathSync(candidate);
|
|
57
|
+
if (isInsidePath(realRoot, realCandidate) && statSync(realCandidate).isFile()) {
|
|
58
|
+
return realCandidate;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface ExecutionContext {
|
|
66
|
+
input: Record<string, any>;
|
|
67
|
+
files: FileInput[];
|
|
68
|
+
stepResults: Record<string, any>;
|
|
69
|
+
jobId: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export class PipelineExecutor {
|
|
73
|
+
private db: Database;
|
|
74
|
+
private apiClient: ExternalApiClient;
|
|
75
|
+
private jobManager: AsyncJobManager;
|
|
76
|
+
private logger: LoggerLike;
|
|
77
|
+
|
|
78
|
+
constructor(db: Database, apiClient: ExternalApiClient, jobManager: AsyncJobManager, logger: LoggerLike) {
|
|
79
|
+
this.db = db;
|
|
80
|
+
this.apiClient = apiClient;
|
|
81
|
+
this.jobManager = jobManager;
|
|
82
|
+
this.logger = logger;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private async resolveFile(urlOrPath: string, fieldName = 'file'): Promise<FileInput | null> {
|
|
86
|
+
if (!urlOrPath || typeof urlOrPath !== 'string') return null;
|
|
87
|
+
|
|
88
|
+
try {
|
|
89
|
+
const localPath = resolveUploadFilePath(urlOrPath);
|
|
90
|
+
if (localPath) {
|
|
91
|
+
const buffer = readFileSync(localPath);
|
|
92
|
+
const mimeType = mime.lookup(localPath) || 'application/octet-stream';
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
fieldName,
|
|
96
|
+
buffer,
|
|
97
|
+
filename: basename(localPath),
|
|
98
|
+
mimeType,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Only files in NocoBase's upload storage are accepted. Fetching arbitrary
|
|
103
|
+
// HTTP(S) URLs here would turn a user/AI-provided value into an SSRF primitive.
|
|
104
|
+
if (urlOrPath.startsWith('http://') || urlOrPath.startsWith('https://')) {
|
|
105
|
+
this.logger.warn?.('Ignoring remote file URL; use a NocoBase upload URL instead.');
|
|
106
|
+
}
|
|
107
|
+
} catch (err) {
|
|
108
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
109
|
+
this.logger.warn?.(`Failed to resolve file input: ${message}`);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async execute(
|
|
116
|
+
pipelineId: number,
|
|
117
|
+
input: Record<string, any>,
|
|
118
|
+
files: FileInput[] = [],
|
|
119
|
+
userId?: number,
|
|
120
|
+
): Promise<JobState> {
|
|
121
|
+
const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
|
|
122
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
123
|
+
|
|
124
|
+
const pipeline = await pipelineRepo.findOne({
|
|
125
|
+
filter: { id: pipelineId },
|
|
126
|
+
appends: ['steps', 'steps.endpoint'],
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
if (!pipeline) throw new Error(`Pipeline ${pipelineId} not found`);
|
|
130
|
+
if (!pipeline.enabled) throw new Error(`Pipeline ${pipelineId} is disabled`);
|
|
131
|
+
|
|
132
|
+
// Create Job
|
|
133
|
+
const job = await jobsRepo.create({
|
|
134
|
+
values: {
|
|
135
|
+
pipelineId,
|
|
136
|
+
status: 'pending',
|
|
137
|
+
input,
|
|
138
|
+
currentStep: 1, // 1-based ordering
|
|
139
|
+
stepResults: {},
|
|
140
|
+
externalTaskIds: {},
|
|
141
|
+
startedAt: new Date(),
|
|
142
|
+
createdById: userId,
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
const resolvedFiles: FileInput[] = [];
|
|
147
|
+
|
|
148
|
+
const tryAddFile = async (urlOrPath: string, fieldName = 'file') => {
|
|
149
|
+
const resolved = await this.resolveFile(urlOrPath, fieldName);
|
|
150
|
+
if (resolved) {
|
|
151
|
+
resolvedFiles.push(resolved);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
// 1. Process files argument
|
|
156
|
+
if (Array.isArray(files)) {
|
|
157
|
+
for (const f of files) {
|
|
158
|
+
if (f && typeof f === 'object') {
|
|
159
|
+
const fileRef = f as FileReferenceInput;
|
|
160
|
+
if (fileRef.buffer) {
|
|
161
|
+
resolvedFiles.push(f);
|
|
162
|
+
} else if (fileRef.url) {
|
|
163
|
+
await tryAddFile(fileRef.url, fileRef.fieldName || 'file');
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 2. Scan input for common file URL keys
|
|
170
|
+
const urlFields = ['file_url', 'file_urls', 'file', 'files'];
|
|
171
|
+
for (const key of urlFields) {
|
|
172
|
+
const val = input[key];
|
|
173
|
+
if (!val) continue;
|
|
174
|
+
|
|
175
|
+
if (typeof val === 'string') {
|
|
176
|
+
if (
|
|
177
|
+
val.startsWith('http://') ||
|
|
178
|
+
val.startsWith('https://') ||
|
|
179
|
+
val.startsWith('/') ||
|
|
180
|
+
val.startsWith('storage/')
|
|
181
|
+
) {
|
|
182
|
+
await tryAddFile(val, 'file');
|
|
183
|
+
} else if (val.includes(',')) {
|
|
184
|
+
const urls = val.split(',').map((s) => s.trim());
|
|
185
|
+
for (const u of urls) {
|
|
186
|
+
if (u.startsWith('http://') || u.startsWith('https://') || u.startsWith('/') || u.startsWith('storage/')) {
|
|
187
|
+
await tryAddFile(u, 'file');
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
} else if (Array.isArray(val)) {
|
|
192
|
+
for (const item of val) {
|
|
193
|
+
if (typeof item === 'string') {
|
|
194
|
+
if (
|
|
195
|
+
item.startsWith('http://') ||
|
|
196
|
+
item.startsWith('https://') ||
|
|
197
|
+
item.startsWith('/') ||
|
|
198
|
+
item.startsWith('storage/')
|
|
199
|
+
) {
|
|
200
|
+
await tryAddFile(item, 'file');
|
|
201
|
+
}
|
|
202
|
+
} else if (item && typeof item === 'object' && item.url) {
|
|
203
|
+
await tryAddFile(item.url, 'file');
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
} else if (val && typeof val === 'object' && val.url) {
|
|
207
|
+
await tryAddFile(val.url, 'file');
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (resolvedFiles.length === 0 && files && files.length > 0) {
|
|
212
|
+
for (const f of files) {
|
|
213
|
+
if ((f as FileReferenceInput).buffer) {
|
|
214
|
+
resolvedFiles.push(f);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const context: ExecutionContext = {
|
|
220
|
+
input,
|
|
221
|
+
files: resolvedFiles,
|
|
222
|
+
stepResults: {},
|
|
223
|
+
jobId: job.id,
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
// Sorting steps by order
|
|
227
|
+
const steps = [...(pipeline.steps || [])].sort((a, b) => a.stepOrder - b.stepOrder);
|
|
228
|
+
|
|
229
|
+
// Run steps (Synchronous part)
|
|
230
|
+
this.runSteps(job, steps, context).catch((err) => {
|
|
231
|
+
this.logger.error(`Background pipeline error for job ${job.id}`, err);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
return job;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
private async runSteps(job: JobState, steps: PipelineStepDef[], context: ExecutionContext, startFromOrder = 1) {
|
|
238
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
239
|
+
let currentOrder = startFromOrder;
|
|
240
|
+
|
|
241
|
+
try {
|
|
242
|
+
await jobsRepo.update({ filterByTk: job.id, values: { status: 'running' } });
|
|
243
|
+
|
|
244
|
+
for (const step of steps) {
|
|
245
|
+
if (step.stepOrder < startFromOrder) continue;
|
|
246
|
+
|
|
247
|
+
context.jobId = job.id;
|
|
248
|
+
currentOrder = step.stepOrder;
|
|
249
|
+
|
|
250
|
+
await jobsRepo.update({ filterByTk: job.id, values: { currentStep: currentOrder } });
|
|
251
|
+
|
|
252
|
+
if (!this.evaluateCondition(step.condition, context)) {
|
|
253
|
+
continue; // Skip step
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (!step.endpoint?.enabled) {
|
|
257
|
+
throw new Error(`Endpoint for step ${step.name} is disabled`);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const mappedBody = this.resolveMapping(step.inputMapping || {}, context);
|
|
261
|
+
let retries = step.onError === 'retry' ? step.retryCount || 0 : 0;
|
|
262
|
+
let success = false;
|
|
263
|
+
let lastError = null;
|
|
264
|
+
|
|
265
|
+
while (retries >= 0 && !success) {
|
|
266
|
+
try {
|
|
267
|
+
const fileFieldName = step.endpoint.fileFieldName || 'file';
|
|
268
|
+
const mappedFiles = context.files
|
|
269
|
+
? context.files.map((f) => ({
|
|
270
|
+
...f,
|
|
271
|
+
fieldName: fileFieldName,
|
|
272
|
+
}))
|
|
273
|
+
: [];
|
|
274
|
+
|
|
275
|
+
const result = await this.apiClient.call({
|
|
276
|
+
endpoint: step.endpoint,
|
|
277
|
+
body: mappedBody,
|
|
278
|
+
files: mappedFiles,
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
if (step.endpoint.executionMode === 'sync') {
|
|
282
|
+
context.stepResults[step.outputAlias || step.stepOrder.toString()] = result.data;
|
|
283
|
+
success = true;
|
|
284
|
+
} else if (step.endpoint.executionMode === 'polling') {
|
|
285
|
+
// Extract taskId from result based on pollTaskIdField
|
|
286
|
+
const taskIdField = step.endpoint.pollTaskIdField || 'task_id';
|
|
287
|
+
const taskId = this.getNestedValue(result.data, taskIdField);
|
|
288
|
+
|
|
289
|
+
if (!taskId) throw new Error(`Polling taskId not found in field ${taskIdField}`);
|
|
290
|
+
|
|
291
|
+
const externalTaskIds = job.externalTaskIds || {};
|
|
292
|
+
externalTaskIds[step.stepOrder.toString()] = taskId;
|
|
293
|
+
|
|
294
|
+
await jobsRepo.update({
|
|
295
|
+
filterByTk: job.id,
|
|
296
|
+
values: { status: 'polling', externalTaskIds },
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
await this.jobManager.startPolling(job.id, step.endpoint, taskId);
|
|
300
|
+
|
|
301
|
+
// Halt execution. Polling callback will resume from next step.
|
|
302
|
+
return;
|
|
303
|
+
} else if (step.endpoint.executionMode === 'webhook') {
|
|
304
|
+
// Wait for webhook
|
|
305
|
+
const taskIdField = step.endpoint.pollTaskIdField || 'task_id';
|
|
306
|
+
const taskId = this.getNestedValue(result.data, taskIdField);
|
|
307
|
+
const externalTaskIds = job.externalTaskIds || {};
|
|
308
|
+
externalTaskIds[step.stepOrder.toString()] = taskId;
|
|
309
|
+
|
|
310
|
+
await jobsRepo.update({
|
|
311
|
+
filterByTk: job.id,
|
|
312
|
+
values: { status: 'polling', externalTaskIds },
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
// End execution. Webhook will resume.
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
} catch (err: any) {
|
|
319
|
+
lastError = err;
|
|
320
|
+
retries--;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (!success) {
|
|
325
|
+
if (step.onError === 'fail') {
|
|
326
|
+
throw lastError || new Error(`Step ${step.name} failed`);
|
|
327
|
+
}
|
|
328
|
+
// if 'skip', we continue the loop
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// If loop completes without being halted for async
|
|
333
|
+
await this.finishJob(job.id, context);
|
|
334
|
+
} catch (err: any) {
|
|
335
|
+
await jobsRepo.update({
|
|
336
|
+
filterByTk: job.id,
|
|
337
|
+
values: { status: 'failed', error: err.message, completedAt: new Date() },
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async resumeFromStep(jobId: number, asyncResult: any) {
|
|
343
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
344
|
+
const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
|
|
345
|
+
|
|
346
|
+
const job = await jobsRepo.findOne({ filterByTk: jobId });
|
|
347
|
+
if (!job) throw new Error(`Job ${jobId} not found`);
|
|
348
|
+
|
|
349
|
+
const pipeline = await pipelineRepo.findOne({
|
|
350
|
+
filter: { id: job.pipelineId },
|
|
351
|
+
appends: ['steps', 'steps.endpoint'],
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
if (!pipeline) throw new Error(`Pipeline not found for job ${jobId}`);
|
|
355
|
+
|
|
356
|
+
const steps = [...(pipeline.steps || [])].sort((a, b) => a.stepOrder - b.stepOrder);
|
|
357
|
+
const step = steps.find((s) => s.stepOrder === job.currentStep);
|
|
358
|
+
|
|
359
|
+
if (step) {
|
|
360
|
+
job.stepResults = job.stepResults || {};
|
|
361
|
+
job.stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
|
|
362
|
+
|
|
363
|
+
await jobsRepo.update({
|
|
364
|
+
filterByTk: jobId,
|
|
365
|
+
values: { stepResults: job.stepResults }, // updating stepResults json
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const context: ExecutionContext = {
|
|
370
|
+
input: job.input,
|
|
371
|
+
files: [], // Files cannot easily persist across webhook unless stored in bucket. For now assume next steps use only json.
|
|
372
|
+
stepResults: job.stepResults,
|
|
373
|
+
jobId: job.id,
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
// resume from next step
|
|
377
|
+
this.runSteps(job, steps, context, job.currentStep + 1).catch((err) => {
|
|
378
|
+
this.logger.error(`Failed executing step ${job.currentStep + 1} for job ${job.id}`, err);
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
private async finishJob(jobId: number, context: ExecutionContext) {
|
|
383
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
384
|
+
const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
|
|
385
|
+
const job = await jobsRepo.findOne({ filterByTk: jobId });
|
|
386
|
+
if (!job) return;
|
|
387
|
+
|
|
388
|
+
const pipeline = await pipelineRepo.findOne({ filter: { id: job.pipelineId } });
|
|
389
|
+
if (!pipeline) return;
|
|
390
|
+
|
|
391
|
+
const finalResult = pipeline.outputMapping
|
|
392
|
+
? this.resolveMapping(pipeline.outputMapping, context)
|
|
393
|
+
: context.stepResults;
|
|
394
|
+
|
|
395
|
+
await jobsRepo.update({
|
|
396
|
+
filterByTk: jobId,
|
|
397
|
+
values: {
|
|
398
|
+
status: 'completed',
|
|
399
|
+
stepResults: context.stepResults,
|
|
400
|
+
finalResult,
|
|
401
|
+
completedAt: new Date(),
|
|
402
|
+
},
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
private resolveMapping(mapping: Record<string, string>, context: ExecutionContext): Record<string, any> {
|
|
407
|
+
const result: Record<string, any> = {};
|
|
408
|
+
for (const [key, value] of Object.entries(mapping)) {
|
|
409
|
+
if (typeof value === 'string') {
|
|
410
|
+
if (value.startsWith('$input.')) {
|
|
411
|
+
result[key] = this.getNestedValue(context.input, value.replace('$input.', ''));
|
|
412
|
+
} else if (value.startsWith('$step[')) {
|
|
413
|
+
const match = value.match(/\$step\[(.*?)\]\.response\.(.*)/);
|
|
414
|
+
if (match) {
|
|
415
|
+
const stepKey = match[1];
|
|
416
|
+
const path = match[2];
|
|
417
|
+
const stepResult = context.stepResults[stepKey];
|
|
418
|
+
result[key] = this.getNestedValue(stepResult, path);
|
|
419
|
+
} else {
|
|
420
|
+
result[key] = value;
|
|
421
|
+
}
|
|
422
|
+
} else if (value === '$files') {
|
|
423
|
+
// special case: mapping wants files. Not mapped here as form data handles files via input.files.
|
|
424
|
+
} else {
|
|
425
|
+
result[key] = value;
|
|
426
|
+
}
|
|
427
|
+
} else {
|
|
428
|
+
result[key] = value; // copy raw if not string mapping
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return result;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
private evaluateCondition(condition: any, context: ExecutionContext): boolean {
|
|
435
|
+
if (!condition) return true;
|
|
436
|
+
|
|
437
|
+
const resolveValue = (v: any) => {
|
|
438
|
+
if (typeof v === 'string' && v.startsWith('$')) {
|
|
439
|
+
// Resolve simple $ expressions
|
|
440
|
+
if (v.startsWith('$step[')) {
|
|
441
|
+
const match = v.match(/\$step\[(.*?)\]\.response\.(.*)/);
|
|
442
|
+
if (match) return this.getNestedValue(context.stepResults[match[1]], match[2]);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
return v;
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
const fieldVal = resolveValue(condition.field);
|
|
449
|
+
const val = resolveValue(condition.value);
|
|
450
|
+
|
|
451
|
+
switch (condition.op) {
|
|
452
|
+
case 'eq':
|
|
453
|
+
return fieldVal === val;
|
|
454
|
+
case 'neq':
|
|
455
|
+
return fieldVal !== val;
|
|
456
|
+
case 'gt':
|
|
457
|
+
return fieldVal > val;
|
|
458
|
+
case 'gte':
|
|
459
|
+
return fieldVal >= val;
|
|
460
|
+
case 'lt':
|
|
461
|
+
return fieldVal < val;
|
|
462
|
+
case 'lte':
|
|
463
|
+
return fieldVal <= val;
|
|
464
|
+
case 'in':
|
|
465
|
+
return Array.isArray(val) && val.includes(fieldVal);
|
|
466
|
+
case 'contains':
|
|
467
|
+
return typeof fieldVal === 'string' && fieldVal.includes(String(val));
|
|
468
|
+
default:
|
|
469
|
+
return false;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
private getNestedValue(obj: any, path: string): any {
|
|
474
|
+
if (!obj) return obj;
|
|
475
|
+
return path.split('.').reduce((acc, part) => acc && acc[part], obj);
|
|
476
|
+
}
|
|
477
|
+
}
|