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
@@ -27,10 +27,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
27
27
  var ElasticReportService_exports = {};
28
28
  __export(ElasticReportService_exports, {
29
29
  ElasticReportService: () => ElasticReportService,
30
- extractCurrentUserId: () => extractCurrentUserId
30
+ extractCurrentUserId: () => extractCurrentUserId,
31
+ extractServerUserContext: () => extractServerUserContext
31
32
  });
32
33
  module.exports = __toCommonJS(ElasticReportService_exports);
33
34
  var import_constants = require("../../shared/constants");
35
+ var import_acl_guard = require("../acl-guard");
34
36
  var import_ReportQueryCompiler = require("./ReportQueryCompiler");
35
37
  function isRecord(value) {
36
38
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -51,6 +53,7 @@ function serializeDataView(row) {
51
53
  indexPattern: typeof plain.indexPattern === "string" ? plain.indexPattern : "",
52
54
  timeField: typeof plain.timeField === "string" && plain.timeField.trim() ? plain.timeField.trim() : null,
53
55
  description: typeof plain.description === "string" ? plain.description : null,
56
+ allowedRoles: (0, import_acl_guard.normalizeRoleList)(plain.allowedRoles),
54
57
  cachedFields: Array.isArray(plain.cachedFields) ? plain.cachedFields : null,
55
58
  ...typeof plain.createdAt === "string" ? { createdAt: plain.createdAt } : {},
56
59
  ...typeof plain.updatedAt === "string" ? { updatedAt: plain.updatedAt } : {}
@@ -68,6 +71,7 @@ function serializeReport(row) {
68
71
  visualization: spec.visualization,
69
72
  spec,
70
73
  published: plain.published !== false,
74
+ allowedRoles: (0, import_acl_guard.normalizeRoleList)(plain.allowedRoles),
71
75
  ...typeof plain.createdAt === "string" ? { createdAt: plain.createdAt } : {},
72
76
  ...typeof plain.updatedAt === "string" ? { updatedAt: plain.updatedAt } : {}
73
77
  };
@@ -80,6 +84,25 @@ class ElasticReportService {
80
84
  async listConnections() {
81
85
  return this.connections.listConnections();
82
86
  }
87
+ async testConnection(dataSourceKey, indexPattern = "*") {
88
+ const client = await this.connections.getClient(dataSourceKey);
89
+ return client.testConnection(indexPattern);
90
+ }
91
+ async listAvailableRoles() {
92
+ if (!this.app.db.hasCollection("roles")) {
93
+ return [];
94
+ }
95
+ const rows = await this.app.db.getRepository("roles").find({
96
+ sort: ["name"]
97
+ });
98
+ return rows.map((row) => {
99
+ const plain = toPlainObject(row);
100
+ const name = typeof plain.name === "string" ? plain.name.trim() : "";
101
+ const rawTitle = typeof plain.title === "string" && plain.title.trim() ? plain.title.trim() : name;
102
+ const title = rawTitle.replace(/^\{\{\s*t\(\s*['"](.+?)['"]\s*\)\s*\}\}$/, "$1");
103
+ return { name, title };
104
+ }).filter((r) => Boolean(r.name) && r.name !== "anonymous");
105
+ }
83
106
  async listIndices(dataSourceKey, indexPattern = "*") {
84
107
  const client = await this.connections.getClient(dataSourceKey);
85
108
  return client.readIndices(indexPattern);
@@ -138,7 +161,8 @@ class ElasticReportService {
138
161
  indexPattern,
139
162
  timeField,
140
163
  description: input.description ?? null,
141
- cachedFields: fields
164
+ cachedFields: fields,
165
+ ...input.allowedRoles !== void 0 ? { allowedRoles: (0, import_acl_guard.normalizeRoleList)(input.allowedRoles) } : {}
142
166
  };
143
167
  if (input.id !== void 0 && input.id !== null && String(input.id).trim() !== "") {
144
168
  await repo.update({
@@ -147,6 +171,9 @@ class ElasticReportService {
147
171
  });
148
172
  return this.getDataView(input.id);
149
173
  }
174
+ if (values.allowedRoles === void 0) {
175
+ values.allowedRoles = [];
176
+ }
150
177
  if (userId !== void 0) {
151
178
  values.createdById = userId;
152
179
  }
@@ -189,6 +216,9 @@ class ElasticReportService {
189
216
  }
190
217
  const dataView = await this.getDataView(input.dataViewId);
191
218
  const spec = (0, import_ReportQueryCompiler.normalizeReportSpec)(input.spec);
219
+ if (spec.queryMode !== "simple" && spec.query && spec.query.trim()) {
220
+ (0, import_ReportQueryCompiler.compileKqlToQueryDsl)(spec.query);
221
+ }
192
222
  const repo = this.app.db.getRepository(import_constants.REPORTS_COLLECTION);
193
223
  const values = {
194
224
  title,
@@ -197,6 +227,7 @@ class ElasticReportService {
197
227
  visualization: spec.visualization,
198
228
  spec,
199
229
  published: input.published !== false,
230
+ ...input.allowedRoles !== void 0 ? { allowedRoles: (0, import_acl_guard.normalizeRoleList)(input.allowedRoles) } : {},
200
231
  ...userId !== void 0 ? { updatedById: userId } : {}
201
232
  };
202
233
  if (input.id !== void 0 && input.id !== null && String(input.id).trim() !== "") {
@@ -206,6 +237,9 @@ class ElasticReportService {
206
237
  });
207
238
  return this.getReport(input.id);
208
239
  }
240
+ if (values.allowedRoles === void 0) {
241
+ values.allowedRoles = [];
242
+ }
209
243
  if (userId !== void 0) {
210
244
  values.createdById = userId;
211
245
  }
@@ -214,39 +248,107 @@ class ElasticReportService {
214
248
  return this.getReport(plain.id);
215
249
  }
216
250
  async previewReport(params) {
251
+ var _a, _b, _c, _d, _e;
217
252
  const { dataView, fields } = await this.inspectDataViewFields(params.dataViewId, false);
218
253
  const normalizedSpec = (0, import_ReportQueryCompiler.normalizeReportSpec)(params.spec);
254
+ const client = await this.connections.getClient(dataView.dataSourceKey);
255
+ let activePitId = (_a = params.overrides) == null ? void 0 : _a.pitId;
256
+ const needsDeepCursor = normalizedSpec.visualization === "table" && !activePitId && ((((_b = params.overrides) == null ? void 0 : _b.page) ?? 1) * (((_c = params.overrides) == null ? void 0 : _c.pageSize) ?? normalizedSpec.pageSize ?? 20) > 1e4 || Boolean((_d = params.overrides) == null ? void 0 : _d.searchAfter));
257
+ if (needsDeepCursor && !((_e = params.overrides) == null ? void 0 : _e.searchAfter)) {
258
+ activePitId = await client.openPit(dataView.indexPattern, "1m") ?? void 0;
259
+ }
219
260
  const { body, effectiveSpec } = (0, import_ReportQueryCompiler.compileSearchRequest)({
220
261
  spec: normalizedSpec,
221
262
  overrides: params.overrides,
222
263
  timeField: dataView.timeField,
223
264
  fields,
224
- maxRowsCap: params.forMcp ? import_constants.MAX_MCP_PREVIEW_SIZE : import_constants.MAX_UI_PAGE_SIZE
265
+ maxRowsCap: params.forMcp ? import_constants.MAX_MCP_PREVIEW_SIZE : import_constants.MAX_UI_PAGE_SIZE,
266
+ userContext: params.userContext,
267
+ usePit: Boolean(activePitId)
225
268
  });
226
- const client = await this.connections.getClient(dataView.dataSourceKey);
227
- const rawSearch = await client.search(dataView.indexPattern, body);
269
+ const rawSearch = await client.search(
270
+ dataView.indexPattern,
271
+ body,
272
+ activePitId ? { pitId: activePitId } : void 0
273
+ );
228
274
  const result = (0, import_ReportQueryCompiler.parseSearchResponse)(rawSearch, body, effectiveSpec, dataView.timeField);
275
+ if (activePitId && !result.pitId) {
276
+ result.pitId = activePitId;
277
+ }
229
278
  return { dataView, result };
230
279
  }
231
280
  async runSavedReport(params) {
232
- var _a, _b, _c;
281
+ var _a, _b, _c, _d, _e, _f, _g;
233
282
  const report = await this.getReport(params.reportId);
234
283
  if (params.requirePublished && !report.published) {
235
284
  throw new Error(`Report "${report.title}" is not published`);
236
285
  }
237
286
  const runtimeOverrides = report.spec.allowInteractiveControls === false ? {
238
- page: (_a = params.overrides) == null ? void 0 : _a.page,
239
- pageSize: (_b = params.overrides) == null ? void 0 : _b.pageSize,
240
- searchAfter: (_c = params.overrides) == null ? void 0 : _c.searchAfter
287
+ contextFilters: (_a = params.overrides) == null ? void 0 : _a.contextFilters,
288
+ sharedFilters: (_b = params.overrides) == null ? void 0 : _b.sharedFilters,
289
+ timeZone: (_c = params.overrides) == null ? void 0 : _c.timeZone,
290
+ page: (_d = params.overrides) == null ? void 0 : _d.page,
291
+ pageSize: (_e = params.overrides) == null ? void 0 : _e.pageSize,
292
+ searchAfter: (_f = params.overrides) == null ? void 0 : _f.searchAfter,
293
+ pitId: (_g = params.overrides) == null ? void 0 : _g.pitId
241
294
  } : params.overrides;
242
295
  const { dataView, result } = await this.previewReport({
243
296
  dataViewId: report.dataViewId,
244
297
  spec: report.spec,
245
298
  overrides: runtimeOverrides,
246
- forMcp: params.forMcp
299
+ forMcp: params.forMcp,
300
+ userContext: params.userContext
247
301
  });
248
302
  return { report, dataView, result };
249
303
  }
304
+ async inspectFieldTopValues(params) {
305
+ const rawField = params.field.trim();
306
+ if (!rawField) {
307
+ throw new Error("field is required");
308
+ }
309
+ let baseSpec = (0, import_ReportQueryCompiler.normalizeReportSpec)({ visualization: "bar" });
310
+ let targetDataViewId = params.dataViewId;
311
+ if (params.reportId !== void 0 && params.reportId !== null && String(params.reportId).trim() !== "") {
312
+ const report = await this.getReport(params.reportId);
313
+ targetDataViewId = report.dataViewId;
314
+ baseSpec = report.spec;
315
+ }
316
+ const { dataView, fields } = await this.inspectDataViewFields(targetDataViewId, false);
317
+ const fieldMap = (0, import_ReportQueryCompiler.buildFieldCapabilityMap)(fields);
318
+ const resolvedField = (0, import_ReportQueryCompiler.resolveAggregatableField)(rawField, fieldMap);
319
+ const topSize = Math.max(1, Math.min(25, Math.trunc(params.size ?? 10)));
320
+ const probeSpec = (0, import_ReportQueryCompiler.normalizeReportSpec)({
321
+ ...baseSpec,
322
+ visualization: "bar",
323
+ chart: {
324
+ bucketType: "terms",
325
+ bucketField: resolvedField,
326
+ topN: topSize,
327
+ metricType: "count"
328
+ }
329
+ });
330
+ const { body, effectiveSpec } = (0, import_ReportQueryCompiler.compileSearchRequest)({
331
+ spec: probeSpec,
332
+ overrides: params.overrides,
333
+ timeField: dataView.timeField,
334
+ fields,
335
+ userContext: params.userContext
336
+ });
337
+ const client = await this.connections.getClient(dataView.dataSourceKey);
338
+ const rawSearch = await client.search(dataView.indexPattern, body);
339
+ const parsed = (0, import_ReportQueryCompiler.parseSearchResponse)(rawSearch, body, effectiveSpec, dataView.timeField);
340
+ const totalDocs = parsed.total;
341
+ return {
342
+ field: rawField,
343
+ resolvedField,
344
+ totalDocs,
345
+ buckets: parsed.series.map((pt) => ({
346
+ value: pt.label,
347
+ count: pt.count,
348
+ percentage: totalDocs > 0 ? Number((pt.count / totalDocs * 100).toFixed(1)) : 0
349
+ }))
350
+ };
351
+ }
250
352
  }
251
353
  function extractCurrentUserId(ctx) {
252
354
  var _a, _b, _c, _d;
@@ -256,8 +358,20 @@ function extractCurrentUserId(ctx) {
256
358
  if (authUser !== void 0 && authUser !== null) return authUser;
257
359
  return void 0;
258
360
  }
361
+ function extractServerUserContext(ctx) {
362
+ var _a;
363
+ const stateUser = (_a = ctx == null ? void 0 : ctx.state) == null ? void 0 : _a.currentUser;
364
+ const effectiveRole = (0, import_acl_guard.getEffectiveRoles)(ctx)[0];
365
+ return {
366
+ userId: extractCurrentUserId(ctx),
367
+ ...typeof (stateUser == null ? void 0 : stateUser.username) === "string" ? { username: stateUser.username } : {},
368
+ ...typeof (stateUser == null ? void 0 : stateUser.email) === "string" ? { email: stateUser.email } : {},
369
+ ...effectiveRole ? { role: effectiveRole } : {}
370
+ };
371
+ }
259
372
  // Annotate the CommonJS export names for ESM import in node:
260
373
  0 && (module.exports = {
261
374
  ElasticReportService,
262
- extractCurrentUserId
375
+ extractCurrentUserId,
376
+ extractServerUserContext
263
377
  });
@@ -27,6 +27,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
27
27
  var ElasticsearchConnectionService_exports = {};
28
28
  __export(ElasticsearchConnectionService_exports, {
29
29
  ElasticsearchConnectionService: () => ElasticsearchConnectionService,
30
+ buildEsClientOptions: () => buildEsClientOptions,
31
+ inferConnectionModes: () => inferConnectionModes,
30
32
  normalizeFieldCapabilitiesResponse: () => normalizeFieldCapabilitiesResponse
31
33
  });
32
34
  module.exports = __toCommonJS(ElasticsearchConnectionService_exports);
@@ -34,6 +36,9 @@ var import_elasticsearch = require("@elastic/elasticsearch");
34
36
  function isRecord(value) {
35
37
  return typeof value === "object" && value !== null && !Array.isArray(value);
36
38
  }
39
+ function toNonEmptyString(value) {
40
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
41
+ }
37
42
  function isRawEsClientLike(value) {
38
43
  return isRecord(value) && typeof value.search === "function";
39
44
  }
@@ -44,28 +49,115 @@ function normaliseApiKey(raw) {
44
49
  }
45
50
  return trimmed;
46
51
  }
52
+ function normalizeCaFingerprint(raw) {
53
+ const cleaned = raw.replace(/[\s:]/g, "").toLowerCase();
54
+ if (!/^[0-9a-f]{64}$/.test(cleaned)) {
55
+ throw new Error("Invalid CA SHA-256 fingerprint: expected 64 hexadecimal characters");
56
+ }
57
+ return cleaned;
58
+ }
59
+ function inferConnectionModes(opts) {
60
+ const endpointMode = opts.endpointMode === "cloud" || opts.endpointMode === "nodes" ? opts.endpointMode : toNonEmptyString(opts.cloudId) ? "cloud" : "nodes";
61
+ let authMode = "none";
62
+ if (opts.authMode === "none" || opts.authMode === "basic" || opts.authMode === "apiKey" || opts.authMode === "bearer") {
63
+ authMode = opts.authMode;
64
+ } else if (opts.hasBearerToken === true || toNonEmptyString(opts.bearerToken)) {
65
+ authMode = "bearer";
66
+ } else if (opts.hasApiKey === true || toNonEmptyString(opts.apiKey)) {
67
+ authMode = "apiKey";
68
+ } else if (toNonEmptyString(opts.username)) {
69
+ authMode = "basic";
70
+ }
71
+ let tlsMode = "verify";
72
+ if (opts.tlsMode === "verify" || opts.tlsMode === "caFingerprint" || opts.tlsMode === "caCert" || opts.tlsMode === "skip") {
73
+ tlsMode = opts.tlsMode;
74
+ } else if (toNonEmptyString(opts.caFingerprint)) {
75
+ tlsMode = "caFingerprint";
76
+ } else if (opts.hasCaCert === true || toNonEmptyString(opts.caCert)) {
77
+ tlsMode = "caCert";
78
+ } else if (opts.rejectUnauthorized === false) {
79
+ tlsMode = "skip";
80
+ }
81
+ return { endpointMode, authMode, tlsMode };
82
+ }
47
83
  function extractConnectionOptions(raw) {
48
84
  if (!isRecord(raw)) return {};
49
- if (typeof raw.nodes === "string") return raw;
85
+ if (typeof raw.nodes === "string" || typeof raw.cloudId === "string" || typeof raw.endpointMode === "string") {
86
+ return raw;
87
+ }
50
88
  if (isRecord(raw.options)) return raw.options;
51
89
  return raw;
52
90
  }
53
91
  function buildEsClientOptions(opts) {
54
- const nodes = (opts.nodes || "http://localhost:9200").split(",").map((item) => item.trim()).filter(Boolean);
92
+ const { endpointMode, authMode, tlsMode } = inferConnectionModes(opts);
93
+ const timeoutMs = typeof opts.requestTimeoutMs === "number" && Number.isFinite(opts.requestTimeoutMs) && opts.requestTimeoutMs >= 1e3 ? Math.min(3e5, Math.trunc(opts.requestTimeoutMs)) : 3e4;
55
94
  const clientOpts = {
56
- nodes,
57
- requestTimeout: 2e4
95
+ requestTimeout: timeoutMs
58
96
  };
59
- if (opts.apiKey) {
60
- clientOpts.auth = { apiKey: normaliseApiKey(opts.apiKey) };
61
- } else if (opts.username) {
62
- clientOpts.auth = {
63
- username: opts.username,
64
- password: opts.password || ""
97
+ if (endpointMode === "cloud") {
98
+ const cloudId = toNonEmptyString(opts.cloudId);
99
+ if (!cloudId) {
100
+ throw new Error("Elasticsearch data source has no configured Cloud ID");
101
+ }
102
+ clientOpts.cloud = { id: cloudId };
103
+ } else {
104
+ const nodes = (opts.nodes || "http://localhost:9200").split(",").map((item) => item.trim()).filter(Boolean);
105
+ clientOpts.nodes = nodes;
106
+ }
107
+ if (authMode === "bearer") {
108
+ const bearer = toNonEmptyString(opts.bearerToken);
109
+ if (bearer) {
110
+ clientOpts.auth = { bearer };
111
+ }
112
+ } else if (authMode === "apiKey") {
113
+ const apiKey = toNonEmptyString(opts.apiKey);
114
+ if (apiKey) {
115
+ clientOpts.auth = { apiKey: normaliseApiKey(apiKey) };
116
+ }
117
+ } else if (authMode === "basic") {
118
+ const username = toNonEmptyString(opts.username);
119
+ if (username) {
120
+ clientOpts.auth = {
121
+ username,
122
+ password: opts.password || ""
123
+ };
124
+ }
125
+ }
126
+ const servername = toNonEmptyString(opts.tlsServerName);
127
+ if (tlsMode === "caFingerprint") {
128
+ const fp = toNonEmptyString(opts.caFingerprint);
129
+ if (fp) {
130
+ clientOpts.caFingerprint = normalizeCaFingerprint(fp);
131
+ clientOpts.tls = {
132
+ rejectUnauthorized: false,
133
+ ...servername ? { servername } : {}
134
+ };
135
+ } else if (servername) {
136
+ clientOpts.tls = { servername };
137
+ }
138
+ } else if (tlsMode === "caCert") {
139
+ const ca = toNonEmptyString(opts.caCert);
140
+ clientOpts.tls = {
141
+ ...ca ? { ca } : {},
142
+ rejectUnauthorized: true,
143
+ ...servername ? { servername } : {}
144
+ };
145
+ } else if (tlsMode === "skip") {
146
+ clientOpts.tls = {
147
+ rejectUnauthorized: false,
148
+ ...servername ? { servername } : {}
65
149
  };
150
+ } else if (servername) {
151
+ clientOpts.tls = {
152
+ rejectUnauthorized: true,
153
+ servername
154
+ };
155
+ }
156
+ if (typeof opts.maxRetries === "number" && Number.isFinite(opts.maxRetries) && opts.maxRetries >= 0) {
157
+ clientOpts.maxRetries = Math.min(10, Math.trunc(opts.maxRetries));
66
158
  }
67
- if (opts.rejectUnauthorized === false) {
68
- clientOpts.tls = { rejectUnauthorized: false };
159
+ if (opts.compression === true) {
160
+ clientOpts.compression = true;
69
161
  }
70
162
  return clientOpts;
71
163
  }
@@ -175,22 +267,109 @@ function linkKeywordSubfields(map) {
175
267
  }
176
268
  return Array.from(map.values()).sort((a, b) => a.name.localeCompare(b.name));
177
269
  }
270
+ function collectResolvedIndexNames(rawResolve, out) {
271
+ const unwrapped = isRecord(rawResolve) && isRecord(rawResolve.body) ? rawResolve.body : rawResolve;
272
+ if (!isRecord(unwrapped)) return;
273
+ for (const bucketKey of ["indices", "data_streams", "aliases"]) {
274
+ const arr = unwrapped[bucketKey];
275
+ if (!Array.isArray(arr)) continue;
276
+ for (const entry of arr) {
277
+ if (!isRecord(entry) || entry.open === false) continue;
278
+ const name = toNonEmptyString(entry.name);
279
+ if (name && !name.startsWith(".")) {
280
+ out.add(name);
281
+ }
282
+ }
283
+ }
284
+ }
178
285
  function wrapEsClient(rawClient) {
179
286
  return {
180
- async readIndices(indexPattern = "*") {
287
+ async testConnection(indexPattern = "*") {
181
288
  var _a;
182
- const safePattern = indexPattern.trim() || "*";
183
- if (!((_a = rawClient.cat) == null ? void 0 : _a.indices)) {
184
- return [];
289
+ const safePattern = assertSafeIndexPattern(indexPattern || "*");
290
+ if (typeof rawClient.info === "function") {
291
+ try {
292
+ const rawInfo = await rawClient.info();
293
+ const info = isRecord(rawInfo) && isRecord(rawInfo.body) ? rawInfo.body : rawInfo;
294
+ const clusterName = isRecord(info) ? toNonEmptyString(info.cluster_name) : void 0;
295
+ const versionObj = isRecord(info) && isRecord(info.version) ? info.version : void 0;
296
+ const version = versionObj ? toNonEmptyString(versionObj.number) : void 0;
297
+ if (clusterName || version) {
298
+ return {
299
+ ok: true,
300
+ ...clusterName ? { clusterName } : {},
301
+ ...version ? { version } : {}
302
+ };
303
+ }
304
+ } catch (err) {
305
+ const statusCode = isRecord(err) && typeof err.statusCode === "number" ? err.statusCode : void 0;
306
+ if (statusCode === 403 && rawClient.fieldCaps) {
307
+ await rawClient.fieldCaps({ index: safePattern, fields: "@timestamp" });
308
+ return { ok: true, limitedPrivileges: true };
309
+ }
310
+ throw err;
311
+ }
185
312
  }
186
- const response = await rawClient.cat.indices({
187
- index: safePattern,
188
- format: "json",
189
- h: "index"
190
- });
191
- const unwrapped = isRecord(response) && Array.isArray(response.body) ? response.body : response;
192
- if (!Array.isArray(unwrapped)) return [];
193
- return unwrapped.map((row) => isRecord(row) && typeof row.index === "string" ? row.index.trim() : "").filter((idx) => Boolean(idx) && !idx.startsWith(".")).sort((a, b) => a.localeCompare(b));
313
+ if (typeof ((_a = rawClient.cluster) == null ? void 0 : _a.health) === "function") {
314
+ try {
315
+ const rawHealth = await rawClient.cluster.health();
316
+ const health = isRecord(rawHealth) && isRecord(rawHealth.body) ? rawHealth.body : rawHealth;
317
+ const clusterName = isRecord(health) ? toNonEmptyString(health.cluster_name) : void 0;
318
+ if (clusterName) {
319
+ return { ok: true, clusterName };
320
+ }
321
+ } catch (err) {
322
+ const statusCode = isRecord(err) && typeof err.statusCode === "number" ? err.statusCode : void 0;
323
+ if (statusCode === 403 && rawClient.fieldCaps) {
324
+ await rawClient.fieldCaps({ index: safePattern, fields: "@timestamp" });
325
+ return { ok: true, limitedPrivileges: true };
326
+ }
327
+ throw err;
328
+ }
329
+ }
330
+ if (typeof rawClient.ping === "function") {
331
+ const pong = await rawClient.ping();
332
+ if (pong) {
333
+ return { ok: true };
334
+ }
335
+ }
336
+ if (rawClient.fieldCaps) {
337
+ await rawClient.fieldCaps({ index: safePattern, fields: "@timestamp" });
338
+ return { ok: true };
339
+ }
340
+ return { ok: true };
341
+ },
342
+ async readIndices(indexPattern = "*") {
343
+ var _a, _b, _c, _d;
344
+ const safePattern = assertSafeIndexPattern(indexPattern || "*");
345
+ const names = /* @__PURE__ */ new Set();
346
+ const resolvePromise = typeof ((_a = rawClient.indices) == null ? void 0 : _a.resolveIndex) === "function" ? rawClient.indices.resolveIndex({ name: safePattern }) : Promise.resolve(null);
347
+ const catPromise = typeof ((_b = rawClient.cat) == null ? void 0 : _b.indices) === "function" ? rawClient.cat.indices({ index: safePattern, format: "json", h: "index" }) : Promise.resolve(null);
348
+ const [resolveOutcome, catOutcome] = await Promise.allSettled([resolvePromise, catPromise]);
349
+ if (resolveOutcome.status === "fulfilled" && resolveOutcome.value) {
350
+ collectResolvedIndexNames(resolveOutcome.value, names);
351
+ }
352
+ if (catOutcome.status === "fulfilled" && catOutcome.value) {
353
+ const unwrapped = isRecord(catOutcome.value) && Array.isArray(catOutcome.value.body) ? catOutcome.value.body : catOutcome.value;
354
+ if (Array.isArray(unwrapped)) {
355
+ for (const row of unwrapped) {
356
+ const idx = isRecord(row) ? toNonEmptyString(row.index) : void 0;
357
+ if (idx && !idx.startsWith(".")) {
358
+ names.add(idx);
359
+ }
360
+ }
361
+ }
362
+ }
363
+ if (resolveOutcome.status === "rejected" && (catOutcome.status === "rejected" || typeof ((_c = rawClient.cat) == null ? void 0 : _c.indices) !== "function")) {
364
+ throw resolveOutcome.reason;
365
+ }
366
+ if (catOutcome.status === "rejected" && typeof ((_d = rawClient.indices) == null ? void 0 : _d.resolveIndex) !== "function") {
367
+ throw catOutcome.reason;
368
+ }
369
+ if (resolveOutcome.status === "rejected" && catOutcome.status === "rejected") {
370
+ throw catOutcome.reason || resolveOutcome.reason;
371
+ }
372
+ return Array.from(names).sort((a, b) => a.localeCompare(b));
194
373
  },
195
374
  async inspectFields(indexPattern) {
196
375
  var _a;
@@ -224,7 +403,42 @@ function wrapEsClient(rawClient) {
224
403
  }
225
404
  return [];
226
405
  },
227
- async search(indexPattern, body) {
406
+ async openPit(indexPattern, keepAlive = "1m") {
407
+ const safePattern = assertSafeIndexPattern(indexPattern);
408
+ if (typeof rawClient.openPointInTime !== "function") {
409
+ return null;
410
+ }
411
+ try {
412
+ const raw = await rawClient.openPointInTime({
413
+ index: safePattern,
414
+ keep_alive: keepAlive
415
+ });
416
+ const unwrapped = isRecord(raw) && isRecord(raw.body) ? raw.body : raw;
417
+ return isRecord(unwrapped) && typeof unwrapped.id === "string" && unwrapped.id ? unwrapped.id : null;
418
+ } catch {
419
+ return null;
420
+ }
421
+ },
422
+ async closePit(pitId) {
423
+ if (!pitId || typeof rawClient.closePointInTime !== "function") {
424
+ return;
425
+ }
426
+ try {
427
+ await rawClient.closePointInTime({ id: pitId });
428
+ } catch {
429
+ }
430
+ },
431
+ async search(indexPattern, body, options) {
432
+ if (options == null ? void 0 : options.pitId) {
433
+ const response2 = await rawClient.search({
434
+ ...body,
435
+ pit: {
436
+ id: options.pitId,
437
+ keep_alive: options.keepAlive ?? "1m"
438
+ }
439
+ });
440
+ return isRecord(response2) && isRecord(response2.body) ? response2.body : response2;
441
+ }
228
442
  const safePattern = assertSafeIndexPattern(indexPattern);
229
443
  const response = await rawClient.search({
230
444
  index: safePattern,
@@ -240,13 +454,13 @@ class ElasticsearchConnectionService {
240
454
  }
241
455
  fallbackClients = /* @__PURE__ */ new Map();
242
456
  async close() {
243
- const clients = Array.from(this.fallbackClients.values());
457
+ const entries = Array.from(this.fallbackClients.values());
244
458
  this.fallbackClients.clear();
245
- await Promise.allSettled(clients.map((client) => client.close()));
459
+ await Promise.allSettled(entries.map((entry) => entry.client.close()));
246
460
  }
247
461
  /**
248
462
  * Discover all Elasticsearch data sources configured via `plugin-data-source-elasticsearch`
249
- * without leaking sensitive credentials (`password`, `apiKey`).
463
+ * without leaking sensitive credentials (`password`, `apiKey`, `bearerToken`, `caCert`).
250
464
  */
251
465
  async listConnections() {
252
466
  var _a;
@@ -260,10 +474,15 @@ class ElasticsearchConnectionService {
260
474
  const opts = extractConnectionOptions(pubOpts ?? ds.options);
261
475
  const isEs = isRawEsClientLike(cm == null ? void 0 : cm.esClient) || ((_a = ds.constructor) == null ? void 0 : _a.name) === "ElasticsearchDataSource";
262
476
  if (!isEs) continue;
477
+ const modes = inferConnectionModes(opts);
263
478
  byKey.set(key, {
264
479
  key,
265
480
  displayName: typeof ds.displayName === "string" && ds.displayName ? ds.displayName : key,
266
481
  status: "loaded",
482
+ endpointMode: modes.endpointMode,
483
+ authMode: modes.authMode,
484
+ tlsMode: modes.tlsMode,
485
+ cloudConfigured: modes.endpointMode === "cloud",
267
486
  ...typeof opts.indexPattern === "string" ? { indexPattern: opts.indexPattern } : {},
268
487
  ...typeof opts.nodes === "string" ? { nodes: opts.nodes } : {}
269
488
  });
@@ -280,11 +499,16 @@ class ElasticsearchConnectionService {
280
499
  if (!isRecord(plain) || typeof plain.key !== "string" || !plain.key.trim()) continue;
281
500
  const key = plain.key.trim();
282
501
  const opts = extractConnectionOptions(plain.options);
502
+ const modes = inferConnectionModes(opts);
283
503
  const existing = byKey.get(key);
284
504
  byKey.set(key, {
285
505
  key,
286
506
  displayName: typeof plain.displayName === "string" && plain.displayName.trim() ? plain.displayName.trim() : (existing == null ? void 0 : existing.displayName) ?? key,
287
507
  status: typeof plain.status === "string" ? plain.status : (existing == null ? void 0 : existing.status) ?? "configured",
508
+ endpointMode: modes.endpointMode,
509
+ authMode: modes.authMode,
510
+ tlsMode: modes.tlsMode,
511
+ cloudConfigured: modes.endpointMode === "cloud",
288
512
  ...typeof opts.indexPattern === "string" ? { indexPattern: opts.indexPattern } : (existing == null ? void 0 : existing.indexPattern) ? { indexPattern: existing.indexPattern } : {},
289
513
  ...typeof opts.nodes === "string" ? { nodes: opts.nodes } : (existing == null ? void 0 : existing.nodes) ? { nodes: existing.nodes } : {}
290
514
  });
@@ -304,29 +528,45 @@ class ElasticsearchConnectionService {
304
528
  if (isRecord(liveDs) && isRecord(liveDs.collectionManager) && isRawEsClientLike(liveDs.collectionManager.esClient)) {
305
529
  return wrapEsClient(liveDs.collectionManager.esClient);
306
530
  }
307
- const cached = this.fallbackClients.get(cleanKey);
308
- if (cached) {
309
- return wrapEsClient(cached);
310
- }
311
531
  const repo = this.app.db.getRepository("dataSources");
312
532
  const record = repo ? await repo.findOne({
313
533
  filter: { key: cleanKey, type: "elasticsearch" }
314
534
  }) : null;
315
535
  if (!record) {
536
+ const existingCached = this.fallbackClients.get(cleanKey);
537
+ if (existingCached) {
538
+ return wrapEsClient(existingCached.client);
539
+ }
316
540
  throw new Error(`Elasticsearch data source "${cleanKey}" was not found or is not loaded`);
317
541
  }
318
542
  const plain = typeof record.toJSON === "function" ? record.toJSON() : record;
319
543
  const opts = extractConnectionOptions(isRecord(plain) ? plain.options : void 0);
320
- if (!opts.nodes) {
544
+ const { endpointMode } = inferConnectionModes(opts);
545
+ if (endpointMode === "cloud") {
546
+ if (!toNonEmptyString(opts.cloudId)) {
547
+ throw new Error(`Elasticsearch data source "${cleanKey}" has no configured Cloud ID`);
548
+ }
549
+ } else if (!toNonEmptyString(opts.nodes)) {
321
550
  throw new Error(`Elasticsearch data source "${cleanKey}" has no configured nodes`);
322
551
  }
552
+ const signature = JSON.stringify(opts);
553
+ const cached = this.fallbackClients.get(cleanKey);
554
+ if (cached && cached.signature === signature) {
555
+ return wrapEsClient(cached.client);
556
+ }
557
+ if (cached) {
558
+ await cached.client.close().catch(() => void 0);
559
+ this.fallbackClients.delete(cleanKey);
560
+ }
323
561
  const client = new import_elasticsearch.Client(buildEsClientOptions(opts));
324
- this.fallbackClients.set(cleanKey, client);
562
+ this.fallbackClients.set(cleanKey, { signature, client });
325
563
  return wrapEsClient(client);
326
564
  }
327
565
  }
328
566
  // Annotate the CommonJS export names for ESM import in node:
329
567
  0 && (module.exports = {
330
568
  ElasticsearchConnectionService,
569
+ buildEsClientOptions,
570
+ inferConnectionModes,
331
571
  normalizeFieldCapabilitiesResponse
332
572
  });