@perses-dev/prometheus-plugin 0.8.1 → 0.10.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 (86) hide show
  1. package/dist/cjs/index.js +21 -5
  2. package/dist/cjs/model/api-types.js +5 -3
  3. package/dist/cjs/model/index.js +34 -0
  4. package/dist/cjs/model/parse-sample-values.js +22 -16
  5. package/dist/cjs/model/prometheus-client.js +52 -66
  6. package/dist/cjs/model/prometheus-selectors.js +37 -0
  7. package/dist/cjs/model/templating.js +14 -10
  8. package/dist/cjs/model/time.js +35 -49
  9. package/dist/cjs/model/utils.js +21 -13
  10. package/dist/cjs/model/utils.test.js +57 -31
  11. package/dist/cjs/plugins/JSONSpecEditor.js +54 -0
  12. package/dist/cjs/plugins/PrometheusTimeSeriesQueryEditor.js +77 -0
  13. package/dist/cjs/plugins/prometheus-datasource.js +54 -0
  14. package/dist/cjs/plugins/prometheus-variables.js +76 -0
  15. package/dist/cjs/plugins/time-series-query.js +82 -0
  16. package/dist/cjs/plugins/variable.js +43 -0
  17. package/dist/cjs/test/setup-tests.js +4 -2
  18. package/dist/index.d.ts +5 -2
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +21 -1
  21. package/dist/index.js.map +1 -0
  22. package/dist/model/api-types.js +15 -1
  23. package/dist/model/api-types.js.map +1 -0
  24. package/dist/model/index.d.ts +8 -0
  25. package/dist/model/index.d.ts.map +1 -0
  26. package/dist/model/index.js +21 -0
  27. package/dist/model/index.js.map +1 -0
  28. package/dist/model/parse-sample-values.d.ts.map +1 -1
  29. package/dist/model/parse-sample-values.js +44 -1
  30. package/dist/model/parse-sample-values.js.map +1 -0
  31. package/dist/model/prometheus-client.d.ts +14 -11
  32. package/dist/model/prometheus-client.d.ts.map +1 -1
  33. package/dist/model/prometheus-client.js +81 -1
  34. package/dist/model/prometheus-client.js.map +1 -0
  35. package/dist/model/prometheus-selectors.d.ts +22 -0
  36. package/dist/model/prometheus-selectors.d.ts.map +1 -0
  37. package/dist/model/prometheus-selectors.js +30 -0
  38. package/dist/model/prometheus-selectors.js.map +1 -0
  39. package/dist/model/templating.js +21 -1
  40. package/dist/model/templating.js.map +1 -0
  41. package/dist/model/time.d.ts +7 -8
  42. package/dist/model/time.d.ts.map +1 -1
  43. package/dist/model/time.js +49 -1
  44. package/dist/model/time.js.map +1 -0
  45. package/dist/model/utils.d.ts +2 -1
  46. package/dist/model/utils.d.ts.map +1 -1
  47. package/dist/model/utils.js +55 -1
  48. package/dist/model/utils.js.map +1 -0
  49. package/dist/model/utils.test.js +110 -1
  50. package/dist/model/utils.test.js.map +1 -0
  51. package/dist/plugins/JSONSpecEditor.d.ts +4 -0
  52. package/dist/plugins/JSONSpecEditor.d.ts.map +1 -0
  53. package/dist/plugins/JSONSpecEditor.js +48 -0
  54. package/dist/plugins/JSONSpecEditor.js.map +1 -0
  55. package/dist/plugins/PrometheusTimeSeriesQueryEditor.d.ts +6 -0
  56. package/dist/plugins/PrometheusTimeSeriesQueryEditor.d.ts.map +1 -0
  57. package/dist/plugins/PrometheusTimeSeriesQueryEditor.js +66 -0
  58. package/dist/plugins/PrometheusTimeSeriesQueryEditor.js.map +1 -0
  59. package/dist/plugins/prometheus-datasource.d.ts +7 -0
  60. package/dist/plugins/prometheus-datasource.d.ts.map +1 -0
  61. package/dist/plugins/prometheus-datasource.js +48 -0
  62. package/dist/plugins/prometheus-datasource.js.map +1 -0
  63. package/dist/plugins/prometheus-variables.d.ts +16 -0
  64. package/dist/plugins/prometheus-variables.d.ts.map +1 -0
  65. package/dist/plugins/prometheus-variables.js +64 -0
  66. package/dist/plugins/prometheus-variables.js.map +1 -0
  67. package/dist/plugins/time-series-query.d.ts +14 -0
  68. package/dist/plugins/time-series-query.d.ts.map +1 -0
  69. package/dist/plugins/time-series-query.js +78 -0
  70. package/dist/plugins/time-series-query.js.map +1 -0
  71. package/dist/plugins/variable.d.ts +8 -0
  72. package/dist/plugins/variable.d.ts.map +1 -0
  73. package/dist/plugins/variable.js +37 -0
  74. package/dist/plugins/variable.js.map +1 -0
  75. package/dist/test/setup-tests.js +15 -1
  76. package/dist/test/setup-tests.js.map +1 -0
  77. package/package.json +11 -8
  78. package/plugin.json +17 -9
  79. package/dist/cjs/model/datasource.js +0 -36
  80. package/dist/cjs/plugins/graph-query.js +0 -84
  81. package/dist/model/datasource.d.ts +0 -11
  82. package/dist/model/datasource.d.ts.map +0 -1
  83. package/dist/model/datasource.js +0 -1
  84. package/dist/plugins/graph-query.d.ts +0 -14
  85. package/dist/plugins/graph-query.d.ts.map +0 -1
  86. package/dist/plugins/graph-query.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"parse-sample-values.d.ts","sourceRoot":"","sources":["../../src/model/parse-sample-values.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC;;GAEG;AACH,oBAAY,gBAAgB,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAEnE;;;GAGG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,UAAU,GAAG,gBAAgB,CAKlE;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,MAAM,CAanE"}
