plugin-elastic-report 0.1.1 → 0.7.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 (60) hide show
  1. package/ai/skills/elastic-report/SKILLS.md +5 -3
  2. package/dist/client/357.0dd385384cab5dbf.js +10 -0
  3. package/dist/client/index.js +1 -1
  4. package/dist/client-v2/851.142c93fc6d666b28.js +10 -0
  5. package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
  6. package/dist/client-v2/877.f4095a3dbcadf98f.js +10 -0
  7. package/dist/client-v2/index.js +1 -1
  8. package/dist/externalVersion.js +3 -2
  9. package/dist/locale/en-US.json +100 -1
  10. package/dist/locale/vi-VN.json +100 -1
  11. package/dist/locale/zh-CN.json +100 -1
  12. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  13. package/dist/server/acl-guard.js +97 -25
  14. package/dist/server/collections/es-report-data-views.js +6 -0
  15. package/dist/server/collections/es-reports.js +6 -0
  16. package/dist/server/mcp/ElasticReportToolCatalog.js +232 -10
  17. package/dist/server/plugin.js +153 -19
  18. package/dist/server/services/ElasticReportService.js +125 -11
  19. package/dist/server/services/ElasticsearchConnectionService.js +274 -34
  20. package/dist/server/services/ReportExportService.js +243 -0
  21. package/dist/server/services/ReportQueryCompiler.js +532 -91
  22. package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
  23. package/dist/shared/constants.js +17 -2
  24. package/package.json +3 -2
  25. package/src/client/index.tsx +16 -1
  26. package/src/client/workflow-instructions.tsx +44 -0
  27. package/src/client-v2/__tests__/elastic-report.test.tsx +519 -39
  28. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
  29. package/src/client-v2/api.ts +96 -0
  30. package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
  31. package/src/client-v2/components/ElasticBasicCharts.tsx +345 -92
  32. package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
  33. package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
  34. package/src/client-v2/components/ElasticReportBlock.tsx +157 -11
  35. package/src/client-v2/components/ElasticReportRenderer.tsx +621 -71
  36. package/src/client-v2/components/ReportSelect.tsx +39 -26
  37. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
  38. package/src/client-v2/models/ElasticReportBlockModel.tsx +36 -3
  39. package/src/client-v2/pages/ElasticReportManager.tsx +432 -26
  40. package/src/client-v2/plugin.tsx +20 -0
  41. package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
  42. package/src/client-v2/workflow/instructions.tsx +149 -0
  43. package/src/locale/en-US.json +100 -1
  44. package/src/locale/vi-VN.json +100 -1
  45. package/src/locale/zh-CN.json +100 -1
  46. package/src/server/__tests__/query-compiler.test.ts +390 -1
  47. package/src/server/__tests__/report-mcp-acl.integration.test.ts +271 -3
  48. package/src/server/acl-guard.ts +119 -28
  49. package/src/server/collections/es-report-data-views.ts +6 -0
  50. package/src/server/collections/es-reports.ts +6 -0
  51. package/src/server/mcp/ElasticReportToolCatalog.ts +255 -9
  52. package/src/server/plugin.ts +189 -21
  53. package/src/server/services/ElasticReportService.ts +165 -5
  54. package/src/server/services/ElasticsearchConnectionService.ts +375 -48
  55. package/src/server/services/ReportExportService.ts +282 -0
  56. package/src/server/services/ReportQueryCompiler.ts +629 -94
  57. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
  58. package/src/shared/constants.ts +7 -0
  59. package/src/shared/types.ts +98 -1
  60. package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
