plugin-elastic-report 0.1.1 → 0.9.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 (80) hide show
  1. package/client-v2.d.ts +2 -2
  2. package/client-v2.js +1 -1
  3. package/client.d.ts +2 -2
  4. package/client.js +1 -1
  5. package/dist/ai/skills/elastic-report/SKILLS.md +52 -0
  6. package/dist/client/357.0dd385384cab5dbf.js +10 -0
  7. package/dist/client/index.js +1 -1
  8. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  9. package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
  10. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  11. package/dist/client-v2/index.js +1 -1
  12. package/dist/externalVersion.js +5 -3
  13. package/dist/locale/en-US.json +213 -99
  14. package/dist/locale/vi-VN.json +213 -99
  15. package/dist/locale/zh-CN.json +213 -99
  16. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  17. package/dist/server/acl-guard.js +97 -25
  18. package/dist/server/collections/es-report-data-views.js +6 -0
  19. package/dist/server/collections/es-reports.js +6 -0
  20. package/dist/server/mcp/ElasticReportToolCatalog.js +238 -14
  21. package/dist/server/plugin.js +156 -22
  22. package/dist/server/report-block-tools.js +340 -0
  23. package/dist/server/services/ElasticReportService.js +137 -17
  24. package/dist/server/services/ElasticsearchConnectionService.js +274 -34
  25. package/dist/server/services/ReportExportService.js +243 -0
  26. package/dist/server/services/ReportQueryCompiler.js +532 -91
  27. package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
  28. package/dist/shared/constants.js +26 -2
  29. package/package.json +3 -3
  30. package/server.d.ts +2 -2
  31. package/server.js +1 -1
  32. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  33. package/src/client/index.tsx +34 -19
  34. package/src/client/workflow-instructions.tsx +44 -0
  35. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -311
  36. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
  37. package/src/client-v2/api.ts +320 -224
  38. package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
  39. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -399
  40. package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
  41. package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
  42. package/src/client-v2/components/ElasticReportBlock.tsx +306 -160
  43. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -707
  44. package/src/client-v2/components/HighlightText.tsx +50 -50
  45. package/src/client-v2/components/ReportSelect.tsx +85 -72
  46. package/src/client-v2/index.tsx +14 -14
  47. package/src/client-v2/locale.ts +23 -23
  48. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
  49. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -85
  50. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1047
  51. package/src/client-v2/plugin.tsx +107 -52
  52. package/src/client-v2/report-destination.tsx +126 -0
  53. package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
  54. package/src/client-v2/workflow/instructions.tsx +149 -0
  55. package/src/index.ts +11 -11
  56. package/src/locale/en-US.json +213 -99
  57. package/src/locale/vi-VN.json +213 -99
  58. package/src/locale/zh-CN.json +213 -99
  59. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  60. package/src/server/__tests__/query-compiler.test.ts +620 -231
  61. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -377
  62. package/src/server/acl-guard.ts +194 -103
  63. package/src/server/collections/es-report-data-views.ts +64 -58
  64. package/src/server/collections/es-reports.ts +80 -74
  65. package/src/server/index.ts +15 -15
  66. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  67. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -417
  68. package/src/server/plugin.ts +599 -431
  69. package/src/server/report-block-tools.ts +400 -0
  70. package/src/server/services/ElasticReportService.ts +494 -326
  71. package/src/server/services/ElasticsearchConnectionService.ts +728 -401
  72. package/src/server/services/ReportExportService.ts +282 -0
  73. package/src/server/services/ReportQueryCompiler.ts +1552 -1017
  74. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
  75. package/src/shared/constants.ts +39 -29
  76. package/src/shared/types.ts +272 -175
  77. package/ai/skills/elastic-report/SKILLS.md +0 -32
  78. package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
  79. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  80. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -0,0 +1,421 @@
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
+
10
+ import { SearchOutlined } from '@ant-design/icons';
11
+ import { AutoComplete, Input, Space, Spin, Tag, Typography } from 'antd';
12
+ import type { AutoCompleteProps, InputRef } from 'antd';
13
+ import React, { useEffect, useMemo, useRef, useState } from 'react';
14
+ import type { EsFieldCapability, FieldTopValueBucket, FieldTopValuesResult, ReportRowHit } from '../../shared/types';
15
+ import { useT } from '../locale';
16
+ import {
17
+ type KqlSuggestionCategory,
18
+ type KqlSuggestionItem,
19
+ buildKqlSuggestions,
20
+ canFetchFieldTopValues,
21
+ } from '../utils/kqlAutocomplete';
22
+
23
+ const { Text } = Typography;
24
+
25
+ const RUN_FREETEXT_SENTINEL = '__es_kql_run_freetext__';
26
+ const LOADING_VALUES_SENTINEL = '__es_kql_loading_values__';
27
+
28
+ export interface ElasticKqlInputProps {
29
+ id?: string;
30
+ value?: string;
31
+ placeholder?: string;
32
+ ariaLabel?: string;
33
+ style?: React.CSSProperties;
34
+ disabled?: boolean;
35
+ fields?: EsFieldCapability[];
36
+ sampleRows?: ReportRowHit[];
37
+ onInspectTopValues?: (field: string) => Promise<FieldTopValuesResult>;
38
+ onFocusEnsureFields?: () => void;
39
+ onChange?: (nextValue: string) => void;
40
+ onClear?: () => void;
41
+ onSubmit?: (submittedValue: string) => void;
42
+ }
43
+
44
+ export const ElasticKqlInput: React.FC<ElasticKqlInputProps> = ({
45
+ id,
46
+ value = '',
47
+ placeholder,
48
+ ariaLabel,
49
+ style,
50
+ disabled = false,
51
+ fields = [],
52
+ sampleRows,
53
+ onInspectTopValues,
54
+ onFocusEnsureFields,
55
+ onChange,
56
+ onClear,
57
+ onSubmit,
58
+ }) => {
59
+ const t = useT();
60
+ const inputRef = useRef<InputRef>(null);
61
+
62
+ const [open, setOpen] = useState(false);
63
+ const [cursorPos, setCursorPos] = useState<number>(value.length);
64
+ const [topValuesCache, setTopValuesCache] = useState<Record<string, FieldTopValueBucket[]>>({});
65
+ const [loadingField, setLoadingField] = useState<string | null>(null);
66
+
67
+ const inFlightFieldsRef = useRef<Set<string>>(new Set());
68
+ const onInspectRef = useRef(onInspectTopValues);
69
+ onInspectRef.current = onInspectTopValues;
70
+
71
+ const justSelectedOptionRef = useRef(false);
72
+ const keepOpenAfterSelectRef = useRef(false);
73
+ const lastCompositionEndAtRef = useRef<number | null>(null);
74
+
75
+ // Reset cached top values when field schema changes (e.g. switching Data View or Report)
76
+ const fieldsSignature = useMemo(() => fields.map((f) => `${f.name}:${f.type}`).join('|'), [fields]);
77
+ useEffect(() => {
78
+ setTopValuesCache({});
79
+ inFlightFieldsRef.current.clear();
80
+ setLoadingField(null);
81
+ }, [fieldsSignature]);
82
+
83
+ // Clamp cursor position if external value shrinks
84
+ const effectiveCursorPos = Math.min(cursorPos, value.length);
85
+
86
+ const prelim = useMemo(
87
+ () =>
88
+ buildKqlSuggestions({
89
+ input: value,
90
+ cursorPos: effectiveCursorPos,
91
+ fields,
92
+ sampleRows,
93
+ t,
94
+ }),
95
+ [effectiveCursorPos, fields, sampleRows, t, value],
96
+ );
97
+
98
+ const activeValueField = prelim.context.stage === 'value' ? prelim.context.field : undefined;
99
+ const activeValueFieldMeta = prelim.context.fieldMeta;
100
+
101
+ // Lazy-fetch top field values from Elasticsearch when user enters value position
102
+ useEffect(() => {
103
+ if (!open || !activeValueField || !onInspectRef.current) {
104
+ return;
105
+ }
106
+ if (!canFetchFieldTopValues(activeValueFieldMeta)) {
107
+ return;
108
+ }
109
+ if (activeValueField in topValuesCache || inFlightFieldsRef.current.has(activeValueField)) {
110
+ return;
111
+ }
112
+
113
+ let cancelled = false;
114
+ inFlightFieldsRef.current.add(activeValueField);
115
+ setLoadingField(activeValueField);
116
+
117
+ const loadFieldValues = async () => {
118
+ try {
119
+ const res = await onInspectRef.current?.(activeValueField);
120
+ if (!cancelled) {
121
+ setTopValuesCache((prev) => ({
122
+ ...prev,
123
+ [activeValueField]: res?.buckets ?? [],
124
+ }));
125
+ }
126
+ } catch {
127
+ if (!cancelled) {
128
+ setTopValuesCache((prev) => ({
129
+ ...prev,
130
+ [activeValueField]: [],
131
+ }));
132
+ }
133
+ } finally {
134
+ inFlightFieldsRef.current.delete(activeValueField);
135
+ if (!cancelled) {
136
+ setLoadingField((prev) => (prev === activeValueField ? null : prev));
137
+ }
138
+ }
139
+ };
140
+
141
+ loadFieldValues();
142
+ return () => {
143
+ cancelled = true;
144
+ };
145
+ }, [activeValueField, activeValueFieldMeta, open, topValuesCache]);
146
+
147
+ const { context, items } = useMemo(
148
+ () =>
149
+ buildKqlSuggestions({
150
+ input: value,
151
+ cursorPos: effectiveCursorPos,
152
+ fields,
153
+ topValueBuckets: activeValueField ? topValuesCache[activeValueField] ?? [] : [],
154
+ sampleRows,
155
+ t,
156
+ }),
157
+ [activeValueField, effectiveCursorPos, fields, sampleRows, t, topValuesCache, value],
158
+ );
159
+
160
+ const { groupedOptions, itemByOptionValue } = useMemo(() => {
161
+ const map = new Map<string, KqlSuggestionItem>();
162
+ const byCat = new Map<
163
+ KqlSuggestionCategory,
164
+ Array<{ value: string; label: React.ReactNode; disabled?: boolean }>
165
+ >();
166
+
167
+ const pushRow = (
168
+ cat: KqlSuggestionCategory,
169
+ row: { value: string; label: React.ReactNode; disabled?: boolean },
170
+ ) => {
171
+ const list = byCat.get(cat) ?? [];
172
+ list.push(row);
173
+ byCat.set(cat, list);
174
+ };
175
+
176
+ if (context.stage === 'value' && activeValueField && loadingField === activeValueField) {
177
+ pushRow('value', {
178
+ value: LOADING_VALUES_SENTINEL,
179
+ disabled: true,
180
+ label: (
181
+ <Space size={6}>
182
+ <Spin size="small" />
183
+ <Text type="secondary" style={{ fontSize: 12 }}>
184
+ {t('Loading field values...')}
185
+ </Text>
186
+ </Space>
187
+ ),
188
+ });
189
+ }
190
+
191
+ for (const item of items) {
192
+ const optionValue = item.submitImmediately ? RUN_FREETEXT_SENTINEL : item.nextQuery;
193
+ if (map.has(optionValue)) continue;
194
+ map.set(optionValue, item);
195
+
196
+ pushRow(item.category, {
197
+ value: optionValue,
198
+ label: (
199
+ <div
200
+ style={{
201
+ display: 'flex',
202
+ alignItems: 'center',
203
+ justifyContent: 'space-between',
204
+ gap: 8,
205
+ width: '100%',
206
+ minWidth: 0,
207
+ }}
208
+ >
209
+ <Text
210
+ code
211
+ style={{
212
+ fontSize: 12,
213
+ margin: 0,
214
+ overflow: 'hidden',
215
+ textOverflow: 'ellipsis',
216
+ whiteSpace: 'nowrap',
217
+ maxWidth: '58%',
218
+ }}
219
+ >
220
+ {item.displayToken}
221
+ </Text>
222
+ <span
223
+ style={{
224
+ display: 'inline-flex',
225
+ alignItems: 'center',
226
+ gap: 4,
227
+ minWidth: 0,
228
+ flexShrink: 1,
229
+ overflow: 'hidden',
230
+ }}
231
+ >
232
+ {item.badge && (
233
+ <Tag bordered={false} style={{ marginInlineEnd: 0, fontSize: 11, lineHeight: '18px' }}>
234
+ {item.badge}
235
+ </Tag>
236
+ )}
237
+ <Text
238
+ type="secondary"
239
+ style={{
240
+ fontSize: 12,
241
+ overflow: 'hidden',
242
+ textOverflow: 'ellipsis',
243
+ whiteSpace: 'nowrap',
244
+ }}
245
+ >
246
+ {item.description}
247
+ </Text>
248
+ </span>
249
+ </div>
250
+ ),
251
+ });
252
+ }
253
+
254
+ const categoryOrder: Array<{ cat: KqlSuggestionCategory; title: string }> = [
255
+ {
256
+ cat: 'field',
257
+ title: !value.trim()
258
+ ? `${t('Suggested Fields')} — ${t('Type keywords freely or select a field below')}`
259
+ : t('Suggested Fields'),
260
+ },
261
+ { cat: 'operator', title: t('Comparisons & Operators') },
262
+ { cat: 'value', title: t('Suggested Values') },
263
+ { cat: 'connector', title: t('Combine Conditions') },
264
+ { cat: 'free_text', title: t('Free-text Search') },
265
+ ];
266
+
267
+ const groups: NonNullable<AutoCompleteProps['options']> = [];
268
+ for (const { cat, title } of categoryOrder) {
269
+ const rows = byCat.get(cat);
270
+ if (rows && rows.length > 0) {
271
+ groups.push({
272
+ label: (
273
+ <Text type="secondary" style={{ fontSize: 11, fontWeight: 600 }}>
274
+ {title}
275
+ </Text>
276
+ ),
277
+ options: rows,
278
+ });
279
+ }
280
+ }
281
+
282
+ return { groupedOptions: groups, itemByOptionValue: map };
283
+ }, [activeValueField, context.stage, items, loadingField, t, value]);
284
+
285
+ const syncCursorFromDom = (target?: HTMLInputElement | null) => {
286
+ const el = target ?? inputRef.current?.input ?? null;
287
+ if (el && typeof el.selectionStart === 'number') {
288
+ setCursorPos(el.selectionStart);
289
+ }
290
+ };
291
+
292
+ const handleSelect = (selectedVal: string) => {
293
+ const picked = itemByOptionValue.get(selectedVal);
294
+ justSelectedOptionRef.current = true;
295
+ queueMicrotask(() => {
296
+ justSelectedOptionRef.current = false;
297
+ });
298
+
299
+ if (!picked) {
300
+ return;
301
+ }
302
+
303
+ if (picked.submitImmediately) {
304
+ keepOpenAfterSelectRef.current = false;
305
+ setOpen(false);
306
+ onSubmit?.(value);
307
+ return;
308
+ }
309
+
310
+ setCursorPos(picked.nextCursor);
311
+ onChange?.(picked.nextQuery);
312
+
313
+ if (picked.keepOpen) {
314
+ keepOpenAfterSelectRef.current = true;
315
+ setOpen(true);
316
+ } else {
317
+ keepOpenAfterSelectRef.current = false;
318
+ setOpen(false);
319
+ }
320
+
321
+ const focusAndPlaceCaret = () => {
322
+ const el = inputRef.current?.input;
323
+ if (el) {
324
+ el.focus();
325
+ try {
326
+ el.setSelectionRange(picked.nextCursor, picked.nextCursor);
327
+ } catch {
328
+ // Ignore selection errors on unsupported input types
329
+ }
330
+ }
331
+ };
332
+
333
+ focusAndPlaceCaret();
334
+ if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
335
+ window.requestAnimationFrame(focusAndPlaceCaret);
336
+ }
337
+ };
338
+
339
+ return (
340
+ <AutoComplete
341
+ id={id}
342
+ value={value}
343
+ options={groupedOptions}
344
+ open={open && groupedOptions.length > 0}
345
+ disabled={disabled}
346
+ filterOption={false}
347
+ defaultActiveFirstOption={false}
348
+ popupMatchSelectWidth={false}
349
+ dropdownStyle={{ minWidth: 320, maxWidth: 'min(480px, calc(100vw - 32px))' }}
350
+ style={style}
351
+ onDropdownVisibleChange={(nextVisible) => {
352
+ if (!nextVisible && keepOpenAfterSelectRef.current) {
353
+ keepOpenAfterSelectRef.current = false;
354
+ setOpen(true);
355
+ return;
356
+ }
357
+ setOpen(nextVisible);
358
+ }}
359
+ onChange={(nextVal) => {
360
+ if (nextVal === RUN_FREETEXT_SENTINEL || nextVal === LOADING_VALUES_SENTINEL) {
361
+ return;
362
+ }
363
+ onChange?.(nextVal);
364
+ }}
365
+ onSelect={handleSelect}
366
+ >
367
+ <Input
368
+ ref={inputRef}
369
+ allowClear
370
+ aria-label={ariaLabel ?? t('KQL / Search Query')}
371
+ placeholder={placeholder ?? t('Search KQL, e.g. status >= 500 AND service: "api"')}
372
+ prefix={<SearchOutlined aria-hidden="true" />}
373
+ onFocus={(e) => {
374
+ onFocusEnsureFields?.();
375
+ syncCursorFromDom(e.currentTarget);
376
+ setOpen(true);
377
+ }}
378
+ onClick={(e) => {
379
+ syncCursorFromDom(e.currentTarget);
380
+ }}
381
+ onChange={(e) => {
382
+ const nextVal = e.target.value;
383
+ setCursorPos(e.target.selectionStart ?? nextVal.length);
384
+ if (nextVal === '' && e.type === 'click') {
385
+ onClear?.();
386
+ }
387
+ }}
388
+ onKeyUp={(e) => {
389
+ if (e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === 'Home' || e.key === 'End') {
390
+ syncCursorFromDom(e.currentTarget);
391
+ }
392
+ }}
393
+ onCompositionEnd={(e) => {
394
+ lastCompositionEndAtRef.current = e.timeStamp;
395
+ }}
396
+ onKeyDown={(e) => {
397
+ if (e.key === 'Enter') {
398
+ if (justSelectedOptionRef.current) {
399
+ justSelectedOptionRef.current = false;
400
+ e.preventDefault();
401
+ return;
402
+ }
403
+ // IME-safe Enter guard (modern-web-guidance: ime-safe-enter-submit)
404
+ if (
405
+ e.nativeEvent.isComposing ||
406
+ e.keyCode === 229 ||
407
+ (lastCompositionEndAtRef.current !== null && Math.abs(e.timeStamp - lastCompositionEndAtRef.current) < 50)
408
+ ) {
409
+ e.preventDefault();
410
+ return;
411
+ }
412
+ e.preventDefault();
413
+ keepOpenAfterSelectRef.current = false;
414
+ setOpen(false);
415
+ onSubmit?.(value);
416
+ }
417
+ }}
418
+ />
419
+ </AutoComplete>
420
+ );
421
+ };