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
@@ -83,7 +83,9 @@ function createElasticReportToolCatalog(app, reportService) {
83
83
  async execute(_args, ctx) {
84
84
  (0, import_acl_guard.assertAuthenticated)(ctx);
85
85
  const dataViews = await reportService.listDataViews();
86
- return { dataViews };
86
+ return {
87
+ dataViews: dataViews.filter((dv) => (0, import_acl_guard.canAccessDataView)(app, ctx, dv))
88
+ };
87
89
  }
88
90
  },
89
91
  {
@@ -118,6 +120,11 @@ function createElasticReportToolCatalog(app, reportService) {
118
120
  description: {
119
121
  type: "string",
120
122
  description: "Optional description of the dataset."
123
+ },
124
+ allowedRoles: {
125
+ type: "array",
126
+ items: { type: "string" },
127
+ description: "Optional role names allowed to access this Data View (empty means all authenticated viewers)."
121
128
  }
122
129
  }
123
130
  },
@@ -131,7 +138,8 @@ function createElasticReportToolCatalog(app, reportService) {
131
138
  dataSourceKey: typeof args.dataSourceKey === "string" ? args.dataSourceKey : "",
132
139
  indexPattern: typeof args.indexPattern === "string" ? args.indexPattern : "",
133
140
  timeField: typeof args.timeField === "string" ? args.timeField : null,
134
- description: typeof args.description === "string" ? args.description : null
141
+ description: typeof args.description === "string" ? args.description : null,
142
+ ...args.allowedRoles !== void 0 ? { allowedRoles: (0, import_acl_guard.normalizeRoleList)(args.allowedRoles) } : {}
135
143
  },
136
144
  (0, import_ElasticReportService.extractCurrentUserId)(ctx)
137
145
  );
@@ -166,6 +174,9 @@ function createElasticReportToolCatalog(app, reportService) {
166
174
  const refresh = args.refresh === true;
167
175
  if (refresh) {
168
176
  (0, import_acl_guard.assertCanManageReports)(app, ctx);
177
+ } else {
178
+ const dv = await reportService.getDataView(dataViewId);
179
+ (0, import_acl_guard.assertCanAccessDataView)(app, ctx, dv);
169
180
  }
170
181
  const { dataView, fields } = await reportService.inspectDataViewFields(dataViewId, refresh);
171
182
  return {
@@ -239,6 +250,36 @@ function createElasticReportToolCatalog(app, reportService) {
239
250
  }
240
251
  }
241
252
  },
253
+ lockedFilters: {
254
+ type: "array",
255
+ description: "Mandatory server-enforced filters (e.g. tenant or department isolation) that viewer interactive overrides can never remove or replace.",
256
+ items: {
257
+ type: "object",
258
+ required: ["field", "operator"],
259
+ properties: {
260
+ field: { type: "string" },
261
+ operator: {
262
+ type: "string",
263
+ enum: [
264
+ "eq",
265
+ "ne",
266
+ "in",
267
+ "not_in",
268
+ "gt",
269
+ "gte",
270
+ "lt",
271
+ "lte",
272
+ "between",
273
+ "contains",
274
+ "exists",
275
+ "not_exists"
276
+ ]
277
+ },
278
+ value: {},
279
+ valueTo: {}
280
+ }
281
+ }
282
+ },
242
283
  sort: {
243
284
  type: "array",
244
285
  items: {
@@ -280,14 +321,23 @@ function createElasticReportToolCatalog(app, reportService) {
280
321
  topN: { type: "number" },
281
322
  metricType: {
282
323
  type: "string",
283
- enum: ["count", "sum", "avg", "min", "max", "cardinality"]
324
+ enum: ["count", "sum", "avg", "min", "max", "cardinality", "p50", "p95", "p99"]
284
325
  },
285
326
  metricField: { type: "string" },
286
327
  metricLabel: { type: "string" },
287
- showHistogram: { type: "boolean" }
328
+ showHistogram: { type: "boolean" },
329
+ splitSeriesField: { type: "string" },
330
+ splitSeriesTopN: { type: "number" },
331
+ stackMode: { type: "string", enum: ["none", "stacked", "percent"] },
332
+ comparePreviousPeriod: { type: "boolean" }
288
333
  }
289
334
  },
290
- allowInteractiveControls: { type: "boolean" }
335
+ fieldFormats: {
336
+ type: "object",
337
+ description: 'Optional map of fieldName -> format ("duration_ms" | "bytes" | "percent" | "number" | "status_badge" | "url").'
338
+ },
339
+ allowInteractiveControls: { type: "boolean" },
340
+ allowExport: { type: "boolean" }
291
341
  }