@@ -0,0 +1,243 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var ReportExportService_exports = {};
28
+ __export(ReportExportService_exports, {
29
+ ReportExportService: () => ReportExportService,
30
+ escapeCsvCell: () => escapeCsvCell
31
+ });
32
+ module.exports = __toCommonJS(ReportExportService_exports);
33
+ var import_events = require("events");
34
+ var import_stream = require("stream");
35
+ var import_constants = require("../../shared/constants");
36
+ var import_ReportQueryCompiler = require("./ReportQueryCompiler");
37
+ function readNestedField(source, path) {
38
+ if (path in source) return source[path];
39
+ const segments = path.split(".");
40
+ let cur = source;
41
+ for (const seg of segments) {
42
+ if (cur && typeof cur === "object" && !Array.isArray(cur) && seg in cur) {
43
+ cur = cur[seg];
44
+ } else {
45
+ return void 0;
46
+ }
47
+ }
48
+ return cur;
49
+ }
50
+ function escapeCsvCell(value, options) {
51
+ if (value === null || value === void 0) return "";
52
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
53
+ let str = typeof value === "string" ? value : JSON.stringify(value);
54
+ const isSafeAtFieldHeader = (options == null ? void 0 : options.allowAtIdentifier) === true && /^@[A-Za-z0-9_.-]+$/.test(str);
55
+ if (!isSafeAtFieldHeader && /^[=+\-@\t\r]/.test(str) && !/^-?\d+(\.\d+)?$/.test(str)) {
56
+ str = `'${str}`;
57
+ }
58
+ if (/[",\r\n]/.test(str)) {
59
+ return `"${str.replace(/"/g, '""')}"`;
60
+ }
61
+ return str;
62
+ }
63
+ function formatRowsAsCsv(rows, columns) {
64
+ const lines = [];
65
+ for (const row of rows) {
66
+ const cells = columns.map((col) => {
67
+ if (col === "_id") return escapeCsvCell(row._id);
68
+ if (col === "_index") return escapeCsvCell(row._index);
69
+ return escapeCsvCell(readNestedField(row.source, col));
70
+ });
71
+ lines.push(`${cells.join(",")}\r
72
+ `);
73
+ }
74
+ return lines.join("");
75
+ }
76
+ function formatRowsAsNdjson(rows) {
77
+ return rows.map((row) => `${JSON.stringify({ _index: row._index, _id: row._id, ...row.source })}
78
+ `).join("");
79
+ }
80
+ async function writeChunk(stream, chunk) {
81
+ if (!chunk) return;
82
+ if (!stream.write(chunk)) {
83
+ await (0, import_events.once)(stream, "drain");
84
+ }
85
+ }
86
+ class ReportExportService {
87
+ constructor(connections, reportService) {
88
+ this.connections = connections;
89
+ this.reportService = reportService;
90
+ }
91
+ resolveMaxExportCap(requested) {
92
+ const envCap = Number(process.env.ELASTIC_REPORT_MAX_EXPORT_ROWS);
93
+ const hardCap = Number.isFinite(envCap) && envCap > 0 ? Math.trunc(envCap) : import_constants.DEFAULT_MAX_EXPORT_ROWS;
94
+ if (typeof requested === "number" && Number.isFinite(requested) && requested > 0) {
95
+ return Math.min(hardCap, Math.trunc(requested));
96
+ }
97
+ return hardCap;
98
+ }
99
+ async createExportStream(params) {
100
+ var _a, _b, _c;
101
+ const report = await this.reportService.getReport(params.reportId);
102
+ if (report.spec.allowExport === false) {
103
+ const err = new Error("Data export is disabled for this report");
104
+ err.status = 403;
105
+ throw err;
106
+ }
107
+ const { dataView, fields } = await this.reportService.inspectDataViewFields(report.dataViewId, false);
108
+ const client = await this.connections.getClient(dataView.dataSourceKey);
109
+ const maxRows = this.resolveMaxExportCap(params.maxRows);
110
+ const batchSize = Math.min(import_constants.EXPORT_BATCH_SIZE, maxRows);
111
+ const exportSpec = (0, import_ReportQueryCompiler.normalizeReportSpec)({
112
+ ...report.spec,
113
+ visualization: "table",
114
+ ...params.columns && params.columns.length > 0 ? { columns: params.columns } : {},
115
+ chart: { ...report.spec.chart, showHistogram: false }
116
+ });
117
+ const effectiveOverrides = report.spec.allowInteractiveControls === false ? {
118
+ contextFilters: (_a = params.overrides) == null ? void 0 : _a.contextFilters,
119
+ sharedFilters: (_b = params.overrides) == null ? void 0 : _b.sharedFilters,
120
+ timeZone: (_c = params.overrides) == null ? void 0 : _c.timeZone
121
+ } : params.overrides;
122
+ const pitId = await client.openPit(dataView.indexPattern, "1m");
123
+ const firstCompile = (0, import_ReportQueryCompiler.compileSearchRequest)({
124
+ spec: exportSpec,
125
+ overrides: {
126
+ ...effectiveOverrides,
127
+ page: 1,
128
+ pageSize: batchSize,
129
+ searchAfter: void 0
130
+ },
131
+ timeField: dataView.timeField,
132
+ fields,
133
+ maxRowsCap: import_constants.EXPORT_BATCH_SIZE,
134
+ userContext: params.userContext,
135
+ usePit: Boolean(pitId)
136
+ });
137
+ firstCompile.body.size = batchSize;
138
+ delete firstCompile.body.from;
139
+ delete firstCompile.body.highlight;
140
+ delete firstCompile.body.aggs;
141
+ let firstParsed;
142
+ try {
143
+ const firstRaw = await client.search(dataView.indexPattern, firstCompile.body, pitId ? { pitId } : void 0);
144
+ firstParsed = (0, import_ReportQueryCompiler.parseSearchResponse)(firstRaw, firstCompile.body, firstCompile.effectiveSpec, dataView.timeField);
145
+ } catch (error) {
146
+ if (pitId) {
147
+ await client.closePit(pitId);
148
+ }
149
+ throw error;
150
+ }
151
+ const resolvedColumns = params.columns && params.columns.length > 0 ? params.columns : firstParsed.columns.length > 0 ? firstParsed.columns : ["@timestamp", "_index", "_id"];
152
+ const safeSlug = report.title.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || `report-${String(report.id)}`;
153
+ const ext = params.format === "ndjson" ? "ndjson" : "csv";
154
+ const filename = `${safeSlug}.${ext}`;
155
+ const contentType = params.format === "ndjson" ? "application/x-ndjson; charset=utf-8" : "text/csv; charset=utf-8";
156
+ const stream = new import_stream.PassThrough();
157
+ const pumpRemainingBatches = async () => {
158
+ let exportedCount = 0;
159
+ let activeCursor = firstParsed.nextSearchAfter;
160
+ let activePit = firstParsed.pitId ?? pitId ?? void 0;
161
+ try {
162
+ if (params.format === "csv") {
163
+ await writeChunk(
164
+ stream,
165
+ `\uFEFF${resolvedColumns.map((col) => escapeCsvCell(col, { allowAtIdentifier: true })).join(",")}\r
166
+ `
167
+ );
168
+ await writeChunk(stream, formatRowsAsCsv(firstParsed.rows, resolvedColumns));
169
+ } else {
170
+ await writeChunk(stream, formatRowsAsNdjson(firstParsed.rows));
171
+ }
172
+ exportedCount += firstParsed.rows.length;
173
+ while (exportedCount < maxRows && firstParsed.rows.length === batchSize && activeCursor && activeCursor.length > 0) {
174
+ const remaining = maxRows - exportedCount;
175
+ const nextSize = Math.min(import_constants.EXPORT_BATCH_SIZE, remaining);
176
+ const nextCompile = (0, import_ReportQueryCompiler.compileSearchRequest)({
177
+ spec: exportSpec,
178
+ overrides: {
179
+ ...effectiveOverrides,
180
+ pageSize: nextSize,
181
+ searchAfter: activeCursor
182
+ },
183
+ timeField: dataView.timeField,
184
+ fields,
185
+ maxRowsCap: import_constants.EXPORT_BATCH_SIZE,
186
+ userContext: params.userContext,
187
+ usePit: Boolean(activePit)
188
+ });
189
+ nextCompile.body.size = nextSize;
190
+ nextCompile.body.search_after = activeCursor;
191
+ delete nextCompile.body.from;
192
+ delete nextCompile.body.highlight;
193
+ delete nextCompile.body.aggs;
194
+ const nextRaw = await client.search(
195
+ dataView.indexPattern,
196
+ nextCompile.body,
197
+ activePit ? { pitId: activePit } : void 0
198
+ );
199
+ const nextParsed = (0, import_ReportQueryCompiler.parseSearchResponse)(
200
+ nextRaw,
201
+ nextCompile.body,
202
+ nextCompile.effectiveSpec,
203
+ dataView.timeField
204
+ );
205
+ if (nextParsed.pitId) {
206
+ activePit = nextParsed.pitId;
207
+ }
208
+ if (nextParsed.rows.length === 0) {
209
+ break;
210
+ }
211
+ if (params.format === "csv") {
212
+ await writeChunk(stream, formatRowsAsCsv(nextParsed.rows, resolvedColumns));
213
+ } else {
214
+ await writeChunk(stream, formatRowsAsNdjson(nextParsed.rows));
215
+ }
216
+ exportedCount += nextParsed.rows.length;
217
+ activeCursor = nextParsed.nextSearchAfter;
218
+ if (nextParsed.rows.length < nextSize) {
219
+ break;
220
+ }
221
+ }
222
+ stream.end();
223
+ } catch (err) {
224
+ stream.destroy(err instanceof Error ? err : new Error(String(err)));
225
+ } finally {
226
+ if (activePit) {
227
+ await client.closePit(activePit);
228
+ }
229
+ }
230
+ };
231
+ pumpRemainingBatches();
232
+ return {
233
+ stream,
234
+ filename,
235
+ contentType
236
+ };
237
+ }
238
+ }
239
+ // Annotate the CommonJS export names for ESM import in node:
240
+ 0 && (module.exports = {
241
+ ReportExportService,
242
+ escapeCsvCell
243
+ });