plugin-document-understanding 1.1.9 → 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.
@@ -14,33 +14,54 @@ import {
14
14
  Tag,
15
15
  Popconfirm,
16
16
  } from 'antd';
17
+ import type { ColumnsType } from 'antd/es/table';
17
18
  import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
18
- import { useApp } from '@nocobase/client-v2';
19
+ import { useFlowContext } from '@nocobase/flow-engine';
20
+ import { useT } from '../locale';
21
+ import { EndpointDef, unwrapData } from '../types';
19
22
 
20
23
  const { TextArea } = Input;
21
24
 
25
+ interface HeaderRow {
26
+ id: string;
27
+ key: string;
28
+ value: string;
29
+ }
30
+
31
+ const sanitizeHeaders = (headers?: Record<string, string>) =>
32
+ Object.entries(headers || {}).reduce<Record<string, string>>((acc, [key, value]) => {
33
+ const headerName = key.trim();
34
+ if (headerName) {
35
+ acc[headerName] = value;
36
+ }
37
+ return acc;
38
+ }, {});
39
+
22
40
  const KeyValueEditor: React.FC<{ value?: Record<string, string>; onChange?: (v: Record<string, string>) => void }> = ({
23
- value = {},
41
+ value,
24
42
  onChange,
25
43
  }) => {
26
- const [rows, setRows] = useState<Array<{ id: string; key: string; value: string }>>([]);
27
- const localChangeRef = useRef(false);
44
+ const t = useT();
45
+ const [rows, setRows] = useState<HeaderRow[]>([]);
46
+ const syncedRef = useRef<string>();
47
+
48
+ // A half-typed row (blank name) has no representation in `value`, so resync only on a genuine
49
+ // outside change. Comparing serialized content — not object identity — keeps such rows alive.
50
+ const serialized = JSON.stringify(value ?? {});
28
51
 
29
52
  useEffect(() => {
30
- if (localChangeRef.current) {
31
- localChangeRef.current = false;
32
- return;
33
- }
53
+ if (syncedRef.current === serialized) return;
54
+ syncedRef.current = serialized;
34
55
  setRows(
35
- Object.entries(value || {}).map(([key, rowValue], index) => ({
56
+ Object.entries(JSON.parse(serialized) as Record<string, string>).map(([key, rowValue], index) => ({
36
57
  id: `${key}_${index}`,
37
58
  key,
38
59
  value: String(rowValue ?? ''),
39
60
  })),
40
61
  );
41
- }, [value]);
62
+ }, [serialized]);
42
63
 
43
- const emit = (nextRows: Array<{ id: string; key: string; value: string }>) => {
64
+ const emit = (nextRows: HeaderRow[]) => {
44
65
  setRows(nextRows);
45
66
  const nextValue = nextRows.reduce<Record<string, string>>((acc, row) => {
46
67
  const key = row.key.trim();
@@ -49,7 +70,7 @@ const KeyValueEditor: React.FC<{ value?: Record<string, string>; onChange?: (v:
49
70
  }
50
71
  return acc;
51
72
  }, {});
52
- localChangeRef.current = true;
73
+ syncedRef.current = JSON.stringify(nextValue);
53
74
  onChange?.(nextValue);
54
75
  };
55
76
 
@@ -62,8 +83,7 @@ const KeyValueEditor: React.FC<{ value?: Record<string, string>; onChange?: (v:
62
83
  const add = () => setRows([...rows, { id: `new_${Date.now()}_${Math.random()}`, key: '', value: '' }]);
63
84
 
64
85
  const remove = (idx: number) => {
65
- const nextRows = rows.filter((_, rowIndex) => rowIndex !== idx);
66
- emit(nextRows);
86
+ emit(rows.filter((_, rowIndex) => rowIndex !== idx));
67
87
  };
68
88
 
69
89
  return (
@@ -71,32 +91,41 @@ const KeyValueEditor: React.FC<{ value?: Record<string, string>; onChange?: (v:
71
91
  {rows.map((row, i) => (
72
92
  <Space key={row.id} style={{ display: 'flex', marginBottom: 4 }}>
73
93
  <Input
74
- placeholder="Header name"
94
+ placeholder={t('Header name')}
95
+ aria-label={t('Header name')}
75
96
  value={row.key}
76
97
  onChange={(e) => update(i, e.target.value, row.value)}
77
98
  style={{ width: 180 }}
78
99
  />
79
100
  <Input
80
- placeholder="Value"
101
+ placeholder={t('Value')}
102
+ aria-label={t('Value')}
81
103
  value={row.value}
82
104
  onChange={(e) => update(i, row.key, e.target.value)}
83
105
  style={{ width: 220 }}
84
106
  />
85
- <Button size="small" danger icon={<DeleteOutlined />} onClick={() => remove(i)} />
107
+ <Button
108
+ size="small"
109
+ danger
110
+ icon={<DeleteOutlined />}
111
+ onClick={() => remove(i)}
112
+ aria-label={`${t('Delete')} ${row.key || t('Header name')}`}
113
+ />
86
114
  </Space>
87
115
  ))}
88
116
  <Button size="small" type="dashed" icon={<PlusOutlined />} onClick={add}>
89
- Add Header
117
+ {t('Add Header')}
90
118
  </Button>
91
119
  </div>
92
120
  );
93
121
  };
94
122
 
95
- const JsonEditor: React.FC<{ value?: any; onChange?: (v: any) => void; placeholder?: string }> = ({
123
+ const JsonEditor: React.FC<{ value?: unknown; onChange?: (v: unknown) => void; placeholder?: string }> = ({
96
124
  value,
97
125
  onChange,
98
126
  placeholder,
99
127
  }) => {
128
+ const t = useT();
100
129
  const [text, setText] = useState('');
101
130
  const [error, setError] = useState('');
102
131
 
@@ -107,7 +136,7 @@ const JsonEditor: React.FC<{ value?: any; onChange?: (v: any) => void; placehold
107
136
  }
108
137
  try {
109
138
  setText(typeof value === 'string' ? JSON.stringify(JSON.parse(value), null, 2) : JSON.stringify(value, null, 2));
110
- } catch (e) {
139
+ } catch {
111
140
  setText(typeof value === 'string' ? value : '');
112
141
  }
113
142
  }, [value]);
@@ -123,7 +152,7 @@ const JsonEditor: React.FC<{ value?: any; onChange?: (v: any) => void; placehold
123
152
  setError('');
124
153
  onChange?.(parsed);
125
154
  } catch {
126
- setError('Invalid JSON');
155
+ setError(t('Invalid JSON'));
127
156
  }
128
157
  };
129
158
 
@@ -135,27 +164,44 @@ const JsonEditor: React.FC<{ value?: any; onChange?: (v: any) => void; placehold
135
164
  onChange={(e) => setText(e.target.value)}
136
165
  onBlur={handleBlur}
137
166
  placeholder={placeholder || '{}'}
167
+ status={error ? 'error' : undefined}
138
168
  style={{ fontFamily: 'monospace', fontSize: 12 }}
139
169
  />
140
- {error && <div style={{ color: '#ff4d4f', fontSize: 12 }}>{error}</div>}
170
+ {error && (
171
+ <div role="alert" style={{ color: '#ff4d4f', fontSize: 12 }}>
172
+ {error}
173
+ </div>
174
+ )}
141
175
  </div>
142
176
  );
143
177
  };
144
178
 
145
179
  export const EndpointsTab = () => {
146
- const app = useApp();
147
- const api = app.apiClient;
148
- const [data, setData] = useState<any[]>([]);
180
+ const ctx = useFlowContext();
181
+ const api = ctx.api;
182
+ const t = useT();
183
+ const [data, setData] = useState<EndpointDef[]>([]);
149
184
  const [loading, setLoading] = useState(false);
150
185
  const [visible, setVisible] = useState(false);
151
- const [form] = Form.useForm();
186
+ const [form] = Form.useForm<Partial<EndpointDef>>();
152
187
  const [editingId, setEditingId] = useState<number | null>(null);
153
188
 
189
+ const executionLabels: Record<string, string> = {
190
+ sync: t('Synchronous'),
191
+ polling: t('Polling'),
192
+ webhook: t('Webhook'),
193
+ };
194
+
195
+ const fileModeLabels: Record<string, string> = {
196
+ multipart: t('Multipart Upload'),
197
+ base64: t('Base64 in JSON'),
198
+ };
199
+
154
200
  const fetchEndpoints = useCallback(async () => {
155
201
  setLoading(true);
156
202
  try {
157
203
  const res = await api.request({ url: 'docUnderstanding:listEndpoints' });
158
- setData(res.data?.data || []);
204
+ setData(unwrapData<EndpointDef[]>(res, []));
159
205
  } finally {
160
206
  setLoading(false);
161
207
  }
@@ -165,7 +211,7 @@ export const EndpointsTab = () => {
165
211
  fetchEndpoints();
166
212
  }, [fetchEndpoints]);
167
213
 
168
- const openEdit = (record: any) => {
214
+ const openEdit = (record: EndpointDef) => {
169
215
  setEditingId(record.id);
170
216
  form.setFieldsValue(record);
171
217
  setVisible(true);
@@ -183,7 +229,7 @@ export const EndpointsTab = () => {
183
229
  method: 'POST',
184
230
  params: { filterByTk: id },
185
231
  });
186
- message.success('Deleted');
232
+ message.success(t('Deleted'));
187
233
  fetchEndpoints();
188
234
  };
189
235
 
@@ -205,65 +251,67 @@ export const EndpointsTab = () => {
205
251
  data: values,
206
252
  });
207
253
  }
208
- message.success('Saved');
254
+ message.success(t('Saved'));
209
255
  setVisible(false);
210
256
  fetchEndpoints();
211
257
  } catch {
212
- // validation error
258
+ // Form validation errors are already surfaced inline by antd.
213
259
  }
214
260
  };
215
261
 
216
- const sanitizeHeaders = (headers?: Record<string, string>) => {
217
- return Object.entries(headers || {}).reduce<Record<string, string>>((acc, [key, value]) => {
218
- const headerName = key.trim();
219
- if (headerName) {
220
- acc[headerName] = value;
221
- }
222
- return acc;
223
- }, {});
224
- };
225
-
226
- const columns = [
227
- { title: 'Name', dataIndex: 'name', width: 150 },
228
- { title: 'Subpath', dataIndex: 'subpath', width: 200 },
262
+ const columns: ColumnsType<EndpointDef> = [
263
+ { title: t('Name'), dataIndex: 'name', width: 150 },
264
+ { title: t('Subpath'), dataIndex: 'subpath', width: 200 },
229
265
  {
230
- title: 'Method',
266
+ title: t('Method'),
231
267
  dataIndex: 'method',
232
268
  width: 80,
233
269
  render: (v: string) => <Tag>{v}</Tag>,
234
270
  },
235
271
  {
236
- title: 'Execution',
272
+ title: t('Execution'),
237
273
  dataIndex: 'executionMode',
238
- width: 100,
274
+ width: 130,
239
275
  render: (v: string) => {
240
276
  const colors: Record<string, string> = { sync: 'green', polling: 'blue', webhook: 'purple' };
241
- return <Tag color={colors[v]}>{v}</Tag>;
277
+ return <Tag color={colors[v]}>{executionLabels[v] || v}</Tag>;
242
278
  },
243
279
  },
244
280
  {
245
- title: 'File',
281
+ title: t('File'),
246
282
  dataIndex: 'fileInputMode',
247
- width: 90,
248
- render: (v: string) => (v === 'none' ? '-' : v),
283
+ width: 130,
284
+ render: (v: string) => (v === 'none' ? '-' : fileModeLabels[v] || v),
249
285
  },
250
286
  {
251
- title: 'Enabled',
287
+ title: t('Enabled'),
252
288
  dataIndex: 'enabled',
253
289
  width: 70,
254
- render: (v: boolean) => (v ? <Tag color="success">Yes</Tag> : <Tag>No</Tag>),
290
+ render: (v: boolean) => (v ? <Tag color="success">{t('Yes')}</Tag> : <Tag>{t('No')}</Tag>),
255
291
  },
256
292
  {
257
- title: 'Action',
293
+ title: t('Action'),
258
294
  width: 120,
259
- render: (_: any, record: any) => (
295
+ render: (_: unknown, record) => (
260
296
  <Space>
261
- <Button type="link" size="small" icon={<EditOutlined />} onClick={() => openEdit(record)}>
262
- Edit
297
+ <Button
298
+ type="link"
299
+ size="small"
300
+ icon={<EditOutlined />}
301
+ onClick={() => openEdit(record)}
302
+ aria-label={`${t('Edit')} ${record.name}`}
303
+ >
304
+ {t('Edit')}
263
305
  </Button>
264
- <Popconfirm title="Delete this endpoint?" onConfirm={() => handleDelete(record.id)}>
265
- <Button type="link" size="small" danger icon={<DeleteOutlined />}>
266
- Delete
306
+ <Popconfirm title={t('Delete this endpoint?')} okText={t('Delete')} onConfirm={() => handleDelete(record.id)}>
307
+ <Button
308
+ type="link"
309
+ size="small"
310
+ danger
311
+ icon={<DeleteOutlined />}
312
+ aria-label={`${t('Delete')} ${record.name}`}
313
+ >
314
+ {t('Delete')}
267
315
  </Button>
268
316
  </Popconfirm>
269
317
  </Space>
@@ -275,16 +323,18 @@ export const EndpointsTab = () => {
275
323
  <div>
276
324
  <div style={{ marginBottom: 16 }}>
277
325
  <Button type="primary" icon={<PlusOutlined />} onClick={openAdd}>
278
- Add Endpoint
326
+ {t('Add Endpoint')}
279
327
  </Button>
280
328
  </div>
281
329
  <Table rowKey="id" columns={columns} dataSource={data} loading={loading} size="small" />
282
330
 
283
331
  <Modal
284
- title={editingId ? 'Edit Endpoint' : 'Add Endpoint'}
332
+ title={editingId ? t('Edit Endpoint') : t('Add Endpoint')}
285
333
  open={visible}
286
334
  onOk={handleSave}
287
335
  onCancel={() => setVisible(false)}
336
+ okText={t('Save')}
337
+ cancelText={t('Cancel')}
288
338
  width={680}
289
339
  destroyOnClose
290
340
  >
@@ -294,27 +344,30 @@ export const EndpointsTab = () => {
294
344
  items={[
295
345
  {
296
346
  key: 'basic',
297
- label: 'Basic',
347
+ label: t('Basic'),
298
348
  children: (
299
349
  <>
300
- <Form.Item name="name" label="Unique Name" rules={[{ required: true }]}>
350
+ <Form.Item name="name" label={t('Unique Name')} rules={[{ required: true }]}>
301
351
  <Input placeholder="ocr, classify, extract..." />
302
352
  </Form.Item>
303
- <Form.Item name="subpath" label="Subpath" rules={[{ required: true }]}>
353
+ <Form.Item name="subpath" label={t('Subpath')} rules={[{ required: true }]}>
304
354
  <Input placeholder="/api/v1/ocr" />
305
355
  </Form.Item>
306
- <Form.Item name="description" label="Description">
307
- <TextArea rows={2} placeholder="What this endpoint does" />
356
+ <Form.Item name="description" label={t('Description')}>
357
+ <TextArea rows={2} placeholder={t('What this endpoint does')} />
308
358
  </Form.Item>
309
359
  <Space size="large">
310
- <Form.Item name="method" label="HTTP Method" initialValue="POST">
311
- <Select style={{ width: 120 }}>
312
- <Select.Option value="GET">GET</Select.Option>
313
- <Select.Option value="POST">POST</Select.Option>
314
- <Select.Option value="PUT">PUT</Select.Option>
315
- </Select>
360
+ <Form.Item name="method" label={t('HTTP Method')} initialValue="POST">
361
+ <Select
362
+ style={{ width: 120 }}
363
+ options={[
364
+ { value: 'GET', label: 'GET' },
365
+ { value: 'POST', label: 'POST' },
366
+ { value: 'PUT', label: 'PUT' },
367
+ ]}
368
+ />
316
369
  </Form.Item>
317
- <Form.Item name="enabled" label="Enabled" valuePropName="checked" initialValue={true}>
370
+ <Form.Item name="enabled" label={t('Enabled')} valuePropName="checked" initialValue={true}>
318
371
  <Switch />
319
372
  </Form.Item>
320
373
  </Space>
@@ -323,24 +376,27 @@ export const EndpointsTab = () => {
323
376
  },
324
377
  {
325
378
  key: 'file',
326
- label: 'File Input',
379
+ label: t('File Input'),
327
380
  children: (
328
381
  <>
329
- <Form.Item name="fileInputMode" label="File Input Mode" initialValue="none">
330
- <Select style={{ width: 200 }}>
331
- <Select.Option value="none">None</Select.Option>
332
- <Select.Option value="multipart">Multipart Upload</Select.Option>
333
- <Select.Option value="base64">Base64 in JSON</Select.Option>
334
- </Select>
382
+ <Form.Item name="fileInputMode" label={t('File Input Mode')} initialValue="none">
383
+ <Select
384
+ style={{ width: 200 }}
385
+ options={[
386
+ { value: 'none', label: t('None') },
387
+ { value: 'multipart', label: t('Multipart Upload') },
388
+ { value: 'base64', label: t('Base64 in JSON') },
389
+ ]}
390
+ />
335
391
  </Form.Item>
336
392
  <Form.Item noStyle dependencies={['fileInputMode']}>
337
393
  {() =>
338
394
  form.getFieldValue('fileInputMode') !== 'none' ? (
339
395
  <>
340
- <Form.Item name="fileFieldName" label="File Field Name" initialValue="file">
396
+ <Form.Item name="fileFieldName" label={t('File Field Name')} initialValue="file">
341
397
  <Input placeholder="file" style={{ width: 200 }} />
342
398
  </Form.Item>
343
- <Form.Item name="maxFiles" label="Max Files" initialValue={1}>
399
+ <Form.Item name="maxFiles" label={t('Max Files')} initialValue={1}>
344
400
  <InputNumber min={1} max={20} style={{ width: 120 }} />
345
401
  </Form.Item>
346
402
  </>
@@ -352,15 +408,18 @@ export const EndpointsTab = () => {
352
408
  },
353
409
  {
354
410
  key: 'async',
355
- label: 'Async Config',
411
+ label: t('Async Config'),
356
412
  children: (
357
413
  <>
358
- <Form.Item name="executionMode" label="Execution Mode" initialValue="sync">
359
- <Select style={{ width: 200 }}>
360
- <Select.Option value="sync">Synchronous</Select.Option>
361
- <Select.Option value="polling">Polling</Select.Option>
362
- <Select.Option value="webhook">Webhook</Select.Option>
363
- </Select>
414
+ <Form.Item name="executionMode" label={t('Execution Mode')} initialValue="sync">
415
+ <Select
416
+ style={{ width: 200 }}
417
+ options={[
418
+ { value: 'sync', label: t('Synchronous') },
419
+ { value: 'polling', label: t('Polling') },
420
+ { value: 'webhook', label: t('Webhook') },
421
+ ]}
422
+ />
364
423
  </Form.Item>
365
424
  <Form.Item noStyle dependencies={['executionMode']}>
366
425
  {() => {
@@ -370,8 +429,8 @@ export const EndpointsTab = () => {
370
429
  <>
371
430
  <Form.Item
372
431
  name="pollTaskIdField"
373
- label="Task ID Field"
374
- help="Field in response containing the async task ID"
432
+ label={t('Task ID Field')}
433
+ help={t('Field in response containing the async task ID')}
375
434
  initialValue="task_id"
376
435
  >
377
436
  <Input placeholder="task_id" />
@@ -381,39 +440,49 @@ export const EndpointsTab = () => {
381
440
  <>
382
441
  <Form.Item
383
442
  name="pollResultSubpath"
384
- label="Poll Result Subpath"
385
- help="URL to poll for result. Use {taskId} as placeholder."
386
- rules={[{ required: true, message: 'Required for polling mode' }]}
443
+ label={t('Poll Result Subpath')}
444
+ help={t('URL to poll for result. Use {taskId} as placeholder.')}
445
+ rules={[{ required: true, message: t('Required for polling mode') }]}
387
446
  >
388
447
  <Input placeholder="/api/v1/tasks/{taskId}/result" />
389
448
  </Form.Item>
390
449
  <Form.Item
391
450
  name="pollResultField"
392
- label="Result Field"
393
- help="Field in poll response containing the actual result"
451
+ label={t('Result Field')}
452
+ help={t('Field in poll response containing the actual result')}
394
453
  >
395
454
  <Input placeholder="result" />
396
455
  </Form.Item>
397
456
  <Form.Item
398
457
  name="pollStatusField"
399
- label="Status Field (optional)"
400
- help="Field to check completion status. If empty, any non-null result = complete."
458
+ label={t('Status Field (optional)')}
459
+ help={t(
460
+ 'Field to check completion status. If empty, any non-null result = complete.',
461
+ )}
401
462
  >
402
463
  <Input placeholder="status" />
403
464
  </Form.Item>
404
465
  <Form.Item
405
466
  name="pollCompletedValue"
406
- label="Completed Value"
407
- help="Value of status field that means 'done'"
467
+ label={t('Completed Value')}
468
+ help={t("Value of status field that means 'done'")}
408
469
  initialValue="completed"
409
470
  >
410
471
  <Input placeholder="completed" />
411
472
  </Form.Item>
412
473
  <Space size="large">
413
- <Form.Item name="pollInterval" label="Poll Interval (ms)" help="Override default">
474
+ <Form.Item
475
+ name="pollInterval"
476
+ label={t('Poll Interval (ms)')}
477
+ help={t('Override default')}
478
+ >
414
479
  <InputNumber min={1000} step={1000} placeholder="5000" style={{ width: 150 }} />
415
480
  </Form.Item>
416
- <Form.Item name="pollTimeout" label="Poll Timeout (ms)" help="Override default">
481
+ <Form.Item
482
+ name="pollTimeout"
483
+ label={t('Poll Timeout (ms)')}
484
+ help={t('Override default')}
485
+ >
417
486
  <InputNumber min={5000} step={5000} placeholder="300000" style={{ width: 150 }} />
418
487
  </Form.Item>
419
488
  </Space>
@@ -428,13 +497,13 @@ export const EndpointsTab = () => {
428
497
  },
429
498
  {
430
499
  key: 'schema',
431
- label: 'Schema',
500
+ label: t('Schema'),
432
501
  children: (
433
502
  <>
434
- <Form.Item name="requestBodySchema" label="Request Body Schema (JSON Schema)">
503
+ <Form.Item name="requestBodySchema" label={t('Request Body Schema (JSON Schema)')}>
435
504
  <JsonEditor placeholder='{ "type": "object", "properties": { ... } }' />
436
505
  </Form.Item>
437
- <Form.Item name="responseSchema" label="Response Schema (JSON Schema)">
506
+ <Form.Item name="responseSchema" label={t('Response Schema (JSON Schema)')}>
438
507
  <JsonEditor placeholder='{ "type": "object", "properties": { ... } }' />
439
508
  </Form.Item>
440
509
  </>
@@ -442,9 +511,9 @@ export const EndpointsTab = () => {
442
511
  },
443
512
  {
444
513
  key: 'headers',
445
- label: 'Custom Headers',
514
+ label: t('Custom Headers'),
446
515
  children: (
447
- <Form.Item name="customHeaders" label="Additional Headers">
516
+ <Form.Item name="customHeaders" label={t('Additional Headers')}>
448
517
  <KeyValueEditor />
449
518
  </Form.Item>
450
519
  ),