plugin-document-understanding 1.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.
- package/README.md +366 -0
- package/client.d.ts +2 -0
- package/client.js +1 -0
- package/dist/client/components/EndpointsTab.d.ts +2 -0
- package/dist/client/components/JobsTab.d.ts +2 -0
- package/dist/client/components/PipelinesTab.d.ts +2 -0
- package/dist/client/components/PluginSettings.d.ts +2 -0
- package/dist/client/components/ServiceConfigTab.d.ts +2 -0
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.js +1 -0
- package/dist/client/locale.d.ts +10 -0
- package/dist/client/models/index.d.ts +11 -0
- package/dist/client/plugin.d.ts +5 -0
- package/dist/externalVersion.js +10 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +39 -0
- package/dist/locale/en-US.json +121 -0
- package/dist/locale/vi-VN.json +121 -0
- package/dist/locale/zh-CN.json +1 -0
- package/dist/server/actions.d.ts +16 -0
- package/dist/server/actions.js +109 -0
- package/dist/server/collections/config.d.ts +2 -0
- package/dist/server/collections/config.js +39 -0
- package/dist/server/collections/endpoints.d.ts +2 -0
- package/dist/server/collections/endpoints.js +47 -0
- package/dist/server/collections/jobs.d.ts +2 -0
- package/dist/server/collections/jobs.js +49 -0
- package/dist/server/collections/pipeline-steps.d.ts +2 -0
- package/dist/server/collections/pipeline-steps.js +47 -0
- package/dist/server/collections/pipelines.d.ts +2 -0
- package/dist/server/collections/pipelines.js +39 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +33 -0
- package/dist/server/plugin.d.ts +15 -0
- package/dist/server/plugin.js +102 -0
- package/dist/server/services/AsyncJobManager.d.ts +23 -0
- package/dist/server/services/AsyncJobManager.js +117 -0
- package/dist/server/services/DocumentUnderstandingService.d.ts +32 -0
- package/dist/server/services/DocumentUnderstandingService.js +189 -0
- package/dist/server/services/ExternalApiClient.d.ts +26 -0
- package/dist/server/services/ExternalApiClient.js +128 -0
- package/dist/server/services/PipelineExecutor.d.ts +23 -0
- package/dist/server/services/PipelineExecutor.js +252 -0
- package/dist/server/tools/document-understanding-tool.d.ts +8 -0
- package/dist/server/tools/document-understanding-tool.js +105 -0
- package/dist/server/types.d.ts +68 -0
- package/dist/server/types.js +15 -0
- package/package.json +16 -0
- package/server.d.ts +2 -0
- package/server.js +1 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Plugin } from '@nocobase/server';
|
|
2
|
+
import { DocumentUnderstandingService } from './services/DocumentUnderstandingService';
|
|
3
|
+
export declare class PluginDocumentUnderstandingServer extends Plugin {
|
|
4
|
+
service: DocumentUnderstandingService;
|
|
5
|
+
afterAdd(): Promise<void>;
|
|
6
|
+
beforeLoad(): Promise<void>;
|
|
7
|
+
load(): Promise<void>;
|
|
8
|
+
private registerActions;
|
|
9
|
+
private registerAITools;
|
|
10
|
+
install(): Promise<void>;
|
|
11
|
+
afterEnable(): Promise<void>;
|
|
12
|
+
afterDisable(): Promise<void>;
|
|
13
|
+
remove(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export default PluginDocumentUnderstandingServer;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var plugin_exports = {};
|
|
19
|
+
__export(plugin_exports, {
|
|
20
|
+
PluginDocumentUnderstandingServer: () => PluginDocumentUnderstandingServer,
|
|
21
|
+
default: () => plugin_default
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(plugin_exports);
|
|
24
|
+
var import_server = require("@nocobase/server");
|
|
25
|
+
var import_path = require("path");
|
|
26
|
+
var import_DocumentUnderstandingService = require("./services/DocumentUnderstandingService");
|
|
27
|
+
var import_actions = require("./actions");
|
|
28
|
+
var import_document_understanding_tool = require("./tools/document-understanding-tool");
|
|
29
|
+
class PluginDocumentUnderstandingServer extends import_server.Plugin {
|
|
30
|
+
service;
|
|
31
|
+
async afterAdd() {
|
|
32
|
+
}
|
|
33
|
+
async beforeLoad() {
|
|
34
|
+
}
|
|
35
|
+
async load() {
|
|
36
|
+
await this.importCollections((0, import_path.resolve)(__dirname, "collections"));
|
|
37
|
+
this.service = new import_DocumentUnderstandingService.DocumentUnderstandingService(this.app, this.db);
|
|
38
|
+
this.app.on("afterStart", async () => {
|
|
39
|
+
try {
|
|
40
|
+
await this.service.initialize();
|
|
41
|
+
} catch (err) {
|
|
42
|
+
this.app.logger.warn("Document Understanding plugin not configured yet, skip init.", err);
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
this.registerActions();
|
|
46
|
+
this.registerAITools();
|
|
47
|
+
this.app.acl.registerSnippet({
|
|
48
|
+
name: `pm.${this.name}`,
|
|
49
|
+
actions: ["docUnderstanding:*"]
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
registerActions() {
|
|
53
|
+
const actions = (0, import_actions.defineActions)(this);
|
|
54
|
+
const resourceName = "docUnderstanding";
|
|
55
|
+
this.app.resource({
|
|
56
|
+
name: resourceName,
|
|
57
|
+
actions: {
|
|
58
|
+
getConfig: actions.getConfig,
|
|
59
|
+
updateConfig: actions.updateConfig,
|
|
60
|
+
listEndpoints: actions.listEndpoints,
|
|
61
|
+
createEndpoint: actions.createEndpoint,
|
|
62
|
+
updateEndpoint: actions.updateEndpoint,
|
|
63
|
+
deleteEndpoint: actions.deleteEndpoint,
|
|
64
|
+
listPipelines: actions.listPipelines,
|
|
65
|
+
createPipeline: actions.createPipeline,
|
|
66
|
+
updatePipeline: actions.updatePipeline,
|
|
67
|
+
deletePipeline: actions.deletePipeline,
|
|
68
|
+
executePipeline: actions.executePipeline,
|
|
69
|
+
getJobStatus: actions.getJobStatus,
|
|
70
|
+
listJobs: actions.listJobs,
|
|
71
|
+
webhookCallback: actions.webhookCallback
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
registerAITools() {
|
|
76
|
+
var _a;
|
|
77
|
+
try {
|
|
78
|
+
const aiPlugin = this.app.pm.get("@nocobase/plugin-ai");
|
|
79
|
+
if (!((_a = aiPlugin == null ? void 0 : aiPlugin.ai) == null ? void 0 : _a.toolsManager)) {
|
|
80
|
+
this.app.logger.warn("Document Understanding: plugin-ai not available, skip AI tool registration.");
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
aiPlugin.ai.toolsManager.registerDynamicTools((0, import_document_understanding_tool.createDynamicPipelineToolsProvider)(this.service));
|
|
84
|
+
this.app.logger.info("Document Understanding: Dynamic pipeline tools provider registered.");
|
|
85
|
+
} catch (err) {
|
|
86
|
+
this.app.logger.warn("Document Understanding: Failed to register AI tools, continue without it.", err);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async install() {
|
|
90
|
+
}
|
|
91
|
+
async afterEnable() {
|
|
92
|
+
}
|
|
93
|
+
async afterDisable() {
|
|
94
|
+
}
|
|
95
|
+
async remove() {
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
var plugin_default = PluginDocumentUnderstandingServer;
|
|
99
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
100
|
+
0 && (module.exports = {
|
|
101
|
+
PluginDocumentUnderstandingServer
|
|
102
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Database } from '@nocobase/database';
|
|
2
|
+
import { ExternalApiClient } from './ExternalApiClient';
|
|
3
|
+
import { EndpointDef } from '../types';
|
|
4
|
+
export declare class AsyncJobManager {
|
|
5
|
+
private db;
|
|
6
|
+
private apiClient;
|
|
7
|
+
private intervals;
|
|
8
|
+
private onJobComplete;
|
|
9
|
+
private onJobError;
|
|
10
|
+
constructor(db: Database, apiClient: ExternalApiClient, callbacks: {
|
|
11
|
+
onJobComplete: (jobId: number, result: any) => Promise<void>;
|
|
12
|
+
onJobError: (jobId: number, error: string) => Promise<void>;
|
|
13
|
+
});
|
|
14
|
+
startPolling(jobId: number, endpoint: EndpointDef, taskId: string, customInterval?: number, customTimeout?: number): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* Recover polling jobs that were in-flight when server restarted.
|
|
17
|
+
* Call this during service initialization.
|
|
18
|
+
*/
|
|
19
|
+
recoverPollingJobs(): Promise<void>;
|
|
20
|
+
stopPolling(jobId: number): void;
|
|
21
|
+
destroy(): void;
|
|
22
|
+
private getNestedValue;
|
|
23
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var AsyncJobManager_exports = {};
|
|
19
|
+
__export(AsyncJobManager_exports, {
|
|
20
|
+
AsyncJobManager: () => AsyncJobManager
|
|
21
|
+
});
|
|
22
|
+
module.exports = __toCommonJS(AsyncJobManager_exports);
|
|
23
|
+
class AsyncJobManager {
|
|
24
|
+
db;
|
|
25
|
+
apiClient;
|
|
26
|
+
intervals = /* @__PURE__ */ new Map();
|
|
27
|
+
onJobComplete;
|
|
28
|
+
onJobError;
|
|
29
|
+
constructor(db, apiClient, callbacks) {
|
|
30
|
+
this.db = db;
|
|
31
|
+
this.apiClient = apiClient;
|
|
32
|
+
this.onJobComplete = callbacks.onJobComplete;
|
|
33
|
+
this.onJobError = callbacks.onJobError;
|
|
34
|
+
}
|
|
35
|
+
async startPolling(jobId, endpoint, taskId, customInterval, customTimeout) {
|
|
36
|
+
if (this.intervals.has(jobId)) return;
|
|
37
|
+
const interval = customInterval || endpoint.pollInterval || 5e3;
|
|
38
|
+
const timeout = customTimeout || endpoint.pollTimeout || 3e5;
|
|
39
|
+
const startTime = Date.now();
|
|
40
|
+
const timer = setInterval(async () => {
|
|
41
|
+
try {
|
|
42
|
+
if (Date.now() - startTime > timeout) {
|
|
43
|
+
this.stopPolling(jobId);
|
|
44
|
+
await this.onJobError(jobId, "Polling timeout exceeded");
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const url = endpoint.pollResultSubpath.replace("{taskId}", taskId);
|
|
48
|
+
const response = await this.apiClient.get(url);
|
|
49
|
+
if (endpoint.pollStatusField) {
|
|
50
|
+
const statusValue = this.getNestedValue(response, endpoint.pollStatusField);
|
|
51
|
+
const completedValue = endpoint.pollCompletedValue || "completed";
|
|
52
|
+
if (String(statusValue) === completedValue) {
|
|
53
|
+
const resultValue = endpoint.pollResultField ? this.getNestedValue(response, endpoint.pollResultField) : response;
|
|
54
|
+
this.stopPolling(jobId);
|
|
55
|
+
await this.onJobComplete(jobId, resultValue);
|
|
56
|
+
} else if (statusValue === "failed" || statusValue === "error") {
|
|
57
|
+
this.stopPolling(jobId);
|
|
58
|
+
await this.onJobError(jobId, `External task failed with status: ${statusValue}`);
|
|
59
|
+
}
|
|
60
|
+
} else {
|
|
61
|
+
const resultValue = endpoint.pollResultField ? this.getNestedValue(response, endpoint.pollResultField) : response;
|
|
62
|
+
if (resultValue !== void 0 && resultValue !== null) {
|
|
63
|
+
this.stopPolling(jobId);
|
|
64
|
+
await this.onJobComplete(jobId, resultValue);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
} catch (err) {
|
|
68
|
+
console.error(`Polling error for job ${jobId}: ${err.message}`);
|
|
69
|
+
}
|
|
70
|
+
}, interval);
|
|
71
|
+
this.intervals.set(jobId, timer);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Recover polling jobs that were in-flight when server restarted.
|
|
75
|
+
* Call this during service initialization.
|
|
76
|
+
*/
|
|
77
|
+
async recoverPollingJobs() {
|
|
78
|
+
var _a;
|
|
79
|
+
const jobsRepo = this.db.getRepository("doc_understanding_jobs");
|
|
80
|
+
const stuckJobs = await jobsRepo.find({ filter: { status: "polling" } });
|
|
81
|
+
for (const job of stuckJobs) {
|
|
82
|
+
if (!job.externalTaskIds) continue;
|
|
83
|
+
const stepKey = job.currentStep.toString();
|
|
84
|
+
const taskId = job.externalTaskIds[stepKey];
|
|
85
|
+
if (!taskId) continue;
|
|
86
|
+
const pipelineRepo = this.db.getRepository("doc_understanding_pipelines");
|
|
87
|
+
const pipeline = await pipelineRepo.findOne({
|
|
88
|
+
filter: { id: job.pipelineId },
|
|
89
|
+
appends: ["steps", "steps.endpoint"]
|
|
90
|
+
});
|
|
91
|
+
if (!pipeline) continue;
|
|
92
|
+
const step = (_a = pipeline.steps) == null ? void 0 : _a.find((s) => s.stepOrder === job.currentStep);
|
|
93
|
+
if (!(step == null ? void 0 : step.endpoint) || step.endpoint.executionMode !== "polling") continue;
|
|
94
|
+
await this.startPolling(job.id, step.endpoint, taskId);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
stopPolling(jobId) {
|
|
98
|
+
if (this.intervals.has(jobId)) {
|
|
99
|
+
clearInterval(this.intervals.get(jobId));
|
|
100
|
+
this.intervals.delete(jobId);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
destroy() {
|
|
104
|
+
for (const timer of this.intervals.values()) {
|
|
105
|
+
clearInterval(timer);
|
|
106
|
+
}
|
|
107
|
+
this.intervals.clear();
|
|
108
|
+
}
|
|
109
|
+
getNestedValue(obj, path) {
|
|
110
|
+
if (!obj) return obj;
|
|
111
|
+
return path.split(".").reduce((acc, part) => acc && acc[part], obj);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
115
|
+
0 && (module.exports = {
|
|
116
|
+
AsyncJobManager
|
|
117
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Application } from '@nocobase/server';
|
|
2
|
+
import { Database } from '@nocobase/database';
|
|
3
|
+
import { FileInput } from './ExternalApiClient';
|
|
4
|
+
import { ServiceConfig, EndpointDef, PipelineDef, JobState } from '../types';
|
|
5
|
+
export declare class DocumentUnderstandingService {
|
|
6
|
+
private app;
|
|
7
|
+
private db;
|
|
8
|
+
private apiClient;
|
|
9
|
+
private pipelineExecutor;
|
|
10
|
+
private jobManager;
|
|
11
|
+
private initialized;
|
|
12
|
+
constructor(app: Application, db: Database);
|
|
13
|
+
initialize(): Promise<void>;
|
|
14
|
+
isReady(): boolean;
|
|
15
|
+
getConfig(): Promise<ServiceConfig>;
|
|
16
|
+
updateConfig(data: Partial<ServiceConfig>): Promise<void>;
|
|
17
|
+
listEndpoints(): Promise<EndpointDef[]>;
|
|
18
|
+
createEndpoint(data: Partial<EndpointDef>): Promise<EndpointDef>;
|
|
19
|
+
updateEndpoint(id: number, data: Partial<EndpointDef>): Promise<void>;
|
|
20
|
+
deleteEndpoint(id: number): Promise<void>;
|
|
21
|
+
listPipelines(): Promise<PipelineDef[]>;
|
|
22
|
+
createPipeline(data: Partial<PipelineDef>): Promise<PipelineDef>;
|
|
23
|
+
updatePipeline(id: number, data: Partial<PipelineDef>): Promise<void>;
|
|
24
|
+
private validateStepAliases;
|
|
25
|
+
deletePipeline(id: number): Promise<void>;
|
|
26
|
+
executePipeline(pipelineId: number, input: Record<string, any>, files?: FileInput[], userId?: number): Promise<{
|
|
27
|
+
jobId: number;
|
|
28
|
+
}>;
|
|
29
|
+
getJobStatus(jobId: number): Promise<JobState>;
|
|
30
|
+
listJobs(filters?: any): Promise<JobState[]>;
|
|
31
|
+
handleWebhook(payload: any, signature?: string): Promise<void>;
|
|
32
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
21
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
22
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
23
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
24
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
25
|
+
mod
|
|
26
|
+
));
|
|
27
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
28
|
+
var DocumentUnderstandingService_exports = {};
|
|
29
|
+
__export(DocumentUnderstandingService_exports, {
|
|
30
|
+
DocumentUnderstandingService: () => DocumentUnderstandingService
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(DocumentUnderstandingService_exports);
|
|
33
|
+
var crypto = __toESM(require("crypto"));
|
|
34
|
+
var import_ExternalApiClient = require("./ExternalApiClient");
|
|
35
|
+
var import_AsyncJobManager = require("./AsyncJobManager");
|
|
36
|
+
var import_PipelineExecutor = require("./PipelineExecutor");
|
|
37
|
+
class DocumentUnderstandingService {
|
|
38
|
+
app;
|
|
39
|
+
db;
|
|
40
|
+
apiClient;
|
|
41
|
+
pipelineExecutor;
|
|
42
|
+
jobManager;
|
|
43
|
+
initialized = false;
|
|
44
|
+
constructor(app, db) {
|
|
45
|
+
this.app = app;
|
|
46
|
+
this.db = db;
|
|
47
|
+
}
|
|
48
|
+
async initialize() {
|
|
49
|
+
const configRepo = this.db.getRepository("doc_understanding_config");
|
|
50
|
+
let config = await configRepo.findOne();
|
|
51
|
+
if (!config) {
|
|
52
|
+
config = await configRepo.create({
|
|
53
|
+
values: {
|
|
54
|
+
baseUrl: "http://localhost:8000",
|
|
55
|
+
authType: "none",
|
|
56
|
+
defaultTimeout: 3e4,
|
|
57
|
+
defaultRetries: 2,
|
|
58
|
+
pollInterval: 5e3,
|
|
59
|
+
pollTimeout: 3e5
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
this.apiClient = new import_ExternalApiClient.ExternalApiClient(config);
|
|
64
|
+
this.jobManager = new import_AsyncJobManager.AsyncJobManager(this.db, this.apiClient, {
|
|
65
|
+
onJobComplete: async (jobId, result) => {
|
|
66
|
+
await this.pipelineExecutor.resumeFromStep(jobId, result);
|
|
67
|
+
},
|
|
68
|
+
onJobError: async (jobId, error) => {
|
|
69
|
+
const jobsRepo = this.db.getRepository("doc_understanding_jobs");
|
|
70
|
+
await jobsRepo.update({
|
|
71
|
+
filterByTk: jobId,
|
|
72
|
+
values: { status: "failed", error, completedAt: /* @__PURE__ */ new Date() }
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
this.pipelineExecutor = new import_PipelineExecutor.PipelineExecutor(this.db, this.apiClient, this.jobManager);
|
|
77
|
+
await this.jobManager.recoverPollingJobs();
|
|
78
|
+
this.initialized = true;
|
|
79
|
+
}
|
|
80
|
+
isReady() {
|
|
81
|
+
return this.initialized;
|
|
82
|
+
}
|
|
83
|
+
async getConfig() {
|
|
84
|
+
const configRepo = this.db.getRepository("doc_understanding_config");
|
|
85
|
+
const conf = await configRepo.findOne();
|
|
86
|
+
if (!conf) throw new Error("Config not found");
|
|
87
|
+
return conf;
|
|
88
|
+
}
|
|
89
|
+
async updateConfig(data) {
|
|
90
|
+
const configRepo = this.db.getRepository("doc_understanding_config");
|
|
91
|
+
const conf = await configRepo.findOne();
|
|
92
|
+
if (conf) {
|
|
93
|
+
await configRepo.update({ filterByTk: conf.id, values: data });
|
|
94
|
+
}
|
|
95
|
+
await this.initialize();
|
|
96
|
+
}
|
|
97
|
+
async listEndpoints() {
|
|
98
|
+
return this.db.getRepository("doc_understanding_endpoints").find({ sort: "sortOrder" });
|
|
99
|
+
}
|
|
100
|
+
async createEndpoint(data) {
|
|
101
|
+
return this.db.getRepository("doc_understanding_endpoints").create({ values: data });
|
|
102
|
+
}
|
|
103
|
+
async updateEndpoint(id, data) {
|
|
104
|
+
await this.db.getRepository("doc_understanding_endpoints").update({ filterByTk: id, values: data });
|
|
105
|
+
}
|
|
106
|
+
async deleteEndpoint(id) {
|
|
107
|
+
await this.db.getRepository("doc_understanding_endpoints").destroy({ filterByTk: id });
|
|
108
|
+
}
|
|
109
|
+
async listPipelines() {
|
|
110
|
+
return this.db.getRepository("doc_understanding_pipelines").find({
|
|
111
|
+
appends: ["steps", "steps.endpoint"]
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
async createPipeline(data) {
|
|
115
|
+
this.validateStepAliases(data.steps);
|
|
116
|
+
return this.db.getRepository("doc_understanding_pipelines").create({ values: data });
|
|
117
|
+
}
|
|
118
|
+
async updatePipeline(id, data) {
|
|
119
|
+
this.validateStepAliases(data.steps);
|
|
120
|
+
await this.db.getRepository("doc_understanding_pipelines").update({ filterByTk: id, values: data });
|
|
121
|
+
}
|
|
122
|
+
validateStepAliases(steps) {
|
|
123
|
+
if (!steps) return;
|
|
124
|
+
const aliases = steps.map((s) => s.outputAlias).filter(Boolean);
|
|
125
|
+
const unique = new Set(aliases);
|
|
126
|
+
if (unique.size !== aliases.length) {
|
|
127
|
+
throw new Error("Pipeline steps must have unique outputAlias values");
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async deletePipeline(id) {
|
|
131
|
+
await this.db.getRepository("doc_understanding_pipelines").destroy({ filterByTk: id });
|
|
132
|
+
}
|
|
133
|
+
async executePipeline(pipelineId, input, files = [], userId) {
|
|
134
|
+
if (!this.isReady()) throw new Error("Service not ready");
|
|
135
|
+
const job = await this.pipelineExecutor.execute(pipelineId, input, files, userId);
|
|
136
|
+
return { jobId: job.id };
|
|
137
|
+
}
|
|
138
|
+
async getJobStatus(jobId) {
|
|
139
|
+
const job = await this.db.getRepository("doc_understanding_jobs").findOne({ filterByTk: jobId });
|
|
140
|
+
if (!job) throw new Error("Job not found");
|
|
141
|
+
return job;
|
|
142
|
+
}
|
|
143
|
+
async listJobs(filters) {
|
|
144
|
+
return this.db.getRepository("doc_understanding_jobs").find({
|
|
145
|
+
filter: filters,
|
|
146
|
+
sort: ["-createdAt"]
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
async handleWebhook(payload, signature) {
|
|
150
|
+
const config = await this.getConfig();
|
|
151
|
+
if (config.webhookSecret) {
|
|
152
|
+
if (!signature) {
|
|
153
|
+
throw new Error("Webhook signature missing");
|
|
154
|
+
}
|
|
155
|
+
const expected = crypto.createHmac("sha256", config.webhookSecret).update(JSON.stringify(payload)).digest("hex");
|
|
156
|
+
const signatureHash = signature.startsWith("sha256=") ? signature.slice(7) : signature;
|
|
157
|
+
if (!crypto.timingSafeEqual(Buffer.from(signatureHash, "hex"), Buffer.from(expected, "hex"))) {
|
|
158
|
+
throw new Error("Webhook signature verification failed");
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const taskId = payload.task_id;
|
|
162
|
+
const result = payload.result;
|
|
163
|
+
if (!taskId) throw new Error("Webhook missing task_id");
|
|
164
|
+
const jobsRepo = this.db.getRepository("doc_understanding_jobs");
|
|
165
|
+
const PAGE_SIZE = 100;
|
|
166
|
+
let offset = 0;
|
|
167
|
+
while (true) {
|
|
168
|
+
const jobs = await jobsRepo.find({
|
|
169
|
+
filter: { status: "polling" },
|
|
170
|
+
limit: PAGE_SIZE,
|
|
171
|
+
offset
|
|
172
|
+
});
|
|
173
|
+
if (jobs.length === 0) break;
|
|
174
|
+
for (const job of jobs) {
|
|
175
|
+
if (Object.values(job.externalTaskIds || {}).includes(taskId)) {
|
|
176
|
+
await this.pipelineExecutor.resumeFromStep(job.id, result || payload);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (jobs.length < PAGE_SIZE) break;
|
|
181
|
+
offset += PAGE_SIZE;
|
|
182
|
+
}
|
|
183
|
+
throw new Error(`Job not found for webhook task ${taskId}`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
187
|
+
0 && (module.exports = {
|
|
188
|
+
DocumentUnderstandingService
|
|
189
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { ServiceConfig, EndpointDef } from '../types';
|
|
3
|
+
export interface FileInput {
|
|
4
|
+
fieldName: string;
|
|
5
|
+
buffer: Buffer;
|
|
6
|
+
filename: string;
|
|
7
|
+
mimeType: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ApiCallOptions {
|
|
10
|
+
endpoint: EndpointDef;
|
|
11
|
+
body?: Record<string, any>;
|
|
12
|
+
files?: FileInput[];
|
|
13
|
+
overrideHeaders?: Record<string, string>;
|
|
14
|
+
}
|
|
15
|
+
export declare class ExternalApiClient {
|
|
16
|
+
private config;
|
|
17
|
+
private client;
|
|
18
|
+
constructor(config: ServiceConfig);
|
|
19
|
+
private buildAuthHeaders;
|
|
20
|
+
call(options: ApiCallOptions): Promise<{
|
|
21
|
+
status: number;
|
|
22
|
+
data: any;
|
|
23
|
+
headers: any;
|
|
24
|
+
}>;
|
|
25
|
+
get(url: string, overrideHeaders?: Record<string, string>): Promise<any>;
|
|
26
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
21
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
22
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
23
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
24
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
25
|
+
mod
|
|
26
|
+
));
|
|
27
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
28
|
+
var ExternalApiClient_exports = {};
|
|
29
|
+
__export(ExternalApiClient_exports, {
|
|
30
|
+
ExternalApiClient: () => ExternalApiClient
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(ExternalApiClient_exports);
|
|
33
|
+
var import_axios = __toESM(require("axios"));
|
|
34
|
+
var import_form_data = __toESM(require("form-data"));
|
|
35
|
+
class ExternalApiClient {
|
|
36
|
+
config;
|
|
37
|
+
client;
|
|
38
|
+
constructor(config) {
|
|
39
|
+
this.config = config;
|
|
40
|
+
this.client = import_axios.default.create({
|
|
41
|
+
baseURL: config.baseUrl,
|
|
42
|
+
timeout: config.defaultTimeout
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
buildAuthHeaders() {
|
|
46
|
+
const headers = {};
|
|
47
|
+
if (!this.config.authType || this.config.authType === "none") {
|
|
48
|
+
return headers;
|
|
49
|
+
}
|
|
50
|
+
if (this.config.authType === "bearer" && this.config.authKey) {
|
|
51
|
+
headers["Authorization"] = `Bearer ${this.config.authKey}`;
|
|
52
|
+
} else if (this.config.authType === "api_key" && this.config.authKey) {
|
|
53
|
+
const name = this.config.authHeaderName || "x-api-key";
|
|
54
|
+
headers[name] = this.config.authKey;
|
|
55
|
+
} else if (this.config.authType === "custom_header" && this.config.authHeaderName && this.config.authKey) {
|
|
56
|
+
headers[this.config.authHeaderName] = this.config.authKey;
|
|
57
|
+
}
|
|
58
|
+
return headers;
|
|
59
|
+
}
|
|
60
|
+
async call(options) {
|
|
61
|
+
const { endpoint, body, files, overrideHeaders } = options;
|
|
62
|
+
const url = endpoint.subpath;
|
|
63
|
+
const method = endpoint.method.toLowerCase();
|
|
64
|
+
let requestData = body;
|
|
65
|
+
let headers = {
|
|
66
|
+
...this.buildAuthHeaders(),
|
|
67
|
+
...endpoint.customHeaders || {},
|
|
68
|
+
...overrideHeaders || {}
|
|
69
|
+
};
|
|
70
|
+
if (endpoint.fileInputMode === "multipart" && files && files.length > 0) {
|
|
71
|
+
const formData = new import_form_data.default();
|
|
72
|
+
if (body) {
|
|
73
|
+
for (const [key, value] of Object.entries(body)) {
|
|
74
|
+
formData.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
for (const file of files) {
|
|
78
|
+
formData.append(file.fieldName, file.buffer, {
|
|
79
|
+
filename: file.filename,
|
|
80
|
+
contentType: file.mimeType
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
requestData = formData;
|
|
84
|
+
headers = { ...headers, ...formData.getHeaders() };
|
|
85
|
+
} else if (endpoint.fileInputMode === "base64" && files && files.length > 0) {
|
|
86
|
+
const base64Files = {};
|
|
87
|
+
for (const f of files) {
|
|
88
|
+
base64Files[f.fieldName] = {
|
|
89
|
+
data: f.buffer.toString("base64"),
|
|
90
|
+
filename: f.filename,
|
|
91
|
+
mimeType: f.mimeType
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
requestData = { ...body, _files: base64Files };
|
|
95
|
+
headers["Content-Type"] = "application/json";
|
|
96
|
+
} else {
|
|
97
|
+
headers["Content-Type"] = "application/json";
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
const response = await this.client.request({
|
|
101
|
+
url,
|
|
102
|
+
method,
|
|
103
|
+
data: ["post", "put", "patch"].includes(method) ? requestData : void 0,
|
|
104
|
+
params: ["get", "delete"].includes(method) ? requestData : void 0,
|
|
105
|
+
headers
|
|
106
|
+
});
|
|
107
|
+
return {
|
|
108
|
+
status: response.status,
|
|
109
|
+
data: response.data,
|
|
110
|
+
headers: response.headers
|
|
111
|
+
};
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (error.response) {
|
|
114
|
+
throw new Error(`API Error [${error.response.status}]: ${JSON.stringify(error.response.data)}`);
|
|
115
|
+
}
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async get(url, overrideHeaders) {
|
|
120
|
+
const headers = { ...this.buildAuthHeaders(), ...overrideHeaders || {} };
|
|
121
|
+
const response = await this.client.get(url, { headers });
|
|
122
|
+
return response.data;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
126
|
+
0 && (module.exports = {
|
|
127
|
+
ExternalApiClient
|
|
128
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Database } from '@nocobase/database';
|
|
2
|
+
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
3
|
+
import { AsyncJobManager } from './AsyncJobManager';
|
|
4
|
+
import { JobState } from '../types';
|
|
5
|
+
export interface ExecutionContext {
|
|
6
|
+
input: Record<string, any>;
|
|
7
|
+
files: FileInput[];
|
|
8
|
+
stepResults: Record<string, any>;
|
|
9
|
+
jobId: number;
|
|
10
|
+
}
|
|
11
|
+
export declare class PipelineExecutor {
|
|
12
|
+
private db;
|
|
13
|
+
private apiClient;
|
|
14
|
+
private jobManager;
|
|
15
|
+
constructor(db: Database, apiClient: ExternalApiClient, jobManager: AsyncJobManager);
|
|
16
|
+
execute(pipelineId: number, input: Record<string, any>, files?: FileInput[], userId?: number): Promise<JobState>;
|
|
17
|
+
private runSteps;
|
|
18
|
+
resumeFromStep(jobId: number, asyncResult: any): Promise<void>;
|
|
19
|
+
private finishJob;
|
|
20
|
+
private resolveMapping;
|
|
21
|
+
private evaluateCondition;
|
|
22
|
+
private getNestedValue;
|
|
23
|
+
}
|