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.
- package/ai/skills/elastic-report/SKILLS.md +5 -3
- package/dist/client/357.0dd385384cab5dbf.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/851.142c93fc6d666b28.js +10 -0
- package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
- package/dist/client-v2/877.f4095a3dbcadf98f.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +3 -2
- package/dist/locale/en-US.json +100 -1
- package/dist/locale/vi-VN.json +100 -1
- package/dist/locale/zh-CN.json +100 -1
- package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
- package/dist/server/acl-guard.js +97 -25
- package/dist/server/collections/es-report-data-views.js +6 -0
- package/dist/server/collections/es-reports.js +6 -0
- package/dist/server/mcp/ElasticReportToolCatalog.js +232 -10
- package/dist/server/plugin.js +153 -19
- package/dist/server/services/ElasticReportService.js +125 -11
- package/dist/server/services/ElasticsearchConnectionService.js +274 -34
- package/dist/server/services/ReportExportService.js +243 -0
- package/dist/server/services/ReportQueryCompiler.js +532 -91
- package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
- package/dist/shared/constants.js +17 -2
- package/package.json +3 -2
- package/src/client/index.tsx +16 -1
- package/src/client/workflow-instructions.tsx +44 -0
- package/src/client-v2/__tests__/elastic-report.test.tsx +519 -39
- package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
- package/src/client-v2/api.ts +96 -0
- package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
- package/src/client-v2/components/ElasticBasicCharts.tsx +345 -92
- package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
- package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
- package/src/client-v2/components/ElasticReportBlock.tsx +157 -11
- package/src/client-v2/components/ElasticReportRenderer.tsx +621 -71
- package/src/client-v2/components/ReportSelect.tsx +39 -26
- package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
- package/src/client-v2/models/ElasticReportBlockModel.tsx +36 -3
- package/src/client-v2/pages/ElasticReportManager.tsx +432 -26
- package/src/client-v2/plugin.tsx +20 -0
- package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
- package/src/client-v2/workflow/instructions.tsx +149 -0
- package/src/locale/en-US.json +100 -1
- package/src/locale/vi-VN.json +100 -1
- package/src/locale/zh-CN.json +100 -1
- package/src/server/__tests__/query-compiler.test.ts +390 -1
- package/src/server/__tests__/report-mcp-acl.integration.test.ts +271 -3
- package/src/server/acl-guard.ts +119 -28
- package/src/server/collections/es-report-data-views.ts +6 -0
- package/src/server/collections/es-reports.ts +6 -0
- package/src/server/mcp/ElasticReportToolCatalog.ts +255 -9
- package/src/server/plugin.ts +189 -21
- package/src/server/services/ElasticReportService.ts +165 -5
- package/src/server/services/ElasticsearchConnectionService.ts +375 -48
- package/src/server/services/ReportExportService.ts +282 -0
- package/src/server/services/ReportQueryCompiler.ts +629 -94
- package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
- package/src/shared/constants.ts +7 -0
- package/src/shared/types.ts +98 -1
- package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
|
@@ -26,9 +26,11 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
26
26
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
27
27
|
var ReportQueryCompiler_exports = {};
|
|
28
28
|
__export(ReportQueryCompiler_exports, {
|
|
29
|
+
KqlSyntaxError: () => KqlSyntaxError,
|
|
29
30
|
buildFieldCapabilityMap: () => buildFieldCapabilityMap,
|
|
30
31
|
compileFilterItem: () => compileFilterItem,
|
|
31
32
|
compileKqlToQueryDsl: () => compileKqlToQueryDsl,
|
|
33
|
+
compilePreviousTimeRange: () => compilePreviousTimeRange,
|
|
32
34
|
compileSearchRequest: () => compileSearchRequest,
|
|
33
35
|
compileTimeRange: () => compileTimeRange,
|
|
34
36
|
mergeSpecWithOverrides: () => mergeSpecWithOverrides,
|
|
@@ -37,10 +39,19 @@ __export(ReportQueryCompiler_exports, {
|
|
|
37
39
|
normalizeReportSpec: () => normalizeReportSpec,
|
|
38
40
|
normalizeTimeRange: () => normalizeTimeRange,
|
|
39
41
|
parseSearchResponse: () => parseSearchResponse,
|
|
40
|
-
resolveAggregatableField: () => resolveAggregatableField
|
|
42
|
+
resolveAggregatableField: () => resolveAggregatableField,
|
|
43
|
+
resolveServerLockedFilters: () => resolveServerLockedFilters,
|
|
44
|
+
sanitizeTimeZone: () => sanitizeTimeZone
|
|
41
45
|
});
|
|
42
46
|
module.exports = __toCommonJS(ReportQueryCompiler_exports);
|
|
43
47
|
var import_constants = require("../../shared/constants");
|
|
48
|
+
class KqlSyntaxError extends Error {
|
|
49
|
+
status = 400;
|
|
50
|
+
constructor(message) {
|
|
51
|
+
super(message);
|
|
52
|
+
this.name = "KqlSyntaxError";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
44
55
|
const VALID_VISUALIZATIONS = /* @__PURE__ */ new Set([
|
|
45
56
|
"table",
|
|
46
57
|
"bar",
|
|
@@ -73,7 +84,27 @@ const VALID_PRESETS = /* @__PURE__ */ new Set([
|
|
|
73
84
|
"all",
|
|
74
85
|
"custom"
|
|
75
86
|
]);
|
|
76
|
-
const VALID_METRICS = /* @__PURE__ */ new Set([
|
|
87
|
+
const VALID_METRICS = /* @__PURE__ */ new Set([
|
|
88
|
+
"count",
|
|
89
|
+
"sum",
|
|
90
|
+
"avg",
|
|
91
|
+
"min",
|
|
92
|
+
"max",
|
|
93
|
+
"cardinality",
|
|
94
|
+
"p50",
|
|
95
|
+
"p95",
|
|
96
|
+
"p99"
|
|
97
|
+
]);
|
|
98
|
+
const VALID_STACK_MODES = /* @__PURE__ */ new Set(["none", "stacked", "percent"]);
|
|
99
|
+
const VALID_FIELD_FORMATS = /* @__PURE__ */ new Set([
|
|
100
|
+
"auto",
|
|
101
|
+
"duration_ms",
|
|
102
|
+
"bytes",
|
|
103
|
+
"percent",
|
|
104
|
+
"number",
|
|
105
|
+
"status_badge",
|
|
106
|
+
"url"
|
|
107
|
+
]);
|
|
77
108
|
const VALID_BUCKETS = /* @__PURE__ */ new Set(["date_histogram", "terms"]);
|
|
78
109
|
const VALID_INTERVALS = /* @__PURE__ */ new Set([
|
|
79
110
|
"auto",
|
|
@@ -85,6 +116,7 @@ const VALID_INTERVALS = /* @__PURE__ */ new Set([
|
|
|
85
116
|
"1w",
|
|
86
117
|
"1M"
|
|
87
118
|
]);
|
|
119
|
+
const CALENDAR_UNIT_INTERVALS = /* @__PURE__ */ new Set(["1m", "1h", "1d", "1w", "1M"]);
|
|
88
120
|
const PRESET_TO_ES_EXPR = {
|
|
89
121
|
last_15m: "now-15m",
|
|
90
122
|
last_1h: "now-1h",
|
|
@@ -93,6 +125,24 @@ const PRESET_TO_ES_EXPR = {
|
|
|
93
125
|
last_30d: "now-30d",
|
|
94
126
|
last_90d: "now-90d"
|
|
95
127
|
};
|
|
128
|
+
const PRESET_TO_PREV_ES_EXPR = {
|
|
129
|
+
last_15m: { gte: "now-30m", lt: "now-15m" },
|
|
130
|
+
last_1h: { gte: "now-2h", lt: "now-1h" },
|
|
131
|
+
last_24h: { gte: "now-48h", lt: "now-24h" },
|
|
132
|
+
last_7d: { gte: "now-14d", lt: "now-7d" },
|
|
133
|
+
last_30d: { gte: "now-60d", lt: "now-30d" },
|
|
134
|
+
last_90d: { gte: "now-180d", lt: "now-90d" }
|
|
135
|
+
};
|
|
136
|
+
function sanitizeTimeZone(raw) {
|
|
137
|
+
if (typeof raw !== "string" || !raw.trim()) return void 0;
|
|
138
|
+
const candidate = raw.trim();
|
|
139
|
+
try {
|
|
140
|
+
Intl.DateTimeFormat(void 0, { timeZone: candidate });
|
|
141
|
+
return candidate;
|
|
142
|
+
} catch {
|
|
143
|
+
return void 0;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
96
146
|
function isRecord(value) {
|
|
97
147
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
98
148
|
}
|
|
@@ -229,12 +279,78 @@ function normalizeTimeRange(raw) {
|
|
|
229
279
|
const preset = typeof raw.preset === "string" && VALID_PRESETS.has(raw.preset) ? raw.preset : "last_24h";
|
|
230
280
|
const from = typeof raw.from === "string" && raw.from.trim() ? raw.from.trim() : void 0;
|
|
231
281
|
const to = typeof raw.to === "string" && raw.to.trim() ? raw.to.trim() : void 0;
|
|
282
|
+
const timeZone = sanitizeTimeZone(raw.timeZone);
|
|
232
283
|
return {
|
|
233
284
|
preset,
|
|
234
285
|
...from ? { from } : {},
|
|
235
|
-
...to ? { to } : {}
|
|
286
|
+
...to ? { to } : {},
|
|
287
|
+
...timeZone ? { timeZone } : {}
|
|
236
288
|
};
|
|
237
289
|
}
|
|
290
|
+
function normalizeFieldFormats(raw) {
|
|
291
|
+
if (!isRecord(raw)) return void 0;
|
|
292
|
+
const out = {};
|
|
293
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
294
|
+
const fieldName = k.trim();
|
|
295
|
+
if (fieldName && typeof v === "string" && VALID_FIELD_FORMATS.has(v) && v !== "auto") {
|
|
296
|
+
out[fieldName] = v;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
300
|
+
}
|
|
301
|
+
function normalizeContextBindings(raw) {
|
|
302
|
+
if (!Array.isArray(raw)) return void 0;
|
|
303
|
+
const out = [];
|
|
304
|
+
for (const item of raw) {
|
|
305
|
+
if (!isRecord(item)) continue;
|
|
306
|
+
const esField = typeof item.esField === "string" ? item.esField.trim() : "";
|
|
307
|
+
const recordFieldPath = typeof item.recordFieldPath === "string" ? item.recordFieldPath.trim() : "";
|
|
308
|
+
if (esField && recordFieldPath) {
|
|
309
|
+
out.push({ esField, recordFieldPath });
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return out.length > 0 ? out : void 0;
|
|
313
|
+
}
|
|
314
|
+
function resolveTokenScalar(val, userCtx) {
|
|
315
|
+
var _a, _b, _c;
|
|
316
|
+
if (typeof val !== "string") return val;
|
|
317
|
+
const trimmed = val.trim();
|
|
318
|
+
const tokenMatch = trimmed.match(/^\{\{\s*\$(user\.(?:id|username|email)|role)\s*\}\}$/);
|
|
319
|
+
if (!tokenMatch) return val;
|
|
320
|
+
const tokenName = tokenMatch[1];
|
|
321
|
+
let resolved;
|
|
322
|
+
if (tokenName === "user.id" && userCtx.userId !== void 0 && userCtx.userId !== null && String(userCtx.userId) !== "") {
|
|
323
|
+
resolved = userCtx.userId;
|
|
324
|
+
} else if (tokenName === "user.username" && ((_a = userCtx.username) == null ? void 0 : _a.trim())) {
|
|
325
|
+
resolved = userCtx.username.trim();
|
|
326
|
+
} else if (tokenName === "user.email" && ((_b = userCtx.email) == null ? void 0 : _b.trim())) {
|
|
327
|
+
resolved = userCtx.email.trim();
|
|
328
|
+
} else if (tokenName === "role" && ((_c = userCtx.role) == null ? void 0 : _c.trim())) {
|
|
329
|
+
resolved = userCtx.role.trim();
|
|
330
|
+
}
|
|
331
|
+
if (resolved === void 0) {
|
|
332
|
+
const err = new Error(
|
|
333
|
+
`Permission denied: missing authenticated value for locked filter token "$${tokenName}"`
|
|
334
|
+
);
|
|
335
|
+
err.status = 403;
|
|
336
|
+
throw err;
|
|
337
|
+
}
|
|
338
|
+
return resolved;
|
|
339
|
+
}
|
|
340
|
+
function resolveServerLockedFilters(lockedFilters, userCtx) {
|
|
341
|
+
if (!lockedFilters || lockedFilters.length === 0) return [];
|
|
342
|
+
const ctx = userCtx ?? {};
|
|
343
|
+
return lockedFilters.map((item) => {
|
|
344
|
+
const nextVal = Array.isArray(item.value) ? item.value.map((v) => resolveTokenScalar(v, ctx)) : item.value !== void 0 ? resolveTokenScalar(item.value, ctx) : void 0;
|
|
345
|
+
const nextValTo = item.valueTo !== void 0 ? resolveTokenScalar(item.valueTo, ctx) : void 0;
|
|
346
|
+
return {
|
|
347
|
+
...item,
|
|
348
|
+
...nextVal !== void 0 ? { value: nextVal } : {},
|
|
349
|
+
...nextValTo !== void 0 ? { valueTo: nextValTo } : {},
|
|
350
|
+
enabled: true
|
|
351
|
+
};
|
|
352
|
+
});
|
|
353
|
+
}
|
|
238
354
|
function normalizeReportSpec(raw, fallbackVisualization) {
|
|
239
355
|
const obj = isRecord(raw) ? raw : {};
|
|
240
356
|
const visCandidate = typeof obj.visualization === "string" ? obj.visualization : fallbackVisualization;
|
|
@@ -242,21 +358,31 @@ function normalizeReportSpec(raw, fallbackVisualization) {
|
|
|
242
358
|
const query = typeof obj.query === "string" ? obj.query.trim() : "";
|
|
243
359
|
const queryMode = obj.queryMode === "simple" ? "simple" : "kql";
|
|
244
360
|
const filters = normalizeReportFilters(obj.filters);
|
|
361
|
+
const lockedFilters = normalizeReportFilters(obj.lockedFilters).map((item) => ({
|
|
362
|
+
...item,
|
|
363
|
+
enabled: true
|
|
364
|
+
}));
|
|
245
365
|
const sort = normalizeReportSort(obj.sort);
|
|
246
366
|
const timeRange = normalizeTimeRange(obj.timeRange);
|
|
247
367
|
const columns = Array.isArray(obj.columns) ? obj.columns.filter((col) => typeof col === "string" && col.trim().length > 0).map((col) => col.trim()) : [];
|
|
368
|
+
const fieldFormats = normalizeFieldFormats(obj.fieldFormats);
|
|
369
|
+
const contextBindings = normalizeContextBindings(obj.contextBindings);
|
|
248
370
|
const pageSize = clamp(typeof obj.pageSize === "number" ? obj.pageSize : import_constants.DEFAULT_PAGE_SIZE, 1, import_constants.MAX_UI_PAGE_SIZE);
|
|
249
371
|
const rawChart = isRecord(obj.chart) ? obj.chart : {};
|
|
250
372
|
const metricType = typeof rawChart.metricType === "string" && VALID_METRICS.has(rawChart.metricType) ? rawChart.metricType : "count";
|
|
251
373
|
const bucketType = typeof rawChart.bucketType === "string" && VALID_BUCKETS.has(rawChart.bucketType) ? rawChart.bucketType : void 0;
|
|
252
374
|
const calendarInterval = typeof rawChart.calendarInterval === "string" && VALID_INTERVALS.has(rawChart.calendarInterval) ? rawChart.calendarInterval : "auto";
|
|
375
|
+
const stackMode = typeof rawChart.stackMode === "string" && VALID_STACK_MODES.has(rawChart.stackMode) ? rawChart.stackMode : "none";
|
|
253
376
|
return {
|
|
254
377
|
query,
|
|
255
378
|
queryMode,
|
|
256
379
|
filters,
|
|
380
|
+
lockedFilters,
|
|
257
381
|
sort,
|
|
258
382
|
...timeRange ? { timeRange } : {},
|
|
259
383
|
columns,
|
|
384
|
+
...fieldFormats ? { fieldFormats } : {},
|
|
385
|
+
...contextBindings ? { contextBindings } : {},
|
|
260
386
|
pageSize,
|
|
261
387
|
visualization,
|
|
262
388
|
chart: {
|
|
@@ -267,17 +393,65 @@ function normalizeReportSpec(raw, fallbackVisualization) {
|
|
|
267
393
|
metricType,
|
|
268
394
|
...typeof rawChart.metricField === "string" && rawChart.metricField.trim() ? { metricField: rawChart.metricField.trim() } : {},
|
|
269
395
|
...typeof rawChart.metricLabel === "string" && rawChart.metricLabel.trim() ? { metricLabel: rawChart.metricLabel.trim() } : {},
|
|
270
|
-
showHistogram: rawChart.showHistogram !== false
|
|
396
|
+
showHistogram: rawChart.showHistogram !== false,
|
|
397
|
+
...typeof rawChart.splitSeriesField === "string" && rawChart.splitSeriesField.trim() ? { splitSeriesField: rawChart.splitSeriesField.trim() } : {},
|
|
398
|
+
...typeof rawChart.splitSeriesTopN === "number" ? { splitSeriesTopN: clamp(rawChart.splitSeriesTopN, 1, import_constants.MAX_SPLIT_SERIES) } : {},
|
|
399
|
+
...stackMode !== "none" ? { stackMode } : {},
|
|
400
|
+
...rawChart.comparePreviousPeriod === true ? { comparePreviousPeriod: true } : {}
|
|
271
401
|
},
|
|
272
|
-
allowInteractiveControls: obj.allowInteractiveControls !== false
|
|
402
|
+
allowInteractiveControls: obj.allowInteractiveControls !== false,
|
|
403
|
+
allowExport: obj.allowExport !== false
|
|
273
404
|
};
|
|
274
405
|
}
|
|
406
|
+
function assertBalancedKqlDelimiters(input) {
|
|
407
|
+
let inQuotes = false;
|
|
408
|
+
let quoteChar = "";
|
|
409
|
+
const openParenPositions = [];
|
|
410
|
+
for (let i = 0; i < input.length; i++) {
|
|
411
|
+
const ch = input[i];
|
|
412
|
+
if (inQuotes) {
|
|
413
|
+
if (ch === "\\") {
|
|
414
|
+
i++;
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if (ch === quoteChar) {
|
|
418
|
+
inQuotes = false;
|
|
419
|
+
}
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
if (ch === '"' || ch === "'") {
|
|
423
|
+
inQuotes = true;
|
|
424
|
+
quoteChar = ch;
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
if (ch === "(") {
|
|
428
|
+
openParenPositions.push(i);
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
if (ch === ")") {
|
|
432
|
+
const openIdx = openParenPositions.pop();
|
|
433
|
+
if (openIdx === void 0) {
|
|
434
|
+
throw new KqlSyntaxError('Invalid KQL syntax: unexpected closing parenthesis ")"');
|
|
435
|
+
}
|
|
436
|
+
if (!input.slice(openIdx + 1, i).trim()) {
|
|
437
|
+
throw new KqlSyntaxError('Invalid KQL syntax: empty parentheses "()"');
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
if (inQuotes) {
|
|
442
|
+
throw new KqlSyntaxError("Invalid KQL syntax: unclosed quotation mark");
|
|
443
|
+
}
|
|
444
|
+
if (openParenPositions.length > 0) {
|
|
445
|
+
throw new KqlSyntaxError('Invalid KQL syntax: unclosed parenthesis "("');
|
|
446
|
+
}
|
|
447
|
+
}
|
|
275
448
|
function splitTopLevelBoolean(input, keyword) {
|
|
276
449
|
const parts = [];
|
|
277
450
|
let depth = 0;
|
|
278
451
|
let inQuotes = false;
|
|
279
452
|
let quoteChar = "";
|
|
280
453
|
let lastIdx = 0;
|
|
454
|
+
let splitFound = false;
|
|
281
455
|
for (let i = 0; i < input.length; i++) {
|
|
282
456
|
const ch = input[i];
|
|
283
457
|
if (inQuotes) {
|
|
@@ -304,18 +478,22 @@ function splitTopLevelBoolean(input, keyword) {
|
|
|
304
478
|
continue;
|
|
305
479
|
}
|
|
306
480
|
if (depth === 0) {
|
|
307
|
-
const prevBoundary = i === 0 ||
|
|
481
|
+
const prevBoundary = i === 0 || /[\s)]/.test(input[i - 1]);
|
|
308
482
|
const slice = input.slice(i, i + keyword.length);
|
|
309
483
|
const nextChar = input[i + keyword.length];
|
|
310
|
-
const nextBoundary = nextChar
|
|
484
|
+
const nextBoundary = nextChar === void 0 || /[\s(]/.test(nextChar);
|
|
311
485
|
if (prevBoundary && nextBoundary && slice.toUpperCase() === keyword) {
|
|
486
|
+
splitFound = true;
|
|
312
487
|
parts.push(input.slice(lastIdx, i).trim());
|
|
313
|
-
i += keyword.length;
|
|
314
|
-
lastIdx = i;
|
|
488
|
+
i += keyword.length - 1;
|
|
489
|
+
lastIdx = i + 1;
|
|
315
490
|
}
|
|
316
491
|
}
|
|
317
492
|
}
|
|
318
493
|
parts.push(input.slice(lastIdx).trim());
|
|
494
|
+
if (splitFound && parts.some((part) => !part)) {
|
|
495
|
+
throw new KqlSyntaxError(`Invalid KQL syntax: missing operand around "${keyword}"`);
|
|
496
|
+
}
|
|
319
497
|
return parts.filter(Boolean);
|
|
320
498
|
}
|
|
321
499
|
function hasBalancedOuterParens(expr) {
|
|
@@ -356,71 +534,144 @@ function unquote(raw) {
|
|
|
356
534
|
}
|
|
357
535
|
return { value: trimmed, wasQuoted: false };
|
|
358
536
|
}
|
|
359
|
-
function
|
|
360
|
-
const
|
|
537
|
+
function compileSingleFieldValue(rawField, rawVal, fieldMap) {
|
|
538
|
+
const trimmed = rawVal.trim();
|
|
539
|
+
if (!trimmed) {
|
|
540
|
+
throw new KqlSyntaxError(`Invalid KQL syntax: missing value for field "${rawField}"`);
|
|
541
|
+
}
|
|
542
|
+
const inlineRangeMatch = trimmed.match(/^(>=|<=|>|<)\s*(.+)$/);
|
|
543
|
+
if (inlineRangeMatch) {
|
|
544
|
+
const [, op, rangeRhs] = inlineRangeMatch;
|
|
545
|
+
const { value: value2 } = unquote(rangeRhs);
|
|
546
|
+
if (!value2) {
|
|
547
|
+
throw new KqlSyntaxError(`Invalid KQL syntax: missing range bound for field "${rawField}"`);
|
|
548
|
+
}
|
|
549
|
+
const coerced2 = coerceLiteral(value2, fieldMap.get(rawField));
|
|
550
|
+
const opKey = op === ">=" ? "gte" : op === "<=" ? "lte" : op === ">" ? "gt" : "lt";
|
|
551
|
+
return { range: { [rawField]: { [opKey]: coerced2 } } };
|
|
552
|
+
}
|
|
553
|
+
const { value, wasQuoted } = unquote(trimmed);
|
|
554
|
+
if (!wasQuoted) {
|
|
555
|
+
if (/^[[{].*[\]}]$/.test(value)) {
|
|
556
|
+
throw new KqlSyntaxError("Lucene range brackets [a TO b] are not valid KQL; use >= and <= instead");
|
|
557
|
+
}
|
|
558
|
+
if (/^\/.*\/$/.test(value)) {
|
|
559
|
+
throw new KqlSyntaxError("Regular expressions /.../ are not valid KQL; use * or ? wildcards instead");
|
|
560
|
+
}
|
|
561
|
+
if (value.includes("(") || value.includes(")")) {
|
|
562
|
+
throw new KqlSyntaxError(`Unsupported KQL field value syntax near "${value}"`);
|
|
563
|
+
}
|
|
564
|
+
if (value.includes(":")) {
|
|
565
|
+
throw new KqlSyntaxError(`Unexpected ":" in unquoted KQL value "${value}"; wrap values containing ":" in quotes`);
|
|
566
|
+
}
|
|
567
|
+
if (value === "*") {
|
|
568
|
+
return { exists: { field: rawField } };
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
const fieldMeta = fieldMap.get(rawField);
|
|
572
|
+
if (!wasQuoted && (value.includes("*") || value.includes("?"))) {
|
|
573
|
+
const wildcardField = resolveAggregatableField(rawField, fieldMap);
|
|
574
|
+
return {
|
|
575
|
+
wildcard: {
|
|
576
|
+
[wildcardField]: {
|
|
577
|
+
value,
|
|
578
|
+
case_insensitive: true
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
if (wasQuoted) {
|
|
584
|
+
if ((fieldMeta == null ? void 0 : fieldMeta.type) === "keyword" || (fieldMeta == null ? void 0 : fieldMeta.type) === "constant_keyword") {
|
|
585
|
+
return { term: { [rawField]: value } };
|
|
586
|
+
}
|
|
587
|
+
return { match_phrase: { [rawField]: value } };
|
|
588
|
+
}
|
|
589
|
+
const coerced = coerceLiteral(value, fieldMeta);
|
|
590
|
+
if (typeof coerced === "number" || typeof coerced === "boolean") {
|
|
591
|
+
return { term: { [rawField]: coerced } };
|
|
592
|
+
}
|
|
593
|
+
if ((fieldMeta == null ? void 0 : fieldMeta.type) === "keyword" || (fieldMeta == null ? void 0 : fieldMeta.type) === "constant_keyword") {
|
|
594
|
+
return { term: { [rawField]: coerced } };
|
|
595
|
+
}
|
|
596
|
+
return { match_phrase: { [rawField]: String(coerced) } };
|
|
597
|
+
}
|
|
598
|
+
function compileFieldGroupClause(fieldName, groupBody, fieldMap) {
|
|
599
|
+
const expr = groupBody.trim();
|
|
600
|
+
if (!expr) {
|
|
601
|
+
throw new KqlSyntaxError(`Invalid KQL syntax: empty value group for field "${fieldName}"`);
|
|
602
|
+
}
|
|
603
|
+
if (/^NOT$/i.test(expr)) {
|
|
604
|
+
throw new KqlSyntaxError(`Invalid KQL syntax: incomplete "NOT" inside "${fieldName}: (...)"`);
|
|
605
|
+
}
|
|
606
|
+
if (hasBalancedOuterParens(expr)) {
|
|
607
|
+
return compileFieldGroupClause(fieldName, expr.slice(1, -1), fieldMap);
|
|
608
|
+
}
|
|
609
|
+
const orParts = splitTopLevelBoolean(expr, "OR");
|
|
610
|
+
if (orParts.length > 1) {
|
|
611
|
+
const should = orParts.map((part) => compileFieldGroupClause(fieldName, part, fieldMap));
|
|
612
|
+
return should.length === 1 ? should[0] : { bool: { should, minimum_should_match: 1 } };
|
|
613
|
+
}
|
|
614
|
+
const andParts = splitTopLevelBoolean(expr, "AND");
|
|
615
|
+
if (andParts.length > 1) {
|
|
616
|
+
const must = andParts.map((part) => compileFieldGroupClause(fieldName, part, fieldMap));
|
|
617
|
+
return must.length === 1 ? must[0] : { bool: { must } };
|
|
618
|
+
}
|
|
619
|
+
if (/^NOT\s+/i.test(expr)) {
|
|
620
|
+
const inner = compileFieldGroupClause(fieldName, expr.replace(/^NOT\s+/i, ""), fieldMap);
|
|
621
|
+
return { bool: { must_not: [inner] } };
|
|
622
|
+
}
|
|
623
|
+
return compileSingleFieldValue(fieldName, expr, fieldMap);
|
|
624
|
+
}
|
|
625
|
+
function compileKqlAst(exprInput, fieldMap) {
|
|
626
|
+
const expr = exprInput.trim();
|
|
361
627
|
if (!expr) return null;
|
|
628
|
+
if (/^NOT$/i.test(expr)) {
|
|
629
|
+
throw new KqlSyntaxError('Invalid KQL syntax: incomplete "NOT" operator');
|
|
630
|
+
}
|
|
362
631
|
if (hasBalancedOuterParens(expr)) {
|
|
363
|
-
return
|
|
632
|
+
return compileKqlAst(expr.slice(1, -1), fieldMap);
|
|
364
633
|
}
|
|
365
634
|
const orParts = splitTopLevelBoolean(expr, "OR");
|
|
366
635
|
if (orParts.length > 1) {
|
|
367
|
-
const should = orParts.map((part) =>
|
|
636
|
+
const should = orParts.map((part) => compileKqlAst(part, fieldMap)).filter((item) => item !== null);
|
|
368
637
|
if (should.length === 0) return null;
|
|
369
638
|
if (should.length === 1) return should[0];
|
|
370
639
|
return { bool: { should, minimum_should_match: 1 } };
|
|
371
640
|
}
|
|
372
641
|
const andParts = splitTopLevelBoolean(expr, "AND");
|
|
373
642
|
if (andParts.length > 1) {
|
|
374
|
-
const must = andParts.map((part) =>
|
|
643
|
+
const must = andParts.map((part) => compileKqlAst(part, fieldMap)).filter((item) => item !== null);
|
|
375
644
|
if (must.length === 0) return null;
|
|
376
645
|
if (must.length === 1) return must[0];
|
|
377
646
|
return { bool: { must } };
|
|
378
647
|
}
|
|
379
648
|
if (/^NOT\s+/i.test(expr)) {
|
|
380
|
-
const
|
|
649
|
+
const rest = expr.replace(/^NOT\s+/i, "").trim();
|
|
650
|
+
if (!rest) {
|
|
651
|
+
throw new KqlSyntaxError('Invalid KQL syntax: incomplete "NOT" operator');
|
|
652
|
+
}
|
|
653
|
+
const inner = compileKqlAst(rest, fieldMap);
|
|
381
654
|
return inner ? { bool: { must_not: [inner] } } : null;
|
|
382
655
|
}
|
|
656
|
+
if (/^[A-Za-z0-9_@.-]+\s*(:|>=|<=|>|<)\s*$/.test(expr)) {
|
|
657
|
+
throw new KqlSyntaxError("Invalid KQL syntax: missing value after field operator");
|
|
658
|
+
}
|
|
383
659
|
const rangeMatch = expr.match(/^([A-Za-z0-9_@.-]+)\s*(>=|<=|>|<)\s*(.+)$/);
|
|
384
660
|
if (rangeMatch) {
|
|
385
661
|
const [, rawField, op, rawVal] = rangeMatch;
|
|
386
|
-
|
|
387
|
-
const coerced = coerceLiteral(value, fieldMap.get(rawField));
|
|
388
|
-
const opKey = op === ">=" ? "gte" : op === "<=" ? "lte" : op === ">" ? "gt" : "lt";
|
|
389
|
-
return { range: { [rawField]: { [opKey]: coerced } } };
|
|
662
|
+
return compileSingleFieldValue(rawField, `${op} ${rawVal}`, fieldMap);
|
|
390
663
|
}
|
|
391
664
|
const colonMatch = expr.match(/^([A-Za-z0-9_@.-]+)\s*:\s*(.+)$/);
|
|
392
665
|
if (colonMatch) {
|
|
393
666
|
const [, rawField, rawVal] = colonMatch;
|
|
394
|
-
const
|
|
395
|
-
if (
|
|
396
|
-
return
|
|
397
|
-
}
|
|
398
|
-
const fieldMeta = fieldMap.get(rawField);
|
|
399
|
-
if (!wasQuoted && (value.includes("*") || value.includes("?"))) {
|
|
400
|
-
const wildcardField = resolveAggregatableField(rawField, fieldMap);
|
|
401
|
-
return {
|
|
402
|
-
wildcard: {
|
|
403
|
-
[wildcardField]: {
|
|
404
|
-
value,
|
|
405
|
-
case_insensitive: true
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
};
|
|
667
|
+
const rhs = rawVal.trim();
|
|
668
|
+
if (hasBalancedOuterParens(rhs)) {
|
|
669
|
+
return compileFieldGroupClause(rawField, rhs.slice(1, -1), fieldMap);
|
|
409
670
|
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
return { match_phrase: { [rawField]: value } };
|
|
415
|
-
}
|
|
416
|
-
const coerced = coerceLiteral(value, fieldMeta);
|
|
417
|
-
if (typeof coerced === "number" || typeof coerced === "boolean") {
|
|
418
|
-
return { term: { [rawField]: coerced } };
|
|
419
|
-
}
|
|
420
|
-
if ((fieldMeta == null ? void 0 : fieldMeta.type) === "keyword" || (fieldMeta == null ? void 0 : fieldMeta.type) === "constant_keyword") {
|
|
421
|
-
return { term: { [rawField]: coerced } };
|
|
422
|
-
}
|
|
423
|
-
return { match_phrase: { [rawField]: String(coerced) } };
|
|
671
|
+
return compileSingleFieldValue(rawField, rhs, fieldMap);
|
|
672
|
+
}
|
|
673
|
+
if (!unquote(expr).wasQuoted && (/^[[{].*[\]}]$/.test(expr) || /^\/.*\/$/.test(expr))) {
|
|
674
|
+
throw new KqlSyntaxError(`Unsupported KQL expression "${expr}"`);
|
|
424
675
|
}
|
|
425
676
|
return {
|
|
426
677
|
simple_query_string: {
|
|
@@ -430,6 +681,12 @@ function compileKqlToQueryDsl(rawQuery, fieldMap = /* @__PURE__ */ new Map()) {
|
|
|
430
681
|
}
|
|
431
682
|
};
|
|
432
683
|
}
|
|
684
|
+
function compileKqlToQueryDsl(rawQuery, fieldMap = /* @__PURE__ */ new Map()) {
|
|
685
|
+
const expr = rawQuery.trim();
|
|
686
|
+
if (!expr) return null;
|
|
687
|
+
assertBalancedKqlDelimiters(expr);
|
|
688
|
+
return compileKqlAst(expr, fieldMap);
|
|
689
|
+
}
|
|
433
690
|
function compileFilterItem(item, fieldMap) {
|
|
434
691
|
if (item.enabled === false || !item.field.trim()) return null;
|
|
435
692
|
const field = item.field.trim();
|
|
@@ -507,14 +764,16 @@ function compileFilterItem(item, fieldMap) {
|
|
|
507
764
|
return null;
|
|
508
765
|
}
|
|
509
766
|
}
|
|
510
|
-
function compileTimeRange(timeRange, timeField) {
|
|
767
|
+
function compileTimeRange(timeRange, timeField, fallbackTimeZone) {
|
|
511
768
|
const cleanField = typeof timeField === "string" ? timeField.trim() : "";
|
|
512
769
|
if (!cleanField || !timeRange || timeRange.preset === "all") return null;
|
|
770
|
+
const tz = sanitizeTimeZone(timeRange.timeZone ?? fallbackTimeZone);
|
|
513
771
|
if (timeRange.preset === "custom") {
|
|
514
772
|
const bounds = {};
|
|
515
773
|
if (timeRange.from) bounds.gte = timeRange.from;
|
|
516
774
|
if (timeRange.to) bounds.lte = timeRange.to;
|
|
517
775
|
if (Object.keys(bounds).length === 0) return null;
|
|
776
|
+
if (tz) bounds.time_zone = tz;
|
|
518
777
|
return { range: { [cleanField]: bounds } };
|
|
519
778
|
}
|
|
520
779
|
const expr = PRESET_TO_ES_EXPR[timeRange.preset];
|
|
@@ -523,26 +782,106 @@ function compileTimeRange(timeRange, timeField) {
|
|
|
523
782
|
range: {
|
|
524
783
|
[cleanField]: {
|
|
525
784
|
gte: expr,
|
|
526
|
-
lte: "now"
|
|
785
|
+
lte: "now",
|
|
786
|
+
...tz ? { time_zone: tz } : {}
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
function compilePreviousTimeRange(timeRange, timeField, fallbackTimeZone) {
|
|
792
|
+
const cleanField = typeof timeField === "string" ? timeField.trim() : "";
|
|
793
|
+
if (!cleanField || !timeRange || timeRange.preset === "all") return null;
|
|
794
|
+
const tz = sanitizeTimeZone(timeRange.timeZone ?? fallbackTimeZone);
|
|
795
|
+
if (timeRange.preset === "custom") {
|
|
796
|
+
const fromMs = timeRange.from ? Date.parse(timeRange.from) : NaN;
|
|
797
|
+
const toMs = timeRange.to ? Date.parse(timeRange.to) : NaN;
|
|
798
|
+
if (!Number.isFinite(fromMs) || !Number.isFinite(toMs) || toMs <= fromMs) {
|
|
799
|
+
return null;
|
|
800
|
+
}
|
|
801
|
+
const duration = toMs - fromMs;
|
|
802
|
+
return {
|
|
803
|
+
range: {
|
|
804
|
+
[cleanField]: {
|
|
805
|
+
gte: new Date(fromMs - duration).toISOString(),
|
|
806
|
+
lt: new Date(fromMs).toISOString(),
|
|
807
|
+
...tz ? { time_zone: tz } : {}
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
const prev = PRESET_TO_PREV_ES_EXPR[timeRange.preset];
|
|
813
|
+
if (!prev) return null;
|
|
814
|
+
return {
|
|
815
|
+
range: {
|
|
816
|
+
[cleanField]: {
|
|
817
|
+
gte: prev.gte,
|
|
818
|
+
lt: prev.lt,
|
|
819
|
+
...tz ? { time_zone: tz } : {}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
function buildMetricAggDefinition(metricType, metricField, fieldMap) {
|
|
825
|
+
if (metricType === "count" || !(metricField == null ? void 0 : metricField.trim())) return void 0;
|
|
826
|
+
const targetField = resolveAggregatableField(metricField, fieldMap);
|
|
827
|
+
if (metricType === "p50" || metricType === "p95" || metricType === "p99") {
|
|
828
|
+
const pct = metricType === "p50" ? 50 : metricType === "p95" ? 95 : 99;
|
|
829
|
+
return {
|
|
830
|
+
percentiles: {
|
|
831
|
+
field: targetField,
|
|
832
|
+
percents: [pct]
|
|
527
833
|
}
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
return {
|
|
837
|
+
[metricType]: {
|
|
838
|
+
field: targetField
|
|
528
839
|
}
|
|
529
840
|
};
|
|
530
841
|
}
|
|
842
|
+
function extractMetricValue(aggNode, metricType, fallbackCount) {
|
|
843
|
+
if (metricType === "count") {
|
|
844
|
+
return fallbackCount;
|
|
845
|
+
}
|
|
846
|
+
if (!isRecord(aggNode)) return null;
|
|
847
|
+
if (metricType === "p50" || metricType === "p95" || metricType === "p99") {
|
|
848
|
+
const values = isRecord(aggNode.values) ? aggNode.values : void 0;
|
|
849
|
+
if (!values) return null;
|
|
850
|
+
const exactKey = metricType === "p50" ? "50.0" : metricType === "p95" ? "95.0" : "99.0";
|
|
851
|
+
const shortKey = metricType === "p50" ? "50" : metricType === "p95" ? "95" : "99";
|
|
852
|
+
const raw = values[exactKey] ?? values[shortKey];
|
|
853
|
+
return typeof raw === "number" && Number.isFinite(raw) ? Number(raw.toFixed(4)) : null;
|
|
854
|
+
}
|
|
855
|
+
return typeof aggNode.value === "number" && Number.isFinite(aggNode.value) ? Number(aggNode.value.toFixed(4)) : null;
|
|
856
|
+
}
|
|
531
857
|
function mergeSpecWithOverrides(spec, overrides) {
|
|
858
|
+
var _a, _b;
|
|
532
859
|
if (!overrides) {
|
|
533
860
|
return {
|
|
534
861
|
effectiveSpec: spec,
|
|
862
|
+
extraRuntimeFilters: [],
|
|
863
|
+
effectiveTimeZone: sanitizeTimeZone((_a = spec.timeRange) == null ? void 0 : _a.timeZone),
|
|
535
864
|
page: 1,
|
|
536
865
|
pageSize: spec.pageSize ?? import_constants.DEFAULT_PAGE_SIZE
|
|
537
866
|
};
|
|
538
867
|
}
|
|
868
|
+
const effectiveTimeRange = overrides.timeRange !== void 0 ? normalizeTimeRange(overrides.timeRange) : spec.timeRange;
|
|
869
|
+
const effectiveTimeZone = sanitizeTimeZone(
|
|
870
|
+
overrides.timeZone ?? (effectiveTimeRange == null ? void 0 : effectiveTimeRange.timeZone) ?? ((_b = spec.timeRange) == null ? void 0 : _b.timeZone)
|
|
871
|
+
);
|
|
539
872
|
const effectiveSpec = {
|
|
540
873
|
...spec,
|
|
541
874
|
query: overrides.query !== void 0 ? overrides.query.trim() : spec.query,
|
|
542
875
|
filters: overrides.filters !== void 0 ? normalizeReportFilters(overrides.filters) : spec.filters,
|
|
876
|
+
// Security invariant: lockedFilters are server-owned and can never be replaced or cleared by runtime overrides.
|
|
877
|
+
lockedFilters: spec.lockedFilters,
|
|
543
878
|
sort: overrides.sort !== void 0 ? normalizeReportSort(overrides.sort) : spec.sort,
|
|
544
|
-
timeRange:
|
|
879
|
+
timeRange: effectiveTimeRange
|
|
545
880
|
};
|
|
881
|
+
const extraRuntimeFilters = [
|
|
882
|
+
...normalizeReportFilters(overrides.sharedFilters),
|
|
883
|
+
...normalizeReportFilters(overrides.contextFilters)
|
|
884
|
+
];
|
|
546
885
|
const page = clamp(typeof overrides.page === "number" ? overrides.page : 1, 1, 1e4);
|
|
547
886
|
const pageSize = clamp(
|
|
548
887
|
typeof overrides.pageSize === "number" ? overrides.pageSize : spec.pageSize ?? import_constants.DEFAULT_PAGE_SIZE,
|
|
@@ -552,6 +891,8 @@ function mergeSpecWithOverrides(spec, overrides) {
|
|
|
552
891
|
const searchAfter = Array.isArray(overrides.searchAfter) && overrides.searchAfter.length > 0 ? overrides.searchAfter : void 0;
|
|
553
892
|
return {
|
|
554
893
|
effectiveSpec,
|
|
894
|
+
extraRuntimeFilters,
|
|
895
|
+
...effectiveTimeZone ? { effectiveTimeZone } : {},
|
|
555
896
|
page,
|
|
556
897
|
pageSize,
|
|
557
898
|
...searchAfter ? { searchAfter } : {}
|
|
@@ -560,7 +901,10 @@ function mergeSpecWithOverrides(spec, overrides) {
|
|
|
560
901
|
function compileSearchRequest(options) {
|
|
561
902
|
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
562
903
|
const fieldMap = buildFieldCapabilityMap(options.fields);
|
|
563
|
-
const { effectiveSpec, page, pageSize, searchAfter } = mergeSpecWithOverrides(
|
|
904
|
+
const { effectiveSpec, extraRuntimeFilters, effectiveTimeZone, page, pageSize, searchAfter } = mergeSpecWithOverrides(
|
|
905
|
+
options.spec,
|
|
906
|
+
options.overrides
|
|
907
|
+
);
|
|
564
908
|
const maxCap = options.maxRowsCap ? clamp(options.maxRowsCap, 1, import_constants.MAX_UI_PAGE_SIZE) : import_constants.MAX_UI_PAGE_SIZE;
|
|
565
909
|
const effectivePageSize = Math.min(pageSize, maxCap);
|
|
566
910
|
const timeField = ((_a = options.timeField) == null ? void 0 : _a.trim()) || null;
|
|
@@ -583,7 +927,13 @@ function compileSearchRequest(options) {
|
|
|
583
927
|
}
|
|
584
928
|
}
|
|
585
929
|
}
|
|
586
|
-
|
|
930
|
+
const resolvedLockedFilters = resolveServerLockedFilters(effectiveSpec.lockedFilters, options.userContext);
|
|
931
|
+
const combinedFilters = [
|
|
932
|
+
...resolvedLockedFilters,
|
|
933
|
+
...extraRuntimeFilters,
|
|
934
|
+
...effectiveSpec.filters ?? []
|
|
935
|
+
];
|
|
936
|
+
for (const item of combinedFilters) {
|
|
587
937
|
const compiled = compileFilterItem(item, fieldMap);
|
|
588
938
|
if (!compiled) continue;
|
|
589
939
|
if (compiled.negated) {
|
|
@@ -592,9 +942,11 @@ function compileSearchRequest(options) {
|
|
|
592
942
|
filter.push(compiled.clause);
|
|
593
943
|
}
|
|
594
944
|
}
|
|
595
|
-
const
|
|
596
|
-
|
|
597
|
-
|
|
945
|
+
const currentTimeClause = compileTimeRange(effectiveSpec.timeRange, timeField, effectiveTimeZone);
|
|
946
|
+
const previousTimeClause = effectiveSpec.visualization === "metric" && ((_b = effectiveSpec.chart) == null ? void 0 : _b.comparePreviousPeriod) === true ? compilePreviousTimeRange(effectiveSpec.timeRange, timeField, effectiveTimeZone) : null;
|
|
947
|
+
const useDualPeriodMetric = Boolean(currentTimeClause && previousTimeClause);
|
|
948
|
+
if (currentTimeClause && !useDualPeriodMetric) {
|
|
949
|
+
filter.push(currentTimeClause);
|
|
598
950
|
}
|
|
599
951
|
let queryDsl;
|
|
600
952
|
if (must.length === 0 && filter.length === 0 && mustNot.length === 0) {
|
|
@@ -610,13 +962,13 @@ function compileSearchRequest(options) {
|
|
|
610
962
|
}
|
|
611
963
|
const body = {
|
|
612
964
|
query: queryDsl,
|
|
613
|
-
track_total_hits: import_constants.MAX_RESULT_WINDOW
|
|
965
|
+
track_total_hits: effectiveSpec.visualization === "metric" ? true : import_constants.MAX_RESULT_WINDOW
|
|
614
966
|
};
|
|
615
967
|
const requestedSorts = effectiveSpec.sort && effectiveSpec.sort.length > 0 ? effectiveSpec.sort : timeField ? [{ field: timeField, order: "desc" }] : [];
|
|
616
968
|
if (effectiveSpec.visualization === "table") {
|
|
617
969
|
body.size = effectivePageSize;
|
|
618
970
|
if (requestedSorts.length > 0) {
|
|
619
|
-
|
|
971
|
+
const sortClauses = requestedSorts.map((sortItem) => {
|
|
620
972
|
const targetField = resolveAggregatableField(sortItem.field, fieldMap);
|
|
621
973
|
const unmappedType = resolveUnmappedSortType(targetField, fieldMap);
|
|
622
974
|
return {
|
|
@@ -626,6 +978,15 @@ function compileSearchRequest(options) {
|
|
|
626
978
|
}
|
|
627
979
|
};
|
|
628
980
|
});
|
|
981
|
+
const hasTieBreaker = requestedSorts.some(
|
|
982
|
+
(s) => s.field === "_id" || s.field === "_shard_doc" || s.field === "_doc"
|
|
983
|
+
);
|
|
984
|
+
const legacyCursorMatchesUserSortOnly = searchAfter !== void 0 && searchAfter.length === requestedSorts.length && !hasTieBreaker;
|
|
985
|
+
if (!hasTieBreaker && !legacyCursorMatchesUserSortOnly) {
|
|
986
|
+
const tieBreakerField = options.usePit ? "_shard_doc" : "_doc";
|
|
987
|
+
sortClauses.push({ [tieBreakerField]: { order: "asc" } });
|
|
988
|
+
}
|
|
989
|
+
body.sort = sortClauses;
|
|
629
990
|
}
|
|
630
991
|
if (searchAfter && body.sort) {
|
|
631
992
|
body.search_after = searchAfter;
|
|
@@ -647,29 +1008,36 @@ function compileSearchRequest(options) {
|
|
|
647
1008
|
number_of_fragments: 2
|
|
648
1009
|
};
|
|
649
1010
|
}
|
|
650
|
-
if (timeField && ((
|
|
1011
|
+
if (timeField && ((_c = effectiveSpec.chart) == null ? void 0 : _c.showHistogram) !== false) {
|
|
651
1012
|
body.aggs = {
|
|
652
1013
|
es_time_histogram: {
|
|
653
1014
|
auto_date_histogram: {
|
|
654
1015
|
field: timeField,
|
|
655
|
-
buckets: 24
|
|
1016
|
+
buckets: 24,
|
|
1017
|
+
...effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}
|
|
656
1018
|
}
|
|
657
1019
|
}
|
|
658
1020
|
};
|
|
659
1021
|
}
|
|
660
1022
|
} else if (effectiveSpec.visualization === "metric") {
|
|
661
1023
|
body.size = 0;
|
|
662
|
-
const metricType = ((
|
|
663
|
-
const
|
|
664
|
-
if (
|
|
665
|
-
const targetMetricField = resolveAggregatableField(metricField, fieldMap);
|
|
1024
|
+
const metricType = ((_d = effectiveSpec.chart) == null ? void 0 : _d.metricType) ?? "count";
|
|
1025
|
+
const metricDef = buildMetricAggDefinition(metricType, (_e = effectiveSpec.chart) == null ? void 0 : _e.metricField, fieldMap);
|
|
1026
|
+
if (useDualPeriodMetric && currentTimeClause && previousTimeClause) {
|
|
666
1027
|
body.aggs = {
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
1028
|
+
es_current_window: {
|
|
1029
|
+
filter: currentTimeClause,
|
|
1030
|
+
...metricDef ? { aggs: { es_metric: metricDef } } : {}
|
|
1031
|
+
},
|
|
1032
|
+
es_previous_window: {
|
|
1033
|
+
filter: previousTimeClause,
|
|
1034
|
+
...metricDef ? { aggs: { es_metric: metricDef } } : {}
|
|
671
1035
|
}
|
|
672
1036
|
};
|
|
1037
|
+
} else if (metricDef) {
|
|
1038
|
+
body.aggs = {
|
|
1039
|
+
es_metric: metricDef
|
|
1040
|
+
};
|
|
673
1041
|
}
|
|
674
1042
|
} else {
|
|
675
1043
|
body.size = 0;
|
|
@@ -678,32 +1046,47 @@ function compileSearchRequest(options) {
|
|
|
678
1046
|
const rawBucketField = ((_f = chartCfg.bucketField) == null ? void 0 : _f.trim()) || (defaultBucketType === "date_histogram" ? timeField : "") || ((_g = Array.from(fieldMap.values()).find((f) => f.aggregatable)) == null ? void 0 : _g.name) || "_index";
|
|
679
1047
|
const bucketField = resolveAggregatableField(rawBucketField, fieldMap);
|
|
680
1048
|
const metricType = chartCfg.metricType ?? "count";
|
|
681
|
-
const
|
|
682
|
-
const
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
1049
|
+
const metricDef = buildMetricAggDefinition(metricType, chartCfg.metricField, fieldMap);
|
|
1050
|
+
const canOrderByMetric = Boolean(metricDef) && metricType !== "p50" && metricType !== "p95" && metricType !== "p99";
|
|
1051
|
+
const rawSplitField = (_h = chartCfg.splitSeriesField) == null ? void 0 : _h.trim();
|
|
1052
|
+
const splitField = rawSplitField ? resolveAggregatableField(rawSplitField, fieldMap) : void 0;
|
|
1053
|
+
const splitTopN = clamp(chartCfg.splitSeriesTopN ?? 5, 1, import_constants.MAX_SPLIT_SERIES);
|
|
1054
|
+
const bucketChildAggs = {};
|
|
1055
|
+
if (metricDef) {
|
|
1056
|
+
bucketChildAggs.es_metric = metricDef;
|
|
1057
|
+
}
|
|
1058
|
+
if (splitField) {
|
|
1059
|
+
bucketChildAggs.es_split = {
|
|
1060
|
+
terms: {
|
|
1061
|
+
field: splitField,
|
|
1062
|
+
size: splitTopN,
|
|
1063
|
+
...canOrderByMetric ? { order: { es_metric: "desc" } } : {}
|
|
1064
|
+
},
|
|
1065
|
+
...metricDef ? { aggs: { es_metric: metricDef } } : {}
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
const hasChildAggs = Object.keys(bucketChildAggs).length > 0;
|
|
689
1069
|
if (defaultBucketType === "date_histogram") {
|
|
690
1070
|
const interval = chartCfg.calendarInterval ?? "auto";
|
|
1071
|
+
const intervalKey = interval !== "auto" && CALENDAR_UNIT_INTERVALS.has(interval) ? "calendar_interval" : "fixed_interval";
|
|
691
1072
|
const bucketAgg = interval === "auto" ? {
|
|
692
1073
|
auto_date_histogram: {
|
|
693
1074
|
field: bucketField,
|
|
694
|
-
buckets: 24
|
|
1075
|
+
buckets: 24,
|
|
1076
|
+
...effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}
|
|
695
1077
|
}
|
|
696
1078
|
} : {
|
|
697
1079
|
date_histogram: {
|
|
698
1080
|
field: bucketField,
|
|
699
|
-
|
|
700
|
-
min_doc_count: 0
|
|
1081
|
+
[intervalKey]: interval,
|
|
1082
|
+
min_doc_count: 0,
|
|
1083
|
+
...effectiveTimeZone ? { time_zone: effectiveTimeZone } : {}
|
|
701
1084
|
}
|
|
702
1085
|
};
|
|
703
1086
|
body.aggs = {
|
|
704
1087
|
es_buckets: {
|
|
705
1088
|
...bucketAgg,
|
|
706
|
-
...
|
|
1089
|
+
...hasChildAggs ? { aggs: bucketChildAggs } : {}
|
|
707
1090
|
}
|
|
708
1091
|
};
|
|
709
1092
|
} else {
|
|
@@ -713,9 +1096,9 @@ function compileSearchRequest(options) {
|
|
|
713
1096
|
terms: {
|
|
714
1097
|
field: bucketField,
|
|
715
1098
|
size: topN,
|
|
716
|
-
...
|
|
1099
|
+
...canOrderByMetric ? { order: { es_metric: "desc" } } : {}
|
|
717
1100
|
},
|
|
718
|
-
...
|
|
1101
|
+
...hasChildAggs ? { aggs: bucketChildAggs } : {}
|
|
719
1102
|
}
|
|
720
1103
|
};
|
|
721
1104
|
}
|
|
@@ -748,9 +1131,23 @@ function buildDefaultMetricLabel(spec) {
|
|
|
748
1131
|
return field ? `${metricType.toUpperCase()}(${field})` : metricType.toUpperCase();
|
|
749
1132
|
}
|
|
750
1133
|
function parseSearchResponse(rawResponse, compiledDsl, spec, timeField) {
|
|
751
|
-
var _a, _b;
|
|
1134
|
+
var _a, _b, _c, _d;
|
|
752
1135
|
const res = isRecord(rawResponse) ? rawResponse : {};
|
|
753
1136
|
const tookMs = typeof res.took === "number" ? res.took : 0;
|
|
1137
|
+
const timedOut = res.timed_out === true;
|
|
1138
|
+
const shards = isRecord(res._shards) ? {
|
|
1139
|
+
total: typeof res._shards.total === "number" ? res._shards.total : 0,
|
|
1140
|
+
successful: typeof res._shards.successful === "number" ? res._shards.successful : 0,
|
|
1141
|
+
skipped: typeof res._shards.skipped === "number" ? res._shards.skipped : 0,
|
|
1142
|
+
failed: typeof res._shards.failed === "number" ? res._shards.failed : 0
|
|
1143
|
+
} : void 0;
|
|
1144
|
+
const warnings = [];
|
|
1145
|
+
if (timedOut) {
|
|
1146
|
+
warnings.push("Elasticsearch query timed out; displayed results may be incomplete.");
|
|
1147
|
+
}
|
|
1148
|
+
if (shards && shards.failed > 0) {
|
|
1149
|
+
warnings.push(`Partial results: ${shards.failed} of ${shards.total} Elasticsearch shards failed.`);
|
|
1150
|
+
}
|
|
754
1151
|
const hitsContainer = isRecord(res.hits) ? res.hits : {};
|
|
755
1152
|
const rawTotal = hitsContainer.total;
|
|
756
1153
|
let total = 0;
|
|
@@ -801,51 +1198,93 @@ function parseSearchResponse(rawResponse, compiledDsl, spec, timeField) {
|
|
|
801
1198
|
});
|
|
802
1199
|
}
|
|
803
1200
|
}
|
|
1201
|
+
const metricType = ((_a = spec.chart) == null ? void 0 : _a.metricType) ?? "count";
|
|
804
1202
|
const series = [];
|
|
1203
|
+
const seenSeriesKeys = /* @__PURE__ */ new Set();
|
|
805
1204
|
if (isRecord(aggs.es_buckets) && Array.isArray(aggs.es_buckets.buckets)) {
|
|
806
1205
|
for (const bucket of aggs.es_buckets.buckets) {
|
|
807
1206
|
if (!isRecord(bucket)) continue;
|
|
808
1207
|
const label = typeof bucket.key_as_string === "string" ? bucket.key_as_string : String(bucket.key ?? "");
|
|
809
1208
|
const docCount = typeof bucket.doc_count === "number" ? bucket.doc_count : 0;
|
|
810
|
-
const
|
|
811
|
-
const metricVal =
|
|
1209
|
+
const extracted = extractMetricValue(bucket.es_metric, metricType, docCount);
|
|
1210
|
+
const metricVal = extracted ?? docCount;
|
|
1211
|
+
let breakdown;
|
|
1212
|
+
if (isRecord(bucket.es_split) && Array.isArray(bucket.es_split.buckets)) {
|
|
1213
|
+
breakdown = [];
|
|
1214
|
+
for (const sub of bucket.es_split.buckets) {
|
|
1215
|
+
if (!isRecord(sub)) continue;
|
|
1216
|
+
const sKey = typeof sub.key_as_string === "string" ? sub.key_as_string : String(sub.key ?? "");
|
|
1217
|
+
const sCount = typeof sub.doc_count === "number" ? sub.doc_count : 0;
|
|
1218
|
+
const sVal = extractMetricValue(sub.es_metric, metricType, sCount) ?? sCount;
|
|
1219
|
+
seenSeriesKeys.add(sKey);
|
|
1220
|
+
breakdown.push({
|
|
1221
|
+
seriesKey: sKey,
|
|
1222
|
+
value: sVal,
|
|
1223
|
+
count: sCount
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
812
1227
|
series.push({
|
|
813
1228
|
key: String(bucket.key ?? label),
|
|
814
1229
|
label,
|
|
815
1230
|
value: metricVal,
|
|
816
|
-
count: docCount
|
|
1231
|
+
count: docCount,
|
|
1232
|
+
...breakdown ? { breakdown } : {}
|
|
817
1233
|
});
|
|
818
1234
|
}
|
|
819
1235
|
}
|
|
820
1236
|
let metricValue = null;
|
|
1237
|
+
let previousMetricValue;
|
|
1238
|
+
let deltaPercent;
|
|
821
1239
|
if (spec.visualization === "metric") {
|
|
822
|
-
|
|
823
|
-
|
|
1240
|
+
if (isRecord(aggs.es_current_window) && isRecord(aggs.es_previous_window)) {
|
|
1241
|
+
const curCount = typeof aggs.es_current_window.doc_count === "number" ? aggs.es_current_window.doc_count : 0;
|
|
1242
|
+
const prevCount = typeof aggs.es_previous_window.doc_count === "number" ? aggs.es_previous_window.doc_count : 0;
|
|
1243
|
+
total = curCount;
|
|
1244
|
+
totalRelation = "eq";
|
|
1245
|
+
metricValue = metricType === "count" || !((_b = spec.chart) == null ? void 0 : _b.metricField) ? curCount : extractMetricValue(aggs.es_current_window.es_metric, metricType, curCount);
|
|
1246
|
+
previousMetricValue = metricType === "count" || !((_c = spec.chart) == null ? void 0 : _c.metricField) ? prevCount : extractMetricValue(aggs.es_previous_window.es_metric, metricType, prevCount);
|
|
1247
|
+
if (metricValue !== null && previousMetricValue !== null && previousMetricValue !== 0) {
|
|
1248
|
+
deltaPercent = Number(((metricValue - previousMetricValue) / Math.abs(previousMetricValue) * 100).toFixed(2));
|
|
1249
|
+
} else {
|
|
1250
|
+
deltaPercent = null;
|
|
1251
|
+
}
|
|
1252
|
+
} else if (metricType === "count" || !((_d = spec.chart) == null ? void 0 : _d.metricField)) {
|
|
824
1253
|
metricValue = total;
|
|
825
|
-
} else
|
|
826
|
-
metricValue =
|
|
1254
|
+
} else {
|
|
1255
|
+
metricValue = extractMetricValue(aggs.es_metric, metricType, total);
|
|
827
1256
|
}
|
|
828
1257
|
}
|
|
1258
|
+
const responsePitId = typeof res.pit_id === "string" && res.pit_id ? res.pit_id : void 0;
|
|
829
1259
|
return {
|
|
830
1260
|
total,
|
|
831
1261
|
totalRelation,
|
|
832
1262
|
tookMs,
|
|
1263
|
+
...timedOut ? { timedOut: true } : {},
|
|
1264
|
+
...shards ? { shards } : {},
|
|
1265
|
+
...warnings.length > 0 ? { warnings } : {},
|
|
833
1266
|
visualization: spec.visualization,
|
|
834
1267
|
rows,
|
|
835
1268
|
columns,
|
|
836
1269
|
...nextSearchAfter ? { nextSearchAfter } : {},
|
|
1270
|
+
...responsePitId ? { pitId: responsePitId } : {},
|
|
837
1271
|
series,
|
|
1272
|
+
...seenSeriesKeys.size > 0 ? { seriesKeys: Array.from(seenSeriesKeys) } : {},
|
|
838
1273
|
histogram,
|
|
839
1274
|
metricValue,
|
|
1275
|
+
...previousMetricValue !== void 0 ? { previousMetricValue } : {},
|
|
1276
|
+
...deltaPercent !== void 0 ? { deltaPercent } : {},
|
|
840
1277
|
metricLabel: buildDefaultMetricLabel(spec),
|
|
841
1278
|
compiledDsl
|
|
842
1279
|
};
|
|
843
1280
|
}
|
|
844
1281
|
// Annotate the CommonJS export names for ESM import in node:
|
|
845
1282
|
0 && (module.exports = {
|
|
1283
|
+
KqlSyntaxError,
|
|
846
1284
|
buildFieldCapabilityMap,
|
|
847
1285
|
compileFilterItem,
|
|
848
1286
|
compileKqlToQueryDsl,
|
|
1287
|
+
compilePreviousTimeRange,
|
|
849
1288
|
compileSearchRequest,
|
|
850
1289
|
compileTimeRange,
|
|
851
1290
|
mergeSpecWithOverrides,
|
|
@@ -854,5 +1293,7 @@ function parseSearchResponse(rawResponse, compiledDsl, spec, timeField) {
|
|
|
854
1293
|
normalizeReportSpec,
|
|
855
1294
|
normalizeTimeRange,
|
|
856
1295
|
parseSearchResponse,
|
|
857
|
-
resolveAggregatableField
|
|
1296
|
+
resolveAggregatableField,
|
|
1297
|
+
resolveServerLockedFilters,
|
|
1298
|
+
sanitizeTimeZone
|
|
858
1299
|
});
|