plugin-elastic-report 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/client-v2.d.ts +2 -2
  2. package/client-v2.js +1 -1
  3. package/client.d.ts +2 -2
  4. package/client.js +1 -1
  5. package/{ai → dist/ai}/skills/elastic-report/SKILLS.md +52 -34
  6. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  7. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +2 -1
  10. package/dist/locale/en-US.json +213 -198
  11. package/dist/locale/vi-VN.json +213 -198
  12. package/dist/locale/zh-CN.json +213 -198
  13. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  14. package/dist/server/mcp/ElasticReportToolCatalog.js +6 -4
  15. package/dist/server/plugin.js +4 -4
  16. package/dist/server/report-block-tools.js +340 -0
  17. package/dist/server/services/ElasticReportService.js +12 -6
  18. package/dist/shared/constants.js +9 -0
  19. package/package.json +2 -3
  20. package/server.d.ts +2 -2
  21. package/server.js +1 -1
  22. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  23. package/src/client/index.tsx +34 -34
  24. package/src/client/workflow-instructions.tsx +44 -44
  25. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -791
  26. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -178
  27. package/src/client-v2/api.ts +320 -320
  28. package/src/client-v2/bus/DashboardFilterBus.ts +212 -212
  29. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -652
  30. package/src/client-v2/components/ElasticFilterBar.tsx +372 -372
  31. package/src/client-v2/components/ElasticKqlInput.tsx +421 -421
  32. package/src/client-v2/components/ElasticReportBlock.tsx +306 -306
  33. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -1257
  34. package/src/client-v2/components/HighlightText.tsx +50 -50
  35. package/src/client-v2/components/ReportSelect.tsx +85 -85
  36. package/src/client-v2/index.tsx +14 -14
  37. package/src/client-v2/locale.ts +23 -23
  38. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -115
  39. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -118
  40. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1453
  41. package/src/client-v2/plugin.tsx +107 -72
  42. package/src/client-v2/report-destination.tsx +126 -0
  43. package/src/client-v2/utils/kqlAutocomplete.ts +861 -861
  44. package/src/client-v2/workflow/instructions.tsx +149 -149
  45. package/src/index.ts +11 -11
  46. package/src/locale/en-US.json +213 -198
  47. package/src/locale/vi-VN.json +213 -198
  48. package/src/locale/zh-CN.json +213 -198
  49. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  50. package/src/server/__tests__/query-compiler.test.ts +620 -620
  51. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -645
  52. package/src/server/acl-guard.ts +194 -194
  53. package/src/server/collections/es-report-data-views.ts +64 -64
  54. package/src/server/collections/es-reports.ts +80 -80
  55. package/src/server/index.ts +15 -15
  56. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  57. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -663
  58. package/src/server/plugin.ts +599 -599
  59. package/src/server/report-block-tools.ts +400 -0
  60. package/src/server/services/ElasticReportService.ts +494 -486
  61. package/src/server/services/ElasticsearchConnectionService.ts +728 -728
  62. package/src/server/services/ReportExportService.ts +282 -282
  63. package/src/server/services/ReportQueryCompiler.ts +1552 -1552
  64. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -124
  65. package/src/shared/constants.ts +39 -36
  66. package/src/shared/types.ts +272 -272
  67. package/dist/client-v2/851.142c93fc6d666b28.js +0 -10
  68. package/dist/client-v2/877.f4095a3dbcadf98f.js +0 -10
  69. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  70. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,620 +1,620 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import { describe, expect, it } from 'vitest';