292
342
  }
293
343
  }
@@ -298,7 +348,8 @@ function createElasticReportToolCatalog(app, reportService) {
298
348
  const { dataView, result } = await reportService.previewReport({
299
349
  dataViewId,
300
350
  spec: isRecord(args.spec) ? args.spec : { visualization: "table" },
301
- forMcp: true
351
+ forMcp: true,
352
+ userContext: (0, import_ElasticReportService.extractServerUserContext)(ctx)
302
353
  });
303
354
  return {
304
355
  dataView: {
@@ -309,12 +360,18 @@ function createElasticReportToolCatalog(app, reportService) {
309
360
  total: result.total,
310
361
  totalRelation: result.totalRelation,
311
362
  tookMs: result.tookMs,
363
+ ...result.timedOut ? { timedOut: true } : {},
364
+ ...result.shards ? { shards: result.shards } : {},
365
+ ...result.warnings && result.warnings.length > 0 ? { warnings: result.warnings } : {},
312
366
  visualization: result.visualization,
313
367
  columns: result.columns,
314
368
  sampleRows: result.rows.slice(0, 10),
315
369
  series: result.series,
370
+ ...result.seriesKeys ? { seriesKeys: result.seriesKeys } : {},
316
371
  histogram: result.histogram,
317
372
  metricValue: result.metricValue,
373
+ ...result.previousMetricValue !== void 0 ? { previousMetricValue: result.previousMetricValue } : {},
374
+ ...result.deltaPercent !== void 0 ? { deltaPercent: result.deltaPercent } : {},
318
375
  metricLabel: result.metricLabel,
319
376
  compiledDsl: result.compiledDsl
320
377
  };
@@ -349,6 +406,11 @@ function createElasticReportToolCatalog(app, reportService) {
349
406
  type: "boolean",
350
407
  description: "Whether the report is published for selection in page blocks (default true)."
351
408
  },
409
+ allowedRoles: {
410
+ type: "array",
411
+ items: { type: "string" },
412
+ description: "Optional role names allowed to view/run this report (empty means all authenticated viewers)."
413
+ },
352
414
  spec: {
353
415
  type: "object",
354
416
  description: "Validated ReportSpec object (same schema as es_preview_report.spec)."
@@ -364,6 +426,7 @@ function createElasticReportToolCatalog(app, reportService) {
364
426
  description: typeof args.description === "string" ? args.description : null,
365
427
  dataViewId: requireId(args.dataViewId, "dataViewId"),
366
428
  published: args.published !== false,
429
+ ...args.allowedRoles !== void 0 ? { allowedRoles: (0, import_acl_guard.normalizeRoleList)(args.allowedRoles) } : {},
367
430
  spec: isRecord(args.spec) ? args.spec : { visualization: "table" }
368
431
  },
369
432
  (0, import_ElasticReportService.extractCurrentUserId)(ctx)
@@ -397,16 +460,175 @@ function createElasticReportToolCatalog(app, reportService) {
397
460
  const isManager = (0, import_acl_guard.canManageReports)(app, ctx);
398
461
  if (args.reportId !== void 0 && args.reportId !== null && String(args.reportId).trim() !== "") {
399
462
  const report = await reportService.getReport(requireId(args.reportId, "reportId"));
400
- if (!isManager && !report.published) {
401
- throw new Error("Report not found");
402
- }
463
+ const dataView = report.dataView ?? await reportService.getDataView(report.dataViewId);
464
+ (0, import_acl_guard.assertCanAccessReport)(app, ctx, report, dataView);
403
465
  return { report };
404
466
  }
405
467
  const reports = await reportService.listReports({
406
468
  publishedOnly: !isManager,
407
469
  search: typeof args.search === "string" ? args.search : void 0
408
470
  });
409
- return { reports };
471
+ return {
472
+ reports: reports.filter((r) => (0, import_acl_guard.canAccessReport)(app, ctx, r, r.dataView))
473
+ };
474
+ }
475
+ },
476
+ {
477
+ name: "es_analyze_report",
478
+ title: "Execute & Analyze Saved Elasticsearch Report (Viewer-Safe)",
479
+ description: "Execute a published Saved Elasticsearch Report under the caller's effective NocoBase role and mandatory server lockedFilters, optionally narrowing with KQL or timeRange overrides, to summarize anomalies, top buckets, KPI deltas, or sample logs.",
480
+ defaultPermission: "ALLOW",
481
+ inputSchema: {
482
+ type: "object",
483
+ required: ["reportId"],
484
+ properties: {
485
+ reportId: {
486
+ type: ["number", "string"],
487
+ description: "ID of the Saved Report from es_list_reports."
488
+ },
489
+ query: {
490
+ type: "string",
491
+ description: "Optional KQL override when the report allows interactive controls."
492
+ },
493
+ timePreset: {
494
+ type: "string",
495
+ enum: ["last_15m", "last_1h", "last_24h", "last_7d", "last_30d", "last_90d", "all"],
496
+ description: "Optional time preset override."
497
+ }
498
+ }
499
+ },
500
+ async execute(args, ctx) {
501
+ (0, import_acl_guard.assertAuthenticated)(ctx);
502
+ const reportId = requireId(args.reportId, "reportId");
503
+ const report = await reportService.getReport(reportId);
504
+ const dataView = report.dataView ?? await reportService.getDataView(report.dataViewId);
505
+ (0, import_acl_guard.assertCanAccessReport)(app, ctx, report, dataView);
506
+ const overrides = {};
507
+ if (typeof args.query === "string") {
508
+ overrides.query = args.query;
509
+ }
510
+ if (typeof args.timePreset === "string" && args.timePreset.trim()) {
511
+ overrides.timeRange = {
512
+ preset: args.timePreset
513
+ };
514
+ }
515
+ const { result } = await reportService.runSavedReport({
516
+ reportId,
517
+ overrides: Object.keys(overrides).length > 0 ? overrides : void 0,
518
+ requirePublished: false,
519
+ forMcp: true,
520
+ userContext: (0, import_ElasticReportService.extractServerUserContext)(ctx)
521
+ });
522
+ return {
523
+ report: {
524
+ id: report.id,
525
+ title: report.title,
526
+ visualization: report.visualization,
527
+ dataViewTitle: dataView.title,
528
+ indexPattern: dataView.indexPattern
529
+ },
530
+ total: result.total,
531
+ totalRelation: result.totalRelation,
532
+ tookMs: result.tookMs,
533
+ ...result.warnings ? { warnings: result.warnings } : {},
534
+ metricLabel: result.metricLabel,
535
+ metricValue: result.metricValue,
536
+ ...result.previousMetricValue !== void 0 ? { previousMetricValue: result.previousMetricValue } : {},
537
+ ...result.deltaPercent !== void 0 ? { deltaPercent: result.deltaPercent } : {},
538
+ series: result.series.slice(0, 15),
539
+ ...result.seriesKeys ? { seriesKeys: result.seriesKeys } : {},
540
+ histogram: result.histogram.slice(0, 24),
541
+ sampleRows: result.rows.slice(0, 15).map((r) => r.source)
542
+ };
543
+ }
544
+ },
545
+ {
546
+ name: "es_create_dashboard_bundle",
547
+ title: "Create Multi-Panel Elasticsearch Dashboard Bundle",
548
+ description: "Create a coordinated set of Saved Elasticsearch Reports (e.g. KPI with previous-period delta, trend line/area chart, stacked/grouped breakdown bar chart, and Discover table) sharing common Data View, lockedFilters, and allowedRoles, ready to combine with an Elastic Filter Bar on a NocoBase page.",
549
+ defaultPermission: "ALLOW",
550
+ inputSchema: {
551
+ type: "object",
552
+ required: ["dataViewId", "panels"],
553
+ properties: {
554
+ dataViewId: {
555
+ type: ["number", "string"],
556
+ description: "Target Data View ID."
557
+ },
558
+ allowedRoles: {
559
+ type: "array",
560
+ items: { type: "string" },
561
+ description: "Optional role names applied to every report in the bundle."
562
+ },
563
+ lockedFilters: {
564
+ type: "array",
565
+ description: "Optional mandatory server-enforced filters applied to every report in the bundle.",
566
+ items: {
567
+ type: "object",
568
+ required: ["field", "operator"],
569
+ properties: {
570
+ field: { type: "string" },
571
+ operator: { type: "string" },
572
+ value: {},
573
+ valueTo: {}
574
+ }
575
+ }
576
+ },
577
+ panels: {
578
+ type: "array",
579
+ minItems: 1,
580
+ maxItems: 8,
581
+ items: {
582
+ type: "object",
583
+ required: ["title", "spec"],
584
+ properties: {
585
+ title: { type: "string" },
586
+ description: { type: "string" },
587
+ spec: { type: "object" }
588
+ }
589
+ }
590
+ }
591
+ }
592
+ },
593
+ async execute(args, ctx) {
594
+ (0, import_acl_guard.assertCanManageReports)(app, ctx);
595
+ const dataViewId = requireId(args.dataViewId, "dataViewId");
596
+ const panels = Array.isArray(args.panels) ? args.panels : [];
597
+ if (panels.length === 0 || panels.length > 8) {
598
+ throw new Error('"panels" must contain between 1 and 8 report definitions');
599
+ }
600
+ const sharedRoles = args.allowedRoles !== void 0 ? (0, import_acl_guard.normalizeRoleList)(args.allowedRoles) : void 0;
601
+ const sharedLockedFilters = Array.isArray(args.lockedFilters) ? args.lockedFilters : void 0;
602
+ const userId = (0, import_ElasticReportService.extractCurrentUserId)(ctx);
603
+ const createdReports = [];
604
+ for (const panel of panels) {
605
+ if (!isRecord(panel)) continue;
606
+ const rawSpec = isRecord(panel.spec) ? { ...panel.spec } : { visualization: "table" };
607
+ if (sharedLockedFilters && !Array.isArray(rawSpec.lockedFilters)) {
608
+ rawSpec.lockedFilters = sharedLockedFilters;
609
+ }
610
+ const saved = await reportService.saveReport(
611
+ {
612
+ title: typeof panel.title === "string" ? panel.title : "Dashboard Panel",
613
+ description: typeof panel.description === "string" ? panel.description : null,
614
+ dataViewId,
615
+ published: true,
616
+ ...sharedRoles !== void 0 ? { allowedRoles: sharedRoles } : {},
617
+ spec: rawSpec
618
+ },
619
+ userId
620
+ );
621
+ createdReports.push({
622
+ id: saved.id,
623
+ title: saved.title,
624
+ visualization: saved.visualization
625
+ });
626
+ }
627
+ return {
628
+ createdCount: createdReports.length,
629
+ reports: createdReports,
630
+ usageHint: 'Add an "Elastic Filter Bar" block at the top of a NocoBase /v/ page, then add an "Elastic Report" block for each created report so all panels cross-filter together.'
631
+ };
410
632
  }
411
633
  }
412
634
  ];
@@ -38,6 +38,8 @@ var import_ElasticReportMcpServer = require("./mcp/ElasticReportMcpServer");
38
38
  var import_ElasticReportToolCatalog = require("./mcp/ElasticReportToolCatalog");
39
39
  var import_ElasticsearchConnectionService = require("./services/ElasticsearchConnectionService");
40
40
  var import_ElasticReportService = require("./services/ElasticReportService");
41
+ var import_ReportExportService = require("./services/ReportExportService");
42
+ var import_ElasticReportQueryInstruction = require("./workflow/ElasticReportQueryInstruction");
41
43
  function isRecord(value) {
42
44
  return typeof value === "object" && value !== null && !Array.isArray(value);
43
45
  }
@@ -61,9 +63,24 @@ function parseIdParam(value, label) {
61
63
  err.status = 400;
62
64
  throw err;
63
65
  }
66
+ function parseOverridesParam(raw) {
67
+ if (isRecord(raw)) {
68
+ return raw;
69
+ }
70
+ if (typeof raw === "string" && raw.trim()) {
71
+ try {
72
+ const parsed = JSON.parse(raw);
73
+ return isRecord(parsed) ? parsed : void 0;
74
+ } catch {
75
+ return void 0;
76
+ }
77
+ }
78
+ return void 0;
79
+ }
64
80
  class PluginElasticReportServer extends import_server.Plugin {
65
81
  connectionService;
66
82
  reportService;
83
+ exportService;
67
84
  mcpServer;
68
85
  toolsCatalog = [];
69
86
  schemaCollections = [import_constants.DATA_VIEWS_COLLECTION, import_constants.REPORTS_COLLECTION];
@@ -74,9 +91,10 @@ class PluginElasticReportServer extends import_server.Plugin {
74
91
  });
75
92
  this.connectionService = new import_ElasticsearchConnectionService.ElasticsearchConnectionService(this.app);
76
93
  this.reportService = new import_ElasticReportService.ElasticReportService(this.app, this.connectionService);
94
+ this.exportService = new import_ReportExportService.ReportExportService(this.connectionService, this.reportService);
77
95
  this.toolsCatalog = (0, import_ElasticReportToolCatalog.createElasticReportToolCatalog)(this.app, this.reportService);
78
96
  this.mcpServer = new import_ElasticReportMcpServer.ElasticReportMcpServer({
79
- version: ((_a = this.options) == null ? void 0 : _a.version) || "0.1.0",
97
+ version: ((_a = this.options) == null ? void 0 : _a.version) || "0.7.0",
80
98
  tools: this.toolsCatalog,
81
99
  logger: this.app.logger
82
100
  });
@@ -85,6 +103,7 @@ class PluginElasticReportServer extends import_server.Plugin {
85
103
  this.registerServiceResource();
86
104
  this.registerMcpEndpoint();
87
105
  this.registerAclRules();
106
+ this.registerWorkflowInstructions();
88
107
  this.registerAITools();
89
108
  await this.registerPluginMcpClientEntry();
90
109
  this.app.on("beforeStop", async () => {
@@ -92,6 +111,16 @@ class PluginElasticReportServer extends import_server.Plugin {
92
111
  await ((_a = this.connectionService) == null ? void 0 : _a.close());
93
112
  });
94
113
  }
114
+ registerWorkflowInstructions() {
115
+ const workflow = this.app.pm.get("workflow");
116
+ if (!workflow || typeof workflow.registerInstruction !== "function") {
117
+ return;
118
+ }
119
+ workflow.registerInstruction(
120
+ import_constants.WORKFLOW_INSTRUCTION_TYPE,
121
+ new import_ElasticReportQueryInstruction.ElasticReportQueryInstruction(workflow, this.reportService)
122
+ );
123
+ }
95
124
  async install(_options) {
96
125
  await this.ensureSchema();
97
126
  }
@@ -117,10 +146,32 @@ class PluginElasticReportServer extends import_server.Plugin {
117
146
  name: import_constants.SERVICE_RESOURCE,
118
147
  actions: {
119
148
  listConnections: async (ctx, next) => {
149
+ (0, import_acl_guard.assertCanManageReports)(this.app, ctx);
120
150
  ctx.body = await this.reportService.listConnections();
121
151
  await next();
122
152
  },
153
+ testConnection: async (ctx, next) => {
154
+ (0, import_acl_guard.assertCanManageReports)(this.app, ctx);
155
+ const payload = getActionPayload(ctx);
156
+ const dataSourceKey = typeof payload.dataSourceKey === "string" ? payload.dataSourceKey.trim() : "";
157
+ if (!dataSourceKey) {
158
+ ctx.throw(400, "dataSourceKey is required");
159
+ }
160
+ const indexPattern = typeof payload.indexPattern === "string" && payload.indexPattern.trim() ? payload.indexPattern.trim() : "*";
161
+ try {
162
+ ctx.body = await this.reportService.testConnection(dataSourceKey, indexPattern);
163
+ } catch (error) {
164
+ ctx.throw(400, error instanceof Error ? error.message : String(error));
165
+ }
166
+ await next();
167
+ },
168
+ listRoles: async (ctx, next) => {
169
+ (0, import_acl_guard.assertCanManageReports)(this.app, ctx);
170
+ ctx.body = await this.reportService.listAvailableRoles();
171
+ await next();
172
+ },
123
173
  listIndices: async (ctx, next) => {
174
+ (0, import_acl_guard.assertCanManageReports)(this.app, ctx);
124
175
  const payload = getActionPayload(ctx);
125
176
  const dataSourceKey = typeof payload.dataSourceKey === "string" ? payload.dataSourceKey.trim() : "";
126
177
  if (!dataSourceKey) {
@@ -138,12 +189,17 @@ class PluginElasticReportServer extends import_server.Plugin {
138
189
  const payload = getActionPayload(ctx);
139
190
  try {
140
191
  if (payload.dataViewId !== void 0 && payload.dataViewId !== null && String(payload.dataViewId).trim()) {
192
+ const dvId = parseIdParam(payload.dataViewId, "dataViewId");
141
193
  const refresh = payload.refresh === true || payload.refresh === "true";
142
- ctx.body = await this.reportService.inspectDataViewFields(
143
- parseIdParam(payload.dataViewId, "dataViewId"),
144
- refresh
145
- );
194
+ if (refresh) {
195
+ (0, import_acl_guard.assertCanManageReports)(this.app, ctx);
196
+ } else {
197
+ const dv = await this.reportService.getDataView(dvId);
198
+ (0, import_acl_guard.assertCanAccessDataView)(this.app, ctx, dv);
199
+ }
200
+ ctx.body = await this.reportService.inspectDataViewFields(dvId, refresh);
146
201
  } else {
202
+ (0, import_acl_guard.assertCanManageReports)(this.app, ctx);
147
203
  const dataSourceKey = typeof payload.dataSourceKey === "string" ? payload.dataSourceKey.trim() : "";
148
204
  const indexPattern = typeof payload.indexPattern === "string" ? payload.indexPattern.trim() : "";
149
205
  if (!dataSourceKey || !indexPattern) {
@@ -159,6 +215,7 @@ class PluginElasticReportServer extends import_server.Plugin {
159
215
  await next();
160
216
  },
161
217
  upsertDataView: async (ctx, next) => {
218
+ (0, import_acl_guard.assertCanManageReports)(this.app, ctx);
162
219
  const payload = getActionPayload(ctx);
163
220
  try {
164
221
  ctx.body = await this.reportService.upsertDataView(
@@ -168,23 +225,27 @@ class PluginElasticReportServer extends import_server.Plugin {
168
225
  dataSourceKey: typeof payload.dataSourceKey === "string" ? payload.dataSourceKey : "",
169
226
  indexPattern: typeof payload.indexPattern === "string" ? payload.indexPattern : "",
170
227
  timeField: typeof payload.timeField === "string" ? payload.timeField : null,
171
- description: typeof payload.description === "string" ? payload.description : null
228
+ description: typeof payload.description === "string" ? payload.description : null,
229
+ ...payload.allowedRoles !== void 0 ? { allowedRoles: (0, import_acl_guard.normalizeRoleList)(payload.allowedRoles) } : {}
172
230
  },
173
231
  (0, import_ElasticReportService.extractCurrentUserId)(ctx)
174
232
  );
175
233
  } catch (error) {
176
- ctx.throw(400, error instanceof Error ? error.message : String(error));
234
+ const status = (error == null ? void 0 : error.status) ?? 400;
235
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
177
236
  }
178
237
  await next();
179
238
  },
180
239
  previewReport: async (ctx, next) => {
240
+ (0, import_acl_guard.assertCanManageReports)(this.app, ctx);
181
241
  const payload = getActionPayload(ctx);
182
242
  try {
183
243
  const dataViewId = parseIdParam(payload.dataViewId, "dataViewId");
184
244
  ctx.body = await this.reportService.previewReport({
185
245
  dataViewId,
186
246
  spec: payload.spec,
187
- overrides: isRecord(payload.overrides) ? payload.overrides : void 0
247
+ overrides: parseOverridesParam(payload.overrides),
248
+ userContext: (0, import_ElasticReportService.extractServerUserContext)(ctx)
188
249
  });
189
250
  } catch (error) {
190
251
  const status = (error == null ? void 0 : error.status) ?? 400;
@@ -193,6 +254,7 @@ class PluginElasticReportServer extends import_server.Plugin {
193
254
  await next();
194
255
  },
195
256
  saveReport: async (ctx, next) => {
257
+ (0, import_acl_guard.assertCanManageReports)(this.app, ctx);
196
258
  const payload = getActionPayload(ctx);
197
259
  try {
198
260
  ctx.body = await this.reportService.saveReport(
@@ -202,22 +264,25 @@ class PluginElasticReportServer extends import_server.Plugin {
202
264
  description: typeof payload.description === "string" ? payload.description : null,
203
265
  dataViewId: parseIdParam(payload.dataViewId, "dataViewId"),
204
266
  spec: payload.spec,
205
- published: payload.published !== false
267
+ published: payload.published !== false,
268
+ ...payload.allowedRoles !== void 0 ? { allowedRoles: (0, import_acl_guard.normalizeRoleList)(payload.allowedRoles) } : {}
206
269
  },
207
270
  (0, import_ElasticReportService.extractCurrentUserId)(ctx)
208
271
  );
209
272
  } catch (error) {
210
- ctx.throw(400, error instanceof Error ? error.message : String(error));
273
+ const status = (error == null ? void 0 : error.status) ?? 400;
274
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
211
275
  }
212
276
  await next();
213
277
  },
214
278
  listPublishedReports: async (ctx, next) => {
215
279
  const payload = getActionPayload(ctx);
216
280
  const search = typeof payload.search === "string" ? payload.search : void 0;
217
- ctx.body = await this.reportService.listReports({
281
+ const publishedReports = await this.reportService.listReports({
218
282
  publishedOnly: true,
219
283
  search
220
284
  });
285
+ ctx.body = publishedReports.filter((report) => (0, import_acl_guard.canAccessReport)(this.app, ctx, report, report.dataView));
221
286
  await next();
222
287
  },
223
288
  getReportMeta: async (ctx, next) => {
@@ -227,11 +292,8 @@ class PluginElasticReportServer extends import_server.Plugin {
227
292
  try {
228
293
  const reportId = parseIdParam(rawId, "reportId");
229
294
  const report = await this.reportService.getReport(reportId);
230
- const isManager = (0, import_acl_guard.canManageReports)(this.app, ctx);
231
- if (!isManager && !report.published) {
232
- ctx.throw(404, "Report not found");
233
- }
234
295
  const { dataView, fields } = await this.reportService.inspectDataViewFields(report.dataViewId, false);
296
+ (0, import_acl_guard.assertCanAccessReport)(this.app, ctx, report, dataView);
235
297
  ctx.body = { report, dataView, fields };
236
298
  } catch (error) {
237
299
  const status = (error == null ? void 0 : error.status) ?? 400;
@@ -245,11 +307,48 @@ class PluginElasticReportServer extends import_server.Plugin {
245
307
  const rawId = payload.reportId ?? ((_b = (_a = ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.filterByTk);
246
308
  try {
247
309
  const reportId = parseIdParam(rawId, "reportId");
248
- const isManager = (0, import_acl_guard.canManageReports)(this.app, ctx);
310
+ const report = await this.reportService.getReport(reportId);
311
+ const dataView = report.dataView ?? await this.reportService.getDataView(report.dataViewId);
312
+ (0, import_acl_guard.assertCanAccessReport)(this.app, ctx, report, dataView);
249
313
  ctx.body = await this.reportService.runSavedReport({
250
314
  reportId,
251
- overrides: isRecord(payload.overrides) ? payload.overrides : void 0,
252
- requirePublished: !isManager
315
+ overrides: parseOverridesParam(payload.overrides),
316
+ requirePublished: false,
317
+ userContext: (0, import_ElasticReportService.extractServerUserContext)(ctx)
318
+ });
319
+ } catch (error) {
320
+ const status = (error == null ? void 0 : error.status) ?? 400;
321
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
322
+ }
323
+ await next();
324
+ },
325
+ inspectTopValues: async (ctx, next) => {
326
+ const payload = getActionPayload(ctx);
327
+ try {
328
+ const field = typeof payload.field === "string" ? payload.field.trim() : "";
329
+ if (!field) {
330
+ ctx.throw(400, "field is required");
331
+ }
332
+ let dataViewId;
333
+ let reportId;
334
+ if (payload.reportId !== void 0 && payload.reportId !== null && String(payload.reportId).trim() !== "") {
335
+ reportId = parseIdParam(payload.reportId, "reportId");
336
+ const report = await this.reportService.getReport(reportId);
337
+ const dataView = report.dataView ?? await this.reportService.getDataView(report.dataViewId);
338
+ (0, import_acl_guard.assertCanAccessReport)(this.app, ctx, report, dataView);
339
+ dataViewId = report.dataViewId;
340
+ } else {
341
+ dataViewId = parseIdParam(payload.dataViewId, "dataViewId");
342
+ const dataView = await this.reportService.getDataView(dataViewId);
343
+ (0, import_acl_guard.assertCanAccessDataView)(this.app, ctx, dataView);
344
+ }
345
+ ctx.body = await this.reportService.inspectFieldTopValues({
346
+ dataViewId,
347
+ ...reportId !== void 0 ? { reportId } : {},
348
+ field,
349
+ size: typeof payload.size === "number" ? payload.size : Number(payload.size) || 10,
350
+ overrides: parseOverridesParam(payload.overrides),
351
+ userContext: (0, import_ElasticReportService.extractServerUserContext)(ctx)
253
352
  });
254
353
  } catch (error) {
255
354
  const status = (error == null ? void 0 : error.status) ?? 400;
@@ -257,6 +356,37 @@ class PluginElasticReportServer extends import_server.Plugin {
257
356
  }
258
357
  await next();
259
358
  },
359
+ exportReport: async (ctx, next) => {
360
+ var _a, _b;
361
+ const payload = getActionPayload(ctx);
362
+ const rawId = payload.reportId ?? ((_b = (_a = ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.filterByTk);
363
+ try {
364
+ const reportId = parseIdParam(rawId, "reportId");
365
+ const report = await this.reportService.getReport(reportId);
366
+ const dataView = report.dataView ?? await this.reportService.getDataView(report.dataViewId);
367
+ (0, import_acl_guard.assertCanAccessReport)(this.app, ctx, report, dataView);
368
+ const format = payload.format === "ndjson" ? "ndjson" : "csv";
369
+ const columns = Array.isArray(payload.columns) ? payload.columns.filter((c) => typeof c === "string" && Boolean(c.trim())) : typeof payload.columns === "string" && payload.columns.trim() ? payload.columns.split(",").map((c) => c.trim()).filter(Boolean) : void 0;
370
+ const maxRows = typeof payload.maxRows === "number" ? payload.maxRows : payload.maxRows !== void 0 ? Number(payload.maxRows) : void 0;
371
+ const { stream, filename, contentType } = await this.exportService.createExportStream({
372
+ reportId,
373
+ format,
374
+ overrides: parseOverridesParam(payload.overrides),
375
+ ...columns ? { columns } : {},
376
+ ...maxRows !== void 0 && Number.isFinite(maxRows) ? { maxRows } : {},
377
+ userContext: (0, import_ElasticReportService.extractServerUserContext)(ctx)
378
+ });
379
+ ctx.withoutDataWrapping = true;
380
+ ctx.status = 200;
381
+ ctx.type = contentType;
382
+ ctx.set("Content-Disposition", `attachment; filename="${filename}"`);
383
+ ctx.body = stream;
384
+ } catch (error) {
385
+ const status = (error == null ? void 0 : error.status) ?? 400;
386
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
387
+ }
388
+ await next();
389
+ },
260
390
  getMcpInfo: async (ctx, next) => {
261
391
  ctx.body = {
262
392
  serverName: import_constants.MCP_SERVER_NAME,
@@ -284,7 +414,11 @@ class PluginElasticReportServer extends import_server.Plugin {
284
414
  });
285
415
  }
286
416
  registerAclRules() {
287
- this.app.acl.allow(import_constants.SERVICE_RESOURCE, ["listPublishedReports", "getReportMeta", "runReport"], "loggedIn");
417
+ this.app.acl.allow(
418
+ import_constants.SERVICE_RESOURCE,
419
+ ["listPublishedReports", "getReportMeta", "runReport", "inspectTopValues", "exportReport"],
420
+ "loggedIn"
421
+ );
288
422
  this.app.acl.allow(import_constants.MCP_RESOURCE_NAME, "*", "loggedIn");
289
423
  this.app.acl.registerSnippet({
290
424
  name: import_constants.ACL_SNIPPET,