@fc-components/monaco-editor 0.1.1

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.
@@ -0,0 +1,2170 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
+
7
+ var React = require('react');
8
+ var React__default = _interopDefault(React);
9
+ var MonacoEditor = _interopDefault(require('react-monaco-editor'));
10
+ var monaco = require('monaco-editor');
11
+ var monacoPromql = require('monaco-promql');
12
+ var lezerMetricsql = require('@fc-components/lezer-metricsql');
13
+ var uuid = require('uuid');
14
+ var css = require('@emotion/css');
15
+ var UFuzzy = _interopDefault(require('@leeoniya/ufuzzy'));
16
+
17
+ function _arrayLikeToArray(r, a) {
18
+ (null == a || a > r.length) && (a = r.length);
19
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
20
+ return n;
21
+ }
22
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
23
+ try {
24
+ var i = n[a](c),
25
+ u = i.value;
26
+ } catch (n) {
27
+ return void e(n);
28
+ }
29
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
30
+ }
31
+ function _asyncToGenerator(n) {
32
+ return function () {
33
+ var t = this,
34
+ e = arguments;
35
+ return new Promise(function (r, o) {
36
+ var a = n.apply(t, e);
37
+ function _next(n) {
38
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
39
+ }
40
+ function _throw(n) {
41
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
42
+ }
43
+ _next(void 0);
44
+ });
45
+ };
46
+ }
47
+ function _construct(t, e, r) {
48
+ if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
49
+ var o = [null];
50
+ o.push.apply(o, e);
51
+ var p = new (t.bind.apply(t, o))();
52
+ return r && _setPrototypeOf(p, r.prototype), p;
53
+ }
54
+ function _defineProperties(e, r) {
55
+ for (var t = 0; t < r.length; t++) {
56
+ var o = r[t];
57
+ o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
58
+ }
59
+ }
60
+ function _createClass(e, r, t) {
61
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
62
+ writable: !1
63
+ }), e;
64
+ }
65
+ function _createForOfIteratorHelperLoose(r, e) {
66
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
67
+ if (t) return (t = t.call(r)).next.bind(t);
68
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
69
+ t && (r = t);
70
+ var o = 0;
71
+ return function () {
72
+ return o >= r.length ? {
73
+ done: !0
74
+ } : {
75
+ done: !1,
76
+ value: r[o++]
77
+ };
78
+ };
79
+ }
80
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
81
+ }
82
+ function _extends() {
83
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
84
+ for (var e = 1; e < arguments.length; e++) {
85
+ var t = arguments[e];
86
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
87
+ }
88
+ return n;
89
+ }, _extends.apply(null, arguments);
90
+ }
91
+ function _getPrototypeOf(t) {
92
+ return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
93
+ return t.__proto__ || Object.getPrototypeOf(t);
94
+ }, _getPrototypeOf(t);
95
+ }
96
+ function _inheritsLoose(t, o) {
97
+ t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
98
+ }
99
+ function _isNativeFunction(t) {
100
+ try {
101
+ return -1 !== Function.toString.call(t).indexOf("[native code]");
102
+ } catch (n) {
103
+ return "function" == typeof t;
104
+ }
105
+ }
106
+ function _isNativeReflectConstruct() {
107
+ try {
108
+ var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
109
+ } catch (t) {}
110
+ return (_isNativeReflectConstruct = function () {
111
+ return !!t;
112
+ })();
113
+ }
114
+ function _objectWithoutPropertiesLoose(r, e) {
115
+ if (null == r) return {};
116
+ var t = {};
117
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
118
+ if (-1 !== e.indexOf(n)) continue;
119
+ t[n] = r[n];
120
+ }
121
+ return t;
122
+ }
123
+ function _regenerator() {
124
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
125
+ var e,
126
+ t,
127
+ r = "function" == typeof Symbol ? Symbol : {},
128
+ n = r.iterator || "@@iterator",
129
+ o = r.toStringTag || "@@toStringTag";
130
+ function i(r, n, o, i) {
131
+ var c = n && n.prototype instanceof Generator ? n : Generator,
132
+ u = Object.create(c.prototype);
133
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
134
+ var i,
135
+ c,
136
+ u,
137
+ f = 0,
138
+ p = o || [],
139
+ y = !1,
140
+ G = {
141
+ p: 0,
142
+ n: 0,
143
+ v: e,
144
+ a: d,
145
+ f: d.bind(e, 4),
146
+ d: function (t, r) {
147
+ return i = t, c = 0, u = e, G.n = r, a;
148
+ }
149
+ };
150
+ function d(r, n) {
151
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
152
+ var o,
153
+ i = p[t],
154
+ d = G.p,
155
+ l = i[2];
156
+ r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
157
+ }
158
+ if (o || r > 1) return a;
159
+ throw y = !0, n;
160
+ }
161
+ return function (o, p, l) {
162
+ if (f > 1) throw TypeError("Generator is already running");
163
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
164
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
165
+ try {
166
+ if (f = 2, i) {
167
+ if (c || (o = "next"), t = i[o]) {
168
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
169
+ if (!t.done) return t;
170
+ u = t.value, c < 2 && (c = 0);
171
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
172
+ i = e;
173
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
174
+ } catch (t) {
175
+ i = e, c = 1, u = t;
176
+ } finally {
177
+ f = 1;
178
+ }
179
+ }
180
+ return {
181
+ value: t,
182
+ done: y
183
+ };
184
+ };
185
+ }(r, o, i), !0), u;
186
+ }
187
+ var a = {};
188
+ function Generator() {}
189
+ function GeneratorFunction() {}
190
+ function GeneratorFunctionPrototype() {}
191
+ t = Object.getPrototypeOf;
192
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
193
+ return this;
194
+ }), t),
195
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
196
+ function f(e) {
197
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
198
+ }
199
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
200
+ return this;
201
+ }), _regeneratorDefine(u, "toString", function () {
202
+ return "[object Generator]";
203
+ }), (_regenerator = function () {
204
+ return {
205
+ w: i,
206
+ m: f
207
+ };
208
+ })();
209
+ }
210
+ function _regeneratorDefine(e, r, n, t) {
211
+ var i = Object.defineProperty;
212
+ try {
213
+ i({}, "", {});
214
+ } catch (e) {
215
+ i = 0;
216
+ }
217
+ _regeneratorDefine = function (e, r, n, t) {
218
+ if (r) i ? i(e, r, {
219
+ value: n,
220
+ enumerable: !t,
221
+ configurable: !t,
222
+ writable: !t
223
+ }) : e[r] = n;else {
224
+ function o(r, n) {
225
+ _regeneratorDefine(e, r, function (e) {
226
+ return this._invoke(r, n, e);
227
+ });
228
+ }
229
+ o("next", 0), o("throw", 1), o("return", 2);
230
+ }
231
+ }, _regeneratorDefine(e, r, n, t);
232
+ }
233
+ function _setPrototypeOf(t, e) {
234
+ return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
235
+ return t.__proto__ = e, t;
236
+ }, _setPrototypeOf(t, e);
237
+ }
238
+ function _toPrimitive(t, r) {
239
+ if ("object" != typeof t || !t) return t;
240
+ var e = t[Symbol.toPrimitive];
241
+ if (void 0 !== e) {
242
+ var i = e.call(t, r || "default");
243
+ if ("object" != typeof i) return i;
244
+ throw new TypeError("@@toPrimitive must return a primitive value.");
245
+ }
246
+ return ("string" === r ? String : Number)(t);
247
+ }
248
+ function _toPropertyKey(t) {
249
+ var i = _toPrimitive(t, "string");
250
+ return "symbol" == typeof i ? i : i + "";
251
+ }
252
+ function _unsupportedIterableToArray(r, a) {
253
+ if (r) {
254
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
255
+ var t = {}.toString.call(r).slice(8, -1);
256
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
257
+ }
258
+ }
259
+ function _wrapNativeSuper(t) {
260
+ var r = "function" == typeof Map ? new Map() : void 0;
261
+ return _wrapNativeSuper = function (t) {
262
+ if (null === t || !_isNativeFunction(t)) return t;
263
+ if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
264
+ if (void 0 !== r) {
265
+ if (r.has(t)) return r.get(t);
266
+ r.set(t, Wrapper);
267
+ }
268
+ function Wrapper() {
269
+ return _construct(t, arguments, _getPrototypeOf(this).constructor);
270
+ }
271
+ return Wrapper.prototype = Object.create(t.prototype, {
272
+ constructor: {
273
+ value: Wrapper,
274
+ enumerable: !1,
275
+ writable: !0,
276
+ configurable: !0
277
+ }
278
+ }), _setPrototypeOf(Wrapper, t);
279
+ }, _wrapNativeSuper(t);
280
+ }
281
+
282
+ var languageConfiguration = {
283
+ // the default separators except `@$`
284
+ wordPattern: /(-?\d*\.\d\w*)|([^`~!#%^&*()\-=+\[{\]}\\|;:'",.<>\/?\s]+)/g,
285
+ // Not possible to make comments in PromQL syntax
286
+ comments: {
287
+ lineComment: '#'
288
+ },
289
+ brackets: [['{', '}'], ['[', ']'], ['(', ')']],
290
+ autoClosingPairs: [{
291
+ open: '{',
292
+ close: '}'
293
+ }, {
294
+ open: '[',
295
+ close: ']'
296
+ }, {
297
+ open: '(',
298
+ close: ')'
299
+ }, {
300
+ open: '"',
301
+ close: '"'
302
+ }, {
303
+ open: "'",
304
+ close: "'"
305
+ }],
306
+ surroundingPairs: [{
307
+ open: '{',
308
+ close: '}'
309
+ }, {
310
+ open: '[',
311
+ close: ']'
312
+ }, {
313
+ open: '(',
314
+ close: ')'
315
+ }, {
316
+ open: '"',
317
+ close: '"'
318
+ }, {
319
+ open: "'",
320
+ close: "'"
321
+ }, {
322
+ open: '<',
323
+ close: '>'
324
+ }],
325
+ folding: {}
326
+ };
327
+ // PromQL Aggregation Operators
328
+ // (https://prometheus.io/docs/prometheus/latest/querying/operators/#aggregation-operators)
329
+ var aggregations = ['sum', 'min', 'max', 'avg', 'group', 'stddev', 'stdvar', 'count', 'count_values', 'bottomk', 'topk', 'quantile', 'quantiles', 'distinct', 'geomean', 'histogram', 'mad', 'mode',
330
+ // metricsql aggregations
331
+ 'any', 'bottomk_avg', 'bottomk_max', 'bottomk_median', 'bottomk_last', 'bottomk_min', 'topk_avg', 'topk_max', 'topk_median', 'topk_last', 'topk_min', 'outliers_mad', 'outliersk', 'share', 'sum2', 'zscore'];
332
+ // PromQL functions
333
+ // (https://prometheus.io/docs/prometheus/latest/querying/functions/)
334
+ var functions = ['abs', 'absent', 'ceil', 'changes', 'clamp_max', 'clamp_min', 'day_of_month', 'day_of_week', 'days_in_month', 'delta', 'deriv', 'exp', 'floor', 'histogram_quantile', 'histogram_avg', 'histogram_count', 'histogram_sum', 'histogram_fraction', 'histogram_stddev', 'histogram_stdvar', 'holt_winters', 'hour', 'idelta', 'increase', 'irate', 'label_join', 'label_replace', 'ln', 'log2', 'log10', 'minute', 'month', 'predict_linear', 'rate', 'resets', 'round', 'scalar', 'sort', 'sort_desc', 'sqrt', 'time', 'timestamp', 'vector', 'year',
335
+ // metricsql functions
336
+ 'aggr_over_time', 'alias', 'ascent_over_time', 'bitmap_and', 'bitmap_or', 'bitmap_xor', 'buckets_limit', 'changes_prometheus', 'count_eq_over_time', 'count_gt_over_time', 'count_le_over_time', 'count_ne_over_time', 'decreases_over_time', 'default_rollup', 'delta_prometheus', 'deriv_fast', 'descent_over_time', 'distinct_over_time', 'drop_common_labels', 'duration_over_time', 'first_over_time', 'geomean_over_time', 'histogram_avg', 'histogram_over_time', 'histogram_quantiles', 'histogram_share', 'hoeffding_bound_lower', 'hoeffding_bound_upper', 'ideriv', 'increase_prometheus', 'increase_pure', 'increases_over_time', 'integrate', 'interpolate', 'keep_last_value', 'keep_next_value', 'label_copy', 'label_del', 'label_graphite_group', 'label_keep', 'label_lowercase', 'label_map', 'label_match', 'label_mismatch', 'label_move', 'label_set', 'label_transform', 'label_uppercase', 'label_value', 'lag', 'lifetime', 'limit_offset', 'mad_over_time', 'median_over_time', 'mode_over_time', 'now', 'prometheus_buckets', 'quantiles_over_time', 'rand', 'rand_exponential', 'rand_normal', 'range_avg', 'range_first', 'range_last', 'range_linear_regression', 'range_mad', 'range_max', 'range_min', 'range_normalize', 'range_over_time', 'range_quantile', 'range_stddev', 'range_stdvar', 'range_sum', 'range_trim_outliers', 'range_trim_spikes', 'range_trim_zscore', 'range_zscore', 'rate_over_sum', 'remove_resets', 'rollup', 'rollup_candlestick', 'rollup_delta', 'rollup_deriv', 'rollup_increase', 'rollup_rate', 'rollup_scrape_interval', 'running_avg', 'running_max', 'running_min', 'running_sum', 'scrape_interval', 'share_eq_over_time', 'share_gt_over_time', 'share_le_over_time', 'smooth_exponential', 'smooth_exponential', 'sort_by_label_desc', 'sort_by_label_numeric', 'sort_by_label_numeric_desc', 'stale_samples_over_time', 'step', 'sum2_over_time', 'tfirst_over_time', 'timestamp_with_name', 'timezone_offset', 'tlast_change_over_time', 'tlast_over_time', 'tmax_over_time', 'tmin_over_time', 'union', 'zscore_over_time', 'avg_daily', 'median_daily', 'avg_weekly', 'median_weekly', 'median_weekly_with_trends'];
337
+ // PromQL specific functions: Aggregations over time
338
+ // (https://prometheus.io/docs/prometheus/latest/querying/functions/#aggregation_over_time)
339
+ var aggregationsOverTime = [];
340
+ for (var _i = 0, aggregations_1 = aggregations; _i < aggregations_1.length; _i++) {
341
+ var agg = aggregations_1[_i];
342
+ aggregationsOverTime.push(agg + '_over_time');
343
+ }
344
+ // PromQL vector matching + the by and without clauses
345
+ // (https://prometheus.io/docs/prometheus/latest/querying/operators/#vector-matching)
346
+ var vectorMatching = ['on', 'ignoring', 'group_right', 'group_left', 'by', 'without'];
347
+ // Produce a regex matching elements : (elt1|elt2|...)
348
+ var vectorMatchingRegex = '(' + /*#__PURE__*/vectorMatching.reduce(function (prev, curr) {
349
+ return prev + '|' + curr;
350
+ }) + ')';
351
+ // PromQL Operators
352
+ // (https://prometheus.io/docs/prometheus/latest/querying/operators/)
353
+ var operators = ['+', '-', '*', '/', '%', '^', '==', '!=', '>', '<', '>=', '<=', 'and', 'or', 'unless'];
354
+ // PromQL offset modifier
355
+ // (https://prometheus.io/docs/prometheus/latest/querying/basics/#offset-modifier)
356
+ var offsetModifier = ['offset'];
357
+ // Merging all the keywords in one list
358
+ var keywords = /*#__PURE__*/aggregations.concat(functions).concat(aggregationsOverTime).concat(vectorMatching).concat(offsetModifier);
359
+ // noinspection JSUnusedGlobalSymbols
360
+ var language = {
361
+ ignoreCase: false,
362
+ defaultToken: '',
363
+ tokenPostfix: '.promql',
364
+ keywords: keywords,
365
+ operators: operators,
366
+ vectorMatching: vectorMatchingRegex,
367
+ // we include these common regular expressions
368
+ symbols: /[=><!~?:&|+\-*\/^%]+/,
369
+ escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
370
+ digits: /\d+(_+\d+)*/,
371
+ octaldigits: /[0-7]+(_+[0-7]+)*/,
372
+ binarydigits: /[0-1]+(_+[0-1]+)*/,
373
+ hexdigits: /[[0-9a-fA-F]+(_+[0-9a-fA-F]+)*/,
374
+ integersuffix: /(ll|LL|u|U|l|L)?(ll|LL|u|U|l|L)?/,
375
+ floatsuffix: /[fFlL]?/,
376
+ // The main tokenizer for our languages
377
+ tokenizer: {
378
+ root: [
379
+ // 'by', 'without' and vector matching
380
+ [/@vectorMatching\s*(?=\()/, 'type', '@clauses'],
381
+ // labels
382
+ [/[a-z_]\w*(?=\s*(=|!=|=~|!~))/, 'tag'],
383
+ // comments
384
+ [/(^#.*$)/, 'comment'],
385
+ // all keywords have the same color
386
+ [/[a-zA-Z_]\w*/, {
387
+ cases: {
388
+ '@keywords': 'type',
389
+ '@default': 'identifier'
390
+ }
391
+ }],
392
+ // strings
393
+ [/"([^"\\]|\\.)*$/, 'string.invalid'], [/'([^'\\]|\\.)*$/, 'string.invalid'], [/"/, 'string', '@string_double'], [/'/, 'string', '@string_single'], [/`/, 'string', '@string_backtick'],
394
+ // whitespace
395
+ {
396
+ include: '@whitespace'
397
+ },
398
+ // delimiters and operators
399
+ [/[{}()\[\]]/, '@brackets'], [/[<>](?!@symbols)/, '@brackets'], [/@symbols/, {
400
+ cases: {
401
+ '@operators': 'delimiter',
402
+ '@default': ''
403
+ }
404
+ }],
405
+ // numbers
406
+ [/\d+[smhdwy]/, 'number'], [/\d*\d+[eE]([\-+]?\d+)?(@floatsuffix)/, 'number.float'], [/\d*\.\d+([eE][\-+]?\d+)?(@floatsuffix)/, 'number.float'], [/0[xX][0-9a-fA-F']*[0-9a-fA-F](@integersuffix)/, 'number.hex'], [/0[0-7']*[0-7](@integersuffix)/, 'number.octal'], [/0[bB][0-1']*[0-1](@integersuffix)/, 'number.binary'], [/\d[\d']*\d(@integersuffix)/, 'number'], [/\d(@integersuffix)/, 'number']],
407
+ string_double: [[/[^\\"]+/, 'string'], [/@escapes/, 'string.escape'], [/\\./, 'string.escape.invalid'], [/"/, 'string', '@pop']],
408
+ string_single: [[/[^\\']+/, 'string'], [/@escapes/, 'string.escape'], [/\\./, 'string.escape.invalid'], [/'/, 'string', '@pop']],
409
+ string_backtick: [[/[^\\`$]+/, 'string'], [/@escapes/, 'string.escape'], [/\\./, 'string.escape.invalid'], [/`/, 'string', '@pop']],
410
+ clauses: [[/[^(,)]/, 'tag'], [/\)/, 'identifier', '@pop']],
411
+ whitespace: [[/[ \t\r\n]+/, 'white']]
412
+ }
413
+ };
414
+ var TRIGONOMETRIC_FUNCTIONS = [{
415
+ label: 'acos',
416
+ insertText: 'acos',
417
+ detail: 'acos(v instant-vector)',
418
+ documentation: 'calculates the arccosine of all elements in v'
419
+ }, {
420
+ label: 'acosh',
421
+ insertText: 'acosh',
422
+ detail: 'acosh(v instant-vector)',
423
+ documentation: 'calculates the inverse hyperbolic cosine of all elements in v'
424
+ }, {
425
+ label: 'asin',
426
+ insertText: 'asin',
427
+ detail: 'asin(v instant-vector)',
428
+ documentation: 'calculates the arcsine of all elements in v'
429
+ }, {
430
+ label: 'asinh',
431
+ insertText: 'asinh',
432
+ detail: 'asinh(v instant-vector)',
433
+ documentation: 'calculates the inverse hyperbolic sine of all elements in v'
434
+ }, {
435
+ label: 'atan',
436
+ insertText: 'atan',
437
+ detail: 'atan(v instant-vector)',
438
+ documentation: 'calculates the arctangent of all elements in v'
439
+ }, {
440
+ label: 'atanh',
441
+ insertText: 'atanh',
442
+ detail: 'atanh(v instant-vector)',
443
+ documentation: 'calculates the inverse hyperbolic tangent of all elements in v'
444
+ }, {
445
+ label: 'cos',
446
+ insertText: 'cos',
447
+ detail: 'cos(v instant-vector)',
448
+ documentation: 'calculates the cosine of all elements in v'
449
+ }, {
450
+ label: 'cosh',
451
+ insertText: 'cosh',
452
+ detail: 'cosh(v instant-vector)',
453
+ documentation: 'calculates the hyperbolic cosine of all elements in v'
454
+ }, {
455
+ label: 'sin',
456
+ insertText: 'sin',
457
+ detail: 'sin(v instant-vector)',
458
+ documentation: 'calculates the sine of all elements in v'
459
+ }, {
460
+ label: 'sinh',
461
+ insertText: 'sinh',
462
+ detail: 'sinh(v instant-vector)',
463
+ documentation: 'calculates the hyperbolic sine of all elements in v'
464
+ }, {
465
+ label: 'tan',
466
+ insertText: 'tan',
467
+ detail: 'tan(v instant-vector)',
468
+ documentation: 'calculates the tangent of all elements in v'
469
+ }, {
470
+ label: 'tanh',
471
+ insertText: 'tanh',
472
+ detail: 'tanh(v instant-vector)',
473
+ documentation: 'calculates the hyperbolic tangent of all elements in v'
474
+ }];
475
+ var AGGREGATION_OPERATORS = [{
476
+ label: 'sum',
477
+ insertText: 'sum',
478
+ documentation: 'Calculate sum over dimensions'
479
+ }, {
480
+ label: 'min',
481
+ insertText: 'min',
482
+ documentation: 'Select minimum over dimensions'
483
+ }, {
484
+ label: 'max',
485
+ insertText: 'max',
486
+ documentation: 'Select maximum over dimensions'
487
+ }, {
488
+ label: 'avg',
489
+ insertText: 'avg',
490
+ documentation: 'Calculate the average over dimensions'
491
+ }, {
492
+ label: 'group',
493
+ insertText: 'group',
494
+ documentation: 'All values in the resulting vector are 1'
495
+ }, {
496
+ label: 'stddev',
497
+ insertText: 'stddev',
498
+ documentation: 'Calculate population standard deviation over dimensions'
499
+ }, {
500
+ label: 'stdvar',
501
+ insertText: 'stdvar',
502
+ documentation: 'Calculate population standard variance over dimensions'
503
+ }, {
504
+ label: 'count',
505
+ insertText: 'count',
506
+ documentation: 'Count number of elements in the vector'
507
+ }, {
508
+ label: 'count_values',
509
+ insertText: 'count_values',
510
+ documentation: 'Count number of elements with the same value'
511
+ }, {
512
+ label: 'bottomk',
513
+ insertText: 'bottomk',
514
+ documentation: 'Smallest k elements by sample value'
515
+ }, {
516
+ label: 'topk',
517
+ insertText: 'topk',
518
+ documentation: 'Largest k elements by sample value'
519
+ }, {
520
+ label: 'quantile',
521
+ insertText: 'quantile',
522
+ documentation: 'Calculate φ-quantile (0 ≤ φ ≤ 1) over dimensions'
523
+ }];
524
+ var FUNCTIONS = /*#__PURE__*/[].concat(AGGREGATION_OPERATORS, TRIGONOMETRIC_FUNCTIONS, [{
525
+ insertText: 'abs',
526
+ label: 'abs',
527
+ detail: 'abs(v instant-vector)',
528
+ documentation: 'Returns the input vector with all sample values converted to their absolute value.'
529
+ }, {
530
+ insertText: 'absent',
531
+ label: 'absent',
532
+ detail: 'absent(v instant-vector)',
533
+ documentation: 'Returns an empty vector if the vector passed to it has any elements and a 1-element vector with the value 1 if the vector passed to it has no elements. This is useful for alerting on when no time series exist for a given metric name and label combination.'
534
+ }, {
535
+ insertText: 'absent_over_time',
536
+ label: 'absent_over_time',
537
+ detail: 'absent(v range-vector)',
538
+ documentation: 'Returns an empty vector if the range vector passed to it has any elements and a 1-element vector with the value 1 if the range vector passed to it has no elements.'
539
+ }, {
540
+ insertText: 'ceil',
541
+ label: 'ceil',
542
+ detail: 'ceil(v instant-vector)',
543
+ documentation: 'Rounds the sample values of all elements in `v` up to the nearest integer.'
544
+ }, {
545
+ insertText: 'changes',
546
+ label: 'changes',
547
+ detail: 'changes(v range-vector)',
548
+ documentation: 'For each input time series, `changes(v range-vector)` returns the number of times its value has changed within the provided time range as an instant vector.'
549
+ }, {
550
+ insertText: 'clamp',
551
+ label: 'clamp',
552
+ detail: 'clamp(v instant-vector, min scalar, max scalar)',
553
+ documentation: 'Clamps the sample values of all elements in `v` to have a lower limit of `min` and an upper limit of `max`.'
554
+ }, {
555
+ insertText: 'clamp_max',
556
+ label: 'clamp_max',
557
+ detail: 'clamp_max(v instant-vector, max scalar)',
558
+ documentation: 'Clamps the sample values of all elements in `v` to have an upper limit of `max`.'
559
+ }, {
560
+ insertText: 'clamp_min',
561
+ label: 'clamp_min',
562
+ detail: 'clamp_min(v instant-vector, min scalar)',
563
+ documentation: 'Clamps the sample values of all elements in `v` to have a lower limit of `min`.'
564
+ }, {
565
+ insertText: 'count_scalar',
566
+ label: 'count_scalar',
567
+ detail: 'count_scalar(v instant-vector)',
568
+ documentation: 'Returns the number of elements in a time series vector as a scalar. This is in contrast to the `count()` aggregation operator, which always returns a vector (an empty one if the input vector is empty) and allows grouping by labels via a `by` clause.'
569
+ }, {
570
+ insertText: 'deg',
571
+ label: 'deg',
572
+ detail: 'deg(v instant-vector)',
573
+ documentation: 'Converts radians to degrees for all elements in v'
574
+ }, {
575
+ insertText: 'day_of_month',
576
+ label: 'day_of_month',
577
+ detail: 'day_of_month(v=vector(time()) instant-vector)',
578
+ documentation: 'Returns the day of the month for each of the given times in UTC. Returned values are from 1 to 31.'
579
+ }, {
580
+ insertText: 'day_of_week',
581
+ label: 'day_of_week',
582
+ detail: 'day_of_week(v=vector(time()) instant-vector)',
583
+ documentation: 'Returns the day of the week for each of the given times in UTC. Returned values are from 0 to 6, where 0 means Sunday etc.'
584
+ }, {
585
+ insertText: 'day_of_year',
586
+ label: 'day_of_year',
587
+ detail: 'day_of_year(v=vector(time()) instant-vector)',
588
+ documentation: 'Returns the day of the year for each of the given times in UTC. Returned values are from 1 to 365 for non-leap years, and 1 to 366 in leap years.'
589
+ }, {
590
+ insertText: 'days_in_month',
591
+ label: 'days_in_month',
592
+ detail: 'days_in_month(v=vector(time()) instant-vector)',
593
+ documentation: 'Returns number of days in the month for each of the given times in UTC. Returned values are from 28 to 31.'
594
+ }, {
595
+ insertText: 'delta',
596
+ label: 'delta',
597
+ detail: 'delta(v range-vector)',
598
+ documentation: 'Calculates the difference between the first and last value of each time series element in a range vector `v`, returning an instant vector with the given deltas and equivalent labels. The delta is extrapolated to cover the full time range as specified in the range vector selector, so that it is possible to get a non-integer result even if the sample values are all integers.'
599
+ }, {
600
+ insertText: 'deriv',
601
+ label: 'deriv',
602
+ detail: 'deriv(v range-vector)',
603
+ documentation: 'Calculates the per-second derivative of the time series in a range vector `v`, using simple linear regression.'
604
+ }, {
605
+ insertText: 'drop_common_labels',
606
+ label: 'drop_common_labels',
607
+ detail: 'drop_common_labels(instant-vector)',
608
+ documentation: 'Drops all labels that have the same name and value across all series in the input vector.'
609
+ }, {
610
+ insertText: 'exp',
611
+ label: 'exp',
612
+ detail: 'exp(v instant-vector)',
613
+ documentation: 'Calculates the exponential function for all elements in `v`.\nSpecial cases are:\n* `Exp(+Inf) = +Inf` \n* `Exp(NaN) = NaN`'
614
+ }, {
615
+ insertText: 'floor',
616
+ label: 'floor',
617
+ detail: 'floor(v instant-vector)',
618
+ documentation: 'Rounds the sample values of all elements in `v` down to the nearest integer.'
619
+ }, {
620
+ insertText: 'histogram_quantile',
621
+ label: 'histogram_quantile',
622
+ detail: 'histogram_quantile(φ float, b instant-vector)',
623
+ documentation: 'Calculates the φ-quantile (0 ≤ φ ≤ 1) from the buckets `b` of a histogram. The samples in `b` are the counts of observations in each bucket. Each sample must have a label `le` where the label value denotes the inclusive upper bound of the bucket. (Samples without such a label are silently ignored.) The histogram metric type automatically provides time series with the `_bucket` suffix and the appropriate labels.'
624
+ }, {
625
+ insertText: 'holt_winters',
626
+ label: 'holt_winters',
627
+ detail: 'holt_winters(v range-vector, sf scalar, tf scalar)',
628
+ documentation: 'Produces a smoothed value for time series based on the range in `v`. The lower the smoothing factor `sf`, the more importance is given to old data. The higher the trend factor `tf`, the more trends in the data is considered. Both `sf` and `tf` must be between 0 and 1.'
629
+ }, {
630
+ insertText: 'hour',
631
+ label: 'hour',
632
+ detail: 'hour(v=vector(time()) instant-vector)',
633
+ documentation: 'Returns the hour of the day for each of the given times in UTC. Returned values are from 0 to 23.'
634
+ }, {
635
+ insertText: 'idelta',
636
+ label: 'idelta',
637
+ detail: 'idelta(v range-vector)',
638
+ documentation: 'Calculates the difference between the last two samples in the range vector `v`, returning an instant vector with the given deltas and equivalent labels.'
639
+ }, {
640
+ insertText: 'increase',
641
+ label: 'increase',
642
+ detail: 'increase(v range-vector)',
643
+ documentation: 'Calculates the increase in the time series in the range vector. Breaks in monotonicity (such as counter resets due to target restarts) are automatically adjusted for. The increase is extrapolated to cover the full time range as specified in the range vector selector, so that it is possible to get a non-integer result even if a counter increases only by integer increments.'
644
+ }, {
645
+ insertText: 'irate',
646
+ label: 'irate',
647
+ detail: 'irate(v range-vector)',
648
+ documentation: 'Calculates the per-second instant rate of increase of the time series in the range vector. This is based on the last two data points. Breaks in monotonicity (such as counter resets due to target restarts) are automatically adjusted for.'
649
+ }, {
650
+ insertText: 'label_join',
651
+ label: 'label_join',
652
+ detail: 'label_join(v instant-vector, dst_label string, separator string, src_label_1 string, src_label_2 string, ...)',
653
+ documentation: 'For each timeseries in `v`, joins all the values of all the `src_labels` using `separator` and returns the timeseries with the label `dst_label` containing the joined value. There can be any number of `src_labels` in this function.'
654
+ }, {
655
+ insertText: 'label_replace',
656
+ label: 'label_replace',
657
+ detail: 'label_replace(v instant-vector, dst_label string, replacement string, src_label string, regex string)',
658
+ documentation: "For each timeseries in `v`, `label_replace(v instant-vector, dst_label string, replacement string, src_label string, regex string)` matches the regular expression `regex` against the label `src_label`. If it matches, then the timeseries is returned with the label `dst_label` replaced by the expansion of `replacement`. `$1` is replaced with the first matching subgroup, `$2` with the second etc. If the regular expression doesn't match then the timeseries is returned unchanged."
659
+ }, {
660
+ insertText: 'ln',
661
+ label: 'ln',
662
+ detail: 'ln(v instant-vector)',
663
+ documentation: 'Calculates the natural logarithm for all elements in `v`.\nSpecial cases are:\n * `ln(+Inf) = +Inf`\n * `ln(0) = -Inf`\n * `ln(x < 0) = NaN`\n * `ln(NaN) = NaN`'
664
+ }, {
665
+ insertText: 'log2',
666
+ label: 'log2',
667
+ detail: 'log2(v instant-vector)',
668
+ documentation: 'Calculates the binary logarithm for all elements in `v`. The special cases are equivalent to those in `ln`.'
669
+ }, {
670
+ insertText: 'log10',
671
+ label: 'log10',
672
+ detail: 'log10(v instant-vector)',
673
+ documentation: 'Calculates the decimal logarithm for all elements in `v`. The special cases are equivalent to those in `ln`.'
674
+ }, {
675
+ insertText: 'minute',
676
+ label: 'minute',
677
+ detail: 'minute(v=vector(time()) instant-vector)',
678
+ documentation: 'Returns the minute of the hour for each of the given times in UTC. Returned values are from 0 to 59.'
679
+ }, {
680
+ insertText: 'month',
681
+ label: 'month',
682
+ detail: 'month(v=vector(time()) instant-vector)',
683
+ documentation: 'Returns the month of the year for each of the given times in UTC. Returned values are from 1 to 12, where 1 means January etc.'
684
+ }, {
685
+ insertText: 'pi',
686
+ label: 'pi',
687
+ detail: 'pi()',
688
+ documentation: 'Returns pi'
689
+ }, {
690
+ insertText: 'predict_linear',
691
+ label: 'predict_linear',
692
+ detail: 'predict_linear(v range-vector, t scalar)',
693
+ documentation: 'Predicts the value of time series `t` seconds from now, based on the range vector `v`, using simple linear regression.'
694
+ }, {
695
+ insertText: 'rad',
696
+ label: 'rad',
697
+ detail: 'rad(v instant-vector)',
698
+ documentation: 'Converts degrees to radians for all elements in v'
699
+ }, {
700
+ insertText: 'rate',
701
+ label: 'rate',
702
+ detail: 'rate(v range-vector)',
703
+ documentation: "Calculates the per-second average rate of increase of the time series in the range vector. Breaks in monotonicity (such as counter resets due to target restarts) are automatically adjusted for. Also, the calculation extrapolates to the ends of the time range, allowing for missed scrapes or imperfect alignment of scrape cycles with the range's time period."
704
+ }, {
705
+ insertText: 'resets',
706
+ label: 'resets',
707
+ detail: 'resets(v range-vector)',
708
+ documentation: 'For each input time series, `resets(v range-vector)` returns the number of counter resets within the provided time range as an instant vector. Any decrease in the value between two consecutive samples is interpreted as a counter reset.'
709
+ }, {
710
+ insertText: 'round',
711
+ label: 'round',
712
+ detail: 'round(v instant-vector, to_nearest=1 scalar)',
713
+ documentation: 'Rounds the sample values of all elements in `v` to the nearest integer. Ties are resolved by rounding up. The optional `to_nearest` argument allows specifying the nearest multiple to which the sample values should be rounded. This multiple may also be a fraction.'
714
+ }, {
715
+ insertText: 'scalar',
716
+ label: 'scalar',
717
+ detail: 'scalar(v instant-vector)',
718
+ documentation: 'Given a single-element input vector, `scalar(v instant-vector)` returns the sample value of that single element as a scalar. If the input vector does not have exactly one element, `scalar` will return `NaN`.'
719
+ }, {
720
+ insertText: 'sgn',
721
+ label: 'sgn',
722
+ detail: 'sgn(v instant-vector)',
723
+ documentation: 'Returns a vector with all sample values converted to their sign, defined as this: 1 if v is positive, -1 if v is negative and 0 if v is equal to zero.'
724
+ }, {
725
+ insertText: 'sort',
726
+ label: 'sort',
727
+ detail: 'sort(v instant-vector)',
728
+ documentation: 'Returns vector elements sorted by their sample values, in ascending order.'
729
+ }, {
730
+ insertText: 'sort_desc',
731
+ label: 'sort_desc',
732
+ detail: 'sort_desc(v instant-vector)',
733
+ documentation: 'Returns vector elements sorted by their sample values, in descending order.'
734
+ }, {
735
+ insertText: 'sqrt',
736
+ label: 'sqrt',
737
+ detail: 'sqrt(v instant-vector)',
738
+ documentation: 'Calculates the square root of all elements in `v`.'
739
+ }, {
740
+ insertText: 'time',
741
+ label: 'time',
742
+ detail: 'time()',
743
+ documentation: 'Returns the number of seconds since January 1, 1970 UTC. Note that this does not actually return the current time, but the time at which the expression is to be evaluated.'
744
+ }, {
745
+ insertText: 'timestamp',
746
+ label: 'timestamp',
747
+ detail: 'timestamp(v instant-vector)',
748
+ documentation: 'Returns the timestamp of each of the samples of the given vector as the number of seconds since January 1, 1970 UTC.'
749
+ }, {
750
+ insertText: 'vector',
751
+ label: 'vector',
752
+ detail: 'vector(s scalar)',
753
+ documentation: 'Returns the scalar `s` as a vector with no labels.'
754
+ }, {
755
+ insertText: 'year',
756
+ label: 'year',
757
+ detail: 'year(v=vector(time()) instant-vector)',
758
+ documentation: 'Returns the year for each of the given times in UTC.'
759
+ }, {
760
+ insertText: 'avg_over_time',
761
+ label: 'avg_over_time',
762
+ detail: 'avg_over_time(range-vector)',
763
+ documentation: 'The average value of all points in the specified interval.'
764
+ }, {
765
+ insertText: 'min_over_time',
766
+ label: 'min_over_time',
767
+ detail: 'min_over_time(range-vector)',
768
+ documentation: 'The minimum value of all points in the specified interval.'
769
+ }, {
770
+ insertText: 'max_over_time',
771
+ label: 'max_over_time',
772
+ detail: 'max_over_time(range-vector)',
773
+ documentation: 'The maximum value of all points in the specified interval.'
774
+ }, {
775
+ insertText: 'sum_over_time',
776
+ label: 'sum_over_time',
777
+ detail: 'sum_over_time(range-vector)',
778
+ documentation: 'The sum of all values in the specified interval.'
779
+ }, {
780
+ insertText: 'count_over_time',
781
+ label: 'count_over_time',
782
+ detail: 'count_over_time(range-vector)',
783
+ documentation: 'The count of all values in the specified interval.'
784
+ }, {
785
+ insertText: 'quantile_over_time',
786
+ label: 'quantile_over_time',
787
+ detail: 'quantile_over_time(scalar, range-vector)',
788
+ documentation: 'The φ-quantile (0 ≤ φ ≤ 1) of the values in the specified interval.'
789
+ }, {
790
+ insertText: 'stddev_over_time',
791
+ label: 'stddev_over_time',
792
+ detail: 'stddev_over_time(range-vector)',
793
+ documentation: 'The population standard deviation of the values in the specified interval.'
794
+ }, {
795
+ insertText: 'stdvar_over_time',
796
+ label: 'stdvar_over_time',
797
+ detail: 'stdvar_over_time(range-vector)',
798
+ documentation: 'The population standard variance of the values in the specified interval.'
799
+ }, {
800
+ insertText: 'last_over_time',
801
+ label: 'last_over_time',
802
+ detail: 'last_over_time(range-vector)',
803
+ documentation: 'The most recent point value in specified interval.'
804
+ }, {
805
+ insertText: 'present_over_time',
806
+ label: 'present_over_time',
807
+ detail: 'present_over_time(range-vector)',
808
+ documentation: 'The value 1 for any series in the specified interval.'
809
+ }, {
810
+ insertText: 'histogram_avg',
811
+ label: 'histogram_avg',
812
+ detail: 'histogram_avg(v instant-vector)',
813
+ documentation: 'Returns the arithmetic average of observed values stored in a native histogram. Samples that are not native histograms are ignored and do not show up in the returned vector.'
814
+ }, {
815
+ insertText: 'histogram_count',
816
+ label: 'histogram_count',
817
+ detail: 'histogram_count(v instant-vector)',
818
+ documentation: 'Returns the count of observations stored in a native histogram.'
819
+ }, {
820
+ insertText: 'histogram_sum',
821
+ label: 'histogram_sum',
822
+ detail: 'histogram_sum(v instant-vector)',
823
+ documentation: 'Returns the sum of observations stored in a native histogram.'
824
+ }, {
825
+ insertText: 'histogram_fraction',
826
+ label: 'histogram_fraction',
827
+ detail: 'histogram_fraction(lower scalar, upper scalar, v instant-vector)',
828
+ documentation: 'Returns the estimated fraction of observations between the provided lower and upper values.'
829
+ }, {
830
+ insertText: 'histogram_stddev',
831
+ label: 'histogram_stddev',
832
+ detail: 'histogram_stddev(v instant-vector)',
833
+ documentation: 'Returns the estimated standard deviation of observations in a native histogram, based on the geometric mean of the buckets where the observations lie.'
834
+ }, {
835
+ insertText: 'histogram_stdvar',
836
+ label: 'histogram_stdvar',
837
+ detail: 'histogram_stdvar(v instant-vector)',
838
+ documentation: 'Returns the estimated standard variance of observations in a native histogram.'
839
+ }]);
840
+
841
+ var NeverCaseError = /*#__PURE__*/function (_Error) {
842
+ function NeverCaseError(_value) {
843
+ return _Error.call(this, 'should never happen') || this;
844
+ }
845
+ _inheritsLoose(NeverCaseError, _Error);
846
+ return NeverCaseError;
847
+ }(/*#__PURE__*/_wrapNativeSuper(Error));
848
+ // based on the openmetrics-documentation, the 3 symbols we have to handle are:
849
+ // - \n ... the newline character
850
+ // - \ ... the backslash character
851
+ // - " ... the double-quote character
852
+ function escapeLabelValueInExactSelector(labelValue) {
853
+ return labelValue.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"');
854
+ }
855
+ function makeSelector(metricName, labels, labelName) {
856
+ if (!labels || labels.length === 0) {
857
+ return metricName;
858
+ }
859
+ var allLabels = [].concat(labels).filter(function (label) {
860
+ return label.name !== labelName && label.value !== '';
861
+ });
862
+ var allLabelTexts = allLabels.map(function (label) {
863
+ return "" + label.name + label.op + "\"" + escapeLabelValueInExactSelector(label.value) + "\"";
864
+ });
865
+ return "{" + allLabelTexts.join(',') + "}";
866
+ }
867
+
868
+ var DEFAULT_SERIES_LIMIT = '40000';
869
+ var badRequest = 400;
870
+ var unprocessableEntity = 422;
871
+ var serviceUnavailable = 503;
872
+ var CODE_MODE_SUGGESTIONS_INCOMPLETE_EVENT = 'codeModeSuggestionsIncomplete';
873
+ var DataProvider = /*#__PURE__*/function () {
874
+ function DataProvider(params) {
875
+ var _this = this;
876
+ this.lookbackInterval = 60 * 60 * 1000 * 12; // 12 hours
877
+ this.variablesNames = [];
878
+ this.httpMethod = 'GET';
879
+ this.apiPrefix = '/api/v1';
880
+ this.customRequest = function (input, init) {
881
+ return fetch(input, init);
882
+ };
883
+ this.fetchSeries = /*#__PURE__*/function () {
884
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(selector, withLimit) {
885
+ var end, start, url, urlParams, request;
886
+ return _regenerator().w(function (_context) {
887
+ while (1) switch (_context.n) {
888
+ case 0:
889
+ end = new Date();
890
+ start = new Date(end.getTime() - _this.lookbackInterval);
891
+ url = _this.apiPrefix + "/series";
892
+ urlParams = {
893
+ start: start.toISOString(),
894
+ end: end.toISOString()
895
+ };
896
+ if (selector) {
897
+ urlParams['match[]'] = selector;
898
+ }
899
+ if (withLimit !== 'none') {
900
+ urlParams = _extends({}, urlParams, {
901
+ limit: withLimit != null ? withLimit : DEFAULT_SERIES_LIMIT
902
+ });
903
+ }
904
+ request = _this.buildRequest(url, new URLSearchParams(urlParams));
905
+ _context.n = 1;
906
+ return _this.request(request.uri, {
907
+ method: _this.httpMethod,
908
+ body: request.body
909
+ })["catch"](function () {
910
+ return [];
911
+ });
912
+ case 1:
913
+ return _context.a(2, _context.v);
914
+ }
915
+ }, _callee);
916
+ }));
917
+ return function (_x, _x2) {
918
+ return _ref.apply(this, arguments);
919
+ };
920
+ }();
921
+ this.fetchLabels = /*#__PURE__*/function () {
922
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(selector) {
923
+ var end, start, url, urlParams, request;
924
+ return _regenerator().w(function (_context2) {
925
+ while (1) switch (_context2.n) {
926
+ case 0:
927
+ end = new Date();
928
+ start = new Date(end.getTime() - _this.lookbackInterval);
929
+ url = _this.apiPrefix + "/labels";
930
+ urlParams = {
931
+ start: start.toISOString(),
932
+ end: end.toISOString()
933
+ };
934
+ if (selector) {
935
+ urlParams['match[]'] = selector;
936
+ }
937
+ request = _this.buildRequest(url, new URLSearchParams(urlParams));
938
+ _context2.n = 1;
939
+ return _this.request(request.uri, {
940
+ method: _this.httpMethod,
941
+ body: request.body
942
+ }).then(function (res) {
943
+ _this.labelKeys = res;
944
+ return res;
945
+ })["catch"](function () {
946
+ return [];
947
+ });
948
+ case 1:
949
+ return _context2.a(2, _context2.v);
950
+ }
951
+ }, _callee2);
952
+ }));
953
+ return function (_x3) {
954
+ return _ref2.apply(this, arguments);
955
+ };
956
+ }();
957
+ this.fetchLabelValues = /*#__PURE__*/function () {
958
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(labelName, selector) {
959
+ var end, start, url, urlParams, request;
960
+ return _regenerator().w(function (_context3) {
961
+ while (1) switch (_context3.n) {
962
+ case 0:
963
+ end = new Date();
964
+ start = new Date(end.getTime() - _this.lookbackInterval);
965
+ url = _this.apiPrefix + "/label/" + labelName + "/values";
966
+ urlParams = {
967
+ start: start.toISOString(),
968
+ end: end.toISOString()
969
+ };
970
+ if (selector) {
971
+ urlParams['match[]'] = selector;
972
+ }
973
+ request = _this.buildRequest(url, new URLSearchParams(urlParams));
974
+ _context3.n = 1;
975
+ return _this.request(request.uri, {
976
+ method: _this.httpMethod,
977
+ body: request.body
978
+ })["catch"](function () {
979
+ return [];
980
+ });
981
+ case 1:
982
+ return _context3.a(2, _context3.v);
983
+ }
984
+ }, _callee3);
985
+ }));
986
+ return function (_x4, _x5) {
987
+ return _ref3.apply(this, arguments);
988
+ };
989
+ }();
990
+ this.start = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() {
991
+ var _t;
992
+ return _regenerator().w(function (_context4) {
993
+ while (1) switch (_context4.n) {
994
+ case 0:
995
+ _context4.n = 1;
996
+ return _this.fetchLabelValues('__name__', makeSelector('', [], '__name__'));
997
+ case 1:
998
+ _t = _context4.v;
999
+ if (_t) {
1000
+ _context4.n = 2;
1001
+ break;
1002
+ }
1003
+ _t = [];
1004
+ case 2:
1005
+ _this.metrics = _t;
1006
+ return _context4.a(2, Promise.all([_this.loadMetricsMetadata()]));
1007
+ }
1008
+ }, _callee4);
1009
+ }));
1010
+ this.inputInRange = '';
1011
+ this.metricNamesSuggestionLimit = 1000;
1012
+ this.suggestionsIncomplete = false;
1013
+ this.url = params.url ? params.url : '';
1014
+ this.errorHandler = params.httpErrorHandler;
1015
+ if (params.lookbackInterval) {
1016
+ this.lookbackInterval = params.lookbackInterval;
1017
+ }
1018
+ if (params.variablesNames) {
1019
+ this.variablesNames = [].concat(params.variablesNames);
1020
+ }
1021
+ if (params.request) {
1022
+ this.customRequest = params.request;
1023
+ }
1024
+ if (params.httpMethod) {
1025
+ this.httpMethod = params.httpMethod;
1026
+ }
1027
+ if (params.apiPrefix) {
1028
+ this.apiPrefix = params.apiPrefix;
1029
+ }
1030
+ this.metrics = [];
1031
+ this.labelKeys = [];
1032
+ }
1033
+ var _proto = DataProvider.prototype;
1034
+ _proto.getVariablesNames = function getVariablesNames() {
1035
+ return this.variablesNames;
1036
+ };
1037
+ _proto.setVariablesNames = function setVariablesNames(variablesNames) {
1038
+ this.variablesNames = [].concat(variablesNames);
1039
+ };
1040
+ _proto.buildRequest = function buildRequest(endpoint, params) {
1041
+ var uri = endpoint;
1042
+ var body = params;
1043
+ if (this.httpMethod === 'GET') {
1044
+ uri = uri + "?" + params;
1045
+ body = null;
1046
+ }
1047
+ return {
1048
+ uri: uri,
1049
+ body: body
1050
+ };
1051
+ };
1052
+ _proto.request = function request(resource, init) {
1053
+ var _this2 = this;
1054
+ return this.customRequest(this.url + resource, init).then(function (res) {
1055
+ if (!res.ok && ![badRequest, unprocessableEntity, serviceUnavailable].includes(res.status)) {
1056
+ throw new Error(res.statusText);
1057
+ }
1058
+ return res;
1059
+ }).then(function (res) {
1060
+ return res.json();
1061
+ }).then(function (apiRes) {
1062
+ if (apiRes.status === 'error') {
1063
+ var error = new Error(apiRes.error !== undefined ? apiRes.error : 'missing "error" field in response JSON');
1064
+ if (_this2.errorHandler) {
1065
+ _this2.errorHandler(error);
1066
+ }
1067
+ throw error;
1068
+ }
1069
+ if (apiRes.data === undefined) {
1070
+ var _error = new Error(apiRes.error !== undefined ? apiRes.error : 'missing "data" field in response JSON');
1071
+ if (_this2.errorHandler) {
1072
+ _this2.errorHandler(_error);
1073
+ }
1074
+ throw _error;
1075
+ }
1076
+ return apiRes.data;
1077
+ })["catch"](function (error) {
1078
+ if (_this2.errorHandler) {
1079
+ _this2.errorHandler(error);
1080
+ }
1081
+ throw error;
1082
+ });
1083
+ };
1084
+ _proto.getAllMetricNames = function getAllMetricNames() {
1085
+ return this.metrics;
1086
+ };
1087
+ _proto.loadMetricsMetadata = /*#__PURE__*/function () {
1088
+ var _loadMetricsMetadata = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5() {
1089
+ var request;
1090
+ return _regenerator().w(function (_context5) {
1091
+ while (1) switch (_context5.n) {
1092
+ case 0:
1093
+ request = this.buildRequest(this.apiPrefix + "/metadata", new URLSearchParams({}));
1094
+ _context5.n = 1;
1095
+ return this.request(request.uri, {
1096
+ method: this.httpMethod,
1097
+ body: request.body
1098
+ })["catch"](function () {
1099
+ return {};
1100
+ });
1101
+ case 1:
1102
+ this.metricsMetadata = _context5.v;
1103
+ case 2:
1104
+ return _context5.a(2);
1105
+ }
1106
+ }, _callee5, this);
1107
+ }));
1108
+ function loadMetricsMetadata() {
1109
+ return _loadMetricsMetadata.apply(this, arguments);
1110
+ }
1111
+ return loadMetricsMetadata;
1112
+ }();
1113
+ _proto.metricNamesToMetrics = function metricNamesToMetrics(metricNames) {
1114
+ var _this3 = this;
1115
+ var result = metricNames.map(function (m) {
1116
+ var _this3$metricsMetadat, _metaItem$help, _metaItem$type;
1117
+ var metaItem = (_this3$metricsMetadat = _this3.metricsMetadata) == null ? void 0 : _this3$metricsMetadat[m];
1118
+ return {
1119
+ name: m,
1120
+ help: (_metaItem$help = metaItem == null ? void 0 : metaItem.help) != null ? _metaItem$help : '',
1121
+ type: (_metaItem$type = metaItem == null ? void 0 : metaItem.type) != null ? _metaItem$type : ''
1122
+ };
1123
+ });
1124
+ return result;
1125
+ };
1126
+ _proto.setInputInRange = function setInputInRange(textInput) {
1127
+ this.inputInRange = textInput;
1128
+ };
1129
+ _proto.enableAutocompleteSuggestionsUpdate = function enableAutocompleteSuggestionsUpdate() {
1130
+ this.suggestionsIncomplete = true;
1131
+ dispatchEvent(new CustomEvent(CODE_MODE_SUGGESTIONS_INCOMPLETE_EVENT, {
1132
+ detail: {
1133
+ limit: this.metricNamesSuggestionLimit
1134
+ }
1135
+ }));
1136
+ };
1137
+ return _createClass(DataProvider, [{
1138
+ key: "monacoSettings",
1139
+ get: function get() {
1140
+ return {
1141
+ /**
1142
+ * Enable autocomplete suggestions update on every input change.
1143
+ *
1144
+ * @remarks
1145
+ * If fuzzy search is used in `getCompletions` to trim down results to improve performance,
1146
+ * we need to instruct Monaco to update the completions on every input change, so that the
1147
+ * completions reflect the current input.
1148
+ */
1149
+ enableAutocompleteSuggestionsUpdate: this.enableAutocompleteSuggestionsUpdate.bind(this),
1150
+ inputInRange: this.inputInRange,
1151
+ setInputInRange: this.setInputInRange.bind(this),
1152
+ suggestionsIncomplete: this.suggestionsIncomplete
1153
+ };
1154
+ }
1155
+ }]);
1156
+ }();
1157
+
1158
+ function move(node, direction) {
1159
+ switch (direction) {
1160
+ case 'parent':
1161
+ return node.parent;
1162
+ case 'firstChild':
1163
+ return node.firstChild;
1164
+ case 'lastChild':
1165
+ return node.lastChild;
1166
+ case 'nextSibling':
1167
+ return node.nextSibling;
1168
+ default:
1169
+ throw new NeverCaseError(direction);
1170
+ }
1171
+ }
1172
+ function walk(node, path) {
1173
+ var current = node;
1174
+ for (var _iterator = _createForOfIteratorHelperLoose(path), _step; !(_step = _iterator()).done;) {
1175
+ var _step$value = _step.value,
1176
+ direction = _step$value[0],
1177
+ expectedType = _step$value[1];
1178
+ current = move(current, direction);
1179
+ if (current === null) {
1180
+ // we could not move in the direction, we stop
1181
+ return null;
1182
+ }
1183
+ if (current.type.id !== expectedType) {
1184
+ // the reached node has wrong type, we stop
1185
+ return null;
1186
+ }
1187
+ }
1188
+ return current;
1189
+ }
1190
+ function getNodeText(node, text) {
1191
+ return text.slice(node.from, node.to);
1192
+ }
1193
+ function parsePromQLStringLiteral(text) {
1194
+ // if it is a string-literal, it is inside quotes of some kind
1195
+ var inside = text.slice(1, text.length - 1);
1196
+ // FIXME: support https://prometheus.io/docs/prometheus/latest/querying/basics/#string-literals
1197
+ // FIXME: maybe check other promql code, if all is supported or not
1198
+ // for now we do only some very simple un-escaping
1199
+ // we start with double-quotes
1200
+ if (text.startsWith('"') && text.endsWith('"')) {
1201
+ // NOTE: this is not 100% perfect, we only unescape the double-quote,
1202
+ // there might be other characters too
1203
+ return inside.replace(/\\"/, '"');
1204
+ }
1205
+ // then single-quote
1206
+ if (text.startsWith("'") && text.endsWith("'")) {
1207
+ // NOTE: this is not 100% perfect, we only unescape the single-quote,
1208
+ // there might be other characters too
1209
+ return inside.replace(/\\'/, "'");
1210
+ }
1211
+ // then backticks
1212
+ if (text.startsWith('`') && text.endsWith('`')) {
1213
+ return inside;
1214
+ }
1215
+ throw new Error('FIXME: invalid string literal');
1216
+ }
1217
+ function isPathMatch(resolverPath, cursorPath) {
1218
+ return resolverPath.every(function (item, index) {
1219
+ return item === cursorPath[index];
1220
+ });
1221
+ }
1222
+ var ERROR_NODE_NAME = 0; // this is used as error-id
1223
+ var RESOLVERS = [{
1224
+ path: [lezerMetricsql.LabelMatchers, lezerMetricsql.VectorSelector],
1225
+ fun: resolveLabelKeysWithEquals
1226
+ }, {
1227
+ path: [lezerMetricsql.PromQL],
1228
+ fun: resolveTopLevel
1229
+ }, {
1230
+ path: [lezerMetricsql.FunctionCallBody],
1231
+ fun: resolveInFunction
1232
+ }, {
1233
+ path: [lezerMetricsql.StringLiteral, lezerMetricsql.UnquotedLabelMatcher],
1234
+ fun: resolveLabelMatcher
1235
+ }, {
1236
+ path: [ERROR_NODE_NAME, lezerMetricsql.BinaryExpr, lezerMetricsql.PromQL],
1237
+ fun: resolveTopLevel
1238
+ }, {
1239
+ path: [ERROR_NODE_NAME, lezerMetricsql.UnquotedLabelMatcher],
1240
+ fun: resolveLabelMatcher
1241
+ }, {
1242
+ path: [ERROR_NODE_NAME, lezerMetricsql.NumberDurationLiteralInDurationContext, lezerMetricsql.MatrixSelector],
1243
+ fun: resolveDurations
1244
+ }, {
1245
+ path: [lezerMetricsql.GroupingLabels],
1246
+ fun: resolveLabelsForGrouping
1247
+ }];
1248
+ var LABEL_OP_MAP = /*#__PURE__*/new Map([[lezerMetricsql.EqlSingle, '='], [lezerMetricsql.EqlRegex, '=~'], [lezerMetricsql.Neq, '!='], [lezerMetricsql.NeqRegex, '!~']]);
1249
+ function getLabelOp(opNode) {
1250
+ var _LABEL_OP_MAP$get;
1251
+ var opChild = opNode.firstChild;
1252
+ if (opChild === null) {
1253
+ return null;
1254
+ }
1255
+ return (_LABEL_OP_MAP$get = LABEL_OP_MAP.get(opChild.type.id)) != null ? _LABEL_OP_MAP$get : null;
1256
+ }
1257
+ function getLabel(labelMatcherNode, text) {
1258
+ if (labelMatcherNode.type.id !== lezerMetricsql.UnquotedLabelMatcher) {
1259
+ return null;
1260
+ }
1261
+ var nameNode = walk(labelMatcherNode, [['firstChild', lezerMetricsql.LabelName]]);
1262
+ if (nameNode === null) {
1263
+ return null;
1264
+ }
1265
+ var opNode = walk(nameNode, [['nextSibling', lezerMetricsql.MatchOp]]);
1266
+ if (opNode === null) {
1267
+ return null;
1268
+ }
1269
+ var op = getLabelOp(opNode);
1270
+ if (op === null) {
1271
+ return null;
1272
+ }
1273
+ var valueNode = walk(labelMatcherNode, [['lastChild', lezerMetricsql.StringLiteral]]);
1274
+ if (valueNode === null) {
1275
+ return null;
1276
+ }
1277
+ var name = getNodeText(nameNode, text);
1278
+ var value = parsePromQLStringLiteral(getNodeText(valueNode, text));
1279
+ return {
1280
+ name: name,
1281
+ value: value,
1282
+ op: op
1283
+ };
1284
+ }
1285
+ function getLabels(labelMatchersNode, text) {
1286
+ if (labelMatchersNode.type.id !== lezerMetricsql.LabelMatchers) {
1287
+ return [];
1288
+ }
1289
+ var labelNodes = labelMatchersNode.getChildren(lezerMetricsql.UnquotedLabelMatcher);
1290
+ return labelNodes.map(function (ln) {
1291
+ return getLabel(ln, text);
1292
+ }).filter(notEmpty);
1293
+ }
1294
+ function getNodeChildren(node) {
1295
+ var child = node.firstChild;
1296
+ var children = [];
1297
+ while (child !== null) {
1298
+ children.push(child);
1299
+ child = child.nextSibling;
1300
+ }
1301
+ return children;
1302
+ }
1303
+ function getNodeInSubtree(node, typeId) {
1304
+ // first we try the current node
1305
+ if (node.type.id === typeId) {
1306
+ return node;
1307
+ }
1308
+ // then we try the children
1309
+ var children = getNodeChildren(node);
1310
+ for (var _iterator2 = _createForOfIteratorHelperLoose(children), _step2; !(_step2 = _iterator2()).done;) {
1311
+ var child = _step2.value;
1312
+ var n = getNodeInSubtree(child, typeId);
1313
+ if (n !== null) {
1314
+ return n;
1315
+ }
1316
+ }
1317
+ return null;
1318
+ }
1319
+ function resolveLabelsForGrouping(node, text, _pos) {
1320
+ var aggrExpNode = walk(node, [['parent', lezerMetricsql.AggregateModifier], ['parent', lezerMetricsql.AggregateExpr]]);
1321
+ if (aggrExpNode === null) {
1322
+ return null;
1323
+ }
1324
+ var bodyNode = aggrExpNode.getChild(lezerMetricsql.FunctionCallBody);
1325
+ if (bodyNode === null) {
1326
+ return null;
1327
+ }
1328
+ var metricIdNode = getNodeInSubtree(bodyNode, lezerMetricsql.Identifier);
1329
+ if (metricIdNode === null) {
1330
+ return null;
1331
+ }
1332
+ var metricName = getNodeText(metricIdNode, text);
1333
+ return {
1334
+ type: 'IN_GROUPING',
1335
+ metricName: metricName,
1336
+ otherLabels: []
1337
+ };
1338
+ }
1339
+ function resolveLabelMatcher(node, text, _pos) {
1340
+ // we can arrive here in two situation. `node` is either:
1341
+ // - a StringNode (like in `{job="^"}`)
1342
+ // - or an error node (like in `{job=^}`)
1343
+ var inStringNode = !node.type.isError;
1344
+ var parent = walk(node, [['parent', lezerMetricsql.UnquotedLabelMatcher]]);
1345
+ if (parent === null) {
1346
+ return null;
1347
+ }
1348
+ var labelNameNode = walk(parent, [['firstChild', lezerMetricsql.LabelName]]);
1349
+ if (labelNameNode === null) {
1350
+ return null;
1351
+ }
1352
+ var labelName = getNodeText(labelNameNode, text);
1353
+ var labelMatchersNode = walk(parent, [['parent', lezerMetricsql.LabelMatchers]]);
1354
+ if (labelMatchersNode === null) {
1355
+ return null;
1356
+ }
1357
+ // now we need to find the other names
1358
+ var allLabels = getLabels(labelMatchersNode, text);
1359
+ // we need to remove "our" label from all-labels, if it is in there
1360
+ var otherLabels = allLabels.filter(function (label) {
1361
+ return label.name !== labelName;
1362
+ });
1363
+ var metricNameNode = walk(labelMatchersNode, [['parent', lezerMetricsql.VectorSelector], ['firstChild', lezerMetricsql.Identifier]]);
1364
+ if (metricNameNode === null) {
1365
+ // we are probably in a situation without a metric name
1366
+ return {
1367
+ type: 'IN_LABEL_SELECTOR_WITH_LABEL_NAME',
1368
+ labelName: labelName,
1369
+ betweenQuotes: inStringNode,
1370
+ otherLabels: otherLabels
1371
+ };
1372
+ }
1373
+ var metricName = getNodeText(metricNameNode, text);
1374
+ return {
1375
+ type: 'IN_LABEL_SELECTOR_WITH_LABEL_NAME',
1376
+ metricName: metricName,
1377
+ labelName: labelName,
1378
+ betweenQuotes: inStringNode,
1379
+ otherLabels: otherLabels
1380
+ };
1381
+ }
1382
+ function resolveTopLevel() {
1383
+ return {
1384
+ type: 'AT_ROOT'
1385
+ };
1386
+ }
1387
+ function resolveInFunction() {
1388
+ return {
1389
+ type: 'IN_FUNCTION'
1390
+ };
1391
+ }
1392
+ function resolveDurations() {
1393
+ return {
1394
+ type: 'IN_DURATION'
1395
+ };
1396
+ }
1397
+ function resolveLabelKeysWithEquals(node, text, pos) {
1398
+ // next false positive:
1399
+ // `something{a="1"^}`
1400
+ var child = walk(node, [['firstChild', lezerMetricsql.UnquotedLabelMatcher]]);
1401
+ if (child !== null) {
1402
+ // means the label-matching part contains at least one label already.
1403
+ //
1404
+ // in this case, we will need to have a `,` character at the end,
1405
+ // to be able to suggest adding the next label.
1406
+ // the area between the end-of-the-child-node and the cursor-pos
1407
+ // must contain a `,` in this case.
1408
+ var textToCheck = text.slice(child.to, pos);
1409
+ if (!textToCheck.includes(',')) {
1410
+ return null;
1411
+ }
1412
+ }
1413
+ var metricNameNode = walk(node, [['parent', lezerMetricsql.VectorSelector], ['firstChild', lezerMetricsql.Identifier]]);
1414
+ var otherLabels = getLabels(node, text);
1415
+ if (metricNameNode === null) {
1416
+ // we are probably in a situation without a metric name.
1417
+ return {
1418
+ type: 'IN_LABEL_SELECTOR_NO_LABEL_NAME',
1419
+ otherLabels: otherLabels
1420
+ };
1421
+ }
1422
+ var metricName = getNodeText(metricNameNode, text);
1423
+ return {
1424
+ type: 'IN_LABEL_SELECTOR_NO_LABEL_NAME',
1425
+ metricName: metricName,
1426
+ otherLabels: otherLabels
1427
+ };
1428
+ }
1429
+ // we find the first error-node in the tree that is at the cursor-position.
1430
+ // NOTE: this might be too slow, might need to optimize it
1431
+ // (ideas: we do not need to go into every subtree, based on from/to)
1432
+ // also, only go to places that are in the sub-tree of the node found
1433
+ // by default by lezer. problem is, `next()` will go upward too,
1434
+ // and we do not want to go higher than our node
1435
+ function getErrorNode(tree, pos) {
1436
+ var cur = tree.cursorAt(pos);
1437
+ while (true) {
1438
+ if (cur.from === pos && cur.to === pos) {
1439
+ var node = cur.node;
1440
+ if (node.type.isError) {
1441
+ return node;
1442
+ }
1443
+ }
1444
+ if (!cur.next()) {
1445
+ break;
1446
+ }
1447
+ }
1448
+ return null;
1449
+ }
1450
+ function getSituation(text, pos) {
1451
+ // there is a special-case when we are at the start of writing text,
1452
+ // so we handle that case first
1453
+ if (text === '') {
1454
+ return {
1455
+ type: 'EMPTY'
1456
+ };
1457
+ }
1458
+ /**
1459
+ PromQL
1460
+ Expr
1461
+ VectorSelector
1462
+ LabelMatchers
1463
+ */
1464
+ var tree = lezerMetricsql.parser.parse(text);
1465
+ // if the tree contains error, it is very probable that
1466
+ // our node is one of those error-nodes.
1467
+ // also, if there are errors, the node lezer finds us,
1468
+ // might not be the best node.
1469
+ // so first we check if there is an error-node at the cursor-position
1470
+ var maybeErrorNode = getErrorNode(tree, pos);
1471
+ var cur = maybeErrorNode != null ? maybeErrorNode.cursor() : tree.cursorAt(pos);
1472
+ var currentNode = cur.node;
1473
+ var ids = [cur.type.id];
1474
+ while (cur.parent()) {
1475
+ ids.push(cur.type.id);
1476
+ }
1477
+ for (var _iterator3 = _createForOfIteratorHelperLoose(RESOLVERS), _step3; !(_step3 = _iterator3()).done;) {
1478
+ var resolver = _step3.value;
1479
+ // i do not use a foreach because i want to stop as soon
1480
+ // as i find something
1481
+ if (isPathMatch(resolver.path, ids)) {
1482
+ return resolver.fun(currentNode, text, pos);
1483
+ }
1484
+ }
1485
+ return null;
1486
+ }
1487
+ function notEmpty(value) {
1488
+ return value !== null && value !== undefined;
1489
+ }
1490
+
1491
+ var metricNamesSearchClient = /*#__PURE__*/new UFuzzy({
1492
+ intraMode: 1
1493
+ });
1494
+ // we order items like: history, functions, metrics
1495
+ function getAllMetricNamesCompletions(dataProvider) {
1496
+ var metricNames = dataProvider.getAllMetricNames();
1497
+ if (metricNames.length > dataProvider.metricNamesSuggestionLimit) {
1498
+ var monacoSettings = dataProvider.monacoSettings;
1499
+ monacoSettings.enableAutocompleteSuggestionsUpdate();
1500
+ if (monacoSettings.inputInRange) {
1501
+ var _metricNamesSearchCli, _metricNamesSearchCli2;
1502
+ metricNames = (_metricNamesSearchCli = (_metricNamesSearchCli2 = metricNamesSearchClient.filter(metricNames, monacoSettings.inputInRange)) == null ? void 0 : _metricNamesSearchCli2.slice(0, dataProvider.metricNamesSuggestionLimit).map(function (idx) {
1503
+ return metricNames[idx];
1504
+ })) != null ? _metricNamesSearchCli : [];
1505
+ } else {
1506
+ metricNames = metricNames.slice(0, dataProvider.metricNamesSuggestionLimit);
1507
+ }
1508
+ }
1509
+ return dataProvider.metricNamesToMetrics(metricNames).map(function (metric) {
1510
+ return {
1511
+ type: 'METRIC_NAME',
1512
+ label: metric.name,
1513
+ insertText: metric.name,
1514
+ detail: metric.name + " : " + metric.type,
1515
+ documentation: metric.help
1516
+ };
1517
+ });
1518
+ }
1519
+ var FUNCTION_COMPLETIONS = /*#__PURE__*/FUNCTIONS.map(function (f) {
1520
+ var _f$insertText;
1521
+ return {
1522
+ type: 'FUNCTION',
1523
+ label: f.label,
1524
+ insertText: (_f$insertText = f.insertText) != null ? _f$insertText : '',
1525
+ detail: f.detail,
1526
+ documentation: f.documentation
1527
+ };
1528
+ });
1529
+ function getAllFunctionsAndMetricNamesCompletions(_x) {
1530
+ return _getAllFunctionsAndMetricNamesCompletions.apply(this, arguments);
1531
+ }
1532
+ function _getAllFunctionsAndMetricNamesCompletions() {
1533
+ _getAllFunctionsAndMetricNamesCompletions = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(dataProvider) {
1534
+ var metricNames;
1535
+ return _regenerator().w(function (_context) {
1536
+ while (1) switch (_context.n) {
1537
+ case 0:
1538
+ metricNames = getAllMetricNamesCompletions(dataProvider);
1539
+ return _context.a(2, [].concat(FUNCTION_COMPLETIONS, metricNames));
1540
+ }
1541
+ }, _callee);
1542
+ }));
1543
+ return _getAllFunctionsAndMetricNamesCompletions.apply(this, arguments);
1544
+ }
1545
+ var DURATION_COMPLETIONS = /*#__PURE__*/['$__interval', '$__range', '$__rate_interval', '1m', '5m', '10m', '30m', '1h', '1d'].map(function (text) {
1546
+ return {
1547
+ type: 'DURATION',
1548
+ label: text,
1549
+ insertText: text
1550
+ };
1551
+ });
1552
+ function getAllHistoryCompletions(_dataProvider) {
1553
+ return [];
1554
+ // function getAllHistoryCompletions(queryHistory: PromHistoryItem[]): Completion[] {
1555
+ // NOTE: the typescript types are wrong. historyItem.query.expr can be undefined
1556
+ // const allHistory = dataProvider.getHistory();
1557
+ // FIXME: find a better history-limit
1558
+ // return allHistory.slice(0, 10).map((expr) => ({
1559
+ // type: 'HISTORY',
1560
+ // label: expr,
1561
+ // insertText: expr,
1562
+ // }));
1563
+ }
1564
+ function getLabelNames(_x2, _x3, _x4) {
1565
+ return _getLabelNames.apply(this, arguments);
1566
+ }
1567
+ function _getLabelNames() {
1568
+ _getLabelNames = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(metric, otherLabels, dataProvider) {
1569
+ var selector, _selector, series, labelNames, _iterator, _step, labelSet, _i, _Object$entries, _Object$entries$_i, key;
1570
+ return _regenerator().w(function (_context2) {
1571
+ while (1) switch (_context2.n) {
1572
+ case 0:
1573
+ if (!(metric === undefined || metric === '')) {
1574
+ _context2.n = 2;
1575
+ break;
1576
+ }
1577
+ selector = makeSelector('', otherLabels);
1578
+ _context2.n = 1;
1579
+ return dataProvider.fetchLabels(selector);
1580
+ case 1:
1581
+ return _context2.a(2, _context2.v);
1582
+ case 2:
1583
+ _selector = makeSelector(metric, otherLabels);
1584
+ _context2.n = 3;
1585
+ return dataProvider.fetchSeries(_selector);
1586
+ case 3:
1587
+ series = _context2.v;
1588
+ labelNames = new Set();
1589
+ _iterator = _createForOfIteratorHelperLoose(series);
1590
+ case 4:
1591
+ if ((_step = _iterator()).done) {
1592
+ _context2.n = 9;
1593
+ break;
1594
+ }
1595
+ labelSet = _step.value;
1596
+ _i = 0, _Object$entries = Object.entries(labelSet);
1597
+ case 5:
1598
+ if (!(_i < _Object$entries.length)) {
1599
+ _context2.n = 8;
1600
+ break;
1601
+ }
1602
+ _Object$entries$_i = _Object$entries[_i], key = _Object$entries$_i[0];
1603
+ if (!(key === '__name__')) {
1604
+ _context2.n = 6;
1605
+ break;
1606
+ }
1607
+ return _context2.a(3, 7);
1608
+ case 6:
1609
+ labelNames.add(key);
1610
+ case 7:
1611
+ _i++;
1612
+ _context2.n = 5;
1613
+ break;
1614
+ case 8:
1615
+ _context2.n = 4;
1616
+ break;
1617
+ case 9:
1618
+ return _context2.a(2, Array.from(labelNames));
1619
+ case 10:
1620
+ return _context2.a(2);
1621
+ }
1622
+ }, _callee2);
1623
+ }));
1624
+ return _getLabelNames.apply(this, arguments);
1625
+ }
1626
+ function getLabelNamesForCompletions(_x5, _x6, _x7, _x8, _x9) {
1627
+ return _getLabelNamesForCompletions.apply(this, arguments);
1628
+ }
1629
+ function _getLabelNamesForCompletions() {
1630
+ _getLabelNamesForCompletions = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(metric, suffix, triggerOnInsert, otherLabels, dataProvider) {
1631
+ var labelNames;
1632
+ return _regenerator().w(function (_context3) {
1633
+ while (1) switch (_context3.n) {
1634
+ case 0:
1635
+ _context3.n = 1;
1636
+ return getLabelNames(metric, otherLabels, dataProvider);
1637
+ case 1:
1638
+ labelNames = _context3.v;
1639
+ return _context3.a(2, labelNames.map(function (text) {
1640
+ return {
1641
+ type: 'LABEL_NAME',
1642
+ label: text,
1643
+ insertText: "" + text + suffix,
1644
+ triggerOnInsert: triggerOnInsert
1645
+ };
1646
+ }));
1647
+ }
1648
+ }, _callee3);
1649
+ }));
1650
+ return _getLabelNamesForCompletions.apply(this, arguments);
1651
+ }
1652
+ function getLabelNamesForSelectorCompletions(_x0, _x1, _x10) {
1653
+ return _getLabelNamesForSelectorCompletions.apply(this, arguments);
1654
+ }
1655
+ function _getLabelNamesForSelectorCompletions() {
1656
+ _getLabelNamesForSelectorCompletions = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(metric, otherLabels, dataProvider) {
1657
+ return _regenerator().w(function (_context4) {
1658
+ while (1) switch (_context4.n) {
1659
+ case 0:
1660
+ return _context4.a(2, getLabelNamesForCompletions(metric, '=', true, otherLabels, dataProvider));
1661
+ }
1662
+ }, _callee4);
1663
+ }));
1664
+ return _getLabelNamesForSelectorCompletions.apply(this, arguments);
1665
+ }
1666
+ function getLabelNamesForByCompletions(_x11, _x12, _x13) {
1667
+ return _getLabelNamesForByCompletions.apply(this, arguments);
1668
+ }
1669
+ function _getLabelNamesForByCompletions() {
1670
+ _getLabelNamesForByCompletions = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(metric, otherLabels, dataProvider) {
1671
+ return _regenerator().w(function (_context5) {
1672
+ while (1) switch (_context5.n) {
1673
+ case 0:
1674
+ return _context5.a(2, getLabelNamesForCompletions(metric, '', false, otherLabels, dataProvider));
1675
+ }
1676
+ }, _callee5);
1677
+ }));
1678
+ return _getLabelNamesForByCompletions.apply(this, arguments);
1679
+ }
1680
+ function getLabelValues(_x14, _x15, _x16, _x17) {
1681
+ return _getLabelValues.apply(this, arguments);
1682
+ }
1683
+ function _getLabelValues() {
1684
+ _getLabelValues = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(metric, labelName, otherLabels, dataProvider) {
1685
+ var selector, _selector2, series, labelValues, _iterator2, _step2, labelSet, _i2, _Object$entries2, _Object$entries2$_i, key, value, variablesNames;
1686
+ return _regenerator().w(function (_context6) {
1687
+ while (1) switch (_context6.n) {
1688
+ case 0:
1689
+ if (!(metric === undefined || metric === '')) {
1690
+ _context6.n = 2;
1691
+ break;
1692
+ }
1693
+ selector = makeSelector('', otherLabels);
1694
+ _context6.n = 1;
1695
+ return dataProvider.fetchLabelValues(labelName, selector);
1696
+ case 1:
1697
+ return _context6.a(2, _context6.v);
1698
+ case 2:
1699
+ _selector2 = makeSelector(metric, otherLabels, labelName);
1700
+ _context6.n = 3;
1701
+ return dataProvider.fetchSeries(_selector2);
1702
+ case 3:
1703
+ series = _context6.v;
1704
+ labelValues = new Set();
1705
+ _iterator2 = _createForOfIteratorHelperLoose(series);
1706
+ case 4:
1707
+ if ((_step2 = _iterator2()).done) {
1708
+ _context6.n = 9;
1709
+ break;
1710
+ }
1711
+ labelSet = _step2.value;
1712
+ _i2 = 0, _Object$entries2 = Object.entries(labelSet);
1713
+ case 5:
1714
+ if (!(_i2 < _Object$entries2.length)) {
1715
+ _context6.n = 8;
1716
+ break;
1717
+ }
1718
+ _Object$entries2$_i = _Object$entries2[_i2], key = _Object$entries2$_i[0], value = _Object$entries2$_i[1];
1719
+ if (!(key === '__name__')) {
1720
+ _context6.n = 6;
1721
+ break;
1722
+ }
1723
+ return _context6.a(3, 7);
1724
+ case 6:
1725
+ if (key === labelName) {
1726
+ labelValues.add(value);
1727
+ }
1728
+ case 7:
1729
+ _i2++;
1730
+ _context6.n = 5;
1731
+ break;
1732
+ case 8:
1733
+ _context6.n = 4;
1734
+ break;
1735
+ case 9:
1736
+ variablesNames = dataProvider.getVariablesNames();
1737
+ return _context6.a(2, variablesNames.concat(Array.from(labelValues)));
1738
+ case 10:
1739
+ return _context6.a(2);
1740
+ }
1741
+ }, _callee6);
1742
+ }));
1743
+ return _getLabelValues.apply(this, arguments);
1744
+ }
1745
+ function getLabelValuesForMetricCompletions(_x18, _x19, _x20, _x21, _x22) {
1746
+ return _getLabelValuesForMetricCompletions.apply(this, arguments);
1747
+ }
1748
+ function _getLabelValuesForMetricCompletions() {
1749
+ _getLabelValuesForMetricCompletions = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(metric, labelName, betweenQuotes, otherLabels, dataProvider) {
1750
+ var values;
1751
+ return _regenerator().w(function (_context7) {
1752
+ while (1) switch (_context7.n) {
1753
+ case 0:
1754
+ _context7.n = 1;
1755
+ return getLabelValues(metric, labelName, otherLabels, dataProvider);
1756
+ case 1:
1757
+ values = _context7.v;
1758
+ return _context7.a(2, values.map(function (text) {
1759
+ return {
1760
+ type: 'LABEL_VALUE',
1761
+ label: text,
1762
+ insertText: betweenQuotes ? text : "\"" + text + "\""
1763
+ };
1764
+ }));
1765
+ }
1766
+ }, _callee7);
1767
+ }));
1768
+ return _getLabelValuesForMetricCompletions.apply(this, arguments);
1769
+ }
1770
+ function getCompletions(situation, dataProvider) {
1771
+ switch (situation.type) {
1772
+ case 'IN_DURATION':
1773
+ return Promise.resolve(DURATION_COMPLETIONS);
1774
+ case 'IN_FUNCTION':
1775
+ return getAllFunctionsAndMetricNamesCompletions(dataProvider);
1776
+ case 'AT_ROOT':
1777
+ {
1778
+ return getAllFunctionsAndMetricNamesCompletions(dataProvider);
1779
+ }
1780
+ case 'EMPTY':
1781
+ {
1782
+ var metricNames = getAllMetricNamesCompletions(dataProvider);
1783
+ var historyCompletions = getAllHistoryCompletions();
1784
+ return Promise.resolve([].concat(historyCompletions, FUNCTION_COMPLETIONS, metricNames));
1785
+ }
1786
+ case 'IN_LABEL_SELECTOR_NO_LABEL_NAME':
1787
+ return getLabelNamesForSelectorCompletions(situation.metricName, situation.otherLabels, dataProvider);
1788
+ case 'IN_GROUPING':
1789
+ return getLabelNamesForByCompletions(situation.metricName, situation.otherLabels, dataProvider);
1790
+ case 'IN_LABEL_SELECTOR_WITH_LABEL_NAME':
1791
+ return getLabelValuesForMetricCompletions(situation.metricName, situation.labelName, situation.betweenQuotes, situation.otherLabels, dataProvider);
1792
+ default:
1793
+ throw new NeverCaseError(situation);
1794
+ }
1795
+ }
1796
+
1797
+ function getMonacoCompletionItemKind(type, monaco) {
1798
+ switch (type) {
1799
+ case 'DURATION':
1800
+ return monaco.languages.CompletionItemKind.Unit;
1801
+ case 'FUNCTION':
1802
+ return monaco.languages.CompletionItemKind.Variable;
1803
+ case 'HISTORY':
1804
+ return monaco.languages.CompletionItemKind.Snippet;
1805
+ case 'LABEL_NAME':
1806
+ return monaco.languages.CompletionItemKind.Enum;
1807
+ case 'LABEL_VALUE':
1808
+ return monaco.languages.CompletionItemKind.EnumMember;
1809
+ case 'METRIC_NAME':
1810
+ return monaco.languages.CompletionItemKind.Constructor;
1811
+ default:
1812
+ throw new NeverCaseError(type);
1813
+ }
1814
+ }
1815
+ function getCompletionProvider(monaco, dataProvider) {
1816
+ var provideCompletionItems = function provideCompletionItems(model, position) {
1817
+ var word = model.getWordAtPosition(position);
1818
+ var range = word != null ? monaco.Range.lift({
1819
+ startLineNumber: position.lineNumber,
1820
+ endLineNumber: position.lineNumber,
1821
+ startColumn: word.startColumn,
1822
+ endColumn: word.endColumn
1823
+ }) : monaco.Range.fromPositions(position);
1824
+ // documentation says `position` will be "adjusted" in `getOffsetAt`
1825
+ // i don't know what that means, to be sure i clone it
1826
+ var positionClone = {
1827
+ column: position.column,
1828
+ lineNumber: position.lineNumber
1829
+ };
1830
+ dataProvider.monacoSettings.setInputInRange(model.getValueInRange(range));
1831
+ // Check to see if the browser supports window.getSelection()
1832
+ if (window.getSelection) {
1833
+ var _window$getSelection;
1834
+ var selectedText = (_window$getSelection = window.getSelection()) == null ? void 0 : _window$getSelection.toString();
1835
+ // If the user has selected text, adjust the cursor position to be at the start of the selection, instead of the end
1836
+ if (selectedText && selectedText.length > 0) {
1837
+ positionClone.column = positionClone.column - selectedText.length;
1838
+ }
1839
+ }
1840
+ var offset = model.getOffsetAt(positionClone);
1841
+ var situation = getSituation(model.getValue(), offset);
1842
+ var completionsPromise = situation != null ? getCompletions(situation, dataProvider) : Promise.resolve([]);
1843
+ return completionsPromise.then(function (items) {
1844
+ // monaco by-default alphabetically orders the items.
1845
+ // to stop it, we use a number-as-string sortkey,
1846
+ // so that monaco keeps the order we use
1847
+ var maxIndexDigits = items.length.toString().length;
1848
+ var suggestions = items.map(function (item, index) {
1849
+ return {
1850
+ kind: getMonacoCompletionItemKind(item.type, monaco),
1851
+ label: item.label,
1852
+ insertText: item.insertText,
1853
+ detail: item.detail,
1854
+ documentation: item.documentation,
1855
+ sortText: index.toString().padStart(maxIndexDigits, '0'),
1856
+ range: range,
1857
+ command: item.triggerOnInsert ? {
1858
+ id: 'editor.action.triggerSuggest',
1859
+ title: ''
1860
+ } : undefined
1861
+ };
1862
+ });
1863
+ return {
1864
+ suggestions: suggestions,
1865
+ incomplete: dataProvider.monacoSettings.suggestionsIncomplete
1866
+ };
1867
+ });
1868
+ };
1869
+ return {
1870
+ triggerCharacters: ['{', ',', '[', '(', '=', '~', ' ', '"'],
1871
+ provideCompletionItems: provideCompletionItems
1872
+ };
1873
+ }
1874
+
1875
+ var ErrorId = 0;
1876
+ function validateQuery(query, interpolatedQuery, queryLines, parser) {
1877
+ if (!query) {
1878
+ return false;
1879
+ }
1880
+ var interpolatedErrors = parseQuery(interpolatedQuery, parser);
1881
+ if (!interpolatedErrors.length) {
1882
+ return false;
1883
+ }
1884
+ var parseErrors = interpolatedErrors;
1885
+ if (query !== interpolatedQuery) {
1886
+ var queryErrors = parseQuery(query, parser);
1887
+ parseErrors = interpolatedErrors.flatMap(function (interpolatedError) {
1888
+ return queryErrors.filter(function (queryError) {
1889
+ return interpolatedError.text === queryError.text;
1890
+ }) || interpolatedError;
1891
+ });
1892
+ }
1893
+ return parseErrors.map(function (parseError) {
1894
+ return findErrorBoundary(query, queryLines, parseError);
1895
+ }).filter(isErrorBoundary);
1896
+ }
1897
+ function parseQuery(query, parser) {
1898
+ var parseErrors = [];
1899
+ var tree = parser.parse(query);
1900
+ tree.iterate({
1901
+ enter: function enter(nodeRef) {
1902
+ if (nodeRef.type.id === ErrorId) {
1903
+ var node = nodeRef.node;
1904
+ parseErrors.push({
1905
+ node: node,
1906
+ text: query.substring(node.from, node.to)
1907
+ });
1908
+ }
1909
+ }
1910
+ });
1911
+ return parseErrors;
1912
+ }
1913
+ function findErrorBoundary(query, queryLines, parseError) {
1914
+ if (queryLines.length === 1) {
1915
+ var isEmptyString = parseError.node.from === parseError.node.to;
1916
+ var errorNode = isEmptyString && parseError.node.parent ? parseError.node.parent : parseError.node;
1917
+ var error = isEmptyString ? query.substring(errorNode.from, errorNode.to) : parseError.text;
1918
+ return {
1919
+ startLineNumber: 1,
1920
+ startColumn: errorNode.from + 1,
1921
+ endLineNumber: 1,
1922
+ endColumn: errorNode.to + 1,
1923
+ error: error
1924
+ };
1925
+ }
1926
+ var startPos = 0,
1927
+ endPos = 0;
1928
+ for (var line = 0; line < queryLines.length; line++) {
1929
+ endPos = startPos + queryLines[line].length;
1930
+ if (parseError.node.from > endPos) {
1931
+ startPos += queryLines[line].length + 1;
1932
+ continue;
1933
+ }
1934
+ return {
1935
+ startLineNumber: line + 1,
1936
+ startColumn: parseError.node.from - startPos + 1,
1937
+ endLineNumber: line + 1,
1938
+ endColumn: parseError.node.to - startPos + 1,
1939
+ error: parseError.text
1940
+ };
1941
+ }
1942
+ return null;
1943
+ }
1944
+ function isErrorBoundary(boundary) {
1945
+ return boundary !== null;
1946
+ }
1947
+
1948
+ var _excluded = ["error"];
1949
+ var PROMQL_LANG_ID = monacoPromql.promLanguageDefinition.id;
1950
+ var EDITOR_HEIGHT_OFFSET = 2;
1951
+ var SIZE_MAP = {
1952
+ small: {
1953
+ className: 'ant-input-sm',
1954
+ top: 1,
1955
+ bottom: 1
1956
+ },
1957
+ middle: {
1958
+ className: 'ant-input-md',
1959
+ top: 1,
1960
+ bottom: 1
1961
+ },
1962
+ large: {
1963
+ className: 'ant-input-lg',
1964
+ top: 3,
1965
+ bottom: 2
1966
+ }
1967
+ };
1968
+ var themeMap = {
1969
+ light: 'vs-light',
1970
+ dark: 'vs-dark'
1971
+ };
1972
+ var getStyles = function getStyles(placeholder) {
1973
+ return {
1974
+ placeholder: css.css({
1975
+ '::after': {
1976
+ content: "'" + placeholder + "'",
1977
+ opacity: 0.6
1978
+ }
1979
+ })
1980
+ };
1981
+ };
1982
+ function PromQLEditor(props) {
1983
+ var id = uuid.v4();
1984
+ var _props$size = props.size,
1985
+ size = _props$size === void 0 ? 'middle' : _props$size,
1986
+ _props$theme = props.theme,
1987
+ theme = _props$theme === void 0 ? 'light' : _props$theme,
1988
+ variablesNames = props.variablesNames,
1989
+ value = props.value,
1990
+ placeholder = props.placeholder,
1991
+ interpolateString = props.interpolateString,
1992
+ onChange = props.onChange,
1993
+ onShiftEnter = props.onShiftEnter,
1994
+ onBlur = props.onBlur;
1995
+ var autocompleteDisposeFun = React.useRef(null);
1996
+ var containerRef = React.useRef(null);
1997
+ var dataProviderRef = React.useRef(null);
1998
+ var styles = getStyles(placeholder);
1999
+ React.useEffect(function () {
2000
+ // 注册 PromQL 语言
2001
+ var aliases = monacoPromql.promLanguageDefinition.aliases,
2002
+ extensions = monacoPromql.promLanguageDefinition.extensions,
2003
+ mimetypes = monacoPromql.promLanguageDefinition.mimetypes;
2004
+ monaco.languages.register({
2005
+ id: PROMQL_LANG_ID,
2006
+ aliases: aliases,
2007
+ extensions: extensions,
2008
+ mimetypes: mimetypes
2009
+ });
2010
+ // 设置语法高亮
2011
+ monaco.languages.setMonarchTokensProvider(PROMQL_LANG_ID, language);
2012
+ // 设置语言配置
2013
+ monaco.languages.setLanguageConfiguration(PROMQL_LANG_ID, languageConfiguration);
2014
+ return function () {
2015
+ autocompleteDisposeFun.current == null || autocompleteDisposeFun.current();
2016
+ };
2017
+ }, []);
2018
+ var handleEditorDidMount = function handleEditorDidMount(editor) {
2019
+ var isEditorFocused = editor.createContextKey('isEditorFocused' + id, false);
2020
+ // we setup on-blur
2021
+ editor.onDidBlurEditorWidget(function () {
2022
+ isEditorFocused.set(false);
2023
+ onBlur == null || onBlur(editor.getValue());
2024
+ });
2025
+ editor.onDidFocusEditorText(function () {
2026
+ isEditorFocused.set(true);
2027
+ });
2028
+ var dataProvider = new DataProvider({
2029
+ url: props.url,
2030
+ lookbackInterval: props.lookbackInterval,
2031
+ variablesNames: props.variablesNames,
2032
+ request: props.request,
2033
+ httpMethod: props.httpMethod,
2034
+ apiPrefix: props.apiPrefix,
2035
+ httpErrorHandler: props.httpErrorHandler
2036
+ });
2037
+ dataProviderRef.current = dataProvider;
2038
+ dataProvider.start();
2039
+ var completionProvider = getCompletionProvider(monaco, dataProvider);
2040
+ var filteringCompletionProvider = _extends({}, completionProvider, {
2041
+ provideCompletionItems: function provideCompletionItems(model, position, context, token) {
2042
+ var _editor$getModel;
2043
+ if (((_editor$getModel = editor.getModel()) == null ? void 0 : _editor$getModel.id) !== model.id) {
2044
+ return {
2045
+ suggestions: []
2046
+ };
2047
+ }
2048
+ return completionProvider.provideCompletionItems(model, position, context, token);
2049
+ }
2050
+ });
2051
+ var _monaco$languages$reg = monaco.languages.registerCompletionItemProvider(PROMQL_LANG_ID, filteringCompletionProvider),
2052
+ dispose = _monaco$languages$reg.dispose;
2053
+ autocompleteDisposeFun.current = dispose;
2054
+ var updateElementHeight = function updateElementHeight() {
2055
+ var containerDiv = containerRef.current;
2056
+ if (containerDiv !== null) {
2057
+ var pixelHeight = editor.getContentHeight();
2058
+ containerDiv.style.height = pixelHeight + EDITOR_HEIGHT_OFFSET + "px";
2059
+ containerDiv.style.width = '100%';
2060
+ var pixelWidth = containerDiv.clientWidth;
2061
+ editor.layout({
2062
+ width: pixelWidth,
2063
+ height: pixelHeight
2064
+ });
2065
+ }
2066
+ };
2067
+ editor.onDidContentSizeChange(updateElementHeight);
2068
+ updateElementHeight();
2069
+ // Fixes Monaco capturing the search key binding and displaying a useless search box within the Editor.
2070
+ monaco.editor.addKeybindingRule({
2071
+ keybinding: monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyF,
2072
+ command: null
2073
+ });
2074
+ // handle: shift + enter
2075
+ editor.addCommand(monaco.KeyMod.Shift | monaco.KeyCode.Enter, function () {
2076
+ console.log(22222);
2077
+ onShiftEnter == null || onShiftEnter(editor.getValue());
2078
+ }, 'isEditorFocused' + id);
2079
+ if (placeholder) {
2080
+ var placeholderDecorators = [{
2081
+ range: new monaco.Range(1, 1, 1, 1),
2082
+ options: {
2083
+ className: styles.placeholder,
2084
+ isWholeLine: true
2085
+ }
2086
+ }];
2087
+ var decorators = [];
2088
+ var checkDecorators = function checkDecorators() {
2089
+ var model = editor.getModel();
2090
+ if (!model) {
2091
+ return;
2092
+ }
2093
+ var newDecorators = model.getValueLength() === 0 ? placeholderDecorators : [];
2094
+ decorators = model.deltaDecorations(decorators, newDecorators);
2095
+ };
2096
+ checkDecorators();
2097
+ editor.onDidChangeModelContent(checkDecorators);
2098
+ }
2099
+ editor.onDidChangeModelContent(function () {
2100
+ var model = editor.getModel();
2101
+ if (model) {
2102
+ var query = model.getValue();
2103
+ var errors = validateQuery(query, interpolateString ? interpolateString(query) : query, model.getLinesContent(), lezerMetricsql.parser) || [];
2104
+ var markers = errors.map(function (_ref) {
2105
+ var error = _ref.error,
2106
+ boundary = _objectWithoutPropertiesLoose(_ref, _excluded);
2107
+ return _extends({
2108
+ message: (error ? "Error parsing \"" + error + "\"" : 'Parse error') + ". The query appears to be incorrect and could fail to be executed.",
2109
+ severity: monaco.MarkerSeverity.Error
2110
+ }, boundary);
2111
+ });
2112
+ monaco.editor.setModelMarkers(model, 'owner', markers);
2113
+ }
2114
+ });
2115
+ };
2116
+ React.useEffect(function () {
2117
+ var dataProvider = dataProviderRef.current;
2118
+ if (dataProvider) {
2119
+ dataProvider.setVariablesNames(variablesNames || []);
2120
+ }
2121
+ }, [JSON.stringify(variablesNames)]);
2122
+ return React__default.createElement("div", {
2123
+ className: 'ant-input' + (size ? " " + SIZE_MAP[size].className : '')
2124
+ }, React__default.createElement("div", {
2125
+ ref: containerRef
2126
+ }, React__default.createElement(MonacoEditor, {
2127
+ width: '100%',
2128
+ height: '100%',
2129
+ language: 'promql',
2130
+ theme: themeMap[theme],
2131
+ value: value,
2132
+ onChange: onChange,
2133
+ editorDidMount: handleEditorDidMount,
2134
+ options: {
2135
+ codeLens: false,
2136
+ contextmenu: false,
2137
+ fixedOverflowWidgets: true,
2138
+ folding: false,
2139
+ fontSize: 12,
2140
+ lineDecorationsWidth: 0,
2141
+ lineNumbers: 'off',
2142
+ minimap: {
2143
+ enabled: false
2144
+ },
2145
+ overviewRulerBorder: false,
2146
+ overviewRulerLanes: 0,
2147
+ padding: {
2148
+ top: SIZE_MAP[size].top,
2149
+ bottom: SIZE_MAP[size].bottom
2150
+ },
2151
+ renderLineHighlight: 'none',
2152
+ scrollbar: {
2153
+ vertical: 'hidden',
2154
+ verticalScrollbarSize: 8,
2155
+ horizontal: 'hidden',
2156
+ horizontalScrollbarSize: 0,
2157
+ alwaysConsumeMouseWheel: false
2158
+ },
2159
+ scrollBeyondLastLine: false,
2160
+ suggest: {
2161
+ showWords: false
2162
+ },
2163
+ suggestFontSize: 12,
2164
+ wordWrap: 'on'
2165
+ }
2166
+ })));
2167
+ }
2168
+
2169
+ exports.PromQLMonacoEditor = PromQLEditor;
2170
+ //# sourceMappingURL=monaco-editor.cjs.development.js.map