11
- import { HIGHLIGHT_POST_TAG, HIGHLIGHT_PRE_TAG } from '../../shared/constants';
12
- import type { EsFieldCapability } from '../../shared/types';
13
- import { buildEsClientOptions, inferConnectionModes } from '../services/ElasticsearchConnectionService';
14
- import { escapeCsvCell } from '../services/ReportExportService';
15
- import {
16
- KqlSyntaxError,
17
- buildFieldCapabilityMap,
18
- compileKqlToQueryDsl,
19
- compileSearchRequest,
20
- normalizeReportSpec,
21
- parseSearchResponse,
22
- resolveServerLockedFilters,
23
- } from '../services/ReportQueryCompiler';
24
- import { evaluateThreshold } from '../workflow/ElasticReportQueryInstruction';
25
-
26
- const SAMPLE_FIELDS: EsFieldCapability[] = [
27
- { name: '@timestamp', type: 'date', searchable: true, aggregatable: true },
28
- {
29
- name: 'service',
30
- type: 'text',
31
- searchable: true,
32
- aggregatable: false,
33
- keywordSubfield: 'service.keyword',
34
- },
35
- {
36
- name: 'service.keyword',
37
- type: 'keyword',
38
- searchable: true,
39
- aggregatable: true,
40
- isSubfield: true,
41
- },
42
- { name: 'status', type: 'integer', searchable: true, aggregatable: true },
43
- { name: 'latency_ms', type: 'double', searchable: true, aggregatable: true },
44
- ];
45
-
46
- describe('ReportQueryCompiler', () => {
47
- it('compiles KQL boolean, range, wildcard, exists, and phrase clauses accurately', () => {
48
- const fieldMap = buildFieldCapabilityMap(SAMPLE_FIELDS);
49
-
50
- const dsl = compileKqlToQueryDsl(
51
- 'status >= 500 AND (service: "checkout-api" OR service: auth*) AND NOT trace_id: *',
52
- fieldMap,
53
- );
54
-
55
- expect(dsl).toEqual({
56
- bool: {
57
- must: [
58
- { range: { status: { gte: 500 } } },
59
- {
60
- bool: {
61
- should: [
62
- { match_phrase: { service: 'checkout-api' } },
63
- { wildcard: { 'service.keyword': { value: 'auth*', case_insensitive: true } } },
64
- ],
65
- minimum_should_match: 1,
66
- },
67
- },
68
- {
69
- bool: {
70
- must_not: [{ exists: { field: 'trace_id' } }],
71
- },
72
- },
73
- ],
74
- },
75
- });
76
- });
77
-
78
- it('resolves .keyword subfield automatically for filters and sorts on text fields', () => {
79
- const spec = normalizeReportSpec({
80
- visualization: 'table',
81
- query: 'timeout',
82
- filters: [
83
- { field: 'service', operator: 'eq', value: 'payment' },
84
- { field: 'status', operator: 'ne', value: 200 },
85
- ],
86
- sort: [{ field: 'service', order: 'asc' }],
87
- timeRange: { preset: 'last_1h' },
88
- columns: ['@timestamp', 'service', 'status'],
89
- pageSize: 25,
90
- });
91
-
92
- const { body } = compileSearchRequest({
93
- spec,
94
- timeField: '@timestamp',
95
- fields: SAMPLE_FIELDS,
96
- });
97
-
98
- expect(body.size).toBe(25);
99
- expect(body.sort).toEqual([
100
- { 'service.keyword': { order: 'asc', unmapped_type: 'keyword' } },
101
- { _doc: { order: 'asc' } },
102
- ]);
103
- expect(body.query).toEqual({
104
- bool: {
105
- must: [
106
- {
107
- simple_query_string: {
108
- query: 'timeout',
109
- default_operator: 'and',
110
- lenient: true,
111
- },
112
- },
113
- ],
114
- filter: [
115
- { term: { 'service.keyword': 'payment' } },
116
- { range: { '@timestamp': { gte: 'now-1h', lte: 'now' } } },
117
- ],
118
- must_not: [{ term: { status: 200 } }],
119
- },
120
- });
121
- expect(body.aggs).toEqual({
122
- es_time_histogram: {
123
- auto_date_histogram: {
124
- field: '@timestamp',
125
- buckets: 24,
126
- },
127
- },
128
- });
129
- });
130
-
131
- it('supports search_after cursor pagination and chart bucket/metric aggregations', () => {
132
- const tableSpec = normalizeReportSpec({
133
- visualization: 'table',
134
- sort: [{ field: '@timestamp', order: 'desc' }],
135
- });
136
-
137
- const paged = compileSearchRequest({
138
- spec: tableSpec,
139
- overrides: { searchAfter: [1730000000000] },
140
- timeField: '@timestamp',
141
- fields: SAMPLE_FIELDS,
142
- });
143
- expect(paged.body.search_after).toEqual([1730000000000]);
144
- expect(paged.body.from).toBeUndefined();
145
-
146
- const barSpec = normalizeReportSpec({
147
- visualization: 'bar',
148
- chart: {
149
- bucketType: 'terms',
150
- bucketField: 'service',
151
- topN: 5,
152
- metricType: 'avg',
153
- metricField: 'latency_ms',
154
- metricLabel: 'Avg Latency (ms)',
155
- },
156
- });
157
-
158
- const { body: chartBody, effectiveSpec } = compileSearchRequest({
159
- spec: barSpec,
160
- timeField: '@timestamp',
161
- fields: SAMPLE_FIELDS,
162
- });
163
-
164
- expect(chartBody.size).toBe(0);
165
- expect(chartBody.aggs).toEqual({
166
- es_buckets: {
167
- terms: {
168
- field: 'service.keyword',
169
- size: 5,
170
- order: { es_metric: 'desc' },
171
- },
172
- aggs: {
173
- es_metric: {
174
- avg: { field: 'latency_ms' },
175
- },
176
- },
177
- },
178
- });
179
-
180
- const parsed = parseSearchResponse(
181
- {
182
- took: 7,
183
- hits: { total: { value: 42, relation: 'eq' }, hits: [] },
184
- aggregations: {
185
- es_buckets: {
186
- buckets: [
187
- { key: 'checkout', doc_count: 30, es_metric: { value: 123.45678 } },
188
- { key: 'search', doc_count: 12, es_metric: { value: 48.5 } },
189
- ],
190
- },
191
- },
192
- },
193
- chartBody,
194
- effectiveSpec,
195
- '@timestamp',
196
- );
197
-
198
- expect(parsed.total).toBe(42);
199
- expect(parsed.metricLabel).toBe('Avg Latency (ms)');
200
- expect(parsed.series).toEqual([
201
- { key: 'checkout', label: 'checkout', value: 123.4568, count: 30 },
202
- { key: 'search', label: 'search', value: 48.5, count: 12 },
203
- ]);
204
- });
205
-
206
- it('extracts document rows, cursor sort values, and safe highlight tokens', () => {
207
- const spec = normalizeReportSpec({ visualization: 'table', query: 'error' });
208
- const parsed = parseSearchResponse(
209
- {
210
- took: 3,
211
- hits: {
212
- total: { value: 1, relation: 'eq' },
213
- hits: [
214
- {
215
- _id: 'doc-1',
216
- _index: 'logs-2026.11',
217
- sort: [1732900000000],
218
- _source: {
219
- '@timestamp': '2026-11-30T00:00:00Z',
220
- message: 'Upstream error timeout',
221
- },
222
- highlight: {
223
- message: [`Upstream ${HIGHLIGHT_PRE_TAG}error${HIGHLIGHT_POST_TAG} timeout`],
224
- },
225
- },
226
- ],
227
- },
228
- },
229
- { query: { match_all: {} } },
230
- spec,
231
- '@timestamp',
232
- );
233
-
234
- expect(parsed.rows).toHaveLength(1);
235
- expect(parsed.nextSearchAfter).toEqual([1732900000000]);
236
- expect(parsed.columns).toEqual(['@timestamp', 'message']);
237
- expect(parsed.rows[0].highlights?.message?.[0]).toContain(HIGHLIGHT_PRE_TAG);
238
- });
239
-
240
- it('uses track_total_hits: true for KPI metric count and fixed_interval for 5m/15m date histograms', () => {
241
- const metricSpec = normalizeReportSpec({
242
- visualization: 'metric',
243
- chart: { metricType: 'count' },
244
- });
245
- const { body: metricBody } = compileSearchRequest({
246
- spec: metricSpec,
247
- timeField: '@timestamp',
248
- fields: SAMPLE_FIELDS,
249
- });
250
- expect(metricBody.size).toBe(0);
251
- expect(metricBody.track_total_hits).toBe(true);
252
-
253
- const line5m = compileSearchRequest({
254
- spec: normalizeReportSpec({
255
- visualization: 'line',
256
- chart: { bucketType: 'date_histogram', calendarInterval: '5m' },
257
- }),
258
- timeField: '@timestamp',
259
- fields: SAMPLE_FIELDS,
260
- });
261
- expect(line5m.body.aggs).toEqual({
262
- es_buckets: {
263
- date_histogram: {
264
- field: '@timestamp',
265
- fixed_interval: '5m',
266
- min_doc_count: 0,
267
- },
268
- },
269
- });
270
-
271
- const line15m = compileSearchRequest({
272
- spec: normalizeReportSpec({
273
- visualization: 'area',
274
- chart: { bucketType: 'date_histogram', calendarInterval: '15m' },
275
- }),
276
- timeField: '@timestamp',
277
- fields: SAMPLE_FIELDS,
278
- });
279
- expect(line15m.body.aggs).toEqual({
280
- es_buckets: {
281
- date_histogram: {
282
- field: '@timestamp',
283
- fixed_interval: '15m',
284
- min_doc_count: 0,
285
- },
286
- },
287
- });
288
-
289
- const line1h = compileSearchRequest({
290
- spec: normalizeReportSpec({
291
- visualization: 'line',
292
- chart: { bucketType: 'date_histogram', calendarInterval: '1h' },
293
- }),
294
- timeField: '@timestamp',
295
- fields: SAMPLE_FIELDS,
296
- });
297
- expect(line1h.body.aggs).toEqual({
298
- es_buckets: {
299
- date_histogram: {
300
- field: '@timestamp',
301
- calendar_interval: '1h',
302
- min_doc_count: 0,
303
- },
304
- },
305
- });
306
- });
307
-
308
- it('supports KQL field value groups and throws KqlSyntaxError on invalid KQL syntax', () => {
309
- const fieldMap = buildFieldCapabilityMap(SAMPLE_FIELDS);
310
-
311
- expect(compileKqlToQueryDsl('status: (400 OR 404)', fieldMap)).toEqual({
312
- bool: {
313
- should: [{ term: { status: 400 } }, { term: { status: 404 } }],
314
- minimum_should_match: 1,
315
- },
316
- });
317
-
318
- expect(
319
- compileKqlToQueryDsl('service: ("checkout-api" OR auth*) AND latency_ms: (>= 100 AND < 500)', fieldMap),
320
- ).toEqual({
321
- bool: {
322
- must: [
323
- {
324
- bool: {
325
- should: [
326
- { match_phrase: { service: 'checkout-api' } },
327
- { wildcard: { 'service.keyword': { value: 'auth*', case_insensitive: true } } },
328
- ],
329
- minimum_should_match: 1,
330
- },
331
- },
332
- {
333
- bool: {
334
- must: [{ range: { latency_ms: { gte: 100 } } }, { range: { latency_ms: { lt: 500 } } }],
335
- },
336
- },
337
- ],
338
- },
339
- });
340
-
341
- expect(() => compileKqlToQueryDsl('status: (400 OR', fieldMap)).toThrow(KqlSyntaxError);
342
- expect(() => compileKqlToQueryDsl('status: [400 TO 499]', fieldMap)).toThrow(KqlSyntaxError);
343
- expect(() => compileKqlToQueryDsl('service: "unclosed', fieldMap)).toThrow(KqlSyntaxError);
344
- expect(() => compileKqlToQueryDsl('AND status: 500', fieldMap)).toThrow(KqlSyntaxError);
345
- expect(() => compileKqlToQueryDsl('status:', fieldMap)).toThrow(KqlSyntaxError);
346
- });
347
-
348
- it('enforces server lockedFilters regardless of viewer overrides and surfaces timeout/shard warnings', () => {
349
- const spec = normalizeReportSpec({
350
- visualization: 'table',
351
- lockedFilters: [{ field: 'service', operator: 'eq', value: 'tenant-a' }],
352
- filters: [{ field: 'status', operator: 'gte', value: 400 }],
353
- timeRange: { preset: 'custom', from: '2026-11-29T00:00:00Z', to: '2026-11-30T00:00:00Z' },
354
- });
355
-
356
- const { body } = compileSearchRequest({
357
- spec,
358
- overrides: {
359
- query: '',
360
- filters: [],
361
- timeRange: { preset: 'custom', from: '2026-11-29T00:00:00Z', to: '2026-11-30T00:00:00Z' },
362
- },
363
- timeField: '@timestamp',
364
- fields: SAMPLE_FIELDS,
365
- });
366
-
367
- expect(body.query).toEqual({
368
- bool: {
369
- filter: [
370
- { term: { 'service.keyword': 'tenant-a' } },
371
- { range: { '@timestamp': { gte: '2026-11-29T00:00:00Z', lte: '2026-11-30T00:00:00Z' } } },
372
- ],
373
- },
374
- });
375
-
376
- const partial = parseSearchResponse(
377
- {
378
- took: 950,
379
- timed_out: true,
380
- _shards: { total: 5, successful: 4, skipped: 0, failed: 1 },
381
- hits: { total: { value: 10000, relation: 'gte' }, hits: [] },
382
- },
383
- body,
384
- spec,
385
- '@timestamp',
386
- );
387
- expect(partial.timedOut).toBe(true);
388
- expect(partial.shards).toEqual({ total: 5, successful: 4, skipped: 0, failed: 1 });
389
- expect(partial.warnings).toHaveLength(2);
390
- });
391
-
392
- it('propagates IANA time_zone, _shard_doc PIT tie-breaker, p95 percentiles, and splitSeriesField breakdown', () => {
393
- const pitTable = compileSearchRequest({
394
- spec: normalizeReportSpec({
395
- visualization: 'table',
396
- timeRange: { preset: 'last_24h' },
397
- }),
398
- overrides: {
399
- timeZone: 'Asia/Ho_Chi_Minh',
400
- },
401
- timeField: '@timestamp',
402
- fields: SAMPLE_FIELDS,
403
- usePit: true,
404
- });
405
-
406
- expect(pitTable.body.sort).toEqual([
407
- { '@timestamp': { order: 'desc', unmapped_type: 'date' } },
408
- { _shard_doc: { order: 'asc' } },
409
- ]);
410
- expect(pitTable.body.query).toEqual({
411
- bool: {
412
- filter: [{ range: { '@timestamp': { gte: 'now-24h', lte: 'now', time_zone: 'Asia/Ho_Chi_Minh' } } }],
413
- },
414
- });
415
- expect(pitTable.body.aggs).toEqual({
416
- es_time_histogram: {
417
- auto_date_histogram: {
418
- field: '@timestamp',
419
- buckets: 24,
420
- time_zone: 'Asia/Ho_Chi_Minh',
421
- },
422
- },
423
- });
424
-
425
- const splitChartSpec = normalizeReportSpec({
426
- visualization: 'bar',
427
- chart: {
428
- bucketType: 'date_histogram',
429
- calendarInterval: '1h',
430
- metricType: 'p95',
431
- metricField: 'latency_ms',
432
- splitSeriesField: 'service',
433
- splitSeriesTopN: 3,
434
- stackMode: 'stacked',
435
- },
436
- });
437
-
438
- const { body: splitBody, effectiveSpec } = compileSearchRequest({
439
- spec: splitChartSpec,
440
- overrides: { timeZone: 'Asia/Ho_Chi_Minh' },
441
- timeField: '@timestamp',
442
- fields: SAMPLE_FIELDS,
443
- });
444
-
445
- expect(splitBody.aggs).toEqual({
446
- es_buckets: {
447
- date_histogram: {
448
- field: '@timestamp',
449
- calendar_interval: '1h',
450
- min_doc_count: 0,
451
- time_zone: 'Asia/Ho_Chi_Minh',
452
- },
453
- aggs: {
454
- es_metric: {
455
- percentiles: { field: 'latency_ms', percents: [95] },
456
- },
457
- es_split: {
458
- terms: { field: 'service.keyword', size: 3 },
459
- aggs: {
460
- es_metric: {
461
- percentiles: { field: 'latency_ms', percents: [95] },
462
- },
463
- },
464
- },
465
- },
466
- },
467
- });
468
-
469
- const parsedSplit = parseSearchResponse(
470
- {
471
- took: 6,
472
- hits: { total: { value: 50, relation: 'eq' }, hits: [] },
473
- aggregations: {
474
- es_buckets: {
475
- buckets: [
476
- {
477
- key_as_string: '2026-11-30T01:00:00+07:00',
478
- key: 1732903200000,
479
- doc_count: 50,
480
- es_metric: { values: { '95.0': 412.5 } },
481
- es_split: {
482
- buckets: [
483
- { key: 'checkout', doc_count: 30, es_metric: { values: { '95.0': 480.25 } } },
484
- { key: 'catalog', doc_count: 20, es_metric: { values: { '95.0': 190.5 } } },
485
- ],
486
- },
487
- },
488
- ],
489
- },
490
- },
491
- },
492
- splitBody,
493
- effectiveSpec,
494
- '@timestamp',
495
- );
496
-
497
- expect(parsedSplit.seriesKeys).toEqual(['checkout', 'catalog']);
498
- expect(parsedSplit.series).toEqual([
499
- {
500
- key: '1732903200000',
501
- label: '2026-11-30T01:00:00+07:00',
502
- value: 412.5,
503
- count: 50,
504
- breakdown: [
505
- { seriesKey: 'checkout', value: 480.25, count: 30 },
506
- { seriesKey: 'catalog', value: 190.5, count: 20 },
507
- ],
508
- },
509
- ]);
510
- });
511
-
512
- it('compiles single-call KPI comparePreviousPeriod dual-window aggregations and computes deltaPercent', () => {
513
- const kpiSpec = normalizeReportSpec({
514
- visualization: 'metric',
515
- timeRange: { preset: 'last_24h' },
516
- chart: {
517
- metricType: 'avg',
518
- metricField: 'latency_ms',
519
- comparePreviousPeriod: true,
520
- },
521
- });
522
-
523
- const { body, effectiveSpec } = compileSearchRequest({
524
- spec: kpiSpec,
525
- timeField: '@timestamp',
526
- fields: SAMPLE_FIELDS,
527
- });
528
-
529
- expect(body.aggs).toEqual({
530
- es_current_window: {
531
- filter: { range: { '@timestamp': { gte: 'now-24h', lte: 'now' } } },
532
- aggs: { es_metric: { avg: { field: 'latency_ms' } } },
533
- },
534
- es_previous_window: {
535
- filter: { range: { '@timestamp': { gte: 'now-48h', lt: 'now-24h' } } },
536
- aggs: { es_metric: { avg: { field: 'latency_ms' } } },
537
- },
538
- });
539
-
540
- const parsed = parseSearchResponse(
541
- {
542
- took: 4,
543
- hits: { total: { value: 200, relation: 'eq' }, hits: [] },
544
- aggregations: {
545
- es_current_window: { doc_count: 120, es_metric: { value: 250 } },
546
- es_previous_window: { doc_count: 80, es_metric: { value: 200 } },
547
- },
548
- },
549
- body,
550
- effectiveSpec,
551
- '@timestamp',
552
- );
553
-
554
- expect(parsed.metricValue).toBe(250);
555
- expect(parsed.previousMetricValue).toBe(200);
556
- expect(parsed.deltaPercent).toBe(25);
557
- });
558
-
559
- it('resolves server lockedFilters user tokens, neutralizes CSV formula injection, and evaluates workflow thresholds', () => {
560
- const resolved = resolveServerLockedFilters(
561
- [
562
- { field: 'tenant_user_id', operator: 'eq', value: '{{$user.id}}' },
563
- { field: 'department', operator: 'eq', value: '{{ $role }}' },
564
- ],
565
- { userId: 7, username: 'alice', role: 'finance-viewer' },
566
- );
567
- expect(resolved).toEqual([
568
- { field: 'tenant_user_id', operator: 'eq', value: 7, enabled: true },
569
- { field: 'department', operator: 'eq', value: 'finance-viewer', enabled: true },
570
- ]);
571
-
572
- expect(() =>
573
- resolveServerLockedFilters([{ field: 'owner_email', operator: 'eq', value: '{{$user.email}}' }], {
574
- userId: 7,
575
- }),
576
- ).toThrow(/Permission denied/);
577
-
578
- // CSV formula-injection neutralization preserves negative numbers and ECS @timestamp header while escaping =, +, -, @ formulas
579
- expect(escapeCsvCell("=CMD|' /C calc'!A0")).toBe("'=CMD|' /C calc'!A0");
580
- expect(escapeCsvCell('@SUM(A1:A5)')).toBe("'@SUM(A1:A5)");
581
- expect(escapeCsvCell('@timestamp', { allowAtIdentifier: true })).toBe('@timestamp');
582
- expect(escapeCsvCell('@SUM(A1:A5)', { allowAtIdentifier: true })).toBe("'@SUM(A1:A5)");
583
- expect(escapeCsvCell('-42.5')).toBe('-42.5');
584
- expect(escapeCsvCell(-42.5)).toBe('-42.5');
585
- expect(escapeCsvCell('hello, "world"')).toBe('"hello, ""world"""');
586
-
587
- // Workflow threshold evaluation
588
- expect(evaluateThreshold(15, 'gte', 10)).toBe(true);
589
- expect(evaluateThreshold(5, 'gte', 10)).toBe(false);
590
- expect(evaluateThreshold(null, 'gt', 0)).toBe(false);
591
- });
592
-
593
- it('synchronizes ES 8.x connection options (CA fingerprint, PEM, Bearer token, Cloud ID) in ElasticsearchConnectionService', () => {
594
- const fp = 'AA:BB:' + '11'.repeat(30);
595
- const opts = buildEsClientOptions({
596
- nodes: 'https://es8-node:9200',
597
- authMode: 'bearer',
598
- bearerToken: 'aae_token_xyz',
599
- tlsMode: 'caFingerprint',
600
- caFingerprint: fp,
601
- requestTimeoutMs: 25000,
602
- maxRetries: 4,
603
- compression: true,
604
- });
605
- expect(opts).toMatchObject({
606
- nodes: ['https://es8-node:9200'],
607
- auth: { bearer: 'aae_token_xyz' },
608
- caFingerprint: 'aabb' + '11'.repeat(30),
609
- tls: { rejectUnauthorized: false },
610
- requestTimeout: 25000,
611
- maxRetries: 4,
612
- compression: true,
613
- });
614
- expect(inferConnectionModes({ hasApiKey: true, hasCaCert: true })).toEqual({
615
- endpointMode: 'nodes',
616
- authMode: 'apiKey',
617
- tlsMode: 'caCert',
618
- });
619
- });
620
- });
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { describe, expect, it } from 'vitest';
11
+ import { HIGHLIGHT_POST_TAG, HIGHLIGHT_PRE_TAG } from '../../shared/constants';
12
+ import type { EsFieldCapability } from '../../shared/types';
13
+ import { buildEsClientOptions, inferConnectionModes } from '../services/ElasticsearchConnectionService';
14
+ import { escapeCsvCell } from '../services/ReportExportService';
15
+ import {
16
+ KqlSyntaxError,
17
+ buildFieldCapabilityMap,
18
+ compileKqlToQueryDsl,
19
+ compileSearchRequest,
20
+ normalizeReportSpec,
21
+ parseSearchResponse,
22
+ resolveServerLockedFilters,
23
+ } from '../services/ReportQueryCompiler';
24
+ import { evaluateThreshold } from '../workflow/ElasticReportQueryInstruction';
25
+
26
+ const SAMPLE_FIELDS: EsFieldCapability[] = [
27
+ { name: '@timestamp', type: 'date', searchable: true, aggregatable: true },
28
+ {
29
+ name: 'service',
30
+ type: 'text',
31
+ searchable: true,
32
+ aggregatable: false,
33
+ keywordSubfield: 'service.keyword',
34
+ },
35
+ {
36
+ name: 'service.keyword',
37
+ type: 'keyword',
38
+ searchable: true,
39
+ aggregatable: true,
40
+ isSubfield: true,
41
+ },
42
+ { name: 'status', type: 'integer', searchable: true, aggregatable: true },
43
+ { name: 'latency_ms', type: 'double', searchable: true, aggregatable: true },
44
+ ];
45
+
46
+ describe('ReportQueryCompiler', () => {
47
+ it('compiles KQL boolean, range, wildcard, exists, and phrase clauses accurately', () => {
48
+ const fieldMap = buildFieldCapabilityMap(SAMPLE_FIELDS);
49
+
50
+ const dsl = compileKqlToQueryDsl(
51
+ 'status >= 500 AND (service: "checkout-api" OR service: auth*) AND NOT trace_id: *',
52
+ fieldMap,
53
+ );
54
+
55
+ expect(dsl).toEqual({
56
+ bool: {
57
+ must: [
58
+ { range: { status: { gte: 500 } } },
59
+ {
60
+ bool: {
61
+ should: [
62
+ { match_phrase: { service: 'checkout-api' } },
63
+ { wildcard: { 'service.keyword': { value: 'auth*', case_insensitive: true } } },
64
+ ],
65
+ minimum_should_match: 1,
66
+ },
67
+ },
68
+ {
69
+ bool: {
70
+ must_not: [{ exists: { field: 'trace_id' } }],
71
+ },
72
+ },
73
+ ],
74
+ },
75
+ });
76
+ });
77
+
78
+ it('resolves .keyword subfield automatically for filters and sorts on text fields', () => {
79
+ const spec = normalizeReportSpec({
80
+ visualization: 'table',
81
+ query: 'timeout',
82
+ filters: [
83
+ { field: 'service', operator: 'eq', value: 'payment' },
84
+ { field: 'status', operator: 'ne', value: 200 },
85
+ ],
86
+ sort: [{ field: 'service', order: 'asc' }],
87
+ timeRange: { preset: 'last_1h' },
88
+ columns: ['@timestamp', 'service', 'status'],
89
+ pageSize: 25,
90
+ });
91
+
92
+ const { body } = compileSearchRequest({
93
+ spec,
94
+ timeField: '@timestamp',
95
+ fields: SAMPLE_FIELDS,
96
+ });
97
+
98
+ expect(body.size).toBe(25);
99
+ expect(body.sort).toEqual([
100
+ { 'service.keyword': { order: 'asc', unmapped_type: 'keyword' } },
101
+ { _doc: { order: 'asc' } },
102
+ ]);
103
+ expect(body.query).toEqual({
104
+ bool: {
105
+ must: [
106
+ {
107
+ simple_query_string: {
108
+ query: 'timeout',
109
+ default_operator: 'and',
110
+ lenient: true,
111
+ },
112
+ },
113
+ ],
114
+ filter: [
115
+ { term: { 'service.keyword': 'payment' } },
116
+ { range: { '@timestamp': { gte: 'now-1h', lte: 'now' } } },
117
+ ],
118
+ must_not: [{ term: { status: 200 } }],
119
+ },
120
+ });
121
+ expect(body.aggs).toEqual({
122
+ es_time_histogram: {
123
+ auto_date_histogram: {
124
+ field: '@timestamp',
125
+ buckets: 24,
126
+ },
127
+ },
128
+ });
129
+ });
130
+
131
+ it('supports search_after cursor pagination and chart bucket/metric aggregations', () => {
132
+ const tableSpec = normalizeReportSpec({
133
+ visualization: 'table',
134
+ sort: [{ field: '@timestamp', order: 'desc' }],
135
+ });
136
+
137
+ const paged = compileSearchRequest({
138
+ spec: tableSpec,
139
+ overrides: { searchAfter: [1730000000000] },
140
+ timeField: '@timestamp',
141
+ fields: SAMPLE_FIELDS,
142
+ });
143
+ expect(paged.body.search_after).toEqual([1730000000000]);
144
+ expect(paged.body.from).toBeUndefined();
145
+
146
+ const barSpec = normalizeReportSpec({
147
+ visualization: 'bar',
148
+ chart: {
149
+ bucketType: 'terms',
150
+ bucketField: 'service',
151
+ topN: 5,
152
+ metricType: 'avg',
153
+ metricField: 'latency_ms',
154
+ metricLabel: 'Avg Latency (ms)',
155
+ },
156
+ });
157
+
158
+ const { body: chartBody, effectiveSpec } = compileSearchRequest({
159
+ spec: barSpec,
160
+ timeField: '@timestamp',
161
+ fields: SAMPLE_FIELDS,
162
+ });
163
+
164
+ expect(chartBody.size).toBe(0);
165
+ expect(chartBody.aggs).toEqual({
166
+ es_buckets: {
167
+ terms: {
168
+ field: 'service.keyword',
169
+ size: 5,
170
+ order: { es_metric: 'desc' },
171
+ },
172
+ aggs: {
173
+ es_metric: {
174
+ avg: { field: 'latency_ms' },
175
+ },
176
+ },
177
+ },
178
+ });
179
+
180
+ const parsed = parseSearchResponse(
181
+ {
182
+ took: 7,
183
+ hits: { total: { value: 42, relation: 'eq' }, hits: [] },
184
+ aggregations: {
185
+ es_buckets: {
186
+ buckets: [
187
+ { key: 'checkout', doc_count: 30, es_metric: { value: 123.45678 } },
188
+ { key: 'search', doc_count: 12, es_metric: { value: 48.5 } },
189
+ ],
190
+ },
191
+ },
192
+ },
193
+ chartBody,
194
+ effectiveSpec,
195
+ '@timestamp',
196
+ );
197
+
198
+ expect(parsed.total).toBe(42);
199
+ expect(parsed.metricLabel).toBe('Avg Latency (ms)');
200
+ expect(parsed.series).toEqual([
201
+ { key: 'checkout', label: 'checkout', value: 123.4568, count: 30 },
202
+ { key: 'search', label: 'search', value: 48.5, count: 12 },
203
+ ]);
204
+ });
205
+
206
+ it('extracts document rows, cursor sort values, and safe highlight tokens', () => {
207
+ const spec = normalizeReportSpec({ visualization: 'table', query: 'error' });
208
+ const parsed = parseSearchResponse(
209
+ {
210
+ took: 3,
211
+ hits: {
212
+ total: { value: 1, relation: 'eq' },
213
+ hits: [
214
+ {
215
+ _id: 'doc-1',
216
+ _index: 'logs-2026.11',
217
+ sort: [1732900000000],
218
+ _source: {
219
+ '@timestamp': '2026-11-30T00:00:00Z',
220
+ message: 'Upstream error timeout',
221
+ },
222
+ highlight: {
223
+ message: [`Upstream ${HIGHLIGHT_PRE_TAG}error${HIGHLIGHT_POST_TAG} timeout`],
224
+ },
225
+ },
226
+ ],
227
+ },
228
+ },
229
+ { query: { match_all: {} } },
230
+ spec,
231
+ '@timestamp',
232
+ );
233
+
234
+ expect(parsed.rows).toHaveLength(1);
235
+ expect(parsed.nextSearchAfter).toEqual([1732900000000]);
236
+ expect(parsed.columns).toEqual(['@timestamp', 'message']);
237
+ expect(parsed.rows[0].highlights?.message?.[0]).toContain(HIGHLIGHT_PRE_TAG);
238
+ });
239
+
240
+ it('uses track_total_hits: true for KPI metric count and fixed_interval for 5m/15m date histograms', () => {
241
+ const metricSpec = normalizeReportSpec({
242
+ visualization: 'metric',
243
+ chart: { metricType: 'count' },
244
+ });
245
+ const { body: metricBody } = compileSearchRequest({
246
+ spec: metricSpec,
247
+ timeField: '@timestamp',
248
+ fields: SAMPLE_FIELDS,
249
+ });
250
+ expect(metricBody.size).toBe(0);
251
+ expect(metricBody.track_total_hits).toBe(true);
252
+
253
+ const line5m = compileSearchRequest({
254
+ spec: normalizeReportSpec({
255
+ visualization: 'line',
256
+ chart: { bucketType: 'date_histogram', calendarInterval: '5m' },
257
+ }),
258
+ timeField: '@timestamp',
259
+ fields: SAMPLE_FIELDS,
260
+ });
261
+ expect(line5m.body.aggs).toEqual({
262
+ es_buckets: {
263
+ date_histogram: {
264
+ field: '@timestamp',
265
+ fixed_interval: '5m',
266
+ min_doc_count: 0,
267
+ },
268
+ },
269
+ });
270
+
271
+ const line15m = compileSearchRequest({
272
+ spec: normalizeReportSpec({
273
+ visualization: 'area',
274
+ chart: { bucketType: 'date_histogram', calendarInterval: '15m' },
275
+ }),
276
+ timeField: '@timestamp',
277
+ fields: SAMPLE_FIELDS,
278
+ });
279
+ expect(line15m.body.aggs).toEqual({
280
+ es_buckets: {
281
+ date_histogram: {
282
+ field: '@timestamp',
283
+ fixed_interval: '15m',
284
+ min_doc_count: 0,
285
+ },
286
+ },
287
+ });
288
+
289
+ const line1h = compileSearchRequest({
290
+ spec: normalizeReportSpec({
291
+ visualization: 'line',
292
+ chart: { bucketType: 'date_histogram', calendarInterval: '1h' },
293
+ }),
294
+ timeField: '@timestamp',
295
+ fields: SAMPLE_FIELDS,
296
+ });
297
+ expect(line1h.body.aggs).toEqual({
298
+ es_buckets: {
299
+ date_histogram: {
300
+ field: '@timestamp',
301
+ calendar_interval: '1h',
302
+ min_doc_count: 0,
303
+ },
304
+ },
305
+ });
306
+ });
307
+
308
+ it('supports KQL field value groups and throws KqlSyntaxError on invalid KQL syntax', () => {
309
+ const fieldMap = buildFieldCapabilityMap(SAMPLE_FIELDS);
310
+
311
+ expect(compileKqlToQueryDsl('status: (400 OR 404)', fieldMap)).toEqual({
312
+ bool: {
313
+ should: [{ term: { status: 400 } }, { term: { status: 404 } }],
314
+ minimum_should_match: 1,
315
+ },
316
+ });
317
+
318
+ expect(
319
+ compileKqlToQueryDsl('service: ("checkout-api" OR auth*) AND latency_ms: (>= 100 AND < 500)', fieldMap),
320
+ ).toEqual({
321
+ bool: {
322
+ must: [
323
+ {
324
+ bool: {
325
+ should: [
326
+ { match_phrase: { service: 'checkout-api' } },
327
+ { wildcard: { 'service.keyword': { value: 'auth*', case_insensitive: true } } },
328
+ ],
329
+ minimum_should_match: 1,
330
+ },
331
+ },
332
+ {
333
+ bool: {
334
+ must: [{ range: { latency_ms: { gte: 100 } } }, { range: { latency_ms: { lt: 500 } } }],
335
+ },
336
+ },
337
+ ],
338
+ },
339
+ });
340
+
341
+ expect(() => compileKqlToQueryDsl('status: (400 OR', fieldMap)).toThrow(KqlSyntaxError);
342
+ expect(() => compileKqlToQueryDsl('status: [400 TO 499]', fieldMap)).toThrow(KqlSyntaxError);
343
+ expect(() => compileKqlToQueryDsl('service: "unclosed', fieldMap)).toThrow(KqlSyntaxError);
344
+ expect(() => compileKqlToQueryDsl('AND status: 500', fieldMap)).toThrow(KqlSyntaxError);
345
+ expect(() => compileKqlToQueryDsl('status:', fieldMap)).toThrow(KqlSyntaxError);
346
+ });
347
+
348
+ it('enforces server lockedFilters regardless of viewer overrides and surfaces timeout/shard warnings', () => {
349
+ const spec = normalizeReportSpec({
350
+ visualization: 'table',
351
+ lockedFilters: [{ field: 'service', operator: 'eq', value: 'tenant-a' }],
352
+ filters: [{ field: 'status', operator: 'gte', value: 400 }],
353
+ timeRange: { preset: 'custom', from: '2026-11-29T00:00:00Z', to: '2026-11-30T00:00:00Z' },
354
+ });
355
+
356
+ const { body } = compileSearchRequest({
357
+ spec,
358
+ overrides: {
359
+ query: '',
360
+ filters: [],
361
+ timeRange: { preset: 'custom', from: '2026-11-29T00:00:00Z', to: '2026-11-30T00:00:00Z' },
362
+ },
363
+ timeField: '@timestamp',
364
+ fields: SAMPLE_FIELDS,
365
+ });
366
+
367
+ expect(body.query).toEqual({
368
+ bool: {
369
+ filter: [
370
+ { term: { 'service.keyword': 'tenant-a' } },
371
+ { range: { '@timestamp': { gte: '2026-11-29T00:00:00Z', lte: '2026-11-30T00:00:00Z' } } },
372
+ ],
373
+ },
374
+ });
375
+
376
+ const partial = parseSearchResponse(
377
+ {
378
+ took: 950,
379
+ timed_out: true,
380
+ _shards: { total: 5, successful: 4, skipped: 0, failed: 1 },
381
+ hits: { total: { value: 10000, relation: 'gte' }, hits: [] },
382
+ },
383
+ body,
384
+ spec,
385
+ '@timestamp',
386
+ );
387
+ expect(partial.timedOut).toBe(true);
388
+ expect(partial.shards).toEqual({ total: 5, successful: 4, skipped: 0, failed: 1 });
389
+ expect(partial.warnings).toHaveLength(2);
390
+ });
391
+
392
+ it('propagates IANA time_zone, _shard_doc PIT tie-breaker, p95 percentiles, and splitSeriesField breakdown', () => {
393
+ const pitTable = compileSearchRequest({
394
+ spec: normalizeReportSpec({
395
+ visualization: 'table',
396
+ timeRange: { preset: 'last_24h' },
397
+ }),
398
+ overrides: {
399
+ timeZone: 'Asia/Ho_Chi_Minh',
400
+ },
401
+ timeField: '@timestamp',
402
+ fields: SAMPLE_FIELDS,
403
+ usePit: true,
404
+ });
405
+
406
+ expect(pitTable.body.sort).toEqual([
407
+ { '@timestamp': { order: 'desc', unmapped_type: 'date' } },
408
+ { _shard_doc: { order: 'asc' } },
409
+ ]);
410
+ expect(pitTable.body.query).toEqual({
411
+ bool: {
412
+ filter: [{ range: { '@timestamp': { gte: 'now-24h', lte: 'now', time_zone: 'Asia/Ho_Chi_Minh' } } }],
413
+ },
414
+ });
415
+ expect(pitTable.body.aggs).toEqual({
416
+ es_time_histogram: {
417
+ auto_date_histogram: {
418
+ field: '@timestamp',
419
+ buckets: 24,
420
+ time_zone: 'Asia/Ho_Chi_Minh',
421
+ },
422
+ },
423
+ });
424
+
425
+ const splitChartSpec = normalizeReportSpec({
426
+ visualization: 'bar',
427
+ chart: {
428
+ bucketType: 'date_histogram',
429
+ calendarInterval: '1h',
430
+ metricType: 'p95',
431
+ metricField: 'latency_ms',
432
+ splitSeriesField: 'service',
433
+ splitSeriesTopN: 3,
434
+ stackMode: 'stacked',
435
+ },
436
+ });
437
+
438
+ const { body: splitBody, effectiveSpec } = compileSearchRequest({
439
+ spec: splitChartSpec,
440
+ overrides: { timeZone: 'Asia/Ho_Chi_Minh' },
441
+ timeField: '@timestamp',
442
+ fields: SAMPLE_FIELDS,
443
+ });
444
+
445
+ expect(splitBody.aggs).toEqual({
446
+ es_buckets: {
447
+ date_histogram: {
448
+ field: '@timestamp',
449
+ calendar_interval: '1h',
450
+ min_doc_count: 0,
451
+ time_zone: 'Asia/Ho_Chi_Minh',
452
+ },
453
+ aggs: {
454
+ es_metric: {
455
+ percentiles: { field: 'latency_ms', percents: [95] },
456
+ },
457
+ es_split: {
458
+ terms: { field: 'service.keyword', size: 3 },
459
+ aggs: {
460
+ es_metric: {
461
+ percentiles: { field: 'latency_ms', percents: [95] },
462
+ },
463
+ },
464
+ },
465
+ },
466
+ },
467
+ });
468
+
469
+ const parsedSplit = parseSearchResponse(
470
+ {
471
+ took: 6,
472
+ hits: { total: { value: 50, relation: 'eq' }, hits: [] },
473
+ aggregations: {
474
+ es_buckets: {
475
+ buckets: [
476
+ {
477
+ key_as_string: '2026-11-30T01:00:00+07:00',
478
+ key: 1732903200000,
479
+ doc_count: 50,
480
+ es_metric: { values: { '95.0': 412.5 } },
481
+ es_split: {
482
+ buckets: [
483
+ { key: 'checkout', doc_count: 30, es_metric: { values: { '95.0': 480.25 } } },
484
+ { key: 'catalog', doc_count: 20, es_metric: { values: { '95.0': 190.5 } } },
485
+ ],
486
+ },
487
+ },
488
+ ],
489
+ },
490
+ },
491
+ },
492
+ splitBody,
493
+ effectiveSpec,
494
+ '@timestamp',
495
+ );
496
+
497
+ expect(parsedSplit.seriesKeys).toEqual(['checkout', 'catalog']);
498
+ expect(parsedSplit.series).toEqual([
499
+ {
500
+ key: '1732903200000',
501
+ label: '2026-11-30T01:00:00+07:00',
502
+ value: 412.5,
503
+ count: 50,
504
+ breakdown: [
505
+ { seriesKey: 'checkout', value: 480.25, count: 30 },
506
+ { seriesKey: 'catalog', value: 190.5, count: 20 },
507
+ ],
508
+ },
509
+ ]);
510
+ });
511
+
512
+ it('compiles single-call KPI comparePreviousPeriod dual-window aggregations and computes deltaPercent', () => {
513
+ const kpiSpec = normalizeReportSpec({
514
+ visualization: 'metric',
515
+ timeRange: { preset: 'last_24h' },
516
+ chart: {
517
+ metricType: 'avg',
518
+ metricField: 'latency_ms',
519
+ comparePreviousPeriod: true,
520
+ },
521
+ });
522
+
523
+ const { body, effectiveSpec } = compileSearchRequest({
524
+ spec: kpiSpec,
525
+ timeField: '@timestamp',
526
+ fields: SAMPLE_FIELDS,
527
+ });
528
+
529
+ expect(body.aggs).toEqual({
530
+ es_current_window: {
531
+ filter: { range: { '@timestamp': { gte: 'now-24h', lte: 'now' } } },
532
+ aggs: { es_metric: { avg: { field: 'latency_ms' } } },
533
+ },
534
+ es_previous_window: {
535
+ filter: { range: { '@timestamp': { gte: 'now-48h', lt: 'now-24h' } } },
536
+ aggs: { es_metric: { avg: { field: 'latency_ms' } } },
537
+ },
538
+ });
539
+
540
+ const parsed = parseSearchResponse(
541
+ {
542
+ took: 4,
543
+ hits: { total: { value: 200, relation: 'eq' }, hits: [] },
544
+ aggregations: {
545
+ es_current_window: { doc_count: 120, es_metric: { value: 250 } },
546
+ es_previous_window: { doc_count: 80, es_metric: { value: 200 } },
547
+ },
548
+ },
549
+ body,
550
+ effectiveSpec,
551
+ '@timestamp',
552
+ );
553
+
554
+ expect(parsed.metricValue).toBe(250);
555
+ expect(parsed.previousMetricValue).toBe(200);
556
+ expect(parsed.deltaPercent).toBe(25);
557
+ });
558
+
559
+ it('resolves server lockedFilters user tokens, neutralizes CSV formula injection, and evaluates workflow thresholds', () => {
560
+ const resolved = resolveServerLockedFilters(
561
+ [
562
+ { field: 'tenant_user_id', operator: 'eq', value: '{{$user.id}}' },
563
+ { field: 'department', operator: 'eq', value: '{{ $role }}' },
564
+ ],
565
+ { userId: 7, username: 'alice', role: 'finance-viewer' },
566
+ );
567
+ expect(resolved).toEqual([
568
+ { field: 'tenant_user_id', operator: 'eq', value: 7, enabled: true },
569
+ { field: 'department', operator: 'eq', value: 'finance-viewer', enabled: true },
570
+ ]);
571
+
572
+ expect(() =>
573
+ resolveServerLockedFilters([{ field: 'owner_email', operator: 'eq', value: '{{$user.email}}' }], {
574
+ userId: 7,
575
+ }),
576
+ ).toThrow(/Permission denied/);
577
+
578
+ // CSV formula-injection neutralization preserves negative numbers and ECS @timestamp header while escaping =, +, -, @ formulas
579
+ expect(escapeCsvCell("=CMD|' /C calc'!A0")).toBe("'=CMD|' /C calc'!A0");
580
+ expect(escapeCsvCell('@SUM(A1:A5)')).toBe("'@SUM(A1:A5)");
581
+ expect(escapeCsvCell('@timestamp', { allowAtIdentifier: true })).toBe('@timestamp');
582
+ expect(escapeCsvCell('@SUM(A1:A5)', { allowAtIdentifier: true })).toBe("'@SUM(A1:A5)");
583
+ expect(escapeCsvCell('-42.5')).toBe('-42.5');
584
+ expect(escapeCsvCell(-42.5)).toBe('-42.5');
585
+ expect(escapeCsvCell('hello, "world"')).toBe('"hello, ""world"""');
586
+
587
+ // Workflow threshold evaluation
588
+ expect(evaluateThreshold(15, 'gte', 10)).toBe(true);
589
+ expect(evaluateThreshold(5, 'gte', 10)).toBe(false);
590
+ expect(evaluateThreshold(null, 'gt', 0)).toBe(false);
591
+ });
592
+
593
+ it('synchronizes ES 8.x connection options (CA fingerprint, PEM, Bearer token, Cloud ID) in ElasticsearchConnectionService', () => {
594
+ const fp = 'AA:BB:' + '11'.repeat(30);
595
+ const opts = buildEsClientOptions({
596
+ nodes: 'https://es8-node:9200',
597
+ authMode: 'bearer',
598
+ bearerToken: 'aae_token_xyz',
599
+ tlsMode: 'caFingerprint',
600
+ caFingerprint: fp,
601
+ requestTimeoutMs: 25000,
602
+ maxRetries: 4,
603
+ compression: true,
604
+ });
605
+ expect(opts).toMatchObject({
606
+ nodes: ['https://es8-node:9200'],
607
+ auth: { bearer: 'aae_token_xyz' },
608
+ caFingerprint: 'aabb' + '11'.repeat(30),
609
+ tls: { rejectUnauthorized: false },
610
+ requestTimeout: 25000,
611
+ maxRetries: 4,
612
+ compression: true,
613
+ });
614
+ expect(inferConnectionModes({ hasApiKey: true, hasCaCert: true })).toEqual({
615
+ endpointMode: 'nodes',
616
+ authMode: 'apiKey',
617
+ tlsMode: 'caCert',
618
+ });
619
+ });
620
+ });