plugin-document-understanding 1.1.16 → 2.0.0

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 (82) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +19 -25
  3. package/dist/client/169.6888909107c553c3.js +10 -0
  4. package/dist/client/379.e29f5ced467ce23d.js +10 -0
  5. package/dist/client/867.3ed3b814115181ca.js +10 -0
  6. package/dist/client/index.js +1 -1
  7. package/dist/client-v2/169.53bf1be2ec192f0c.js +10 -0
  8. package/dist/client-v2/379.e75c4829567cdb89.js +10 -0
  9. package/dist/client-v2/867.66d7291e95f1de78.js +10 -0
  10. package/dist/client-v2/index.js +1 -1
  11. package/dist/externalVersion.js +9 -7
  12. package/dist/locale/en-US.json +126 -0
  13. package/dist/locale/vi-VN.json +130 -2
  14. package/dist/locale/zh-CN.json +127 -1
  15. package/dist/node_modules/form-data/package.json +1 -1
  16. package/dist/node_modules/mime-types/package.json +1 -1
  17. package/dist/server/actions.js +211 -11
  18. package/dist/server/collections/api-keys.js +55 -0
  19. package/dist/server/collections/artifacts.js +59 -0
  20. package/dist/server/collections/config.js +9 -3
  21. package/dist/server/collections/endpoints.js +3 -0
  22. package/dist/server/collections/jobs.js +7 -4
  23. package/dist/server/collections/operations.js +76 -0
  24. package/dist/server/contracts/du-contracts.js +828 -0
  25. package/dist/server/dugate-seed.js +98 -340
  26. package/dist/server/plugin.js +49 -7
  27. package/dist/server/routes/du-gateway-router.js +443 -0
  28. package/dist/server/services/ArtifactStorageService.js +459 -0
  29. package/dist/server/services/AsyncJobManager.js +1 -1
  30. package/dist/server/services/BuiltinBusinessEngine.js +1223 -0
  31. package/dist/server/services/DocumentUnderstandingService.js +151 -25
  32. package/dist/server/services/ExternalDuReworkClient.js +210 -0
  33. package/dist/server/services/OperationOrchestrator.js +1087 -0
  34. package/dist/server/services/PipelineExecutor.js +164 -43
  35. package/dist/server/tools/document-understanding-tool.js +49 -24
  36. package/dist/server/workflow/DocumentUnderstandingInstruction.js +292 -0
  37. package/package.json +8 -4
  38. package/src/client/index.tsx +11 -0
  39. package/src/client-v2/components/ApiKeysTab.tsx +198 -0
  40. package/src/client-v2/components/EndpointsTab.tsx +39 -2
  41. package/src/client-v2/components/JobsTab.tsx +136 -21
  42. package/src/client-v2/components/OperationsTab.tsx +586 -0
  43. package/src/client-v2/components/PluginSettings.tsx +12 -0
  44. package/src/client-v2/components/ServiceConfigTab.tsx +225 -65
  45. package/src/client-v2/components/__tests__/PluginSettings.test.tsx +4 -0
  46. package/src/client-v2/locale.ts +1 -8
  47. package/src/client-v2/models/index.ts +1 -8
  48. package/src/client-v2/plugin.tsx +12 -8
  49. package/src/client-v2/types.ts +13 -1
  50. package/src/client-v2/workflow/DocumentUnderstandingFieldset.tsx +122 -0
  51. package/src/client-v2/workflow/DocumentUnderstandingInstruction.tsx +49 -0
  52. package/src/locale/en-US.json +126 -0
  53. package/src/locale/vi-VN.json +130 -2
  54. package/src/locale/zh-CN.json +127 -1
  55. package/src/server/__tests__/actions.test.ts +1 -8
  56. package/src/server/__tests__/du-rework-gateway.test.ts +462 -0
  57. package/src/server/__tests__/dugate-integration.test.ts +79 -42
  58. package/src/server/__tests__/smoke.test.ts +1 -8
  59. package/src/server/__tests__/upload-security.test.ts +1 -8
  60. package/src/server/actions.ts +252 -36
  61. package/src/server/collections/api-keys.ts +35 -0
  62. package/src/server/collections/artifacts.ts +39 -0
  63. package/src/server/collections/config.ts +18 -2
  64. package/src/server/collections/endpoints.ts +12 -0
  65. package/src/server/collections/jobs.ts +16 -4
  66. package/src/server/collections/operations.ts +56 -0
  67. package/src/server/contracts/du-contracts.ts +1026 -0
  68. package/src/server/dugate-seed.ts +126 -453
  69. package/src/server/plugin.ts +64 -14
  70. package/src/server/routes/du-gateway-router.ts +465 -0
  71. package/src/server/services/ArtifactStorageService.ts +596 -0
  72. package/src/server/services/AsyncJobManager.ts +10 -1
  73. package/src/server/services/BuiltinBusinessEngine.ts +1544 -0
  74. package/src/server/services/DocumentUnderstandingService.ts +186 -44
  75. package/src/server/services/ExternalDuReworkClient.ts +222 -0
  76. package/src/server/services/OperationOrchestrator.ts +1359 -0
  77. package/src/server/services/PipelineExecutor.ts +245 -108
  78. package/src/server/tools/document-understanding-tool.ts +63 -45
  79. package/src/server/types.ts +101 -16
  80. package/src/server/workflow/DocumentUnderstandingInstruction.ts +308 -0
  81. package/dist/client/345.277fbb2b97424db5.js +0 -10
  82. package/dist/client-v2/345.2fa9834b46dd4531.js +0 -10