1
+ {"version":3,"file":"parse-sample-values.d.ts","sourceRoot":"","sources":["../../src/model/parse-sample-values.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC;;GAEG;AACH,oBAAY,gBAAgB,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAEnE;;;GAGG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,UAAU,GAAG,gBAAgB,CAKlE;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,MAAM,CAenE"}
@@ -1 +1,44 @@
1
- export function parseValueTuple(e){const[a,r]=e;return[1e3*a,parseSampleValue(r)]}export function parseSampleValue(e){let a;switch(e){case"+Inf":a=Number.POSITIVE_INFINITY;case"-Inf":a=Number.NEGATIVE_INFINITY;default:a=parseFloat(e)}return a}
1
+ // Copyright 2022 The Perses Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ /**
14
+ * Parse a ValueTuple from a PromServer response into the a millisecond-based
15
+ * unix time and a numeric sample value.
16
+ */ export function parseValueTuple(data) {
17
+ const [unixTimeSeconds, sampleValue] = data;
18
+ // Prom returns unix time in seconds, so convert to ms
19
+ return [
20
+ unixTimeSeconds * 1000,
21
+ parseSampleValue(sampleValue)
22
+ ];
23
+ }
24
+ /**
25
+ * Parses a string sample value from Prometheus, usually included as the
26
+ * second member of a ValueTuple.
27
+ */ export function parseSampleValue(sampleValue) {
28
+ // Account for Prometheus' representation of +/- infinity, otherwise just
29
+ // parse the sample value as a float
30
+ let value;
31
+ switch(sampleValue){
32
+ case '+Inf':
33
+ value = Number.POSITIVE_INFINITY;
34
+ break;
35
+ case '-Inf':
36
+ value = Number.NEGATIVE_INFINITY;
37
+ break;
38
+ default:
39
+ value = parseFloat(sampleValue);
40
+ }
41
+ return value;
42
+ }
43
+
44
+ //# sourceMappingURL=parse-sample-values.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/model/parse-sample-values.ts"],"sourcesContent":["// Copyright 2022 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { ValueTuple } from './api-types';\n\n/**\n * ValueTuple from the Prom server, parsed into ms and floating point number\n */\nexport type ParsedValueTuple = [unixTimeMs: number, value: number];\n\n/**\n * Parse a ValueTuple from a PromServer response into the a millisecond-based\n * unix time and a numeric sample value.\n */\nexport function parseValueTuple(data: ValueTuple): ParsedValueTuple {\n const [unixTimeSeconds, sampleValue] = data;\n\n // Prom returns unix time in seconds, so convert to ms\n return [unixTimeSeconds * 1000, parseSampleValue(sampleValue)];\n}\n\n/**\n * Parses a string sample value from Prometheus, usually included as the\n * second member of a ValueTuple.\n */\nexport function parseSampleValue(sampleValue: ValueTuple[1]): number {\n // Account for Prometheus' representation of +/- infinity, otherwise just\n // parse the sample value as a float\n let value: number;\n switch (sampleValue) {\n case '+Inf':\n value = Number.POSITIVE_INFINITY;\n break;\n case '-Inf':\n value = Number.NEGATIVE_INFINITY;\n break;\n default:\n value = parseFloat(sampleValue);\n }\n return value;\n}\n"],"names":["parseValueTuple","data","unixTimeSeconds","sampleValue","parseSampleValue","value","Number","POSITIVE_INFINITY","NEGATIVE_INFINITY","parseFloat"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AASjC;;;CAGC,GACD,OAAO,SAASA,eAAe,CAACC,IAAgB,EAAoB;IAClE,MAAM,CAACC,eAAe,EAAEC,WAAW,CAAC,GAAGF,IAAI,AAAC;IAE5C,sDAAsD;IACtD,OAAO;QAACC,eAAe,GAAG,IAAI;QAAEE,gBAAgB,CAACD,WAAW,CAAC;KAAC,CAAC;AACjE,CAAC;AAED;;;CAGC,GACD,OAAO,SAASC,gBAAgB,CAACD,WAA0B,EAAU;IACnE,yEAAyE;IACzE,oCAAoC;IACpC,IAAIE,KAAK,AAAQ,AAAC;IAClB,OAAQF,WAAW;QACjB,KAAK,MAAM;YACTE,KAAK,GAAGC,MAAM,CAACC,iBAAiB,CAAC;YACjC,MAAM;QACR,KAAK,MAAM;YACTF,KAAK,GAAGC,MAAM,CAACE,iBAAiB,CAAC;YACjC,MAAM;QACR;YACEH,KAAK,GAAGI,UAAU,CAACN,WAAW,CAAC,CAAC;KACnC;IACD,OAAOE,KAAK,CAAC;AACf,CAAC"}
@@ -1,24 +1,27 @@
1
- import { UseQueryOptions } from 'react-query';
2
- import { DatasourceSelector } from '@perses-dev/core';
3
1
  import { InstantQueryRequestParameters, InstantQueryResponse, LabelNamesRequestParameters, LabelNamesResponse, LabelValuesRequestParameters, LabelValuesResponse, RangeQueryRequestParameters, RangeQueryResponse } from './api-types';
4
- export declare type QueryOptions = Pick<UseQueryOptions, 'enabled'> & {
5
- datasource?: DatasourceSelector;
6
- };
2
+ export interface PrometheusClient {
3
+ instantQuery(params: InstantQueryRequestParameters): Promise<InstantQueryResponse>;
4
+ rangeQuery(params: RangeQueryRequestParameters): Promise<RangeQueryResponse>;
5
+ labelNames(params: LabelNamesRequestParameters): Promise<LabelNamesResponse>;
6
+ labelValues(params: LabelValuesRequestParameters): Promise<LabelValuesResponse>;
7
+ }
8
+ export interface QueryOptions {
9
+ datasourceUrl: string;
10
+ }
7
11
  /**
8
12
  * Calls the `/api/v1/query` endpoint to get metrics data.
9
13
  */
10
- export declare function useInstantQuery(params: InstantQueryRequestParameters, queryOptions?: QueryOptions): import("react-query").UseQueryResult<InstantQueryResponse, Error>;
14
+ export declare function instantQuery(params: InstantQueryRequestParameters, queryOptions: QueryOptions): Promise<InstantQueryResponse>;
11
15
  /**
12
16
  * Calls the `/api/v1/query_range` endpoint to get metrics data.
13
17
  */
14
- export declare function useRangeQuery(params: RangeQueryRequestParameters, queryOptions?: QueryOptions): import("react-query").UseQueryResult<RangeQueryResponse, Error>;
18
+ export declare function rangeQuery(params: RangeQueryRequestParameters, queryOptions: QueryOptions): Promise<RangeQueryResponse>;
15
19
  /**
16
20
  * Calls the `/api/v1/labels` endpoint to get a list of label names.
17
21
  */
18
- export declare function useLabelNames(params: LabelNamesRequestParameters, queryOptions?: QueryOptions): import("react-query").UseQueryResult<LabelNamesResponse, Error>;
22
+ export declare function labelNames(params: LabelNamesRequestParameters, queryOptions: QueryOptions): Promise<LabelNamesResponse>;
19
23
  /**
20
- * Calls the `/api/v1/label/{labelName}/values` endpoint to get a list of
21
- * values for a label.
24
+ * Calls the `/api/v1/label/{labelName}/values` endpoint to get a list of values for a label.
22
25
  */
23
- export declare function useLabelValues(params: LabelValuesRequestParameters, queryOptions?: QueryOptions): import("react-query").UseQueryResult<LabelValuesResponse, Error>;
26
+ export declare function labelValues(params: LabelValuesRequestParameters, queryOptions: QueryOptions): Promise<LabelValuesResponse>;
24
27
  //# sourceMappingURL=prometheus-client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"prometheus-client.d.ts","sourceRoot":"","sources":["../../src/model/prometheus-client.ts"],"names":[],"mappings":"AAaA,OAAO,EAAY,eAAe,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAsB,kBAAkB,EAAa,MAAM,kBAAkB,CAAC;AACrF,OAAO,EACL,6BAA6B,EAC7B,oBAAoB,EACpB,2BAA2B,EAC3B,kBAAkB,EAClB,4BAA4B,EAC5B,mBAAmB,EACnB,2BAA2B,EAC3B,kBAAkB,EACnB,MAAM,aAAa,CAAC;AAGrB,oBAAY,YAAY,GAAG,IAAI,CAAC,eAAe,EAAE,SAAS,CAAC,GAAG;IAC5D,UAAU,CAAC,EAAE,kBAAkB,CAAC;CACjC,CAAC;AAEF;;GAEG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,6BAA6B,EAAE,YAAY,CA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;GAEG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,4BAA4B,EAAE,YAAY,EAAE,YAAY,gCAI3F"}
@@ -1 +1,81 @@
1
- import{useQuery}from"react-query";import{buildDatasourceURL,fetchJson}from"@perses-dev/core";import{usePrometheusConfig}from"./datasource";export function useInstantQuery(e,t){return useQueryWithPost("/api/v1/query",e,t)}export function useRangeQuery(e,t){return useQueryWithPost("/api/v1/query_range",e,t)}export function useLabelNames(e,t){return useQueryWithPost("/api/v1/labels",e,t)}export function useLabelValues(e,t){const{labelName:r,...o}=e;return useQueryWithGet(`/api/v1/label/${encodeURIComponent(r)}/values`,o,t)}function useQueryWithGet(e,t,r){const o=usePrometheusConfig(null==r?void 0:r.datasource),u=buildDatasourceURL(o.metadata.name,o.spec.http);return useQuery([u,e,t],(()=>{let r=`${u}${e}`;const o=createSearchParams(t).toString();return""!==o&&(r+=`?${o}`),fetchJson(r,{method:"GET"})}),r)}function useQueryWithPost(e,t,r){const o=usePrometheusConfig(null==r?void 0:r.datasource),u=buildDatasourceURL(o.metadata.name,o.spec.http);return useQuery([u,e,t],(()=>{const r=`${u}${e}`,o={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:createSearchParams(t)};return fetchJson(r,o)}),r)}function createSearchParams(e){const t=new URLSearchParams;for(const r in e){const o=e[r];if(void 0!==o)if("string"!=typeof o)if("number"!=typeof o)for(const e of o)t.append(r,e);else t.append(r,o.toString());else t.append(r,o)}return t}
1
+ // Copyright 2022 The Perses Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ import { fetchJson } from '@perses-dev/core';
14
+ /**
15
+ * Calls the `/api/v1/query` endpoint to get metrics data.
16
+ */ export function instantQuery(params, queryOptions) {
17
+ return fetchWithPost('/api/v1/query', params, queryOptions);
18
+ }
19
+ /**
20
+ * Calls the `/api/v1/query_range` endpoint to get metrics data.
21
+ */ export function rangeQuery(params, queryOptions) {
22
+ return fetchWithPost('/api/v1/query_range', params, queryOptions);
23
+ }
24
+ /**
25
+ * Calls the `/api/v1/labels` endpoint to get a list of label names.
26
+ */ export function labelNames(params, queryOptions) {
27
+ return fetchWithPost('/api/v1/labels', params, queryOptions);
28
+ }
29
+ /**
30
+ * Calls the `/api/v1/label/{labelName}/values` endpoint to get a list of values for a label.
31
+ */ export function labelValues(params, queryOptions) {
32
+ const { labelName , ...searchParams } = params;
33
+ const apiURI = `/api/v1/label/${encodeURIComponent(labelName)}/values`;
34
+ return fetchWithGet(apiURI, searchParams, queryOptions);
35
+ }
36
+ function fetchWithGet(apiURI, params, queryOptions) {
37
+ const { datasourceUrl } = queryOptions;
38
+ let url = `${datasourceUrl}${apiURI}`;
39
+ const urlParams = createSearchParams(params).toString();
40
+ if (urlParams !== '') {
41
+ url += `?${urlParams}`;
42
+ }
43
+ return fetchJson(url, {
44
+ method: 'GET'
45
+ });
46
+ }
47
+ function fetchWithPost(apiURI, params, queryOptions) {
48
+ const { datasourceUrl } = queryOptions;
49
+ const url = `${datasourceUrl}${apiURI}`;
50
+ const init = {
51
+ method: 'POST',
52
+ headers: {
53
+ 'Content-Type': 'application/x-www-form-urlencoded'
54
+ },
55
+ body: createSearchParams(params)
56
+ };
57
+ return fetchJson(url, init);
58
+ }
59
+ /**
60
+ * Creates URLSearchParams from a request params object.
61
+ */ function createSearchParams(params) {
62
+ const searchParams = new URLSearchParams();
63
+ for(const key in params){
64
+ const value = params[key];
65
+ if (value === undefined) continue;
66
+ if (typeof value === 'string') {
67
+ searchParams.append(key, value);
68
+ continue;
69
+ }
70
+ if (typeof value === 'number') {
71
+ searchParams.append(key, value.toString());
72
+ continue;
73
+ }
74
+ for (const val of value){
75
+ searchParams.append(key, val);
76
+ }
77
+ }
78
+ return searchParams;
79
+ }
80
+
81
+ //# sourceMappingURL=prometheus-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/model/prometheus-client.ts"],"sourcesContent":["// Copyright 2022 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { fetchJson } from '@perses-dev/core';\nimport {\n InstantQueryRequestParameters,\n InstantQueryResponse,\n LabelNamesRequestParameters,\n LabelNamesResponse,\n LabelValuesRequestParameters,\n LabelValuesResponse,\n RangeQueryRequestParameters,\n RangeQueryResponse,\n} from './api-types';\n\nexport interface PrometheusClient {\n instantQuery(params: InstantQueryRequestParameters): Promise<InstantQueryResponse>;\n rangeQuery(params: RangeQueryRequestParameters): Promise<RangeQueryResponse>;\n labelNames(params: LabelNamesRequestParameters): Promise<LabelNamesResponse>;\n labelValues(params: LabelValuesRequestParameters): Promise<LabelValuesResponse>;\n}\n\nexport interface QueryOptions {\n datasourceUrl: string;\n}\n\n/**\n * Calls the `/api/v1/query` endpoint to get metrics data.\n */\nexport function instantQuery(params: InstantQueryRequestParameters, queryOptions: QueryOptions) {\n return fetchWithPost<InstantQueryRequestParameters, InstantQueryResponse>('/api/v1/query', params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/query_range` endpoint to get metrics data.\n */\nexport function rangeQuery(params: RangeQueryRequestParameters, queryOptions: QueryOptions) {\n return fetchWithPost<RangeQueryRequestParameters, RangeQueryResponse>('/api/v1/query_range', params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/labels` endpoint to get a list of label names.\n */\nexport function labelNames(params: LabelNamesRequestParameters, queryOptions: QueryOptions) {\n return fetchWithPost<LabelNamesRequestParameters, LabelNamesResponse>('/api/v1/labels', params, queryOptions);\n}\n\n/**\n * Calls the `/api/v1/label/{labelName}/values` endpoint to get a list of values for a label.\n */\nexport function labelValues(params: LabelValuesRequestParameters, queryOptions: QueryOptions) {\n const { labelName, ...searchParams } = params;\n const apiURI = `/api/v1/label/${encodeURIComponent(labelName)}/values`;\n return fetchWithGet<typeof searchParams, LabelValuesResponse>(apiURI, searchParams, queryOptions);\n}\n\nfunction fetchWithGet<T extends RequestParams<T>, TResponse>(apiURI: string, params: T, queryOptions: QueryOptions) {\n const { datasourceUrl } = queryOptions;\n\n let url = `${datasourceUrl}${apiURI}`;\n const urlParams = createSearchParams(params).toString();\n if (urlParams !== '') {\n url += `?${urlParams}`;\n }\n return fetchJson<TResponse>(url, { method: 'GET' });\n}\n\nfunction fetchWithPost<T extends RequestParams<T>, TResponse>(apiURI: string, params: T, queryOptions: QueryOptions) {\n const { datasourceUrl } = queryOptions;\n\n const url = `${datasourceUrl}${apiURI}`;\n const init = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: createSearchParams(params),\n };\n return fetchJson<TResponse>(url, init);\n}\n\n// Request parameter values we know how to serialize\ntype ParamValue = string | string[] | number | undefined;\n\n// Used to constrain the types that can be passed to createSearchParams to\n// just the ones we know how to serialize\ntype RequestParams<T> = {\n [K in keyof T]: ParamValue;\n};\n\n/**\n * Creates URLSearchParams from a request params object.\n */\nfunction createSearchParams<T extends RequestParams<T>>(params: T) {\n const searchParams = new URLSearchParams();\n for (const key in params) {\n const value: ParamValue = params[key];\n if (value === undefined) continue;\n\n if (typeof value === 'string') {\n searchParams.append(key, value);\n continue;\n }\n\n if (typeof value === 'number') {\n searchParams.append(key, value.toString());\n continue;\n }\n\n for (const val of value) {\n searchParams.append(key, val);\n }\n }\n return searchParams;\n}\n"],"names":["fetchJson","instantQuery","params","queryOptions","fetchWithPost","rangeQuery","labelNames","labelValues","labelName","searchParams","apiURI","encodeURIComponent","fetchWithGet","datasourceUrl","url","urlParams","createSearchParams","toString","method","init","headers","body","URLSearchParams","key","value","undefined","append","val"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,SAAS,QAAQ,kBAAkB,CAAC;AAuB7C;;CAEC,GACD,OAAO,SAASC,YAAY,CAACC,MAAqC,EAAEC,YAA0B,EAAE;IAC9F,OAAOC,aAAa,CAAsD,eAAe,EAAEF,MAAM,EAAEC,YAAY,CAAC,CAAC;AACnH,CAAC;AAED;;CAEC,GACD,OAAO,SAASE,UAAU,CAACH,MAAmC,EAAEC,YAA0B,EAAE;IAC1F,OAAOC,aAAa,CAAkD,qBAAqB,EAAEF,MAAM,EAAEC,YAAY,CAAC,CAAC;AACrH,CAAC;AAED;;CAEC,GACD,OAAO,SAASG,UAAU,CAACJ,MAAmC,EAAEC,YAA0B,EAAE;IAC1F,OAAOC,aAAa,CAAkD,gBAAgB,EAAEF,MAAM,EAAEC,YAAY,CAAC,CAAC;AAChH,CAAC;AAED;;CAEC,GACD,OAAO,SAASI,WAAW,CAACL,MAAoC,EAAEC,YAA0B,EAAE;IAC5F,MAAM,EAAEK,SAAS,CAAA,EAAE,GAAGC,YAAY,EAAE,GAAGP,MAAM,AAAC;IAC9C,MAAMQ,MAAM,GAAG,CAAC,cAAc,EAAEC,kBAAkB,CAACH,SAAS,CAAC,CAAC,OAAO,CAAC,AAAC;IACvE,OAAOI,YAAY,CAA2CF,MAAM,EAAED,YAAY,EAAEN,YAAY,CAAC,CAAC;AACpG,CAAC;AAED,SAASS,YAAY,CAAwCF,MAAc,EAAER,MAAS,EAAEC,YAA0B,EAAE;IA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C;QAED,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE;YAC7Bf,YAAY,CAACiB,MAAM,CAACH,GAAG,EAAEC,KAAK,CAACP,QAAQ,EAAE,CAAC,CAAC;YAC3C,SAAS;QACX,CAAC;QAED,KAAK,MAAMU,GAAG,IAAIH,KAAK,CAAE;YACvBf,YAAY,CAACiB,MAAM,CAACH,GAAG,EAAEI,GAAG,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IACD,OAAOlB,YAAY,CAAC;AACtB,CAAC"}
@@ -0,0 +1,22 @@
1
+ import { DatasourceSelector } from '@perses-dev/core';
2
+ declare const PROM_DATASOURCE_KIND: "PrometheusDatasource";
3
+ /**
4
+ * DatasourceSelector for Prom Datasources.
5
+ */
6
+ export interface PrometheusDatasourceSelector extends DatasourceSelector {
7
+ kind: typeof PROM_DATASOURCE_KIND;
8
+ }
9
+ /**
10
+ * A default selector that asks for the default Prom Datasource.
11
+ */
12
+ export declare const DEFAULT_PROM: PrometheusDatasourceSelector;
13
+ /**
14
+ * Returns true if the provided PrometheusDatasourceSelector is the default one.
15
+ */
16
+ export declare function isDefaultPromSelector(selector: PrometheusDatasourceSelector): boolean;
17
+ /**
18
+ * Type guard to make sure a DatasourceSelector is a Prometheus one.
19
+ */
20
+ export declare function isPrometheusDatasourceSelector(selector: DatasourceSelector): selector is PrometheusDatasourceSelector;
21
+ export {};
22
+ //# sourceMappingURL=prometheus-selectors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prometheus-selectors.d.ts","sourceRoot":"","sources":["../../src/model/prometheus-selectors.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEtD,QAAA,MAAM,oBAAoB,wBAAkC,CAAC;AAE7D;;GAEG;AACH,MAAM,WAAW,4BAA6B,SAAQ,kBAAkB;IACtE,IAAI,EAAE,OAAO,oBAAoB,CAAC;CACnC;AAED;;GAEG;AACH,eAAO,MAAM,YAAY,EAAE,4BAA6D,CAAC;AAEzF;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,4BAA4B,WAE3E;AAED;;GAEG;AACH,wBAAgB,8BAA8B,CAAC,QAAQ,EAAE,kBAAkB,GAAG,QAAQ,IAAI,4BAA4B,CAErH"}
@@ -0,0 +1,30 @@
1
+ // Copyright 2022 The Perses Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ const PROM_DATASOURCE_KIND = 'PrometheusDatasource';
14
+ /**
15
+ * A default selector that asks for the default Prom Datasource.
16
+ */ export const DEFAULT_PROM = {
17
+ kind: PROM_DATASOURCE_KIND
18
+ };
19
+ /**
20
+ * Returns true if the provided PrometheusDatasourceSelector is the default one.
21
+ */ export function isDefaultPromSelector(selector) {
22
+ return selector.name === undefined;
23
+ }
24
+ /**
25
+ * Type guard to make sure a DatasourceSelector is a Prometheus one.
26
+ */ export function isPrometheusDatasourceSelector(selector) {
27
+ return selector.kind === PROM_DATASOURCE_KIND;
28
+ }
29
+
30
+ //# sourceMappingURL=prometheus-selectors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/model/prometheus-selectors.ts"],"sourcesContent":["// Copyright 2022 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { DatasourceSelector } from '@perses-dev/core';\n\nconst PROM_DATASOURCE_KIND = 'PrometheusDatasource' as const;\n\n/**\n * DatasourceSelector for Prom Datasources.\n */\nexport interface PrometheusDatasourceSelector extends DatasourceSelector {\n kind: typeof PROM_DATASOURCE_KIND;\n}\n\n/**\n * A default selector that asks for the default Prom Datasource.\n */\nexport const DEFAULT_PROM: PrometheusDatasourceSelector = { kind: PROM_DATASOURCE_KIND };\n\n/**\n * Returns true if the provided PrometheusDatasourceSelector is the default one.\n */\nexport function isDefaultPromSelector(selector: PrometheusDatasourceSelector) {\n return selector.name === undefined;\n}\n\n/**\n * Type guard to make sure a DatasourceSelector is a Prometheus one.\n */\nexport function isPrometheusDatasourceSelector(selector: DatasourceSelector): selector is PrometheusDatasourceSelector {\n return selector.kind === PROM_DATASOURCE_KIND;\n}\n"],"names":["PROM_DATASOURCE_KIND","DEFAULT_PROM","kind","isDefaultPromSelector","selector","name","undefined","isPrometheusDatasourceSelector"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAIjC,MAAMA,oBAAoB,GAAG,sBAAsB,AAAS,AAAC;AAS7D;;CAEC,GACD,OAAO,MAAMC,YAAY,GAAiC;IAAEC,IAAI,EAAEF,oBAAoB;CAAE,CAAC;AAEzF;;CAEC,GACD,OAAO,SAASG,qBAAqB,CAACC,QAAsC,EAAE;IAC5E,OAAOA,QAAQ,CAACC,IAAI,KAAKC,SAAS,CAAC;AACrC,CAAC;AAED;;CAEC,GACD,OAAO,SAASC,8BAA8B,CAACH,QAA4B,EAA4C;IACrH,OAAOA,QAAQ,CAACF,IAAI,KAAKF,oBAAoB,CAAC;AAChD,CAAC"}
@@ -1 +1,21 @@
1
- import{useTemplateVariableValues}from"@perses-dev/plugin-system";import{replaceTemplateVariables,parseTemplateVariables}from"./utils";export function useReplaceTemplateString(e){const a=parseTemplateVariables(e||""),l=useTemplateVariableValues(a);return replaceTemplateVariables(e||"",l)}
1
+ // Copyright 2022 The Perses Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ import { useTemplateVariableValues } from '@perses-dev/plugin-system';
14
+ import { replaceTemplateVariables, parseTemplateVariables } from './utils';
15
+ export function useReplaceTemplateString(templateString) {
16
+ const templateVariablesInTemplate = parseTemplateVariables(templateString || '');
17
+ const variables = useTemplateVariableValues(templateVariablesInTemplate);
18
+ return replaceTemplateVariables(templateString || '', variables);
19
+ }
20
+
21
+ //# sourceMappingURL=templating.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/model/templating.ts"],"sourcesContent":["// Copyright 2022 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { useTemplateVariableValues } from '@perses-dev/plugin-system';\nimport { replaceTemplateVariables, parseTemplateVariables } from './utils';\n\n/**\n * Type alias to indicate what parts of the API support template variables.\n */\nexport type TemplateString = string;\n\nexport function useReplaceTemplateString(templateString?: TemplateString) {\n const templateVariablesInTemplate = parseTemplateVariables(templateString || '');\n const variables = useTemplateVariableValues(templateVariablesInTemplate);\n return replaceTemplateVariables(templateString || '', variables);\n}\n"],"names":["useTemplateVariableValues","replaceTemplateVariables","parseTemplateVariables","useReplaceTemplateString","templateString","templateVariablesInTemplate","variables"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,yBAAyB,QAAQ,2BAA2B,CAAC;AACtE,SAASC,wBAAwB,EAAEC,sBAAsB,QAAQ,SAAS,CAAC;AAO3E,OAAO,SAASC,wBAAwB,CAACC,cAA+B,EAAE;IACxE,MAAMC,2BAA2B,GAAGH,sBAAsB,CAACE,cAAc,IAAI,EAAE,CAAC,AAAC;IACjF,MAAME,SAAS,GAAGN,yBAAyB,CAACK,2BAA2B,CAAC,AAAC;IACzE,OAAOJ,wBAAwB,CAACG,cAAc,IAAI,EAAE,EAAEE,SAAS,CAAC,CAAC;AACnE,CAAC"}
@@ -1,23 +1,22 @@
1
- import { DurationString } from '@perses-dev/core';
1
+ import { AbsoluteTimeRange, DurationString } from '@perses-dev/core';
2
2
  import { UnixTimestampSeconds } from './api-types';
3
3
  export interface PrometheusTimeRange {
4
4
  start: UnixTimestampSeconds;
5
5
  end: UnixTimestampSeconds;
6
6
  }
7
7
  /**
8
- * Get the time range for the current dashboard, converted to Prometheus time.
8
+ * Converts an AbsoluteTimeRange to Prometheus time in Unix time (i.e. in seconds).
9
9
  */
10
- export declare function useDashboardPrometheusTimeRange(): {
10
+ export declare function getPrometheusTimeRange(timeRange: AbsoluteTimeRange): {
11
11
  start: number;
12
12
  end: number;
13
13
  };
14
14
  /**
15
- * Gets the step to use for a Panel range query. Tries to take into account
16
- * the width of the panel, any minimum step/resolution set by the user, and
17
- * a "safe" step based on the max data points we want to allow returning from
18
- * a Prom query.
15
+ * Gets the step to use for a Prom range query. Tries to take into account a suggested step size (probably based on the
16
+ * width of a visualization where the data will be graphed), any minimum step/resolution set by the user, and a "safe"
17
+ * step based on the max data points we want to allow returning from a Prom query.
19
18
  */
20
- export declare function usePanelRangeStep(timeRange: PrometheusTimeRange, minStepSeconds?: number, resolution?: number, suggestedStepMs?: number): number;
19
+ export declare function getRangeStep(timeRange: PrometheusTimeRange, minStepSeconds?: number, resolution?: number, suggestedStepMs?: number): number;
21
20
  /**
22
21
  * Converts a DurationString to seconds, rounding down.
23
22
  */
@@ -1 +1 @@
1
- {"version":3,"file":"time.d.ts","sourceRoot":"","sources":["../../src/model/time.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,cAAc,EAAoC,MAAM,kBAAkB,CAAC;AAIpF,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,oBAAoB,CAAC;IAC5B,GAAG,EAAE,oBAAoB,CAAC;CAC3B;AAED;;GAEG;AACH,wBAAgB,+BAA+B;;;EAY9C;AAMD;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC/B,SAAS,EAAE,mBAAmB,EAC9B,cAAc,SAAK,EACnB,UAAU,SAAI,EACd,eAAe,SAAI,UAiBpB;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,cAAc,CAAC,EAAE,cAAc,sBAMvE"}
1
+ {"version":3,"file":"time.d.ts","sourceRoot":"","sources":["../../src/model/time.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAuB,MAAM,kBAAkB,CAAC;AAE1F,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,oBAAoB,CAAC;IAC5B,GAAG,EAAE,oBAAoB,CAAC;CAC3B;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,iBAAiB;;;EAMlE;AAMD;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,SAAS,EAAE,mBAAmB,EAAE,cAAc,SAAK,EAAE,UAAU,SAAI,EAAE,eAAe,SAAI,UAUpH;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,cAAc,CAAC,EAAE,cAAc,sBAMvE"}
@@ -1 +1,49 @@
1
- import{parseDurationString,useMemoized}from"@perses-dev/core";import{useTimeRange}from"@perses-dev/plugin-system";import{milliseconds,getUnixTime}from"date-fns";import{useRef}from"react";export function useDashboardPrometheusTimeRange(){const{timeRange:{start:e,end:t}}=useTimeRange();return useMemoized((()=>({start:Math.ceil(getUnixTime(e)),end:Math.ceil(getUnixTime(t))})),[e,t])}const MAX_PROM_DATA_POINTS=1e4;export function usePanelRangeStep(e,t=15,r=1,n=0){const i=useRef(1e3*n);return i.current=1e3*n,useMemoized((()=>{let n=(e.end-e.start)/1e4;return n>1&&(n=Math.ceil(n)),Math.max(i.current*r,t,n)}),[e,t,r])}export function getDurationStringSeconds(e){if(void 0===e)return;const t=parseDurationString(e),r=milliseconds(t);return Math.floor(r/1e3)}
1
+ // Copyright 2022 The Perses Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ import { parseDurationString } from '@perses-dev/core';
14
+ import { milliseconds, getUnixTime } from 'date-fns';
15
+ /**
16
+ * Converts an AbsoluteTimeRange to Prometheus time in Unix time (i.e. in seconds).
17
+ */ export function getPrometheusTimeRange(timeRange) {
18
+ const { start , end } = timeRange;
19
+ return {
20
+ start: Math.ceil(getUnixTime(start)),
21
+ end: Math.ceil(getUnixTime(end))
22
+ };
23
+ }
24
+ // Max data points to allow returning from a Prom Query, used to calculate a
25
+ // "safe" step for a range query
26
+ const MAX_PROM_DATA_POINTS = 10000;
27
+ /**
28
+ * Gets the step to use for a Prom range query. Tries to take into account a suggested step size (probably based on the
29
+ * width of a visualization where the data will be graphed), any minimum step/resolution set by the user, and a "safe"
30
+ * step based on the max data points we want to allow returning from a Prom query.
31
+ */ export function getRangeStep(timeRange, minStepSeconds = 15, resolution = 1, suggestedStepMs = 0) {
32
+ const suggestedStepSeconds = suggestedStepMs / 1000;
33
+ const queryRangeSeconds = timeRange.end - timeRange.start;
34
+ let safeStep = queryRangeSeconds / MAX_PROM_DATA_POINTS;
35
+ if (safeStep > 1) {
36
+ safeStep = Math.ceil(safeStep);
37
+ }
38
+ return Math.max(suggestedStepSeconds * resolution, minStepSeconds, safeStep);
39
+ }
40
+ /**
41
+ * Converts a DurationString to seconds, rounding down.
42
+ */ export function getDurationStringSeconds(durationString) {
43
+ if (durationString === undefined) return undefined;
44
+ const duration = parseDurationString(durationString);
45
+ const ms = milliseconds(duration);
46
+ return Math.floor(ms / 1000);
47
+ }
48
+
49
+ //# sourceMappingURL=time.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/model/time.ts"],"sourcesContent":["// Copyright 2022 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { AbsoluteTimeRange, DurationString, parseDurationString } from '@perses-dev/core';\nimport { milliseconds, getUnixTime } from 'date-fns';\nimport { UnixTimestampSeconds } from './api-types';\n\nexport interface PrometheusTimeRange {\n start: UnixTimestampSeconds;\n end: UnixTimestampSeconds;\n}\n\n/**\n * Converts an AbsoluteTimeRange to Prometheus time in Unix time (i.e. in seconds).\n */\nexport function getPrometheusTimeRange(timeRange: AbsoluteTimeRange) {\n const { start, end } = timeRange;\n return {\n start: Math.ceil(getUnixTime(start)),\n end: Math.ceil(getUnixTime(end)),\n };\n}\n\n// Max data points to allow returning from a Prom Query, used to calculate a\n// \"safe\" step for a range query\nconst MAX_PROM_DATA_POINTS = 10000;\n\n/**\n * Gets the step to use for a Prom range query. Tries to take into account a suggested step size (probably based on the\n * width of a visualization where the data will be graphed), any minimum step/resolution set by the user, and a \"safe\"\n * step based on the max data points we want to allow returning from a Prom query.\n */\nexport function getRangeStep(timeRange: PrometheusTimeRange, minStepSeconds = 15, resolution = 1, suggestedStepMs = 0) {\n const suggestedStepSeconds = suggestedStepMs / 1000;\n const queryRangeSeconds = timeRange.end - timeRange.start;\n\n let safeStep = queryRangeSeconds / MAX_PROM_DATA_POINTS;\n if (safeStep > 1) {\n safeStep = Math.ceil(safeStep);\n }\n\n return Math.max(suggestedStepSeconds * resolution, minStepSeconds, safeStep);\n}\n\n/**\n * Converts a DurationString to seconds, rounding down.\n */\nexport function getDurationStringSeconds(durationString?: DurationString) {\n if (durationString === undefined) return undefined;\n\n const duration = parseDurationString(durationString);\n const ms = milliseconds(duration);\n return Math.floor(ms / 1000);\n}\n"],"names":["parseDurationString","milliseconds","getUnixTime","getPrometheusTimeRange","timeRange","start","end","Math","ceil","MAX_PROM_DATA_POINTS","getRangeStep","minStepSeconds","resolution","suggestedStepMs","suggestedStepSeconds","queryRangeSeconds","safeStep","max","getDurationStringSeconds","durationString","undefined","duration","ms","floor"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAA4CA,mBAAmB,QAAQ,kBAAkB,CAAC;AAC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AOd,IAAI,CAACgB,KAAK,CAACD,EAAE,GAAG,IAAI,CAAC,CAAC;AAC/B,CAAC"}
@@ -1,4 +1,5 @@
1
- import { VariableStateMap, VariableValue } from '@perses-dev/core';
1
+ import { VariableValue } from '@perses-dev/core';
2
+ import { VariableStateMap } from '@perses-dev/plugin-system';
2
3
  export declare function replaceTemplateVariables(text: string, variableState: VariableStateMap): string;
3
4
  export declare function replaceTemplateVariable(text: string, varName: string, templateVariableValue: VariableValue): string;
4
5
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/model/utils.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEnE,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,EAAE,gBAAgB,GAAG,MAAM,CAW9F;AAED,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,qBAAqB,EAAE,aAAa,UAW1G;AAID;;GAEG;AACH,eAAO,MAAM,sBAAsB,SAAU,MAAM,aAclD,CAAC"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/model/utils.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAE7D,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,aAAa,EAAE,gBAAgB,GAAG,MAAM,CAW9F;AAED,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,qBAAqB,EAAE,aAAa,UAW1G;AAMD;;GAEG;AACH,eAAO,MAAM,sBAAsB,SAAU,MAAM,aAclD,CAAC"}
@@ -1 +1,55 @@
1
- export function replaceTemplateVariables(e,r){const l=parseTemplateVariables(e);let a=e;return l.forEach((e=>{const l=r[e];l&&(null==l?void 0:l.value)&&(a=replaceTemplateVariable(a,e,null==l?void 0:l.value))})),a}export function replaceTemplateVariable(e,r,l){const a="$"+r;let t="";return Array.isArray(l)&&(t=`(${l.join("|")})`),"string"==typeof l&&(t=l),e.replaceAll(a,t)}const TEMPLATE_VARIABLE_REGEX=/\$(\w+)|\${(\w+)(?:\.([^:^\}]+))?(?::([^\}]+))?}/gm;export const parseTemplateVariables=e=>{const r=TEMPLATE_VARIABLE_REGEX,l=[];let a;for(;null!==(a=r.exec(e));)a&&a&&a.length>1&&a[1]&&l.push(a[1]);return Array.from(new Set(l))};
1
+ // Copyright 2022 The Perses Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ export function replaceTemplateVariables(text, variableState) {
14
+ const variables = parseTemplateVariables(text);
15
+ let finalText = text;
16
+ variables.forEach((v)=>{
17
+ const variable = variableState[v];
18
+ if (variable && (variable === null || variable === void 0 ? void 0 : variable.value)) {
19
+ finalText = replaceTemplateVariable(finalText, v, variable === null || variable === void 0 ? void 0 : variable.value);
20
+ }
21
+ });
22
+ return finalText;
23
+ }
24
+ export function replaceTemplateVariable(text, varName, templateVariableValue) {
25
+ const variableTemplate = '$' + varName;
26
+ let replaceString = '';
27
+ if (Array.isArray(templateVariableValue)) {
28
+ replaceString = `(${templateVariableValue.join('|')})`; // regex style
29
+ }
30
+ if (typeof templateVariableValue === 'string') {
31
+ replaceString = templateVariableValue;
32
+ }
33
+ return text.replaceAll(variableTemplate, replaceString);
34
+ }
35
+ // TODO: Fix this lint eror
36
+ // eslint-disable-next-line no-useless-escape
37
+ const TEMPLATE_VARIABLE_REGEX = /\$(\w+)|\${(\w+)(?:\.([^:^\}]+))?(?::([^\}]+))?}/gm;
38
+ /**
39
+ * Returns a list of template variables
40
+ */ export const parseTemplateVariables = (text)=>{
41
+ const regex = TEMPLATE_VARIABLE_REGEX;
42
+ const matches = [];
43
+ let match;
44
+ while((match = regex.exec(text)) !== null){
45
+ if (match) {
46
+ if (match && match.length > 1 && match[1]) {
47
+ matches.push(match[1]);
48
+ }
49
+ }
50
+ }
51
+ // return unique matches
52
+ return Array.from(new Set(matches));
53
+ };
54
+
55
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/model/utils.ts"],"sourcesContent":["// Copyright 2022 The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { VariableValue } from '@perses-dev/core';\nimport { VariableStateMap } from '@perses-dev/plugin-system';\n\nexport function replaceTemplateVariables(text: string, variableState: VariableStateMap): string {\n const variables = parseTemplateVariables(text);\n let finalText = text;\n variables.forEach((v) => {\n const variable = variableState[v];\n if (variable && variable?.value) {\n finalText = replaceTemplateVariable(finalText, v, variable?.value);\n }\n });\n\n return finalText;\n}\n\nexport function replaceTemplateVariable(text: string, varName: string, templateVariableValue: VariableValue) {\n const variableTemplate = '$' + varName;\n let replaceString = '';\n if (Array.isArray(templateVariableValue)) {\n replaceString = `(${templateVariableValue.join('|')})`; // regex style\n }\n if (typeof templateVariableValue === 'string') {\n replaceString = templateVariableValue;\n }\n\n return text.replaceAll(variableTemplate, replaceString);\n}\n\n// TODO: Fix this lint eror\n// eslint-disable-next-line no-useless-escape\nconst TEMPLATE_VARIABLE_REGEX = /\\$(\\w+)|\\${(\\w+)(?:\\.([^:^\\}]+))?(?::([^\\}]+))?}/gm;\n\n/**\n * Returns a list of template variables\n */\nexport const parseTemplateVariables = (text: string) => {\n const regex = TEMPLATE_VARIABLE_REGEX;\n const matches = [];\n let match;\n\n while ((match = regex.exec(text)) !== null) {\n if (match) {\n if (match && match.length > 1 && match[1]) {\n matches.push(match[1]);\n }\n }\n }\n // return unique matches\n return Array.from(new Set(matches));\n};\n"],"names":["replaceTemplateVariables","text","variableState","variables","parseTemplateVariables","finalText","forEach","v","variable","value","replaceTemplateVariable","varName","templateVariableValue","variableTemplate","replaceString","Array","isArray","join","replaceAll","TEMPLATE_VARIABLE_REGEX","regex","matches","match","exec","length","push","from","Set"],"mappings":"AAAA,oCAAoC;AACpC,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAKjC,OAAO,SAASA,wBAAwB,CAACC,IAAY,EAAEC,aAA+B,EAAU;IAC9F,MAAMC,SAAS,GAAGC,sBAAsB,CAACH,IAAI,CAAC,AAAC;IAC/C,IAAII,SAAS,GAAGJ,IAAI,AAAC;IACrBE,SAAS,CAACG,OAAO,CAAC,CAACC,CAAC,GAAK;QACvB,MAAMC,QAAQ,GAAGN,aAAa,CAACK,CAAC,CAAC,AAAC;QAClC,IAAIC,QAAQ,IAAIA,CAAAA,QAAQ,aAARA,QAAQ,WAAO,GAAfA,KAAAA,CAAe,GAAfA,QAAQ,CAAEC,KAAK,CAAA,EAAE;YAC/BJ,SAAS,GAAGK,uBAAuB,CAACL,SAAS,EAAEE,CAAC,EAAEC,QAAQ,aAARA,QAAQ,WAAO,GAAfA,KAAAA,CAAe,GAAfA,QAAQ,CAAEC,KAAK,CAAC,CAAC;QACrE,CAAC;IACH,CAAC,CAAC,CAA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C"}
@@ -1 +1,110 @@
1
- import{parseTemplateVariables,replaceTemplateVariable,replaceTemplateVariables}from"./utils";describe("parseTemplateVariables()",(()=>{[{text:"hello $var1 world $var2",variables:["var1","var2"]}].forEach((({text:e,variables:a})=>{it(`parses ${e}`,(()=>{expect(parseTemplateVariables(e)).toEqual(a)}))}))})),describe("replaceTemplateVariable()",(()=>{[{text:"hello $var1",varName:"var1",value:"world",expected:"hello world"},{text:"hello $var1 $var1",varName:"var1",value:"world",expected:"hello world world"},{text:"hello $var1",varName:"var1",value:["world","w"],expected:"hello (world|w)"},{text:"hello $var1 $var1",varName:"var1",value:["world","w"],expected:"hello (world|w) (world|w)"}].forEach((({text:e,value:a,varName:l,expected:r})=>{it(`replaces ${e} ${a}`,(()=>{expect(replaceTemplateVariable(e,l,a)).toEqual(r)}))}))})),describe("replaceTemplateVariables()",(()=>{[{text:"hello $var1 $var2",state:{var1:{value:"world",loading:!1},var2:{value:"world",loading:!1}},expected:"hello world world"},{text:"hello $var1 $var2",state:{var1:{value:"world",loading:!1},var2:{value:["a","b"],loading:!1}},expected:"hello world (a|b)"}].forEach((({text:e,state:a,expected:l})=>{it(`replaces ${e} ${JSON.stringify(a)}`,(()=>{expect(replaceTemplateVariables(e,a)).toEqual(l)}))}))}));
1
+ // Copyright 2022 The Perses Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ import { parseTemplateVariables, replaceTemplateVariable, replaceTemplateVariables } from './utils';
14
+ describe('parseTemplateVariables()', ()=>{
15
+ const tests = [
16
+ {
17
+ text: 'hello $var1 world $var2',
18
+ variables: [
19
+ 'var1',
20
+ 'var2'
21
+ ]
22
+ }
23
+ ];
24
+ tests.forEach(({ text , variables })=>{
25
+ it(`parses ${text}`, ()=>{
26
+ expect(parseTemplateVariables(text)).toEqual(variables);
27
+ });
28
+ });
29
+ });
30
+ describe('replaceTemplateVariable()', ()=>{
31
+ const tests = [
32
+ {
33
+ text: 'hello $var1',
34
+ varName: 'var1',
35
+ value: 'world',
36
+ expected: 'hello world'
37
+ },
38
+ {
39
+ text: 'hello $var1 $var1',
40
+ varName: 'var1',
41
+ value: 'world',
42
+ expected: 'hello world world'
43
+ },
44
+ {
45
+ text: 'hello $var1',
46
+ varName: 'var1',
47
+ value: [
48
+ 'world',
49
+ 'w'
50
+ ],
51
+ expected: 'hello (world|w)'
52
+ },
53
+ {
54
+ text: 'hello $var1 $var1',
55
+ varName: 'var1',
56
+ value: [
57
+ 'world',
58
+ 'w'
59
+ ],
60
+ expected: 'hello (world|w) (world|w)'
61
+ }
62
+ ];
63
+ tests.forEach(({ text , value , varName , expected })=>{
64
+ it(`replaces ${text} ${value}`, ()=>{
65
+ expect(replaceTemplateVariable(text, varName, value)).toEqual(expected);
66
+ });
67
+ });
68
+ });
69
+ describe('replaceTemplateVariables()', ()=>{
70
+ const tests = [
71
+ {
72
+ text: 'hello $var1 $var2',
73
+ state: {
74
+ var1: {
75
+ value: 'world',
76
+ loading: false
77
+ },
78
+ var2: {
79
+ value: 'world',
80
+ loading: false
81
+ }
82
+ },
83
+ expected: 'hello world world'
84
+ },
85
+ {
86
+ text: 'hello $var1 $var2',
87
+ state: {
88
+ var1: {
89
+ value: 'world',
90
+ loading: false
91
+ },
92
+ var2: {
93
+ value: [
94
+ 'a',
95
+ 'b'
96
+ ],
97
+ loading: false
98
+ }
99
+ },
100
+ expected: 'hello world (a|b)'
101
+ }
102
+ ];
103
+ tests.forEach(({ text , state , expected })=>{
104
+ it(`replaces ${text} ${JSON.stringify(state)}`, ()=>{
105
+ expect(replaceTemplateVariables(text, state)).toEqual(expected);
106
+ });
107
+ });
108
+ });
109
+
110
+ //# sourceMappingURL=utils.test.js.map