plugin-document-understanding 1.1.3 → 1.1.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.
- package/README.md +21 -8
- package/client-v2.d.ts +2 -0
- package/client-v2.js +1 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/794.9b984a25b2fc7c14.js +10 -0
- package/dist/client-v2/index.js +10 -0
- package/dist/externalVersion.js +7 -6
- package/dist/node_modules/form-data/License +19 -0
- package/dist/node_modules/form-data/index.d.ts +62 -0
- package/dist/node_modules/form-data/lib/browser.js +4 -0
- package/dist/node_modules/form-data/lib/form_data.js +14 -0
- package/dist/node_modules/form-data/lib/populate.js +10 -0
- package/dist/node_modules/form-data/package.json +1 -0
- package/dist/node_modules/mime-types/LICENSE +23 -0
- package/dist/node_modules/mime-types/index.js +14 -0
- package/dist/node_modules/mime-types/package.json +1 -0
- package/dist/server/actions.js +7 -6
- package/dist/server/collections/endpoints.js +1 -1
- package/dist/server/plugin.js +7 -3
- package/dist/server/services/AsyncJobManager.js +14 -5
- package/dist/server/services/DocumentUnderstandingService.js +53 -23
- package/dist/server/services/PipelineExecutor.js +81 -94
- package/package.json +49 -16
- package/src/client/index.tsx +9 -0
- package/src/client-v2/client.d.ts +249 -0
- package/src/client-v2/components/EndpointsTab.tsx +458 -0
- package/src/client-v2/components/JobsTab.tsx +259 -0
- package/src/client-v2/components/PipelinesTab.tsx +872 -0
- package/src/client-v2/components/PluginSettings.tsx +48 -0
- package/src/client-v2/components/ServiceConfigTab.tsx +122 -0
- package/src/client-v2/locale.ts +21 -0
- package/{dist/client/models/index.d.ts → src/client-v2/models/index.ts} +3 -2
- package/src/client-v2/plugin.tsx +21 -0
- package/src/locale/en-US.json +121 -0
- package/src/locale/vi-VN.json +121 -0
- package/src/locale/zh-CN.json +1 -0
- package/src/server/__tests__/actions.test.ts +98 -0
- package/src/server/__tests__/pipeline-executor.test.ts +33 -0
- package/src/server/__tests__/smoke.test.ts +55 -0
- package/src/server/actions.ts +176 -0
- package/src/server/collections/.gitkeep +0 -0
- package/src/server/collections/config.ts +18 -0
- package/src/server/collections/endpoints.ts +28 -0
- package/src/server/collections/jobs.ts +29 -0
- package/src/server/collections/pipeline-steps.ts +27 -0
- package/src/server/collections/pipelines.ts +19 -0
- package/src/server/plugin.ts +108 -0
- package/src/server/services/AsyncJobManager.ts +172 -0
- package/src/server/services/DocumentUnderstandingService.ts +264 -0
- package/src/server/services/ExternalApiClient.ts +143 -0
- package/src/server/services/PipelineExecutor.ts +502 -0
- package/src/server/tools/document-understanding-tool.ts +181 -0
- package/src/server/types.ts +73 -0
- package/dist/client/components/EndpointsTab.d.ts +0 -2
- package/dist/client/components/JobsTab.d.ts +0 -2
- package/dist/client/components/PipelinesTab.d.ts +0 -2
- package/dist/client/components/PluginSettings.d.ts +0 -2
- package/dist/client/components/ServiceConfigTab.d.ts +0 -2
- package/dist/client/locale.d.ts +0 -10
- package/dist/client/plugin.d.ts +0 -6
- package/dist/server/actions.d.ts +0 -17
- package/dist/server/collections/config.d.ts +0 -3
- package/dist/server/collections/endpoints.d.ts +0 -3
- package/dist/server/collections/jobs.d.ts +0 -3
- package/dist/server/collections/pipeline-steps.d.ts +0 -3
- package/dist/server/collections/pipelines.d.ts +0 -3
- package/dist/server/plugin.d.ts +0 -15
- package/dist/server/services/AsyncJobManager.d.ts +0 -27
- package/dist/server/services/DocumentUnderstandingService.d.ts +0 -35
- package/dist/server/services/ExternalApiClient.d.ts +0 -28
- package/dist/server/services/PipelineExecutor.d.ts +0 -24
- package/dist/server/tools/document-understanding-tool.d.ts +0 -8
- package/dist/server/types.d.ts +0 -69
- /package/{dist/client/index.d.ts → src/client-v2/index.tsx} +0 -0
- /package/{dist/index.d.ts → src/index.ts} +0 -0
- /package/{dist/server/index.d.ts → src/server/index.ts} +0 -0
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import * as crypto from 'crypto';
|
|
2
|
+
import { Application } from '@nocobase/server';
|
|
3
|
+
import { Database, Repository } from '@nocobase/database';
|
|
4
|
+
import { ExternalApiClient, FileInput } from './ExternalApiClient';
|
|
5
|
+
import { AsyncJobManager } from './AsyncJobManager';
|
|
6
|
+
import { PipelineExecutor } from './PipelineExecutor';
|
|
7
|
+
import { ServiceConfig, EndpointDef, PipelineDef, JobState } from '../types';
|
|
8
|
+
|
|
9
|
+
export class DocumentUnderstandingService {
|
|
10
|
+
private app: Application;
|
|
11
|
+
private db: Database;
|
|
12
|
+
private apiClient!: ExternalApiClient;
|
|
13
|
+
private pipelineExecutor!: PipelineExecutor;
|
|
14
|
+
private jobManager!: AsyncJobManager;
|
|
15
|
+
private initialized = false;
|
|
16
|
+
private startupRecoveryCompleted = false;
|
|
17
|
+
private initializationPromise?: Promise<void>;
|
|
18
|
+
private static readonly HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
19
|
+
|
|
20
|
+
constructor(app: Application, db: Database) {
|
|
21
|
+
this.app = app;
|
|
22
|
+
this.db = db;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async initialize(options: { recoverJobs?: boolean } = {}): Promise<void> {
|
|
26
|
+
if (this.initializationPromise) {
|
|
27
|
+
await this.initializationPromise;
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
this.initializationPromise = this.doInitialize(options.recoverJobs ?? false).finally(() => {
|
|
32
|
+
this.initializationPromise = undefined;
|
|
33
|
+
});
|
|
34
|
+
await this.initializationPromise;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async ensureInitialized(): Promise<void> {
|
|
38
|
+
if (this.initialized) return;
|
|
39
|
+
await this.initialize();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
private async doInitialize(recoverJobs: boolean): Promise<void> {
|
|
43
|
+
const config = await this.ensureConfig();
|
|
44
|
+
|
|
45
|
+
this.jobManager?.destroy();
|
|
46
|
+
this.apiClient = new ExternalApiClient(config);
|
|
47
|
+
this.jobManager = new AsyncJobManager(
|
|
48
|
+
this.db,
|
|
49
|
+
this.apiClient,
|
|
50
|
+
{
|
|
51
|
+
onJobComplete: async (jobId, result) => {
|
|
52
|
+
await this.pipelineExecutor.resumeFromStep(jobId, result);
|
|
53
|
+
},
|
|
54
|
+
onJobError: async (jobId, error) => {
|
|
55
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
56
|
+
await jobsRepo.update({
|
|
57
|
+
filterByTk: jobId,
|
|
58
|
+
values: { status: 'failed', error, completedAt: new Date() },
|
|
59
|
+
});
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
this.app.logger,
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
this.pipelineExecutor = new PipelineExecutor(this.db, this.apiClient, this.jobManager, this.app.logger);
|
|
66
|
+
|
|
67
|
+
if (recoverJobs && !this.startupRecoveryCompleted) {
|
|
68
|
+
await this.jobManager.cleanupStuckJobs();
|
|
69
|
+
await this.jobManager.recoverPollingJobs();
|
|
70
|
+
this.startupRecoveryCompleted = true;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
this.initialized = true;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
private async ensureConfig(): Promise<ServiceConfig> {
|
|
77
|
+
const configRepo = this.db.getRepository<any>('doc_understanding_config');
|
|
78
|
+
let config = await configRepo.findOne();
|
|
79
|
+
|
|
80
|
+
if (!config) {
|
|
81
|
+
config = await configRepo.create({
|
|
82
|
+
values: {
|
|
83
|
+
baseUrl: 'http://localhost:8000',
|
|
84
|
+
authType: 'none',
|
|
85
|
+
defaultTimeout: 30000,
|
|
86
|
+
defaultRetries: 2,
|
|
87
|
+
pollInterval: 5000,
|
|
88
|
+
pollTimeout: 300000,
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return config;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
isReady(): boolean {
|
|
97
|
+
return this.initialized;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async getConfig(): Promise<ServiceConfig> {
|
|
101
|
+
return this.ensureConfig();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async updateConfig(data: Partial<ServiceConfig>): Promise<void> {
|
|
105
|
+
const configRepo = this.db.getRepository<any>('doc_understanding_config');
|
|
106
|
+
const conf = await configRepo.findOne();
|
|
107
|
+
if (conf) {
|
|
108
|
+
await configRepo.update({ filterByTk: conf.id, values: data });
|
|
109
|
+
}
|
|
110
|
+
// Reinitialize to pick up new config
|
|
111
|
+
await this.initialize();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async listEndpoints(): Promise<EndpointDef[]> {
|
|
115
|
+
await this.ensureInitialized();
|
|
116
|
+
return this.db.getRepository<any>('doc_understanding_endpoints').find({ sort: 'sortOrder' });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async createEndpoint(data: Partial<EndpointDef>): Promise<EndpointDef> {
|
|
120
|
+
return this.db.getRepository<any>('doc_understanding_endpoints').create({ values: this.normalizeEndpoint(data) });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async updateEndpoint(id: number, data: Partial<EndpointDef>): Promise<void> {
|
|
124
|
+
await this.db.getRepository<any>('doc_understanding_endpoints').update({
|
|
125
|
+
filterByTk: id,
|
|
126
|
+
values: this.normalizeEndpoint(data),
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private normalizeEndpoint(data: Partial<EndpointDef> = {}): Partial<EndpointDef> {
|
|
131
|
+
if (!Object.prototype.hasOwnProperty.call(data, 'customHeaders')) {
|
|
132
|
+
return data;
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
...data,
|
|
136
|
+
customHeaders: this.normalizeHeaders(data.customHeaders),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private normalizeHeaders(headers?: Record<string, any>): Record<string, string> {
|
|
141
|
+
const normalized: Record<string, string> = {};
|
|
142
|
+
if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
|
|
143
|
+
return normalized;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
for (const [rawName, rawValue] of Object.entries(headers)) {
|
|
147
|
+
const name = rawName.trim();
|
|
148
|
+
if (!name) continue;
|
|
149
|
+
if (!DocumentUnderstandingService.HEADER_NAME_RE.test(name)) {
|
|
150
|
+
throw new Error(`Invalid HTTP header name: ${rawName}`);
|
|
151
|
+
}
|
|
152
|
+
if (rawValue === undefined || rawValue === null) continue;
|
|
153
|
+
normalized[name] = String(rawValue);
|
|
154
|
+
}
|
|
155
|
+
return normalized;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async deleteEndpoint(id: number): Promise<void> {
|
|
159
|
+
await this.db.getRepository<any>('doc_understanding_endpoints').destroy({ filterByTk: id });
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async listPipelines(): Promise<PipelineDef[]> {
|
|
163
|
+
await this.ensureInitialized();
|
|
164
|
+
return this.db.getRepository<any>('doc_understanding_pipelines').find({
|
|
165
|
+
appends: ['steps', 'steps.endpoint'],
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async createPipeline(data: Partial<PipelineDef>): Promise<PipelineDef> {
|
|
170
|
+
this.validateStepAliases(data.steps);
|
|
171
|
+
return this.db.getRepository<any>('doc_understanding_pipelines').create({ values: data });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async updatePipeline(id: number, data: Partial<PipelineDef>): Promise<void> {
|
|
175
|
+
this.validateStepAliases(data.steps);
|
|
176
|
+
await this.db.getRepository<any>('doc_understanding_pipelines').update({ filterByTk: id, values: data });
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
private validateStepAliases(steps?: any[]) {
|
|
180
|
+
if (!steps) return;
|
|
181
|
+
const aliases = steps.map((s) => s.outputAlias).filter(Boolean);
|
|
182
|
+
const unique = new Set(aliases);
|
|
183
|
+
if (unique.size !== aliases.length) {
|
|
184
|
+
throw new Error('Pipeline steps must have unique outputAlias values');
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async deletePipeline(id: number): Promise<void> {
|
|
189
|
+
await this.db.getRepository<any>('doc_understanding_pipelines').destroy({ filterByTk: id });
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async executePipeline(
|
|
193
|
+
pipelineId: number,
|
|
194
|
+
input: Record<string, any>,
|
|
195
|
+
files: FileInput[] = [],
|
|
196
|
+
userId?: number,
|
|
197
|
+
): Promise<{ jobId: number }> {
|
|
198
|
+
await this.ensureInitialized();
|
|
199
|
+
const job = await this.pipelineExecutor.execute(pipelineId, input, files, userId);
|
|
200
|
+
return { jobId: job.id };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async getJobStatus(jobId: number): Promise<JobState> {
|
|
204
|
+
const job = await this.db.getRepository<any>('doc_understanding_jobs').findOne({ filterByTk: jobId });
|
|
205
|
+
if (!job) throw new Error('Job not found');
|
|
206
|
+
return job;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async listJobs(filters?: any): Promise<JobState[]> {
|
|
210
|
+
return this.db.getRepository<any>('doc_understanding_jobs').find({
|
|
211
|
+
filter: filters,
|
|
212
|
+
sort: ['-createdAt'],
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async handleWebhook(payload: any, signature?: string): Promise<void> {
|
|
217
|
+
await this.ensureInitialized();
|
|
218
|
+
const config = await this.getConfig();
|
|
219
|
+
if (config.webhookSecret) {
|
|
220
|
+
if (!signature) {
|
|
221
|
+
throw new Error('Webhook signature missing');
|
|
222
|
+
}
|
|
223
|
+
const expected = crypto.createHmac('sha256', config.webhookSecret).update(JSON.stringify(payload)).digest('hex');
|
|
224
|
+
const signatureHash = signature.startsWith('sha256=') ? signature.slice(7) : signature;
|
|
225
|
+
if (!crypto.timingSafeEqual(Buffer.from(signatureHash, 'hex'), Buffer.from(expected, 'hex'))) {
|
|
226
|
+
throw new Error('Webhook signature verification failed');
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const taskId = payload.task_id;
|
|
231
|
+
const result = payload.result;
|
|
232
|
+
if (!taskId) throw new Error('Webhook missing task_id');
|
|
233
|
+
|
|
234
|
+
// Paginated search to avoid loading all polling jobs into memory
|
|
235
|
+
const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
|
|
236
|
+
const PAGE_SIZE = 100;
|
|
237
|
+
let offset = 0;
|
|
238
|
+
let hasMoreJobs = true;
|
|
239
|
+
|
|
240
|
+
while (hasMoreJobs) {
|
|
241
|
+
const jobs = await jobsRepo.find({
|
|
242
|
+
filter: { status: 'polling' },
|
|
243
|
+
limit: PAGE_SIZE,
|
|
244
|
+
offset,
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
if (jobs.length === 0) break;
|
|
248
|
+
|
|
249
|
+
for (const job of jobs) {
|
|
250
|
+
if (Object.values(job.externalTaskIds || {}).includes(taskId)) {
|
|
251
|
+
await this.pipelineExecutor.resumeFromStep(job.id, result || payload);
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
hasMoreJobs = jobs.length >= PAGE_SIZE;
|
|
257
|
+
if (hasMoreJobs) {
|
|
258
|
+
offset += PAGE_SIZE;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
throw new Error(`Job not found for webhook task ${taskId}`);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import axios, { AxiosInstance, AxiosResponse } from 'axios';
|
|
2
|
+
import { ServiceConfig, EndpointDef } from '../types';
|
|
3
|
+
import FormData from 'form-data';
|
|
4
|
+
|
|
5
|
+
export interface FileInput {
|
|
6
|
+
fieldName: string;
|
|
7
|
+
buffer: Buffer;
|
|
8
|
+
filename: string;
|
|
9
|
+
mimeType: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ApiCallOptions {
|
|
13
|
+
endpoint: EndpointDef;
|
|
14
|
+
body?: Record<string, any>;
|
|
15
|
+
files?: FileInput[];
|
|
16
|
+
overrideHeaders?: Record<string, string>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class ExternalApiClient {
|
|
20
|
+
private config: ServiceConfig;
|
|
21
|
+
private client: AxiosInstance;
|
|
22
|
+
private static readonly HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
23
|
+
|
|
24
|
+
constructor(config: ServiceConfig) {
|
|
25
|
+
this.config = config;
|
|
26
|
+
this.client = axios.create({
|
|
27
|
+
baseURL: config.baseUrl,
|
|
28
|
+
timeout: config.defaultTimeout,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
private buildAuthHeaders(): Record<string, string> {
|
|
33
|
+
const headers: Record<string, string> = {};
|
|
34
|
+
if (!this.config.authType || this.config.authType === 'none') {
|
|
35
|
+
return headers;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (this.config.authType === 'bearer' && this.config.authKey) {
|
|
39
|
+
headers['Authorization'] = `Bearer ${this.config.authKey}`;
|
|
40
|
+
} else if (this.config.authType === 'api_key' && this.config.authKey) {
|
|
41
|
+
// Assuming api_key is sent in Authorization header or x-api-key based on common patterns.
|
|
42
|
+
// Usually authHeaderName handles custom API keys, but we'll default to x-api-key if not provided.
|
|
43
|
+
const name = this.config.authHeaderName || 'x-api-key';
|
|
44
|
+
headers[name] = this.config.authKey;
|
|
45
|
+
} else if (this.config.authType === 'custom_header' && this.config.authHeaderName && this.config.authKey) {
|
|
46
|
+
headers[this.config.authHeaderName] = this.config.authKey;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return headers;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
private sanitizeHeaders(headers?: Record<string, any>): Record<string, string> {
|
|
53
|
+
const normalized: Record<string, string> = {};
|
|
54
|
+
if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
|
|
55
|
+
return normalized;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
for (const [rawName, rawValue] of Object.entries(headers)) {
|
|
59
|
+
const name = rawName.trim();
|
|
60
|
+
if (!name) continue;
|
|
61
|
+
if (!ExternalApiClient.HEADER_NAME_RE.test(name)) {
|
|
62
|
+
throw new Error(`Invalid HTTP header name: ${rawName}`);
|
|
63
|
+
}
|
|
64
|
+
if (rawValue === undefined || rawValue === null) continue;
|
|
65
|
+
normalized[name] = String(rawValue);
|
|
66
|
+
}
|
|
67
|
+
return normalized;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async call(options: ApiCallOptions): Promise<{ status: number; data: any; headers: any }> {
|
|
71
|
+
const { endpoint, body, files, overrideHeaders } = options;
|
|
72
|
+
|
|
73
|
+
const url = endpoint.subpath;
|
|
74
|
+
const method = endpoint.method.toLowerCase();
|
|
75
|
+
|
|
76
|
+
let requestData: any = body;
|
|
77
|
+
let headers: Record<string, string> = {
|
|
78
|
+
...this.sanitizeHeaders(this.buildAuthHeaders()),
|
|
79
|
+
...this.sanitizeHeaders(endpoint.customHeaders),
|
|
80
|
+
...this.sanitizeHeaders(overrideHeaders),
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
if (endpoint.fileInputMode === 'multipart' && files && files.length > 0) {
|
|
84
|
+
const formData = new FormData();
|
|
85
|
+
if (body) {
|
|
86
|
+
for (const [key, value] of Object.entries(body)) {
|
|
87
|
+
formData.append(key, typeof value === 'object' ? JSON.stringify(value) : String(value));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
for (const file of files) {
|
|
91
|
+
formData.append(file.fieldName, file.buffer, {
|
|
92
|
+
filename: file.filename,
|
|
93
|
+
contentType: file.mimeType,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
requestData = formData;
|
|
97
|
+
headers = { ...headers, ...formData.getHeaders() };
|
|
98
|
+
} else if (endpoint.fileInputMode === 'base64' && files && files.length > 0) {
|
|
99
|
+
// Place base64 files under their fieldName keys within the body.
|
|
100
|
+
// PipelineExecutor's inputMapping should map $files[n].base64 to the correct body path.
|
|
101
|
+
// Here we nest them under a `_files` key to avoid overwriting body fields.
|
|
102
|
+
const base64Files: Record<string, { data: string; filename: string; mimeType: string }> = {};
|
|
103
|
+
for (const f of files) {
|
|
104
|
+
base64Files[f.fieldName] = {
|
|
105
|
+
data: f.buffer.toString('base64'),
|
|
106
|
+
filename: f.filename,
|
|
107
|
+
mimeType: f.mimeType,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
requestData = { ...body, _files: base64Files };
|
|
111
|
+
headers['Content-Type'] = 'application/json';
|
|
112
|
+
} else {
|
|
113
|
+
headers['Content-Type'] = 'application/json';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
try {
|
|
117
|
+
const response: AxiosResponse = await this.client.request({
|
|
118
|
+
url,
|
|
119
|
+
method,
|
|
120
|
+
data: ['post', 'put', 'patch'].includes(method) ? requestData : undefined,
|
|
121
|
+
params: ['get', 'delete'].includes(method) ? requestData : undefined,
|
|
122
|
+
headers,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
status: response.status,
|
|
127
|
+
data: response.data,
|
|
128
|
+
headers: response.headers,
|
|
129
|
+
};
|
|
130
|
+
} catch (error: any) {
|
|
131
|
+
if (error.response) {
|
|
132
|
+
throw new Error(`API Error [${error.response.status}]: ${JSON.stringify(error.response.data)}`);
|
|
133
|
+
}
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async get(url: string, overrideHeaders?: Record<string, string>): Promise<any> {
|
|
139
|
+
const headers = { ...this.buildAuthHeaders(), ...(overrideHeaders || {}) };
|
|
140
|
+
const response = await this.client.get(url, { headers });
|
|
141
|
+
return response.data;
|
|
142
|
+
}
|
|
143
|
+
}
|