@@ -0,0 +1,596 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import * as crypto from 'crypto';
4
+ import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs';
5
+ import { basename, extname, resolve, sep } from 'path';
6
+ import type { Database } from '@nocobase/database';
7
+ import mime from 'mime-types';
8
+ import {
9
+ createProblem,
10
+ expandPageRanges,
11
+ type DuArtifactRole,
12
+ type DuArtifactState,
13
+ type PageSelectionSpec,
14
+ type ProblemDetails,
15
+ } from '../contracts/du-contracts';
16
+
17
+ export class DuHttpError extends Error {
18
+ public readonly problem: ProblemDetails;
19
+
20
+ constructor(problem: ProblemDetails) {
21
+ super(problem.detail || problem.title);
22
+ this.name = 'DuHttpError';
23
+ this.problem = problem;
24
+ }
25
+
26
+ get status(): number {
27
+ return this.problem.status;
28
+ }
29
+ }
30
+
31
+ export interface ArtifactRecord {
32
+ id?: number;
33
+ artifactId: string;
34
+ tenantId: string;
35
+ operationId?: string | null;
36
+ role: DuArtifactRole;
37
+ state: DuArtifactState;
38
+ fileName: string;
39
+ mimeType: string;
40
+ sizeBytes: number;
41
+ hashSha256?: string | null;
42
+ storagePath: string;
43
+ idempotencyKey?: string | null;
44
+ createdById?: number | null;
45
+ }
46
+
47
+ export interface ParsedPage {
48
+ pageNumber: number;
49
+ text: string;
50
+ }
51
+
52
+ export interface ParsedDocument {
53
+ artifactId: string;
54
+ fileName: string;
55
+ mimeType: string;
56
+ detectedFormat: string;
57
+ totalPageCount: number;
58
+ selectedPages: ParsedPage[];
59
+ markdown: string;
60
+ text: string;
61
+ requiresVision: boolean;
62
+ parser: string;
63
+ }
64
+
65
+ type LoadByWorkerFn = (
66
+ ext: string,
67
+ options: { filePath: string; mimeType?: string; timeout?: number },
68
+ ) => Promise<Array<{ pageContent: string; metadata?: Record<string, unknown> }>>;
69
+
70
+ const ARTIFACTS_COLLECTION = 'doc_understanding_artifacts';
71
+ const DEFAULT_GATEWAY_UPLOAD_MAX_BYTES = 64 * 1024 * 1024; // 64 MiB per BRD
72
+
73
+ function sanitizeSegment(raw: string, fallback: string): string {
74
+ const cleaned = basename(raw || fallback)
75
+ .replace(/[^a-zA-Z0-9._-]/g, '_')
76
+ .replace(/_{2,}/g, '_')
77
+ .slice(0, 120);
78
+ return cleaned || fallback;
79
+ }
80
+
81
+ function sha256Hex(buffer: Buffer): string {
82
+ return crypto.createHash('sha256').update(buffer).digest('hex');
83
+ }
84
+
85
+ function htmlToMarkdown(html: string): string {
86
+ return html
87
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
88
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
89
+ .replace(/<h1[^>]*>([\s\S]*?)<\/h1>/gi, '\n# $1\n')
90
+ .replace(/<h2[^>]*>([\s\S]*?)<\/h2>/gi, '\n## $1\n')
91
+ .replace(/<h3[^>]*>([\s\S]*?)<\/h3>/gi, '\n### $1\n')
92
+ .replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, '\n- $1')
93
+ .replace(/<br\s*\/?>/gi, '\n')
94
+ .replace(/<\/p>/gi, '\n\n')
95
+ .replace(/<\/tr>/gi, '\n')
96
+ .replace(/<t[dh][^>]*>([\s\S]*?)<\/t[dh]>/gi, ' | $1')
97
+ .replace(/<[^>]+>/g, '')
98
+ .replace(/&nbsp;/gi, ' ')
99
+ .replace(/&amp;/gi, '&')
100
+ .replace(/&lt;/gi, '<')
101
+ .replace(/&gt;/gi, '>')
102
+ .replace(/&quot;/gi, '"')
103
+ .replace(/\n{3,}/g, '\n\n')
104
+ .trim();
105
+ }
106
+
107
+ function toPlainRecord<T>(row: unknown): T {
108
+ if (row && typeof row === 'object' && typeof (row as { toJSON?: () => T }).toJSON === 'function') {
109
+ return (row as { toJSON: () => T }).toJSON();
110
+ }
111
+ return row as T;
112
+ }
113
+
114
+ function resolveAiWorkerLoader(): LoadByWorkerFn | null {
115
+ try {
116
+ // Loaded lazily so pure unit tests without worker runtime stay fast and deterministic.
117
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
118
+ const aiModule = require('@nocobase/ai') as { loadByWorker?: LoadByWorkerFn };
119
+ return typeof aiModule.loadByWorker === 'function' ? aiModule.loadByWorker : null;
120
+ } catch {
121
+ return null;
122
+ }
123
+ }
124
+
125
+ export class ArtifactStorageService {
126
+ private readonly db: Database;
127
+ private readonly storageRoot: string;
128
+
129
+ constructor(db: Database, customStorageRoot?: string) {
130
+ this.db = db;
131
+ this.storageRoot =
132
+ customStorageRoot || resolve(process.cwd(), 'storage', 'uploads', 'doc-understanding', 'artifacts');
133
+ mkdirSync(this.storageRoot, { recursive: true });
134
+ }
135
+
136
+ private assertSafeStoragePath(targetPath: string): string {
137
+ const resolvedRoot = existsSync(this.storageRoot) ? realpathSync(this.storageRoot) : resolve(this.storageRoot);
138
+ const resolvedTarget = resolve(targetPath);
139
+ if (resolvedTarget !== resolvedRoot && !resolvedTarget.startsWith(`${resolvedRoot}${sep}`)) {
140
+ throw new DuHttpError(createProblem(403, 'PERMISSION_DENIED', 'Artifact storage path is outside allowed root'));
141
+ }
142
+ return resolvedTarget;
143
+ }
144
+
145
+ private buildArtifactPath(tenantId: string, artifactId: string, fileName: string): string {
146
+ const safeTenant = sanitizeSegment(tenantId, 'default');
147
+ const tenantDir = resolve(this.storageRoot, safeTenant);
148
+ mkdirSync(tenantDir, { recursive: true });
149
+ const safeName = sanitizeSegment(fileName, 'document.bin');
150
+ return this.assertSafeStoragePath(resolve(tenantDir, `${artifactId}__${safeName}`));
151
+ }
152
+
153
+ async initiateUpload(params: {
154
+ tenantId: string;
155
+ fileName: string;
156
+ mimeType?: string;
157
+ sizeBytes: number;
158
+ uploadToken?: string;
159
+ idempotencyKey?: string;
160
+ maxFileSizeBytes?: number;
161
+ userId?: number;
162
+ urlPrefix?: string;
163
+ }): Promise<{
164
+ httpStatus: 200 | 201;
165
+ artifactId: string;
166
+ state: DuArtifactState;
167
+ replayed: boolean;
168
+ uploadUrl: string;
169
+ }> {
170
+ const {
171
+ tenantId,
172
+ fileName,
173
+ sizeBytes,
174
+ uploadToken,
175
+ idempotencyKey,
176
+ maxFileSizeBytes = DEFAULT_GATEWAY_UPLOAD_MAX_BYTES,
177
+ userId,
178
+ urlPrefix = '/api/du/v1',
179
+ } = params;
180
+
181
+ if (!fileName || typeof fileName !== 'string' || !fileName.trim()) {
182
+ throw new DuHttpError(
183
+ createProblem(422, 'INVALID_SCHEMA', 'fileName is required', {
184
+ errors: [{ pointer: '/fileName', message: 'Expected non-empty string' }],
185
+ }),
186
+ );
187
+ }
188
+ if (!Number.isFinite(sizeBytes) || sizeBytes < 0) {
189
+ throw new DuHttpError(
190
+ createProblem(422, 'INVALID_SCHEMA', 'sizeBytes must be a non-negative integer', {
191
+ errors: [{ pointer: '/sizeBytes', message: 'Expected integer >= 0' }],
192
+ }),
193
+ );
194
+ }
195
+ if (sizeBytes > maxFileSizeBytes) {
196
+ throw new DuHttpError(
197
+ createProblem(413, 'PAYLOAD_TOO_LARGE', `Upload size ${sizeBytes} exceeds limit ${maxFileSizeBytes} bytes`),
198
+ );
199
+ }
200
+
201
+ const resolvedMime = (params.mimeType || mime.lookup(fileName) || 'application/octet-stream').toString();
202
+ const repo = this.db.getRepository(ARTIFACTS_COLLECTION);
203
+ const dedupKey = idempotencyKey?.trim() || uploadToken?.trim();
204
+
205
+ if (dedupKey) {
206
+ const existingRow = await repo.findOne({
207
+ filter: uploadToken
208
+ ? { tenantId, $or: [{ artifactId: uploadToken }, { idempotencyKey: dedupKey }] }
209
+ : { tenantId, idempotencyKey: dedupKey },
210
+ });
211
+ if (existingRow) {
212
+ const existing = toPlainRecord<ArtifactRecord>(existingRow);
213
+ if (existing.fileName !== fileName || existing.mimeType !== resolvedMime) {
214
+ throw new DuHttpError(
215
+ createProblem(
216
+ 409,
217
+ 'IDEMPOTENCY_CONFLICT',
218
+ 'Idempotency-Key / uploadToken reused with different file metadata',
219
+ ),
220
+ );
221
+ }
222
+ return {
223
+ httpStatus: 200,
224
+ artifactId: existing.artifactId,
225
+ state: existing.state,
226
+ replayed: true,
227
+ uploadUrl: `${urlPrefix}/uploads/${existing.artifactId}/content`,
228
+ };
229
+ }
230
+ }
231
+
232
+ const artifactId =
233
+ uploadToken && /^[0-9a-fA-F-]{8,64}$/.test(uploadToken.trim()) ? uploadToken.trim() : crypto.randomUUID();
234
+ const storagePath = this.buildArtifactPath(tenantId, artifactId, fileName);
235
+
236
+ await repo.create({
237
+ values: {
238
+ artifactId,
239
+ tenantId,
240
+ role: 'input',
241
+ state: 'UPLOADING',
242
+ fileName: fileName.trim(),
243
+ mimeType: resolvedMime,
244
+ sizeBytes,
245
+ storagePath,
246
+ idempotencyKey: dedupKey || null,
247
+ createdById: userId ?? null,
248
+ },
249
+ });
250
+
251
+ return {
252
+ httpStatus: 201,
253
+ artifactId,
254
+ state: 'UPLOADING',
255
+ replayed: false,
256
+ uploadUrl: `${urlPrefix}/uploads/${artifactId}/content`,
257
+ };
258
+ }
259
+
260
+ async writeUploadContent(params: {
261
+ tenantId: string;
262
+ artifactId: string;
263
+ buffer: Buffer;
264
+ expectedSha256?: string;
265
+ maxFileSizeBytes?: number;
266
+ }): Promise<{
267
+ httpStatus: 200 | 201;
268
+ artifactId: string;
269
+ state: 'READY';
270
+ sizeBytes: number;
271
+ hashSha256: string;
272
+ replayed: boolean;
273
+ }> {
274
+ const {
275
+ tenantId,
276
+ artifactId,
277
+ buffer,
278
+ expectedSha256,
279
+ maxFileSizeBytes = DEFAULT_GATEWAY_UPLOAD_MAX_BYTES,
280
+ } = params;
281
+
282
+ if (buffer.length > maxFileSizeBytes) {
283
+ throw new DuHttpError(
284
+ createProblem(
285
+ 413,
286
+ 'PAYLOAD_TOO_LARGE',
287
+ `Payload size ${buffer.length} exceeds limit ${maxFileSizeBytes} bytes`,
288
+ ),
289
+ );
290
+ }
291
+
292
+ const repo = this.db.getRepository(ARTIFACTS_COLLECTION);
293
+ const row = await repo.findOne({ filter: { tenantId, artifactId } });
294
+ if (!row) {
295
+ throw new DuHttpError(createProblem(404, 'NOT_FOUND', `Upload session ${artifactId} not found`));
296
+ }
297
+
298
+ const record = toPlainRecord<ArtifactRecord>(row);
299
+ if (record.state === 'ABORTED') {
300
+ throw new DuHttpError(createProblem(409, 'STATE_CONFLICT', 'Upload session has already been aborted'));
301
+ }
302
+
303
+ const actualSha256 = sha256Hex(buffer);
304
+ if (expectedSha256 && expectedSha256.trim().toLowerCase() !== actualSha256) {
305
+ throw new DuHttpError(createProblem(422, 'CHECKSUM_MISMATCH', 'x-content-sha256 does not match uploaded bytes'));
306
+ }
307
+
308
+ if (record.state === 'READY') {
309
+ if (record.hashSha256 && record.hashSha256 !== actualSha256) {
310
+ throw new DuHttpError(
311
+ createProblem(409, 'IDEMPOTENCY_CONFLICT', 'Artifact content already finalized with a different digest'),
312
+ );
313
+ }
314
+ return {
315
+ httpStatus: 200,
316
+ artifactId,
317
+ state: 'READY',
318
+ sizeBytes: record.sizeBytes,
319
+ hashSha256: actualSha256,
320
+ replayed: true,
321
+ };
322
+ }
323
+
324
+ const safePath = this.assertSafeStoragePath(record.storagePath);
325
+ mkdirSync(resolve(safePath, '..'), { recursive: true });
326
+ writeFileSync(safePath, buffer);
327
+
328
+ await repo.update({
329
+ filter: { tenantId, artifactId },
330
+ values: {
331
+ state: 'READY',
332
+ sizeBytes: buffer.length,
333
+ hashSha256: actualSha256,
334
+ },
335
+ });
336
+
337
+ return {
338
+ httpStatus: 201,
339
+ artifactId,
340
+ state: 'READY',
341
+ sizeBytes: buffer.length,
342
+ hashSha256: actualSha256,
343
+ replayed: false,
344
+ };
345
+ }
346
+
347
+ async completeUpload(
348
+ tenantId: string,
349
+ artifactId: string,
350
+ ): Promise<{ artifactId: string; state: DuArtifactState; replayed: boolean }> {
351
+ const record = await this.getArtifactOrThrow(tenantId, artifactId);
352
+ if (record.state !== 'READY') {
353
+ throw new DuHttpError(
354
+ createProblem(409, 'STATE_CONFLICT', `Artifact ${artifactId} cannot complete from state ${record.state}`),
355
+ );
356
+ }
357
+ return { artifactId, state: 'READY', replayed: true };
358
+ }
359
+
360
+ async abortUpload(tenantId: string, artifactId: string): Promise<{ artifactId: string; state: 'ABORTED' }> {
361
+ const repo = this.db.getRepository(ARTIFACTS_COLLECTION);
362
+ const record = await this.getArtifactOrThrow(tenantId, artifactId);
363
+ if (record.state === 'READY') {
364
+ throw new DuHttpError(createProblem(409, 'STATE_CONFLICT', 'Cannot abort an already READY artifact'));
365
+ }
366
+ try {
367
+ const safePath = this.assertSafeStoragePath(record.storagePath);
368
+ if (existsSync(safePath)) {
369
+ rmSync(safePath, { force: true });
370
+ }
371
+ } catch {
372
+ // Ignore file removal errors on partial uploads
373
+ }
374
+ await repo.update({
375
+ filter: { tenantId, artifactId },
376
+ values: { state: 'ABORTED' },
377
+ });
378
+ return { artifactId, state: 'ABORTED' };
379
+ }
380
+
381
+ async createReadyArtifactFromBuffer(params: {
382
+ tenantId: string;
383
+ fileName: string;
384
+ mimeType?: string;
385
+ buffer: Buffer;
386
+ role?: DuArtifactRole;
387
+ operationId?: string;
388
+ userId?: number;
389
+ }): Promise<ArtifactRecord> {
390
+ const artifactId = crypto.randomUUID();
391
+ const resolvedMime = (params.mimeType || mime.lookup(params.fileName) || 'application/octet-stream').toString();
392
+ const storagePath = this.buildArtifactPath(params.tenantId, artifactId, params.fileName);
393
+ const hashSha256 = sha256Hex(params.buffer);
394
+ writeFileSync(storagePath, params.buffer);
395
+
396
+ const values: ArtifactRecord = {
397
+ artifactId,
398
+ tenantId: params.tenantId,
399
+ operationId: params.operationId ?? null,
400
+ role: params.role || 'input',
401
+ state: 'READY',
402
+ fileName: params.fileName,
403
+ mimeType: resolvedMime,
404
+ sizeBytes: params.buffer.length,
405
+ hashSha256,
406
+ storagePath,
407
+ createdById: params.userId ?? null,
408
+ };
409
+
410
+ const created = await this.db.getRepository(ARTIFACTS_COLLECTION).create({ values });
411
+ return toPlainRecord<ArtifactRecord>(created);
412
+ }
413
+
414
+ async createJsonOutputArtifact(params: {
415
+ tenantId: string;
416
+ operationId: string;
417
+ fileName?: string;
418
+ payload: unknown;
419
+ userId?: number;
420
+ }): Promise<ArtifactRecord> {
421
+ const serialized = Buffer.from(JSON.stringify(params.payload, null, 2), 'utf8');
422
+ return this.createReadyArtifactFromBuffer({
423
+ tenantId: params.tenantId,
424
+ operationId: params.operationId,
425
+ role: 'output',
426
+ fileName: params.fileName || `${params.operationId}.result.json`,
427
+ mimeType: 'application/json',
428
+ buffer: serialized,
429
+ userId: params.userId,
430
+ });
431
+ }
432
+
433
+ async getArtifactOrThrow(tenantId: string, artifactId: string): Promise<ArtifactRecord> {
434
+ const row = await this.db.getRepository(ARTIFACTS_COLLECTION).findOne({
435
+ filter: { tenantId, artifactId },
436
+ });
437
+ if (!row) {
438
+ throw new DuHttpError(createProblem(404, 'NOT_FOUND', `Artifact ${artifactId} not found`));
439
+ }
440
+ return toPlainRecord<ArtifactRecord>(row);
441
+ }
442
+
443
+ readArtifactBuffer(record: ArtifactRecord): Buffer {
444
+ if (record.state !== 'READY') {
445
+ throw new DuHttpError(
446
+ createProblem(
447
+ 409,
448
+ 'STATE_CONFLICT',
449
+ `Artifact ${record.artifactId} is in state ${record.state}, expected READY`,
450
+ ),
451
+ );
452
+ }
453
+ const safePath = this.assertSafeStoragePath(record.storagePath);
454
+ if (!existsSync(safePath)) {
455
+ throw new DuHttpError(createProblem(404, 'NOT_FOUND', `Artifact ${record.artifactId} blob missing from storage`));
456
+ }
457
+ return readFileSync(safePath);
458
+ }
459
+
460
+ /**
461
+ * Local Document Kit: parses digital documents (PDF, DOCX, XLSX, PPTX, CSV, TXT, MD, JSON, HTML)
462
+ * into per-page text/Markdown and applies DI-06 page selection when requested.
463
+ */
464
+ async parseArtifactPages(
465
+ record: ArtifactRecord,
466
+ selection: PageSelectionSpec = { kind: 'all' },
467
+ ): Promise<ParsedDocument> {
468
+ const buffer = this.readArtifactBuffer(record);
469
+ const ext = (extname(record.fileName) || `.${mime.extension(record.mimeType) || 'txt'}`).toLowerCase();
470
+ const isImage =
471
+ record.mimeType.startsWith('image/') || ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff'].includes(ext);
472
+
473
+ if (isImage) {
474
+ const pages: ParsedPage[] = [{ pageNumber: 1, text: '' }];
475
+ const selectedNums = expandPageRanges(selection, 1);
476
+ return {
477
+ artifactId: record.artifactId,
478
+ fileName: record.fileName,
479
+ mimeType: record.mimeType,
480
+ detectedFormat: ext.replace(/^\./, '') || 'image',
481
+ totalPageCount: 1,
482
+ selectedPages: pages.filter((p) => selectedNums.includes(p.pageNumber)),
483
+ markdown: '',
484
+ text: '',
485
+ requiresVision: true,
486
+ parser: 'image-vision-candidate',
487
+ };
488
+ }
489
+
490
+ let pages: ParsedPage[] = [];
491
+ let parserName = 'local-text';
492
+ let requiresVision = false;
493
+
494
+ if (ext === '.html' || ext === '.htm' || record.mimeType === 'text/html') {
495
+ const md = htmlToMarkdown(buffer.toString('utf8'));
496
+ pages = [{ pageNumber: 1, text: md }];
497
+ parserName = 'local-html';
498
+ } else if (ext === '.json' || record.mimeType === 'application/json') {
499
+ const raw = buffer.toString('utf8');
500
+ let formatted = raw;
501
+ try {
502
+ formatted = JSON.stringify(JSON.parse(raw), null, 2);
503
+ } catch {
504
+ // Keep raw text when malformed JSON is inspected
505
+ }
506
+ pages = [{ pageNumber: 1, text: formatted }];
507
+ parserName = 'local-json';
508
+ } else if (
509
+ ['.txt', '.md'].includes(ext) ||
510
+ record.mimeType.startsWith('text/plain') ||
511
+ record.mimeType === 'text/markdown'
512
+ ) {
513
+ const raw = buffer.toString('utf8');
514
+ const formFeedPages = raw.split('\f');
515
+ pages = formFeedPages.map((content, idx) => ({ pageNumber: idx + 1, text: content.trim() }));
516
+ if (pages.length === 0) pages = [{ pageNumber: 1, text: '' }];
517
+ parserName = 'local-text';
518
+ } else {
519
+ const workerLoader = resolveAiWorkerLoader();
520
+ const safePath = this.assertSafeStoragePath(record.storagePath);
521
+ if (workerLoader && ['.pdf', '.docx', '.doc', '.pptx', '.xlsx', '.xls', '.xlsm', '.csv'].includes(ext)) {
522
+ try {
523
+ const docs = await workerLoader(ext, {
524
+ filePath: safePath,
525
+ mimeType: record.mimeType,
526
+ timeout: 60_000,
527
+ });
528
+ if (docs.length > 0) {
529
+ pages = docs.map((doc, idx) => {
530
+ const loc = doc.metadata?.loc as { pageNumber?: number } | undefined;
531
+ const pageNumber = typeof loc?.pageNumber === 'number' ? loc.pageNumber : idx + 1;
532
+ return { pageNumber, text: (doc.pageContent || '').trim() };
533
+ });
534
+ parserName = 'nocobase-ai-worker';
535
+ }
536
+ } catch {
537
+ // Fall through to lightweight fallback below
538
+ }
539
+ }
540
+
541
+ if (pages.length === 0) {
542
+ if (ext === '.csv' || record.mimeType === 'text/csv') {
543
+ pages = [{ pageNumber: 1, text: buffer.toString('utf8').trim() }];
544
+ parserName = 'local-csv';
545
+ } else if (ext === '.pdf' || record.mimeType === 'application/pdf') {
546
+ // Scanned or image-only PDF with no text layer extracted
547
+ pages = [{ pageNumber: 1, text: '' }];
548
+ requiresVision = true;
549
+ parserName = 'pdf-ocr-candidate';
550
+ } else {
551
+ pages = [{ pageNumber: 1, text: buffer.toString('utf8').trim() }];
552
+ parserName = 'utf8-fallback';
553
+ }
554
+ }
555
+ }
556
+
557
+ if (pages.every((p) => !p.text.trim()) && (ext === '.pdf' || record.mimeType === 'application/pdf')) {
558
+ requiresVision = true;
559
+ }
560
+
561
+ const totalPageCount = Math.max(pages.length, 1);
562
+ let selectedNums: number[];
563
+ try {
564
+ selectedNums = expandPageRanges(selection, totalPageCount);
565
+ } catch (err) {
566
+ throw new DuHttpError(
567
+ createProblem(422, 'INVALID_SCHEMA', err instanceof Error ? err.message : String(err), {
568
+ errors: [{ pointer: '/documentSelection', message: err instanceof Error ? err.message : String(err) }],
569
+ }),
570
+ );
571
+ }
572
+
573
+ const selectedPages = pages.filter((p) => selectedNums.includes(p.pageNumber));
574
+ const joinedMarkdown = selectedPages
575
+ .map((p) => (totalPageCount > 1 ? `<!-- page ${p.pageNumber} -->\n${p.text}` : p.text))
576
+ .join('\n\n')
577
+ .trim();
578
+ const joinedText = selectedPages
579
+ .map((p) => p.text)
580
+ .join('\n\n')
581
+ .trim();
582
+
583
+ return {
584
+ artifactId: record.artifactId,
585
+ fileName: record.fileName,
586
+ mimeType: record.mimeType,
587
+ detectedFormat: ext.replace(/^\./, '') || 'bin',
588
+ totalPageCount,
589
+ selectedPages,
590
+ markdown: joinedMarkdown,
591
+ text: joinedText,
592
+ requiresVision,
593
+ parser: parserName,
594
+ };
595
+ }
596
+ }
@@ -1,3 +1,12 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
1
10
  import { Database } from '@nocobase/database';
2
11
  import { ExternalApiClient } from './ExternalApiClient';
3
12
  import { EndpointDef } from '../types';
@@ -95,7 +104,7 @@ export class AsyncJobManager {
95
104
  : response;
96
105
  this.stopPolling(jobId);
97
106
  await this.onJobComplete(jobId, resultValue);
98
- } else if (statusValue === 'failed' || statusValue === 'error') {
107
+ } else if (['failed', 'error', 'cancelled', 'timed_out'].includes(String(statusValue).toLowerCase())) {
99
108
  this.stopPolling(jobId);
100
109
  await this.onJobError(jobId, `External task failed with status: ${statusValue}`);
101
110
  }